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