OSDN Git Service

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