OSDN Git Service

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