OSDN Git Service

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