Don't crash on tuple initialization from erroneous channel.
[gcc.git] / gcc / go / gofrontend / gogo.cc
1 // gogo.cc -- Go frontend parsed representation.
2
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.
6
7 #include "go-system.h"
8
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 "import.h"
17 #include "export.h"
18 #include "gogo.h"
19
20 // Class Gogo.
21
22 Gogo::Gogo(int int_type_size, int float_type_size, int pointer_size)
23 : package_(NULL),
24 functions_(),
25 globals_(new Bindings(NULL)),
26 imports_(),
27 imported_unsafe_(false),
28 packages_(),
29 map_descriptors_(NULL),
30 type_descriptor_decls_(NULL),
31 init_functions_(),
32 need_init_fn_(false),
33 init_fn_name_(),
34 imported_init_fns_(),
35 unique_prefix_(),
36 interface_types_()
37 {
38 const source_location loc = BUILTINS_LOCATION;
39
40 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
41 RUNTIME_TYPE_KIND_UINT8);
42 this->add_named_type(uint8_type);
43 this->add_named_type(Type::make_integer_type("uint16", true, 16,
44 RUNTIME_TYPE_KIND_UINT16));
45 this->add_named_type(Type::make_integer_type("uint32", true, 32,
46 RUNTIME_TYPE_KIND_UINT32));
47 this->add_named_type(Type::make_integer_type("uint64", true, 64,
48 RUNTIME_TYPE_KIND_UINT64));
49
50 this->add_named_type(Type::make_integer_type("int8", false, 8,
51 RUNTIME_TYPE_KIND_INT8));
52 this->add_named_type(Type::make_integer_type("int16", false, 16,
53 RUNTIME_TYPE_KIND_INT16));
54 this->add_named_type(Type::make_integer_type("int32", false, 32,
55 RUNTIME_TYPE_KIND_INT32));
56 this->add_named_type(Type::make_integer_type("int64", false, 64,
57 RUNTIME_TYPE_KIND_INT64));
58
59 this->add_named_type(Type::make_float_type("float32", 32,
60 RUNTIME_TYPE_KIND_FLOAT32));
61 this->add_named_type(Type::make_float_type("float64", 64,
62 RUNTIME_TYPE_KIND_FLOAT64));
63
64 this->add_named_type(Type::make_complex_type("complex64", 64,
65 RUNTIME_TYPE_KIND_COMPLEX64));
66 this->add_named_type(Type::make_complex_type("complex128", 128,
67 RUNTIME_TYPE_KIND_COMPLEX128));
68
69 if (int_type_size < 32)
70 int_type_size = 32;
71 this->add_named_type(Type::make_integer_type("uint", true,
72 int_type_size,
73 RUNTIME_TYPE_KIND_UINT));
74 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
75 RUNTIME_TYPE_KIND_INT);
76 this->add_named_type(int_type);
77
78 // "byte" is an alias for "uint8". Construct a Named_object which
79 // points to UINT8_TYPE. Note that this breaks the normal pairing
80 // in which a Named_object points to a Named_type which points back
81 // to the same Named_object.
82 Named_object* byte_type = this->declare_type("byte", loc);
83 byte_type->set_type_value(uint8_type);
84
85 this->add_named_type(Type::make_integer_type("uintptr", true,
86 pointer_size,
87 RUNTIME_TYPE_KIND_UINTPTR));
88
89 this->add_named_type(Type::make_float_type("float", float_type_size,
90 RUNTIME_TYPE_KIND_FLOAT));
91
92 this->add_named_type(Type::make_complex_type("complex", float_type_size * 2,
93 RUNTIME_TYPE_KIND_COMPLEX));
94
95 this->add_named_type(Type::make_named_bool_type());
96
97 this->add_named_type(Type::make_named_string_type());
98
99 this->globals_->add_constant(Typed_identifier("true",
100 Type::make_boolean_type(),
101 loc),
102 NULL,
103 Expression::make_boolean(true, loc),
104 0);
105 this->globals_->add_constant(Typed_identifier("false",
106 Type::make_boolean_type(),
107 loc),
108 NULL,
109 Expression::make_boolean(false, loc),
110 0);
111
112 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
113 loc),
114 NULL,
115 Expression::make_nil(loc),
116 0);
117
118 Type* abstract_int_type = Type::make_abstract_integer_type();
119 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
120 loc),
121 NULL,
122 Expression::make_iota(),
123 0);
124
125 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
126 new_type->set_is_varargs();
127 new_type->set_is_builtin();
128 this->globals_->add_function_declaration("new", NULL, new_type, loc);
129
130 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
131 make_type->set_is_varargs();
132 make_type->set_is_builtin();
133 this->globals_->add_function_declaration("make", NULL, make_type, loc);
134
135 Typed_identifier_list* len_result = new Typed_identifier_list();
136 len_result->push_back(Typed_identifier("", int_type, loc));
137 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
138 loc);
139 len_type->set_is_builtin();
140 this->globals_->add_function_declaration("len", NULL, len_type, loc);
141
142 Typed_identifier_list* cap_result = new Typed_identifier_list();
143 cap_result->push_back(Typed_identifier("", int_type, loc));
144 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
145 loc);
146 cap_type->set_is_builtin();
147 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
148
149 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
150 print_type->set_is_varargs();
151 print_type->set_is_builtin();
152 this->globals_->add_function_declaration("print", NULL, print_type, loc);
153
154 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
155 print_type->set_is_varargs();
156 print_type->set_is_builtin();
157 this->globals_->add_function_declaration("println", NULL, print_type, loc);
158
159 Type *empty = Type::make_interface_type(NULL, loc);
160 Typed_identifier_list* panic_parms = new Typed_identifier_list();
161 panic_parms->push_back(Typed_identifier("e", empty, loc));
162 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
163 NULL, loc);
164 panic_type->set_is_builtin();
165 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
166
167 Typed_identifier_list* recover_result = new Typed_identifier_list();
168 recover_result->push_back(Typed_identifier("", empty, loc));
169 Function_type* recover_type = Type::make_function_type(NULL, NULL,
170 recover_result,
171 loc);
172 recover_type->set_is_builtin();
173 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
174
175 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
176 close_type->set_is_varargs();
177 close_type->set_is_builtin();
178 this->globals_->add_function_declaration("close", NULL, close_type, loc);
179
180 Typed_identifier_list* closed_result = new Typed_identifier_list();
181 closed_result->push_back(Typed_identifier("", Type::lookup_bool_type(),
182 loc));
183 Function_type* closed_type = Type::make_function_type(NULL, NULL,
184 closed_result, loc);
185 closed_type->set_is_varargs();
186 closed_type->set_is_builtin();
187 this->globals_->add_function_declaration("closed", NULL, closed_type, loc);
188
189 Typed_identifier_list* copy_result = new Typed_identifier_list();
190 copy_result->push_back(Typed_identifier("", int_type, loc));
191 Function_type* copy_type = Type::make_function_type(NULL, NULL,
192 copy_result, loc);
193 copy_type->set_is_varargs();
194 copy_type->set_is_builtin();
195 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
196
197 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 append_type->set_is_varargs();
199 append_type->set_is_builtin();
200 this->globals_->add_function_declaration("append", NULL, append_type, loc);
201
202 Function_type* cmplx_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 cmplx_type->set_is_varargs();
204 cmplx_type->set_is_builtin();
205 this->globals_->add_function_declaration("cmplx", NULL, cmplx_type, loc);
206
207 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
208 real_type->set_is_varargs();
209 real_type->set_is_builtin();
210 this->globals_->add_function_declaration("real", NULL, real_type, loc);
211
212 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
213 imag_type->set_is_varargs();
214 imag_type->set_is_builtin();
215 this->globals_->add_function_declaration("imag", NULL, cmplx_type, loc);
216
217 this->define_builtin_function_trees();
218
219 // Declare "init", to ensure that it is not defined with parameters
220 // or return values.
221 this->declare_function("init",
222 Type::make_function_type(NULL, NULL, NULL, loc),
223 loc);
224 }
225
226 // Munge name for use in an error message.
227
228 std::string
229 Gogo::message_name(const std::string& name)
230 {
231 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
232 }
233
234 // Get the package name.
235
236 const std::string&
237 Gogo::package_name() const
238 {
239 gcc_assert(this->package_ != NULL);
240 return this->package_->name();
241 }
242
243 // Set the package name.
244
245 void
246 Gogo::set_package_name(const std::string& package_name,
247 source_location location)
248 {
249 if (this->package_ != NULL && this->package_->name() != package_name)
250 {
251 error_at(location, "expected package %<%s%>",
252 Gogo::message_name(this->package_->name()).c_str());
253 return;
254 }
255
256 // If the user did not specify a unique prefix, we always use "go".
257 // This in effect requires that the package name be unique.
258 if (this->unique_prefix_.empty())
259 this->unique_prefix_ = "go";
260
261 this->package_ = this->register_package(package_name, this->unique_prefix_,
262 location);
263
264 // We used to permit people to qualify symbols with the current
265 // package name (e.g., P.x), but we no longer do.
266 // this->globals_->add_package(package_name, this->package_);
267
268 if (package_name == "main")
269 {
270 // Declare "main" as a function which takes no parameters and
271 // returns no value.
272 this->declare_function("main",
273 Type::make_function_type(NULL, NULL, NULL,
274 BUILTINS_LOCATION),
275 BUILTINS_LOCATION);
276 }
277 }
278
279 // Import a package.
280
281 void
282 Gogo::import_package(const std::string& filename,
283 const std::string& local_name,
284 bool is_local_name_exported,
285 source_location location)
286 {
287 if (filename == "unsafe")
288 {
289 this->import_unsafe(local_name, is_local_name_exported, location);
290 return;
291 }
292
293 Imports::const_iterator p = this->imports_.find(filename);
294 if (p != this->imports_.end())
295 {
296 Package* package = p->second;
297 package->set_location(location);
298 package->set_is_imported();
299 std::string ln = local_name;
300 bool is_ln_exported = is_local_name_exported;
301 if (ln.empty())
302 {
303 ln = package->name();
304 is_ln_exported = Lex::is_exported_name(ln);
305 }
306 if (ln != ".")
307 {
308 ln = this->pack_hidden_name(ln, is_ln_exported);
309 this->package_->bindings()->add_package(ln, package);
310 }
311 else
312 {
313 Bindings* bindings = package->bindings();
314 for (Bindings::const_declarations_iterator p =
315 bindings->begin_declarations();
316 p != bindings->end_declarations();
317 ++p)
318 this->add_named_object(p->second);
319 }
320 return;
321 }
322
323 Import::Stream* stream = Import::open_package(filename, location);
324 if (stream == NULL)
325 {
326 error_at(location, "import file %qs not found", filename.c_str());
327 return;
328 }
329
330 Import imp(stream, location);
331 imp.register_builtin_types(this);
332 Package* package = imp.import(this, local_name, is_local_name_exported);
333 this->imports_.insert(std::make_pair(filename, package));
334 package->set_is_imported();
335
336 delete stream;
337 }
338
339 // Add an import control function for an imported package to the list.
340
341 void
342 Gogo::add_import_init_fn(const std::string& package_name,
343 const std::string& init_name, int prio)
344 {
345 for (std::set<Import_init>::const_iterator p =
346 this->imported_init_fns_.begin();
347 p != this->imported_init_fns_.end();
348 ++p)
349 {
350 if (p->init_name() == init_name
351 && (p->package_name() != package_name || p->priority() != prio))
352 {
353 error("duplicate package initialization name %qs",
354 Gogo::message_name(init_name).c_str());
355 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
356 Gogo::message_name(p->package_name()).c_str(),
357 p->priority());
358 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
359 Gogo::message_name(package_name).c_str(), prio);
360 return;
361 }
362 }
363
364 this->imported_init_fns_.insert(Import_init(package_name, init_name,
365 prio));
366 }
367
368 // Return whether we are at the global binding level.
369
370 bool
371 Gogo::in_global_scope() const
372 {
373 return this->functions_.empty();
374 }
375
376 // Return the current binding contour.
377
378 Bindings*
379 Gogo::current_bindings()
380 {
381 if (!this->functions_.empty())
382 return this->functions_.back().blocks.back()->bindings();
383 else if (this->package_ != NULL)
384 return this->package_->bindings();
385 else
386 return this->globals_;
387 }
388
389 const Bindings*
390 Gogo::current_bindings() const
391 {
392 if (!this->functions_.empty())
393 return this->functions_.back().blocks.back()->bindings();
394 else if (this->package_ != NULL)
395 return this->package_->bindings();
396 else
397 return this->globals_;
398 }
399
400 // Return the current block.
401
402 Block*
403 Gogo::current_block()
404 {
405 if (this->functions_.empty())
406 return NULL;
407 else
408 return this->functions_.back().blocks.back();
409 }
410
411 // Look up a name in the current binding contour. If PFUNCTION is not
412 // NULL, set it to the function in which the name is defined, or NULL
413 // if the name is defined in global scope.
414
415 Named_object*
416 Gogo::lookup(const std::string& name, Named_object** pfunction) const
417 {
418 if (Gogo::is_sink_name(name))
419 return Named_object::make_sink();
420
421 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
422 p != this->functions_.rend();
423 ++p)
424 {
425 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
426 if (ret != NULL)
427 {
428 if (pfunction != NULL)
429 *pfunction = p->function;
430 return ret;
431 }
432 }
433
434 if (pfunction != NULL)
435 *pfunction = NULL;
436
437 if (this->package_ != NULL)
438 {
439 Named_object* ret = this->package_->bindings()->lookup(name);
440 if (ret != NULL)
441 {
442 if (ret->package() != NULL)
443 ret->package()->set_used();
444 return ret;
445 }
446 }
447
448 // We do not look in the global namespace. If we did, the global
449 // namespace would effectively hide names which were defined in
450 // package scope which we have not yet seen. Instead,
451 // define_global_names is called after parsing is over to connect
452 // undefined names at package scope with names defined at global
453 // scope.
454
455 return NULL;
456 }
457
458 // Look up a name in the current block, without searching enclosing
459 // blocks.
460
461 Named_object*
462 Gogo::lookup_in_block(const std::string& name) const
463 {
464 gcc_assert(!this->functions_.empty());
465 gcc_assert(!this->functions_.back().blocks.empty());
466 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
467 }
468
469 // Look up a name in the global namespace.
470
471 Named_object*
472 Gogo::lookup_global(const char* name) const
473 {
474 return this->globals_->lookup(name);
475 }
476
477 // Add an imported package.
478
479 Package*
480 Gogo::add_imported_package(const std::string& real_name,
481 const std::string& alias_arg,
482 bool is_alias_exported,
483 const std::string& unique_prefix,
484 source_location location,
485 bool* padd_to_globals)
486 {
487 // FIXME: Now that we compile packages as a whole, should we permit
488 // importing the current package?
489 if (this->package_name() == real_name
490 && this->unique_prefix() == unique_prefix)
491 {
492 *padd_to_globals = false;
493 if (!alias_arg.empty() && alias_arg != ".")
494 {
495 std::string alias = this->pack_hidden_name(alias_arg,
496 is_alias_exported);
497 this->package_->bindings()->add_package(alias, this->package_);
498 }
499 return this->package_;
500 }
501 else if (alias_arg == ".")
502 {
503 *padd_to_globals = true;
504 return this->register_package(real_name, unique_prefix, location);
505 }
506 else if (alias_arg == "_")
507 {
508 Package* ret = this->register_package(real_name, unique_prefix, location);
509 ret->set_uses_sink_alias();
510 return ret;
511 }
512 else
513 {
514 *padd_to_globals = false;
515 std::string alias = alias_arg;
516 if (alias.empty())
517 {
518 alias = real_name;
519 is_alias_exported = Lex::is_exported_name(alias);
520 }
521 alias = this->pack_hidden_name(alias, is_alias_exported);
522 Named_object* no = this->add_package(real_name, alias, unique_prefix,
523 location);
524 if (!no->is_package())
525 return NULL;
526 return no->package_value();
527 }
528 }
529
530 // Add a package.
531
532 Named_object*
533 Gogo::add_package(const std::string& real_name, const std::string& alias,
534 const std::string& unique_prefix, source_location location)
535 {
536 gcc_assert(this->in_global_scope());
537
538 // Register the package. Note that we might have already seen it in
539 // an earlier import.
540 Package* package = this->register_package(real_name, unique_prefix, location);
541
542 return this->package_->bindings()->add_package(alias, package);
543 }
544
545 // Register a package. This package may or may not be imported. This
546 // returns the Package structure for the package, creating if it
547 // necessary.
548
549 Package*
550 Gogo::register_package(const std::string& package_name,
551 const std::string& unique_prefix,
552 source_location location)
553 {
554 gcc_assert(!unique_prefix.empty() && !package_name.empty());
555 std::string name = unique_prefix + '.' + package_name;
556 Package* package = NULL;
557 std::pair<Packages::iterator, bool> ins =
558 this->packages_.insert(std::make_pair(name, package));
559 if (!ins.second)
560 {
561 // We have seen this package name before.
562 package = ins.first->second;
563 gcc_assert(package != NULL);
564 gcc_assert(package->name() == package_name
565 && package->unique_prefix() == unique_prefix);
566 if (package->location() == UNKNOWN_LOCATION)
567 package->set_location(location);
568 }
569 else
570 {
571 // First time we have seen this package name.
572 package = new Package(package_name, unique_prefix, location);
573 gcc_assert(ins.first->second == NULL);
574 ins.first->second = package;
575 }
576
577 return package;
578 }
579
580 // Start compiling a function.
581
582 Named_object*
583 Gogo::start_function(const std::string& name, Function_type* type,
584 bool add_method_to_type, source_location location)
585 {
586 bool at_top_level = this->functions_.empty();
587
588 Block* block = new Block(NULL, location);
589
590 Function* enclosing = (at_top_level
591 ? NULL
592 : this->functions_.back().function->func_value());
593
594 Function* function = new Function(type, enclosing, block, location);
595
596 if (type->is_method())
597 {
598 const Typed_identifier* receiver = type->receiver();
599 Variable* this_param = new Variable(receiver->type(), NULL, false,
600 true, true, location);
601 std::string name = receiver->name();
602 if (name.empty())
603 {
604 // We need to give receivers a name since they wind up in
605 // DECL_ARGUMENTS. FIXME.
606 static unsigned int count;
607 char buf[50];
608 snprintf(buf, sizeof buf, "r.%u", count);
609 ++count;
610 name = buf;
611 }
612 block->bindings()->add_variable(name, NULL, this_param);
613 }
614
615 const Typed_identifier_list* parameters = type->parameters();
616 bool is_varargs = type->is_varargs();
617 if (parameters != NULL)
618 {
619 for (Typed_identifier_list::const_iterator p = parameters->begin();
620 p != parameters->end();
621 ++p)
622 {
623 Variable* param = new Variable(p->type(), NULL, false, true, false,
624 location);
625 if (is_varargs && p + 1 == parameters->end())
626 param->set_is_varargs_parameter();
627
628 std::string name = p->name();
629 if (name.empty() || Gogo::is_sink_name(name))
630 {
631 // We need to give parameters a name since they wind up
632 // in DECL_ARGUMENTS. FIXME.
633 static unsigned int count;
634 char buf[50];
635 snprintf(buf, sizeof buf, "p.%u", count);
636 ++count;
637 name = buf;
638 }
639 block->bindings()->add_variable(name, NULL, param);
640 }
641 }
642
643 function->create_named_result_variables(this);
644
645 const std::string* pname;
646 std::string nested_name;
647 if (!name.empty())
648 pname = &name;
649 else
650 {
651 // Invent a name for a nested function.
652 static int nested_count;
653 char buf[30];
654 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
655 ++nested_count;
656 nested_name = buf;
657 pname = &nested_name;
658 }
659
660 Named_object* ret;
661 if (Gogo::is_sink_name(*pname))
662 ret = Named_object::make_sink();
663 else if (!type->is_method())
664 {
665 ret = this->package_->bindings()->add_function(*pname, NULL, function);
666 if (!ret->is_function())
667 {
668 // Redefinition error.
669 ret = Named_object::make_function(name, NULL, function);
670 }
671 }
672 else
673 {
674 if (!add_method_to_type)
675 ret = Named_object::make_function(name, NULL, function);
676 else
677 {
678 gcc_assert(at_top_level);
679 Type* rtype = type->receiver()->type();
680
681 // We want to look through the pointer created by the
682 // parser, without getting an error if the type is not yet
683 // defined.
684 if (rtype->classification() == Type::TYPE_POINTER)
685 rtype = rtype->points_to();
686
687 if (rtype->is_error_type())
688 ret = Named_object::make_function(name, NULL, function);
689 else if (rtype->named_type() != NULL)
690 {
691 ret = rtype->named_type()->add_method(name, function);
692 if (!ret->is_function())
693 {
694 // Redefinition error.
695 ret = Named_object::make_function(name, NULL, function);
696 }
697 }
698 else if (rtype->forward_declaration_type() != NULL)
699 {
700 Named_object* type_no =
701 rtype->forward_declaration_type()->named_object();
702 if (type_no->is_unknown())
703 {
704 // If we are seeing methods it really must be a
705 // type. Declare it as such. An alternative would
706 // be to support lists of methods for unknown
707 // expressions. Either way the error messages if
708 // this is not a type are going to get confusing.
709 Named_object* declared =
710 this->declare_package_type(type_no->name(),
711 type_no->location());
712 gcc_assert(declared
713 == type_no->unknown_value()->real_named_object());
714 }
715 ret = rtype->forward_declaration_type()->add_method(name,
716 function);
717 }
718 else
719 gcc_unreachable();
720 }
721 this->package_->bindings()->add_method(ret);
722 }
723
724 this->functions_.resize(this->functions_.size() + 1);
725 Open_function& of(this->functions_.back());
726 of.function = ret;
727 of.blocks.push_back(block);
728
729 if (!type->is_method() && Gogo::unpack_hidden_name(name) == "init")
730 {
731 this->init_functions_.push_back(ret);
732 this->need_init_fn_ = true;
733 }
734
735 return ret;
736 }
737
738 // Finish compiling a function.
739
740 void
741 Gogo::finish_function(source_location location)
742 {
743 this->finish_block(location);
744 gcc_assert(this->functions_.back().blocks.empty());
745 this->functions_.pop_back();
746 }
747
748 // Return the current function.
749
750 Named_object*
751 Gogo::current_function() const
752 {
753 gcc_assert(!this->functions_.empty());
754 return this->functions_.back().function;
755 }
756
757 // Start a new block.
758
759 void
760 Gogo::start_block(source_location location)
761 {
762 gcc_assert(!this->functions_.empty());
763 Block* block = new Block(this->current_block(), location);
764 this->functions_.back().blocks.push_back(block);
765 }
766
767 // Finish a block.
768
769 Block*
770 Gogo::finish_block(source_location location)
771 {
772 gcc_assert(!this->functions_.empty());
773 gcc_assert(!this->functions_.back().blocks.empty());
774 Block* block = this->functions_.back().blocks.back();
775 this->functions_.back().blocks.pop_back();
776 block->set_end_location(location);
777 return block;
778 }
779
780 // Add an unknown name.
781
782 Named_object*
783 Gogo::add_unknown_name(const std::string& name, source_location location)
784 {
785 return this->package_->bindings()->add_unknown_name(name, location);
786 }
787
788 // Declare a function.
789
790 Named_object*
791 Gogo::declare_function(const std::string& name, Function_type* type,
792 source_location location)
793 {
794 if (!type->is_method())
795 return this->current_bindings()->add_function_declaration(name, NULL, type,
796 location);
797 else
798 {
799 // We don't bother to add this to the list of global
800 // declarations.
801 Type* rtype = type->receiver()->type();
802
803 // We want to look through the pointer created by the
804 // parser, without getting an error if the type is not yet
805 // defined.
806 if (rtype->classification() == Type::TYPE_POINTER)
807 rtype = rtype->points_to();
808
809 if (rtype->is_error_type())
810 return NULL;
811 else if (rtype->named_type() != NULL)
812 return rtype->named_type()->add_method_declaration(name, NULL, type,
813 location);
814 else if (rtype->forward_declaration_type() != NULL)
815 {
816 Forward_declaration_type* ftype = rtype->forward_declaration_type();
817 return ftype->add_method_declaration(name, type, location);
818 }
819 else
820 gcc_unreachable();
821 }
822 }
823
824 // Add a label definition.
825
826 Label*
827 Gogo::add_label_definition(const std::string& label_name,
828 source_location location)
829 {
830 gcc_assert(!this->functions_.empty());
831 Function* func = this->functions_.back().function->func_value();
832 Label* label = func->add_label_definition(label_name, location);
833 this->add_statement(Statement::make_label_statement(label, location));
834 return label;
835 }
836
837 // Add a label reference.
838
839 Label*
840 Gogo::add_label_reference(const std::string& label_name)
841 {
842 gcc_assert(!this->functions_.empty());
843 Function* func = this->functions_.back().function->func_value();
844 return func->add_label_reference(label_name);
845 }
846
847 // Add a statement.
848
849 void
850 Gogo::add_statement(Statement* statement)
851 {
852 gcc_assert(!this->functions_.empty()
853 && !this->functions_.back().blocks.empty());
854 this->functions_.back().blocks.back()->add_statement(statement);
855 }
856
857 // Add a block.
858
859 void
860 Gogo::add_block(Block* block, source_location location)
861 {
862 gcc_assert(!this->functions_.empty()
863 && !this->functions_.back().blocks.empty());
864 Statement* statement = Statement::make_block_statement(block, location);
865 this->functions_.back().blocks.back()->add_statement(statement);
866 }
867
868 // Add a constant.
869
870 Named_object*
871 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
872 int iota_value)
873 {
874 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
875 }
876
877 // Add a type.
878
879 void
880 Gogo::add_type(const std::string& name, Type* type, source_location location)
881 {
882 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
883 location);
884 if (!this->in_global_scope())
885 no->type_value()->set_in_function(this->functions_.back().function);
886 }
887
888 // Add a named type.
889
890 void
891 Gogo::add_named_type(Named_type* type)
892 {
893 gcc_assert(this->in_global_scope());
894 this->current_bindings()->add_named_type(type);
895 }
896
897 // Declare a type.
898
899 Named_object*
900 Gogo::declare_type(const std::string& name, source_location location)
901 {
902 Bindings* bindings = this->current_bindings();
903 Named_object* no = bindings->add_type_declaration(name, NULL, location);
904 if (!this->in_global_scope())
905 {
906 Named_object* f = this->functions_.back().function;
907 no->type_declaration_value()->set_in_function(f);
908 }
909 return no;
910 }
911
912 // Declare a type at the package level.
913
914 Named_object*
915 Gogo::declare_package_type(const std::string& name, source_location location)
916 {
917 return this->package_->bindings()->add_type_declaration(name, NULL, location);
918 }
919
920 // Define a type which was already declared.
921
922 void
923 Gogo::define_type(Named_object* no, Named_type* type)
924 {
925 this->current_bindings()->define_type(no, type);
926 }
927
928 // Add a variable.
929
930 Named_object*
931 Gogo::add_variable(const std::string& name, Variable* variable)
932 {
933 Named_object* no = this->current_bindings()->add_variable(name, NULL,
934 variable);
935
936 // In a function the middle-end wants to see a DECL_EXPR node.
937 if (no != NULL
938 && no->is_variable()
939 && !no->var_value()->is_parameter()
940 && !this->functions_.empty())
941 this->add_statement(Statement::make_variable_declaration(no));
942
943 return no;
944 }
945
946 // Add a sink--a reference to the blank identifier _.
947
948 Named_object*
949 Gogo::add_sink()
950 {
951 return Named_object::make_sink();
952 }
953
954 // Add a named object.
955
956 void
957 Gogo::add_named_object(Named_object* no)
958 {
959 this->current_bindings()->add_named_object(no);
960 }
961
962 // Record that we've seen an interface type.
963
964 void
965 Gogo::record_interface_type(Interface_type* itype)
966 {
967 this->interface_types_.push_back(itype);
968 }
969
970 // Return a name for a thunk object.
971
972 std::string
973 Gogo::thunk_name()
974 {
975 static int thunk_count;
976 char thunk_name[50];
977 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
978 ++thunk_count;
979 return thunk_name;
980 }
981
982 // Return whether a function is a thunk.
983
984 bool
985 Gogo::is_thunk(const Named_object* no)
986 {
987 return no->name().compare(0, 6, "$thunk") == 0;
988 }
989
990 // Define the global names. We do this only after parsing all the
991 // input files, because the program might define the global names
992 // itself.
993
994 void
995 Gogo::define_global_names()
996 {
997 for (Bindings::const_declarations_iterator p =
998 this->globals_->begin_declarations();
999 p != this->globals_->end_declarations();
1000 ++p)
1001 {
1002 Named_object* global_no = p->second;
1003 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1004 Named_object* no = this->package_->bindings()->lookup(name);
1005 if (no == NULL)
1006 continue;
1007 no = no->resolve();
1008 if (no->is_type_declaration())
1009 {
1010 if (global_no->is_type())
1011 {
1012 if (no->type_declaration_value()->has_methods())
1013 error_at(no->location(),
1014 "may not define methods for global type");
1015 no->set_type_value(global_no->type_value());
1016 }
1017 else
1018 {
1019 error_at(no->location(), "expected type");
1020 Type* errtype = Type::make_error_type();
1021 Named_object* err = Named_object::make_type("error", NULL,
1022 errtype,
1023 BUILTINS_LOCATION);
1024 no->set_type_value(err->type_value());
1025 }
1026 }
1027 else if (no->is_unknown())
1028 no->unknown_value()->set_real_named_object(global_no);
1029 }
1030 }
1031
1032 // Clear out names in file scope.
1033
1034 void
1035 Gogo::clear_file_scope()
1036 {
1037 this->package_->bindings()->clear_file_scope();
1038
1039 // Warn about packages which were imported but not used.
1040 for (Packages::iterator p = this->packages_.begin();
1041 p != this->packages_.end();
1042 ++p)
1043 {
1044 Package* package = p->second;
1045 if (package != this->package_
1046 && package->is_imported()
1047 && !package->used()
1048 && !package->uses_sink_alias()
1049 && !saw_errors())
1050 error_at(package->location(), "imported and not used: %s",
1051 Gogo::message_name(package->name()).c_str());
1052 package->clear_is_imported();
1053 package->clear_uses_sink_alias();
1054 package->clear_used();
1055 }
1056 }
1057
1058 // Traverse the tree.
1059
1060 void
1061 Gogo::traverse(Traverse* traverse)
1062 {
1063 // Traverse the current package first for consistency. The other
1064 // packages will only contain imported types, constants, and
1065 // declarations.
1066 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1067 return;
1068 for (Packages::const_iterator p = this->packages_.begin();
1069 p != this->packages_.end();
1070 ++p)
1071 {
1072 if (p->second != this->package_)
1073 {
1074 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1075 break;
1076 }
1077 }
1078 }
1079
1080 // Traversal class used to verify types.
1081
1082 class Verify_types : public Traverse
1083 {
1084 public:
1085 Verify_types()
1086 : Traverse(traverse_types)
1087 { }
1088
1089 int
1090 type(Type*);
1091 };
1092
1093 // Verify that a type is correct.
1094
1095 int
1096 Verify_types::type(Type* t)
1097 {
1098 // Don't verify types defined in other packages.
1099 Named_type* nt = t->named_type();
1100 if (nt != NULL && nt->named_object()->package() != NULL)
1101 return TRAVERSE_SKIP_COMPONENTS;
1102
1103 if (!t->verify())
1104 return TRAVERSE_SKIP_COMPONENTS;
1105 return TRAVERSE_CONTINUE;
1106 }
1107
1108 // Verify that all types are correct.
1109
1110 void
1111 Gogo::verify_types()
1112 {
1113 Verify_types traverse;
1114 this->traverse(&traverse);
1115 }
1116
1117 // Traversal class used to lower parse tree.
1118
1119 class Lower_parse_tree : public Traverse
1120 {
1121 public:
1122 Lower_parse_tree(Gogo* gogo, Named_object* function)
1123 : Traverse(traverse_constants
1124 | traverse_functions
1125 | traverse_statements
1126 | traverse_expressions),
1127 gogo_(gogo), function_(function), iota_value_(-1)
1128 { }
1129
1130 int
1131 constant(Named_object*, bool);
1132
1133 int
1134 function(Named_object*);
1135
1136 int
1137 statement(Block*, size_t* pindex, Statement*);
1138
1139 int
1140 expression(Expression**);
1141
1142 private:
1143 // General IR.
1144 Gogo* gogo_;
1145 // The function we are traversing.
1146 Named_object* function_;
1147 // Value to use for the predeclared constant iota.
1148 int iota_value_;
1149 };
1150
1151 // Lower constants. We handle constants specially so that we can set
1152 // the right value for the predeclared constant iota. This works in
1153 // conjunction with the way we lower Const_expression objects.
1154
1155 int
1156 Lower_parse_tree::constant(Named_object* no, bool)
1157 {
1158 Named_constant* nc = no->const_value();
1159
1160 // We can recursively a constant if the initializer expression
1161 // manages to refer to itself.
1162 if (nc->lowering())
1163 return TRAVERSE_CONTINUE;
1164 nc->set_lowering();
1165
1166 gcc_assert(this->iota_value_ == -1);
1167 this->iota_value_ = nc->iota_value();
1168 nc->traverse_expression(this);
1169 this->iota_value_ = -1;
1170
1171 nc->clear_lowering();
1172
1173 // We will traverse the expression a second time, but that will be
1174 // fast.
1175
1176 return TRAVERSE_CONTINUE;
1177 }
1178
1179 // Lower function closure types. Record the function while lowering
1180 // it, so that we can pass it down when lowering an expression.
1181
1182 int
1183 Lower_parse_tree::function(Named_object* no)
1184 {
1185 no->func_value()->set_closure_type();
1186
1187 gcc_assert(this->function_ == NULL);
1188 this->function_ = no;
1189 int t = no->func_value()->traverse(this);
1190 this->function_ = NULL;
1191
1192 if (t == TRAVERSE_EXIT)
1193 return t;
1194 return TRAVERSE_SKIP_COMPONENTS;
1195 }
1196
1197 // Lower statement parse trees.
1198
1199 int
1200 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1201 {
1202 // Lower the expressions first.
1203 int t = sorig->traverse_contents(this);
1204 if (t == TRAVERSE_EXIT)
1205 return t;
1206
1207 // Keep lowering until nothing changes.
1208 Statement* s = sorig;
1209 while (true)
1210 {
1211 Statement* snew = s->lower(this->gogo_, block);
1212 if (snew == s)
1213 break;
1214 s = snew;
1215 t = s->traverse_contents(this);
1216 if (t == TRAVERSE_EXIT)
1217 return t;
1218 }
1219
1220 if (s != sorig)
1221 block->replace_statement(*pindex, s);
1222
1223 return TRAVERSE_SKIP_COMPONENTS;
1224 }
1225
1226 // Lower expression parse trees.
1227
1228 int
1229 Lower_parse_tree::expression(Expression** pexpr)
1230 {
1231 // We have to lower all subexpressions first, so that we can get
1232 // their type if necessary. This is awkward, because we don't have
1233 // a postorder traversal pass.
1234 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1235 return TRAVERSE_EXIT;
1236 // Keep lowering until nothing changes.
1237 while (true)
1238 {
1239 Expression* e = *pexpr;
1240 Expression* enew = e->lower(this->gogo_, this->function_,
1241 this->iota_value_);
1242 if (enew == e)
1243 break;
1244 *pexpr = enew;
1245 }
1246 return TRAVERSE_SKIP_COMPONENTS;
1247 }
1248
1249 // Lower the parse tree. This is called after the parse is complete,
1250 // when all names should be resolved.
1251
1252 void
1253 Gogo::lower_parse_tree()
1254 {
1255 Lower_parse_tree lower_parse_tree(this, NULL);
1256 this->traverse(&lower_parse_tree);
1257 }
1258
1259 // Lower an expression.
1260
1261 void
1262 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1263 {
1264 Lower_parse_tree lower_parse_tree(this, function);
1265 lower_parse_tree.expression(pexpr);
1266 }
1267
1268 // Lower a constant. This is called when lowering a reference to a
1269 // constant. We have to make sure that the constant has already been
1270 // lowered.
1271
1272 void
1273 Gogo::lower_constant(Named_object* no)
1274 {
1275 gcc_assert(no->is_const());
1276 Lower_parse_tree lower(this, NULL);
1277 lower.constant(no, false);
1278 }
1279
1280 // Look for interface types to finalize methods of inherited
1281 // interfaces.
1282
1283 class Finalize_methods : public Traverse
1284 {
1285 public:
1286 Finalize_methods(Gogo* gogo)
1287 : Traverse(traverse_types),
1288 gogo_(gogo)
1289 { }
1290
1291 int
1292 type(Type*);
1293
1294 private:
1295 Gogo* gogo_;
1296 };
1297
1298 // Finalize the methods of an interface type.
1299
1300 int
1301 Finalize_methods::type(Type* t)
1302 {
1303 // Check the classification so that we don't finalize the methods
1304 // twice for a named interface type.
1305 switch (t->classification())
1306 {
1307 case Type::TYPE_INTERFACE:
1308 t->interface_type()->finalize_methods();
1309 break;
1310
1311 case Type::TYPE_NAMED:
1312 {
1313 // We have to finalize the methods of the real type first.
1314 // But if the real type is a struct type, then we only want to
1315 // finalize the methods of the field types, not of the struct
1316 // type itself. We don't want to add methods to the struct,
1317 // since it has a name.
1318 Type* rt = t->named_type()->real_type();
1319 if (rt->classification() != Type::TYPE_STRUCT)
1320 {
1321 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1322 return TRAVERSE_EXIT;
1323 }
1324 else
1325 {
1326 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1327 return TRAVERSE_EXIT;
1328 }
1329
1330 t->named_type()->finalize_methods(this->gogo_);
1331
1332 return TRAVERSE_SKIP_COMPONENTS;
1333 }
1334
1335 case Type::TYPE_STRUCT:
1336 t->struct_type()->finalize_methods(this->gogo_);
1337 break;
1338
1339 default:
1340 break;
1341 }
1342
1343 return TRAVERSE_CONTINUE;
1344 }
1345
1346 // Finalize method lists and build stub methods for types.
1347
1348 void
1349 Gogo::finalize_methods()
1350 {
1351 Finalize_methods finalize(this);
1352 this->traverse(&finalize);
1353 }
1354
1355 // Set types for unspecified variables and constants.
1356
1357 void
1358 Gogo::determine_types()
1359 {
1360 Bindings* bindings = this->current_bindings();
1361 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1362 p != bindings->end_definitions();
1363 ++p)
1364 {
1365 if ((*p)->is_function())
1366 (*p)->func_value()->determine_types();
1367 else if ((*p)->is_variable())
1368 (*p)->var_value()->determine_type();
1369 else if ((*p)->is_const())
1370 (*p)->const_value()->determine_type();
1371
1372 // See if a variable requires us to build an initialization
1373 // function. We know that we will see all global variables
1374 // here.
1375 if (!this->need_init_fn_ && (*p)->is_variable())
1376 {
1377 Variable* variable = (*p)->var_value();
1378
1379 // If this is a global variable which requires runtime
1380 // initialization, we need an initialization function.
1381 if (!variable->is_global() || variable->init() == NULL)
1382 ;
1383 else if (variable->type()->interface_type() != NULL)
1384 this->need_init_fn_ = true;
1385 else if (variable->init()->is_constant())
1386 ;
1387 else if (!variable->init()->is_composite_literal())
1388 this->need_init_fn_ = true;
1389 else if (variable->init()->is_nonconstant_composite_literal())
1390 this->need_init_fn_ = true;
1391
1392 // If this is a global variable which holds a pointer value,
1393 // then we need an initialization function to register it as a
1394 // GC root.
1395 if (variable->is_global() && variable->type()->has_pointer())
1396 this->need_init_fn_ = true;
1397 }
1398 }
1399
1400 // Determine the types of constants in packages.
1401 for (Packages::const_iterator p = this->packages_.begin();
1402 p != this->packages_.end();
1403 ++p)
1404 p->second->determine_types();
1405 }
1406
1407 // Traversal class used for type checking.
1408
1409 class Check_types_traverse : public Traverse
1410 {
1411 public:
1412 Check_types_traverse(Gogo* gogo)
1413 : Traverse(traverse_variables
1414 | traverse_constants
1415 | traverse_statements
1416 | traverse_expressions),
1417 gogo_(gogo)
1418 { }
1419
1420 int
1421 variable(Named_object*);
1422
1423 int
1424 constant(Named_object*, bool);
1425
1426 int
1427 statement(Block*, size_t* pindex, Statement*);
1428
1429 int
1430 expression(Expression**);
1431
1432 private:
1433 // General IR.
1434 Gogo* gogo_;
1435 };
1436
1437 // Check that a variable initializer has the right type.
1438
1439 int
1440 Check_types_traverse::variable(Named_object* named_object)
1441 {
1442 if (named_object->is_variable())
1443 {
1444 Variable* var = named_object->var_value();
1445 Expression* init = var->init();
1446 std::string reason;
1447 if (init != NULL
1448 && !Type::are_assignable(var->type(), init->type(), &reason))
1449 {
1450 if (reason.empty())
1451 error_at(var->location(), "incompatible type in initialization");
1452 else
1453 error_at(var->location(),
1454 "incompatible type in initialization (%s)",
1455 reason.c_str());
1456 var->clear_init();
1457 }
1458 }
1459 return TRAVERSE_CONTINUE;
1460 }
1461
1462 // Check that a constant initializer has the right type.
1463
1464 int
1465 Check_types_traverse::constant(Named_object* named_object, bool)
1466 {
1467 Named_constant* constant = named_object->const_value();
1468 Type* ctype = constant->type();
1469 if (ctype->integer_type() == NULL
1470 && ctype->float_type() == NULL
1471 && ctype->complex_type() == NULL
1472 && !ctype->is_boolean_type()
1473 && !ctype->is_string_type())
1474 {
1475 error_at(constant->location(), "invalid constant type");
1476 constant->set_error();
1477 }
1478 else if (!constant->expr()->is_constant())
1479 {
1480 error_at(constant->expr()->location(), "expression is not constant");
1481 constant->set_error();
1482 }
1483 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1484 NULL))
1485 {
1486 error_at(constant->location(),
1487 "initialization expression has wrong type");
1488 constant->set_error();
1489 }
1490 return TRAVERSE_CONTINUE;
1491 }
1492
1493 // Check that types are valid in a statement.
1494
1495 int
1496 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1497 {
1498 s->check_types(this->gogo_);
1499 return TRAVERSE_CONTINUE;
1500 }
1501
1502 // Check that types are valid in an expression.
1503
1504 int
1505 Check_types_traverse::expression(Expression** expr)
1506 {
1507 (*expr)->check_types(this->gogo_);
1508 return TRAVERSE_CONTINUE;
1509 }
1510
1511 // Check that types are valid.
1512
1513 void
1514 Gogo::check_types()
1515 {
1516 Check_types_traverse traverse(this);
1517 this->traverse(&traverse);
1518 }
1519
1520 // Check the types in a single block.
1521
1522 void
1523 Gogo::check_types_in_block(Block* block)
1524 {
1525 Check_types_traverse traverse(this);
1526 block->traverse(&traverse);
1527 }
1528
1529 // A traversal class used to find a single shortcut operator within an
1530 // expression.
1531
1532 class Find_shortcut : public Traverse
1533 {
1534 public:
1535 Find_shortcut()
1536 : Traverse(traverse_blocks
1537 | traverse_statements
1538 | traverse_expressions),
1539 found_(NULL)
1540 { }
1541
1542 // A pointer to the expression which was found, or NULL if none was
1543 // found.
1544 Expression**
1545 found() const
1546 { return this->found_; }
1547
1548 protected:
1549 int
1550 block(Block*)
1551 { return TRAVERSE_SKIP_COMPONENTS; }
1552
1553 int
1554 statement(Block*, size_t*, Statement*)
1555 { return TRAVERSE_SKIP_COMPONENTS; }
1556
1557 int
1558 expression(Expression**);
1559
1560 private:
1561 Expression** found_;
1562 };
1563
1564 // Find a shortcut expression.
1565
1566 int
1567 Find_shortcut::expression(Expression** pexpr)
1568 {
1569 Expression* expr = *pexpr;
1570 Binary_expression* be = expr->binary_expression();
1571 if (be == NULL)
1572 return TRAVERSE_CONTINUE;
1573 Operator op = be->op();
1574 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1575 return TRAVERSE_CONTINUE;
1576 gcc_assert(this->found_ == NULL);
1577 this->found_ = pexpr;
1578 return TRAVERSE_EXIT;
1579 }
1580
1581 // A traversal class used to turn shortcut operators into explicit if
1582 // statements.
1583
1584 class Shortcuts : public Traverse
1585 {
1586 public:
1587 Shortcuts()
1588 : Traverse(traverse_variables
1589 | traverse_statements)
1590 { }
1591
1592 protected:
1593 int
1594 variable(Named_object*);
1595
1596 int
1597 statement(Block*, size_t*, Statement*);
1598
1599 private:
1600 // Convert a shortcut operator.
1601 Statement*
1602 convert_shortcut(Block* enclosing, Expression** pshortcut);
1603 };
1604
1605 // Remove shortcut operators in a single statement.
1606
1607 int
1608 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1609 {
1610 // FIXME: This approach doesn't work for switch statements, because
1611 // we add the new statements before the whole switch when we need to
1612 // instead add them just before the switch expression. The right
1613 // fix is probably to lower switch statements with nonconstant cases
1614 // to a series of conditionals.
1615 if (s->switch_statement() != NULL)
1616 return TRAVERSE_CONTINUE;
1617
1618 while (true)
1619 {
1620 Find_shortcut find_shortcut;
1621
1622 // If S is a variable declaration, then ordinary traversal won't
1623 // do anything. We want to explicitly traverse the
1624 // initialization expression if there is one.
1625 Variable_declaration_statement* vds = s->variable_declaration_statement();
1626 Expression* init = NULL;
1627 if (vds == NULL)
1628 s->traverse_contents(&find_shortcut);
1629 else
1630 {
1631 init = vds->var()->var_value()->init();
1632 if (init == NULL)
1633 return TRAVERSE_CONTINUE;
1634 init->traverse(&init, &find_shortcut);
1635 }
1636 Expression** pshortcut = find_shortcut.found();
1637 if (pshortcut == NULL)
1638 return TRAVERSE_CONTINUE;
1639
1640 Statement* snew = this->convert_shortcut(block, pshortcut);
1641 block->insert_statement_before(*pindex, snew);
1642 ++*pindex;
1643
1644 if (pshortcut == &init)
1645 vds->var()->var_value()->set_init(init);
1646 }
1647 }
1648
1649 // Remove shortcut operators in the initializer of a global variable.
1650
1651 int
1652 Shortcuts::variable(Named_object* no)
1653 {
1654 if (no->is_result_variable())
1655 return TRAVERSE_CONTINUE;
1656 Variable* var = no->var_value();
1657 Expression* init = var->init();
1658 if (!var->is_global() || init == NULL)
1659 return TRAVERSE_CONTINUE;
1660
1661 while (true)
1662 {
1663 Find_shortcut find_shortcut;
1664 init->traverse(&init, &find_shortcut);
1665 Expression** pshortcut = find_shortcut.found();
1666 if (pshortcut == NULL)
1667 return TRAVERSE_CONTINUE;
1668
1669 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1670 var->add_preinit_statement(snew);
1671 if (pshortcut == &init)
1672 var->set_init(init);
1673 }
1674 }
1675
1676 // Given an expression which uses a shortcut operator, return a
1677 // statement which implements it, and update *PSHORTCUT accordingly.
1678
1679 Statement*
1680 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1681 {
1682 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1683 Expression* left = shortcut->left();
1684 Expression* right = shortcut->right();
1685 source_location loc = shortcut->location();
1686
1687 Block* retblock = new Block(enclosing, loc);
1688 retblock->set_end_location(loc);
1689
1690 Temporary_statement* ts = Statement::make_temporary(Type::make_boolean_type(),
1691 left, loc);
1692 retblock->add_statement(ts);
1693
1694 Block* block = new Block(retblock, loc);
1695 block->set_end_location(loc);
1696 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1697 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1698 block->add_statement(assign);
1699
1700 Expression* cond = Expression::make_temporary_reference(ts, loc);
1701 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1702 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1703
1704 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1705 loc);
1706 retblock->add_statement(if_statement);
1707
1708 *pshortcut = Expression::make_temporary_reference(ts, loc);
1709
1710 delete shortcut;
1711
1712 // Now convert any shortcut operators in LEFT and RIGHT.
1713 Shortcuts shortcuts;
1714 retblock->traverse(&shortcuts);
1715
1716 return Statement::make_block_statement(retblock, loc);
1717 }
1718
1719 // Turn shortcut operators into explicit if statements. Doing this
1720 // considerably simplifies the order of evaluation rules.
1721
1722 void
1723 Gogo::remove_shortcuts()
1724 {
1725 Shortcuts shortcuts;
1726 this->traverse(&shortcuts);
1727 }
1728
1729 // A traversal class which finds all the expressions which must be
1730 // evaluated in order within a statement or larger expression. This
1731 // is used to implement the rules about order of evaluation.
1732
1733 class Find_eval_ordering : public Traverse
1734 {
1735 private:
1736 typedef std::vector<Expression**> Expression_pointers;
1737
1738 public:
1739 Find_eval_ordering()
1740 : Traverse(traverse_blocks
1741 | traverse_statements
1742 | traverse_expressions),
1743 exprs_()
1744 { }
1745
1746 size_t
1747 size() const
1748 { return this->exprs_.size(); }
1749
1750 typedef Expression_pointers::const_iterator const_iterator;
1751
1752 const_iterator
1753 begin() const
1754 { return this->exprs_.begin(); }
1755
1756 const_iterator
1757 end() const
1758 { return this->exprs_.end(); }
1759
1760 protected:
1761 int
1762 block(Block*)
1763 { return TRAVERSE_SKIP_COMPONENTS; }
1764
1765 int
1766 statement(Block*, size_t*, Statement*)
1767 { return TRAVERSE_SKIP_COMPONENTS; }
1768
1769 int
1770 expression(Expression**);
1771
1772 private:
1773 // A list of pointers to expressions with side-effects.
1774 Expression_pointers exprs_;
1775 };
1776
1777 // If an expression must be evaluated in order, put it on the list.
1778
1779 int
1780 Find_eval_ordering::expression(Expression** expression_pointer)
1781 {
1782 // We have to look at subexpressions before this one.
1783 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1784 return TRAVERSE_EXIT;
1785 if ((*expression_pointer)->must_eval_in_order())
1786 this->exprs_.push_back(expression_pointer);
1787 return TRAVERSE_SKIP_COMPONENTS;
1788 }
1789
1790 // A traversal class for ordering evaluations.
1791
1792 class Order_eval : public Traverse
1793 {
1794 public:
1795 Order_eval()
1796 : Traverse(traverse_variables
1797 | traverse_statements)
1798 { }
1799
1800 int
1801 variable(Named_object*);
1802
1803 int
1804 statement(Block*, size_t*, Statement*);
1805 };
1806
1807 // Implement the order of evaluation rules for a statement.
1808
1809 int
1810 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1811 {
1812 // FIXME: This approach doesn't work for switch statements, because
1813 // we add the new statements before the whole switch when we need to
1814 // instead add them just before the switch expression. The right
1815 // fix is probably to lower switch statements with nonconstant cases
1816 // to a series of conditionals.
1817 if (s->switch_statement() != NULL)
1818 return TRAVERSE_CONTINUE;
1819
1820 Find_eval_ordering find_eval_ordering;
1821
1822 // If S is a variable declaration, then ordinary traversal won't do
1823 // anything. We want to explicitly traverse the initialization
1824 // expression if there is one.
1825 Variable_declaration_statement* vds = s->variable_declaration_statement();
1826 Expression* init = NULL;
1827 Expression* orig_init = NULL;
1828 if (vds == NULL)
1829 s->traverse_contents(&find_eval_ordering);
1830 else
1831 {
1832 init = vds->var()->var_value()->init();
1833 if (init == NULL)
1834 return TRAVERSE_CONTINUE;
1835 orig_init = init;
1836
1837 // It might seem that this could be
1838 // init->traverse_subexpressions. Unfortunately that can fail
1839 // in a case like
1840 // var err os.Error
1841 // newvar, err := call(arg())
1842 // Here newvar will have an init of call result 0 of
1843 // call(arg()). If we only traverse subexpressions, we will
1844 // only find arg(), and we won't bother to move anything out.
1845 // Then we get to the assignment to err, we will traverse the
1846 // whole statement, and this time we will find both call() and
1847 // arg(), and so we will move them out. This will cause them to
1848 // be put into temporary variables before the assignment to err
1849 // but after the declaration of newvar. To avoid that problem,
1850 // we traverse the entire expression here.
1851 Expression::traverse(&init, &find_eval_ordering);
1852 }
1853
1854 if (find_eval_ordering.size() <= 1)
1855 {
1856 // If there is only one expression with a side-effect, we can
1857 // leave it in place.
1858 return TRAVERSE_CONTINUE;
1859 }
1860
1861 bool is_thunk = s->thunk_statement() != NULL;
1862 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1863 p != find_eval_ordering.end();
1864 ++p)
1865 {
1866 Expression** pexpr = *p;
1867
1868 // If the last expression is a send or receive expression, we
1869 // may be ignoring the value; we don't want to evaluate it
1870 // early.
1871 if (p + 1 == find_eval_ordering.end()
1872 && ((*pexpr)->classification() == Expression::EXPRESSION_SEND
1873 || (*pexpr)->classification() == Expression::EXPRESSION_RECEIVE))
1874 break;
1875
1876 // The last expression in a thunk will be the call passed to go
1877 // or defer, which we must not evaluate early.
1878 if (is_thunk && p + 1 == find_eval_ordering.end())
1879 break;
1880
1881 source_location loc = (*pexpr)->location();
1882 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1883 block->insert_statement_before(*pindex, ts);
1884 ++*pindex;
1885
1886 *pexpr = Expression::make_temporary_reference(ts, loc);
1887 }
1888
1889 if (init != orig_init)
1890 vds->var()->var_value()->set_init(init);
1891
1892 return TRAVERSE_CONTINUE;
1893 }
1894
1895 // Implement the order of evaluation rules for the initializer of a
1896 // global variable.
1897
1898 int
1899 Order_eval::variable(Named_object* no)
1900 {
1901 if (no->is_result_variable())
1902 return TRAVERSE_CONTINUE;
1903 Variable* var = no->var_value();
1904 Expression* init = var->init();
1905 if (!var->is_global() || init == NULL)
1906 return TRAVERSE_CONTINUE;
1907
1908 Find_eval_ordering find_eval_ordering;
1909 init->traverse_subexpressions(&find_eval_ordering);
1910
1911 if (find_eval_ordering.size() <= 1)
1912 {
1913 // If there is only one expression with a side-effect, we can
1914 // leave it in place.
1915 return TRAVERSE_SKIP_COMPONENTS;
1916 }
1917
1918 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1919 p != find_eval_ordering.end();
1920 ++p)
1921 {
1922 Expression** pexpr = *p;
1923 source_location loc = (*pexpr)->location();
1924 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1925 var->add_preinit_statement(ts);
1926 *pexpr = Expression::make_temporary_reference(ts, loc);
1927 }
1928
1929 return TRAVERSE_SKIP_COMPONENTS;
1930 }
1931
1932 // Use temporary variables to implement the order of evaluation rules.
1933
1934 void
1935 Gogo::order_evaluations()
1936 {
1937 Order_eval order_eval;
1938 this->traverse(&order_eval);
1939 }
1940
1941 // Traversal to convert calls to the predeclared recover function to
1942 // pass in an argument indicating whether it can recover from a panic
1943 // or not.
1944
1945 class Convert_recover : public Traverse
1946 {
1947 public:
1948 Convert_recover(Named_object* arg)
1949 : Traverse(traverse_expressions),
1950 arg_(arg)
1951 { }
1952
1953 protected:
1954 int
1955 expression(Expression**);
1956
1957 private:
1958 // The argument to pass to the function.
1959 Named_object* arg_;
1960 };
1961
1962 // Convert calls to recover.
1963
1964 int
1965 Convert_recover::expression(Expression** pp)
1966 {
1967 Call_expression* ce = (*pp)->call_expression();
1968 if (ce != NULL && ce->is_recover_call())
1969 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
1970 ce->location()));
1971 return TRAVERSE_CONTINUE;
1972 }
1973
1974 // Traversal for build_recover_thunks.
1975
1976 class Build_recover_thunks : public Traverse
1977 {
1978 public:
1979 Build_recover_thunks(Gogo* gogo)
1980 : Traverse(traverse_functions),
1981 gogo_(gogo)
1982 { }
1983
1984 int
1985 function(Named_object*);
1986
1987 private:
1988 Expression*
1989 can_recover_arg(source_location);
1990
1991 // General IR.
1992 Gogo* gogo_;
1993 };
1994
1995 // If this function calls recover, turn it into a thunk.
1996
1997 int
1998 Build_recover_thunks::function(Named_object* orig_no)
1999 {
2000 Function* orig_func = orig_no->func_value();
2001 if (!orig_func->calls_recover()
2002 || orig_func->is_recover_thunk()
2003 || orig_func->has_recover_thunk())
2004 return TRAVERSE_CONTINUE;
2005
2006 Gogo* gogo = this->gogo_;
2007 source_location location = orig_func->location();
2008
2009 static int count;
2010 char buf[50];
2011
2012 Function_type* orig_fntype = orig_func->type();
2013 Typed_identifier_list* new_params = new Typed_identifier_list();
2014 std::string receiver_name;
2015 if (orig_fntype->is_method())
2016 {
2017 const Typed_identifier* receiver = orig_fntype->receiver();
2018 snprintf(buf, sizeof buf, "rt.%u", count);
2019 ++count;
2020 receiver_name = buf;
2021 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2022 receiver->location()));
2023 }
2024 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2025 if (orig_params != NULL && !orig_params->empty())
2026 {
2027 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2028 p != orig_params->end();
2029 ++p)
2030 {
2031 snprintf(buf, sizeof buf, "pt.%u", count);
2032 ++count;
2033 new_params->push_back(Typed_identifier(buf, p->type(),
2034 p->location()));
2035 }
2036 }
2037 snprintf(buf, sizeof buf, "pr.%u", count);
2038 ++count;
2039 std::string can_recover_name = buf;
2040 new_params->push_back(Typed_identifier(can_recover_name,
2041 Type::make_boolean_type(),
2042 orig_fntype->location()));
2043
2044 const Typed_identifier_list* orig_results = orig_fntype->results();
2045 Typed_identifier_list* new_results;
2046 if (orig_results == NULL || orig_results->empty())
2047 new_results = NULL;
2048 else
2049 {
2050 new_results = new Typed_identifier_list();
2051 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2052 p != orig_results->end();
2053 ++p)
2054 new_results->push_back(*p);
2055 }
2056
2057 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2058 new_results,
2059 orig_fntype->location());
2060 if (orig_fntype->is_varargs())
2061 new_fntype->set_is_varargs();
2062
2063 std::string name = orig_no->name() + "$recover";
2064 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2065 location);
2066 Function *new_func = new_no->func_value();
2067 if (orig_func->enclosing() != NULL)
2068 new_func->set_enclosing(orig_func->enclosing());
2069
2070 // We build the code for the original function attached to the new
2071 // function, and then swap the original and new function bodies.
2072 // This means that existing references to the original function will
2073 // then refer to the new function. That makes this code a little
2074 // confusing, in that the reference to NEW_NO really refers to the
2075 // other function, not the one we are building.
2076
2077 Expression* closure = NULL;
2078 if (orig_func->needs_closure())
2079 {
2080 Named_object* orig_closure_no = orig_func->closure_var();
2081 Variable* orig_closure_var = orig_closure_no->var_value();
2082 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2083 true, false, location);
2084 snprintf(buf, sizeof buf, "closure.%u", count);
2085 ++count;
2086 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2087 new_var);
2088 new_func->set_closure_var(new_closure_no);
2089 closure = Expression::make_var_reference(new_closure_no, location);
2090 }
2091
2092 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2093
2094 Expression_list* args = new Expression_list();
2095 if (orig_fntype->is_method())
2096 {
2097 Named_object* rec_no = gogo->lookup(receiver_name, NULL);
2098 gcc_assert(rec_no != NULL
2099 && rec_no->is_variable()
2100 && rec_no->var_value()->is_parameter());
2101 args->push_back(Expression::make_var_reference(rec_no, location));
2102 }
2103 if (new_params != NULL)
2104 {
2105 // Note that we skip the last parameter, which is the boolean
2106 // indicating whether recover can succed.
2107 for (Typed_identifier_list::const_iterator p = new_params->begin();
2108 p + 1 != new_params->end();
2109 ++p)
2110 {
2111 Named_object* p_no = gogo->lookup(p->name(), NULL);
2112 gcc_assert(p_no != NULL
2113 && p_no->is_variable()
2114 && p_no->var_value()->is_parameter());
2115 args->push_back(Expression::make_var_reference(p_no, location));
2116 }
2117 }
2118 args->push_back(this->can_recover_arg(location));
2119
2120 Expression* call = Expression::make_call(fn, args, false, location);
2121
2122 Statement* s;
2123 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2124 s = Statement::make_statement(call);
2125 else
2126 {
2127 Expression_list* vals = new Expression_list();
2128 vals->push_back(call);
2129 s = Statement::make_return_statement(new_func->type()->results(),
2130 vals, location);
2131 }
2132 s->determine_types();
2133 gogo->add_statement(s);
2134
2135 gogo->finish_function(location);
2136
2137 // Swap the function bodies and types.
2138 new_func->swap_for_recover(orig_func);
2139 orig_func->set_is_recover_thunk();
2140 new_func->set_calls_recover();
2141 new_func->set_has_recover_thunk();
2142
2143 Bindings* orig_bindings = orig_func->block()->bindings();
2144 Bindings* new_bindings = new_func->block()->bindings();
2145 if (orig_fntype->is_method())
2146 {
2147 // We changed the receiver to be a regular parameter. We have
2148 // to update the binding accordingly in both functions.
2149 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2150 gcc_assert(orig_rec_no != NULL
2151 && orig_rec_no->is_variable()
2152 && !orig_rec_no->var_value()->is_receiver());
2153 orig_rec_no->var_value()->set_is_receiver();
2154
2155 Named_object* new_rec_no = new_bindings->lookup_local(receiver_name);
2156 gcc_assert(new_rec_no != NULL
2157 && new_rec_no->is_variable()
2158 && !new_rec_no->var_value()->is_receiver());
2159 new_rec_no->var_value()->set_is_not_receiver();
2160 }
2161
2162 // Because we flipped blocks but not types, the can_recover
2163 // parameter appears in the (now) old bindings as a parameter.
2164 // Change it to a local variable, whereupon it will be discarded.
2165 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2166 gcc_assert(can_recover_no != NULL
2167 && can_recover_no->is_variable()
2168 && can_recover_no->var_value()->is_parameter());
2169 orig_bindings->remove_binding(can_recover_no);
2170
2171 // Add the can_recover argument to the (now) new bindings, and
2172 // attach it to any recover statements.
2173 Variable* can_recover_var = new Variable(Type::make_boolean_type(), NULL,
2174 false, true, false, location);
2175 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2176 can_recover_var);
2177 Convert_recover convert_recover(can_recover_no);
2178 new_func->traverse(&convert_recover);
2179
2180 return TRAVERSE_CONTINUE;
2181 }
2182
2183 // Return the expression to pass for the .can_recover parameter to the
2184 // new function. This indicates whether a call to recover may return
2185 // non-nil. The expression is
2186 // __go_can_recover(__builtin_return_address()).
2187
2188 Expression*
2189 Build_recover_thunks::can_recover_arg(source_location location)
2190 {
2191 static Named_object* builtin_return_address;
2192 if (builtin_return_address == NULL)
2193 {
2194 const source_location bloc = BUILTINS_LOCATION;
2195
2196 Typed_identifier_list* param_types = new Typed_identifier_list();
2197 Type* uint_type = Type::lookup_integer_type("uint");
2198 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2199
2200 Typed_identifier_list* return_types = new Typed_identifier_list();
2201 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2202 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2203
2204 Function_type* fntype = Type::make_function_type(NULL, param_types,
2205 return_types, bloc);
2206 builtin_return_address =
2207 Named_object::make_function_declaration("__builtin_return_address",
2208 NULL, fntype, bloc);
2209 const char* n = "__builtin_return_address";
2210 builtin_return_address->func_declaration_value()->set_asm_name(n);
2211 }
2212
2213 static Named_object* can_recover;
2214 if (can_recover == NULL)
2215 {
2216 const source_location bloc = BUILTINS_LOCATION;
2217 Typed_identifier_list* param_types = new Typed_identifier_list();
2218 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2219 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2220 Type* boolean_type = Type::make_boolean_type();
2221 Typed_identifier_list* results = new Typed_identifier_list();
2222 results->push_back(Typed_identifier("", boolean_type, bloc));
2223 Function_type* fntype = Type::make_function_type(NULL, param_types,
2224 results, bloc);
2225 can_recover = Named_object::make_function_declaration("__go_can_recover",
2226 NULL, fntype,
2227 bloc);
2228 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2229 }
2230
2231 Expression* fn = Expression::make_func_reference(builtin_return_address,
2232 NULL, location);
2233
2234 mpz_t zval;
2235 mpz_init_set_ui(zval, 0UL);
2236 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2237 mpz_clear(zval);
2238 Expression_list *args = new Expression_list();
2239 args->push_back(zexpr);
2240
2241 Expression* call = Expression::make_call(fn, args, false, location);
2242
2243 args = new Expression_list();
2244 args->push_back(call);
2245
2246 fn = Expression::make_func_reference(can_recover, NULL, location);
2247 return Expression::make_call(fn, args, false, location);
2248 }
2249
2250 // Build thunks for functions which call recover. We build a new
2251 // function with an extra parameter, which is whether a call to
2252 // recover can succeed. We then move the body of this function to
2253 // that one. We then turn this function into a thunk which calls the
2254 // new one, passing the value of
2255 // __go_can_recover(__builtin_return_address()). The function will be
2256 // marked as not splitting the stack. This will cooperate with the
2257 // implementation of defer to make recover do the right thing.
2258
2259 void
2260 Gogo::build_recover_thunks()
2261 {
2262 Build_recover_thunks build_recover_thunks(this);
2263 this->traverse(&build_recover_thunks);
2264 }
2265
2266 // Look for named types to see whether we need to create an interface
2267 // method table.
2268
2269 class Build_method_tables : public Traverse
2270 {
2271 public:
2272 Build_method_tables(Gogo* gogo,
2273 const std::vector<Interface_type*>& interfaces)
2274 : Traverse(traverse_types),
2275 gogo_(gogo), interfaces_(interfaces)
2276 { }
2277
2278 int
2279 type(Type*);
2280
2281 private:
2282 // The IR.
2283 Gogo* gogo_;
2284 // A list of locally defined interfaces which have hidden methods.
2285 const std::vector<Interface_type*>& interfaces_;
2286 };
2287
2288 // Build all required interface method tables for types. We need to
2289 // ensure that we have an interface method table for every interface
2290 // which has a hidden method, for every named type which implements
2291 // that interface. Normally we can just build interface method tables
2292 // as we need them. However, in some cases we can require an
2293 // interface method table for an interface defined in a different
2294 // package for a type defined in that package. If that interface and
2295 // type both use a hidden method, that is OK. However, we will not be
2296 // able to build that interface method table when we need it, because
2297 // the type's hidden method will be static. So we have to build it
2298 // here, and just refer it from other packages as needed.
2299
2300 void
2301 Gogo::build_interface_method_tables()
2302 {
2303 std::vector<Interface_type*> hidden_interfaces;
2304 hidden_interfaces.reserve(this->interface_types_.size());
2305 for (std::vector<Interface_type*>::const_iterator pi =
2306 this->interface_types_.begin();
2307 pi != this->interface_types_.end();
2308 ++pi)
2309 {
2310 const Typed_identifier_list* methods = (*pi)->methods();
2311 if (methods == NULL)
2312 continue;
2313 for (Typed_identifier_list::const_iterator pm = methods->begin();
2314 pm != methods->end();
2315 ++pm)
2316 {
2317 if (Gogo::is_hidden_name(pm->name()))
2318 {
2319 hidden_interfaces.push_back(*pi);
2320 break;
2321 }
2322 }
2323 }
2324
2325 if (!hidden_interfaces.empty())
2326 {
2327 // Now traverse the tree looking for all named types.
2328 Build_method_tables bmt(this, hidden_interfaces);
2329 this->traverse(&bmt);
2330 }
2331
2332 // We no longer need the list of interfaces.
2333
2334 this->interface_types_.clear();
2335 }
2336
2337 // This is called for each type. For a named type, for each of the
2338 // interfaces with hidden methods that it implements, create the
2339 // method table.
2340
2341 int
2342 Build_method_tables::type(Type* type)
2343 {
2344 Named_type* nt = type->named_type();
2345 if (nt != NULL)
2346 {
2347 for (std::vector<Interface_type*>::const_iterator p =
2348 this->interfaces_.begin();
2349 p != this->interfaces_.end();
2350 ++p)
2351 {
2352 // We ask whether a pointer to the named type implements the
2353 // interface, because a pointer can implement more methods
2354 // than a value.
2355 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2356 {
2357 nt->interface_method_table(this->gogo_, *p, false);
2358 nt->interface_method_table(this->gogo_, *p, true);
2359 }
2360 }
2361 }
2362 return TRAVERSE_CONTINUE;
2363 }
2364
2365 // Traversal class used to check for return statements.
2366
2367 class Check_return_statements_traverse : public Traverse
2368 {
2369 public:
2370 Check_return_statements_traverse()
2371 : Traverse(traverse_functions)
2372 { }
2373
2374 int
2375 function(Named_object*);
2376 };
2377
2378 // Check that a function has a return statement if it needs one.
2379
2380 int
2381 Check_return_statements_traverse::function(Named_object* no)
2382 {
2383 Function* func = no->func_value();
2384 const Function_type* fntype = func->type();
2385 const Typed_identifier_list* results = fntype->results();
2386
2387 // We only need a return statement if there is a return value.
2388 if (results == NULL || results->empty())
2389 return TRAVERSE_CONTINUE;
2390
2391 if (func->block()->may_fall_through())
2392 error_at(func->location(), "control reaches end of non-void function");
2393
2394 return TRAVERSE_CONTINUE;
2395 }
2396
2397 // Check return statements.
2398
2399 void
2400 Gogo::check_return_statements()
2401 {
2402 Check_return_statements_traverse traverse;
2403 this->traverse(&traverse);
2404 }
2405
2406 // Get the unique prefix to use before all exported symbols. This
2407 // must be unique across the entire link.
2408
2409 const std::string&
2410 Gogo::unique_prefix() const
2411 {
2412 gcc_assert(!this->unique_prefix_.empty());
2413 return this->unique_prefix_;
2414 }
2415
2416 // Set the unique prefix to use before all exported symbols. This
2417 // comes from the command line option -fgo-prefix=XXX.
2418
2419 void
2420 Gogo::set_unique_prefix(const std::string& arg)
2421 {
2422 gcc_assert(this->unique_prefix_.empty());
2423 this->unique_prefix_ = arg;
2424 }
2425
2426 // Work out the package priority. It is one more than the maximum
2427 // priority of an imported package.
2428
2429 int
2430 Gogo::package_priority() const
2431 {
2432 int priority = 0;
2433 for (Packages::const_iterator p = this->packages_.begin();
2434 p != this->packages_.end();
2435 ++p)
2436 if (p->second->priority() > priority)
2437 priority = p->second->priority();
2438 return priority + 1;
2439 }
2440
2441 // Export identifiers as requested.
2442
2443 void
2444 Gogo::do_exports()
2445 {
2446 // For now we always stream to a section. Later we may want to
2447 // support streaming to a separate file.
2448 Stream_to_section stream;
2449
2450 Export exp(&stream);
2451 exp.register_builtin_types(this);
2452 exp.export_globals(this->package_name(),
2453 this->unique_prefix(),
2454 this->package_priority(),
2455 (this->need_init_fn_ && this->package_name() != "main"
2456 ? this->get_init_fn_name()
2457 : ""),
2458 this->imported_init_fns_,
2459 this->package_->bindings());
2460 }
2461
2462 // Class Function.
2463
2464 Function::Function(Function_type* type, Function* enclosing, Block* block,
2465 source_location location)
2466 : type_(type), enclosing_(enclosing), named_results_(NULL),
2467 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2468 defer_stack_(NULL), calls_recover_(false), is_recover_thunk_(false),
2469 has_recover_thunk_(false)
2470 {
2471 }
2472
2473 // Create the named result variables.
2474
2475 void
2476 Function::create_named_result_variables(Gogo* gogo)
2477 {
2478 const Typed_identifier_list* results = this->type_->results();
2479 if (results == NULL
2480 || results->empty()
2481 || results->front().name().empty())
2482 return;
2483
2484 this->named_results_ = new Named_results();
2485 this->named_results_->reserve(results->size());
2486
2487 Block* block = this->block_;
2488 int index = 0;
2489 for (Typed_identifier_list::const_iterator p = results->begin();
2490 p != results->end();
2491 ++p, ++index)
2492 {
2493 std::string name = p->name();
2494 if (Gogo::is_sink_name(name))
2495 {
2496 static int unnamed_result_counter;
2497 char buf[100];
2498 snprintf(buf, sizeof buf, "_$%d", unnamed_result_counter);
2499 ++unnamed_result_counter;
2500 name = gogo->pack_hidden_name(buf, false);
2501 }
2502 Result_variable* result = new Result_variable(p->type(), this, index);
2503 Named_object* no = block->bindings()->add_result_variable(name, result);
2504 this->named_results_->push_back(no);
2505 }
2506 }
2507
2508 // Return the closure variable, creating it if necessary.
2509
2510 Named_object*
2511 Function::closure_var()
2512 {
2513 if (this->closure_var_ == NULL)
2514 {
2515 // We don't know the type of the variable yet. We add fields as
2516 // we find them.
2517 source_location loc = this->type_->location();
2518 Struct_field_list* sfl = new Struct_field_list;
2519 Type* struct_type = Type::make_struct_type(sfl, loc);
2520 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2521 NULL, false, true, false, loc);
2522 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2523 // Note that the new variable is not in any binding contour.
2524 }
2525 return this->closure_var_;
2526 }
2527
2528 // Set the type of the closure variable.
2529
2530 void
2531 Function::set_closure_type()
2532 {
2533 if (this->closure_var_ == NULL)
2534 return;
2535 Named_object* closure = this->closure_var_;
2536 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2537 unsigned int index = 0;
2538 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2539 p != this->closure_fields_.end();
2540 ++p, ++index)
2541 {
2542 Named_object* no = p->first;
2543 char buf[20];
2544 snprintf(buf, sizeof buf, "%u", index);
2545 std::string n = no->name() + buf;
2546 Type* var_type;
2547 if (no->is_variable())
2548 var_type = no->var_value()->type();
2549 else
2550 var_type = no->result_var_value()->type();
2551 Type* field_type = Type::make_pointer_type(var_type);
2552 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2553 }
2554 }
2555
2556 // Return whether this function is a method.
2557
2558 bool
2559 Function::is_method() const
2560 {
2561 return this->type_->is_method();
2562 }
2563
2564 // Add a label definition.
2565
2566 Label*
2567 Function::add_label_definition(const std::string& label_name,
2568 source_location location)
2569 {
2570 Label* lnull = NULL;
2571 std::pair<Labels::iterator, bool> ins =
2572 this->labels_.insert(std::make_pair(label_name, lnull));
2573 if (ins.second)
2574 {
2575 // This is a new label.
2576 Label* label = new Label(label_name);
2577 label->define(location);
2578 ins.first->second = label;
2579 return label;
2580 }
2581 else
2582 {
2583 // The label was already in the hash table.
2584 Label* label = ins.first->second;
2585 if (!label->is_defined())
2586 {
2587 label->define(location);
2588 return label;
2589 }
2590 else
2591 {
2592 error_at(location, "redefinition of label %qs",
2593 Gogo::message_name(label_name).c_str());
2594 inform(label->location(), "previous definition of %qs was here",
2595 Gogo::message_name(label_name).c_str());
2596 return new Label(label_name);
2597 }
2598 }
2599 }
2600
2601 // Add a reference to a label.
2602
2603 Label*
2604 Function::add_label_reference(const std::string& label_name)
2605 {
2606 Label* lnull = NULL;
2607 std::pair<Labels::iterator, bool> ins =
2608 this->labels_.insert(std::make_pair(label_name, lnull));
2609 if (!ins.second)
2610 {
2611 // The label was already in the hash table.
2612 return ins.first->second;
2613 }
2614 else
2615 {
2616 gcc_assert(ins.first->second == NULL);
2617 Label* label = new Label(label_name);
2618 ins.first->second = label;
2619 return label;
2620 }
2621 }
2622
2623 // Swap one function with another. This is used when building the
2624 // thunk we use to call a function which calls recover. It may not
2625 // work for any other case.
2626
2627 void
2628 Function::swap_for_recover(Function *x)
2629 {
2630 gcc_assert(this->enclosing_ == x->enclosing_);
2631 gcc_assert(this->named_results_ == x->named_results_);
2632 std::swap(this->closure_var_, x->closure_var_);
2633 std::swap(this->block_, x->block_);
2634 gcc_assert(this->location_ == x->location_);
2635 gcc_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2636 gcc_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2637 }
2638
2639 // Traverse the tree.
2640
2641 int
2642 Function::traverse(Traverse* traverse)
2643 {
2644 unsigned int traverse_mask = traverse->traverse_mask();
2645
2646 // FIXME: We should check traverse_functions here if nested
2647 // functions are stored in block bindings.
2648 if (this->block_ != NULL
2649 && (traverse_mask
2650 & (Traverse::traverse_variables
2651 | Traverse::traverse_constants
2652 | Traverse::traverse_blocks
2653 | Traverse::traverse_statements
2654 | Traverse::traverse_expressions
2655 | Traverse::traverse_types)) != 0)
2656 {
2657 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2658 return TRAVERSE_EXIT;
2659 }
2660
2661 return TRAVERSE_CONTINUE;
2662 }
2663
2664 // Work out types for unspecified variables and constants.
2665
2666 void
2667 Function::determine_types()
2668 {
2669 if (this->block_ != NULL)
2670 this->block_->determine_types();
2671 }
2672
2673 // Export the function.
2674
2675 void
2676 Function::export_func(Export* exp, const std::string& name) const
2677 {
2678 Function::export_func_with_type(exp, name, this->type_);
2679 }
2680
2681 // Export a function with a type.
2682
2683 void
2684 Function::export_func_with_type(Export* exp, const std::string& name,
2685 const Function_type* fntype)
2686 {
2687 exp->write_c_string("func ");
2688
2689 if (fntype->is_method())
2690 {
2691 exp->write_c_string("(");
2692 exp->write_type(fntype->receiver()->type());
2693 exp->write_c_string(") ");
2694 }
2695
2696 exp->write_string(name);
2697
2698 exp->write_c_string(" (");
2699 const Typed_identifier_list* parameters = fntype->parameters();
2700 if (parameters != NULL)
2701 {
2702 bool is_varargs = fntype->is_varargs();
2703 bool first = true;
2704 for (Typed_identifier_list::const_iterator p = parameters->begin();
2705 p != parameters->end();
2706 ++p)
2707 {
2708 if (first)
2709 first = false;
2710 else
2711 exp->write_c_string(", ");
2712 if (!is_varargs || p + 1 != parameters->end())
2713 exp->write_type(p->type());
2714 else
2715 {
2716 exp->write_c_string("...");
2717 exp->write_type(p->type()->array_type()->element_type());
2718 }
2719 }
2720 }
2721 exp->write_c_string(")");
2722
2723 const Typed_identifier_list* results = fntype->results();
2724 if (results != NULL)
2725 {
2726 if (results->size() == 1)
2727 {
2728 exp->write_c_string(" ");
2729 exp->write_type(results->begin()->type());
2730 }
2731 else
2732 {
2733 exp->write_c_string(" (");
2734 bool first = true;
2735 for (Typed_identifier_list::const_iterator p = results->begin();
2736 p != results->end();
2737 ++p)
2738 {
2739 if (first)
2740 first = false;
2741 else
2742 exp->write_c_string(", ");
2743 exp->write_type(p->type());
2744 }
2745 exp->write_c_string(")");
2746 }
2747 }
2748 exp->write_c_string(";\n");
2749 }
2750
2751 // Import a function.
2752
2753 void
2754 Function::import_func(Import* imp, std::string* pname,
2755 Typed_identifier** preceiver,
2756 Typed_identifier_list** pparameters,
2757 Typed_identifier_list** presults,
2758 bool* is_varargs)
2759 {
2760 imp->require_c_string("func ");
2761
2762 *preceiver = NULL;
2763 if (imp->peek_char() == '(')
2764 {
2765 imp->require_c_string("(");
2766 Type* rtype = imp->read_type();
2767 *preceiver = new Typed_identifier(Import::import_marker, rtype,
2768 imp->location());
2769 imp->require_c_string(") ");
2770 }
2771
2772 *pname = imp->read_identifier();
2773
2774 Typed_identifier_list* parameters;
2775 *is_varargs = false;
2776 imp->require_c_string(" (");
2777 if (imp->peek_char() == ')')
2778 parameters = NULL;
2779 else
2780 {
2781 parameters = new Typed_identifier_list();
2782 while (true)
2783 {
2784 if (imp->match_c_string("..."))
2785 {
2786 imp->advance(3);
2787 *is_varargs = true;
2788 }
2789
2790 Type* ptype = imp->read_type();
2791 if (*is_varargs)
2792 ptype = Type::make_array_type(ptype, NULL);
2793 parameters->push_back(Typed_identifier(Import::import_marker,
2794 ptype, imp->location()));
2795 if (imp->peek_char() != ',')
2796 break;
2797 gcc_assert(!*is_varargs);
2798 imp->require_c_string(", ");
2799 }
2800 }
2801 imp->require_c_string(")");
2802 *pparameters = parameters;
2803
2804 Typed_identifier_list* results;
2805 if (imp->peek_char() != ' ')
2806 results = NULL;
2807 else
2808 {
2809 results = new Typed_identifier_list();
2810 imp->require_c_string(" ");
2811 if (imp->peek_char() != '(')
2812 {
2813 Type* rtype = imp->read_type();
2814 results->push_back(Typed_identifier(Import::import_marker, rtype,
2815 imp->location()));
2816 }
2817 else
2818 {
2819 imp->require_c_string("(");
2820 while (true)
2821 {
2822 Type* rtype = imp->read_type();
2823 results->push_back(Typed_identifier(Import::import_marker,
2824 rtype, imp->location()));
2825 if (imp->peek_char() != ',')
2826 break;
2827 imp->require_c_string(", ");
2828 }
2829 imp->require_c_string(")");
2830 }
2831 }
2832 imp->require_c_string(";\n");
2833 *presults = results;
2834 }
2835
2836 // Class Block.
2837
2838 Block::Block(Block* enclosing, source_location location)
2839 : enclosing_(enclosing), statements_(),
2840 bindings_(new Bindings(enclosing == NULL
2841 ? NULL
2842 : enclosing->bindings())),
2843 start_location_(location),
2844 end_location_(UNKNOWN_LOCATION)
2845 {
2846 }
2847
2848 // Add a statement to a block.
2849
2850 void
2851 Block::add_statement(Statement* statement)
2852 {
2853 this->statements_.push_back(statement);
2854 }
2855
2856 // Add a statement to the front of a block. This is slow but is only
2857 // used for reference counts of parameters.
2858
2859 void
2860 Block::add_statement_at_front(Statement* statement)
2861 {
2862 this->statements_.insert(this->statements_.begin(), statement);
2863 }
2864
2865 // Replace a statement in a block.
2866
2867 void
2868 Block::replace_statement(size_t index, Statement* s)
2869 {
2870 gcc_assert(index < this->statements_.size());
2871 this->statements_[index] = s;
2872 }
2873
2874 // Add a statement before another statement.
2875
2876 void
2877 Block::insert_statement_before(size_t index, Statement* s)
2878 {
2879 gcc_assert(index < this->statements_.size());
2880 this->statements_.insert(this->statements_.begin() + index, s);
2881 }
2882
2883 // Add a statement after another statement.
2884
2885 void
2886 Block::insert_statement_after(size_t index, Statement* s)
2887 {
2888 gcc_assert(index < this->statements_.size());
2889 this->statements_.insert(this->statements_.begin() + index + 1, s);
2890 }
2891
2892 // Traverse the tree.
2893
2894 int
2895 Block::traverse(Traverse* traverse)
2896 {
2897 unsigned int traverse_mask = traverse->traverse_mask();
2898
2899 if ((traverse_mask & Traverse::traverse_blocks) != 0)
2900 {
2901 int t = traverse->block(this);
2902 if (t == TRAVERSE_EXIT)
2903 return TRAVERSE_EXIT;
2904 else if (t == TRAVERSE_SKIP_COMPONENTS)
2905 return TRAVERSE_CONTINUE;
2906 }
2907
2908 if ((traverse_mask
2909 & (Traverse::traverse_variables
2910 | Traverse::traverse_constants
2911 | Traverse::traverse_expressions
2912 | Traverse::traverse_types)) != 0)
2913 {
2914 for (Bindings::const_definitions_iterator pb =
2915 this->bindings_->begin_definitions();
2916 pb != this->bindings_->end_definitions();
2917 ++pb)
2918 {
2919 switch ((*pb)->classification())
2920 {
2921 case Named_object::NAMED_OBJECT_CONST:
2922 if ((traverse_mask & Traverse::traverse_constants) != 0)
2923 {
2924 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
2925 return TRAVERSE_EXIT;
2926 }
2927 if ((traverse_mask & Traverse::traverse_types) != 0
2928 || (traverse_mask & Traverse::traverse_expressions) != 0)
2929 {
2930 Type* t = (*pb)->const_value()->type();
2931 if (t != NULL
2932 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
2933 return TRAVERSE_EXIT;
2934 }
2935 if ((traverse_mask & Traverse::traverse_expressions) != 0
2936 || (traverse_mask & Traverse::traverse_types) != 0)
2937 {
2938 if ((*pb)->const_value()->traverse_expression(traverse)
2939 == TRAVERSE_EXIT)
2940 return TRAVERSE_EXIT;
2941 }
2942 break;
2943
2944 case Named_object::NAMED_OBJECT_VAR:
2945 case Named_object::NAMED_OBJECT_RESULT_VAR:
2946 if ((traverse_mask & Traverse::traverse_variables) != 0)
2947 {
2948 if (traverse->variable(*pb) == TRAVERSE_EXIT)
2949 return TRAVERSE_EXIT;
2950 }
2951 if (((traverse_mask & Traverse::traverse_types) != 0
2952 || (traverse_mask & Traverse::traverse_expressions) != 0)
2953 && ((*pb)->is_result_variable()
2954 || (*pb)->var_value()->has_type()))
2955 {
2956 Type* t = ((*pb)->is_variable()
2957 ? (*pb)->var_value()->type()
2958 : (*pb)->result_var_value()->type());
2959 if (t != NULL
2960 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
2961 return TRAVERSE_EXIT;
2962 }
2963 if ((*pb)->is_variable()
2964 && ((traverse_mask & Traverse::traverse_expressions) != 0
2965 || (traverse_mask & Traverse::traverse_types) != 0))
2966 {
2967 if ((*pb)->var_value()->traverse_expression(traverse)
2968 == TRAVERSE_EXIT)
2969 return TRAVERSE_EXIT;
2970 }
2971 break;
2972
2973 case Named_object::NAMED_OBJECT_FUNC:
2974 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2975 // FIXME: Where will nested functions be found?
2976 gcc_unreachable();
2977
2978 case Named_object::NAMED_OBJECT_TYPE:
2979 if ((traverse_mask & Traverse::traverse_types) != 0
2980 || (traverse_mask & Traverse::traverse_expressions) != 0)
2981 {
2982 if (Type::traverse((*pb)->type_value(), traverse)
2983 == TRAVERSE_EXIT)
2984 return TRAVERSE_EXIT;
2985 }
2986 break;
2987
2988 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2989 case Named_object::NAMED_OBJECT_UNKNOWN:
2990 break;
2991
2992 case Named_object::NAMED_OBJECT_PACKAGE:
2993 case Named_object::NAMED_OBJECT_SINK:
2994 gcc_unreachable();
2995
2996 default:
2997 gcc_unreachable();
2998 }
2999 }
3000 }
3001
3002 // No point in checking traverse_mask here--if we got here we always
3003 // want to walk the statements. The traversal can insert new
3004 // statements before or after the current statement. Inserting
3005 // statements before the current statement requires updating I via
3006 // the pointer; those statements will not be traversed. Any new
3007 // statements inserted after the current statement will be traversed
3008 // in their turn.
3009 for (size_t i = 0; i < this->statements_.size(); ++i)
3010 {
3011 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3012 return TRAVERSE_EXIT;
3013 }
3014
3015 return TRAVERSE_CONTINUE;
3016 }
3017
3018 // Work out types for unspecified variables and constants.
3019
3020 void
3021 Block::determine_types()
3022 {
3023 for (Bindings::const_definitions_iterator pb =
3024 this->bindings_->begin_definitions();
3025 pb != this->bindings_->end_definitions();
3026 ++pb)
3027 {
3028 if ((*pb)->is_variable())
3029 (*pb)->var_value()->determine_type();
3030 else if ((*pb)->is_const())
3031 (*pb)->const_value()->determine_type();
3032 }
3033
3034 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3035 ps != this->statements_.end();
3036 ++ps)
3037 (*ps)->determine_types();
3038 }
3039
3040 // Return true if the statements in this block may fall through.
3041
3042 bool
3043 Block::may_fall_through() const
3044 {
3045 if (this->statements_.empty())
3046 return true;
3047 return this->statements_.back()->may_fall_through();
3048 }
3049
3050 // Class Variable.
3051
3052 Variable::Variable(Type* type, Expression* init, bool is_global,
3053 bool is_parameter, bool is_receiver,
3054 source_location location)
3055 : type_(type), init_(init), preinit_(NULL), location_(location),
3056 is_global_(is_global), is_parameter_(is_parameter),
3057 is_receiver_(is_receiver), is_varargs_parameter_(false),
3058 is_address_taken_(false), init_is_lowered_(false),
3059 type_from_init_tuple_(false), type_from_range_index_(false),
3060 type_from_range_value_(false), type_from_chan_element_(false),
3061 is_type_switch_var_(false)
3062 {
3063 gcc_assert(type != NULL || init != NULL);
3064 gcc_assert(!is_parameter || init == NULL);
3065 }
3066
3067 // Traverse the initializer expression.
3068
3069 int
3070 Variable::traverse_expression(Traverse* traverse)
3071 {
3072 if (this->preinit_ != NULL)
3073 {
3074 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3075 return TRAVERSE_EXIT;
3076 }
3077 if (this->init_ != NULL)
3078 {
3079 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3080 return TRAVERSE_EXIT;
3081 }
3082 return TRAVERSE_CONTINUE;
3083 }
3084
3085 // Lower the initialization expression after parsing is complete.
3086
3087 void
3088 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3089 {
3090 if (this->init_ != NULL && !this->init_is_lowered_)
3091 {
3092 gogo->lower_expression(function, &this->init_);
3093 this->init_is_lowered_ = true;
3094 }
3095 }
3096
3097 // Get the preinit block.
3098
3099 Block*
3100 Variable::preinit_block()
3101 {
3102 gcc_assert(this->is_global_);
3103 if (this->preinit_ == NULL)
3104 this->preinit_ = new Block(NULL, this->location());
3105 return this->preinit_;
3106 }
3107
3108 // Add a statement to be run before the initialization expression.
3109
3110 void
3111 Variable::add_preinit_statement(Statement* s)
3112 {
3113 Block* b = this->preinit_block();
3114 b->add_statement(s);
3115 b->set_end_location(s->location());
3116 }
3117
3118 // In an assignment which sets a variable to a tuple of EXPR, return
3119 // the type of the first element of the tuple.
3120
3121 Type*
3122 Variable::type_from_tuple(Expression* expr, bool report_error) const
3123 {
3124 if (expr->map_index_expression() != NULL)
3125 return expr->map_index_expression()->get_map_type()->val_type();
3126 else if (expr->receive_expression() != NULL)
3127 {
3128 Expression* channel = expr->receive_expression()->channel();
3129 Type* channel_type = channel->type();
3130 if (channel_type->is_error_type())
3131 return Type::make_error_type();
3132 return channel_type->channel_type()->element_type();
3133 }
3134 else
3135 {
3136 if (report_error)
3137 error_at(this->location(), "invalid tuple definition");
3138 return Type::make_error_type();
3139 }
3140 }
3141
3142 // Given EXPR used in a range clause, return either the index type or
3143 // the value type of the range, depending upon GET_INDEX_TYPE.
3144
3145 Type*
3146 Variable::type_from_range(Expression* expr, bool get_index_type,
3147 bool report_error) const
3148 {
3149 Type* t = expr->type();
3150 if (t->array_type() != NULL
3151 || (t->points_to() != NULL
3152 && t->points_to()->array_type() != NULL
3153 && !t->points_to()->is_open_array_type()))
3154 {
3155 if (get_index_type)
3156 return Type::lookup_integer_type("int");
3157 else
3158 return t->deref()->array_type()->element_type();
3159 }
3160 else if (t->is_string_type())
3161 return Type::lookup_integer_type("int");
3162 else if (t->map_type() != NULL)
3163 {
3164 if (get_index_type)
3165 return t->map_type()->key_type();
3166 else
3167 return t->map_type()->val_type();
3168 }
3169 else if (t->channel_type() != NULL)
3170 {
3171 if (get_index_type)
3172 return t->channel_type()->element_type();
3173 else
3174 {
3175 if (report_error)
3176 error_at(this->location(),
3177 "invalid definition of value variable for channel range");
3178 return Type::make_error_type();
3179 }
3180 }
3181 else
3182 {
3183 if (report_error)
3184 error_at(this->location(), "invalid type for range clause");
3185 return Type::make_error_type();
3186 }
3187 }
3188
3189 // EXPR should be a channel. Return the channel's element type.
3190
3191 Type*
3192 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3193 {
3194 Type* t = expr->type();
3195 if (t->channel_type() != NULL)
3196 return t->channel_type()->element_type();
3197 else
3198 {
3199 if (report_error)
3200 error_at(this->location(), "expected channel");
3201 return Type::make_error_type();
3202 }
3203 }
3204
3205 // Return the type of the Variable. This may be called before
3206 // Variable::determine_type is called, which means that we may need to
3207 // get the type from the initializer. FIXME: If we combine lowering
3208 // with type determination, then this should be unnecessary.
3209
3210 Type*
3211 Variable::type() const
3212 {
3213 // A variable in a type switch with a nil case will have the wrong
3214 // type here. This gets fixed up in determine_type, below.
3215 Type* type = this->type_;
3216 Expression* init = this->init_;
3217 if (this->is_type_switch_var_
3218 && this->type_->is_nil_constant_as_type())
3219 {
3220 Type_guard_expression* tge = this->init_->type_guard_expression();
3221 gcc_assert(tge != NULL);
3222 init = tge->expr();
3223 type = NULL;
3224 }
3225
3226 if (type != NULL)
3227 return type;
3228 else if (this->type_from_init_tuple_)
3229 return this->type_from_tuple(init, false);
3230 else if (this->type_from_range_index_ || this->type_from_range_value_)
3231 return this->type_from_range(init, this->type_from_range_index_, false);
3232 else if (this->type_from_chan_element_)
3233 return this->type_from_chan_element(init, false);
3234 else
3235 {
3236 gcc_assert(init != NULL);
3237 type = init->type();
3238 gcc_assert(type != NULL);
3239
3240 // Variables should not have abstract types.
3241 if (type->is_abstract())
3242 type = type->make_non_abstract_type();
3243
3244 if (type->is_void_type())
3245 type = Type::make_error_type();
3246
3247 return type;
3248 }
3249 }
3250
3251 // Set the type if necessary.
3252
3253 void
3254 Variable::determine_type()
3255 {
3256 // A variable in a type switch with a nil case will have the wrong
3257 // type here. It will have an initializer which is a type guard.
3258 // We want to initialize it to the value without the type guard, and
3259 // use the type of that value as well.
3260 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3261 {
3262 Type_guard_expression* tge = this->init_->type_guard_expression();
3263 gcc_assert(tge != NULL);
3264 this->type_ = NULL;
3265 this->init_ = tge->expr();
3266 }
3267
3268 if (this->init_ == NULL)
3269 gcc_assert(this->type_ != NULL && !this->type_->is_abstract());
3270 else if (this->type_from_init_tuple_)
3271 {
3272 Expression *init = this->init_;
3273 init->determine_type_no_context();
3274 this->type_ = this->type_from_tuple(init, true);
3275 this->init_ = NULL;
3276 }
3277 else if (this->type_from_range_index_ || this->type_from_range_value_)
3278 {
3279 Expression* init = this->init_;
3280 init->determine_type_no_context();
3281 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3282 true);
3283 this->init_ = NULL;
3284 }
3285 else
3286 {
3287 // type_from_chan_element_ should have been cleared during
3288 // lowering.
3289 gcc_assert(!this->type_from_chan_element_);
3290
3291 Type_context context(this->type_, false);
3292 this->init_->determine_type(&context);
3293 if (this->type_ == NULL)
3294 {
3295 Type* type = this->init_->type();
3296 gcc_assert(type != NULL);
3297 if (type->is_abstract())
3298 type = type->make_non_abstract_type();
3299
3300 if (type->is_void_type())
3301 {
3302 error_at(this->location_, "variable has no type");
3303 type = Type::make_error_type();
3304 }
3305 else if (type->is_nil_type())
3306 {
3307 error_at(this->location_, "variable defined to nil type");
3308 type = Type::make_error_type();
3309 }
3310 else if (type->is_call_multiple_result_type())
3311 {
3312 error_at(this->location_,
3313 "single variable set to multiple value function call");
3314 type = Type::make_error_type();
3315 }
3316
3317 this->type_ = type;
3318 }
3319 }
3320 }
3321
3322 // Export the variable
3323
3324 void
3325 Variable::export_var(Export* exp, const std::string& name) const
3326 {
3327 gcc_assert(this->is_global_);
3328 exp->write_c_string("var ");
3329 exp->write_string(name);
3330 exp->write_c_string(" ");
3331 exp->write_type(this->type());
3332 exp->write_c_string(";\n");
3333 }
3334
3335 // Import a variable.
3336
3337 void
3338 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3339 {
3340 imp->require_c_string("var ");
3341 *pname = imp->read_identifier();
3342 imp->require_c_string(" ");
3343 *ptype = imp->read_type();
3344 imp->require_c_string(";\n");
3345 }
3346
3347 // Class Named_constant.
3348
3349 // Traverse the initializer expression.
3350
3351 int
3352 Named_constant::traverse_expression(Traverse* traverse)
3353 {
3354 return Expression::traverse(&this->expr_, traverse);
3355 }
3356
3357 // Determine the type of the constant.
3358
3359 void
3360 Named_constant::determine_type()
3361 {
3362 if (this->type_ != NULL)
3363 {
3364 Type_context context(this->type_, false);
3365 this->expr_->determine_type(&context);
3366 }
3367 else
3368 {
3369 // A constant may have an abstract type.
3370 Type_context context(NULL, true);
3371 this->expr_->determine_type(&context);
3372 this->type_ = this->expr_->type();
3373 gcc_assert(this->type_ != NULL);
3374 }
3375 }
3376
3377 // Indicate that we found and reported an error for this constant.
3378
3379 void
3380 Named_constant::set_error()
3381 {
3382 this->type_ = Type::make_error_type();
3383 this->expr_ = Expression::make_error(this->location_);
3384 }
3385
3386 // Export a constant.
3387
3388 void
3389 Named_constant::export_const(Export* exp, const std::string& name) const
3390 {
3391 exp->write_c_string("const ");
3392 exp->write_string(name);
3393 exp->write_c_string(" ");
3394 if (!this->type_->is_abstract())
3395 {
3396 exp->write_type(this->type_);
3397 exp->write_c_string(" ");
3398 }
3399 exp->write_c_string("= ");
3400 this->expr()->export_expression(exp);
3401 exp->write_c_string(";\n");
3402 }
3403
3404 // Import a constant.
3405
3406 void
3407 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3408 Expression** pexpr)
3409 {
3410 imp->require_c_string("const ");
3411 *pname = imp->read_identifier();
3412 imp->require_c_string(" ");
3413 if (imp->peek_char() == '=')
3414 *ptype = NULL;
3415 else
3416 {
3417 *ptype = imp->read_type();
3418 imp->require_c_string(" ");
3419 }
3420 imp->require_c_string("= ");
3421 *pexpr = Expression::import_expression(imp);
3422 imp->require_c_string(";\n");
3423 }
3424
3425 // Add a method.
3426
3427 Named_object*
3428 Type_declaration::add_method(const std::string& name, Function* function)
3429 {
3430 Named_object* ret = Named_object::make_function(name, NULL, function);
3431 this->methods_.push_back(ret);
3432 return ret;
3433 }
3434
3435 // Add a method declaration.
3436
3437 Named_object*
3438 Type_declaration::add_method_declaration(const std::string& name,
3439 Function_type* type,
3440 source_location location)
3441 {
3442 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3443 location);
3444 this->methods_.push_back(ret);
3445 return ret;
3446 }
3447
3448 // Return whether any methods ere defined.
3449
3450 bool
3451 Type_declaration::has_methods() const
3452 {
3453 return !this->methods_.empty();
3454 }
3455
3456 // Define methods for the real type.
3457
3458 void
3459 Type_declaration::define_methods(Named_type* nt)
3460 {
3461 for (Methods::const_iterator p = this->methods_.begin();
3462 p != this->methods_.end();
3463 ++p)
3464 nt->add_existing_method(*p);
3465 }
3466
3467 // We are using the type. Return true if we should issue a warning.
3468
3469 bool
3470 Type_declaration::using_type()
3471 {
3472 bool ret = !this->issued_warning_;
3473 this->issued_warning_ = true;
3474 return ret;
3475 }
3476
3477 // Class Unknown_name.
3478
3479 // Set the real named object.
3480
3481 void
3482 Unknown_name::set_real_named_object(Named_object* no)
3483 {
3484 gcc_assert(this->real_named_object_ == NULL);
3485 gcc_assert(!no->is_unknown());
3486 this->real_named_object_ = no;
3487 }
3488
3489 // Class Named_object.
3490
3491 Named_object::Named_object(const std::string& name,
3492 const Package* package,
3493 Classification classification)
3494 : name_(name), package_(package), classification_(classification),
3495 tree_(NULL)
3496 {
3497 if (Gogo::is_sink_name(name))
3498 gcc_assert(classification == NAMED_OBJECT_SINK);
3499 }
3500
3501 // Make an unknown name. This is used by the parser. The name must
3502 // be resolved later. Unknown names are only added in the current
3503 // package.
3504
3505 Named_object*
3506 Named_object::make_unknown_name(const std::string& name,
3507 source_location location)
3508 {
3509 Named_object* named_object = new Named_object(name, NULL,
3510 NAMED_OBJECT_UNKNOWN);
3511 Unknown_name* value = new Unknown_name(location);
3512 named_object->u_.unknown_value = value;
3513 return named_object;
3514 }
3515
3516 // Make a constant.
3517
3518 Named_object*
3519 Named_object::make_constant(const Typed_identifier& tid,
3520 const Package* package, Expression* expr,
3521 int iota_value)
3522 {
3523 Named_object* named_object = new Named_object(tid.name(), package,
3524 NAMED_OBJECT_CONST);
3525 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3526 iota_value,
3527 tid.location());
3528 named_object->u_.const_value = named_constant;
3529 return named_object;
3530 }
3531
3532 // Make a named type.
3533
3534 Named_object*
3535 Named_object::make_type(const std::string& name, const Package* package,
3536 Type* type, source_location location)
3537 {
3538 Named_object* named_object = new Named_object(name, package,
3539 NAMED_OBJECT_TYPE);
3540 Named_type* named_type = Type::make_named_type(named_object, type, location);
3541 named_object->u_.type_value = named_type;
3542 return named_object;
3543 }
3544
3545 // Make a type declaration.
3546
3547 Named_object*
3548 Named_object::make_type_declaration(const std::string& name,
3549 const Package* package,
3550 source_location location)
3551 {
3552 Named_object* named_object = new Named_object(name, package,
3553 NAMED_OBJECT_TYPE_DECLARATION);
3554 Type_declaration* type_declaration = new Type_declaration(location);
3555 named_object->u_.type_declaration = type_declaration;
3556 return named_object;
3557 }
3558
3559 // Make a variable.
3560
3561 Named_object*
3562 Named_object::make_variable(const std::string& name, const Package* package,
3563 Variable* variable)
3564 {
3565 Named_object* named_object = new Named_object(name, package,
3566 NAMED_OBJECT_VAR);
3567 named_object->u_.var_value = variable;
3568 return named_object;
3569 }
3570
3571 // Make a result variable.
3572
3573 Named_object*
3574 Named_object::make_result_variable(const std::string& name,
3575 Result_variable* result)
3576 {
3577 Named_object* named_object = new Named_object(name, NULL,
3578 NAMED_OBJECT_RESULT_VAR);
3579 named_object->u_.result_var_value = result;
3580 return named_object;
3581 }
3582
3583 // Make a sink. This is used for the special blank identifier _.
3584
3585 Named_object*
3586 Named_object::make_sink()
3587 {
3588 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
3589 }
3590
3591 // Make a named function.
3592
3593 Named_object*
3594 Named_object::make_function(const std::string& name, const Package* package,
3595 Function* function)
3596 {
3597 Named_object* named_object = new Named_object(name, package,
3598 NAMED_OBJECT_FUNC);
3599 named_object->u_.func_value = function;
3600 return named_object;
3601 }
3602
3603 // Make a function declaration.
3604
3605 Named_object*
3606 Named_object::make_function_declaration(const std::string& name,
3607 const Package* package,
3608 Function_type* fntype,
3609 source_location location)
3610 {
3611 Named_object* named_object = new Named_object(name, package,
3612 NAMED_OBJECT_FUNC_DECLARATION);
3613 Function_declaration *func_decl = new Function_declaration(fntype, location);
3614 named_object->u_.func_declaration_value = func_decl;
3615 return named_object;
3616 }
3617
3618 // Make a package.
3619
3620 Named_object*
3621 Named_object::make_package(const std::string& alias, Package* package)
3622 {
3623 Named_object* named_object = new Named_object(alias, NULL,
3624 NAMED_OBJECT_PACKAGE);
3625 named_object->u_.package_value = package;
3626 return named_object;
3627 }
3628
3629 // Return the name to use in an error message.
3630
3631 std::string
3632 Named_object::message_name() const
3633 {
3634 if (this->package_ == NULL)
3635 return Gogo::message_name(this->name_);
3636 std::string ret = Gogo::message_name(this->package_->name());
3637 ret += '.';
3638 ret += Gogo::message_name(this->name_);
3639 return ret;
3640 }
3641
3642 // Set the type when a declaration is defined.
3643
3644 void
3645 Named_object::set_type_value(Named_type* named_type)
3646 {
3647 gcc_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
3648 Type_declaration* td = this->u_.type_declaration;
3649 td->define_methods(named_type);
3650 Named_object* in_function = td->in_function();
3651 if (in_function != NULL)
3652 named_type->set_in_function(in_function);
3653 delete td;
3654 this->classification_ = NAMED_OBJECT_TYPE;
3655 this->u_.type_value = named_type;
3656 }
3657
3658 // Define a function which was previously declared.
3659
3660 void
3661 Named_object::set_function_value(Function* function)
3662 {
3663 gcc_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
3664 this->classification_ = NAMED_OBJECT_FUNC;
3665 // FIXME: We should free the old value.
3666 this->u_.func_value = function;
3667 }
3668
3669 // Return the location of a named object.
3670
3671 source_location
3672 Named_object::location() const
3673 {
3674 switch (this->classification_)
3675 {
3676 default:
3677 case NAMED_OBJECT_UNINITIALIZED:
3678 gcc_unreachable();
3679
3680 case NAMED_OBJECT_UNKNOWN:
3681 return this->unknown_value()->location();
3682
3683 case NAMED_OBJECT_CONST:
3684 return this->const_value()->location();
3685
3686 case NAMED_OBJECT_TYPE:
3687 return this->type_value()->location();
3688
3689 case NAMED_OBJECT_TYPE_DECLARATION:
3690 return this->type_declaration_value()->location();
3691
3692 case NAMED_OBJECT_VAR:
3693 return this->var_value()->location();
3694
3695 case NAMED_OBJECT_RESULT_VAR:
3696 return this->result_var_value()->function()->location();
3697
3698 case NAMED_OBJECT_SINK:
3699 gcc_unreachable();
3700
3701 case NAMED_OBJECT_FUNC:
3702 return this->func_value()->location();
3703
3704 case NAMED_OBJECT_FUNC_DECLARATION:
3705 return this->func_declaration_value()->location();
3706
3707 case NAMED_OBJECT_PACKAGE:
3708 return this->package_value()->location();
3709 }
3710 }
3711
3712 // Export a named object.
3713
3714 void
3715 Named_object::export_named_object(Export* exp) const
3716 {
3717 switch (this->classification_)
3718 {
3719 default:
3720 case NAMED_OBJECT_UNINITIALIZED:
3721 case NAMED_OBJECT_UNKNOWN:
3722 gcc_unreachable();
3723
3724 case NAMED_OBJECT_CONST:
3725 this->const_value()->export_const(exp, this->name_);
3726 break;
3727
3728 case NAMED_OBJECT_TYPE:
3729 this->type_value()->export_named_type(exp, this->name_);
3730 break;
3731
3732 case NAMED_OBJECT_TYPE_DECLARATION:
3733 error_at(this->type_declaration_value()->location(),
3734 "attempt to export %<%s%> which was declared but not defined",
3735 this->message_name().c_str());
3736 break;
3737
3738 case NAMED_OBJECT_FUNC_DECLARATION:
3739 this->func_declaration_value()->export_func(exp, this->name_);
3740 break;
3741
3742 case NAMED_OBJECT_VAR:
3743 this->var_value()->export_var(exp, this->name_);
3744 break;
3745
3746 case NAMED_OBJECT_RESULT_VAR:
3747 case NAMED_OBJECT_SINK:
3748 gcc_unreachable();
3749
3750 case NAMED_OBJECT_FUNC:
3751 this->func_value()->export_func(exp, this->name_);
3752 break;
3753 }
3754 }
3755
3756 // Class Bindings.
3757
3758 Bindings::Bindings(Bindings* enclosing)
3759 : enclosing_(enclosing), named_objects_(), bindings_()
3760 {
3761 }
3762
3763 // Clear imports.
3764
3765 void
3766 Bindings::clear_file_scope()
3767 {
3768 Contour::iterator p = this->bindings_.begin();
3769 while (p != this->bindings_.end())
3770 {
3771 bool keep;
3772 if (p->second->package() != NULL)
3773 keep = false;
3774 else if (p->second->is_package())
3775 keep = false;
3776 else if (p->second->is_function()
3777 && !p->second->func_value()->type()->is_method()
3778 && Gogo::unpack_hidden_name(p->second->name()) == "init")
3779 keep = false;
3780 else
3781 keep = true;
3782
3783 if (keep)
3784 ++p;
3785 else
3786 p = this->bindings_.erase(p);
3787 }
3788 }
3789
3790 // Look up a symbol.
3791
3792 Named_object*
3793 Bindings::lookup(const std::string& name) const
3794 {
3795 Contour::const_iterator p = this->bindings_.find(name);
3796 if (p != this->bindings_.end())
3797 return p->second->resolve();
3798 else if (this->enclosing_ != NULL)
3799 return this->enclosing_->lookup(name);
3800 else
3801 return NULL;
3802 }
3803
3804 // Look up a symbol locally.
3805
3806 Named_object*
3807 Bindings::lookup_local(const std::string& name) const
3808 {
3809 Contour::const_iterator p = this->bindings_.find(name);
3810 if (p == this->bindings_.end())
3811 return NULL;
3812 return p->second;
3813 }
3814
3815 // Remove an object from a set of bindings. This is used for a
3816 // special case in thunks for functions which call recover.
3817
3818 void
3819 Bindings::remove_binding(Named_object* no)
3820 {
3821 Contour::iterator pb = this->bindings_.find(no->name());
3822 gcc_assert(pb != this->bindings_.end());
3823 this->bindings_.erase(pb);
3824 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
3825 pn != this->named_objects_.end();
3826 ++pn)
3827 {
3828 if (*pn == no)
3829 {
3830 this->named_objects_.erase(pn);
3831 return;
3832 }
3833 }
3834 gcc_unreachable();
3835 }
3836
3837 // Add a method to the list of objects. This is not added to the
3838 // lookup table. This is so that we have a single list of objects
3839 // declared at the top level, which we walk through when it's time to
3840 // convert to trees.
3841
3842 void
3843 Bindings::add_method(Named_object* method)
3844 {
3845 this->named_objects_.push_back(method);
3846 }
3847
3848 // Add a generic Named_object to a Contour.
3849
3850 Named_object*
3851 Bindings::add_named_object_to_contour(Contour* contour,
3852 Named_object* named_object)
3853 {
3854 gcc_assert(named_object == named_object->resolve());
3855 const std::string& name(named_object->name());
3856 gcc_assert(!Gogo::is_sink_name(name));
3857
3858 std::pair<Contour::iterator, bool> ins =
3859 contour->insert(std::make_pair(name, named_object));
3860 if (!ins.second)
3861 {
3862 // The name was already there.
3863 if (named_object->package() != NULL
3864 && ins.first->second->package() == named_object->package()
3865 && (ins.first->second->classification()
3866 == named_object->classification()))
3867 {
3868 // This is a second import of the same object.
3869 return ins.first->second;
3870 }
3871 ins.first->second = this->new_definition(ins.first->second,
3872 named_object);
3873 return ins.first->second;
3874 }
3875 else
3876 {
3877 // Don't push declarations on the list. We push them on when
3878 // and if we find the definitions. That way we genericize the
3879 // functions in order.
3880 if (!named_object->is_type_declaration()
3881 && !named_object->is_function_declaration()
3882 && !named_object->is_unknown())
3883 this->named_objects_.push_back(named_object);
3884 return named_object;
3885 }
3886 }
3887
3888 // We had an existing named object OLD_OBJECT, and we've seen a new
3889 // one NEW_OBJECT with the same name. FIXME: This does not free the
3890 // new object when we don't need it.
3891
3892 Named_object*
3893 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
3894 {
3895 std::string reason;
3896 switch (old_object->classification())
3897 {
3898 default:
3899 case Named_object::NAMED_OBJECT_UNINITIALIZED:
3900 gcc_unreachable();
3901
3902 case Named_object::NAMED_OBJECT_UNKNOWN:
3903 {
3904 Named_object* real = old_object->unknown_value()->real_named_object();
3905 if (real != NULL)
3906 return this->new_definition(real, new_object);
3907 gcc_assert(!new_object->is_unknown());
3908 old_object->unknown_value()->set_real_named_object(new_object);
3909 if (!new_object->is_type_declaration()
3910 && !new_object->is_function_declaration())
3911 this->named_objects_.push_back(new_object);
3912 return new_object;
3913 }
3914
3915 case Named_object::NAMED_OBJECT_CONST:
3916 break;
3917
3918 case Named_object::NAMED_OBJECT_TYPE:
3919 if (new_object->is_type_declaration())
3920 return old_object;
3921 break;
3922
3923 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3924 if (new_object->is_type_declaration())
3925 return old_object;
3926 if (new_object->is_type())
3927 {
3928 old_object->set_type_value(new_object->type_value());
3929 new_object->type_value()->set_named_object(old_object);
3930 this->named_objects_.push_back(old_object);
3931 return old_object;
3932 }
3933 break;
3934
3935 case Named_object::NAMED_OBJECT_VAR:
3936 case Named_object::NAMED_OBJECT_RESULT_VAR:
3937 break;
3938
3939 case Named_object::NAMED_OBJECT_SINK:
3940 gcc_unreachable();
3941
3942 case Named_object::NAMED_OBJECT_FUNC:
3943 if (new_object->is_function_declaration())
3944 {
3945 if (!new_object->func_declaration_value()->asm_name().empty())
3946 sorry("__asm__ for function definitions");
3947 Function_type* old_type = old_object->func_value()->type();
3948 Function_type* new_type =
3949 new_object->func_declaration_value()->type();
3950 if (old_type->is_valid_redeclaration(new_type, &reason))
3951 return old_object;
3952 }
3953 break;
3954
3955 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3956 {
3957 Function_type* old_type = old_object->func_declaration_value()->type();
3958 if (new_object->is_function_declaration())
3959 {
3960 Function_type* new_type =
3961 new_object->func_declaration_value()->type();
3962 if (old_type->is_valid_redeclaration(new_type, &reason))
3963 return old_object;
3964 }
3965 if (new_object->is_function())
3966 {
3967 Function_type* new_type = new_object->func_value()->type();
3968 if (old_type->is_valid_redeclaration(new_type, &reason))
3969 {
3970 if (!old_object->func_declaration_value()->asm_name().empty())
3971 sorry("__asm__ for function definitions");
3972 old_object->set_function_value(new_object->func_value());
3973 this->named_objects_.push_back(old_object);
3974 return old_object;
3975 }
3976 }
3977 }
3978 break;
3979
3980 case Named_object::NAMED_OBJECT_PACKAGE:
3981 if (new_object->is_package()
3982 && (old_object->package_value()->name()
3983 == new_object->package_value()->name()))
3984 return old_object;
3985
3986 break;
3987 }
3988
3989 std::string n = old_object->message_name();
3990 if (reason.empty())
3991 error_at(new_object->location(), "redefinition of %qs", n.c_str());
3992 else
3993 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
3994 reason.c_str());
3995
3996 inform(old_object->location(), "previous definition of %qs was here",
3997 n.c_str());
3998
3999 return old_object;
4000 }
4001
4002 // Add a named type.
4003
4004 Named_object*
4005 Bindings::add_named_type(Named_type* named_type)
4006 {
4007 return this->add_named_object(named_type->named_object());
4008 }
4009
4010 // Add a function.
4011
4012 Named_object*
4013 Bindings::add_function(const std::string& name, const Package* package,
4014 Function* function)
4015 {
4016 return this->add_named_object(Named_object::make_function(name, package,
4017 function));
4018 }
4019
4020 // Add a function declaration.
4021
4022 Named_object*
4023 Bindings::add_function_declaration(const std::string& name,
4024 const Package* package,
4025 Function_type* type,
4026 source_location location)
4027 {
4028 Named_object* no = Named_object::make_function_declaration(name, package,
4029 type, location);
4030 return this->add_named_object(no);
4031 }
4032
4033 // Define a type which was previously declared.
4034
4035 void
4036 Bindings::define_type(Named_object* no, Named_type* type)
4037 {
4038 no->set_type_value(type);
4039 this->named_objects_.push_back(no);
4040 }
4041
4042 // Traverse bindings.
4043
4044 int
4045 Bindings::traverse(Traverse* traverse, bool is_global)
4046 {
4047 unsigned int traverse_mask = traverse->traverse_mask();
4048
4049 // We don't use an iterator because we permit the traversal to add
4050 // new global objects.
4051 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4052 {
4053 Named_object* p = this->named_objects_[i];
4054 switch (p->classification())
4055 {
4056 case Named_object::NAMED_OBJECT_CONST:
4057 if ((traverse_mask & Traverse::traverse_constants) != 0)
4058 {
4059 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4060 return TRAVERSE_EXIT;
4061 }
4062 if ((traverse_mask & Traverse::traverse_types) != 0
4063 || (traverse_mask & Traverse::traverse_expressions) != 0)
4064 {
4065 Type* t = p->const_value()->type();
4066 if (t != NULL
4067 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4068 return TRAVERSE_EXIT;
4069 }
4070 if ((traverse_mask & Traverse::traverse_expressions) != 0)
4071 {
4072 if (p->const_value()->traverse_expression(traverse)
4073 == TRAVERSE_EXIT)
4074 return TRAVERSE_EXIT;
4075 }
4076 break;
4077
4078 case Named_object::NAMED_OBJECT_VAR:
4079 case Named_object::NAMED_OBJECT_RESULT_VAR:
4080 if ((traverse_mask & Traverse::traverse_variables) != 0)
4081 {
4082 if (traverse->variable(p) == TRAVERSE_EXIT)
4083 return TRAVERSE_EXIT;
4084 }
4085 if (((traverse_mask & Traverse::traverse_types) != 0
4086 || (traverse_mask & Traverse::traverse_expressions) != 0)
4087 && (p->is_result_variable()
4088 || p->var_value()->has_type()))
4089 {
4090 Type* t = (p->is_variable()
4091 ? p->var_value()->type()
4092 : p->result_var_value()->type());
4093 if (t != NULL
4094 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4095 return TRAVERSE_EXIT;
4096 }
4097 if (p->is_variable()
4098 && (traverse_mask & Traverse::traverse_expressions) != 0)
4099 {
4100 if (p->var_value()->traverse_expression(traverse)
4101 == TRAVERSE_EXIT)
4102 return TRAVERSE_EXIT;
4103 }
4104 break;
4105
4106 case Named_object::NAMED_OBJECT_FUNC:
4107 if ((traverse_mask & Traverse::traverse_functions) != 0)
4108 {
4109 int t = traverse->function(p);
4110 if (t == TRAVERSE_EXIT)
4111 return TRAVERSE_EXIT;
4112 else if (t == TRAVERSE_SKIP_COMPONENTS)
4113 break;
4114 }
4115
4116 if ((traverse_mask
4117 & (Traverse::traverse_variables
4118 | Traverse::traverse_constants
4119 | Traverse::traverse_functions
4120 | Traverse::traverse_blocks
4121 | Traverse::traverse_statements
4122 | Traverse::traverse_expressions
4123 | Traverse::traverse_types)) != 0)
4124 {
4125 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4126 return TRAVERSE_EXIT;
4127 }
4128 break;
4129
4130 case Named_object::NAMED_OBJECT_PACKAGE:
4131 // These are traversed in Gogo::traverse.
4132 gcc_assert(is_global);
4133 break;
4134
4135 case Named_object::NAMED_OBJECT_TYPE:
4136 if ((traverse_mask & Traverse::traverse_types) != 0
4137 || (traverse_mask & Traverse::traverse_expressions) != 0)
4138 {
4139 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4140 return TRAVERSE_EXIT;
4141 }
4142 break;
4143
4144 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4145 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4146 case Named_object::NAMED_OBJECT_UNKNOWN:
4147 break;
4148
4149 case Named_object::NAMED_OBJECT_SINK:
4150 default:
4151 gcc_unreachable();
4152 }
4153 }
4154
4155 return TRAVERSE_CONTINUE;
4156 }
4157
4158 // Class Package.
4159
4160 Package::Package(const std::string& name, const std::string& unique_prefix,
4161 source_location location)
4162 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4163 priority_(0), location_(location), used_(false), is_imported_(false),
4164 uses_sink_alias_(false)
4165 {
4166 gcc_assert(!name.empty() && !unique_prefix.empty());
4167 }
4168
4169 // Set the priority. We may see multiple priorities for an imported
4170 // package; we want to use the largest one.
4171
4172 void
4173 Package::set_priority(int priority)
4174 {
4175 if (priority > this->priority_)
4176 this->priority_ = priority;
4177 }
4178
4179 // Determine types of constants. Everything else in a package
4180 // (variables, function declarations) should already have a fixed
4181 // type. Constants may have abstract types.
4182
4183 void
4184 Package::determine_types()
4185 {
4186 Bindings* bindings = this->bindings_;
4187 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4188 p != bindings->end_definitions();
4189 ++p)
4190 {
4191 if ((*p)->is_const())
4192 (*p)->const_value()->determine_type();
4193 }
4194 }
4195
4196 // Class Traverse.
4197
4198 // Destructor.
4199
4200 Traverse::~Traverse()
4201 {
4202 if (this->types_seen_ != NULL)
4203 delete this->types_seen_;
4204 if (this->expressions_seen_ != NULL)
4205 delete this->expressions_seen_;
4206 }
4207
4208 // Record that we are looking at a type, and return true if we have
4209 // already seen it.
4210
4211 bool
4212 Traverse::remember_type(const Type* type)
4213 {
4214 if (type->is_error_type())
4215 return true;
4216 gcc_assert((this->traverse_mask() & traverse_types) != 0
4217 || (this->traverse_mask() & traverse_expressions) != 0);
4218 // We only have to remember named types, as they are the only ones
4219 // we can see multiple times in a traversal.
4220 if (type->classification() != Type::TYPE_NAMED)
4221 return false;
4222 if (this->types_seen_ == NULL)
4223 this->types_seen_ = new Types_seen();
4224 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4225 return !ins.second;
4226 }
4227
4228 // Record that we are looking at an expression, and return true if we
4229 // have already seen it.
4230
4231 bool
4232 Traverse::remember_expression(const Expression* expression)
4233 {
4234 gcc_assert((this->traverse_mask() & traverse_types) != 0
4235 || (this->traverse_mask() & traverse_expressions) != 0);
4236 if (this->expressions_seen_ == NULL)
4237 this->expressions_seen_ = new Expressions_seen();
4238 std::pair<Expressions_seen::iterator, bool> ins =
4239 this->expressions_seen_->insert(expression);
4240 return !ins.second;
4241 }
4242
4243 // The default versions of these functions should never be called: the
4244 // traversal mask indicates which functions may be called.
4245
4246 int
4247 Traverse::variable(Named_object*)
4248 {
4249 gcc_unreachable();
4250 }
4251
4252 int
4253 Traverse::constant(Named_object*, bool)
4254 {
4255 gcc_unreachable();
4256 }
4257
4258 int
4259 Traverse::function(Named_object*)
4260 {
4261 gcc_unreachable();
4262 }
4263
4264 int
4265 Traverse::block(Block*)
4266 {
4267 gcc_unreachable();
4268 }
4269
4270 int
4271 Traverse::statement(Block*, size_t*, Statement*)
4272 {
4273 gcc_unreachable();
4274 }
4275
4276 int
4277 Traverse::expression(Expression**)
4278 {
4279 gcc_unreachable();
4280 }
4281
4282 int
4283 Traverse::type(Type*)
4284 {
4285 gcc_unreachable();
4286 }