OSDN Git Service

compiler: Add -fgo-relative-import-path.
[pf3gnuchains/gcc-fork.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 =