OSDN Git Service

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