OSDN Git Service

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