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