OSDN Git Service

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