OSDN Git Service

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