compiler: Adjust for GCC always being built with C++.
[gcc.git] / gcc / go / gofrontend / expressions.cc
1 // expressions.cc -- Go frontend expression handling.
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 <algorithm>
10
11 #include <gmp.h>
12
13 #include "toplev.h"
14 #include "intl.h"
15 #include "tree.h"
16 #include "gimple.h"
17 #include "tree-iterator.h"
18 #include "convert.h"
19 #include "real.h"
20 #include "realmpfr.h"
21
22 #include "go-c.h"
23 #include "gogo.h"
24 #include "types.h"
25 #include "export.h"
26 #include "import.h"
27 #include "statements.h"
28 #include "lex.h"
29 #include "runtime.h"
30 #include "backend.h"
31 #include "expressions.h"
32 #include "ast-dump.h"
33
34 // Class Expression.
35
36 Expression::Expression(Expression_classification classification,
37 Location location)
38 : classification_(classification), location_(location)
39 {
40 }
41
42 Expression::~Expression()
43 {
44 }
45
46 // Traverse the expressions.
47
48 int
49 Expression::traverse(Expression** pexpr, Traverse* traverse)
50 {
51 Expression* expr = *pexpr;
52 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
53 {
54 int t = traverse->expression(pexpr);
55 if (t == TRAVERSE_EXIT)
56 return TRAVERSE_EXIT;
57 else if (t == TRAVERSE_SKIP_COMPONENTS)
58 return TRAVERSE_CONTINUE;
59 }
60 return expr->do_traverse(traverse);
61 }
62
63 // Traverse subexpressions of this expression.
64
65 int
66 Expression::traverse_subexpressions(Traverse* traverse)
67 {
68 return this->do_traverse(traverse);
69 }
70
71 // Default implementation for do_traverse for child classes.
72
73 int
74 Expression::do_traverse(Traverse*)
75 {
76 return TRAVERSE_CONTINUE;
77 }
78
79 // This virtual function is called by the parser if the value of this
80 // expression is being discarded. By default, we give an error.
81 // Expressions with side effects override.
82
83 void
84 Expression::do_discarding_value()
85 {
86 this->unused_value_error();
87 }
88
89 // This virtual function is called to export expressions. This will
90 // only be used by expressions which may be constant.
91
92 void
93 Expression::do_export(Export*) const
94 {
95 go_unreachable();
96 }
97
98 // Give an error saying that the value of the expression is not used.
99
100 void
101 Expression::unused_value_error()
102 {
103 error_at(this->location(), "value computed is not used");
104 }
105
106 // Note that this expression is an error. This is called by children
107 // when they discover an error.
108
109 void
110 Expression::set_is_error()
111 {
112 this->classification_ = EXPRESSION_ERROR;
113 }
114
115 // For children to call to report an error conveniently.
116
117 void
118 Expression::report_error(const char* msg)
119 {
120 error_at(this->location_, "%s", msg);
121 this->set_is_error();
122 }
123
124 // Set types of variables and constants. This is implemented by the
125 // child class.
126
127 void
128 Expression::determine_type(const Type_context* context)
129 {
130 this->do_determine_type(context);
131 }
132
133 // Set types when there is no context.
134
135 void
136 Expression::determine_type_no_context()
137 {
138 Type_context context;
139 this->do_determine_type(&context);
140 }
141
142 // Return a tree handling any conversions which must be done during
143 // assignment.
144
145 tree
146 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
147 Type* rhs_type, tree rhs_tree,
148 Location location)
149 {
150 if (lhs_type->is_error() || rhs_type->is_error())
151 return error_mark_node;
152
153 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
154 return error_mark_node;
155
156 Gogo* gogo = context->gogo();
157
158 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
159 if (lhs_type_tree == error_mark_node)
160 return error_mark_node;
161
162 if (lhs_type->forwarded() != rhs_type->forwarded()
163 && lhs_type->interface_type() != NULL)
164 {
165 if (rhs_type->interface_type() == NULL)
166 return Expression::convert_type_to_interface(context, lhs_type,
167 rhs_type, rhs_tree,
168 location);
169 else
170 return Expression::convert_interface_to_interface(context, lhs_type,
171 rhs_type, rhs_tree,
172 false, location);
173 }
174 else if (lhs_type->forwarded() != rhs_type->forwarded()
175 && rhs_type->interface_type() != NULL)
176 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
177 rhs_tree, location);
178 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
179 {
180 // Assigning nil to an open array.
181 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
182
183 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
184
185 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
186 tree field = TYPE_FIELDS(lhs_type_tree);
187 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
188 "__values") == 0);
189 elt->index = field;
190 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
191
192 elt = VEC_quick_push(constructor_elt, init, NULL);
193 field = DECL_CHAIN(field);
194 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195 "__count") == 0);
196 elt->index = field;
197 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
198
199 elt = VEC_quick_push(constructor_elt, init, NULL);
200 field = DECL_CHAIN(field);
201 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202 "__capacity") == 0);
203 elt->index = field;
204 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
205
206 tree val = build_constructor(lhs_type_tree, init);
207 TREE_CONSTANT(val) = 1;
208
209 return val;
210 }
211 else if (rhs_type->is_nil_type())
212 {
213 // The left hand side should be a pointer type at the tree
214 // level.
215 go_assert(POINTER_TYPE_P(lhs_type_tree));
216 return fold_convert(lhs_type_tree, null_pointer_node);
217 }
218 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
219 {
220 // No conversion is needed.
221 return rhs_tree;
222 }
223 else if (POINTER_TYPE_P(lhs_type_tree)
224 || INTEGRAL_TYPE_P(lhs_type_tree)
225 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
226 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
227 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
228 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
229 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
230 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
231 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
232 {
233 // Avoid confusion from zero sized variables which may be
234 // represented as non-zero-sized.
235 if (int_size_in_bytes(lhs_type_tree) == 0
236 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
237 return rhs_tree;
238
239 // This conversion must be permitted by Go, or we wouldn't have
240 // gotten here.
241 go_assert(int_size_in_bytes(lhs_type_tree)
242 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
243 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
244 lhs_type_tree, rhs_tree);
245 }
246 else
247 {
248 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
249 return rhs_tree;
250 }
251 }
252
253 // Return a tree for a conversion from a non-interface type to an
254 // interface type.
255
256 tree
257 Expression::convert_type_to_interface(Translate_context* context,
258 Type* lhs_type, Type* rhs_type,
259 tree rhs_tree, Location location)
260 {
261 Gogo* gogo = context->gogo();
262 Interface_type* lhs_interface_type = lhs_type->interface_type();
263 bool lhs_is_empty = lhs_interface_type->is_empty();
264
265 // Since RHS_TYPE is a static type, we can create the interface
266 // method table at compile time.
267
268 // When setting an interface to nil, we just set both fields to
269 // NULL.
270 if (rhs_type->is_nil_type())
271 {
272 Btype* lhs_btype = lhs_type->get_backend(gogo);
273 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
274 }
275
276 // This should have been checked already.
277 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
278
279 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
280 if (lhs_type_tree == error_mark_node)
281 return error_mark_node;
282
283 // An interface is a tuple. If LHS_TYPE is an empty interface type,
284 // then the first field is the type descriptor for RHS_TYPE.
285 // Otherwise it is the interface method table for RHS_TYPE.
286 tree first_field_value;
287 if (lhs_is_empty)
288 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
289 else
290 {
291 // Build the interface method table for this interface and this
292 // object type: a list of function pointers for each interface
293 // method.
294 Named_type* rhs_named_type = rhs_type->named_type();
295 bool is_pointer = false;
296 if (rhs_named_type == NULL)
297 {
298 rhs_named_type = rhs_type->deref()->named_type();
299 is_pointer = true;
300 }
301 tree method_table;
302 if (rhs_named_type == NULL)
303 method_table = null_pointer_node;
304 else
305 method_table =
306 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
307 is_pointer);
308 first_field_value = fold_convert_loc(location.gcc_location(),
309 const_ptr_type_node, method_table);
310 }
311 if (first_field_value == error_mark_node)
312 return error_mark_node;
313
314 // Start building a constructor for the value we will return.
315
316 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
317
318 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
319 tree field = TYPE_FIELDS(lhs_type_tree);
320 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
321 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
322 elt->index = field;
323 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
324 first_field_value);
325
326 elt = VEC_quick_push(constructor_elt, init, NULL);
327 field = DECL_CHAIN(field);
328 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
329 elt->index = field;
330
331 if (rhs_type->points_to() != NULL)
332 {
333 // We are assigning a pointer to the interface; the interface
334 // holds the pointer itself.
335 elt->value = rhs_tree;
336 return build_constructor(lhs_type_tree, init);
337 }
338
339 // We are assigning a non-pointer value to the interface; the
340 // interface gets a copy of the value in the heap.
341
342 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
343
344 tree space = gogo->allocate_memory(rhs_type, object_size, location);
345 space = fold_convert_loc(location.gcc_location(),
346 build_pointer_type(TREE_TYPE(rhs_tree)), space);
347 space = save_expr(space);
348
349 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
350 TREE_THIS_NOTRAP(ref) = 1;
351 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
352 void_type_node, ref, rhs_tree);
353
354 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
355 space);
356
357 return build2(COMPOUND_EXPR, lhs_type_tree, set,
358 build_constructor(lhs_type_tree, init));
359 }
360
361 // Return a tree for the type descriptor of RHS_TREE, which has
362 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
363 // NULL.
364
365 tree
366 Expression::get_interface_type_descriptor(Translate_context*,
367 Type* rhs_type, tree rhs_tree,
368 Location location)
369 {
370 tree rhs_type_tree = TREE_TYPE(rhs_tree);
371 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
372 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
373 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
374 NULL_TREE);
375 if (rhs_type->interface_type()->is_empty())
376 {
377 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
378 "__type_descriptor") == 0);
379 return v;
380 }
381
382 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
383 == 0);
384 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
385 v = save_expr(v);
386 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
387 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
388 tree f = TYPE_FIELDS(TREE_TYPE(v1));
389 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
390 == 0);
391 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
392
393 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
394 v, fold_convert_loc(location.gcc_location(),
395 TREE_TYPE(v),
396 null_pointer_node));
397 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
398 null_pointer_node);
399 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
400 eq, n, v1);
401 }
402
403 // Return a tree for the conversion of an interface type to an
404 // interface type.
405
406 tree
407 Expression::convert_interface_to_interface(Translate_context* context,
408 Type *lhs_type, Type *rhs_type,
409 tree rhs_tree, bool for_type_guard,
410 Location location)
411 {
412 Gogo* gogo = context->gogo();
413 Interface_type* lhs_interface_type = lhs_type->interface_type();
414 bool lhs_is_empty = lhs_interface_type->is_empty();
415
416 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
417 if (lhs_type_tree == error_mark_node)
418 return error_mark_node;
419
420 // In the general case this requires runtime examination of the type
421 // method table to match it up with the interface methods.
422
423 // FIXME: If all of the methods in the right hand side interface
424 // also appear in the left hand side interface, then we don't need
425 // to do a runtime check, although we still need to build a new
426 // method table.
427
428 // Get the type descriptor for the right hand side. This will be
429 // NULL for a nil interface.
430
431 if (!DECL_P(rhs_tree))
432 rhs_tree = save_expr(rhs_tree);
433
434 tree rhs_type_descriptor =
435 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
436 location);
437
438 // The result is going to be a two element constructor.
439
440 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
441
442 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
443 tree field = TYPE_FIELDS(lhs_type_tree);
444 elt->index = field;
445
446 if (for_type_guard)
447 {
448 // A type assertion fails when converting a nil interface.
449 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
450 location);
451 static tree assert_interface_decl;
452 tree call = Gogo::call_builtin(&assert_interface_decl,
453 location,
454 "__go_assert_interface",
455 2,
456 ptr_type_node,
457 TREE_TYPE(lhs_type_descriptor),
458 lhs_type_descriptor,
459 TREE_TYPE(rhs_type_descriptor),
460 rhs_type_descriptor);
461 if (call == error_mark_node)
462 return error_mark_node;
463 // This will panic if the interface conversion fails.
464 TREE_NOTHROW(assert_interface_decl) = 0;
465 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
466 call);
467 }
468 else if (lhs_is_empty)
469 {
470 // A convertion to an empty interface always succeeds, and the
471 // first field is just the type descriptor of the object.
472 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
473 "__type_descriptor") == 0);
474 elt->value = fold_convert_loc(location.gcc_location(),
475 TREE_TYPE(field), rhs_type_descriptor);
476 }
477 else
478 {
479 // A conversion to a non-empty interface may fail, but unlike a
480 // type assertion converting nil will always succeed.
481 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
482 == 0);
483 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
484 location);
485 static tree convert_interface_decl;
486 tree call = Gogo::call_builtin(&convert_interface_decl,
487 location,
488 "__go_convert_interface",
489 2,
490 ptr_type_node,
491 TREE_TYPE(lhs_type_descriptor),
492 lhs_type_descriptor,
493 TREE_TYPE(rhs_type_descriptor),
494 rhs_type_descriptor);
495 if (call == error_mark_node)
496 return error_mark_node;
497 // This will panic if the interface conversion fails.
498 TREE_NOTHROW(convert_interface_decl) = 0;
499 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
500 call);
501 }
502
503 // The second field is simply the object pointer.
504
505 elt = VEC_quick_push(constructor_elt, init, NULL);
506 field = DECL_CHAIN(field);
507 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
508 elt->index = field;
509
510 tree rhs_type_tree = TREE_TYPE(rhs_tree);
511 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
512 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
513 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
514 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
515 NULL_TREE);
516
517 return build_constructor(lhs_type_tree, init);
518 }
519
520 // Return a tree for the conversion of an interface type to a
521 // non-interface type.
522
523 tree
524 Expression::convert_interface_to_type(Translate_context* context,
525 Type *lhs_type, Type* rhs_type,
526 tree rhs_tree, Location location)
527 {
528 Gogo* gogo = context->gogo();
529 tree rhs_type_tree = TREE_TYPE(rhs_tree);
530
531 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
532 if (lhs_type_tree == error_mark_node)
533 return error_mark_node;
534
535 // Call a function to check that the type is valid. The function
536 // will panic with an appropriate runtime type error if the type is
537 // not valid.
538
539 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
540
541 if (!DECL_P(rhs_tree))
542 rhs_tree = save_expr(rhs_tree);
543
544 tree rhs_type_descriptor =
545 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
546 location);
547
548 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
549 location);
550
551 static tree check_interface_type_decl;
552 tree call = Gogo::call_builtin(&check_interface_type_decl,
553 location,
554 "__go_check_interface_type",
555 3,
556 void_type_node,
557 TREE_TYPE(lhs_type_descriptor),
558 lhs_type_descriptor,
559 TREE_TYPE(rhs_type_descriptor),
560 rhs_type_descriptor,
561 TREE_TYPE(rhs_inter_descriptor),
562 rhs_inter_descriptor);
563 if (call == error_mark_node)
564 return error_mark_node;
565 // This call will panic if the conversion is invalid.
566 TREE_NOTHROW(check_interface_type_decl) = 0;
567
568 // If the call succeeds, pull out the value.
569 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
570 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
571 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
572 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
573 NULL_TREE);
574
575 // If the value is a pointer, then it is the value we want.
576 // Otherwise it points to the value.
577 if (lhs_type->points_to() == NULL)
578 {
579 val = fold_convert_loc(location.gcc_location(),
580 build_pointer_type(lhs_type_tree), val);
581 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
582 }
583
584 return build2(COMPOUND_EXPR, lhs_type_tree, call,
585 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
586 }
587
588 // Convert an expression to a tree. This is implemented by the child
589 // class. Not that it is not in general safe to call this multiple
590 // times for a single expression, but that we don't catch such errors.
591
592 tree
593 Expression::get_tree(Translate_context* context)
594 {
595 // The child may have marked this expression as having an error.
596 if (this->classification_ == EXPRESSION_ERROR)
597 return error_mark_node;
598
599 return this->do_get_tree(context);
600 }
601
602 // Return a tree for VAL in TYPE.
603
604 tree
605 Expression::integer_constant_tree(mpz_t val, tree type)
606 {
607 if (type == error_mark_node)
608 return error_mark_node;
609 else if (TREE_CODE(type) == INTEGER_TYPE)
610 return double_int_to_tree(type,
611 mpz_get_double_int(type, val, true));
612 else if (TREE_CODE(type) == REAL_TYPE)
613 {
614 mpfr_t fval;
615 mpfr_init_set_z(fval, val, GMP_RNDN);
616 tree ret = Expression::float_constant_tree(fval, type);
617 mpfr_clear(fval);
618 return ret;
619 }
620 else if (TREE_CODE(type) == COMPLEX_TYPE)
621 {
622 mpfr_t fval;
623 mpfr_init_set_z(fval, val, GMP_RNDN);
624 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
625 mpfr_clear(fval);
626 tree imag = build_real_from_int_cst(TREE_TYPE(type),
627 integer_zero_node);
628 return build_complex(type, real, imag);
629 }
630 else
631 go_unreachable();
632 }
633
634 // Return a tree for VAL in TYPE.
635
636 tree
637 Expression::float_constant_tree(mpfr_t val, tree type)
638 {
639 if (type == error_mark_node)
640 return error_mark_node;
641 else if (TREE_CODE(type) == INTEGER_TYPE)
642 {
643 mpz_t ival;
644 mpz_init(ival);
645 mpfr_get_z(ival, val, GMP_RNDN);
646 tree ret = Expression::integer_constant_tree(ival, type);
647 mpz_clear(ival);
648 return ret;
649 }
650 else if (TREE_CODE(type) == REAL_TYPE)
651 {
652 REAL_VALUE_TYPE r1;
653 real_from_mpfr(&r1, val, type, GMP_RNDN);
654 REAL_VALUE_TYPE r2;
655 real_convert(&r2, TYPE_MODE(type), &r1);
656 return build_real(type, r2);
657 }
658 else if (TREE_CODE(type) == COMPLEX_TYPE)
659 {
660 REAL_VALUE_TYPE r1;
661 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
662 REAL_VALUE_TYPE r2;
663 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
664 tree imag = build_real_from_int_cst(TREE_TYPE(type),
665 integer_zero_node);
666 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
667 }
668 else
669 go_unreachable();
670 }
671
672 // Return a tree for REAL/IMAG in TYPE.
673
674 tree
675 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
676 {
677 if (type == error_mark_node)
678 return error_mark_node;
679 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
680 return Expression::float_constant_tree(real, type);
681 else if (TREE_CODE(type) == COMPLEX_TYPE)
682 {
683 REAL_VALUE_TYPE r1;
684 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
685 REAL_VALUE_TYPE r2;
686 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
687
688 REAL_VALUE_TYPE r3;
689 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
690 REAL_VALUE_TYPE r4;
691 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
692
693 return build_complex(type, build_real(TREE_TYPE(type), r2),
694 build_real(TREE_TYPE(type), r4));
695 }
696 else
697 go_unreachable();
698 }
699
700 // Return a tree which evaluates to true if VAL, of arbitrary integer
701 // type, is negative or is more than the maximum value of BOUND_TYPE.
702 // If SOFAR is not NULL, it is or'red into the result. The return
703 // value may be NULL if SOFAR is NULL.
704
705 tree
706 Expression::check_bounds(tree val, tree bound_type, tree sofar,
707 Location loc)
708 {
709 tree val_type = TREE_TYPE(val);
710 tree ret = NULL_TREE;
711
712 if (!TYPE_UNSIGNED(val_type))
713 {
714 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
715 build_int_cst(val_type, 0));
716 if (ret == boolean_false_node)
717 ret = NULL_TREE;
718 }
719
720 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
721 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
722 go_assert(val_type_size != -1 && bound_type_size != -1);
723 if (val_type_size > bound_type_size
724 || (val_type_size == bound_type_size
725 && TYPE_UNSIGNED(val_type)
726 && !TYPE_UNSIGNED(bound_type)))
727 {
728 tree max = TYPE_MAX_VALUE(bound_type);
729 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
730 val, fold_convert_loc(loc.gcc_location(),
731 val_type, max));
732 if (big == boolean_false_node)
733 ;
734 else if (ret == NULL_TREE)
735 ret = big;
736 else
737 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
738 boolean_type_node, ret, big);
739 }
740
741 if (ret == NULL_TREE)
742 return sofar;
743 else if (sofar == NULL_TREE)
744 return ret;
745 else
746 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
747 sofar, ret);
748 }
749
750 void
751 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
752 {
753 this->do_dump_expression(ast_dump_context);
754 }
755
756 // Error expressions. This are used to avoid cascading errors.
757
758 class Error_expression : public Expression
759 {
760 public:
761 Error_expression(Location location)
762 : Expression(EXPRESSION_ERROR, location)
763 { }
764
765 protected:
766 bool
767 do_is_constant() const
768 { return true; }
769
770 bool
771 do_numeric_constant_value(Numeric_constant* nc) const
772 {
773 nc->set_unsigned_long(NULL, 0);
774 return true;
775 }
776
777 void
778 do_discarding_value()
779 { }
780
781 Type*
782 do_type()
783 { return Type::make_error_type(); }
784
785 void
786 do_determine_type(const Type_context*)
787 { }
788
789 Expression*
790 do_copy()
791 { return this; }
792
793 bool
794 do_is_addressable() const
795 { return true; }
796
797 tree
798 do_get_tree(Translate_context*)
799 { return error_mark_node; }
800
801 void
802 do_dump_expression(Ast_dump_context*) const;
803 };
804
805 // Dump the ast representation for an error expression to a dump context.
806
807 void
808 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
809 {
810 ast_dump_context->ostream() << "_Error_" ;
811 }
812
813 Expression*
814 Expression::make_error(Location location)
815 {
816 return new Error_expression(location);
817 }
818
819 // An expression which is really a type. This is used during parsing.
820 // It is an error if these survive after lowering.
821
822 class
823 Type_expression : public Expression
824 {
825 public:
826 Type_expression(Type* type, Location location)
827 : Expression(EXPRESSION_TYPE, location),
828 type_(type)
829 { }
830
831 protected:
832 int
833 do_traverse(Traverse* traverse)
834 { return Type::traverse(this->type_, traverse); }
835
836 Type*
837 do_type()
838 { return this->type_; }
839
840 void
841 do_determine_type(const Type_context*)
842 { }
843
844 void
845 do_check_types(Gogo*)
846 { this->report_error(_("invalid use of type")); }
847
848 Expression*
849 do_copy()
850 { return this; }
851
852 tree
853 do_get_tree(Translate_context*)
854 { go_unreachable(); }
855
856 void do_dump_expression(Ast_dump_context*) const;
857
858 private:
859 // The type which we are representing as an expression.
860 Type* type_;
861 };
862
863 void
864 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
865 {
866 ast_dump_context->dump_type(this->type_);
867 }
868
869 Expression*
870 Expression::make_type(Type* type, Location location)
871 {
872 return new Type_expression(type, location);
873 }
874
875 // Class Parser_expression.
876
877 Type*
878 Parser_expression::do_type()
879 {
880 // We should never really ask for the type of a Parser_expression.
881 // However, it can happen, at least when we have an invalid const
882 // whose initializer refers to the const itself. In that case we
883 // may ask for the type when lowering the const itself.
884 go_assert(saw_errors());
885 return Type::make_error_type();
886 }
887
888 // Class Var_expression.
889
890 // Lower a variable expression. Here we just make sure that the
891 // initialization expression of the variable has been lowered. This
892 // ensures that we will be able to determine the type of the variable
893 // if necessary.
894
895 Expression*
896 Var_expression::do_lower(Gogo* gogo, Named_object* function,
897 Statement_inserter* inserter, int)
898 {
899 if (this->variable_->is_variable())
900 {
901 Variable* var = this->variable_->var_value();
902 // This is either a local variable or a global variable. A
903 // reference to a variable which is local to an enclosing
904 // function will be a reference to a field in a closure.
905 if (var->is_global())
906 {
907 function = NULL;
908 inserter = NULL;
909 }
910 var->lower_init_expression(gogo, function, inserter);
911 }
912 return this;
913 }
914
915 // Return the type of a reference to a variable.
916
917 Type*
918 Var_expression::do_type()
919 {
920 if (this->variable_->is_variable())
921 return this->variable_->var_value()->type();
922 else if (this->variable_->is_result_variable())
923 return this->variable_->result_var_value()->type();
924 else
925 go_unreachable();
926 }
927
928 // Determine the type of a reference to a variable.
929
930 void
931 Var_expression::do_determine_type(const Type_context*)
932 {
933 if (this->variable_->is_variable())
934 this->variable_->var_value()->determine_type();
935 }
936
937 // Something takes the address of this variable. This means that we
938 // may want to move the variable onto the heap.
939
940 void
941 Var_expression::do_address_taken(bool escapes)
942 {
943 if (!escapes)
944 {
945 if (this->variable_->is_variable())
946 this->variable_->var_value()->set_non_escaping_address_taken();
947 else if (this->variable_->is_result_variable())
948 this->variable_->result_var_value()->set_non_escaping_address_taken();
949 else
950 go_unreachable();
951 }
952 else
953 {
954 if (this->variable_->is_variable())
955 this->variable_->var_value()->set_address_taken();
956 else if (this->variable_->is_result_variable())
957 this->variable_->result_var_value()->set_address_taken();
958 else
959 go_unreachable();
960 }
961 }
962
963 // Get the tree for a reference to a variable.
964
965 tree
966 Var_expression::do_get_tree(Translate_context* context)
967 {
968 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
969 context->function());
970 tree ret = var_to_tree(bvar);
971 if (ret == error_mark_node)
972 return error_mark_node;
973 bool is_in_heap;
974 if (this->variable_->is_variable())
975 is_in_heap = this->variable_->var_value()->is_in_heap();
976 else if (this->variable_->is_result_variable())
977 is_in_heap = this->variable_->result_var_value()->is_in_heap();
978 else
979 go_unreachable();
980 if (is_in_heap)
981 {
982 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
983 TREE_THIS_NOTRAP(ret) = 1;
984 }
985 return ret;
986 }
987
988 // Ast dump for variable expression.
989
990 void
991 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
992 {
993 ast_dump_context->ostream() << this->variable_->name() ;
994 }
995
996 // Make a reference to a variable in an expression.
997
998 Expression*
999 Expression::make_var_reference(Named_object* var, Location location)
1000 {
1001 if (var->is_sink())
1002 return Expression::make_sink(location);
1003
1004 // FIXME: Creating a new object for each reference to a variable is
1005 // wasteful.
1006 return new Var_expression(var, location);
1007 }
1008
1009 // Class Temporary_reference_expression.
1010
1011 // The type.
1012
1013 Type*
1014 Temporary_reference_expression::do_type()
1015 {
1016 return this->statement_->type();
1017 }
1018
1019 // Called if something takes the address of this temporary variable.
1020 // We never have to move temporary variables to the heap, but we do
1021 // need to know that they must live in the stack rather than in a
1022 // register.
1023
1024 void
1025 Temporary_reference_expression::do_address_taken(bool)
1026 {
1027 this->statement_->set_is_address_taken();
1028 }
1029
1030 // Get a tree referring to the variable.
1031
1032 tree
1033 Temporary_reference_expression::do_get_tree(Translate_context* context)
1034 {
1035 Bvariable* bvar = this->statement_->get_backend_variable(context);
1036
1037 // The gcc backend can't represent the same set of recursive types
1038 // that the Go frontend can. In some cases this means that a
1039 // temporary variable won't have the right backend type. Correct
1040 // that here by adding a type cast. We need to use base() to push
1041 // the circularity down one level.
1042 tree ret = var_to_tree(bvar);
1043 if (!this->is_lvalue_
1044 && POINTER_TYPE_P(TREE_TYPE(ret))
1045 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1046 {
1047 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1048 tree type_tree = type_to_tree(type_btype);
1049 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1050 }
1051 return ret;
1052 }
1053
1054 // Ast dump for temporary reference.
1055
1056 void
1057 Temporary_reference_expression::do_dump_expression(
1058 Ast_dump_context* ast_dump_context) const
1059 {
1060 ast_dump_context->dump_temp_variable_name(this->statement_);
1061 }
1062
1063 // Make a reference to a temporary variable.
1064
1065 Temporary_reference_expression*
1066 Expression::make_temporary_reference(Temporary_statement* statement,
1067 Location location)
1068 {
1069 return new Temporary_reference_expression(statement, location);
1070 }
1071
1072 // Class Set_and_use_temporary_expression.
1073
1074 // Return the type.
1075
1076 Type*
1077 Set_and_use_temporary_expression::do_type()
1078 {
1079 return this->statement_->type();
1080 }
1081
1082 // Take the address.
1083
1084 void
1085 Set_and_use_temporary_expression::do_address_taken(bool)
1086 {
1087 this->statement_->set_is_address_taken();
1088 }
1089
1090 // Return the backend representation.
1091
1092 tree
1093 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1094 {
1095 Bvariable* bvar = this->statement_->get_backend_variable(context);
1096 tree var_tree = var_to_tree(bvar);
1097 tree expr_tree = this->expr_->get_tree(context);
1098 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1099 return error_mark_node;
1100 Location loc = this->location();
1101 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1102 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1103 var_tree, expr_tree),
1104 var_tree);
1105 }
1106
1107 // Dump.
1108
1109 void
1110 Set_and_use_temporary_expression::do_dump_expression(
1111 Ast_dump_context* ast_dump_context) const
1112 {
1113 ast_dump_context->ostream() << '(';
1114 ast_dump_context->dump_temp_variable_name(this->statement_);
1115 ast_dump_context->ostream() << " = ";
1116 this->expr_->dump_expression(ast_dump_context);
1117 ast_dump_context->ostream() << ')';
1118 }
1119
1120 // Make a set-and-use temporary.
1121
1122 Set_and_use_temporary_expression*
1123 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1124 Expression* expr, Location location)
1125 {
1126 return new Set_and_use_temporary_expression(statement, expr, location);
1127 }
1128
1129 // A sink expression--a use of the blank identifier _.
1130
1131 class Sink_expression : public Expression
1132 {
1133 public:
1134 Sink_expression(Location location)
1135 : Expression(EXPRESSION_SINK, location),
1136 type_(NULL), var_(NULL_TREE)
1137 { }
1138
1139 protected:
1140 void
1141 do_discarding_value()
1142 { }
1143
1144 Type*
1145 do_type();
1146
1147 void
1148 do_determine_type(const Type_context*);
1149
1150 Expression*
1151 do_copy()
1152 { return new Sink_expression(this->location()); }
1153
1154 tree
1155 do_get_tree(Translate_context*);
1156
1157 void
1158 do_dump_expression(Ast_dump_context*) const;
1159
1160 private:
1161 // The type of this sink variable.
1162 Type* type_;
1163 // The temporary variable we generate.
1164 tree var_;
1165 };
1166
1167 // Return the type of a sink expression.
1168
1169 Type*
1170 Sink_expression::do_type()
1171 {
1172 if (this->type_ == NULL)
1173 return Type::make_sink_type();
1174 return this->type_;
1175 }
1176
1177 // Determine the type of a sink expression.
1178
1179 void
1180 Sink_expression::do_determine_type(const Type_context* context)
1181 {
1182 if (context->type != NULL)
1183 this->type_ = context->type;
1184 }
1185
1186 // Return a temporary variable for a sink expression. This will
1187 // presumably be a write-only variable which the middle-end will drop.
1188
1189 tree
1190 Sink_expression::do_get_tree(Translate_context* context)
1191 {
1192 if (this->var_ == NULL_TREE)
1193 {
1194 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1195 Btype* bt = this->type_->get_backend(context->gogo());
1196 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1197 }
1198 return this->var_;
1199 }
1200
1201 // Ast dump for sink expression.
1202
1203 void
1204 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1205 {
1206 ast_dump_context->ostream() << "_" ;
1207 }
1208
1209 // Make a sink expression.
1210
1211 Expression*
1212 Expression::make_sink(Location location)
1213 {
1214 return new Sink_expression(location);
1215 }
1216
1217 // Class Func_expression.
1218
1219 // FIXME: Can a function expression appear in a constant expression?
1220 // The value is unchanging. Initializing a constant to the address of
1221 // a function seems like it could work, though there might be little
1222 // point to it.
1223
1224 // Traversal.
1225
1226 int
1227 Func_expression::do_traverse(Traverse* traverse)
1228 {
1229 return (this->closure_ == NULL
1230 ? TRAVERSE_CONTINUE
1231 : Expression::traverse(&this->closure_, traverse));
1232 }
1233
1234 // Return the type of a function expression.
1235
1236 Type*
1237 Func_expression::do_type()
1238 {
1239 if (this->function_->is_function())
1240 return this->function_->func_value()->type();
1241 else if (this->function_->is_function_declaration())
1242 return this->function_->func_declaration_value()->type();
1243 else
1244 go_unreachable();
1245 }
1246
1247 // Get the tree for a function expression without evaluating the
1248 // closure.
1249
1250 tree
1251 Func_expression::get_tree_without_closure(Gogo* gogo)
1252 {
1253 Function_type* fntype;
1254 if (this->function_->is_function())
1255 fntype = this->function_->func_value()->type();
1256 else if (this->function_->is_function_declaration())
1257 fntype = this->function_->func_declaration_value()->type();
1258 else
1259 go_unreachable();
1260
1261 // Builtin functions are handled specially by Call_expression. We
1262 // can't take their address.
1263 if (fntype->is_builtin())
1264 {
1265 error_at(this->location(),
1266 "invalid use of special builtin function %qs; must be called",
1267 this->function_->name().c_str());
1268 return error_mark_node;
1269 }
1270
1271 Named_object* no = this->function_;
1272
1273 tree id = no->get_id(gogo);
1274 if (id == error_mark_node)
1275 return error_mark_node;
1276
1277 tree fndecl;
1278 if (no->is_function())
1279 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1280 else if (no->is_function_declaration())
1281 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1282 else
1283 go_unreachable();
1284
1285 if (fndecl == error_mark_node)
1286 return error_mark_node;
1287
1288 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1289 }
1290
1291 // Get the tree for a function expression. This is used when we take
1292 // the address of a function rather than simply calling it. If the
1293 // function has a closure, we must use a trampoline.
1294
1295 tree
1296 Func_expression::do_get_tree(Translate_context* context)
1297 {
1298 Gogo* gogo = context->gogo();
1299
1300 tree fnaddr = this->get_tree_without_closure(gogo);
1301 if (fnaddr == error_mark_node)
1302 return error_mark_node;
1303
1304 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1305 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1306 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1307
1308 // If there is no closure, that is all have to do.
1309 if (this->closure_ == NULL)
1310 return fnaddr;
1311
1312 go_assert(this->function_->func_value()->enclosing() != NULL);
1313
1314 // Get the value of the closure. This will be a pointer to space
1315 // allocated on the heap.
1316 tree closure_tree = this->closure_->get_tree(context);
1317 if (closure_tree == error_mark_node)
1318 return error_mark_node;
1319 go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1320
1321 // Now we need to build some code on the heap. This code will load
1322 // the static chain pointer with the closure and then jump to the
1323 // body of the function. The normal gcc approach is to build the
1324 // code on the stack. Unfortunately we can not do that, as Go
1325 // permits us to return the function pointer.
1326
1327 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1328 }
1329
1330 // Ast dump for function.
1331
1332 void
1333 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1334 {
1335 ast_dump_context->ostream() << this->function_->name();
1336 if (this->closure_ != NULL)
1337 {
1338 ast_dump_context->ostream() << " {closure = ";
1339 this->closure_->dump_expression(ast_dump_context);
1340 ast_dump_context->ostream() << "}";
1341 }
1342 }
1343
1344 // Make a reference to a function in an expression.
1345
1346 Expression*
1347 Expression::make_func_reference(Named_object* function, Expression* closure,
1348 Location location)
1349 {
1350 return new Func_expression(function, closure, location);
1351 }
1352
1353 // Class Unknown_expression.
1354
1355 // Return the name of an unknown expression.
1356
1357 const std::string&
1358 Unknown_expression::name() const
1359 {
1360 return this->named_object_->name();
1361 }
1362
1363 // Lower a reference to an unknown name.
1364
1365 Expression*
1366 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1367 {
1368 Location location = this->location();
1369 Named_object* no = this->named_object_;
1370 Named_object* real;
1371 if (!no->is_unknown())
1372 real = no;
1373 else
1374 {
1375 real = no->unknown_value()->real_named_object();
1376 if (real == NULL)
1377 {
1378 if (this->is_composite_literal_key_)
1379 return this;
1380 if (!this->no_error_message_)
1381 error_at(location, "reference to undefined name %qs",
1382 this->named_object_->message_name().c_str());
1383 return Expression::make_error(location);
1384 }
1385 }
1386 switch (real->classification())
1387 {
1388 case Named_object::NAMED_OBJECT_CONST:
1389 return Expression::make_const_reference(real, location);
1390 case Named_object::NAMED_OBJECT_TYPE:
1391 return Expression::make_type(real->type_value(), location);
1392 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1393 if (this->is_composite_literal_key_)
1394 return this;
1395 if (!this->no_error_message_)
1396 error_at(location, "reference to undefined type %qs",
1397 real->message_name().c_str());
1398 return Expression::make_error(location);
1399 case Named_object::NAMED_OBJECT_VAR:
1400 real->var_value()->set_is_used();
1401 return Expression::make_var_reference(real, location);
1402 case Named_object::NAMED_OBJECT_FUNC:
1403 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1404 return Expression::make_func_reference(real, NULL, location);
1405 case Named_object::NAMED_OBJECT_PACKAGE:
1406 if (this->is_composite_literal_key_)
1407 return this;
1408 if (!this->no_error_message_)
1409 error_at(location, "unexpected reference to package");
1410 return Expression::make_error(location);
1411 default:
1412 go_unreachable();
1413 }
1414 }
1415
1416 // Dump the ast representation for an unknown expression to a dump context.
1417
1418 void
1419 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1420 {
1421 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1422 << ")";
1423 }
1424
1425 // Make a reference to an unknown name.
1426
1427 Unknown_expression*
1428 Expression::make_unknown_reference(Named_object* no, Location location)
1429 {
1430 return new Unknown_expression(no, location);
1431 }
1432
1433 // A boolean expression.
1434
1435 class Boolean_expression : public Expression
1436 {
1437 public:
1438 Boolean_expression(bool val, Location location)
1439 : Expression(EXPRESSION_BOOLEAN, location),
1440 val_(val), type_(NULL)
1441 { }
1442
1443 static Expression*
1444 do_import(Import*);
1445
1446 protected:
1447 bool
1448 do_is_constant() const
1449 { return true; }
1450
1451 Type*
1452 do_type();
1453
1454 void
1455 do_determine_type(const Type_context*);
1456
1457 Expression*
1458 do_copy()
1459 { return this; }
1460
1461 tree
1462 do_get_tree(Translate_context*)
1463 { return this->val_ ? boolean_true_node : boolean_false_node; }
1464
1465 void
1466 do_export(Export* exp) const
1467 { exp->write_c_string(this->val_ ? "true" : "false"); }
1468
1469 void
1470 do_dump_expression(Ast_dump_context* ast_dump_context) const
1471 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1472
1473 private:
1474 // The constant.
1475 bool val_;
1476 // The type as determined by context.
1477 Type* type_;
1478 };
1479
1480 // Get the type.
1481
1482 Type*
1483 Boolean_expression::do_type()
1484 {
1485 if (this->type_ == NULL)
1486 this->type_ = Type::make_boolean_type();
1487 return this->type_;
1488 }
1489
1490 // Set the type from the context.
1491
1492 void
1493 Boolean_expression::do_determine_type(const Type_context* context)
1494 {
1495 if (this->type_ != NULL && !this->type_->is_abstract())
1496 ;
1497 else if (context->type != NULL && context->type->is_boolean_type())
1498 this->type_ = context->type;
1499 else if (!context->may_be_abstract)
1500 this->type_ = Type::lookup_bool_type();
1501 }
1502
1503 // Import a boolean constant.
1504
1505 Expression*
1506 Boolean_expression::do_import(Import* imp)
1507 {
1508 if (imp->peek_char() == 't')
1509 {
1510 imp->require_c_string("true");
1511 return Expression::make_boolean(true, imp->location());
1512 }
1513 else
1514 {
1515 imp->require_c_string("false");
1516 return Expression::make_boolean(false, imp->location());
1517 }
1518 }
1519
1520 // Make a boolean expression.
1521
1522 Expression*
1523 Expression::make_boolean(bool val, Location location)
1524 {
1525 return new Boolean_expression(val, location);
1526 }
1527
1528 // Class String_expression.
1529
1530 // Get the type.
1531
1532 Type*
1533 String_expression::do_type()
1534 {
1535 if (this->type_ == NULL)
1536 this->type_ = Type::make_string_type();
1537 return this->type_;
1538 }
1539
1540 // Set the type from the context.
1541
1542 void
1543 String_expression::do_determine_type(const Type_context* context)
1544 {
1545 if (this->type_ != NULL && !this->type_->is_abstract())
1546 ;
1547 else if (context->type != NULL && context->type->is_string_type())
1548 this->type_ = context->type;
1549 else if (!context->may_be_abstract)
1550 this->type_ = Type::lookup_string_type();
1551 }
1552
1553 // Build a string constant.
1554
1555 tree
1556 String_expression::do_get_tree(Translate_context* context)
1557 {
1558 return context->gogo()->go_string_constant_tree(this->val_);
1559 }
1560
1561 // Write string literal to string dump.
1562
1563 void
1564 String_expression::export_string(String_dump* exp,
1565 const String_expression* str)
1566 {
1567 std::string s;
1568 s.reserve(str->val_.length() * 4 + 2);
1569 s += '"';
1570 for (std::string::const_iterator p = str->val_.begin();
1571 p != str->val_.end();
1572 ++p)
1573 {
1574 if (*p == '\\' || *p == '"')
1575 {
1576 s += '\\';
1577 s += *p;
1578 }
1579 else if (*p >= 0x20 && *p < 0x7f)
1580 s += *p;
1581 else if (*p == '\n')
1582 s += "\\n";
1583 else if (*p == '\t')
1584 s += "\\t";
1585 else
1586 {
1587 s += "\\x";
1588 unsigned char c = *p;
1589 unsigned int dig = c >> 4;
1590 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1591 dig = c & 0xf;
1592 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1593 }
1594 }
1595 s += '"';
1596 exp->write_string(s);
1597 }
1598
1599 // Export a string expression.
1600
1601 void
1602 String_expression::do_export(Export* exp) const
1603 {
1604 String_expression::export_string(exp, this);
1605 }
1606
1607 // Import a string expression.
1608
1609 Expression*
1610 String_expression::do_import(Import* imp)
1611 {
1612 imp->require_c_string("\"");
1613 std::string val;
1614 while (true)
1615 {
1616 int c = imp->get_char();
1617 if (c == '"' || c == -1)
1618 break;
1619 if (c != '\\')
1620 val += static_cast<char>(c);
1621 else
1622 {
1623 c = imp->get_char();
1624 if (c == '\\' || c == '"')
1625 val += static_cast<char>(c);
1626 else if (c == 'n')
1627 val += '\n';
1628 else if (c == 't')
1629 val += '\t';
1630 else if (c == 'x')
1631 {
1632 c = imp->get_char();
1633 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1634 c = imp->get_char();
1635 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1636 char v = (vh << 4) | vl;
1637 val += v;
1638 }
1639 else
1640 {
1641 error_at(imp->location(), "bad string constant");
1642 return Expression::make_error(imp->location());
1643 }
1644 }
1645 }
1646 return Expression::make_string(val, imp->location());
1647 }
1648
1649 // Ast dump for string expression.
1650
1651 void
1652 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1653 {
1654 String_expression::export_string(ast_dump_context, this);
1655 }
1656
1657 // Make a string expression.
1658
1659 Expression*
1660 Expression::make_string(const std::string& val, Location location)
1661 {
1662 return new String_expression(val, location);
1663 }
1664
1665 // Make an integer expression.
1666
1667 class Integer_expression : public Expression
1668 {
1669 public:
1670 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1671 Location location)
1672 : Expression(EXPRESSION_INTEGER, location),
1673 type_(type), is_character_constant_(is_character_constant)
1674 { mpz_init_set(this->val_, *val); }
1675
1676 static Expression*
1677 do_import(Import*);
1678
1679 // Write VAL to string dump.
1680 static void
1681 export_integer(String_dump* exp, const mpz_t val);
1682
1683 // Write VAL to dump context.
1684 static void
1685 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1686
1687 protected:
1688 bool
1689 do_is_constant() const
1690 { return true; }
1691
1692 bool
1693 do_numeric_constant_value(Numeric_constant* nc) const;
1694
1695 Type*
1696 do_type();
1697
1698 void
1699 do_determine_type(const Type_context* context);
1700
1701 void
1702 do_check_types(Gogo*);
1703
1704 tree
1705 do_get_tree(Translate_context*);
1706
1707 Expression*
1708 do_copy()
1709 {
1710 if (this->is_character_constant_)
1711 return Expression::make_character(&this->val_, this->type_,
1712 this->location());
1713 else
1714 return Expression::make_integer(&this->val_, this->type_,
1715 this->location());
1716 }
1717
1718 void
1719 do_export(Export*) const;
1720
1721 void
1722 do_dump_expression(Ast_dump_context*) const;
1723
1724 private:
1725 // The integer value.
1726 mpz_t val_;
1727 // The type so far.
1728 Type* type_;
1729 // Whether this is a character constant.
1730 bool is_character_constant_;
1731 };
1732
1733 // Return a numeric constant for this expression. We have to mark
1734 // this as a character when appropriate.
1735
1736 bool
1737 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1738 {
1739 if (this->is_character_constant_)
1740 nc->set_rune(this->type_, this->val_);
1741 else
1742 nc->set_int(this->type_, this->val_);
1743 return true;
1744 }
1745
1746 // Return the current type. If we haven't set the type yet, we return
1747 // an abstract integer type.
1748
1749 Type*
1750 Integer_expression::do_type()
1751 {
1752 if (this->type_ == NULL)
1753 {
1754 if (this->is_character_constant_)
1755 this->type_ = Type::make_abstract_character_type();
1756 else
1757 this->type_ = Type::make_abstract_integer_type();
1758 }
1759 return this->type_;
1760 }
1761
1762 // Set the type of the integer value. Here we may switch from an
1763 // abstract type to a real type.
1764
1765 void
1766 Integer_expression::do_determine_type(const Type_context* context)
1767 {
1768 if (this->type_ != NULL && !this->type_->is_abstract())
1769 ;
1770 else if (context->type != NULL && context->type->is_numeric_type())
1771 this->type_ = context->type;
1772 else if (!context->may_be_abstract)
1773 {
1774 if (this->is_character_constant_)
1775 this->type_ = Type::lookup_integer_type("int32");
1776 else
1777 this->type_ = Type::lookup_integer_type("int");
1778 }
1779 }
1780
1781 // Check the type of an integer constant.
1782
1783 void
1784 Integer_expression::do_check_types(Gogo*)
1785 {
1786 Type* type = this->type_;
1787 if (type == NULL)
1788 return;
1789 Numeric_constant nc;
1790 if (this->is_character_constant_)
1791 nc.set_rune(NULL, this->val_);
1792 else
1793 nc.set_int(NULL, this->val_);
1794 if (!nc.set_type(type, true, this->location()))
1795 this->set_is_error();
1796 }
1797
1798 // Get a tree for an integer constant.
1799
1800 tree
1801 Integer_expression::do_get_tree(Translate_context* context)
1802 {
1803 Gogo* gogo = context->gogo();
1804 tree type;
1805 if (this->type_ != NULL && !this->type_->is_abstract())
1806 type = type_to_tree(this->type_->get_backend(gogo));
1807 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1808 {
1809 // We are converting to an abstract floating point type.
1810 Type* ftype = Type::lookup_float_type("float64");
1811 type = type_to_tree(ftype->get_backend(gogo));
1812 }
1813 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1814 {
1815 // We are converting to an abstract complex type.
1816 Type* ctype = Type::lookup_complex_type("complex128");
1817 type = type_to_tree(ctype->get_backend(gogo));
1818 }
1819 else
1820 {
1821 // If we still have an abstract type here, then this is being
1822 // used in a constant expression which didn't get reduced for
1823 // some reason. Use a type which will fit the value. We use <,
1824 // not <=, because we need an extra bit for the sign bit.
1825 int bits = mpz_sizeinbase(this->val_, 2);
1826 if (bits < INT_TYPE_SIZE)
1827 {
1828 Type* t = Type::lookup_integer_type("int");
1829 type = type_to_tree(t->get_backend(gogo));
1830 }
1831 else if (bits < 64)
1832 {
1833 Type* t = Type::lookup_integer_type("int64");
1834 type = type_to_tree(t->get_backend(gogo));
1835 }
1836 else
1837 type = long_long_integer_type_node;
1838 }
1839 return Expression::integer_constant_tree(this->val_, type);
1840 }
1841
1842 // Write VAL to export data.
1843
1844 void
1845 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1846 {
1847 char* s = mpz_get_str(NULL, 10, val);
1848 exp->write_c_string(s);
1849 free(s);
1850 }
1851
1852 // Export an integer in a constant expression.
1853
1854 void
1855 Integer_expression::do_export(Export* exp) const
1856 {
1857 Integer_expression::export_integer(exp, this->val_);
1858 if (this->is_character_constant_)
1859 exp->write_c_string("'");
1860 // A trailing space lets us reliably identify the end of the number.
1861 exp->write_c_string(" ");
1862 }
1863
1864 // Import an integer, floating point, or complex value. This handles
1865 // all these types because they all start with digits.
1866
1867 Expression*
1868 Integer_expression::do_import(Import* imp)
1869 {
1870 std::string num = imp->read_identifier();
1871 imp->require_c_string(" ");
1872 if (!num.empty() && num[num.length() - 1] == 'i')
1873 {
1874 mpfr_t real;
1875 size_t plus_pos = num.find('+', 1);
1876 size_t minus_pos = num.find('-', 1);
1877 size_t pos;
1878 if (plus_pos == std::string::npos)
1879 pos = minus_pos;
1880 else if (minus_pos == std::string::npos)
1881 pos = plus_pos;
1882 else
1883 {
1884 error_at(imp->location(), "bad number in import data: %qs",
1885 num.c_str());
1886 return Expression::make_error(imp->location());
1887 }
1888 if (pos == std::string::npos)
1889 mpfr_set_ui(real, 0, GMP_RNDN);
1890 else
1891 {
1892 std::string real_str = num.substr(0, pos);
1893 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1894 {
1895 error_at(imp->location(), "bad number in import data: %qs",
1896 real_str.c_str());
1897 return Expression::make_error(imp->location());
1898 }
1899 }
1900
1901 std::string imag_str;
1902 if (pos == std::string::npos)
1903 imag_str = num;
1904 else
1905 imag_str = num.substr(pos);
1906 imag_str = imag_str.substr(0, imag_str.size() - 1);
1907 mpfr_t imag;
1908 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1909 {
1910 error_at(imp->location(), "bad number in import data: %qs",
1911 imag_str.c_str());
1912 return Expression::make_error(imp->location());
1913 }
1914 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1915 imp->location());
1916 mpfr_clear(real);
1917 mpfr_clear(imag);
1918 return ret;
1919 }
1920 else if (num.find('.') == std::string::npos
1921 && num.find('E') == std::string::npos)
1922 {
1923 bool is_character_constant = (!num.empty()
1924 && num[num.length() - 1] == '\'');
1925 if (is_character_constant)
1926 num = num.substr(0, num.length() - 1);
1927 mpz_t val;
1928 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1929 {
1930 error_at(imp->location(), "bad number in import data: %qs",
1931 num.c_str());
1932 return Expression::make_error(imp->location());
1933 }
1934 Expression* ret;
1935 if (is_character_constant)
1936 ret = Expression::make_character(&val, NULL, imp->location());
1937 else
1938 ret = Expression::make_integer(&val, NULL, imp->location());
1939 mpz_clear(val);
1940 return ret;
1941 }
1942 else
1943 {
1944 mpfr_t val;
1945 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1946 {
1947 error_at(imp->location(), "bad number in import data: %qs",
1948 num.c_str());
1949 return Expression::make_error(imp->location());
1950 }
1951 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1952 mpfr_clear(val);
1953 return ret;
1954 }
1955 }
1956 // Ast dump for integer expression.
1957
1958 void
1959 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1960 {
1961 if (this->is_character_constant_)
1962 ast_dump_context->ostream() << '\'';
1963 Integer_expression::export_integer(ast_dump_context, this->val_);
1964 if (this->is_character_constant_)
1965 ast_dump_context->ostream() << '\'';
1966 }
1967
1968 // Build a new integer value.
1969
1970 Expression*
1971 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1972 {
1973 return new Integer_expression(val, type, false, location);
1974 }
1975
1976 // Build a new character constant value.
1977
1978 Expression*
1979 Expression::make_character(const mpz_t* val, Type* type, Location location)
1980 {
1981 return new Integer_expression(val, type, true, location);
1982 }
1983
1984 // Floats.
1985
1986 class Float_expression : public Expression
1987 {
1988 public:
1989 Float_expression(const mpfr_t* val, Type* type, Location location)
1990 : Expression(EXPRESSION_FLOAT, location),
1991 type_(type)
1992 {
1993 mpfr_init_set(this->val_, *val, GMP_RNDN);
1994 }
1995
1996 // Write VAL to export data.
1997 static void
1998 export_float(String_dump* exp, const mpfr_t val);
1999
2000 // Write VAL to dump file.
2001 static void
2002 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2003
2004 protected:
2005 bool
2006 do_is_constant() const
2007 { return true; }
2008
2009 bool
2010 do_numeric_constant_value(Numeric_constant* nc) const
2011 {
2012 nc->set_float(this->type_, this->val_);
2013 return true;
2014 }
2015
2016 Type*
2017 do_type();
2018
2019 void
2020 do_determine_type(const Type_context*);
2021
2022 void
2023 do_check_types(Gogo*);
2024
2025 Expression*
2026 do_copy()
2027 { return Expression::make_float(&this->val_, this->type_,
2028 this->location()); }
2029
2030 tree
2031 do_get_tree(Translate_context*);
2032
2033 void
2034 do_export(Export*) const;
2035
2036 void
2037 do_dump_expression(Ast_dump_context*) const;
2038
2039 private:
2040 // The floating point value.
2041 mpfr_t val_;
2042 // The type so far.
2043 Type* type_;
2044 };
2045
2046 // Return the current type. If we haven't set the type yet, we return
2047 // an abstract float type.
2048
2049 Type*
2050 Float_expression::do_type()
2051 {
2052 if (this->type_ == NULL)
2053 this->type_ = Type::make_abstract_float_type();
2054 return this->type_;
2055 }
2056
2057 // Set the type of the float value. Here we may switch from an
2058 // abstract type to a real type.
2059
2060 void
2061 Float_expression::do_determine_type(const Type_context* context)
2062 {
2063 if (this->type_ != NULL && !this->type_->is_abstract())
2064 ;
2065 else if (context->type != NULL
2066 && (context->type->integer_type() != NULL
2067 || context->type->float_type() != NULL
2068 || context->type->complex_type() != NULL))
2069 this->type_ = context->type;
2070 else if (!context->may_be_abstract)
2071 this->type_ = Type::lookup_float_type("float64");
2072 }
2073
2074 // Check the type of a float value.
2075
2076 void
2077 Float_expression::do_check_types(Gogo*)
2078 {
2079 Type* type = this->type_;
2080 if (type == NULL)
2081 return;
2082 Numeric_constant nc;
2083 nc.set_float(NULL, this->val_);
2084 if (!nc.set_type(this->type_, true, this->location()))
2085 this->set_is_error();
2086 }
2087
2088 // Get a tree for a float constant.
2089
2090 tree
2091 Float_expression::do_get_tree(Translate_context* context)
2092 {
2093 Gogo* gogo = context->gogo();
2094 tree type;
2095 if (this->type_ != NULL && !this->type_->is_abstract())
2096 type = type_to_tree(this->type_->get_backend(gogo));
2097 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2098 {
2099 // We have an abstract integer type. We just hope for the best.
2100 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2101 }
2102 else
2103 {
2104 // If we still have an abstract type here, then this is being
2105 // used in a constant expression which didn't get reduced. We
2106 // just use float64 and hope for the best.
2107 Type* ft = Type::lookup_float_type("float64");
2108 type = type_to_tree(ft->get_backend(gogo));
2109 }
2110 return Expression::float_constant_tree(this->val_, type);
2111 }
2112
2113 // Write a floating point number to a string dump.
2114
2115 void
2116 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2117 {
2118 mp_exp_t exponent;
2119 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2120 if (*s == '-')
2121 exp->write_c_string("-");
2122 exp->write_c_string("0.");
2123 exp->write_c_string(*s == '-' ? s + 1 : s);
2124 mpfr_free_str(s);
2125 char buf[30];
2126 snprintf(buf, sizeof buf, "E%ld", exponent);
2127 exp->write_c_string(buf);
2128 }
2129
2130 // Export a floating point number in a constant expression.
2131
2132 void
2133 Float_expression::do_export(Export* exp) const
2134 {
2135 Float_expression::export_float(exp, this->val_);
2136 // A trailing space lets us reliably identify the end of the number.
2137 exp->write_c_string(" ");
2138 }
2139
2140 // Dump a floating point number to the dump file.
2141
2142 void
2143 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2144 {
2145 Float_expression::export_float(ast_dump_context, this->val_);
2146 }
2147
2148 // Make a float expression.
2149
2150 Expression*
2151 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2152 {
2153 return new Float_expression(val, type, location);
2154 }
2155
2156 // Complex numbers.
2157
2158 class Complex_expression : public Expression
2159 {
2160 public:
2161 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2162 Location location)
2163 : Expression(EXPRESSION_COMPLEX, location),
2164 type_(type)
2165 {
2166 mpfr_init_set(this->real_, *real, GMP_RNDN);
2167 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2168 }
2169
2170 // Write REAL/IMAG to string dump.
2171 static void
2172 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2173
2174 // Write REAL/IMAG to dump context.
2175 static void
2176 dump_complex(Ast_dump_context* ast_dump_context,
2177 const mpfr_t real, const mpfr_t val);
2178
2179 protected:
2180 bool
2181 do_is_constant() const
2182 { return true; }
2183
2184 bool
2185 do_numeric_constant_value(Numeric_constant* nc) const
2186 {
2187 nc->set_complex(this->type_, this->real_, this->imag_);
2188 return true;
2189 }
2190
2191 Type*
2192 do_type();
2193
2194 void
2195 do_determine_type(const Type_context*);
2196
2197 void
2198 do_check_types(Gogo*);
2199
2200 Expression*
2201 do_copy()
2202 {
2203 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2204 this->location());
2205 }
2206
2207 tree
2208 do_get_tree(Translate_context*);
2209
2210 void
2211 do_export(Export*) const;
2212
2213 void
2214 do_dump_expression(Ast_dump_context*) const;
2215
2216 private:
2217 // The real part.
2218 mpfr_t real_;
2219 // The imaginary part;
2220 mpfr_t imag_;
2221 // The type if known.
2222 Type* type_;
2223 };
2224
2225 // Return the current type. If we haven't set the type yet, we return
2226 // an abstract complex type.
2227
2228 Type*
2229 Complex_expression::do_type()
2230 {
2231 if (this->type_ == NULL)
2232 this->type_ = Type::make_abstract_complex_type();
2233 return this->type_;
2234 }
2235
2236 // Set the type of the complex value. Here we may switch from an
2237 // abstract type to a real type.
2238
2239 void
2240 Complex_expression::do_determine_type(const Type_context* context)
2241 {
2242 if (this->type_ != NULL && !this->type_->is_abstract())
2243 ;
2244 else if (context->type != NULL
2245 && context->type->complex_type() != NULL)
2246 this->type_ = context->type;
2247 else if (!context->may_be_abstract)
2248 this->type_ = Type::lookup_complex_type("complex128");
2249 }
2250
2251 // Check the type of a complex value.
2252
2253 void
2254 Complex_expression::do_check_types(Gogo*)
2255 {
2256 Type* type = this->type_;
2257 if (type == NULL)
2258 return;
2259 Numeric_constant nc;
2260 nc.set_complex(NULL, this->real_, this->imag_);
2261 if (!nc.set_type(this->type_, true, this->location()))
2262 this->set_is_error();
2263 }
2264
2265 // Get a tree for a complex constant.
2266
2267 tree
2268 Complex_expression::do_get_tree(Translate_context* context)
2269 {
2270 Gogo* gogo = context->gogo();
2271 tree type;
2272 if (this->type_ != NULL && !this->type_->is_abstract())
2273 type = type_to_tree(this->type_->get_backend(gogo));
2274 else
2275 {
2276 // If we still have an abstract type here, this this is being
2277 // used in a constant expression which didn't get reduced. We
2278 // just use complex128 and hope for the best.
2279 Type* ct = Type::lookup_complex_type("complex128");
2280 type = type_to_tree(ct->get_backend(gogo));
2281 }
2282 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2283 }
2284
2285 // Write REAL/IMAG to export data.
2286
2287 void
2288 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2289 const mpfr_t imag)
2290 {
2291 if (!mpfr_zero_p(real))
2292 {
2293 Float_expression::export_float(exp, real);
2294 if (mpfr_sgn(imag) > 0)
2295 exp->write_c_string("+");
2296 }
2297 Float_expression::export_float(exp, imag);
2298 exp->write_c_string("i");
2299 }
2300
2301 // Export a complex number in a constant expression.
2302
2303 void
2304 Complex_expression::do_export(Export* exp) const
2305 {
2306 Complex_expression::export_complex(exp, this->real_, this->imag_);
2307 // A trailing space lets us reliably identify the end of the number.
2308 exp->write_c_string(" ");
2309 }
2310
2311 // Dump a complex expression to the dump file.
2312
2313 void
2314 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2315 {
2316 Complex_expression::export_complex(ast_dump_context,
2317 this->real_,
2318 this->imag_);
2319 }
2320
2321 // Make a complex expression.
2322
2323 Expression*
2324 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2325 Location location)
2326 {
2327 return new Complex_expression(real, imag, type, location);
2328 }
2329
2330 // Find a named object in an expression.
2331
2332 class Find_named_object : public Traverse
2333 {
2334 public:
2335 Find_named_object(Named_object* no)
2336 : Traverse(traverse_expressions),
2337 no_(no), found_(false)
2338 { }
2339
2340 // Whether we found the object.
2341 bool
2342 found() const
2343 { return this->found_; }
2344
2345 protected:
2346 int
2347 expression(Expression**);
2348
2349 private:
2350 // The object we are looking for.
2351 Named_object* no_;
2352 // Whether we found it.
2353 bool found_;
2354 };
2355
2356 // A reference to a const in an expression.
2357
2358 class Const_expression : public Expression
2359 {
2360 public:
2361 Const_expression(Named_object* constant, Location location)
2362 : Expression(EXPRESSION_CONST_REFERENCE, location),
2363 constant_(constant), type_(NULL), seen_(false)
2364 { }
2365
2366 Named_object*
2367 named_object()
2368 { return this->constant_; }
2369
2370 // Check that the initializer does not refer to the constant itself.
2371 void
2372 check_for_init_loop();
2373
2374 protected:
2375 int
2376 do_traverse(Traverse*);
2377
2378 Expression*
2379 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2380
2381 bool
2382 do_is_constant() const
2383 { return true; }
2384
2385 bool
2386 do_numeric_constant_value(Numeric_constant* nc) const;
2387
2388 bool
2389 do_string_constant_value(std::string* val) const;
2390
2391 Type*
2392 do_type();
2393
2394 // The type of a const is set by the declaration, not the use.
2395 void
2396 do_determine_type(const Type_context*);
2397
2398 void
2399 do_check_types(Gogo*);
2400
2401 Expression*
2402 do_copy()
2403 { return this; }
2404
2405 tree
2406 do_get_tree(Translate_context* context);
2407
2408 // When exporting a reference to a const as part of a const
2409 // expression, we export the value. We ignore the fact that it has
2410 // a name.
2411 void
2412 do_export(Export* exp) const
2413 { this->constant_->const_value()->expr()->export_expression(exp); }
2414
2415 void
2416 do_dump_expression(Ast_dump_context*) const;
2417
2418 private:
2419 // The constant.
2420 Named_object* constant_;
2421 // The type of this reference. This is used if the constant has an
2422 // abstract type.
2423 Type* type_;
2424 // Used to prevent infinite recursion when a constant incorrectly
2425 // refers to itself.
2426 mutable bool seen_;
2427 };
2428
2429 // Traversal.
2430
2431 int
2432 Const_expression::do_traverse(Traverse* traverse)
2433 {
2434 if (this->type_ != NULL)
2435 return Type::traverse(this->type_, traverse);
2436 return TRAVERSE_CONTINUE;
2437 }
2438
2439 // Lower a constant expression. This is where we convert the
2440 // predeclared constant iota into an integer value.
2441
2442 Expression*
2443 Const_expression::do_lower(Gogo* gogo, Named_object*,
2444 Statement_inserter*, int iota_value)
2445 {
2446 if (this->constant_->const_value()->expr()->classification()
2447 == EXPRESSION_IOTA)
2448 {
2449 if (iota_value == -1)
2450 {
2451 error_at(this->location(),
2452 "iota is only defined in const declarations");
2453 iota_value = 0;
2454 }
2455 mpz_t val;
2456 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2457 Expression* ret = Expression::make_integer(&val, NULL,
2458 this->location());
2459 mpz_clear(val);
2460 return ret;
2461 }
2462
2463 // Make sure that the constant itself has been lowered.
2464 gogo->lower_constant(this->constant_);
2465
2466 return this;
2467 }
2468
2469 // Return a numeric constant value.
2470
2471 bool
2472 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2473 {
2474 if (this->seen_)
2475 return false;
2476
2477 Expression* e = this->constant_->const_value()->expr();
2478
2479 this->seen_ = true;
2480
2481 bool r = e->numeric_constant_value(nc);
2482
2483 this->seen_ = false;
2484
2485 Type* ctype;
2486 if (this->type_ != NULL)
2487 ctype = this->type_;
2488 else
2489 ctype = this->constant_->const_value()->type();
2490 if (r && ctype != NULL)
2491 {
2492 if (!nc->set_type(ctype, false, this->location()))
2493 return false;
2494 }
2495
2496 return r;
2497 }
2498
2499 bool
2500 Const_expression::do_string_constant_value(std::string* val) const
2501 {
2502 if (this->seen_)
2503 return false;
2504
2505 Expression* e = this->constant_->const_value()->expr();
2506
2507 this->seen_ = true;
2508 bool ok = e->string_constant_value(val);
2509 this->seen_ = false;
2510
2511 return ok;
2512 }
2513
2514 // Return the type of the const reference.
2515
2516 Type*
2517 Const_expression::do_type()
2518 {
2519 if (this->type_ != NULL)
2520 return this->type_;
2521
2522 Named_constant* nc = this->constant_->const_value();
2523
2524 if (this->seen_ || nc->lowering())
2525 {
2526 this->report_error(_("constant refers to itself"));
2527 this->type_ = Type::make_error_type();
2528 return this->type_;
2529 }
2530
2531 this->seen_ = true;
2532
2533 Type* ret = nc->type();
2534
2535 if (ret != NULL)
2536 {
2537 this->seen_ = false;
2538 return ret;
2539 }
2540
2541 // During parsing, a named constant may have a NULL type, but we
2542 // must not return a NULL type here.
2543 ret = nc->expr()->type();
2544
2545 this->seen_ = false;
2546
2547 return ret;
2548 }
2549
2550 // Set the type of the const reference.
2551
2552 void
2553 Const_expression::do_determine_type(const Type_context* context)
2554 {
2555 Type* ctype = this->constant_->const_value()->type();
2556 Type* cetype = (ctype != NULL
2557 ? ctype
2558 : this->constant_->const_value()->expr()->type());
2559 if (ctype != NULL && !ctype->is_abstract())
2560 ;
2561 else if (context->type != NULL
2562 && context->type->is_numeric_type()
2563 && cetype->is_numeric_type())
2564 this->type_ = context->type;
2565 else if (context->type != NULL
2566 && context->type->is_string_type()
2567 && cetype->is_string_type())
2568 this->type_ = context->type;
2569 else if (context->type != NULL
2570 && context->type->is_boolean_type()
2571 && cetype->is_boolean_type())
2572 this->type_ = context->type;
2573 else if (!context->may_be_abstract)
2574 {
2575 if (cetype->is_abstract())
2576 cetype = cetype->make_non_abstract_type();
2577 this->type_ = cetype;
2578 }
2579 }
2580
2581 // Check for a loop in which the initializer of a constant refers to
2582 // the constant itself.
2583
2584 void
2585 Const_expression::check_for_init_loop()
2586 {
2587 if (this->type_ != NULL && this->type_->is_error())
2588 return;
2589
2590 if (this->seen_)
2591 {
2592 this->report_error(_("constant refers to itself"));
2593 this->type_ = Type::make_error_type();
2594 return;
2595 }
2596
2597 Expression* init = this->constant_->const_value()->expr();
2598 Find_named_object find_named_object(this->constant_);
2599
2600 this->seen_ = true;
2601 Expression::traverse(&init, &find_named_object);
2602 this->seen_ = false;
2603
2604 if (find_named_object.found())
2605 {
2606 if (this->type_ == NULL || !this->type_->is_error())
2607 {
2608 this->report_error(_("constant refers to itself"));
2609 this->type_ = Type::make_error_type();
2610 }
2611 return;
2612 }
2613 }
2614
2615 // Check types of a const reference.
2616
2617 void
2618 Const_expression::do_check_types(Gogo*)
2619 {
2620 if (this->type_ != NULL && this->type_->is_error())
2621 return;
2622
2623 this->check_for_init_loop();
2624
2625 // Check that numeric constant fits in type.
2626 if (this->type_ != NULL && this->type_->is_numeric_type())
2627 {
2628 Numeric_constant nc;
2629 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2630 {
2631 if (!nc.set_type(this->type_, true, this->location()))
2632 this->set_is_error();
2633 }
2634 }
2635 }
2636
2637 // Return a tree for the const reference.
2638
2639 tree
2640 Const_expression::do_get_tree(Translate_context* context)
2641 {
2642 Gogo* gogo = context->gogo();
2643 tree type_tree;
2644 if (this->type_ == NULL)
2645 type_tree = NULL_TREE;
2646 else
2647 {
2648 type_tree = type_to_tree(this->type_->get_backend(gogo));
2649 if (type_tree == error_mark_node)
2650 return error_mark_node;
2651 }
2652
2653 // If the type has been set for this expression, but the underlying
2654 // object is an abstract int or float, we try to get the abstract
2655 // value. Otherwise we may lose something in the conversion.
2656 if (this->type_ != NULL
2657 && this->type_->is_numeric_type()
2658 && (this->constant_->const_value()->type() == NULL
2659 || this->constant_->const_value()->type()->is_abstract()))
2660 {
2661 Expression* expr = this->constant_->const_value()->expr();
2662 Numeric_constant nc;
2663 if (expr->numeric_constant_value(&nc)
2664 && nc.set_type(this->type_, false, this->location()))
2665 {
2666 Expression* e = nc.expression(this->location());
2667 return e->get_tree(context);
2668 }
2669 }
2670
2671 tree const_tree = this->constant_->get_tree(gogo, context->function());
2672 if (this->type_ == NULL
2673 || const_tree == error_mark_node
2674 || TREE_TYPE(const_tree) == error_mark_node)
2675 return const_tree;
2676
2677 tree ret;
2678 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2679 ret = fold_convert(type_tree, const_tree);
2680 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2681 ret = fold(convert_to_integer(type_tree, const_tree));
2682 else if (TREE_CODE(type_tree) == REAL_TYPE)
2683 ret = fold(convert_to_real(type_tree, const_tree));
2684 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2685 ret = fold(convert_to_complex(type_tree, const_tree));
2686 else
2687 go_unreachable();
2688 return ret;
2689 }
2690
2691 // Dump ast representation for constant expression.
2692
2693 void
2694 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2695 {
2696 ast_dump_context->ostream() << this->constant_->name();
2697 }
2698
2699 // Make a reference to a constant in an expression.
2700
2701 Expression*
2702 Expression::make_const_reference(Named_object* constant,
2703 Location location)
2704 {
2705 return new Const_expression(constant, location);
2706 }
2707
2708 // Find a named object in an expression.
2709
2710 int
2711 Find_named_object::expression(Expression** pexpr)
2712 {
2713 switch ((*pexpr)->classification())
2714 {
2715 case Expression::EXPRESSION_CONST_REFERENCE:
2716 {
2717 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2718 if (ce->named_object() == this->no_)
2719 break;
2720
2721 // We need to check a constant initializer explicitly, as
2722 // loops here will not be caught by the loop checking for
2723 // variable initializers.
2724 ce->check_for_init_loop();
2725
2726 return TRAVERSE_CONTINUE;
2727 }
2728
2729 case Expression::EXPRESSION_VAR_REFERENCE:
2730 if ((*pexpr)->var_expression()->named_object() == this->no_)
2731 break;
2732 return TRAVERSE_CONTINUE;
2733 case Expression::EXPRESSION_FUNC_REFERENCE:
2734 if ((*pexpr)->func_expression()->named_object() == this->no_)
2735 break;
2736 return TRAVERSE_CONTINUE;
2737 default:
2738 return TRAVERSE_CONTINUE;
2739 }
2740 this->found_ = true;
2741 return TRAVERSE_EXIT;
2742 }
2743
2744 // The nil value.
2745
2746 class Nil_expression : public Expression
2747 {
2748 public:
2749 Nil_expression(Location location)
2750 : Expression(EXPRESSION_NIL, location)
2751 { }
2752
2753 static Expression*
2754 do_import(Import*);
2755
2756 protected:
2757 bool
2758 do_is_constant() const
2759 { return true; }
2760
2761 Type*
2762 do_type()
2763 { return Type::make_nil_type(); }
2764
2765 void
2766 do_determine_type(const Type_context*)
2767 { }
2768
2769 Expression*
2770 do_copy()
2771 { return this; }
2772
2773 tree
2774 do_get_tree(Translate_context*)
2775 { return null_pointer_node; }
2776
2777 void
2778 do_export(Export* exp) const
2779 { exp->write_c_string("nil"); }
2780
2781 void
2782 do_dump_expression(Ast_dump_context* ast_dump_context) const
2783 { ast_dump_context->ostream() << "nil"; }
2784 };
2785
2786 // Import a nil expression.
2787
2788 Expression*
2789 Nil_expression::do_import(Import* imp)
2790 {
2791 imp->require_c_string("nil");
2792 return Expression::make_nil(imp->location());
2793 }
2794
2795 // Make a nil expression.
2796
2797 Expression*
2798 Expression::make_nil(Location location)
2799 {
2800 return new Nil_expression(location);
2801 }
2802
2803 // The value of the predeclared constant iota. This is little more
2804 // than a marker. This will be lowered to an integer in
2805 // Const_expression::do_lower, which is where we know the value that
2806 // it should have.
2807
2808 class Iota_expression : public Parser_expression
2809 {
2810 public:
2811 Iota_expression(Location location)
2812 : Parser_expression(EXPRESSION_IOTA, location)
2813 { }
2814
2815 protected:
2816 Expression*
2817 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2818 { go_unreachable(); }
2819
2820 // There should only ever be one of these.
2821 Expression*
2822 do_copy()
2823 { go_unreachable(); }
2824
2825 void
2826 do_dump_expression(Ast_dump_context* ast_dump_context) const
2827 { ast_dump_context->ostream() << "iota"; }
2828 };
2829
2830 // Make an iota expression. This is only called for one case: the
2831 // value of the predeclared constant iota.
2832
2833 Expression*
2834 Expression::make_iota()
2835 {
2836 static Iota_expression iota_expression(Linemap::unknown_location());
2837 return &iota_expression;
2838 }
2839
2840 // A type conversion expression.
2841
2842 class Type_conversion_expression : public Expression
2843 {
2844 public:
2845 Type_conversion_expression(Type* type, Expression* expr,
2846 Location location)
2847 : Expression(EXPRESSION_CONVERSION, location),
2848 type_(type), expr_(expr), may_convert_function_types_(false)
2849 { }
2850
2851 // Return the type to which we are converting.
2852 Type*
2853 type() const
2854 { return this->type_; }
2855
2856 // Return the expression which we are converting.
2857 Expression*
2858 expr() const
2859 { return this->expr_; }
2860
2861 // Permit converting from one function type to another. This is
2862 // used internally for method expressions.
2863 void
2864 set_may_convert_function_types()
2865 {
2866 this->may_convert_function_types_ = true;
2867 }
2868
2869 // Import a type conversion expression.
2870 static Expression*
2871 do_import(Import*);
2872
2873 protected:
2874 int
2875 do_traverse(Traverse* traverse);
2876
2877 Expression*
2878 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2879
2880 bool
2881 do_is_constant() const
2882 { return this->expr_->is_constant(); }
2883
2884 bool
2885 do_numeric_constant_value(Numeric_constant*) const;
2886
2887 bool
2888 do_string_constant_value(std::string*) const;
2889
2890 Type*
2891 do_type()
2892 { return this->type_; }
2893
2894 void
2895 do_determine_type(const Type_context*)
2896 {
2897 Type_context subcontext(this->type_, false);
2898 this->expr_->determine_type(&subcontext);
2899 }
2900
2901 void
2902 do_check_types(Gogo*);
2903
2904 Expression*
2905 do_copy()
2906 {
2907 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2908 this->location());
2909 }
2910
2911 tree
2912 do_get_tree(Translate_context* context);
2913
2914 void
2915 do_export(Export*) const;
2916
2917 void
2918 do_dump_expression(Ast_dump_context*) const;
2919
2920 private:
2921 // The type to convert to.
2922 Type* type_;
2923 // The expression to convert.
2924 Expression* expr_;
2925 // True if this is permitted to convert function types. This is
2926 // used internally for method expressions.
2927 bool may_convert_function_types_;
2928 };
2929
2930 // Traversal.
2931
2932 int
2933 Type_conversion_expression::do_traverse(Traverse* traverse)
2934 {
2935 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2936 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2937 return TRAVERSE_EXIT;
2938 return TRAVERSE_CONTINUE;
2939 }
2940
2941 // Convert to a constant at lowering time.
2942
2943 Expression*
2944 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2945 Statement_inserter*, int)
2946 {
2947 Type* type = this->type_;
2948 Expression* val = this->expr_;
2949 Location location = this->location();
2950
2951 if (type->is_numeric_type())
2952 {
2953 Numeric_constant nc;
2954 if (val->numeric_constant_value(&nc))
2955 {
2956 if (!nc.set_type(type, true, location))
2957 return Expression::make_error(location);
2958 return nc.expression(location);
2959 }
2960 }
2961
2962 if (type->is_slice_type())
2963 {
2964 Type* element_type = type->array_type()->element_type()->forwarded();
2965 bool is_byte = (element_type->integer_type() != NULL
2966 && element_type->integer_type()->is_byte());
2967 bool is_rune = (element_type->integer_type() != NULL
2968 && element_type->integer_type()->is_rune());
2969 if (is_byte || is_rune)
2970 {
2971 std::string s;
2972 if (val->string_constant_value(&s))
2973 {
2974 Expression_list* vals = new Expression_list();
2975 if (is_byte)
2976 {
2977 for (std::string::const_iterator p = s.begin();
2978 p != s.end();
2979 p++)
2980 {
2981 mpz_t val;
2982 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2983 Expression* v = Expression::make_integer(&val,
2984 element_type,
2985 location);
2986 vals->push_back(v);
2987 mpz_clear(val);
2988 }
2989 }
2990 else
2991 {
2992 const char *p = s.data();
2993 const char *pend = s.data() + s.length();
2994 while (p < pend)
2995 {
2996 unsigned int c;
2997 int adv = Lex::fetch_char(p, &c);
2998 if (adv == 0)
2999 {
3000 warning_at(this->location(), 0,
3001 "invalid UTF-8 encoding");
3002 adv = 1;
3003 }
3004 p += adv;
3005 mpz_t val;
3006 mpz_init_set_ui(val, c);
3007 Expression* v = Expression::make_integer(&val,
3008 element_type,
3009 location);
3010 vals->push_back(v);
3011 mpz_clear(val);
3012 }
3013 }
3014
3015 return Expression::make_slice_composite_literal(type, vals,
3016 location);
3017 }
3018 }
3019 }
3020
3021 return this;
3022 }
3023
3024 // Return the constant numeric value if there is one.
3025
3026 bool
3027 Type_conversion_expression::do_numeric_constant_value(
3028 Numeric_constant* nc) const
3029 {
3030 if (!this->type_->is_numeric_type())
3031 return false;
3032 if (!this->expr_->numeric_constant_value(nc))
3033 return false;
3034 return nc->set_type(this->type_, false, this->location());
3035 }
3036
3037 // Return the constant string value if there is one.
3038
3039 bool
3040 Type_conversion_expression::do_string_constant_value(std::string* val) const
3041 {
3042 if (this->type_->is_string_type()
3043 && this->expr_->type()->integer_type() != NULL)
3044 {
3045 Numeric_constant nc;
3046 if (this->expr_->numeric_constant_value(&nc))
3047 {
3048 unsigned long ival;
3049 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3050 {
3051 val->clear();
3052 Lex::append_char(ival, true, val, this->location());
3053 return true;
3054 }
3055 }
3056 }
3057
3058 // FIXME: Could handle conversion from const []int here.
3059
3060 return false;
3061 }
3062
3063 // Check that types are convertible.
3064
3065 void
3066 Type_conversion_expression::do_check_types(Gogo*)
3067 {
3068 Type* type = this->type_;
3069 Type* expr_type = this->expr_->type();
3070 std::string reason;
3071
3072 if (type->is_error() || expr_type->is_error())
3073 {
3074 this->set_is_error();
3075 return;
3076 }
3077
3078 if (this->may_convert_function_types_
3079 && type->function_type() != NULL
3080 && expr_type->function_type() != NULL)
3081 return;
3082
3083 if (Type::are_convertible(type, expr_type, &reason))
3084 return;
3085
3086 error_at(this->location(), "%s", reason.c_str());
3087 this->set_is_error();
3088 }
3089
3090 // Get a tree for a type conversion.
3091
3092 tree
3093 Type_conversion_expression::do_get_tree(Translate_context* context)
3094 {
3095 Gogo* gogo = context->gogo();
3096 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3097 tree expr_tree = this->expr_->get_tree(context);
3098
3099 if (type_tree == error_mark_node
3100 || expr_tree == error_mark_node
3101 || TREE_TYPE(expr_tree) == error_mark_node)
3102 return error_mark_node;
3103
3104 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3105 return fold_convert(type_tree, expr_tree);
3106
3107 Type* type = this->type_;
3108 Type* expr_type = this->expr_->type();
3109 tree ret;
3110 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3111 ret = Expression::convert_for_assignment(context, type, expr_type,
3112 expr_tree, this->location());
3113 else if (type->integer_type() != NULL)
3114 {
3115 if (expr_type->integer_type() != NULL
3116 || expr_type->float_type() != NULL
3117 || expr_type->is_unsafe_pointer_type())
3118 ret = fold(convert_to_integer(type_tree, expr_tree));
3119 else
3120 go_unreachable();
3121 }
3122 else if (type->float_type() != NULL)
3123 {
3124 if (expr_type->integer_type() != NULL
3125 || expr_type->float_type() != NULL)
3126 ret = fold(convert_to_real(type_tree, expr_tree));
3127 else
3128 go_unreachable();
3129 }
3130 else if (type->complex_type() != NULL)
3131 {
3132 if (expr_type->complex_type() != NULL)
3133 ret = fold(convert_to_complex(type_tree, expr_tree));
3134 else
3135 go_unreachable();
3136 }
3137 else if (type->is_string_type()
3138 && expr_type->integer_type() != NULL)
3139 {
3140 expr_tree = fold_convert(integer_type_node, expr_tree);
3141 if (host_integerp(expr_tree, 0))
3142 {
3143 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3144 std::string s;
3145 Lex::append_char(intval, true, &s, this->location());
3146 Expression* se = Expression::make_string(s, this->location());
3147 return se->get_tree(context);
3148 }
3149
3150 static tree int_to_string_fndecl;
3151 ret = Gogo::call_builtin(&int_to_string_fndecl,
3152 this->location(),
3153 "__go_int_to_string",
3154 1,
3155 type_tree,
3156 integer_type_node,
3157 fold_convert(integer_type_node, expr_tree));
3158 }
3159 else if (type->is_string_type() && expr_type->is_slice_type())
3160 {
3161 if (!DECL_P(expr_tree))
3162 expr_tree = save_expr(expr_tree);
3163 Array_type* a = expr_type->array_type();
3164 Type* e = a->element_type()->forwarded();
3165 go_assert(e->integer_type() != NULL);
3166 tree valptr = fold_convert(const_ptr_type_node,
3167 a->value_pointer_tree(gogo, expr_tree));
3168 tree len = a->length_tree(gogo, expr_tree);
3169 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3170 len);
3171 if (e->integer_type()->is_byte())
3172 {
3173 static tree byte_array_to_string_fndecl;
3174 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3175 this->location(),
3176 "__go_byte_array_to_string",
3177 2,
3178 type_tree,
3179 const_ptr_type_node,
3180 valptr,
3181 integer_type_node,
3182 len);
3183 }
3184 else
3185 {
3186 go_assert(e->integer_type()->is_rune());
3187 static tree int_array_to_string_fndecl;
3188 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3189 this->location(),
3190 "__go_int_array_to_string",
3191 2,
3192 type_tree,
3193 const_ptr_type_node,
3194 valptr,
3195 integer_type_node,
3196 len);
3197 }
3198 }
3199 else if (type->is_slice_type() && expr_type->is_string_type())
3200 {
3201 Type* e = type->array_type()->element_type()->forwarded();
3202 go_assert(e->integer_type() != NULL);
3203 if (e->integer_type()->is_byte())
3204 {
3205 tree string_to_byte_array_fndecl = NULL_TREE;
3206 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3207 this->location(),
3208 "__go_string_to_byte_array",
3209 1,
3210 type_tree,
3211 TREE_TYPE(expr_tree),
3212 expr_tree);
3213 }
3214 else
3215 {
3216 go_assert(e->integer_type()->is_rune());
3217 tree string_to_int_array_fndecl = NULL_TREE;
3218 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3219 this->location(),
3220 "__go_string_to_int_array",
3221 1,
3222 type_tree,
3223 TREE_TYPE(expr_tree),
3224 expr_tree);
3225 }
3226 }
3227 else if ((type->is_unsafe_pointer_type()
3228 && expr_type->points_to() != NULL)
3229 || (expr_type->is_unsafe_pointer_type()
3230 && type->points_to() != NULL))
3231 ret = fold_convert(type_tree, expr_tree);
3232 else if (type->is_unsafe_pointer_type()
3233 && expr_type->integer_type() != NULL)
3234 ret = convert_to_pointer(type_tree, expr_tree);
3235 else if (this->may_convert_function_types_
3236 && type->function_type() != NULL
3237 && expr_type->function_type() != NULL)
3238 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3239 expr_tree);
3240 else
3241 ret = Expression::convert_for_assignment(context, type, expr_type,
3242 expr_tree, this->location());
3243
3244 return ret;
3245 }
3246
3247 // Output a type conversion in a constant expression.
3248
3249 void
3250 Type_conversion_expression::do_export(Export* exp) const
3251 {
3252 exp->write_c_string("convert(");
3253 exp->write_type(this->type_);
3254 exp->write_c_string(", ");
3255 this->expr_->export_expression(exp);
3256 exp->write_c_string(")");
3257 }
3258
3259 // Import a type conversion or a struct construction.
3260
3261 Expression*
3262 Type_conversion_expression::do_import(Import* imp)
3263 {
3264 imp->require_c_string("convert(");
3265 Type* type = imp->read_type();
3266 imp->require_c_string(", ");
3267 Expression* val = Expression::import_expression(imp);
3268 imp->require_c_string(")");
3269 return Expression::make_cast(type, val, imp->location());
3270 }
3271
3272 // Dump ast representation for a type conversion expression.
3273
3274 void
3275 Type_conversion_expression::do_dump_expression(
3276 Ast_dump_context* ast_dump_context) const
3277 {
3278 ast_dump_context->dump_type(this->type_);
3279 ast_dump_context->ostream() << "(";
3280 ast_dump_context->dump_expression(this->expr_);
3281 ast_dump_context->ostream() << ") ";
3282 }
3283
3284 // Make a type cast expression.
3285
3286 Expression*
3287 Expression::make_cast(Type* type, Expression* val, Location location)
3288 {
3289 if (type->is_error_type() || val->is_error_expression())
3290 return Expression::make_error(location);
3291 return new Type_conversion_expression(type, val, location);
3292 }
3293
3294 // An unsafe type conversion, used to pass values to builtin functions.
3295
3296 class Unsafe_type_conversion_expression : public Expression
3297 {
3298 public:
3299 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3300 Location location)
3301 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3302 type_(type), expr_(expr)
3303 { }
3304
3305 protected:
3306 int
3307 do_traverse(Traverse* traverse);
3308
3309 Type*
3310 do_type()
3311 { return this->type_; }
3312
3313 void
3314 do_determine_type(const Type_context*)
3315 { this->expr_->determine_type_no_context(); }
3316
3317 Expression*
3318 do_copy()
3319 {
3320 return new Unsafe_type_conversion_expression(this->type_,
3321 this->expr_->copy(),
3322 this->location());
3323 }
3324
3325 tree
3326 do_get_tree(Translate_context*);
3327
3328 void
3329 do_dump_expression(Ast_dump_context*) const;
3330
3331 private:
3332 // The type to convert to.
3333 Type* type_;
3334 // The expression to convert.
3335 Expression* expr_;
3336 };
3337
3338 // Traversal.
3339
3340 int
3341 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3342 {
3343 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3344 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3345 return TRAVERSE_EXIT;
3346 return TRAVERSE_CONTINUE;
3347 }
3348
3349 // Convert to backend representation.
3350
3351 tree
3352 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3353 {
3354 // We are only called for a limited number of cases.
3355
3356 Type* t = this->type_;
3357 Type* et = this->expr_->type();
3358
3359 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3360 tree expr_tree = this->expr_->get_tree(context);
3361 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3362 return error_mark_node;
3363
3364 Location loc = this->location();
3365
3366 bool use_view_convert = false;
3367 if (t->is_slice_type())
3368 {
3369 go_assert(et->is_slice_type());
3370 use_view_convert = true;
3371 }
3372 else if (t->map_type() != NULL)
3373 go_assert(et->map_type() != NULL);
3374 else if (t->channel_type() != NULL)
3375 go_assert(et->channel_type() != NULL);
3376 else if (t->points_to() != NULL)
3377 go_assert(et->points_to() != NULL || et->is_nil_type());
3378 else if (et->is_unsafe_pointer_type())
3379 go_assert(t->points_to() != NULL);
3380 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3381 {
3382 go_assert(et->interface_type() != NULL
3383 && !et->interface_type()->is_empty());
3384 use_view_convert = true;
3385 }
3386 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3387 {
3388 go_assert(et->interface_type() != NULL
3389 && et->interface_type()->is_empty());
3390 use_view_convert = true;
3391 }
3392 else if (t->integer_type() != NULL)
3393 {
3394 go_assert(et->is_boolean_type()
3395 || et->integer_type() != NULL
3396 || et->function_type() != NULL
3397 || et->points_to() != NULL
3398 || et->map_type() != NULL
3399 || et->channel_type() != NULL);
3400 return convert_to_integer(type_tree, expr_tree);
3401 }
3402 else
3403 go_unreachable();
3404
3405 if (use_view_convert)
3406 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3407 expr_tree);
3408 else
3409 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3410 }
3411
3412 // Dump ast representation for an unsafe type conversion expression.
3413
3414 void
3415 Unsafe_type_conversion_expression::do_dump_expression(
3416 Ast_dump_context* ast_dump_context) const
3417 {
3418 ast_dump_context->dump_type(this->type_);
3419 ast_dump_context->ostream() << "(";
3420 ast_dump_context->dump_expression(this->expr_);
3421 ast_dump_context->ostream() << ") ";
3422 }
3423
3424 // Make an unsafe type conversion expression.
3425
3426 Expression*
3427 Expression::make_unsafe_cast(Type* type, Expression* expr,
3428 Location location)
3429 {
3430 return new Unsafe_type_conversion_expression(type, expr, location);
3431 }
3432
3433 // Unary expressions.
3434
3435 class Unary_expression : public Expression
3436 {
3437 public:
3438 Unary_expression(Operator op, Expression* expr, Location location)
3439 : Expression(EXPRESSION_UNARY, location),
3440 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3441 { }
3442
3443 // Return the operator.
3444 Operator
3445 op() const
3446 { return this->op_; }
3447
3448 // Return the operand.
3449 Expression*
3450 operand() const
3451 { return this->expr_; }
3452
3453 // Record that an address expression does not escape.
3454 void
3455 set_does_not_escape()
3456 {
3457 go_assert(this->op_ == OPERATOR_AND);
3458 this->escapes_ = false;
3459 }
3460
3461 // Record that this is an address expression which should create a
3462 // temporary variable if necessary. This is used for method calls.
3463 void
3464 set_create_temp()
3465 {
3466 go_assert(this->op_ == OPERATOR_AND);
3467 this->create_temp_ = true;
3468 }
3469
3470 // Apply unary opcode OP to UNC, setting NC. Return true if this
3471 // could be done, false if not. Issue errors for overflow.
3472 static bool
3473 eval_constant(Operator op, const Numeric_constant* unc,
3474 Location, Numeric_constant* nc);
3475
3476 static Expression*
3477 do_import(Import*);
3478
3479 protected:
3480 int
3481 do_traverse(Traverse* traverse)
3482 { return Expression::traverse(&this->expr_, traverse); }
3483
3484 Expression*
3485 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3486
3487 bool
3488 do_is_constant() const;
3489
3490 bool
3491 do_numeric_constant_value(Numeric_constant*) const;
3492
3493 Type*
3494 do_type();
3495
3496 void
3497 do_determine_type(const Type_context*);
3498
3499 void
3500 do_check_types(Gogo*);
3501
3502 Expression*
3503 do_copy()
3504 {
3505 return Expression::make_unary(this->op_, this->expr_->copy(),
3506 this->location());
3507 }
3508
3509 bool
3510 do_must_eval_subexpressions_in_order(int*) const
3511 { return this->op_ == OPERATOR_MULT; }
3512
3513 bool
3514 do_is_addressable() const
3515 { return this->op_ == OPERATOR_MULT; }
3516
3517 tree
3518 do_get_tree(Translate_context*);
3519
3520 void
3521 do_export(Export*) const;
3522
3523 void
3524 do_dump_expression(Ast_dump_context*) const;
3525
3526 private:
3527 // The unary operator to apply.
3528 Operator op_;
3529 // Normally true. False if this is an address expression which does
3530 // not escape the current function.
3531 bool escapes_;
3532 // True if this is an address expression which should create a
3533 // temporary variable if necessary.
3534 bool create_temp_;
3535 // The operand.
3536 Expression* expr_;
3537 };
3538
3539 // If we are taking the address of a composite literal, and the
3540 // contents are not constant, then we want to make a heap composite
3541 // instead.
3542
3543 Expression*
3544 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3545 {
3546 Location loc = this->location();
3547 Operator op = this->op_;
3548 Expression* expr = this->expr_;
3549
3550 if (op == OPERATOR_MULT && expr->is_type_expression())
3551 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3552
3553 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3554 // moving x to the heap. FIXME: Is it worth doing a real escape
3555 // analysis here? This case is found in math/unsafe.go and is
3556 // therefore worth special casing.
3557 if (op == OPERATOR_MULT)
3558 {
3559 Expression* e = expr;
3560 while (e->classification() == EXPRESSION_CONVERSION)
3561 {
3562 Type_conversion_expression* te
3563 = static_cast<Type_conversion_expression*>(e);
3564 e = te->expr();
3565 }
3566
3567 if (e->classification() == EXPRESSION_UNARY)
3568 {
3569 Unary_expression* ue = static_cast<Unary_expression*>(e);
3570 if (ue->op_ == OPERATOR_AND)
3571 {
3572 if (e == expr)
3573 {
3574 // *&x == x.
3575 return ue->expr_;
3576 }
3577 ue->set_does_not_escape();
3578 }
3579 }
3580 }
3581
3582 // Catching an invalid indirection of unsafe.Pointer here avoid
3583 // having to deal with TYPE_VOID in other places.
3584 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3585 {
3586 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3587 return Expression::make_error(this->location());
3588 }
3589
3590 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3591 {
3592 Numeric_constant nc;
3593 if (expr->numeric_constant_value(&nc))
3594 {
3595 Numeric_constant result;
3596 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3597 return result.expression(loc);
3598 }
3599 }
3600
3601 return this;
3602 }
3603
3604 // Return whether a unary expression is a constant.
3605
3606 bool
3607 Unary_expression::do_is_constant() const
3608 {
3609 if (this->op_ == OPERATOR_MULT)
3610 {
3611 // Indirecting through a pointer is only constant if the object
3612 // to which the expression points is constant, but we currently
3613 // have no way to determine that.
3614 return false;
3615 }
3616 else if (this->op_ == OPERATOR_AND)
3617 {
3618 // Taking the address of a variable is constant if it is a
3619 // global variable, not constant otherwise. In other cases
3620 // taking the address is probably not a constant.
3621 Var_expression* ve = this->expr_->var_expression();
3622 if (ve != NULL)
3623 {
3624 Named_object* no = ve->named_object();
3625 return no->is_variable() && no->var_value()->is_global();
3626 }
3627 return false;
3628 }
3629 else
3630 return this->expr_->is_constant();
3631 }
3632
3633 // Apply unary opcode OP to UNC, setting NC. Return true if this
3634 // could be done, false if not. Issue errors for overflow.
3635
3636 bool
3637 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3638 Location location, Numeric_constant* nc)
3639 {
3640 switch (op)
3641 {
3642 case OPERATOR_PLUS:
3643 *nc = *unc;
3644 return true;
3645
3646 case OPERATOR_MINUS:
3647 if (unc->is_int() || unc->is_rune())
3648 break;
3649 else if (unc->is_float())
3650 {
3651 mpfr_t uval;
3652 unc->get_float(&uval);
3653 mpfr_t val;
3654 mpfr_init(val);
3655 mpfr_neg(val, uval, GMP_RNDN);
3656 nc->set_float(unc->type(), val);
3657 mpfr_clear(uval);
3658 mpfr_clear(val);
3659 return true;
3660 }
3661 else if (unc->is_complex())
3662 {
3663 mpfr_t ureal, uimag;
3664 unc->get_complex(&ureal, &uimag);
3665 mpfr_t real, imag;
3666 mpfr_init(real);
3667 mpfr_init(imag);
3668 mpfr_neg(real, ureal, GMP_RNDN);
3669 mpfr_neg(imag, uimag, GMP_RNDN);
3670 nc->set_complex(unc->type(), real, imag);
3671 mpfr_clear(ureal);
3672 mpfr_clear(uimag);
3673 mpfr_clear(real);
3674 mpfr_clear(imag);
3675 return true;
3676 }
3677 else
3678 go_unreachable();
3679
3680 case OPERATOR_XOR:
3681 break;
3682
3683 case OPERATOR_NOT:
3684 case OPERATOR_AND:
3685 case OPERATOR_MULT:
3686 return false;
3687
3688 default:
3689 go_unreachable();
3690 }
3691
3692 if (!unc->is_int() && !unc->is_rune())
3693 return false;
3694
3695 mpz_t uval;
3696 if (unc->is_rune())
3697 unc->get_rune(&uval);
3698 else
3699 unc->get_int(&uval);
3700 mpz_t val;
3701 mpz_init(val);
3702
3703 switch (op)
3704 {
3705 case OPERATOR_MINUS:
3706 mpz_neg(val, uval);
3707 break;
3708
3709 case OPERATOR_NOT:
3710 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3711 break;
3712
3713 case OPERATOR_XOR:
3714 {
3715 Type* utype = unc->type();
3716 if (utype->integer_type() == NULL
3717 || utype->integer_type()->is_abstract())
3718 mpz_com(val, uval);
3719 else
3720 {
3721 // The number of HOST_WIDE_INTs that it takes to represent
3722 // UVAL.
3723 size_t count = ((mpz_sizeinbase(uval, 2)
3724 + HOST_BITS_PER_WIDE_INT
3725 - 1)
3726 / HOST_BITS_PER_WIDE_INT);
3727
3728 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3729 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3730
3731 size_t obits = utype->integer_type()->bits();
3732
3733 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3734 {
3735 mpz_t adj;
3736 mpz_init_set_ui(adj, 1);
3737 mpz_mul_2exp(adj, adj, obits);
3738 mpz_add(uval, uval, adj);
3739 mpz_clear(adj);
3740 }
3741
3742 size_t ecount;
3743 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3744 go_assert(ecount <= count);
3745
3746 // Trim down to the number of words required by the type.
3747 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3748 / HOST_BITS_PER_WIDE_INT);
3749 go_assert(ocount <= count);
3750
3751 for (size_t i = 0; i < ocount; ++i)
3752 phwi[i] = ~phwi[i];
3753
3754 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3755 if (clearbits != 0)
3756 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3757 >> clearbits);
3758
3759 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3760
3761 if (!utype->integer_type()->is_unsigned()
3762 && mpz_tstbit(val, obits - 1))
3763 {
3764 mpz_t adj;
3765 mpz_init_set_ui(adj, 1);
3766 mpz_mul_2exp(adj, adj, obits);
3767 mpz_sub(val, val, adj);
3768 mpz_clear(adj);
3769 }
3770
3771 delete[] phwi;
3772 }
3773 }
3774 break;
3775
3776 default:
3777 go_unreachable();
3778 }
3779
3780 if (unc->is_rune())
3781 nc->set_rune(NULL, val);
3782 else
3783 nc->set_int(NULL, val);
3784
3785 mpz_clear(uval);
3786 mpz_clear(val);
3787
3788 return nc->set_type(unc->type(), true, location);
3789 }
3790
3791 // Return the integral constant value of a unary expression, if it has one.
3792
3793 bool
3794 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3795 {
3796 Numeric_constant unc;
3797 if (!this->expr_->numeric_constant_value(&unc))
3798 return false;
3799 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3800 nc);
3801 }
3802
3803 // Return the type of a unary expression.
3804
3805 Type*
3806 Unary_expression::do_type()
3807 {
3808 switch (this->op_)
3809 {
3810 case OPERATOR_PLUS:
3811 case OPERATOR_MINUS:
3812 case OPERATOR_NOT:
3813 case OPERATOR_XOR:
3814 return this->expr_->type();
3815
3816 case OPERATOR_AND:
3817 return Type::make_pointer_type(this->expr_->type());
3818
3819 case OPERATOR_MULT:
3820 {
3821 Type* subtype = this->expr_->type();
3822 Type* points_to = subtype->points_to();
3823 if (points_to == NULL)
3824 return Type::make_error_type();
3825 return points_to;
3826 }
3827
3828 default:
3829 go_unreachable();
3830 }
3831 }
3832
3833 // Determine abstract types for a unary expression.
3834
3835 void
3836 Unary_expression::do_determine_type(const Type_context* context)
3837 {
3838 switch (this->op_)
3839 {
3840 case OPERATOR_PLUS:
3841 case OPERATOR_MINUS:
3842 case OPERATOR_NOT:
3843 case OPERATOR_XOR:
3844 this->expr_->determine_type(context);
3845 break;
3846
3847 case OPERATOR_AND:
3848 // Taking the address of something.
3849 {
3850 Type* subtype = (context->type == NULL
3851 ? NULL
3852 : context->type->points_to());
3853 Type_context subcontext(subtype, false);
3854 this->expr_->determine_type(&subcontext);
3855 }
3856 break;
3857
3858 case OPERATOR_MULT:
3859 // Indirecting through a pointer.
3860 {
3861 Type* subtype = (context->type == NULL
3862 ? NULL
3863 : Type::make_pointer_type(context->type));
3864 Type_context subcontext(subtype, false);
3865 this->expr_->determine_type(&subcontext);
3866 }
3867 break;
3868
3869 default:
3870 go_unreachable();
3871 }
3872 }
3873
3874 // Check types for a unary expression.
3875
3876 void
3877 Unary_expression::do_check_types(Gogo*)
3878 {
3879 Type* type = this->expr_->type();
3880 if (type->is_error())
3881 {
3882 this->set_is_error();
3883 return;
3884 }
3885
3886 switch (this->op_)
3887 {
3888 case OPERATOR_PLUS:
3889 case OPERATOR_MINUS:
3890 if (type->integer_type() == NULL
3891 && type->float_type() == NULL
3892 && type->complex_type() == NULL)
3893 this->report_error(_("expected numeric type"));
3894 break;
3895
3896 case OPERATOR_NOT:
3897 if (!type->is_boolean_type())
3898 this->report_error(_("expected boolean type"));
3899 break;
3900
3901 case OPERATOR_XOR:
3902 if (type->integer_type() == NULL
3903 && !type->is_boolean_type())
3904 this->report_error(_("expected integer or boolean type"));
3905 break;
3906
3907 case OPERATOR_AND:
3908 if (!this->expr_->is_addressable())
3909 {
3910 if (!this->create_temp_)
3911 this->report_error(_("invalid operand for unary %<&%>"));
3912 }
3913 else
3914 this->expr_->address_taken(this->escapes_);
3915 break;
3916
3917 case OPERATOR_MULT:
3918 // Indirecting through a pointer.
3919 if (type->points_to() == NULL)
3920 this->report_error(_("expected pointer"));
3921 break;
3922
3923 default:
3924 go_unreachable();
3925 }
3926 }
3927
3928 // Get a tree for a unary expression.
3929
3930 tree
3931 Unary_expression::do_get_tree(Translate_context* context)
3932 {
3933 Location loc = this->location();
3934
3935 // Taking the address of a set-and-use-temporary expression requires
3936 // setting the temporary and then taking the address.
3937 if (this->op_ == OPERATOR_AND)
3938 {
3939 Set_and_use_temporary_expression* sut =
3940 this->expr_->set_and_use_temporary_expression();
3941 if (sut != NULL)
3942 {
3943 Temporary_statement* temp = sut->temporary();
3944 Bvariable* bvar = temp->get_backend_variable(context);
3945 tree var_tree = var_to_tree(bvar);
3946 Expression* val = sut->expression();
3947 tree val_tree = val->get_tree(context);
3948 if (var_tree == error_mark_node || val_tree == error_mark_node)
3949 return error_mark_node;
3950 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3951 var_tree);
3952 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3953 TREE_TYPE(addr_tree),
3954 build2_loc(sut->location().gcc_location(),
3955 MODIFY_EXPR, void_type_node,
3956 var_tree, val_tree),
3957 addr_tree);
3958 }
3959 }
3960
3961 tree expr = this->expr_->get_tree(context);
3962 if (expr == error_mark_node)
3963 return error_mark_node;
3964
3965 switch (this->op_)
3966 {
3967 case OPERATOR_PLUS:
3968 return expr;
3969
3970 case OPERATOR_MINUS:
3971 {
3972 tree type = TREE_TYPE(expr);
3973 tree compute_type = excess_precision_type(type);
3974 if (compute_type != NULL_TREE)
3975 expr = ::convert(compute_type, expr);
3976 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3977 (compute_type != NULL_TREE
3978 ? compute_type
3979 : type),
3980 expr);
3981 if (compute_type != NULL_TREE)
3982 ret = ::convert(type, ret);
3983 return ret;
3984 }
3985
3986 case OPERATOR_NOT:
3987 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
3988 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
3989 TREE_TYPE(expr), expr);
3990 else
3991 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
3992 expr, build_int_cst(TREE_TYPE(expr), 0));
3993
3994 case OPERATOR_XOR:
3995 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
3996 expr);
3997
3998 case OPERATOR_AND:
3999 if (!this->create_temp_)
4000 {
4001 // We should not see a non-constant constructor here; cases
4002 // where we would see one should have been moved onto the
4003 // heap at parse time. Taking the address of a nonconstant
4004 // constructor will not do what the programmer expects.
4005 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4006 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4007 }
4008
4009 // Build a decl for a constant constructor.
4010 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4011 {
4012 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4013 create_tmp_var_name("C"), TREE_TYPE(expr));
4014 DECL_EXTERNAL(decl) = 0;
4015 TREE_PUBLIC(decl) = 0;
4016 TREE_READONLY(decl) = 1;
4017 TREE_CONSTANT(decl) = 1;
4018 TREE_STATIC(decl) = 1;
4019 TREE_ADDRESSABLE(decl) = 1;
4020 DECL_ARTIFICIAL(decl) = 1;
4021 DECL_INITIAL(decl) = expr;
4022 rest_of_decl_compilation(decl, 1, 0);
4023 expr = decl;
4024 }
4025
4026 if (this->create_temp_
4027 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4028 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
4029 && TREE_CODE(expr) != INDIRECT_REF
4030 && TREE_CODE(expr) != COMPONENT_REF)
4031 {
4032 if (current_function_decl != NULL)
4033 {
4034 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4035 DECL_IGNORED_P(tmp) = 1;
4036 DECL_INITIAL(tmp) = expr;
4037 TREE_ADDRESSABLE(tmp) = 1;
4038 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4039 build_pointer_type(TREE_TYPE(expr)),
4040 build1_loc(loc.gcc_location(), DECL_EXPR,
4041 void_type_node, tmp),
4042 build_fold_addr_expr_loc(loc.gcc_location(),
4043 tmp));
4044 }
4045 else
4046 {
4047 tree tmp = build_decl(loc.gcc_location(), VAR_DECL,
4048 create_tmp_var_name("A"), TREE_TYPE(expr));
4049 DECL_EXTERNAL(tmp) = 0;
4050 TREE_PUBLIC(tmp) = 0;
4051 TREE_STATIC(tmp) = 1;
4052 DECL_ARTIFICIAL(tmp) = 1;
4053 TREE_ADDRESSABLE(tmp) = 1;
4054 tree make_tmp;
4055 if (!TREE_CONSTANT(expr))
4056 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
4057 void_type_node, tmp, expr);
4058 else
4059 {
4060 TREE_READONLY(tmp) = 1;
4061 TREE_CONSTANT(tmp) = 1;
4062 DECL_INITIAL(tmp) = expr;
4063 make_tmp = NULL_TREE;
4064 }
4065 rest_of_decl_compilation(tmp, 1, 0);
4066 tree addr = build_fold_addr_expr_loc(loc.gcc_location(), tmp);
4067 if (make_tmp == NULL_TREE)
4068 return addr;
4069 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4070 TREE_TYPE(addr), make_tmp, addr);
4071 }
4072 }
4073
4074 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4075
4076 case OPERATOR_MULT:
4077 {
4078 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4079
4080 // If we are dereferencing the pointer to a large struct, we
4081 // need to check for nil. We don't bother to check for small
4082 // structs because we expect the system to crash on a nil
4083 // pointer dereference.
4084 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4085 if (!VOID_TYPE_P(target_type_tree))
4086 {
4087 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4088 if (s == -1 || s >= 4096)
4089 {
4090 if (!DECL_P(expr))
4091 expr = save_expr(expr);
4092 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4093 boolean_type_node,
4094 expr,
4095 fold_convert(TREE_TYPE(expr),
4096 null_pointer_node));
4097 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4098 loc);
4099 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4100 TREE_TYPE(expr), build3(COND_EXPR,
4101 void_type_node,
4102 compare, crash,
4103 NULL_TREE),
4104 expr);
4105 }
4106 }
4107
4108 // If the type of EXPR is a recursive pointer type, then we
4109 // need to insert a cast before indirecting.
4110 if (VOID_TYPE_P(target_type_tree))
4111 {
4112 Type* pt = this->expr_->type()->points_to();
4113 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4114 expr = fold_convert_loc(loc.gcc_location(),
4115 build_pointer_type(ind), expr);
4116 }
4117
4118 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4119 }
4120
4121 default:
4122 go_unreachable();
4123 }
4124 }
4125
4126 // Export a unary expression.
4127
4128 void
4129 Unary_expression::do_export(Export* exp) const
4130 {
4131 switch (this->op_)
4132 {
4133 case OPERATOR_PLUS:
4134 exp->write_c_string("+ ");
4135 break;
4136 case OPERATOR_MINUS:
4137 exp->write_c_string("- ");
4138 break;
4139 case OPERATOR_NOT:
4140 exp->write_c_string("! ");
4141 break;
4142 case OPERATOR_XOR:
4143 exp->write_c_string("^ ");
4144 break;
4145 case OPERATOR_AND:
4146 case OPERATOR_MULT:
4147 default:
4148 go_unreachable();
4149 }
4150 this->expr_->export_expression(exp);
4151 }
4152
4153 // Import a unary expression.
4154
4155 Expression*
4156 Unary_expression::do_import(Import* imp)
4157 {
4158 Operator op;
4159 switch (imp->get_char())
4160 {
4161 case '+':
4162 op = OPERATOR_PLUS;
4163 break;
4164 case '-':
4165 op = OPERATOR_MINUS;
4166 break;
4167 case '!':
4168 op = OPERATOR_NOT;
4169 break;
4170 case '^':
4171 op = OPERATOR_XOR;
4172 break;
4173 default:
4174 go_unreachable();
4175 }
4176 imp->require_c_string(" ");
4177 Expression* expr = Expression::import_expression(imp);
4178 return Expression::make_unary(op, expr, imp->location());
4179 }
4180
4181 // Dump ast representation of an unary expression.
4182
4183 void
4184 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4185 {
4186 ast_dump_context->dump_operator(this->op_);
4187 ast_dump_context->ostream() << "(";
4188 ast_dump_context->dump_expression(this->expr_);
4189 ast_dump_context->ostream() << ") ";
4190 }
4191
4192 // Make a unary expression.
4193
4194 Expression*
4195 Expression::make_unary(Operator op, Expression* expr, Location location)
4196 {
4197 return new Unary_expression(op, expr, location);
4198 }
4199
4200 // If this is an indirection through a pointer, return the expression
4201 // being pointed through. Otherwise return this.
4202
4203 Expression*
4204 Expression::deref()
4205 {
4206 if (this->classification_ == EXPRESSION_UNARY)
4207 {
4208 Unary_expression* ue = static_cast<Unary_expression*>(this);
4209 if (ue->op() == OPERATOR_MULT)
4210 return ue->operand();
4211 }
4212 return this;
4213 }
4214
4215 // Class Binary_expression.
4216
4217 // Traversal.
4218
4219 int
4220 Binary_expression::do_traverse(Traverse* traverse)
4221 {
4222 int t = Expression::traverse(&this->left_, traverse);
4223 if (t == TRAVERSE_EXIT)
4224 return TRAVERSE_EXIT;
4225 return Expression::traverse(&this->right_, traverse);
4226 }
4227
4228 // Return the type to use for a binary operation on operands of
4229 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4230 // such may be NULL or abstract.
4231
4232 bool
4233 Binary_expression::operation_type(Operator op, Type* left_type,
4234 Type* right_type, Type** result_type)
4235 {
4236 if (left_type != right_type
4237 && !left_type->is_abstract()
4238 && !right_type->is_abstract()
4239 && left_type->base() != right_type->base()
4240 && op != OPERATOR_LSHIFT
4241 && op != OPERATOR_RSHIFT)
4242 {
4243 // May be a type error--let it be diagnosed elsewhere.
4244 return false;
4245 }
4246
4247 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4248 {
4249 if (left_type->integer_type() != NULL)
4250 *result_type = left_type;
4251 else
4252 *result_type = Type::make_abstract_integer_type();
4253 }
4254 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4255 *result_type = left_type;
4256 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4257 *result_type = right_type;
4258 else if (!left_type->is_abstract())
4259 *result_type = left_type;
4260 else if (!right_type->is_abstract())
4261 *result_type = right_type;
4262 else if (left_type->complex_type() != NULL)
4263 *result_type = left_type;
4264 else if (right_type->complex_type() != NULL)
4265 *result_type = right_type;
4266 else if (left_type->float_type() != NULL)
4267 *result_type = left_type;
4268 else if (right_type->float_type() != NULL)
4269 *result_type = right_type;
4270 else if (left_type->integer_type() != NULL
4271 && left_type->integer_type()->is_rune())
4272 *result_type = left_type;
4273 else if (right_type->integer_type() != NULL
4274 && right_type->integer_type()->is_rune())
4275 *result_type = right_type;
4276 else
4277 *result_type = left_type;
4278
4279 return true;
4280 }
4281
4282 // Convert an integer comparison code and an operator to a boolean
4283 // value.
4284
4285 bool
4286 Binary_expression::cmp_to_bool(Operator op, int cmp)
4287 {
4288 switch (op)
4289 {
4290 case OPERATOR_EQEQ:
4291 return cmp == 0;
4292 break;
4293 case OPERATOR_NOTEQ:
4294 return cmp != 0;
4295 break;
4296 case OPERATOR_LT:
4297 return cmp < 0;
4298 break;
4299 case OPERATOR_LE:
4300 return cmp <= 0;
4301 case OPERATOR_GT:
4302 return cmp > 0;
4303 case OPERATOR_GE:
4304 return cmp >= 0;
4305 default:
4306 go_unreachable();
4307 }
4308 }
4309
4310 // Compare constants according to OP.
4311
4312 bool
4313 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4314 Numeric_constant* right_nc,
4315 Location location, bool* result)
4316 {
4317 Type* left_type = left_nc->type();
4318 Type* right_type = right_nc->type();
4319
4320 Type* type;
4321 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4322 return false;
4323
4324 // When comparing an untyped operand to a typed operand, we are
4325 // effectively coercing the untyped operand to the other operand's
4326 // type, so make sure that is valid.
4327 if (!left_nc->set_type(type, true, location)
4328 || !right_nc->set_type(type, true, location))
4329 return false;
4330
4331 bool ret;
4332 int cmp;
4333 if (type->complex_type() != NULL)
4334 {
4335 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4336 return false;
4337 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4338 }
4339 else if (type->float_type() != NULL)
4340 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4341 else
4342 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4343
4344 if (ret)
4345 *result = Binary_expression::cmp_to_bool(op, cmp);
4346
4347 return ret;
4348 }
4349
4350 // Compare integer constants.
4351
4352 bool
4353 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4354 const Numeric_constant* right_nc,
4355 int* cmp)
4356 {
4357 mpz_t left_val;
4358 if (!left_nc->to_int(&left_val))
4359 return false;
4360 mpz_t right_val;
4361 if (!right_nc->to_int(&right_val))
4362 {
4363 mpz_clear(left_val);
4364 return false;
4365 }
4366
4367 *cmp = mpz_cmp(left_val, right_val);
4368
4369 mpz_clear(left_val);
4370 mpz_clear(right_val);
4371
4372 return true;
4373 }
4374
4375 // Compare floating point constants.
4376
4377 bool
4378 Binary_expression::compare_float(const Numeric_constant* left_nc,
4379 const Numeric_constant* right_nc,
4380 int* cmp)
4381 {
4382 mpfr_t left_val;
4383 if (!left_nc->to_float(&left_val))
4384 return false;
4385 mpfr_t right_val;
4386 if (!right_nc->to_float(&right_val))
4387 {
4388 mpfr_clear(left_val);
4389 return false;
4390 }
4391
4392 // We already coerced both operands to the same type. If that type
4393 // is not an abstract type, we need to round the values accordingly.
4394 Type* type = left_nc->type();
4395 if (!type->is_abstract() && type->float_type() != NULL)
4396 {
4397 int bits = type->float_type()->bits();
4398 mpfr_prec_round(left_val, bits, GMP_RNDN);
4399 mpfr_prec_round(right_val, bits, GMP_RNDN);
4400 }
4401
4402 *cmp = mpfr_cmp(left_val, right_val);
4403
4404 mpfr_clear(left_val);
4405 mpfr_clear(right_val);
4406
4407 return true;
4408 }
4409
4410 // Compare complex constants. Complex numbers may only be compared
4411 // for equality.
4412
4413 bool
4414 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4415 const Numeric_constant* right_nc,
4416 int* cmp)
4417 {
4418 mpfr_t left_real, left_imag;
4419 if (!left_nc->to_complex(&left_real, &left_imag))
4420 return false;
4421 mpfr_t right_real, right_imag;
4422 if (!right_nc->to_complex(&right_real, &right_imag))
4423 {
4424 mpfr_clear(left_real);
4425 mpfr_clear(left_imag);
4426 return false;
4427 }
4428
4429 // We already coerced both operands to the same type. If that type
4430 // is not an abstract type, we need to round the values accordingly.
4431 Type* type = left_nc->type();
4432 if (!type->is_abstract() && type->complex_type() != NULL)
4433 {
4434 int bits = type->complex_type()->bits();
4435 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4436 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4437 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4438 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4439 }
4440
4441 *cmp = (mpfr_cmp(left_real, right_real) != 0
4442 || mpfr_cmp(left_imag, right_imag) != 0);
4443
4444 mpfr_clear(left_real);
4445 mpfr_clear(left_imag);
4446 mpfr_clear(right_real);
4447 mpfr_clear(right_imag);
4448
4449 return true;
4450 }
4451
4452 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4453 // true if this could be done, false if not. Issue errors at LOCATION
4454 // as appropriate.
4455
4456 bool
4457 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4458 Numeric_constant* right_nc,
4459 Location location, Numeric_constant* nc)
4460 {
4461 switch (op)
4462 {
4463 case OPERATOR_OROR:
4464 case OPERATOR_ANDAND:
4465 case OPERATOR_EQEQ:
4466 case OPERATOR_NOTEQ:
4467 case OPERATOR_LT:
4468 case OPERATOR_LE:
4469 case OPERATOR_GT:
4470 case OPERATOR_GE:
4471 // These return boolean values, not numeric.
4472 return false;
4473 default:
4474 break;
4475 }
4476
4477 Type* left_type = left_nc->type();
4478 Type* right_type = right_nc->type();
4479
4480 Type* type;
4481 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4482 return false;
4483
4484 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4485
4486 // When combining an untyped operand with a typed operand, we are
4487 // effectively coercing the untyped operand to the other operand's
4488 // type, so make sure that is valid.
4489 if (!left_nc->set_type(type, true, location))
4490 return false;
4491 if (!is_shift && !right_nc->set_type(type, true, location))
4492 return false;
4493
4494 bool r;
4495 if (type->complex_type() != NULL)
4496 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4497 else if (type->float_type() != NULL)
4498 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4499 else
4500 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4501
4502 if (r)
4503 r = nc->set_type(type, true, location);
4504
4505 return r;
4506 }
4507
4508 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4509 // integer operations. Return true if this could be done, false if
4510 // not.
4511
4512 bool
4513 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4514 const Numeric_constant* right_nc,
4515 Location location, Numeric_constant* nc)
4516 {
4517 mpz_t left_val;
4518 if (!left_nc->to_int(&left_val))
4519 return false;
4520 mpz_t right_val;
4521 if (!right_nc->to_int(&right_val))
4522 {
4523 mpz_clear(left_val);
4524 return false;
4525 }
4526
4527 mpz_t val;
4528 mpz_init(val);
4529
4530 switch (op)
4531 {
4532 case OPERATOR_PLUS:
4533 mpz_add(val, left_val, right_val);
4534 break;
4535 case OPERATOR_MINUS:
4536 mpz_sub(val, left_val, right_val);
4537 break;
4538 case OPERATOR_OR:
4539 mpz_ior(val, left_val, right_val);
4540 break;
4541 case OPERATOR_XOR:
4542 mpz_xor(val, left_val, right_val);
4543 break;
4544 case OPERATOR_MULT:
4545 mpz_mul(val, left_val, right_val);
4546 break;
4547 case OPERATOR_DIV:
4548 if (mpz_sgn(right_val) != 0)
4549 mpz_tdiv_q(val, left_val, right_val);
4550 else
4551 {
4552 error_at(location, "division by zero");
4553 mpz_set_ui(val, 0);
4554 }
4555 break;
4556 case OPERATOR_MOD:
4557 if (mpz_sgn(right_val) != 0)
4558 mpz_tdiv_r(val, left_val, right_val);
4559 else
4560 {
4561 error_at(location, "division by zero");
4562 mpz_set_ui(val, 0);
4563 }
4564 break;
4565 case OPERATOR_LSHIFT:
4566 {
4567 unsigned long shift = mpz_get_ui(right_val);
4568 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4569 mpz_mul_2exp(val, left_val, shift);
4570 else
4571 {
4572 error_at(location, "shift count overflow");
4573 mpz_set_ui(val, 0);
4574 }
4575 break;
4576 }
4577 break;
4578 case OPERATOR_RSHIFT:
4579 {
4580 unsigned long shift = mpz_get_ui(right_val);
4581 if (mpz_cmp_ui(right_val, shift) != 0)
4582 {
4583 error_at(location, "shift count overflow");
4584 mpz_set_ui(val, 0);
4585 }
4586 else
4587 {
4588 if (mpz_cmp_ui(left_val, 0) >= 0)
4589 mpz_tdiv_q_2exp(val, left_val, shift);
4590 else
4591 mpz_fdiv_q_2exp(val, left_val, shift);
4592 }
4593 break;
4594 }
4595 break;
4596 case OPERATOR_AND:
4597 mpz_and(val, left_val, right_val);
4598 break;
4599 case OPERATOR_BITCLEAR:
4600 {
4601 mpz_t tval;
4602 mpz_init(tval);
4603 mpz_com(tval, right_val);
4604 mpz_and(val, left_val, tval);
4605 mpz_clear(tval);
4606 }
4607 break;
4608 default:
4609 go_unreachable();
4610 }
4611
4612 mpz_clear(left_val);
4613 mpz_clear(right_val);
4614
4615 if (left_nc->is_rune()
4616 || (op != OPERATOR_LSHIFT
4617 && op != OPERATOR_RSHIFT
4618 && right_nc->is_rune()))
4619 nc->set_rune(NULL, val);
4620 else
4621 nc->set_int(NULL, val);
4622
4623 mpz_clear(val);
4624
4625 return true;
4626 }
4627
4628 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4629 // floating point operations. Return true if this could be done,
4630 // false if not.
4631
4632 bool
4633 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4634 const Numeric_constant* right_nc,
4635 Location location, Numeric_constant* nc)
4636 {
4637 mpfr_t left_val;
4638 if (!left_nc->to_float(&left_val))
4639 return false;
4640 mpfr_t right_val;
4641 if (!right_nc->to_float(&right_val))
4642 {
4643 mpfr_clear(left_val);
4644 return false;
4645 }
4646
4647 mpfr_t val;
4648 mpfr_init(val);
4649
4650 bool ret = true;
4651 switch (op)
4652 {
4653 case OPERATOR_PLUS:
4654 mpfr_add(val, left_val, right_val, GMP_RNDN);
4655 break;
4656 case OPERATOR_MINUS:
4657 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4658 break;
4659 case OPERATOR_OR:
4660 case OPERATOR_XOR:
4661 case OPERATOR_AND:
4662 case OPERATOR_BITCLEAR:
4663 case OPERATOR_MOD:
4664 case OPERATOR_LSHIFT:
4665 case OPERATOR_RSHIFT:
4666 mpfr_set_ui(val, 0, GMP_RNDN);
4667 ret = false;
4668 break;
4669 case OPERATOR_MULT:
4670 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4671 break;
4672 case OPERATOR_DIV:
4673 if (!mpfr_zero_p(right_val))
4674 mpfr_div(val, left_val, right_val, GMP_RNDN);
4675 else
4676 {
4677 error_at(location, "division by zero");
4678 mpfr_set_ui(val, 0, GMP_RNDN);
4679 }
4680 break;
4681 default:
4682 go_unreachable();
4683 }
4684
4685 mpfr_clear(left_val);
4686 mpfr_clear(right_val);
4687
4688 nc->set_float(NULL, val);
4689 mpfr_clear(val);
4690
4691 return ret;
4692 }
4693
4694 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4695 // complex operations. Return true if this could be done, false if
4696 // not.
4697
4698 bool
4699 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4700 const Numeric_constant* right_nc,
4701 Location location, Numeric_constant* nc)
4702 {
4703 mpfr_t left_real, left_imag;
4704 if (!left_nc->to_complex(&left_real, &left_imag))
4705 return false;
4706 mpfr_t right_real, right_imag;
4707 if (!right_nc->to_complex(&right_real, &right_imag))
4708 {
4709 mpfr_clear(left_real);
4710 mpfr_clear(left_imag);
4711 return false;
4712 }
4713
4714 mpfr_t real, imag;
4715 mpfr_init(real);
4716 mpfr_init(imag);
4717
4718 bool ret = true;
4719 switch (op)
4720 {
4721 case OPERATOR_PLUS:
4722 mpfr_add(real, left_real, right_real, GMP_RNDN);
4723 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4724 break;
4725 case OPERATOR_MINUS:
4726 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4727 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4728 break;
4729 case OPERATOR_OR:
4730 case OPERATOR_XOR:
4731 case OPERATOR_AND:
4732 case OPERATOR_BITCLEAR:
4733 case OPERATOR_MOD:
4734 case OPERATOR_LSHIFT:
4735 case OPERATOR_RSHIFT:
4736 mpfr_set_ui(real, 0, GMP_RNDN);
4737 mpfr_set_ui(imag, 0, GMP_RNDN);
4738 ret = false;
4739 break;
4740 case OPERATOR_MULT:
4741 {
4742 // You might think that multiplying two complex numbers would
4743 // be simple, and you would be right, until you start to think
4744 // about getting the right answer for infinity. If one
4745 // operand here is infinity and the other is anything other
4746 // than zero or NaN, then we are going to wind up subtracting
4747 // two infinity values. That will give us a NaN, but the
4748 // correct answer is infinity.
4749
4750 mpfr_t lrrr;
4751 mpfr_init(lrrr);
4752 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4753
4754 mpfr_t lrri;
4755 mpfr_init(lrri);
4756 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4757
4758 mpfr_t lirr;
4759 mpfr_init(lirr);
4760 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4761
4762 mpfr_t liri;
4763 mpfr_init(liri);
4764 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4765
4766 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4767 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4768
4769 // If we get NaN on both sides, check whether it should really
4770 // be infinity. The rule is that if either side of the
4771 // complex number is infinity, then the whole value is
4772 // infinity, even if the other side is NaN. So the only case
4773 // we have to fix is the one in which both sides are NaN.
4774 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4775 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4776 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4777 {
4778 bool is_infinity = false;
4779
4780 mpfr_t lr;
4781 mpfr_t li;
4782 mpfr_init_set(lr, left_real, GMP_RNDN);
4783 mpfr_init_set(li, left_imag, GMP_RNDN);
4784
4785 mpfr_t rr;
4786 mpfr_t ri;
4787 mpfr_init_set(rr, right_real, GMP_RNDN);
4788 mpfr_init_set(ri, right_imag, GMP_RNDN);
4789
4790 // If the left side is infinity, then the result is
4791 // infinity.
4792 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4793 {
4794 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4795 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4796 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4797 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4798 if (mpfr_nan_p(rr))
4799 {
4800 mpfr_set_ui(rr, 0, GMP_RNDN);
4801 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4802 }
4803 if (mpfr_nan_p(ri))
4804 {
4805 mpfr_set_ui(ri, 0, GMP_RNDN);
4806 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4807 }
4808 is_infinity = true;
4809 }
4810
4811 // If the right side is infinity, then the result is
4812 // infinity.
4813 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4814 {
4815 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4816 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4817 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4818 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4819 if (mpfr_nan_p(lr))
4820 {
4821 mpfr_set_ui(lr, 0, GMP_RNDN);
4822 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4823 }
4824 if (mpfr_nan_p(li))
4825 {
4826 mpfr_set_ui(li, 0, GMP_RNDN);
4827 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4828 }
4829 is_infinity = true;
4830 }
4831
4832 // If we got an overflow in the intermediate computations,
4833 // then the result is infinity.
4834 if (!is_infinity
4835 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4836 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4837 {
4838 if (mpfr_nan_p(lr))
4839 {
4840 mpfr_set_ui(lr, 0, GMP_RNDN);
4841 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4842 }
4843 if (mpfr_nan_p(li))
4844 {
4845 mpfr_set_ui(li, 0, GMP_RNDN);
4846 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4847 }
4848 if (mpfr_nan_p(rr))
4849 {
4850 mpfr_set_ui(rr, 0, GMP_RNDN);
4851 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4852 }
4853 if (mpfr_nan_p(ri))
4854 {
4855 mpfr_set_ui(ri, 0, GMP_RNDN);
4856 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4857 }
4858 is_infinity = true;
4859 }
4860
4861 if (is_infinity)
4862 {
4863 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4864 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4865 mpfr_mul(lirr, li, rr, GMP_RNDN);
4866 mpfr_mul(liri, li, ri, GMP_RNDN);
4867 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4868 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4869 mpfr_set_inf(real, mpfr_sgn(real));
4870 mpfr_set_inf(imag, mpfr_sgn(imag));
4871 }
4872
4873 mpfr_clear(lr);
4874 mpfr_clear(li);
4875 mpfr_clear(rr);
4876 mpfr_clear(ri);
4877 }
4878
4879 mpfr_clear(lrrr);
4880 mpfr_clear(lrri);
4881 mpfr_clear(lirr);
4882 mpfr_clear(liri);
4883 }
4884 break;
4885 case OPERATOR_DIV:
4886 {
4887 // For complex division we want to avoid having an
4888 // intermediate overflow turn the whole result in a NaN. We
4889 // scale the values to try to avoid this.
4890
4891 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4892 {
4893 error_at(location, "division by zero");
4894 mpfr_set_ui(real, 0, GMP_RNDN);
4895 mpfr_set_ui(imag, 0, GMP_RNDN);
4896 break;
4897 }
4898
4899 mpfr_t rra;
4900 mpfr_t ria;
4901 mpfr_init(rra);
4902 mpfr_init(ria);
4903 mpfr_abs(rra, right_real, GMP_RNDN);
4904 mpfr_abs(ria, right_imag, GMP_RNDN);
4905 mpfr_t t;
4906 mpfr_init(t);
4907 mpfr_max(t, rra, ria, GMP_RNDN);
4908
4909 mpfr_t rr;
4910 mpfr_t ri;
4911 mpfr_init_set(rr, right_real, GMP_RNDN);
4912 mpfr_init_set(ri, right_imag, GMP_RNDN);
4913 long ilogbw = 0;
4914 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4915 {
4916 ilogbw = mpfr_get_exp(t);
4917 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4918 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4919 }
4920
4921 mpfr_t denom;
4922 mpfr_init(denom);
4923 mpfr_mul(denom, rr, rr, GMP_RNDN);
4924 mpfr_mul(t, ri, ri, GMP_RNDN);
4925 mpfr_add(denom, denom, t, GMP_RNDN);
4926
4927 mpfr_mul(real, left_real, rr, GMP_RNDN);
4928 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4929 mpfr_add(real, real, t, GMP_RNDN);
4930 mpfr_div(real, real, denom, GMP_RNDN);
4931 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4932
4933 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4934 mpfr_mul(t, left_real, ri, GMP_RNDN);
4935 mpfr_sub(imag, imag, t, GMP_RNDN);
4936 mpfr_div(imag, imag, denom, GMP_RNDN);
4937 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4938
4939 // If we wind up with NaN on both sides, check whether we
4940 // should really have infinity. The rule is that if either
4941 // side of the complex number is infinity, then the whole
4942 // value is infinity, even if the other side is NaN. So the
4943 // only case we have to fix is the one in which both sides are
4944 // NaN.
4945 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4946 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4947 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4948 {
4949 if (mpfr_zero_p(denom))
4950 {
4951 mpfr_set_inf(real, mpfr_sgn(rr));
4952 mpfr_mul(real, real, left_real, GMP_RNDN);
4953 mpfr_set_inf(imag, mpfr_sgn(rr));
4954 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4955 }
4956 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4957 && mpfr_number_p(rr) && mpfr_number_p(ri))
4958 {
4959 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4960 mpfr_copysign(t, t, left_real, GMP_RNDN);
4961
4962 mpfr_t t2;
4963 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4964 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4965
4966 mpfr_t t3;
4967 mpfr_init(t3);
4968 mpfr_mul(t3, t, rr, GMP_RNDN);
4969
4970 mpfr_t t4;
4971 mpfr_init(t4);
4972 mpfr_mul(t4, t2, ri, GMP_RNDN);
4973
4974 mpfr_add(t3, t3, t4, GMP_RNDN);
4975 mpfr_set_inf(real, mpfr_sgn(t3));
4976
4977 mpfr_mul(t3, t2, rr, GMP_RNDN);
4978 mpfr_mul(t4, t, ri, GMP_RNDN);
4979 mpfr_sub(t3, t3, t4, GMP_RNDN);
4980 mpfr_set_inf(imag, mpfr_sgn(t3));
4981
4982 mpfr_clear(t2);
4983 mpfr_clear(t3);
4984 mpfr_clear(t4);
4985 }
4986 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4987 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4988 {
4989 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4990 mpfr_copysign(t, t, rr, GMP_RNDN);
4991
4992 mpfr_t t2;
4993 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4994 mpfr_copysign(t2, t2, ri, GMP_RNDN);
4995
4996 mpfr_t t3;
4997 mpfr_init(t3);
4998 mpfr_mul(t3, left_real, t, GMP_RNDN);
4999
5000 mpfr_t t4;
5001 mpfr_init(t4);
5002 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5003
5004 mpfr_add(t3, t3, t4, GMP_RNDN);
5005 mpfr_set_ui(real, 0, GMP_RNDN);
5006 mpfr_mul(real, real, t3, GMP_RNDN);
5007
5008 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5009 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5010 mpfr_sub(t3, t3, t4, GMP_RNDN);
5011 mpfr_set_ui(imag, 0, GMP_RNDN);
5012 mpfr_mul(imag, imag, t3, GMP_RNDN);
5013
5014 mpfr_clear(t2);
5015 mpfr_clear(t3);
5016 mpfr_clear(t4);
5017 }
5018 }
5019
5020 mpfr_clear(denom);
5021 mpfr_clear(rr);
5022 mpfr_clear(ri);
5023 mpfr_clear(t);
5024 mpfr_clear(rra);
5025 mpfr_clear(ria);
5026 }
5027 break;
5028 default:
5029 go_unreachable();
5030 }
5031
5032 mpfr_clear(left_real);
5033 mpfr_clear(left_imag);
5034 mpfr_clear(right_real);
5035 mpfr_clear(right_imag);
5036
5037 nc->set_complex(NULL, real, imag);
5038 mpfr_clear(real);
5039 mpfr_clear(imag);
5040
5041 return ret;
5042 }
5043
5044 // Lower a binary expression. We have to evaluate constant
5045 // expressions now, in order to implement Go's unlimited precision
5046 // constants.
5047
5048 Expression*
5049 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5050 Statement_inserter* inserter, int)
5051 {
5052 Location location = this->location();
5053 Operator op = this->op_;
5054 Expression* left = this->left_;
5055 Expression* right = this->right_;
5056
5057 const bool is_comparison = (op == OPERATOR_EQEQ
5058 || op == OPERATOR_NOTEQ
5059 || op == OPERATOR_LT
5060 || op == OPERATOR_LE
5061 || op == OPERATOR_GT
5062 || op == OPERATOR_GE);
5063
5064 // Numeric constant expressions.
5065 {
5066 Numeric_constant left_nc;
5067 Numeric_constant right_nc;
5068 if (left->numeric_constant_value(&left_nc)
5069 && right->numeric_constant_value(&right_nc))
5070 {
5071 if (is_comparison)
5072 {
5073 bool result;
5074 if (!Binary_expression::compare_constant(op, &left_nc,
5075 &right_nc, location,
5076 &result))
5077 return this;
5078 return Expression::make_cast(Type::lookup_bool_type(),
5079 Expression::make_boolean(result,
5080 location),
5081 location);
5082 }
5083 else
5084 {
5085 Numeric_constant nc;
5086 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5087 location, &nc))
5088 return this;
5089 return nc.expression(location);
5090 }
5091 }
5092 }
5093
5094 // String constant expressions.
5095 if (left->type()->is_string_type() && right->type()->is_string_type())
5096 {
5097 std::string left_string;
5098 std::string right_string;
5099 if (left->string_constant_value(&left_string)
5100 && right->string_constant_value(&right_string))
5101 {
5102 if (op == OPERATOR_PLUS)
5103 return Expression::make_string(left_string + right_string,
5104 location);
5105 else if (is_comparison)
5106 {
5107 int cmp = left_string.compare(right_string);
5108 bool r = Binary_expression::cmp_to_bool(op, cmp);
5109 return Expression::make_cast(Type::lookup_bool_type(),
5110 Expression::make_boolean(r,
5111 location),
5112 location);
5113 }
5114 }
5115 }
5116
5117 // Lower struct and array comparisons.
5118 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5119 {
5120 if (left->type()->struct_type() != NULL)
5121 return this->lower_struct_comparison(gogo, inserter);
5122 else if (left->type()->array_type() != NULL
5123 && !left->type()->is_slice_type())
5124 return this->lower_array_comparison(gogo, inserter);
5125 }
5126
5127 return this;
5128 }
5129
5130 // Lower a struct comparison.
5131
5132 Expression*
5133 Binary_expression::lower_struct_comparison(Gogo* gogo,
5134 Statement_inserter* inserter)
5135 {
5136 Struct_type* st = this->left_->type()->struct_type();
5137 Struct_type* st2 = this->right_->type()->struct_type();
5138 if (st2 == NULL)
5139 return this;
5140 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5141 return this;
5142 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5143 this->right_->type(), NULL))
5144 return this;
5145
5146 // See if we can compare using memcmp. As a heuristic, we use
5147 // memcmp rather than field references and comparisons if there are
5148 // more than two fields.
5149 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5150 return this->lower_compare_to_memcmp(gogo, inserter);
5151
5152 Location loc = this->location();
5153
5154 Expression* left = this->left_;
5155 Temporary_statement* left_temp = NULL;
5156 if (left->var_expression() == NULL
5157 && left->temporary_reference_expression() == NULL)
5158 {
5159 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5160 inserter->insert(left_temp);
5161 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5162 }
5163
5164 Expression* right = this->right_;
5165 Temporary_statement* right_temp = NULL;
5166 if (right->var_expression() == NULL
5167 && right->temporary_reference_expression() == NULL)
5168 {
5169 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5170 inserter->insert(right_temp);
5171 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5172 }
5173
5174 Expression* ret = Expression::make_boolean(true, loc);
5175 const Struct_field_list* fields = st->fields();
5176 unsigned int field_index = 0;
5177 for (Struct_field_list::const_iterator pf = fields->begin();
5178 pf != fields->end();
5179 ++pf, ++field_index)
5180 {
5181 if (field_index > 0)
5182 {
5183 if (left_temp == NULL)
5184 left = left->copy();
5185 else
5186 left = Expression::make_temporary_reference(left_temp, loc);
5187 if (right_temp == NULL)
5188 right = right->copy();
5189 else
5190 right = Expression::make_temporary_reference(right_temp, loc);
5191 }
5192 Expression* f1 = Expression::make_field_reference(left, field_index,
5193 loc);
5194 Expression* f2 = Expression::make_field_reference(right, field_index,
5195 loc);
5196 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5197 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5198 }
5199
5200 if (this->op_ == OPERATOR_NOTEQ)
5201 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5202
5203 return ret;
5204 }
5205
5206 // Lower an array comparison.
5207
5208 Expression*
5209 Binary_expression::lower_array_comparison(Gogo* gogo,
5210 Statement_inserter* inserter)
5211 {
5212 Array_type* at = this->left_->type()->array_type();
5213 Array_type* at2 = this->right_->type()->array_type();
5214 if (at2 == NULL)
5215 return this;
5216 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5217 return this;
5218 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5219 this->right_->type(), NULL))
5220 return this;
5221
5222 // Call memcmp directly if possible. This may let the middle-end
5223 // optimize the call.
5224 if (at->compare_is_identity(gogo))
5225 return this->lower_compare_to_memcmp(gogo, inserter);
5226
5227 // Call the array comparison function.
5228 Named_object* hash_fn;
5229 Named_object* equal_fn;
5230 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5231 &hash_fn, &equal_fn);
5232
5233 Location loc = this->location();
5234
5235 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5236
5237 Expression_list* args = new Expression_list();
5238 args->push_back(this->operand_address(inserter, this->left_));
5239 args->push_back(this->operand_address(inserter, this->right_));
5240 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5241
5242 Expression* ret = Expression::make_call(func, args, false, loc);
5243
5244 if (this->op_ == OPERATOR_NOTEQ)
5245 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5246
5247 return ret;
5248 }
5249
5250 // Lower a struct or array comparison to a call to memcmp.
5251
5252 Expression*
5253 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5254 {
5255 Location loc = this->location();
5256
5257 Expression* a1 = this->operand_address(inserter, this->left_);
5258 Expression* a2 = this->operand_address(inserter, this->right_);
5259 Expression* len = Expression::make_type_info(this->left_->type(),
5260 TYPE_INFO_SIZE);
5261
5262 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5263
5264 mpz_t zval;
5265 mpz_init_set_ui(zval, 0);
5266 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5267 mpz_clear(zval);
5268
5269 return Expression::make_binary(this->op_, call, zero, loc);
5270 }
5271
5272 // Return the address of EXPR, cast to unsafe.Pointer.
5273
5274 Expression*
5275 Binary_expression::operand_address(Statement_inserter* inserter,
5276 Expression* expr)
5277 {
5278 Location loc = this->location();
5279
5280 if (!expr->is_addressable())
5281 {
5282 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5283 loc);
5284 inserter->insert(temp);
5285 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5286 }
5287 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5288 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5289 Type* void_type = Type::make_void_type();
5290 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5291 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5292 }
5293
5294 // Return the numeric constant value, if it has one.
5295
5296 bool
5297 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5298 {
5299 Numeric_constant left_nc;
5300 if (!this->left_->numeric_constant_value(&left_nc))
5301 return false;
5302 Numeric_constant right_nc;
5303 if (!this->right_->numeric_constant_value(&right_nc))
5304 return false;
5305 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5306 this->location(), nc);
5307 }
5308
5309 // Note that the value is being discarded.
5310
5311 void
5312 Binary_expression::do_discarding_value()
5313 {
5314 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5315 this->right_->discarding_value();
5316 else
5317 this->unused_value_error();
5318 }
5319
5320 // Get type.
5321
5322 Type*
5323 Binary_expression::do_type()
5324 {
5325 if (this->classification() == EXPRESSION_ERROR)
5326 return Type::make_error_type();
5327
5328 switch (this->op_)
5329 {
5330 case OPERATOR_OROR:
5331 case OPERATOR_ANDAND:
5332 case OPERATOR_EQEQ:
5333 case OPERATOR_NOTEQ:
5334 case OPERATOR_LT:
5335 case OPERATOR_LE:
5336 case OPERATOR_GT:
5337 case OPERATOR_GE:
5338 return Type::lookup_bool_type();
5339
5340 case OPERATOR_PLUS:
5341 case OPERATOR_MINUS:
5342 case OPERATOR_OR:
5343 case OPERATOR_XOR:
5344 case OPERATOR_MULT:
5345 case OPERATOR_DIV:
5346 case OPERATOR_MOD:
5347 case OPERATOR_AND:
5348 case OPERATOR_BITCLEAR:
5349 {
5350 Type* type;
5351 if (!Binary_expression::operation_type(this->op_,
5352 this->left_->type(),
5353 this->right_->type(),
5354 &type))
5355 return Type::make_error_type();
5356 return type;
5357 }
5358
5359 case OPERATOR_LSHIFT:
5360 case OPERATOR_RSHIFT:
5361 return this->left_->type();
5362
5363 default:
5364 go_unreachable();
5365 }
5366 }
5367
5368 // Set type for a binary expression.
5369
5370 void
5371 Binary_expression::do_determine_type(const Type_context* context)
5372 {
5373 Type* tleft = this->left_->type();
5374 Type* tright = this->right_->type();
5375
5376 // Both sides should have the same type, except for the shift
5377 // operations. For a comparison, we should ignore the incoming
5378 // type.
5379
5380 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5381 || this->op_ == OPERATOR_RSHIFT);
5382
5383 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5384 || this->op_ == OPERATOR_NOTEQ
5385 || this->op_ == OPERATOR_LT
5386 || this->op_ == OPERATOR_LE
5387 || this->op_ == OPERATOR_GT
5388 || this->op_ == OPERATOR_GE);
5389
5390 Type_context subcontext(*context);
5391
5392 if (is_comparison)
5393 {
5394 // In a comparison, the context does not determine the types of
5395 // the operands.
5396 subcontext.type = NULL;
5397 }
5398
5399 // Set the context for the left hand operand.
5400 if (is_shift_op)
5401 {
5402 // The right hand operand of a shift plays no role in
5403 // determining the type of the left hand operand.
5404 }
5405 else if (!tleft->is_abstract())
5406 subcontext.type = tleft;
5407 else if (!tright->is_abstract())
5408 subcontext.type = tright;
5409 else if (subcontext.type == NULL)
5410 {
5411 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5412 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5413 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5414 {
5415 // Both sides have an abstract integer, abstract float, or
5416 // abstract complex type. Just let CONTEXT determine
5417 // whether they may remain abstract or not.
5418 }
5419 else if (tleft->complex_type() != NULL)
5420 subcontext.type = tleft;
5421 else if (tright->complex_type() != NULL)
5422 subcontext.type = tright;
5423 else if (tleft->float_type() != NULL)
5424 subcontext.type = tleft;
5425 else if (tright->float_type() != NULL)
5426 subcontext.type = tright;
5427 else
5428 subcontext.type = tleft;
5429
5430 if (subcontext.type != NULL && !context->may_be_abstract)
5431 subcontext.type = subcontext.type->make_non_abstract_type();
5432 }
5433
5434 this->left_->determine_type(&subcontext);
5435
5436 if (is_shift_op)
5437 {
5438 // We may have inherited an unusable type for the shift operand.
5439 // Give a useful error if that happened.
5440 if (tleft->is_abstract()
5441 && subcontext.type != NULL
5442 && (this->left_->type()->integer_type() == NULL
5443 || (subcontext.type->integer_type() == NULL
5444 && subcontext.type->float_type() == NULL
5445 && subcontext.type->complex_type() == NULL)))
5446 this->report_error(("invalid context-determined non-integer type "
5447 "for shift operand"));
5448
5449 // The context for the right hand operand is the same as for the
5450 // left hand operand, except for a shift operator.
5451 subcontext.type = Type::lookup_integer_type("uint");
5452 subcontext.may_be_abstract = false;
5453 }
5454
5455 this->right_->determine_type(&subcontext);
5456 }
5457
5458 // Report an error if the binary operator OP does not support TYPE.
5459 // OTYPE is the type of the other operand. Return whether the
5460 // operation is OK. This should not be used for shift.
5461
5462 bool
5463 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5464 Location location)
5465 {
5466 switch (op)
5467 {
5468 case OPERATOR_OROR:
5469 case OPERATOR_ANDAND:
5470 if (!type->is_boolean_type())
5471 {
5472 error_at(location, "expected boolean type");
5473 return false;
5474 }
5475 break;
5476
5477 case OPERATOR_EQEQ:
5478 case OPERATOR_NOTEQ:
5479 {
5480 std::string reason;
5481 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5482 {
5483 error_at(location, "%s", reason.c_str());
5484 return false;
5485 }
5486 }
5487 break;
5488
5489 case OPERATOR_LT:
5490 case OPERATOR_LE:
5491 case OPERATOR_GT:
5492 case OPERATOR_GE:
5493 {
5494 std::string reason;
5495 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5496 {
5497 error_at(location, "%s", reason.c_str());
5498 return false;
5499 }
5500 }
5501 break;
5502
5503 case OPERATOR_PLUS:
5504 case OPERATOR_PLUSEQ:
5505 if (type->integer_type() == NULL
5506 && type->float_type() == NULL
5507 && type->complex_type() == NULL
5508 && !type->is_string_type())
5509 {
5510 error_at(location,
5511 "expected integer, floating, complex, or string type");
5512 return false;
5513 }
5514 break;
5515
5516 case OPERATOR_MINUS:
5517 case OPERATOR_MINUSEQ:
5518 case OPERATOR_MULT:
5519 case OPERATOR_MULTEQ:
5520 case OPERATOR_DIV:
5521 case OPERATOR_DIVEQ:
5522 if (type->integer_type() == NULL
5523 && type->float_type() == NULL
5524 && type->complex_type() == NULL)
5525 {
5526 error_at(location, "expected integer, floating, or complex type");
5527 return false;
5528 }
5529 break;
5530
5531 case OPERATOR_MOD:
5532 case OPERATOR_MODEQ:
5533 case OPERATOR_OR:
5534 case OPERATOR_OREQ:
5535 case OPERATOR_AND:
5536 case OPERATOR_ANDEQ:
5537 case OPERATOR_XOR:
5538 case OPERATOR_XOREQ:
5539 case OPERATOR_BITCLEAR:
5540 case OPERATOR_BITCLEAREQ:
5541 if (type->integer_type() == NULL)
5542 {
5543 error_at(location, "expected integer type");
5544 return false;
5545 }
5546 break;
5547
5548 default:
5549 go_unreachable();
5550 }
5551
5552 return true;
5553 }
5554
5555 // Check types.
5556
5557 void
5558 Binary_expression::do_check_types(Gogo*)
5559 {
5560 if (this->classification() == EXPRESSION_ERROR)
5561 return;
5562
5563 Type* left_type = this->left_->type();
5564 Type* right_type = this->right_->type();
5565 if (left_type->is_error() || right_type->is_error())
5566 {
5567 this->set_is_error();
5568 return;
5569 }
5570
5571 if (this->op_ == OPERATOR_EQEQ
5572 || this->op_ == OPERATOR_NOTEQ
5573 || this->op_ == OPERATOR_LT
5574 || this->op_ == OPERATOR_LE
5575 || this->op_ == OPERATOR_GT
5576 || this->op_ == OPERATOR_GE)
5577 {
5578 if (!Type::are_assignable(left_type, right_type, NULL)
5579 && !Type::are_assignable(right_type, left_type, NULL))
5580 {
5581 this->report_error(_("incompatible types in binary expression"));
5582 return;
5583 }
5584 if (!Binary_expression::check_operator_type(this->op_, left_type,
5585 right_type,
5586 this->location())
5587 || !Binary_expression::check_operator_type(this->op_, right_type,
5588 left_type,
5589 this->location()))
5590 {
5591 this->set_is_error();
5592 return;
5593 }
5594 }
5595 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5596 {
5597 if (!Type::are_compatible_for_binop(left_type, right_type))
5598 {
5599 this->report_error(_("incompatible types in binary expression"));
5600 return;
5601 }
5602 if (!Binary_expression::check_operator_type(this->op_, left_type,
5603 right_type,
5604 this->location()))
5605 {
5606 this->set_is_error();
5607 return;
5608 }
5609 }
5610 else
5611 {
5612 if (left_type->integer_type() == NULL)
5613 this->report_error(_("shift of non-integer operand"));
5614
5615 if (!right_type->is_abstract()
5616 && (right_type->integer_type() == NULL
5617 || !right_type->integer_type()->is_unsigned()))
5618 this->report_error(_("shift count not unsigned integer"));
5619 else
5620 {
5621 Numeric_constant nc;
5622 if (this->right_->numeric_constant_value(&nc))
5623 {
5624 mpz_t val;
5625 if (!nc.to_int(&val))
5626 this->report_error(_("shift count not unsigned integer"));
5627 else
5628 {
5629 if (mpz_sgn(val) < 0)
5630 {
5631 this->report_error(_("negative shift count"));
5632 mpz_set_ui(val, 0);
5633 Location rloc = this->right_->location();
5634 this->right_ = Expression::make_integer(&val, right_type,
5635 rloc);
5636 }
5637 mpz_clear(val);
5638 }
5639 }
5640 }
5641 }
5642 }
5643
5644 // Get a tree for a binary expression.
5645
5646 tree
5647 Binary_expression::do_get_tree(Translate_context* context)
5648 {
5649 tree left = this->left_->get_tree(context);
5650 tree right = this->right_->get_tree(context);
5651
5652 if (left == error_mark_node || right == error_mark_node)
5653 return error_mark_node;
5654
5655 enum tree_code code;
5656 bool use_left_type = true;
5657 bool is_shift_op = false;
5658 bool is_idiv_op = false;
5659 switch (this->op_)
5660 {
5661 case OPERATOR_EQEQ:
5662 case OPERATOR_NOTEQ:
5663 case OPERATOR_LT:
5664 case OPERATOR_LE:
5665 case OPERATOR_GT:
5666 case OPERATOR_GE:
5667 return Expression::comparison_tree(context, this->op_,
5668 this->left_->type(), left,
5669 this->right_->type(), right,
5670 this->location());
5671
5672 case OPERATOR_OROR:
5673 code = TRUTH_ORIF_EXPR;
5674 use_left_type = false;
5675 break;
5676 case OPERATOR_ANDAND:
5677 code = TRUTH_ANDIF_EXPR;
5678 use_left_type = false;
5679 break;
5680 case OPERATOR_PLUS:
5681 code = PLUS_EXPR;
5682 break;
5683 case OPERATOR_MINUS:
5684 code = MINUS_EXPR;
5685 break;
5686 case OPERATOR_OR:
5687 code = BIT_IOR_EXPR;
5688 break;
5689 case OPERATOR_XOR:
5690 code = BIT_XOR_EXPR;
5691 break;
5692 case OPERATOR_MULT:
5693 code = MULT_EXPR;
5694 break;
5695 case OPERATOR_DIV:
5696 {
5697 Type *t = this->left_->type();
5698 if (t->float_type() != NULL || t->complex_type() != NULL)
5699 code = RDIV_EXPR;
5700 else
5701 {
5702 code = TRUNC_DIV_EXPR;
5703 is_idiv_op = true;
5704 }
5705 }
5706 break;
5707 case OPERATOR_MOD:
5708 code = TRUNC_MOD_EXPR;
5709 is_idiv_op = true;
5710 break;
5711 case OPERATOR_LSHIFT:
5712 code = LSHIFT_EXPR;
5713 is_shift_op = true;
5714 break;
5715 case OPERATOR_RSHIFT:
5716 code = RSHIFT_EXPR;
5717 is_shift_op = true;
5718 break;
5719 case OPERATOR_AND:
5720 code = BIT_AND_EXPR;
5721 break;
5722 case OPERATOR_BITCLEAR:
5723 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5724 code = BIT_AND_EXPR;
5725 break;
5726 default:
5727 go_unreachable();
5728 }
5729
5730 location_t gccloc = this->location().gcc_location();
5731 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5732
5733 if (this->left_->type()->is_string_type())
5734 {
5735 go_assert(this->op_ == OPERATOR_PLUS);
5736 Type* st = Type::make_string_type();
5737 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5738 static tree string_plus_decl;
5739 return Gogo::call_builtin(&string_plus_decl,
5740 this->location(),
5741 "__go_string_plus",
5742 2,
5743 string_type,
5744 string_type,
5745 left,
5746 string_type,
5747 right);
5748 }
5749
5750 tree compute_type = excess_precision_type(type);
5751 if (compute_type != NULL_TREE)
5752 {
5753 left = ::convert(compute_type, left);
5754 right = ::convert(compute_type, right);
5755 }
5756
5757 tree eval_saved = NULL_TREE;
5758 if (is_shift_op
5759 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5760 {
5761 // Make sure the values are evaluated.
5762 if (!DECL_P(left))
5763 {
5764 left = save_expr(left);
5765 eval_saved = left;
5766 }
5767 if (!DECL_P(right))
5768 {
5769 right = save_expr(right);
5770 if (eval_saved == NULL_TREE)
5771 eval_saved = right;
5772 else
5773 eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
5774 void_type_node, eval_saved, right);
5775 }
5776 }
5777
5778 tree ret = fold_build2_loc(gccloc, code,
5779 compute_type != NULL_TREE ? compute_type : type,
5780 left, right);
5781
5782 if (compute_type != NULL_TREE)
5783 ret = ::convert(type, ret);
5784
5785 // In Go, a shift larger than the size of the type is well-defined.
5786 // This is not true in GENERIC, so we need to insert a conditional.
5787 if (is_shift_op)
5788 {
5789 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5790 go_assert(this->left_->type()->integer_type() != NULL);
5791 int bits = TYPE_PRECISION(TREE_TYPE(left));
5792
5793 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5794 build_int_cst_type(TREE_TYPE(right), bits));
5795
5796 tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
5797 integer_zero_node);
5798 if (this->op_ == OPERATOR_RSHIFT
5799 && !this->left_->type()->integer_type()->is_unsigned())
5800 {
5801 tree neg =
5802 fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
5803 left,
5804 fold_convert_loc(gccloc, TREE_TYPE(left),
5805 integer_zero_node));
5806 tree neg_one =
5807 fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
5808 fold_convert_loc(gccloc, TREE_TYPE(left),
5809 integer_zero_node),
5810 fold_convert_loc(gccloc, TREE_TYPE(left),
5811 integer_one_node));
5812 overflow_result =
5813 fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5814 neg, neg_one, overflow_result);
5815 }
5816
5817 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5818 compare, ret, overflow_result);
5819
5820 if (eval_saved != NULL_TREE)
5821 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5822 eval_saved, ret);
5823 }
5824
5825 // Add checks for division by zero and division overflow as needed.
5826 if (is_idiv_op)
5827 {
5828 if (go_check_divide_zero)
5829 {
5830 // right == 0
5831 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5832 right,
5833 fold_convert_loc(gccloc,
5834 TREE_TYPE(right),
5835 integer_zero_node));
5836
5837 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
5838 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5839 tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5840 Gogo::runtime_error(errcode,
5841 this->location()),
5842 fold_convert_loc(gccloc, TREE_TYPE(ret),
5843 integer_zero_node));
5844
5845 // right == 0 ? (__go_runtime_error(...), 0) : ret
5846 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5847 check, panic, ret);
5848 }
5849
5850 if (go_check_divide_overflow)
5851 {
5852 // right == -1
5853 // FIXME: It would be nice to say that this test is expected
5854 // to return false.
5855 tree m1 = integer_minus_one_node;
5856 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5857 right,
5858 fold_convert_loc(gccloc,
5859 TREE_TYPE(right),
5860 m1));
5861
5862 tree overflow;
5863 if (TYPE_UNSIGNED(TREE_TYPE(ret)))
5864 {
5865 // An unsigned -1 is the largest possible number, so
5866 // dividing is always 1 or 0.
5867 tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5868 left, right);
5869 if (this->op_ == OPERATOR_DIV)
5870 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5871 cmp,
5872 fold_convert_loc(gccloc,
5873 TREE_TYPE(ret),
5874 integer_one_node),
5875 fold_convert_loc(gccloc,
5876 TREE_TYPE(ret),
5877 integer_zero_node));
5878 else
5879 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5880 cmp,
5881 fold_convert_loc(gccloc,
5882 TREE_TYPE(ret),
5883 integer_zero_node),
5884 left);
5885 }
5886 else
5887 {
5888 // Computing left / -1 is the same as computing - left,
5889 // which does not overflow since Go sets -fwrapv.
5890 if (this->op_ == OPERATOR_DIV)
5891 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
5892 left);
5893 else
5894 overflow = integer_zero_node;
5895 }
5896 overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
5897
5898 // right == -1 ? - left : ret
5899 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5900 check, overflow, ret);
5901 }
5902
5903 if (eval_saved != NULL_TREE)
5904 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5905 eval_saved, ret);
5906 }
5907
5908 return ret;
5909 }
5910
5911 // Export a binary expression.
5912
5913 void
5914 Binary_expression::do_export(Export* exp) const
5915 {
5916 exp->write_c_string("(");
5917 this->left_->export_expression(exp);
5918 switch (this->op_)
5919 {
5920 case OPERATOR_OROR:
5921 exp->write_c_string(" || ");
5922 break;
5923 case OPERATOR_ANDAND:
5924 exp->write_c_string(" && ");
5925 break;
5926 case OPERATOR_EQEQ:
5927 exp->write_c_string(" == ");
5928 break;
5929 case OPERATOR_NOTEQ:
5930 exp->write_c_string(" != ");
5931 break;
5932 case OPERATOR_LT:
5933 exp->write_c_string(" < ");
5934 break;
5935 case OPERATOR_LE:
5936 exp->write_c_string(" <= ");
5937 break;
5938 case OPERATOR_GT:
5939 exp->write_c_string(" > ");
5940 break;
5941 case OPERATOR_GE:
5942 exp->write_c_string(" >= ");
5943 break;
5944 case OPERATOR_PLUS:
5945 exp->write_c_string(" + ");
5946 break;
5947 case OPERATOR_MINUS:
5948 exp->write_c_string(" - ");
5949 break;
5950 case OPERATOR_OR:
5951 exp->write_c_string(" | ");
5952 break;
5953 case OPERATOR_XOR:
5954 exp->write_c_string(" ^ ");
5955 break;
5956 case OPERATOR_MULT:
5957 exp->write_c_string(" * ");
5958 break;
5959 case OPERATOR_DIV:
5960 exp->write_c_string(" / ");
5961 break;
5962 case OPERATOR_MOD:
5963 exp->write_c_string(" % ");
5964 break;
5965 case OPERATOR_LSHIFT:
5966 exp->write_c_string(" << ");
5967 break;
5968 case OPERATOR_RSHIFT:
5969 exp->write_c_string(" >> ");
5970 break;
5971 case OPERATOR_AND:
5972 exp->write_c_string(" & ");
5973 break;
5974 case OPERATOR_BITCLEAR:
5975 exp->write_c_string(" &^ ");
5976 break;
5977 default:
5978 go_unreachable();
5979 }
5980 this->right_->export_expression(exp);
5981 exp->write_c_string(")");
5982 }
5983
5984 // Import a binary expression.
5985
5986 Expression*
5987 Binary_expression::do_import(Import* imp)
5988 {
5989 imp->require_c_string("(");
5990
5991 Expression* left = Expression::import_expression(imp);
5992
5993 Operator op;
5994 if (imp->match_c_string(" || "))
5995 {
5996 op = OPERATOR_OROR;
5997 imp->advance(4);
5998 }
5999 else if (imp->match_c_string(" && "))
6000 {
6001 op = OPERATOR_ANDAND;
6002 imp->advance(4);
6003 }
6004 else if (imp->match_c_string(" == "))
6005 {
6006 op = OPERATOR_EQEQ;
6007 imp->advance(4);
6008 }
6009 else if (imp->match_c_string(" != "))
6010 {
6011 op = OPERATOR_NOTEQ;
6012 imp->advance(4);
6013 }
6014 else if (imp->match_c_string(" < "))
6015 {
6016 op = OPERATOR_LT;
6017 imp->advance(3);
6018 }
6019 else if (imp->match_c_string(" <= "))
6020 {
6021 op = OPERATOR_LE;
6022 imp->advance(4);
6023 }
6024 else if (imp->match_c_string(" > "))
6025 {
6026 op = OPERATOR_GT;
6027 imp->advance(3);
6028 }
6029 else if (imp->match_c_string(" >= "))
6030 {
6031 op = OPERATOR_GE;
6032 imp->advance(4);
6033 }
6034 else if (imp->match_c_string(" + "))
6035 {
6036 op = OPERATOR_PLUS;
6037 imp->advance(3);
6038 }
6039 else if (imp->match_c_string(" - "))
6040 {
6041 op = OPERATOR_MINUS;
6042 imp->advance(3);
6043 }
6044 else if (imp->match_c_string(" | "))
6045 {
6046 op = OPERATOR_OR;
6047 imp->advance(3);
6048 }
6049 else if (imp->match_c_string(" ^ "))
6050 {
6051 op = OPERATOR_XOR;
6052 imp->advance(3);
6053 }
6054 else if (imp->match_c_string(" * "))
6055 {
6056 op = OPERATOR_MULT;
6057 imp->advance(3);
6058 }
6059 else if (imp->match_c_string(" / "))
6060 {
6061 op = OPERATOR_DIV;
6062 imp->advance(3);
6063 }
6064 else if (imp->match_c_string(" % "))
6065 {
6066 op = OPERATOR_MOD;
6067 imp->advance(3);
6068 }
6069 else if (imp->match_c_string(" << "))
6070 {
6071 op = OPERATOR_LSHIFT;
6072 imp->advance(4);
6073 }
6074 else if (imp->match_c_string(" >> "))
6075 {
6076 op = OPERATOR_RSHIFT;
6077 imp->advance(4);
6078 }
6079 else if (imp->match_c_string(" & "))
6080 {
6081 op = OPERATOR_AND;
6082 imp->advance(3);
6083 }
6084 else if (imp->match_c_string(" &^ "))
6085 {
6086 op = OPERATOR_BITCLEAR;
6087 imp->advance(4);
6088 }
6089 else
6090 {
6091 error_at(imp->location(), "unrecognized binary operator");
6092 return Expression::make_error(imp->location());
6093 }
6094
6095 Expression* right = Expression::import_expression(imp);
6096
6097 imp->require_c_string(")");
6098
6099 return Expression::make_binary(op, left, right, imp->location());
6100 }
6101
6102 // Dump ast representation of a binary expression.
6103
6104 void
6105 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6106 {
6107 ast_dump_context->ostream() << "(";
6108 ast_dump_context->dump_expression(this->left_);
6109 ast_dump_context->ostream() << " ";
6110 ast_dump_context->dump_operator(this->op_);
6111 ast_dump_context->ostream() << " ";
6112 ast_dump_context->dump_expression(this->right_);
6113 ast_dump_context->ostream() << ") ";
6114 }
6115
6116 // Make a binary expression.
6117
6118 Expression*
6119 Expression::make_binary(Operator op, Expression* left, Expression* right,
6120 Location location)
6121 {
6122 return new Binary_expression(op, left, right, location);
6123 }
6124
6125 // Implement a comparison.
6126
6127 tree
6128 Expression::comparison_tree(Translate_context* context, Operator op,
6129 Type* left_type, tree left_tree,
6130 Type* right_type, tree right_tree,
6131 Location location)
6132 {
6133 enum tree_code code;
6134 switch (op)
6135 {
6136 case OPERATOR_EQEQ:
6137 code = EQ_EXPR;
6138 break;
6139 case OPERATOR_NOTEQ:
6140 code = NE_EXPR;
6141 break;
6142 case OPERATOR_LT:
6143 code = LT_EXPR;
6144 break;
6145 case OPERATOR_LE:
6146 code = LE_EXPR;
6147 break;
6148 case OPERATOR_GT:
6149 code = GT_EXPR;
6150 break;
6151 case OPERATOR_GE:
6152 code = GE_EXPR;
6153 break;
6154 default:
6155 go_unreachable();
6156 }
6157
6158 if (left_type->is_string_type() && right_type->is_string_type())
6159 {
6160 Type* st = Type::make_string_type();
6161 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6162 static tree string_compare_decl;
6163 left_tree = Gogo::call_builtin(&string_compare_decl,
6164 location,
6165 "__go_strcmp",
6166 2,
6167 integer_type_node,
6168 string_type,
6169 left_tree,
6170 string_type,
6171 right_tree);
6172 right_tree = build_int_cst_type(integer_type_node, 0);
6173 }
6174 else if ((left_type->interface_type() != NULL
6175 && right_type->interface_type() == NULL
6176 && !right_type->is_nil_type())
6177 || (left_type->interface_type() == NULL
6178 && !left_type->is_nil_type()
6179 && right_type->interface_type() != NULL))
6180 {
6181 // Comparing an interface value to a non-interface value.
6182 if (left_type->interface_type() == NULL)
6183 {
6184 std::swap(left_type, right_type);
6185 std::swap(left_tree, right_tree);
6186 }
6187
6188 // The right operand is not an interface. We need to take its
6189 // address if it is not a pointer.
6190 tree make_tmp;
6191 tree arg;
6192 if (right_type->points_to() != NULL)
6193 {
6194 make_tmp = NULL_TREE;
6195 arg = right_tree;
6196 }
6197 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree))
6198 || (TREE_CODE(right_tree) != CONST_DECL
6199 && DECL_P(right_tree)))
6200 {
6201 make_tmp = NULL_TREE;
6202 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6203 if (DECL_P(right_tree))
6204 TREE_ADDRESSABLE(right_tree) = 1;
6205 }
6206 else
6207 {
6208 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6209 get_name(right_tree));
6210 DECL_IGNORED_P(tmp) = 0;
6211 DECL_INITIAL(tmp) = right_tree;
6212 TREE_ADDRESSABLE(tmp) = 1;
6213 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6214 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6215 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6216 }
6217 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6218
6219 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6220 location);
6221
6222 if (left_type->interface_type()->is_empty())
6223 {
6224 static tree empty_interface_value_compare_decl;
6225 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6226 location,
6227 "__go_empty_interface_value_compare",
6228 3,
6229 integer_type_node,
6230 TREE_TYPE(left_tree),
6231 left_tree,
6232 TREE_TYPE(descriptor),
6233 descriptor,
6234 ptr_type_node,
6235 arg);
6236 if (left_tree == error_mark_node)
6237 return error_mark_node;
6238 // This can panic if the type is not comparable.
6239 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6240 }
6241 else
6242 {
6243 static tree interface_value_compare_decl;
6244 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6245 location,
6246 "__go_interface_value_compare",
6247 3,
6248 integer_type_node,
6249 TREE_TYPE(left_tree),
6250 left_tree,
6251 TREE_TYPE(descriptor),
6252 descriptor,
6253 ptr_type_node,
6254 arg);
6255 if (left_tree == error_mark_node)
6256 return error_mark_node;
6257 // This can panic if the type is not comparable.
6258 TREE_NOTHROW(interface_value_compare_decl) = 0;
6259 }
6260 right_tree = build_int_cst_type(integer_type_node, 0);
6261
6262 if (make_tmp != NULL_TREE)
6263 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6264 left_tree);
6265 }
6266 else if (left_type->interface_type() != NULL
6267 && right_type->interface_type() != NULL)
6268 {
6269 if (left_type->interface_type()->is_empty()
6270 && right_type->interface_type()->is_empty())
6271 {
6272 static tree empty_interface_compare_decl;
6273 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6274 location,
6275 "__go_empty_interface_compare",
6276 2,
6277 integer_type_node,
6278 TREE_TYPE(left_tree),
6279 left_tree,
6280 TREE_TYPE(right_tree),
6281 right_tree);
6282 if (left_tree == error_mark_node)
6283 return error_mark_node;
6284 // This can panic if the type is uncomparable.
6285 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6286 }
6287 else if (!left_type->interface_type()->is_empty()
6288 && !right_type->interface_type()->is_empty())
6289 {
6290 static tree interface_compare_decl;
6291 left_tree = Gogo::call_builtin(&interface_compare_decl,
6292 location,
6293 "__go_interface_compare",
6294 2,
6295 integer_type_node,
6296 TREE_TYPE(left_tree),
6297 left_tree,
6298 TREE_TYPE(right_tree),
6299 right_tree);
6300 if (left_tree == error_mark_node)
6301 return error_mark_node;
6302 // This can panic if the type is uncomparable.
6303 TREE_NOTHROW(interface_compare_decl) = 0;
6304 }
6305 else
6306 {
6307 if (left_type->interface_type()->is_empty())
6308 {
6309 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6310 std::swap(left_type, right_type);
6311 std::swap(left_tree, right_tree);
6312 }
6313 go_assert(!left_type->interface_type()->is_empty());
6314 go_assert(right_type->interface_type()->is_empty());
6315 static tree interface_empty_compare_decl;
6316 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6317 location,
6318 "__go_interface_empty_compare",
6319 2,
6320 integer_type_node,
6321 TREE_TYPE(left_tree),
6322 left_tree,
6323 TREE_TYPE(right_tree),
6324 right_tree);
6325 if (left_tree == error_mark_node)
6326 return error_mark_node;
6327 // This can panic if the type is uncomparable.
6328 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6329 }
6330
6331 right_tree = build_int_cst_type(integer_type_node, 0);
6332 }
6333
6334 if (left_type->is_nil_type()
6335 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6336 {
6337 std::swap(left_type, right_type);
6338 std::swap(left_tree, right_tree);
6339 }
6340
6341 if (right_type->is_nil_type())
6342 {
6343 if (left_type->array_type() != NULL
6344 && left_type->array_type()->length() == NULL)
6345 {
6346 Array_type* at = left_type->array_type();
6347 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6348 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6349 }
6350 else if (left_type->interface_type() != NULL)
6351 {
6352 // An interface is nil if the first field is nil.
6353 tree left_type_tree = TREE_TYPE(left_tree);
6354 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6355 tree field = TYPE_FIELDS(left_type_tree);
6356 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6357 field, NULL_TREE);
6358 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6359 }
6360 else
6361 {
6362 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6363 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6364 }
6365 }
6366
6367 if (left_tree == error_mark_node || right_tree == error_mark_node)
6368 return error_mark_node;
6369
6370 tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6371 if (CAN_HAVE_LOCATION_P(ret))
6372 SET_EXPR_LOCATION(ret, location.gcc_location());
6373 return ret;
6374 }
6375
6376 // Class Bound_method_expression.
6377
6378 // Traversal.
6379
6380 int
6381 Bound_method_expression::do_traverse(Traverse* traverse)
6382 {
6383 return Expression::traverse(&this->expr_, traverse);
6384 }
6385
6386 // Return the type of a bound method expression. The type of this
6387 // object is really the type of the method with no receiver. We
6388 // should be able to get away with just returning the type of the
6389 // method.
6390
6391 Type*
6392 Bound_method_expression::do_type()
6393 {
6394 if (this->method_->is_function())
6395 return this->method_->func_value()->type();
6396 else if (this->method_->is_function_declaration())
6397 return this->method_->func_declaration_value()->type();
6398 else
6399 return Type::make_error_type();
6400 }
6401
6402 // Determine the types of a method expression.
6403
6404 void
6405 Bound_method_expression::do_determine_type(const Type_context*)
6406 {
6407 Function_type* fntype = this->type()->function_type();
6408 if (fntype == NULL || !fntype->is_method())
6409 this->expr_->determine_type_no_context();
6410 else
6411 {
6412 Type_context subcontext(fntype->receiver()->type(), false);
6413 this->expr_->determine_type(&subcontext);
6414 }
6415 }
6416
6417 // Check the types of a method expression.
6418
6419 void
6420 Bound_method_expression::do_check_types(Gogo*)
6421 {
6422 if (!this->method_->is_function()
6423 && !this->method_->is_function_declaration())
6424 this->report_error(_("object is not a method"));
6425 else
6426 {
6427 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6428 Type* etype = (this->expr_type_ != NULL
6429 ? this->expr_type_
6430 : this->expr_->type());
6431 etype = etype->deref();
6432 if (!Type::are_identical(rtype, etype, true, NULL))
6433 this->report_error(_("method type does not match object type"));
6434 }
6435 }
6436
6437 // Get the tree for a method expression. There is no standard tree
6438 // representation for this. The only places it may currently be used
6439 // are in a Call_expression or a Go_statement, which will take it
6440 // apart directly. So this has nothing to do at present.
6441
6442 tree
6443 Bound_method_expression::do_get_tree(Translate_context*)
6444 {
6445 error_at(this->location(), "reference to method other than calling it");
6446 return error_mark_node;
6447 }
6448
6449 // Dump ast representation of a bound method expression.
6450
6451 void
6452 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6453 const
6454 {
6455 if (this->expr_type_ != NULL)
6456 ast_dump_context->ostream() << "(";
6457 ast_dump_context->dump_expression(this->expr_);
6458 if (this->expr_type_ != NULL)
6459 {
6460 ast_dump_context->ostream() << ":";
6461 ast_dump_context->dump_type(this->expr_type_);
6462 ast_dump_context->ostream() << ")";
6463 }
6464
6465 ast_dump_context->ostream() << "." << this->method_->name();
6466 }
6467
6468 // Make a method expression.
6469
6470 Bound_method_expression*
6471 Expression::make_bound_method(Expression* expr, Named_object* method,
6472 Location location)
6473 {
6474 return new Bound_method_expression(expr, method, location);
6475 }
6476
6477 // Class Builtin_call_expression. This is used for a call to a
6478 // builtin function.
6479
6480 class Builtin_call_expression : public Call_expression
6481 {
6482 public:
6483 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6484 bool is_varargs, Location location);
6485
6486 protected:
6487 // This overrides Call_expression::do_lower.
6488 Expression*
6489 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6490
6491 bool
6492 do_is_constant() const;
6493
6494 bool
6495 do_numeric_constant_value(Numeric_constant*) const;
6496
6497 void
6498 do_discarding_value();
6499
6500 Type*
6501 do_type();
6502
6503 void
6504 do_determine_type(const Type_context*);
6505
6506 void
6507 do_check_types(Gogo*);
6508
6509 Expression*
6510 do_copy()
6511 {
6512 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6513 this->args()->copy(),
6514 this->is_varargs(),
6515 this->location());
6516 }
6517
6518 tree
6519 do_get_tree(Translate_context*);
6520
6521 void
6522 do_export(Export*) const;
6523
6524 virtual bool
6525 do_is_recover_call() const;
6526
6527 virtual void
6528 do_set_recover_arg(Expression*);
6529
6530 private:
6531 // The builtin functions.
6532 enum Builtin_function_code
6533 {
6534 BUILTIN_INVALID,
6535
6536 // Predeclared builtin functions.
6537 BUILTIN_APPEND,
6538 BUILTIN_CAP,
6539 BUILTIN_CLOSE,
6540 BUILTIN_COMPLEX,
6541 BUILTIN_COPY,
6542 BUILTIN_DELETE,
6543 BUILTIN_IMAG,
6544 BUILTIN_LEN,
6545 BUILTIN_MAKE,
6546 BUILTIN_NEW,
6547 BUILTIN_PANIC,
6548 BUILTIN_PRINT,
6549 BUILTIN_PRINTLN,
6550 BUILTIN_REAL,
6551 BUILTIN_RECOVER,
6552
6553 // Builtin functions from the unsafe package.
6554 BUILTIN_ALIGNOF,
6555 BUILTIN_OFFSETOF,
6556 BUILTIN_SIZEOF
6557 };
6558
6559 Expression*
6560 one_arg() const;
6561
6562 bool
6563 check_one_arg();
6564
6565 static Type*
6566 real_imag_type(Type*);
6567
6568 static Type*
6569 complex_type(Type*);
6570
6571 Expression*
6572 lower_make();
6573
6574 bool
6575 check_int_value(Expression*);
6576
6577 // A pointer back to the general IR structure. This avoids a global
6578 // variable, or passing it around everywhere.
6579 Gogo* gogo_;
6580 // The builtin function being called.
6581 Builtin_function_code code_;
6582 // Used to stop endless loops when the length of an array uses len
6583 // or cap of the array itself.
6584 mutable bool seen_;
6585 };
6586
6587 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6588 Expression* fn,
6589 Expression_list* args,
6590 bool is_varargs,
6591 Location location)
6592 : Call_expression(fn, args, is_varargs, location),
6593 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6594 {
6595 Func_expression* fnexp = this->fn()->func_expression();
6596 go_assert(fnexp != NULL);
6597 const std::string& name(fnexp->named_object()->name());
6598 if (name == "append")
6599 this->code_ = BUILTIN_APPEND;
6600 else if (name == "cap")
6601 this->code_ = BUILTIN_CAP;
6602 else if (name == "close")
6603 this->code_ = BUILTIN_CLOSE;
6604 else if (name == "complex")
6605 this->code_ = BUILTIN_COMPLEX;
6606 else if (name == "copy")
6607 this->code_ = BUILTIN_COPY;
6608 else if (name == "delete")
6609 this->code_ = BUILTIN_DELETE;
6610 else if (name == "imag")
6611 this->code_ = BUILTIN_IMAG;
6612 else if (name == "len")
6613 this->code_ = BUILTIN_LEN;
6614 else if (name == "make")
6615 this->code_ = BUILTIN_MAKE;
6616 else if (name == "new")
6617 this->code_ = BUILTIN_NEW;
6618 else if (name == "panic")
6619 this->code_ = BUILTIN_PANIC;
6620 else if (name == "print")
6621 this->code_ = BUILTIN_PRINT;
6622 else if (name == "println")
6623 this->code_ = BUILTIN_PRINTLN;
6624 else if (name == "real")
6625 this->code_ = BUILTIN_REAL;
6626 else if (name == "recover")
6627 this->code_ = BUILTIN_RECOVER;
6628 else if (name == "Alignof")
6629 this->code_ = BUILTIN_ALIGNOF;
6630 else if (name == "Offsetof")
6631 this->code_ = BUILTIN_OFFSETOF;
6632 else if (name == "Sizeof")
6633 this->code_ = BUILTIN_SIZEOF;
6634 else
6635 go_unreachable();
6636 }
6637
6638 // Return whether this is a call to recover. This is a virtual
6639 // function called from the parent class.
6640
6641 bool
6642 Builtin_call_expression::do_is_recover_call() const
6643 {
6644 if (this->classification() == EXPRESSION_ERROR)
6645 return false;
6646 return this->code_ == BUILTIN_RECOVER;
6647 }
6648
6649 // Set the argument for a call to recover.
6650
6651 void
6652 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6653 {
6654 const Expression_list* args = this->args();
6655 go_assert(args == NULL || args->empty());
6656 Expression_list* new_args = new Expression_list();
6657 new_args->push_back(arg);
6658 this->set_args(new_args);
6659 }
6660
6661 // A traversal class which looks for a call expression.
6662
6663 class Find_call_expression : public Traverse
6664 {
6665 public:
6666 Find_call_expression()
6667 : Traverse(traverse_expressions),
6668 found_(false)
6669 { }
6670
6671 int
6672 expression(Expression**);
6673
6674 bool
6675 found()
6676 { return this->found_; }
6677
6678 private:
6679 bool found_;
6680 };
6681
6682 int
6683 Find_call_expression::expression(Expression** pexpr)
6684 {
6685 if ((*pexpr)->call_expression() != NULL)
6686 {
6687 this->found_ = true;
6688 return TRAVERSE_EXIT;
6689 }
6690 return TRAVERSE_CONTINUE;
6691 }
6692
6693 // Lower a builtin call expression. This turns new and make into
6694 // specific expressions. We also convert to a constant if we can.
6695
6696 Expression*
6697 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6698 Statement_inserter* inserter, int)
6699 {
6700 if (this->classification() == EXPRESSION_ERROR)
6701 return this;
6702
6703 Location loc = this->location();
6704
6705 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6706 {
6707 this->report_error(_("invalid use of %<...%> with builtin function"));
6708 return Expression::make_error(loc);
6709 }
6710
6711 if (this->is_constant())
6712 {
6713 // We can only lower len and cap if there are no function calls
6714 // in the arguments. Otherwise we have to make the call.
6715 if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6716 {
6717 Expression* arg = this->one_arg();
6718 if (arg != NULL && !arg->is_constant())
6719 {
6720 Find_call_expression find_call;
6721 Expression::traverse(&arg, &find_call);
6722 if (find_call.found())
6723 return this;
6724 }
6725 }
6726
6727 Numeric_constant nc;
6728 if (this->numeric_constant_value(&nc))
6729 return nc.expression(loc);
6730 }
6731
6732 switch (this->code_)
6733 {
6734 default:
6735 break;
6736
6737 case BUILTIN_NEW:
6738 {
6739 const Expression_list* args = this->args();
6740 if (args == NULL || args->size() < 1)
6741 this->report_error(_("not enough arguments"));
6742 else if (args->size() > 1)
6743 this->report_error(_("too many arguments"));
6744 else
6745 {
6746 Expression* arg = args->front();
6747 if (!arg->is_type_expression())
6748 {
6749 error_at(arg->location(), "expected type");
6750 this->set_is_error();
6751 }
6752 else
6753 return Expression::make_allocation(arg->type(), loc);
6754 }
6755 }
6756 break;
6757
6758 case BUILTIN_MAKE:
6759 return this->lower_make();
6760
6761 case BUILTIN_RECOVER:
6762 if (function != NULL)
6763 function->func_value()->set_calls_recover();
6764 else
6765 {
6766 // Calling recover outside of a function always returns the
6767 // nil empty interface.
6768 Type* eface = Type::make_empty_interface_type(loc);
6769 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6770 }
6771 break;
6772
6773 case BUILTIN_APPEND:
6774 {
6775 // Lower the varargs.
6776 const Expression_list* args = this->args();
6777 if (args == NULL || args->empty())
6778 return this;
6779 Type* slice_type = args->front()->type();
6780 if (!slice_type->is_slice_type())
6781 {
6782 error_at(args->front()->location(), "argument 1 must be a slice");
6783 this->set_is_error();
6784 return this;
6785 }
6786 Type* element_type = slice_type->array_type()->element_type();
6787 this->lower_varargs(gogo, function, inserter,
6788 Type::make_array_type(element_type, NULL),
6789 2);
6790 }
6791 break;
6792
6793 case BUILTIN_DELETE:
6794 {
6795 // Lower to a runtime function call.
6796 const Expression_list* args = this->args();
6797 if (args == NULL || args->size() < 2)
6798 this->report_error(_("not enough arguments"));
6799 else if (args->size() > 2)
6800 this->report_error(_("too many arguments"));
6801 else if (args->front()->type()->map_type() == NULL)
6802 this->report_error(_("argument 1 must be a map"));
6803 else
6804 {
6805 // Since this function returns no value it must appear in
6806 // a statement by itself, so we don't have to worry about
6807 // order of evaluation of values around it. Evaluate the
6808 // map first to get order of evaluation right.
6809 Map_type* mt = args->front()->type()->map_type();
6810 Temporary_statement* map_temp =
6811 Statement::make_temporary(mt, args->front(), loc);
6812 inserter->insert(map_temp);
6813
6814 Temporary_statement* key_temp =
6815 Statement::make_temporary(mt->key_type(), args->back(), loc);
6816 inserter->insert(key_temp);
6817
6818 Expression* e1 = Expression::make_temporary_reference(map_temp,
6819 loc);
6820 Expression* e2 = Expression::make_temporary_reference(key_temp,
6821 loc);
6822 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6823 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6824 2, e1, e2);
6825 }
6826 }
6827 break;
6828 }
6829
6830 return this;
6831 }
6832
6833 // Lower a make expression.
6834
6835 Expression*
6836 Builtin_call_expression::lower_make()
6837 {
6838 Location loc = this->location();
6839
6840 const Expression_list* args = this->args();
6841 if (args == NULL || args->size() < 1)
6842 {
6843 this->report_error(_("not enough arguments"));
6844 return Expression::make_error(this->location());
6845 }
6846
6847 Expression_list::const_iterator parg = args->begin();
6848
6849 Expression* first_arg = *parg;
6850 if (!first_arg->is_type_expression())
6851 {
6852 error_at(first_arg->location(), "expected type");
6853 this->set_is_error();
6854 return Expression::make_error(this->location());
6855 }
6856 Type* type = first_arg->type();
6857
6858 bool is_slice = false;
6859 bool is_map = false;
6860 bool is_chan = false;
6861 if (type->is_slice_type())
6862 is_slice = true;
6863 else if (type->map_type() != NULL)
6864 is_map = true;
6865 else if (type->channel_type() != NULL)
6866 is_chan = true;
6867 else
6868 {
6869 this->report_error(_("invalid type for make function"));
6870 return Expression::make_error(this->location());
6871 }
6872
6873 bool have_big_args = false;
6874 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6875 int uintptr_bits = uintptr_type->integer_type()->bits();
6876
6877 ++parg;
6878 Expression* len_arg;
6879 if (parg == args->end())
6880 {
6881 if (is_slice)
6882 {
6883 this->report_error(_("length required when allocating a slice"));
6884 return Expression::make_error(this->location());
6885 }
6886
6887 mpz_t zval;
6888 mpz_init_set_ui(zval, 0);
6889 len_arg = Expression::make_integer(&zval, NULL, loc);
6890 mpz_clear(zval);
6891 }
6892 else
6893 {
6894 len_arg = *parg;
6895 if (!this->check_int_value(len_arg))
6896 {
6897 this->report_error(_("bad size for make"));
6898 return Expression::make_error(this->location());
6899 }
6900 if (len_arg->type()->integer_type() != NULL
6901 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6902 have_big_args = true;
6903 ++parg;
6904 }
6905
6906 Expression* cap_arg = NULL;
6907 if (is_slice && parg != args->end())
6908 {
6909 cap_arg = *parg;
6910 if (!this->check_int_value(cap_arg))
6911 {
6912 this->report_error(_("bad capacity when making slice"));
6913 return Expression::make_error(this->location());
6914 }
6915 if (cap_arg->type()->integer_type() != NULL
6916 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6917 have_big_args = true;
6918 ++parg;
6919 }
6920
6921 if (parg != args->end())
6922 {
6923 this->report_error(_("too many arguments to make"));
6924 return Expression::make_error(this->location());
6925 }
6926
6927 Location type_loc = first_arg->location();
6928 Expression* type_arg;
6929 if (is_slice || is_chan)
6930 type_arg = Expression::make_type_descriptor(type, type_loc);
6931 else if (is_map)
6932 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6933 else
6934 go_unreachable();
6935
6936 Expression* call;
6937 if (is_slice)
6938 {
6939 if (cap_arg == NULL)
6940 call = Runtime::make_call((have_big_args
6941 ? Runtime::MAKESLICE1BIG
6942 : Runtime::MAKESLICE1),
6943 loc, 2, type_arg, len_arg);
6944 else
6945 call = Runtime::make_call((have_big_args
6946 ? Runtime::MAKESLICE2BIG
6947 : Runtime::MAKESLICE2),
6948 loc, 3, type_arg, len_arg, cap_arg);
6949 }
6950 else if (is_map)
6951 call = Runtime::make_call((have_big_args
6952 ? Runtime::MAKEMAPBIG
6953 : Runtime::MAKEMAP),
6954 loc, 2, type_arg, len_arg);
6955 else if (is_chan)
6956 call = Runtime::make_call((have_big_args
6957 ? Runtime::MAKECHANBIG
6958 : Runtime::MAKECHAN),
6959 loc, 2, type_arg, len_arg);
6960 else
6961 go_unreachable();
6962
6963 return Expression::make_unsafe_cast(type, call, loc);
6964 }
6965
6966 // Return whether an expression has an integer value. Report an error
6967 // if not. This is used when handling calls to the predeclared make
6968 // function.
6969
6970 bool
6971 Builtin_call_expression::check_int_value(Expression* e)
6972 {
6973 if (e->type()->integer_type() != NULL)
6974 return true;
6975
6976 // Check for a floating point constant with integer value.
6977 Numeric_constant nc;
6978 mpz_t ival;
6979 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6980 {
6981 mpz_clear(ival);
6982 return true;
6983 }
6984
6985 return false;
6986 }
6987
6988 // Return the type of the real or imag functions, given the type of
6989 // the argument. We need to map complex to float, complex64 to
6990 // float32, and complex128 to float64, so it has to be done by name.
6991 // This returns NULL if it can't figure out the type.
6992
6993 Type*
6994 Builtin_call_expression::real_imag_type(Type* arg_type)
6995 {
6996 if (arg_type == NULL || arg_type->is_abstract())
6997 return NULL;
6998 Named_type* nt = arg_type->named_type();
6999 if (nt == NULL)
7000 return NULL;
7001 while (nt->real_type()->named_type() != NULL)
7002 nt = nt->real_type()->named_type();
7003 if (nt->name() == "complex64")
7004 return Type::lookup_float_type("float32");
7005 else if (nt->name() == "complex128")
7006 return Type::lookup_float_type("float64");
7007 else
7008 return NULL;
7009 }
7010
7011 // Return the type of the complex function, given the type of one of the
7012 // argments. Like real_imag_type, we have to map by name.
7013
7014 Type*
7015 Builtin_call_expression::complex_type(Type* arg_type)
7016 {
7017 if (arg_type == NULL || arg_type->is_abstract())
7018 return NULL;
7019 Named_type* nt = arg_type->named_type();
7020 if (nt == NULL)
7021 return NULL;
7022 while (nt->real_type()->named_type() != NULL)
7023 nt = nt->real_type()->named_type();
7024 if (nt->name() == "float32")
7025 return Type::lookup_complex_type("complex64");
7026 else if (nt->name() == "float64")
7027 return Type::lookup_complex_type("complex128");
7028 else
7029 return NULL;
7030 }
7031
7032 // Return a single argument, or NULL if there isn't one.
7033
7034 Expression*
7035 Builtin_call_expression::one_arg() const
7036 {
7037 const Expression_list* args = this->args();
7038 if (args == NULL || args->size() != 1)
7039 return NULL;
7040 return args->front();
7041 }
7042
7043 // Return whether this is constant: len of a string, or len or cap of
7044 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
7045
7046 bool
7047 Builtin_call_expression::do_is_constant() const
7048 {
7049 switch (this->code_)
7050 {
7051 case BUILTIN_LEN:
7052 case BUILTIN_CAP:
7053 {
7054 if (this->seen_)
7055 return false;
7056
7057 Expression* arg = this->one_arg();
7058 if (arg == NULL)
7059 return false;
7060 Type* arg_type = arg->type();
7061
7062 if (arg_type->points_to() != NULL
7063 && arg_type->points_to()->array_type() != NULL
7064 && !arg_type->points_to()->is_slice_type())
7065 arg_type = arg_type->points_to();
7066
7067 if (arg_type->array_type() != NULL
7068 && arg_type->array_type()->length() != NULL)
7069 return true;
7070
7071 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7072 {
7073 this->seen_ = true;
7074 bool ret = arg->is_constant();
7075 this->seen_ = false;
7076 return ret;
7077 }
7078 }
7079 break;
7080
7081 case BUILTIN_SIZEOF:
7082 case BUILTIN_ALIGNOF:
7083 return this->one_arg() != NULL;
7084
7085 case BUILTIN_OFFSETOF:
7086 {
7087 Expression* arg = this->one_arg();
7088 if (arg == NULL)
7089 return false;
7090 return arg->field_reference_expression() != NULL;
7091 }
7092
7093 case BUILTIN_COMPLEX:
7094 {
7095 const Expression_list* args = this->args();
7096 if (args != NULL && args->size() == 2)
7097 return args->front()->is_constant() && args->back()->is_constant();
7098 }
7099 break;
7100
7101 case BUILTIN_REAL:
7102 case BUILTIN_IMAG:
7103 {
7104 Expression* arg = this->one_arg();
7105 return arg != NULL && arg->is_constant();
7106 }
7107
7108 default:
7109 break;
7110 }
7111
7112 return false;
7113 }
7114
7115 // Return a numeric constant if possible.
7116
7117 bool
7118 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7119 {
7120 if (this->code_ == BUILTIN_LEN
7121 || this->code_ == BUILTIN_CAP)
7122 {
7123 Expression* arg = this->one_arg();
7124 if (arg == NULL)
7125 return false;
7126 Type* arg_type = arg->type();
7127
7128 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7129 {
7130 std::string sval;
7131 if (arg->string_constant_value(&sval))
7132 {
7133 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7134 sval.length());
7135 return true;
7136 }
7137 }
7138
7139 if (arg_type->points_to() != NULL
7140 && arg_type->points_to()->array_type() != NULL
7141 && !arg_type->points_to()->is_slice_type())
7142 arg_type = arg_type->points_to();
7143
7144 if (arg_type->array_type() != NULL
7145 && arg_type->array_type()->length() != NULL)
7146 {
7147 if (this->seen_)
7148 return false;
7149 Expression* e = arg_type->array_type()->length();
7150 this->seen_ = true;
7151 bool r = e->numeric_constant_value(nc);
7152 this->seen_ = false;
7153 if (r)
7154 {
7155 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7156 this->location()))
7157 r = false;
7158 }
7159 return r;
7160 }
7161 }
7162 else if (this->code_ == BUILTIN_SIZEOF
7163 || this->code_ == BUILTIN_ALIGNOF)
7164 {
7165 Expression* arg = this->one_arg();
7166 if (arg == NULL)
7167 return false;
7168 Type* arg_type = arg->type();
7169 if (arg_type->is_error())
7170 return false;
7171 if (arg_type->is_abstract())
7172 return false;
7173 if (arg_type->named_type() != NULL)
7174 arg_type->named_type()->convert(this->gogo_);
7175
7176 unsigned int ret;
7177 if (this->code_ == BUILTIN_SIZEOF)
7178 {
7179 if (!arg_type->backend_type_size(this->gogo_, &ret))
7180 return false;
7181 }
7182 else if (this->code_ == BUILTIN_ALIGNOF)
7183 {
7184 if (arg->field_reference_expression() == NULL)
7185 {
7186 if (!arg_type->backend_type_align(this->gogo_, &ret))
7187 return false;
7188 }
7189 else
7190 {
7191 // Calling unsafe.Alignof(s.f) returns the alignment of
7192 // the type of f when it is used as a field in a struct.
7193 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7194 return false;
7195 }
7196 }
7197 else
7198 go_unreachable();
7199
7200 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7201 static_cast<unsigned long>(ret));
7202 return true;
7203 }
7204 else if (this->code_ == BUILTIN_OFFSETOF)
7205 {
7206 Expression* arg = this->one_arg();
7207 if (arg == NULL)
7208 return false;
7209 Field_reference_expression* farg = arg->field_reference_expression();
7210 if (farg == NULL)
7211 return false;
7212 Expression* struct_expr = farg->expr();
7213 Type* st = struct_expr->type();
7214 if (st->struct_type() == NULL)
7215 return false;
7216 if (st->named_type() != NULL)
7217 st->named_type()->convert(this->gogo_);
7218 unsigned int offset;
7219 if (!st->struct_type()->backend_field_offset(this->gogo_,
7220 farg->field_index(),
7221 &offset))
7222 return false;
7223 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7224 static_cast<unsigned long>(offset));
7225 return true;
7226 }
7227 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7228 {
7229 Expression* arg = this->one_arg();
7230 if (arg == NULL)
7231 return false;
7232
7233 Numeric_constant argnc;
7234 if (!arg->numeric_constant_value(&argnc))
7235 return false;
7236
7237 mpfr_t real;
7238 mpfr_t imag;
7239 if (!argnc.to_complex(&real, &imag))
7240 return false;
7241
7242 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7243 if (this->code_ == BUILTIN_REAL)
7244 nc->set_float(type, real);
7245 else
7246 nc->set_float(type, imag);
7247 return true;
7248 }
7249 else if (this->code_ == BUILTIN_COMPLEX)
7250 {
7251 const Expression_list* args = this->args();
7252 if (args == NULL || args->size() != 2)
7253 return false;
7254
7255 Numeric_constant rnc;
7256 if (!args->front()->numeric_constant_value(&rnc))
7257 return false;
7258 Numeric_constant inc;
7259 if (!args->back()->numeric_constant_value(&inc))
7260 return false;
7261
7262 if (rnc.type() != NULL
7263 && !rnc.type()->is_abstract()
7264 && inc.type() != NULL
7265 && !inc.type()->is_abstract()
7266 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7267 return false;
7268
7269 mpfr_t r;
7270 if (!rnc.to_float(&r))
7271 return false;
7272 mpfr_t i;
7273 if (!inc.to_float(&i))
7274 {
7275 mpfr_clear(r);
7276 return false;
7277 }
7278
7279 Type* arg_type = rnc.type();
7280 if (arg_type == NULL || arg_type->is_abstract())
7281 arg_type = inc.type();
7282
7283 Type* type = Builtin_call_expression::complex_type(arg_type);
7284 nc->set_complex(type, r, i);
7285
7286 mpfr_clear(r);
7287 mpfr_clear(i);
7288
7289 return true;
7290 }
7291
7292 return false;
7293 }
7294
7295 // Give an error if we are discarding the value of an expression which
7296 // should not normally be discarded. We don't give an error for
7297 // discarding the value of an ordinary function call, but we do for
7298 // builtin functions, purely for consistency with the gc compiler.
7299
7300 void
7301 Builtin_call_expression::do_discarding_value()
7302 {
7303 switch (this->code_)
7304 {
7305 case BUILTIN_INVALID:
7306 default:
7307 go_unreachable();
7308
7309 case BUILTIN_APPEND:
7310 case BUILTIN_CAP:
7311 case BUILTIN_COMPLEX:
7312 case BUILTIN_IMAG:
7313 case BUILTIN_LEN:
7314 case BUILTIN_MAKE:
7315 case BUILTIN_NEW:
7316 case BUILTIN_REAL:
7317 case BUILTIN_ALIGNOF:
7318 case BUILTIN_OFFSETOF:
7319 case BUILTIN_SIZEOF:
7320 this->unused_value_error();
7321 break;
7322
7323 case BUILTIN_CLOSE:
7324 case BUILTIN_COPY:
7325 case BUILTIN_DELETE:
7326 case BUILTIN_PANIC:
7327 case BUILTIN_PRINT:
7328 case BUILTIN_PRINTLN:
7329 case BUILTIN_RECOVER:
7330 break;
7331 }
7332 }
7333
7334 // Return the type.
7335
7336 Type*
7337 Builtin_call_expression::do_type()
7338 {
7339 switch (this->code_)
7340 {
7341 case BUILTIN_INVALID:
7342 default:
7343 go_unreachable();
7344
7345 case BUILTIN_NEW:
7346 case BUILTIN_MAKE:
7347 {
7348 const Expression_list* args = this->args();
7349 if (args == NULL || args->empty())
7350 return Type::make_error_type();
7351 return Type::make_pointer_type(args->front()->type());
7352 }
7353
7354 case BUILTIN_CAP:
7355 case BUILTIN_COPY:
7356 case BUILTIN_LEN:
7357 return Type::lookup_integer_type("int");
7358
7359 case BUILTIN_ALIGNOF:
7360 case BUILTIN_OFFSETOF:
7361 case BUILTIN_SIZEOF:
7362 return Type::lookup_integer_type("uintptr");
7363
7364 case BUILTIN_CLOSE:
7365 case BUILTIN_DELETE:
7366 case BUILTIN_PANIC:
7367 case BUILTIN_PRINT:
7368 case BUILTIN_PRINTLN:
7369 return Type::make_void_type();
7370
7371 case BUILTIN_RECOVER:
7372 return Type::make_empty_interface_type(Linemap::predeclared_location());
7373
7374 case BUILTIN_APPEND:
7375 {
7376 const Expression_list* args = this->args();
7377 if (args == NULL || args->empty())
7378 return Type::make_error_type();
7379 return args->front()->type();
7380 }
7381
7382 case BUILTIN_REAL:
7383 case BUILTIN_IMAG:
7384 {
7385 Expression* arg = this->one_arg();
7386 if (arg == NULL)
7387 return Type::make_error_type();
7388 Type* t = arg->type();
7389 if (t->is_abstract())
7390 t = t->make_non_abstract_type();
7391 t = Builtin_call_expression::real_imag_type(t);
7392 if (t == NULL)
7393 t = Type::make_error_type();
7394 return t;
7395 }
7396
7397 case BUILTIN_COMPLEX:
7398 {
7399 const Expression_list* args = this->args();
7400 if (args == NULL || args->size() != 2)
7401 return Type::make_error_type();
7402 Type* t = args->front()->type();
7403 if (t->is_abstract())
7404 {
7405 t = args->back()->type();
7406 if (t->is_abstract())
7407 t = t->make_non_abstract_type();
7408 }
7409 t = Builtin_call_expression::complex_type(t);
7410 if (t == NULL)
7411 t = Type::make_error_type();
7412 return t;
7413 }
7414 }
7415 }
7416
7417 // Determine the type.
7418
7419 void
7420 Builtin_call_expression::do_determine_type(const Type_context* context)
7421 {
7422 if (!this->determining_types())
7423 return;
7424
7425 this->fn()->determine_type_no_context();
7426
7427 const Expression_list* args = this->args();
7428
7429 bool is_print;
7430 Type* arg_type = NULL;
7431 switch (this->code_)
7432 {
7433 case BUILTIN_PRINT:
7434 case BUILTIN_PRINTLN:
7435 // Do not force a large integer constant to "int".
7436 is_print = true;
7437 break;
7438
7439 case BUILTIN_REAL:
7440 case BUILTIN_IMAG:
7441 arg_type = Builtin_call_expression::complex_type(context->type);
7442 is_print = false;
7443 break;
7444
7445 case BUILTIN_COMPLEX:
7446 {
7447 // For the complex function the type of one operand can
7448 // determine the type of the other, as in a binary expression.
7449 arg_type = Builtin_call_expression::real_imag_type(context->type);
7450 if (args != NULL && args->size() == 2)
7451 {
7452 Type* t1 = args->front()->type();
7453 Type* t2 = args->front()->type();
7454 if (!t1->is_abstract())
7455 arg_type = t1;
7456 else if (!t2->is_abstract())
7457 arg_type = t2;
7458 }
7459 is_print = false;
7460 }
7461 break;
7462
7463 default:
7464 is_print = false;
7465 break;
7466 }
7467
7468 if (args != NULL)
7469 {
7470 for (Expression_list::const_iterator pa = args->begin();
7471 pa != args->end();
7472 ++pa)
7473 {
7474 Type_context subcontext;
7475 subcontext.type = arg_type;
7476
7477 if (is_print)
7478 {
7479 // We want to print large constants, we so can't just
7480 // use the appropriate nonabstract type. Use uint64 for
7481 // an integer if we know it is nonnegative, otherwise
7482 // use int64 for a integer, otherwise use float64 for a
7483 // float or complex128 for a complex.
7484 Type* want_type = NULL;
7485 Type* atype = (*pa)->type();
7486 if (atype->is_abstract())
7487 {
7488 if (atype->integer_type() != NULL)
7489 {
7490 Numeric_constant nc;
7491 if (this->numeric_constant_value(&nc))
7492 {
7493 mpz_t val;
7494 if (nc.to_int(&val))
7495 {
7496 if (mpz_sgn(val) >= 0)
7497 want_type = Type::lookup_integer_type("uint64");
7498 mpz_clear(val);
7499 }
7500 }
7501 if (want_type == NULL)
7502 want_type = Type::lookup_integer_type("int64");
7503 }
7504 else if (atype->float_type() != NULL)
7505 want_type = Type::lookup_float_type("float64");
7506 else if (atype->complex_type() != NULL)
7507 want_type = Type::lookup_complex_type("complex128");
7508 else if (atype->is_abstract_string_type())
7509 want_type = Type::lookup_string_type();
7510 else if (atype->is_abstract_boolean_type())
7511 want_type = Type::lookup_bool_type();
7512 else
7513 go_unreachable();
7514 subcontext.type = want_type;
7515 }
7516 }
7517
7518 (*pa)->determine_type(&subcontext);
7519 }
7520 }
7521 }
7522
7523 // If there is exactly one argument, return true. Otherwise give an
7524 // error message and return false.
7525
7526 bool
7527 Builtin_call_expression::check_one_arg()
7528 {
7529 const Expression_list* args = this->args();
7530 if (args == NULL || args->size() < 1)
7531 {
7532 this->report_error(_("not enough arguments"));
7533 return false;
7534 }
7535 else if (args->size() > 1)
7536 {
7537 this->report_error(_("too many arguments"));
7538 return false;
7539 }
7540 if (args->front()->is_error_expression()
7541 || args->front()->type()->is_error())
7542 {
7543 this->set_is_error();
7544 return false;
7545 }
7546 return true;
7547 }
7548
7549 // Check argument types for a builtin function.
7550
7551 void
7552 Builtin_call_expression::do_check_types(Gogo*)
7553 {
7554 if (this->is_error_expression())
7555 return;
7556 switch (this->code_)
7557 {
7558 case BUILTIN_INVALID:
7559 case BUILTIN_NEW:
7560 case BUILTIN_MAKE:
7561 case BUILTIN_DELETE:
7562 return;
7563
7564 case BUILTIN_LEN:
7565 case BUILTIN_CAP:
7566 {
7567 // The single argument may be either a string or an array or a
7568 // map or a channel, or a pointer to a closed array.
7569 if (this->check_one_arg())
7570 {
7571 Type* arg_type = this->one_arg()->type();
7572 if (arg_type->points_to() != NULL
7573 && arg_type->points_to()->array_type() != NULL
7574 && !arg_type->points_to()->is_slice_type())
7575 arg_type = arg_type->points_to();
7576 if (this->code_ == BUILTIN_CAP)
7577 {
7578 if (!arg_type->is_error()
7579 && arg_type->array_type() == NULL
7580 && arg_type->channel_type() == NULL)
7581 this->report_error(_("argument must be array or slice "
7582 "or channel"));
7583 }
7584 else
7585 {
7586 if (!arg_type->is_error()
7587 && !arg_type->is_string_type()
7588 && arg_type->array_type() == NULL
7589 && arg_type->map_type() == NULL
7590 && arg_type->channel_type() == NULL)
7591 this->report_error(_("argument must be string or "
7592 "array or slice or map or channel"));
7593 }
7594 }
7595 }
7596 break;
7597
7598 case BUILTIN_PRINT:
7599 case BUILTIN_PRINTLN:
7600 {
7601 const Expression_list* args = this->args();
7602 if (args == NULL)
7603 {
7604 if (this->code_ == BUILTIN_PRINT)
7605 warning_at(this->location(), 0,
7606 "no arguments for builtin function %<%s%>",
7607 (this->code_ == BUILTIN_PRINT
7608 ? "print"
7609 : "println"));
7610 }
7611 else
7612 {
7613 for (Expression_list::const_iterator p = args->begin();
7614 p != args->end();
7615 ++p)
7616 {
7617 Type* type = (*p)->type();
7618 if (type->is_error()
7619 || type->is_string_type()
7620 || type->integer_type() != NULL
7621 || type->float_type() != NULL
7622 || type->complex_type() != NULL
7623 || type->is_boolean_type()
7624 || type->points_to() != NULL
7625 || type->interface_type() != NULL
7626 || type->channel_type() != NULL
7627 || type->map_type() != NULL
7628 || type->function_type() != NULL
7629 || type->is_slice_type())
7630 ;
7631 else if ((*p)->is_type_expression())
7632 {
7633 // If this is a type expression it's going to give
7634 // an error anyhow, so we don't need one here.
7635 }
7636 else
7637 this->report_error(_("unsupported argument type to "
7638 "builtin function"));
7639 }
7640 }
7641 }
7642 break;
7643
7644 case BUILTIN_CLOSE:
7645 if (this->check_one_arg())
7646 {
7647 if (this->one_arg()->type()->channel_type() == NULL)
7648 this->report_error(_("argument must be channel"));
7649 else if (!this->one_arg()->type()->channel_type()->may_send())
7650 this->report_error(_("cannot close receive-only channel"));
7651 }
7652 break;
7653
7654 case BUILTIN_PANIC:
7655 case BUILTIN_SIZEOF:
7656 case BUILTIN_ALIGNOF:
7657 this->check_one_arg();
7658 break;
7659
7660 case BUILTIN_RECOVER:
7661 if (this->args() != NULL && !this->args()->empty())
7662 this->report_error(_("too many arguments"));
7663 break;
7664
7665 case BUILTIN_OFFSETOF:
7666 if (this->check_one_arg())
7667 {
7668 Expression* arg = this->one_arg();
7669 if (arg->field_reference_expression() == NULL)
7670 this->report_error(_("argument must be a field reference"));
7671 }
7672 break;
7673
7674 case BUILTIN_COPY:
7675 {
7676 const Expression_list* args = this->args();
7677 if (args == NULL || args->size() < 2)
7678 {
7679 this->report_error(_("not enough arguments"));
7680 break;
7681 }
7682 else if (args->size() > 2)
7683 {
7684 this->report_error(_("too many arguments"));
7685 break;
7686 }
7687 Type* arg1_type = args->front()->type();
7688 Type* arg2_type = args->back()->type();
7689 if (arg1_type->is_error() || arg2_type->is_error())
7690 break;
7691
7692 Type* e1;
7693 if (arg1_type->is_slice_type())
7694 e1 = arg1_type->array_type()->element_type();
7695 else
7696 {
7697 this->report_error(_("left argument must be a slice"));
7698 break;
7699 }
7700
7701 if (arg2_type->is_slice_type())
7702 {
7703 Type* e2 = arg2_type->array_type()->element_type();
7704 if (!Type::are_identical(e1, e2, true, NULL))
7705 this->report_error(_("element types must be the same"));
7706 }
7707 else if (arg2_type->is_string_type())
7708 {
7709 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7710 this->report_error(_("first argument must be []byte"));
7711 }
7712 else
7713 this->report_error(_("second argument must be slice or string"));
7714 }
7715 break;
7716
7717 case BUILTIN_APPEND:
7718 {
7719 const Expression_list* args = this->args();
7720 if (args == NULL || args->size() < 2)
7721 {
7722 this->report_error(_("not enough arguments"));
7723 break;
7724 }
7725 if (args->size() > 2)
7726 {
7727 this->report_error(_("too many arguments"));
7728 break;
7729 }
7730 if (args->front()->type()->is_error()
7731 || args->back()->type()->is_error())
7732 break;
7733
7734 Array_type* at = args->front()->type()->array_type();
7735 Type* e = at->element_type();
7736
7737 // The language permits appending a string to a []byte, as a
7738 // special case.
7739 if (args->back()->type()->is_string_type())
7740 {
7741 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7742 break;
7743 }
7744
7745 // The language says that the second argument must be
7746 // assignable to a slice of the element type of the first
7747 // argument. We already know the first argument is a slice
7748 // type.
7749 Type* arg2_type = Type::make_array_type(e, NULL);
7750 std::string reason;
7751 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7752 {
7753 if (reason.empty())
7754 this->report_error(_("argument 2 has invalid type"));
7755 else
7756 {
7757 error_at(this->location(), "argument 2 has invalid type (%s)",
7758 reason.c_str());
7759 this->set_is_error();
7760 }
7761 }
7762 break;
7763 }
7764
7765 case BUILTIN_REAL:
7766 case BUILTIN_IMAG:
7767 if (this->check_one_arg())
7768 {
7769 if (this->one_arg()->type()->complex_type() == NULL)
7770 this->report_error(_("argument must have complex type"));
7771 }
7772 break;
7773
7774 case BUILTIN_COMPLEX:
7775 {
7776 const Expression_list* args = this->args();
7777 if (args == NULL || args->size() < 2)
7778 this->report_error(_("not enough arguments"));
7779 else if (args->size() > 2)
7780 this->report_error(_("too many arguments"));
7781 else if (args->front()->is_error_expression()
7782 || args->front()->type()->is_error()
7783 || args->back()->is_error_expression()
7784 || args->back()->type()->is_error())
7785 this->set_is_error();
7786 else if (!Type::are_identical(args->front()->type(),
7787 args->back()->type(), true, NULL))
7788 this->report_error(_("complex arguments must have identical types"));
7789 else if (args->front()->type()->float_type() == NULL)
7790 this->report_error(_("complex arguments must have "
7791 "floating-point type"));
7792 }
7793 break;
7794
7795 default:
7796 go_unreachable();
7797 }
7798 }
7799
7800 // Return the tree for a builtin function.
7801
7802 tree
7803 Builtin_call_expression::do_get_tree(Translate_context* context)
7804 {
7805 Gogo* gogo = context->gogo();
7806 Location location = this->location();
7807 switch (this->code_)
7808 {
7809 case BUILTIN_INVALID:
7810 case BUILTIN_NEW:
7811 case BUILTIN_MAKE:
7812 go_unreachable();
7813
7814 case BUILTIN_LEN:
7815 case BUILTIN_CAP:
7816 {
7817 const Expression_list* args = this->args();
7818 go_assert(args != NULL && args->size() == 1);
7819 Expression* arg = *args->begin();
7820 Type* arg_type = arg->type();
7821
7822 if (this->seen_)
7823 {
7824 go_assert(saw_errors());
7825 return error_mark_node;
7826 }
7827 this->seen_ = true;
7828
7829 tree arg_tree = arg->get_tree(context);
7830
7831 this->seen_ = false;
7832
7833 if (arg_tree == error_mark_node)
7834 return error_mark_node;
7835
7836 if (arg_type->points_to() != NULL)
7837 {
7838 arg_type = arg_type->points_to();
7839 go_assert(arg_type->array_type() != NULL
7840 && !arg_type->is_slice_type());
7841 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7842 arg_tree = build_fold_indirect_ref(arg_tree);
7843 }
7844
7845 tree val_tree;
7846 if (this->code_ == BUILTIN_LEN)
7847 {
7848 if (arg_type->is_string_type())
7849 val_tree = String_type::length_tree(gogo, arg_tree);
7850 else if (arg_type->array_type() != NULL)
7851 {
7852 if (this->seen_)
7853 {
7854 go_assert(saw_errors());
7855 return error_mark_node;
7856 }
7857 this->seen_ = true;
7858 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7859 this->seen_ = false;
7860 }
7861 else if (arg_type->map_type() != NULL)
7862 {
7863 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7864 static tree map_len_fndecl;
7865 val_tree = Gogo::call_builtin(&map_len_fndecl,
7866 location,
7867 "__go_map_len",
7868 1,
7869 integer_type_node,
7870 arg_type_tree,
7871 arg_tree);
7872 }
7873 else if (arg_type->channel_type() != NULL)
7874 {
7875 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7876 static tree chan_len_fndecl;
7877 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7878 location,
7879 "__go_chan_len",
7880 1,
7881 integer_type_node,
7882 arg_type_tree,
7883 arg_tree);
7884 }
7885 else
7886 go_unreachable();
7887 }
7888 else
7889 {
7890 if (arg_type->array_type() != NULL)
7891 {
7892 if (this->seen_)
7893 {
7894 go_assert(saw_errors());
7895 return error_mark_node;
7896 }
7897 this->seen_ = true;
7898 val_tree = arg_type->array_type()->capacity_tree(gogo,
7899 arg_tree);
7900 this->seen_ = false;
7901 }
7902 else if (arg_type->channel_type() != NULL)
7903 {
7904 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7905 static tree chan_cap_fndecl;
7906 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7907 location,
7908 "__go_chan_cap",
7909 1,
7910 integer_type_node,
7911 arg_type_tree,
7912 arg_tree);
7913 }
7914 else
7915 go_unreachable();
7916 }
7917
7918 if (val_tree == error_mark_node)
7919 return error_mark_node;
7920
7921 Type* int_type = Type::lookup_integer_type("int");
7922 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7923 if (type_tree == TREE_TYPE(val_tree))
7924 return val_tree;
7925 else
7926 return fold(convert_to_integer(type_tree, val_tree));
7927 }
7928
7929 case BUILTIN_PRINT:
7930 case BUILTIN_PRINTLN:
7931 {
7932 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7933 tree stmt_list = NULL_TREE;
7934
7935 const Expression_list* call_args = this->args();
7936 if (call_args != NULL)
7937 {
7938 for (Expression_list::const_iterator p = call_args->begin();
7939 p != call_args->end();
7940 ++p)
7941 {
7942 if (is_ln && p != call_args->begin())
7943 {
7944 static tree print_space_fndecl;
7945 tree call = Gogo::call_builtin(&print_space_fndecl,
7946 location,
7947 "__go_print_space",
7948 0,
7949 void_type_node);
7950 if (call == error_mark_node)
7951 return error_mark_node;
7952 append_to_statement_list(call, &stmt_list);
7953 }
7954
7955 Type* type = (*p)->type();
7956
7957 tree arg = (*p)->get_tree(context);
7958 if (arg == error_mark_node)
7959 return error_mark_node;
7960
7961 tree* pfndecl;
7962 const char* fnname;
7963 if (type->is_string_type())
7964 {
7965 static tree print_string_fndecl;
7966 pfndecl = &print_string_fndecl;
7967 fnname = "__go_print_string";
7968 }
7969 else if (type->integer_type() != NULL
7970 && type->integer_type()->is_unsigned())
7971 {
7972 static tree print_uint64_fndecl;
7973 pfndecl = &print_uint64_fndecl;
7974 fnname = "__go_print_uint64";
7975 Type* itype = Type::lookup_integer_type("uint64");
7976 Btype* bitype = itype->get_backend(gogo);
7977 arg = fold_convert_loc(location.gcc_location(),
7978 type_to_tree(bitype), arg);
7979 }
7980 else if (type->integer_type() != NULL)
7981 {
7982 static tree print_int64_fndecl;
7983 pfndecl = &print_int64_fndecl;
7984 fnname = "__go_print_int64";
7985 Type* itype = Type::lookup_integer_type("int64");
7986 Btype* bitype = itype->get_backend(gogo);
7987 arg = fold_convert_loc(location.gcc_location(),
7988 type_to_tree(bitype), arg);
7989 }
7990 else if (type->float_type() != NULL)
7991 {
7992 static tree print_double_fndecl;
7993 pfndecl = &print_double_fndecl;
7994 fnname = "__go_print_double";
7995 arg = fold_convert_loc(location.gcc_location(),
7996 double_type_node, arg);
7997 }
7998 else if (type->complex_type() != NULL)
7999 {
8000 static tree print_complex_fndecl;
8001 pfndecl = &print_complex_fndecl;
8002 fnname = "__go_print_complex";
8003 arg = fold_convert_loc(location.gcc_location(),
8004 complex_double_type_node, arg);
8005 }
8006 else if (type->is_boolean_type())
8007 {
8008 static tree print_bool_fndecl;
8009 pfndecl = &print_bool_fndecl;
8010 fnname = "__go_print_bool";
8011 }
8012 else if (type->points_to() != NULL
8013 || type->channel_type() != NULL
8014 || type->map_type() != NULL
8015 || type->function_type() != NULL)
8016 {
8017 static tree print_pointer_fndecl;
8018 pfndecl = &print_pointer_fndecl;
8019 fnname = "__go_print_pointer";
8020 arg = fold_convert_loc(location.gcc_location(),
8021 ptr_type_node, arg);
8022 }
8023 else if (type->interface_type() != NULL)
8024 {
8025 if (type->interface_type()->is_empty())
8026 {
8027 static tree print_empty_interface_fndecl;
8028 pfndecl = &print_empty_interface_fndecl;
8029 fnname = "__go_print_empty_interface";
8030 }
8031 else
8032 {
8033 static tree print_interface_fndecl;
8034 pfndecl = &print_interface_fndecl;
8035 fnname = "__go_print_interface";
8036 }
8037 }
8038 else if (type->is_slice_type())
8039 {
8040 static tree print_slice_fndecl;
8041 pfndecl = &print_slice_fndecl;
8042 fnname = "__go_print_slice";
8043 }
8044 else
8045 {
8046 go_assert(saw_errors());
8047 return error_mark_node;
8048 }
8049
8050 tree call = Gogo::call_builtin(pfndecl,
8051 location,
8052 fnname,
8053 1,
8054 void_type_node,
8055 TREE_TYPE(arg),
8056 arg);
8057 if (call == error_mark_node)
8058 return error_mark_node;
8059 append_to_statement_list(call, &stmt_list);
8060 }
8061 }
8062
8063 if (is_ln)
8064 {
8065 static tree print_nl_fndecl;
8066 tree call = Gogo::call_builtin(&print_nl_fndecl,
8067 location,
8068 "__go_print_nl",
8069 0,
8070 void_type_node);
8071 if (call == error_mark_node)
8072 return error_mark_node;
8073 append_to_statement_list(call, &stmt_list);
8074 }
8075
8076 return stmt_list;
8077 }
8078
8079 case BUILTIN_PANIC:
8080 {
8081 const Expression_list* args = this->args();
8082 go_assert(args != NULL && args->size() == 1);
8083 Expression* arg = args->front();
8084 tree arg_tree = arg->get_tree(context);
8085 if (arg_tree == error_mark_node)
8086 return error_mark_node;
8087 Type *empty =
8088 Type::make_empty_interface_type(Linemap::predeclared_location());
8089 arg_tree = Expression::convert_for_assignment(context, empty,
8090 arg->type(),
8091 arg_tree, location);
8092 static tree panic_fndecl;
8093 tree call = Gogo::call_builtin(&panic_fndecl,
8094 location,
8095 "__go_panic",
8096 1,
8097 void_type_node,
8098 TREE_TYPE(arg_tree),
8099 arg_tree);
8100 if (call == error_mark_node)
8101 return error_mark_node;
8102 // This function will throw an exception.
8103 TREE_NOTHROW(panic_fndecl) = 0;
8104 // This function will not return.
8105 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8106 return call;
8107 }
8108
8109 case BUILTIN_RECOVER:
8110 {
8111 // The argument is set when building recover thunks. It's a
8112 // boolean value which is true if we can recover a value now.
8113 const Expression_list* args = this->args();
8114 go_assert(args != NULL && args->size() == 1);
8115 Expression* arg = args->front();
8116 tree arg_tree = arg->get_tree(context);
8117 if (arg_tree == error_mark_node)
8118 return error_mark_node;
8119
8120 Type *empty =
8121 Type::make_empty_interface_type(Linemap::predeclared_location());
8122 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8123
8124 Type* nil_type = Type::make_nil_type();
8125 Expression* nil = Expression::make_nil(location);
8126 tree nil_tree = nil->get_tree(context);
8127 tree empty_nil_tree = Expression::convert_for_assignment(context,
8128 empty,
8129 nil_type,
8130 nil_tree,
8131 location);
8132
8133 // We need to handle a deferred call to recover specially,
8134 // because it changes whether it can recover a panic or not.
8135 // See test7 in test/recover1.go.
8136 tree call;
8137 if (this->is_deferred())
8138 {
8139 static tree deferred_recover_fndecl;
8140 call = Gogo::call_builtin(&deferred_recover_fndecl,
8141 location,
8142 "__go_deferred_recover",
8143 0,
8144 empty_tree);
8145 }
8146 else
8147 {
8148 static tree recover_fndecl;
8149 call = Gogo::call_builtin(&recover_fndecl,
8150 location,
8151 "__go_recover",
8152 0,
8153 empty_tree);
8154 }
8155 if (call == error_mark_node)
8156 return error_mark_node;
8157 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8158 arg_tree, call, empty_nil_tree);
8159 }
8160
8161 case BUILTIN_CLOSE:
8162 {
8163 const Expression_list* args = this->args();
8164 go_assert(args != NULL && args->size() == 1);
8165 Expression* arg = args->front();
8166 tree arg_tree = arg->get_tree(context);
8167 if (arg_tree == error_mark_node)
8168 return error_mark_node;
8169 static tree close_fndecl;
8170 return Gogo::call_builtin(&close_fndecl,
8171 location,
8172 "__go_builtin_close",
8173 1,
8174 void_type_node,
8175 TREE_TYPE(arg_tree),
8176 arg_tree);
8177 }
8178
8179 case BUILTIN_SIZEOF:
8180 case BUILTIN_OFFSETOF:
8181 case BUILTIN_ALIGNOF:
8182 {
8183 Numeric_constant nc;
8184 unsigned long val;
8185 if (!this->numeric_constant_value(&nc)
8186 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8187 {
8188 go_assert(saw_errors());
8189 return error_mark_node;
8190 }
8191 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8192 tree type = type_to_tree(uintptr_type->get_backend(gogo));
8193 return build_int_cst(type, val);
8194 }
8195
8196 case BUILTIN_COPY:
8197 {
8198 const Expression_list* args = this->args();
8199 go_assert(args != NULL && args->size() == 2);
8200 Expression* arg1 = args->front();
8201 Expression* arg2 = args->back();
8202
8203 tree arg1_tree = arg1->get_tree(context);
8204 tree arg2_tree = arg2->get_tree(context);
8205 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8206 return error_mark_node;
8207
8208 Type* arg1_type = arg1->type();
8209 Array_type* at = arg1_type->array_type();
8210 arg1_tree = save_expr(arg1_tree);
8211 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8212 tree arg1_len = at->length_tree(gogo, arg1_tree);
8213 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8214 return error_mark_node;
8215
8216 Type* arg2_type = arg2->type();
8217 tree arg2_val;
8218 tree arg2_len;
8219 if (arg2_type->is_slice_type())
8220 {
8221 at = arg2_type->array_type();
8222 arg2_tree = save_expr(arg2_tree);
8223 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8224 arg2_len = at->length_tree(gogo, arg2_tree);
8225 }
8226 else
8227 {
8228 arg2_tree = save_expr(arg2_tree);
8229 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8230 arg2_len = String_type::length_tree(gogo, arg2_tree);
8231 }
8232 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8233 return error_mark_node;
8234
8235 arg1_len = save_expr(arg1_len);
8236 arg2_len = save_expr(arg2_len);
8237 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8238 TREE_TYPE(arg1_len),
8239 fold_build2_loc(location.gcc_location(),
8240 LT_EXPR, boolean_type_node,
8241 arg1_len, arg2_len),
8242 arg1_len, arg2_len);
8243 len = save_expr(len);
8244
8245 Type* element_type = at->element_type();
8246 Btype* element_btype = element_type->get_backend(gogo);
8247 tree element_type_tree = type_to_tree(element_btype);
8248 if (element_type_tree == error_mark_node)
8249 return error_mark_node;
8250 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8251 tree bytecount = fold_convert_loc(location.gcc_location(),
8252 TREE_TYPE(element_size), len);
8253 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8254 TREE_TYPE(element_size),
8255 bytecount, element_size);
8256 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8257 bytecount);
8258
8259 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8260 arg1_val);
8261 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8262 arg2_val);
8263
8264 static tree copy_fndecl;
8265 tree call = Gogo::call_builtin(&copy_fndecl,
8266 location,
8267 "__go_copy",
8268 3,
8269 void_type_node,
8270 ptr_type_node,
8271 arg1_val,
8272 ptr_type_node,
8273 arg2_val,
8274 size_type_node,
8275 bytecount);
8276 if (call == error_mark_node)
8277 return error_mark_node;
8278
8279 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8280 TREE_TYPE(len), call, len);
8281 }
8282
8283 case BUILTIN_APPEND:
8284 {
8285 const Expression_list* args = this->args();
8286 go_assert(args != NULL && args->size() == 2);
8287 Expression* arg1 = args->front();
8288 Expression* arg2 = args->back();
8289
8290 tree arg1_tree = arg1->get_tree(context);
8291 tree arg2_tree = arg2->get_tree(context);
8292 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8293 return error_mark_node;
8294
8295 Array_type* at = arg1->type()->array_type();
8296 Type* element_type = at->element_type()->forwarded();
8297
8298 tree arg2_val;
8299 tree arg2_len;
8300 tree element_size;
8301 if (arg2->type()->is_string_type()
8302 && element_type->integer_type() != NULL
8303 && element_type->integer_type()->is_byte())
8304 {
8305 arg2_tree = save_expr(arg2_tree);
8306 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8307 arg2_len = String_type::length_tree(gogo, arg2_tree);
8308 element_size = size_int(1);
8309 }
8310 else
8311 {
8312 arg2_tree = Expression::convert_for_assignment(context, at,
8313 arg2->type(),
8314 arg2_tree,
8315 location);
8316 if (arg2_tree == error_mark_node)
8317 return error_mark_node;
8318
8319 arg2_tree = save_expr(arg2_tree);
8320
8321 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8322 arg2_len = at->length_tree(gogo, arg2_tree);
8323
8324 Btype* element_btype = element_type->get_backend(gogo);
8325 tree element_type_tree = type_to_tree(element_btype);
8326 if (element_type_tree == error_mark_node)
8327 return error_mark_node;
8328 element_size = TYPE_SIZE_UNIT(element_type_tree);
8329 }
8330
8331 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8332 arg2_val);
8333 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8334 arg2_len);
8335 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8336 element_size);
8337
8338 if (arg2_val == error_mark_node
8339 || arg2_len == error_mark_node
8340 || element_size == error_mark_node)
8341 return error_mark_node;
8342
8343 // We rebuild the decl each time since the slice types may
8344 // change.
8345 tree append_fndecl = NULL_TREE;
8346 return Gogo::call_builtin(&append_fndecl,
8347 location,
8348 "__go_append",
8349 4,
8350 TREE_TYPE(arg1_tree),
8351 TREE_TYPE(arg1_tree),
8352 arg1_tree,
8353 ptr_type_node,
8354 arg2_val,
8355 size_type_node,
8356 arg2_len,
8357 size_type_node,
8358 element_size);
8359 }
8360
8361 case BUILTIN_REAL:
8362 case BUILTIN_IMAG:
8363 {
8364 const Expression_list* args = this->args();
8365 go_assert(args != NULL && args->size() == 1);
8366 Expression* arg = args->front();
8367 tree arg_tree = arg->get_tree(context);
8368 if (arg_tree == error_mark_node)
8369 return error_mark_node;
8370 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8371 if (this->code_ == BUILTIN_REAL)
8372 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8373 TREE_TYPE(TREE_TYPE(arg_tree)),
8374 arg_tree);
8375 else
8376 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8377 TREE_TYPE(TREE_TYPE(arg_tree)),
8378 arg_tree);
8379 }
8380
8381 case BUILTIN_COMPLEX:
8382 {
8383 const Expression_list* args = this->args();
8384 go_assert(args != NULL && args->size() == 2);
8385 tree r = args->front()->get_tree(context);
8386 tree i = args->back()->get_tree(context);
8387 if (r == error_mark_node || i == error_mark_node)
8388 return error_mark_node;
8389 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8390 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8391 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8392 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8393 build_complex_type(TREE_TYPE(r)),
8394 r, i);
8395 }
8396
8397 default:
8398 go_unreachable();
8399 }
8400 }
8401
8402 // We have to support exporting a builtin call expression, because
8403 // code can set a constant to the result of a builtin expression.
8404
8405 void
8406 Builtin_call_expression::do_export(Export* exp) const
8407 {
8408 Numeric_constant nc;
8409 if (!this->numeric_constant_value(&nc))
8410 {
8411 error_at(this->location(), "value is not constant");
8412 return;
8413 }
8414
8415 if (nc.is_int())
8416 {
8417 mpz_t val;
8418 nc.get_int(&val);
8419 Integer_expression::export_integer(exp, val);
8420 mpz_clear(val);
8421 }
8422 else if (nc.is_float())
8423 {
8424 mpfr_t fval;
8425 nc.get_float(&fval);
8426 Float_expression::export_float(exp, fval);
8427 mpfr_clear(fval);
8428 }
8429 else if (nc.is_complex())
8430 {
8431 mpfr_t real;
8432 mpfr_t imag;
8433 Complex_expression::export_complex(exp, real, imag);
8434 mpfr_clear(real);
8435 mpfr_clear(imag);
8436 }
8437 else
8438 go_unreachable();
8439
8440 // A trailing space lets us reliably identify the end of the number.
8441 exp->write_c_string(" ");
8442 }
8443
8444 // Class Call_expression.
8445
8446 // Traversal.
8447
8448 int
8449 Call_expression::do_traverse(Traverse* traverse)
8450 {
8451 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8452 return TRAVERSE_EXIT;
8453 if (this->args_ != NULL)
8454 {
8455 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8456 return TRAVERSE_EXIT;
8457 }
8458 return TRAVERSE_CONTINUE;
8459 }
8460
8461 // Lower a call statement.
8462
8463 Expression*
8464 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8465 Statement_inserter* inserter, int)
8466 {
8467 Location loc = this->location();
8468
8469 // A type cast can look like a function call.
8470 if (this->fn_->is_type_expression()
8471 && this->args_ != NULL
8472 && this->args_->size() == 1)
8473 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8474 loc);
8475
8476 // Recognize a call to a builtin function.
8477 Func_expression* fne = this->fn_->func_expression();
8478 if (fne != NULL
8479 && fne->named_object()->is_function_declaration()
8480 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8481 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8482 this->is_varargs_, loc);
8483
8484 // Handle an argument which is a call to a function which returns
8485 // multiple results.
8486 if (this->args_ != NULL
8487 && this->args_->size() == 1
8488 && this->args_->front()->call_expression() != NULL
8489 && this->fn_->type()->function_type() != NULL)
8490 {
8491 Function_type* fntype = this->fn_->type()->function_type();
8492 size_t rc = this->args_->front()->call_expression()->result_count();
8493 if (rc > 1
8494 && fntype->parameters() != NULL
8495 && (fntype->parameters()->size() == rc
8496 || (fntype->is_varargs()
8497 && fntype->parameters()->size() - 1 <= rc)))
8498 {
8499 Call_expression* call = this->args_->front()->call_expression();
8500 Expression_list* args = new Expression_list;
8501 for (size_t i = 0; i < rc; ++i)
8502 args->push_back(Expression::make_call_result(call, i));
8503 // We can't return a new call expression here, because this
8504 // one may be referenced by Call_result expressions. We
8505 // also can't delete the old arguments, because we may still
8506 // traverse them somewhere up the call stack. FIXME.
8507 this->args_ = args;
8508 }
8509 }
8510
8511 // If this call returns multiple results, create a temporary
8512 // variable for each result.
8513 size_t rc = this->result_count();
8514 if (rc > 1 && this->results_ == NULL)
8515 {
8516 std::vector<Temporary_statement*>* temps =
8517 new std::vector<Temporary_statement*>;
8518 temps->reserve(rc);
8519 const Typed_identifier_list* results =
8520 this->fn_->type()->function_type()->results();
8521 for (Typed_identifier_list::const_iterator p = results->begin();
8522 p != results->end();
8523 ++p)
8524 {
8525 Temporary_statement* temp = Statement::make_temporary(p->type(),
8526 NULL, loc);
8527 inserter->insert(temp);
8528 temps->push_back(temp);
8529 }
8530 this->results_ = temps;
8531 }
8532
8533 // Handle a call to a varargs function by packaging up the extra
8534 // parameters.
8535 if (this->fn_->type()->function_type() != NULL
8536 && this->fn_->type()->function_type()->is_varargs())
8537 {
8538 Function_type* fntype = this->fn_->type()->function_type();
8539 const Typed_identifier_list* parameters = fntype->parameters();
8540 go_assert(parameters != NULL && !parameters->empty());
8541 Type* varargs_type = parameters->back().type();
8542 this->lower_varargs(gogo, function, inserter, varargs_type,
8543 parameters->size());
8544 }
8545
8546 // If this is call to a method, call the method directly passing the
8547 // object as the first parameter.
8548 Bound_method_expression* bme = this->fn_->bound_method_expression();
8549 if (bme != NULL)
8550 {
8551 Named_object* method = bme->method();
8552 Expression* first_arg = bme->first_argument();
8553
8554 // We always pass a pointer when calling a method.
8555 if (first_arg->type()->points_to() == NULL
8556 && !first_arg->type()->is_error())
8557 {
8558 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8559 // We may need to create a temporary variable so that we can
8560 // take the address. We can't do that here because it will
8561 // mess up the order of evaluation.
8562 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8563 ue->set_create_temp();
8564 }
8565
8566 // If we are calling a method which was inherited from an
8567 // embedded struct, and the method did not get a stub, then the
8568 // first type may be wrong.
8569 Type* fatype = bme->first_argument_type();
8570 if (fatype != NULL)
8571 {
8572 if (fatype->points_to() == NULL)
8573 fatype = Type::make_pointer_type(fatype);
8574 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8575 }
8576
8577 Expression_list* new_args = new Expression_list();
8578 new_args->push_back(first_arg);
8579 if (this->args_ != NULL)
8580 {
8581 for (Expression_list::const_iterator p = this->args_->begin();
8582 p != this->args_->end();
8583 ++p)
8584 new_args->push_back(*p);
8585 }
8586
8587 // We have to change in place because this structure may be
8588 // referenced by Call_result_expressions. We can't delete the
8589 // old arguments, because we may be traversing them up in some
8590 // caller. FIXME.
8591 this->args_ = new_args;
8592 this->fn_ = Expression::make_func_reference(method, NULL,
8593 bme->location());
8594 }
8595
8596 return this;
8597 }
8598
8599 // Lower a call to a varargs function. FUNCTION is the function in
8600 // which the call occurs--it's not the function we are calling.
8601 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8602 // PARAM_COUNT is the number of parameters of the function we are
8603 // calling; the last of these parameters will be the varargs
8604 // parameter.
8605
8606 void
8607 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8608 Statement_inserter* inserter,
8609 Type* varargs_type, size_t param_count)
8610 {
8611 if (this->varargs_are_lowered_)
8612 return;
8613
8614 Location loc = this->location();
8615
8616 go_assert(param_count > 0);
8617 go_assert(varargs_type->is_slice_type());
8618
8619 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8620 if (arg_count < param_count - 1)
8621 {
8622 // Not enough arguments; will be caught in check_types.
8623 return;
8624 }
8625
8626 Expression_list* old_args = this->args_;
8627 Expression_list* new_args = new Expression_list();
8628 bool push_empty_arg = false;
8629 if (old_args == NULL || old_args->empty())
8630 {
8631 go_assert(param_count == 1);
8632 push_empty_arg = true;
8633 }
8634 else
8635 {
8636 Expression_list::const_iterator pa;
8637 int i = 1;
8638 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8639 {
8640 if (static_cast<size_t>(i) == param_count)
8641 break;
8642 new_args->push_back(*pa);
8643 }
8644
8645 // We have reached the varargs parameter.
8646
8647 bool issued_error = false;
8648 if (pa == old_args->end())
8649 push_empty_arg = true;
8650 else if (pa + 1 == old_args->end() && this->is_varargs_)
8651 new_args->push_back(*pa);
8652 else if (this->is_varargs_)
8653 {
8654 if ((*pa)->type()->is_slice_type())
8655 this->report_error(_("too many arguments"));
8656 else
8657 {
8658 error_at(this->location(),
8659 _("invalid use of %<...%> with non-slice"));
8660 this->set_is_error();
8661 }
8662 return;
8663 }
8664 else
8665 {
8666 Type* element_type = varargs_type->array_type()->element_type();
8667 Expression_list* vals = new Expression_list;
8668 for (; pa != old_args->end(); ++pa, ++i)
8669 {
8670 // Check types here so that we get a better message.
8671 Type* patype = (*pa)->type();
8672 Location paloc = (*pa)->location();
8673 if (!this->check_argument_type(i, element_type, patype,
8674 paloc, issued_error))
8675 continue;
8676 vals->push_back(*pa);
8677 }
8678 Expression* val =
8679 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8680 gogo->lower_expression(function, inserter, &val);
8681 new_args->push_back(val);
8682 }
8683 }
8684
8685 if (push_empty_arg)
8686 new_args->push_back(Expression::make_nil(loc));
8687
8688 // We can't return a new call expression here, because this one may
8689 // be referenced by Call_result expressions. FIXME. We can't
8690 // delete OLD_ARGS because we may have both a Call_expression and a
8691 // Builtin_call_expression which refer to them. FIXME.
8692 this->args_ = new_args;
8693 this->varargs_are_lowered_ = true;
8694 }
8695
8696 // Get the function type. This can return NULL in error cases.
8697
8698 Function_type*
8699 Call_expression::get_function_type() const
8700 {
8701 return this->fn_->type()->function_type();
8702 }
8703
8704 // Return the number of values which this call will return.
8705
8706 size_t
8707 Call_expression::result_count() const
8708 {
8709 const Function_type* fntype = this->get_function_type();
8710 if (fntype == NULL)
8711 return 0;
8712 if (fntype->results() == NULL)
8713 return 0;
8714 return fntype->results()->size();
8715 }
8716
8717 // Return the temporary which holds a result.
8718
8719 Temporary_statement*
8720 Call_expression::result(size_t i) const
8721 {
8722 if (this->results_ == NULL || this->results_->size() <= i)
8723 {
8724 go_assert(saw_errors());
8725 return NULL;
8726 }
8727 return (*this->results_)[i];
8728 }
8729
8730 // Return whether this is a call to the predeclared function recover.
8731
8732 bool
8733 Call_expression::is_recover_call() const
8734 {
8735 return this->do_is_recover_call();
8736 }
8737
8738 // Set the argument to the recover function.
8739
8740 void
8741 Call_expression::set_recover_arg(Expression* arg)
8742 {
8743 this->do_set_recover_arg(arg);
8744 }
8745
8746 // Virtual functions also implemented by Builtin_call_expression.
8747
8748 bool
8749 Call_expression::do_is_recover_call() const
8750 {
8751 return false;
8752 }
8753
8754 void
8755 Call_expression::do_set_recover_arg(Expression*)
8756 {
8757 go_unreachable();
8758 }
8759
8760 // We have found an error with this call expression; return true if
8761 // we should report it.
8762
8763 bool
8764 Call_expression::issue_error()
8765 {
8766 if (this->issued_error_)
8767 return false;
8768 else
8769 {
8770 this->issued_error_ = true;
8771 return true;
8772 }
8773 }
8774
8775 // Get the type.
8776
8777 Type*
8778 Call_expression::do_type()
8779 {
8780 if (this->type_ != NULL)
8781 return this->type_;
8782
8783 Type* ret;
8784 Function_type* fntype = this->get_function_type();
8785 if (fntype == NULL)
8786 return Type::make_error_type();
8787
8788 const Typed_identifier_list* results = fntype->results();
8789 if (results == NULL)
8790 ret = Type::make_void_type();
8791 else if (results->size() == 1)
8792 ret = results->begin()->type();
8793 else
8794 ret = Type::make_call_multiple_result_type(this);
8795
8796 this->type_ = ret;
8797
8798 return this->type_;
8799 }
8800
8801 // Determine types for a call expression. We can use the function
8802 // parameter types to set the types of the arguments.
8803
8804 void
8805 Call_expression::do_determine_type(const Type_context*)
8806 {
8807 if (!this->determining_types())
8808 return;
8809
8810 this->fn_->determine_type_no_context();
8811 Function_type* fntype = this->get_function_type();
8812 const Typed_identifier_list* parameters = NULL;
8813 if (fntype != NULL)
8814 parameters = fntype->parameters();
8815 if (this->args_ != NULL)
8816 {
8817 Typed_identifier_list::const_iterator pt;
8818 if (parameters != NULL)
8819 pt = parameters->begin();
8820 bool first = true;
8821 for (Expression_list::const_iterator pa = this->args_->begin();
8822 pa != this->args_->end();
8823 ++pa)
8824 {
8825 if (first)
8826 {
8827 first = false;
8828 // If this is a method, the first argument is the
8829 // receiver.
8830 if (fntype != NULL && fntype->is_method())
8831 {
8832 Type* rtype = fntype->receiver()->type();
8833 // The receiver is always passed as a pointer.
8834 if (rtype->points_to() == NULL)
8835 rtype = Type::make_pointer_type(rtype);
8836 Type_context subcontext(rtype, false);
8837 (*pa)->determine_type(&subcontext);
8838 continue;
8839 }
8840 }
8841
8842 if (parameters != NULL && pt != parameters->end())
8843 {
8844 Type_context subcontext(pt->type(), false);
8845 (*pa)->determine_type(&subcontext);
8846 ++pt;
8847 }
8848 else
8849 (*pa)->determine_type_no_context();
8850 }
8851 }
8852 }
8853
8854 // Called when determining types for a Call_expression. Return true
8855 // if we should go ahead, false if they have already been determined.
8856
8857 bool
8858 Call_expression::determining_types()
8859 {
8860 if (this->types_are_determined_)
8861 return false;
8862 else
8863 {
8864 this->types_are_determined_ = true;
8865 return true;
8866 }
8867 }
8868
8869 // Check types for parameter I.
8870
8871 bool
8872 Call_expression::check_argument_type(int i, const Type* parameter_type,
8873 const Type* argument_type,
8874 Location argument_location,
8875 bool issued_error)
8876 {
8877 std::string reason;
8878 bool ok;
8879 if (this->are_hidden_fields_ok_)
8880 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8881 &reason);
8882 else
8883 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8884 if (!ok)
8885 {
8886 if (!issued_error)
8887 {
8888 if (reason.empty())
8889 error_at(argument_location, "argument %d has incompatible type", i);
8890 else
8891 error_at(argument_location,
8892 "argument %d has incompatible type (%s)",
8893 i, reason.c_str());
8894 }
8895 this->set_is_error();
8896 return false;
8897 }
8898 return true;
8899 }
8900
8901 // Check types.
8902
8903 void
8904 Call_expression::do_check_types(Gogo*)
8905 {
8906 if (this->classification() == EXPRESSION_ERROR)
8907 return;
8908
8909 Function_type* fntype = this->get_function_type();
8910 if (fntype == NULL)
8911 {
8912 if (!this->fn_->type()->is_error())
8913 this->report_error(_("expected function"));
8914 return;
8915 }
8916
8917 bool is_method = fntype->is_method();
8918 if (is_method)
8919 {
8920 go_assert(this->args_ != NULL && !this->args_->empty());
8921 Type* rtype = fntype->receiver()->type();
8922 Expression* first_arg = this->args_->front();
8923 // The language permits copying hidden fields for a method
8924 // receiver. We dereference the values since receivers are
8925 // always passed as pointers.
8926 std::string reason;
8927 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8928 first_arg->type()->deref(),
8929 &reason))
8930 {
8931 if (reason.empty())
8932 this->report_error(_("incompatible type for receiver"));
8933 else
8934 {
8935 error_at(this->location(),
8936 "incompatible type for receiver (%s)",
8937 reason.c_str());
8938 this->set_is_error();
8939 }
8940 }
8941 }
8942
8943 // Note that varargs was handled by the lower_varargs() method, so
8944 // we don't have to worry about it here unless something is wrong.
8945 if (this->is_varargs_ && !this->varargs_are_lowered_)
8946 {
8947 if (!fntype->is_varargs())
8948 {
8949 error_at(this->location(),
8950 _("invalid use of %<...%> calling non-variadic function"));
8951 this->set_is_error();
8952 return;
8953 }
8954 }
8955
8956 const Typed_identifier_list* parameters = fntype->parameters();
8957 if (this->args_ == NULL)
8958 {
8959 if (parameters != NULL && !parameters->empty())
8960 this->report_error(_("not enough arguments"));
8961 }
8962 else if (parameters == NULL)
8963 {
8964 if (!is_method || this->args_->size() > 1)
8965 this->report_error(_("too many arguments"));
8966 }
8967 else
8968 {
8969 int i = 0;
8970 Expression_list::const_iterator pa = this->args_->begin();
8971 if (is_method)
8972 ++pa;
8973 for (Typed_identifier_list::const_iterator pt = parameters->begin();
8974 pt != parameters->end();
8975 ++pt, ++pa, ++i)
8976 {
8977 if (pa == this->args_->end())
8978 {
8979 this->report_error(_("not enough arguments"));
8980 return;
8981 }
8982 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8983 (*pa)->location(), false);
8984 }
8985 if (pa != this->args_->end())
8986 this->report_error(_("too many arguments"));
8987 }
8988 }
8989
8990 // Return whether we have to use a temporary variable to ensure that
8991 // we evaluate this call expression in order. If the call returns no
8992 // results then it will inevitably be executed last.
8993
8994 bool
8995 Call_expression::do_must_eval_in_order() const
8996 {
8997 return this->result_count() > 0;
8998 }
8999
9000 // Get the function and the first argument to use when calling an
9001 // interface method.
9002
9003 tree
9004 Call_expression::interface_method_function(
9005 Translate_context* context,
9006 Interface_field_reference_expression* interface_method,
9007 tree* first_arg_ptr)
9008 {
9009 tree expr = interface_method->expr()->get_tree(context);
9010 if (expr == error_mark_node)
9011 return error_mark_node;
9012 expr = save_expr(expr);
9013 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9014 if (first_arg == error_mark_node)
9015 return error_mark_node;
9016 *first_arg_ptr = first_arg;
9017 return interface_method->get_function_tree(context, expr);
9018 }
9019
9020 // Build the call expression.
9021
9022 tree
9023 Call_expression::do_get_tree(Translate_context* context)
9024 {
9025 if (this->tree_ != NULL_TREE)
9026 return this->tree_;
9027
9028 Function_type* fntype = this->get_function_type();
9029 if (fntype == NULL)
9030 return error_mark_node;
9031
9032 if (this->fn_->is_error_expression())
9033 return error_mark_node;
9034
9035 Gogo* gogo = context->gogo();
9036 Location location = this->location();
9037
9038 Func_expression* func = this->fn_->func_expression();
9039 Interface_field_reference_expression* interface_method =
9040 this->fn_->interface_field_reference_expression();
9041 const bool has_closure = func != NULL && func->closure() != NULL;
9042 const bool is_interface_method = interface_method != NULL;
9043
9044 int nargs;
9045 tree* args;
9046 if (this->args_ == NULL || this->args_->empty())
9047 {
9048 nargs = is_interface_method ? 1 : 0;
9049 args = nargs == 0 ? NULL : new tree[nargs];
9050 }
9051 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9052 {
9053 // Passing a receiver parameter.
9054 go_assert(!is_interface_method
9055 && fntype->is_method()
9056 && this->args_->size() == 1);
9057 nargs = 1;
9058 args = new tree[nargs];
9059 args[0] = this->args_->front()->get_tree(context);
9060 }
9061 else
9062 {
9063 const Typed_identifier_list* params = fntype->parameters();
9064
9065 nargs = this->args_->size();
9066 int i = is_interface_method ? 1 : 0;
9067 nargs += i;
9068 args = new tree[nargs];
9069
9070 Typed_identifier_list::const_iterator pp = params->begin();
9071 Expression_list::const_iterator pe = this->args_->begin();
9072 if (!is_interface_method && fntype->is_method())
9073 {
9074 args[i] = (*pe)->get_tree(context);
9075 ++pe;
9076 ++i;
9077 }
9078 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9079 {
9080 go_assert(pp != params->end());
9081 tree arg_val = (*pe)->get_tree(context);
9082 args[i] = Expression::convert_for_assignment(context,
9083 pp->type(),
9084 (*pe)->type(),
9085 arg_val,
9086 location);
9087 if (args[i] == error_mark_node)
9088 {
9089 delete[] args;
9090 return error_mark_node;
9091 }
9092 }
9093 go_assert(pp == params->end());
9094 go_assert(i == nargs);
9095 }
9096
9097 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
9098 if (rettype == error_mark_node)
9099 {
9100 delete[] args;
9101 return error_mark_node;
9102 }
9103
9104 tree fn;
9105 if (has_closure)
9106 fn = func->get_tree_without_closure(gogo);
9107 else if (!is_interface_method)
9108 fn = this->fn_->get_tree(context);
9109 else
9110 fn = this->interface_method_function(context, interface_method, &args[0]);
9111
9112 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9113 {
9114 delete[] args;
9115 return error_mark_node;
9116 }
9117
9118 tree fndecl = fn;
9119 if (TREE_CODE(fndecl) == ADDR_EXPR)
9120 fndecl = TREE_OPERAND(fndecl, 0);
9121
9122 // Add a type cast in case the type of the function is a recursive
9123 // type which refers to itself.
9124 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9125 {
9126 tree fnt = type_to_tree(fntype->get_backend(gogo));
9127 if (fnt == error_mark_node)
9128 return error_mark_node;
9129 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9130 }
9131
9132 // This is to support builtin math functions when using 80387 math.
9133 tree excess_type = NULL_TREE;
9134 if (optimize
9135 && TREE_CODE(fndecl) == FUNCTION_DECL
9136 && DECL_IS_BUILTIN(fndecl)
9137 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9138 && nargs > 0
9139 && ((SCALAR_FLOAT_TYPE_P(rettype)
9140 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9141 || (COMPLEX_FLOAT_TYPE_P(rettype)
9142 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9143 {
9144 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9145 if (excess_type != NULL_TREE)
9146 {
9147 tree excess_fndecl = mathfn_built_in(excess_type,
9148 DECL_FUNCTION_CODE(fndecl));
9149 if (excess_fndecl == NULL_TREE)
9150 excess_type = NULL_TREE;
9151 else
9152 {
9153 fn = build_fold_addr_expr_loc(location.gcc_location(),
9154 excess_fndecl);
9155 for (int i = 0; i < nargs; ++i)
9156 {
9157 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9158 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9159 args[i] = ::convert(excess_type, args[i]);
9160 }
9161 }
9162 }
9163 }
9164
9165 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9166 fn, nargs, args);
9167 delete[] args;
9168
9169 SET_EXPR_LOCATION(ret, location.gcc_location());
9170
9171 if (has_closure)
9172 {
9173 tree closure_tree = func->closure()->get_tree(context);
9174 if (closure_tree != error_mark_node)
9175 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9176 }
9177
9178 // If this is a recursive function type which returns itself, as in
9179 // type F func() F
9180 // we have used ptr_type_node for the return type. Add a cast here
9181 // to the correct type.
9182 if (TREE_TYPE(ret) == ptr_type_node)
9183 {
9184 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9185 ret = fold_convert_loc(location.gcc_location(), t, ret);
9186 }
9187
9188 if (excess_type != NULL_TREE)
9189 {
9190 // Calling convert here can undo our excess precision change.
9191 // That may or may not be a bug in convert_to_real.
9192 ret = build1(NOP_EXPR, rettype, ret);
9193 }
9194
9195 if (this->results_ != NULL)
9196 ret = this->set_results(context, ret);
9197
9198 this->tree_ = ret;
9199
9200 return ret;
9201 }
9202
9203 // Set the result variables if this call returns multiple results.
9204
9205 tree
9206 Call_expression::set_results(Translate_context* context, tree call_tree)
9207 {
9208 tree stmt_list = NULL_TREE;
9209
9210 call_tree = save_expr(call_tree);
9211
9212 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9213 {
9214 go_assert(saw_errors());
9215 return call_tree;
9216 }
9217
9218 Location loc = this->location();
9219 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9220 size_t rc = this->result_count();
9221 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9222 {
9223 go_assert(field != NULL_TREE);
9224
9225 Temporary_statement* temp = this->result(i);
9226 if (temp == NULL)
9227 {
9228 go_assert(saw_errors());
9229 return error_mark_node;
9230 }
9231 Temporary_reference_expression* ref =
9232 Expression::make_temporary_reference(temp, loc);
9233 ref->set_is_lvalue();
9234 tree temp_tree = ref->get_tree(context);
9235 if (temp_tree == error_mark_node)
9236 return error_mark_node;
9237
9238 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9239 TREE_TYPE(field), call_tree, field, NULL_TREE);
9240 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9241 void_type_node, temp_tree, val_tree);
9242
9243 append_to_statement_list(set_tree, &stmt_list);
9244 }
9245 go_assert(field == NULL_TREE);
9246
9247 return save_expr(stmt_list);
9248 }
9249
9250 // Dump ast representation for a call expressin.
9251
9252 void
9253 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9254 {
9255 this->fn_->dump_expression(ast_dump_context);
9256 ast_dump_context->ostream() << "(";
9257 if (args_ != NULL)
9258 ast_dump_context->dump_expression_list(this->args_);
9259
9260 ast_dump_context->ostream() << ") ";
9261 }
9262
9263 // Make a call expression.
9264
9265 Call_expression*
9266 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9267 Location location)
9268 {
9269 return new Call_expression(fn, args, is_varargs, location);
9270 }
9271
9272 // A single result from a call which returns multiple results.
9273
9274 class Call_result_expression : public Expression
9275 {
9276 public:
9277 Call_result_expression(Call_expression* call, unsigned int index)
9278 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9279 call_(call), index_(index)
9280 { }
9281
9282 protected:
9283 int
9284 do_traverse(Traverse*);
9285
9286 Type*
9287 do_type();
9288
9289 void
9290 do_determine_type(const Type_context*);
9291
9292 void
9293 do_check_types(Gogo*);
9294
9295 Expression*
9296 do_copy()
9297 {
9298 return new Call_result_expression(this->call_->call_expression(),
9299 this->index_);
9300 }
9301
9302 bool
9303 do_must_eval_in_order() const
9304 { return true; }
9305
9306 tree
9307 do_get_tree(Translate_context*);
9308
9309 void
9310 do_dump_expression(Ast_dump_context*) const;
9311
9312 private:
9313 // The underlying call expression.
9314 Expression* call_;
9315 // Which result we want.
9316 unsigned int index_;
9317 };
9318
9319 // Traverse a call result.
9320
9321 int
9322 Call_result_expression::do_traverse(Traverse* traverse)
9323 {
9324 if (traverse->remember_expression(this->call_))
9325 {
9326 // We have already traversed the call expression.
9327 return TRAVERSE_CONTINUE;
9328 }
9329 return Expression::traverse(&this->call_, traverse);
9330 }
9331
9332 // Get the type.
9333
9334 Type*
9335 Call_result_expression::do_type()
9336 {
9337 if (this->classification() == EXPRESSION_ERROR)
9338 return Type::make_error_type();
9339
9340 // THIS->CALL_ can be replaced with a temporary reference due to
9341 // Call_expression::do_must_eval_in_order when there is an error.
9342 Call_expression* ce = this->call_->call_expression();
9343 if (ce == NULL)
9344 {
9345 this->set_is_error();
9346 return Type::make_error_type();
9347 }
9348 Function_type* fntype = ce->get_function_type();
9349 if (fntype == NULL)
9350 {
9351 if (ce->issue_error())
9352 {
9353 if (!ce->fn()->type()->is_error())
9354 this->report_error(_("expected function"));
9355 }
9356 this->set_is_error();
9357 return Type::make_error_type();
9358 }
9359 const Typed_identifier_list* results = fntype->results();
9360 if (results == NULL || results->size() < 2)
9361 {
9362 if (ce->issue_error())
9363 this->report_error(_("number of results does not match "
9364 "number of values"));
9365 return Type::make_error_type();
9366 }
9367 Typed_identifier_list::const_iterator pr = results->begin();
9368 for (unsigned int i = 0; i < this->index_; ++i)
9369 {
9370 if (pr == results->end())
9371 break;
9372 ++pr;
9373 }
9374 if (pr == results->end())
9375 {
9376 if (ce->issue_error())
9377 this->report_error(_("number of results does not match "
9378 "number of values"));
9379 return Type::make_error_type();
9380 }
9381 return pr->type();
9382 }
9383
9384 // Check the type. Just make sure that we trigger the warning in
9385 // do_type.
9386
9387 void
9388 Call_result_expression::do_check_types(Gogo*)
9389 {
9390 this->type();
9391 }
9392
9393 // Determine the type. We have nothing to do here, but the 0 result
9394 // needs to pass down to the caller.
9395
9396 void
9397 Call_result_expression::do_determine_type(const Type_context*)
9398 {
9399 this->call_->determine_type_no_context();
9400 }
9401
9402 // Return the tree. We just refer to the temporary set by the call
9403 // expression. We don't do this at lowering time because it makes it
9404 // hard to evaluate the call at the right time.
9405
9406 tree
9407 Call_result_expression::do_get_tree(Translate_context* context)
9408 {
9409 Call_expression* ce = this->call_->call_expression();
9410 if (ce == NULL)
9411 {
9412 go_assert(this->call_->is_error_expression());
9413 return error_mark_node;
9414 }
9415 Temporary_statement* ts = ce->result(this->index_);
9416 if (ts == NULL)
9417 {
9418 go_assert(saw_errors());
9419 return error_mark_node;
9420 }
9421 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9422 return ref->get_tree(context);
9423 }
9424
9425 // Dump ast representation for a call result expression.
9426
9427 void
9428 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9429 const
9430 {
9431 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9432 // (struct) and the fields are referenced instead.
9433 ast_dump_context->ostream() << this->index_ << "@(";
9434 ast_dump_context->dump_expression(this->call_);
9435 ast_dump_context->ostream() << ")";
9436 }
9437
9438 // Make a reference to a single result of a call which returns
9439 // multiple results.
9440
9441 Expression*
9442 Expression::make_call_result(Call_expression* call, unsigned int index)
9443 {
9444 return new Call_result_expression(call, index);
9445 }
9446
9447 // Class Index_expression.
9448
9449 // Traversal.
9450
9451 int
9452 Index_expression::do_traverse(Traverse* traverse)
9453 {
9454 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9455 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9456 || (this->end_ != NULL
9457 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9458 return TRAVERSE_EXIT;
9459 return TRAVERSE_CONTINUE;
9460 }
9461
9462 // Lower an index expression. This converts the generic index
9463 // expression into an array index, a string index, or a map index.
9464
9465 Expression*
9466 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9467 {
9468 Location location = this->location();
9469 Expression* left = this->left_;
9470 Expression* start = this->start_;
9471 Expression* end = this->end_;
9472
9473 Type* type = left->type();
9474 if (type->is_error())
9475 return Expression::make_error(location);
9476 else if (left->is_type_expression())
9477 {
9478 error_at(location, "attempt to index type expression");
9479 return Expression::make_error(location);
9480 }
9481 else if (type->array_type() != NULL)
9482 return Expression::make_array_index(left, start, end, location);
9483 else if (type->points_to() != NULL
9484 && type->points_to()->array_type() != NULL
9485 && !type->points_to()->is_slice_type())
9486 {
9487 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9488 location);
9489 return Expression::make_array_index(deref, start, end, location);
9490 }
9491 else if (type->is_string_type())
9492 return Expression::make_string_index(left, start, end, location);
9493 else if (type->map_type() != NULL)
9494 {
9495 if (end != NULL)
9496 {
9497 error_at(location, "invalid slice of map");
9498 return Expression::make_error(location);
9499 }
9500 Map_index_expression* ret = Expression::make_map_index(left, start,
9501 location);
9502 if (this->is_lvalue_)
9503 ret->set_is_lvalue();
9504 return ret;
9505 }
9506 else
9507 {
9508 error_at(location,
9509 "attempt to index object which is not array, string, or map");
9510 return Expression::make_error(location);
9511 }
9512 }
9513
9514 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9515 // dump context
9516
9517 void
9518 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9519 const Expression* expr,
9520 const Expression* start,
9521 const Expression* end)
9522 {
9523 expr->dump_expression(ast_dump_context);
9524 ast_dump_context->ostream() << "[";
9525 start->dump_expression(ast_dump_context);
9526 if (end != NULL)
9527 {
9528 ast_dump_context->ostream() << ":";
9529 end->dump_expression(ast_dump_context);
9530 }
9531 ast_dump_context->ostream() << "]";
9532 }
9533
9534 // Dump ast representation for an index expression.
9535
9536 void
9537 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9538 const
9539 {
9540 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9541 this->start_, this->end_);
9542 }
9543
9544 // Make an index expression.
9545
9546 Expression*
9547 Expression::make_index(Expression* left, Expression* start, Expression* end,
9548 Location location)
9549 {
9550 return new Index_expression(left, start, end, location);
9551 }
9552
9553 // An array index. This is used for both indexing and slicing.
9554
9555 class Array_index_expression : public Expression
9556 {
9557 public:
9558 Array_index_expression(Expression* array, Expression* start,
9559 Expression* end, Location location)
9560 : Expression(EXPRESSION_ARRAY_INDEX, location),
9561 array_(array), start_(start), end_(end), type_(NULL)
9562 { }
9563
9564 protected:
9565 int
9566 do_traverse(Traverse*);
9567
9568 Type*
9569 do_type();
9570
9571 void
9572 do_determine_type(const Type_context*);
9573
9574 void
9575 do_check_types(Gogo*);
9576
9577 Expression*
9578 do_copy()
9579 {
9580 return Expression::make_array_index(this->array_->copy(),
9581 this->start_->copy(),
9582 (this->end_ == NULL
9583 ? NULL
9584 : this->end_->copy()),
9585 this->location());
9586 }
9587
9588 bool
9589 do_must_eval_subexpressions_in_order(int* skip) const
9590 {
9591 *skip = 1;
9592 return true;
9593 }
9594
9595 bool
9596 do_is_addressable() const;
9597
9598 void
9599 do_address_taken(bool escapes)
9600 { this->array_->address_taken(escapes); }
9601
9602 tree
9603 do_get_tree(Translate_context*);
9604
9605 void
9606 do_dump_expression(Ast_dump_context*) const;
9607
9608 private:
9609 // The array we are getting a value from.
9610 Expression* array_;
9611 // The start or only index.
9612 Expression* start_;
9613 // The end index of a slice. This may be NULL for a simple array
9614 // index, or it may be a nil expression for the length of the array.
9615 Expression* end_;
9616 // The type of the expression.
9617 Type* type_;
9618 };
9619
9620 // Array index traversal.
9621
9622 int
9623 Array_index_expression::do_traverse(Traverse* traverse)
9624 {
9625 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9626 return TRAVERSE_EXIT;
9627 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9628 return TRAVERSE_EXIT;
9629 if (this->end_ != NULL)
9630 {
9631 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9632 return TRAVERSE_EXIT;
9633 }
9634 return TRAVERSE_CONTINUE;
9635 }
9636
9637 // Return the type of an array index.
9638
9639 Type*
9640 Array_index_expression::do_type()
9641 {
9642 if (this->type_ == NULL)
9643 {
9644 Array_type* type = this->array_->type()->array_type();
9645 if (type == NULL)
9646 this->type_ = Type::make_error_type();
9647 else if (this->end_ == NULL)
9648 this->type_ = type->element_type();
9649 else if (type->is_slice_type())
9650 {
9651 // A slice of a slice has the same type as the original
9652 // slice.
9653 this->type_ = this->array_->type()->deref();
9654 }
9655 else
9656 {
9657 // A slice of an array is a slice.
9658 this->type_ = Type::make_array_type(type->element_type(), NULL);
9659 }
9660 }
9661 return this->type_;
9662 }
9663
9664 // Set the type of an array index.
9665
9666 void
9667 Array_index_expression::do_determine_type(const Type_context*)
9668 {
9669 this->array_->determine_type_no_context();
9670 this->start_->determine_type_no_context();
9671 if (this->end_ != NULL)
9672 this->end_->determine_type_no_context();
9673 }
9674
9675 // Check types of an array index.
9676
9677 void
9678 Array_index_expression::do_check_types(Gogo*)
9679 {
9680 if (this->start_->type()->integer_type() == NULL)
9681 this->report_error(_("index must be integer"));
9682 if (this->end_ != NULL
9683 && this->end_->type()->integer_type() == NULL
9684 && !this->end_->type()->is_error()
9685 && !this->end_->is_nil_expression()
9686 && !this->end_->is_error_expression())
9687 this->report_error(_("slice end must be integer"));
9688
9689 Array_type* array_type = this->array_->type()->array_type();
9690 if (array_type == NULL)
9691 {
9692 go_assert(this->array_->type()->is_error());
9693 return;
9694 }
9695
9696 unsigned int int_bits =
9697 Type::lookup_integer_type("int")->integer_type()->bits();
9698
9699 Numeric_constant lvalnc;
9700 mpz_t lval;
9701 bool lval_valid = (array_type->length() != NULL
9702 && array_type->length()->numeric_constant_value(&lvalnc)
9703 && lvalnc.to_int(&lval));
9704 Numeric_constant inc;
9705 mpz_t ival;
9706 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9707 {
9708 if (mpz_sgn(ival) < 0
9709 || mpz_sizeinbase(ival, 2) >= int_bits
9710 || (lval_valid
9711 && (this->end_ == NULL
9712 ? mpz_cmp(ival, lval) >= 0
9713 : mpz_cmp(ival, lval) > 0)))
9714 {
9715 error_at(this->start_->location(), "array index out of bounds");
9716 this->set_is_error();
9717 }
9718 mpz_clear(ival);
9719 }
9720 if (this->end_ != NULL && !this->end_->is_nil_expression())
9721 {
9722 Numeric_constant enc;
9723 mpz_t eval;
9724 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9725 {
9726 if (mpz_sgn(eval) < 0
9727 || mpz_sizeinbase(eval, 2) >= int_bits
9728 || (lval_valid && mpz_cmp(eval, lval) > 0))
9729 {
9730 error_at(this->end_->location(), "array index out of bounds");
9731 this->set_is_error();
9732 }
9733 mpz_clear(eval);
9734 }
9735 }
9736 if (lval_valid)
9737 mpz_clear(lval);
9738
9739 // A slice of an array requires an addressable array. A slice of a
9740 // slice is always possible.
9741 if (this->end_ != NULL && !array_type->is_slice_type())
9742 {
9743 if (!this->array_->is_addressable())
9744 this->report_error(_("slice of unaddressable value"));
9745 else
9746 this->array_->address_taken(true);
9747 }
9748 }
9749
9750 // Return whether this expression is addressable.
9751
9752 bool
9753 Array_index_expression::do_is_addressable() const
9754 {
9755 // A slice expression is not addressable.
9756 if (this->end_ != NULL)
9757 return false;
9758
9759 // An index into a slice is addressable.
9760 if (this->array_->type()->is_slice_type())
9761 return true;
9762
9763 // An index into an array is addressable if the array is
9764 // addressable.
9765 return this->array_->is_addressable();
9766 }
9767
9768 // Get a tree for an array index.
9769
9770 tree
9771 Array_index_expression::do_get_tree(Translate_context* context)
9772 {
9773 Gogo* gogo = context->gogo();
9774 Location loc = this->location();
9775
9776 Array_type* array_type = this->array_->type()->array_type();
9777 if (array_type == NULL)
9778 {
9779 go_assert(this->array_->type()->is_error());
9780 return error_mark_node;
9781 }
9782
9783 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9784 if (type_tree == error_mark_node)
9785 return error_mark_node;
9786
9787 tree array_tree = this->array_->get_tree(context);
9788 if (array_tree == error_mark_node)
9789 return error_mark_node;
9790
9791 if (array_type->length() == NULL && !DECL_P(array_tree))
9792 array_tree = save_expr(array_tree);
9793
9794 tree length_tree = NULL_TREE;
9795 if (this->end_ == NULL || this->end_->is_nil_expression())
9796 {
9797 length_tree = array_type->length_tree(gogo, array_tree);
9798 if (length_tree == error_mark_node)
9799 return error_mark_node;
9800 length_tree = save_expr(length_tree);
9801 }
9802
9803 tree capacity_tree = NULL_TREE;
9804 if (this->end_ != NULL)
9805 {
9806 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9807 if (capacity_tree == error_mark_node)
9808 return error_mark_node;
9809 capacity_tree = save_expr(capacity_tree);
9810 }
9811
9812 tree length_type = (length_tree != NULL_TREE
9813 ? TREE_TYPE(length_tree)
9814 : TREE_TYPE(capacity_tree));
9815
9816 tree bad_index = boolean_false_node;
9817
9818 tree start_tree = this->start_->get_tree(context);
9819 if (start_tree == error_mark_node)
9820 return error_mark_node;
9821 if (!DECL_P(start_tree))
9822 start_tree = save_expr(start_tree);
9823 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9824 start_tree = convert_to_integer(length_type, start_tree);
9825
9826 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9827 loc);
9828
9829 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9830 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9831 boolean_type_node, bad_index,
9832 fold_build2_loc(loc.gcc_location(),
9833 (this->end_ == NULL
9834 ? GE_EXPR
9835 : GT_EXPR),
9836 boolean_type_node, start_tree,
9837 (this->end_ == NULL
9838 ? length_tree
9839 : capacity_tree)));
9840
9841 int code = (array_type->length() != NULL
9842 ? (this->end_ == NULL
9843 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9844 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9845 : (this->end_ == NULL
9846 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9847 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9848 tree crash = Gogo::runtime_error(code, loc);
9849
9850 if (this->end_ == NULL)
9851 {
9852 // Simple array indexing. This has to return an l-value, so
9853 // wrap the index check into START_TREE.
9854 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9855 build3(COND_EXPR, void_type_node,
9856 bad_index, crash, NULL_TREE),
9857 start_tree);
9858 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9859
9860 if (array_type->length() != NULL)
9861 {
9862 // Fixed array.
9863 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9864 start_tree, NULL_TREE, NULL_TREE);
9865 }
9866 else
9867 {
9868 // Open array.
9869 tree values = array_type->value_pointer_tree(gogo, array_tree);
9870 Type* element_type = array_type->element_type();
9871 Btype* belement_type = element_type->get_backend(gogo);
9872 tree element_type_tree = type_to_tree(belement_type);
9873 if (element_type_tree == error_mark_node)
9874 return error_mark_node;
9875 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9876 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9877 start_tree, element_size);
9878 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9879 TREE_TYPE(values), values, offset);
9880 return build_fold_indirect_ref(ptr);
9881 }
9882 }
9883
9884 // Array slice.
9885
9886 tree end_tree;
9887 if (this->end_->is_nil_expression())
9888 end_tree = length_tree;
9889 else
9890 {
9891 end_tree = this->end_->get_tree(context);
9892 if (end_tree == error_mark_node)
9893 return error_mark_node;
9894 if (!DECL_P(end_tree))
9895 end_tree = save_expr(end_tree);
9896 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9897 end_tree = convert_to_integer(length_type, end_tree);
9898
9899 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9900 loc);
9901
9902 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9903
9904 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9905 boolean_type_node,
9906 fold_build2_loc(loc.gcc_location(),
9907 LT_EXPR, boolean_type_node,
9908 end_tree, start_tree),
9909 fold_build2_loc(loc.gcc_location(),
9910 GT_EXPR, boolean_type_node,
9911 end_tree, capacity_tree));
9912 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9913 boolean_type_node, bad_index, bad_end);
9914 }
9915
9916 Type* element_type = array_type->element_type();
9917 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9918 if (element_type_tree == error_mark_node)
9919 return error_mark_node;
9920 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9921
9922 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9923 fold_convert_loc(loc.gcc_location(), sizetype,
9924 start_tree),
9925 element_size);
9926
9927 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9928 if (value_pointer == error_mark_node)
9929 return error_mark_node;
9930
9931 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9932 TREE_TYPE(value_pointer),
9933 value_pointer, offset);
9934
9935 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9936 length_type, end_tree, start_tree);
9937
9938 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9939 length_type, capacity_tree,
9940 start_tree);
9941
9942 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9943 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9944
9945 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9946
9947 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9948 tree field = TYPE_FIELDS(struct_tree);
9949 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9950 elt->index = field;
9951 elt->value = value_pointer;
9952
9953 elt = VEC_quick_push(constructor_elt, init, NULL);
9954 field = DECL_CHAIN(field);
9955 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9956 elt->index = field;
9957 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9958 result_length_tree);
9959
9960 elt = VEC_quick_push(constructor_elt, init, NULL);
9961 field = DECL_CHAIN(field);
9962 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9963 elt->index = field;
9964 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9965 result_capacity_tree);
9966
9967 tree constructor = build_constructor(struct_tree, init);
9968
9969 if (TREE_CONSTANT(value_pointer)
9970 && TREE_CONSTANT(result_length_tree)
9971 && TREE_CONSTANT(result_capacity_tree))
9972 TREE_CONSTANT(constructor) = 1;
9973
9974 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9975 TREE_TYPE(constructor),
9976 build3(COND_EXPR, void_type_node,
9977 bad_index, crash, NULL_TREE),
9978 constructor);
9979 }
9980
9981 // Dump ast representation for an array index expression.
9982
9983 void
9984 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9985 const
9986 {
9987 Index_expression::dump_index_expression(ast_dump_context, this->array_,
9988 this->start_, this->end_);
9989 }
9990
9991 // Make an array index expression. END may be NULL.
9992
9993 Expression*
9994 Expression::make_array_index(Expression* array, Expression* start,
9995 Expression* end, Location location)
9996 {
9997 return new Array_index_expression(array, start, end, location);
9998 }
9999
10000 // A string index. This is used for both indexing and slicing.
10001
10002 class String_index_expression : public Expression
10003 {
10004 public:
10005 String_index_expression(Expression* string, Expression* start,
10006 Expression* end, Location location)
10007 : Expression(EXPRESSION_STRING_INDEX, location),
10008 string_(string), start_(start), end_(end)
10009 { }
10010
10011 protected:
10012 int
10013 do_traverse(Traverse*);
10014
10015 Type*
10016 do_type();
10017
10018 void
10019 do_determine_type(const Type_context*);
10020
10021 void
10022 do_check_types(Gogo*);
10023
10024 Expression*
10025 do_copy()
10026 {
10027 return Expression::make_string_index(this->string_->copy(),
10028 this->start_->copy(),
10029 (this->end_ == NULL
10030 ? NULL
10031 : this->end_->copy()),
10032 this->location());
10033 }
10034
10035 bool
10036 do_must_eval_subexpressions_in_order(int* skip) const
10037 {
10038 *skip = 1;
10039 return true;
10040 }
10041
10042 tree
10043 do_get_tree(Translate_context*);
10044
10045 void
10046 do_dump_expression(Ast_dump_context*) const;
10047
10048 private:
10049 // The string we are getting a value from.
10050 Expression* string_;
10051 // The start or only index.
10052 Expression* start_;
10053 // The end index of a slice. This may be NULL for a single index,
10054 // or it may be a nil expression for the length of the string.
10055 Expression* end_;
10056 };
10057
10058 // String index traversal.
10059
10060 int
10061 String_index_expression::do_traverse(Traverse* traverse)
10062 {
10063 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10064 return TRAVERSE_EXIT;
10065 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10066 return TRAVERSE_EXIT;
10067 if (this->end_ != NULL)
10068 {
10069 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10070 return TRAVERSE_EXIT;
10071 }
10072 return TRAVERSE_CONTINUE;
10073 }
10074
10075 // Return the type of a string index.
10076
10077 Type*
10078 String_index_expression::do_type()
10079 {
10080 if (this->end_ == NULL)
10081 return Type::lookup_integer_type("uint8");
10082 else
10083 return this->string_->type();
10084 }
10085
10086 // Determine the type of a string index.
10087
10088 void
10089 String_index_expression::do_determine_type(const Type_context*)
10090 {
10091 this->string_->determine_type_no_context();
10092 this->start_->determine_type_no_context();
10093 if (this->end_ != NULL)
10094 this->end_->determine_type_no_context();
10095 }
10096
10097 // Check types of a string index.
10098
10099 void
10100 String_index_expression::do_check_types(Gogo*)
10101 {
10102 if (this->start_->type()->integer_type() == NULL)
10103 this->report_error(_("index must be integer"));
10104 if (this->end_ != NULL
10105 && this->end_->type()->integer_type() == NULL
10106 && !this->end_->is_nil_expression())
10107 this->report_error(_("slice end must be integer"));
10108
10109 std::string sval;
10110 bool sval_valid = this->string_->string_constant_value(&sval);
10111
10112 Numeric_constant inc;
10113 mpz_t ival;
10114 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10115 {
10116 if (mpz_sgn(ival) < 0
10117 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10118 {
10119 error_at(this->start_->location(), "string index out of bounds");
10120 this->set_is_error();
10121 }
10122 mpz_clear(ival);
10123 }
10124 if (this->end_ != NULL && !this->end_->is_nil_expression())
10125 {
10126 Numeric_constant enc;
10127 mpz_t eval;
10128 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10129 {
10130 if (mpz_sgn(eval) < 0
10131 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10132 {
10133 error_at(this->end_->location(), "string index out of bounds");
10134 this->set_is_error();
10135 }
10136 mpz_clear(eval);
10137 }
10138 }
10139 }
10140
10141 // Get a tree for a string index.
10142
10143 tree
10144 String_index_expression::do_get_tree(Translate_context* context)
10145 {
10146 Location loc = this->location();
10147
10148 tree string_tree = this->string_->get_tree(context);
10149 if (string_tree == error_mark_node)
10150 return error_mark_node;
10151
10152 if (this->string_->type()->points_to() != NULL)
10153 string_tree = build_fold_indirect_ref(string_tree);
10154 if (!DECL_P(string_tree))
10155 string_tree = save_expr(string_tree);
10156 tree string_type = TREE_TYPE(string_tree);
10157
10158 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10159 length_tree = save_expr(length_tree);
10160 tree length_type = TREE_TYPE(length_tree);
10161
10162 tree bad_index = boolean_false_node;
10163
10164 tree start_tree = this->start_->get_tree(context);
10165 if (start_tree == error_mark_node)
10166 return error_mark_node;
10167 if (!DECL_P(start_tree))
10168 start_tree = save_expr(start_tree);
10169 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10170 start_tree = convert_to_integer(length_type, start_tree);
10171
10172 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10173 loc);
10174
10175 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10176
10177 int code = (this->end_ == NULL
10178 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10179 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10180 tree crash = Gogo::runtime_error(code, loc);
10181
10182 if (this->end_ == NULL)
10183 {
10184 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10185 boolean_type_node, bad_index,
10186 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10187 boolean_type_node,
10188 start_tree, length_tree));
10189
10190 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10191 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10192 TREE_TYPE(bytes_tree),
10193 bytes_tree,
10194 fold_convert_loc(loc.gcc_location(), sizetype,
10195 start_tree));
10196 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10197
10198 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10199 build3(COND_EXPR, void_type_node,
10200 bad_index, crash, NULL_TREE),
10201 index);
10202 }
10203 else
10204 {
10205 tree end_tree;
10206 if (this->end_->is_nil_expression())
10207 end_tree = build_int_cst(length_type, -1);
10208 else
10209 {
10210 end_tree = this->end_->get_tree(context);
10211 if (end_tree == error_mark_node)
10212 return error_mark_node;
10213 if (!DECL_P(end_tree))
10214 end_tree = save_expr(end_tree);
10215 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10216 end_tree = convert_to_integer(length_type, end_tree);
10217
10218 bad_index = Expression::check_bounds(end_tree, length_type,
10219 bad_index, loc);
10220
10221 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10222 end_tree);
10223 }
10224
10225 static tree strslice_fndecl;
10226 tree ret = Gogo::call_builtin(&strslice_fndecl,
10227 loc,
10228 "__go_string_slice",
10229 3,
10230 string_type,
10231 string_type,
10232 string_tree,
10233 length_type,
10234 start_tree,
10235 length_type,
10236 end_tree);
10237 if (ret == error_mark_node)
10238 return error_mark_node;
10239 // This will panic if the bounds are out of range for the
10240 // string.
10241 TREE_NOTHROW(strslice_fndecl) = 0;
10242
10243 if (bad_index == boolean_false_node)
10244 return ret;
10245 else
10246 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10247 build3(COND_EXPR, void_type_node,
10248 bad_index, crash, NULL_TREE),
10249 ret);
10250 }
10251 }
10252
10253 // Dump ast representation for a string index expression.
10254
10255 void
10256 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10257 const
10258 {
10259 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10260 this->start_, this->end_);
10261 }
10262
10263 // Make a string index expression. END may be NULL.
10264
10265 Expression*
10266 Expression::make_string_index(Expression* string, Expression* start,
10267 Expression* end, Location location)
10268 {
10269 return new String_index_expression(string, start, end, location);
10270 }
10271
10272 // Class Map_index.
10273
10274 // Get the type of the map.
10275
10276 Map_type*
10277 Map_index_expression::get_map_type() const
10278 {
10279 Map_type* mt = this->map_->type()->deref()->map_type();
10280 if (mt == NULL)
10281 go_assert(saw_errors());
10282 return mt;
10283 }
10284
10285 // Map index traversal.
10286
10287 int
10288 Map_index_expression::do_traverse(Traverse* traverse)
10289 {
10290 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10291 return TRAVERSE_EXIT;
10292 return Expression::traverse(&this->index_, traverse);
10293 }
10294
10295 // Return the type of a map index.
10296
10297 Type*
10298 Map_index_expression::do_type()
10299 {
10300 Map_type* mt = this->get_map_type();
10301 if (mt == NULL)
10302 return Type::make_error_type();
10303 Type* type = mt->val_type();
10304 // If this map index is in a tuple assignment, we actually return a
10305 // pointer to the value type. Tuple_map_assignment_statement is
10306 // responsible for handling this correctly. We need to get the type
10307 // right in case this gets assigned to a temporary variable.
10308 if (this->is_in_tuple_assignment_)
10309 type = Type::make_pointer_type(type);
10310 return type;
10311 }
10312
10313 // Fix the type of a map index.
10314
10315 void
10316 Map_index_expression::do_determine_type(const Type_context*)
10317 {
10318 this->map_->determine_type_no_context();
10319 Map_type* mt = this->get_map_type();
10320 Type* key_type = mt == NULL ? NULL : mt->key_type();
10321 Type_context subcontext(key_type, false);
10322 this->index_->determine_type(&subcontext);
10323 }
10324
10325 // Check types of a map index.
10326
10327 void
10328 Map_index_expression::do_check_types(Gogo*)
10329 {
10330 std::string reason;
10331 Map_type* mt = this->get_map_type();
10332 if (mt == NULL)
10333 return;
10334 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10335 {
10336 if (reason.empty())
10337 this->report_error(_("incompatible type for map index"));
10338 else
10339 {
10340 error_at(this->location(), "incompatible type for map index (%s)",
10341 reason.c_str());
10342 this->set_is_error();
10343 }
10344 }
10345 }
10346
10347 // Get a tree for a map index.
10348
10349 tree
10350 Map_index_expression::do_get_tree(Translate_context* context)
10351 {
10352 Map_type* type = this->get_map_type();
10353 if (type == NULL)
10354 return error_mark_node;
10355
10356 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10357 if (valptr == error_mark_node)
10358 return error_mark_node;
10359 valptr = save_expr(valptr);
10360
10361 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10362
10363 if (this->is_lvalue_)
10364 return build_fold_indirect_ref(valptr);
10365 else if (this->is_in_tuple_assignment_)
10366 {
10367 // Tuple_map_assignment_statement is responsible for using this
10368 // appropriately.
10369 return valptr;
10370 }
10371 else
10372 {
10373 Gogo* gogo = context->gogo();
10374 Btype* val_btype = type->val_type()->get_backend(gogo);
10375 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10376 return fold_build3(COND_EXPR, val_type_tree,
10377 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10378 fold_convert(TREE_TYPE(valptr),
10379 null_pointer_node)),
10380 expr_to_tree(val_zero),
10381 build_fold_indirect_ref(valptr));
10382 }
10383 }
10384
10385 // Get a tree for the map index. This returns a tree which evaluates
10386 // to a pointer to a value. The pointer will be NULL if the key is
10387 // not in the map.
10388
10389 tree
10390 Map_index_expression::get_value_pointer(Translate_context* context,
10391 bool insert)
10392 {
10393 Map_type* type = this->get_map_type();
10394 if (type == NULL)
10395 return error_mark_node;
10396
10397 tree map_tree = this->map_->get_tree(context);
10398 tree index_tree = this->index_->get_tree(context);
10399 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10400 this->index_->type(),
10401 index_tree,
10402 this->location());
10403 if (map_tree == error_mark_node || index_tree == error_mark_node)
10404 return error_mark_node;
10405
10406 if (this->map_->type()->points_to() != NULL)
10407 map_tree = build_fold_indirect_ref(map_tree);
10408
10409 // We need to pass in a pointer to the key, so stuff it into a
10410 // variable.
10411 tree tmp;
10412 tree make_tmp;
10413 if (current_function_decl != NULL)
10414 {
10415 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10416 DECL_IGNORED_P(tmp) = 0;
10417 DECL_INITIAL(tmp) = index_tree;
10418 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10419 TREE_ADDRESSABLE(tmp) = 1;
10420 }
10421 else
10422 {
10423 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10424 create_tmp_var_name("M"),
10425 TREE_TYPE(index_tree));
10426 DECL_EXTERNAL(tmp) = 0;
10427 TREE_PUBLIC(tmp) = 0;
10428 TREE_STATIC(tmp) = 1;
10429 DECL_ARTIFICIAL(tmp) = 1;
10430 if (!TREE_CONSTANT(index_tree))
10431 make_tmp = fold_build2_loc(this->location().gcc_location(),
10432 INIT_EXPR, void_type_node,
10433 tmp, index_tree);
10434 else
10435 {
10436 TREE_READONLY(tmp) = 1;
10437 TREE_CONSTANT(tmp) = 1;
10438 DECL_INITIAL(tmp) = index_tree;
10439 make_tmp = NULL_TREE;
10440 }
10441 rest_of_decl_compilation(tmp, 1, 0);
10442 }
10443 tree tmpref =
10444 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10445 build_fold_addr_expr_loc(this->location().gcc_location(),
10446 tmp));
10447
10448 static tree map_index_fndecl;
10449 tree call = Gogo::call_builtin(&map_index_fndecl,
10450 this->location(),
10451 "__go_map_index",
10452 3,
10453 const_ptr_type_node,
10454 TREE_TYPE(map_tree),
10455 map_tree,
10456 const_ptr_type_node,
10457 tmpref,
10458 boolean_type_node,
10459 (insert
10460 ? boolean_true_node
10461 : boolean_false_node));
10462 if (call == error_mark_node)
10463 return error_mark_node;
10464 // This can panic on a map of interface type if the interface holds
10465 // an uncomparable or unhashable type.
10466 TREE_NOTHROW(map_index_fndecl) = 0;
10467
10468 Type* val_type = type->val_type();
10469 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10470 if (val_type_tree == error_mark_node)
10471 return error_mark_node;
10472 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10473
10474 tree ret = fold_convert_loc(this->location().gcc_location(),
10475 ptr_val_type_tree, call);
10476 if (make_tmp != NULL_TREE)
10477 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10478 return ret;
10479 }
10480
10481 // Dump ast representation for a map index expression
10482
10483 void
10484 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10485 const
10486 {
10487 Index_expression::dump_index_expression(ast_dump_context,
10488 this->map_, this->index_, NULL);
10489 }
10490
10491 // Make a map index expression.
10492
10493 Map_index_expression*
10494 Expression::make_map_index(Expression* map, Expression* index,
10495 Location location)
10496 {
10497 return new Map_index_expression(map, index, location);
10498 }
10499
10500 // Class Field_reference_expression.
10501
10502 // Return the type of a field reference.
10503
10504 Type*
10505 Field_reference_expression::do_type()
10506 {
10507 Type* type = this->expr_->type();
10508 if (type->is_error())
10509 return type;
10510 Struct_type* struct_type = type->struct_type();
10511 go_assert(struct_type != NULL);
10512 return struct_type->field(this->field_index_)->type();
10513 }
10514
10515 // Check the types for a field reference.
10516
10517 void
10518 Field_reference_expression::do_check_types(Gogo*)
10519 {
10520 Type* type = this->expr_->type();
10521 if (type->is_error())
10522 return;
10523 Struct_type* struct_type = type->struct_type();
10524 go_assert(struct_type != NULL);
10525 go_assert(struct_type->field(this->field_index_) != NULL);
10526 }
10527
10528 // Get a tree for a field reference.
10529
10530 tree
10531 Field_reference_expression::do_get_tree(Translate_context* context)
10532 {
10533 tree struct_tree = this->expr_->get_tree(context);
10534 if (struct_tree == error_mark_node
10535 || TREE_TYPE(struct_tree) == error_mark_node)
10536 return error_mark_node;
10537 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10538 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10539 if (field == NULL_TREE)
10540 {
10541 // This can happen for a type which refers to itself indirectly
10542 // and then turns out to be erroneous.
10543 go_assert(saw_errors());
10544 return error_mark_node;
10545 }
10546 for (unsigned int i = this->field_index_; i > 0; --i)
10547 {
10548 field = DECL_CHAIN(field);
10549 go_assert(field != NULL_TREE);
10550 }
10551 if (TREE_TYPE(field) == error_mark_node)
10552 return error_mark_node;
10553 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10554 NULL_TREE);
10555 }
10556
10557 // Dump ast representation for a field reference expression.
10558
10559 void
10560 Field_reference_expression::do_dump_expression(
10561 Ast_dump_context* ast_dump_context) const
10562 {
10563 this->expr_->dump_expression(ast_dump_context);
10564 ast_dump_context->ostream() << "." << this->field_index_;
10565 }
10566
10567 // Make a reference to a qualified identifier in an expression.
10568
10569 Field_reference_expression*
10570 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10571 Location location)
10572 {
10573 return new Field_reference_expression(expr, field_index, location);
10574 }
10575
10576 // Class Interface_field_reference_expression.
10577
10578 // Return a tree for the pointer to the function to call.
10579
10580 tree
10581 Interface_field_reference_expression::get_function_tree(Translate_context*,
10582 tree expr)
10583 {
10584 if (this->expr_->type()->points_to() != NULL)
10585 expr = build_fold_indirect_ref(expr);
10586
10587 tree expr_type = TREE_TYPE(expr);
10588 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10589
10590 tree field = TYPE_FIELDS(expr_type);
10591 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10592
10593 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10594 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10595
10596 table = build_fold_indirect_ref(table);
10597 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10598
10599 std::string name = Gogo::unpack_hidden_name(this->name_);
10600 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10601 field != NULL_TREE;
10602 field = DECL_CHAIN(field))
10603 {
10604 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10605 break;
10606 }
10607 go_assert(field != NULL_TREE);
10608
10609 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10610 }
10611
10612 // Return a tree for the first argument to pass to the interface
10613 // function.
10614
10615 tree
10616 Interface_field_reference_expression::get_underlying_object_tree(
10617 Translate_context*,
10618 tree expr)
10619 {
10620 if (this->expr_->type()->points_to() != NULL)
10621 expr = build_fold_indirect_ref(expr);
10622
10623 tree expr_type = TREE_TYPE(expr);
10624 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10625
10626 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10627 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10628
10629 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10630 }
10631
10632 // Traversal.
10633
10634 int
10635 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10636 {
10637 return Expression::traverse(&this->expr_, traverse);
10638 }
10639
10640 // Return the type of an interface field reference.
10641
10642 Type*
10643 Interface_field_reference_expression::do_type()
10644 {
10645 Type* expr_type = this->expr_->type();
10646
10647 Type* points_to = expr_type->points_to();
10648 if (points_to != NULL)
10649 expr_type = points_to;
10650
10651 Interface_type* interface_type = expr_type->interface_type();
10652 if (interface_type == NULL)
10653 return Type::make_error_type();
10654
10655 const Typed_identifier* method = interface_type->find_method(this->name_);
10656 if (method == NULL)
10657 return Type::make_error_type();
10658
10659 return method->type();
10660 }
10661
10662 // Determine types.
10663
10664 void
10665 Interface_field_reference_expression::do_determine_type(const Type_context*)
10666 {
10667 this->expr_->determine_type_no_context();
10668 }
10669
10670 // Check the types for an interface field reference.
10671
10672 void
10673 Interface_field_reference_expression::do_check_types(Gogo*)
10674 {
10675 Type* type = this->expr_->type();
10676
10677 Type* points_to = type->points_to();
10678 if (points_to != NULL)
10679 type = points_to;
10680
10681 Interface_type* interface_type = type->interface_type();
10682 if (interface_type == NULL)
10683 {
10684 if (!type->is_error_type())
10685 this->report_error(_("expected interface or pointer to interface"));
10686 }
10687 else
10688 {
10689 const Typed_identifier* method =
10690 interface_type->find_method(this->name_);
10691 if (method == NULL)
10692 {
10693 error_at(this->location(), "method %qs not in interface",
10694 Gogo::message_name(this->name_).c_str());
10695 this->set_is_error();
10696 }
10697 }
10698 }
10699
10700 // Get a tree for a reference to a field in an interface. There is no
10701 // standard tree type representation for this: it's a function
10702 // attached to its first argument, like a Bound_method_expression.
10703 // The only places it may currently be used are in a Call_expression
10704 // or a Go_statement, which will take it apart directly. So this has
10705 // nothing to do at present.
10706
10707 tree
10708 Interface_field_reference_expression::do_get_tree(Translate_context*)
10709 {
10710 error_at(this->location(), "reference to method other than calling it");
10711 return error_mark_node;
10712 }
10713
10714 // Dump ast representation for an interface field reference.
10715
10716 void
10717 Interface_field_reference_expression::do_dump_expression(
10718 Ast_dump_context* ast_dump_context) const
10719 {
10720 this->expr_->dump_expression(ast_dump_context);
10721 ast_dump_context->ostream() << "." << this->name_;
10722 }
10723
10724 // Make a reference to a field in an interface.
10725
10726 Expression*
10727 Expression::make_interface_field_reference(Expression* expr,
10728 const std::string& field,
10729 Location location)
10730 {
10731 return new Interface_field_reference_expression(expr, field, location);
10732 }
10733
10734 // A general selector. This is a Parser_expression for LEFT.NAME. It
10735 // is lowered after we know the type of the left hand side.
10736
10737 class Selector_expression : public Parser_expression
10738 {
10739 public:
10740 Selector_expression(Expression* left, const std::string& name,
10741 Location location)
10742 : Parser_expression(EXPRESSION_SELECTOR, location),
10743 left_(left), name_(name)
10744 { }
10745
10746 protected:
10747 int
10748 do_traverse(Traverse* traverse)
10749 { return Expression::traverse(&this->left_, traverse); }
10750
10751 Expression*
10752 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10753
10754 Expression*
10755 do_copy()
10756 {
10757 return new Selector_expression(this->left_->copy(), this->name_,
10758 this->location());
10759 }
10760
10761 void
10762 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10763
10764 private:
10765 Expression*
10766 lower_method_expression(Gogo*);
10767
10768 // The expression on the left hand side.
10769 Expression* left_;
10770 // The name on the right hand side.
10771 std::string name_;
10772 };
10773
10774 // Lower a selector expression once we know the real type of the left
10775 // hand side.
10776
10777 Expression*
10778 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10779 int)
10780 {
10781 Expression* left = this->left_;
10782 if (left->is_type_expression())
10783 return this->lower_method_expression(gogo);
10784 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10785 this->location());
10786 }
10787
10788 // Lower a method expression T.M or (*T).M. We turn this into a
10789 // function literal.
10790
10791 Expression*
10792 Selector_expression::lower_method_expression(Gogo* gogo)
10793 {
10794 Location location = this->location();
10795 Type* type = this->left_->type();
10796 const std::string& name(this->name_);
10797
10798 bool is_pointer;
10799 if (type->points_to() == NULL)
10800 is_pointer = false;
10801 else
10802 {
10803 is_pointer = true;
10804 type = type->points_to();
10805 }
10806 Named_type* nt = type->named_type();
10807 if (nt == NULL)
10808 {
10809 error_at(location,
10810 ("method expression requires named type or "
10811 "pointer to named type"));
10812 return Expression::make_error(location);
10813 }
10814
10815 bool is_ambiguous;
10816 Method* method = nt->method_function(name, &is_ambiguous);
10817 const Typed_identifier* imethod = NULL;
10818 if (method == NULL && !is_pointer)
10819 {
10820 Interface_type* it = nt->interface_type();
10821 if (it != NULL)
10822 imethod = it->find_method(name);
10823 }
10824
10825 if (method == NULL && imethod == NULL)
10826 {
10827 if (!is_ambiguous)
10828 error_at(location, "type %<%s%s%> has no method %<%s%>",
10829 is_pointer ? "*" : "",
10830 nt->message_name().c_str(),
10831 Gogo::message_name(name).c_str());
10832 else
10833 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10834 Gogo::message_name(name).c_str(),
10835 is_pointer ? "*" : "",
10836 nt->message_name().c_str());
10837 return Expression::make_error(location);
10838 }
10839
10840 if (method != NULL && !is_pointer && !method->is_value_method())
10841 {
10842 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10843 nt->message_name().c_str(),
10844 Gogo::message_name(name).c_str());
10845 return Expression::make_error(location);
10846 }
10847
10848 // Build a new function type in which the receiver becomes the first
10849 // argument.
10850 Function_type* method_type;
10851 if (method != NULL)
10852 {
10853 method_type = method->type();
10854 go_assert(method_type->is_method());
10855 }
10856 else
10857 {
10858 method_type = imethod->type()->function_type();
10859 go_assert(method_type != NULL && !method_type->is_method());
10860 }
10861
10862 const char* const receiver_name = "$this";
10863 Typed_identifier_list* parameters = new Typed_identifier_list();
10864 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10865 location));
10866
10867 const Typed_identifier_list* method_parameters = method_type->parameters();
10868 if (method_parameters != NULL)
10869 {
10870 int i = 0;
10871 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10872 p != method_parameters->end();
10873 ++p, ++i)
10874 {
10875 if (!p->name().empty())
10876 parameters->push_back(*p);
10877 else
10878 {
10879 char buf[20];
10880 snprintf(buf, sizeof buf, "$param%d", i);
10881 parameters->push_back(Typed_identifier(buf, p->type(),
10882 p->location()));
10883 }
10884 }
10885 }
10886
10887 const Typed_identifier_list* method_results = method_type->results();
10888 Typed_identifier_list* results;
10889 if (method_results == NULL)
10890 results = NULL;
10891 else
10892 {
10893 results = new Typed_identifier_list();
10894 for (Typed_identifier_list::const_iterator p = method_results->begin();
10895 p != method_results->end();
10896 ++p)
10897 results->push_back(*p);
10898 }
10899
10900 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10901 location);
10902 if (method_type->is_varargs())
10903 fntype->set_is_varargs();
10904
10905 // We generate methods which always takes a pointer to the receiver
10906 // as their first argument. If this is for a pointer type, we can
10907 // simply reuse the existing function. We use an internal hack to
10908 // get the right type.
10909
10910 if (method != NULL && is_pointer)
10911 {
10912 Named_object* mno = (method->needs_stub_method()
10913 ? method->stub_object()
10914 : method->named_object());
10915 Expression* f = Expression::make_func_reference(mno, NULL, location);
10916 f = Expression::make_cast(fntype, f, location);
10917 Type_conversion_expression* tce =
10918 static_cast<Type_conversion_expression*>(f);
10919 tce->set_may_convert_function_types();
10920 return f;
10921 }
10922
10923 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10924 location);
10925
10926 Named_object* vno = gogo->lookup(receiver_name, NULL);
10927 go_assert(vno != NULL);
10928 Expression* ve = Expression::make_var_reference(vno, location);
10929 Expression* bm;
10930 if (method != NULL)
10931 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10932 else
10933 bm = Expression::make_interface_field_reference(ve, name, location);
10934
10935 // Even though we found the method above, if it has an error type we
10936 // may see an error here.
10937 if (bm->is_error_expression())
10938 {
10939 gogo->finish_function(location);
10940 return bm;
10941 }
10942
10943 Expression_list* args;
10944 if (parameters->size() <= 1)
10945 args = NULL;
10946 else
10947 {
10948 args = new Expression_list();
10949 Typed_identifier_list::const_iterator p = parameters->begin();
10950 ++p;
10951 for (; p != parameters->end(); ++p)
10952 {
10953 vno = gogo->lookup(p->name(), NULL);
10954 go_assert(vno != NULL);
10955 args->push_back(Expression::make_var_reference(vno, location));
10956 }
10957 }
10958
10959 gogo->start_block(location);
10960
10961 Call_expression* call = Expression::make_call(bm, args,
10962 method_type->is_varargs(),
10963 location);
10964
10965 size_t count = call->result_count();
10966 Statement* s;
10967 if (count == 0)
10968 s = Statement::make_statement(call, true);
10969 else
10970 {
10971 Expression_list* retvals = new Expression_list();
10972 if (count <= 1)
10973 retvals->push_back(call);
10974 else
10975 {
10976 for (size_t i = 0; i < count; ++i)
10977 retvals->push_back(Expression::make_call_result(call, i));
10978 }
10979 s = Statement::make_return_statement(retvals, location);
10980 }
10981 gogo->add_statement(s);
10982
10983 Block* b = gogo->finish_block(location);
10984
10985 gogo->add_block(b, location);
10986
10987 // Lower the call in case there are multiple results.
10988 gogo->lower_block(no, b);
10989
10990 gogo->finish_function(location);
10991
10992 return Expression::make_func_reference(no, NULL, location);
10993 }
10994
10995 // Dump the ast for a selector expression.
10996
10997 void
10998 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10999 const
11000 {
11001 ast_dump_context->dump_expression(this->left_);
11002 ast_dump_context->ostream() << ".";
11003 ast_dump_context->ostream() << this->name_;
11004 }
11005
11006 // Make a selector expression.
11007
11008 Expression*
11009 Expression::make_selector(Expression* left, const std::string& name,
11010 Location location)
11011 {
11012 return new Selector_expression(left, name, location);
11013 }
11014
11015 // Implement the builtin function new.
11016
11017 class Allocation_expression : public Expression
11018 {
11019 public:
11020 Allocation_expression(Type* type, Location location)
11021 : Expression(EXPRESSION_ALLOCATION, location),
11022 type_(type)
11023 { }
11024
11025 protected:
11026 int
11027 do_traverse(Traverse* traverse)
11028 { return Type::traverse(this->type_, traverse); }
11029
11030 Type*
11031 do_type()
11032 { return Type::make_pointer_type(this->type_); }
11033
11034 void
11035 do_determine_type(const Type_context*)
11036 { }
11037
11038 Expression*
11039 do_copy()
11040 { return new Allocation_expression(this->type_, this->location()); }
11041
11042 tree
11043 do_get_tree(Translate_context*);
11044
11045 void
11046 do_dump_expression(Ast_dump_context*) const;
11047
11048 private:
11049 // The type we are allocating.
11050 Type* type_;
11051 };
11052
11053 // Return a tree for an allocation expression.
11054
11055 tree
11056 Allocation_expression::do_get_tree(Translate_context* context)
11057 {
11058 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11059 if (type_tree == error_mark_node)
11060 return error_mark_node;
11061 tree size_tree = TYPE_SIZE_UNIT(type_tree);
11062 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11063 this->location());
11064 if (space == error_mark_node)
11065 return error_mark_node;
11066 return fold_convert(build_pointer_type(type_tree), space);
11067 }
11068
11069 // Dump ast representation for an allocation expression.
11070
11071 void
11072 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11073 const
11074 {
11075 ast_dump_context->ostream() << "new(";
11076 ast_dump_context->dump_type(this->type_);
11077 ast_dump_context->ostream() << ")";
11078 }
11079
11080 // Make an allocation expression.
11081
11082 Expression*
11083 Expression::make_allocation(Type* type, Location location)
11084 {
11085 return new Allocation_expression(type, location);
11086 }
11087
11088 // Construct a struct.
11089
11090 class Struct_construction_expression : public Expression
11091 {
11092 public:
11093 Struct_construction_expression(Type* type, Expression_list* vals,
11094 Location location)
11095 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11096 type_(type), vals_(vals), traverse_order_(NULL)
11097 { }
11098
11099 // Set the traversal order, used to ensure that we implement the
11100 // order of evaluation rules. Takes ownership of the argument.
11101 void
11102 set_traverse_order(std::vector<int>* traverse_order)
11103 { this->traverse_order_ = traverse_order; }
11104
11105 // Return whether this is a constant initializer.
11106 bool
11107 is_constant_struct() const;
11108
11109 protected:
11110 int
11111 do_traverse(Traverse* traverse);
11112
11113 Type*
11114 do_type()
11115 { return this->type_; }
11116
11117 void
11118 do_determine_type(const Type_context*);
11119
11120 void
11121 do_check_types(Gogo*);
11122
11123 Expression*
11124 do_copy()
11125 {
11126 Struct_construction_expression* ret =
11127 new Struct_construction_expression(this->type_, this->vals_->copy(),
11128 this->location());
11129 if (this->traverse_order_ != NULL)
11130 ret->set_traverse_order(this->traverse_order_);
11131 return ret;
11132 }
11133
11134 tree
11135 do_get_tree(Translate_context*);
11136
11137 void
11138 do_export(Export*) const;
11139
11140 void
11141 do_dump_expression(Ast_dump_context*) const;
11142
11143 private:
11144 // The type of the struct to construct.
11145 Type* type_;
11146 // The list of values, in order of the fields in the struct. A NULL
11147 // entry means that the field should be zero-initialized.
11148 Expression_list* vals_;
11149 // If not NULL, the order in which to traverse vals_. This is used
11150 // so that we implement the order of evaluation rules correctly.
11151 std::vector<int>* traverse_order_;
11152 };
11153
11154 // Traversal.
11155
11156 int
11157 Struct_construction_expression::do_traverse(Traverse* traverse)
11158 {
11159 if (this->vals_ != NULL)
11160 {
11161 if (this->traverse_order_ == NULL)
11162 {
11163 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11164 return TRAVERSE_EXIT;
11165 }
11166 else
11167 {
11168 for (std::vector<int>::const_iterator p =
11169 this->traverse_order_->begin();
11170 p != this->traverse_order_->end();
11171 ++p)
11172 {
11173 if (Expression::traverse(&this->vals_->at(*p), traverse)
11174 == TRAVERSE_EXIT)
11175 return TRAVERSE_EXIT;
11176 }
11177 }
11178 }
11179 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11180 return TRAVERSE_EXIT;
11181 return TRAVERSE_CONTINUE;
11182 }
11183
11184 // Return whether this is a constant initializer.
11185
11186 bool
11187 Struct_construction_expression::is_constant_struct() const
11188 {
11189 if (this->vals_ == NULL)
11190 return true;
11191 for (Expression_list::const_iterator pv = this->vals_->begin();
11192 pv != this->vals_->end();
11193 ++pv)
11194 {
11195 if (*pv != NULL
11196 && !(*pv)->is_constant()
11197 && (!(*pv)->is_composite_literal()
11198 || (*pv)->is_nonconstant_composite_literal()))
11199 return false;
11200 }
11201
11202 const Struct_field_list* fields = this->type_->struct_type()->fields();
11203 for (Struct_field_list::const_iterator pf = fields->begin();
11204 pf != fields->end();
11205 ++pf)
11206 {
11207 // There are no constant constructors for interfaces.
11208 if (pf->type()->interface_type() != NULL)
11209 return false;
11210 }
11211
11212 return true;
11213 }
11214
11215 // Final type determination.
11216
11217 void
11218 Struct_construction_expression::do_determine_type(const Type_context*)
11219 {
11220 if (this->vals_ == NULL)
11221 return;
11222 const Struct_field_list* fields = this->type_->struct_type()->fields();
11223 Expression_list::const_iterator pv = this->vals_->begin();
11224 for (Struct_field_list::const_iterator pf = fields->begin();
11225 pf != fields->end();
11226 ++pf, ++pv)
11227 {
11228 if (pv == this->vals_->end())
11229 return;
11230 if (*pv != NULL)
11231 {
11232 Type_context subcontext(pf->type(), false);
11233 (*pv)->determine_type(&subcontext);
11234 }
11235 }
11236 // Extra values are an error we will report elsewhere; we still want
11237 // to determine the type to avoid knockon errors.
11238 for (; pv != this->vals_->end(); ++pv)
11239 (*pv)->determine_type_no_context();
11240 }
11241
11242 // Check types.
11243
11244 void
11245 Struct_construction_expression::do_check_types(Gogo*)
11246 {
11247 if (this->vals_ == NULL)
11248 return;
11249
11250 Struct_type* st = this->type_->struct_type();
11251 if (this->vals_->size() > st->field_count())
11252 {
11253 this->report_error(_("too many expressions for struct"));
11254 return;
11255 }
11256
11257 const Struct_field_list* fields = st->fields();
11258 Expression_list::const_iterator pv = this->vals_->begin();
11259 int i = 0;
11260 for (Struct_field_list::const_iterator pf = fields->begin();
11261 pf != fields->end();
11262 ++pf, ++pv, ++i)
11263 {
11264 if (pv == this->vals_->end())
11265 {
11266 this->report_error(_("too few expressions for struct"));
11267 break;
11268 }
11269
11270 if (*pv == NULL)
11271 continue;
11272
11273 std::string reason;
11274 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11275 {
11276 if (reason.empty())
11277 error_at((*pv)->location(),
11278 "incompatible type for field %d in struct construction",
11279 i + 1);
11280 else
11281 error_at((*pv)->location(),
11282 ("incompatible type for field %d in "
11283 "struct construction (%s)"),
11284 i + 1, reason.c_str());
11285 this->set_is_error();
11286 }
11287 }
11288 go_assert(pv == this->vals_->end());
11289 }
11290
11291 // Return a tree for constructing a struct.
11292
11293 tree
11294 Struct_construction_expression::do_get_tree(Translate_context* context)
11295 {
11296 Gogo* gogo = context->gogo();
11297
11298 if (this->vals_ == NULL)
11299 {
11300 Btype* btype = this->type_->get_backend(gogo);
11301 return expr_to_tree(gogo->backend()->zero_expression(btype));
11302 }
11303
11304 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11305 if (type_tree == error_mark_node)
11306 return error_mark_node;
11307 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11308
11309 bool is_constant = true;
11310 const Struct_field_list* fields = this->type_->struct_type()->fields();
11311 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11312 fields->size());
11313 Struct_field_list::const_iterator pf = fields->begin();
11314 Expression_list::const_iterator pv = this->vals_->begin();
11315 for (tree field = TYPE_FIELDS(type_tree);
11316 field != NULL_TREE;
11317 field = DECL_CHAIN(field), ++pf)
11318 {
11319 go_assert(pf != fields->end());
11320
11321 Btype* fbtype = pf->type()->get_backend(gogo);
11322
11323 tree val;
11324 if (pv == this->vals_->end())
11325 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11326 else if (*pv == NULL)
11327 {
11328 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11329 ++pv;
11330 }
11331 else
11332 {
11333 val = Expression::convert_for_assignment(context, pf->type(),
11334 (*pv)->type(),
11335 (*pv)->get_tree(context),
11336 this->location());
11337 ++pv;
11338 }
11339
11340 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11341 return error_mark_node;
11342
11343 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11344 elt->index = field;
11345 elt->value = val;
11346 if (!TREE_CONSTANT(val))
11347 is_constant = false;
11348 }
11349 go_assert(pf == fields->end());
11350
11351 tree ret = build_constructor(type_tree, elts);
11352 if (is_constant)
11353 TREE_CONSTANT(ret) = 1;
11354 return ret;
11355 }
11356
11357 // Export a struct construction.
11358
11359 void
11360 Struct_construction_expression::do_export(Export* exp) const
11361 {
11362 exp->write_c_string("convert(");
11363 exp->write_type(this->type_);
11364 for (Expression_list::const_iterator pv = this->vals_->begin();
11365 pv != this->vals_->end();
11366 ++pv)
11367 {
11368 exp->write_c_string(", ");
11369 if (*pv != NULL)
11370 (*pv)->export_expression(exp);
11371 }
11372 exp->write_c_string(")");
11373 }
11374
11375 // Dump ast representation of a struct construction expression.
11376
11377 void
11378 Struct_construction_expression::do_dump_expression(
11379 Ast_dump_context* ast_dump_context) const
11380 {
11381 ast_dump_context->dump_type(this->type_);
11382 ast_dump_context->ostream() << "{";
11383 ast_dump_context->dump_expression_list(this->vals_);
11384 ast_dump_context->ostream() << "}";
11385 }
11386
11387 // Make a struct composite literal. This used by the thunk code.
11388
11389 Expression*
11390 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11391 Location location)
11392 {
11393 go_assert(type->struct_type() != NULL);
11394 return new Struct_construction_expression(type, vals, location);
11395 }
11396
11397 // Construct an array. This class is not used directly; instead we
11398 // use the child classes, Fixed_array_construction_expression and
11399 // Open_array_construction_expression.
11400
11401 class Array_construction_expression : public Expression
11402 {
11403 protected:
11404 Array_construction_expression(Expression_classification classification,
11405 Type* type,
11406 const std::vector<unsigned long>* indexes,
11407 Expression_list* vals, Location location)
11408 : Expression(classification, location),
11409 type_(type), indexes_(indexes), vals_(vals)
11410 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11411
11412 public:
11413 // Return whether this is a constant initializer.
11414 bool
11415 is_constant_array() const;
11416
11417 // Return the number of elements.
11418 size_t
11419 element_count() const
11420 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11421
11422 protected:
11423 int
11424 do_traverse(Traverse* traverse);
11425
11426 Type*
11427 do_type()
11428 { return this->type_; }
11429
11430 void
11431 do_determine_type(const Type_context*);
11432
11433 void
11434 do_check_types(Gogo*);
11435
11436 void
11437 do_export(Export*) const;
11438
11439 // The indexes.
11440 const std::vector<unsigned long>*
11441 indexes()
11442 { return this->indexes_; }
11443
11444 // The list of values.
11445 Expression_list*
11446 vals()
11447 { return this->vals_; }
11448
11449 // Get a constructor tree for the array values.
11450 tree
11451 get_constructor_tree(Translate_context* context, tree type_tree);
11452
11453 void
11454 do_dump_expression(Ast_dump_context*) const;
11455
11456 private:
11457 // The type of the array to construct.
11458 Type* type_;
11459 // The list of indexes into the array, one for each value. This may
11460 // be NULL, in which case the indexes start at zero and increment.
11461 const std::vector<unsigned long>* indexes_;
11462 // The list of values. This may be NULL if there are no values.
11463 Expression_list* vals_;
11464 };
11465
11466 // Traversal.
11467
11468 int
11469 Array_construction_expression::do_traverse(Traverse* traverse)
11470 {
11471 if (this->vals_ != NULL
11472 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11473 return TRAVERSE_EXIT;
11474 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11475 return TRAVERSE_EXIT;
11476 return TRAVERSE_CONTINUE;
11477 }
11478
11479 // Return whether this is a constant initializer.
11480
11481 bool
11482 Array_construction_expression::is_constant_array() const
11483 {
11484 if (this->vals_ == NULL)
11485 return true;
11486
11487 // There are no constant constructors for interfaces.
11488 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11489 return false;
11490
11491 for (Expression_list::const_iterator pv = this->vals_->begin();
11492 pv != this->vals_->end();
11493 ++pv)
11494 {
11495 if (*pv != NULL
11496 && !(*pv)->is_constant()
11497 && (!(*pv)->is_composite_literal()
11498 || (*pv)->is_nonconstant_composite_literal()))
11499 return false;
11500 }
11501 return true;
11502 }
11503
11504 // Final type determination.
11505
11506 void
11507 Array_construction_expression::do_determine_type(const Type_context*)
11508 {
11509 if (this->vals_ == NULL)
11510 return;
11511 Type_context subcontext(this->type_->array_type()->element_type(), false);
11512 for (Expression_list::const_iterator pv = this->vals_->begin();
11513 pv != this->vals_->end();
11514 ++pv)
11515 {
11516 if (*pv != NULL)
11517 (*pv)->determine_type(&subcontext);
11518 }
11519 }
11520
11521 // Check types.
11522
11523 void
11524 Array_construction_expression::do_check_types(Gogo*)
11525 {
11526 if (this->vals_ == NULL)
11527 return;
11528
11529 Array_type* at = this->type_->array_type();
11530 int i = 0;
11531 Type* element_type = at->element_type();
11532 for (Expression_list::const_iterator pv = this->vals_->begin();
11533 pv != this->vals_->end();
11534 ++pv, ++i)
11535 {
11536 if (*pv != NULL
11537 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11538 {
11539 error_at((*pv)->location(),
11540 "incompatible type for element %d in composite literal",
11541 i + 1);
11542 this->set_is_error();
11543 }
11544 }
11545 }
11546
11547 // Get a constructor tree for the array values.
11548
11549 tree
11550 Array_construction_expression::get_constructor_tree(Translate_context* context,
11551 tree type_tree)
11552 {
11553 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11554 (this->vals_ == NULL
11555 ? 0
11556 : this->vals_->size()));
11557 Type* element_type = this->type_->array_type()->element_type();
11558 bool is_constant = true;
11559 if (this->vals_ != NULL)
11560 {
11561 size_t i = 0;
11562 std::vector<unsigned long>::const_iterator pi;
11563 if (this->indexes_ != NULL)
11564 pi = this->indexes_->begin();
11565 for (Expression_list::const_iterator pv = this->vals_->begin();
11566 pv != this->vals_->end();
11567 ++pv, ++i)
11568 {
11569 if (this->indexes_ != NULL)
11570 go_assert(pi != this->indexes_->end());
11571 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11572
11573 if (this->indexes_ == NULL)
11574 elt->index = size_int(i);
11575 else
11576 elt->index = size_int(*pi);
11577
11578 if (*pv == NULL)
11579 {
11580 Gogo* gogo = context->gogo();
11581 Btype* ebtype = element_type->get_backend(gogo);
11582 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11583 elt->value = expr_to_tree(zv);
11584 }
11585 else
11586 {
11587 tree value_tree = (*pv)->get_tree(context);
11588 elt->value = Expression::convert_for_assignment(context,
11589 element_type,
11590 (*pv)->type(),
11591 value_tree,
11592 this->location());
11593 }
11594 if (elt->value == error_mark_node)
11595 return error_mark_node;
11596 if (!TREE_CONSTANT(elt->value))
11597 is_constant = false;
11598 if (this->indexes_ != NULL)
11599 ++pi;
11600 }
11601 if (this->indexes_ != NULL)
11602 go_assert(pi == this->indexes_->end());
11603 }
11604
11605 tree ret = build_constructor(type_tree, values);
11606 if (is_constant)
11607 TREE_CONSTANT(ret) = 1;
11608 return ret;
11609 }
11610
11611 // Export an array construction.
11612
11613 void
11614 Array_construction_expression::do_export(Export* exp) const
11615 {
11616 exp->write_c_string("convert(");
11617 exp->write_type(this->type_);
11618 if (this->vals_ != NULL)
11619 {
11620 std::vector<unsigned long>::const_iterator pi;
11621 if (this->indexes_ != NULL)
11622 pi = this->indexes_->begin();
11623 for (Expression_list::const_iterator pv = this->vals_->begin();
11624 pv != this->vals_->end();
11625 ++pv)
11626 {
11627 exp->write_c_string(", ");
11628
11629 if (this->indexes_ != NULL)
11630 {
11631 char buf[100];
11632 snprintf(buf, sizeof buf, "%lu", *pi);
11633 exp->write_c_string(buf);
11634 exp->write_c_string(":");
11635 }
11636
11637 if (*pv != NULL)
11638 (*pv)->export_expression(exp);
11639
11640 if (this->indexes_ != NULL)
11641 ++pi;
11642 }
11643 }
11644 exp->write_c_string(")");
11645 }
11646
11647 // Dump ast representation of an array construction expressin.
11648
11649 void
11650 Array_construction_expression::do_dump_expression(
11651 Ast_dump_context* ast_dump_context) const
11652 {
11653 Expression* length = this->type_->array_type()->length();
11654
11655 ast_dump_context->ostream() << "[" ;
11656 if (length != NULL)
11657 {
11658 ast_dump_context->dump_expression(length);
11659 }
11660 ast_dump_context->ostream() << "]" ;
11661 ast_dump_context->dump_type(this->type_);
11662 ast_dump_context->ostream() << "{" ;
11663 if (this->indexes_ == NULL)
11664 ast_dump_context->dump_expression_list(this->vals_);
11665 else
11666 {
11667 Expression_list::const_iterator pv = this->vals_->begin();
11668 for (std::vector<unsigned long>::const_iterator pi =
11669 this->indexes_->begin();
11670 pi != this->indexes_->end();
11671 ++pi, ++pv)
11672 {
11673 if (pi != this->indexes_->begin())
11674 ast_dump_context->ostream() << ", ";
11675 ast_dump_context->ostream() << *pi << ':';
11676 ast_dump_context->dump_expression(*pv);
11677 }
11678 }
11679 ast_dump_context->ostream() << "}" ;
11680
11681 }
11682
11683 // Construct a fixed array.
11684
11685 class Fixed_array_construction_expression :
11686 public Array_construction_expression
11687 {
11688 public:
11689 Fixed_array_construction_expression(Type* type,
11690 const std::vector<unsigned long>* indexes,
11691 Expression_list* vals, Location location)
11692 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11693 type, indexes, vals, location)
11694 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11695
11696 protected:
11697 Expression*
11698 do_copy()
11699 {
11700 return new Fixed_array_construction_expression(this->type(),
11701 this->indexes(),
11702 (this->vals() == NULL
11703 ? NULL
11704 : this->vals()->copy()),
11705 this->location());
11706 }
11707
11708 tree
11709 do_get_tree(Translate_context*);
11710 };
11711
11712 // Return a tree for constructing a fixed array.
11713
11714 tree
11715 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11716 {
11717 Type* type = this->type();
11718 Btype* btype = type->get_backend(context->gogo());
11719 return this->get_constructor_tree(context, type_to_tree(btype));
11720 }
11721
11722 // Construct an open array.
11723
11724 class Open_array_construction_expression : public Array_construction_expression
11725 {
11726 public:
11727 Open_array_construction_expression(Type* type,
11728 const std::vector<unsigned long>* indexes,
11729 Expression_list* vals, Location location)
11730 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11731 type, indexes, vals, location)
11732 { go_assert(type->is_slice_type()); }
11733
11734 protected:
11735 // Note that taking the address of an open array literal is invalid.
11736
11737 Expression*
11738 do_copy()
11739 {
11740 return new Open_array_construction_expression(this->type(),
11741 this->indexes(),
11742 (this->vals() == NULL
11743 ? NULL
11744 : this->vals()->copy()),
11745 this->location());
11746 }
11747
11748 tree
11749 do_get_tree(Translate_context*);
11750 };
11751
11752 // Return a tree for constructing an open array.
11753
11754 tree
11755 Open_array_construction_expression::do_get_tree(Translate_context* context)
11756 {
11757 Array_type* array_type = this->type()->array_type();
11758 if (array_type == NULL)
11759 {
11760 go_assert(this->type()->is_error());
11761 return error_mark_node;
11762 }
11763
11764 Type* element_type = array_type->element_type();
11765 Btype* belement_type = element_type->get_backend(context->gogo());
11766 tree element_type_tree = type_to_tree(belement_type);
11767 if (element_type_tree == error_mark_node)
11768 return error_mark_node;
11769
11770 tree values;
11771 tree length_tree;
11772 if (this->vals() == NULL || this->vals()->empty())
11773 {
11774 // We need to create a unique value.
11775 tree max = size_int(0);
11776 tree constructor_type = build_array_type(element_type_tree,
11777 build_index_type(max));
11778 if (constructor_type == error_mark_node)
11779 return error_mark_node;
11780 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11781 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11782 elt->index = size_int(0);
11783 Gogo* gogo = context->gogo();
11784 Btype* btype = element_type->get_backend(gogo);
11785 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11786 values = build_constructor(constructor_type, vec);
11787 if (TREE_CONSTANT(elt->value))
11788 TREE_CONSTANT(values) = 1;
11789 length_tree = size_int(0);
11790 }
11791 else
11792 {
11793 unsigned long max_index;
11794 if (this->indexes() == NULL)
11795 max_index = this->vals()->size() - 1;
11796 else
11797 max_index = this->indexes()->back();
11798 tree max_tree = size_int(max_index);
11799 tree constructor_type = build_array_type(element_type_tree,
11800 build_index_type(max_tree));
11801 if (constructor_type == error_mark_node)
11802 return error_mark_node;
11803 values = this->get_constructor_tree(context, constructor_type);
11804 length_tree = size_int(max_index + 1);
11805 }
11806
11807 if (values == error_mark_node)
11808 return error_mark_node;
11809
11810 bool is_constant_initializer = TREE_CONSTANT(values);
11811
11812 // We have to copy the initial values into heap memory if we are in
11813 // a function or if the values are not constants. We also have to
11814 // copy them if they may contain pointers in a non-constant context,
11815 // as otherwise the garbage collector won't see them.
11816 bool copy_to_heap = (context->function() != NULL
11817 || !is_constant_initializer
11818 || (element_type->has_pointer()
11819 && !context->is_const()));
11820
11821 if (is_constant_initializer)
11822 {
11823 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11824 create_tmp_var_name("C"), TREE_TYPE(values));
11825 DECL_EXTERNAL(tmp) = 0;
11826 TREE_PUBLIC(tmp) = 0;
11827 TREE_STATIC(tmp) = 1;
11828 DECL_ARTIFICIAL(tmp) = 1;
11829 if (copy_to_heap)
11830 {
11831 // If we are not copying the value to the heap, we will only
11832 // initialize the value once, so we can use this directly
11833 // rather than copying it. In that case we can't make it
11834 // read-only, because the program is permitted to change it.
11835 TREE_READONLY(tmp) = 1;
11836 TREE_CONSTANT(tmp) = 1;
11837 }
11838 DECL_INITIAL(tmp) = values;
11839 rest_of_decl_compilation(tmp, 1, 0);
11840 values = tmp;
11841 }
11842
11843 tree space;
11844 tree set;
11845 if (!copy_to_heap)
11846 {
11847 // the initializer will only run once.
11848 space = build_fold_addr_expr(values);
11849 set = NULL_TREE;
11850 }
11851 else
11852 {
11853 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11854 space = context->gogo()->allocate_memory(element_type, memsize,
11855 this->location());
11856 space = save_expr(space);
11857
11858 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11859 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11860 s);
11861 TREE_THIS_NOTRAP(ref) = 1;
11862 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11863 }
11864
11865 // Build a constructor for the open array.
11866
11867 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11868 if (type_tree == error_mark_node)
11869 return error_mark_node;
11870 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11871
11872 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11873
11874 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11875 tree field = TYPE_FIELDS(type_tree);
11876 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11877 elt->index = field;
11878 elt->value = fold_convert(TREE_TYPE(field), space);
11879
11880 elt = VEC_quick_push(constructor_elt, init, NULL);
11881 field = DECL_CHAIN(field);
11882 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11883 elt->index = field;
11884 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11885
11886 elt = VEC_quick_push(constructor_elt, init, NULL);
11887 field = DECL_CHAIN(field);
11888 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11889 elt->index = field;
11890 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11891
11892 tree constructor = build_constructor(type_tree, init);
11893 if (constructor == error_mark_node)
11894 return error_mark_node;
11895 if (!copy_to_heap)
11896 TREE_CONSTANT(constructor) = 1;
11897
11898 if (set == NULL_TREE)
11899 return constructor;
11900 else
11901 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11902 }
11903
11904 // Make a slice composite literal. This is used by the type
11905 // descriptor code.
11906
11907 Expression*
11908 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11909 Location location)
11910 {
11911 go_assert(type->is_slice_type());
11912 return new Open_array_construction_expression(type, NULL, vals, location);
11913 }
11914
11915 // Construct a map.
11916
11917 class Map_construction_expression : public Expression
11918 {
11919 public:
11920 Map_construction_expression(Type* type, Expression_list* vals,
11921 Location location)
11922 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11923 type_(type), vals_(vals)
11924 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11925
11926 protected:
11927 int
11928 do_traverse(Traverse* traverse);
11929
11930 Type*
11931 do_type()
11932 { return this->type_; }
11933
11934 void
11935 do_determine_type(const Type_context*);
11936
11937 void
11938 do_check_types(Gogo*);
11939
11940 Expression*
11941 do_copy()
11942 {
11943 return new Map_construction_expression(this->type_, this->vals_->copy(),
11944 this->location());
11945 }
11946
11947 tree
11948 do_get_tree(Translate_context*);
11949
11950 void
11951 do_export(Export*) const;
11952
11953 void
11954 do_dump_expression(Ast_dump_context*) const;
11955
11956 private:
11957 // The type of the map to construct.
11958 Type* type_;
11959 // The list of values.
11960 Expression_list* vals_;
11961 };
11962
11963 // Traversal.
11964
11965 int
11966 Map_construction_expression::do_traverse(Traverse* traverse)
11967 {
11968 if (this->vals_ != NULL
11969 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11970 return TRAVERSE_EXIT;
11971 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11972 return TRAVERSE_EXIT;
11973 return TRAVERSE_CONTINUE;
11974 }
11975
11976 // Final type determination.
11977
11978 void
11979 Map_construction_expression::do_determine_type(const Type_context*)
11980 {
11981 if (this->vals_ == NULL)
11982 return;
11983
11984 Map_type* mt = this->type_->map_type();
11985 Type_context key_context(mt->key_type(), false);
11986 Type_context val_context(mt->val_type(), false);
11987 for (Expression_list::const_iterator pv = this->vals_->begin();
11988 pv != this->vals_->end();
11989 ++pv)
11990 {
11991 (*pv)->determine_type(&key_context);
11992 ++pv;
11993 (*pv)->determine_type(&val_context);
11994 }
11995 }
11996
11997 // Check types.
11998
11999 void
12000 Map_construction_expression::do_check_types(Gogo*)
12001 {
12002 if (this->vals_ == NULL)
12003 return;
12004
12005 Map_type* mt = this->type_->map_type();
12006 int i = 0;
12007 Type* key_type = mt->key_type();
12008 Type* val_type = mt->val_type();
12009 for (Expression_list::const_iterator pv = this->vals_->begin();
12010 pv != this->vals_->end();
12011 ++pv, ++i)
12012 {
12013 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12014 {
12015 error_at((*pv)->location(),
12016 "incompatible type for element %d key in map construction",
12017 i + 1);
12018 this->set_is_error();
12019 }
12020 ++pv;
12021 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12022 {
12023 error_at((*pv)->location(),
12024 ("incompatible type for element %d value "
12025 "in map construction"),
12026 i + 1);
12027 this->set_is_error();
12028 }
12029 }
12030 }
12031
12032 // Return a tree for constructing a map.
12033
12034 tree
12035 Map_construction_expression::do_get_tree(Translate_context* context)
12036 {
12037 Gogo* gogo = context->gogo();
12038 Location loc = this->location();
12039
12040 Map_type* mt = this->type_->map_type();
12041
12042 // Build a struct to hold the key and value.
12043 tree struct_type = make_node(RECORD_TYPE);
12044
12045 Type* key_type = mt->key_type();
12046 tree id = get_identifier("__key");
12047 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12048 if (key_type_tree == error_mark_node)
12049 return error_mark_node;
12050 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12051 key_type_tree);
12052 DECL_CONTEXT(key_field) = struct_type;
12053 TYPE_FIELDS(struct_type) = key_field;
12054
12055 Type* val_type = mt->val_type();
12056 id = get_identifier("__val");
12057 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12058 if (val_type_tree == error_mark_node)
12059 return error_mark_node;
12060 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12061 val_type_tree);
12062 DECL_CONTEXT(val_field) = struct_type;
12063 DECL_CHAIN(key_field) = val_field;
12064
12065 layout_type(struct_type);
12066
12067 bool is_constant = true;
12068 size_t i = 0;
12069 tree valaddr;
12070 tree make_tmp;
12071
12072 if (this->vals_ == NULL || this->vals_->empty())
12073 {
12074 valaddr = null_pointer_node;
12075 make_tmp = NULL_TREE;
12076 }
12077 else
12078 {
12079 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12080 this->vals_->size() / 2);
12081
12082 for (Expression_list::const_iterator pv = this->vals_->begin();
12083 pv != this->vals_->end();
12084 ++pv, ++i)
12085 {
12086 bool one_is_constant = true;
12087
12088 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12089
12090 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12091 elt->index = key_field;
12092 tree val_tree = (*pv)->get_tree(context);
12093 elt->value = Expression::convert_for_assignment(context, key_type,
12094 (*pv)->type(),
12095 val_tree, loc);
12096 if (elt->value == error_mark_node)
12097 return error_mark_node;
12098 if (!TREE_CONSTANT(elt->value))
12099 one_is_constant = false;
12100
12101 ++pv;
12102
12103 elt = VEC_quick_push(constructor_elt, one, NULL);
12104 elt->index = val_field;
12105 val_tree = (*pv)->get_tree(context);
12106 elt->value = Expression::convert_for_assignment(context, val_type,
12107 (*pv)->type(),
12108 val_tree, loc);
12109 if (elt->value == error_mark_node)
12110 return error_mark_node;
12111 if (!TREE_CONSTANT(elt->value))
12112 one_is_constant = false;
12113
12114 elt = VEC_quick_push(constructor_elt, values, NULL);
12115 elt->index = size_int(i);
12116 elt->value = build_constructor(struct_type, one);
12117 if (one_is_constant)
12118 TREE_CONSTANT(elt->value) = 1;
12119 else
12120 is_constant = false;
12121 }
12122
12123 tree index_type = build_index_type(size_int(i - 1));
12124 tree array_type = build_array_type(struct_type, index_type);
12125 tree init = build_constructor(array_type, values);
12126 if (is_constant)
12127 TREE_CONSTANT(init) = 1;
12128 tree tmp;
12129 if (current_function_decl != NULL)
12130 {
12131 tmp = create_tmp_var(array_type, get_name(array_type));
12132 DECL_INITIAL(tmp) = init;
12133 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12134 void_type_node, tmp);
12135 TREE_ADDRESSABLE(tmp) = 1;
12136 }
12137 else
12138 {
12139 tmp = build_decl(loc.gcc_location(), VAR_DECL,
12140 create_tmp_var_name("M"), array_type);
12141 DECL_EXTERNAL(tmp) = 0;
12142 TREE_PUBLIC(tmp) = 0;
12143 TREE_STATIC(tmp) = 1;
12144 DECL_ARTIFICIAL(tmp) = 1;
12145 if (!TREE_CONSTANT(init))
12146 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
12147 void_type_node, tmp, init);
12148 else
12149 {
12150 TREE_READONLY(tmp) = 1;
12151 TREE_CONSTANT(tmp) = 1;
12152 DECL_INITIAL(tmp) = init;
12153 make_tmp = NULL_TREE;
12154 }
12155 rest_of_decl_compilation(tmp, 1, 0);
12156 }
12157
12158 valaddr = build_fold_addr_expr(tmp);
12159 }
12160
12161 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
12162
12163 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12164 if (type_tree == error_mark_node)
12165 return error_mark_node;
12166
12167 static tree construct_map_fndecl;
12168 tree call = Gogo::call_builtin(&construct_map_fndecl,
12169 loc,
12170 "__go_construct_map",
12171 6,
12172 type_tree,
12173 TREE_TYPE(descriptor),
12174 descriptor,
12175 sizetype,
12176 size_int(i),
12177 sizetype,
12178 TYPE_SIZE_UNIT(struct_type),
12179 sizetype,
12180 byte_position(val_field),
12181 sizetype,
12182 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
12183 const_ptr_type_node,
12184 fold_convert(const_ptr_type_node, valaddr));
12185 if (call == error_mark_node)
12186 return error_mark_node;
12187
12188 tree ret;
12189 if (make_tmp == NULL)
12190 ret = call;
12191 else
12192 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12193 make_tmp, call);
12194 return ret;
12195 }
12196
12197 // Export an array construction.
12198
12199 void
12200 Map_construction_expression::do_export(Export* exp) const
12201 {
12202 exp->write_c_string("convert(");
12203 exp->write_type(this->type_);
12204 for (Expression_list::const_iterator pv = this->vals_->begin();
12205 pv != this->vals_->end();
12206 ++pv)
12207 {
12208 exp->write_c_string(", ");
12209 (*pv)->export_expression(exp);
12210 }
12211 exp->write_c_string(")");
12212 }
12213
12214 // Dump ast representation for a map construction expression.
12215
12216 void
12217 Map_construction_expression::do_dump_expression(
12218 Ast_dump_context* ast_dump_context) const
12219 {
12220 ast_dump_context->ostream() << "{" ;
12221 ast_dump_context->dump_expression_list(this->vals_, true);
12222 ast_dump_context->ostream() << "}";
12223 }
12224
12225 // A general composite literal. This is lowered to a type specific
12226 // version.
12227
12228 class Composite_literal_expression : public Parser_expression
12229 {
12230 public:
12231 Composite_literal_expression(Type* type, int depth, bool has_keys,
12232 Expression_list* vals, Location location)
12233 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12234 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12235 { }
12236
12237 protected:
12238 int
12239 do_traverse(Traverse* traverse);
12240
12241 Expression*
12242 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12243
12244 Expression*
12245 do_copy()
12246 {
12247 return new Composite_literal_expression(this->type_, this->depth_,
12248 this->has_keys_,
12249 (this->vals_ == NULL
12250 ? NULL
12251 : this->vals_->copy()),
12252 this->location());
12253 }
12254
12255 void
12256 do_dump_expression(Ast_dump_context*) const;
12257
12258 private:
12259 Expression*
12260 lower_struct(Gogo*, Type*);
12261
12262 Expression*
12263 lower_array(Type*);
12264
12265 Expression*
12266 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12267
12268 Expression*
12269 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12270
12271 // The type of the composite literal.
12272 Type* type_;
12273 // The depth within a list of composite literals within a composite
12274 // literal, when the type is omitted.
12275 int depth_;
12276 // The values to put in the composite literal.
12277 Expression_list* vals_;
12278 // If this is true, then VALS_ is a list of pairs: a key and a
12279 // value. In an array initializer, a missing key will be NULL.
12280 bool has_keys_;
12281 };
12282
12283 // Traversal.
12284
12285 int
12286 Composite_literal_expression::do_traverse(Traverse* traverse)
12287 {
12288 if (this->vals_ != NULL
12289 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12290 return TRAVERSE_EXIT;
12291 return Type::traverse(this->type_, traverse);
12292 }
12293
12294 // Lower a generic composite literal into a specific version based on
12295 // the type.
12296
12297 Expression*
12298 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12299 Statement_inserter* inserter, int)
12300 {
12301 Type* type = this->type_;
12302
12303 for (int depth = this->depth_; depth > 0; --depth)
12304 {
12305 if (type->array_type() != NULL)
12306 type = type->array_type()->element_type();
12307 else if (type->map_type() != NULL)
12308 type = type->map_type()->val_type();
12309 else
12310 {
12311 if (!type->is_error())
12312 error_at(this->location(),
12313 ("may only omit types within composite literals "
12314 "of slice, array, or map type"));
12315 return Expression::make_error(this->location());
12316 }
12317 }
12318
12319 Type *pt = type->points_to();
12320 bool is_pointer = false;
12321 if (pt != NULL)
12322 {
12323 is_pointer = true;
12324 type = pt;
12325 }
12326
12327 Expression* ret;
12328 if (type->is_error())
12329 return Expression::make_error(this->location());
12330 else if (type->struct_type() != NULL)
12331 ret = this->lower_struct(gogo, type);
12332 else if (type->array_type() != NULL)
12333 ret = this->lower_array(type);
12334 else if (type->map_type() != NULL)
12335 ret = this->lower_map(gogo, function, inserter, type);
12336 else
12337 {
12338 error_at(this->location(),
12339 ("expected struct, slice, array, or map type "
12340 "for composite literal"));
12341 return Expression::make_error(this->location());
12342 }
12343
12344 if (is_pointer)
12345 ret = Expression::make_heap_composite(ret, this->location());
12346
12347 return ret;
12348 }
12349
12350 // Lower a struct composite literal.
12351
12352 Expression*
12353 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12354 {
12355 Location location = this->location();
12356 Struct_type* st = type->struct_type();
12357 if (this->vals_ == NULL || !this->has_keys_)
12358 {
12359 if (this->vals_ != NULL
12360 && !this->vals_->empty()
12361 && type->named_type() != NULL
12362 && type->named_type()->named_object()->package() != NULL)
12363 {
12364 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12365 pf != st->fields()->end();
12366 ++pf)
12367 {
12368 if (Gogo::is_hidden_name(pf->field_name()))
12369 error_at(this->location(),
12370 "assignment of unexported field %qs in %qs literal",
12371 Gogo::message_name(pf->field_name()).c_str(),
12372 type->named_type()->message_name().c_str());
12373 }
12374 }
12375
12376 return new Struct_construction_expression(type, this->vals_, location);
12377 }
12378
12379 size_t field_count = st->field_count();
12380 std::vector<Expression*> vals(field_count);
12381 std::vector<int>* traverse_order = new(std::vector<int>);
12382 Expression_list::const_iterator p = this->vals_->begin();
12383 while (p != this->vals_->end())
12384 {
12385 Expression* name_expr = *p;
12386
12387 ++p;
12388 go_assert(p != this->vals_->end());
12389 Expression* val = *p;
12390
12391 ++p;
12392
12393 if (name_expr == NULL)
12394 {
12395 error_at(val->location(), "mixture of field and value initializers");
12396 return Expression::make_error(location);
12397 }
12398
12399 bool bad_key = false;
12400 std::string name;
12401 const Named_object* no = NULL;
12402 switch (name_expr->classification())
12403 {
12404 case EXPRESSION_UNKNOWN_REFERENCE:
12405 name = name_expr->unknown_expression()->name();
12406 break;
12407
12408 case EXPRESSION_CONST_REFERENCE:
12409 no = static_cast<Const_expression*>(name_expr)->named_object();
12410 break;
12411
12412 case EXPRESSION_TYPE:
12413 {
12414 Type* t = name_expr->type();
12415 Named_type* nt = t->named_type();
12416 if (nt == NULL)
12417 bad_key = true;
12418 else
12419 no = nt->named_object();
12420 }
12421 break;
12422
12423 case EXPRESSION_VAR_REFERENCE:
12424 no = name_expr->var_expression()->named_object();
12425 break;
12426
12427 case EXPRESSION_FUNC_REFERENCE:
12428 no = name_expr->func_expression()->named_object();
12429 break;
12430
12431 case EXPRESSION_UNARY:
12432 // If there is a local variable around with the same name as
12433 // the field, and this occurs in the closure, then the
12434 // parser may turn the field reference into an indirection
12435 // through the closure. FIXME: This is a mess.
12436 {
12437 bad_key = true;
12438 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12439 if (ue->op() == OPERATOR_MULT)
12440 {
12441 Field_reference_expression* fre =
12442 ue->operand()->field_reference_expression();
12443 if (fre != NULL)
12444 {
12445 Struct_type* st =
12446 fre->expr()->type()->deref()->struct_type();
12447 if (st != NULL)
12448 {
12449 const Struct_field* sf = st->field(fre->field_index());
12450 name = sf->field_name();
12451
12452 // See below. FIXME.
12453 if (!Gogo::is_hidden_name(name)
12454 && name[0] >= 'a'
12455 && name[0] <= 'z')
12456 {
12457 if (gogo->lookup_global(name.c_str()) != NULL)
12458 name = gogo->pack_hidden_name(name, false);
12459 }
12460
12461 char buf[20];
12462 snprintf(buf, sizeof buf, "%u", fre->field_index());
12463 size_t buflen = strlen(buf);
12464 if (name.compare(name.length() - buflen, buflen, buf)
12465 == 0)
12466 {
12467 name = name.substr(0, name.length() - buflen);
12468 bad_key = false;
12469 }
12470 }
12471 }
12472 }
12473 }
12474 break;
12475
12476 default:
12477 bad_key = true;
12478 break;
12479 }
12480 if (bad_key)
12481 {
12482 error_at(name_expr->location(), "expected struct field name");
12483 return Expression::make_error(location);
12484 }
12485
12486 if (no != NULL)
12487 {
12488 name = no->name();
12489
12490 // A predefined name won't be packed. If it starts with a
12491 // lower case letter we need to check for that case, because
12492 // the field name will be packed. FIXME.
12493 if (!Gogo::is_hidden_name(name)
12494 && name[0] >= 'a'
12495 && name[0] <= 'z')
12496 {
12497 Named_object* gno = gogo->lookup_global(name.c_str());
12498 if (gno == no)
12499 name = gogo->pack_hidden_name(name, false);
12500 }
12501 }
12502
12503 unsigned int index;
12504 const Struct_field* sf = st->find_local_field(name, &index);
12505 if (sf == NULL)
12506 {
12507 error_at(name_expr->location(), "unknown field %qs in %qs",
12508 Gogo::message_name(name).c_str(),
12509 (type->named_type() != NULL
12510 ? type->named_type()->message_name().c_str()
12511 : "unnamed struct"));
12512 return Expression::make_error(location);
12513 }
12514 if (vals[index] != NULL)
12515 {
12516 error_at(name_expr->location(),
12517 "duplicate value for field %qs in %qs",
12518 Gogo::message_name(name).c_str(),
12519 (type->named_type() != NULL
12520 ? type->named_type()->message_name().c_str()
12521 : "unnamed struct"));
12522 return Expression::make_error(location);
12523 }
12524
12525 if (type->named_type() != NULL
12526 && type->named_type()->named_object()->package() != NULL
12527 && Gogo::is_hidden_name(sf->field_name()))
12528 error_at(name_expr->location(),
12529 "assignment of unexported field %qs in %qs literal",
12530 Gogo::message_name(sf->field_name()).c_str(),
12531 type->named_type()->message_name().c_str());
12532
12533 vals[index] = val;
12534 traverse_order->push_back(index);
12535 }
12536
12537 Expression_list* list = new Expression_list;
12538 list->reserve(field_count);
12539 for (size_t i = 0; i < field_count; ++i)
12540 list->push_back(vals[i]);
12541
12542 Struct_construction_expression* ret =
12543 new Struct_construction_expression(type, list, location);
12544 ret->set_traverse_order(traverse_order);
12545 return ret;
12546 }
12547
12548 // Used to sort an index/value array.
12549
12550 class Index_value_compare
12551 {
12552 public:
12553 bool
12554 operator()(const std::pair<unsigned long, Expression*>& a,
12555 const std::pair<unsigned long, Expression*>& b)
12556 { return a.first < b.first; }
12557 };
12558
12559 // Lower an array composite literal.
12560
12561 Expression*
12562 Composite_literal_expression::lower_array(Type* type)
12563 {
12564 Location location = this->location();
12565 if (this->vals_ == NULL || !this->has_keys_)
12566 return this->make_array(type, NULL, this->vals_);
12567
12568 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12569 indexes->reserve(this->vals_->size());
12570 bool indexes_out_of_order = false;
12571 Expression_list* vals = new Expression_list();
12572 vals->reserve(this->vals_->size());
12573 unsigned long index = 0;
12574 Expression_list::const_iterator p = this->vals_->begin();
12575 while (p != this->vals_->end())
12576 {
12577 Expression* index_expr = *p;
12578
12579 ++p;
12580 go_assert(p != this->vals_->end());
12581 Expression* val = *p;
12582
12583 ++p;
12584
12585 if (index_expr == NULL)
12586 {
12587 if (!indexes->empty())
12588 indexes->push_back(index);
12589 }
12590 else
12591 {
12592 if (indexes->empty() && !vals->empty())
12593 {
12594 for (size_t i = 0; i < vals->size(); ++i)
12595 indexes->push_back(i);
12596 }
12597
12598 Numeric_constant nc;
12599 if (!index_expr->numeric_constant_value(&nc))
12600 {
12601 error_at(index_expr->location(),
12602 "index expression is not integer constant");
12603 return Expression::make_error(location);
12604 }
12605
12606 switch (nc.to_unsigned_long(&index))
12607 {
12608 case Numeric_constant::NC_UL_VALID:
12609 break;
12610 case Numeric_constant::NC_UL_NOTINT:
12611 error_at(index_expr->location(),
12612 "index expression is not integer constant");
12613 return Expression::make_error(location);
12614 case Numeric_constant::NC_UL_NEGATIVE:
12615 error_at(index_expr->location(), "index expression is negative");
12616 return Expression::make_error(location);
12617 case Numeric_constant::NC_UL_BIG:
12618 error_at(index_expr->location(), "index value overflow");
12619 return Expression::make_error(location);
12620 default:
12621 go_unreachable();
12622 }
12623
12624 Named_type* ntype = Type::lookup_integer_type("int");
12625 Integer_type* inttype = ntype->integer_type();
12626 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12627 && index >> (inttype->bits() - 1) != 0)
12628 {
12629 error_at(index_expr->location(), "index value overflow");
12630 return Expression::make_error(location);
12631 }
12632
12633 if (std::find(indexes->begin(), indexes->end(), index)
12634 != indexes->end())
12635 {
12636 error_at(index_expr->location(), "duplicate value for index %lu",
12637 index);
12638 return Expression::make_error(location);
12639 }
12640
12641 if (!indexes->empty() && index < indexes->back())
12642 indexes_out_of_order = true;
12643
12644 indexes->push_back(index);
12645 }
12646
12647 vals->push_back(val);
12648
12649 ++index;
12650 }
12651
12652 if (indexes->empty())
12653 {
12654 delete indexes;
12655 indexes = NULL;
12656 }
12657
12658 if (indexes_out_of_order)
12659 {
12660 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12661
12662 V v;
12663 v.reserve(indexes->size());
12664 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12665 for (Expression_list::const_iterator pe = vals->begin();
12666 pe != vals->end();
12667 ++pe, ++pi)
12668 v.push_back(std::make_pair(*pi, *pe));
12669
12670 std::sort(v.begin(), v.end(), Index_value_compare());
12671
12672 delete indexes;
12673 delete vals;
12674 indexes = new std::vector<unsigned long>();
12675 indexes->reserve(v.size());
12676 vals = new Expression_list();
12677 vals->reserve(v.size());
12678
12679 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12680 {
12681 indexes->push_back(p->first);
12682 vals->push_back(p->second);
12683 }
12684 }
12685
12686 return this->make_array(type, indexes, vals);
12687 }
12688
12689 // Actually build the array composite literal. This handles
12690 // [...]{...}.
12691
12692 Expression*
12693 Composite_literal_expression::make_array(
12694 Type* type,
12695 const std::vector<unsigned long>* indexes,
12696 Expression_list* vals)
12697 {
12698 Location location = this->location();
12699 Array_type* at = type->array_type();
12700
12701 if (at->length() != NULL && at->length()->is_nil_expression())
12702 {
12703 size_t size;
12704 if (vals == NULL)
12705 size = 0;
12706 else if (indexes != NULL)
12707 size = indexes->back() + 1;
12708 else
12709 {
12710 size = vals->size();
12711 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12712 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12713 && size >> (it->bits() - 1) != 0)
12714 {
12715 error_at(location, "too many elements in composite literal");
12716 return Expression::make_error(location);
12717 }
12718 }
12719
12720 mpz_t vlen;
12721 mpz_init_set_ui(vlen, size);
12722 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12723 mpz_clear(vlen);
12724 at = Type::make_array_type(at->element_type(), elen);
12725 type = at;
12726 }
12727 else if (at->length() != NULL
12728 && !at->length()->is_error_expression()
12729 && this->vals_ != NULL)
12730 {
12731 Numeric_constant nc;
12732 unsigned long val;
12733 if (at->length()->numeric_constant_value(&nc)
12734 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12735 {
12736 if (indexes == NULL)
12737 {
12738 if (this->vals_->size() > val)
12739 {
12740 error_at(location, "too many elements in composite literal");
12741 return Expression::make_error(location);
12742 }
12743 }
12744 else
12745 {
12746 unsigned long max = indexes->back();
12747 if (max >= val)
12748 {
12749 error_at(location,
12750 ("some element keys in composite literal "
12751 "are out of range"));
12752 return Expression::make_error(location);
12753 }
12754 }
12755 }
12756 }
12757
12758 if (at->length() != NULL)
12759 return new Fixed_array_construction_expression(type, indexes, vals,
12760 location);
12761 else
12762 return new Open_array_construction_expression(type, indexes, vals,
12763 location);
12764 }
12765
12766 // Lower a map composite literal.
12767
12768 Expression*
12769 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12770 Statement_inserter* inserter,
12771 Type* type)
12772 {
12773 Location location = this->location();
12774 if (this->vals_ != NULL)
12775 {
12776 if (!this->has_keys_)
12777 {
12778 error_at(location, "map composite literal must have keys");
12779 return Expression::make_error(location);
12780 }
12781
12782 for (Expression_list::iterator p = this->vals_->begin();
12783 p != this->vals_->end();
12784 p += 2)
12785 {
12786 if (*p == NULL)
12787 {
12788 ++p;
12789 error_at((*p)->location(),
12790 "map composite literal must have keys for every value");
12791 return Expression::make_error(location);
12792 }
12793 // Make sure we have lowered the key; it may not have been
12794 // lowered in order to handle keys for struct composite
12795 // literals. Lower it now to get the right error message.
12796 if ((*p)->unknown_expression() != NULL)
12797 {
12798 (*p)->unknown_expression()->clear_is_composite_literal_key();
12799 gogo->lower_expression(function, inserter, &*p);
12800 go_assert((*p)->is_error_expression());
12801 return Expression::make_error(location);
12802 }
12803 }
12804 }
12805
12806 return new Map_construction_expression(type, this->vals_, location);
12807 }
12808
12809 // Dump ast representation for a composite literal expression.
12810
12811 void
12812 Composite_literal_expression::do_dump_expression(
12813 Ast_dump_context* ast_dump_context) const
12814 {
12815 ast_dump_context->ostream() << "composite(";
12816 ast_dump_context->dump_type(this->type_);
12817 ast_dump_context->ostream() << ", {";
12818 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12819 ast_dump_context->ostream() << "})";
12820 }
12821
12822 // Make a composite literal expression.
12823
12824 Expression*
12825 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12826 Expression_list* vals,
12827 Location location)
12828 {
12829 return new Composite_literal_expression(type, depth, has_keys, vals,
12830 location);
12831 }
12832
12833 // Return whether this expression is a composite literal.
12834
12835 bool
12836 Expression::is_composite_literal() const
12837 {
12838 switch (this->classification_)
12839 {
12840 case EXPRESSION_COMPOSITE_LITERAL:
12841 case EXPRESSION_STRUCT_CONSTRUCTION:
12842 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12843 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12844 case EXPRESSION_MAP_CONSTRUCTION:
12845 return true;
12846 default:
12847 return false;
12848 }
12849 }
12850
12851 // Return whether this expression is a composite literal which is not
12852 // constant.
12853
12854 bool
12855 Expression::is_nonconstant_composite_literal() const
12856 {
12857 switch (this->classification_)
12858 {
12859 case EXPRESSION_STRUCT_CONSTRUCTION:
12860 {
12861 const Struct_construction_expression *psce =
12862 static_cast<const Struct_construction_expression*>(this);
12863 return !psce->is_constant_struct();
12864 }
12865 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12866 {
12867 const Fixed_array_construction_expression *pace =
12868 static_cast<const Fixed_array_construction_expression*>(this);
12869 return !pace->is_constant_array();
12870 }
12871 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12872 {
12873 const Open_array_construction_expression *pace =
12874 static_cast<const Open_array_construction_expression*>(this);
12875 return !pace->is_constant_array();
12876 }
12877 case EXPRESSION_MAP_CONSTRUCTION:
12878 return true;
12879 default:
12880 return false;
12881 }
12882 }
12883
12884 // Return true if this is a reference to a local variable.
12885
12886 bool
12887 Expression::is_local_variable() const
12888 {
12889 const Var_expression* ve = this->var_expression();
12890 if (ve == NULL)
12891 return false;
12892 const Named_object* no = ve->named_object();
12893 return (no->is_result_variable()
12894 || (no->is_variable() && !no->var_value()->is_global()));
12895 }
12896
12897 // Class Type_guard_expression.
12898
12899 // Traversal.
12900
12901 int
12902 Type_guard_expression::do_traverse(Traverse* traverse)
12903 {
12904 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12905 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12906 return TRAVERSE_EXIT;
12907 return TRAVERSE_CONTINUE;
12908 }
12909
12910 // Check types of a type guard expression. The expression must have
12911 // an interface type, but the actual type conversion is checked at run
12912 // time.
12913
12914 void
12915 Type_guard_expression::do_check_types(Gogo*)
12916 {
12917 // 6g permits using a type guard with unsafe.pointer; we are
12918 // compatible.
12919 Type* expr_type = this->expr_->type();
12920 if (expr_type->is_unsafe_pointer_type())
12921 {
12922 if (this->type_->points_to() == NULL
12923 && (this->type_->integer_type() == NULL
12924 || (this->type_->forwarded()
12925 != Type::lookup_integer_type("uintptr"))))
12926 this->report_error(_("invalid unsafe.Pointer conversion"));
12927 }
12928 else if (this->type_->is_unsafe_pointer_type())
12929 {
12930 if (expr_type->points_to() == NULL
12931 && (expr_type->integer_type() == NULL
12932 || (expr_type->forwarded()
12933 != Type::lookup_integer_type("uintptr"))))
12934 this->report_error(_("invalid unsafe.Pointer conversion"));
12935 }
12936 else if (expr_type->interface_type() == NULL)
12937 {
12938 if (!expr_type->is_error() && !this->type_->is_error())
12939 this->report_error(_("type assertion only valid for interface types"));
12940 this->set_is_error();
12941 }
12942 else if (this->type_->interface_type() == NULL)
12943 {
12944 std::string reason;
12945 if (!expr_type->interface_type()->implements_interface(this->type_,
12946 &reason))
12947 {
12948 if (!this->type_->is_error())
12949 {
12950 if (reason.empty())
12951 this->report_error(_("impossible type assertion: "
12952 "type does not implement interface"));
12953 else
12954 error_at(this->location(),
12955 ("impossible type assertion: "
12956 "type does not implement interface (%s)"),
12957 reason.c_str());
12958 }
12959 this->set_is_error();
12960 }
12961 }
12962 }
12963
12964 // Return a tree for a type guard expression.
12965
12966 tree
12967 Type_guard_expression::do_get_tree(Translate_context* context)
12968 {
12969 Gogo* gogo = context->gogo();
12970 tree expr_tree = this->expr_->get_tree(context);
12971 if (expr_tree == error_mark_node)
12972 return error_mark_node;
12973 Type* expr_type = this->expr_->type();
12974 if ((this->type_->is_unsafe_pointer_type()
12975 && (expr_type->points_to() != NULL
12976 || expr_type->integer_type() != NULL))
12977 || (expr_type->is_unsafe_pointer_type()
12978 && this->type_->points_to() != NULL))
12979 return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12980 expr_tree);
12981 else if (expr_type->is_unsafe_pointer_type()
12982 && this->type_->integer_type() != NULL)
12983 return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12984 expr_tree);
12985 else if (this->type_->interface_type() != NULL)
12986 return Expression::convert_interface_to_interface(context, this->type_,
12987 this->expr_->type(),
12988 expr_tree, true,
12989 this->location());
12990 else
12991 return Expression::convert_for_assignment(context, this->type_,
12992 this->expr_->type(), expr_tree,
12993 this->location());
12994 }
12995
12996 // Dump ast representation for a type guard expression.
12997
12998 void
12999 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13000 const
13001 {
13002 this->expr_->dump_expression(ast_dump_context);
13003 ast_dump_context->ostream() << ".";
13004 ast_dump_context->dump_type(this->type_);
13005 }
13006
13007 // Make a type guard expression.
13008
13009 Expression*
13010 Expression::make_type_guard(Expression* expr, Type* type,
13011 Location location)
13012 {
13013 return new Type_guard_expression(expr, type, location);
13014 }
13015
13016 // Class Heap_composite_expression.
13017
13018 // When you take the address of a composite literal, it is allocated
13019 // on the heap. This class implements that.
13020
13021 class Heap_composite_expression : public Expression
13022 {
13023 public:
13024 Heap_composite_expression(Expression* expr, Location location)
13025 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13026 expr_(expr)
13027 { }
13028
13029 protected:
13030 int
13031 do_traverse(Traverse* traverse)
13032 { return Expression::traverse(&this->expr_, traverse); }
13033
13034 Type*
13035 do_type()
13036 { return Type::make_pointer_type(this->expr_->type()); }
13037
13038 void
13039 do_determine_type(const Type_context*)
13040 { this->expr_->determine_type_no_context(); }
13041
13042 Expression*
13043 do_copy()
13044 {
13045 return Expression::make_heap_composite(this->expr_->copy(),
13046 this->location());
13047 }
13048
13049 tree
13050 do_get_tree(Translate_context*);
13051
13052 // We only export global objects, and the parser does not generate
13053 // this in global scope.
13054 void
13055 do_export(Export*) const
13056 { go_unreachable(); }
13057
13058 void
13059 do_dump_expression(Ast_dump_context*) const;
13060
13061 private:
13062 // The composite literal which is being put on the heap.
13063 Expression* expr_;
13064 };
13065
13066 // Return a tree which allocates a composite literal on the heap.
13067
13068 tree
13069 Heap_composite_expression::do_get_tree(Translate_context* context)
13070 {
13071 tree expr_tree = this->expr_->get_tree(context);
13072 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13073 return error_mark_node;
13074 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13075 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13076 tree space = context->gogo()->allocate_memory(this->expr_->type(),
13077 expr_size, this->location());
13078 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13079 space = save_expr(space);
13080 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13081 space);
13082 TREE_THIS_NOTRAP(ref) = 1;
13083 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13084 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13085 space);
13086 SET_EXPR_LOCATION(ret, this->location().gcc_location());
13087 return ret;
13088 }
13089
13090 // Dump ast representation for a heap composite expression.
13091
13092 void
13093 Heap_composite_expression::do_dump_expression(
13094 Ast_dump_context* ast_dump_context) const
13095 {
13096 ast_dump_context->ostream() << "&(";
13097 ast_dump_context->dump_expression(this->expr_);
13098 ast_dump_context->ostream() << ")";
13099 }
13100
13101 // Allocate a composite literal on the heap.
13102
13103 Expression*
13104 Expression::make_heap_composite(Expression* expr, Location location)
13105 {
13106 return new Heap_composite_expression(expr, location);
13107 }
13108
13109 // Class Receive_expression.
13110
13111 // Return the type of a receive expression.
13112
13113 Type*
13114 Receive_expression::do_type()
13115 {
13116 Channel_type* channel_type = this->channel_->type()->channel_type();
13117 if (channel_type == NULL)
13118 return Type::make_error_type();
13119 return channel_type->element_type();
13120 }
13121
13122 // Check types for a receive expression.
13123
13124 void
13125 Receive_expression::do_check_types(Gogo*)
13126 {
13127 Type* type = this->channel_->type();
13128 if (type->is_error())
13129 {
13130 this->set_is_error();
13131 return;
13132 }
13133 if (type->channel_type() == NULL)
13134 {
13135 this->report_error(_("expected channel"));
13136 return;
13137 }
13138 if (!type->channel_type()->may_receive())
13139 {
13140 this->report_error(_("invalid receive on send-only channel"));
13141 return;
13142 }
13143 }
13144
13145 // Get a tree for a receive expression.
13146
13147 tree
13148 Receive_expression::do_get_tree(Translate_context* context)
13149 {
13150 Location loc = this->location();
13151
13152 Channel_type* channel_type = this->channel_->type()->channel_type();
13153 if (channel_type == NULL)
13154 {
13155 go_assert(this->channel_->type()->is_error());
13156 return error_mark_node;
13157 }
13158
13159 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13160 tree td_tree = td->get_tree(context);
13161
13162 Type* element_type = channel_type->element_type();
13163 Btype* element_type_btype = element_type->get_backend(context->gogo());
13164 tree element_type_tree = type_to_tree(element_type_btype);
13165
13166 tree channel = this->channel_->get_tree(context);
13167 if (element_type_tree == error_mark_node || channel == error_mark_node)
13168 return error_mark_node;
13169
13170 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13171 }
13172
13173 // Dump ast representation for a receive expression.
13174
13175 void
13176 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13177 {
13178 ast_dump_context->ostream() << " <- " ;
13179 ast_dump_context->dump_expression(channel_);
13180 }
13181
13182 // Make a receive expression.
13183
13184 Receive_expression*
13185 Expression::make_receive(Expression* channel, Location location)
13186 {
13187 return new Receive_expression(channel, location);
13188 }
13189
13190 // An expression which evaluates to a pointer to the type descriptor
13191 // of a type.
13192
13193 class Type_descriptor_expression : public Expression
13194 {
13195 public:
13196 Type_descriptor_expression(Type* type, Location location)
13197 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13198 type_(type)
13199 { }
13200
13201 protected:
13202 Type*
13203 do_type()
13204 { return Type::make_type_descriptor_ptr_type(); }
13205
13206 void
13207 do_determine_type(const Type_context*)
13208 { }
13209
13210 Expression*
13211 do_copy()
13212 { return this; }
13213
13214 tree
13215 do_get_tree(Translate_context* context)
13216 {
13217 return this->type_->type_descriptor_pointer(context->gogo(),
13218 this->location());
13219 }
13220
13221 void
13222 do_dump_expression(Ast_dump_context*) const;
13223
13224 private:
13225 // The type for which this is the descriptor.
13226 Type* type_;
13227 };
13228
13229 // Dump ast representation for a type descriptor expression.
13230
13231 void
13232 Type_descriptor_expression::do_dump_expression(
13233 Ast_dump_context* ast_dump_context) const
13234 {
13235 ast_dump_context->dump_type(this->type_);
13236 }
13237
13238 // Make a type descriptor expression.
13239
13240 Expression*
13241 Expression::make_type_descriptor(Type* type, Location location)
13242 {
13243 return new Type_descriptor_expression(type, location);
13244 }
13245
13246 // An expression which evaluates to some characteristic of a type.
13247 // This is only used to initialize fields of a type descriptor. Using
13248 // a new expression class is slightly inefficient but gives us a good
13249 // separation between the frontend and the middle-end with regard to
13250 // how types are laid out.
13251
13252 class Type_info_expression : public Expression
13253 {
13254 public:
13255 Type_info_expression(Type* type, Type_info type_info)
13256 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13257 type_(type), type_info_(type_info)
13258 { }
13259
13260 protected:
13261 Type*
13262 do_type();
13263
13264 void
13265 do_determine_type(const Type_context*)
13266 { }
13267
13268 Expression*
13269 do_copy()
13270 { return this; }
13271
13272 tree
13273 do_get_tree(Translate_context* context);
13274
13275 void
13276 do_dump_expression(Ast_dump_context*) const;
13277
13278 private:
13279 // The type for which we are getting information.
13280 Type* type_;
13281 // What information we want.
13282 Type_info type_info_;
13283 };
13284
13285 // The type is chosen to match what the type descriptor struct
13286 // expects.
13287
13288 Type*
13289 Type_info_expression::do_type()
13290 {
13291 switch (this->type_info_)
13292 {
13293 case TYPE_INFO_SIZE:
13294 return Type::lookup_integer_type("uintptr");
13295 case TYPE_INFO_ALIGNMENT:
13296 case TYPE_INFO_FIELD_ALIGNMENT:
13297 return Type::lookup_integer_type("uint8");
13298 default:
13299 go_unreachable();
13300 }
13301 }
13302
13303 // Return type information in GENERIC.
13304
13305 tree
13306 Type_info_expression::do_get_tree(Translate_context* context)
13307 {
13308 Btype* btype = this->type_->get_backend(context->gogo());
13309 Gogo* gogo = context->gogo();
13310 size_t val;
13311 switch (this->type_info_)
13312 {
13313 case TYPE_INFO_SIZE:
13314 val = gogo->backend()->type_size(btype);
13315 break;
13316 case TYPE_INFO_ALIGNMENT:
13317 val = gogo->backend()->type_alignment(btype);
13318 break;
13319 case TYPE_INFO_FIELD_ALIGNMENT:
13320 val = gogo->backend()->type_field_alignment(btype);
13321 break;
13322 default:
13323 go_unreachable();
13324 }
13325 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13326 go_assert(val_type_tree != error_mark_node);
13327 return build_int_cstu(val_type_tree, val);
13328 }
13329
13330 // Dump ast representation for a type info expression.
13331
13332 void
13333 Type_info_expression::do_dump_expression(
13334 Ast_dump_context* ast_dump_context) const
13335 {
13336 ast_dump_context->ostream() << "typeinfo(";
13337 ast_dump_context->dump_type(this->type_);
13338 ast_dump_context->ostream() << ",";
13339 ast_dump_context->ostream() <<
13340 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13341 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13342 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13343 : "unknown");
13344 ast_dump_context->ostream() << ")";
13345 }
13346
13347 // Make a type info expression.
13348
13349 Expression*
13350 Expression::make_type_info(Type* type, Type_info type_info)
13351 {
13352 return new Type_info_expression(type, type_info);
13353 }
13354
13355 // An expression which evaluates to the offset of a field within a
13356 // struct. This, like Type_info_expression, q.v., is only used to
13357 // initialize fields of a type descriptor.
13358
13359 class Struct_field_offset_expression : public Expression
13360 {
13361 public:
13362 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13363 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13364 Linemap::predeclared_location()),
13365 type_(type), field_(field)
13366 { }
13367
13368 protected:
13369 Type*
13370 do_type()
13371 { return Type::lookup_integer_type("uintptr"); }
13372
13373 void
13374 do_determine_type(const Type_context*)
13375 { }
13376
13377 Expression*
13378 do_copy()
13379 { return this; }
13380
13381 tree
13382 do_get_tree(Translate_context* context);
13383
13384 void
13385 do_dump_expression(Ast_dump_context*) const;
13386
13387 private:
13388 // The type of the struct.
13389 Struct_type* type_;
13390 // The field.
13391 const Struct_field* field_;
13392 };
13393
13394 // Return a struct field offset in GENERIC.
13395
13396 tree
13397 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13398 {
13399 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13400 if (type_tree == error_mark_node)
13401 return error_mark_node;
13402
13403 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13404 go_assert(val_type_tree != error_mark_node);
13405
13406 const Struct_field_list* fields = this->type_->fields();
13407 tree struct_field_tree = TYPE_FIELDS(type_tree);
13408 Struct_field_list::const_iterator p;
13409 for (p = fields->begin();
13410 p != fields->end();
13411 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13412 {
13413 go_assert(struct_field_tree != NULL_TREE);
13414 if (&*p == this->field_)
13415 break;
13416 }
13417 go_assert(&*p == this->field_);
13418
13419 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13420 byte_position(struct_field_tree));
13421 }
13422
13423 // Dump ast representation for a struct field offset expression.
13424
13425 void
13426 Struct_field_offset_expression::do_dump_expression(
13427 Ast_dump_context* ast_dump_context) const
13428 {
13429 ast_dump_context->ostream() << "unsafe.Offsetof(";
13430 ast_dump_context->dump_type(this->type_);
13431 ast_dump_context->ostream() << '.';
13432 ast_dump_context->ostream() <<
13433 Gogo::message_name(this->field_->field_name());
13434 ast_dump_context->ostream() << ")";
13435 }
13436
13437 // Make an expression for a struct field offset.
13438
13439 Expression*
13440 Expression::make_struct_field_offset(Struct_type* type,
13441 const Struct_field* field)
13442 {
13443 return new Struct_field_offset_expression(type, field);
13444 }
13445
13446 // An expression which evaluates to a pointer to the map descriptor of
13447 // a map type.
13448
13449 class Map_descriptor_expression : public Expression
13450 {
13451 public:
13452 Map_descriptor_expression(Map_type* type, Location location)
13453 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13454 type_(type)
13455 { }
13456
13457 protected:
13458 Type*
13459 do_type()
13460 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13461
13462 void
13463 do_determine_type(const Type_context*)
13464 { }
13465
13466 Expression*
13467 do_copy()
13468 { return this; }
13469
13470 tree
13471 do_get_tree(Translate_context* context)
13472 {
13473 return this->type_->map_descriptor_pointer(context->gogo(),
13474 this->location());
13475 }
13476
13477 void
13478 do_dump_expression(Ast_dump_context*) const;
13479
13480 private:
13481 // The type for which this is the descriptor.
13482 Map_type* type_;
13483 };
13484
13485 // Dump ast representation for a map descriptor expression.
13486
13487 void
13488 Map_descriptor_expression::do_dump_expression(
13489 Ast_dump_context* ast_dump_context) const
13490 {
13491 ast_dump_context->ostream() << "map_descriptor(";
13492 ast_dump_context->dump_type(this->type_);
13493 ast_dump_context->ostream() << ")";
13494 }
13495
13496 // Make a map descriptor expression.
13497
13498 Expression*
13499 Expression::make_map_descriptor(Map_type* type, Location location)
13500 {
13501 return new Map_descriptor_expression(type, location);
13502 }
13503
13504 // An expression which evaluates to the address of an unnamed label.
13505
13506 class Label_addr_expression : public Expression
13507 {
13508 public:
13509 Label_addr_expression(Label* label, Location location)
13510 : Expression(EXPRESSION_LABEL_ADDR, location),
13511 label_(label)
13512 { }
13513
13514 protected:
13515 Type*
13516 do_type()
13517 { return Type::make_pointer_type(Type::make_void_type()); }
13518
13519 void
13520 do_determine_type(const Type_context*)
13521 { }
13522
13523 Expression*
13524 do_copy()
13525 { return new Label_addr_expression(this->label_, this->location()); }
13526
13527 tree
13528 do_get_tree(Translate_context* context)
13529 {
13530 return expr_to_tree(this->label_->get_addr(context, this->location()));
13531 }
13532
13533 void
13534 do_dump_expression(Ast_dump_context* ast_dump_context) const
13535 { ast_dump_context->ostream() << this->label_->name(); }
13536
13537 private:
13538 // The label whose address we are taking.
13539 Label* label_;
13540 };
13541
13542 // Make an expression for the address of an unnamed label.
13543
13544 Expression*
13545 Expression::make_label_addr(Label* label, Location location)
13546 {
13547 return new Label_addr_expression(label, location);
13548 }
13549
13550 // Import an expression. This comes at the end in order to see the
13551 // various class definitions.
13552
13553 Expression*
13554 Expression::import_expression(Import* imp)
13555 {
13556 int c = imp->peek_char();
13557 if (imp->match_c_string("- ")
13558 || imp->match_c_string("! ")
13559 || imp->match_c_string("^ "))
13560 return Unary_expression::do_import(imp);
13561 else if (c == '(')
13562 return Binary_expression::do_import(imp);
13563 else if (imp->match_c_string("true")
13564 || imp->match_c_string("false"))
13565 return Boolean_expression::do_import(imp);
13566 else if (c == '"')
13567 return String_expression::do_import(imp);
13568 else if (c == '-' || (c >= '0' && c <= '9'))
13569 {
13570 // This handles integers, floats and complex constants.
13571 return Integer_expression::do_import(imp);
13572 }
13573 else if (imp->match_c_string("nil"))
13574 return Nil_expression::do_import(imp);
13575 else if (imp->match_c_string("convert"))
13576 return Type_conversion_expression::do_import(imp);
13577 else
13578 {
13579 error_at(imp->location(), "import error: expected expression");
13580 return Expression::make_error(imp->location());
13581 }
13582 }
13583
13584 // Class Expression_list.
13585
13586 // Traverse the list.
13587
13588 int
13589 Expression_list::traverse(Traverse* traverse)
13590 {
13591 for (Expression_list::iterator p = this->begin();
13592 p != this->end();
13593 ++p)
13594 {
13595 if (*p != NULL)
13596 {
13597 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13598 return TRAVERSE_EXIT;
13599 }
13600 }
13601 return TRAVERSE_CONTINUE;
13602 }
13603
13604 // Copy the list.
13605
13606 Expression_list*
13607 Expression_list::copy()
13608 {
13609 Expression_list* ret = new Expression_list();
13610 for (Expression_list::iterator p = this->begin();
13611 p != this->end();
13612 ++p)
13613 {
13614 if (*p == NULL)
13615 ret->push_back(NULL);
13616 else
13617 ret->push_back((*p)->copy());
13618 }
13619 return ret;
13620 }
13621
13622 // Return whether an expression list has an error expression.
13623
13624 bool
13625 Expression_list::contains_error() const
13626 {
13627 for (Expression_list::const_iterator p = this->begin();
13628 p != this->end();
13629 ++p)
13630 if (*p != NULL && (*p)->is_error_expression())
13631 return true;
13632 return false;
13633 }
13634
13635 // Class Numeric_constant.
13636
13637 // Destructor.
13638
13639 Numeric_constant::~Numeric_constant()
13640 {
13641 this->clear();
13642 }
13643
13644 // Copy constructor.
13645
13646 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13647 : classification_(a.classification_), type_(a.type_)
13648 {
13649 switch (a.classification_)
13650 {
13651 case NC_INVALID:
13652 break;
13653 case NC_INT:
13654 case NC_RUNE:
13655 mpz_init_set(this->u_.int_val, a.u_.int_val);
13656 break;
13657 case NC_FLOAT:
13658 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13659 break;
13660 case NC_COMPLEX:
13661 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13662 GMP_RNDN);
13663 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13664 GMP_RNDN);
13665 break;
13666 default:
13667 go_unreachable();
13668 }
13669 }
13670
13671 // Assignment operator.
13672
13673 Numeric_constant&
13674 Numeric_constant::operator=(const Numeric_constant& a)
13675 {
13676 this->clear();
13677 this->classification_ = a.classification_;
13678 this->type_ = a.type_;
13679 switch (a.classification_)
13680 {
13681 case NC_INVALID:
13682 break;
13683 case NC_INT:
13684 case NC_RUNE:
13685 mpz_init_set(this->u_.int_val, a.u_.int_val);
13686 break;
13687 case NC_FLOAT:
13688 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13689 break;
13690 case NC_COMPLEX:
13691 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13692 GMP_RNDN);
13693 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13694 GMP_RNDN);
13695 break;
13696 default:
13697 go_unreachable();
13698 }
13699 return *this;
13700 }
13701
13702 // Clear the contents.
13703
13704 void
13705 Numeric_constant::clear()
13706 {
13707 switch (this->classification_)
13708 {
13709 case NC_INVALID:
13710 break;
13711 case NC_INT:
13712 case NC_RUNE:
13713 mpz_clear(this->u_.int_val);
13714 break;
13715 case NC_FLOAT:
13716 mpfr_clear(this->u_.float_val);
13717 break;
13718 case NC_COMPLEX:
13719 mpfr_clear(this->u_.complex_val.real);
13720 mpfr_clear(this->u_.complex_val.imag);
13721 break;
13722 default:
13723 go_unreachable();
13724 }
13725 this->classification_ = NC_INVALID;
13726 }
13727
13728 // Set to an unsigned long value.
13729
13730 void
13731 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13732 {
13733 this->clear();
13734 this->classification_ = NC_INT;
13735 this->type_ = type;
13736 mpz_init_set_ui(this->u_.int_val, val);
13737 }
13738
13739 // Set to an integer value.
13740
13741 void
13742 Numeric_constant::set_int(Type* type, const mpz_t val)
13743 {
13744 this->clear();
13745 this->classification_ = NC_INT;
13746 this->type_ = type;
13747 mpz_init_set(this->u_.int_val, val);
13748 }
13749
13750 // Set to a rune value.
13751
13752 void
13753 Numeric_constant::set_rune(Type* type, const mpz_t val)
13754 {
13755 this->clear();
13756 this->classification_ = NC_RUNE;
13757 this->type_ = type;
13758 mpz_init_set(this->u_.int_val, val);
13759 }
13760
13761 // Set to a floating point value.
13762
13763 void
13764 Numeric_constant::set_float(Type* type, const mpfr_t val)
13765 {
13766 this->clear();
13767 this->classification_ = NC_FLOAT;
13768 this->type_ = type;
13769 // Numeric constants do not have negative zero values, so remove
13770 // them here. They also don't have infinity or NaN values, but we
13771 // should never see them here.
13772 if (mpfr_zero_p(val))
13773 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
13774 else
13775 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13776 }
13777
13778 // Set to a complex value.
13779
13780 void
13781 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13782 {
13783 this->clear();
13784 this->classification_ = NC_COMPLEX;
13785 this->type_ = type;
13786 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13787 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13788 }
13789
13790 // Get an int value.
13791
13792 void
13793 Numeric_constant::get_int(mpz_t* val) const
13794 {
13795 go_assert(this->is_int());
13796 mpz_init_set(*val, this->u_.int_val);
13797 }
13798
13799 // Get a rune value.
13800
13801 void
13802 Numeric_constant::get_rune(mpz_t* val) const
13803 {
13804 go_assert(this->is_rune());
13805 mpz_init_set(*val, this->u_.int_val);
13806 }
13807
13808 // Get a floating point value.
13809
13810 void
13811 Numeric_constant::get_float(mpfr_t* val) const
13812 {
13813 go_assert(this->is_float());
13814 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13815 }
13816
13817 // Get a complex value.
13818
13819 void
13820 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13821 {
13822 go_assert(this->is_complex());
13823 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13824 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13825 }
13826
13827 // Express value as unsigned long if possible.
13828
13829 Numeric_constant::To_unsigned_long
13830 Numeric_constant::to_unsigned_long(unsigned long* val) const
13831 {
13832 switch (this->classification_)
13833 {
13834 case NC_INT:
13835 case NC_RUNE:
13836 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13837 case NC_FLOAT:
13838 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13839 case NC_COMPLEX:
13840 if (!mpfr_zero_p(this->u_.complex_val.imag))
13841 return NC_UL_NOTINT;
13842 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13843 default:
13844 go_unreachable();
13845 }
13846 }
13847
13848 // Express integer value as unsigned long if possible.
13849
13850 Numeric_constant::To_unsigned_long
13851 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13852 unsigned long *val) const
13853 {
13854 if (mpz_sgn(ival) < 0)
13855 return NC_UL_NEGATIVE;
13856 unsigned long ui = mpz_get_ui(ival);
13857 if (mpz_cmp_ui(ival, ui) != 0)
13858 return NC_UL_BIG;
13859 *val = ui;
13860 return NC_UL_VALID;
13861 }
13862
13863 // Express floating point value as unsigned long if possible.
13864
13865 Numeric_constant::To_unsigned_long
13866 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13867 unsigned long *val) const
13868 {
13869 if (!mpfr_integer_p(fval))
13870 return NC_UL_NOTINT;
13871 mpz_t ival;
13872 mpz_init(ival);
13873 mpfr_get_z(ival, fval, GMP_RNDN);
13874 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13875 mpz_clear(ival);
13876 return ret;
13877 }
13878
13879 // Convert value to integer if possible.
13880
13881 bool
13882 Numeric_constant::to_int(mpz_t* val) const
13883 {
13884 switch (this->classification_)
13885 {
13886 case NC_INT:
13887 case NC_RUNE:
13888 mpz_init_set(*val, this->u_.int_val);
13889 return true;
13890 case NC_FLOAT:
13891 if (!mpfr_integer_p(this->u_.float_val))
13892 return false;
13893 mpz_init(*val);
13894 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13895 return true;
13896 case NC_COMPLEX:
13897 if (!mpfr_zero_p(this->u_.complex_val.imag)
13898 || !mpfr_integer_p(this->u_.complex_val.real))
13899 return false;
13900 mpz_init(*val);
13901 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13902 return true;
13903 default:
13904 go_unreachable();
13905 }
13906 }
13907
13908 // Convert value to floating point if possible.
13909
13910 bool
13911 Numeric_constant::to_float(mpfr_t* val) const
13912 {
13913 switch (this->classification_)
13914 {
13915 case NC_INT:
13916 case NC_RUNE:
13917 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13918 return true;
13919 case NC_FLOAT:
13920 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13921 return true;
13922 case NC_COMPLEX:
13923 if (!mpfr_zero_p(this->u_.complex_val.imag))
13924 return false;
13925 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13926 return true;
13927 default:
13928 go_unreachable();
13929 }
13930 }
13931
13932 // Convert value to complex.
13933
13934 bool
13935 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13936 {
13937 switch (this->classification_)
13938 {
13939 case NC_INT:
13940 case NC_RUNE:
13941 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13942 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13943 return true;
13944 case NC_FLOAT:
13945 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13946 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13947 return true;
13948 case NC_COMPLEX:
13949 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13950 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13951 return true;
13952 default:
13953 go_unreachable();
13954 }
13955 }
13956
13957 // Get the type.
13958
13959 Type*
13960 Numeric_constant::type() const
13961 {
13962 if (this->type_ != NULL)
13963 return this->type_;
13964 switch (this->classification_)
13965 {
13966 case NC_INT:
13967 return Type::make_abstract_integer_type();
13968 case NC_RUNE:
13969 return Type::make_abstract_character_type();
13970 case NC_FLOAT:
13971 return Type::make_abstract_float_type();
13972 case NC_COMPLEX:
13973 return Type::make_abstract_complex_type();
13974 default:
13975 go_unreachable();
13976 }
13977 }
13978
13979 // If the constant can be expressed in TYPE, then set the type of the
13980 // constant to TYPE and return true. Otherwise return false, and, if
13981 // ISSUE_ERROR is true, report an appropriate error message.
13982
13983 bool
13984 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13985 {
13986 bool ret;
13987 if (type == NULL)
13988 ret = true;
13989 else if (type->integer_type() != NULL)
13990 ret = this->check_int_type(type->integer_type(), issue_error, loc);
13991 else if (type->float_type() != NULL)
13992 ret = this->check_float_type(type->float_type(), issue_error, loc);
13993 else if (type->complex_type() != NULL)
13994 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
13995 else
13996 go_unreachable();
13997 if (ret)
13998 this->type_ = type;
13999 return ret;
14000 }
14001
14002 // Check whether the constant can be expressed in an integer type.
14003
14004 bool
14005 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
14006 Location location) const
14007 {
14008 mpz_t val;
14009 switch (this->classification_)
14010 {
14011 case NC_INT:
14012 case NC_RUNE:
14013 mpz_init_set(val, this->u_.int_val);
14014 break;
14015
14016 case NC_FLOAT:
14017 if (!mpfr_integer_p(this->u_.float_val))
14018 {
14019 if (issue_error)
14020 error_at(location, "floating point constant truncated to integer");
14021 return false;
14022 }
14023 mpz_init(val);
14024 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
14025 break;
14026
14027 case NC_COMPLEX:
14028 if (!mpfr_integer_p(this->u_.complex_val.real)
14029 || !mpfr_zero_p(this->u_.complex_val.imag))
14030 {
14031 if (issue_error)
14032 error_at(location, "complex constant truncated to integer");
14033 return false;
14034 }
14035 mpz_init(val);
14036 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
14037 break;
14038
14039 default:
14040 go_unreachable();
14041 }
14042
14043 bool ret;
14044 if (type->is_abstract())
14045 ret = true;
14046 else
14047 {
14048 int bits = mpz_sizeinbase(val, 2);
14049 if (type->is_unsigned())
14050 {
14051 // For an unsigned type we can only accept a nonnegative
14052 // number, and we must be able to represents at least BITS.
14053 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
14054 }
14055 else
14056 {
14057 // For a signed type we need an extra bit to indicate the
14058 // sign. We have to handle the most negative integer
14059 // specially.
14060 ret = (bits + 1 <= type->bits()
14061 || (bits <= type->bits()
14062 && mpz_sgn(val) < 0
14063 && (mpz_scan1(val, 0)
14064 == static_cast<unsigned long>(type->bits() - 1))
14065 && mpz_scan0(val, type->bits()) == ULONG_MAX));
14066 }
14067 }
14068
14069 if (!ret && issue_error)
14070 error_at(location, "integer constant overflow");
14071
14072 return ret;
14073 }
14074
14075 // Check whether the constant can be expressed in a floating point
14076 // type.
14077
14078 bool
14079 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
14080 Location location) const
14081 {
14082 mpfr_t val;
14083 switch (this->classification_)
14084 {
14085 case NC_INT:
14086 case NC_RUNE:
14087 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
14088 break;
14089
14090 case NC_FLOAT:
14091 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
14092 break;
14093
14094 case NC_COMPLEX:
14095 if (!mpfr_zero_p(this->u_.complex_val.imag))
14096 {
14097 if (issue_error)
14098 error_at(location, "complex constant truncated to float");
14099 return false;
14100 }
14101 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
14102 break;
14103
14104 default:
14105 go_unreachable();
14106 }
14107
14108 bool ret;
14109 if (type->is_abstract())
14110 ret = true;
14111 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
14112 {
14113 // A NaN or Infinity always fits in the range of the type.
14114 ret = true;
14115 }
14116 else
14117 {
14118 mp_exp_t exp = mpfr_get_exp(val);
14119 mp_exp_t max_exp;
14120 switch (type->bits())
14121 {
14122 case 32:
14123 max_exp = 128;
14124 break;
14125 case 64:
14126 max_exp = 1024;
14127 break;
14128 default:
14129 go_unreachable();
14130 }
14131
14132 ret = exp <= max_exp;
14133 }
14134
14135 mpfr_clear(val);
14136
14137 if (!ret && issue_error)
14138 error_at(location, "floating point constant overflow");
14139
14140 return ret;
14141 }
14142
14143 // Check whether the constant can be expressed in a complex type.
14144
14145 bool
14146 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
14147 Location location) const
14148 {
14149 if (type->is_abstract())
14150 return true;
14151
14152 mp_exp_t max_exp;
14153 switch (type->bits())
14154 {
14155 case 64:
14156 max_exp = 128;
14157 break;
14158 case 128:
14159 max_exp = 1024;
14160 break;
14161 default:
14162 go_unreachable();
14163 }
14164
14165 mpfr_t real;
14166 switch (this->classification_)
14167 {
14168 case NC_INT:
14169 case NC_RUNE:
14170 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
14171 break;
14172
14173 case NC_FLOAT:
14174 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
14175 break;
14176
14177 case NC_COMPLEX:
14178 if (!mpfr_nan_p(this->u_.complex_val.imag)
14179 && !mpfr_inf_p(this->u_.complex_val.imag)
14180 && !mpfr_zero_p(this->u_.complex_val.imag))
14181 {
14182 if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
14183 {
14184 if (issue_error)
14185 error_at(location, "complex imaginary part overflow");
14186 return false;
14187 }
14188 }
14189 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
14190 break;
14191
14192 default:
14193 go_unreachable();
14194 }
14195
14196 bool ret;
14197 if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
14198 ret = true;
14199 else
14200 ret = mpfr_get_exp(real) <= max_exp;
14201
14202 mpfr_clear(real);
14203
14204 if (!ret && issue_error)
14205 error_at(location, "complex real part overflow");
14206
14207 return ret;
14208 }
14209
14210 // Return an Expression for this value.
14211
14212 Expression*
14213 Numeric_constant::expression(Location loc) const
14214 {
14215 switch (this->classification_)
14216 {
14217 case NC_INT:
14218 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
14219 case NC_RUNE:
14220 return Expression::make_character(&this->u_.int_val, this->type_, loc);
14221 case NC_FLOAT:
14222 return Expression::make_float(&this->u_.float_val, this->type_, loc);
14223 case NC_COMPLEX:
14224 return Expression::make_complex(&this->u_.complex_val.real,
14225 &this->u_.complex_val.imag,
14226 this->type_, loc);
14227 default:
14228 go_unreachable();
14229 }
14230 }