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