OSDN Git Service

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