OSDN Git Service

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