OSDN Git Service

compiler: Handle recursive interfaces.
[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 "go-c.h"
10 #include "go-dump.h"
11 #include "lex.h"
12 #include "types.h"
13 #include "statements.h"
14 #include "expressions.h"
15 #include "dataflow.h"
16 #include "runtime.h"
17 #include "import.h"
18 #include "export.h"
19 #include "backend.h"
20 #include "gogo.h"
21
22 // Class Gogo.
23
24 Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
25            int pointer_size)
26   : backend_(backend),
27     linemap_(linemap),
28     package_(NULL),
29     functions_(),
30     globals_(new Bindings(NULL)),
31     imports_(),
32     imported_unsafe_(false),
33     packages_(),
34     init_functions_(),
35     need_init_fn_(false),
36     init_fn_name_(),
37     imported_init_fns_(),
38     unique_prefix_(),
39     unique_prefix_specified_(false),
40     interface_types_(),
41     specific_type_functions_(),
42     specific_type_functions_are_written_(false),
43     named_types_are_converted_(false)
44 {
45   const Location loc = Linemap::predeclared_location();
46
47   Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
48                                                    RUNTIME_TYPE_KIND_UINT8);
49   this->add_named_type(uint8_type);
50   this->add_named_type(Type::make_integer_type("uint16", true,  16,
51                                                RUNTIME_TYPE_KIND_UINT16));
52   this->add_named_type(Type::make_integer_type("uint32", true,  32,
53                                                RUNTIME_TYPE_KIND_UINT32));
54   this->add_named_type(Type::make_integer_type("uint64", true,  64,
55                                                RUNTIME_TYPE_KIND_UINT64));
56
57   this->add_named_type(Type::make_integer_type("int8",  false,   8,
58                                                RUNTIME_TYPE_KIND_INT8));
59   this->add_named_type(Type::make_integer_type("int16", false,  16,
60                                                RUNTIME_TYPE_KIND_INT16));
61   this->add_named_type(Type::make_integer_type("int32", false,  32,
62                                                RUNTIME_TYPE_KIND_INT32));
63   this->add_named_type(Type::make_integer_type("int64", false,  64,
64                                                RUNTIME_TYPE_KIND_INT64));
65
66   this->add_named_type(Type::make_float_type("float32", 32,
67                                              RUNTIME_TYPE_KIND_FLOAT32));
68   this->add_named_type(Type::make_float_type("float64", 64,
69                                              RUNTIME_TYPE_KIND_FLOAT64));
70
71   this->add_named_type(Type::make_complex_type("complex64", 64,
72                                                RUNTIME_TYPE_KIND_COMPLEX64));
73   this->add_named_type(Type::make_complex_type("complex128", 128,
74                                                RUNTIME_TYPE_KIND_COMPLEX128));
75
76   if (int_type_size < 32)
77     int_type_size = 32;
78   this->add_named_type(Type::make_integer_type("uint", true,
79                                                int_type_size,
80                                                RUNTIME_TYPE_KIND_UINT));
81   Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
82                                                  RUNTIME_TYPE_KIND_INT);
83   this->add_named_type(int_type);
84
85   // "byte" is an alias for "uint8".  Construct a Named_object which
86   // points to UINT8_TYPE.  Note that this breaks the normal pairing
87   // in which a Named_object points to a Named_type which points back
88   // to the same Named_object.
89   Named_object* byte_type = this->declare_type("byte", loc);
90   byte_type->set_type_value(uint8_type);
91   uint8_type->integer_type()->set_is_byte();
92
93   // "rune" is an alias for "int".
94   Named_object* rune_type = this->declare_type("rune", loc);
95   rune_type->set_type_value(int_type);
96   int_type->integer_type()->set_is_rune();
97
98   this->add_named_type(Type::make_integer_type("uintptr", true,
99                                                pointer_size,
100                                                RUNTIME_TYPE_KIND_UINTPTR));
101
102   this->add_named_type(Type::make_named_bool_type());
103
104   this->add_named_type(Type::make_named_string_type());
105
106   // "error" is interface { Error() string }.
107   {
108     Typed_identifier_list *methods = new Typed_identifier_list;
109     Typed_identifier_list *results = new Typed_identifier_list;
110     results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
111     Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
112     methods->push_back(Typed_identifier("Error", method_type, loc));
113     Interface_type *error_iface = Type::make_interface_type(methods, loc);
114     error_iface->finalize_methods();
115     Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
116     this->add_named_type(error_type);
117   }
118
119   this->globals_->add_constant(Typed_identifier("true",
120                                                 Type::make_boolean_type(),
121                                                 loc),
122                                NULL,
123                                Expression::make_boolean(true, loc),
124                                0);
125   this->globals_->add_constant(Typed_identifier("false",
126                                                 Type::make_boolean_type(),
127                                                 loc),
128                                NULL,
129                                Expression::make_boolean(false, loc),
130                                0);
131
132   this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
133                                                 loc),
134                                NULL,
135                                Expression::make_nil(loc),
136                                0);
137
138   Type* abstract_int_type = Type::make_abstract_integer_type();
139   this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
140                                                 loc),
141                                NULL,
142                                Expression::make_iota(),
143                                0);
144
145   Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
146   new_type->set_is_varargs();
147   new_type->set_is_builtin();
148   this->globals_->add_function_declaration("new", NULL, new_type, loc);
149
150   Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
151   make_type->set_is_varargs();
152   make_type->set_is_builtin();
153   this->globals_->add_function_declaration("make", NULL, make_type, loc);
154
155   Typed_identifier_list* len_result = new Typed_identifier_list();
156   len_result->push_back(Typed_identifier("", int_type, loc));
157   Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
158                                                      loc);
159   len_type->set_is_builtin();
160   this->globals_->add_function_declaration("len", NULL, len_type, loc);
161
162   Typed_identifier_list* cap_result = new Typed_identifier_list();
163   cap_result->push_back(Typed_identifier("", int_type, loc));
164   Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
165                                                      loc);
166   cap_type->set_is_builtin();
167   this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
168
169   Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
170   print_type->set_is_varargs();
171   print_type->set_is_builtin();
172   this->globals_->add_function_declaration("print", NULL, print_type, loc);
173
174   print_type = Type::make_function_type(NULL, NULL, NULL, loc);
175   print_type->set_is_varargs();
176   print_type->set_is_builtin();
177   this->globals_->add_function_declaration("println", NULL, print_type, loc);
178
179   Type *empty = Type::make_empty_interface_type(loc);
180   Typed_identifier_list* panic_parms = new Typed_identifier_list();
181   panic_parms->push_back(Typed_identifier("e", empty, loc));
182   Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
183                                                        NULL, loc);
184   panic_type->set_is_builtin();
185   this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
186
187   Typed_identifier_list* recover_result = new Typed_identifier_list();
188   recover_result->push_back(Typed_identifier("", empty, loc));
189   Function_type* recover_type = Type::make_function_type(NULL, NULL,
190                                                          recover_result,
191                                                          loc);
192   recover_type->set_is_builtin();
193   this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
194
195   Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
196   close_type->set_is_varargs();
197   close_type->set_is_builtin();
198   this->globals_->add_function_declaration("close", NULL, close_type, loc);
199
200   Typed_identifier_list* copy_result = new Typed_identifier_list();
201   copy_result->push_back(Typed_identifier("", int_type, loc));
202   Function_type* copy_type = Type::make_function_type(NULL, NULL,
203                                                       copy_result, loc);
204   copy_type->set_is_varargs();
205   copy_type->set_is_builtin();
206   this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
207
208   Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
209   append_type->set_is_varargs();
210   append_type->set_is_builtin();
211   this->globals_->add_function_declaration("append", NULL, append_type, loc);
212
213   Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
214   complex_type->set_is_varargs();
215   complex_type->set_is_builtin();
216   this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
217
218   Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
219   real_type->set_is_varargs();
220   real_type->set_is_builtin();
221   this->globals_->add_function_declaration("real", NULL, real_type, loc);
222
223   Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
224   imag_type->set_is_varargs();
225   imag_type->set_is_builtin();
226   this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
227
228   Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
229   delete_type->set_is_varargs();
230   delete_type->set_is_builtin();
231   this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
232 }
233
234 // Munge name for use in an error message.
235
236 std::string
237 Gogo::message_name(const std::string& name)
238 {
239   return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
240 }
241
242 // Get the package name.
243
244 const std::string&
245 Gogo::package_name() const
246 {
247   go_assert(this->package_ != NULL);
248   return this->package_->name();
249 }
250
251 // Set the package name.
252
253 void
254 Gogo::set_package_name(const std::string& package_name,
255                        Location location)
256 {
257   if (this->package_ != NULL && this->package_->name() != package_name)
258     {
259       error_at(location, "expected package %<%s%>",
260                Gogo::message_name(this->package_->name()).c_str());
261       return;
262     }
263
264   // If the user did not specify a unique prefix, we always use "go".
265   // This in effect requires that the package name be unique.
266   if (this->unique_prefix_.empty())
267     this->unique_prefix_ = "go";
268
269   this->package_ = this->register_package(package_name, this->unique_prefix_,
270                                           location);
271
272   // We used to permit people to qualify symbols with the current
273   // package name (e.g., P.x), but we no longer do.
274   // this->globals_->add_package(package_name, this->package_);
275
276   if (this->is_main_package())
277     {
278       // Declare "main" as a function which takes no parameters and
279       // returns no value.
280       Location uloc = Linemap::unknown_location();
281       this->declare_function("main",
282                              Type::make_function_type (NULL, NULL, NULL, uloc),
283                              uloc);
284     }
285 }
286
287 // Return whether this is the "main" package.  This is not true if
288 // -fgo-prefix was used.
289
290 bool
291 Gogo::is_main_package() const
292 {
293   return this->package_name() == "main" && !this->unique_prefix_specified_;
294 }
295
296 // Import a package.
297
298 void
299 Gogo::import_package(const std::string& filename,
300                      const std::string& local_name,
301                      bool is_local_name_exported,
302                      Location location)
303 {
304   if (filename == "unsafe")
305     {
306       this->import_unsafe(local_name, is_local_name_exported, location);
307       return;
308     }
309
310   Imports::const_iterator p = this->imports_.find(filename);
311   if (p != this->imports_.end())
312     {
313       Package* package = p->second;
314       package->set_location(location);
315       package->set_is_imported();
316       std::string ln = local_name;
317       bool is_ln_exported = is_local_name_exported;
318       if (ln.empty())
319         {
320           ln = package->name();
321           is_ln_exported = Lex::is_exported_name(ln);
322         }
323       if (ln == ".")
324         {
325           Bindings* bindings = package->bindings();
326           for (Bindings::const_declarations_iterator p =
327                  bindings->begin_declarations();
328                p != bindings->end_declarations();
329                ++p)
330             this->add_named_object(p->second);
331         }
332       else if (ln == "_")
333         package->set_uses_sink_alias();
334       else
335         {
336           ln = this->pack_hidden_name(ln, is_ln_exported);
337           this->package_->bindings()->add_package(ln, package);
338         }
339       return;
340     }
341
342   Import::Stream* stream = Import::open_package(filename, location);
343   if (stream == NULL)
344     {
345       error_at(location, "import file %qs not found", filename.c_str());
346       return;
347     }
348
349   Import imp(stream, location);
350   imp.register_builtin_types(this);
351   Package* package = imp.import(this, local_name, is_local_name_exported);
352   if (package != NULL)
353     {
354       if (package->name() == this->package_name()
355           && package->unique_prefix() == this->unique_prefix())
356         error_at(location,
357                  ("imported package uses same package name and prefix "
358                   "as package being compiled (see -fgo-prefix option)"));
359
360       this->imports_.insert(std::make_pair(filename, package));
361       package->set_is_imported();
362     }
363
364   delete stream;
365 }
366
367 // Add an import control function for an imported package to the list.
368
369 void
370 Gogo::add_import_init_fn(const std::string& package_name,
371                          const std::string& init_name, int prio)
372 {
373   for (std::set<Import_init>::const_iterator p =
374          this->imported_init_fns_.begin();
375        p != this->imported_init_fns_.end();
376        ++p)
377     {
378       if (p->init_name() == init_name
379           && (p->package_name() != package_name || p->priority() != prio))
380         {
381           error("duplicate package initialization name %qs",
382                 Gogo::message_name(init_name).c_str());
383           inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
384                  Gogo::message_name(p->package_name()).c_str(),
385                  p->priority());
386           inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
387                  Gogo::message_name(package_name).c_str(), prio);
388           return;
389         }
390     }
391
392   this->imported_init_fns_.insert(Import_init(package_name, init_name,
393                                               prio));
394 }
395
396 // Return whether we are at the global binding level.
397
398 bool
399 Gogo::in_global_scope() const
400 {
401   return this->functions_.empty();
402 }
403
404 // Return the current binding contour.
405
406 Bindings*
407 Gogo::current_bindings()
408 {
409   if (!this->functions_.empty())
410     return this->functions_.back().blocks.back()->bindings();
411   else if (this->package_ != NULL)
412     return this->package_->bindings();
413   else
414     return this->globals_;
415 }
416
417 const Bindings*
418 Gogo::current_bindings() const
419 {
420   if (!this->functions_.empty())
421     return this->functions_.back().blocks.back()->bindings();
422   else if (this->package_ != NULL)
423     return this->package_->bindings();
424   else
425     return this->globals_;
426 }
427
428 // Return the current block.
429
430 Block*
431 Gogo::current_block()
432 {
433   if (this->functions_.empty())
434     return NULL;
435   else
436     return this->functions_.back().blocks.back();
437 }
438
439 // Look up a name in the current binding contour.  If PFUNCTION is not
440 // NULL, set it to the function in which the name is defined, or NULL
441 // if the name is defined in global scope.
442
443 Named_object*
444 Gogo::lookup(const std::string& name, Named_object** pfunction) const
445 {
446   if (pfunction != NULL)
447     *pfunction = NULL;
448
449   if (Gogo::is_sink_name(name))
450     return Named_object::make_sink();
451
452   for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
453        p != this->functions_.rend();
454        ++p)
455     {
456       Named_object* ret = p->blocks.back()->bindings()->lookup(name);
457       if (ret != NULL)
458         {
459           if (pfunction != NULL)
460             *pfunction = p->function;
461           return ret;
462         }
463     }
464
465   if (this->package_ != NULL)
466     {
467       Named_object* ret = this->package_->bindings()->lookup(name);
468       if (ret != NULL)
469         {
470           if (ret->package() != NULL)
471             ret->package()->set_used();
472           return ret;
473         }
474     }
475
476   // We do not look in the global namespace.  If we did, the global
477   // namespace would effectively hide names which were defined in
478   // package scope which we have not yet seen.  Instead,
479   // define_global_names is called after parsing is over to connect
480   // undefined names at package scope with names defined at global
481   // scope.
482
483   return NULL;
484 }
485
486 // Look up a name in the current block, without searching enclosing
487 // blocks.
488
489 Named_object*
490 Gogo::lookup_in_block(const std::string& name) const
491 {
492   go_assert(!this->functions_.empty());
493   go_assert(!this->functions_.back().blocks.empty());
494   return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
495 }
496
497 // Look up a name in the global namespace.
498
499 Named_object*
500 Gogo::lookup_global(const char* name) const
501 {
502   return this->globals_->lookup(name);
503 }
504
505 // Add an imported package.
506
507 Package*
508 Gogo::add_imported_package(const std::string& real_name,
509                            const std::string& alias_arg,
510                            bool is_alias_exported,
511                            const std::string& unique_prefix,
512                            Location location,
513                            bool* padd_to_globals)
514 {
515   // FIXME: Now that we compile packages as a whole, should we permit
516   // importing the current package?
517   if (this->package_name() == real_name
518       && this->unique_prefix() == unique_prefix)
519     {
520       *padd_to_globals = false;
521       if (!alias_arg.empty() && alias_arg != ".")
522         {
523           std::string alias = this->pack_hidden_name(alias_arg,
524                                                      is_alias_exported);
525           this->package_->bindings()->add_package(alias, this->package_);
526         }
527       return this->package_;
528     }
529   else if (alias_arg == ".")
530     {
531       *padd_to_globals = true;
532       return this->register_package(real_name, unique_prefix, location);
533     }
534   else if (alias_arg == "_")
535     {
536       Package* ret = this->register_package(real_name, unique_prefix, location);
537       ret->set_uses_sink_alias();
538       return ret;
539     }
540   else
541     {
542       *padd_to_globals = false;
543       std::string alias = alias_arg;
544       if (alias.empty())
545         {
546           alias = real_name;
547           is_alias_exported = Lex::is_exported_name(alias);
548         }
549       alias = this->pack_hidden_name(alias, is_alias_exported);
550       Named_object* no = this->add_package(real_name, alias, unique_prefix,
551                                            location);
552       if (!no->is_package())
553         return NULL;
554       return no->package_value();
555     }
556 }
557
558 // Add a package.
559
560 Named_object*
561 Gogo::add_package(const std::string& real_name, const std::string& alias,
562                   const std::string& unique_prefix, Location location)
563 {
564   go_assert(this->in_global_scope());
565
566   // Register the package.  Note that we might have already seen it in
567   // an earlier import.
568   Package* package = this->register_package(real_name, unique_prefix, location);
569
570   return this->package_->bindings()->add_package(alias, package);
571 }
572
573 // Register a package.  This package may or may not be imported.  This
574 // returns the Package structure for the package, creating if it
575 // necessary.
576
577 Package*
578 Gogo::register_package(const std::string& package_name,
579                        const std::string& unique_prefix,
580                        Location location)
581 {
582   go_assert(!unique_prefix.empty() && !package_name.empty());
583   std::string name = unique_prefix + '.' + package_name;
584   Package* package = NULL;
585   std::pair<Packages::iterator, bool> ins =
586     this->packages_.insert(std::make_pair(name, package));
587   if (!ins.second)
588     {
589       // We have seen this package name before.
590       package = ins.first->second;
591       go_assert(package != NULL);
592       go_assert(package->name() == package_name
593                  && package->unique_prefix() == unique_prefix);
594       if (Linemap::is_unknown_location(package->location()))
595         package->set_location(location);
596     }
597   else
598     {
599       // First time we have seen this package name.
600       package = new Package(package_name, unique_prefix, location);
601       go_assert(ins.first->second == NULL);
602       ins.first->second = package;
603     }
604
605   return package;
606 }
607
608 // Start compiling a function.
609
610 Named_object*
611 Gogo::start_function(const std::string& name, Function_type* type,
612                      bool add_method_to_type, Location location)
613 {
614   bool at_top_level = this->functions_.empty();
615
616   Block* block = new Block(NULL, location);
617
618   Function* enclosing = (at_top_level
619                          ? NULL
620                          : this->functions_.back().function->func_value());
621
622   Function* function = new Function(type, enclosing, block, location);
623
624   if (type->is_method())
625     {
626       const Typed_identifier* receiver = type->receiver();
627       Variable* this_param = new Variable(receiver->type(), NULL, false,
628                                           true, true, location);
629       std::string name = receiver->name();
630       if (name.empty())
631         {
632           // We need to give receivers a name since they wind up in
633           // DECL_ARGUMENTS.  FIXME.
634           static unsigned int count;
635           char buf[50];
636           snprintf(buf, sizeof buf, "r.%u", count);
637           ++count;
638           name = buf;
639         }
640       block->bindings()->add_variable(name, NULL, this_param);
641     }
642
643   const Typed_identifier_list* parameters = type->parameters();
644   bool is_varargs = type->is_varargs();
645   if (parameters != NULL)
646     {
647       for (Typed_identifier_list::const_iterator p = parameters->begin();
648            p != parameters->end();
649            ++p)
650         {
651           Variable* param = new Variable(p->type(), NULL, false, true, false,
652                                          location);
653           if (is_varargs && p + 1 == parameters->end())
654             param->set_is_varargs_parameter();
655
656           std::string name = p->name();
657           if (name.empty() || Gogo::is_sink_name(name))
658             {
659               // We need to give parameters a name since they wind up
660               // in DECL_ARGUMENTS.  FIXME.
661               static unsigned int count;
662               char buf[50];
663               snprintf(buf, sizeof buf, "p.%u", count);
664               ++count;
665               name = buf;
666             }
667           block->bindings()->add_variable(name, NULL, param);
668         }
669     }
670
671   function->create_result_variables(this);
672
673   const std::string* pname;
674   std::string nested_name;
675   bool is_init = false;
676   if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
677     {
678       if ((type->parameters() != NULL && !type->parameters()->empty())
679           || (type->results() != NULL && !type->results()->empty()))
680         error_at(location,
681                  "func init must have no arguments and no return values");
682       // There can be multiple "init" functions, so give them each a
683       // different name.
684       static int init_count;
685       char buf[30];
686       snprintf(buf, sizeof buf, ".$init%d", init_count);
687       ++init_count;
688       nested_name = buf;
689       pname = &nested_name;
690       is_init = true;
691     }
692   else if (!name.empty())
693     pname = &name;
694   else
695     {
696       // Invent a name for a nested function.
697       static int nested_count;
698       char buf[30];
699       snprintf(buf, sizeof buf, ".$nested%d", nested_count);
700       ++nested_count;
701       nested_name = buf;
702       pname = &nested_name;
703     }
704
705   Named_object* ret;
706   if (Gogo::is_sink_name(*pname))
707     {
708       static int sink_count;
709       char buf[30];
710       snprintf(buf, sizeof buf, ".$sink%d", sink_count);
711       ++sink_count;
712       ret = Named_object::make_function(buf, NULL, function);
713     }
714   else if (!type->is_method())
715     {
716       ret = this->package_->bindings()->add_function(*pname, NULL, function);
717       if (!ret->is_function() || ret->func_value() != function)
718         {
719           // Redefinition error.  Invent a name to avoid knockon
720           // errors.
721           static int redefinition_count;
722           char buf[30];
723           snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
724           ++redefinition_count;
725           ret = this->package_->bindings()->add_function(buf, NULL, function);
726         }
727     }
728   else
729     {
730       if (!add_method_to_type)
731         ret = Named_object::make_function(name, NULL, function);
732       else
733         {
734           go_assert(at_top_level);
735           Type* rtype = type->receiver()->type();
736
737           // We want to look through the pointer created by the
738           // parser, without getting an error if the type is not yet
739           // defined.
740           if (rtype->classification() == Type::TYPE_POINTER)
741             rtype = rtype->points_to();
742
743           if (rtype->is_error_type())
744             ret = Named_object::make_function(name, NULL, function);
745           else if (rtype->named_type() != NULL)
746             {
747               ret = rtype->named_type()->add_method(name, function);
748               if (!ret->is_function())
749                 {
750                   // Redefinition error.
751                   ret = Named_object::make_function(name, NULL, function);
752                 }
753             }
754           else if (rtype->forward_declaration_type() != NULL)
755             {
756               Named_object* type_no =
757                 rtype->forward_declaration_type()->named_object();
758               if (type_no->is_unknown())
759                 {
760                   // If we are seeing methods it really must be a
761                   // type.  Declare it as such.  An alternative would
762                   // be to support lists of methods for unknown
763                   // expressions.  Either way the error messages if
764                   // this is not a type are going to get confusing.
765                   Named_object* declared =
766                     this->declare_package_type(type_no->name(),
767                                                type_no->location());
768                   go_assert(declared
769                              == type_no->unknown_value()->real_named_object());
770                 }
771               ret = rtype->forward_declaration_type()->add_method(name,
772                                                                   function);
773             }
774           else
775             go_unreachable();
776         }
777       this->package_->bindings()->add_method(ret);
778     }
779
780   this->functions_.resize(this->functions_.size() + 1);
781   Open_function& of(this->functions_.back());
782   of.function = ret;
783   of.blocks.push_back(block);
784
785   if (is_init)
786     {
787       this->init_functions_.push_back(ret);
788       this->need_init_fn_ = true;
789     }
790
791   return ret;
792 }
793
794 // Finish compiling a function.
795
796 void
797 Gogo::finish_function(Location location)
798 {
799   this->finish_block(location);
800   go_assert(this->functions_.back().blocks.empty());
801   this->functions_.pop_back();
802 }
803
804 // Return the current function.
805
806 Named_object*
807 Gogo::current_function() const
808 {
809   go_assert(!this->functions_.empty());
810   return this->functions_.back().function;
811 }
812
813 // Start a new block.
814
815 void
816 Gogo::start_block(Location location)
817 {
818   go_assert(!this->functions_.empty());
819   Block* block = new Block(this->current_block(), location);
820   this->functions_.back().blocks.push_back(block);
821 }
822
823 // Finish a block.
824
825 Block*
826 Gogo::finish_block(Location location)
827 {
828   go_assert(!this->functions_.empty());
829   go_assert(!this->functions_.back().blocks.empty());
830   Block* block = this->functions_.back().blocks.back();
831   this->functions_.back().blocks.pop_back();
832   block->set_end_location(location);
833   return block;
834 }
835
836 // Add an unknown name.
837
838 Named_object*
839 Gogo::add_unknown_name(const std::string& name, Location location)
840 {
841   return this->package_->bindings()->add_unknown_name(name, location);
842 }
843
844 // Declare a function.
845
846 Named_object*
847 Gogo::declare_function(const std::string& name, Function_type* type,
848                        Location location)
849 {
850   if (!type->is_method())
851     return this->current_bindings()->add_function_declaration(name, NULL, type,
852                                                               location);
853   else
854     {
855       // We don't bother to add this to the list of global
856       // declarations.
857       Type* rtype = type->receiver()->type();
858
859       // We want to look through the pointer created by the
860       // parser, without getting an error if the type is not yet
861       // defined.
862       if (rtype->classification() == Type::TYPE_POINTER)
863         rtype = rtype->points_to();
864
865       if (rtype->is_error_type())
866         return NULL;
867       else if (rtype->named_type() != NULL)
868         return rtype->named_type()->add_method_declaration(name, NULL, type,
869                                                            location);
870       else if (rtype->forward_declaration_type() != NULL)
871         {
872           Forward_declaration_type* ftype = rtype->forward_declaration_type();
873           return ftype->add_method_declaration(name, type, location);
874         }
875       else
876         go_unreachable();
877     }
878 }
879
880 // Add a label definition.
881
882 Label*
883 Gogo::add_label_definition(const std::string& label_name,
884                            Location location)
885 {
886   go_assert(!this->functions_.empty());
887   Function* func = this->functions_.back().function->func_value();
888   Label* label = func->add_label_definition(this, label_name, location);
889   this->add_statement(Statement::make_label_statement(label, location));
890   return label;
891 }
892
893 // Add a label reference.
894
895 Label*
896 Gogo::add_label_reference(const std::string& label_name,
897                           Location location, bool issue_goto_errors)
898 {
899   go_assert(!this->functions_.empty());
900   Function* func = this->functions_.back().function->func_value();
901   return func->add_label_reference(this, label_name, location,
902                                    issue_goto_errors);
903 }
904
905 // Return the current binding state.
906
907 Bindings_snapshot*
908 Gogo::bindings_snapshot(Location location)
909 {
910   return new Bindings_snapshot(this->current_block(), location);
911 }
912
913 // Add a statement.
914
915 void
916 Gogo::add_statement(Statement* statement)
917 {
918   go_assert(!this->functions_.empty()
919              && !this->functions_.back().blocks.empty());
920   this->functions_.back().blocks.back()->add_statement(statement);
921 }
922
923 // Add a block.
924
925 void
926 Gogo::add_block(Block* block, Location location)
927 {
928   go_assert(!this->functions_.empty()
929              && !this->functions_.back().blocks.empty());
930   Statement* statement = Statement::make_block_statement(block, location);
931   this->functions_.back().blocks.back()->add_statement(statement);
932 }
933
934 // Add a constant.
935
936 Named_object*
937 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
938                    int iota_value)
939 {
940   return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
941 }
942
943 // Add a type.
944
945 void
946 Gogo::add_type(const std::string& name, Type* type, Location location)
947 {
948   Named_object* no = this->current_bindings()->add_type(name, NULL, type,
949                                                         location);
950   if (!this->in_global_scope() && no->is_type())
951     no->type_value()->set_in_function(this->functions_.back().function);
952 }
953
954 // Add a named type.
955
956 void
957 Gogo::add_named_type(Named_type* type)
958 {
959   go_assert(this->in_global_scope());
960   this->current_bindings()->add_named_type(type);
961 }
962
963 // Declare a type.
964
965 Named_object*
966 Gogo::declare_type(const std::string& name, Location location)
967 {
968   Bindings* bindings = this->current_bindings();
969   Named_object* no = bindings->add_type_declaration(name, NULL, location);
970   if (!this->in_global_scope() && no->is_type_declaration())
971     {
972       Named_object* f = this->functions_.back().function;
973       no->type_declaration_value()->set_in_function(f);
974     }
975   return no;
976 }
977
978 // Declare a type at the package level.
979
980 Named_object*
981 Gogo::declare_package_type(const std::string& name, Location location)
982 {
983   return this->package_->bindings()->add_type_declaration(name, NULL, location);
984 }
985
986 // Declare a function at the package level.
987
988 Named_object*
989 Gogo::declare_package_function(const std::string& name, Function_type* type,
990                                Location location)
991 {
992   return this->package_->bindings()->add_function_declaration(name, NULL, type,
993                                                               location);
994 }
995
996 // Define a type which was already declared.
997
998 void
999 Gogo::define_type(Named_object* no, Named_type* type)
1000 {
1001   this->current_bindings()->define_type(no, type);
1002 }
1003
1004 // Add a variable.
1005
1006 Named_object*
1007 Gogo::add_variable(const std::string& name, Variable* variable)
1008 {
1009   Named_object* no = this->current_bindings()->add_variable(name, NULL,
1010                                                             variable);
1011
1012   // In a function the middle-end wants to see a DECL_EXPR node.
1013   if (no != NULL
1014       && no->is_variable()
1015       && !no->var_value()->is_parameter()
1016       && !this->functions_.empty())
1017     this->add_statement(Statement::make_variable_declaration(no));
1018
1019   return no;
1020 }
1021
1022 // Add a sink--a reference to the blank identifier _.
1023
1024 Named_object*
1025 Gogo::add_sink()
1026 {
1027   return Named_object::make_sink();
1028 }
1029
1030 // Add a named object.
1031
1032 void
1033 Gogo::add_named_object(Named_object* no)
1034 {
1035   this->current_bindings()->add_named_object(no);
1036 }
1037
1038 // Record that we've seen an interface type.
1039
1040 void
1041 Gogo::record_interface_type(Interface_type* itype)
1042 {
1043   this->interface_types_.push_back(itype);
1044 }
1045
1046 // Return a name for a thunk object.
1047
1048 std::string
1049 Gogo::thunk_name()
1050 {
1051   static int thunk_count;
1052   char thunk_name[50];
1053   snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1054   ++thunk_count;
1055   return thunk_name;
1056 }
1057
1058 // Return whether a function is a thunk.
1059
1060 bool
1061 Gogo::is_thunk(const Named_object* no)
1062 {
1063   return no->name().compare(0, 6, "$thunk") == 0;
1064 }
1065
1066 // Define the global names.  We do this only after parsing all the
1067 // input files, because the program might define the global names
1068 // itself.
1069
1070 void
1071 Gogo::define_global_names()
1072 {
1073   for (Bindings::const_declarations_iterator p =
1074          this->globals_->begin_declarations();
1075        p != this->globals_->end_declarations();
1076        ++p)
1077     {
1078       Named_object* global_no = p->second;
1079       std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1080       Named_object* no = this->package_->bindings()->lookup(name);
1081       if (no == NULL)
1082         continue;
1083       no = no->resolve();
1084       if (no->is_type_declaration())
1085         {
1086           if (global_no->is_type())
1087             {
1088               if (no->type_declaration_value()->has_methods())
1089                 error_at(no->location(),
1090                          "may not define methods for global type");
1091               no->set_type_value(global_no->type_value());
1092             }
1093           else
1094             {
1095               error_at(no->location(), "expected type");
1096               Type* errtype = Type::make_error_type();
1097               Named_object* err =
1098                 Named_object::make_type("erroneous_type", NULL, errtype,
1099                                         Linemap::predeclared_location());
1100               no->set_type_value(err->type_value());
1101             }
1102         }
1103       else if (no->is_unknown())
1104         no->unknown_value()->set_real_named_object(global_no);
1105     }
1106 }
1107
1108 // Clear out names in file scope.
1109
1110 void
1111 Gogo::clear_file_scope()
1112 {
1113   this->package_->bindings()->clear_file_scope();
1114
1115   // Warn about packages which were imported but not used.
1116   for (Packages::iterator p = this->packages_.begin();
1117        p != this->packages_.end();
1118        ++p)
1119     {
1120       Package* package = p->second;
1121       if (package != this->package_
1122           && package->is_imported()
1123           && !package->used()
1124           && !package->uses_sink_alias()
1125           && !saw_errors())
1126         error_at(package->location(), "imported and not used: %s",
1127                  Gogo::message_name(package->name()).c_str());
1128       package->clear_is_imported();
1129       package->clear_uses_sink_alias();
1130       package->clear_used();
1131     }
1132 }
1133
1134 // Queue up a type specific function for later writing.  These are
1135 // written out in write_specific_type_functions, called after the
1136 // parse tree is lowered.
1137
1138 void
1139 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1140                                    const std::string& hash_name,
1141                                    Function_type* hash_fntype,
1142                                    const std::string& equal_name,
1143                                    Function_type* equal_fntype)
1144 {
1145   go_assert(!this->specific_type_functions_are_written_);
1146   go_assert(!this->in_global_scope());
1147   Specific_type_function* tsf = new Specific_type_function(type, name,
1148                                                            hash_name,
1149                                                            hash_fntype,
1150                                                            equal_name,
1151                                                            equal_fntype);
1152   this->specific_type_functions_.push_back(tsf);
1153 }
1154
1155 // Look for types which need specific hash or equality functions.
1156
1157 class Specific_type_functions : public Traverse
1158 {
1159  public:
1160   Specific_type_functions(Gogo* gogo)
1161     : Traverse(traverse_types),
1162       gogo_(gogo)
1163   { }
1164
1165   int
1166   type(Type*);
1167
1168  private:
1169   Gogo* gogo_;
1170 };
1171
1172 int
1173 Specific_type_functions::type(Type* t)
1174 {
1175   Named_object* hash_fn;
1176   Named_object* equal_fn;
1177   switch (t->classification())
1178     {
1179     case Type::TYPE_NAMED:
1180       {
1181         if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1182           t->type_functions(this->gogo_, t->named_type(), NULL, NULL, &hash_fn,
1183                             &equal_fn);
1184
1185         // If this is a struct type, we don't want to make functions
1186         // for the unnamed struct.
1187         Type* rt = t->named_type()->real_type();
1188         if (rt->struct_type() == NULL)
1189           {
1190             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1191               return TRAVERSE_EXIT;
1192           }
1193         else
1194           {
1195             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1196               return TRAVERSE_EXIT;
1197           }
1198
1199         return TRAVERSE_SKIP_COMPONENTS;
1200       }
1201
1202     case Type::TYPE_STRUCT:
1203     case Type::TYPE_ARRAY:
1204       if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1205         t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1206       break;
1207
1208     default:
1209       break;
1210     }
1211
1212   return TRAVERSE_CONTINUE;
1213 }
1214
1215 // Write out type specific functions.
1216
1217 void
1218 Gogo::write_specific_type_functions()
1219 {
1220   Specific_type_functions stf(this);
1221   this->traverse(&stf);
1222
1223   while (!this->specific_type_functions_.empty())
1224     {
1225       Specific_type_function* tsf = this->specific_type_functions_.back();
1226       this->specific_type_functions_.pop_back();
1227       tsf->type->write_specific_type_functions(this, tsf->name,
1228                                                tsf->hash_name,
1229                                                tsf->hash_fntype,
1230                                                tsf->equal_name,
1231                                                tsf->equal_fntype);
1232       delete tsf;
1233     }
1234   this->specific_type_functions_are_written_ = true;
1235 }
1236
1237 // Traverse the tree.
1238
1239 void
1240 Gogo::traverse(Traverse* traverse)
1241 {
1242   // Traverse the current package first for consistency.  The other
1243   // packages will only contain imported types, constants, and
1244   // declarations.
1245   if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1246     return;
1247   for (Packages::const_iterator p = this->packages_.begin();
1248        p != this->packages_.end();
1249        ++p)
1250     {
1251       if (p->second != this->package_)
1252         {
1253           if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1254             break;
1255         }
1256     }
1257 }
1258
1259 // Traversal class used to verify types.
1260
1261 class Verify_types : public Traverse
1262 {
1263  public:
1264   Verify_types()
1265     : Traverse(traverse_types)
1266   { }
1267
1268   int
1269   type(Type*);
1270 };
1271
1272 // Verify that a type is correct.
1273
1274 int
1275 Verify_types::type(Type* t)
1276 {
1277   if (!t->verify())
1278     return TRAVERSE_SKIP_COMPONENTS;
1279   return TRAVERSE_CONTINUE;
1280 }
1281
1282 // Verify that all types are correct.
1283
1284 void
1285 Gogo::verify_types()
1286 {
1287   Verify_types traverse;
1288   this->traverse(&traverse);
1289 }
1290
1291 // Traversal class used to lower parse tree.
1292
1293 class Lower_parse_tree : public Traverse
1294 {
1295  public:
1296   Lower_parse_tree(Gogo* gogo, Named_object* function)
1297     : Traverse(traverse_variables
1298                | traverse_constants
1299                | traverse_functions
1300                | traverse_statements
1301                | traverse_expressions),
1302       gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1303   { }
1304
1305   void
1306   set_inserter(const Statement_inserter* inserter)
1307   { this->inserter_ = *inserter; }
1308
1309   int
1310   variable(Named_object*);
1311
1312   int
1313   constant(Named_object*, bool);
1314
1315   int
1316   function(Named_object*);
1317
1318   int
1319   statement(Block*, size_t* pindex, Statement*);
1320
1321   int
1322   expression(Expression**);
1323
1324  private:
1325   // General IR.
1326   Gogo* gogo_;
1327   // The function we are traversing.
1328   Named_object* function_;
1329   // Value to use for the predeclared constant iota.
1330   int iota_value_;
1331   // Current statement inserter for use by expressions.
1332   Statement_inserter inserter_;
1333 };
1334
1335 // Lower variables.
1336
1337 int
1338 Lower_parse_tree::variable(Named_object* no)
1339 {
1340   if (!no->is_variable())
1341     return TRAVERSE_CONTINUE;
1342
1343   if (no->is_variable() && no->var_value()->is_global())
1344     {
1345       // Global variables can have loops in their initialization
1346       // expressions.  This is handled in lower_init_expression.
1347       no->var_value()->lower_init_expression(this->gogo_, this->function_,
1348                                              &this->inserter_);
1349       return TRAVERSE_CONTINUE;
1350     }
1351
1352   // This is a local variable.  We are going to return
1353   // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1354   // initialization expression when we reach the variable declaration
1355   // statement.  However, that means that we need to traverse the type
1356   // ourselves.
1357   if (no->var_value()->has_type())
1358     {
1359       Type* type = no->var_value()->type();
1360       if (type != NULL)
1361         {
1362           if (Type::traverse(type, this) == TRAVERSE_EXIT)
1363             return TRAVERSE_EXIT;
1364         }
1365     }
1366   go_assert(!no->var_value()->has_pre_init());
1367
1368   return TRAVERSE_SKIP_COMPONENTS;
1369 }
1370
1371 // Lower constants.  We handle constants specially so that we can set
1372 // the right value for the predeclared constant iota.  This works in
1373 // conjunction with the way we lower Const_expression objects.
1374
1375 int
1376 Lower_parse_tree::constant(Named_object* no, bool)
1377 {
1378   Named_constant* nc = no->const_value();
1379
1380   // Don't get into trouble if the constant's initializer expression
1381   // refers to the constant itself.
1382   if (nc->lowering())
1383     return TRAVERSE_CONTINUE;
1384   nc->set_lowering();
1385
1386   go_assert(this->iota_value_ == -1);
1387   this->iota_value_ = nc->iota_value();
1388   nc->traverse_expression(this);
1389   this->iota_value_ = -1;
1390
1391   nc->clear_lowering();
1392
1393   // We will traverse the expression a second time, but that will be
1394   // fast.
1395
1396   return TRAVERSE_CONTINUE;
1397 }
1398
1399 // Lower function closure types.  Record the function while lowering
1400 // it, so that we can pass it down when lowering an expression.
1401
1402 int
1403 Lower_parse_tree::function(Named_object* no)
1404 {
1405   no->func_value()->set_closure_type();
1406
1407   go_assert(this->function_ == NULL);
1408   this->function_ = no;
1409   int t = no->func_value()->traverse(this);
1410   this->function_ = NULL;
1411
1412   if (t == TRAVERSE_EXIT)
1413     return t;
1414   return TRAVERSE_SKIP_COMPONENTS;
1415 }
1416
1417 // Lower statement parse trees.
1418
1419 int
1420 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1421 {
1422   // Because we explicitly traverse the statement's contents
1423   // ourselves, we want to skip block statements here.  There is
1424   // nothing to lower in a block statement.
1425   if (sorig->is_block_statement())
1426     return TRAVERSE_CONTINUE;
1427
1428   Statement_inserter hold_inserter(this->inserter_);
1429   this->inserter_ = Statement_inserter(block, pindex);
1430
1431   // Lower the expressions first.
1432   int t = sorig->traverse_contents(this);
1433   if (t == TRAVERSE_EXIT)
1434     {
1435       this->inserter_ = hold_inserter;
1436       return t;
1437     }
1438
1439   // Keep lowering until nothing changes.
1440   Statement* s = sorig;
1441   while (true)
1442     {
1443       Statement* snew = s->lower(this->gogo_, this->function_, block,
1444                                  &this->inserter_);
1445       if (snew == s)
1446         break;
1447       s = snew;
1448       t = s->traverse_contents(this);
1449       if (t == TRAVERSE_EXIT)
1450         {
1451           this->inserter_ = hold_inserter;
1452           return t;
1453         }
1454     }
1455
1456   if (s != sorig)
1457     block->replace_statement(*pindex, s);
1458
1459   this->inserter_ = hold_inserter;
1460   return TRAVERSE_SKIP_COMPONENTS;
1461 }
1462
1463 // Lower expression parse trees.
1464
1465 int
1466 Lower_parse_tree::expression(Expression** pexpr)
1467 {
1468   // We have to lower all subexpressions first, so that we can get
1469   // their type if necessary.  This is awkward, because we don't have
1470   // a postorder traversal pass.
1471   if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1472     return TRAVERSE_EXIT;
1473   // Keep lowering until nothing changes.
1474   while (true)
1475     {
1476       Expression* e = *pexpr;
1477       Expression* enew = e->lower(this->gogo_, this->function_,
1478                                   &this->inserter_, this->iota_value_);
1479       if (enew == e)
1480         break;
1481       *pexpr = enew;
1482     }
1483   return TRAVERSE_SKIP_COMPONENTS;
1484 }
1485
1486 // Lower the parse tree.  This is called after the parse is complete,
1487 // when all names should be resolved.
1488
1489 void
1490 Gogo::lower_parse_tree()
1491 {
1492   Lower_parse_tree lower_parse_tree(this, NULL);
1493   this->traverse(&lower_parse_tree);
1494 }
1495
1496 // Lower a block.
1497
1498 void
1499 Gogo::lower_block(Named_object* function, Block* block)
1500 {
1501   Lower_parse_tree lower_parse_tree(this, function);
1502   block->traverse(&lower_parse_tree);
1503 }
1504
1505 // Lower an expression.  INSERTER may be NULL, in which case the
1506 // expression had better not need to create any temporaries.
1507
1508 void
1509 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1510                        Expression** pexpr)
1511 {
1512   Lower_parse_tree lower_parse_tree(this, function);
1513   if (inserter != NULL)
1514     lower_parse_tree.set_inserter(inserter);
1515   lower_parse_tree.expression(pexpr);
1516 }
1517
1518 // Lower a constant.  This is called when lowering a reference to a
1519 // constant.  We have to make sure that the constant has already been
1520 // lowered.
1521
1522 void
1523 Gogo::lower_constant(Named_object* no)
1524 {
1525   go_assert(no->is_const());
1526   Lower_parse_tree lower(this, NULL);
1527   lower.constant(no, false);
1528 }
1529
1530 // Look for interface types to finalize methods of inherited
1531 // interfaces.
1532
1533 class Finalize_methods : public Traverse
1534 {
1535  public:
1536   Finalize_methods(Gogo* gogo)
1537     : Traverse(traverse_types),
1538       gogo_(gogo)
1539   { }
1540
1541   int
1542   type(Type*);
1543
1544  private:
1545   Gogo* gogo_;
1546 };
1547
1548 // Finalize the methods of an interface type.
1549
1550 int
1551 Finalize_methods::type(Type* t)
1552 {
1553   // Check the classification so that we don't finalize the methods
1554   // twice for a named interface type.
1555   switch (t->classification())
1556     {
1557     case Type::TYPE_INTERFACE:
1558       t->interface_type()->finalize_methods();
1559       break;
1560
1561     case Type::TYPE_NAMED:
1562       {
1563         // We have to finalize the methods of the real type first.
1564         // But if the real type is a struct type, then we only want to
1565         // finalize the methods of the field types, not of the struct
1566         // type itself.  We don't want to add methods to the struct,
1567         // since it has a name.
1568         Named_type* nt = t->named_type();
1569         Type* rt = nt->real_type();
1570         if (rt->classification() != Type::TYPE_STRUCT)
1571           {
1572             if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1573               return TRAVERSE_EXIT;
1574           }
1575         else
1576           {
1577             if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1578               return TRAVERSE_EXIT;
1579           }
1580
1581         nt->finalize_methods(this->gogo_);
1582
1583         // If this type is defined in a different package, then finalize the
1584         // types of all the methods, since we won't see them otherwise.
1585         if (nt->named_object()->package() != NULL && nt->has_any_methods())
1586           {
1587             const Methods* methods = nt->methods();
1588             for (Methods::const_iterator p = methods->begin();
1589                  p != methods->end();
1590                  ++p)
1591               {
1592                 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1593                   return TRAVERSE_EXIT;
1594               }
1595           }
1596
1597         return TRAVERSE_SKIP_COMPONENTS;
1598       }
1599
1600     case Type::TYPE_STRUCT:
1601       t->struct_type()->finalize_methods(this->gogo_);
1602       break;
1603
1604     default:
1605       break;
1606     }
1607
1608   return TRAVERSE_CONTINUE;
1609 }
1610
1611 // Finalize method lists and build stub methods for types.
1612
1613 void
1614 Gogo::finalize_methods()
1615 {
1616   Finalize_methods finalize(this);
1617   this->traverse(&finalize);
1618 }
1619
1620 // Set types for unspecified variables and constants.
1621
1622 void
1623 Gogo::determine_types()
1624 {
1625   Bindings* bindings = this->current_bindings();
1626   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1627        p != bindings->end_definitions();
1628        ++p)
1629     {
1630       if ((*p)->is_function())
1631         (*p)->func_value()->determine_types();
1632       else if ((*p)->is_variable())
1633         (*p)->var_value()->determine_type();
1634       else if ((*p)->is_const())
1635         (*p)->const_value()->determine_type();
1636
1637       // See if a variable requires us to build an initialization
1638       // function.  We know that we will see all global variables
1639       // here.
1640       if (!this->need_init_fn_ && (*p)->is_variable())
1641         {
1642           Variable* variable = (*p)->var_value();
1643
1644           // If this is a global variable which requires runtime
1645           // initialization, we need an initialization function.
1646           if (!variable->is_global())
1647             ;
1648           else if (variable->init() == NULL)
1649             ;
1650           else if (variable->type()->interface_type() != NULL)
1651             this->need_init_fn_ = true;
1652           else if (variable->init()->is_constant())
1653             ;
1654           else if (!variable->init()->is_composite_literal())
1655             this->need_init_fn_ = true;
1656           else if (variable->init()->is_nonconstant_composite_literal())
1657             this->need_init_fn_ = true;
1658
1659           // If this is a global variable which holds a pointer value,
1660           // then we need an initialization function to register it as a
1661           // GC root.
1662           if (variable->is_global() && variable->type()->has_pointer())
1663             this->need_init_fn_ = true;
1664         }
1665     }
1666
1667   // Determine the types of constants in packages.
1668   for (Packages::const_iterator p = this->packages_.begin();
1669        p != this->packages_.end();
1670        ++p)
1671     p->second->determine_types();
1672 }
1673
1674 // Traversal class used for type checking.
1675
1676 class Check_types_traverse : public Traverse
1677 {
1678  public:
1679   Check_types_traverse(Gogo* gogo)
1680     : Traverse(traverse_variables
1681                | traverse_constants
1682                | traverse_functions
1683                | traverse_statements
1684                | traverse_expressions),
1685       gogo_(gogo)
1686   { }
1687
1688   int
1689   variable(Named_object*);
1690
1691   int
1692   constant(Named_object*, bool);
1693
1694   int
1695   function(Named_object*);
1696
1697   int
1698   statement(Block*, size_t* pindex, Statement*);
1699
1700   int
1701   expression(Expression**);
1702
1703  private:
1704   // General IR.
1705   Gogo* gogo_;
1706 };
1707
1708 // Check that a variable initializer has the right type.
1709
1710 int
1711 Check_types_traverse::variable(Named_object* named_object)
1712 {
1713   if (named_object->is_variable())
1714     {
1715       Variable* var = named_object->var_value();
1716
1717       // Give error if variable type is not defined.
1718       var->type()->base();
1719
1720       Expression* init = var->init();
1721       std::string reason;
1722       if (init != NULL
1723           && !Type::are_assignable(var->type(), init->type(), &reason))
1724         {
1725           if (reason.empty())
1726             error_at(var->location(), "incompatible type in initialization");
1727           else
1728             error_at(var->location(),
1729                      "incompatible type in initialization (%s)",
1730                      reason.c_str());
1731           var->clear_init();
1732         }
1733     }
1734   return TRAVERSE_CONTINUE;
1735 }
1736
1737 // Check that a constant initializer has the right type.
1738
1739 int
1740 Check_types_traverse::constant(Named_object* named_object, bool)
1741 {
1742   Named_constant* constant = named_object->const_value();
1743   Type* ctype = constant->type();
1744   if (ctype->integer_type() == NULL
1745       && ctype->float_type() == NULL
1746       && ctype->complex_type() == NULL
1747       && !ctype->is_boolean_type()
1748       && !ctype->is_string_type())
1749     {
1750       if (ctype->is_nil_type())
1751         error_at(constant->location(), "const initializer cannot be nil");
1752       else if (!ctype->is_error())
1753         error_at(constant->location(), "invalid constant type");
1754       constant->set_error();
1755     }
1756   else if (!constant->expr()->is_constant())
1757     {
1758       error_at(constant->expr()->location(), "expression is not constant");
1759       constant->set_error();
1760     }
1761   else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1762                                  NULL))
1763     {
1764       error_at(constant->location(),
1765                "initialization expression has wrong type");
1766       constant->set_error();
1767     }
1768   return TRAVERSE_CONTINUE;
1769 }
1770
1771 // There are no types to check in a function, but this is where we
1772 // issue warnings about labels which are defined but not referenced.
1773
1774 int
1775 Check_types_traverse::function(Named_object* no)
1776 {
1777   no->func_value()->check_labels();
1778   return TRAVERSE_CONTINUE;
1779 }
1780
1781 // Check that types are valid in a statement.
1782
1783 int
1784 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1785 {
1786   s->check_types(this->gogo_);
1787   return TRAVERSE_CONTINUE;
1788 }
1789
1790 // Check that types are valid in an expression.
1791
1792 int
1793 Check_types_traverse::expression(Expression** expr)
1794 {
1795   (*expr)->check_types(this->gogo_);
1796   return TRAVERSE_CONTINUE;
1797 }
1798
1799 // Check that types are valid.
1800
1801 void
1802 Gogo::check_types()
1803 {
1804   Check_types_traverse traverse(this);
1805   this->traverse(&traverse);
1806 }
1807
1808 // Check the types in a single block.
1809
1810 void
1811 Gogo::check_types_in_block(Block* block)
1812 {
1813   Check_types_traverse traverse(this);
1814   block->traverse(&traverse);
1815 }
1816
1817 // A traversal class used to find a single shortcut operator within an
1818 // expression.
1819
1820 class Find_shortcut : public Traverse
1821 {
1822  public:
1823   Find_shortcut()
1824     : Traverse(traverse_blocks
1825                | traverse_statements
1826                | traverse_expressions),
1827       found_(NULL)
1828   { }
1829
1830   // A pointer to the expression which was found, or NULL if none was
1831   // found.
1832   Expression**
1833   found() const
1834   { return this->found_; }
1835
1836  protected:
1837   int
1838   block(Block*)
1839   { return TRAVERSE_SKIP_COMPONENTS; }
1840
1841   int
1842   statement(Block*, size_t*, Statement*)
1843   { return TRAVERSE_SKIP_COMPONENTS; }
1844
1845   int
1846   expression(Expression**);
1847
1848  private:
1849   Expression** found_;
1850 };
1851
1852 // Find a shortcut expression.
1853
1854 int
1855 Find_shortcut::expression(Expression** pexpr)
1856 {
1857   Expression* expr = *pexpr;
1858   Binary_expression* be = expr->binary_expression();
1859   if (be == NULL)
1860     return TRAVERSE_CONTINUE;
1861   Operator op = be->op();
1862   if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1863     return TRAVERSE_CONTINUE;
1864   go_assert(this->found_ == NULL);
1865   this->found_ = pexpr;
1866   return TRAVERSE_EXIT;
1867 }
1868
1869 // A traversal class used to turn shortcut operators into explicit if
1870 // statements.
1871
1872 class Shortcuts : public Traverse
1873 {
1874  public:
1875   Shortcuts(Gogo* gogo)
1876     : Traverse(traverse_variables
1877                | traverse_statements),
1878       gogo_(gogo)
1879   { }
1880
1881  protected:
1882   int
1883   variable(Named_object*);
1884
1885   int
1886   statement(Block*, size_t*, Statement*);
1887
1888  private:
1889   // Convert a shortcut operator.
1890   Statement*
1891   convert_shortcut(Block* enclosing, Expression** pshortcut);
1892
1893   // The IR.
1894   Gogo* gogo_;
1895 };
1896
1897 // Remove shortcut operators in a single statement.
1898
1899 int
1900 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1901 {
1902   // FIXME: This approach doesn't work for switch statements, because
1903   // we add the new statements before the whole switch when we need to
1904   // instead add them just before the switch expression.  The right
1905   // fix is probably to lower switch statements with nonconstant cases
1906   // to a series of conditionals.
1907   if (s->switch_statement() != NULL)
1908     return TRAVERSE_CONTINUE;
1909
1910   while (true)
1911     {
1912       Find_shortcut find_shortcut;
1913
1914       // If S is a variable declaration, then ordinary traversal won't
1915       // do anything.  We want to explicitly traverse the
1916       // initialization expression if there is one.
1917       Variable_declaration_statement* vds = s->variable_declaration_statement();
1918       Expression* init = NULL;
1919       if (vds == NULL)
1920         s->traverse_contents(&find_shortcut);
1921       else
1922         {
1923           init = vds->var()->var_value()->init();
1924           if (init == NULL)
1925             return TRAVERSE_CONTINUE;
1926           init->traverse(&init, &find_shortcut);
1927         }
1928       Expression** pshortcut = find_shortcut.found();
1929       if (pshortcut == NULL)
1930         return TRAVERSE_CONTINUE;
1931
1932       Statement* snew = this->convert_shortcut(block, pshortcut);
1933       block->insert_statement_before(*pindex, snew);
1934       ++*pindex;
1935
1936       if (pshortcut == &init)
1937         vds->var()->var_value()->set_init(init);
1938     }
1939 }
1940
1941 // Remove shortcut operators in the initializer of a global variable.
1942
1943 int
1944 Shortcuts::variable(Named_object* no)
1945 {
1946   if (no->is_result_variable())
1947     return TRAVERSE_CONTINUE;
1948   Variable* var = no->var_value();
1949   Expression* init = var->init();
1950   if (!var->is_global() || init == NULL)
1951     return TRAVERSE_CONTINUE;
1952
1953   while (true)
1954     {
1955       Find_shortcut find_shortcut;
1956       init->traverse(&init, &find_shortcut);
1957       Expression** pshortcut = find_shortcut.found();
1958       if (pshortcut == NULL)
1959         return TRAVERSE_CONTINUE;
1960
1961       Statement* snew = this->convert_shortcut(NULL, pshortcut);
1962       var->add_preinit_statement(this->gogo_, snew);
1963       if (pshortcut == &init)
1964         var->set_init(init);
1965     }
1966 }
1967
1968 // Given an expression which uses a shortcut operator, return a
1969 // statement which implements it, and update *PSHORTCUT accordingly.
1970
1971 Statement*
1972 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1973 {
1974   Binary_expression* shortcut = (*pshortcut)->binary_expression();
1975   Expression* left = shortcut->left();
1976   Expression* right = shortcut->right();
1977   Location loc = shortcut->location();
1978
1979   Block* retblock = new Block(enclosing, loc);
1980   retblock->set_end_location(loc);
1981
1982   Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1983                                                       left, loc);
1984   retblock->add_statement(ts);
1985
1986   Block* block = new Block(retblock, loc);
1987   block->set_end_location(loc);
1988   Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1989   Statement* assign = Statement::make_assignment(tmpref, right, loc);
1990   block->add_statement(assign);
1991
1992   Expression* cond = Expression::make_temporary_reference(ts, loc);
1993   if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1994     cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1995
1996   Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1997                                                          loc);
1998   retblock->add_statement(if_statement);
1999
2000   *pshortcut = Expression::make_temporary_reference(ts, loc);
2001
2002   delete shortcut;
2003
2004   // Now convert any shortcut operators in LEFT and RIGHT.
2005   Shortcuts shortcuts(this->gogo_);
2006   retblock->traverse(&shortcuts);
2007
2008   return Statement::make_block_statement(retblock, loc);
2009 }
2010
2011 // Turn shortcut operators into explicit if statements.  Doing this
2012 // considerably simplifies the order of evaluation rules.
2013
2014 void
2015 Gogo::remove_shortcuts()
2016 {
2017   Shortcuts shortcuts(this);
2018   this->traverse(&shortcuts);
2019 }
2020
2021 // A traversal class which finds all the expressions which must be
2022 // evaluated in order within a statement or larger expression.  This
2023 // is used to implement the rules about order of evaluation.
2024
2025 class Find_eval_ordering : public Traverse
2026 {
2027  private:
2028   typedef std::vector<Expression**> Expression_pointers;
2029
2030  public:
2031   Find_eval_ordering()
2032     : Traverse(traverse_blocks
2033                | traverse_statements
2034                | traverse_expressions),
2035       exprs_()
2036   { }
2037
2038   size_t
2039   size() const
2040   { return this->exprs_.size(); }
2041
2042   typedef Expression_pointers::const_iterator const_iterator;
2043
2044   const_iterator
2045   begin() const
2046   { return this->exprs_.begin(); }
2047
2048   const_iterator
2049   end() const
2050   { return this->exprs_.end(); }
2051
2052  protected:
2053   int
2054   block(Block*)
2055   { return TRAVERSE_SKIP_COMPONENTS; }
2056
2057   int
2058   statement(Block*, size_t*, Statement*)
2059   { return TRAVERSE_SKIP_COMPONENTS; }
2060
2061   int
2062   expression(Expression**);
2063
2064  private:
2065   // A list of pointers to expressions with side-effects.
2066   Expression_pointers exprs_;
2067 };
2068
2069 // If an expression must be evaluated in order, put it on the list.
2070
2071 int
2072 Find_eval_ordering::expression(Expression** expression_pointer)
2073 {
2074   // We have to look at subexpressions before this one.
2075   if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2076     return TRAVERSE_EXIT;
2077   if ((*expression_pointer)->must_eval_in_order())
2078     this->exprs_.push_back(expression_pointer);
2079   return TRAVERSE_SKIP_COMPONENTS;
2080 }
2081
2082 // A traversal class for ordering evaluations.
2083
2084 class Order_eval : public Traverse
2085 {
2086  public:
2087   Order_eval(Gogo* gogo)
2088     : Traverse(traverse_variables
2089                | traverse_statements),
2090       gogo_(gogo)
2091   { }
2092
2093   int
2094   variable(Named_object*);
2095
2096   int
2097   statement(Block*, size_t*, Statement*);
2098
2099  private:
2100   // The IR.
2101   Gogo* gogo_;
2102 };
2103
2104 // Implement the order of evaluation rules for a statement.
2105
2106 int
2107 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2108 {
2109   // FIXME: This approach doesn't work for switch statements, because
2110   // we add the new statements before the whole switch when we need to
2111   // instead add them just before the switch expression.  The right
2112   // fix is probably to lower switch statements with nonconstant cases
2113   // to a series of conditionals.
2114   if (s->switch_statement() != NULL)
2115     return TRAVERSE_CONTINUE;
2116
2117   Find_eval_ordering find_eval_ordering;
2118
2119   // If S is a variable declaration, then ordinary traversal won't do
2120   // anything.  We want to explicitly traverse the initialization
2121   // expression if there is one.
2122   Variable_declaration_statement* vds = s->variable_declaration_statement();
2123   Expression* init = NULL;
2124   Expression* orig_init = NULL;
2125   if (vds == NULL)
2126     s->traverse_contents(&find_eval_ordering);
2127   else
2128     {
2129       init = vds->var()->var_value()->init();
2130       if (init == NULL)
2131         return TRAVERSE_CONTINUE;
2132       orig_init = init;
2133
2134       // It might seem that this could be
2135       // init->traverse_subexpressions.  Unfortunately that can fail
2136       // in a case like
2137       //   var err os.Error
2138       //   newvar, err := call(arg())
2139       // Here newvar will have an init of call result 0 of
2140       // call(arg()).  If we only traverse subexpressions, we will
2141       // only find arg(), and we won't bother to move anything out.
2142       // Then we get to the assignment to err, we will traverse the
2143       // whole statement, and this time we will find both call() and
2144       // arg(), and so we will move them out.  This will cause them to
2145       // be put into temporary variables before the assignment to err
2146       // but after the declaration of newvar.  To avoid that problem,
2147       // we traverse the entire expression here.
2148       Expression::traverse(&init, &find_eval_ordering);
2149     }
2150
2151   if (find_eval_ordering.size() <= 1)
2152     {
2153       // If there is only one expression with a side-effect, we can
2154       // leave it in place.
2155       return TRAVERSE_CONTINUE;
2156     }
2157
2158   bool is_thunk = s->thunk_statement() != NULL;
2159   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2160        p != find_eval_ordering.end();
2161        ++p)
2162     {
2163       Expression** pexpr = *p;
2164
2165       // The last expression in a thunk will be the call passed to go
2166       // or defer, which we must not evaluate early.
2167       if (is_thunk && p + 1 == find_eval_ordering.end())
2168         break;
2169
2170       Location loc = (*pexpr)->location();
2171       Statement* s;
2172       if ((*pexpr)->call_expression() == NULL
2173           || (*pexpr)->call_expression()->result_count() < 2)
2174         {
2175           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2176                                                               loc);
2177           s = ts;
2178           *pexpr = Expression::make_temporary_reference(ts, loc);
2179         }
2180       else
2181         {
2182           // A call expression which returns multiple results needs to
2183           // be handled specially.  We can't create a temporary
2184           // because there is no type to give it.  Any actual uses of
2185           // the values will be done via Call_result_expressions.
2186           s = Statement::make_statement(*pexpr, true);
2187         }
2188
2189       block->insert_statement_before(*pindex, s);
2190       ++*pindex;
2191     }
2192
2193   if (init != orig_init)
2194     vds->var()->var_value()->set_init(init);
2195
2196   return TRAVERSE_CONTINUE;
2197 }
2198
2199 // Implement the order of evaluation rules for the initializer of a
2200 // global variable.
2201
2202 int
2203 Order_eval::variable(Named_object* no)
2204 {
2205   if (no->is_result_variable())
2206     return TRAVERSE_CONTINUE;
2207   Variable* var = no->var_value();
2208   Expression* init = var->init();
2209   if (!var->is_global() || init == NULL)
2210     return TRAVERSE_CONTINUE;
2211
2212   Find_eval_ordering find_eval_ordering;
2213   Expression::traverse(&init, &find_eval_ordering);
2214
2215   if (find_eval_ordering.size() <= 1)
2216     {
2217       // If there is only one expression with a side-effect, we can
2218       // leave it in place.
2219       return TRAVERSE_SKIP_COMPONENTS;
2220     }
2221
2222   Expression* orig_init = init;
2223
2224   for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2225        p != find_eval_ordering.end();
2226        ++p)
2227     {
2228       Expression** pexpr = *p;
2229       Location loc = (*pexpr)->location();
2230       Statement* s;
2231       if ((*pexpr)->call_expression() == NULL
2232           || (*pexpr)->call_expression()->result_count() < 2)
2233         {
2234           Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2235                                                               loc);
2236           s = ts;
2237           *pexpr = Expression::make_temporary_reference(ts, loc);
2238         }
2239       else
2240         {
2241           // A call expression which returns multiple results needs to
2242           // be handled specially.
2243           s = Statement::make_statement(*pexpr, true);
2244         }
2245       var->add_preinit_statement(this->gogo_, s);
2246     }
2247
2248   if (init != orig_init)
2249     var->set_init(init);
2250
2251   return TRAVERSE_SKIP_COMPONENTS;
2252 }
2253
2254 // Use temporary variables to implement the order of evaluation rules.
2255
2256 void
2257 Gogo::order_evaluations()
2258 {
2259   Order_eval order_eval(this);
2260   this->traverse(&order_eval);
2261 }
2262
2263 // Traversal to convert calls to the predeclared recover function to
2264 // pass in an argument indicating whether it can recover from a panic
2265 // or not.
2266
2267 class Convert_recover : public Traverse
2268 {
2269  public:
2270   Convert_recover(Named_object* arg)
2271     : Traverse(traverse_expressions),
2272       arg_(arg)
2273   { }
2274
2275  protected:
2276   int
2277   expression(Expression**);
2278
2279  private:
2280   // The argument to pass to the function.
2281   Named_object* arg_;
2282 };
2283
2284 // Convert calls to recover.
2285
2286 int
2287 Convert_recover::expression(Expression** pp)
2288 {
2289   Call_expression* ce = (*pp)->call_expression();
2290   if (ce != NULL && ce->is_recover_call())
2291     ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2292                                                        ce->location()));
2293   return TRAVERSE_CONTINUE;
2294 }
2295
2296 // Traversal for build_recover_thunks.
2297
2298 class Build_recover_thunks : public Traverse
2299 {
2300  public:
2301   Build_recover_thunks(Gogo* gogo)
2302     : Traverse(traverse_functions),
2303       gogo_(gogo)
2304   { }
2305
2306   int
2307   function(Named_object*);
2308
2309  private:
2310   Expression*
2311   can_recover_arg(Location);
2312
2313   // General IR.
2314   Gogo* gogo_;
2315 };
2316
2317 // If this function calls recover, turn it into a thunk.
2318
2319 int
2320 Build_recover_thunks::function(Named_object* orig_no)
2321 {
2322   Function* orig_func = orig_no->func_value();
2323   if (!orig_func->calls_recover()
2324       || orig_func->is_recover_thunk()
2325       || orig_func->has_recover_thunk())
2326     return TRAVERSE_CONTINUE;
2327
2328   Gogo* gogo = this->gogo_;
2329   Location location = orig_func->location();
2330
2331   static int count;
2332   char buf[50];
2333
2334   Function_type* orig_fntype = orig_func->type();
2335   Typed_identifier_list* new_params = new Typed_identifier_list();
2336   std::string receiver_name;
2337   if (orig_fntype->is_method())
2338     {
2339       const Typed_identifier* receiver = orig_fntype->receiver();
2340       snprintf(buf, sizeof buf, "rt.%u", count);
2341       ++count;
2342       receiver_name = buf;
2343       new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2344                                              receiver->location()));
2345     }
2346   const Typed_identifier_list* orig_params = orig_fntype->parameters();
2347   if (orig_params != NULL && !orig_params->empty())
2348     {
2349       for (Typed_identifier_list::const_iterator p = orig_params->begin();
2350            p != orig_params->end();
2351            ++p)
2352         {
2353           snprintf(buf, sizeof buf, "pt.%u", count);
2354           ++count;
2355           new_params->push_back(Typed_identifier(buf, p->type(),
2356                                                  p->location()));
2357         }
2358     }
2359   snprintf(buf, sizeof buf, "pr.%u", count);
2360   ++count;
2361   std::string can_recover_name = buf;
2362   new_params->push_back(Typed_identifier(can_recover_name,
2363                                          Type::lookup_bool_type(),
2364                                          orig_fntype->location()));
2365
2366   const Typed_identifier_list* orig_results = orig_fntype->results();
2367   Typed_identifier_list* new_results;
2368   if (orig_results == NULL || orig_results->empty())
2369     new_results = NULL;
2370   else
2371     {
2372       new_results = new Typed_identifier_list();
2373       for (Typed_identifier_list::const_iterator p = orig_results->begin();
2374            p != orig_results->end();
2375            ++p)
2376         new_results->push_back(Typed_identifier("", p->type(), p->location()));
2377     }
2378
2379   Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2380                                                        new_results,
2381                                                        orig_fntype->location());
2382   if (orig_fntype->is_varargs())
2383     new_fntype->set_is_varargs();
2384
2385   std::string name = orig_no->name() + "$recover";
2386   Named_object *new_no = gogo->start_function(name, new_fntype, false,
2387                                               location);
2388   Function *new_func = new_no->func_value();
2389   if (orig_func->enclosing() != NULL)
2390     new_func->set_enclosing(orig_func->enclosing());
2391
2392   // We build the code for the original function attached to the new
2393   // function, and then swap the original and new function bodies.
2394   // This means that existing references to the original function will
2395   // then refer to the new function.  That makes this code a little
2396   // confusing, in that the reference to NEW_NO really refers to the
2397   // other function, not the one we are building.
2398
2399   Expression* closure = NULL;
2400   if (orig_func->needs_closure())
2401     {
2402       Named_object* orig_closure_no = orig_func->closure_var();
2403       Variable* orig_closure_var = orig_closure_no->var_value();
2404       Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2405                                        true, false, location);
2406       snprintf(buf, sizeof buf, "closure.%u", count);
2407       ++count;
2408       Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2409                                                                  new_var);
2410       new_func->set_closure_var(new_closure_no);
2411       closure = Expression::make_var_reference(new_closure_no, location);
2412     }
2413
2414   Expression* fn = Expression::make_func_reference(new_no, closure, location);
2415
2416   Expression_list* args = new Expression_list();
2417   if (new_params != NULL)
2418     {
2419       // Note that we skip the last parameter, which is the boolean
2420       // indicating whether recover can succed.
2421       for (Typed_identifier_list::const_iterator p = new_params->begin();
2422            p + 1 != new_params->end();
2423            ++p)
2424         {
2425           Named_object* p_no = gogo->lookup(p->name(), NULL);
2426           go_assert(p_no != NULL
2427                      && p_no->is_variable()
2428                      && p_no->var_value()->is_parameter());
2429           args->push_back(Expression::make_var_reference(p_no, location));
2430         }
2431     }
2432   args->push_back(this->can_recover_arg(location));
2433
2434   gogo->start_block(location);
2435
2436   Call_expression* call = Expression::make_call(fn, args, false, location);
2437
2438   Statement* s;
2439   if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2440     s = Statement::make_statement(call, true);
2441   else
2442     {
2443       Expression_list* vals = new Expression_list();
2444       size_t rc = orig_fntype->results()->size();
2445       if (rc == 1)
2446         vals->push_back(call);
2447       else
2448         {
2449           for (size_t i = 0; i < rc; ++i)
2450             vals->push_back(Expression::make_call_result(call, i));
2451         }
2452       s = Statement::make_return_statement(vals, location);
2453     }
2454   s->determine_types();
2455   gogo->add_statement(s);
2456
2457   Block* b = gogo->finish_block(location);
2458
2459   gogo->add_block(b, location);
2460
2461   // Lower the call in case it returns multiple results.
2462   gogo->lower_block(new_no, b);
2463
2464   gogo->finish_function(location);
2465
2466   // Swap the function bodies and types.
2467   new_func->swap_for_recover(orig_func);
2468   orig_func->set_is_recover_thunk();
2469   new_func->set_calls_recover();
2470   new_func->set_has_recover_thunk();
2471
2472   Bindings* orig_bindings = orig_func->block()->bindings();
2473   Bindings* new_bindings = new_func->block()->bindings();
2474   if (orig_fntype->is_method())
2475     {
2476       // We changed the receiver to be a regular parameter.  We have
2477       // to update the binding accordingly in both functions.
2478       Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2479       go_assert(orig_rec_no != NULL
2480                  && orig_rec_no->is_variable()
2481                  && !orig_rec_no->var_value()->is_receiver());
2482       orig_rec_no->var_value()->set_is_receiver();
2483
2484       const std::string& new_receiver_name(orig_fntype->receiver()->name());
2485       Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2486       if (new_rec_no == NULL)
2487         go_assert(saw_errors());
2488       else
2489         {
2490           go_assert(new_rec_no->is_variable()
2491                      && new_rec_no->var_value()->is_receiver());
2492           new_rec_no->var_value()->set_is_not_receiver();
2493         }
2494     }
2495
2496   // Because we flipped blocks but not types, the can_recover
2497   // parameter appears in the (now) old bindings as a parameter.
2498   // Change it to a local variable, whereupon it will be discarded.
2499   Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2500   go_assert(can_recover_no != NULL
2501              && can_recover_no->is_variable()
2502              && can_recover_no->var_value()->is_parameter());
2503   orig_bindings->remove_binding(can_recover_no);
2504
2505   // Add the can_recover argument to the (now) new bindings, and
2506   // attach it to any recover statements.
2507   Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2508                                            false, true, false, location);
2509   can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2510                                               can_recover_var);
2511   Convert_recover convert_recover(can_recover_no);
2512   new_func->traverse(&convert_recover);
2513
2514   // Update the function pointers in any named results.
2515   new_func->update_result_variables();
2516   orig_func->update_result_variables();
2517
2518   return TRAVERSE_CONTINUE;
2519 }
2520
2521 // Return the expression to pass for the .can_recover parameter to the
2522 // new function.  This indicates whether a call to recover may return
2523 // non-nil.  The expression is
2524 // __go_can_recover(__builtin_return_address()).
2525
2526 Expression*
2527 Build_recover_thunks::can_recover_arg(Location location)
2528 {
2529   static Named_object* builtin_return_address;
2530   if (builtin_return_address == NULL)
2531     {
2532       const Location bloc = Linemap::predeclared_location();
2533
2534       Typed_identifier_list* param_types = new Typed_identifier_list();
2535       Type* uint_type = Type::lookup_integer_type("uint");
2536       param_types->push_back(Typed_identifier("l", uint_type, bloc));
2537
2538       Typed_identifier_list* return_types = new Typed_identifier_list();
2539       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2540       return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2541
2542       Function_type* fntype = Type::make_function_type(NULL, param_types,
2543                                                        return_types, bloc);
2544       builtin_return_address =
2545         Named_object::make_function_declaration("__builtin_return_address",
2546                                                 NULL, fntype, bloc);
2547       const char* n = "__builtin_return_address";
2548       builtin_return_address->func_declaration_value()->set_asm_name(n);
2549     }
2550
2551   static Named_object* can_recover;
2552   if (can_recover == NULL)
2553     {
2554       const Location bloc = Linemap::predeclared_location();
2555       Typed_identifier_list* param_types = new Typed_identifier_list();
2556       Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2557       param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2558       Type* boolean_type = Type::lookup_bool_type();
2559       Typed_identifier_list* results = new Typed_identifier_list();
2560       results->push_back(Typed_identifier("", boolean_type, bloc));
2561       Function_type* fntype = Type::make_function_type(NULL, param_types,
2562                                                        results, bloc);
2563       can_recover = Named_object::make_function_declaration("__go_can_recover",
2564                                                             NULL, fntype,
2565                                                             bloc);
2566       can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2567     }
2568
2569   Expression* fn = Expression::make_func_reference(builtin_return_address,
2570                                                    NULL, location);
2571
2572   mpz_t zval;
2573   mpz_init_set_ui(zval, 0UL);
2574   Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2575   mpz_clear(zval);
2576   Expression_list *args = new Expression_list();
2577   args->push_back(zexpr);
2578
2579   Expression* call = Expression::make_call(fn, args, false, location);
2580
2581   args = new Expression_list();
2582   args->push_back(call);
2583
2584   fn = Expression::make_func_reference(can_recover, NULL, location);
2585   return Expression::make_call(fn, args, false, location);
2586 }
2587
2588 // Build thunks for functions which call recover.  We build a new
2589 // function with an extra parameter, which is whether a call to
2590 // recover can succeed.  We then move the body of this function to
2591 // that one.  We then turn this function into a thunk which calls the
2592 // new one, passing the value of
2593 // __go_can_recover(__builtin_return_address()).  The function will be
2594 // marked as not splitting the stack.  This will cooperate with the
2595 // implementation of defer to make recover do the right thing.
2596
2597 void
2598 Gogo::build_recover_thunks()
2599 {
2600   Build_recover_thunks build_recover_thunks(this);
2601   this->traverse(&build_recover_thunks);
2602 }
2603
2604 // Look for named types to see whether we need to create an interface
2605 // method table.
2606
2607 class Build_method_tables : public Traverse
2608 {
2609  public:
2610   Build_method_tables(Gogo* gogo,
2611                       const std::vector<Interface_type*>& interfaces)
2612     : Traverse(traverse_types),
2613       gogo_(gogo), interfaces_(interfaces)
2614   { }
2615
2616   int
2617   type(Type*);
2618
2619  private:
2620   // The IR.
2621   Gogo* gogo_;
2622   // A list of locally defined interfaces which have hidden methods.
2623   const std::vector<Interface_type*>& interfaces_;
2624 };
2625
2626 // Build all required interface method tables for types.  We need to
2627 // ensure that we have an interface method table for every interface
2628 // which has a hidden method, for every named type which implements
2629 // that interface.  Normally we can just build interface method tables
2630 // as we need them.  However, in some cases we can require an
2631 // interface method table for an interface defined in a different
2632 // package for a type defined in that package.  If that interface and
2633 // type both use a hidden method, that is OK.  However, we will not be
2634 // able to build that interface method table when we need it, because
2635 // the type's hidden method will be static.  So we have to build it
2636 // here, and just refer it from other packages as needed.
2637
2638 void
2639 Gogo::build_interface_method_tables()
2640 {
2641   if (saw_errors())
2642     return;
2643
2644   std::vector<Interface_type*> hidden_interfaces;
2645   hidden_interfaces.reserve(this->interface_types_.size());
2646   for (std::vector<Interface_type*>::const_iterator pi =
2647          this->interface_types_.begin();
2648        pi != this->interface_types_.end();
2649        ++pi)
2650     {
2651       const Typed_identifier_list* methods = (*pi)->methods();
2652       if (methods == NULL)
2653         continue;
2654       for (Typed_identifier_list::const_iterator pm = methods->begin();
2655            pm != methods->end();
2656            ++pm)
2657         {
2658           if (Gogo::is_hidden_name(pm->name()))
2659             {
2660               hidden_interfaces.push_back(*pi);
2661               break;
2662             }
2663         }
2664     }
2665
2666   if (!hidden_interfaces.empty())
2667     {
2668       // Now traverse the tree looking for all named types.
2669       Build_method_tables bmt(this, hidden_interfaces);
2670       this->traverse(&bmt);
2671     }
2672
2673   // We no longer need the list of interfaces.
2674
2675   this->interface_types_.clear();
2676 }
2677
2678 // This is called for each type.  For a named type, for each of the
2679 // interfaces with hidden methods that it implements, create the
2680 // method table.
2681
2682 int
2683 Build_method_tables::type(Type* type)
2684 {
2685   Named_type* nt = type->named_type();
2686   if (nt != NULL)
2687     {
2688       for (std::vector<Interface_type*>::const_iterator p =
2689              this->interfaces_.begin();
2690            p != this->interfaces_.end();
2691            ++p)
2692         {
2693           // We ask whether a pointer to the named type implements the
2694           // interface, because a pointer can implement more methods
2695           // than a value.
2696           if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2697             {
2698               nt->interface_method_table(this->gogo_, *p, false);
2699               nt->interface_method_table(this->gogo_, *p, true);
2700             }
2701         }
2702     }
2703   return TRAVERSE_CONTINUE;
2704 }
2705
2706 // Traversal class used to check for return statements.
2707
2708 class Check_return_statements_traverse : public Traverse
2709 {
2710  public:
2711   Check_return_statements_traverse()
2712     : Traverse(traverse_functions)
2713   { }
2714
2715   int
2716   function(Named_object*);
2717 };
2718
2719 // Check that a function has a return statement if it needs one.
2720
2721 int
2722 Check_return_statements_traverse::function(Named_object* no)
2723 {
2724   Function* func = no->func_value();
2725   const Function_type* fntype = func->type();
2726   const Typed_identifier_list* results = fntype->results();
2727
2728   // We only need a return statement if there is a return value.
2729   if (results == NULL || results->empty())
2730     return TRAVERSE_CONTINUE;
2731
2732   if (func->block()->may_fall_through())
2733     error_at(func->location(), "control reaches end of non-void function");
2734
2735   return TRAVERSE_CONTINUE;
2736 }
2737
2738 // Check return statements.
2739
2740 void
2741 Gogo::check_return_statements()
2742 {
2743   Check_return_statements_traverse traverse;
2744   this->traverse(&traverse);
2745 }
2746
2747 // Get the unique prefix to use before all exported symbols.  This
2748 // must be unique across the entire link.
2749
2750 const std::string&
2751 Gogo::unique_prefix() const
2752 {
2753   go_assert(!this->unique_prefix_.empty());
2754   return this->unique_prefix_;
2755 }
2756
2757 // Set the unique prefix to use before all exported symbols.  This
2758 // comes from the command line option -fgo-prefix=XXX.
2759
2760 void
2761 Gogo::set_unique_prefix(const std::string& arg)
2762 {
2763   go_assert(this->unique_prefix_.empty());
2764   this->unique_prefix_ = arg;
2765   this->unique_prefix_specified_ = true;
2766 }
2767
2768 // Work out the package priority.  It is one more than the maximum
2769 // priority of an imported package.
2770
2771 int
2772 Gogo::package_priority() const
2773 {
2774   int priority = 0;
2775   for (Packages::const_iterator p = this->packages_.begin();
2776        p != this->packages_.end();
2777        ++p)
2778     if (p->second->priority() > priority)
2779       priority = p->second->priority();
2780   return priority + 1;
2781 }
2782
2783 // Export identifiers as requested.
2784
2785 void
2786 Gogo::do_exports()
2787 {
2788   // For now we always stream to a section.  Later we may want to
2789   // support streaming to a separate file.
2790   Stream_to_section stream;
2791
2792   Export exp(&stream);
2793   exp.register_builtin_types(this);
2794   exp.export_globals(this->package_name(),
2795                      this->unique_prefix(),
2796                      this->package_priority(),
2797                      (this->need_init_fn_ && !this->is_main_package()
2798                       ? this->get_init_fn_name()
2799                       : ""),
2800                      this->imported_init_fns_,
2801                      this->package_->bindings());
2802 }
2803
2804 // Find the blocks in order to convert named types defined in blocks.
2805
2806 class Convert_named_types : public Traverse
2807 {
2808  public:
2809   Convert_named_types(Gogo* gogo)
2810     : Traverse(traverse_blocks),
2811       gogo_(gogo)
2812   { }
2813
2814  protected:
2815   int
2816   block(Block* block);
2817
2818  private:
2819   Gogo* gogo_;
2820 };
2821
2822 int
2823 Convert_named_types::block(Block* block)
2824 {
2825   this->gogo_->convert_named_types_in_bindings(block->bindings());
2826   return TRAVERSE_CONTINUE;
2827 }
2828
2829 // Convert all named types to the backend representation.  Since named
2830 // types can refer to other types, this needs to be done in the right
2831 // sequence, which is handled by Named_type::convert.  Here we arrange
2832 // to call that for each named type.
2833
2834 void
2835 Gogo::convert_named_types()
2836 {
2837   this->convert_named_types_in_bindings(this->globals_);
2838   for (Packages::iterator p = this->packages_.begin();
2839        p != this->packages_.end();
2840        ++p)
2841     {
2842       Package* package = p->second;
2843       this->convert_named_types_in_bindings(package->bindings());
2844     }
2845
2846   Convert_named_types cnt(this);
2847   this->traverse(&cnt);
2848
2849   // Make all the builtin named types used for type descriptors, and
2850   // then convert them.  They will only be written out if they are
2851   // needed.
2852   Type::make_type_descriptor_type();
2853   Type::make_type_descriptor_ptr_type();
2854   Function_type::make_function_type_descriptor_type();
2855   Pointer_type::make_pointer_type_descriptor_type();
2856   Struct_type::make_struct_type_descriptor_type();
2857   Array_type::make_array_type_descriptor_type();
2858   Array_type::make_slice_type_descriptor_type();
2859   Map_type::make_map_type_descriptor_type();
2860   Map_type::make_map_descriptor_type();
2861   Channel_type::make_chan_type_descriptor_type();
2862   Interface_type::make_interface_type_descriptor_type();
2863   Type::convert_builtin_named_types(this);
2864
2865   Runtime::convert_types(this);
2866
2867   Function_type::convert_types(this);
2868
2869   this->named_types_are_converted_ = true;
2870 }
2871
2872 // Convert all names types in a set of bindings.
2873
2874 void
2875 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2876 {
2877   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2878        p != bindings->end_definitions();
2879        ++p)
2880     {
2881       if ((*p)->is_type())
2882         (*p)->type_value()->convert(this);
2883     }
2884 }
2885
2886 // Class Function.
2887
2888 Function::Function(Function_type* type, Function* enclosing, Block* block,
2889                    Location location)
2890   : type_(type), enclosing_(enclosing), results_(NULL),
2891     closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2892     defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2893     is_recover_thunk_(false), has_recover_thunk_(false)
2894 {
2895 }
2896
2897 // Create the named result variables.
2898
2899 void
2900 Function::create_result_variables(Gogo* gogo)
2901 {
2902   const Typed_identifier_list* results = this->type_->results();
2903   if (results == NULL || results->empty())
2904     return;
2905
2906   if (!results->front().name().empty())
2907     this->results_are_named_ = true;
2908
2909   this->results_ = new Results();
2910   this->results_->reserve(results->size());
2911
2912   Block* block = this->block_;
2913   int index = 0;
2914   for (Typed_identifier_list::const_iterator p = results->begin();
2915        p != results->end();
2916        ++p, ++index)
2917     {
2918       std::string name = p->name();
2919       if (name.empty() || Gogo::is_sink_name(name))
2920         {
2921           static int result_counter;
2922           char buf[100];
2923           snprintf(buf, sizeof buf, "$ret%d", result_counter);
2924           ++result_counter;
2925           name = gogo->pack_hidden_name(buf, false);
2926         }
2927       Result_variable* result = new Result_variable(p->type(), this, index,
2928                                                     p->location());
2929       Named_object* no = block->bindings()->add_result_variable(name, result);
2930       if (no->is_result_variable())
2931         this->results_->push_back(no);
2932       else
2933         {
2934           static int dummy_result_count;
2935           char buf[100];
2936           snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2937           ++dummy_result_count;
2938           name = gogo->pack_hidden_name(buf, false);
2939           no = block->bindings()->add_result_variable(name, result);
2940           go_assert(no->is_result_variable());
2941           this->results_->push_back(no);
2942         }
2943     }
2944 }
2945
2946 // Update the named result variables when cloning a function which
2947 // calls recover.
2948
2949 void
2950 Function::update_result_variables()
2951 {
2952   if (this->results_ == NULL)
2953     return;
2954
2955   for (Results::iterator p = this->results_->begin();
2956        p != this->results_->end();
2957        ++p)
2958     (*p)->result_var_value()->set_function(this);
2959 }
2960
2961 // Return the closure variable, creating it if necessary.
2962
2963 Named_object*
2964 Function::closure_var()
2965 {
2966   if (this->closure_var_ == NULL)
2967     {
2968       // We don't know the type of the variable yet.  We add fields as
2969       // we find them.
2970       Location loc = this->type_->location();
2971       Struct_field_list* sfl = new Struct_field_list;
2972       Type* struct_type = Type::make_struct_type(sfl, loc);
2973       Variable* var = new Variable(Type::make_pointer_type(struct_type),
2974                                    NULL, false, true, false, loc);
2975       this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2976       // Note that the new variable is not in any binding contour.
2977     }
2978   return this->closure_var_;
2979 }
2980
2981 // Set the type of the closure variable.
2982
2983 void
2984 Function::set_closure_type()
2985 {
2986   if (this->closure_var_ == NULL)
2987     return;
2988   Named_object* closure = this->closure_var_;
2989   Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2990   unsigned int index = 0;
2991   for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2992        p != this->closure_fields_.end();
2993        ++p, ++index)
2994     {
2995       Named_object* no = p->first;
2996       char buf[20];
2997       snprintf(buf, sizeof buf, "%u", index);
2998       std::string n = no->name() + buf;
2999       Type* var_type;
3000       if (no->is_variable())
3001         var_type = no->var_value()->type();
3002       else
3003         var_type = no->result_var_value()->type();
3004       Type* field_type = Type::make_pointer_type(var_type);
3005       st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3006     }
3007 }
3008
3009 // Return whether this function is a method.
3010
3011 bool
3012 Function::is_method() const
3013 {
3014   return this->type_->is_method();
3015 }
3016
3017 // Add a label definition.
3018
3019 Label*
3020 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3021                                Location location)
3022 {
3023   Label* lnull = NULL;
3024   std::pair<Labels::iterator, bool> ins =
3025     this->labels_.insert(std::make_pair(label_name, lnull));
3026   Label* label;
3027   if (ins.second)
3028     {
3029       // This is a new label.
3030       label = new Label(label_name);
3031       ins.first->second = label;
3032     }
3033   else
3034     {
3035       // The label was already in the hash table.
3036       label = ins.first->second;
3037       if (label->is_defined())
3038         {
3039           error_at(location, "label %qs already defined",
3040                    Gogo::message_name(label_name).c_str());
3041           inform(label->location(), "previous definition of %qs was here",
3042                  Gogo::message_name(label_name).c_str());
3043           return new Label(label_name);
3044         }
3045     }
3046
3047   label->define(location, gogo->bindings_snapshot(location));
3048
3049   // Issue any errors appropriate for any previous goto's to this
3050   // label.
3051   const std::vector<Bindings_snapshot*>& refs(label->refs());
3052   for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3053        p != refs.end();
3054        ++p)
3055     (*p)->check_goto_to(gogo->current_block());
3056   label->clear_refs();
3057
3058   return label;
3059 }
3060
3061 // Add a reference to a label.
3062
3063 Label*
3064 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3065                               Location location, bool issue_goto_errors)
3066 {
3067   Label* lnull = NULL;
3068   std::pair<Labels::iterator, bool> ins =
3069     this->labels_.insert(std::make_pair(label_name, lnull));
3070   Label* label;
3071   if (!ins.second)
3072     {
3073       // The label was already in the hash table.
3074       label = ins.first->second;
3075     }
3076   else
3077     {
3078       go_assert(ins.first->second == NULL);
3079       label = new Label(label_name);
3080       ins.first->second = label;
3081     }
3082
3083   label->set_is_used();
3084
3085   if (issue_goto_errors)
3086     {
3087       Bindings_snapshot* snapshot = label->snapshot();
3088       if (snapshot != NULL)
3089         snapshot->check_goto_from(gogo->current_block(), location);
3090       else
3091         label->add_snapshot_ref(gogo->bindings_snapshot(location));
3092     }
3093
3094   return label;
3095 }
3096
3097 // Warn about labels that are defined but not used.
3098
3099 void
3100 Function::check_labels() const
3101 {
3102   for (Labels::const_iterator p = this->labels_.begin();
3103        p != this->labels_.end();
3104        p++)
3105     {
3106       Label* label = p->second;
3107       if (!label->is_used())
3108         error_at(label->location(), "label %qs defined and not used",
3109                  Gogo::message_name(label->name()).c_str());
3110     }
3111 }
3112
3113 // Swap one function with another.  This is used when building the
3114 // thunk we use to call a function which calls recover.  It may not
3115 // work for any other case.
3116
3117 void
3118 Function::swap_for_recover(Function *x)
3119 {
3120   go_assert(this->enclosing_ == x->enclosing_);
3121   std::swap(this->results_, x->results_);
3122   std::swap(this->closure_var_, x->closure_var_);
3123   std::swap(this->block_, x->block_);
3124   go_assert(this->location_ == x->location_);
3125   go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3126   go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3127 }
3128
3129 // Traverse the tree.
3130
3131 int
3132 Function::traverse(Traverse* traverse)
3133 {
3134   unsigned int traverse_mask = traverse->traverse_mask();
3135
3136   if ((traverse_mask
3137        & (Traverse::traverse_types | Traverse::traverse_expressions))
3138       != 0)
3139     {
3140       if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3141         return TRAVERSE_EXIT;
3142     }
3143
3144   // FIXME: We should check traverse_functions here if nested
3145   // functions are stored in block bindings.
3146   if (this->block_ != NULL
3147       && (traverse_mask
3148           & (Traverse::traverse_variables
3149              | Traverse::traverse_constants
3150              | Traverse::traverse_blocks
3151              | Traverse::traverse_statements
3152              | Traverse::traverse_expressions
3153              | Traverse::traverse_types)) != 0)
3154     {
3155       if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3156         return TRAVERSE_EXIT;
3157     }
3158
3159   return TRAVERSE_CONTINUE;
3160 }
3161
3162 // Work out types for unspecified variables and constants.
3163
3164 void
3165 Function::determine_types()
3166 {
3167   if (this->block_ != NULL)
3168     this->block_->determine_types();
3169 }
3170
3171 // Get a pointer to the variable representing the defer stack for this
3172 // function, making it if necessary.  The value of the variable is set
3173 // by the runtime routines to true if the function is returning,
3174 // rather than panicing through.  A pointer to this variable is used
3175 // as a marker for the functions on the defer stack associated with
3176 // this function.  A function-specific variable permits inlining a
3177 // function which uses defer.
3178
3179 Expression*
3180 Function::defer_stack(Location location)
3181 {
3182   if (this->defer_stack_ == NULL)
3183     {
3184       Type* t = Type::lookup_bool_type();
3185       Expression* n = Expression::make_boolean(false, location);
3186       this->defer_stack_ = Statement::make_temporary(t, n, location);
3187       this->defer_stack_->set_is_address_taken();
3188     }
3189   Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3190                                                          location);
3191   return Expression::make_unary(OPERATOR_AND, ref, location);
3192 }
3193
3194 // Export the function.
3195
3196 void
3197 Function::export_func(Export* exp, const std::string& name) const
3198 {
3199   Function::export_func_with_type(exp, name, this->type_);
3200 }
3201
3202 // Export a function with a type.
3203
3204 void
3205 Function::export_func_with_type(Export* exp, const std::string& name,
3206                                 const Function_type* fntype)
3207 {
3208   exp->write_c_string("func ");
3209
3210   if (fntype->is_method())
3211     {
3212       exp->write_c_string("(");
3213       exp->write_type(fntype->receiver()->type());
3214       exp->write_c_string(") ");
3215     }
3216
3217   exp->write_string(name);
3218
3219   exp->write_c_string(" (");
3220   const Typed_identifier_list* parameters = fntype->parameters();
3221   if (parameters != NULL)
3222     {
3223       bool is_varargs = fntype->is_varargs();
3224       bool first = true;
3225       for (Typed_identifier_list::const_iterator p = parameters->begin();
3226            p != parameters->end();
3227            ++p)
3228         {
3229           if (first)
3230             first = false;
3231           else
3232             exp->write_c_string(", ");
3233           if (!is_varargs || p + 1 != parameters->end())
3234             exp->write_type(p->type());
3235           else
3236             {
3237               exp->write_c_string("...");
3238               exp->write_type(p->type()->array_type()->element_type());
3239             }
3240         }
3241     }
3242   exp->write_c_string(")");
3243
3244   const Typed_identifier_list* results = fntype->results();
3245   if (results != NULL)
3246     {
3247       if (results->size() == 1)
3248         {
3249           exp->write_c_string(" ");
3250           exp->write_type(results->begin()->type());
3251         }
3252       else
3253         {
3254           exp->write_c_string(" (");
3255           bool first = true;
3256           for (Typed_identifier_list::const_iterator p = results->begin();
3257                p != results->end();
3258                ++p)
3259             {
3260               if (first)
3261                 first = false;
3262               else
3263                 exp->write_c_string(", ");
3264               exp->write_type(p->type());
3265             }
3266           exp->write_c_string(")");
3267         }
3268     }
3269   exp->write_c_string(";\n");
3270 }
3271
3272 // Import a function.
3273
3274 void
3275 Function::import_func(Import* imp, std::string* pname,
3276                       Typed_identifier** preceiver,
3277                       Typed_identifier_list** pparameters,
3278                       Typed_identifier_list** presults,
3279                       bool* is_varargs)
3280 {
3281   imp->require_c_string("func ");
3282
3283   *preceiver = NULL;
3284   if (imp->peek_char() == '(')
3285     {
3286       imp->require_c_string("(");
3287       Type* rtype = imp->read_type();
3288       *preceiver = new Typed_identifier(Import::import_marker, rtype,
3289                                         imp->location());
3290       imp->require_c_string(") ");
3291     }
3292
3293   *pname = imp->read_identifier();
3294
3295   Typed_identifier_list* parameters;
3296   *is_varargs = false;
3297   imp->require_c_string(" (");
3298   if (imp->peek_char() == ')')
3299     parameters = NULL;
3300   else
3301     {
3302       parameters = new Typed_identifier_list();
3303       while (true)
3304         {
3305           if (imp->match_c_string("..."))
3306             {
3307               imp->advance(3);
3308               *is_varargs = true;
3309             }
3310
3311           Type* ptype = imp->read_type();
3312           if (*is_varargs)
3313             ptype = Type::make_array_type(ptype, NULL);
3314           parameters->push_back(Typed_identifier(Import::import_marker,
3315                                                  ptype, imp->location()));
3316           if (imp->peek_char() != ',')
3317             break;
3318           go_assert(!*is_varargs);
3319           imp->require_c_string(", ");
3320         }
3321     }
3322   imp->require_c_string(")");
3323   *pparameters = parameters;
3324
3325   Typed_identifier_list* results;
3326   if (imp->peek_char() != ' ')
3327     results = NULL;
3328   else
3329     {
3330       results = new Typed_identifier_list();
3331       imp->require_c_string(" ");
3332       if (imp->peek_char() != '(')
3333         {
3334           Type* rtype = imp->read_type();
3335           results->push_back(Typed_identifier(Import::import_marker, rtype,
3336                                               imp->location()));
3337         }
3338       else
3339         {
3340           imp->require_c_string("(");
3341           while (true)
3342             {
3343               Type* rtype = imp->read_type();
3344               results->push_back(Typed_identifier(Import::import_marker,
3345                                                   rtype, imp->location()));
3346               if (imp->peek_char() != ',')
3347                 break;
3348               imp->require_c_string(", ");
3349             }
3350           imp->require_c_string(")");
3351         }
3352     }
3353   imp->require_c_string(";\n");
3354   *presults = results;
3355 }
3356
3357 // Class Block.
3358
3359 Block::Block(Block* enclosing, Location location)
3360   : enclosing_(enclosing), statements_(),
3361     bindings_(new Bindings(enclosing == NULL
3362                            ? NULL
3363                            : enclosing->bindings())),
3364     start_location_(location),
3365     end_location_(UNKNOWN_LOCATION)
3366 {
3367 }
3368
3369 // Add a statement to a block.
3370
3371 void
3372 Block::add_statement(Statement* statement)
3373 {
3374   this->statements_.push_back(statement);
3375 }
3376
3377 // Add a statement to the front of a block.  This is slow but is only
3378 // used for reference counts of parameters.
3379
3380 void
3381 Block::add_statement_at_front(Statement* statement)
3382 {
3383   this->statements_.insert(this->statements_.begin(), statement);
3384 }
3385
3386 // Replace a statement in a block.
3387
3388 void
3389 Block::replace_statement(size_t index, Statement* s)
3390 {
3391   go_assert(index < this->statements_.size());
3392   this->statements_[index] = s;
3393 }
3394
3395 // Add a statement before another statement.
3396
3397 void
3398 Block::insert_statement_before(size_t index, Statement* s)
3399 {
3400   go_assert(index < this->statements_.size());
3401   this->statements_.insert(this->statements_.begin() + index, s);
3402 }
3403
3404 // Add a statement after another statement.
3405
3406 void
3407 Block::insert_statement_after(size_t index, Statement* s)
3408 {
3409   go_assert(index < this->statements_.size());
3410   this->statements_.insert(this->statements_.begin() + index + 1, s);
3411 }
3412
3413 // Traverse the tree.
3414
3415 int
3416 Block::traverse(Traverse* traverse)
3417 {
3418   unsigned int traverse_mask = traverse->traverse_mask();
3419
3420   if ((traverse_mask & Traverse::traverse_blocks) != 0)
3421     {
3422       int t = traverse->block(this);
3423       if (t == TRAVERSE_EXIT)
3424         return TRAVERSE_EXIT;
3425       else if (t == TRAVERSE_SKIP_COMPONENTS)
3426         return TRAVERSE_CONTINUE;
3427     }
3428
3429   if ((traverse_mask
3430        & (Traverse::traverse_variables
3431           | Traverse::traverse_constants
3432           | Traverse::traverse_expressions
3433           | Traverse::traverse_types)) != 0)
3434     {
3435       const unsigned int e_or_t = (Traverse::traverse_expressions
3436                                    | Traverse::traverse_types);
3437       const unsigned int e_or_t_or_s = (e_or_t
3438                                         | Traverse::traverse_statements);
3439       for (Bindings::const_definitions_iterator pb =
3440              this->bindings_->begin_definitions();
3441            pb != this->bindings_->end_definitions();
3442            ++pb)
3443         {
3444           int t = TRAVERSE_CONTINUE;
3445           switch ((*pb)->classification())
3446             {
3447             case Named_object::NAMED_OBJECT_CONST:
3448               if ((traverse_mask & Traverse::traverse_constants) != 0)
3449                 t = traverse->constant(*pb, false);
3450               if (t == TRAVERSE_CONTINUE
3451                   && (traverse_mask & e_or_t) != 0)
3452                 {
3453                   Type* tc = (*pb)->const_value()->type();
3454                   if (tc != NULL
3455                       && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3456                     return TRAVERSE_EXIT;
3457                   t = (*pb)->const_value()->traverse_expression(traverse);
3458                 }
3459               break;
3460
3461             case Named_object::NAMED_OBJECT_VAR:
3462             case Named_object::NAMED_OBJECT_RESULT_VAR:
3463               if ((traverse_mask & Traverse::traverse_variables) != 0)
3464                 t = traverse->variable(*pb);
3465               if (t == TRAVERSE_CONTINUE
3466                   && (traverse_mask & e_or_t) != 0)
3467                 {
3468                   if ((*pb)->is_result_variable()
3469                       || (*pb)->var_value()->has_type())
3470                     {
3471                       Type* tv = ((*pb)->is_variable()
3472                                   ? (*pb)->var_value()->type()
3473                                   : (*pb)->result_var_value()->type());
3474                       if (tv != NULL
3475                           && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3476                         return TRAVERSE_EXIT;
3477                     }
3478                 }
3479               if (t == TRAVERSE_CONTINUE
3480                   && (traverse_mask & e_or_t_or_s) != 0
3481                   && (*pb)->is_variable())
3482                 t = (*pb)->var_value()->traverse_expression(traverse,
3483                                                             traverse_mask);
3484               break;
3485
3486             case Named_object::NAMED_OBJECT_FUNC:
3487             case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3488               go_unreachable();
3489
3490             case Named_object::NAMED_OBJECT_TYPE:
3491               if ((traverse_mask & e_or_t) != 0)
3492                 t = Type::traverse((*pb)->type_value(), traverse);
3493               break;
3494
3495             case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3496             case Named_object::NAMED_OBJECT_UNKNOWN:
3497               break;
3498
3499             case Named_object::NAMED_OBJECT_PACKAGE:
3500             case Named_object::NAMED_OBJECT_SINK:
3501               go_unreachable();
3502
3503             default:
3504               go_unreachable();
3505             }
3506
3507           if (t == TRAVERSE_EXIT)
3508             return TRAVERSE_EXIT;
3509         }
3510     }
3511
3512   // No point in checking traverse_mask here--if we got here we always
3513   // want to walk the statements.  The traversal can insert new
3514   // statements before or after the current statement.  Inserting
3515   // statements before the current statement requires updating I via
3516   // the pointer; those statements will not be traversed.  Any new
3517   // statements inserted after the current statement will be traversed
3518   // in their turn.
3519   for (size_t i = 0; i < this->statements_.size(); ++i)
3520     {
3521       if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3522         return TRAVERSE_EXIT;
3523     }
3524
3525   return TRAVERSE_CONTINUE;
3526 }
3527
3528 // Work out types for unspecified variables and constants.
3529
3530 void
3531 Block::determine_types()