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