OSDN Git Service

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