OSDN Git Service

349ee255382df48e73e0c2f1dd2d0223a6943c03
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / gogo-tree.cc
1 // gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees.
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 <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "toplev.h"
17 #include "tree.h"
18 #include "gimple.h"
19 #include "tree-iterator.h"
20 #include "cgraph.h"
21 #include "langhooks.h"
22 #include "convert.h"
23 #include "output.h"
24 #include "diagnostic.h"
25
26 #ifndef ENABLE_BUILD_WITH_CXX
27 }
28 #endif
29
30 #include "go-c.h"
31 #include "types.h"
32 #include "expressions.h"
33 #include "statements.h"
34 #include "runtime.h"
35 #include "backend.h"
36 #include "gogo.h"
37
38 // Whether we have seen any errors.
39
40 bool
41 saw_errors()
42 {
43   return errorcount != 0 || sorrycount != 0;
44 }
45
46 // A helper function.
47
48 static inline tree
49 get_identifier_from_string(const std::string& str)
50 {
51   return get_identifier_with_length(str.data(), str.length());
52 }
53
54 // Builtin functions.
55
56 static std::map<std::string, tree> builtin_functions;
57
58 // Define a builtin function.  BCODE is the builtin function code
59 // defined by builtins.def.  NAME is the name of the builtin function.
60 // LIBNAME is the name of the corresponding library function, and is
61 // NULL if there isn't one.  FNTYPE is the type of the function.
62 // CONST_P is true if the function has the const attribute.
63
64 static void
65 define_builtin(built_in_function bcode, const char* name, const char* libname,
66                tree fntype, bool const_p)
67 {
68   tree decl = add_builtin_function(name, fntype, bcode, BUILT_IN_NORMAL,
69                                    libname, NULL_TREE);
70   if (const_p)
71     TREE_READONLY(decl) = 1;
72   set_builtin_decl(bcode, decl, true);
73   builtin_functions[name] = decl;
74   if (libname != NULL)
75     {
76       decl = add_builtin_function(libname, fntype, bcode, BUILT_IN_NORMAL,
77                                   NULL, NULL_TREE);
78       if (const_p)
79         TREE_READONLY(decl) = 1;
80       builtin_functions[libname] = decl;
81     }
82 }
83
84 // Create trees for implicit builtin functions.
85
86 void
87 Gogo::define_builtin_function_trees()
88 {
89   /* We need to define the fetch_and_add functions, since we use them
90      for ++ and --.  */
91   tree t = go_type_for_size(BITS_PER_UNIT, 1);
92   tree p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
93   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_1, "__sync_fetch_and_add_1", NULL,
94                  build_function_type_list(t, p, t, NULL_TREE), false);
95
96   t = go_type_for_size(BITS_PER_UNIT * 2, 1);
97   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
98   define_builtin (BUILT_IN_SYNC_ADD_AND_FETCH_2, "__sync_fetch_and_add_2", NULL,
99                   build_function_type_list(t, p, t, NULL_TREE), false);
100
101   t = go_type_for_size(BITS_PER_UNIT * 4, 1);
102   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
103   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_4, "__sync_fetch_and_add_4", NULL,
104                  build_function_type_list(t, p, t, NULL_TREE), false);
105
106   t = go_type_for_size(BITS_PER_UNIT * 8, 1);
107   p = build_pointer_type(build_qualified_type(t, TYPE_QUAL_VOLATILE));
108   define_builtin(BUILT_IN_SYNC_ADD_AND_FETCH_8, "__sync_fetch_and_add_8", NULL,
109                  build_function_type_list(t, p, t, NULL_TREE), false);
110
111   // We use __builtin_expect for magic import functions.
112   define_builtin(BUILT_IN_EXPECT, "__builtin_expect", NULL,
113                  build_function_type_list(long_integer_type_node,
114                                           long_integer_type_node,
115                                           long_integer_type_node,
116                                           NULL_TREE),
117                  true);
118
119   // We use __builtin_memmove for the predeclared copy function.
120   define_builtin(BUILT_IN_MEMMOVE, "__builtin_memmove", "memmove",
121                  build_function_type_list(ptr_type_node,
122                                           ptr_type_node,
123                                           const_ptr_type_node,
124                                           size_type_node,
125                                           NULL_TREE),
126                  false);
127
128   // We provide sqrt for the math library.
129   define_builtin(BUILT_IN_SQRT, "__builtin_sqrt", "sqrt",
130                  build_function_type_list(double_type_node,
131                                           double_type_node,
132                                           NULL_TREE),
133                  true);
134   define_builtin(BUILT_IN_SQRTL, "__builtin_sqrtl", "sqrtl",
135                  build_function_type_list(long_double_type_node,
136                                           long_double_type_node,
137                                           NULL_TREE),
138                  true);
139
140   // We use __builtin_return_address in the thunk we build for
141   // functions which call recover.
142   define_builtin(BUILT_IN_RETURN_ADDRESS, "__builtin_return_address", NULL,
143                  build_function_type_list(ptr_type_node,
144                                           unsigned_type_node,
145                                           NULL_TREE),
146                  false);
147
148   // The compiler uses __builtin_trap for some exception handling
149   // cases.
150   define_builtin(BUILT_IN_TRAP, "__builtin_trap", NULL,
151                  build_function_type(void_type_node, void_list_node),
152                  false);
153 }
154
155 // Get the name to use for the import control function.  If there is a
156 // global function or variable, then we know that that name must be
157 // unique in the link, and we use it as the basis for our name.
158
159 const std::string&
160 Gogo::get_init_fn_name()
161 {
162   if (this->init_fn_name_.empty())
163     {
164       go_assert(this->package_ != NULL);
165       if (this->is_main_package())
166         {
167           // Use a name which the runtime knows.
168           this->init_fn_name_ = "__go_init_main";
169         }
170       else
171         {
172           std::string s = this->unique_prefix();
173           s.append(1, '.');
174           s.append(this->package_name());
175           s.append("..import");
176           this->init_fn_name_ = s;
177         }
178     }
179
180   return this->init_fn_name_;
181 }
182
183 // Add statements to INIT_STMT_LIST which run the initialization
184 // functions for imported packages.  This is only used for the "main"
185 // package.
186
187 void
188 Gogo::init_imports(tree* init_stmt_list)
189 {
190   go_assert(this->is_main_package());
191
192   if (this->imported_init_fns_.empty())
193     return;
194
195   tree fntype = build_function_type(void_type_node, void_list_node);
196
197   // We must call them in increasing priority order.
198   std::vector<Import_init> v;
199   for (std::set<Import_init>::const_iterator p =
200          this->imported_init_fns_.begin();
201        p != this->imported_init_fns_.end();
202        ++p)
203     v.push_back(*p);
204   std::sort(v.begin(), v.end());
205
206   for (std::vector<Import_init>::const_iterator p = v.begin();
207        p != v.end();
208        ++p)
209     {
210       std::string user_name = p->package_name() + ".init";
211       tree decl = build_decl(UNKNOWN_LOCATION, FUNCTION_DECL,
212                              get_identifier_from_string(user_name),
213                              fntype);
214       const std::string& init_name(p->init_name());
215       SET_DECL_ASSEMBLER_NAME(decl, get_identifier_from_string(init_name));
216       TREE_PUBLIC(decl) = 1;
217       DECL_EXTERNAL(decl) = 1;
218       append_to_statement_list(build_call_expr(decl, 0), init_stmt_list);
219     }
220 }
221
222 // Register global variables with the garbage collector.  We need to
223 // register all variables which can hold a pointer value.  They become
224 // roots during the mark phase.  We build a struct that is easy to
225 // hook into a list of roots.
226
227 // struct __go_gc_root_list
228 // {
229 //   struct __go_gc_root_list* __next;
230 //   struct __go_gc_root
231 //   {
232 //     void* __decl;
233 //     size_t __size;
234 //   } __roots[];
235 // };
236
237 // The last entry in the roots array has a NULL decl field.
238
239 void
240 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
241                        tree* init_stmt_list)
242 {
243   if (var_gc.empty())
244     return;
245
246   size_t count = var_gc.size();
247
248   tree root_type = Gogo::builtin_struct(NULL, "__go_gc_root", NULL_TREE, 2,
249                                         "__next",
250                                         ptr_type_node,
251                                         "__size",
252                                         sizetype);
253
254   tree index_type = build_index_type(size_int(count));
255   tree array_type = build_array_type(root_type, index_type);
256
257   tree root_list_type = make_node(RECORD_TYPE);
258   root_list_type = Gogo::builtin_struct(NULL, "__go_gc_root_list",
259                                         root_list_type, 2,
260                                         "__next",
261                                         build_pointer_type(root_list_type),
262                                         "__roots",
263                                         array_type);
264
265   // Build an initialier for the __roots array.
266
267   VEC(constructor_elt,gc)* roots_init = VEC_alloc(constructor_elt, gc,
268                                                   count + 1);
269
270   size_t i = 0;
271   for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
272        p != var_gc.end();
273        ++p, ++i)
274     {
275       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
276
277       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
278       tree field = TYPE_FIELDS(root_type);
279       elt->index = field;
280       Bvariable* bvar = (*p)->get_backend_variable(this, NULL);
281       tree decl = var_to_tree(bvar);
282       go_assert(TREE_CODE(decl) == VAR_DECL);
283       elt->value = build_fold_addr_expr(decl);
284
285       elt = VEC_quick_push(constructor_elt, init, NULL);
286       field = DECL_CHAIN(field);
287       elt->index = field;
288       elt->value = DECL_SIZE_UNIT(decl);
289
290       elt = VEC_quick_push(constructor_elt, roots_init, NULL);
291       elt->index = size_int(i);
292       elt->value = build_constructor(root_type, init);
293     }
294
295   // The list ends with a NULL entry.
296
297   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
298
299   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
300   tree field = TYPE_FIELDS(root_type);
301   elt->index = field;
302   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
303
304   elt = VEC_quick_push(constructor_elt, init, NULL);
305   field = DECL_CHAIN(field);
306   elt->index = field;
307   elt->value = size_zero_node;
308
309   elt = VEC_quick_push(constructor_elt, roots_init, NULL);
310   elt->index = size_int(i);
311   elt->value = build_constructor(root_type, init);
312
313   // Build a constructor for the struct.
314
315   VEC(constructor_elt,gc*) root_list_init = VEC_alloc(constructor_elt, gc, 2);
316
317   elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
318   field = TYPE_FIELDS(root_list_type);
319   elt->index = field;
320   elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
321
322   elt = VEC_quick_push(constructor_elt, root_list_init, NULL);
323   field = DECL_CHAIN(field);
324   elt->index = field;
325   elt->value = build_constructor(array_type, roots_init);
326
327   // Build a decl to register.
328
329   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL,
330                          create_tmp_var_name("gc"), root_list_type);
331   DECL_EXTERNAL(decl) = 0;
332   TREE_PUBLIC(decl) = 0;
333   TREE_STATIC(decl) = 1;
334   DECL_ARTIFICIAL(decl) = 1;
335   DECL_INITIAL(decl) = build_constructor(root_list_type, root_list_init);
336   rest_of_decl_compilation(decl, 1, 0);
337
338   static tree register_gc_fndecl;
339   tree call = Gogo::call_builtin(&register_gc_fndecl, BUILTINS_LOCATION,
340                                  "__go_register_gc_roots",
341                                  1,
342                                  void_type_node,
343                                  build_pointer_type(root_list_type),
344                                  build_fold_addr_expr(decl));
345   if (call != error_mark_node)
346     append_to_statement_list(call, init_stmt_list);
347 }
348
349 // Build the decl for the initialization function.
350
351 tree
352 Gogo::initialization_function_decl()
353 {
354   // The tedious details of building your own function.  There doesn't
355   // seem to be a helper function for this.
356   std::string name = this->package_name() + ".init";
357   tree fndecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL,
358                            get_identifier_from_string(name),
359                            build_function_type(void_type_node,
360                                                void_list_node));
361   const std::string& asm_name(this->get_init_fn_name());
362   SET_DECL_ASSEMBLER_NAME(fndecl, get_identifier_from_string(asm_name));
363
364   tree resdecl = build_decl(BUILTINS_LOCATION, RESULT_DECL, NULL_TREE,
365                             void_type_node);
366   DECL_ARTIFICIAL(resdecl) = 1;
367   DECL_CONTEXT(resdecl) = fndecl;
368   DECL_RESULT(fndecl) = resdecl;
369
370   TREE_STATIC(fndecl) = 1;
371   TREE_USED(fndecl) = 1;
372   DECL_ARTIFICIAL(fndecl) = 1;
373   TREE_PUBLIC(fndecl) = 1;
374
375   DECL_INITIAL(fndecl) = make_node(BLOCK);
376   TREE_USED(DECL_INITIAL(fndecl)) = 1;
377
378   return fndecl;
379 }
380
381 // Create the magic initialization function.  INIT_STMT_LIST is the
382 // code that it needs to run.
383
384 void
385 Gogo::write_initialization_function(tree fndecl, tree init_stmt_list)
386 {
387   // Make sure that we thought we needed an initialization function,
388   // as otherwise we will not have reported it in the export data.
389   go_assert(this->is_main_package() || this->need_init_fn_);
390
391   if (fndecl == NULL_TREE)
392     fndecl = this->initialization_function_decl();
393
394   DECL_SAVED_TREE(fndecl) = init_stmt_list;
395
396   current_function_decl = fndecl;
397   if (DECL_STRUCT_FUNCTION(fndecl) == NULL)
398     push_struct_function(fndecl);
399   else
400     push_cfun(DECL_STRUCT_FUNCTION(fndecl));
401   cfun->function_end_locus = BUILTINS_LOCATION;
402
403   gimplify_function_tree(fndecl);
404
405   cgraph_add_new_function(fndecl, false);
406   cgraph_mark_needed_node(cgraph_get_node(fndecl));
407
408   current_function_decl = NULL_TREE;
409   pop_cfun();
410 }
411
412 // Search for references to VAR in any statements or called functions.
413
414 class Find_var : public Traverse
415 {
416  public:
417   // A hash table we use to avoid looping.  The index is the name of a
418   // named object.  We only look through objects defined in this
419   // package.
420   typedef Unordered_set(std::string) Seen_objects;
421
422   Find_var(Named_object* var, Seen_objects* seen_objects)
423     : Traverse(traverse_expressions),
424       var_(var), seen_objects_(seen_objects), found_(false)
425   { }
426
427   // Whether the variable was found.
428   bool
429   found() const
430   { return this->found_; }
431
432   int
433   expression(Expression**);
434
435  private:
436   // The variable we are looking for.
437   Named_object* var_;
438   // Names of objects we have already seen.
439   Seen_objects* seen_objects_;
440   // True if the variable was found.
441   bool found_;
442 };
443
444 // See if EXPR refers to VAR, looking through function calls and
445 // variable initializations.
446
447 int
448 Find_var::expression(Expression** pexpr)
449 {
450   Expression* e = *pexpr;
451
452   Var_expression* ve = e->var_expression();
453   if (ve != NULL)
454     {
455       Named_object* v = ve->named_object();
456       if (v == this->var_)
457         {
458           this->found_ = true;
459           return TRAVERSE_EXIT;
460         }
461
462       if (v->is_variable() && v->package() == NULL)
463         {
464           Expression* init = v->var_value()->init();
465           if (init != NULL)
466             {
467               std::pair<Seen_objects::iterator, bool> ins =
468                 this->seen_objects_->insert(v->name());
469               if (ins.second)
470                 {
471                   // This is the first time we have seen this name.
472                   if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
473                     return TRAVERSE_EXIT;
474                 }
475             }
476         }
477     }
478
479   // We traverse the code of any function we see.  Note that this
480   // means that we will traverse the code of a function whose address
481   // is taken even if it is not called.
482   Func_expression* fe = e->func_expression();
483   if (fe != NULL)
484     {
485       const Named_object* f = fe->named_object();
486       if (f->is_function() && f->package() == NULL)
487         {
488           std::pair<Seen_objects::iterator, bool> ins =
489             this->seen_objects_->insert(f->name());
490           if (ins.second)
491             {
492               // This is the first time we have seen this name.
493               if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
494                 return TRAVERSE_EXIT;
495             }
496         }
497     }
498
499   return TRAVERSE_CONTINUE;
500 }
501
502 // Return true if EXPR refers to VAR.
503
504 static bool
505 expression_requires(Expression* expr, Block* preinit, Named_object* var)
506 {
507   Find_var::Seen_objects seen_objects;
508   Find_var find_var(var, &seen_objects);
509   if (expr != NULL)
510     Expression::traverse(&expr, &find_var);
511   if (preinit != NULL)
512     preinit->traverse(&find_var);
513   
514   return find_var.found();
515 }
516
517 // Sort variable initializations.  If the initialization expression
518 // for variable A refers directly or indirectly to the initialization
519 // expression for variable B, then we must initialize B before A.
520
521 class Var_init
522 {
523  public:
524   Var_init()
525     : var_(NULL), init_(NULL_TREE), waiting_(0)
526   { }
527
528   Var_init(Named_object* var, tree init)
529     : var_(var), init_(init), waiting_(0)
530   { }
531
532   // Return the variable.
533   Named_object*
534   var() const
535   { return this->var_; }
536
537   // Return the initialization expression.
538   tree
539   init() const
540   { return this->init_; }
541
542   // Return the number of variables waiting for this one to be
543   // initialized.
544   size_t
545   waiting() const
546   { return this->waiting_; }
547
548   // Increment the number waiting.
549   void
550   increment_waiting()
551   { ++this->waiting_; }
552
553  private:
554   // The variable being initialized.
555   Named_object* var_;
556   // The initialization expression to run.
557   tree init_;
558   // The number of variables which are waiting for this one.
559   size_t waiting_;
560 };
561
562 typedef std::list<Var_init> Var_inits;
563
564 // Sort the variable initializations.  The rule we follow is that we
565 // emit them in the order they appear in the array, except that if the
566 // initialization expression for a variable V1 depends upon another
567 // variable V2 then we initialize V1 after V2.
568
569 static void
570 sort_var_inits(Var_inits* var_inits)
571 {
572   Var_inits ready;
573   while (!var_inits->empty())
574     {
575       Var_inits::iterator p1 = var_inits->begin();
576       Named_object* var = p1->var();
577       Expression* init = var->var_value()->init();
578       Block* preinit = var->var_value()->preinit();
579
580       // Start walking through the list to see which variables VAR
581       // needs to wait for.  We can skip P1->WAITING variables--that
582       // is the number we've already checked.
583       Var_inits::iterator p2 = p1;
584       ++p2;
585       for (size_t i = p1->waiting(); i > 0; --i)
586         ++p2;
587
588       for (; p2 != var_inits->end(); ++p2)
589         {
590           if (expression_requires(init, preinit, p2->var()))
591             {
592               // Check for cycles.
593               if (expression_requires(p2->var()->var_value()->init(),
594                                       p2->var()->var_value()->preinit(),
595                                       var))
596                 {
597                   error_at(var->location(),
598                            ("initialization expressions for %qs and "
599                             "%qs depend upon each other"),
600                            var->message_name().c_str(),
601                            p2->var()->message_name().c_str());
602                   inform(p2->var()->location(), "%qs defined here",
603                          p2->var()->message_name().c_str());
604                   p2 = var_inits->end();
605                 }
606               else
607                 {
608                   // We can't emit P1 until P2 is emitted.  Move P1.
609                   // Note that the WAITING loop always executes at
610                   // least once, which is what we want.
611                   p2->increment_waiting();
612                   Var_inits::iterator p3 = p2;
613                   for (size_t i = p2->waiting(); i > 0; --i)
614                     ++p3;
615                   var_inits->splice(p3, *var_inits, p1);
616                 }
617               break;
618             }
619         }
620
621       if (p2 == var_inits->end())
622         {
623           // VAR does not depends upon any other initialization expressions.
624
625           // Check for a loop of VAR on itself.  We only do this if
626           // INIT is not NULL; when INIT is NULL, it means that
627           // PREINIT sets VAR, which we will interpret as a loop.
628           if (init != NULL && expression_requires(init, preinit, var))
629             error_at(var->location(),
630                      "initialization expression for %qs depends upon itself",
631                      var->message_name().c_str());
632           ready.splice(ready.end(), *var_inits, p1);
633         }
634     }
635
636   // Now READY is the list in the desired initialization order.
637   var_inits->swap(ready);
638 }
639
640 // Write out the global definitions.
641
642 void
643 Gogo::write_globals()
644 {
645   this->convert_named_types();
646   this->build_interface_method_tables();
647
648   Bindings* bindings = this->current_bindings();
649   size_t count = bindings->size_definitions();
650
651   tree* vec = new tree[count];
652
653   tree init_fndecl = NULL_TREE;
654   tree init_stmt_list = NULL_TREE;
655
656   if (this->is_main_package())
657     this->init_imports(&init_stmt_list);
658
659   // A list of variable initializations.
660   Var_inits var_inits;
661
662   // A list of variables which need to be registered with the garbage
663   // collector.
664   std::vector<Named_object*> var_gc;
665   var_gc.reserve(count);
666
667   tree var_init_stmt_list = NULL_TREE;
668   size_t i = 0;
669   for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
670        p != bindings->end_definitions();
671        ++p, ++i)
672     {
673       Named_object* no = *p;
674
675       go_assert(!no->is_type_declaration() && !no->is_function_declaration());
676       // There is nothing to do for a package.
677       if (no->is_package())
678         {
679           --i;
680           --count;
681           continue;
682         }
683
684       // There is nothing to do for an object which was imported from
685       // a different package into the global scope.
686       if (no->package() != NULL)
687         {
688           --i;
689           --count;
690           continue;
691         }
692
693       // There is nothing useful we can output for constants which
694       // have ideal or non-integeral type.
695       if (no->is_const())
696         {
697           Type* type = no->const_value()->type();
698           if (type == NULL)
699             type = no->const_value()->expr()->type();
700           if (type->is_abstract() || type->integer_type() == NULL)
701             {
702               --i;
703               --count;
704               continue;
705             }
706         }
707
708       if (!no->is_variable())
709         {
710           vec[i] = no->get_tree(this, NULL);
711           if (vec[i] == error_mark_node)
712             {
713               go_assert(saw_errors());
714               --i;
715               --count;
716               continue;
717             }
718         }
719       else
720         {
721           Bvariable* var = no->get_backend_variable(this, NULL);
722           vec[i] = var_to_tree(var);
723           if (vec[i] == error_mark_node)
724             {
725               go_assert(saw_errors());
726               --i;
727               --count;
728               continue;
729             }
730
731           // Check for a sink variable, which may be used to run an
732           // initializer purely for its side effects.
733           bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
734
735           tree var_init_tree = NULL_TREE;
736           if (!no->var_value()->has_pre_init())
737             {
738               tree init = no->var_value()->get_init_tree(this, NULL);
739               if (init == error_mark_node)
740                 go_assert(saw_errors());
741               else if (init == NULL_TREE)
742                 ;
743               else if (TREE_CONSTANT(init))
744                 this->backend()->global_variable_set_init(var,
745                                                           tree_to_expr(init));
746               else if (is_sink)
747                 var_init_tree = init;
748               else
749                 var_init_tree = fold_build2_loc(no->location(), MODIFY_EXPR,
750                                                 void_type_node, vec[i], init);
751             }
752           else
753             {
754               // We are going to create temporary variables which
755               // means that we need an fndecl.
756               if (init_fndecl == NULL_TREE)
757                 init_fndecl = this->initialization_function_decl();
758               current_function_decl = init_fndecl;
759               if (DECL_STRUCT_FUNCTION(init_fndecl) == NULL)
760                 push_struct_function(init_fndecl);
761               else
762                 push_cfun(DECL_STRUCT_FUNCTION(init_fndecl));
763
764               tree var_decl = is_sink ? NULL_TREE : vec[i];
765               var_init_tree = no->var_value()->get_init_block(this, NULL,
766                                                               var_decl);
767
768               current_function_decl = NULL_TREE;
769               pop_cfun();
770             }
771
772           if (var_init_tree != NULL_TREE && var_init_tree != error_mark_node)
773             {
774               if (no->var_value()->init() == NULL
775                   && !no->var_value()->has_pre_init())
776                 append_to_statement_list(var_init_tree, &var_init_stmt_list);
777               else
778                 var_inits.push_back(Var_init(no, var_init_tree));
779             }
780
781           if (!is_sink && no->var_value()->type()->has_pointer())
782             var_gc.push_back(no);
783         }
784     }
785
786   // Register global variables with the garbage collector.
787   this->register_gc_vars(var_gc, &init_stmt_list);
788
789   // Simple variable initializations, after all variables are
790   // registered.
791   append_to_statement_list(var_init_stmt_list, &init_stmt_list);
792
793   // Complex variable initializations, first sorting them into a
794   // workable order.
795   if (!var_inits.empty())
796     {
797       sort_var_inits(&var_inits);
798       for (Var_inits::const_iterator p = var_inits.begin();
799            p != var_inits.end();
800            ++p)
801         append_to_statement_list(p->init(), &init_stmt_list);
802     }
803
804   // After all the variables are initialized, call the "init"
805   // functions if there are any.
806   for (std::vector<Named_object*>::const_iterator p =
807          this->init_functions_.begin();
808        p != this->init_functions_.end();
809        ++p)
810     {
811       tree decl = (*p)->get_tree(this, NULL);
812       tree call = build_call_expr(decl, 0);
813       append_to_statement_list(call, &init_stmt_list);
814     }
815
816   // Set up a magic function to do all the initialization actions.
817   // This will be called if this package is imported.
818   if (init_stmt_list != NULL_TREE
819       || this->need_init_fn_
820       || this->is_main_package())
821     this->write_initialization_function(init_fndecl, init_stmt_list);
822
823   // Pass everything back to the middle-end.
824
825   wrapup_global_declarations(vec, count);
826
827   cgraph_finalize_compilation_unit();
828
829   check_global_declarations(vec, count);
830   emit_debug_global_declarations(vec, count);
831
832   delete[] vec;
833 }
834
835 // Get a tree for the identifier for a named object.
836
837 tree
838 Named_object::get_id(Gogo* gogo)
839 {
840   go_assert(!this->is_variable() && !this->is_result_variable());
841   std::string decl_name;
842   if (this->is_function_declaration()
843       && !this->func_declaration_value()->asm_name().empty())
844     decl_name = this->func_declaration_value()->asm_name();
845   else if (this->is_type()
846            && this->type_value()->location() == BUILTINS_LOCATION)
847     {
848       // We don't need the package name for builtin types.
849       decl_name = Gogo::unpack_hidden_name(this->name_);
850     }
851   else
852     {
853       std::string package_name;
854       if (this->package_ == NULL)
855         package_name = gogo->package_name();
856       else
857         package_name = this->package_->name();
858
859       decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
860
861       Function_type* fntype;
862       if (this->is_function())
863         fntype = this->func_value()->type();
864       else if (this->is_function_declaration())
865         fntype = this->func_declaration_value()->type();
866       else
867         fntype = NULL;
868       if (fntype != NULL && fntype->is_method())
869         {
870           decl_name.push_back('.');
871           decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
872         }
873     }
874   if (this->is_type())
875     {
876       const Named_object* in_function = this->type_value()->in_function();
877       if (in_function != NULL)
878         decl_name += '$' + in_function->name();
879     }
880   return get_identifier_from_string(decl_name);
881 }
882
883 // Get a tree for a named object.
884
885 tree
886 Named_object::get_tree(Gogo* gogo, Named_object* function)
887 {
888   if (this->tree_ != NULL_TREE)
889     return this->tree_;
890
891   tree name;
892   if (this->classification_ == NAMED_OBJECT_TYPE)
893     name = NULL_TREE;
894   else
895     name = this->get_id(gogo);
896   tree decl;
897   switch (this->classification_)
898     {
899     case NAMED_OBJECT_CONST:
900       {
901         Named_constant* named_constant = this->u_.const_value;
902         Translate_context subcontext(gogo, function, NULL, NULL);
903         tree expr_tree = named_constant->expr()->get_tree(&subcontext);
904         if (expr_tree == error_mark_node)
905           decl = error_mark_node;
906         else
907           {
908             Type* type = named_constant->type();
909             if (type != NULL && !type->is_abstract())
910               {
911                 if (type->is_error())
912                   expr_tree = error_mark_node;
913                 else
914                   {
915                     Btype* btype = type->get_backend(gogo);
916                     expr_tree = fold_convert(type_to_tree(btype), expr_tree);
917                   }
918               }
919             if (expr_tree == error_mark_node)
920               decl = error_mark_node;
921             else if (INTEGRAL_TYPE_P(TREE_TYPE(expr_tree)))
922               {
923                 decl = build_decl(named_constant->location(), CONST_DECL,
924                                   name, TREE_TYPE(expr_tree));
925                 DECL_INITIAL(decl) = expr_tree;
926                 TREE_CONSTANT(decl) = 1;
927                 TREE_READONLY(decl) = 1;
928               }
929             else
930               {
931                 // A CONST_DECL is only for an enum constant, so we
932                 // shouldn't use for non-integral types.  Instead we
933                 // just return the constant itself, rather than a
934                 // decl.
935                 decl = expr_tree;
936               }
937           }
938       }
939       break;
940
941     case NAMED_OBJECT_TYPE:
942       {
943         Named_type* named_type = this->u_.type_value;
944         tree type_tree = type_to_tree(named_type->get_backend(gogo));
945         if (type_tree == error_mark_node)
946           decl = error_mark_node;
947         else
948           {
949             decl = TYPE_NAME(type_tree);
950             go_assert(decl != NULL_TREE);
951
952             // We need to produce a type descriptor for every named
953             // type, and for a pointer to every named type, since
954             // other files or packages might refer to them.  We need
955             // to do this even for hidden types, because they might
956             // still be returned by some function.  Simply calling the
957             // type_descriptor method is enough to create the type
958             // descriptor, even though we don't do anything with it.
959             if (this->package_ == NULL)
960               {
961                 named_type->type_descriptor_pointer(gogo, BUILTINS_LOCATION);
962                 Type* pn = Type::make_pointer_type(named_type);
963                 pn->type_descriptor_pointer(gogo, BUILTINS_LOCATION);
964               }
965           }
966       }
967       break;
968
969     case NAMED_OBJECT_TYPE_DECLARATION:
970       error("reference to undefined type %qs",
971             this->message_name().c_str());
972       return error_mark_node;
973
974     case NAMED_OBJECT_VAR:
975     case NAMED_OBJECT_RESULT_VAR:
976     case NAMED_OBJECT_SINK:
977       go_unreachable();
978
979     case NAMED_OBJECT_FUNC:
980       {
981         Function* func = this->u_.func_value;
982         decl = func->get_or_make_decl(gogo, this, name);
983         if (decl != error_mark_node)
984           {
985             if (func->block() != NULL)
986               {
987                 if (DECL_STRUCT_FUNCTION(decl) == NULL)
988                   push_struct_function(decl);
989                 else
990                   push_cfun(DECL_STRUCT_FUNCTION(decl));
991
992                 cfun->function_end_locus = func->block()->end_location();
993
994                 current_function_decl = decl;
995
996                 func->build_tree(gogo, this);
997
998                 gimplify_function_tree(decl);
999
1000                 cgraph_finalize_function(decl, true);
1001
1002                 current_function_decl = NULL_TREE;
1003                 pop_cfun();
1004               }
1005           }
1006       }
1007       break;
1008
1009     default:
1010       go_unreachable();
1011     }
1012
1013   if (TREE_TYPE(decl) == error_mark_node)
1014     decl = error_mark_node;
1015
1016   tree ret = decl;
1017
1018   this->tree_ = ret;
1019
1020   if (ret != error_mark_node)
1021     go_preserve_from_gc(ret);
1022
1023   return ret;
1024 }
1025
1026 // Get the initial value of a variable as a tree.  This does not
1027 // consider whether the variable is in the heap--it returns the
1028 // initial value as though it were always stored in the stack.
1029
1030 tree
1031 Variable::get_init_tree(Gogo* gogo, Named_object* function)
1032 {
1033   go_assert(this->preinit_ == NULL);
1034   if (this->init_ == NULL)
1035     {
1036       go_assert(!this->is_parameter_);
1037       if (this->is_global_ || this->is_in_heap())
1038         return NULL;
1039       Btype* btype = this->type_->get_backend(gogo);
1040       return expr_to_tree(gogo->backend()->zero_expression(btype));
1041     }
1042   else
1043     {
1044       Translate_context context(gogo, function, NULL, NULL);
1045       tree rhs_tree = this->init_->get_tree(&context);
1046       return Expression::convert_for_assignment(&context, this->type(),
1047                                                 this->init_->type(),
1048                                                 rhs_tree, this->location());
1049     }
1050 }
1051
1052 // Get the initial value of a variable when a block is required.
1053 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
1054
1055 tree
1056 Variable::get_init_block(Gogo* gogo, Named_object* function, tree var_decl)
1057 {
1058   go_assert(this->preinit_ != NULL);
1059
1060   // We want to add the variable assignment to the end of the preinit
1061   // block.  The preinit block may have a TRY_FINALLY_EXPR and a
1062   // TRY_CATCH_EXPR; if it does, we want to add to the end of the
1063   // regular statements.
1064
1065   Translate_context context(gogo, function, NULL, NULL);
1066   Bblock* bblock = this->preinit_->get_backend(&context);
1067   tree block_tree = block_to_tree(bblock);
1068   if (block_tree == error_mark_node)
1069     return error_mark_node;
1070   go_assert(TREE_CODE(block_tree) == BIND_EXPR);
1071   tree statements = BIND_EXPR_BODY(block_tree);
1072   while (statements != NULL_TREE
1073          && (TREE_CODE(statements) == TRY_FINALLY_EXPR
1074              || TREE_CODE(statements) == TRY_CATCH_EXPR))
1075     statements = TREE_OPERAND(statements, 0);
1076
1077   // It's possible to have pre-init statements without an initializer
1078   // if the pre-init statements set the variable.
1079   if (this->init_ != NULL)
1080     {
1081       tree rhs_tree = this->init_->get_tree(&context);
1082       if (rhs_tree == error_mark_node)
1083         return error_mark_node;
1084       if (var_decl == NULL_TREE)
1085         append_to_statement_list(rhs_tree, &statements);
1086       else
1087         {
1088           tree val = Expression::convert_for_assignment(&context, this->type(),
1089                                                         this->init_->type(),
1090                                                         rhs_tree,
1091                                                         this->location());
1092           if (val == error_mark_node)
1093             return error_mark_node;
1094           tree set = fold_build2_loc(this->location(), MODIFY_EXPR,
1095                                      void_type_node, var_decl, val);
1096           append_to_statement_list(set, &statements);
1097         }
1098     }
1099
1100   return block_tree;
1101 }
1102
1103 // Get a tree for a function decl.
1104
1105 tree
1106 Function::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1107 {
1108   if (this->fndecl_ == NULL_TREE)
1109     {
1110       tree functype = type_to_tree(this->type_->get_backend(gogo));
1111       if (functype == error_mark_node)
1112         this->fndecl_ = error_mark_node;
1113       else
1114         {
1115           // The type of a function comes back as a pointer, but we
1116           // want the real function type for a function declaration.
1117           go_assert(POINTER_TYPE_P(functype));
1118           functype = TREE_TYPE(functype);
1119           tree decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1120
1121           this->fndecl_ = decl;
1122
1123           if (no->package() != NULL)
1124             ;
1125           else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
1126             ;
1127           else if (Gogo::unpack_hidden_name(no->name()) == "init"
1128                    && !this->type_->is_method())
1129             ;
1130           else if (Gogo::unpack_hidden_name(no->name()) == "main"
1131                    && gogo->is_main_package())
1132             TREE_PUBLIC(decl) = 1;
1133           // Methods have to be public even if they are hidden because
1134           // they can be pulled into type descriptors when using
1135           // anonymous fields.
1136           else if (!Gogo::is_hidden_name(no->name())
1137                    || this->type_->is_method())
1138             {
1139               TREE_PUBLIC(decl) = 1;
1140               std::string asm_name = gogo->unique_prefix();
1141               asm_name.append(1, '.');
1142               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1143               SET_DECL_ASSEMBLER_NAME(decl,
1144                                       get_identifier_from_string(asm_name));
1145             }
1146
1147           // Why do we have to do this in the frontend?
1148           tree restype = TREE_TYPE(functype);
1149           tree resdecl = build_decl(this->location(), RESULT_DECL, NULL_TREE,
1150                                     restype);
1151           DECL_ARTIFICIAL(resdecl) = 1;
1152           DECL_IGNORED_P(resdecl) = 1;
1153           DECL_CONTEXT(resdecl) = decl;
1154           DECL_RESULT(decl) = resdecl;
1155
1156           if (this->enclosing_ != NULL)
1157             DECL_STATIC_CHAIN(decl) = 1;
1158
1159           // If a function calls the predeclared recover function, we
1160           // can't inline it, because recover behaves differently in a
1161           // function passed directly to defer.  If this is a recover
1162           // thunk that we built to test whether a function can be
1163           // recovered, we can't inline it, because that will mess up
1164           // our return address comparison.
1165           if (this->calls_recover_ || this->is_recover_thunk_)
1166             DECL_UNINLINABLE(decl) = 1;
1167
1168           // If this is a thunk created to call a function which calls
1169           // the predeclared recover function, we need to disable
1170           // stack splitting for the thunk.
1171           if (this->is_recover_thunk_)
1172             {
1173               tree attr = get_identifier("__no_split_stack__");
1174               DECL_ATTRIBUTES(decl) = tree_cons(attr, NULL_TREE, NULL_TREE);
1175             }
1176
1177           go_preserve_from_gc(decl);
1178
1179           if (this->closure_var_ != NULL)
1180             {
1181               push_struct_function(decl);
1182
1183               Bvariable* bvar = this->closure_var_->get_backend_variable(gogo,
1184                                                                          no);
1185               tree closure_decl = var_to_tree(bvar);
1186               if (closure_decl == error_mark_node)
1187                 this->fndecl_ = error_mark_node;
1188               else
1189                 {
1190                   DECL_ARTIFICIAL(closure_decl) = 1;
1191                   DECL_IGNORED_P(closure_decl) = 1;
1192                   TREE_USED(closure_decl) = 1;
1193                   DECL_ARG_TYPE(closure_decl) = TREE_TYPE(closure_decl);
1194                   TREE_READONLY(closure_decl) = 1;
1195
1196                   DECL_STRUCT_FUNCTION(decl)->static_chain_decl = closure_decl;
1197                 }
1198
1199               pop_cfun();
1200             }
1201         }
1202     }
1203   return this->fndecl_;
1204 }
1205
1206 // Get a tree for a function declaration.
1207
1208 tree
1209 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no, tree id)
1210 {
1211   if (this->fndecl_ == NULL_TREE)
1212     {
1213       // Let Go code use an asm declaration to pick up a builtin
1214       // function.
1215       if (!this->asm_name_.empty())
1216         {
1217           std::map<std::string, tree>::const_iterator p =
1218             builtin_functions.find(this->asm_name_);
1219           if (p != builtin_functions.end())
1220             {
1221               this->fndecl_ = p->second;
1222               return this->fndecl_;
1223             }
1224         }
1225
1226       tree functype = type_to_tree(this->fntype_->get_backend(gogo));
1227       tree decl;
1228       if (functype == error_mark_node)
1229         decl = error_mark_node;
1230       else
1231         {
1232           // The type of a function comes back as a pointer, but we
1233           // want the real function type for a function declaration.
1234           go_assert(POINTER_TYPE_P(functype));
1235           functype = TREE_TYPE(functype);
1236           decl = build_decl(this->location(), FUNCTION_DECL, id, functype);
1237           TREE_PUBLIC(decl) = 1;
1238           DECL_EXTERNAL(decl) = 1;
1239
1240           if (this->asm_name_.empty())
1241             {
1242               std::string asm_name = (no->package() == NULL
1243                                       ? gogo->unique_prefix()
1244                                       : no->package()->unique_prefix());
1245               asm_name.append(1, '.');
1246               asm_name.append(IDENTIFIER_POINTER(id), IDENTIFIER_LENGTH(id));
1247               SET_DECL_ASSEMBLER_NAME(decl,
1248                                       get_identifier_from_string(asm_name));
1249             }
1250         }
1251       this->fndecl_ = decl;
1252       go_preserve_from_gc(decl);
1253     }
1254   return this->fndecl_;
1255 }
1256
1257 // We always pass the receiver to a method as a pointer.  If the
1258 // receiver is actually declared as a non-pointer type, then we copy
1259 // the value into a local variable, so that it has the right type.  In
1260 // this function we create the real PARM_DECL to use, and set
1261 // DEC_INITIAL of the var_decl to be the value passed in.
1262
1263 tree
1264 Function::make_receiver_parm_decl(Gogo* gogo, Named_object* no, tree var_decl)
1265 {
1266   if (var_decl == error_mark_node)
1267     return error_mark_node;
1268   go_assert(TREE_CODE(var_decl) == VAR_DECL);
1269   tree val_type = TREE_TYPE(var_decl);
1270   bool is_in_heap = no->var_value()->is_in_heap();
1271   if (is_in_heap)
1272     {
1273       go_assert(POINTER_TYPE_P(val_type));
1274       val_type = TREE_TYPE(val_type);
1275     }
1276
1277   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1278   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1279   name += ".pointer";
1280   tree id = get_identifier_from_string(name);
1281   tree parm_decl = build_decl(loc, PARM_DECL, id, build_pointer_type(val_type));
1282   DECL_CONTEXT(parm_decl) = current_function_decl;
1283   DECL_ARG_TYPE(parm_decl) = TREE_TYPE(parm_decl);
1284
1285   go_assert(DECL_INITIAL(var_decl) == NULL_TREE);
1286   tree init = build_fold_indirect_ref_loc(loc, parm_decl);
1287
1288   if (is_in_heap)
1289     {
1290       tree size = TYPE_SIZE_UNIT(val_type);
1291       tree space = gogo->allocate_memory(no->var_value()->type(), size,
1292                                          no->location());
1293       space = save_expr(space);
1294       space = fold_convert(build_pointer_type(val_type), space);
1295       tree spaceref = build_fold_indirect_ref_loc(no->location(), space);
1296       TREE_THIS_NOTRAP(spaceref) = 1;
1297       tree set = fold_build2_loc(loc, MODIFY_EXPR, void_type_node,
1298                                  spaceref, init);
1299       init = fold_build2_loc(loc, COMPOUND_EXPR, TREE_TYPE(space), set, space);
1300     }
1301
1302   DECL_INITIAL(var_decl) = init;
1303
1304   return parm_decl;
1305 }
1306
1307 // If we take the address of a parameter, then we need to copy it into
1308 // the heap.  We will access it as a local variable via an
1309 // indirection.
1310
1311 tree
1312 Function::copy_parm_to_heap(Gogo* gogo, Named_object* no, tree var_decl)
1313 {
1314   if (var_decl == error_mark_node)
1315     return error_mark_node;
1316   go_assert(TREE_CODE(var_decl) == VAR_DECL);
1317   source_location loc = DECL_SOURCE_LOCATION(var_decl);
1318
1319   std::string name = IDENTIFIER_POINTER(DECL_NAME(var_decl));
1320   name += ".param";
1321   tree id = get_identifier_from_string(name);
1322
1323   tree type = TREE_TYPE(var_decl);
1324   go_assert(POINTER_TYPE_P(type));
1325   type = TREE_TYPE(type);
1326
1327   tree parm_decl = build_decl(loc, PARM_DECL, id, type);
1328   DECL_CONTEXT(parm_decl) = current_function_decl;
1329   DECL_ARG_TYPE(parm_decl) = type;
1330
1331   tree size = TYPE_SIZE_UNIT(type);
1332   tree space = gogo->allocate_memory(no->var_value()->type(), size, loc);
1333   space = save_expr(space);
1334   space = fold_convert(TREE_TYPE(var_decl), space);
1335   tree spaceref = build_fold_indirect_ref_loc(loc, space);
1336   TREE_THIS_NOTRAP(spaceref) = 1;
1337   tree init = build2(COMPOUND_EXPR, TREE_TYPE(space),
1338                      build2(MODIFY_EXPR, void_type_node, spaceref, parm_decl),
1339                      space);
1340   DECL_INITIAL(var_decl) = init;
1341
1342   return parm_decl;
1343 }
1344
1345 // Get a tree for function code.
1346
1347 void
1348 Function::build_tree(Gogo* gogo, Named_object* named_function)
1349 {
1350   tree fndecl = this->fndecl_;
1351   go_assert(fndecl != NULL_TREE);
1352
1353   tree params = NULL_TREE;
1354   tree* pp = &params;
1355
1356   tree declare_vars = NULL_TREE;
1357   for (Bindings::const_definitions_iterator p =
1358          this->block_->bindings()->begin_definitions();
1359        p != this->block_->bindings()->end_definitions();
1360        ++p)
1361     {
1362       if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
1363         {
1364           Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1365           *pp = var_to_tree(bvar);
1366
1367           // We always pass the receiver to a method as a pointer.  If
1368           // the receiver is declared as a non-pointer type, then we
1369           // copy the value into a local variable.
1370           if ((*p)->var_value()->is_receiver()
1371               && (*p)->var_value()->type()->points_to() == NULL)
1372             {
1373               tree parm_decl = this->make_receiver_parm_decl(gogo, *p, *pp);
1374               tree var = *pp;
1375               if (var != error_mark_node)
1376                 {
1377                   go_assert(TREE_CODE(var) == VAR_DECL);
1378                   DECL_CHAIN(var) = declare_vars;
1379                   declare_vars = var;
1380                 }
1381               *pp = parm_decl;
1382             }
1383           else if ((*p)->var_value()->is_in_heap())
1384             {
1385               // If we take the address of a parameter, then we need
1386               // to copy it into the heap.
1387               tree parm_decl = this->copy_parm_to_heap(gogo, *p, *pp);
1388               tree var = *pp;
1389               if (var != error_mark_node)
1390                 {
1391                   go_assert(TREE_CODE(var) == VAR_DECL);
1392                   DECL_CHAIN(var) = declare_vars;
1393                   declare_vars = var;
1394                 }
1395               *pp = parm_decl;
1396             }
1397
1398           if (*pp != error_mark_node)
1399             {
1400               go_assert(TREE_CODE(*pp) == PARM_DECL);
1401               pp = &DECL_CHAIN(*pp);
1402             }
1403         }
1404       else if ((*p)->is_result_variable())
1405         {
1406           Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
1407           tree var_decl = var_to_tree(bvar);
1408
1409           Type* type = (*p)->result_var_value()->type();
1410           tree init;
1411           if (!(*p)->result_var_value()->is_in_heap())
1412             {
1413               Btype* btype = type->get_backend(gogo);
1414               init = expr_to_tree(gogo->backend()->zero_expression(btype));
1415             }
1416           else
1417             {
1418               source_location loc = (*p)->location();
1419               tree type_tree = type_to_tree(type->get_backend(gogo));
1420               tree space = gogo->allocate_memory(type,
1421                                                  TYPE_SIZE_UNIT(type_tree),
1422                                                  loc);
1423               tree ptr_type_tree = build_pointer_type(type_tree);
1424               init = fold_convert_loc(loc, ptr_type_tree, space);
1425             }
1426
1427           if (var_decl != error_mark_node)
1428             {
1429               go_assert(TREE_CODE(var_decl) == VAR_DECL);
1430               DECL_INITIAL(var_decl) = init;
1431               DECL_CHAIN(var_decl) = declare_vars;
1432               declare_vars = var_decl;
1433             }
1434         }
1435     }
1436   *pp = NULL_TREE;
1437
1438   DECL_ARGUMENTS(fndecl) = params;
1439
1440   if (this->block_ != NULL)
1441     {
1442       go_assert(DECL_INITIAL(fndecl) == NULL_TREE);
1443
1444       // Declare variables if necessary.
1445       tree bind = NULL_TREE;
1446       tree defer_init = NULL_TREE;
1447       if (declare_vars != NULL_TREE || this->defer_stack_ != NULL)
1448         {
1449           tree block = make_node(BLOCK);
1450           BLOCK_SUPERCONTEXT(block) = fndecl;
1451           DECL_INITIAL(fndecl) = block;
1452           BLOCK_VARS(block) = declare_vars;
1453           TREE_USED(block) = 1;
1454
1455           bind = build3(BIND_EXPR, void_type_node, BLOCK_VARS(block),
1456                         NULL_TREE, block);
1457           TREE_SIDE_EFFECTS(bind) = 1;
1458
1459           if (this->defer_stack_ != NULL)
1460             {
1461               Translate_context dcontext(gogo, named_function, this->block_,
1462                                          tree_to_block(bind));
1463               Bstatement* bdi = this->defer_stack_->get_backend(&dcontext);
1464               defer_init = stat_to_tree(bdi);
1465             }
1466         }
1467
1468       // Build the trees for all the statements in the function.
1469       Translate_context context(gogo, named_function, NULL, NULL);
1470       Bblock* bblock = this->block_->get_backend(&context);
1471       tree code = block_to_tree(bblock);
1472
1473       tree init = NULL_TREE;
1474       tree except = NULL_TREE;
1475       tree fini = NULL_TREE;
1476
1477       // Initialize variables if necessary.
1478       for (tree v = declare_vars; v != NULL_TREE; v = DECL_CHAIN(v))
1479         {
1480           tree dv = build1(DECL_EXPR, void_type_node, v);
1481           SET_EXPR_LOCATION(dv, DECL_SOURCE_LOCATION(v));
1482           append_to_statement_list(dv, &init);
1483         }
1484
1485       // If we have a defer stack, initialize it at the start of a
1486       // function.
1487       if (defer_init != NULL_TREE && defer_init != error_mark_node)
1488         {
1489           SET_EXPR_LOCATION(defer_init, this->block_->start_location());
1490           append_to_statement_list(defer_init, &init);
1491
1492           // Clean up the defer stack when we leave the function.
1493           this->build_defer_wrapper(gogo, named_function, &except, &fini);
1494         }
1495
1496       if (code != NULL_TREE && code != error_mark_node)
1497         {
1498           if (init != NULL_TREE)
1499             code = build2(COMPOUND_EXPR, void_type_node, init, code);
1500           if (except != NULL_TREE)
1501             code = build2(TRY_CATCH_EXPR, void_type_node, code,
1502                           build2(CATCH_EXPR, void_type_node, NULL, except));
1503           if (fini != NULL_TREE)
1504             code = build2(TRY_FINALLY_EXPR, void_type_node, code, fini);
1505         }
1506
1507       // Stick the code into the block we built for the receiver, if
1508       // we built on.
1509       if (bind != NULL_TREE && code != NULL_TREE && code != error_mark_node)
1510         {
1511           BIND_EXPR_BODY(bind) = code;
1512           code = bind;
1513         }
1514
1515       DECL_SAVED_TREE(fndecl) = code;
1516     }
1517 }
1518
1519 // Build the wrappers around function code needed if the function has
1520 // any defer statements.  This sets *EXCEPT to an exception handler
1521 // and *FINI to a finally handler.
1522
1523 void
1524 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
1525                               tree *except, tree *fini)
1526 {
1527   source_location end_loc = this->block_->end_location();
1528
1529   // Add an exception handler.  This is used if a panic occurs.  Its
1530   // purpose is to stop the stack unwinding if a deferred function
1531   // calls recover.  There are more details in
1532   // libgo/runtime/go-unwind.c.
1533
1534   tree stmt_list = NULL_TREE;
1535
1536   Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1537                                         this->defer_stack(end_loc));
1538   Translate_context context(gogo, named_function, NULL, NULL);
1539   tree call_tree = call->get_tree(&context);
1540   if (call_tree != error_mark_node)
1541     append_to_statement_list(call_tree, &stmt_list);
1542
1543   tree retval = this->return_value(gogo, named_function, end_loc, &stmt_list);
1544   tree set;
1545   if (retval == NULL_TREE)
1546     set = NULL_TREE;
1547   else
1548     set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1549                           DECL_RESULT(this->fndecl_), retval);
1550   tree ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1551   append_to_statement_list(ret_stmt, &stmt_list);
1552
1553   go_assert(*except == NULL_TREE);
1554   *except = stmt_list;
1555
1556   // Add some finally code to run the defer functions.  This is used
1557   // both in the normal case, when no panic occurs, and also if a
1558   // panic occurs to run any further defer functions.  Of course, it
1559   // is possible for a defer function to call panic which should be
1560   // caught by another defer function.  To handle that we use a loop.
1561   //  finish:
1562   //   try { __go_undefer(); } catch { __go_check_defer(); goto finish; }
1563   //   if (return values are named) return named_vals;
1564
1565   stmt_list = NULL;
1566
1567   tree label = create_artificial_label(end_loc);
1568   tree define_label = fold_build1_loc(end_loc, LABEL_EXPR, void_type_node,
1569                                       label);
1570   append_to_statement_list(define_label, &stmt_list);
1571
1572   call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1,
1573                             this->defer_stack(end_loc));
1574   tree undefer = call->get_tree(&context);
1575
1576   call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
1577                             this->defer_stack(end_loc));
1578   tree defer = call->get_tree(&context);
1579
1580   if (undefer == error_mark_node || defer == error_mark_node)
1581     return;
1582
1583   tree jump = fold_build1_loc(end_loc, GOTO_EXPR, void_type_node, label);
1584   tree catch_body = build2(COMPOUND_EXPR, void_type_node, defer, jump);
1585   catch_body = build2(CATCH_EXPR, void_type_node, NULL, catch_body);
1586   tree try_catch = build2(TRY_CATCH_EXPR, void_type_node, undefer, catch_body);
1587
1588   append_to_statement_list(try_catch, &stmt_list);
1589
1590   if (this->type_->results() != NULL
1591       && !this->type_->results()->empty()
1592       && !this->type_->results()->front().name().empty())
1593     {
1594       // If the result variables are named, and we are returning from
1595       // this function rather than panicing through it, we need to
1596       // return them again, because they might have been changed by a
1597       // defer function.  The runtime routines set the defer_stack
1598       // variable to true if we are returning from this function.
1599       retval = this->return_value(gogo, named_function, end_loc,
1600                                   &stmt_list);
1601       set = fold_build2_loc(end_loc, MODIFY_EXPR, void_type_node,
1602                             DECL_RESULT(this->fndecl_), retval);
1603       ret_stmt = fold_build1_loc(end_loc, RETURN_EXPR, void_type_node, set);
1604
1605       Expression* ref =
1606         Expression::make_temporary_reference(this->defer_stack_, end_loc);
1607       tree tref = ref->get_tree(&context);
1608       tree s = build3_loc(end_loc, COND_EXPR, void_type_node, tref,
1609                           ret_stmt, NULL_TREE);
1610
1611       append_to_statement_list(s, &stmt_list);
1612
1613     }
1614   
1615   go_assert(*fini == NULL_TREE);
1616   *fini = stmt_list;
1617 }
1618
1619 // Return the value to assign to DECL_RESULT(this->fndecl_).  This may
1620 // also add statements to STMT_LIST, which need to be executed before
1621 // the assignment.  This is used for a return statement with no
1622 // explicit values.
1623
1624 tree
1625 Function::return_value(Gogo* gogo, Named_object* named_function,
1626                        source_location location, tree* stmt_list) const
1627 {
1628   const Typed_identifier_list* results = this->type_->results();
1629   if (results == NULL || results->empty())
1630     return NULL_TREE;
1631
1632   go_assert(this->results_ != NULL);
1633   if (this->results_->size() != results->size())
1634     {
1635       go_assert(saw_errors());
1636       return error_mark_node;
1637     }
1638
1639   tree retval;
1640   if (results->size() == 1)
1641     {
1642       Bvariable* bvar =
1643         this->results_->front()->get_backend_variable(gogo,
1644                                                       named_function);
1645       tree ret = var_to_tree(bvar);
1646       if (this->results_->front()->result_var_value()->is_in_heap())
1647         ret = build_fold_indirect_ref_loc(location, ret);
1648       return ret;
1649     }
1650   else
1651     {
1652       tree rettype = TREE_TYPE(DECL_RESULT(this->fndecl_));
1653       retval = create_tmp_var(rettype, "RESULT");
1654       tree field = TYPE_FIELDS(rettype);
1655       int index = 0;
1656       for (Typed_identifier_list::const_iterator pr = results->begin();
1657            pr != results->end();
1658            ++pr, ++index, field = DECL_CHAIN(field))
1659         {
1660           go_assert(field != NULL);
1661           Named_object* no = (*this->results_)[index];
1662           Bvariable* bvar = no->get_backend_variable(gogo, named_function);
1663           tree val = var_to_tree(bvar);
1664           if (no->result_var_value()->is_in_heap())
1665             val = build_fold_indirect_ref_loc(location, val);
1666           tree set = fold_build2_loc(location, MODIFY_EXPR, void_type_node,
1667                                      build3(COMPONENT_REF, TREE_TYPE(field),
1668                                             retval, field, NULL_TREE),
1669                                      val);
1670           append_to_statement_list(set, stmt_list);
1671         }
1672       return retval;
1673     }
1674 }
1675
1676 // Return the integer type to use for a size.
1677
1678 GO_EXTERN_C
1679 tree
1680 go_type_for_size(unsigned int bits, int unsignedp)
1681 {
1682   const char* name;
1683   switch (bits)
1684     {
1685     case 8:
1686       name = unsignedp ? "uint8" : "int8";
1687       break;
1688     case 16:
1689       name = unsignedp ? "uint16" : "int16";
1690       break;
1691     case 32:
1692       name = unsignedp ? "uint32" : "int32";
1693       break;
1694     case 64:
1695       name = unsignedp ? "uint64" : "int64";
1696       break;
1697     default:
1698       if (bits == POINTER_SIZE && unsignedp)
1699         name = "uintptr";
1700       else
1701         return NULL_TREE;
1702     }
1703   Type* type = Type::lookup_integer_type(name);
1704   return type_to_tree(type->get_backend(go_get_gogo()));
1705 }
1706
1707 // Return the type to use for a mode.
1708
1709 GO_EXTERN_C
1710 tree
1711 go_type_for_mode(enum machine_mode mode, int unsignedp)
1712 {
1713   // FIXME: This static_cast should be in machmode.h.
1714   enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
1715   if (mc == MODE_INT)
1716     return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
1717   else if (mc == MODE_FLOAT)
1718     {
1719       Type* type;
1720       switch (GET_MODE_BITSIZE (mode))
1721         {
1722         case 32:
1723           type = Type::lookup_float_type("float32");
1724           break;
1725         case 64:
1726           type = Type::lookup_float_type("float64");
1727           break;
1728         default:
1729           // We have to check for long double in order to support
1730           // i386 excess precision.
1731           if (mode == TYPE_MODE(long_double_type_node))
1732             return long_double_type_node;
1733           return NULL_TREE;
1734         }
1735       return type_to_tree(type->get_backend(go_get_gogo()));
1736     }
1737   else if (mc == MODE_COMPLEX_FLOAT)
1738     {
1739       Type *type;
1740       switch (GET_MODE_BITSIZE (mode))
1741         {
1742         case 64:
1743           type = Type::lookup_complex_type("complex64");
1744           break;
1745         case 128:
1746           type = Type::lookup_complex_type("complex128");
1747           break;
1748         default:
1749           // We have to check for long double in order to support
1750           // i386 excess precision.
1751           if (mode == TYPE_MODE(complex_long_double_type_node))
1752             return complex_long_double_type_node;
1753           return NULL_TREE;
1754         }
1755       return type_to_tree(type->get_backend(go_get_gogo()));
1756     }
1757   else
1758     return NULL_TREE;
1759 }
1760
1761 // Return a tree which allocates SIZE bytes which will holds value of
1762 // type TYPE.
1763
1764 tree
1765 Gogo::allocate_memory(Type* type, tree size, source_location location)
1766 {
1767   // If the package imports unsafe, then it may play games with
1768   // pointers that look like integers.
1769   if (this->imported_unsafe_ || type->has_pointer())
1770     {
1771       static tree new_fndecl;
1772       return Gogo::call_builtin(&new_fndecl,
1773                                 location,
1774                                 "__go_new",
1775                                 1,
1776                                 ptr_type_node,
1777                                 sizetype,
1778                                 size);
1779     }
1780   else
1781     {
1782       static tree new_nopointers_fndecl;
1783       return Gogo::call_builtin(&new_nopointers_fndecl,
1784                                 location,
1785                                 "__go_new_nopointers",
1786                                 1,
1787                                 ptr_type_node,
1788                                 sizetype,
1789                                 size);
1790     }
1791 }
1792
1793 // Build a builtin struct with a list of fields.  The name is
1794 // STRUCT_NAME.  STRUCT_TYPE is NULL_TREE or an empty RECORD_TYPE
1795 // node; this exists so that the struct can have fields which point to
1796 // itself.  If PTYPE is not NULL, store the result in *PTYPE.  There
1797 // are NFIELDS fields.  Each field is a name (a const char*) followed
1798 // by a type (a tree).
1799
1800 tree
1801 Gogo::builtin_struct(tree* ptype, const char* struct_name, tree struct_type,
1802                      int nfields, ...)
1803 {
1804   if (ptype != NULL && *ptype != NULL_TREE)
1805     return *ptype;
1806
1807   va_list ap;
1808   va_start(ap, nfields);
1809
1810   tree fields = NULL_TREE;
1811   for (int i = 0; i < nfields; ++i)
1812     {
1813       const char* field_name = va_arg(ap, const char*);
1814       tree type = va_arg(ap, tree);
1815       if (type == error_mark_node)
1816         {
1817           if (ptype != NULL)
1818             *ptype = error_mark_node;
1819           return error_mark_node;
1820         }
1821       tree field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
1822                               get_identifier(field_name), type);
1823       DECL_CHAIN(field) = fields;
1824       fields = field;
1825     }
1826
1827   va_end(ap);
1828
1829   if (struct_type == NULL_TREE)
1830     struct_type = make_node(RECORD_TYPE);
1831   finish_builtin_struct(struct_type, struct_name, fields, NULL_TREE);
1832
1833   if (ptype != NULL)
1834     {
1835       go_preserve_from_gc(struct_type);
1836       *ptype = struct_type;
1837     }
1838
1839   return struct_type;
1840 }
1841
1842 // Return a type to use for pointer to const char for a string.
1843
1844 tree
1845 Gogo::const_char_pointer_type_tree()
1846 {
1847   static tree type;
1848   if (type == NULL_TREE)
1849     {
1850       tree const_char_type = build_qualified_type(unsigned_char_type_node,
1851                                                   TYPE_QUAL_CONST);
1852       type = build_pointer_type(const_char_type);
1853       go_preserve_from_gc(type);
1854     }
1855   return type;
1856 }
1857
1858 // Return a tree for a string constant.
1859
1860 tree
1861 Gogo::string_constant_tree(const std::string& val)
1862 {
1863   tree index_type = build_index_type(size_int(val.length()));
1864   tree const_char_type = build_qualified_type(unsigned_char_type_node,
1865                                               TYPE_QUAL_CONST);
1866   tree string_type = build_array_type(const_char_type, index_type);
1867   string_type = build_variant_type_copy(string_type);
1868   TYPE_STRING_FLAG(string_type) = 1;
1869   tree string_val = build_string(val.length(), val.data());
1870   TREE_TYPE(string_val) = string_type;
1871   return string_val;
1872 }
1873
1874 // Return a tree for a Go string constant.
1875
1876 tree
1877 Gogo::go_string_constant_tree(const std::string& val)
1878 {
1879   tree string_type = type_to_tree(Type::make_string_type()->get_backend(this));
1880
1881   VEC(constructor_elt, gc)* init = VEC_alloc(constructor_elt, gc, 2);
1882
1883   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
1884   tree field = TYPE_FIELDS(string_type);
1885   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__data") == 0);
1886   elt->index = field;
1887   tree str = Gogo::string_constant_tree(val);
1888   elt->value = fold_convert(TREE_TYPE(field),
1889                             build_fold_addr_expr(str));
1890
1891   elt = VEC_quick_push(constructor_elt, init, NULL);
1892   field = DECL_CHAIN(field);
1893   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__length") == 0);
1894   elt->index = field;
1895   elt->value = build_int_cst_type(TREE_TYPE(field), val.length());
1896
1897   tree constructor = build_constructor(string_type, init);
1898   TREE_READONLY(constructor) = 1;
1899   TREE_CONSTANT(constructor) = 1;
1900
1901   return constructor;
1902 }
1903
1904 // Return a tree for a pointer to a Go string constant.  This is only
1905 // used for type descriptors, so we return a pointer to a constant
1906 // decl.
1907
1908 tree
1909 Gogo::ptr_go_string_constant_tree(const std::string& val)
1910 {
1911   tree pval = this->go_string_constant_tree(val);
1912
1913   tree decl = build_decl(UNKNOWN_LOCATION, VAR_DECL,
1914                          create_tmp_var_name("SP"), TREE_TYPE(pval));
1915   DECL_EXTERNAL(decl) = 0;
1916   TREE_PUBLIC(decl) = 0;
1917   TREE_USED(decl) = 1;
1918   TREE_READONLY(decl) = 1;
1919   TREE_CONSTANT(decl) = 1;
1920   TREE_STATIC(decl) = 1;
1921   DECL_ARTIFICIAL(decl) = 1;
1922   DECL_INITIAL(decl) = pval;
1923   rest_of_decl_compilation(decl, 1, 0);
1924
1925   return build_fold_addr_expr(decl);
1926 }
1927
1928 // Build a constructor for a slice.  SLICE_TYPE_TREE is the type of
1929 // the slice.  VALUES is the value pointer and COUNT is the number of
1930 // entries.  If CAPACITY is not NULL, it is the capacity; otherwise
1931 // the capacity and the count are the same.
1932
1933 tree
1934 Gogo::slice_constructor(tree slice_type_tree, tree values, tree count,
1935                         tree capacity)
1936 {
1937   go_assert(TREE_CODE(slice_type_tree) == RECORD_TYPE);
1938
1939   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
1940
1941   tree field = TYPE_FIELDS(slice_type_tree);
1942   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
1943   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
1944   elt->index = field;
1945   go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(field))
1946              == TYPE_MAIN_VARIANT(TREE_TYPE(values)));
1947   elt->value = values;
1948
1949   count = fold_convert(sizetype, count);
1950   if (capacity == NULL_TREE)
1951     {
1952       count = save_expr(count);
1953       capacity = count;
1954     }
1955
1956   field = DECL_CHAIN(field);
1957   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
1958   elt = VEC_quick_push(constructor_elt, init, NULL);
1959   elt->index = field;
1960   elt->value = fold_convert(TREE_TYPE(field), count);
1961
1962   field = DECL_CHAIN(field);
1963   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
1964   elt = VEC_quick_push(constructor_elt, init, NULL);
1965   elt->index = field;
1966   elt->value = fold_convert(TREE_TYPE(field), capacity);
1967
1968   return build_constructor(slice_type_tree, init);
1969 }
1970
1971 // Build an interface method table for a type: a list of function
1972 // pointers, one for each interface method.  This is used for
1973 // interfaces.
1974
1975 tree
1976 Gogo::interface_method_table_for_type(const Interface_type* interface,
1977                                       Named_type* type,
1978                                       bool is_pointer)
1979 {
1980   const Typed_identifier_list* interface_methods = interface->methods();
1981   go_assert(!interface_methods->empty());
1982
1983   std::string mangled_name = ((is_pointer ? "__go_pimt__" : "__go_imt_")
1984                               + interface->mangled_name(this)
1985                               + "__"
1986                               + type->mangled_name(this));
1987
1988   tree id = get_identifier_from_string(mangled_name);
1989
1990   // See whether this interface has any hidden methods.
1991   bool has_hidden_methods = false;
1992   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
1993        p != interface_methods->end();
1994        ++p)
1995     {
1996       if (Gogo::is_hidden_name(p->name()))
1997         {
1998           has_hidden_methods = true;
1999           break;
2000         }
2001     }
2002
2003   // We already know that the named type is convertible to the
2004   // interface.  If the interface has hidden methods, and the named
2005   // type is defined in a different package, then the interface
2006   // conversion table will be defined by that other package.
2007   if (has_hidden_methods && type->named_object()->package() != NULL)
2008     {
2009       tree array_type = build_array_type(const_ptr_type_node, NULL);
2010       tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2011       TREE_READONLY(decl) = 1;
2012       TREE_CONSTANT(decl) = 1;
2013       TREE_PUBLIC(decl) = 1;
2014       DECL_EXTERNAL(decl) = 1;
2015       go_preserve_from_gc(decl);
2016       return decl;
2017     }
2018
2019   size_t count = interface_methods->size();
2020   VEC(constructor_elt, gc)* pointers = VEC_alloc(constructor_elt, gc,
2021                                                  count + 1);
2022
2023   // The first element is the type descriptor.
2024   constructor_elt* elt = VEC_quick_push(constructor_elt, pointers, NULL);
2025   elt->index = size_zero_node;
2026   Type* td_type;
2027   if (!is_pointer)
2028     td_type = type;
2029   else
2030     td_type = Type::make_pointer_type(type);
2031   tree tdp = td_type->type_descriptor_pointer(this, BUILTINS_LOCATION);
2032   elt->value = fold_convert(const_ptr_type_node, tdp);
2033
2034   size_t i = 1;
2035   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
2036        p != interface_methods->end();
2037        ++p, ++i)
2038     {
2039       bool is_ambiguous;
2040       Method* m = type->method_function(p->name(), &is_ambiguous);
2041       go_assert(m != NULL);
2042
2043       Named_object* no = m->named_object();
2044
2045       tree fnid = no->get_id(this);
2046
2047       tree fndecl;
2048       if (no->is_function())
2049         fndecl = no->func_value()->get_or_make_decl(this, no, fnid);
2050       else if (no->is_function_declaration())
2051         fndecl = no->func_declaration_value()->get_or_make_decl(this, no,
2052                                                                 fnid);
2053       else
2054         go_unreachable();
2055       fndecl = build_fold_addr_expr(fndecl);
2056
2057       elt = VEC_quick_push(constructor_elt, pointers, NULL);
2058       elt->index = size_int(i);
2059       elt->value = fold_convert(const_ptr_type_node, fndecl);
2060     }
2061   go_assert(i == count + 1);
2062
2063   tree array_type = build_array_type(const_ptr_type_node,
2064                                      build_index_type(size_int(count)));
2065   tree constructor = build_constructor(array_type, pointers);
2066
2067   tree decl = build_decl(BUILTINS_LOCATION, VAR_DECL, id, array_type);
2068   TREE_STATIC(decl) = 1;
2069   TREE_USED(decl) = 1;
2070   TREE_READONLY(decl) = 1;
2071   TREE_CONSTANT(decl) = 1;
2072   DECL_INITIAL(decl) = constructor;
2073
2074   // If the interface type has hidden methods, then this is the only
2075   // definition of the table.  Otherwise it is a comdat table which
2076   // may be defined in multiple packages.
2077   if (has_hidden_methods)
2078     TREE_PUBLIC(decl) = 1;
2079   else
2080     {
2081       make_decl_one_only(decl, DECL_ASSEMBLER_NAME(decl));
2082       resolve_unique_section(decl, 1, 0);
2083     }
2084
2085   rest_of_decl_compilation(decl, 1, 0);
2086
2087   go_preserve_from_gc(decl);
2088
2089   return decl;
2090 }
2091
2092 // Mark a function as a builtin library function.
2093
2094 void
2095 Gogo::mark_fndecl_as_builtin_library(tree fndecl)
2096 {
2097   DECL_EXTERNAL(fndecl) = 1;
2098   TREE_PUBLIC(fndecl) = 1;
2099   DECL_ARTIFICIAL(fndecl) = 1;
2100   TREE_NOTHROW(fndecl) = 1;
2101   DECL_VISIBILITY(fndecl) = VISIBILITY_DEFAULT;
2102   DECL_VISIBILITY_SPECIFIED(fndecl) = 1;
2103 }
2104
2105 // Build a call to a builtin function.
2106
2107 tree
2108 Gogo::call_builtin(tree* pdecl, source_location location, const char* name,
2109                    int nargs, tree rettype, ...)
2110 {
2111   if (rettype == error_mark_node)
2112     return error_mark_node;
2113
2114   tree* types = new tree[nargs];
2115   tree* args = new tree[nargs];
2116
2117   va_list ap;
2118   va_start(ap, rettype);
2119   for (int i = 0; i < nargs; ++i)
2120     {
2121       types[i] = va_arg(ap, tree);
2122       args[i] = va_arg(ap, tree);
2123       if (types[i] == error_mark_node || args[i] == error_mark_node)
2124         {
2125           delete[] types;
2126           delete[] args;
2127           return error_mark_node;
2128         }
2129     }
2130   va_end(ap);
2131
2132   if (*pdecl == NULL_TREE)
2133     {
2134       tree fnid = get_identifier(name);
2135
2136       tree argtypes = NULL_TREE;
2137       tree* pp = &argtypes;
2138       for (int i = 0; i < nargs; ++i)
2139         {
2140           *pp = tree_cons(NULL_TREE, types[i], NULL_TREE);
2141           pp = &TREE_CHAIN(*pp);
2142         }
2143       *pp = void_list_node;
2144
2145       tree fntype = build_function_type(rettype, argtypes);
2146
2147       *pdecl = build_decl(BUILTINS_LOCATION, FUNCTION_DECL, fnid, fntype);
2148       Gogo::mark_fndecl_as_builtin_library(*pdecl);
2149       go_preserve_from_gc(*pdecl);
2150     }
2151
2152   tree fnptr = build_fold_addr_expr(*pdecl);
2153   if (CAN_HAVE_LOCATION_P(fnptr))
2154     SET_EXPR_LOCATION(fnptr, location);
2155
2156   tree ret = build_call_array(rettype, fnptr, nargs, args);
2157   SET_EXPR_LOCATION(ret, location);
2158
2159   delete[] types;
2160   delete[] args;
2161
2162   return ret;
2163 }
2164
2165 // Build a call to the runtime error function.
2166
2167 tree
2168 Gogo::runtime_error(int code, source_location location)
2169 {
2170   static tree runtime_error_fndecl;
2171   tree ret = Gogo::call_builtin(&runtime_error_fndecl,
2172                                 location,
2173                                 "__go_runtime_error",
2174                                 1,
2175                                 void_type_node,
2176                                 integer_type_node,
2177                                 build_int_cst(integer_type_node, code));
2178   if (ret == error_mark_node)
2179     return error_mark_node;
2180   // The runtime error function panics and does not return.
2181   TREE_NOTHROW(runtime_error_fndecl) = 0;
2182   TREE_THIS_VOLATILE(runtime_error_fndecl) = 1;
2183   return ret;
2184 }
2185
2186 // Return a tree for receiving a value of type TYPE_TREE on CHANNEL.
2187 // This does a blocking receive and returns the value read from the
2188 // channel.  If FOR_SELECT is true, this is being done because it was
2189 // chosen in a select statement.
2190
2191 tree
2192 Gogo::receive_from_channel(tree type_tree, tree channel, bool for_select,
2193                            source_location location)
2194 {
2195   if (type_tree == error_mark_node || channel == error_mark_node)
2196     return error_mark_node;
2197
2198   if (int_size_in_bytes(type_tree) <= 8
2199       && !AGGREGATE_TYPE_P(type_tree)
2200       && !FLOAT_TYPE_P(type_tree))
2201     {
2202       static tree receive_small_fndecl;
2203       tree call = Gogo::call_builtin(&receive_small_fndecl,
2204                                      location,
2205                                      "__go_receive_small",
2206                                      2,
2207                                      uint64_type_node,
2208                                      ptr_type_node,
2209                                      channel,
2210                                      boolean_type_node,
2211                                      (for_select
2212                                       ? boolean_true_node
2213                                       : boolean_false_node));
2214       if (call == error_mark_node)
2215         return error_mark_node;
2216       // This can panic if there are too many operations on a closed
2217       // channel.
2218       TREE_NOTHROW(receive_small_fndecl) = 0;
2219       int bitsize = GET_MODE_BITSIZE(TYPE_MODE(type_tree));
2220       tree int_type_tree = go_type_for_size(bitsize, 1);
2221       return fold_convert_loc(location, type_tree,
2222                               fold_convert_loc(location, int_type_tree,
2223                                                call));
2224     }
2225   else
2226     {
2227       tree tmp = create_tmp_var(type_tree, get_name(type_tree));
2228       DECL_IGNORED_P(tmp) = 0;
2229       TREE_ADDRESSABLE(tmp) = 1;
2230       tree make_tmp = build1(DECL_EXPR, void_type_node, tmp);
2231       SET_EXPR_LOCATION(make_tmp, location);
2232       tree tmpaddr = build_fold_addr_expr(tmp);
2233       tmpaddr = fold_convert(ptr_type_node, tmpaddr);
2234       static tree receive_big_fndecl;
2235       tree call = Gogo::call_builtin(&receive_big_fndecl,
2236                                      location,
2237                                      "__go_receive_big",
2238                                      3,
2239                                      boolean_type_node,
2240                                      ptr_type_node,
2241                                      channel,
2242                                      ptr_type_node,
2243                                      tmpaddr,
2244                                      boolean_type_node,
2245                                      (for_select
2246                                       ? boolean_true_node
2247                                       : boolean_false_node));
2248       if (call == error_mark_node)
2249         return error_mark_node;
2250       // This can panic if there are too many operations on a closed
2251       // channel.
2252       TREE_NOTHROW(receive_big_fndecl) = 0;
2253       return build2(COMPOUND_EXPR, type_tree, make_tmp,
2254                     build2(COMPOUND_EXPR, type_tree, call, tmp));
2255     }
2256 }
2257
2258 // Return the type of a function trampoline.  This is like
2259 // get_trampoline_type in tree-nested.c.
2260
2261 tree
2262 Gogo::trampoline_type_tree()
2263 {
2264   static tree type_tree;
2265   if (type_tree == NULL_TREE)
2266     {
2267       unsigned int size;
2268       unsigned int align;
2269       go_trampoline_info(&size, &align);
2270       tree t = build_index_type(build_int_cst(integer_type_node, size - 1));
2271       t = build_array_type(char_type_node, t);
2272
2273       type_tree = Gogo::builtin_struct(NULL, "__go_trampoline", NULL_TREE, 1,
2274                                        "__data", t);
2275       t = TYPE_FIELDS(type_tree);
2276       DECL_ALIGN(t) = align;
2277       DECL_USER_ALIGN(t) = 1;
2278
2279       go_preserve_from_gc(type_tree);
2280     }
2281   return type_tree;
2282 }
2283
2284 // Make a trampoline which calls FNADDR passing CLOSURE.
2285
2286 tree
2287 Gogo::make_trampoline(tree fnaddr, tree closure, source_location location)
2288 {
2289   tree trampoline_type = Gogo::trampoline_type_tree();
2290   tree trampoline_size = TYPE_SIZE_UNIT(trampoline_type);
2291
2292   closure = save_expr(closure);
2293
2294   // We allocate the trampoline using a special function which will
2295   // mark it as executable.
2296   static tree trampoline_fndecl;
2297   tree x = Gogo::call_builtin(&trampoline_fndecl,
2298                               location,
2299                               "__go_allocate_trampoline",
2300                               2,
2301                               ptr_type_node,
2302                               size_type_node,
2303                               trampoline_size,
2304                               ptr_type_node,
2305                               fold_convert_loc(location, ptr_type_node,
2306                                                closure));
2307   if (x == error_mark_node)
2308     return error_mark_node;
2309
2310   x = save_expr(x);
2311
2312   // Initialize the trampoline.
2313   tree ini = build_call_expr(builtin_decl_implicit(BUILT_IN_INIT_TRAMPOLINE),
2314                              3, x, fnaddr, closure);
2315
2316   // On some targets the trampoline address needs to be adjusted.  For
2317   // example, when compiling in Thumb mode on the ARM, the address
2318   // needs to have the low bit set.
2319   x = build_call_expr(builtin_decl_explicit(BUILT_IN_ADJUST_TRAMPOLINE), 1, x);
2320   x = fold_convert(TREE_TYPE(fnaddr), x);
2321
2322   return build2(COMPOUND_EXPR, TREE_TYPE(x), ini, x);
2323 }