compiler: add an option to emit optimization diagnostics
[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 <fstream>
10
11 #include "filenames.h"
12
13 #include "go-c.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
16 #include "go-dump.h"
17 #include "go-optimize.h"
18 #include "lex.h"
19 #include "types.h"
20 #include "statements.h"
21 #include "expressions.h"
22 #include "runtime.h"
23 #include "import.h"
24 #include "export.h"
25 #include "backend.h"
26 #include "gogo.h"
27
28 // Class Gogo.
29
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31 : backend_(backend),
32 linemap_(linemap),
33 package_(NULL),
34 functions_(),
35 globals_(new Bindings(NULL)),
36 file_block_names_(),
37 imports_(),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 packages_(),
41 init_functions_(),
42 var_deps_(),
43 need_init_fn_(false),
44 init_fn_name_(),
45 imported_init_fns_(),
46 pkgpath_(),
47 pkgpath_symbol_(),
48 prefix_(),
49 pkgpath_set_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
53 c_header_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 debug_optimization_(false),
59 nil_check_size_threshold_(4096),
60 verify_types_(),
61 interface_types_(),
62 specific_type_functions_(),
63 specific_type_functions_are_written_(false),
64 named_types_are_converted_(false),
65 analysis_sets_(),
66 gc_roots_(),
67 imported_inlinable_functions_(),
68 imported_inline_functions_()
69 {
70 const Location loc = Linemap::predeclared_location();
71
72 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
73 RUNTIME_TYPE_KIND_UINT8);
74 this->add_named_type(uint8_type);
75 this->add_named_type(Type::make_integer_type("uint16", true, 16,
76 RUNTIME_TYPE_KIND_UINT16));
77 this->add_named_type(Type::make_integer_type("uint32", true, 32,
78 RUNTIME_TYPE_KIND_UINT32));
79 this->add_named_type(Type::make_integer_type("uint64", true, 64,
80 RUNTIME_TYPE_KIND_UINT64));
81
82 this->add_named_type(Type::make_integer_type("int8", false, 8,
83 RUNTIME_TYPE_KIND_INT8));
84 this->add_named_type(Type::make_integer_type("int16", false, 16,
85 RUNTIME_TYPE_KIND_INT16));
86 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
87 RUNTIME_TYPE_KIND_INT32);
88 this->add_named_type(int32_type);
89 this->add_named_type(Type::make_integer_type("int64", false, 64,
90 RUNTIME_TYPE_KIND_INT64));
91
92 this->add_named_type(Type::make_float_type("float32", 32,
93 RUNTIME_TYPE_KIND_FLOAT32));
94 this->add_named_type(Type::make_float_type("float64", 64,
95 RUNTIME_TYPE_KIND_FLOAT64));
96
97 this->add_named_type(Type::make_complex_type("complex64", 64,
98 RUNTIME_TYPE_KIND_COMPLEX64));
99 this->add_named_type(Type::make_complex_type("complex128", 128,
100 RUNTIME_TYPE_KIND_COMPLEX128));
101
102 int int_type_size = pointer_size;
103 if (int_type_size < 32)
104 int_type_size = 32;
105 this->add_named_type(Type::make_integer_type("uint", true,
106 int_type_size,
107 RUNTIME_TYPE_KIND_UINT));
108 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
109 RUNTIME_TYPE_KIND_INT);
110 this->add_named_type(int_type);
111
112 this->add_named_type(Type::make_integer_type("uintptr", true,
113 pointer_size,
114 RUNTIME_TYPE_KIND_UINTPTR));
115
116 // "byte" is an alias for "uint8".
117 uint8_type->integer_type()->set_is_byte();
118 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
119 loc);
120 byte_type->type_value()->set_is_alias();
121 this->add_named_type(byte_type->type_value());
122
123 // "rune" is an alias for "int32".
124 int32_type->integer_type()->set_is_rune();
125 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
126 loc);
127 rune_type->type_value()->set_is_alias();
128 this->add_named_type(rune_type->type_value());
129
130 this->add_named_type(Type::make_named_bool_type());
131
132 this->add_named_type(Type::make_named_string_type());
133
134 // "error" is interface { Error() string }.
135 {
136 Typed_identifier_list *methods = new Typed_identifier_list;
137 Typed_identifier_list *results = new Typed_identifier_list;
138 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
139 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
140 methods->push_back(Typed_identifier("Error", method_type, loc));
141 Interface_type *error_iface = Type::make_interface_type(methods, loc);
142 error_iface->finalize_methods();
143 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
144 this->add_named_type(error_type);
145 }
146
147 this->globals_->add_constant(Typed_identifier("true",
148 Type::make_boolean_type(),
149 loc),
150 NULL,
151 Expression::make_boolean(true, loc),
152 0);
153 this->globals_->add_constant(Typed_identifier("false",
154 Type::make_boolean_type(),
155 loc),
156 NULL,
157 Expression::make_boolean(false, loc),
158 0);
159
160 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
161 loc),
162 NULL,
163 Expression::make_nil(loc),
164 0);
165
166 Type* abstract_int_type = Type::make_abstract_integer_type();
167 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
168 loc),
169 NULL,
170 Expression::make_iota(),
171 0);
172
173 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
174 new_type->set_is_varargs();
175 new_type->set_is_builtin();
176 this->globals_->add_function_declaration("new", NULL, new_type, loc);
177
178 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
179 make_type->set_is_varargs();
180 make_type->set_is_builtin();
181 this->globals_->add_function_declaration("make", NULL, make_type, loc);
182
183 Typed_identifier_list* len_result = new Typed_identifier_list();
184 len_result->push_back(Typed_identifier("", int_type, loc));
185 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
186 loc);
187 len_type->set_is_builtin();
188 this->globals_->add_function_declaration("len", NULL, len_type, loc);
189
190 Typed_identifier_list* cap_result = new Typed_identifier_list();
191 cap_result->push_back(Typed_identifier("", int_type, loc));
192 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
193 loc);
194 cap_type->set_is_builtin();
195 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
196
197 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 print_type->set_is_varargs();
199 print_type->set_is_builtin();
200 this->globals_->add_function_declaration("print", NULL, print_type, loc);
201
202 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 print_type->set_is_varargs();
204 print_type->set_is_builtin();
205 this->globals_->add_function_declaration("println", NULL, print_type, loc);
206
207 Type *empty = Type::make_empty_interface_type(loc);
208 Typed_identifier_list* panic_parms = new Typed_identifier_list();
209 panic_parms->push_back(Typed_identifier("e", empty, loc));
210 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
211 NULL, loc);
212 panic_type->set_is_builtin();
213 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
214
215 Typed_identifier_list* recover_result = new Typed_identifier_list();
216 recover_result->push_back(Typed_identifier("", empty, loc));
217 Function_type* recover_type = Type::make_function_type(NULL, NULL,
218 recover_result,
219 loc);
220 recover_type->set_is_builtin();
221 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
222
223 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
224 close_type->set_is_varargs();
225 close_type->set_is_builtin();
226 this->globals_->add_function_declaration("close", NULL, close_type, loc);
227
228 Typed_identifier_list* copy_result = new Typed_identifier_list();
229 copy_result->push_back(Typed_identifier("", int_type, loc));
230 Function_type* copy_type = Type::make_function_type(NULL, NULL,
231 copy_result, loc);
232 copy_type->set_is_varargs();
233 copy_type->set_is_builtin();
234 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
235
236 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
237 append_type->set_is_varargs();
238 append_type->set_is_builtin();
239 this->globals_->add_function_declaration("append", NULL, append_type, loc);
240
241 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
242 complex_type->set_is_varargs();
243 complex_type->set_is_builtin();
244 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
245
246 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
247 real_type->set_is_varargs();
248 real_type->set_is_builtin();
249 this->globals_->add_function_declaration("real", NULL, real_type, loc);
250
251 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
252 imag_type->set_is_varargs();
253 imag_type->set_is_builtin();
254 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
255
256 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
257 delete_type->set_is_varargs();
258 delete_type->set_is_builtin();
259 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
260 }
261
262 std::string
263 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
264 {
265 go_assert(!pkgpath.empty());
266 return go_encode_id(pkgpath);
267 }
268
269 // Return a hash code for a string, given a starting hash.
270
271 unsigned int
272 Gogo::hash_string(const std::string& s, unsigned int h)
273 {
274 const char* p = s.data();
275 size_t len = s.length();
276 for (; len > 0; --len)
277 {
278 h ^= *p++;
279 h*= 16777619;
280 }
281 return h;
282 }
283
284 // Get the package path to use for type reflection data. This should
285 // ideally be unique across the entire link.
286
287 const std::string&
288 Gogo::pkgpath() const
289 {
290 go_assert(this->pkgpath_set_);
291 return this->pkgpath_;
292 }
293
294 // Set the package path from the -fgo-pkgpath command line option.
295
296 void
297 Gogo::set_pkgpath(const std::string& arg)
298 {
299 go_assert(!this->pkgpath_set_);
300 this->pkgpath_ = arg;
301 this->pkgpath_set_ = true;
302 this->pkgpath_from_option_ = true;
303 }
304
305 // Get the package path to use for symbol names.
306
307 const std::string&
308 Gogo::pkgpath_symbol() const
309 {
310 go_assert(this->pkgpath_set_);
311 return this->pkgpath_symbol_;
312 }
313
314 // Set the unique prefix to use to determine the package path, from
315 // the -fgo-prefix command line option.
316
317 void
318 Gogo::set_prefix(const std::string& arg)
319 {
320 go_assert(!this->prefix_from_option_);
321 this->prefix_ = arg;
322 this->prefix_from_option_ = true;
323 }
324
325 // Given a name which may or may not have been hidden, append the
326 // appropriate version of the name to the result string. Take care
327 // to avoid creating a sequence that will be rejected by go_encode_id
328 // (avoid ..u, ..U, ..z).
329 void
330 Gogo::append_possibly_hidden_name(std::string *result, const std::string& name)
331 {
332 // FIXME: This adds in pkgpath twice for hidden symbols, which is
333 // less than ideal.
334 if (!Gogo::is_hidden_name(name))
335 (*result) += name;
336 else
337 {
338 std::string n = ".";
339 std::string pkgpath = Gogo::hidden_name_pkgpath(name);
340 char lastR = result->at(result->length() - 1);
341 char firstP = pkgpath.at(0);
342 if (lastR == '.' && (firstP == 'u' || firstP == 'U' || firstP == 'z'))
343 n = "_.";
344 n.append(pkgpath);
345 n.append(1, '.');
346 n.append(Gogo::unpack_hidden_name(name));
347 (*result) += n;
348 }
349 }
350
351 // Munge name for use in an error message.
352
353 std::string
354 Gogo::message_name(const std::string& name)
355 {
356 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
357 }
358
359 // Get the package name.
360
361 const std::string&
362 Gogo::package_name() const
363 {
364 go_assert(this->package_ != NULL);
365 return this->package_->package_name();
366 }
367
368 // Set the package name.
369
370 void
371 Gogo::set_package_name(const std::string& package_name,
372 Location location)
373 {
374 if (this->package_ != NULL)
375 {
376 if (this->package_->package_name() != package_name)
377 go_error_at(location, "expected package %<%s%>",
378 Gogo::message_name(this->package_->package_name()).c_str());
379 return;
380 }
381
382 // Now that we know the name of the package we are compiling, set
383 // the package path to use for reflect.Type.PkgPath and global
384 // symbol names.
385 if (this->pkgpath_set_)
386 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
387 else
388 {
389 if (!this->prefix_from_option_ && package_name == "main")
390 {
391 this->pkgpath_ = package_name;
392 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
393 }
394 else
395 {
396 if (!this->prefix_from_option_)
397 this->prefix_ = "go";
398 this->pkgpath_ = this->prefix_ + '.' + package_name;
399 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
400 + Gogo::pkgpath_for_symbol(package_name));
401 }
402 this->pkgpath_set_ = true;
403 }
404
405 this->package_ = this->register_package(this->pkgpath_,
406 this->pkgpath_symbol_, location);
407 this->package_->set_package_name(package_name, location);
408
409 if (this->is_main_package())
410 {
411 // Declare "main" as a function which takes no parameters and
412 // returns no value.
413 Location uloc = Linemap::unknown_location();
414 this->declare_function(Gogo::pack_hidden_name("main", false),
415 Type::make_function_type (NULL, NULL, NULL, uloc),
416 uloc);
417 }
418 }
419
420 // Return whether this is the "main" package. This is not true if
421 // -fgo-pkgpath or -fgo-prefix was used.
422
423 bool
424 Gogo::is_main_package() const
425 {
426 return (this->package_name() == "main"
427 && !this->pkgpath_from_option_
428 && !this->prefix_from_option_);
429 }
430
431 // Import a package.
432
433 void
434 Gogo::import_package(const std::string& filename,
435 const std::string& local_name,
436 bool is_local_name_exported,
437 bool must_exist,
438 Location location)
439 {
440 if (filename.empty())
441 {
442 go_error_at(location, "import path is empty");
443 return;
444 }
445
446 const char *pf = filename.data();
447 const char *pend = pf + filename.length();
448 while (pf < pend)
449 {
450 unsigned int c;
451 int adv = Lex::fetch_char(pf, &c);
452 if (adv == 0)
453 {
454 go_error_at(location, "import path contains invalid UTF-8 sequence");
455 return;
456 }
457 if (c == '\0')
458 {
459 go_error_at(location, "import path contains NUL");
460 return;
461 }
462 if (c < 0x20 || c == 0x7f)
463 {
464 go_error_at(location, "import path contains control character");
465 return;
466 }
467 if (c == '\\')
468 {
469 go_error_at(location, "import path contains backslash; use slash");
470 return;
471 }
472 if (Lex::is_unicode_space(c))
473 {
474 go_error_at(location, "import path contains space character");
475 return;
476 }
477 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
478 {
479 go_error_at(location,
480 "import path contains invalid character '%c'", c);
481 return;
482 }
483 pf += adv;
484 }
485
486 if (IS_ABSOLUTE_PATH(filename.c_str()))
487 {
488 go_error_at(location, "import path cannot be absolute path");
489 return;
490 }
491
492 if (local_name == "init")
493 go_error_at(location, "cannot import package as init");
494
495 if (filename == "unsafe")
496 {
497 this->import_unsafe(local_name, is_local_name_exported, location);
498 this->current_file_imported_unsafe_ = true;
499 return;
500 }
501
502 Imports::const_iterator p = this->imports_.find(filename);
503 if (p != this->imports_.end())
504 {
505 Package* package = p->second;
506 package->set_location(location);
507 std::string ln = local_name;
508 bool is_ln_exported = is_local_name_exported;
509 if (ln.empty())
510 {
511 ln = package->package_name();
512 go_assert(!ln.empty());
513 is_ln_exported = Lex::is_exported_name(ln);
514 }
515 if (ln == "_")
516 ;
517 else if (ln == ".")
518 {
519 Bindings* bindings = package->bindings();
520 for (Bindings::const_declarations_iterator p =
521 bindings->begin_declarations();
522 p != bindings->end_declarations();
523 ++p)
524 this->add_dot_import_object(p->second);
525 std::string dot_alias = "." + package->package_name();
526 package->add_alias(dot_alias, location);
527 }
528 else
529 {
530 package->add_alias(ln, location);
531 ln = this->pack_hidden_name(ln, is_ln_exported);
532 this->package_->bindings()->add_package(ln, package);
533 }
534 return;
535 }
536
537 Import::Stream* stream = Import::open_package(filename, location,
538 this->relative_import_path_);
539 if (stream == NULL)
540 {
541 if (must_exist)
542 go_error_at(location, "import file %qs not found", filename.c_str());
543 return;
544 }
545
546 Import* imp = new Import(stream, location);
547 imp->register_builtin_types(this);
548 Package* package = imp->import(this, local_name, is_local_name_exported);
549 if (package != NULL)
550 {
551 if (package->pkgpath() == this->pkgpath())
552 go_error_at(location,
553 ("imported package uses same package path as package "
554 "being compiled (see -fgo-pkgpath option)"));
555
556 this->imports_.insert(std::make_pair(filename, package));
557 }
558
559 imp->clear_stream();
560 delete stream;
561
562 // FIXME: we never delete imp; we may need it for inlinable functions.
563 }
564
565 Import_init *
566 Gogo::lookup_init(const std::string& init_name)
567 {
568 Import_init tmp("", init_name, -1);
569 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
570 return (it != this->imported_init_fns_.end()) ? *it : NULL;
571 }
572
573 // Add an import control function for an imported package to the list.
574
575 void
576 Gogo::add_import_init_fn(const std::string& package_name,
577 const std::string& init_name, int prio)
578 {
579 for (Import_init_set::iterator p =
580 this->imported_init_fns_.begin();
581 p != this->imported_init_fns_.end();
582 ++p)
583 {
584 Import_init *ii = (*p);
585 if (ii->init_name() == init_name)
586 {
587 // If a test of package P1, built as part of package P1,
588 // imports package P2, and P2 imports P1 (perhaps
589 // indirectly), then we will see the same import name with
590 // different import priorities. That is OK, so don't give
591 // an error about it.
592 if (ii->package_name() != package_name)
593 {
594 go_error_at(Linemap::unknown_location(),
595 "duplicate package initialization name %qs",
596 Gogo::message_name(init_name).c_str());
597 go_inform(Linemap::unknown_location(), "used by package %qs",
598 Gogo::message_name(ii->package_name()).c_str());
599 go_inform(Linemap::unknown_location(), " and by package %qs",
600 Gogo::message_name(package_name).c_str());
601 }
602 ii->set_priority(prio);
603 return;
604 }
605 }
606
607 Import_init* nii = new Import_init(package_name, init_name, prio);
608 this->imported_init_fns_.insert(nii);
609 }
610
611 // Return whether we are at the global binding level.
612
613 bool
614 Gogo::in_global_scope() const
615 {
616 return this->functions_.empty();
617 }
618
619 // Return the current binding contour.
620
621 Bindings*
622 Gogo::current_bindings()
623 {
624 if (!this->functions_.empty())
625 return this->functions_.back().blocks.back()->bindings();
626 else if (this->package_ != NULL)
627 return this->package_->bindings();
628 else
629 return this->globals_;
630 }
631
632 const Bindings*
633 Gogo::current_bindings() const
634 {
635 if (!this->functions_.empty())
636 return this->functions_.back().blocks.back()->bindings();
637 else if (this->package_ != NULL)
638 return this->package_->bindings();
639 else
640 return this->globals_;
641 }
642
643 void
644 Gogo::update_init_priority(Import_init* ii,
645 std::set<const Import_init *>* visited)
646 {
647 visited->insert(ii);
648 int succ_prior = -1;
649
650 for (std::set<std::string>::const_iterator pci =
651 ii->precursors().begin();
652 pci != ii->precursors().end();
653 ++pci)
654 {
655 Import_init* succ = this->lookup_init(*pci);
656 if (visited->find(succ) == visited->end())
657 update_init_priority(succ, visited);
658 succ_prior = std::max(succ_prior, succ->priority());
659 }
660 if (ii->priority() <= succ_prior)
661 ii->set_priority(succ_prior + 1);
662 }
663
664 void
665 Gogo::recompute_init_priorities()
666 {
667 std::set<Import_init *> nonroots;
668
669 for (Import_init_set::const_iterator p =
670 this->imported_init_fns_.begin();
671 p != this->imported_init_fns_.end();
672 ++p)
673 {
674 const Import_init *ii = *p;
675 for (std::set<std::string>::const_iterator pci =
676 ii->precursors().begin();
677 pci != ii->precursors().end();
678 ++pci)
679 {
680 Import_init* ii = this->lookup_init(*pci);
681 nonroots.insert(ii);
682 }
683 }
684
685 // Recursively update priorities starting at roots.
686 std::set<const Import_init*> visited;
687 for (Import_init_set::iterator p =
688 this->imported_init_fns_.begin();
689 p != this->imported_init_fns_.end();
690 ++p)
691 {
692 Import_init* ii = *p;
693 if (nonroots.find(ii) != nonroots.end())
694 continue;
695 update_init_priority(ii, &visited);
696 }
697 }
698
699 // Add statements to INIT_STMTS which run the initialization
700 // functions for imported packages. This is only used for the "main"
701 // package.
702
703 void
704 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
705 {
706 go_assert(this->is_main_package());
707
708 if (this->imported_init_fns_.empty())
709 return;
710
711 Location unknown_loc = Linemap::unknown_location();
712 Function_type* func_type =
713 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
714 Btype* fntype = func_type->get_backend_fntype(this);
715
716 // Recompute init priorities based on a walk of the init graph.
717 recompute_init_priorities();
718
719 // We must call them in increasing priority order.
720 std::vector<const Import_init*> v;
721 for (Import_init_set::const_iterator p =
722 this->imported_init_fns_.begin();
723 p != this->imported_init_fns_.end();
724 ++p)
725 {
726 if ((*p)->priority() < 0)
727 go_error_at(Linemap::unknown_location(),
728 "internal error: failed to set init priority for %s",
729 (*p)->package_name().c_str());
730 v.push_back(*p);
731 }
732 std::sort(v.begin(), v.end(), priority_compare);
733
734 // We build calls to the init functions, which take no arguments.
735 std::vector<Bexpression*> empty_args;
736 for (std::vector<const Import_init*>::const_iterator p = v.begin();
737 p != v.end();
738 ++p)
739 {
740 const Import_init* ii = *p;
741 std::string user_name = ii->package_name() + ".init";
742 const std::string& init_name(ii->init_name());
743 const unsigned int flags =
744 (Backend::function_is_visible
745 | Backend::function_is_declaration
746 | Backend::function_is_inlinable);
747 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
748 flags, unknown_loc);
749 Bexpression* pfunc_code =
750 this->backend()->function_code_expression(pfunc, unknown_loc);
751 Bexpression* pfunc_call =
752 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
753 NULL, unknown_loc);
754 init_stmts.push_back(this->backend()->expression_statement(bfunction,
755 pfunc_call));
756 }
757 }
758
759 // Register global variables with the garbage collector. We need to
760 // register all variables which can hold a pointer value. They become
761 // roots during the mark phase. We build a struct that is easy to
762 // hook into a list of roots.
763
764 // type gcRoot struct {
765 // decl unsafe.Pointer // Pointer to variable.
766 // size uintptr // Total size of variable.
767 // ptrdata uintptr // Length of variable's gcdata.
768 // gcdata *byte // Pointer mask.
769 // }
770 //
771 // type gcRootList struct {
772 // next *gcRootList
773 // count int
774 // roots [...]gcRoot
775 // }
776
777 // The last entry in the roots array has a NULL decl field.
778
779 void
780 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
781 std::vector<Bstatement*>& init_stmts,
782 Bfunction* init_bfn)
783 {
784 if (var_gc.empty() && this->gc_roots_.empty())
785 return;
786
787 Type* pvt = Type::make_pointer_type(Type::make_void_type());
788 Type* uintptr_type = Type::lookup_integer_type("uintptr");
789 Type* byte_type = this->lookup_global("byte")->type_value();
790 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
791 Struct_type* root_type =
792 Type::make_builtin_struct_type(4,
793 "decl", pvt,
794 "size", uintptr_type,
795 "ptrdata", uintptr_type,
796 "gcdata", pointer_byte_type);
797
798 Location builtin_loc = Linemap::predeclared_location();
799 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
800 Expression* length = Expression::make_integer_ul(roots_len, NULL,
801 builtin_loc);
802 Array_type* root_array_type = Type::make_array_type(root_type, length);
803 root_array_type->set_is_array_incomparable();
804
805 Type* int_type = Type::lookup_integer_type("int");
806 Struct_type* root_list_type =
807 Type::make_builtin_struct_type(3,
808 "next", pvt,
809 "count", int_type,
810 "roots", root_array_type);
811
812 // Build an initializer for the roots array.
813
814 Expression_list* roots_init = new Expression_list();
815
816 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
817 p != var_gc.end();
818 ++p)
819 {
820 Expression_list* init = new Expression_list();
821
822 Location no_loc = (*p)->location();
823 Expression* decl = Expression::make_var_reference(*p, no_loc);
824 Expression* decl_addr =
825 Expression::make_unary(OPERATOR_AND, decl, no_loc);
826 decl_addr->unary_expression()->set_does_not_escape();
827 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
828 init->push_back(decl_addr);
829
830 Expression* size =
831 Expression::make_type_info(decl->type(),
832 Expression::TYPE_INFO_SIZE);
833 init->push_back(size);
834
835 Expression* ptrdata =
836 Expression::make_type_info(decl->type(),
837 Expression::TYPE_INFO_BACKEND_PTRDATA);
838 init->push_back(ptrdata);
839
840 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
841 init->push_back(gcdata);
842
843 Expression* root_ctor =
844 Expression::make_struct_composite_literal(root_type, init, no_loc);
845 roots_init->push_back(root_ctor);
846 }
847
848 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
849 p != this->gc_roots_.end();
850 ++p)
851 {
852 Expression_list *init = new Expression_list();
853
854 Expression* expr = *p;
855 Location eloc = expr->location();
856 init->push_back(Expression::make_cast(pvt, expr, eloc));
857
858 Type* type = expr->type()->points_to();
859 go_assert(type != NULL);
860
861 Expression* size =
862 Expression::make_type_info(type,
863 Expression::TYPE_INFO_SIZE);
864 init->push_back(size);
865
866 Expression* ptrdata =
867 Expression::make_type_info(type,
868 Expression::TYPE_INFO_BACKEND_PTRDATA);
869 init->push_back(ptrdata);
870
871 Expression* gcdata = Expression::make_ptrmask_symbol(type);
872 init->push_back(gcdata);
873
874 Expression* root_ctor =
875 Expression::make_struct_composite_literal(root_type, init, eloc);
876 roots_init->push_back(root_ctor);
877 }
878
879 // Build a constructor for the struct.
880
881 Expression_list* root_list_init = new Expression_list();
882 root_list_init->push_back(Expression::make_nil(builtin_loc));
883 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
884 builtin_loc));
885
886 Expression* roots_ctor =
887 Expression::make_array_composite_literal(root_array_type, roots_init,
888 builtin_loc);
889 root_list_init->push_back(roots_ctor);
890
891 Expression* root_list_ctor =
892 Expression::make_struct_composite_literal(root_list_type, root_list_init,
893 builtin_loc);
894
895 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
896 builtin_loc);
897 root_addr->unary_expression()->set_is_gc_root();
898 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
899 builtin_loc, 1, root_addr);
900
901 Translate_context context(this, NULL, NULL, NULL);
902 Bexpression* bcall = register_roots->get_backend(&context);
903 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
904 }
905
906 // Build the decl for the initialization function.
907
908 Named_object*
909 Gogo::initialization_function_decl()
910 {
911 std::string name = this->get_init_fn_name();
912 Location loc = this->package_->location();
913
914 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
915 Function* initfn = new Function(fntype, NULL, NULL, loc);
916 return Named_object::make_function(name, NULL, initfn);
917 }
918
919 // Create the magic initialization function. CODE_STMT is the
920 // code that it needs to run.
921
922 Named_object*
923 Gogo::create_initialization_function(Named_object* initfn,
924 Bstatement* code_stmt)
925 {
926 // Make sure that we thought we needed an initialization function,
927 // as otherwise we will not have reported it in the export data.
928 go_assert(this->is_main_package() || this->need_init_fn_);
929
930 if (initfn == NULL)
931 initfn = this->initialization_function_decl();
932
933 // Bind the initialization function code to a block.
934 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
935 Location pkg_loc = this->package_->location();
936 std::vector<Bvariable*> vars;
937 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
938
939 if (!this->backend()->function_set_body(fndecl, code_stmt))
940 {
941 go_assert(saw_errors());
942 return NULL;
943 }
944 return initfn;
945 }
946
947 // Given an expression, collect all the global variables defined in
948 // this package that it references.
949
950 class Find_vars : public Traverse
951 {
952 private:
953 // The list of variables we accumulate.
954 typedef Unordered_set(Named_object*) Vars;
955
956 // A hash table we use to avoid looping. The index is a
957 // Named_object* or a Temporary_statement*. We only look through
958 // objects defined in this package.
959 typedef Unordered_set(const void*) Seen_objects;
960
961 public:
962 Find_vars()
963 : Traverse(traverse_expressions),
964 vars_(), seen_objects_()
965 { }
966
967 // An iterator through the variables found, after the traversal.
968 typedef Vars::const_iterator const_iterator;
969
970 const_iterator
971 begin() const
972 { return this->vars_.begin(); }
973
974 const_iterator
975 end() const
976 { return this->vars_.end(); }
977
978 int
979 expression(Expression**);
980
981 private:
982 // Accumulated variables.
983 Vars vars_;
984 // Objects we have already seen.
985 Seen_objects seen_objects_;
986 };
987
988 // Collect global variables referenced by EXPR. Look through function
989 // calls and variable initializations.
990
991 int
992 Find_vars::expression(Expression** pexpr)
993 {
994 Expression* e = *pexpr;
995
996 Var_expression* ve = e->var_expression();
997 if (ve != NULL)
998 {
999 Named_object* v = ve->named_object();
1000 if (!v->is_variable() || v->package() != NULL)
1001 {
1002 // This is a result parameter or a variable defined in a
1003 // different package. Either way we don't care about it.
1004 return TRAVERSE_CONTINUE;
1005 }
1006
1007 std::pair<Seen_objects::iterator, bool> ins =
1008 this->seen_objects_.insert(v);
1009 if (!ins.second)
1010 {
1011 // We've seen this variable before.
1012 return TRAVERSE_CONTINUE;
1013 }
1014
1015 if (v->var_value()->is_global())
1016 this->vars_.insert(v);
1017
1018 Expression* init = v->var_value()->init();
1019 if (init != NULL)
1020 {
1021 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1022 return TRAVERSE_EXIT;
1023 }
1024 }
1025
1026 // We traverse the code of any function or bound method we see. Note that
1027 // this means that we will traverse the code of a function or bound method
1028 // whose address is taken even if it is not called.
1029 Func_expression* fe = e->func_expression();
1030 Bound_method_expression* bme = e->bound_method_expression();
1031 if (fe != NULL || bme != NULL)
1032 {
1033 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1034 if (f->is_function() && f->package() == NULL)
1035 {
1036 std::pair<Seen_objects::iterator, bool> ins =
1037 this->seen_objects_.insert(f);
1038 if (ins.second)
1039 {
1040 // This is the first time we have seen this name.
1041 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1042 return TRAVERSE_EXIT;
1043 }
1044 }
1045 }
1046
1047 Temporary_reference_expression* tre = e->temporary_reference_expression();
1048 if (tre != NULL)
1049 {
1050 Temporary_statement* ts = tre->statement();
1051 Expression* init = ts->init();
1052 if (init != NULL)
1053 {
1054 std::pair<Seen_objects::iterator, bool> ins =
1055 this->seen_objects_.insert(ts);
1056 if (ins.second)
1057 {
1058 // This is the first time we have seen this temporary
1059 // statement.
1060 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1061 return TRAVERSE_EXIT;
1062 }
1063 }
1064 }
1065
1066 return TRAVERSE_CONTINUE;
1067 }
1068
1069 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1070
1071 static bool
1072 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1073 Named_object* var)
1074 {
1075 Find_vars find_vars;
1076 if (expr != NULL)
1077 Expression::traverse(&expr, &find_vars);
1078 if (preinit != NULL)
1079 preinit->traverse(&find_vars);
1080 if (dep != NULL)
1081 {
1082 Expression* init = dep->var_value()->init();
1083 if (init != NULL)
1084 Expression::traverse(&init, &find_vars);
1085 if (dep->var_value()->has_pre_init())
1086 dep->var_value()->preinit()->traverse(&find_vars);
1087 }
1088
1089 for (Find_vars::const_iterator p = find_vars.begin();
1090 p != find_vars.end();
1091 ++p)
1092 {
1093 if (*p == var)
1094 return true;
1095 }
1096 return false;
1097 }
1098
1099 // Sort variable initializations. If the initialization expression
1100 // for variable A refers directly or indirectly to the initialization
1101 // expression for variable B, then we must initialize B before A.
1102
1103 class Var_init
1104 {
1105 public:
1106 Var_init()
1107 : var_(NULL), init_(NULL), refs_(NULL), dep_count_(0)
1108 { }
1109
1110 Var_init(Named_object* var, Bstatement* init)
1111 : var_(var), init_(init), refs_(NULL), dep_count_(0)
1112 { }
1113
1114 // Return the variable.
1115 Named_object*
1116 var() const
1117 { return this->var_; }
1118
1119 // Return the initialization expression.
1120 Bstatement*
1121 init() const
1122 { return this->init_; }
1123
1124 // Add a reference.
1125 void
1126 add_ref(Named_object* var);
1127
1128 // The variables which this variable's initializers refer to.
1129 const std::vector<Named_object*>*
1130 refs()
1131 { return this->refs_; }
1132
1133 // Clear the references, if any.
1134 void
1135 clear_refs();
1136
1137 // Return the number of remaining dependencies.
1138 size_t
1139 dep_count() const
1140 { return this->dep_count_; }
1141
1142 // Increment the number of dependencies.
1143 void
1144 add_dependency()
1145 { ++this->dep_count_; }
1146
1147 // Decrement the number of dependencies.
1148 void
1149 remove_dependency()
1150 { --this->dep_count_; }
1151
1152 private:
1153 // The variable being initialized.
1154 Named_object* var_;
1155 // The backend initialization statement.
1156 Bstatement* init_;
1157 // Variables this refers to.
1158 std::vector<Named_object*>* refs_;
1159 // The number of initializations this is dependent on. A variable
1160 // initialization should not be emitted if any of its dependencies
1161 // have not yet been resolved.
1162 size_t dep_count_;
1163 };
1164
1165 // Add a reference.
1166
1167 void
1168 Var_init::add_ref(Named_object* var)
1169 {
1170 if (this->refs_ == NULL)
1171 this->refs_ = new std::vector<Named_object*>;
1172 this->refs_->push_back(var);
1173 }
1174
1175 // Clear the references, if any.
1176
1177 void
1178 Var_init::clear_refs()
1179 {
1180 if (this->refs_ != NULL)
1181 {
1182 delete this->refs_;
1183 this->refs_ = NULL;
1184 }
1185 }
1186
1187 // For comparing Var_init keys in a map.
1188
1189 inline bool
1190 operator<(const Var_init& v1, const Var_init& v2)
1191 { return v1.var()->name() < v2.var()->name(); }
1192
1193 typedef std::list<Var_init> Var_inits;
1194
1195 // Sort the variable initializations. The rule we follow is that we
1196 // emit them in the order they appear in the array, except that if the
1197 // initialization expression for a variable V1 depends upon another
1198 // variable V2 then we initialize V1 after V2.
1199
1200 static void
1201 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1202 {
1203 if (var_inits->empty())
1204 return;
1205
1206 std::map<Named_object*, Var_init*> var_to_init;
1207
1208 // A mapping from a variable initialization to a set of
1209 // variable initializations that depend on it.
1210 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1211 Init_deps init_deps;
1212 bool init_loop = false;
1213
1214 // Compute all variable references.
1215 for (Var_inits::iterator pvar = var_inits->begin();
1216 pvar != var_inits->end();
1217 ++pvar)
1218 {
1219 Named_object* var = pvar->var();
1220 var_to_init[var] = &*pvar;
1221
1222 Find_vars find_vars;
1223 Expression* init = var->var_value()->init();
1224 if (init != NULL)
1225 Expression::traverse(&init, &find_vars);
1226 if (var->var_value()->has_pre_init())
1227 var->var_value()->preinit()->traverse(&find_vars);
1228 Named_object* dep = gogo->var_depends_on(var->var_value());
1229 if (dep != NULL)
1230 {
1231 Expression* dinit = dep->var_value()->init();
1232 if (dinit != NULL)
1233 Expression::traverse(&dinit, &find_vars);
1234 if (dep->var_value()->has_pre_init())
1235 dep->var_value()->preinit()->traverse(&find_vars);
1236 }
1237 for (Find_vars::const_iterator p = find_vars.begin();
1238 p != find_vars.end();
1239 ++p)
1240 pvar->add_ref(*p);
1241 }
1242
1243 // Add dependencies to init_deps, and check for cycles.
1244 for (Var_inits::iterator pvar = var_inits->begin();
1245 pvar != var_inits->end();
1246 ++pvar)
1247 {
1248 Named_object* var = pvar->var();
1249
1250 const std::vector<Named_object*>* refs = pvar->refs();
1251 if (refs == NULL)
1252 continue;
1253 for (std::vector<Named_object*>::const_iterator pdep = refs->begin();
1254 pdep != refs->end();
1255 ++pdep)
1256 {
1257 Named_object* dep = *pdep;
1258 if (var == dep)
1259 {
1260 // This is a reference from a variable to itself, which
1261 // may indicate a loop. We only report an error if
1262 // there is an initializer and there is no dependency.
1263 // When there is no initializer, it means that the
1264 // preinitializer sets the variable, which will appear
1265 // to be a loop here.
1266 if (var->var_value()->init() != NULL
1267 && gogo->var_depends_on(var->var_value()) == NULL)
1268 go_error_at(var->location(),
1269 ("initialization expression for %qs "
1270 "depends upon itself"),
1271 var->message_name().c_str());
1272
1273 continue;
1274 }
1275
1276 Var_init* dep_init = var_to_init[dep];
1277 if (dep_init == NULL)
1278 {
1279 // This is a dependency on some variable that doesn't
1280 // have an initializer, so for purposes of
1281 // initialization ordering this is irrelevant.
1282 continue;
1283 }
1284
1285 init_deps[*dep_init].insert(&(*pvar));
1286 pvar->add_dependency();
1287
1288 // Check for cycles.
1289 const std::vector<Named_object*>* deprefs = dep_init->refs();
1290 if (deprefs == NULL)
1291 continue;
1292 for (std::vector<Named_object*>::const_iterator pdepdep =
1293 deprefs->begin();
1294 pdepdep != deprefs->end();
1295 ++pdepdep)
1296 {
1297 if (*pdepdep == var)
1298 {
1299 go_error_at(var->location(),
1300 ("initialization expressions for %qs and "
1301 "%qs depend upon each other"),
1302 var->message_name().c_str(),
1303 dep->message_name().c_str());
1304 go_inform(dep->location(), "%qs defined here",
1305 dep->message_name().c_str());
1306 init_loop = true;
1307 break;
1308 }
1309 }
1310 }
1311 }
1312
1313 var_to_init.clear();
1314 for (Var_inits::iterator pvar = var_inits->begin();
1315 pvar != var_inits->end();
1316 ++pvar)
1317 pvar->clear_refs();
1318
1319 // If there are no dependencies then the declaration order is sorted.
1320 if (!init_deps.empty() && !init_loop)
1321 {
1322 // Otherwise, sort variable initializations by emitting all variables with
1323 // no dependencies in declaration order. VAR_INITS is already in
1324 // declaration order.
1325 Var_inits ready;
1326 while (!var_inits->empty())
1327 {
1328 Var_inits::iterator v1;;
1329 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1330 {
1331 if (v1->dep_count() == 0)
1332 break;
1333 }
1334 go_assert(v1 != var_inits->end());
1335
1336 // V1 either has no dependencies or its dependencies have already
1337 // been emitted, add it to READY next. When V1 is emitted, remove
1338 // a dependency from each V that depends on V1.
1339 ready.splice(ready.end(), *var_inits, v1);
1340
1341 Init_deps::iterator p1 = init_deps.find(*v1);
1342 if (p1 != init_deps.end())
1343 {
1344 std::set<Var_init*> resolved = p1->second;
1345 for (std::set<Var_init*>::iterator pv = resolved.begin();
1346 pv != resolved.end();
1347 ++pv)
1348 (*pv)->remove_dependency();
1349 init_deps.erase(p1);
1350 }
1351 }
1352 var_inits->swap(ready);
1353 go_assert(init_deps.empty());
1354 }
1355 }
1356
1357 // Give an error if the initialization expression for VAR depends on
1358 // itself. We only check if INIT is not NULL and there is no
1359 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1360 // which we will interpret as a loop.
1361
1362 void
1363 Gogo::check_self_dep(Named_object* var)
1364 {
1365 Expression* init = var->var_value()->init();
1366 Block* preinit = var->var_value()->preinit();
1367 Named_object* dep = this->var_depends_on(var->var_value());
1368 if (init != NULL
1369 && dep == NULL
1370 && expression_requires(init, preinit, NULL, var))
1371 go_error_at(var->location(),
1372 "initialization expression for %qs depends upon itself",
1373 var->message_name().c_str());
1374 }
1375
1376 // Write out the global definitions.
1377
1378 void
1379 Gogo::write_globals()
1380 {
1381 this->build_interface_method_tables();
1382
1383 Bindings* bindings = this->current_bindings();
1384
1385 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1386 p != bindings->end_declarations();
1387 ++p)
1388 {
1389 // If any function declarations needed a descriptor, make sure
1390 // we build it.
1391 Named_object* no = p->second;
1392 if (no->is_function_declaration())
1393 no->func_declaration_value()->build_backend_descriptor(this);
1394 }
1395
1396 // Lists of globally declared types, variables, constants, and functions
1397 // that must be defined.
1398 std::vector<Btype*> type_decls;
1399 std::vector<Bvariable*> var_decls;
1400 std::vector<Bexpression*> const_decls;
1401 std::vector<Bfunction*> func_decls;
1402
1403 // The init function declaration and associated Bfunction, if necessary.
1404 Named_object* init_fndecl = NULL;
1405 Bfunction* init_bfn = NULL;
1406
1407 std::vector<Bstatement*> init_stmts;
1408 std::vector<Bstatement*> var_init_stmts;
1409
1410 if (this->is_main_package())
1411 {
1412 init_fndecl = this->initialization_function_decl();
1413 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1414 this->init_imports(init_stmts, init_bfn);
1415 }
1416
1417 // A list of variable initializations.
1418 Var_inits var_inits;
1419
1420 // A list of variables which need to be registered with the garbage
1421 // collector.
1422 size_t count_definitions = bindings->size_definitions();
1423 std::vector<Named_object*> var_gc;
1424 var_gc.reserve(count_definitions);
1425
1426 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1427 p != bindings->end_definitions();
1428 ++p)
1429 {
1430 Named_object* no = *p;
1431 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1432
1433 // There is nothing to do for a package.
1434 if (no->is_package())
1435 continue;
1436
1437 // There is nothing to do for an object which was imported from
1438 // a different package into the global scope.
1439 if (no->package() != NULL)
1440 continue;
1441
1442 // Skip blank named functions and constants.
1443 if ((no->is_function() && no->func_value()->is_sink())
1444 || (no->is_const() && no->const_value()->is_sink()))
1445 continue;
1446
1447 // There is nothing useful we can output for constants which
1448 // have ideal or non-integral type.
1449 if (no->is_const())
1450 {
1451 Type* type = no->const_value()->type();
1452 if (type == NULL)
1453 type = no->const_value()->expr()->type();
1454 if (type->is_abstract() || !type->is_numeric_type())
1455 continue;
1456 }
1457
1458 if (!no->is_variable())
1459 no->get_backend(this, const_decls, type_decls, func_decls);
1460 else
1461 {
1462 Variable* var = no->var_value();
1463 Bvariable* bvar = no->get_backend_variable(this, NULL);
1464 var_decls.push_back(bvar);
1465
1466 // Check for a sink variable, which may be used to run an
1467 // initializer purely for its side effects.
1468 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1469
1470 Bstatement* var_init_stmt = NULL;
1471 if (!var->has_pre_init())
1472 {
1473 // If the backend representation of the variable initializer is
1474 // constant, we can just set the initial value using
1475 // global_var_set_init instead of during the init() function.
1476 // The initializer is constant if it is the zero-value of the
1477 // variable's type or if the initial value is an immutable value
1478 // that is not copied to the heap.
1479 bool is_static_initializer = false;
1480 if (var->init() == NULL)
1481 is_static_initializer = true;
1482 else
1483 {
1484 Type* var_type = var->type();
1485 Expression* init = var->init();
1486 Expression* init_cast =
1487 Expression::make_cast(var_type, init, var->location());
1488 is_static_initializer = init_cast->is_static_initializer();
1489 }
1490
1491 // Non-constant variable initializations might need to create
1492 // temporary variables, which will need the initialization
1493 // function as context.
1494 Named_object* var_init_fn;
1495 if (is_static_initializer)
1496 var_init_fn = NULL;
1497 else
1498 {
1499 if (init_fndecl == NULL)
1500 {
1501 init_fndecl = this->initialization_function_decl();
1502 Function* func = init_fndecl->func_value();
1503 init_bfn = func->get_or_make_decl(this, init_fndecl);
1504 }
1505 var_init_fn = init_fndecl;
1506 }
1507 Bexpression* var_binit = var->get_init(this, var_init_fn);
1508
1509 if (var_binit == NULL)
1510 ;
1511 else if (is_static_initializer)
1512 {
1513 if (expression_requires(var->init(), NULL,
1514 this->var_depends_on(var), no))
1515 go_error_at(no->location(),
1516 "initialization expression for %qs depends "
1517 "upon itself",
1518 no->message_name().c_str());
1519 this->backend()->global_variable_set_init(bvar, var_binit);
1520 }
1521 else if (is_sink)
1522 var_init_stmt =
1523 this->backend()->expression_statement(init_bfn, var_binit);
1524 else
1525 {
1526 Location loc = var->location();
1527 Bexpression* var_expr =
1528 this->backend()->var_expression(bvar, loc);
1529 var_init_stmt =
1530 this->backend()->assignment_statement(init_bfn, var_expr,
1531 var_binit, loc);
1532 }
1533 }
1534 else
1535 {
1536 // We are going to create temporary variables which
1537 // means that we need an fndecl.
1538 if (init_fndecl == NULL)
1539 init_fndecl = this->initialization_function_decl();
1540
1541 Bvariable* var_decl = is_sink ? NULL : bvar;
1542 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1543 }
1544
1545 if (var_init_stmt != NULL)
1546 {
1547 if (var->init() == NULL && !var->has_pre_init())
1548 var_init_stmts.push_back(var_init_stmt);
1549 else
1550 var_inits.push_back(Var_init(no, var_init_stmt));
1551 }
1552 else if (this->var_depends_on(var) != NULL)
1553 {
1554 // This variable is initialized from something that is
1555 // not in its init or preinit. This variable needs to
1556 // participate in dependency analysis sorting, in case
1557 // some other variable depends on this one.
1558 Btype* btype = no->var_value()->type()->get_backend(this);
1559 Bexpression* zero = this->backend()->zero_expression(btype);
1560 Bstatement* zero_stmt =
1561 this->backend()->expression_statement(init_bfn, zero);
1562 var_inits.push_back(Var_init(no, zero_stmt));
1563 }
1564
1565 // Collect a list of all global variables with pointers,
1566 // to register them for the garbage collector.
1567 if (!is_sink && var->type()->has_pointer())
1568 {
1569 // Avoid putting runtime.gcRoots itself on the list.
1570 if (this->compiling_runtime()
1571 && this->package_name() == "runtime"
1572 && (Gogo::unpack_hidden_name(no->name()) == "gcRoots"
1573 || Gogo::unpack_hidden_name(no->name()) == "gcRootsIndex"))
1574 ;
1575 else
1576 var_gc.push_back(no);
1577 }
1578 }
1579 }
1580
1581 // Output inline functions, which are in different packages.
1582 for (std::vector<Named_object*>::const_iterator p =
1583 this->imported_inline_functions_.begin();
1584 p != this->imported_inline_functions_.end();
1585 ++p)
1586 (*p)->get_backend(this, const_decls, type_decls, func_decls);
1587
1588 // Register global variables with the garbage collector.
1589 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1590
1591 // Simple variable initializations, after all variables are
1592 // registered.
1593 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1594
1595 // Complete variable initializations, first sorting them into a
1596 // workable order.
1597 if (!var_inits.empty())
1598 {
1599 sort_var_inits(this, &var_inits);
1600 for (Var_inits::const_iterator p = var_inits.begin();
1601 p != var_inits.end();
1602 ++p)
1603 init_stmts.push_back(p->init());
1604 }
1605
1606 // After all the variables are initialized, call the init
1607 // functions if there are any. Init functions take no arguments, so
1608 // we pass in EMPTY_ARGS to call them.
1609 std::vector<Bexpression*> empty_args;
1610 for (std::vector<Named_object*>::const_iterator p =
1611 this->init_functions_.begin();
1612 p != this->init_functions_.end();
1613 ++p)
1614 {
1615 Location func_loc = (*p)->location();
1616 Function* func = (*p)->func_value();
1617 Bfunction* initfn = func->get_or_make_decl(this, *p);
1618 Bexpression* func_code =
1619 this->backend()->function_code_expression(initfn, func_loc);
1620 Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1621 empty_args,
1622 NULL, func_loc);
1623 Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1624 init_stmts.push_back(ist);
1625 }
1626
1627 // Set up a magic function to do all the initialization actions.
1628 // This will be called if this package is imported.
1629 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1630 if (this->need_init_fn_ || this->is_main_package())
1631 {
1632 init_fndecl =
1633 this->create_initialization_function(init_fndecl, init_fncode);
1634 if (init_fndecl != NULL)
1635 func_decls.push_back(init_fndecl->func_value()->get_decl());
1636 }
1637
1638 // We should not have seen any new bindings created during the conversion.
1639 go_assert(count_definitions == this->current_bindings()->size_definitions());
1640
1641 // Define all globally declared values.
1642 if (!saw_errors())
1643 this->backend()->write_global_definitions(type_decls, const_decls,
1644 func_decls, var_decls);
1645 }
1646
1647 // Return the current block.
1648
1649 Block*
1650 Gogo::current_block()
1651 {
1652 if (this->functions_.empty())
1653 return NULL;
1654 else
1655 return this->functions_.back().blocks.back();
1656 }
1657
1658 // Look up a name in the current binding contour. If PFUNCTION is not
1659 // NULL, set it to the function in which the name is defined, or NULL
1660 // if the name is defined in global scope.
1661
1662 Named_object*
1663 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1664 {
1665 if (pfunction != NULL)
1666 *pfunction = NULL;
1667
1668 if (Gogo::is_sink_name(name))
1669 return Named_object::make_sink();
1670
1671 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1672 p != this->functions_.rend();
1673 ++p)
1674 {
1675 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1676 if (ret != NULL)
1677 {
1678 if (pfunction != NULL)
1679 *pfunction = p->function;
1680 return ret;
1681 }
1682 }
1683
1684 if (this->package_ != NULL)
1685 {
1686 Named_object* ret = this->package_->bindings()->lookup(name);
1687 if (ret != NULL)
1688 {
1689 if (ret->package() != NULL)
1690 {
1691 std::string dot_alias = "." + ret->package()->package_name();
1692 ret->package()->note_usage(dot_alias);
1693 }
1694 return ret;
1695 }
1696 }
1697
1698 // We do not look in the global namespace. If we did, the global
1699 // namespace would effectively hide names which were defined in
1700 // package scope which we have not yet seen. Instead,
1701 // define_global_names is called after parsing is over to connect
1702 // undefined names at package scope with names defined at global
1703 // scope.
1704
1705 return NULL;
1706 }
1707
1708 // Look up a name in the current block, without searching enclosing
1709 // blocks.
1710
1711 Named_object*
1712 Gogo::lookup_in_block(const std::string& name) const
1713 {
1714 go_assert(!this->functions_.empty());
1715 go_assert(!this->functions_.back().blocks.empty());
1716 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1717 }
1718
1719 // Look up a name in the global namespace.
1720
1721 Named_object*
1722 Gogo::lookup_global(const char* name) const
1723 {
1724 return this->globals_->lookup(name);
1725 }
1726
1727 // Add an imported package.
1728
1729 Package*
1730 Gogo::add_imported_package(const std::string& real_name,
1731 const std::string& alias_arg,
1732 bool is_alias_exported,
1733 const std::string& pkgpath,
1734 const std::string& pkgpath_symbol,
1735 Location location,
1736 bool* padd_to_globals)
1737 {
1738 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1739 ret->set_package_name(real_name, location);
1740
1741 *padd_to_globals = false;
1742
1743 if (alias_arg == "_")
1744 ;
1745 else if (alias_arg == ".")
1746 {
1747 *padd_to_globals = true;
1748 std::string dot_alias = "." + real_name;
1749 ret->add_alias(dot_alias, location);
1750 }
1751 else
1752 {
1753 std::string alias = alias_arg;
1754 if (alias.empty())
1755 {
1756 alias = real_name;
1757 is_alias_exported = Lex::is_exported_name(alias);
1758 }
1759 ret->add_alias(alias, location);
1760 alias = this->pack_hidden_name(alias, is_alias_exported);
1761 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1762 if (!no->is_package())
1763 return NULL;
1764 }
1765
1766 return ret;
1767 }
1768
1769 // Register a package. This package may or may not be imported. This
1770 // returns the Package structure for the package, creating if it
1771 // necessary. LOCATION is the location of the import statement that
1772 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1773 // for names in the package; it may be the empty string, in which case
1774 // we either get it later or make a guess when we need it.
1775
1776 Package*
1777 Gogo::register_package(const std::string& pkgpath,
1778 const std::string& pkgpath_symbol, Location location)
1779 {
1780 Package* package = NULL;
1781 std::pair<Packages::iterator, bool> ins =
1782 this->packages_.insert(std::make_pair(pkgpath, package));
1783 if (!ins.second)
1784 {
1785 // We have seen this package name before.
1786 package = ins.first->second;
1787 go_assert(package != NULL && package->pkgpath() == pkgpath);
1788 if (!pkgpath_symbol.empty())
1789 package->set_pkgpath_symbol(pkgpath_symbol);
1790 if (Linemap::is_unknown_location(package->location()))
1791 package->set_location(location);
1792 }
1793 else
1794 {
1795 // First time we have seen this package name.
1796 package = new Package(pkgpath, pkgpath_symbol, location);
1797 go_assert(ins.first->second == NULL);
1798 ins.first->second = package;
1799 }
1800
1801 return package;
1802 }
1803
1804 // Return the pkgpath symbol for a package, given the pkgpath.
1805
1806 std::string
1807 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1808 {
1809 Packages::iterator p = this->packages_.find(pkgpath);
1810 go_assert(p != this->packages_.end());
1811 return p->second->pkgpath_symbol();
1812 }
1813
1814 // Start compiling a function.
1815
1816 Named_object*
1817 Gogo::start_function(const std::string& name, Function_type* type,
1818 bool add_method_to_type, Location location)
1819 {
1820 bool at_top_level = this->functions_.empty();
1821
1822 Block* block = new Block(NULL, location);
1823
1824 Named_object* enclosing = (at_top_level
1825 ? NULL
1826 : this->functions_.back().function);
1827
1828 Function* function = new Function(type, enclosing, block, location);
1829
1830 if (type->is_method())
1831 {
1832 const Typed_identifier* receiver = type->receiver();
1833 Variable* this_param = new Variable(receiver->type(), NULL, false,
1834 true, true, location);
1835 std::string rname = receiver->name();
1836 unsigned rcounter = 0;
1837
1838 // We need to give a nameless receiver parameter a synthesized name to
1839 // avoid having it clash with some other nameless param. FIXME.
1840 Gogo::rename_if_empty(&rname, "r", &rcounter);
1841
1842 block->bindings()->add_variable(rname, NULL, this_param);
1843 }
1844
1845 const Typed_identifier_list* parameters = type->parameters();
1846 bool is_varargs = type->is_varargs();
1847 unsigned pcounter = 0;
1848 if (parameters != NULL)
1849 {
1850 for (Typed_identifier_list::const_iterator p = parameters->begin();
1851 p != parameters->end();
1852 ++p)
1853 {
1854 Variable* param = new Variable(p->type(), NULL, false, true, false,
1855 p->location());
1856 if (is_varargs && p + 1 == parameters->end())
1857 param->set_is_varargs_parameter();
1858
1859 std::string pname = p->name();
1860
1861 // We need to give each nameless parameter a non-empty name to avoid
1862 // having it clash with some other nameless param. FIXME.
1863 Gogo::rename_if_empty(&pname, "p", &pcounter);
1864
1865 block->bindings()->add_variable(pname, NULL, param);
1866 }
1867 }
1868
1869 function->create_result_variables(this);
1870
1871 const std::string* pname;
1872 std::string nested_name;
1873 bool is_init = false;
1874 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1875 {
1876 if ((type->parameters() != NULL && !type->parameters()->empty())
1877 || (type->results() != NULL && !type->results()->empty()))
1878 go_error_at(location,
1879 "func init must have no arguments and no return values");
1880 // There can be multiple "init" functions, so give them each a
1881 // different name.
1882 nested_name = this->init_function_name();
1883 pname = &nested_name;
1884 is_init = true;
1885 }
1886 else if (!name.empty())
1887 pname = &name;
1888 else
1889 {
1890 // Invent a name for a nested function.
1891 nested_name = this->nested_function_name(enclosing);
1892 pname = &nested_name;
1893 }
1894
1895 Named_object* ret;
1896 if (Gogo::is_sink_name(*pname))
1897 {
1898 std::string sname(this->sink_function_name());
1899 ret = Named_object::make_function(sname, NULL, function);
1900 ret->func_value()->set_is_sink();
1901
1902 if (!type->is_method())
1903 ret = this->package_->bindings()->add_named_object(ret);
1904 else if (add_method_to_type)
1905 {
1906 // We should report errors even for sink methods.
1907 Type* rtype = type->receiver()->type();
1908 // Avoid points_to and deref to avoid getting an error if
1909 // the type is not yet defined.
1910 if (rtype->classification() == Type::TYPE_POINTER)
1911 rtype = rtype->points_to();
1912 while (rtype->named_type() != NULL
1913 && rtype->named_type()->is_alias())
1914 rtype = rtype->named_type()->real_type()->forwarded();
1915 if (rtype->is_error_type())
1916 ;
1917 else if (rtype->named_type() != NULL)
1918 {
1919 if (rtype->named_type()->named_object()->package() != NULL)
1920 go_error_at(type->receiver()->location(),
1921 "may not define methods on non-local type");
1922 }
1923 else if (rtype->forward_declaration_type() != NULL)
1924 {
1925 // Go ahead and add the method in case we need to report
1926 // an error when we see the definition.
1927 rtype->forward_declaration_type()->add_existing_method(ret);
1928 }
1929 else
1930 go_error_at(type->receiver()->location(),
1931 ("invalid receiver type "
1932 "(receiver must be a named type)"));
1933 }
1934 }
1935 else if (!type->is_method())
1936 {
1937 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1938 if (!ret->is_function() || ret->func_value() != function)
1939 {
1940 // Redefinition error. Invent a name to avoid knockon
1941 // errors.
1942 std::string rname(this->redefined_function_name());
1943 ret = this->package_->bindings()->add_function(rname, NULL, function);
1944 }
1945 }
1946 else
1947 {
1948 if (!add_method_to_type)
1949 ret = Named_object::make_function(name, NULL, function);
1950 else
1951 {
1952 go_assert(at_top_level);
1953 Type* rtype = type->receiver()->type();
1954
1955 while (rtype->named_type() != NULL
1956 && rtype->named_type()->is_alias())
1957 rtype = rtype->named_type()->real_type()->forwarded();
1958
1959 // We want to look through the pointer created by the
1960 // parser, without getting an error if the type is not yet
1961 // defined.
1962 if (rtype->classification() == Type::TYPE_POINTER)
1963 rtype = rtype->points_to();
1964
1965 while (rtype->named_type() != NULL
1966 && rtype->named_type()->is_alias())
1967 rtype = rtype->named_type()->real_type()->forwarded();
1968
1969 if (rtype->is_error_type())
1970 ret = Named_object::make_function(name, NULL, function);
1971 else if (rtype->named_type() != NULL)
1972 {
1973 if (rtype->named_type()->named_object()->package() != NULL)
1974 {
1975 go_error_at(type->receiver()->location(),
1976 "may not define methods on non-local type");
1977 ret = Named_object::make_function(name, NULL, function);
1978 }
1979 else
1980 {
1981 ret = rtype->named_type()->add_method(name, function);
1982 if (!ret->is_function())
1983 {
1984 // Redefinition error.
1985 ret = Named_object::make_function(name, NULL, function);
1986 }
1987 }
1988 }
1989 else if (rtype->forward_declaration_type() != NULL)
1990 {
1991 Named_object* type_no =
1992 rtype->forward_declaration_type()->named_object();
1993 if (type_no->is_unknown())
1994 {
1995 // If we are seeing methods it really must be a
1996 // type. Declare it as such. An alternative would
1997 // be to support lists of methods for unknown
1998 // expressions. Either way the error messages if
1999 // this is not a type are going to get confusing.
2000 Named_object* declared =
2001 this->declare_package_type(type_no->name(),
2002 type_no->location());
2003 go_assert(declared
2004 == type_no->unknown_value()->real_named_object());
2005 }
2006 ret = rtype->forward_declaration_type()->add_method(name,
2007 function);
2008 }
2009 else
2010 {
2011 go_error_at(type->receiver()->location(),
2012 ("invalid receiver type (receiver must "
2013 "be a named type)"));
2014 ret = Named_object::make_function(name, NULL, function);
2015 }
2016 }
2017 this->package_->bindings()->add_method(ret);
2018 }
2019
2020 this->functions_.resize(this->functions_.size() + 1);
2021 Open_function& of(this->functions_.back());
2022 of.function = ret;
2023 of.blocks.push_back(block);
2024
2025 if (is_init)
2026 {
2027 this->init_functions_.push_back(ret);
2028 this->need_init_fn_ = true;
2029 }
2030
2031 return ret;
2032 }
2033
2034 // Finish compiling a function.
2035
2036 void
2037 Gogo::finish_function(Location location)
2038 {
2039 this->finish_block(location);
2040 go_assert(this->functions_.back().blocks.empty());
2041 this->functions_.pop_back();
2042 }
2043
2044 // Return the current function.
2045
2046 Named_object*
2047 Gogo::current_function() const
2048 {
2049 go_assert(!this->functions_.empty());
2050 return this->functions_.back().function;
2051 }
2052
2053 // Start a new block.
2054
2055 void
2056 Gogo::start_block(Location location)
2057 {
2058 go_assert(!this->functions_.empty());
2059 Block* block = new Block(this->current_block(), location);
2060 this->functions_.back().blocks.push_back(block);
2061 }
2062
2063 // Finish a block.
2064
2065 Block*
2066 Gogo::finish_block(Location location)
2067 {
2068 go_assert(!this->functions_.empty());
2069 go_assert(!this->functions_.back().blocks.empty());
2070 Block* block = this->functions_.back().blocks.back();
2071 this->functions_.back().blocks.pop_back();
2072 block->set_end_location(location);
2073 return block;
2074 }
2075
2076 // Add an erroneous name.
2077
2078 Named_object*
2079 Gogo::add_erroneous_name(const std::string& name)
2080 {
2081 return this->package_->bindings()->add_erroneous_name(name);
2082 }
2083
2084 // Add an unknown name.
2085
2086 Named_object*
2087 Gogo::add_unknown_name(const std::string& name, Location location)
2088 {
2089 return this->package_->bindings()->add_unknown_name(name, location);
2090 }
2091
2092 // Declare a function.
2093
2094 Named_object*
2095 Gogo::declare_function(const std::string& name, Function_type* type,
2096 Location location)
2097 {
2098 if (!type->is_method())
2099 return this->current_bindings()->add_function_declaration(name, NULL, type,
2100 location);
2101 else
2102 {
2103 // We don't bother to add this to the list of global
2104 // declarations.
2105 Type* rtype = type->receiver()->type();
2106
2107 while (rtype->named_type() != NULL
2108 && rtype->named_type()->is_alias())
2109 rtype = rtype->named_type()->real_type()->forwarded();
2110
2111 // We want to look through the pointer created by the
2112 // parser, without getting an error if the type is not yet
2113 // defined.
2114 if (rtype->classification() == Type::TYPE_POINTER)
2115 rtype = rtype->points_to();
2116
2117 while (rtype->named_type() != NULL
2118 && rtype->named_type()->is_alias())
2119 rtype = rtype->named_type()->real_type()->forwarded();
2120
2121 if (rtype->is_error_type())
2122 return NULL;
2123 else if (rtype->named_type() != NULL)
2124 return rtype->named_type()->add_method_declaration(name, NULL, type,
2125 location);
2126 else if (rtype->forward_declaration_type() != NULL)
2127 {
2128 Forward_declaration_type* ftype = rtype->forward_declaration_type();
2129 return ftype->add_method_declaration(name, NULL, type, location);
2130 }
2131 else
2132 {
2133 go_error_at(type->receiver()->location(),
2134 "invalid receiver type (receiver must be a named type)");
2135 return Named_object::make_erroneous_name(name);
2136 }
2137 }
2138 }
2139
2140 // Add a label definition.
2141
2142 Label*
2143 Gogo::add_label_definition(const std::string& label_name,
2144 Location location)
2145 {
2146 go_assert(!this->functions_.empty());
2147 Function* func = this->functions_.back().function->func_value();
2148 Label* label = func->add_label_definition(this, label_name, location);
2149 this->add_statement(Statement::make_label_statement(label, location));
2150 return label;
2151 }
2152
2153 // Add a label reference.
2154
2155 Label*
2156 Gogo::add_label_reference(const std::string& label_name,
2157 Location location, bool issue_goto_errors)
2158 {
2159 go_assert(!this->functions_.empty());
2160 Function* func = this->functions_.back().function->func_value();
2161 return func->add_label_reference(this, label_name, location,
2162 issue_goto_errors);
2163 }
2164
2165 // Return the current binding state.
2166
2167 Bindings_snapshot*
2168 Gogo::bindings_snapshot(Location location)
2169 {
2170 return new Bindings_snapshot(this->current_block(), location);
2171 }
2172
2173 // Add a statement.
2174
2175 void
2176 Gogo::add_statement(Statement* statement)
2177 {
2178 go_assert(!this->functions_.empty()
2179 && !this->functions_.back().blocks.empty());
2180 this->functions_.back().blocks.back()->add_statement(statement);
2181 }
2182
2183 // Add a block.
2184
2185 void
2186 Gogo::add_block(Block* block, Location location)
2187 {
2188 go_assert(!this->functions_.empty()
2189 && !this->functions_.back().blocks.empty());
2190 Statement* statement = Statement::make_block_statement(block, location);
2191 this->functions_.back().blocks.back()->add_statement(statement);
2192 }
2193
2194 // Add a constant.
2195
2196 Named_object*
2197 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2198 int iota_value)
2199 {
2200 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2201 }
2202
2203 // Add a type.
2204
2205 void
2206 Gogo::add_type(const std::string& name, Type* type, Location location)
2207 {
2208 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2209 location);
2210 if (!this->in_global_scope() && no->is_type())
2211 {
2212 Named_object* f = this->functions_.back().function;
2213 unsigned int index;
2214 if (f->is_function())
2215 index = f->func_value()->new_local_type_index();
2216 else
2217 index = 0;
2218 no->type_value()->set_in_function(f, index);
2219 }
2220 }
2221
2222 // Add a named type.
2223
2224 void
2225 Gogo::add_named_type(Named_type* type)
2226 {
2227 go_assert(this->in_global_scope());
2228 this->current_bindings()->add_named_type(type);
2229 }
2230
2231 // Declare a type.
2232
2233 Named_object*
2234 Gogo::declare_type(const std::string& name, Location location)
2235 {
2236 Bindings* bindings = this->current_bindings();
2237 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2238 if (!this->in_global_scope() && no->is_type_declaration())
2239 {
2240 Named_object* f = this->functions_.back().function;
2241 unsigned int index;
2242 if (f->is_function())
2243 index = f->func_value()->new_local_type_index();
2244 else
2245 index = 0;
2246 no->type_declaration_value()->set_in_function(f, index);
2247 }
2248 return no;
2249 }
2250
2251 // Declare a type at the package level.
2252
2253 Named_object*
2254 Gogo::declare_package_type(const std::string& name, Location location)
2255 {
2256 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2257 }
2258
2259 // Declare a function at the package level.
2260
2261 Named_object*
2262 Gogo::declare_package_function(const std::string& name, Function_type* type,
2263 Location location)
2264 {
2265 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2266 location);
2267 }
2268
2269 // Add a function declaration to the list of functions we may want to
2270 // inline.
2271
2272 void
2273 Gogo::add_imported_inlinable_function(Named_object* no)
2274 {
2275 go_assert(no->is_function_declaration());
2276 Function_declaration* fd = no->func_declaration_value();
2277 if (fd->is_on_inlinable_list())
2278 return;
2279 this->imported_inlinable_functions_.push_back(no);
2280 fd->set_is_on_inlinable_list();
2281 }
2282
2283 // Define a type which was already declared.
2284
2285 void
2286 Gogo::define_type(Named_object* no, Named_type* type)
2287 {
2288 this->current_bindings()->define_type(no, type);
2289 }
2290
2291 // Add a variable.
2292
2293 Named_object*
2294 Gogo::add_variable(const std::string& name, Variable* variable)
2295 {
2296 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2297 variable);
2298
2299 // In a function the middle-end wants to see a DECL_EXPR node.
2300 if (no != NULL
2301 && no->is_variable()
2302 && !no->var_value()->is_parameter()
2303 && !this->functions_.empty())
2304 this->add_statement(Statement::make_variable_declaration(no));
2305
2306 return no;
2307 }
2308
2309 void
2310 Gogo::rename_if_empty(std::string* pname, const char* tag, unsigned* count)
2311 {
2312 if (pname->empty() || Gogo::is_sink_name(*pname))
2313 {
2314 char buf[50];
2315 go_assert(strlen(tag) < 10);
2316 snprintf(buf, sizeof buf, "%s.%u", tag, *count);
2317 ++(*count);
2318 *pname = buf;
2319 }
2320 }
2321
2322
2323 // Add a sink--a reference to the blank identifier _.
2324
2325 Named_object*
2326 Gogo::add_sink()
2327 {
2328 return Named_object::make_sink();
2329 }
2330
2331 // Add a named object for a dot import.
2332
2333 void
2334 Gogo::add_dot_import_object(Named_object* no)
2335 {
2336 // If the name already exists, then it was defined in some file seen
2337 // earlier. If the earlier name is just a declaration, don't add
2338 // this name, because that will cause the previous declaration to
2339 // merge to this imported name, which should not happen. Just add
2340 // this name to the list of file block names to get appropriate
2341 // errors if we see a later definition.
2342 Named_object* e = this->package_->bindings()->lookup(no->name());
2343 if (e != NULL && e->package() == NULL)
2344 {
2345 if (e->is_unknown())
2346 e = e->resolve();
2347 if (e->package() == NULL
2348 && (e->is_type_declaration()
2349 || e->is_function_declaration()
2350 || e->is_unknown()))
2351 {
2352 this->add_file_block_name(no->name(), no->location());
2353 return;
2354 }
2355 }
2356
2357 this->current_bindings()->add_named_object(no);
2358 }
2359
2360 // Add a linkname. This implements the go:linkname compiler directive.
2361 // We only support this for functions and function declarations.
2362
2363 void
2364 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2365 const std::string& ext_name, Location loc)
2366 {
2367 Named_object* no =
2368 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2369 is_exported));
2370 if (no == NULL)
2371 go_error_at(loc, "%s is not defined", go_name.c_str());
2372 else if (no->is_function())
2373 no->func_value()->set_asm_name(ext_name);
2374 else if (no->is_function_declaration())
2375 no->func_declaration_value()->set_asm_name(ext_name);
2376 else
2377 go_error_at(loc,
2378 ("%s is not a function; "
2379 "//go:linkname is only supported for functions"),
2380 go_name.c_str());
2381 }
2382
2383 // Mark all local variables used. This is used when some types of
2384 // parse error occur.
2385
2386 void
2387 Gogo::mark_locals_used()
2388 {
2389 for (Open_functions::iterator pf = this->functions_.begin();
2390 pf != this->functions_.end();
2391 ++pf)
2392 {
2393 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2394 pb != pf->blocks.end();
2395 ++pb)
2396 (*pb)->bindings()->mark_locals_used();
2397 }
2398 }
2399
2400 // Record that we've seen an interface type.
2401
2402 void
2403 Gogo::record_interface_type(Interface_type* itype)
2404 {
2405 this->interface_types_.push_back(itype);
2406 }
2407
2408 // Define the global names. We do this only after parsing all the
2409 // input files, because the program might define the global names
2410 // itself.
2411
2412 void
2413 Gogo::define_global_names()
2414 {
2415 if (this->is_main_package())
2416 {
2417 // Every Go program has to import the runtime package, so that
2418 // it is properly initialized.
2419 this->import_package("runtime", "_", false, false,
2420 Linemap::predeclared_location());
2421 }
2422
2423 for (Bindings::const_declarations_iterator p =
2424 this->globals_->begin_declarations();
2425 p != this->globals_->end_declarations();
2426 ++p)
2427 {
2428 Named_object* global_no = p->second;
2429 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2430 Named_object* no = this->package_->bindings()->lookup(name);
2431 if (no == NULL)
2432 continue;
2433 no = no->resolve();
2434 if (no->is_type_declaration())
2435 {
2436 if (global_no->is_type())
2437 {
2438 if (no->type_declaration_value()->has_methods())
2439 {
2440 for (std::vector<Named_object*>::const_iterator p =
2441 no->type_declaration_value()->methods()->begin();
2442 p != no->type_declaration_value()->methods()->end();
2443 p++)
2444 go_error_at((*p)->location(),
2445 "may not define methods on non-local type");
2446 }
2447 no->set_type_value(global_no->type_value());
2448 }
2449 else
2450 {
2451 go_error_at(no->location(), "expected type");
2452 Type* errtype = Type::make_error_type();
2453 Named_object* err =
2454 Named_object::make_type("erroneous_type", NULL, errtype,
2455 Linemap::predeclared_location());
2456 no->set_type_value(err->type_value());
2457 }
2458 }
2459 else if (no->is_unknown())
2460 no->unknown_value()->set_real_named_object(global_no);
2461 }
2462
2463 // Give an error if any name is defined in both the package block
2464 // and the file block. For example, this can happen if one file
2465 // imports "fmt" and another file defines a global variable fmt.
2466 for (Bindings::const_declarations_iterator p =
2467 this->package_->bindings()->begin_declarations();
2468 p != this->package_->bindings()->end_declarations();
2469 ++p)
2470 {
2471 if (p->second->is_unknown()
2472 && p->second->unknown_value()->real_named_object() == NULL)
2473 {
2474 // No point in warning about an undefined name, as we will
2475 // get other errors later anyhow.
2476 continue;
2477 }
2478 File_block_names::const_iterator pf =
2479 this->file_block_names_.find(p->second->name());
2480 if (pf != this->file_block_names_.end())
2481 {
2482 std::string n = p->second->message_name();
2483 go_error_at(p->second->location(),
2484 "%qs defined as both imported name and global name",
2485 n.c_str());
2486 go_inform(pf->second, "%qs imported here", n.c_str());
2487 }
2488
2489 // No package scope identifier may be named "init".
2490 if (!p->second->is_function()
2491 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2492 {
2493 go_error_at(p->second->location(),
2494 "cannot declare init - must be func");
2495 }
2496 }
2497 }
2498
2499 // Clear out names in file scope.
2500
2501 void
2502 Gogo::clear_file_scope()
2503 {
2504 this->package_->bindings()->clear_file_scope(this);
2505
2506 // Warn about packages which were imported but not used.
2507 bool quiet = saw_errors();
2508 for (Packages::iterator p = this->packages_.begin();
2509 p != this->packages_.end();
2510 ++p)
2511 {
2512 Package* package = p->second;
2513 if (package != this->package_ && !quiet)
2514 {
2515 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2516 p1 != package->aliases().end();
2517 ++p1)
2518 {
2519 if (!p1->second->used())
2520 {
2521 // Give a more refined error message if the alias name is known.
2522 std::string pkg_name = package->package_name();
2523 if (p1->first != pkg_name && p1->first[0] != '.')
2524 {
2525 go_error_at(p1->second->location(),
2526 "imported and not used: %s as %s",
2527 Gogo::message_name(pkg_name).c_str(),
2528 Gogo::message_name(p1->first).c_str());
2529 }
2530 else
2531 go_error_at(p1->second->location(),
2532 "imported and not used: %s",
2533 Gogo::message_name(pkg_name).c_str());
2534 }
2535 }
2536 }
2537 package->clear_used();
2538 }
2539
2540 this->current_file_imported_unsafe_ = false;
2541 }
2542
2543 // Queue up a type specific function for later writing. These are
2544 // written out in write_specific_type_functions, called after the
2545 // parse tree is lowered.
2546
2547 void
2548 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2549 const std::string& hash_name,
2550 Function_type* hash_fntype,
2551 const std::string& equal_name,
2552 Function_type* equal_fntype)
2553 {
2554 go_assert(!this->specific_type_functions_are_written_);
2555 go_assert(!this->in_global_scope());
2556 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2557 hash_name,
2558 hash_fntype,
2559 equal_name,
2560 equal_fntype);
2561 this->specific_type_functions_.push_back(tsf);
2562 }
2563
2564 // Look for types which need specific hash or equality functions.
2565
2566 class Specific_type_functions : public Traverse
2567 {
2568 public:
2569 Specific_type_functions(Gogo* gogo)
2570 : Traverse(traverse_types),
2571 gogo_(gogo)
2572 { }
2573
2574 int
2575 type(Type*);
2576
2577 private:
2578 Gogo* gogo_;
2579 };
2580
2581 int
2582 Specific_type_functions::type(Type* t)
2583 {
2584 Named_object* hash_fn;
2585 Named_object* equal_fn;
2586 switch (t->classification())
2587 {
2588 case Type::TYPE_NAMED:
2589 {
2590 Named_type* nt = t->named_type();
2591 if (nt->is_alias())
2592 return TRAVERSE_CONTINUE;
2593 if (t->needs_specific_type_functions(this->gogo_))
2594 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2595
2596 // If this is a struct type, we don't want to make functions
2597 // for the unnamed struct.
2598 Type* rt = nt->real_type();
2599 if (rt->struct_type() == NULL)
2600 {
2601 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2602 return TRAVERSE_EXIT;
2603 }
2604 else
2605 {
2606 // If this type is defined in another package, then we don't
2607 // need to worry about the unexported fields.
2608 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2609 const Struct_field_list* fields = rt->struct_type()->fields();
2610 for (Struct_field_list::const_iterator p = fields->begin();
2611 p != fields->end();
2612 ++p)
2613 {
2614 if (is_defined_elsewhere
2615 && Gogo::is_hidden_name(p->field_name()))
2616 continue;
2617 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2618 return TRAVERSE_EXIT;
2619 }
2620 }
2621
2622 return TRAVERSE_SKIP_COMPONENTS;
2623 }
2624
2625 case Type::TYPE_STRUCT:
2626 case Type::TYPE_ARRAY:
2627 if (t->needs_specific_type_functions(this->gogo_))
2628 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2629 break;
2630
2631 default:
2632 break;
2633 }
2634
2635 return TRAVERSE_CONTINUE;
2636 }
2637
2638 // Write out type specific functions.
2639
2640 void
2641 Gogo::write_specific_type_functions()
2642 {
2643 Specific_type_functions stf(this);
2644 this->traverse(&stf);
2645
2646 while (!this->specific_type_functions_.empty())
2647 {
2648 Specific_type_function* tsf = this->specific_type_functions_.back();
2649 this->specific_type_functions_.pop_back();
2650 tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2651 tsf->hash_name,
2652 tsf->hash_fntype,
2653 tsf->equal_name,
2654 tsf->equal_fntype);
2655 delete tsf;
2656 }
2657 this->specific_type_functions_are_written_ = true;
2658 }
2659
2660 // Traverse the tree.
2661
2662 void
2663 Gogo::traverse(Traverse* traverse)
2664 {
2665 // Traverse the current package first for consistency. The other
2666 // packages will only contain imported types, constants, and
2667 // declarations.
2668 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2669 return;
2670 for (Packages::const_iterator p = this->packages_.begin();
2671 p != this->packages_.end();
2672 ++p)
2673 {
2674 if (p->second != this->package_)
2675 {
2676 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2677 break;
2678 }
2679 }
2680 }
2681
2682 // Add a type to verify. This is used for types of sink variables, in
2683 // order to give appropriate error messages.
2684
2685 void
2686 Gogo::add_type_to_verify(Type* type)
2687 {
2688 this->verify_types_.push_back(type);
2689 }
2690
2691 // Traversal class used to verify types.
2692
2693 class Verify_types : public Traverse
2694 {
2695 public:
2696 Verify_types()
2697 : Traverse(traverse_types)
2698 { }
2699
2700 int
2701 type(Type*);
2702 };
2703
2704 // Verify that a type is correct.
2705
2706 int
2707 Verify_types::type(Type* t)
2708 {
2709 if (!t->verify())
2710 return TRAVERSE_SKIP_COMPONENTS;
2711 return TRAVERSE_CONTINUE;
2712 }
2713
2714 // Verify that all types are correct.
2715
2716 void
2717 Gogo::verify_types()
2718 {
2719 Verify_types traverse;
2720 this->traverse(&traverse);
2721
2722 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2723 p != this->verify_types_.end();
2724 ++p)
2725 (*p)->verify();
2726 this->verify_types_.clear();
2727 }
2728
2729 // Traversal class used to lower parse tree.
2730
2731 class Lower_parse_tree : public Traverse
2732 {
2733 public:
2734 Lower_parse_tree(Gogo* gogo, Named_object* function)
2735 : Traverse(traverse_variables
2736 | traverse_constants
2737 | traverse_functions
2738 | traverse_statements
2739 | traverse_expressions),
2740 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2741 { }
2742
2743 void
2744 set_inserter(const Statement_inserter* inserter)
2745 { this->inserter_ = *inserter; }
2746
2747 int
2748 variable(Named_object*);
2749
2750 int
2751 constant(Named_object*, bool);
2752
2753 int
2754 function(Named_object*);
2755
2756 int
2757 statement(Block*, size_t* pindex, Statement*);
2758
2759 int
2760 expression(Expression**);
2761
2762 private:
2763 // General IR.
2764 Gogo* gogo_;
2765 // The function we are traversing.
2766 Named_object* function_;
2767 // Value to use for the predeclared constant iota.
2768 int iota_value_;
2769 // Current statement inserter for use by expressions.
2770 Statement_inserter inserter_;
2771 };
2772
2773 // Lower variables.
2774
2775 int
2776 Lower_parse_tree::variable(Named_object* no)
2777 {
2778 if (!no->is_variable())
2779 return TRAVERSE_CONTINUE;
2780
2781 if (no->is_variable() && no->var_value()->is_global())
2782 {
2783 // Global variables can have loops in their initialization
2784 // expressions. This is handled in lower_init_expression.
2785 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2786 &this->inserter_);
2787 return TRAVERSE_CONTINUE;
2788 }
2789
2790 // This is a local variable. We are going to return
2791 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2792 // initialization expression when we reach the variable declaration
2793 // statement. However, that means that we need to traverse the type
2794 // ourselves.
2795 if (no->var_value()->has_type())
2796 {
2797 Type* type = no->var_value()->type();
2798 if (type != NULL)
2799 {
2800 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2801 return TRAVERSE_EXIT;
2802 }
2803 }
2804 go_assert(!no->var_value()->has_pre_init());
2805
2806 return TRAVERSE_SKIP_COMPONENTS;
2807 }
2808
2809 // Lower constants. We handle constants specially so that we can set
2810 // the right value for the predeclared constant iota. This works in
2811 // conjunction with the way we lower Const_expression objects.
2812
2813 int
2814 Lower_parse_tree::constant(Named_object* no, bool)
2815 {
2816 Named_constant* nc = no->const_value();
2817
2818 // Don't get into trouble if the constant's initializer expression
2819 // refers to the constant itself.
2820 if (nc->lowering())
2821 return TRAVERSE_CONTINUE;
2822 nc->set_lowering();
2823
2824 go_assert(this->iota_value_ == -1);
2825 this->iota_value_ = nc->iota_value();
2826 nc->traverse_expression(this);
2827 this->iota_value_ = -1;
2828
2829 nc->clear_lowering();
2830
2831 // We will traverse the expression a second time, but that will be
2832 // fast.
2833
2834 return TRAVERSE_CONTINUE;
2835 }
2836
2837 // Lower the body of a function, and set the closure type. Record the
2838 // function while lowering it, so that we can pass it down when
2839 // lowering an expression.
2840
2841 int
2842 Lower_parse_tree::function(Named_object* no)
2843 {
2844 no->func_value()->set_closure_type();
2845
2846 go_assert(this->function_ == NULL);
2847 this->function_ = no;
2848 int t = no->func_value()->traverse(this);
2849 this->function_ = NULL;
2850
2851 if (t == TRAVERSE_EXIT)
2852 return t;
2853 return TRAVERSE_SKIP_COMPONENTS;
2854 }
2855
2856 // Lower statement parse trees.
2857
2858 int
2859 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2860 {
2861 // Because we explicitly traverse the statement's contents
2862 // ourselves, we want to skip block statements here. There is
2863 // nothing to lower in a block statement.
2864 if (sorig->is_block_statement())
2865 return TRAVERSE_CONTINUE;
2866
2867 Statement_inserter hold_inserter(this->inserter_);
2868 this->inserter_ = Statement_inserter(block, pindex);
2869
2870 // Lower the expressions first.
2871 int t = sorig->traverse_contents(this);
2872 if (t == TRAVERSE_EXIT)
2873 {
2874 this->inserter_ = hold_inserter;
2875 return t;
2876 }
2877
2878 // Keep lowering until nothing changes.
2879 Statement* s = sorig;
2880 while (true)
2881 {
2882 Statement* snew = s->lower(this->gogo_, this->function_, block,
2883 &this->inserter_);
2884 if (snew == s)
2885 break;
2886 s = snew;
2887 t = s->traverse_contents(this);
2888 if (t == TRAVERSE_EXIT)
2889 {
2890 this->inserter_ = hold_inserter;
2891 return t;
2892 }
2893 }
2894
2895 if (s != sorig)
2896 block->replace_statement(*pindex, s);
2897
2898 this->inserter_ = hold_inserter;
2899 return TRAVERSE_SKIP_COMPONENTS;
2900 }
2901
2902 // Lower expression parse trees.
2903
2904 int
2905 Lower_parse_tree::expression(Expression** pexpr)
2906 {
2907 // We have to lower all subexpressions first, so that we can get
2908 // their type if necessary. This is awkward, because we don't have
2909 // a postorder traversal pass.
2910 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2911 return TRAVERSE_EXIT;
2912 // Keep lowering until nothing changes.
2913 while (true)
2914 {
2915 Expression* e = *pexpr;
2916 Expression* enew = e->lower(this->gogo_, this->function_,
2917 &this->inserter_, this->iota_value_);
2918 if (enew == e)
2919 break;
2920 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2921 return TRAVERSE_EXIT;
2922 *pexpr = enew;
2923 }
2924
2925 // Lower the type of this expression before the parent looks at it,
2926 // in case the type contains an array that has expressions in its
2927 // length. Skip an Unknown_expression, as at this point that means
2928 // a composite literal key that does not have a type.
2929 if ((*pexpr)->unknown_expression() == NULL)
2930 Type::traverse((*pexpr)->type(), this);
2931
2932 return TRAVERSE_SKIP_COMPONENTS;
2933 }
2934
2935 // Lower the parse tree. This is called after the parse is complete,
2936 // when all names should be resolved.
2937
2938 void
2939 Gogo::lower_parse_tree()
2940 {
2941 Lower_parse_tree lower_parse_tree(this, NULL);
2942 this->traverse(&lower_parse_tree);
2943
2944 // If we found any functions defined in other packages that are
2945 // inlinables, import their bodies and turn them into functions.
2946 //
2947 // Note that as we import inlinable functions we may find more
2948 // inlinable functions, so don't use an iterator.
2949 for (size_t i = 0; i < this->imported_inlinable_functions_.size(); i++)
2950 {
2951 Named_object* no = this->imported_inlinable_functions_[i];
2952 no->func_declaration_value()->import_function_body(this, no);
2953 }
2954
2955 // There might be type definitions that involve expressions such as the
2956 // array length. Make sure to lower these expressions as well. Otherwise,
2957 // errors hidden within a type can introduce unexpected errors into later
2958 // passes.
2959 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2960 p != this->verify_types_.end();
2961 ++p)
2962 Type::traverse(*p, &lower_parse_tree);
2963 }
2964
2965 // Lower a block.
2966
2967 void
2968 Gogo::lower_block(Named_object* function, Block* block)
2969 {
2970 Lower_parse_tree lower_parse_tree(this, function);
2971 block->traverse(&lower_parse_tree);
2972 }
2973
2974 // Lower an expression. INSERTER may be NULL, in which case the
2975 // expression had better not need to create any temporaries.
2976
2977 void
2978 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2979 Expression** pexpr)
2980 {
2981 Lower_parse_tree lower_parse_tree(this, function);
2982 if (inserter != NULL)
2983 lower_parse_tree.set_inserter(inserter);
2984 lower_parse_tree.expression(pexpr);
2985 }
2986
2987 // Lower a constant. This is called when lowering a reference to a
2988 // constant. We have to make sure that the constant has already been
2989 // lowered.
2990
2991 void
2992 Gogo::lower_constant(Named_object* no)
2993 {
2994 go_assert(no->is_const());
2995 Lower_parse_tree lower(this, NULL);
2996 lower.constant(no, false);
2997 }
2998
2999 // Traverse the tree to create function descriptors as needed.
3000
3001 class Create_function_descriptors : public Traverse
3002 {
3003 public:
3004 Create_function_descriptors(Gogo* gogo)
3005 : Traverse(traverse_functions | traverse_expressions),
3006 gogo_(gogo)
3007 { }
3008
3009 int
3010 function(Named_object*);
3011
3012 int
3013 expression(Expression**);
3014
3015 private:
3016 Gogo* gogo_;
3017 };
3018
3019 // Create a descriptor for every top-level exported function.
3020
3021 int
3022 Create_function_descriptors::function(Named_object* no)
3023 {
3024 if (no->is_function()
3025 && no->func_value()->enclosing() == NULL
3026 && !no->func_value()->is_method()
3027 && !Gogo::is_hidden_name(no->name())
3028 && !Gogo::is_thunk(no))
3029 no->func_value()->descriptor(this->gogo_, no);
3030
3031 return TRAVERSE_CONTINUE;
3032 }
3033
3034 // If we see a function referenced in any way other than calling it,
3035 // create a descriptor for it.
3036
3037 int
3038 Create_function_descriptors::expression(Expression** pexpr)
3039 {
3040 Expression* expr = *pexpr;
3041
3042 Func_expression* fe = expr->func_expression();
3043 if (fe != NULL)
3044 {
3045 // We would not get here for a call to this function, so this is
3046 // a reference to a function other than calling it. We need a
3047 // descriptor.
3048 if (fe->closure() != NULL)
3049 return TRAVERSE_CONTINUE;
3050 Named_object* no = fe->named_object();
3051 if (no->is_function() && !no->func_value()->is_method())
3052 no->func_value()->descriptor(this->gogo_, no);
3053 else if (no->is_function_declaration()
3054 && !no->func_declaration_value()->type()->is_method()
3055 && !Linemap::is_predeclared_location(no->location()))
3056 no->func_declaration_value()->descriptor(this->gogo_, no);
3057 return TRAVERSE_CONTINUE;
3058 }
3059
3060 Bound_method_expression* bme = expr->bound_method_expression();
3061 if (bme != NULL)
3062 {
3063 // We would not get here for a call to this method, so this is a
3064 // method value. We need to create a thunk.
3065 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
3066 bme->function());
3067 return TRAVERSE_CONTINUE;
3068 }
3069
3070 Interface_field_reference_expression* ifre =
3071 expr->interface_field_reference_expression();
3072 if (ifre != NULL)
3073 {
3074 // We would not get here for a call to this interface method, so
3075 // this is a method value. We need to create a thunk.
3076 Interface_type* type = ifre->expr()->type()->interface_type();
3077 if (type != NULL)
3078 Interface_field_reference_expression::create_thunk(this->gogo_, type,
3079 ifre->name());
3080 return TRAVERSE_CONTINUE;
3081 }
3082
3083 Call_expression* ce = expr->call_expression();
3084 if (ce != NULL)
3085 {
3086 Expression* fn = ce->fn();
3087 if (fn->func_expression() != NULL
3088 || fn->bound_method_expression() != NULL
3089 || fn->interface_field_reference_expression() != NULL)
3090 {
3091 // Traverse the arguments but not the function.
3092 Expression_list* args = ce->args();
3093 if (args != NULL)
3094 {
3095 if (args->traverse(this) == TRAVERSE_EXIT)
3096 return TRAVERSE_EXIT;
3097 }
3098 return TRAVERSE_SKIP_COMPONENTS;
3099 }
3100 }
3101
3102 return TRAVERSE_CONTINUE;
3103 }
3104
3105 // Create function descriptors as needed. We need a function
3106 // descriptor for all exported functions and for all functions that
3107 // are referenced without being called.
3108
3109 void
3110 Gogo::create_function_descriptors()
3111 {
3112 // Create a function descriptor for any exported function that is
3113 // declared in this package. This is so that we have a descriptor
3114 // for functions written in assembly. Gather the descriptors first
3115 // so that we don't add declarations while looping over them.
3116 std::vector<Named_object*> fndecls;
3117 Bindings* b = this->package_->bindings();
3118 for (Bindings::const_declarations_iterator p = b->begin_declarations();
3119 p != b->end_declarations();
3120 ++p)
3121 {
3122 Named_object* no = p->second;
3123 if (no->is_function_declaration()
3124 && !no->func_declaration_value()->type()->is_method()
3125 && !Linemap::is_predeclared_location(no->location())
3126 && !Gogo::is_hidden_name(no->name()))
3127 fndecls.push_back(no);
3128 }
3129 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3130 p != fndecls.end();
3131 ++p)
3132 (*p)->func_declaration_value()->descriptor(this, *p);
3133 fndecls.clear();
3134
3135 Create_function_descriptors cfd(this);
3136 this->traverse(&cfd);
3137 }
3138
3139 // Look for interface types to finalize methods of inherited
3140 // interfaces.
3141
3142 class Finalize_methods : public Traverse
3143 {
3144 public:
3145 Finalize_methods(Gogo* gogo)
3146 : Traverse(traverse_types),
3147 gogo_(gogo)
3148 { }
3149
3150 int
3151 type(Type*);
3152
3153 private:
3154 Gogo* gogo_;
3155 };
3156
3157 // Finalize the methods of an interface type.
3158
3159 int
3160 Finalize_methods::type(Type* t)
3161 {
3162 // Check the classification so that we don't finalize the methods
3163 // twice for a named interface type.
3164 switch (t->classification())
3165 {
3166 case Type::TYPE_INTERFACE:
3167 t->interface_type()->finalize_methods();
3168 break;
3169
3170 case Type::TYPE_NAMED:
3171 {
3172 Named_type* nt = t->named_type();
3173 Type* rt = nt->real_type();
3174 if (rt->classification() != Type::TYPE_STRUCT)
3175 {
3176 // Finalize the methods of the real type first.
3177 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3178 return TRAVERSE_EXIT;
3179
3180 // Finalize the methods of this type.
3181 nt->finalize_methods(this->gogo_);
3182 }
3183 else
3184 {
3185 // We don't want to finalize the methods of a named struct
3186 // type, as the methods should be attached to the named
3187 // type, not the struct type. We just want to finalize
3188 // the field types.
3189 //
3190 // It is possible that a field type refers indirectly to
3191 // this type, such as via a field with function type with
3192 // an argument or result whose type is this type. To
3193 // avoid the cycle, first finalize the methods of any
3194 // embedded types, which are the only types we need to
3195 // know to finalize the methods of this type.
3196 const Struct_field_list* fields = rt->struct_type()->fields();
3197 if (fields != NULL)
3198 {
3199 for (Struct_field_list::const_iterator pf = fields->begin();
3200 pf != fields->end();
3201 ++pf)
3202 {
3203 if (pf->is_anonymous())
3204 {
3205 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3206 return TRAVERSE_EXIT;
3207 }
3208 }
3209 }
3210
3211 // Finalize the methods of this type.
3212 nt->finalize_methods(this->gogo_);
3213
3214 // Finalize all the struct fields.
3215 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3216 return TRAVERSE_EXIT;
3217 }
3218
3219 // If this type is defined in a different package, then finalize the
3220 // types of all the methods, since we won't see them otherwise.
3221 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3222 {
3223 const Methods* methods = nt->methods();
3224 for (Methods::const_iterator p = methods->begin();
3225 p != methods->end();
3226 ++p)
3227 {
3228 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3229 return TRAVERSE_EXIT;
3230 }
3231 }
3232
3233 // Finalize the types of all methods that are declared but not
3234 // defined, since we won't see the declarations otherwise.
3235 if (nt->named_object()->package() == NULL
3236 && nt->local_methods() != NULL)
3237 {
3238 const Bindings* methods = nt->local_methods();
3239 for (Bindings::const_declarations_iterator p =
3240 methods->begin_declarations();
3241 p != methods->end_declarations();
3242 p++)
3243 {
3244 if (p->second->is_function_declaration())
3245 {
3246 Type* mt = p->second->func_declaration_value()->type();
3247 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3248 return TRAVERSE_EXIT;
3249 }
3250 }
3251 }
3252
3253 return TRAVERSE_SKIP_COMPONENTS;
3254 }
3255
3256 case Type::TYPE_STRUCT:
3257 // Traverse the field types first in case there is an embedded
3258 // field with methods that the struct should inherit.
3259 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3260 return TRAVERSE_EXIT;
3261 t->struct_type()->finalize_methods(this->gogo_);
3262 return TRAVERSE_SKIP_COMPONENTS;
3263
3264 default:
3265 break;
3266 }
3267
3268 return TRAVERSE_CONTINUE;
3269 }
3270
3271 // Finalize method lists and build stub methods for types.
3272
3273 void
3274 Gogo::finalize_methods()
3275 {
3276 Finalize_methods finalize(this);
3277 this->traverse(&finalize);
3278 }
3279
3280 // Finalize the method list for a type. This is called when a type is
3281 // parsed for an inlined function body, which happens after the
3282 // finalize_methods pass.
3283
3284 void
3285 Gogo::finalize_methods_for_type(Type* type)
3286 {
3287 Finalize_methods finalize(this);
3288 Type::traverse(type, &finalize);
3289 }
3290
3291 // Set types for unspecified variables and constants.
3292
3293 void
3294 Gogo::determine_types()
3295 {
3296 Bindings* bindings = this->current_bindings();
3297 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3298 p != bindings->end_definitions();
3299 ++p)
3300 {
3301 if ((*p)->is_function())
3302 (*p)->func_value()->determine_types();
3303 else if ((*p)->is_variable())
3304 (*p)->var_value()->determine_type();
3305 else if ((*p)->is_const())
3306 (*p)->const_value()->determine_type();
3307
3308 // See if a variable requires us to build an initialization
3309 // function. We know that we will see all global variables
3310 // here.
3311 if (!this->need_init_fn_ && (*p)->is_variable())
3312 {
3313 Variable* variable = (*p)->var_value();
3314
3315 // If this is a global variable which requires runtime
3316 // initialization, we need an initialization function.
3317 if (!variable->is_global())
3318 ;
3319 else if (variable->init() == NULL)
3320 ;
3321 else if (variable->type()->interface_type() != NULL)
3322 this->need_init_fn_ = true;
3323 else if (variable->init()->is_constant())
3324 ;
3325 else if (!variable->init()->is_composite_literal())
3326 this->need_init_fn_ = true;
3327 else if (variable->init()->is_nonconstant_composite_literal())
3328 this->need_init_fn_ = true;
3329
3330 // If this is a global variable which holds a pointer value,
3331 // then we need an initialization function to register it as a
3332 // GC root.
3333 if (variable->is_global() && variable->type()->has_pointer())
3334 this->need_init_fn_ = true;
3335 }
3336 }
3337
3338 // Determine the types of constants in packages.
3339 for (Packages::const_iterator p = this->packages_.begin();
3340 p != this->packages_.end();
3341 ++p)
3342 p->second->determine_types();
3343 }
3344
3345 // Traversal class used for type checking.
3346
3347 class Check_types_traverse : public Traverse
3348 {
3349 public:
3350 Check_types_traverse(Gogo* gogo)
3351 : Traverse(traverse_variables
3352 | traverse_constants
3353 | traverse_functions
3354 | traverse_statements
3355 | traverse_expressions),
3356 gogo_(gogo)
3357 { }
3358
3359 int
3360 variable(Named_object*);
3361
3362 int
3363 constant(Named_object*, bool);
3364
3365 int
3366 function(Named_object*);
3367
3368 int
3369 statement(Block*, size_t* pindex, Statement*);
3370
3371 int
3372 expression(Expression**);
3373
3374 private:
3375 // General IR.
3376 Gogo* gogo_;
3377 };
3378
3379 // Check that a variable initializer has the right type.
3380
3381 int
3382 Check_types_traverse::variable(Named_object* named_object)
3383 {
3384 if (named_object->is_variable())
3385 {
3386 Variable* var = named_object->var_value();
3387
3388 // Give error if variable type is not defined.
3389 var->type()->base();
3390
3391 Expression* init = var->init();
3392 std::string reason;
3393 if (init != NULL
3394 && !Type::are_assignable(var->type(), init->type(), &reason))
3395 {
3396 if (reason.empty())
3397 go_error_at(var->location(), "incompatible type in initialization");
3398 else
3399 go_error_at(var->location(),
3400 "incompatible type in initialization (%s)",
3401 reason.c_str());
3402 init = Expression::make_error(named_object->location());
3403 var->clear_init();
3404 }
3405 else if (init != NULL
3406 && init->func_expression() != NULL)
3407 {
3408 Named_object* no = init->func_expression()->named_object();
3409 Function_type* fntype;
3410 if (no->is_function())
3411 fntype = no->func_value()->type();
3412 else if (no->is_function_declaration())
3413 fntype = no->func_declaration_value()->type();
3414 else
3415 go_unreachable();
3416
3417 // Builtin functions cannot be used as function values for variable
3418 // initialization.
3419 if (fntype->is_builtin())
3420 {
3421 go_error_at(init->location(),
3422 "invalid use of special builtin function %qs; "
3423 "must be called",
3424 no->message_name().c_str());
3425 }
3426 }
3427 if (!var->is_used()
3428 && !var->is_global()
3429 && !var->is_parameter()
3430 && !var->is_receiver()
3431 && !var->type()->is_error()
3432 && (init == NULL || !init->is_error_expression())
3433 && !Lex::is_invalid_identifier(named_object->name()))
3434 go_error_at(var->location(), "%qs declared and not used",
3435 named_object->message_name().c_str());
3436 }
3437 return TRAVERSE_CONTINUE;
3438 }
3439
3440 // Check that a constant initializer has the right type.
3441
3442 int
3443 Check_types_traverse::constant(Named_object* named_object, bool)
3444 {
3445 Named_constant* constant = named_object->const_value();
3446 Type* ctype = constant->type();
3447 if (ctype->integer_type() == NULL
3448 && ctype->float_type() == NULL
3449 && ctype->complex_type() == NULL
3450 && !ctype->is_boolean_type()
3451 && !ctype->is_string_type())
3452 {
3453 if (ctype->is_nil_type())
3454 go_error_at(constant->location(), "const initializer cannot be nil");
3455 else if (!ctype->is_error())
3456 go_error_at(constant->location(), "invalid constant type");
3457 constant->set_error();
3458 }
3459 else if (!constant->expr()->is_constant())
3460 {
3461 go_error_at(constant->expr()->location(), "expression is not constant");
3462 constant->set_error();
3463 }
3464 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3465 NULL))
3466 {
3467 go_error_at(constant->location(),
3468 "initialization expression has wrong type");
3469 constant->set_error();
3470 }
3471 return TRAVERSE_CONTINUE;
3472 }
3473
3474 // There are no types to check in a function, but this is where we
3475 // issue warnings about labels which are defined but not referenced.
3476
3477 int
3478 Check_types_traverse::function(Named_object* no)
3479 {
3480 no->func_value()->check_labels();
3481 return TRAVERSE_CONTINUE;
3482 }
3483
3484 // Check that types are valid in a statement.
3485
3486 int
3487 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3488 {
3489 s->check_types(this->gogo_);
3490 return TRAVERSE_CONTINUE;
3491 }
3492
3493 // Check that types are valid in an expression.
3494
3495 int
3496 Check_types_traverse::expression(Expression** expr)
3497 {
3498 (*expr)->check_types(this->gogo_);
3499 return TRAVERSE_CONTINUE;
3500 }
3501
3502 // Check that types are valid.
3503
3504 void
3505 Gogo::check_types()
3506 {
3507 Check_types_traverse traverse(this);
3508 this->traverse(&traverse);
3509
3510 Bindings* bindings = this->current_bindings();
3511 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3512 p != bindings->end_declarations();
3513 ++p)
3514 {
3515 // Also check the types in a function declaration's signature.
3516 Named_object* no = p->second;
3517 if (no->is_function_declaration())
3518 no->func_declaration_value()->check_types();
3519 }
3520 }
3521
3522 // Check the types in a single block.
3523
3524 void
3525 Gogo::check_types_in_block(Block* block)
3526 {
3527 Check_types_traverse traverse(this);
3528 block->traverse(&traverse);
3529 }
3530
3531 // A traversal class which finds all the expressions which must be
3532 // evaluated in order within a statement or larger expression. This
3533 // is used to implement the rules about order of evaluation.
3534
3535 class Find_eval_ordering : public Traverse
3536 {
3537 private:
3538 typedef std::vector<Expression**> Expression_pointers;
3539
3540 public:
3541 Find_eval_ordering()
3542 : Traverse(traverse_blocks
3543 | traverse_statements
3544 | traverse_expressions),
3545 exprs_()
3546 { }
3547
3548 size_t
3549 size() const
3550 { return this->exprs_.size(); }
3551
3552 typedef Expression_pointers::const_iterator const_iterator;
3553
3554 const_iterator
3555 begin() const
3556 { return this->exprs_.begin(); }
3557
3558 const_iterator
3559 end() const
3560 { return this->exprs_.end(); }
3561
3562 protected:
3563 int
3564 block(Block*)
3565 { return TRAVERSE_SKIP_COMPONENTS; }
3566
3567 int
3568 statement(Block*, size_t*, Statement*)
3569 { return TRAVERSE_SKIP_COMPONENTS; }
3570
3571 int
3572 expression(Expression**);
3573
3574 private:
3575 // A list of pointers to expressions with side-effects.
3576 Expression_pointers exprs_;
3577 };
3578
3579 // If an expression must be evaluated in order, put it on the list.
3580
3581 int
3582 Find_eval_ordering::expression(Expression** expression_pointer)
3583 {
3584 Binary_expression* binexp = (*expression_pointer)->binary_expression();
3585 if (binexp != NULL
3586 && (binexp->op() == OPERATOR_ANDAND || binexp->op() == OPERATOR_OROR))
3587 {
3588 // Shortcut expressions may potentially have side effects which need
3589 // to be ordered, so add them to the list.
3590 // We don't order its subexpressions here since they may be evaluated
3591 // conditionally. This is handled in remove_shortcuts.
3592 this->exprs_.push_back(expression_pointer);
3593 return TRAVERSE_SKIP_COMPONENTS;
3594 }
3595
3596 // We have to look at subexpressions before this one.
3597 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3598 return TRAVERSE_EXIT;
3599 if ((*expression_pointer)->must_eval_in_order())
3600 this->exprs_.push_back(expression_pointer);
3601 return TRAVERSE_SKIP_COMPONENTS;
3602 }
3603
3604 // A traversal class for ordering evaluations.
3605
3606 class Order_eval : public Traverse
3607 {
3608 public:
3609 Order_eval(Gogo* gogo)
3610 : Traverse(traverse_variables
3611 | traverse_statements),
3612 gogo_(gogo)
3613 { }
3614
3615 int
3616 variable(Named_object*);
3617
3618 int
3619 statement(Block*, size_t*, Statement*);
3620
3621 private:
3622 // The IR.
3623 Gogo* gogo_;
3624 };
3625
3626 // Implement the order of evaluation rules for a statement.
3627
3628 int
3629 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3630 {
3631 // FIXME: This approach doesn't work for switch statements, because
3632 // we add the new statements before the whole switch when we need to
3633 // instead add them just before the switch expression. The right
3634 // fix is probably to lower switch statements with nonconstant cases
3635 // to a series of conditionals.
3636 if (stmt->switch_statement() != NULL)
3637 return TRAVERSE_CONTINUE;
3638
3639 Find_eval_ordering find_eval_ordering;
3640
3641 // If S is a variable declaration, then ordinary traversal won't do
3642 // anything. We want to explicitly traverse the initialization
3643 // expression if there is one.
3644 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3645 Expression* init = NULL;
3646 Expression* orig_init = NULL;
3647 if (vds == NULL)
3648 stmt->traverse_contents(&find_eval_ordering);
3649 else
3650 {
3651 init = vds->var()->var_value()->init();
3652 if (init == NULL)
3653 return TRAVERSE_CONTINUE;
3654 orig_init = init;
3655
3656 // It might seem that this could be
3657 // init->traverse_subexpressions. Unfortunately that can fail
3658 // in a case like
3659 // var err os.Error
3660 // newvar, err := call(arg())
3661 // Here newvar will have an init of call result 0 of
3662 // call(arg()). If we only traverse subexpressions, we will
3663 // only find arg(), and we won't bother to move anything out.
3664 // Then we get to the assignment to err, we will traverse the
3665 // whole statement, and this time we will find both call() and
3666 // arg(), and so we will move them out. This will cause them to
3667 // be put into temporary variables before the assignment to err
3668 // but after the declaration of newvar. To avoid that problem,
3669 // we traverse the entire expression here.
3670 Expression::traverse(&init, &find_eval_ordering);
3671 }
3672
3673 size_t c = find_eval_ordering.size();
3674 if (c == 0)
3675 return TRAVERSE_CONTINUE;
3676
3677 // If there is only one expression with a side-effect, we can
3678 // usually leave it in place.
3679 if (c == 1)
3680 {
3681 switch (stmt->classification())
3682 {
3683 case Statement::STATEMENT_ASSIGNMENT:
3684 // For an assignment statement, we need to evaluate an
3685 // expression on the right hand side before we evaluate any
3686 // index expression on the left hand side, so for that case
3687 // we always move the expression. Otherwise we mishandle
3688 // m[0] = len(m) where m is a map.
3689 break;
3690
3691 case Statement::STATEMENT_EXPRESSION:
3692 {
3693 // If this is a call statement that doesn't return any
3694 // values, it will not have been counted as a value to
3695 // move. We need to move any subexpressions in case they
3696 // are themselves call statements that require passing a
3697 // closure.
3698 Expression* expr = stmt->expression_statement()->expr();
3699 if (expr->call_expression() != NULL
3700 && expr->call_expression()->result_count() == 0)
3701 break;
3702 return TRAVERSE_CONTINUE;
3703 }
3704
3705 default:
3706 // We can leave the expression in place.
3707 return TRAVERSE_CONTINUE;
3708 }
3709 }
3710
3711 bool is_thunk = stmt->thunk_statement() != NULL;
3712 Expression_statement* es = stmt->expression_statement();
3713 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3714 p != find_eval_ordering.end();
3715 ++p)
3716 {
3717 Expression** pexpr = *p;
3718
3719 // The last expression in a thunk will be the call passed to go
3720 // or defer, which we must not evaluate early.
3721 if (is_thunk && p + 1 == find_eval_ordering.end())
3722 break;
3723
3724 Location loc = (*pexpr)->location();
3725 Statement* s;
3726 if ((*pexpr)->call_expression() == NULL
3727 || (*pexpr)->call_expression()->result_count() < 2)
3728 {
3729 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3730 loc);
3731 s = ts;
3732 *pexpr = Expression::make_temporary_reference(ts, loc);
3733 }
3734 else
3735 {
3736 // A call expression which returns multiple results needs to
3737 // be handled specially. We can't create a temporary
3738 // because there is no type to give it. Any actual uses of
3739 // the values will be done via Call_result_expressions.
3740 //
3741 // Since a given call expression can be shared by multiple
3742 // Call_result_expressions, avoid hoisting the call the
3743 // second time we see it here. In addition, don't try to
3744 // hoist the top-level multi-return call in the statement,
3745 // since doing this would result a tree with more than one copy
3746 // of the call.
3747 if (this->remember_expression(*pexpr))
3748 s = NULL;
3749 else if (es != NULL && *pexpr == es->expr())
3750 s = NULL;
3751 else
3752 s = Statement::make_statement(*pexpr, true);
3753 }
3754
3755 if (s != NULL)
3756 {
3757 block->insert_statement_before(*pindex, s);
3758 ++*pindex;
3759 }
3760 }
3761
3762 if (init != orig_init)
3763 vds->var()->var_value()->set_init(init);
3764
3765 return TRAVERSE_CONTINUE;
3766 }
3767
3768 // Implement the order of evaluation rules for the initializer of a
3769 // global variable.
3770
3771 int
3772 Order_eval::variable(Named_object* no)
3773 {
3774 if (no->is_result_variable())
3775 return TRAVERSE_CONTINUE;
3776 Variable* var = no->var_value();
3777 Expression* init = var->init();
3778 if (!var->is_global() || init == NULL)
3779 return TRAVERSE_CONTINUE;
3780
3781 Find_eval_ordering find_eval_ordering;
3782 Expression::traverse(&init, &find_eval_ordering);
3783
3784 if (find_eval_ordering.size() <= 1)
3785 {
3786 // If there is only one expression with a side-effect, we can
3787 // leave it in place.
3788 return TRAVERSE_SKIP_COMPONENTS;
3789 }
3790
3791 Expression* orig_init = init;
3792
3793 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3794 p != find_eval_ordering.end();
3795 ++p)
3796 {
3797 Expression** pexpr = *p;
3798 Location loc = (*pexpr)->location();
3799 Statement* s;
3800 if ((*pexpr)->call_expression() == NULL
3801 || (*pexpr)->call_expression()->result_count() < 2)
3802 {
3803 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3804 loc);
3805 s = ts;
3806 *pexpr = Expression::make_temporary_reference(ts, loc);
3807 }
3808 else
3809 {
3810 // A call expression which returns multiple results needs to
3811 // be handled specially.
3812 s = Statement::make_statement(*pexpr, true);
3813 }
3814 var->add_preinit_statement(this->gogo_, s);
3815 }
3816
3817 if (init != orig_init)
3818 var->set_init(init);
3819
3820 return TRAVERSE_SKIP_COMPONENTS;
3821 }
3822
3823 // Use temporary variables to implement the order of evaluation rules.
3824
3825 void
3826 Gogo::order_evaluations()
3827 {
3828 Order_eval order_eval(this);
3829 this->traverse(&order_eval);
3830 }
3831
3832 // A traversal class used to find a single shortcut operator within an
3833 // expression.
3834
3835 class Find_shortcut : public Traverse
3836 {
3837 public:
3838 Find_shortcut()
3839 : Traverse(traverse_blocks
3840 | traverse_statements
3841 | traverse_expressions),
3842 found_(NULL)
3843 { }
3844
3845 // A pointer to the expression which was found, or NULL if none was
3846 // found.
3847 Expression**
3848 found() const
3849 { return this->found_; }
3850
3851 protected:
3852 int
3853 block(Block*)
3854 { return TRAVERSE_SKIP_COMPONENTS; }
3855
3856 int
3857 statement(Block*, size_t*, Statement*)
3858 { return TRAVERSE_SKIP_COMPONENTS; }
3859
3860 int
3861 expression(Expression**);
3862
3863 private:
3864 Expression** found_;
3865 };
3866
3867 // Find a shortcut expression.
3868
3869 int
3870 Find_shortcut::expression(Expression** pexpr)
3871 {
3872 Expression* expr = *pexpr;
3873 Binary_expression* be = expr->binary_expression();
3874 if (be == NULL)
3875 return TRAVERSE_CONTINUE;
3876 Operator op = be->op();
3877 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3878 return TRAVERSE_CONTINUE;
3879 go_assert(this->found_ == NULL);
3880 this->found_ = pexpr;
3881 return TRAVERSE_EXIT;
3882 }
3883
3884 // A traversal class used to turn shortcut operators into explicit if
3885 // statements.
3886
3887 class Shortcuts : public Traverse
3888 {
3889 public:
3890 Shortcuts(Gogo* gogo)
3891 : Traverse(traverse_variables
3892 | traverse_statements),
3893 gogo_(gogo)
3894 { }
3895
3896 protected:
3897 int
3898 variable(Named_object*);
3899
3900 int
3901 statement(Block*, size_t*, Statement*);
3902
3903 private:
3904 // Convert a shortcut operator.
3905 Statement*
3906 convert_shortcut(Block* enclosing, Expression** pshortcut);
3907
3908 // The IR.
3909 Gogo* gogo_;
3910 };
3911
3912 // Remove shortcut operators in a single statement.
3913
3914 int
3915 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3916 {
3917 // FIXME: This approach doesn't work for switch statements, because
3918 // we add the new statements before the whole switch when we need to
3919 // instead add them just before the switch expression. The right
3920 // fix is probably to lower switch statements with nonconstant cases
3921 // to a series of conditionals.
3922 if (s->switch_statement() != NULL)
3923 return TRAVERSE_CONTINUE;
3924
3925 while (true)
3926 {
3927 Find_shortcut find_shortcut;
3928
3929 // If S is a variable declaration, then ordinary traversal won't
3930 // do anything. We want to explicitly traverse the
3931 // initialization expression if there is one.
3932 Variable_declaration_statement* vds = s->variable_declaration_statement();
3933 Expression* init = NULL;
3934 if (vds == NULL)
3935 s->traverse_contents(&find_shortcut);
3936 else
3937 {
3938 init = vds->var()->var_value()->init();
3939 if (init == NULL)
3940 return TRAVERSE_CONTINUE;
3941 init->traverse(&init, &find_shortcut);
3942 }
3943 Expression** pshortcut = find_shortcut.found();
3944 if (pshortcut == NULL)
3945 return TRAVERSE_CONTINUE;
3946
3947 Statement* snew = this->convert_shortcut(block, pshortcut);
3948 block->insert_statement_before(*pindex, snew);
3949 ++*pindex;
3950
3951 if (pshortcut == &init)
3952 vds->var()->var_value()->set_init(init);
3953 }
3954 }
3955
3956 // Remove shortcut operators in the initializer of a global variable.
3957
3958 int
3959 Shortcuts::variable(Named_object* no)
3960 {
3961 if (no->is_result_variable())
3962 return TRAVERSE_CONTINUE;
3963 Variable* var = no->var_value();
3964 Expression* init = var->init();
3965 if (!var->is_global() || init == NULL)
3966 return TRAVERSE_CONTINUE;
3967
3968 while (true)
3969 {
3970 Find_shortcut find_shortcut;
3971 init->traverse(&init, &find_shortcut);
3972 Expression** pshortcut = find_shortcut.found();
3973 if (pshortcut == NULL)
3974 return TRAVERSE_CONTINUE;
3975
3976 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3977 var->add_preinit_statement(this->gogo_, snew);
3978 if (pshortcut == &init)
3979 var->set_init(init);
3980 }
3981 }
3982
3983 // Given an expression which uses a shortcut operator, return a
3984 // statement which implements it, and update *PSHORTCUT accordingly.
3985
3986 Statement*
3987 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3988 {
3989 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3990 Expression* left = shortcut->left();
3991 Expression* right = shortcut->right();
3992 Location loc = shortcut->location();
3993
3994 Block* retblock = new Block(enclosing, loc);
3995 retblock->set_end_location(loc);
3996
3997 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3998 left, loc);
3999 retblock->add_statement(ts);
4000
4001 Block* block = new Block(retblock, loc);
4002 block->set_end_location(loc);
4003 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
4004 Statement* assign = Statement::make_assignment(tmpref, right, loc);
4005 block->add_statement(assign);
4006
4007 Expression* cond = Expression::make_temporary_reference(ts, loc);
4008 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
4009 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
4010
4011 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
4012 loc);
4013 retblock->add_statement(if_statement);
4014
4015 *pshortcut = Expression::make_temporary_reference(ts, loc);
4016
4017 delete shortcut;
4018
4019 // Now convert any shortcut operators in LEFT and RIGHT.
4020 // LEFT and RIGHT were skipped in the top level
4021 // Gogo::order_evaluations. We need to order their
4022 // components first.
4023 Order_eval order_eval(this->gogo_);
4024 retblock->traverse(&order_eval);
4025 Shortcuts shortcuts(this->gogo_);
4026 retblock->traverse(&shortcuts);
4027
4028 return Statement::make_block_statement(retblock, loc);
4029 }
4030
4031 // Turn shortcut operators into explicit if statements. Doing this
4032 // considerably simplifies the order of evaluation rules.
4033
4034 void
4035 Gogo::remove_shortcuts()
4036 {
4037 Shortcuts shortcuts(this);
4038 this->traverse(&shortcuts);
4039 }
4040
4041 // Traversal to flatten parse tree after order of evaluation rules are applied.
4042
4043 class Flatten : public Traverse
4044 {
4045 public:
4046 Flatten(Gogo* gogo, Named_object* function)
4047 : Traverse(traverse_variables
4048 | traverse_functions
4049 | traverse_statements
4050 | traverse_expressions),
4051 gogo_(gogo), function_(function), inserter_()
4052 { }
4053
4054 void
4055 set_inserter(const Statement_inserter* inserter)
4056 { this->inserter_ = *inserter; }
4057
4058 int
4059 variable(Named_object*);
4060
4061 int
4062 function(Named_object*);
4063
4064 int
4065 statement(Block*, size_t* pindex, Statement*);
4066
4067 int
4068 expression(Expression**);
4069
4070 private:
4071 // General IR.
4072 Gogo* gogo_;
4073 // The function we are traversing.
4074 Named_object* function_;
4075 // Current statement inserter for use by expressions.
4076 Statement_inserter inserter_;
4077 };
4078
4079 // Flatten variables.
4080
4081 int
4082 Flatten::variable(Named_object* no)
4083 {
4084 if (!no->is_variable())
4085 return TRAVERSE_CONTINUE;
4086
4087 if (no->is_variable() && no->var_value()->is_global())
4088 {
4089 // Global variables can have loops in their initialization
4090 // expressions. This is handled in flatten_init_expression.
4091 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
4092 &this->inserter_);
4093 return TRAVERSE_CONTINUE;
4094 }
4095
4096 if (!no->var_value()->is_parameter()
4097 && !no->var_value()->is_receiver()
4098 && !no->var_value()->is_closure()
4099 && no->var_value()->is_non_escaping_address_taken()
4100 && !no->var_value()->is_in_heap()
4101 && no->var_value()->toplevel_decl() == NULL)
4102 {
4103 // Local variable that has address taken but not escape.
4104 // It needs to be live beyond its lexical scope. So we
4105 // create a top-level declaration for it.
4106 // No need to do it if it is already in the top level.
4107 Block* top_block = function_->func_value()->block();
4108 if (top_block->bindings()->lookup_local(no->name()) != no)
4109 {
4110 Variable* var = no->var_value();
4111 Temporary_statement* ts =
4112 Statement::make_temporary(var->type(), NULL, var->location());
4113 ts->set_is_address_taken();
4114 top_block->add_statement_at_front(ts);
4115 var->set_toplevel_decl(ts);
4116 }
4117 }
4118
4119 go_assert(!no->var_value()->has_pre_init());
4120
4121 return TRAVERSE_SKIP_COMPONENTS;
4122 }
4123
4124 // Flatten the body of a function. Record the function while flattening it,
4125 // so that we can pass it down when flattening an expression.
4126
4127 int
4128 Flatten::function(Named_object* no)
4129 {
4130 go_assert(this->function_ == NULL);
4131 this->function_ = no;
4132 int t = no->func_value()->traverse(this);
4133 this->function_ = NULL;
4134
4135 if (t == TRAVERSE_EXIT)
4136 return t;
4137 return TRAVERSE_SKIP_COMPONENTS;
4138 }
4139
4140 // Flatten statement parse trees.
4141
4142 int
4143 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
4144 {
4145 // Because we explicitly traverse the statement's contents
4146 // ourselves, we want to skip block statements here. There is
4147 // nothing to flatten in a block statement.
4148 if (sorig->is_block_statement())
4149 return TRAVERSE_CONTINUE;
4150
4151 Statement_inserter hold_inserter(this->inserter_);
4152 this->inserter_ = Statement_inserter(block, pindex);
4153
4154 // Flatten the expressions first.
4155 int t = sorig->traverse_contents(this);
4156 if (t == TRAVERSE_EXIT)
4157 {
4158 this->inserter_ = hold_inserter;
4159 return t;
4160 }
4161
4162 // Keep flattening until nothing changes.
4163 Statement* s = sorig;
4164 while (true)
4165 {
4166 Statement* snew = s->flatten(this->gogo_, this->function_, block,
4167 &this->inserter_);
4168 if (snew == s)
4169 break;
4170 s = snew;
4171 t = s->traverse_contents(this);
4172 if (t == TRAVERSE_EXIT)
4173 {
4174 this->inserter_ = hold_inserter;
4175 return t;
4176 }
4177 }
4178
4179 if (s != sorig)
4180 block->replace_statement(*pindex, s);
4181
4182 this->inserter_ = hold_inserter;
4183 return TRAVERSE_SKIP_COMPONENTS;
4184 }
4185
4186 // Flatten expression parse trees.
4187
4188 int
4189 Flatten::expression(Expression** pexpr)
4190 {
4191 // Keep flattening until nothing changes.
4192 while (true)
4193 {
4194 Expression* e = *pexpr;
4195 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
4196 return TRAVERSE_EXIT;
4197
4198 Expression* enew = e->flatten(this->gogo_, this->function_,
4199 &this->inserter_);
4200 if (enew == e)
4201 break;
4202 *pexpr = enew;
4203 }
4204 return TRAVERSE_SKIP_COMPONENTS;
4205 }
4206
4207 // Flatten a block.
4208
4209 void
4210 Gogo::flatten_block(Named_object* function, Block* block)
4211 {
4212 Flatten flatten(this, function);
4213 block->traverse(&flatten);
4214 }
4215
4216 // Flatten an expression. INSERTER may be NULL, in which case the
4217 // expression had better not need to create any temporaries.
4218
4219 void
4220 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4221 Expression** pexpr)
4222 {
4223 Flatten flatten(this, function);
4224 if (inserter != NULL)
4225 flatten.set_inserter(inserter);
4226 flatten.expression(pexpr);
4227 }
4228
4229 void
4230 Gogo::flatten()
4231 {
4232 Flatten flatten(this, NULL);
4233 this->traverse(&flatten);
4234 }
4235
4236 // Traversal to convert calls to the predeclared recover function to
4237 // pass in an argument indicating whether it can recover from a panic
4238 // or not.
4239
4240 class Convert_recover : public Traverse
4241 {
4242 public:
4243 Convert_recover(Named_object* arg)
4244 : Traverse(traverse_expressions),
4245 arg_(arg)
4246 { }
4247
4248 protected:
4249 int
4250 expression(Expression**);
4251
4252 private:
4253 // The argument to pass to the function.
4254 Named_object* arg_;
4255 };
4256
4257 // Convert calls to recover.
4258
4259 int
4260 Convert_recover::expression(Expression** pp)
4261 {
4262 Call_expression* ce = (*pp)->call_expression();
4263 if (ce != NULL && ce->is_recover_call())
4264 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4265 ce->location()));
4266 return TRAVERSE_CONTINUE;
4267 }
4268
4269 // Traversal for build_recover_thunks.
4270
4271 class Build_recover_thunks : public Traverse
4272 {
4273 public:
4274 Build_recover_thunks(Gogo* gogo)
4275 : Traverse(traverse_functions),
4276 gogo_(gogo)
4277 { }
4278
4279 int
4280 function(Named_object*);
4281
4282 private:
4283 Expression*
4284 can_recover_arg(Location);
4285
4286 // General IR.
4287 Gogo* gogo_;
4288 };
4289
4290 // If this function calls recover, turn it into a thunk.
4291
4292 int
4293 Build_recover_thunks::function(Named_object* orig_no)
4294 {
4295 Function* orig_func = orig_no->func_value();
4296 if (!orig_func->calls_recover()
4297 || orig_func->is_recover_thunk()
4298 || orig_func->has_recover_thunk())
4299 return TRAVERSE_CONTINUE;
4300
4301 Gogo* gogo = this->gogo_;
4302 Location location = orig_func->location();
4303
4304 static int count;
4305 char buf[50];
4306
4307 Function_type* orig_fntype = orig_func->type();
4308 Typed_identifier_list* new_params = new Typed_identifier_list();
4309 std::string receiver_name;
4310 if (orig_fntype->is_method())
4311 {
4312 const Typed_identifier* receiver = orig_fntype->receiver();
4313 snprintf(buf, sizeof buf, "rt.%u", count);
4314 ++count;
4315 receiver_name = buf;
4316 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4317 receiver->location()));
4318 }
4319 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4320 if (orig_params != NULL && !orig_params->empty())
4321 {
4322 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4323 p != orig_params->end();
4324 ++p)
4325 {
4326 snprintf(buf, sizeof buf, "pt.%u", count);
4327 ++count;
4328 new_params->push_back(Typed_identifier(buf, p->type(),
4329 p->location()));
4330 }
4331 }
4332 snprintf(buf, sizeof buf, "pr.%u", count);
4333 ++count;
4334 std::string can_recover_name = buf;
4335 new_params->push_back(Typed_identifier(can_recover_name,
4336 Type::lookup_bool_type(),
4337 orig_fntype->location()));
4338
4339 const Typed_identifier_list* orig_results = orig_fntype->results();
4340 Typed_identifier_list* new_results;
4341 if (orig_results == NULL || orig_results->empty())
4342 new_results = NULL;
4343 else
4344 {
4345 new_results = new Typed_identifier_list();
4346 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4347 p != orig_results->end();
4348 ++p)
4349 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4350 }
4351
4352 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4353 new_results,
4354 orig_fntype->location());
4355 if (orig_fntype->is_varargs())
4356 new_fntype->set_is_varargs();
4357
4358 Type* rtype = NULL;
4359 if (orig_fntype->is_method())
4360 rtype = orig_fntype->receiver()->type();
4361 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4362 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4363 location);
4364 Function *new_func = new_no->func_value();
4365 if (orig_func->enclosing() != NULL)
4366 new_func->set_enclosing(orig_func->enclosing());
4367
4368 // We build the code for the original function attached to the new
4369 // function, and then swap the original and new function bodies.
4370 // This means that existing references to the original function will
4371 // then refer to the new function. That makes this code a little
4372 // confusing, in that the reference to NEW_NO really refers to the
4373 // other function, not the one we are building.
4374
4375 Expression* closure = NULL;
4376 if (orig_func->needs_closure())
4377 {
4378 // For the new function we are creating, declare a new parameter
4379 // variable NEW_CLOSURE_NO and set it to be the closure variable
4380 // of the function. This will be set to the closure value
4381 // passed in by the caller. Then pass a reference to this
4382 // variable as the closure value when calling the original
4383 // function. In other words, simply pass the closure value
4384 // through the thunk we are creating.
4385 Named_object* orig_closure_no = orig_func->closure_var();
4386 Variable* orig_closure_var = orig_closure_no->var_value();
4387 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4388 false, false, location);
4389 new_var->set_is_closure();
4390 snprintf(buf, sizeof buf, "closure.%u", count);
4391 ++count;
4392 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4393 new_var);
4394 new_func->set_closure_var(new_closure_no);
4395 closure = Expression::make_var_reference(new_closure_no, location);
4396 }
4397
4398 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4399
4400 Expression_list* args = new Expression_list();
4401 if (new_params != NULL)
4402 {
4403 // Note that we skip the last parameter, which is the boolean
4404 // indicating whether recover can succed.
4405 for (Typed_identifier_list::const_iterator p = new_params->begin();
4406 p + 1 != new_params->end();
4407 ++p)
4408 {
4409 Named_object* p_no = gogo->lookup(p->name(), NULL);
4410 go_assert(p_no != NULL
4411 && p_no->is_variable()
4412 && p_no->var_value()->is_parameter());
4413 args->push_back(Expression::make_var_reference(p_no, location));
4414 }
4415 }
4416 args->push_back(this->can_recover_arg(location));
4417
4418 gogo->start_block(location);
4419
4420 Call_expression* call = Expression::make_call(fn, args, false, location);
4421
4422 // Any varargs call has already been lowered.
4423 call->set_varargs_are_lowered();
4424
4425 Statement* s = Statement::make_return_from_call(call, location);
4426 s->determine_types();
4427 gogo->add_statement(s);
4428
4429 Block* b = gogo->finish_block(location);
4430
4431 gogo->add_block(b, location);
4432
4433 // Lower the call in case it returns multiple results.
4434 gogo->lower_block(new_no, b);
4435
4436 gogo->finish_function(location);
4437
4438 // Swap the function bodies and types.
4439 new_func->swap_for_recover(orig_func);
4440 orig_func->set_is_recover_thunk();
4441 new_func->set_calls_recover();
4442 new_func->set_has_recover_thunk();
4443
4444 Bindings* orig_bindings = orig_func->block()->bindings();
4445 Bindings* new_bindings = new_func->block()->bindings();
4446 if (orig_fntype->is_method())
4447 {
4448 // We changed the receiver to be a regular parameter. We have
4449 // to update the binding accordingly in both functions.
4450 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4451 go_assert(orig_rec_no != NULL
4452 && orig_rec_no->is_variable()
4453 && !orig_rec_no->var_value()->is_receiver());
4454 orig_rec_no->var_value()->set_is_receiver();
4455
4456 std::string new_receiver_name(orig_fntype->receiver()->name());
4457 if (new_receiver_name.empty())
4458 {
4459 // Find the receiver. It was named "r.NNN" in
4460 // Gogo::start_function.
4461 for (Bindings::const_definitions_iterator p =
4462 new_bindings->begin_definitions();
4463 p != new_bindings->end_definitions();
4464 ++p)
4465 {
4466 const std::string& pname((*p)->name());
4467 if (pname[0] == 'r' && pname[1] == '.')
4468 {
4469 new_receiver_name = pname;
4470 break;
4471 }
4472 }
4473 go_assert(!new_receiver_name.empty());
4474 }
4475 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4476 if (new_rec_no == NULL)
4477 go_assert(saw_errors());
4478 else
4479 {
4480 go_assert(new_rec_no->is_variable()
4481 && new_rec_no->var_value()->is_receiver());
4482 new_rec_no->var_value()->set_is_not_receiver();
4483 }
4484 }
4485
4486 // Because we flipped blocks but not types, the can_recover
4487 // parameter appears in the (now) old bindings as a parameter.
4488 // Change it to a local variable, whereupon it will be discarded.
4489 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4490 go_assert(can_recover_no != NULL
4491 && can_recover_no->is_variable()
4492 && can_recover_no->var_value()->is_parameter());
4493 orig_bindings->remove_binding(can_recover_no);
4494
4495 // Add the can_recover argument to the (now) new bindings, and
4496 // attach it to any recover statements.
4497 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4498 false, true, false, location);
4499 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4500 can_recover_var);
4501 Convert_recover convert_recover(can_recover_no);
4502 new_func->traverse(&convert_recover);
4503
4504 // Update the function pointers in any named results.
4505 new_func->update_result_variables();
4506 orig_func->update_result_variables();
4507
4508 return TRAVERSE_CONTINUE;
4509 }
4510
4511 // Return the expression to pass for the .can_recover parameter to the
4512 // new function. This indicates whether a call to recover may return
4513 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4514
4515 Expression*
4516 Build_recover_thunks::can_recover_arg(Location location)
4517 {
4518 static Named_object* builtin_return_address;
4519 if (builtin_return_address == NULL)
4520 builtin_return_address =
4521 Gogo::declare_builtin_rf_address("__builtin_return_address", true);
4522
4523 Type* uintptr_type = Type::lookup_integer_type("uintptr");
4524 static Named_object* can_recover;
4525 if (can_recover == NULL)
4526 {
4527 const Location bloc = Linemap::predeclared_location();
4528 Typed_identifier_list* param_types = new Typed_identifier_list();
4529 param_types->push_back(Typed_identifier("a", uintptr_type, bloc));
4530 Type* boolean_type = Type::lookup_bool_type();
4531 Typed_identifier_list* results = new Typed_identifier_list();
4532 results->push_back(Typed_identifier("", boolean_type, bloc));
4533 Function_type* fntype = Type::make_function_type(NULL, param_types,
4534 results, bloc);
4535 can_recover =
4536 Named_object::make_function_declaration("runtime_canrecover",
4537 NULL, fntype, bloc);
4538 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4539 }
4540
4541 Expression* fn = Expression::make_func_reference(builtin_return_address,
4542 NULL, location);
4543
4544 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4545 Expression_list *args = new Expression_list();
4546 args->push_back(zexpr);
4547
4548 Expression* call = Expression::make_call(fn, args, false, location);
4549 call = Expression::make_unsafe_cast(uintptr_type, call, location);
4550
4551 args = new Expression_list();
4552 args->push_back(call);
4553
4554 fn = Expression::make_func_reference(can_recover, NULL, location);
4555 return Expression::make_call(fn, args, false, location);
4556 }
4557
4558 // Build thunks for functions which call recover. We build a new
4559 // function with an extra parameter, which is whether a call to
4560 // recover can succeed. We then move the body of this function to
4561 // that one. We then turn this function into a thunk which calls the
4562 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4563 // The function will be marked as not splitting the stack. This will
4564 // cooperate with the implementation of defer to make recover do the
4565 // right thing.
4566
4567 void
4568 Gogo::build_recover_thunks()
4569 {
4570 Build_recover_thunks build_recover_thunks(this);
4571 this->traverse(&build_recover_thunks);
4572 }
4573
4574 // Return a declaration for __builtin_return_address or
4575 // __builtin_dwarf_cfa.
4576
4577 Named_object*
4578 Gogo::declare_builtin_rf_address(const char* name, bool hasarg)
4579 {
4580 const Location bloc = Linemap::predeclared_location();
4581
4582 Typed_identifier_list* param_types = new Typed_identifier_list();
4583 if (hasarg)
4584 {
4585 Type* uint32_type = Type::lookup_integer_type("uint32");
4586 param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4587 }
4588
4589 Typed_identifier_list* return_types = new Typed_identifier_list();
4590 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4591 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4592
4593 Function_type* fntype = Type::make_function_type(NULL, param_types,
4594 return_types, bloc);
4595 Named_object* ret = Named_object::make_function_declaration(name, NULL,
4596 fntype, bloc);
4597 ret->func_declaration_value()->set_asm_name(name);
4598 return ret;
4599 }
4600
4601 // Build a call to the runtime error function.
4602
4603 Expression*
4604 Gogo::runtime_error(int code, Location location)
4605 {
4606 Type* int32_type = Type::lookup_integer_type("int32");
4607 Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4608 location);
4609 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4610 }
4611
4612 // Look for named types to see whether we need to create an interface
4613 // method table.
4614
4615 class Build_method_tables : public Traverse
4616 {
4617 public:
4618 Build_method_tables(Gogo* gogo,
4619 const std::vector<Interface_type*>& interfaces)
4620 : Traverse(traverse_types),
4621 gogo_(gogo), interfaces_(interfaces)
4622 { }
4623
4624 int
4625 type(Type*);
4626
4627 private:
4628 // The IR.
4629 Gogo* gogo_;
4630 // A list of locally defined interfaces which have hidden methods.
4631 const std::vector<Interface_type*>& interfaces_;
4632 };
4633
4634 // Build all required interface method tables for types. We need to
4635 // ensure that we have an interface method table for every interface
4636 // which has a hidden method, for every named type which implements
4637 // that interface. Normally we can just build interface method tables
4638 // as we need them. However, in some cases we can require an
4639 // interface method table for an interface defined in a different
4640 // package for a type defined in that package. If that interface and
4641 // type both use a hidden method, that is OK. However, we will not be
4642 // able to build that interface method table when we need it, because
4643 // the type's hidden method will be static. So we have to build it
4644 // here, and just refer it from other packages as needed.
4645
4646 void
4647 Gogo::build_interface_method_tables()
4648 {
4649 if (saw_errors())
4650 return;
4651
4652 std::vector<Interface_type*> hidden_interfaces;
4653 hidden_interfaces.reserve(this->interface_types_.size());
4654 for (std::vector<Interface_type*>::const_iterator pi =
4655 this->interface_types_.begin();
4656 pi != this->interface_types_.end();
4657 ++pi)
4658 {
4659 const Typed_identifier_list* methods = (*pi)->methods();
4660 if (methods == NULL)
4661 continue;
4662 for (Typed_identifier_list::const_iterator pm = methods->begin();
4663 pm != methods->end();
4664 ++pm)
4665 {
4666 if (Gogo::is_hidden_name(pm->name()))
4667 {
4668 hidden_interfaces.push_back(*pi);
4669 break;
4670 }
4671 }
4672 }
4673
4674 if (!hidden_interfaces.empty())
4675 {
4676 // Now traverse the tree looking for all named types.
4677 Build_method_tables bmt(this, hidden_interfaces);
4678 this->traverse(&bmt);
4679 }
4680
4681 // We no longer need the list of interfaces.
4682
4683 this->interface_types_.clear();
4684 }
4685
4686 // This is called for each type. For a named type, for each of the
4687 // interfaces with hidden methods that it implements, create the
4688 // method table.
4689
4690 int
4691 Build_method_tables::type(Type* type)
4692 {
4693 Named_type* nt = type->named_type();
4694 Struct_type* st = type->struct_type();
4695 if (nt != NULL || st != NULL)
4696 {
4697 Translate_context context(this->gogo_, NULL, NULL, NULL);
4698 for (std::vector<Interface_type*>::const_iterator p =
4699 this->interfaces_.begin();
4700 p != this->interfaces_.end();
4701 ++p)
4702 {
4703 // We ask whether a pointer to the named type implements the
4704 // interface, because a pointer can implement more methods
4705 // than a value.
4706 if (nt != NULL)
4707 {
4708 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4709 NULL))
4710 {
4711 nt->interface_method_table(*p, false)->get_backend(&context);
4712 nt->interface_method_table(*p, true)->get_backend(&context);
4713 }
4714 }
4715 else
4716 {
4717 if ((*p)->implements_interface(Type::make_pointer_type(st),
4718 NULL))
4719 {
4720 st->interface_method_table(*p, false)->get_backend(&context);
4721 st->interface_method_table(*p, true)->get_backend(&context);
4722 }
4723 }
4724 }
4725 }
4726 return TRAVERSE_CONTINUE;
4727 }
4728
4729 // Return an expression which allocates memory to hold values of type TYPE.
4730
4731 Expression*
4732 Gogo::allocate_memory(Type* type, Location location)
4733 {
4734 Expression* td = Expression::make_type_descriptor(type, location);
4735 return Runtime::make_call(Runtime::NEW, location, 1, td);
4736 }
4737
4738 // Traversal class used to check for return statements.
4739
4740 class Check_return_statements_traverse : public Traverse
4741 {
4742 public:
4743 Check_return_statements_traverse()
4744 : Traverse(traverse_functions)
4745 { }
4746
4747 int
4748 function(Named_object*);
4749 };
4750
4751 // Check that a function has a return statement if it needs one.
4752
4753 int
4754 Check_return_statements_traverse::function(Named_object* no)
4755 {
4756 Function* func = no->func_value();
4757 const Function_type* fntype = func->type();
4758 const Typed_identifier_list* results = fntype->results();
4759
4760 // We only need a return statement if there is a return value.
4761 if (results == NULL || results->empty())
4762 return TRAVERSE_CONTINUE;
4763
4764 if (func->block()->may_fall_through())
4765 go_error_at(func->block()->end_location(),
4766 "missing return at end of function");
4767
4768 return TRAVERSE_CONTINUE;
4769 }
4770
4771 // Check return statements.
4772
4773 void
4774 Gogo::check_return_statements()
4775 {
4776 Check_return_statements_traverse traverse;
4777 this->traverse(&traverse);
4778 }
4779
4780 // Traversal class to decide whether a function body is less than the
4781 // inlining budget. This adjusts *available as it goes, and stops the
4782 // traversal if it goes negative.
4783
4784 class Inline_within_budget : public Traverse
4785 {
4786 public:
4787 Inline_within_budget(int* available)
4788 : Traverse(traverse_statements
4789 | traverse_expressions),
4790 available_(available)
4791 { }
4792
4793 int
4794 statement(Block*, size_t*, Statement*);
4795
4796 int
4797 expression(Expression**);
4798
4799 private:
4800 // Pointer to remaining budget.
4801 int* available_;
4802 };
4803
4804 // Adjust the budget for the inlining cost of a statement.
4805
4806 int
4807 Inline_within_budget::statement(Block*, size_t*, Statement* s)
4808 {
4809 if (*this->available_ < 0)
4810 return TRAVERSE_EXIT;
4811 *this->available_ -= s->inlining_cost();
4812 return TRAVERSE_CONTINUE;
4813 }
4814
4815 // Adjust the budget for the inlining cost of an expression.
4816
4817 int
4818 Inline_within_budget::expression(Expression** pexpr)
4819 {
4820 if (*this->available_ < 0)
4821 return TRAVERSE_EXIT;
4822 *this->available_ -= (*pexpr)->inlining_cost();
4823 return TRAVERSE_CONTINUE;
4824 }
4825
4826 // Traversal class to find functions whose body should be exported for
4827 // inlining by other packages.
4828
4829 class Mark_inline_candidates : public Traverse
4830 {
4831 public:
4832 Mark_inline_candidates()
4833 : Traverse(traverse_functions
4834 | traverse_types)
4835 { }
4836
4837 int
4838 function(Named_object*);
4839
4840 int
4841 type(Type*);
4842
4843 private:
4844 // We traverse the function body trying to determine how expensive
4845 // it is for inlining. We start with a budget, and decrease that
4846 // budget for each statement and expression. If the budget goes
4847 // negative, we do not export the function body. The value of this
4848 // budget is a heuristic. In the usual GCC spirit, we could
4849 // consider setting this via a command line option.
4850 const int budget_heuristic = 80;
4851 };
4852
4853 // Mark a function if it is an inline candidate.
4854
4855 int
4856 Mark_inline_candidates::function(Named_object* no)
4857 {
4858 Function* func = no->func_value();
4859 int budget = budget_heuristic;
4860 Inline_within_budget iwb(&budget);
4861 func->block()->traverse(&iwb);
4862 if (budget >= 0)
4863 func->set_export_for_inlining();
4864 return TRAVERSE_CONTINUE;
4865 }
4866
4867 // Mark methods if they are inline candidates.
4868
4869 int
4870 Mark_inline_candidates::type(Type* t)
4871 {
4872 Named_type* nt = t->named_type();
4873 if (nt == NULL || nt->is_alias())
4874 return TRAVERSE_CONTINUE;
4875 const Bindings* methods = nt->local_methods();
4876 if (methods == NULL)
4877 return TRAVERSE_CONTINUE;
4878 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
4879 p != methods->end_definitions();
4880 ++p)
4881 {
4882 Named_object* no = *p;
4883 go_assert(no->is_function());
4884 Function *func = no->func_value();
4885 int budget = budget_heuristic;
4886 Inline_within_budget iwb(&budget);
4887 func->block()->traverse(&iwb);
4888 if (budget >= 0)
4889 func->set_export_for_inlining();
4890 }
4891 return TRAVERSE_CONTINUE;
4892 }
4893
4894 // Export identifiers as requested.
4895
4896 void
4897 Gogo::do_exports()
4898 {
4899 // Mark any functions whose body should be exported for inlining by
4900 // other packages.
4901 Mark_inline_candidates mic;
4902 this->traverse(&mic);
4903
4904 // For now we always stream to a section. Later we may want to
4905 // support streaming to a separate file.
4906 Stream_to_section stream(this->backend());
4907
4908 // Write out either the prefix or pkgpath depending on how we were
4909 // invoked.
4910 std::string prefix;
4911 std::string pkgpath;
4912 if (this->pkgpath_from_option_)
4913 pkgpath = this->pkgpath_;
4914 else if (this->prefix_from_option_)
4915 prefix = this->prefix_;
4916 else if (this->is_main_package())
4917 pkgpath = "main";
4918 else
4919 prefix = "go";
4920
4921 Export exp(&stream);
4922 exp.register_builtin_types(this);
4923 exp.export_globals(this->package_name(),
4924 prefix,
4925 pkgpath,
4926 this->packages_,
4927 this->imports_,
4928 (this->need_init_fn_ && !this->is_main_package()
4929 ? this->get_init_fn_name()
4930 : ""),
4931 this->imported_init_fns_,
4932 this->package_->bindings());
4933
4934 if (!this->c_header_.empty() && !saw_errors())
4935 this->write_c_header();
4936 }
4937
4938 // Write the top level named struct types in C format to a C header
4939 // file. This is used when building the runtime package, to share
4940 // struct definitions between C and Go.
4941
4942 void
4943 Gogo::write_c_header()
4944 {
4945 std::ofstream out;
4946 out.open(this->c_header_.c_str());
4947 if (out.fail())
4948 {
4949 go_error_at(Linemap::unknown_location(),
4950 "cannot open %s: %m", this->c_header_.c_str());
4951 return;
4952 }
4953
4954 std::list<Named_object*> types;
4955 Bindings* top = this->package_->bindings();
4956 for (Bindings::const_definitions_iterator p = top->begin_definitions();
4957 p != top->end_definitions();
4958 ++p)
4959 {
4960 Named_object* no = *p;
4961
4962 // Skip names that start with underscore followed by something
4963 // other than an uppercase letter, as when compiling the runtime
4964 // package they are mostly types defined by mkrsysinfo.sh based
4965 // on the C system header files. We don't need to translate
4966 // types to C and back to Go. But do accept the special cases
4967 // _defer and _panic.
4968 std::string name = Gogo::unpack_hidden_name(no->name());
4969 if (name[0] == '_'
4970 && (name[1] < 'A' || name[1] > 'Z')
4971 && (name != "_defer" && name != "_panic"))
4972 continue;
4973
4974 if (no->is_type() && no->type_value()->struct_type() != NULL)
4975 types.push_back(no);
4976 if (no->is_const()
4977 && no->const_value()->type()->integer_type() != NULL
4978 && !no->const_value()->is_sink())
4979 {
4980 Numeric_constant nc;
4981 unsigned long val;
4982 if (no->const_value()->expr()->numeric_constant_value(&nc)
4983 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4984 {
4985 out << "#define " << no->message_name() << ' ' << val
4986 << std::endl;
4987 }
4988 }
4989 }
4990
4991 std::vector<const Named_object*> written;
4992 int loop = 0;
4993 while (!types.empty())
4994 {
4995 Named_object* no = types.front();
4996 types.pop_front();
4997
4998 std::vector<const Named_object*> requires;
4999 std::vector<const Named_object*> declare;
5000 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
5001 &declare))
5002 continue;
5003
5004 bool ok = true;
5005 for (std::vector<const Named_object*>::const_iterator pr
5006 = requires.begin();
5007 pr != requires.end() && ok;
5008 ++pr)
5009 {
5010 for (std::list<Named_object*>::const_iterator pt = types.begin();
5011 pt != types.end() && ok;
5012 ++pt)
5013 if (*pr == *pt)
5014 ok = false;
5015 }
5016 if (!ok)
5017 {
5018 ++loop;
5019 if (loop > 10000)
5020 {
5021 // This should be impossible since the code parsed and
5022 // type checked.
5023 go_unreachable();
5024 }
5025
5026 types.push_back(no);
5027 continue;
5028 }
5029
5030 for (std::vector<const Named_object*>::const_iterator pd
5031 = declare.begin();
5032 pd != declare.end();
5033 ++pd)
5034 {
5035 if (*pd == no)
5036 continue;
5037
5038 std::vector<const Named_object*> drequires;
5039 std::vector<const Named_object*> ddeclare;
5040 if (!(*pd)->type_value()->struct_type()->
5041 can_write_to_c_header(&drequires, &ddeclare))
5042 continue;
5043
5044 bool done = false;
5045 for (std::vector<const Named_object*>::const_iterator pw
5046 = written.begin();
5047 pw != written.end();
5048 ++pw)
5049 {
5050 if (*pw == *pd)
5051 {
5052 done = true;
5053 break;
5054 }
5055 }
5056 if (!done)
5057 {
5058 out << std::endl;
5059 out << "struct " << (*pd)->message_name() << ";" << std::endl;
5060 written.push_back(*pd);
5061 }
5062 }
5063
5064 out << std::endl;
5065 out << "struct " << no->message_name() << " {" << std::endl;
5066 no->type_value()->struct_type()->write_to_c_header(out);
5067 out << "};" << std::endl;
5068 written.push_back(no);
5069 }
5070
5071 out.close();
5072 if (out.fail())
5073 go_error_at(Linemap::unknown_location(),
5074 "error writing to %s: %m", this->c_header_.c_str());
5075 }
5076
5077 // Find the blocks in order to convert named types defined in blocks.
5078
5079 class Convert_named_types : public Traverse
5080 {
5081 public:
5082 Convert_named_types(Gogo* gogo)
5083 : Traverse(traverse_blocks),
5084 gogo_(gogo)
5085 { }
5086
5087 protected:
5088 int
5089 block(Block* block);
5090
5091 private:
5092 Gogo* gogo_;
5093 };
5094
5095 int
5096 Convert_named_types::block(Block* block)
5097 {
5098 this->gogo_->convert_named_types_in_bindings(block->bindings());
5099 return TRAVERSE_CONTINUE;
5100 }
5101
5102 // Convert all named types to the backend representation. Since named
5103 // types can refer to other types, this needs to be done in the right
5104 // sequence, which is handled by Named_type::convert. Here we arrange
5105 // to call that for each named type.
5106
5107 void
5108 Gogo::convert_named_types()
5109 {
5110 this->convert_named_types_in_bindings(this->globals_);
5111 for (Packages::iterator p = this->packages_.begin();
5112 p != this->packages_.end();
5113 ++p)
5114 {
5115 Package* package = p->second;
5116 this->convert_named_types_in_bindings(package->bindings());
5117 }
5118
5119 Convert_named_types cnt(this);
5120 this->traverse(&cnt);
5121
5122 // Make all the builtin named types used for type descriptors, and
5123 // then convert them. They will only be written out if they are
5124 // needed.
5125 Type::make_type_descriptor_type();
5126 Type::make_type_descriptor_ptr_type();
5127 Function_type::make_function_type_descriptor_type();
5128 Pointer_type::make_pointer_type_descriptor_type();
5129 Struct_type::make_struct_type_descriptor_type();
5130 Array_type::make_array_type_descriptor_type();
5131 Array_type::make_slice_type_descriptor_type();
5132 Map_type::make_map_type_descriptor_type();
5133 Channel_type::make_chan_type_descriptor_type();
5134 Interface_type::make_interface_type_descriptor_type();
5135 Expression::make_func_descriptor_type();
5136 Type::convert_builtin_named_types(this);
5137
5138 Runtime::convert_types(this);
5139
5140 this->named_types_are_converted_ = true;
5141
5142 Type::finish_pointer_types(this);
5143 }
5144
5145 // Convert all names types in a set of bindings.
5146
5147 void
5148 Gogo::convert_named_types_in_bindings(Bindings* bindings)
5149 {
5150 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5151 p != bindings->end_definitions();
5152 ++p)
5153 {
5154 if ((*p)->is_type())
5155 (*p)->type_value()->convert(this);
5156 }
5157 }
5158
5159 // Class Function.
5160
5161 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
5162 Location location)
5163 : type_(type), enclosing_(enclosing), results_(NULL),
5164 closure_var_(NULL), block_(block), location_(location), labels_(),
5165 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
5166 pragmas_(0), nested_functions_(0), is_sink_(false),
5167 results_are_named_(false), is_unnamed_type_stub_method_(false),
5168 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5169 calls_defer_retaddr_(false), is_type_specific_function_(false),
5170 in_unique_section_(false), export_for_inlining_(false),
5171 is_inline_only_(false)
5172 {
5173 }
5174
5175 // Create the named result variables.
5176
5177 void
5178 Function::create_result_variables(Gogo* gogo)
5179 {
5180 const Typed_identifier_list* results = this->type_->results();
5181 if (results == NULL || results->empty())
5182 return;
5183
5184 if (!results->front().name().empty())
5185 this->results_are_named_ = true;
5186
5187 this->results_ = new Results();
5188 this->results_->reserve(results->size());
5189
5190 Block* block = this->block_;
5191 int index = 0;
5192 for (Typed_identifier_list::const_iterator p = results->begin();
5193 p != results->end();
5194 ++p, ++index)
5195 {
5196 std::string name = p->name();
5197 if (name.empty() || Gogo::is_sink_name(name))
5198 {
5199 static int result_counter;
5200 char buf[100];
5201 snprintf(buf, sizeof buf, "$ret%d", result_counter);
5202 ++result_counter;
5203 name = gogo->pack_hidden_name(buf, false);
5204 }
5205 Result_variable* result = new Result_variable(p->type(), this, index,
5206 p->location());
5207 Named_object* no = block->bindings()->add_result_variable(name, result);
5208 if (no->is_result_variable())
5209 this->results_->push_back(no);
5210 else
5211 {
5212 static int dummy_result_count;
5213 char buf[100];
5214 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
5215 ++dummy_result_count;
5216 name = gogo->pack_hidden_name(buf, false);
5217 no = block->bindings()->add_result_variable(name, result);
5218 go_assert(no->is_result_variable());
5219 this->results_->push_back(no);
5220 }
5221 }
5222 }
5223
5224 // Update the named result variables when cloning a function which
5225 // calls recover.
5226
5227 void
5228 Function::update_result_variables()
5229 {
5230 if (this->results_ == NULL)
5231 return;
5232
5233 for (Results::iterator p = this->results_->begin();
5234 p != this->results_->end();
5235 ++p)
5236 (*p)->result_var_value()->set_function(this);
5237 }
5238
5239 // Whether this method should not be included in the type descriptor.
5240
5241 bool
5242 Function::nointerface() const
5243 {
5244 go_assert(this->is_method());
5245 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
5246 }
5247
5248 // Record that this method should not be included in the type
5249 // descriptor.
5250
5251 void
5252 Function::set_nointerface()
5253 {
5254 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
5255 }
5256
5257 // Return the closure variable, creating it if necessary.
5258
5259 Named_object*
5260 Function::closure_var()
5261 {
5262 if (this->closure_var_ == NULL)
5263 {
5264 go_assert(this->descriptor_ == NULL);
5265 // We don't know the type of the variable yet. We add fields as
5266 // we find them.
5267 Location loc = this->type_->location();
5268 Struct_field_list* sfl = new Struct_field_list;
5269 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
5270 struct_type->set_is_struct_incomparable();
5271 Variable* var = new Variable(Type::make_pointer_type(struct_type),
5272 NULL, false, false, false, loc);
5273 var->set_is_used();
5274 var->set_is_closure();
5275 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
5276 // Note that the new variable is not in any binding contour.
5277 }
5278 return this->closure_var_;
5279 }
5280
5281 // Set the type of the closure variable.
5282
5283 void
5284 Function::set_closure_type()
5285 {
5286 if (this->closure_var_ == NULL)
5287 return;
5288 Named_object* closure = this->closure_var_;
5289 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
5290
5291 // The first field of a closure is always a pointer to the function
5292 // code.
5293 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
5294 st->push_field(Struct_field(Typed_identifier(".f", voidptr_type,
5295 this->location_)));
5296
5297 unsigned int index = 1;
5298 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
5299 p != this->closure_fields_.end();
5300 ++p, ++index)
5301 {
5302 Named_object* no = p->first;
5303 char buf[20];
5304 snprintf(buf, sizeof buf, "%u", index);
5305 std::string n = no->name() + buf;
5306 Type* var_type;
5307 if (no->is_variable())
5308 var_type = no->var_value()->type();
5309 else
5310 var_type = no->result_var_value()->type();
5311 Type* field_type = Type::make_pointer_type(var_type);
5312 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
5313 }
5314 }
5315
5316 // Return whether this function is a method.
5317
5318 bool
5319 Function::is_method() const
5320 {
5321 return this->type_->is_method();
5322 }
5323
5324 // Add a label definition.
5325
5326 Label*
5327 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5328 Location location)
5329 {
5330 Label* lnull = NULL;
5331 std::pair<Labels::iterator, bool> ins =
5332 this->labels_.insert(std::make_pair(label_name, lnull));
5333 Label* label;
5334 if (label_name == "_")
5335 {
5336 label = Label::create_dummy_label();
5337 if (ins.second)
5338 ins.first->second = label;
5339 }
5340 else if (ins.second)
5341 {
5342 // This is a new label.
5343 label = new Label(label_name);
5344 ins.first->second = label;
5345 }
5346 else
5347 {
5348 // The label was already in the hash table.
5349 label = ins.first->second;
5350 if (label->is_defined())
5351 {
5352 go_error_at(location, "label %qs already defined",
5353 Gogo::message_name(label_name).c_str());
5354 go_inform(label->location(), "previous definition of %qs was here",
5355 Gogo::message_name(label_name).c_str());
5356 return new Label(label_name);
5357 }
5358 }
5359
5360 label->define(location, gogo->bindings_snapshot(location));
5361
5362 // Issue any errors appropriate for any previous goto's to this
5363 // label.
5364 const std::vector<Bindings_snapshot*>& refs(label->refs());
5365 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5366 p != refs.end();
5367 ++p)
5368 (*p)->check_goto_to(gogo->current_block());
5369 label->clear_refs();
5370
5371 return label;
5372 }
5373
5374 // Add a reference to a label.
5375
5376 Label*
5377 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5378 Location location, bool issue_goto_errors)
5379 {
5380 Label* lnull = NULL;
5381 std::pair<Labels::iterator, bool> ins =
5382 this->labels_.insert(std::make_pair(label_name, lnull));
5383 Label* label;
5384 if (!ins.second)
5385 {
5386 // The label was already in the hash table.
5387 label = ins.first->second;
5388 }
5389 else
5390 {
5391 go_assert(ins.first->second == NULL);
5392 label = new Label(label_name);
5393 ins.first->second = label;
5394 }
5395
5396 label->set_is_used();
5397
5398 if (issue_goto_errors)
5399 {
5400 Bindings_snapshot* snapshot = label->snapshot();
5401 if (snapshot != NULL)
5402 snapshot->check_goto_from(gogo->current_block(), location);
5403 else
5404 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5405 }
5406
5407 return label;
5408 }
5409
5410 // Warn about labels that are defined but not used.
5411
5412 void
5413 Function::check_labels() const
5414 {
5415 for (Labels::const_iterator p = this->labels_.begin();
5416 p != this->labels_.end();
5417 p++)
5418 {
5419 Label* label = p->second;
5420 if (!label->is_used())
5421 go_error_at(label->location(), "label %qs defined and not used",
5422 Gogo::message_name(label->name()).c_str());
5423 }
5424 }
5425
5426 // Swap one function with another. This is used when building the
5427 // thunk we use to call a function which calls recover. It may not
5428 // work for any other case.
5429
5430 void
5431 Function::swap_for_recover(Function *x)
5432 {
5433 go_assert(this->enclosing_ == x->enclosing_);
5434 std::swap(this->results_, x->results_);
5435 std::swap(this->closure_var_, x->closure_var_);
5436 std::swap(this->block_, x->block_);
5437 go_assert(this->location_ == x->location_);
5438 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5439 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5440 }
5441
5442 // Traverse the tree.
5443
5444 int
5445 Function::traverse(Traverse* traverse)
5446 {
5447 unsigned int traverse_mask = traverse->traverse_mask();
5448
5449 if ((traverse_mask
5450 & (Traverse::traverse_types | Traverse::traverse_expressions))
5451 != 0)
5452 {
5453 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5454 return TRAVERSE_EXIT;
5455 }
5456
5457 // FIXME: We should check traverse_functions here if nested
5458 // functions are stored in block bindings.
5459 if (this->block_ != NULL
5460 && (traverse_mask
5461 & (Traverse::traverse_variables
5462 | Traverse::traverse_constants
5463 | Traverse::traverse_blocks
5464 | Traverse::traverse_statements
5465 | Traverse::traverse_expressions
5466 | Traverse::traverse_types)) != 0)
5467 {
5468 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5469 return TRAVERSE_EXIT;
5470 }
5471
5472 return TRAVERSE_CONTINUE;
5473 }
5474
5475 // Work out types for unspecified variables and constants.
5476
5477 void
5478 Function::determine_types()
5479 {
5480 if (this->block_ != NULL)
5481 this->block_->determine_types();
5482 }
5483
5484 // Return the function descriptor, the value you get when you refer to
5485 // the function in Go code without calling it.
5486
5487 Expression*
5488 Function::descriptor(Gogo*, Named_object* no)
5489 {
5490 go_assert(!this->is_method());
5491 go_assert(this->closure_var_ == NULL);
5492 if (this->descriptor_ == NULL)
5493 this->descriptor_ = Expression::make_func_descriptor(no);
5494 return this->descriptor_;
5495 }
5496
5497 // Get a pointer to the variable representing the defer stack for this
5498 // function, making it if necessary. The value of the variable is set
5499 // by the runtime routines to true if the function is returning,
5500 // rather than panicing through. A pointer to this variable is used
5501 // as a marker for the functions on the defer stack associated with
5502 // this function. A function-specific variable permits inlining a
5503 // function which uses defer.
5504
5505 Expression*
5506 Function::defer_stack(Location location)
5507 {
5508 if (this->defer_stack_ == NULL)
5509 {
5510 Type* t = Type::lookup_bool_type();
5511 Expression* n = Expression::make_boolean(false, location);
5512 this->defer_stack_ = Statement::make_temporary(t, n, location);
5513 this->defer_stack_->set_is_address_taken();
5514 }
5515 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5516 location);
5517 return Expression::make_unary(OPERATOR_AND, ref, location);
5518 }
5519
5520 // Export the function.
5521
5522 void
5523 Function::export_func(Export* exp, const std::string& name) const
5524 {
5525 Block* block = NULL;
5526 if (this->export_for_inlining())
5527 block = this->block_;
5528 Function::export_func_with_type(exp, name, this->type_, this->results_,
5529 this->is_method() && this->nointerface(),
5530 block, this->location_);
5531 }
5532
5533 // Export a function with a type.
5534
5535 void
5536 Function::export_func_with_type(Export* exp, const std::string& name,
5537 const Function_type* fntype,
5538 Function::Results* result_vars,
5539 bool nointerface, Block* block, Location loc)
5540 {
5541 exp->write_c_string("func ");
5542
5543 if (nointerface)
5544 {
5545 go_assert(fntype->is_method());
5546 exp->write_c_string("/*nointerface*/ ");
5547 }
5548
5549 if (fntype->is_method())
5550 {
5551 exp->write_c_string("(");
5552 const Typed_identifier* receiver = fntype->receiver();
5553 exp->write_name(receiver->name());
5554 exp->write_escape(receiver->note());
5555 exp->write_c_string(" ");
5556 exp->write_type(receiver->type());
5557 exp->write_c_string(") ");
5558 }
5559
5560 exp->write_string(name);
5561
5562 exp->write_c_string(" (");
5563 const Typed_identifier_list* parameters = fntype->parameters();
5564 if (parameters != NULL)
5565 {
5566 size_t i = 0;
5567 bool is_varargs = fntype->is_varargs();
5568 bool first = true;
5569 for (Typed_identifier_list::const_iterator p = parameters->begin();
5570 p != parameters->end();
5571 ++p, ++i)
5572 {
5573 if (first)
5574 first = false;
5575 else
5576 exp->write_c_string(", ");
5577 exp->write_name(p->name());
5578 exp->write_escape(p->note());
5579 exp->write_c_string(" ");
5580 if (!is_varargs || p + 1 != parameters->end())
5581 exp->write_type(p->type());
5582 else
5583 {
5584 exp->write_c_string("...");
5585 exp->write_type(p->type()->array_type()->element_type());
5586 }
5587 }
5588 }
5589 exp->write_c_string(")");
5590
5591 const Typed_identifier_list* result_decls = fntype->results();
5592 if (result_decls != NULL)
5593 {
5594 if (result_decls->size() == 1
5595 && result_decls->begin()->name().empty()
5596 && block == NULL)
5597 {
5598 exp->write_c_string(" ");
5599 exp->write_type(result_decls->begin()->type());
5600 }
5601 else
5602 {
5603 exp->write_c_string(" (");
5604 bool first = true;
5605 Results::const_iterator pr;
5606 if (result_vars != NULL)
5607 pr = result_vars->begin();
5608 for (Typed_identifier_list::const_iterator pd = result_decls->begin();
5609 pd != result_decls->end();
5610 ++pd)
5611 {
5612 if (first)
5613 first = false;
5614 else
5615 exp->write_c_string(", ");
5616 // We only use pr->name, which may be artificial, if
5617 // need it for inlining.
5618 if (block == NULL || result_vars == NULL)
5619 exp->write_name(pd->name());
5620 else
5621 exp->write_name((*pr)->name());
5622 exp->write_escape(pd->note());
5623 exp->write_c_string(" ");
5624 exp->write_type(pd->type());
5625 if (result_vars != NULL)
5626 ++pr;
5627 }
5628 if (result_vars != NULL)
5629 go_assert(pr == result_vars->end());
5630 exp->write_c_string(")");
5631 }
5632 }
5633
5634 if (block == NULL)
5635 exp->write_c_string("\n");
5636 else
5637 {
5638 int indent = 1;
5639 if (fntype->is_method())
5640 indent++;
5641
5642 Export_function_body efb(exp, indent);
5643
5644 efb.indent();
5645 efb.write_c_string("// ");
5646 efb.write_string(Linemap::location_to_file(block->start_location()));
5647 efb.write_char(':');
5648 char buf[100];
5649 snprintf(buf, sizeof buf, "%d", Linemap::location_to_line(loc));
5650 efb.write_c_string(buf);
5651 efb.write_char('\n');
5652 block->export_block(&efb);
5653
5654 const std::string& body(efb.body());
5655
5656 snprintf(buf, sizeof buf, " <inl:%lu>\n",
5657 static_cast<unsigned long>(body.length()));
5658 exp->write_c_string(buf);
5659
5660 exp->write_string(body);
5661 }
5662 }
5663
5664 // Import a function.
5665
5666 void
5667 Function::import_func(Import* imp, std::string* pname,
5668 Typed_identifier** preceiver,
5669 Typed_identifier_list** pparameters,
5670 Typed_identifier_list** presults,
5671 bool* is_varargs,
5672 bool* nointerface,
5673 std::string* body)
5674 {
5675 imp->require_c_string("func ");
5676
5677 *nointerface = false;
5678 if (imp->match_c_string("/*"))
5679 {
5680 imp->require_c_string("/*nointerface*/ ");
5681 *nointerface = true;
5682
5683 // Only a method can be nointerface.
5684 go_assert(imp->peek_char() == '(');
5685 }
5686
5687 *preceiver = NULL;
5688 if (imp->peek_char() == '(')
5689 {
5690 imp->require_c_string("(");
5691 std::string name = imp->read_name();
5692 std::string escape_note = imp->read_escape();
5693 imp->require_c_string(" ");
5694 Type* rtype = imp->read_type();
5695 *preceiver = new Typed_identifier(name, rtype, imp->location());
5696 (*preceiver)->set_note(escape_note);
5697 imp->require_c_string(") ");
5698 }
5699
5700 *pname = imp->read_identifier();
5701
5702 Typed_identifier_list* parameters;
5703 *is_varargs = false;
5704 imp->require_c_string(" (");
5705 if (imp->peek_char() == ')')
5706 parameters = NULL;
5707 else
5708 {
5709 parameters = new Typed_identifier_list();
5710 while (true)
5711 {
5712 std::string name = imp->read_name();
5713 std::string escape_note = imp->read_escape();
5714 imp->require_c_string(" ");
5715
5716 if (imp->match_c_string("..."))
5717 {
5718 imp->advance(3);
5719 *is_varargs = true;
5720 }
5721
5722 Type* ptype = imp->read_type();
5723 if (*is_varargs)
5724 ptype = Type::make_array_type(ptype, NULL);
5725 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5726 t.set_note(escape_note);
5727 parameters->push_back(t);
5728 if (imp->peek_char() != ',')
5729 break;
5730 go_assert(!*is_varargs);
5731 imp->require_c_string(", ");
5732 }
5733 }
5734 imp->require_c_string(")");
5735 *pparameters = parameters;
5736
5737 Typed_identifier_list* results;
5738 if (imp->peek_char() != ' ' || imp->match_c_string(" <inl"))
5739 results = NULL;
5740 else
5741 {
5742 results = new Typed_identifier_list();
5743 imp->require_c_string(" ");
5744 if (imp->peek_char() != '(')
5745 {
5746 Type* rtype = imp->read_type();
5747 results->push_back(Typed_identifier("", rtype, imp->location()));
5748 }
5749 else
5750 {
5751 imp->require_c_string("(");
5752 while (true)
5753 {
5754 std::string name = imp->read_name();
5755 std::string note = imp->read_escape();
5756 imp->require_c_string(" ");
5757 Type* rtype = imp->read_type();
5758 Typed_identifier t = Typed_identifier(name, rtype,
5759 imp->location());
5760 t.set_note(note);
5761 results->push_back(t);
5762 if (imp->peek_char() != ',')
5763 break;
5764 imp->require_c_string(", ");
5765 }
5766 imp->require_c_string(")");
5767 }
5768 }
5769 *presults = results;
5770
5771 if (!imp->match_c_string(" <inl:"))
5772 {
5773 imp->require_semicolon_if_old_version();
5774 imp->require_c_string("\n");
5775 body->clear();
5776 }
5777 else
5778 {
5779 imp->require_c_string(" <inl:");
5780 std::string lenstr;
5781 int c;
5782 while (true)
5783 {
5784 c = imp->peek_char();
5785 if (c < '0' || c > '9')
5786 break;
5787 lenstr += c;
5788 imp->get_char();
5789 }
5790 imp->require_c_string(">\n");
5791
5792 errno = 0;
5793 char* end;
5794 long llen = strtol(lenstr.c_str(), &end, 10);
5795 if (*end != '\0'
5796 || llen < 0
5797 || (llen == LONG_MAX && errno == ERANGE))
5798 {
5799 go_error_at(imp->location(), "invalid inline function length %s",
5800 lenstr.c_str());
5801 return;
5802 }
5803
5804 *body = imp->read(static_cast<size_t>(llen));
5805 }
5806 }
5807
5808 // Get the backend representation.
5809
5810 Bfunction*
5811 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5812 {
5813 if (this->fndecl_ == NULL)
5814 {
5815 unsigned int flags = 0;
5816 bool is_init_fn = false;
5817 if (no->package() != NULL)
5818 ;
5819 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5820 ;
5821 else if (Gogo::unpack_hidden_name(no->name()) == "init"
5822 && !this->type_->is_method())
5823 ;
5824 else if (no->name() == gogo->get_init_fn_name())
5825 {
5826 flags |= Backend::function_is_visible;
5827 is_init_fn = true;
5828 }
5829 else if (Gogo::unpack_hidden_name(no->name()) == "main"
5830 && gogo->is_main_package())
5831 flags |= Backend::function_is_visible;
5832 // Methods have to be public even if they are hidden because
5833 // they can be pulled into type descriptors when using
5834 // anonymous fields.
5835 else if (!Gogo::is_hidden_name(no->name())
5836 || this->type_->is_method())
5837 {
5838 if (!this->is_unnamed_type_stub_method_)
5839 flags |= Backend::function_is_visible;
5840 }
5841
5842 Type* rtype = NULL;
5843 if (this->type_->is_method())
5844 rtype = this->type_->receiver()->type();
5845
5846 std::string asm_name;
5847 if (!this->asm_name_.empty())
5848 {
5849 asm_name = this->asm_name_;
5850
5851 // If an assembler name is explicitly specified, there must
5852 // be some reason to refer to the symbol from a different
5853 // object file.
5854 flags |= Backend::function_is_visible;
5855 }
5856 else if (is_init_fn)
5857 {
5858 // These names appear in the export data and are used
5859 // directly in the assembler code. If we change this here
5860 // we need to change Gogo::init_imports.
5861 asm_name = no->name();
5862 }
5863 else
5864 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5865
5866 // If a function calls the predeclared recover function, we
5867 // can't inline it, because recover behaves differently in a
5868 // function passed directly to defer. If this is a recover
5869 // thunk that we built to test whether a function can be
5870 // recovered, we can't inline it, because that will mess up
5871 // our return address comparison.
5872 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5873
5874 // If a function calls __go_set_defer_retaddr, then mark it as
5875 // uninlinable. This prevents the GCC backend from splitting
5876 // the function; splitting the function is a bad idea because we
5877 // want the return address label to be in the same function as
5878 // the call.
5879 if (this->calls_defer_retaddr_)
5880 is_inlinable = false;
5881
5882 // Check the //go:noinline compiler directive.
5883 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5884 is_inlinable = false;
5885
5886 if (is_inlinable)
5887 flags |= Backend::function_is_inlinable;
5888
5889 // If this is a thunk created to call a function which calls
5890 // the predeclared recover function, we need to disable
5891 // stack splitting for the thunk.
5892 bool disable_split_stack = this->is_recover_thunk_;
5893
5894 // Check the //go:nosplit compiler directive.
5895 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5896 disable_split_stack = true;
5897
5898 if (disable_split_stack)
5899 flags |= Backend::function_no_split_stack;
5900
5901 // This should go into a unique section if that has been
5902 // requested elsewhere, or if this is a nointerface function.
5903 // We want to put a nointerface function into a unique section
5904 // because there is a good chance that the linker garbage
5905 // collection can discard it.
5906 if (this->in_unique_section_
5907 || (this->is_method() && this->nointerface()))
5908 flags |= Backend::function_in_unique_section;
5909
5910 if (this->is_inline_only_)
5911 flags |= Backend::function_only_inline;
5912
5913 Btype* functype = this->type_->get_backend_fntype(gogo);
5914 this->fndecl_ =
5915 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5916 flags, this->location());
5917 }
5918 return this->fndecl_;
5919 }
5920
5921 // Get the backend representation.
5922
5923 Bfunction*
5924 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5925 {
5926 if (this->fndecl_ == NULL)
5927 {
5928 unsigned int flags =
5929 (Backend::function_is_visible
5930 | Backend::function_is_declaration
5931 | Backend::function_is_inlinable);
5932
5933 // Let Go code use an asm declaration to pick up a builtin
5934 // function.
5935 if (!this->asm_name_.empty())
5936 {
5937 Bfunction* builtin_decl =
5938 gogo->backend()->lookup_builtin(this->asm_name_);
5939 if (builtin_decl != NULL)
5940 {
5941 this->fndecl_ = builtin_decl;
5942 return this->fndecl_;
5943 }
5944
5945 if (this->asm_name_ == "runtime.gopanic"
5946 || this->asm_name_ == "__go_runtime_error")
5947 flags |= Backend::function_does_not_return;
5948 }
5949
5950 std::string asm_name;
5951 if (this->asm_name_.empty())
5952 {
5953 Type* rtype = NULL;
5954 if (this->fntype_->is_method())
5955 rtype = this->fntype_->receiver()->type();
5956 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5957 }
5958 else if (go_id_needs_encoding(no->get_id(gogo)))
5959 asm_name = go_encode_id(no->get_id(gogo));
5960
5961 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5962 this->fndecl_ =
5963 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5964 flags, this->location());
5965 }
5966
5967 return this->fndecl_;
5968 }
5969
5970 // Build the descriptor for a function declaration. This won't
5971 // necessarily happen if the package has just a declaration for the
5972 // function and no other reference to it, but we may still need the
5973 // descriptor for references from other packages.
5974 void
5975 Function_declaration::build_backend_descriptor(Gogo* gogo)
5976 {
5977 if (this->descriptor_ != NULL)
5978 {
5979 Translate_context context(gogo, NULL, NULL, NULL);
5980 this->descriptor_->get_backend(&context);
5981 }
5982 }
5983
5984 // Check that the types used in this declaration's signature are defined.
5985 // Reports errors for any undefined type.
5986
5987 void
5988 Function_declaration::check_types() const
5989 {
5990 // Calling Type::base will give errors for any undefined types.
5991 Function_type* fntype = this->type();
5992 if (fntype->receiver() != NULL)
5993 fntype->receiver()->type()->base();
5994 if (fntype->parameters() != NULL)
5995 {
5996 const Typed_identifier_list* params = fntype->parameters();
5997 for (Typed_identifier_list::const_iterator p = params->begin();
5998 p != params->end();
5999 ++p)
6000 p->type()->base();
6001 }
6002 }
6003
6004 // Return the function's decl after it has been built.
6005
6006 Bfunction*
6007 Function::get_decl() const
6008 {
6009 go_assert(this->fndecl_ != NULL);
6010 return this->fndecl_;
6011 }
6012
6013 // Build the backend representation for the function code.
6014
6015 void
6016 Function::build(Gogo* gogo, Named_object* named_function)
6017 {
6018 Translate_context context(gogo, named_function, NULL, NULL);
6019
6020 // A list of parameter variables for this function.
6021 std::vector<Bvariable*> param_vars;
6022
6023 // Variables that need to be declared for this function and their
6024 // initial values.
6025 std::vector<Bvariable*> vars;
6026 std::vector<Bexpression*> var_inits;
6027 std::vector<Statement*> var_decls_stmts;
6028 for (Bindings::const_definitions_iterator p =
6029 this->block_->bindings()->begin_definitions();
6030 p != this->block_->bindings()->end_definitions();
6031 ++p)
6032 {
6033 Location loc = (*p)->location();
6034 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
6035 {
6036 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6037 Bvariable* parm_bvar = bvar;
6038
6039 // We always pass the receiver to a method as a pointer. If
6040 // the receiver is declared as a non-pointer type, then we
6041 // copy the value into a local variable.
6042 if ((*p)->var_value()->is_receiver()
6043 && !(*p)->var_value()->type()->is_direct_iface_type())
6044 {
6045 std::string name = (*p)->name() + ".pointer";
6046 Type* var_type = (*p)->var_value()->type();
6047 Variable* parm_var =
6048 new Variable(Type::make_pointer_type(var_type), NULL, false,
6049 true, false, loc);
6050 Named_object* parm_no =
6051 Named_object::make_variable(name, NULL, parm_var);
6052 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6053
6054 vars.push_back(bvar);
6055 Expression* parm_ref =
6056 Expression::make_var_reference(parm_no, loc);
6057 parm_ref =
6058 Expression::make_dereference(parm_ref,
6059 Expression::NIL_CHECK_NEEDED,
6060 loc);
6061 if ((*p)->var_value()->is_in_heap())
6062 parm_ref = Expression::make_heap_expression(parm_ref, loc);
6063 var_inits.push_back(parm_ref->get_backend(&context));
6064 }
6065 else if ((*p)->var_value()->is_in_heap())
6066 {
6067 // If we take the address of a parameter, then we need
6068 // to copy it into the heap.
6069 std::string parm_name = (*p)->name() + ".param";
6070 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
6071 false, true, false, loc);
6072 Named_object* parm_no =
6073 Named_object::make_variable(parm_name, NULL, parm_var);
6074 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
6075
6076 vars.push_back(bvar);
6077 Expression* var_ref =
6078 Expression::make_var_reference(parm_no, loc);
6079 var_ref = Expression::make_heap_expression(var_ref, loc);
6080 var_inits.push_back(var_ref->get_backend(&context));
6081 }
6082 param_vars.push_back(parm_bvar);
6083 }
6084 else if ((*p)->is_result_variable())
6085 {
6086 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
6087
6088 Type* type = (*p)->result_var_value()->type();
6089 Bexpression* init;
6090 if (!(*p)->result_var_value()->is_in_heap())
6091 {
6092 Btype* btype = type->get_backend(gogo);
6093 init = gogo->backend()->zero_expression(btype);
6094 }
6095 else
6096 init = Expression::make_allocation(type,
6097 loc)->get_backend(&context);
6098
6099 vars.push_back(bvar);
6100 var_inits.push_back(init);
6101 }
6102 else if (this->defer_stack_ != NULL
6103 && (*p)->is_variable()
6104 && (*p)->var_value()->is_non_escaping_address_taken()
6105 && !(*p)->var_value()->is_in_heap())
6106 {
6107 // Local variable captured by deferred closure needs to be live
6108 // until the end of the function. We create a top-level
6109 // declaration for it.
6110 // TODO: we don't need to do this if the variable is not captured
6111 // by the defer closure. There is no easy way to check it here,
6112 // so we do this for all address-taken variables for now.
6113 Variable* var = (*p)->var_value();
6114 Temporary_statement* ts =
6115 Statement::make_temporary(var->type(), NULL, var->location());
6116 ts->set_is_address_taken();
6117 var->set_toplevel_decl(ts);
6118 var_decls_stmts.push_back(ts);
6119 }
6120 }
6121 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
6122 {
6123 go_assert(saw_errors());
6124 return;
6125 }
6126
6127 // If we need a closure variable, make sure to create it.
6128 // It gets installed in the function as a side effect of creation.
6129 if (this->closure_var_ != NULL)
6130 {
6131 go_assert(this->closure_var_->var_value()->is_closure());
6132 this->closure_var_->get_backend_variable(gogo, named_function);
6133 }
6134
6135 if (this->block_ != NULL)
6136 {
6137 // Declare variables if necessary.
6138 Bblock* var_decls = NULL;
6139 std::vector<Bstatement*> var_decls_bstmt_list;
6140 Bstatement* defer_init = NULL;
6141 if (!vars.empty() || this->defer_stack_ != NULL)
6142 {
6143 var_decls =
6144 gogo->backend()->block(this->fndecl_, NULL, vars,
6145 this->block_->start_location(),
6146 this->block_->end_location());
6147
6148 if (this->defer_stack_ != NULL)
6149 {
6150 Translate_context dcontext(gogo, named_function, this->block_,
6151 var_decls);
6152 defer_init = this->defer_stack_->get_backend(&dcontext);
6153 var_decls_bstmt_list.push_back(defer_init);
6154 for (std::vector<Statement*>::iterator p = var_decls_stmts.begin();
6155 p != var_decls_stmts.end();
6156 ++p)
6157 {
6158 Bstatement* bstmt = (*p)->get_backend(&dcontext);
6159 var_decls_bstmt_list.push_back(bstmt);
6160 }
6161 }
6162 }
6163
6164 // Build the backend representation for all the statements in the
6165 // function.
6166 Translate_context context(gogo, named_function, NULL, NULL);
6167 Bblock* code_block = this->block_->get_backend(&context);
6168
6169 // Initialize variables if necessary.
6170 std::vector<Bstatement*> init;
6171 go_assert(vars.size() == var_inits.size());
6172 for (size_t i = 0; i < vars.size(); ++i)
6173 {
6174 Bstatement* init_stmt =
6175 gogo->backend()->init_statement(this->fndecl_, vars[i],
6176 var_inits[i]);
6177 init.push_back(init_stmt);
6178 }
6179 Bstatement* var_init = gogo->backend()->statement_list(init);
6180
6181 // Initialize all variables before executing this code block.
6182 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
6183 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
6184
6185 // If we have a defer stack, initialize it at the start of a
6186 // function.
6187 Bstatement* except = NULL;
6188 Bstatement* fini = NULL;
6189 if (defer_init != NULL)
6190 {
6191 // Clean up the defer stack when we leave the function.
6192 this->build_defer_wrapper(gogo, named_function, &except, &fini);
6193
6194 // Wrap the code for this function in an exception handler to handle
6195 // defer calls.
6196 code_stmt =
6197 gogo->backend()->exception_handler_statement(code_stmt,
6198 except, fini,
6199 this->location_);
6200 }
6201
6202 // Stick the code into the block we built for the receiver, if
6203 // we built one.
6204 if (var_decls != NULL)
6205 {
6206 var_decls_bstmt_list.push_back(code_stmt);
6207 gogo->backend()->block_add_statements(var_decls, var_decls_bstmt_list);
6208 code_stmt = gogo->backend()->block_statement(var_decls);
6209 }
6210
6211 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
6212 {
6213 go_assert(saw_errors());
6214 return;
6215 }
6216 }
6217
6218 // If we created a descriptor for the function, make sure we emit it.
6219 if (this->descriptor_ != NULL)
6220 {
6221 Translate_context context(gogo, NULL, NULL, NULL);
6222 this->descriptor_->get_backend(&context);
6223 }
6224 }
6225
6226 // Build the wrappers around function code needed if the function has
6227 // any defer statements. This sets *EXCEPT to an exception handler
6228 // and *FINI to a finally handler.
6229
6230 void
6231 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
6232 Bstatement** except, Bstatement** fini)
6233 {
6234 Location end_loc = this->block_->end_location();
6235
6236 // Add an exception handler. This is used if a panic occurs. Its
6237 // purpose is to stop the stack unwinding if a deferred function
6238 // calls recover. There are more details in
6239 // libgo/runtime/go-unwind.c.
6240
6241 std::vector<Bstatement*> stmts;
6242 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6243 this->defer_stack(end_loc));
6244 Translate_context context(gogo, named_function, NULL, NULL);
6245 Bexpression* defer = call->get_backend(&context);
6246 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
6247
6248 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
6249 if (ret_bstmt != NULL)
6250 stmts.push_back(ret_bstmt);
6251
6252 go_assert(*except == NULL);
6253 *except = gogo->backend()->statement_list(stmts);
6254
6255 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
6256 this->defer_stack(end_loc));
6257 defer = call->get_backend(&context);
6258
6259 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
6260 this->defer_stack(end_loc));
6261 Bexpression* undefer = call->get_backend(&context);
6262 Bstatement* function_defer =
6263 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
6264 end_loc);
6265 stmts = std::vector<Bstatement*>(1, function_defer);
6266 if (this->type_->results() != NULL
6267 && !this->type_->results()->empty()
6268 && !this->type_->results()->front().name().empty())
6269 {
6270 // If the result variables are named, and we are returning from
6271 // this function rather than panicing through it, we need to
6272 // return them again, because they might have been changed by a
6273 // defer function. The runtime routines set the defer_stack
6274 // variable to true if we are returning from this function.
6275
6276 ret_bstmt = this->return_value(gogo, named_function, end_loc);
6277 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
6278 Bexpression* ret =
6279 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
6280 Expression* ref =
6281 Expression::make_temporary_reference(this->defer_stack_, end_loc);
6282 Bexpression* bref = ref->get_backend(&context);
6283 ret = gogo->backend()->conditional_expression(this->fndecl_,
6284 NULL, bref, ret, NULL,
6285 end_loc);
6286 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
6287 }
6288
6289 go_assert(*fini == NULL);
6290 *fini = gogo->backend()->statement_list(stmts);
6291 }
6292
6293 // Return the statement that assigns values to this function's result struct.
6294
6295 Bstatement*
6296 Function::return_value(Gogo* gogo, Named_object* named_function,
6297 Location location) const
6298 {
6299 const Typed_identifier_list* results = this->type_->results();
6300 if (results == NULL || results->empty())
6301 return NULL;
6302
6303 go_assert(this->results_ != NULL);
6304 if (this->results_->size() != results->size())
6305 {
6306 go_assert(saw_errors());
6307 return gogo->backend()->error_statement();
6308 }
6309
6310 std::vector<Bexpression*> vals(results->size());
6311 for (size_t i = 0; i < vals.size(); ++i)
6312 {
6313 Named_object* no = (*this->results_)[i];
6314 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
6315 Bexpression* val = gogo->backend()->var_expression(bvar, location);
6316 if (no->result_var_value()->is_in_heap())
6317 {
6318 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
6319 val = gogo->backend()->indirect_expression(bt, val, true, location);
6320 }
6321 vals[i] = val;
6322 }
6323 return gogo->backend()->return_statement(this->fndecl_, vals, location);
6324 }
6325
6326 // Class Block.
6327
6328 Block::Block(Block* enclosing, Location location)
6329 : enclosing_(enclosing), statements_(),
6330 bindings_(new Bindings(enclosing == NULL
6331 ? NULL
6332 : enclosing->bindings())),
6333 start_location_(location),
6334 end_location_(Linemap::unknown_location())
6335 {
6336 }
6337
6338 // Add a statement to a block.
6339
6340 void
6341 Block::add_statement(Statement* statement)
6342 {
6343 this->statements_.push_back(statement);
6344 }
6345
6346 // Add a statement to the front of a block. This is slow but is only
6347 // used for reference counts of parameters.
6348
6349 void
6350 Block::add_statement_at_front(Statement* statement)
6351 {
6352 this->statements_.insert(this->statements_.begin(), statement);
6353 }
6354
6355 // Replace a statement in a block.
6356
6357 void
6358 Block::replace_statement(size_t index, Statement* s)
6359 {
6360 go_assert(index < this->statements_.size());
6361 this->statements_[index] = s;
6362 }
6363
6364 // Add a statement before another statement.
6365
6366 void
6367 Block::insert_statement_before(size_t index, Statement* s)
6368 {
6369 go_assert(index < this->statements_.size());
6370 this->statements_.insert(this->statements_.begin() + index, s);
6371 }
6372
6373 // Add a statement after another statement.
6374
6375 void
6376 Block::insert_statement_after(size_t index, Statement* s)
6377 {
6378 go_assert(index < this->statements_.size());
6379 this->statements_.insert(this->statements_.begin() + index + 1, s);
6380 }
6381
6382 // Traverse the tree.
6383
6384 int
6385 Block::traverse(Traverse* traverse)
6386 {
6387 unsigned int traverse_mask = traverse->traverse_mask();
6388
6389 if ((traverse_mask & Traverse::traverse_blocks) != 0)
6390 {
6391 int t = traverse->block(this);
6392 if (t == TRAVERSE_EXIT)
6393 return TRAVERSE_EXIT;
6394 else if (t == TRAVERSE_SKIP_COMPONENTS)
6395 return TRAVERSE_CONTINUE;
6396 }
6397
6398 if ((traverse_mask
6399 & (Traverse::traverse_variables
6400 | Traverse::traverse_constants
6401 | Traverse::traverse_expressions
6402 | Traverse::traverse_types)) != 0)
6403 {
6404 const unsigned int e_or_t = (Traverse::traverse_expressions
6405 | Traverse::traverse_types);
6406 const unsigned int e_or_t_or_s = (e_or_t
6407 | Traverse::traverse_statements);
6408 for (Bindings::const_definitions_iterator pb =
6409 this->bindings_->begin_definitions();
6410 pb != this->bindings_->end_definitions();
6411 ++pb)
6412 {
6413 int t = TRAVERSE_CONTINUE;
6414 switch ((*pb)->classification())
6415 {
6416 case Named_object::NAMED_OBJECT_CONST:
6417 if ((traverse_mask & Traverse::traverse_constants) != 0)
6418 t = traverse->constant(*pb, false);
6419 if (t == TRAVERSE_CONTINUE
6420 && (traverse_mask & e_or_t) != 0)
6421 {
6422 Type* tc = (*pb)->const_value()->type();
6423 if (tc != NULL
6424 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
6425 return TRAVERSE_EXIT;
6426 t = (*pb)->const_value()->traverse_expression(traverse);
6427 }
6428 break;
6429
6430 case Named_object::NAMED_OBJECT_VAR:
6431 case Named_object::NAMED_OBJECT_RESULT_VAR:
6432 if ((traverse_mask & Traverse::traverse_variables) != 0)
6433 t = traverse->variable(*pb);
6434 if (t == TRAVERSE_CONTINUE
6435 && (traverse_mask & e_or_t) != 0)
6436 {
6437 if ((*pb)->is_result_variable()
6438 || (*pb)->var_value()->has_type())
6439 {
6440 Type* tv = ((*pb)->is_variable()
6441 ? (*pb)->var_value()->type()
6442 : (*pb)->result_var_value()->type());
6443 if (tv != NULL
6444 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
6445 return TRAVERSE_EXIT;
6446 }
6447 }
6448 if (t == TRAVERSE_CONTINUE
6449 && (traverse_mask & e_or_t_or_s) != 0
6450 && (*pb)->is_variable())
6451 t = (*pb)->var_value()->traverse_expression(traverse,
6452 traverse_mask);
6453 break;
6454
6455 case Named_object::NAMED_OBJECT_FUNC:
6456 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6457 go_unreachable();
6458
6459 case Named_object::NAMED_OBJECT_TYPE:
6460 if ((traverse_mask & e_or_t) != 0)
6461 t = Type::traverse((*pb)->type_value(), traverse);
6462 break;
6463
6464 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6465 case Named_object::NAMED_OBJECT_UNKNOWN:
6466 case Named_object::NAMED_OBJECT_ERRONEOUS:
6467 break;
6468
6469 case Named_object::NAMED_OBJECT_PACKAGE:
6470 case Named_object::NAMED_OBJECT_SINK:
6471 go_unreachable();
6472
6473 default:
6474 go_unreachable();
6475 }
6476
6477 if (t == TRAVERSE_EXIT)
6478 return TRAVERSE_EXIT;
6479 }
6480 }
6481
6482 // No point in checking traverse_mask here--if we got here we always
6483 // want to walk the statements. The traversal can insert new
6484 // statements before or after the current statement. Inserting
6485 // statements before the current statement requires updating I via
6486 // the pointer; those statements will not be traversed. Any new
6487 // statements inserted after the current statement will be traversed
6488 // in their turn.
6489 for (size_t i = 0; i < this->statements_.size(); ++i)
6490 {
6491 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6492 return TRAVERSE_EXIT;
6493 }
6494
6495 return TRAVERSE_CONTINUE;
6496 }
6497
6498 // Work out types for unspecified variables and constants.
6499
6500 void
6501 Block::determine_types()
6502 {
6503 for (Bindings::const_definitions_iterator pb =
6504 this->bindings_->begin_definitions();
6505 pb != this->bindings_->end_definitions();
6506 ++pb)
6507 {
6508 if ((*pb)->is_variable())
6509 (*pb)->var_value()->determine_type();
6510 else if ((*pb)->is_const())
6511 (*pb)->const_value()->determine_type();
6512 }
6513
6514 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6515 ps != this->statements_.end();
6516 ++ps)
6517 (*ps)->determine_types();
6518 }
6519
6520 // Return true if the statements in this block may fall through.
6521
6522 bool
6523 Block::may_fall_through() const
6524 {
6525 if (this->statements_.empty())
6526 return true;
6527 return this->statements_.back()->may_fall_through();
6528 }
6529
6530 // Write export data for a block.
6531
6532 void
6533 Block::export_block(Export_function_body* efb)
6534 {
6535 for (Block::iterator p = this->begin();
6536 p != this->end();
6537 ++p)
6538 {
6539 efb->indent();
6540
6541 efb->increment_indent();
6542 (*p)->export_statement(efb);
6543 efb->decrement_indent();
6544
6545 Location loc = (*p)->location();
6546 if ((*p)->is_block_statement())
6547 {
6548 // For a block we put the start location on the first brace
6549 // in Block_statement::do_export_statement. Here we put the
6550 // end location on the final brace.
6551 loc = (*p)->block_statement()->block()->end_location();
6552 }
6553 char buf[50];
6554 snprintf(buf, sizeof buf, " //%d\n", Linemap::location_to_line(loc));
6555 efb->write_c_string(buf);
6556 }
6557 }
6558
6559 // Add exported block data to SET, reading from BODY starting at OFF.
6560 // Returns whether the import succeeded.
6561
6562 bool
6563 Block::import_block(Block* set, Import_function_body *ifb, Location loc)
6564 {
6565 Location eloc = ifb->location();
6566 Location sloc = loc;
6567 const std::string& body(ifb->body());
6568 size_t off = ifb->off();
6569 while (off < body.length())
6570 {
6571 int indent = ifb->indent();
6572 if (off + indent >= body.length())
6573 {
6574 go_error_at(eloc,
6575 "invalid export data for %qs: insufficient indentation",
6576 ifb->name().c_str());
6577 return false;
6578 }
6579 for (int i = 0; i < indent - 1; i++)
6580 {
6581 if (body[off + i] != ' ')
6582 {
6583 go_error_at(eloc,
6584 "invalid export data for %qs: bad indentation",
6585 ifb->name().c_str());
6586 return false;
6587 }
6588 }
6589
6590 bool at_end = false;
6591 if (body[off + indent - 1] == '}')
6592 at_end = true;
6593 else if (body[off + indent - 1] != ' ')
6594 {
6595 go_error_at(eloc,
6596 "invalid export data for %qs: bad indentation",
6597 ifb->name().c_str());
6598 return false;
6599 }
6600
6601 off += indent;
6602
6603 size_t nl = body.find('\n', off);
6604 if (nl == std::string::npos)
6605 {
6606 go_error_at(eloc, "invalid export data for %qs: missing newline",
6607 ifb->name().c_str());
6608 return false;
6609 }
6610
6611 size_t lineno_pos = body.find(" //", off);
6612 if (lineno_pos == std::string::npos || lineno_pos >= nl)
6613 {
6614 go_error_at(eloc, "invalid export data for %qs: missing line number",
6615 ifb->name().c_str());
6616 return false;
6617 }
6618
6619 unsigned int lineno = 0;
6620 for (size_t i = lineno_pos + 3; i < nl; ++i)
6621 {
6622 char c = body[i];
6623 if (c < '0' || c > '9')
6624 {
6625 go_error_at(loc,
6626 "invalid export data for %qs: invalid line number",
6627 ifb->name().c_str());
6628 return false;
6629 }
6630 lineno = lineno * 10 + c - '0';
6631 }
6632
6633 ifb->gogo()->linemap()->start_line(lineno, 1);
6634 sloc = ifb->gogo()->linemap()->get_location(0);
6635
6636 if (at_end)
6637 {
6638 off = nl + 1;
6639 break;
6640 }
6641
6642 ifb->set_off(off);
6643 Statement* s = Statement::import_statement(ifb, sloc);
6644 if (s == NULL)
6645 return false;
6646
6647 set->add_statement(s);
6648
6649 size_t at = ifb->off();
6650 if (at < nl + 1)
6651 off = nl + 1;
6652 else
6653 off = at;
6654 }
6655
6656 ifb->set_off(off);
6657 set->set_end_location(sloc);
6658 return true;
6659 }
6660
6661 // Convert a block to the backend representation.
6662
6663 Bblock*
6664 Block::get_backend(Translate_context* context)
6665 {
6666 Gogo* gogo = context->gogo();
6667 Named_object* function = context->function();
6668 std::vector<Bvariable*> vars;
6669 vars.reserve(this->bindings_->size_definitions());
6670 for (Bindings::const_definitions_iterator pv =
6671 this->bindings_->begin_definitions();
6672 pv != this->bindings_->end_definitions();
6673 ++pv)
6674 {
6675 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6676 vars.push_back((*pv)->get_backend_variable(gogo, function));
6677 }
6678
6679 go_assert(function != NULL);
6680 Bfunction* bfunction =
6681 function->func_value()->get_or_make_decl(gogo, function);
6682 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6683 vars, this->start_location_,
6684 this->end_location_);
6685
6686 Translate_context subcontext(gogo, function, this, ret);
6687 std::vector<Bstatement*> bstatements;
6688 bstatements.reserve(this->statements_.size());
6689 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6690 p != this->statements_.end();
6691 ++p)
6692 bstatements.push_back((*p)->get_backend(&subcontext));
6693
6694 context->backend()->block_add_statements(ret, bstatements);
6695
6696 return ret;
6697 }
6698
6699 // Class Bindings_snapshot.
6700
6701 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6702 : block_(b), counts_(), location_(location)
6703 {
6704 while (b != NULL)
6705 {
6706 this->counts_.push_back(b->bindings()->size_definitions());
6707 b = b->enclosing();
6708 }
6709 }
6710
6711 // Report errors appropriate for a goto from B to this.
6712
6713 void
6714 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6715 {
6716 size_t dummy;
6717 if (!this->check_goto_block(loc, b, this->block_, &dummy))
6718 return;
6719 this->check_goto_defs(loc, this->block_,
6720 this->block_->bindings()->size_definitions(),
6721 this->counts_[0]);
6722 }
6723
6724 // Report errors appropriate for a goto from this to B.
6725
6726 void
6727 Bindings_snapshot::check_goto_to(const Block* b)
6728 {
6729 size_t index;
6730 if (!this->check_goto_block(this->location_, this->block_, b, &index))
6731 return;
6732 this->check_goto_defs(this->location_, b, this->counts_[index],
6733 b->bindings()->size_definitions());
6734 }
6735
6736 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6737 // Return true if all is well, false if we reported an error. If this
6738 // returns true, it sets *PINDEX to the number of blocks BTO is above
6739 // BFROM.
6740
6741 bool
6742 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6743 const Block* bto, size_t* pindex)
6744 {
6745 // It is an error if BTO is not either BFROM or above BFROM.
6746 size_t index = 0;
6747 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6748 {
6749 if (pb == NULL)
6750 {
6751 go_error_at(loc, "goto jumps into block");
6752 go_inform(bto->start_location(), "goto target block starts here");
6753 return false;
6754 }
6755 }
6756 *pindex = index;
6757 return true;
6758 }
6759
6760 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6761 // CFROM is the number of names defined at the point of the goto and
6762 // CTO is the number of names defined at the point of the label.
6763
6764 void
6765 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6766 size_t cfrom, size_t cto)
6767 {
6768 if (cfrom < cto)
6769 {
6770 Bindings::const_definitions_iterator p =
6771 block->bindings()->begin_definitions();
6772 for (size_t i = 0; i < cfrom; ++i)
6773 {
6774 go_assert(p != block->bindings()->end_definitions());
6775 ++p;
6776 }
6777 go_assert(p != block->bindings()->end_definitions());
6778
6779 for (; p != block->bindings()->end_definitions(); ++p)
6780 {
6781 if ((*p)->is_variable())
6782 {
6783 std::string n = (*p)->message_name();
6784 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6785 go_inform((*p)->location(), "%qs defined here", n.c_str());
6786 }
6787 }
6788 }
6789 }
6790
6791 // Class Function_declaration.
6792
6793 // Whether this declares a method.
6794
6795 bool
6796 Function_declaration::is_method() const
6797 {
6798 return this->fntype_->is_method();
6799 }
6800
6801 // Whether this method should not be included in the type descriptor.
6802
6803 bool
6804 Function_declaration::nointerface() const
6805 {
6806 go_assert(this->is_method());
6807 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
6808 }
6809
6810 // Record that this method should not be included in the type
6811 // descriptor.
6812
6813 void
6814 Function_declaration::set_nointerface()
6815 {
6816 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
6817 }
6818
6819 // Import an inlinable function. This is used for an inlinable
6820 // function whose body is recorded in the export data. Parse the
6821 // export data into a Block and create a regular function using that
6822 // Block as its body. Redeclare this function declaration as the
6823 // function.
6824
6825 void
6826 Function_declaration::import_function_body(Gogo* gogo, Named_object* no)
6827 {
6828 go_assert(no->func_declaration_value() == this);
6829 go_assert(no->package() != NULL);
6830 const std::string& body(this->imported_body_);
6831 go_assert(!body.empty());
6832
6833 // Read the "//FILE:LINE" comment starts the export data.
6834
6835 size_t indent = 1;
6836 if (this->is_method())
6837 indent = 2;
6838 size_t i = 0;
6839 for (; i < indent; i++)
6840 {
6841 if (body.at(i) != ' ')
6842 {
6843 go_error_at(this->location_,
6844 "invalid export body for %qs: bad initial indentation",
6845 no->message_name().c_str());
6846 return;
6847 }
6848 }
6849
6850 if (body.substr(i, 2) != "//")
6851 {
6852 go_error_at(this->location_,
6853 "invalid export body for %qs: missing file comment",
6854 no->message_name().c_str());
6855 return;
6856 }
6857
6858 size_t colon = body.find(':', i + 2);
6859 size_t nl = body.find('\n', i + 2);
6860 if (nl == std::string::npos)
6861 {
6862 go_error_at(this->location_,
6863 "invalid export body for %qs: missing file name",
6864 no->message_name().c_str());
6865 return;
6866 }
6867 if (colon == std::string::npos || nl < colon)
6868 {
6869 go_error_at(this->location_,
6870 "invalid export body for %qs: missing initial line number",
6871 no->message_name().c_str());
6872 return;
6873 }
6874
6875 std::string file = body.substr(i + 2, colon - (i + 2));
6876 std::string linestr = body.substr(colon + 1, nl - (colon + 1));
6877 char* end;
6878 long linenol = strtol(linestr.c_str(), &end, 10);
6879 if (*end != '\0')
6880 {
6881 go_error_at(this->location_,
6882 "invalid export body for %qs: invalid initial line number",
6883 no->message_name().c_str());
6884 return;
6885 }
6886 unsigned int lineno = static_cast<unsigned int>(linenol);
6887
6888 // Turn the file/line into a location.
6889
6890 char* alc = new char[file.length() + 1];
6891 memcpy(alc, file.data(), file.length());
6892 alc[file.length()] = '\0';
6893 gogo->linemap()->start_file(alc, lineno);
6894 gogo->linemap()->start_line(lineno, 1);
6895 Location start_loc = gogo->linemap()->get_location(0);
6896
6897 // Define the function with an outer block that declares the
6898 // parameters.
6899
6900 Function_type* fntype = this->fntype_;
6901
6902 Block* outer = new Block(NULL, start_loc);
6903
6904 Function* fn = new Function(fntype, NULL, outer, start_loc);
6905 fn->set_is_inline_only();
6906
6907 if (fntype->is_method())
6908 {
6909 if (this->nointerface())
6910 fn->set_nointerface();
6911 const Typed_identifier* receiver = fntype->receiver();
6912 Variable* recv_param = new Variable(receiver->type(), NULL, false,
6913 true, true, start_loc);
6914
6915 std::string rname = receiver->name();
6916 unsigned rcounter = 0;
6917
6918 // We need to give a nameless receiver a name to avoid having it
6919 // clash with some other nameless param. FIXME.
6920 Gogo::rename_if_empty(&rname, "r", &rcounter);
6921
6922 outer->bindings()->add_variable(rname, NULL, recv_param);
6923 }
6924
6925 const Typed_identifier_list* params = fntype->parameters();
6926 bool is_varargs = fntype->is_varargs();
6927 unsigned pcounter = 0;
6928 if (params != NULL)
6929 {
6930 for (Typed_identifier_list::const_iterator p = params->begin();
6931 p != params->end();
6932 ++p)
6933 {
6934 Variable* param = new Variable(p->type(), NULL, false, true, false,
6935 start_loc);
6936 if (is_varargs && p + 1 == params->end())
6937 param->set_is_varargs_parameter();
6938
6939 std::string pname = p->name();
6940
6941 // We need to give each nameless parameter a non-empty name to avoid
6942 // having it clash with some other nameless param. FIXME.
6943 Gogo::rename_if_empty(&pname, "p", &pcounter);
6944
6945 outer->bindings()->add_variable(pname, NULL, param);
6946 }
6947 }
6948
6949 fn->create_result_variables(gogo);
6950
6951 if (!fntype->is_method())
6952 {
6953 const Package* package = no->package();
6954 no = package->bindings()->add_function(no->name(), package, fn);
6955 }
6956 else
6957 {
6958 Named_type* rtype = fntype->receiver()->type()->deref()->named_type();
6959 go_assert(rtype != NULL);
6960 no = rtype->add_method(no->name(), fn);
6961 }
6962
6963 Import_function_body ifb(gogo, this->imp_, no, body, nl + 1, outer, indent);
6964
6965 if (!Block::import_block(outer, &ifb, start_loc))
6966 return;
6967
6968 gogo->lower_block(no, outer);
6969
6970 gogo->add_imported_inline_function(no);
6971 }
6972
6973 // Return the function descriptor.
6974
6975 Expression*
6976 Function_declaration::descriptor(Gogo*, Named_object* no)
6977 {
6978 go_assert(!this->fntype_->is_method());
6979 if (this->descriptor_ == NULL)
6980 this->descriptor_ = Expression::make_func_descriptor(no);
6981 return this->descriptor_;
6982 }
6983
6984 // Class Variable.
6985
6986 Variable::Variable(Type* type, Expression* init, bool is_global,
6987 bool is_parameter, bool is_receiver,
6988 Location location)
6989 : type_(type), init_(init), preinit_(NULL), location_(location),
6990 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6991 is_closure_(false), is_receiver_(is_receiver),
6992 is_varargs_parameter_(false), is_used_(false),
6993 is_address_taken_(false), is_non_escaping_address_taken_(false),
6994 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6995 type_from_init_tuple_(false), type_from_range_index_(false),
6996 type_from_range_value_(false), type_from_chan_element_(false),
6997 is_type_switch_var_(false), determined_type_(false),
6998 in_unique_section_(false), toplevel_decl_(NULL)
6999 {
7000 go_assert(type != NULL || init != NULL);
7001 go_assert(!is_parameter || init == NULL);
7002 }
7003
7004 // Traverse the initializer expression.
7005
7006 int
7007 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
7008 {
7009 if (this->preinit_ != NULL)
7010 {
7011 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
7012 return TRAVERSE_EXIT;
7013 }
7014 if (this->init_ != NULL
7015 && ((traverse_mask
7016 & (Traverse::traverse_expressions | Traverse::traverse_types))
7017 != 0))
7018 {
7019 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
7020 return TRAVERSE_EXIT;
7021 }
7022 return TRAVERSE_CONTINUE;
7023 }
7024
7025 // Lower the initialization expression after parsing is complete.
7026
7027 void
7028 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
7029 Statement_inserter* inserter)
7030 {
7031 Named_object* dep = gogo->var_depends_on(this);
7032 if (dep != NULL && dep->is_variable())
7033 dep->var_value()->lower_init_expression(gogo, function, inserter);
7034
7035 if (this->init_ != NULL && !this->init_is_lowered_)
7036 {
7037 if (this->seen_)
7038 {
7039 // We will give an error elsewhere, this is just to prevent
7040 // an infinite loop.
7041 return;
7042 }
7043 this->seen_ = true;
7044
7045 Statement_inserter global_inserter;
7046 if (this->is_global_)
7047 {
7048 global_inserter = Statement_inserter(gogo, this);
7049 inserter = &global_inserter;
7050 }
7051
7052 gogo->lower_expression(function, inserter, &this->init_);
7053
7054 this->seen_ = false;
7055
7056 this->init_is_lowered_ = true;
7057 }
7058 }
7059
7060 // Flatten the initialization expression after ordering evaluations.
7061
7062 void
7063 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
7064 Statement_inserter* inserter)
7065 {
7066 Named_object* dep = gogo->var_depends_on(this);
7067 if (dep != NULL && dep->is_variable())
7068 dep->var_value()->flatten_init_expression(gogo, function, inserter);
7069
7070 if (this->init_ != NULL && !this->init_is_flattened_)
7071 {
7072 if (this->seen_)
7073 {
7074 // We will give an error elsewhere, this is just to prevent
7075 // an infinite loop.
7076 return;
7077 }
7078 this->seen_ = true;
7079
7080 Statement_inserter global_inserter;
7081 if (this->is_global_)
7082 {
7083 global_inserter = Statement_inserter(gogo, this);
7084 inserter = &global_inserter;
7085 }
7086
7087 gogo->flatten_expression(function, inserter, &this->init_);
7088
7089 // If an interface conversion is needed, we need a temporary
7090 // variable.
7091 if (this->type_ != NULL
7092 && !Type::are_identical(this->type_, this->init_->type(),
7093 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
7094 NULL)
7095 && this->init_->type()->interface_type() != NULL
7096 && !this->init_->is_variable())
7097 {
7098 Temporary_statement* temp =
7099 Statement::make_temporary(NULL, this->init_, this->location_);
7100 inserter->insert(temp);
7101 this->init_ = Expression::make_temporary_reference(temp,
7102 this->location_);
7103 }
7104
7105 this->seen_ = false;
7106 this->init_is_flattened_ = true;
7107 }
7108 }
7109
7110 // Get the preinit block.
7111
7112 Block*
7113 Variable::preinit_block(Gogo* gogo)
7114 {
7115 go_assert(this->is_global_);
7116 if (this->preinit_ == NULL)
7117 this->preinit_ = new Block(NULL, this->location());
7118
7119 // If a global variable has a preinitialization statement, then we
7120 // need to have an initialization function.
7121 gogo->set_need_init_fn();
7122
7123 return this->preinit_;
7124 }
7125
7126 // Add a statement to be run before the initialization expression.
7127
7128 void
7129 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
7130 {
7131 Block* b = this->preinit_block(gogo);
7132 b->add_statement(s);
7133 b->set_end_location(s->location());
7134 }
7135
7136 // Whether this variable has a type.
7137
7138 bool
7139 Variable::has_type() const
7140 {
7141 if (this->type_ == NULL)
7142 return false;
7143
7144 // A variable created in a type switch case nil does not actually
7145 // have a type yet. It will be changed to use the initializer's
7146 // type in determine_type.
7147 if (this->is_type_switch_var_
7148 && this->type_->is_nil_constant_as_type())
7149 return false;
7150
7151 return true;
7152 }
7153
7154 // In an assignment which sets a variable to a tuple of EXPR, return
7155 // the type of the first element of the tuple.
7156
7157 Type*
7158 Variable::type_from_tuple(Expression* expr, bool report_error) const
7159 {
7160 if (expr->map_index_expression() != NULL)
7161 {
7162 Map_type* mt = expr->map_index_expression()->get_map_type();
7163 if (mt == NULL)
7164 return Type::make_error_type();
7165 return mt->val_type();
7166 }
7167 else if (expr->receive_expression() != NULL)
7168 {
7169 Expression* channel = expr->receive_expression()->channel();
7170 Type* channel_type = channel->type();
7171 if (channel_type->channel_type() == NULL)
7172 return Type::make_error_type();
7173 return channel_type->channel_type()->element_type();
7174 }
7175 else
7176 {
7177 if (report_error)
7178 go_error_at(this->location(), "invalid tuple definition");
7179 return Type::make_error_type();
7180 }
7181 }
7182
7183 // Given EXPR used in a range clause, return either the index type or
7184 // the value type of the range, depending upon GET_INDEX_TYPE.
7185
7186 Type*
7187 Variable::type_from_range(Expression* expr, bool get_index_type,
7188 bool report_error) const
7189 {
7190 Type* t = expr->type();
7191 if (t->array_type() != NULL
7192 || (t->points_to() != NULL
7193 && t->points_to()->array_type() != NULL
7194 && !t->points_to()->is_slice_type()))
7195 {
7196 if (get_index_type)
7197 return Type::lookup_integer_type("int");
7198 else
7199 return t->deref()->array_type()->element_type();
7200 }
7201 else if (t->is_string_type())
7202 {
7203 if (get_index_type)
7204 return Type::lookup_integer_type("int");
7205 else
7206 return Type::lookup_integer_type("int32");
7207 }
7208 else if (t->map_type() != NULL)
7209 {
7210 if (get_index_type)
7211 return t->map_type()->key_type();
7212 else
7213 return t->map_type()->val_type();
7214 }
7215 else if (t->channel_type() != NULL)
7216 {
7217 if (get_index_type)
7218 return t->channel_type()->element_type();
7219 else
7220 {
7221 if (report_error)
7222 go_error_at(this->location(),
7223 ("invalid definition of value variable "
7224 "for channel range"));
7225 return Type::make_error_type();
7226 }
7227 }
7228 else
7229 {
7230 if (report_error)
7231 go_error_at(this->location(), "invalid type for range clause");
7232 return Type::make_error_type();
7233 }
7234 }
7235
7236 // EXPR should be a channel. Return the channel's element type.
7237
7238 Type*
7239 Variable::type_from_chan_element(Expression* expr, bool report_error) const
7240 {
7241 Type* t = expr->type();
7242 if (t->channel_type() != NULL)
7243 return t->channel_type()->element_type();
7244 else
7245 {
7246 if (report_error)
7247 go_error_at(this->location(), "expected channel");
7248 return Type::make_error_type();
7249 }
7250 }
7251
7252 // Return the type of the Variable. This may be called before
7253 // Variable::determine_type is called, which means that we may need to
7254 // get the type from the initializer. FIXME: If we combine lowering
7255 // with type determination, then this should be unnecessary.
7256
7257 Type*
7258 Variable::type()
7259 {
7260 // A variable in a type switch with a nil case will have the wrong
7261 // type here. This gets fixed up in determine_type, below.
7262 Type* type = this->type_;
7263 Expression* init = this->init_;
7264 if (this->is_type_switch_var_
7265 && type != NULL
7266 && this->type_->is_nil_constant_as_type())
7267 {
7268 Type_guard_expression* tge = this->init_->type_guard_expression();
7269 go_assert(tge != NULL);
7270 init = tge->expr();
7271 type = NULL;
7272 }
7273
7274 if (this->seen_)
7275 {
7276 if (this->type_ == NULL || !this->type_->is_error_type())
7277 {
7278 go_error_at(this->location_, "variable initializer refers to itself");
7279 this->type_ = Type::make_error_type();
7280 }
7281 return this->type_;
7282 }
7283
7284 this->seen_ = true;
7285
7286 if (type != NULL)
7287 ;
7288 else if (this->type_from_init_tuple_)
7289 type = this->type_from_tuple(init, false);
7290 else if (this->type_from_range_index_ || this->type_from_range_value_)
7291 type = this->type_from_range(init, this->type_from_range_index_, false);
7292 else if (this->type_from_chan_element_)
7293 type = this->type_from_chan_element(init, false);
7294 else
7295 {
7296 go_assert(init != NULL);
7297 type = init->type();
7298 go_assert(type != NULL);
7299
7300 // Variables should not have abstract types.
7301 if (type->is_abstract())
7302 type = type->make_non_abstract_type();
7303
7304 if (type->is_void_type())
7305 type = Type::make_error_type();
7306 }
7307
7308 this->seen_ = false;
7309
7310 return type;
7311 }
7312
7313 // Fetch the type from a const pointer, in which case it should have
7314 // been set already.
7315
7316 Type*
7317 Variable::type() const
7318 {
7319 go_assert(this->type_ != NULL);
7320 return this->type_;
7321 }
7322
7323 // Set the type if necessary.
7324
7325 void
7326 Variable::determine_type()
7327 {
7328 if (this->determined_type_)
7329 return;
7330 this->determined_type_ = true;
7331
7332 if (this->preinit_ != NULL)
7333 this->preinit_->determine_types();
7334
7335 // A variable in a type switch with a nil case will have the wrong
7336 // type here. It will have an initializer which is a type guard.
7337 // We want to initialize it to the value without the type guard, and
7338 // use the type of that value as well.
7339 if (this->is_type_switch_var_
7340 && this->type_ != NULL
7341 && this->type_->is_nil_constant_as_type())
7342 {
7343 Type_guard_expression* tge = this->init_->type_guard_expression();
7344 go_assert(tge != NULL);
7345 this->type_ = NULL;
7346 this->init_ = tge->expr();
7347 }
7348
7349 if (this->init_ == NULL)
7350 go_assert(this->type_ != NULL && !this->type_->is_abstract());
7351 else if (this->type_from_init_tuple_)
7352 {
7353 Expression *init = this->init_;
7354 init->determine_type_no_context();
7355 this->type_ = this->type_from_tuple(init, true);
7356 this->init_ = NULL;
7357 }
7358 else if (this->type_from_range_index_ || this->type_from_range_value_)
7359 {
7360 Expression* init = this->init_;
7361 init->determine_type_no_context();
7362 this->type_ = this->type_from_range(init, this->type_from_range_index_,
7363 true);
7364 this->init_ = NULL;
7365 }
7366 else if (this->type_from_chan_element_)
7367 {
7368 Expression* init = this->init_;
7369 init->determine_type_no_context();
7370 this->type_ = this->type_from_chan_element(init, true);
7371 this->init_ = NULL;
7372 }
7373 else
7374 {
7375 Type_context context(this->type_, false);
7376 this->init_->determine_type(&context);
7377 if (this->type_ == NULL)
7378 {
7379 Type* type = this->init_->type();
7380 go_assert(type != NULL);
7381 if (type->is_abstract())
7382 type = type->make_non_abstract_type();
7383
7384 if (type->is_void_type())
7385 {
7386 go_error_at(this->location_, "variable has no type");
7387 type = Type::make_error_type();
7388 }
7389 else if (type->is_nil_type())
7390 {
7391 go_error_at(this->location_, "variable defined to nil type");
7392 type = Type::make_error_type();
7393 }
7394 else if (type->is_call_multiple_result_type())
7395 {
7396 go_error_at(this->location_,
7397 "single variable set to multiple-value function call");
7398 type = Type::make_error_type();
7399 }
7400
7401 this->type_ = type;
7402 }
7403 }
7404 }
7405
7406 // Get the initial value of a variable. This does not
7407 // consider whether the variable is in the heap--it returns the
7408 // initial value as though it were always stored in the stack.
7409
7410 Bexpression*
7411 Variable::get_init(Gogo* gogo, Named_object* function)
7412 {
7413 go_assert(this->preinit_ == NULL);
7414 Location loc = this->location();
7415 if (this->init_ == NULL)
7416 {
7417 go_assert(!this->is_parameter_);
7418 if (this->is_global_ || this->is_in_heap())
7419 return NULL;
7420 Btype* btype = this->type()->get_backend(gogo);
7421 return gogo->backend()->zero_expression(btype);
7422 }
7423 else
7424 {
7425 Translate_context context(gogo, function, NULL, NULL);
7426 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
7427 return init->get_backend(&context);
7428 }
7429 }
7430
7431 // Get the initial value of a variable when a block is required.
7432 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7433
7434 Bstatement*
7435 Variable::get_init_block(Gogo* gogo, Named_object* function,
7436 Bvariable* var_decl)
7437 {
7438 go_assert(this->preinit_ != NULL);
7439
7440 // We want to add the variable assignment to the end of the preinit
7441 // block.
7442
7443 Translate_context context(gogo, function, NULL, NULL);
7444 Bblock* bblock = this->preinit_->get_backend(&context);
7445 Bfunction* bfunction =
7446 function->func_value()->get_or_make_decl(gogo, function);
7447
7448 // It's possible to have pre-init statements without an initializer
7449 // if the pre-init statements set the variable.
7450 Bstatement* decl_init = NULL;
7451 if (this->init_ != NULL)
7452 {
7453 if (var_decl == NULL)
7454 {
7455 Bexpression* init_bexpr = this->init_->get_backend(&context);
7456 decl_init = gogo->backend()->expression_statement(bfunction,
7457 init_bexpr);
7458 }
7459 else
7460 {
7461 Location loc = this->location();
7462 Expression* val_expr =
7463 Expression::make_cast(this->type(), this->init_, loc);
7464 Bexpression* val = val_expr->get_backend(&context);
7465 Bexpression* var_ref =
7466 gogo->backend()->var_expression(var_decl, loc);
7467 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
7468 val, loc);
7469 }
7470 }
7471 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
7472 if (decl_init != NULL)
7473 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
7474 return block_stmt;
7475 }
7476
7477 // Export the variable
7478
7479 void
7480 Variable::export_var(Export* exp, const std::string& name) const
7481 {
7482 go_assert(this->is_global_);
7483 exp->write_c_string("var ");
7484 exp->write_string(name);
7485 exp->write_c_string(" ");
7486 exp->write_type(this->type());
7487 exp->write_c_string("\n");
7488 }
7489
7490 // Import a variable.
7491
7492 void
7493 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
7494 {
7495 imp->require_c_string("var ");
7496 *pname = imp->read_identifier();
7497 imp->require_c_string(" ");
7498 *ptype = imp->read_type();
7499 imp->require_semicolon_if_old_version();
7500 imp->require_c_string("\n");
7501 }
7502
7503 // Convert a variable to the backend representation.
7504
7505 Bvariable*
7506 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
7507 const Package* package, const std::string& name)
7508 {
7509 if (this->backend_ == NULL)
7510 {
7511 Backend* backend = gogo->backend();
7512 Type* type = this->type_;
7513 if (type->is_error_type()
7514 || (type->is_undefined()
7515 && (!this->is_global_ || package == NULL)))
7516 this->backend_ = backend->error_variable();
7517 else
7518 {
7519 bool is_parameter = this->is_parameter_;
7520 if (this->is_receiver_ && !type->is_direct_iface_type())
7521 is_parameter = false;
7522 if (this->is_in_heap())
7523 {
7524 is_parameter = false;
7525 type = Type::make_pointer_type(type);
7526 }
7527
7528 const std::string n = Gogo::unpack_hidden_name(name);
7529 Btype* btype = type->get_backend(gogo);
7530
7531 Bvariable* bvar;
7532 if (Map_type::is_zero_value(this))
7533 bvar = Map_type::backend_zero_value(gogo);
7534 else if (this->is_global_)
7535 {
7536 std::string var_name(package != NULL
7537 ? package->package_name()
7538 : gogo->package_name());
7539 var_name.push_back('.');
7540 var_name.append(n);
7541
7542 std::string asm_name(gogo->global_var_asm_name(name, package));
7543
7544 bool is_hidden = Gogo::is_hidden_name(name);
7545 // Hack to export runtime.writeBarrier. FIXME.
7546 // This is because go:linkname doesn't work on variables.
7547 if (gogo->compiling_runtime()
7548 && var_name == "runtime.writeBarrier")
7549 is_hidden = false;
7550
7551 bvar = backend->global_variable(var_name,
7552 asm_name,
7553 btype,
7554 package != NULL,
7555 is_hidden,
7556 this->in_unique_section_,
7557 this->location_);
7558 }
7559 else if (function == NULL)
7560 {
7561 go_assert(saw_errors());
7562 bvar = backend->error_variable();
7563 }
7564 else
7565 {
7566 Bfunction* bfunction = function->func_value()->get_decl();
7567 bool is_address_taken = (this->is_non_escaping_address_taken_
7568 && !this->is_in_heap());
7569 if (this->is_closure())
7570 bvar = backend->static_chain_variable(bfunction, n, btype,
7571 this->location_);
7572 else if (is_parameter)
7573 bvar = backend->parameter_variable(bfunction, n, btype,
7574 is_address_taken,
7575 this->location_);
7576 else
7577 {
7578 Bvariable* bvar_decl = NULL;
7579 if (this->toplevel_decl_ != NULL)
7580 {
7581 Translate_context context(gogo, NULL, NULL, NULL);
7582 bvar_decl = this->toplevel_decl_->temporary_statement()
7583 ->get_backend_variable(&context);
7584 }
7585 bvar = backend->local_variable(bfunction, n, btype,
7586 bvar_decl,
7587 is_address_taken,
7588 this->location_);
7589 }
7590 }
7591 this->backend_ = bvar;
7592 }
7593 }
7594 return this->backend_;
7595 }
7596
7597 // Class Result_variable.
7598
7599 // Convert a result variable to the backend representation.
7600
7601 Bvariable*
7602 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
7603 const std::string& name)
7604 {
7605 if (this->backend_ == NULL)
7606 {
7607 Backend* backend = gogo->backend();
7608 Type* type = this->type_;
7609 if (type->is_error())
7610 this->backend_ = backend->error_variable();
7611 else
7612 {
7613 if (this->is_in_heap())
7614 type = Type::make_pointer_type(type);
7615 Btype* btype = type->get_backend(gogo);
7616 Bfunction* bfunction = function->func_value()->get_decl();
7617 std::string n = Gogo::unpack_hidden_name(name);
7618 bool is_address_taken = (this->is_non_escaping_address_taken_
7619 && !this->is_in_heap());
7620 this->backend_ = backend->local_variable(bfunction, n, btype,
7621 NULL, is_address_taken,
7622 this->location_);
7623 }
7624 }
7625 return this->backend_;
7626 }
7627
7628 // Class Named_constant.
7629
7630 // Set the type of a named constant. This is only used to set the
7631 // type to an error type.
7632
7633 void
7634 Named_constant::set_type(Type* t)
7635 {
7636 go_assert(this->type_ == NULL || t->is_error_type());
7637 this->type_ = t;
7638 }
7639
7640 // Traverse the initializer expression.
7641
7642 int
7643 Named_constant::traverse_expression(Traverse* traverse)
7644 {
7645 return Expression::traverse(&this->expr_, traverse);
7646 }
7647
7648 // Determine the type of the constant.
7649
7650 void
7651 Named_constant::determine_type()
7652 {
7653 if (this->type_ != NULL)
7654 {
7655 Type_context context(this->type_, false);
7656 this->expr_->determine_type(&context);
7657 }
7658 else
7659 {
7660 // A constant may have an abstract type.
7661 Type_context context(NULL, true);
7662 this->expr_->determine_type(&context);
7663 this->type_ = this->expr_->type();
7664 go_assert(this->type_ != NULL);
7665 }
7666 }
7667
7668 // Indicate that we found and reported an error for this constant.
7669
7670 void
7671 Named_constant::set_error()
7672 {
7673 this->type_ = Type::make_error_type();
7674 this->expr_ = Expression::make_error(this->location_);
7675 }
7676
7677 // Export a constant.
7678
7679 void
7680 Named_constant::export_const(Export* exp, const std::string& name) const
7681 {
7682 exp->write_c_string("const ");
7683 exp->write_string(name);
7684 exp->write_c_string(" ");
7685 if (!this->type_->is_abstract())
7686 {
7687 exp->write_type(this->type_);
7688 exp->write_c_string(" ");
7689 }
7690 exp->write_c_string("= ");
7691
7692 Export_function_body efb(exp, 0);
7693 if (!this->type_->is_abstract())
7694 efb.set_type_context(this->type_);
7695 this->expr()->export_expression(&efb);
7696 exp->write_string(efb.body());
7697
7698 exp->write_c_string("\n");
7699 }
7700
7701 // Import a constant.
7702
7703 void
7704 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
7705 Expression** pexpr)
7706 {
7707 imp->require_c_string("const ");
7708 *pname = imp->read_identifier();
7709 imp->require_c_string(" ");
7710 if (imp->peek_char() == '=')
7711 *ptype = NULL;
7712 else
7713 {
7714 *ptype = imp->read_type();
7715 imp->require_c_string(" ");
7716 }
7717 imp->require_c_string("= ");
7718 *pexpr = Expression::import_expression(imp, imp->location());
7719 imp->require_semicolon_if_old_version();
7720 imp->require_c_string("\n");
7721 }
7722
7723 // Get the backend representation.
7724
7725 Bexpression*
7726 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
7727 {
7728 if (this->bconst_ == NULL)
7729 {
7730 Translate_context subcontext(gogo, NULL, NULL, NULL);
7731 Type* type = this->type();
7732 Location loc = this->location();
7733
7734 Expression* const_ref = Expression::make_const_reference(const_no, loc);
7735 Bexpression* const_decl = const_ref->get_backend(&subcontext);
7736 if (type != NULL && type->is_numeric_type())
7737 {
7738 Btype* btype = type->get_backend(gogo);
7739 std::string name = const_no->get_id(gogo);
7740 const_decl =
7741 gogo->backend()->named_constant_expression(btype, name,
7742 const_decl, loc);
7743 }
7744 this->bconst_ = const_decl;
7745 }
7746 return this->bconst_;
7747 }
7748
7749 // Add a method.
7750
7751 Named_object*
7752 Type_declaration::add_method(const std::string& name, Function* function)
7753 {
7754 Named_object* ret = Named_object::make_function(name, NULL, function);
7755 this->methods_.push_back(ret);
7756 return ret;
7757 }
7758
7759 // Add a method declaration.
7760
7761 Named_object*
7762 Type_declaration::add_method_declaration(const std::string& name,
7763 Package* package,
7764 Function_type* type,
7765 Location location)
7766 {
7767 Named_object* ret = Named_object::make_function_declaration(name, package,
7768 type, location);
7769 this->methods_.push_back(ret);
7770 return ret;
7771 }
7772
7773 // Return whether any methods are defined.
7774
7775 bool
7776 Type_declaration::has_methods() const
7777 {
7778 return !this->methods_.empty();
7779 }
7780
7781 // Define methods for the real type.
7782
7783 void
7784 Type_declaration::define_methods(Named_type* nt)
7785 {
7786 if (this->methods_.empty())
7787 return;
7788
7789 while (nt->is_alias())
7790 {
7791 Type *t = nt->real_type()->forwarded();
7792 if (t->named_type() != NULL)
7793 nt = t->named_type();
7794 else if (t->forward_declaration_type() != NULL)
7795 {
7796 Named_object* no = t->forward_declaration_type()->named_object();
7797 Type_declaration* td = no->type_declaration_value();
7798 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
7799 this->methods_.end());
7800 this->methods_.clear();
7801 return;
7802 }
7803 else
7804 {
7805 for (std::vector<Named_object*>::const_iterator p =
7806 this->methods_.begin();
7807 p != this->methods_.end();
7808 ++p)
7809 go_error_at((*p)->location(),
7810 ("invalid receiver type "
7811 "(receiver must be a named type"));
7812 return;
7813 }
7814 }
7815
7816 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
7817 p != this->methods_.end();
7818 ++p)
7819 {
7820 if ((*p)->is_function_declaration()
7821 || !(*p)->func_value()->is_sink())
7822 nt->add_existing_method(*p);
7823 }
7824 }
7825
7826 // We are using the type. Return true if we should issue a warning.
7827
7828 bool
7829 Type_declaration::using_type()
7830 {
7831 bool ret = !this->issued_warning_;
7832 this->issued_warning_ = true;
7833 return ret;
7834 }
7835
7836 // Class Unknown_name.
7837
7838 // Set the real named object.
7839
7840 void
7841 Unknown_name::set_real_named_object(Named_object* no)
7842 {
7843 go_assert(this->real_named_object_ == NULL);
7844 go_assert(!no->is_unknown());
7845 this->real_named_object_ = no;
7846 }
7847
7848 // Class Named_object.
7849
7850 Named_object::Named_object(const std::string& name,
7851 const Package* package,
7852 Classification classification)
7853 : name_(name), package_(package), classification_(classification),
7854 is_redefinition_(false)
7855 {
7856 if (Gogo::is_sink_name(name))
7857 go_assert(classification == NAMED_OBJECT_SINK);
7858 }
7859
7860 // Make an unknown name. This is used by the parser. The name must
7861 // be resolved later. Unknown names are only added in the current
7862 // package.
7863
7864 Named_object*
7865 Named_object::make_unknown_name(const std::string& name,
7866 Location location)
7867 {
7868 Named_object* named_object = new Named_object(name, NULL,
7869 NAMED_OBJECT_UNKNOWN);
7870 Unknown_name* value = new Unknown_name(location);
7871 named_object->u_.unknown_value = value;
7872 return named_object;
7873 }
7874
7875 // Make a constant.
7876
7877 Named_object*
7878 Named_object::make_constant(const Typed_identifier& tid,
7879 const Package* package, Expression* expr,
7880 int iota_value)
7881 {
7882 Named_object* named_object = new Named_object(tid.name(), package,
7883 NAMED_OBJECT_CONST);
7884 Named_constant* named_constant = new Named_constant(tid.type(), expr,
7885 iota_value,
7886 tid.location());
7887 named_object->u_.const_value = named_constant;
7888 return named_object;
7889 }
7890
7891 // Make a named type.
7892
7893 Named_object*
7894 Named_object::make_type(const std::string& name, const Package* package,
7895 Type* type, Location location)
7896 {
7897 Named_object* named_object = new Named_object(name, package,
7898 NAMED_OBJECT_TYPE);
7899 Named_type* named_type = Type::make_named_type(named_object, type, location);
7900 named_object->u_.type_value = named_type;
7901 return named_object;
7902 }
7903
7904 // Make a type declaration.
7905
7906 Named_object*
7907 Named_object::make_type_declaration(const std::string& name,
7908 const Package* package,
7909 Location location)
7910 {
7911 Named_object* named_object = new Named_object(name, package,
7912 NAMED_OBJECT_TYPE_DECLARATION);
7913 Type_declaration* type_declaration = new Type_declaration(location);
7914 named_object->u_.type_declaration = type_declaration;
7915 return named_object;
7916 }
7917
7918 // Make a variable.
7919
7920 Named_object*
7921 Named_object::make_variable(const std::string& name, const Package* package,
7922 Variable* variable)
7923 {
7924 Named_object* named_object = new Named_object(name, package,
7925 NAMED_OBJECT_VAR);
7926 named_object->u_.var_value = variable;
7927 return named_object;
7928 }
7929
7930 // Make a result variable.
7931
7932 Named_object*
7933 Named_object::make_result_variable(const std::string& name,
7934 Result_variable* result)
7935 {
7936 Named_object* named_object = new Named_object(name, NULL,
7937 NAMED_OBJECT_RESULT_VAR);
7938 named_object->u_.result_var_value = result;
7939 return named_object;
7940 }
7941
7942 // Make a sink. This is used for the special blank identifier _.
7943
7944 Named_object*
7945 Named_object::make_sink()
7946 {
7947 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7948 }
7949
7950 // Make a named function.
7951
7952 Named_object*
7953 Named_object::make_function(const std::string& name, const Package* package,
7954 Function* function)
7955 {
7956 Named_object* named_object = new Named_object(name, package,
7957 NAMED_OBJECT_FUNC);
7958 named_object->u_.func_value = function;
7959 return named_object;
7960 }
7961
7962 // Make a function declaration.
7963
7964 Named_object*
7965 Named_object::make_function_declaration(const std::string& name,
7966 const Package* package,
7967 Function_type* fntype,
7968 Location location)
7969 {
7970 Named_object* named_object = new Named_object(name, package,
7971 NAMED_OBJECT_FUNC_DECLARATION);
7972 Function_declaration *func_decl = new Function_declaration(fntype, location);
7973 named_object->u_.func_declaration_value = func_decl;
7974 return named_object;
7975 }
7976
7977 // Make a package.
7978
7979 Named_object*
7980 Named_object::make_package(const std::string& alias, Package* package)
7981 {
7982 Named_object* named_object = new Named_object(alias, NULL,
7983 NAMED_OBJECT_PACKAGE);
7984 named_object->u_.package_value = package;
7985 return named_object;
7986 }
7987
7988 // Return the name to use in an error message.
7989
7990 std::string
7991 Named_object::message_name() const
7992 {
7993 if (this->package_ == NULL)
7994 return Gogo::message_name(this->name_);
7995 std::string ret;
7996 if (this->package_->has_package_name())
7997 ret = this->package_->package_name();
7998 else
7999 ret = this->package_->pkgpath();
8000 ret = Gogo::message_name(ret);
8001 ret += '.';
8002 ret += Gogo::message_name(this->name_);
8003 return ret;
8004 }
8005
8006 // Set the type when a declaration is defined.
8007
8008 void
8009 Named_object::set_type_value(Named_type* named_type)
8010 {
8011 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
8012 Type_declaration* td = this->u_.type_declaration;
8013 td->define_methods(named_type);
8014 unsigned int index;
8015 Named_object* in_function = td->in_function(&index);
8016 if (in_function != NULL)
8017 named_type->set_in_function(in_function, index);
8018 delete td;
8019 this->classification_ = NAMED_OBJECT_TYPE;
8020 this->u_.type_value = named_type;
8021 }
8022
8023 // Define a function which was previously declared.
8024
8025 void
8026 Named_object::set_function_value(Function* function)
8027 {
8028 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
8029 if (this->func_declaration_value()->has_descriptor())
8030 {
8031 Expression* descriptor =
8032 this->func_declaration_value()->descriptor(NULL, NULL);
8033 function->set_descriptor(descriptor);
8034 }
8035 this->classification_ = NAMED_OBJECT_FUNC;
8036 // FIXME: We should free the old value.
8037 this->u_.func_value = function;
8038 }
8039
8040 // Declare an unknown object as a type declaration.
8041
8042 void
8043 Named_object::declare_as_type()
8044 {
8045 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
8046 Unknown_name* unk = this->u_.unknown_value;
8047 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
8048 this->u_.type_declaration = new Type_declaration(unk->location());
8049 delete unk;
8050 }
8051
8052 // Return the location of a named object.
8053
8054 Location
8055 Named_object::location() const
8056 {
8057 switch (this->classification_)
8058 {
8059 default:
8060 case NAMED_OBJECT_UNINITIALIZED:
8061 go_unreachable();
8062
8063 case NAMED_OBJECT_ERRONEOUS:
8064 return Linemap::unknown_location();
8065
8066 case NAMED_OBJECT_UNKNOWN:
8067 return this->unknown_value()->location();
8068
8069 case NAMED_OBJECT_CONST:
8070 return this->const_value()->location();
8071
8072 case NAMED_OBJECT_TYPE:
8073 return this->type_value()->location();
8074
8075 case NAMED_OBJECT_TYPE_DECLARATION:
8076 return this->type_declaration_value()->location();
8077
8078 case NAMED_OBJECT_VAR:
8079 return this->var_value()->location();
8080
8081 case NAMED_OBJECT_RESULT_VAR:
8082 return this->result_var_value()->location();
8083
8084 case NAMED_OBJECT_SINK:
8085 go_unreachable();
8086
8087 case NAMED_OBJECT_FUNC:
8088 return this->func_value()->location();
8089
8090 case NAMED_OBJECT_FUNC_DECLARATION:
8091 return this->func_declaration_value()->location();
8092
8093 case NAMED_OBJECT_PACKAGE:
8094 return this->package_value()->location();
8095 }
8096 }
8097
8098 // Export a named object.
8099
8100 void
8101 Named_object::export_named_object(Export* exp) const
8102 {
8103 switch (this->classification_)
8104 {
8105 default:
8106 case NAMED_OBJECT_UNINITIALIZED:
8107 case NAMED_OBJECT_UNKNOWN:
8108 go_unreachable();
8109
8110 case NAMED_OBJECT_ERRONEOUS:
8111 break;
8112
8113 case NAMED_OBJECT_CONST:
8114 this->const_value()->export_const(exp, this->name_);
8115 break;
8116
8117 case NAMED_OBJECT_TYPE:
8118 // Types are handled by export::write_types.
8119 go_unreachable();
8120
8121 case NAMED_OBJECT_TYPE_DECLARATION:
8122 go_error_at(this->type_declaration_value()->location(),
8123 "attempt to export %<%s%> which was declared but not defined",
8124 this->message_name().c_str());
8125 break;
8126
8127 case NAMED_OBJECT_FUNC_DECLARATION:
8128 this->func_declaration_value()->export_func(exp, this->name_);
8129 break;
8130
8131 case NAMED_OBJECT_VAR:
8132 this->var_value()->export_var(exp, this->name_);
8133 break;
8134
8135 case NAMED_OBJECT_RESULT_VAR:
8136 case NAMED_OBJECT_SINK:
8137 go_unreachable();
8138
8139 case NAMED_OBJECT_FUNC:
8140 this->func_value()->export_func(exp, this->name_);
8141 break;
8142 }
8143 }
8144
8145 // Convert a variable to the backend representation.
8146
8147 Bvariable*
8148 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
8149 {
8150 if (this->classification_ == NAMED_OBJECT_VAR)
8151 return this->var_value()->get_backend_variable(gogo, function,
8152 this->package_, this->name_);
8153 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
8154 return this->result_var_value()->get_backend_variable(gogo, function,
8155 this->name_);
8156 else
8157 go_unreachable();
8158 }
8159
8160 // Return the external identifier for this object.
8161
8162 std::string
8163 Named_object::get_id(Gogo* gogo)
8164 {
8165 go_assert(!this->is_variable()
8166 && !this->is_result_variable()
8167 && !this->is_type());
8168 std::string decl_name;
8169 if (this->is_function_declaration()
8170 && !this->func_declaration_value()->asm_name().empty())
8171 decl_name = this->func_declaration_value()->asm_name();
8172 else
8173 {
8174 std::string package_name;
8175 if (this->package_ == NULL)
8176 package_name = gogo->package_name();
8177 else
8178 package_name = this->package_->package_name();
8179
8180 // Note that this will be misleading if this is an unexported
8181 // method generated for an embedded imported type. In that case
8182 // the unexported method should have the package name of the
8183 // package from which it is imported, but we are going to give
8184 // it our package name. Fixing this would require knowing the
8185 // package name, but we only know the package path. It might be
8186 // better to use package paths here anyhow. This doesn't affect
8187 // the assembler code, because we always set that name in
8188 // Function::get_or_make_decl anyhow. FIXME.
8189
8190 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
8191
8192 Function_type* fntype;
8193 if (this->is_function())
8194 fntype = this->func_value()->type();
8195 else if (this->is_function_declaration())
8196 fntype = this->func_declaration_value()->type();
8197 else
8198 fntype = NULL;
8199 if (fntype != NULL && fntype->is_method())
8200 {
8201 decl_name.push_back('.');
8202 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
8203 }
8204 }
8205 return decl_name;
8206 }
8207
8208 // Get the backend representation for this named object.
8209
8210 void
8211 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
8212 std::vector<Btype*>& type_decls,
8213 std::vector<Bfunction*>& func_decls)
8214 {
8215 // If this is a definition, avoid trying to get the backend
8216 // representation, as that can crash.
8217 if (this->is_redefinition_)
8218 {
8219 go_assert(saw_errors());
8220 return;
8221 }
8222
8223 switch (this->classification_)
8224 {
8225 case NAMED_OBJECT_CONST:
8226 if (!Gogo::is_erroneous_name(this->name_))
8227 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
8228 break;
8229
8230 case NAMED_OBJECT_TYPE:
8231 {
8232 Named_type* named_type = this->u_.type_value;
8233 if (!Gogo::is_erroneous_name(this->name_) && !named_type->is_alias())
8234 type_decls.push_back(named_type->get_backend(gogo));
8235
8236 // We need to produce a type descriptor for every named
8237 // type, and for a pointer to every named type, since
8238 // other files or packages might refer to them. We need
8239 // to do this even for hidden types, because they might
8240 // still be returned by some function. Simply calling the
8241 // type_descriptor method is enough to create the type
8242 // descriptor, even though we don't do anything with it.
8243 if (this->package_ == NULL && !saw_errors())
8244 {
8245 named_type->
8246 type_descriptor_pointer(gogo, Linemap::predeclared_location());
8247 named_type->gc_symbol_pointer(gogo);
8248 Type* pn = Type::make_pointer_type(named_type);
8249 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
8250 pn->gc_symbol_pointer(gogo);
8251 }
8252 }
8253 break;
8254
8255 case NAMED_OBJECT_TYPE_DECLARATION:
8256 go_error_at(Linemap::unknown_location(),
8257 "reference to undefined type %qs",
8258 this->message_name().c_str());
8259 return;
8260
8261 case NAMED_OBJECT_VAR:
8262 case NAMED_OBJECT_RESULT_VAR:
8263 case NAMED_OBJECT_SINK:
8264 go_unreachable();
8265
8266 case NAMED_OBJECT_FUNC:
8267 {
8268 Function* func = this->u_.func_value;
8269 if (!Gogo::is_erroneous_name(this->name_))
8270 func_decls.push_back(func->get_or_make_decl(gogo, this));
8271
8272 if (func->block() != NULL)
8273 func->build(gogo, this);
8274 }
8275 break;
8276
8277 case NAMED_OBJECT_ERRONEOUS:
8278 break;
8279
8280 default:
8281 go_unreachable();
8282 }
8283 }
8284
8285 // Class Bindings.
8286
8287 Bindings::Bindings(Bindings* enclosing)
8288 : enclosing_(enclosing), named_objects_(), bindings_()
8289 {
8290 }
8291
8292 // Clear imports.
8293
8294 void
8295 Bindings::clear_file_scope(Gogo* gogo)
8296 {
8297 Contour::iterator p = this->bindings_.begin();
8298 while (p != this->bindings_.end())
8299 {
8300 bool keep;
8301 if (p->second->package() != NULL)
8302 keep = false;
8303 else if (p->second->is_package())
8304 keep = false;
8305 else if (p->second->is_function()
8306 && !p->second->func_value()->type()->is_method()
8307 && Gogo::unpack_hidden_name(p->second->name()) == "init")
8308 keep = false;
8309 else
8310 keep = true;
8311
8312 if (keep)
8313 ++p;
8314 else
8315 {
8316 gogo->add_file_block_name(p->second->name(), p->second->location());
8317 p = this->bindings_.erase(p);
8318 }
8319 }
8320 }
8321
8322 // Look up a symbol.
8323
8324 Named_object*
8325 Bindings::lookup(const std::string& name) const
8326 {
8327 Contour::const_iterator p = this->bindings_.find(name);
8328 if (p != this->bindings_.end())
8329 return p->second->resolve();
8330 else if (this->enclosing_ != NULL)
8331 return this->enclosing_->lookup(name);
8332 else
8333 return NULL;
8334 }
8335
8336 // Look up a symbol locally.
8337
8338 Named_object*
8339 Bindings::lookup_local(const std::string& name) const
8340 {
8341 Contour::const_iterator p = this->bindings_.find(name);
8342 if (p == this->bindings_.end())
8343 return NULL;
8344 return p->second;
8345 }
8346
8347 // Remove an object from a set of bindings. This is used for a
8348 // special case in thunks for functions which call recover.
8349
8350 void
8351 Bindings::remove_binding(Named_object* no)
8352 {
8353 Contour::iterator pb = this->bindings_.find(no->name());
8354 go_assert(pb != this->bindings_.end());
8355 this->bindings_.erase(pb);
8356 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
8357 pn != this->named_objects_.end();
8358 ++pn)
8359 {
8360 if (*pn == no)
8361 {
8362 this->named_objects_.erase(pn);
8363 return;
8364 }
8365 }
8366 go_unreachable();
8367 }
8368
8369 // Add a method to the list of objects. This is not added to the
8370 // lookup table. This is so that we have a single list of objects
8371 // declared at the top level, which we walk through when it's time to
8372 // convert to trees.
8373
8374 void
8375 Bindings::add_method(Named_object* method)
8376 {
8377 this->named_objects_.push_back(method);
8378 }
8379
8380 // Add a generic Named_object to a Contour.
8381
8382 Named_object*
8383 Bindings::add_named_object_to_contour(Contour* contour,
8384 Named_object* named_object)
8385 {
8386 go_assert(named_object == named_object->resolve());
8387 const std::string& name(named_object->name());
8388 go_assert(!Gogo::is_sink_name(name));
8389
8390 std::pair<Contour::iterator, bool> ins =
8391 contour->insert(std::make_pair(name, named_object));
8392 if (!ins.second)
8393 {
8394 // The name was already there.
8395 if (named_object->package() != NULL
8396 && ins.first->second->package() == named_object->package()
8397 && (ins.first->second->classification()
8398 == named_object->classification()))
8399 {
8400 // This is a second import of the same object.
8401 return ins.first->second;
8402 }
8403 ins.first->second = this->new_definition(ins.first->second,
8404 named_object);
8405 return ins.first->second;
8406 }
8407 else
8408 {
8409 // Don't push declarations on the list. We push them on when
8410 // and if we find the definitions. That way we genericize the
8411 // functions in order.
8412 if (!named_object->is_type_declaration()
8413 && !named_object->is_function_declaration()
8414 && !named_object->is_unknown())
8415 this->named_objects_.push_back(named_object);
8416 return named_object;
8417 }
8418 }
8419
8420 // We had an existing named object OLD_OBJECT, and we've seen a new
8421 // one NEW_OBJECT with the same name. FIXME: This does not free the
8422 // new object when we don't need it.
8423
8424 Named_object*
8425 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
8426 {
8427 if (new_object->is_erroneous() && !old_object->is_erroneous())
8428 return new_object;
8429
8430 std::string reason;
8431 switch (old_object->classification())
8432 {
8433 default:
8434 case Named_object::NAMED_OBJECT_UNINITIALIZED:
8435 go_unreachable();
8436
8437 case Named_object::NAMED_OBJECT_ERRONEOUS:
8438 return old_object;
8439
8440 case Named_object::NAMED_OBJECT_UNKNOWN:
8441 {
8442 Named_object* real = old_object->unknown_value()->real_named_object();
8443 if (real != NULL)
8444 return this->new_definition(real, new_object);
8445 go_assert(!new_object->is_unknown());
8446 old_object->unknown_value()->set_real_named_object(new_object);
8447 if (!new_object->is_type_declaration()
8448 && !new_object->is_function_declaration())
8449 this->named_objects_.push_back(new_object);
8450 return new_object;
8451 }
8452
8453 case Named_object::NAMED_OBJECT_CONST:
8454 break;
8455
8456 case Named_object::NAMED_OBJECT_TYPE:
8457 if (new_object->is_type_declaration())
8458 return old_object;
8459 break;
8460
8461 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8462 if (new_object->is_type_declaration())
8463 return old_object;
8464 if (new_object->is_type())
8465 {
8466 old_object->set_type_value(new_object->type_value());
8467 new_object->type_value()->set_named_object(old_object);
8468 this->named_objects_.push_back(old_object);
8469 return old_object;
8470 }
8471 break;
8472
8473 case Named_object::NAMED_OBJECT_VAR:
8474 case Named_object::NAMED_OBJECT_RESULT_VAR:
8475 // We have already given an error in the parser for cases where
8476 // one parameter or result variable redeclares another one.
8477 if ((new_object->is_variable()
8478 && new_object->var_value()->is_parameter())
8479 || new_object->is_result_variable())
8480 return old_object;
8481 break;
8482
8483 case Named_object::NAMED_OBJECT_SINK:
8484 go_unreachable();
8485
8486 case Named_object::NAMED_OBJECT_FUNC:
8487 break;
8488
8489 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8490 {
8491 // We declare the hash and equality functions before defining
8492 // them, because we sometimes see that we need the declaration
8493 // while we are in the middle of a different function.
8494 //
8495 // We declare the main function before the user defines it, to
8496 // give better error messages.
8497 //
8498 // We declare inline functions before we define them, as we
8499 // only define them if we need them.
8500 if (new_object->is_function()
8501 && ((Linemap::is_predeclared_location(old_object->location())
8502 && Linemap::is_predeclared_location(new_object->location()))
8503 || (Gogo::unpack_hidden_name(old_object->name()) == "main"
8504 && Linemap::is_unknown_location(old_object->location()))
8505 || (new_object->package() != NULL
8506 && old_object->func_declaration_value()->has_imported_body()
8507 && new_object->func_value()->is_inline_only())))
8508 {
8509 Function_type* old_type =
8510 old_object->func_declaration_value()->type();
8511 Function_type* new_type = new_object->func_value()->type();
8512 if (old_type->is_valid_redeclaration(new_type, &reason))
8513 {
8514 Function_declaration* fd =
8515 old_object->func_declaration_value();
8516 go_assert(fd->asm_name().empty());
8517 old_object->set_function_value(new_object->func_value());
8518 this->named_objects_.push_back(old_object);
8519 return old_object;
8520 }
8521 }
8522 }
8523 break;
8524
8525 case Named_object::NAMED_OBJECT_PACKAGE:
8526 break;
8527 }
8528
8529 std::string n = old_object->message_name();
8530 if (reason.empty())
8531 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
8532 else
8533 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
8534 reason.c_str());
8535 old_object->set_is_redefinition();
8536 new_object->set_is_redefinition();
8537
8538 if (!Linemap::is_unknown_location(old_object->location())
8539 && !Linemap::is_predeclared_location(old_object->location()))
8540 go_inform(old_object->location(), "previous definition of %qs was here",
8541 n.c_str());
8542
8543 return old_object;
8544 }
8545
8546 // Add a named type.
8547
8548 Named_object*
8549 Bindings::add_named_type(Named_type* named_type)
8550 {
8551 return this->add_named_object(named_type->named_object());
8552 }
8553
8554 // Add a function.
8555
8556 Named_object*
8557 Bindings::add_function(const std::string& name, const Package* package,
8558 Function* function)
8559 {
8560 return this->add_named_object(Named_object::make_function(name, package,
8561 function));
8562 }
8563
8564 // Add a function declaration.
8565
8566 Named_object*
8567 Bindings::add_function_declaration(const std::string& name,
8568 const Package* package,
8569 Function_type* type,
8570 Location location)
8571 {
8572 Named_object* no = Named_object::make_function_declaration(name, package,
8573 type, location);
8574 return this->add_named_object(no);
8575 }
8576
8577 // Define a type which was previously declared.
8578
8579 void
8580 Bindings::define_type(Named_object* no, Named_type* type)
8581 {
8582 no->set_type_value(type);
8583 this->named_objects_.push_back(no);
8584 }
8585
8586 // Mark all local variables as used. This is used for some types of
8587 // parse error.
8588
8589 void
8590 Bindings::mark_locals_used()
8591 {
8592 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
8593 p != this->named_objects_.end();
8594 ++p)
8595 if ((*p)->is_variable())
8596 (*p)->var_value()->set_is_used();
8597 }
8598
8599 // Traverse bindings.
8600
8601 int
8602 Bindings::traverse(Traverse* traverse, bool is_global)
8603 {
8604 unsigned int traverse_mask = traverse->traverse_mask();
8605
8606 // We don't use an iterator because we permit the traversal to add
8607 // new global objects.
8608 const unsigned int e_or_t = (Traverse::traverse_expressions
8609 | Traverse::traverse_types);
8610 const unsigned int e_or_t_or_s = (e_or_t
8611 | Traverse::traverse_statements);
8612 for (size_t i = 0; i < this->named_objects_.size(); ++i)
8613 {
8614 Named_object* p = this->named_objects_[i];
8615 int t = TRAVERSE_CONTINUE;
8616 switch (p->classification())
8617 {
8618 case Named_object::NAMED_OBJECT_CONST:
8619 if ((traverse_mask & Traverse::traverse_constants) != 0)
8620 t = traverse->constant(p, is_global);
8621 if (t == TRAVERSE_CONTINUE
8622 && (traverse_mask & e_or_t) != 0)
8623 {
8624 Type* tc = p->const_value()->type();
8625 if (tc != NULL
8626 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
8627 return TRAVERSE_EXIT;
8628 t = p->const_value()->traverse_expression(traverse);
8629 }
8630 break;
8631
8632 case Named_object::NAMED_OBJECT_VAR:
8633 case Named_object::NAMED_OBJECT_RESULT_VAR:
8634 if ((traverse_mask & Traverse::traverse_variables) != 0)
8635 t = traverse->variable(p);
8636 if (t == TRAVERSE_CONTINUE
8637 && (traverse_mask & e_or_t) != 0)
8638 {
8639 if (p->is_result_variable()
8640 || p->var_value()->has_type())
8641 {
8642 Type* tv = (p->is_variable()
8643 ? p->var_value()->type()
8644 : p->result_var_value()->type());
8645 if (tv != NULL
8646 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
8647 return TRAVERSE_EXIT;
8648 }
8649 }
8650 if (t == TRAVERSE_CONTINUE
8651 && (traverse_mask & e_or_t_or_s) != 0
8652 && p->is_variable())
8653 t = p->var_value()->traverse_expression(traverse, traverse_mask);
8654 break;
8655
8656 case Named_object::NAMED_OBJECT_FUNC:
8657 if ((traverse_mask & Traverse::traverse_functions) != 0)
8658 t = traverse->function(p);
8659
8660 if (t == TRAVERSE_CONTINUE
8661 && (traverse_mask
8662 & (Traverse::traverse_variables
8663 | Traverse::traverse_constants
8664 | Traverse::traverse_functions
8665 | Traverse::traverse_blocks
8666 | Traverse::traverse_statements
8667 | Traverse::traverse_expressions
8668 | Traverse::traverse_types)) != 0)
8669 t = p->func_value()->traverse(traverse);
8670 break;
8671
8672 case Named_object::NAMED_OBJECT_PACKAGE:
8673 // These are traversed in Gogo::traverse.
8674 go_assert(is_global);
8675 break;
8676
8677 case Named_object::NAMED_OBJECT_TYPE:
8678 if ((traverse_mask & e_or_t) != 0)
8679 t = Type::traverse(p->type_value(), traverse);
8680 break;
8681
8682 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
8683 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
8684 case Named_object::NAMED_OBJECT_UNKNOWN:
8685 case Named_object::NAMED_OBJECT_ERRONEOUS:
8686 break;
8687
8688 case Named_object::NAMED_OBJECT_SINK:
8689 default:
8690 go_unreachable();
8691 }
8692
8693 if (t == TRAVERSE_EXIT)
8694 return TRAVERSE_EXIT;
8695 }
8696
8697 // If we need to traverse types, check the function declarations,
8698 // which have types. Also check any methods of a type declaration.
8699 if ((traverse_mask & e_or_t) != 0)
8700 {
8701 for (Bindings::const_declarations_iterator p =
8702 this->begin_declarations();
8703 p != this->end_declarations();
8704 ++p)
8705 {
8706 if (p->second->is_function_declaration())
8707 {
8708 if (Type::traverse(p->second->func_declaration_value()->type(),
8709 traverse)
8710 == TRAVERSE_EXIT)
8711 return TRAVERSE_EXIT;
8712 }
8713 else if (p->second->is_type_declaration())
8714 {
8715 const std::vector<Named_object*>* methods =
8716 p->second->type_declaration_value()->methods();
8717 for (std::vector<Named_object*>::const_iterator pm =
8718 methods->begin();
8719 pm != methods->end();
8720 pm++)
8721 {
8722 Named_object* no = *pm;
8723 Type *t;
8724 if (no->is_function())
8725 t = no->func_value()->type();
8726 else if (no->is_function_declaration())
8727 t = no->func_declaration_value()->type();
8728 else
8729 continue;
8730 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
8731 return TRAVERSE_EXIT;
8732 }
8733 }
8734 }
8735 }
8736
8737 // Traverse function declarations when needed.
8738 if ((traverse_mask & Traverse::traverse_func_declarations) != 0)
8739 {
8740 for (Bindings::const_declarations_iterator p = this->begin_declarations();
8741 p != this->end_declarations();
8742 ++p)
8743 {
8744 if (p->second->is_function_declaration())
8745 {
8746 if (traverse->function_declaration(p->second) == TRAVERSE_EXIT)
8747 return TRAVERSE_EXIT;
8748 }
8749 }
8750 }
8751
8752 return TRAVERSE_CONTINUE;
8753 }
8754
8755 // Class Label.
8756
8757 // Clear any references to this label.
8758
8759 void
8760 Label::clear_refs()
8761 {
8762 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
8763 p != this->refs_.end();
8764 ++p)
8765 delete *p;
8766 this->refs_.clear();
8767 }
8768
8769 // Get the backend representation for a label.
8770
8771 Blabel*
8772 Label::get_backend_label(Translate_context* context)
8773 {
8774 if (this->blabel_ == NULL)
8775 {
8776 Function* function = context->function()->func_value();
8777 Bfunction* bfunction = function->get_decl();
8778 this->blabel_ = context->backend()->label(bfunction, this->name_,
8779 this->location_);
8780 }
8781 return this->blabel_;
8782 }
8783
8784 // Return an expression for the address of this label.
8785
8786 Bexpression*
8787 Label::get_addr(Translate_context* context, Location location)
8788 {
8789 Blabel* label = this->get_backend_label(context);
8790 return context->backend()->label_address(label, location);
8791 }
8792
8793 // Return the dummy label that represents any instance of the blank label.
8794
8795 Label*
8796 Label::create_dummy_label()
8797 {
8798 static Label* dummy_label;
8799 if (dummy_label == NULL)
8800 {
8801 dummy_label = new Label("_");
8802 dummy_label->set_is_used();
8803 }
8804 return dummy_label;
8805 }
8806
8807 // Class Unnamed_label.
8808
8809 // Get the backend representation for an unnamed label.
8810
8811 Blabel*
8812 Unnamed_label::get_blabel(Translate_context* context)
8813 {
8814 if (this->blabel_ == NULL)
8815 {
8816 Function* function = context->function()->func_value();
8817 Bfunction* bfunction = function->get_decl();
8818 this->blabel_ = context->backend()->label(bfunction, "",
8819 this->location_);
8820 }
8821 return this->blabel_;
8822 }
8823
8824 // Return a statement which defines this unnamed label.
8825
8826 Bstatement*
8827 Unnamed_label::get_definition(Translate_context* context)
8828 {
8829 Blabel* blabel = this->get_blabel(context);
8830 return context->backend()->label_definition_statement(blabel);
8831 }
8832
8833 // Return a goto statement to this unnamed label.
8834
8835 Bstatement*
8836 Unnamed_label::get_goto(Translate_context* context, Location location)
8837 {
8838 Blabel* blabel = this->get_blabel(context);
8839 return context->backend()->goto_statement(blabel, location);
8840 }
8841
8842 // Class Package.
8843
8844 Package::Package(const std::string& pkgpath,
8845 const std::string& pkgpath_symbol, Location location)
8846 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
8847 package_name_(), bindings_(new Bindings(NULL)),
8848 location_(location)
8849 {
8850 go_assert(!pkgpath.empty());
8851 }
8852
8853 // Set the package name.
8854
8855 void
8856 Package::set_package_name(const std::string& package_name, Location location)
8857 {
8858 go_assert(!package_name.empty());
8859 if (this->package_name_.empty())
8860 this->package_name_ = package_name;
8861 else if (this->package_name_ != package_name)
8862 go_error_at(location,
8863 ("saw two different packages with "
8864 "the same package path %s: %s, %s"),
8865 this->pkgpath_.c_str(), this->package_name_.c_str(),
8866 package_name.c_str());
8867 }
8868
8869 // Return the pkgpath symbol, which is a prefix for symbols defined in
8870 // this package.
8871
8872 std::string
8873 Package::pkgpath_symbol() const
8874 {
8875 if (this->pkgpath_symbol_.empty())
8876 return Gogo::pkgpath_for_symbol(this->pkgpath_);
8877 return this->pkgpath_symbol_;
8878 }
8879
8880 // Set the package path symbol.
8881
8882 void
8883 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8884 {
8885 go_assert(!pkgpath_symbol.empty());
8886 if (this->pkgpath_symbol_.empty())
8887 this->pkgpath_symbol_ = pkgpath_symbol;
8888 else
8889 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8890 }
8891
8892 // Note that symbol from this package was and qualified by ALIAS.
8893
8894 void
8895 Package::note_usage(const std::string& alias) const
8896 {
8897 Aliases::const_iterator p = this->aliases_.find(alias);
8898 go_assert(p != this->aliases_.end());
8899 p->second->note_usage();
8900 }
8901
8902 // Forget a given usage. If forgetting this usage means this package becomes
8903 // unused, report that error.
8904
8905 void
8906 Package::forget_usage(Expression* usage) const
8907 {
8908 if (this->fake_uses_.empty())
8909 return;
8910
8911 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8912 go_assert(p != this->fake_uses_.end());
8913 this->fake_uses_.erase(p);
8914
8915 if (this->fake_uses_.empty())
8916 go_error_at(this->location(), "imported and not used: %s",
8917 Gogo::message_name(this->package_name()).c_str());
8918 }
8919
8920 // Clear the used field for the next file. If the only usages of this package
8921 // are possibly fake, keep the fake usages for lowering.
8922
8923 void
8924 Package::clear_used()
8925 {
8926 std::string dot_alias = "." + this->package_name();
8927 Aliases::const_iterator p = this->aliases_.find(dot_alias);
8928 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8929 this->fake_uses_.clear();
8930
8931 this->aliases_.clear();
8932 }
8933
8934 Package_alias*
8935 Package::add_alias(const std::string& alias, Location location)
8936 {
8937 Aliases::const_iterator p = this->aliases_.find(alias);
8938 if (p == this->aliases_.end())
8939 {
8940 std::pair<Aliases::iterator, bool> ret;
8941 ret = this->aliases_.insert(std::make_pair(alias,
8942 new Package_alias(location)));
8943 p = ret.first;
8944 }
8945 return p->second;
8946 }
8947
8948 // Determine types of constants. Everything else in a package
8949 // (variables, function declarations) should already have a fixed
8950 // type. Constants may have abstract types.
8951
8952 void
8953 Package::determine_types()
8954 {
8955 Bindings* bindings = this->bindings_;
8956 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8957 p != bindings->end_definitions();
8958 ++p)
8959 {
8960 if ((*p)->is_const())
8961 (*p)->const_value()->determine_type();
8962 }
8963 }
8964
8965 // Class Traverse.
8966
8967 // Destructor.
8968
8969 Traverse::~Traverse()
8970 {
8971 if (this->types_seen_ != NULL)
8972 delete this->types_seen_;
8973 if (this->expressions_seen_ != NULL)
8974 delete this->expressions_seen_;
8975 }
8976
8977 // Record that we are looking at a type, and return true if we have
8978 // already seen it.
8979
8980 bool
8981 Traverse::remember_type(const Type* type)
8982 {
8983 if (type->is_error_type())
8984 return true;
8985 go_assert((this->traverse_mask() & traverse_types) != 0
8986 || (this->traverse_mask() & traverse_expressions) != 0);
8987 // We mostly only have to remember named types. But it turns out
8988 // that an interface type can refer to itself without using a name
8989 // by relying on interface inheritance, as in
8990 //
8991 // type I interface { F() interface{I} }
8992 //
8993 // Similarly it is possible for array types to refer to themselves
8994 // without a name, e.g.
8995 //
8996 // var x [uintptr(unsafe.Sizeof(&x))]byte
8997 //
8998 if (type->classification() != Type::TYPE_NAMED
8999 && type->classification() != Type::TYPE_ARRAY
9000 && type->classification() != Type::TYPE_INTERFACE)
9001 return false;
9002 if (this->types_seen_ == NULL)
9003 this->types_seen_ = new Types_seen();
9004 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
9005 return !ins.second;
9006 }
9007
9008 // Record that we are looking at an expression, and return true if we
9009 // have already seen it. NB: this routine used to assert if the traverse
9010 // mask did not include expressions/types -- this is no longer the case,
9011 // since it can be useful to remember specific expressions during
9012 // walks that only cover statements.
9013
9014 bool
9015 Traverse::remember_expression(const Expression* expression)
9016 {
9017 if (this->expressions_seen_ == NULL)
9018 this->expressions_seen_ = new Expressions_seen();
9019 std::pair<Expressions_seen::iterator, bool> ins =
9020 this->expressions_seen_->insert(expression);
9021 return !ins.second;
9022 }
9023
9024 // The default versions of these functions should never be called: the
9025 // traversal mask indicates which functions may be called.
9026
9027 int
9028 Traverse::variable(Named_object*)
9029 {
9030 go_unreachable();
9031 }
9032
9033 int
9034 Traverse::constant(Named_object*, bool)
9035 {
9036 go_unreachable();
9037 }
9038
9039 int
9040 Traverse::function(Named_object*)
9041 {
9042 go_unreachable();
9043 }
9044
9045 int
9046 Traverse::block(Block*)
9047 {
9048 go_unreachable();
9049 }
9050
9051 int
9052 Traverse::statement(Block*, size_t*, Statement*)
9053 {
9054 go_unreachable();
9055 }
9056
9057 int
9058 Traverse::expression(Expression**)
9059 {
9060 go_unreachable();
9061 }
9062
9063 int
9064 Traverse::type(Type*)
9065 {
9066 go_unreachable();
9067 }
9068
9069 int
9070 Traverse::function_declaration(Named_object*)
9071 {
9072 go_unreachable();
9073 }
9074
9075 // Class Statement_inserter.
9076
9077 void
9078 Statement_inserter::insert(Statement* s)
9079 {
9080 if (this->statements_added_ != NULL)
9081 this->statements_added_->insert(s);
9082
9083 if (this->block_ != NULL)
9084 {
9085 go_assert(this->pindex_ != NULL);
9086 this->block_->insert_statement_before(*this->pindex_, s);
9087 ++*this->pindex_;
9088 }
9089 else if (this->var_ != NULL)
9090 this->var_->add_preinit_statement(this->gogo_, s);
9091 else
9092 go_assert(saw_errors());
9093 }