1 // expressions.cc -- Go frontend expression handling.
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.
13 #ifndef ENABLE_BUILD_WITH_CXX
22 #include "tree-iterator.h"
27 #ifndef ENABLE_BUILD_WITH_CXX
36 #include "statements.h"
40 #include "expressions.h"
45 Expression::Expression(Expression_classification classification,
47 : classification_(classification), location_(location)
51 Expression::~Expression()
55 // Traverse the expressions.
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
60 Expression* expr = *pexpr;
61 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
63 int t = traverse->expression(pexpr);
64 if (t == TRAVERSE_EXIT)
66 else if (t == TRAVERSE_SKIP_COMPONENTS)
67 return TRAVERSE_CONTINUE;
69 return expr->do_traverse(traverse);
72 // Traverse subexpressions of this expression.
75 Expression::traverse_subexpressions(Traverse* traverse)
77 return this->do_traverse(traverse);
80 // Default implementation for do_traverse for child classes.
83 Expression::do_traverse(Traverse*)
85 return TRAVERSE_CONTINUE;
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded. By default, we give an error.
90 // Expressions with side effects override.
93 Expression::do_discarding_value()
95 this->unused_value_error();
99 // This virtual function is called to export expressions. This will
100 // only be used by expressions which may be constant.
103 Expression::do_export(Export*) const
108 // Give an error saying that the value of the expression is not used.
111 Expression::unused_value_error()
113 this->report_error(_("value computed is not used"));
116 // Note that this expression is an error. This is called by children
117 // when they discover an error.
120 Expression::set_is_error()
122 this->classification_ = EXPRESSION_ERROR;
125 // For children to call to report an error conveniently.
128 Expression::report_error(const char* msg)
130 error_at(this->location_, "%s", msg);
131 this->set_is_error();
134 // Set types of variables and constants. This is implemented by the
138 Expression::determine_type(const Type_context* context)
140 this->do_determine_type(context);
143 // Set types when there is no context.
146 Expression::determine_type_no_context()
148 Type_context context;
149 this->do_determine_type(&context);
152 // Return a tree handling any conversions which must be done during
156 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
157 Type* rhs_type, tree rhs_tree,
160 if (lhs_type->is_error() || rhs_type->is_error())
161 return error_mark_node;
163 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
164 return error_mark_node;
166 Gogo* gogo = context->gogo();
168 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
169 if (lhs_type_tree == error_mark_node)
170 return error_mark_node;
172 if (lhs_type->forwarded() != rhs_type->forwarded()
173 && lhs_type->interface_type() != NULL)
175 if (rhs_type->interface_type() == NULL)
176 return Expression::convert_type_to_interface(context, lhs_type,
180 return Expression::convert_interface_to_interface(context, lhs_type,
184 else if (lhs_type->forwarded() != rhs_type->forwarded()
185 && rhs_type->interface_type() != NULL)
186 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
188 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
190 // Assigning nil to an open array.
191 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
193 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
195 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
196 tree field = TYPE_FIELDS(lhs_type_tree);
197 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
200 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
202 elt = VEC_quick_push(constructor_elt, init, NULL);
203 field = DECL_CHAIN(field);
204 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
207 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
209 elt = VEC_quick_push(constructor_elt, init, NULL);
210 field = DECL_CHAIN(field);
211 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
214 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
216 tree val = build_constructor(lhs_type_tree, init);
217 TREE_CONSTANT(val) = 1;
221 else if (rhs_type->is_nil_type())
223 // The left hand side should be a pointer type at the tree
225 go_assert(POINTER_TYPE_P(lhs_type_tree));
226 return fold_convert(lhs_type_tree, null_pointer_node);
228 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
230 // No conversion is needed.
233 else if (POINTER_TYPE_P(lhs_type_tree)
234 || INTEGRAL_TYPE_P(lhs_type_tree)
235 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
236 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
237 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
238 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
239 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
240 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
241 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
243 // Avoid confusion from zero sized variables which may be
244 // represented as non-zero-sized.
245 if (int_size_in_bytes(lhs_type_tree) == 0
246 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
249 // This conversion must be permitted by Go, or we wouldn't have
251 go_assert(int_size_in_bytes(lhs_type_tree)
252 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
253 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
254 lhs_type_tree, rhs_tree);
258 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
263 // Return a tree for a conversion from a non-interface type to an
267 Expression::convert_type_to_interface(Translate_context* context,
268 Type* lhs_type, Type* rhs_type,
269 tree rhs_tree, Location location)
271 Gogo* gogo = context->gogo();
272 Interface_type* lhs_interface_type = lhs_type->interface_type();
273 bool lhs_is_empty = lhs_interface_type->is_empty();
275 // Since RHS_TYPE is a static type, we can create the interface
276 // method table at compile time.
278 // When setting an interface to nil, we just set both fields to
280 if (rhs_type->is_nil_type())
282 Btype* lhs_btype = lhs_type->get_backend(gogo);
283 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
286 // This should have been checked already.
287 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
289 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
290 if (lhs_type_tree == error_mark_node)
291 return error_mark_node;
293 // An interface is a tuple. If LHS_TYPE is an empty interface type,
294 // then the first field is the type descriptor for RHS_TYPE.
295 // Otherwise it is the interface method table for RHS_TYPE.
296 tree first_field_value;
298 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
301 // Build the interface method table for this interface and this
302 // object type: a list of function pointers for each interface
304 Named_type* rhs_named_type = rhs_type->named_type();
305 Struct_type* rhs_struct_type = rhs_type->struct_type();
306 bool is_pointer = false;
307 if (rhs_named_type == NULL && rhs_struct_type == NULL)
309 rhs_named_type = rhs_type->deref()->named_type();
310 rhs_struct_type = rhs_type->deref()->struct_type();
314 if (rhs_named_type != NULL)
316 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
318 else if (rhs_struct_type != NULL)
320 rhs_struct_type->interface_method_table(gogo, lhs_interface_type,
323 method_table = null_pointer_node;
324 first_field_value = fold_convert_loc(location.gcc_location(),
325 const_ptr_type_node, method_table);
327 if (first_field_value == error_mark_node)
328 return error_mark_node;
330 // Start building a constructor for the value we will return.
332 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
334 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
335 tree field = TYPE_FIELDS(lhs_type_tree);
336 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
337 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
339 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
342 elt = VEC_quick_push(constructor_elt, init, NULL);
343 field = DECL_CHAIN(field);
344 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
347 if (rhs_type->points_to() != NULL)
349 // We are assigning a pointer to the interface; the interface
350 // holds the pointer itself.
351 elt->value = rhs_tree;
352 return build_constructor(lhs_type_tree, init);
355 // We are assigning a non-pointer value to the interface; the
356 // interface gets a copy of the value in the heap.
358 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
360 tree space = gogo->allocate_memory(rhs_type, object_size, location);
361 space = fold_convert_loc(location.gcc_location(),
362 build_pointer_type(TREE_TYPE(rhs_tree)), space);
363 space = save_expr(space);
365 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
366 TREE_THIS_NOTRAP(ref) = 1;
367 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
368 void_type_node, ref, rhs_tree);
370 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
373 return build2(COMPOUND_EXPR, lhs_type_tree, set,
374 build_constructor(lhs_type_tree, init));
377 // Return a tree for the type descriptor of RHS_TREE, which has
378 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
382 Expression::get_interface_type_descriptor(Translate_context*,
383 Type* rhs_type, tree rhs_tree,
386 tree rhs_type_tree = TREE_TYPE(rhs_tree);
387 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
388 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
389 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
391 if (rhs_type->interface_type()->is_empty())
393 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
394 "__type_descriptor") == 0);
398 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
400 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
402 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
403 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
404 tree f = TYPE_FIELDS(TREE_TYPE(v1));
405 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
407 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
409 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
410 v, fold_convert_loc(location.gcc_location(),
413 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
415 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
419 // Return a tree for the conversion of an interface type to an
423 Expression::convert_interface_to_interface(Translate_context* context,
424 Type *lhs_type, Type *rhs_type,
425 tree rhs_tree, bool for_type_guard,
428 Gogo* gogo = context->gogo();
429 Interface_type* lhs_interface_type = lhs_type->interface_type();
430 bool lhs_is_empty = lhs_interface_type->is_empty();
432 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
433 if (lhs_type_tree == error_mark_node)
434 return error_mark_node;
436 // In the general case this requires runtime examination of the type
437 // method table to match it up with the interface methods.
439 // FIXME: If all of the methods in the right hand side interface
440 // also appear in the left hand side interface, then we don't need
441 // to do a runtime check, although we still need to build a new
444 // Get the type descriptor for the right hand side. This will be
445 // NULL for a nil interface.
447 if (!DECL_P(rhs_tree))
448 rhs_tree = save_expr(rhs_tree);
450 tree rhs_type_descriptor =
451 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
454 // The result is going to be a two element constructor.
456 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
458 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
459 tree field = TYPE_FIELDS(lhs_type_tree);
464 // A type assertion fails when converting a nil interface.
465 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
467 static tree assert_interface_decl;
468 tree call = Gogo::call_builtin(&assert_interface_decl,
470 "__go_assert_interface",
473 TREE_TYPE(lhs_type_descriptor),
475 TREE_TYPE(rhs_type_descriptor),
476 rhs_type_descriptor);
477 if (call == error_mark_node)
478 return error_mark_node;
479 // This will panic if the interface conversion fails.
480 TREE_NOTHROW(assert_interface_decl) = 0;
481 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
484 else if (lhs_is_empty)
486 // A convertion to an empty interface always succeeds, and the
487 // first field is just the type descriptor of the object.
488 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
489 "__type_descriptor") == 0);
490 elt->value = fold_convert_loc(location.gcc_location(),
491 TREE_TYPE(field), rhs_type_descriptor);
495 // A conversion to a non-empty interface may fail, but unlike a
496 // type assertion converting nil will always succeed.
497 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
499 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
501 static tree convert_interface_decl;
502 tree call = Gogo::call_builtin(&convert_interface_decl,
504 "__go_convert_interface",
507 TREE_TYPE(lhs_type_descriptor),
509 TREE_TYPE(rhs_type_descriptor),
510 rhs_type_descriptor);
511 if (call == error_mark_node)
512 return error_mark_node;
513 // This will panic if the interface conversion fails.
514 TREE_NOTHROW(convert_interface_decl) = 0;
515 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
519 // The second field is simply the object pointer.
521 elt = VEC_quick_push(constructor_elt, init, NULL);
522 field = DECL_CHAIN(field);
523 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
526 tree rhs_type_tree = TREE_TYPE(rhs_tree);
527 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
528 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
529 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
530 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
533 return build_constructor(lhs_type_tree, init);
536 // Return a tree for the conversion of an interface type to a
537 // non-interface type.
540 Expression::convert_interface_to_type(Translate_context* context,
541 Type *lhs_type, Type* rhs_type,
542 tree rhs_tree, Location location)
544 Gogo* gogo = context->gogo();
545 tree rhs_type_tree = TREE_TYPE(rhs_tree);
547 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
548 if (lhs_type_tree == error_mark_node)
549 return error_mark_node;
551 // Call a function to check that the type is valid. The function
552 // will panic with an appropriate runtime type error if the type is
555 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
557 if (!DECL_P(rhs_tree))
558 rhs_tree = save_expr(rhs_tree);
560 tree rhs_type_descriptor =
561 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
564 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
567 static tree check_interface_type_decl;
568 tree call = Gogo::call_builtin(&check_interface_type_decl,
570 "__go_check_interface_type",
573 TREE_TYPE(lhs_type_descriptor),
575 TREE_TYPE(rhs_type_descriptor),
577 TREE_TYPE(rhs_inter_descriptor),
578 rhs_inter_descriptor);
579 if (call == error_mark_node)
580 return error_mark_node;
581 // This call will panic if the conversion is invalid.
582 TREE_NOTHROW(check_interface_type_decl) = 0;
584 // If the call succeeds, pull out the value.
585 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
586 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
587 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
588 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
591 // If the value is a pointer, then it is the value we want.
592 // Otherwise it points to the value.
593 if (lhs_type->points_to() == NULL)
595 val = fold_convert_loc(location.gcc_location(),
596 build_pointer_type(lhs_type_tree), val);
597 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
600 return build2(COMPOUND_EXPR, lhs_type_tree, call,
601 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
604 // Convert an expression to a tree. This is implemented by the child
605 // class. Not that it is not in general safe to call this multiple
606 // times for a single expression, but that we don't catch such errors.
609 Expression::get_tree(Translate_context* context)
611 // The child may have marked this expression as having an error.
612 if (this->classification_ == EXPRESSION_ERROR)
613 return error_mark_node;
615 return this->do_get_tree(context);
618 // Return a tree for VAL in TYPE.
621 Expression::integer_constant_tree(mpz_t val, tree type)
623 if (type == error_mark_node)
624 return error_mark_node;
625 else if (TREE_CODE(type) == INTEGER_TYPE)
626 return double_int_to_tree(type,
627 mpz_get_double_int(type, val, true));
628 else if (TREE_CODE(type) == REAL_TYPE)
631 mpfr_init_set_z(fval, val, GMP_RNDN);
632 tree ret = Expression::float_constant_tree(fval, type);
636 else if (TREE_CODE(type) == COMPLEX_TYPE)
639 mpfr_init_set_z(fval, val, GMP_RNDN);
640 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
642 tree imag = build_real_from_int_cst(TREE_TYPE(type),
644 return build_complex(type, real, imag);
650 // Return a tree for VAL in TYPE.
653 Expression::float_constant_tree(mpfr_t val, tree type)
655 if (type == error_mark_node)
656 return error_mark_node;
657 else if (TREE_CODE(type) == INTEGER_TYPE)
661 mpfr_get_z(ival, val, GMP_RNDN);
662 tree ret = Expression::integer_constant_tree(ival, type);
666 else if (TREE_CODE(type) == REAL_TYPE)
669 real_from_mpfr(&r1, val, type, GMP_RNDN);
671 real_convert(&r2, TYPE_MODE(type), &r1);
672 return build_real(type, r2);
674 else if (TREE_CODE(type) == COMPLEX_TYPE)
677 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
679 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
680 tree imag = build_real_from_int_cst(TREE_TYPE(type),
682 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
688 // Return a tree for REAL/IMAG in TYPE.
691 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
693 if (type == error_mark_node)
694 return error_mark_node;
695 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
696 return Expression::float_constant_tree(real, type);
697 else if (TREE_CODE(type) == COMPLEX_TYPE)
700 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
702 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
705 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
707 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
709 return build_complex(type, build_real(TREE_TYPE(type), r2),
710 build_real(TREE_TYPE(type), r4));
716 // Return a tree which evaluates to true if VAL, of arbitrary integer
717 // type, is negative or is more than the maximum value of BOUND_TYPE.
718 // If SOFAR is not NULL, it is or'red into the result. The return
719 // value may be NULL if SOFAR is NULL.
722 Expression::check_bounds(tree val, tree bound_type, tree sofar,
725 tree val_type = TREE_TYPE(val);
726 tree ret = NULL_TREE;
728 if (!TYPE_UNSIGNED(val_type))
730 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
731 build_int_cst(val_type, 0));
732 if (ret == boolean_false_node)
736 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
737 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
738 go_assert(val_type_size != -1 && bound_type_size != -1);
739 if (val_type_size > bound_type_size
740 || (val_type_size == bound_type_size
741 && TYPE_UNSIGNED(val_type)
742 && !TYPE_UNSIGNED(bound_type)))
744 tree max = TYPE_MAX_VALUE(bound_type);
745 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
746 val, fold_convert_loc(loc.gcc_location(),
748 if (big == boolean_false_node)
750 else if (ret == NULL_TREE)
753 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
754 boolean_type_node, ret, big);
757 if (ret == NULL_TREE)
759 else if (sofar == NULL_TREE)
762 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
767 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
769 this->do_dump_expression(ast_dump_context);
772 // Error expressions. This are used to avoid cascading errors.
774 class Error_expression : public Expression
777 Error_expression(Location location)
778 : Expression(EXPRESSION_ERROR, location)
783 do_is_constant() const
787 do_numeric_constant_value(Numeric_constant* nc) const
789 nc->set_unsigned_long(NULL, 0);
794 do_discarding_value()
799 { return Type::make_error_type(); }
802 do_determine_type(const Type_context*)
810 do_is_addressable() const
814 do_get_tree(Translate_context*)
815 { return error_mark_node; }
818 do_dump_expression(Ast_dump_context*) const;
821 // Dump the ast representation for an error expression to a dump context.
824 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
826 ast_dump_context->ostream() << "_Error_" ;
830 Expression::make_error(Location location)
832 return new Error_expression(location);
835 // An expression which is really a type. This is used during parsing.
836 // It is an error if these survive after lowering.
839 Type_expression : public Expression
842 Type_expression(Type* type, Location location)
843 : Expression(EXPRESSION_TYPE, location),
849 do_traverse(Traverse* traverse)
850 { return Type::traverse(this->type_, traverse); }
854 { return this->type_; }
857 do_determine_type(const Type_context*)
861 do_check_types(Gogo*)
862 { this->report_error(_("invalid use of type")); }
869 do_get_tree(Translate_context*)
870 { go_unreachable(); }
872 void do_dump_expression(Ast_dump_context*) const;
875 // The type which we are representing as an expression.
880 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
882 ast_dump_context->dump_type(this->type_);
886 Expression::make_type(Type* type, Location location)
888 return new Type_expression(type, location);
891 // Class Parser_expression.
894 Parser_expression::do_type()
896 // We should never really ask for the type of a Parser_expression.
897 // However, it can happen, at least when we have an invalid const
898 // whose initializer refers to the const itself. In that case we
899 // may ask for the type when lowering the const itself.
900 go_assert(saw_errors());
901 return Type::make_error_type();
904 // Class Var_expression.
906 // Lower a variable expression. Here we just make sure that the
907 // initialization expression of the variable has been lowered. This
908 // ensures that we will be able to determine the type of the variable
912 Var_expression::do_lower(Gogo* gogo, Named_object* function,
913 Statement_inserter* inserter, int)
915 if (this->variable_->is_variable())
917 Variable* var = this->variable_->var_value();
918 // This is either a local variable or a global variable. A
919 // reference to a variable which is local to an enclosing
920 // function will be a reference to a field in a closure.
921 if (var->is_global())
926 var->lower_init_expression(gogo, function, inserter);
931 // Return the type of a reference to a variable.
934 Var_expression::do_type()
936 if (this->variable_->is_variable())
937 return this->variable_->var_value()->type();
938 else if (this->variable_->is_result_variable())
939 return this->variable_->result_var_value()->type();
944 // Determine the type of a reference to a variable.
947 Var_expression::do_determine_type(const Type_context*)
949 if (this->variable_->is_variable())
950 this->variable_->var_value()->determine_type();
953 // Something takes the address of this variable. This means that we
954 // may want to move the variable onto the heap.
957 Var_expression::do_address_taken(bool escapes)
961 if (this->variable_->is_variable())
962 this->variable_->var_value()->set_non_escaping_address_taken();
963 else if (this->variable_->is_result_variable())
964 this->variable_->result_var_value()->set_non_escaping_address_taken();
970 if (this->variable_->is_variable())
971 this->variable_->var_value()->set_address_taken();
972 else if (this->variable_->is_result_variable())
973 this->variable_->result_var_value()->set_address_taken();
979 // Get the tree for a reference to a variable.
982 Var_expression::do_get_tree(Translate_context* context)
984 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
985 context->function());
986 tree ret = var_to_tree(bvar);
987 if (ret == error_mark_node)
988 return error_mark_node;
990 if (this->variable_->is_variable())
991 is_in_heap = this->variable_->var_value()->is_in_heap();
992 else if (this->variable_->is_result_variable())
993 is_in_heap = this->variable_->result_var_value()->is_in_heap();
998 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
999 TREE_THIS_NOTRAP(ret) = 1;
1004 // Ast dump for variable expression.
1007 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1009 ast_dump_context->ostream() << this->variable_->name() ;
1012 // Make a reference to a variable in an expression.
1015 Expression::make_var_reference(Named_object* var, Location location)
1018 return Expression::make_sink(location);
1020 // FIXME: Creating a new object for each reference to a variable is
1022 return new Var_expression(var, location);
1025 // Class Temporary_reference_expression.
1030 Temporary_reference_expression::do_type()
1032 return this->statement_->type();
1035 // Called if something takes the address of this temporary variable.
1036 // We never have to move temporary variables to the heap, but we do
1037 // need to know that they must live in the stack rather than in a
1041 Temporary_reference_expression::do_address_taken(bool)
1043 this->statement_->set_is_address_taken();
1046 // Get a tree referring to the variable.
1049 Temporary_reference_expression::do_get_tree(Translate_context* context)
1051 Bvariable* bvar = this->statement_->get_backend_variable(context);
1053 // The gcc backend can't represent the same set of recursive types
1054 // that the Go frontend can. In some cases this means that a
1055 // temporary variable won't have the right backend type. Correct
1056 // that here by adding a type cast. We need to use base() to push
1057 // the circularity down one level.
1058 tree ret = var_to_tree(bvar);
1059 if (!this->is_lvalue_
1060 && POINTER_TYPE_P(TREE_TYPE(ret))
1061 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1063 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1064 tree type_tree = type_to_tree(type_btype);
1065 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1070 // Ast dump for temporary reference.
1073 Temporary_reference_expression::do_dump_expression(
1074 Ast_dump_context* ast_dump_context) const
1076 ast_dump_context->dump_temp_variable_name(this->statement_);
1079 // Make a reference to a temporary variable.
1081 Temporary_reference_expression*
1082 Expression::make_temporary_reference(Temporary_statement* statement,
1085 return new Temporary_reference_expression(statement, location);
1088 // Class Set_and_use_temporary_expression.
1093 Set_and_use_temporary_expression::do_type()
1095 return this->statement_->type();
1098 // Take the address.
1101 Set_and_use_temporary_expression::do_address_taken(bool)
1103 this->statement_->set_is_address_taken();
1106 // Return the backend representation.
1109 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1111 Bvariable* bvar = this->statement_->get_backend_variable(context);
1112 tree var_tree = var_to_tree(bvar);
1113 tree expr_tree = this->expr_->get_tree(context);
1114 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1115 return error_mark_node;
1116 Location loc = this->location();
1117 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1118 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1119 var_tree, expr_tree),
1126 Set_and_use_temporary_expression::do_dump_expression(
1127 Ast_dump_context* ast_dump_context) const
1129 ast_dump_context->ostream() << '(';
1130 ast_dump_context->dump_temp_variable_name(this->statement_);
1131 ast_dump_context->ostream() << " = ";
1132 this->expr_->dump_expression(ast_dump_context);
1133 ast_dump_context->ostream() << ')';
1136 // Make a set-and-use temporary.
1138 Set_and_use_temporary_expression*
1139 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1140 Expression* expr, Location location)
1142 return new Set_and_use_temporary_expression(statement, expr, location);
1145 // A sink expression--a use of the blank identifier _.
1147 class Sink_expression : public Expression
1150 Sink_expression(Location location)
1151 : Expression(EXPRESSION_SINK, location),
1152 type_(NULL), var_(NULL_TREE)
1157 do_discarding_value()
1164 do_determine_type(const Type_context*);
1168 { return new Sink_expression(this->location()); }
1171 do_get_tree(Translate_context*);
1174 do_dump_expression(Ast_dump_context*) const;
1177 // The type of this sink variable.
1179 // The temporary variable we generate.
1183 // Return the type of a sink expression.
1186 Sink_expression::do_type()
1188 if (this->type_ == NULL)
1189 return Type::make_sink_type();
1193 // Determine the type of a sink expression.
1196 Sink_expression::do_determine_type(const Type_context* context)
1198 if (context->type != NULL)
1199 this->type_ = context->type;
1202 // Return a temporary variable for a sink expression. This will
1203 // presumably be a write-only variable which the middle-end will drop.
1206 Sink_expression::do_get_tree(Translate_context* context)
1208 if (this->var_ == NULL_TREE)
1210 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1211 Btype* bt = this->type_->get_backend(context->gogo());
1212 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1217 // Ast dump for sink expression.
1220 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1222 ast_dump_context->ostream() << "_" ;
1225 // Make a sink expression.
1228 Expression::make_sink(Location location)
1230 return new Sink_expression(location);
1233 // Class Func_expression.
1235 // FIXME: Can a function expression appear in a constant expression?
1236 // The value is unchanging. Initializing a constant to the address of
1237 // a function seems like it could work, though there might be little
1243 Func_expression::do_traverse(Traverse* traverse)
1245 return (this->closure_ == NULL
1247 : Expression::traverse(&this->closure_, traverse));
1250 // Return the type of a function expression.
1253 Func_expression::do_type()
1255 if (this->function_->is_function())
1256 return this->function_->func_value()->type();
1257 else if (this->function_->is_function_declaration())
1258 return this->function_->func_declaration_value()->type();
1263 // Get the tree for a function expression without evaluating the
1267 Func_expression::get_tree_without_closure(Gogo* gogo)
1269 Function_type* fntype;
1270 if (this->function_->is_function())
1271 fntype = this->function_->func_value()->type();
1272 else if (this->function_->is_function_declaration())
1273 fntype = this->function_->func_declaration_value()->type();
1277 // Builtin functions are handled specially by Call_expression. We
1278 // can't take their address.
1279 if (fntype->is_builtin())
1281 error_at(this->location(),
1282 "invalid use of special builtin function %qs; must be called",
1283 this->function_->name().c_str());
1284 return error_mark_node;
1287 Named_object* no = this->function_;
1289 tree id = no->get_id(gogo);
1290 if (id == error_mark_node)
1291 return error_mark_node;
1294 if (no->is_function())
1295 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1296 else if (no->is_function_declaration())
1297 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1301 if (fndecl == error_mark_node)
1302 return error_mark_node;
1304 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1307 // Get the tree for a function expression. This is used when we take
1308 // the address of a function rather than simply calling it. If the
1309 // function has a closure, we must use a trampoline.
1312 Func_expression::do_get_tree(Translate_context* context)
1314 Gogo* gogo = context->gogo();
1316 tree fnaddr = this->get_tree_without_closure(gogo);
1317 if (fnaddr == error_mark_node)
1318 return error_mark_node;
1320 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1321 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1322 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1324 // If there is no closure, that is all have to do.
1325 if (this->closure_ == NULL)
1328 go_assert(this->function_->func_value()->enclosing() != NULL);
1330 // Get the value of the closure. This will be a pointer to space
1331 // allocated on the heap.
1332 tree closure_tree = this->closure_->get_tree(context);
1333 if (closure_tree == error_mark_node)
1334 return error_mark_node;
1335 go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1337 // Now we need to build some code on the heap. This code will load
1338 // the static chain pointer with the closure and then jump to the
1339 // body of the function. The normal gcc approach is to build the
1340 // code on the stack. Unfortunately we can not do that, as Go
1341 // permits us to return the function pointer.
1343 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1346 // Ast dump for function.
1349 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1351 ast_dump_context->ostream() << this->function_->name();
1352 if (this->closure_ != NULL)
1354 ast_dump_context->ostream() << " {closure = ";
1355 this->closure_->dump_expression(ast_dump_context);
1356 ast_dump_context->ostream() << "}";
1360 // Make a reference to a function in an expression.
1363 Expression::make_func_reference(Named_object* function, Expression* closure,
1366 return new Func_expression(function, closure, location);
1369 // Class Unknown_expression.
1371 // Return the name of an unknown expression.
1374 Unknown_expression::name() const
1376 return this->named_object_->name();
1379 // Lower a reference to an unknown name.
1382 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1384 Location location = this->location();
1385 Named_object* no = this->named_object_;
1387 if (!no->is_unknown())
1391 real = no->unknown_value()->real_named_object();
1394 if (this->is_composite_literal_key_)
1396 if (!this->no_error_message_)
1397 error_at(location, "reference to undefined name %qs",
1398 this->named_object_->message_name().c_str());
1399 return Expression::make_error(location);
1402 switch (real->classification())
1404 case Named_object::NAMED_OBJECT_CONST:
1405 return Expression::make_const_reference(real, location);
1406 case Named_object::NAMED_OBJECT_TYPE:
1407 return Expression::make_type(real->type_value(), location);
1408 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1409 if (this->is_composite_literal_key_)
1411 if (!this->no_error_message_)
1412 error_at(location, "reference to undefined type %qs",
1413 real->message_name().c_str());
1414 return Expression::make_error(location);
1415 case Named_object::NAMED_OBJECT_VAR:
1416 real->var_value()->set_is_used();
1417 return Expression::make_var_reference(real, location);
1418 case Named_object::NAMED_OBJECT_FUNC:
1419 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1420 return Expression::make_func_reference(real, NULL, location);
1421 case Named_object::NAMED_OBJECT_PACKAGE:
1422 if (this->is_composite_literal_key_)
1424 if (!this->no_error_message_)
1425 error_at(location, "unexpected reference to package");
1426 return Expression::make_error(location);
1432 // Dump the ast representation for an unknown expression to a dump context.
1435 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1437 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1441 // Make a reference to an unknown name.
1444 Expression::make_unknown_reference(Named_object* no, Location location)
1446 return new Unknown_expression(no, location);
1449 // A boolean expression.
1451 class Boolean_expression : public Expression
1454 Boolean_expression(bool val, Location location)
1455 : Expression(EXPRESSION_BOOLEAN, location),
1456 val_(val), type_(NULL)
1464 do_is_constant() const
1471 do_determine_type(const Type_context*);
1478 do_get_tree(Translate_context*)
1479 { return this->val_ ? boolean_true_node : boolean_false_node; }
1482 do_export(Export* exp) const
1483 { exp->write_c_string(this->val_ ? "true" : "false"); }
1486 do_dump_expression(Ast_dump_context* ast_dump_context) const
1487 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1492 // The type as determined by context.
1499 Boolean_expression::do_type()
1501 if (this->type_ == NULL)
1502 this->type_ = Type::make_boolean_type();
1506 // Set the type from the context.
1509 Boolean_expression::do_determine_type(const Type_context* context)
1511 if (this->type_ != NULL && !this->type_->is_abstract())
1513 else if (context->type != NULL && context->type->is_boolean_type())
1514 this->type_ = context->type;
1515 else if (!context->may_be_abstract)
1516 this->type_ = Type::lookup_bool_type();
1519 // Import a boolean constant.
1522 Boolean_expression::do_import(Import* imp)
1524 if (imp->peek_char() == 't')
1526 imp->require_c_string("true");
1527 return Expression::make_boolean(true, imp->location());
1531 imp->require_c_string("false");
1532 return Expression::make_boolean(false, imp->location());
1536 // Make a boolean expression.
1539 Expression::make_boolean(bool val, Location location)
1541 return new Boolean_expression(val, location);
1544 // Class String_expression.
1549 String_expression::do_type()
1551 if (this->type_ == NULL)
1552 this->type_ = Type::make_string_type();
1556 // Set the type from the context.
1559 String_expression::do_determine_type(const Type_context* context)
1561 if (this->type_ != NULL && !this->type_->is_abstract())
1563 else if (context->type != NULL && context->type->is_string_type())
1564 this->type_ = context->type;
1565 else if (!context->may_be_abstract)
1566 this->type_ = Type::lookup_string_type();
1569 // Build a string constant.
1572 String_expression::do_get_tree(Translate_context* context)
1574 return context->gogo()->go_string_constant_tree(this->val_);
1577 // Write string literal to string dump.
1580 String_expression::export_string(String_dump* exp,
1581 const String_expression* str)
1584 s.reserve(str->val_.length() * 4 + 2);
1586 for (std::string::const_iterator p = str->val_.begin();
1587 p != str->val_.end();
1590 if (*p == '\\' || *p == '"')
1595 else if (*p >= 0x20 && *p < 0x7f)
1597 else if (*p == '\n')
1599 else if (*p == '\t')
1604 unsigned char c = *p;
1605 unsigned int dig = c >> 4;
1606 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1608 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1612 exp->write_string(s);
1615 // Export a string expression.
1618 String_expression::do_export(Export* exp) const
1620 String_expression::export_string(exp, this);
1623 // Import a string expression.
1626 String_expression::do_import(Import* imp)
1628 imp->require_c_string("\"");
1632 int c = imp->get_char();
1633 if (c == '"' || c == -1)
1636 val += static_cast<char>(c);
1639 c = imp->get_char();
1640 if (c == '\\' || c == '"')
1641 val += static_cast<char>(c);
1648 c = imp->get_char();
1649 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1650 c = imp->get_char();
1651 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1652 char v = (vh << 4) | vl;
1657 error_at(imp->location(), "bad string constant");
1658 return Expression::make_error(imp->location());
1662 return Expression::make_string(val, imp->location());
1665 // Ast dump for string expression.
1668 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1670 String_expression::export_string(ast_dump_context, this);
1673 // Make a string expression.
1676 Expression::make_string(const std::string& val, Location location)
1678 return new String_expression(val, location);
1681 // Make an integer expression.
1683 class Integer_expression : public Expression
1686 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1688 : Expression(EXPRESSION_INTEGER, location),
1689 type_(type), is_character_constant_(is_character_constant)
1690 { mpz_init_set(this->val_, *val); }
1695 // Write VAL to string dump.
1697 export_integer(String_dump* exp, const mpz_t val);
1699 // Write VAL to dump context.
1701 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1705 do_is_constant() const
1709 do_numeric_constant_value(Numeric_constant* nc) const;
1715 do_determine_type(const Type_context* context);
1718 do_check_types(Gogo*);
1721 do_get_tree(Translate_context*);
1726 if (this->is_character_constant_)
1727 return Expression::make_character(&this->val_, this->type_,
1730 return Expression::make_integer(&this->val_, this->type_,
1735 do_export(Export*) const;
1738 do_dump_expression(Ast_dump_context*) const;
1741 // The integer value.
1745 // Whether this is a character constant.
1746 bool is_character_constant_;
1749 // Return a numeric constant for this expression. We have to mark
1750 // this as a character when appropriate.
1753 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1755 if (this->is_character_constant_)
1756 nc->set_rune(this->type_, this->val_);
1758 nc->set_int(this->type_, this->val_);
1762 // Return the current type. If we haven't set the type yet, we return
1763 // an abstract integer type.
1766 Integer_expression::do_type()
1768 if (this->type_ == NULL)
1770 if (this->is_character_constant_)
1771 this->type_ = Type::make_abstract_character_type();
1773 this->type_ = Type::make_abstract_integer_type();
1778 // Set the type of the integer value. Here we may switch from an
1779 // abstract type to a real type.
1782 Integer_expression::do_determine_type(const Type_context* context)
1784 if (this->type_ != NULL && !this->type_->is_abstract())
1786 else if (context->type != NULL && context->type->is_numeric_type())
1787 this->type_ = context->type;
1788 else if (!context->may_be_abstract)
1790 if (this->is_character_constant_)
1791 this->type_ = Type::lookup_integer_type("int32");
1793 this->type_ = Type::lookup_integer_type("int");
1797 // Check the type of an integer constant.
1800 Integer_expression::do_check_types(Gogo*)
1802 Type* type = this->type_;
1805 Numeric_constant nc;
1806 if (this->is_character_constant_)
1807 nc.set_rune(NULL, this->val_);
1809 nc.set_int(NULL, this->val_);
1810 if (!nc.set_type(type, true, this->location()))
1811 this->set_is_error();
1814 // Get a tree for an integer constant.
1817 Integer_expression::do_get_tree(Translate_context* context)
1819 Gogo* gogo = context->gogo();
1821 if (this->type_ != NULL && !this->type_->is_abstract())
1822 type = type_to_tree(this->type_->get_backend(gogo));
1823 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1825 // We are converting to an abstract floating point type.
1826 Type* ftype = Type::lookup_float_type("float64");
1827 type = type_to_tree(ftype->get_backend(gogo));
1829 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1831 // We are converting to an abstract complex type.
1832 Type* ctype = Type::lookup_complex_type("complex128");
1833 type = type_to_tree(ctype->get_backend(gogo));
1837 // If we still have an abstract type here, then this is being
1838 // used in a constant expression which didn't get reduced for
1839 // some reason. Use a type which will fit the value. We use <,
1840 // not <=, because we need an extra bit for the sign bit.
1841 int bits = mpz_sizeinbase(this->val_, 2);
1842 if (bits < INT_TYPE_SIZE)
1844 Type* t = Type::lookup_integer_type("int");
1845 type = type_to_tree(t->get_backend(gogo));
1849 Type* t = Type::lookup_integer_type("int64");
1850 type = type_to_tree(t->get_backend(gogo));
1853 type = long_long_integer_type_node;
1855 return Expression::integer_constant_tree(this->val_, type);
1858 // Write VAL to export data.
1861 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1863 char* s = mpz_get_str(NULL, 10, val);
1864 exp->write_c_string(s);
1868 // Export an integer in a constant expression.
1871 Integer_expression::do_export(Export* exp) const
1873 Integer_expression::export_integer(exp, this->val_);
1874 if (this->is_character_constant_)
1875 exp->write_c_string("'");
1876 // A trailing space lets us reliably identify the end of the number.
1877 exp->write_c_string(" ");
1880 // Import an integer, floating point, or complex value. This handles
1881 // all these types because they all start with digits.
1884 Integer_expression::do_import(Import* imp)
1886 std::string num = imp->read_identifier();
1887 imp->require_c_string(" ");
1888 if (!num.empty() && num[num.length() - 1] == 'i')
1891 size_t plus_pos = num.find('+', 1);
1892 size_t minus_pos = num.find('-', 1);
1894 if (plus_pos == std::string::npos)
1896 else if (minus_pos == std::string::npos)
1900 error_at(imp->location(), "bad number in import data: %qs",
1902 return Expression::make_error(imp->location());
1904 if (pos == std::string::npos)
1905 mpfr_set_ui(real, 0, GMP_RNDN);
1908 std::string real_str = num.substr(0, pos);
1909 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1911 error_at(imp->location(), "bad number in import data: %qs",
1913 return Expression::make_error(imp->location());
1917 std::string imag_str;
1918 if (pos == std::string::npos)
1921 imag_str = num.substr(pos);
1922 imag_str = imag_str.substr(0, imag_str.size() - 1);
1924 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1926 error_at(imp->location(), "bad number in import data: %qs",
1928 return Expression::make_error(imp->location());
1930 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1936 else if (num.find('.') == std::string::npos
1937 && num.find('E') == std::string::npos)
1939 bool is_character_constant = (!num.empty()
1940 && num[num.length() - 1] == '\'');
1941 if (is_character_constant)
1942 num = num.substr(0, num.length() - 1);
1944 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1946 error_at(imp->location(), "bad number in import data: %qs",
1948 return Expression::make_error(imp->location());
1951 if (is_character_constant)
1952 ret = Expression::make_character(&val, NULL, imp->location());
1954 ret = Expression::make_integer(&val, NULL, imp->location());
1961 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1963 error_at(imp->location(), "bad number in import data: %qs",
1965 return Expression::make_error(imp->location());
1967 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1972 // Ast dump for integer expression.
1975 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1977 if (this->is_character_constant_)
1978 ast_dump_context->ostream() << '\'';
1979 Integer_expression::export_integer(ast_dump_context, this->val_);
1980 if (this->is_character_constant_)
1981 ast_dump_context->ostream() << '\'';
1984 // Build a new integer value.
1987 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1989 return new Integer_expression(val, type, false, location);
1992 // Build a new character constant value.
1995 Expression::make_character(const mpz_t* val, Type* type, Location location)
1997 return new Integer_expression(val, type, true, location);
2002 class Float_expression : public Expression
2005 Float_expression(const mpfr_t* val, Type* type, Location location)
2006 : Expression(EXPRESSION_FLOAT, location),
2009 mpfr_init_set(this->val_, *val, GMP_RNDN);
2012 // Write VAL to export data.
2014 export_float(String_dump* exp, const mpfr_t val);
2016 // Write VAL to dump file.
2018 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2022 do_is_constant() const
2026 do_numeric_constant_value(Numeric_constant* nc) const
2028 nc->set_float(this->type_, this->val_);
2036 do_determine_type(const Type_context*);
2039 do_check_types(Gogo*);
2043 { return Expression::make_float(&this->val_, this->type_,
2044 this->location()); }
2047 do_get_tree(Translate_context*);
2050 do_export(Export*) const;
2053 do_dump_expression(Ast_dump_context*) const;
2056 // The floating point value.
2062 // Return the current type. If we haven't set the type yet, we return
2063 // an abstract float type.
2066 Float_expression::do_type()
2068 if (this->type_ == NULL)
2069 this->type_ = Type::make_abstract_float_type();
2073 // Set the type of the float value. Here we may switch from an
2074 // abstract type to a real type.
2077 Float_expression::do_determine_type(const Type_context* context)
2079 if (this->type_ != NULL && !this->type_->is_abstract())
2081 else if (context->type != NULL
2082 && (context->type->integer_type() != NULL
2083 || context->type->float_type() != NULL
2084 || context->type->complex_type() != NULL))
2085 this->type_ = context->type;
2086 else if (!context->may_be_abstract)
2087 this->type_ = Type::lookup_float_type("float64");
2090 // Check the type of a float value.
2093 Float_expression::do_check_types(Gogo*)
2095 Type* type = this->type_;
2098 Numeric_constant nc;
2099 nc.set_float(NULL, this->val_);
2100 if (!nc.set_type(this->type_, true, this->location()))
2101 this->set_is_error();
2104 // Get a tree for a float constant.
2107 Float_expression::do_get_tree(Translate_context* context)
2109 Gogo* gogo = context->gogo();
2111 if (this->type_ != NULL && !this->type_->is_abstract())
2112 type = type_to_tree(this->type_->get_backend(gogo));
2113 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2115 // We have an abstract integer type. We just hope for the best.
2116 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2120 // If we still have an abstract type here, then this is being
2121 // used in a constant expression which didn't get reduced. We
2122 // just use float64 and hope for the best.
2123 Type* ft = Type::lookup_float_type("float64");
2124 type = type_to_tree(ft->get_backend(gogo));
2126 return Expression::float_constant_tree(this->val_, type);
2129 // Write a floating point number to a string dump.
2132 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2135 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2137 exp->write_c_string("-");
2138 exp->write_c_string("0.");
2139 exp->write_c_string(*s == '-' ? s + 1 : s);
2142 snprintf(buf, sizeof buf, "E%ld", exponent);
2143 exp->write_c_string(buf);
2146 // Export a floating point number in a constant expression.
2149 Float_expression::do_export(Export* exp) const
2151 Float_expression::export_float(exp, this->val_);
2152 // A trailing space lets us reliably identify the end of the number.
2153 exp->write_c_string(" ");
2156 // Dump a floating point number to the dump file.
2159 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2161 Float_expression::export_float(ast_dump_context, this->val_);
2164 // Make a float expression.
2167 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2169 return new Float_expression(val, type, location);
2174 class Complex_expression : public Expression
2177 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2179 : Expression(EXPRESSION_COMPLEX, location),
2182 mpfr_init_set(this->real_, *real, GMP_RNDN);
2183 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2186 // Write REAL/IMAG to string dump.
2188 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2190 // Write REAL/IMAG to dump context.
2192 dump_complex(Ast_dump_context* ast_dump_context,
2193 const mpfr_t real, const mpfr_t val);
2197 do_is_constant() const
2201 do_numeric_constant_value(Numeric_constant* nc) const
2203 nc->set_complex(this->type_, this->real_, this->imag_);
2211 do_determine_type(const Type_context*);
2214 do_check_types(Gogo*);
2219 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2224 do_get_tree(Translate_context*);
2227 do_export(Export*) const;
2230 do_dump_expression(Ast_dump_context*) const;
2235 // The imaginary part;
2237 // The type if known.
2241 // Return the current type. If we haven't set the type yet, we return
2242 // an abstract complex type.
2245 Complex_expression::do_type()
2247 if (this->type_ == NULL)
2248 this->type_ = Type::make_abstract_complex_type();
2252 // Set the type of the complex value. Here we may switch from an
2253 // abstract type to a real type.
2256 Complex_expression::do_determine_type(const Type_context* context)
2258 if (this->type_ != NULL && !this->type_->is_abstract())
2260 else if (context->type != NULL
2261 && context->type->complex_type() != NULL)
2262 this->type_ = context->type;
2263 else if (!context->may_be_abstract)
2264 this->type_ = Type::lookup_complex_type("complex128");
2267 // Check the type of a complex value.
2270 Complex_expression::do_check_types(Gogo*)
2272 Type* type = this->type_;
2275 Numeric_constant nc;
2276 nc.set_complex(NULL, this->real_, this->imag_);
2277 if (!nc.set_type(this->type_, true, this->location()))
2278 this->set_is_error();
2281 // Get a tree for a complex constant.
2284 Complex_expression::do_get_tree(Translate_context* context)
2286 Gogo* gogo = context->gogo();
2288 if (this->type_ != NULL && !this->type_->is_abstract())
2289 type = type_to_tree(this->type_->get_backend(gogo));
2292 // If we still have an abstract type here, this this is being
2293 // used in a constant expression which didn't get reduced. We
2294 // just use complex128 and hope for the best.
2295 Type* ct = Type::lookup_complex_type("complex128");
2296 type = type_to_tree(ct->get_backend(gogo));
2298 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2301 // Write REAL/IMAG to export data.
2304 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2307 if (!mpfr_zero_p(real))
2309 Float_expression::export_float(exp, real);
2310 if (mpfr_sgn(imag) > 0)
2311 exp->write_c_string("+");
2313 Float_expression::export_float(exp, imag);
2314 exp->write_c_string("i");
2317 // Export a complex number in a constant expression.
2320 Complex_expression::do_export(Export* exp) const
2322 Complex_expression::export_complex(exp, this->real_, this->imag_);
2323 // A trailing space lets us reliably identify the end of the number.
2324 exp->write_c_string(" ");
2327 // Dump a complex expression to the dump file.
2330 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2332 Complex_expression::export_complex(ast_dump_context,
2337 // Make a complex expression.
2340 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2343 return new Complex_expression(real, imag, type, location);
2346 // Find a named object in an expression.
2348 class Find_named_object : public Traverse
2351 Find_named_object(Named_object* no)
2352 : Traverse(traverse_expressions),
2353 no_(no), found_(false)
2356 // Whether we found the object.
2359 { return this->found_; }
2363 expression(Expression**);
2366 // The object we are looking for.
2368 // Whether we found it.
2372 // A reference to a const in an expression.
2374 class Const_expression : public Expression
2377 Const_expression(Named_object* constant, Location location)
2378 : Expression(EXPRESSION_CONST_REFERENCE, location),
2379 constant_(constant), type_(NULL), seen_(false)
2384 { return this->constant_; }
2386 // Check that the initializer does not refer to the constant itself.
2388 check_for_init_loop();
2392 do_traverse(Traverse*);
2395 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2398 do_is_constant() const
2402 do_numeric_constant_value(Numeric_constant* nc) const;
2405 do_string_constant_value(std::string* val) const;
2410 // The type of a const is set by the declaration, not the use.
2412 do_determine_type(const Type_context*);
2415 do_check_types(Gogo*);
2422 do_get_tree(Translate_context* context);
2424 // When exporting a reference to a const as part of a const
2425 // expression, we export the value. We ignore the fact that it has
2428 do_export(Export* exp) const
2429 { this->constant_->const_value()->expr()->export_expression(exp); }
2432 do_dump_expression(Ast_dump_context*) const;
2436 Named_object* constant_;
2437 // The type of this reference. This is used if the constant has an
2440 // Used to prevent infinite recursion when a constant incorrectly
2441 // refers to itself.
2448 Const_expression::do_traverse(Traverse* traverse)
2450 if (this->type_ != NULL)
2451 return Type::traverse(this->type_, traverse);
2452 return TRAVERSE_CONTINUE;
2455 // Lower a constant expression. This is where we convert the
2456 // predeclared constant iota into an integer value.
2459 Const_expression::do_lower(Gogo* gogo, Named_object*,
2460 Statement_inserter*, int iota_value)
2462 if (this->constant_->const_value()->expr()->classification()
2465 if (iota_value == -1)
2467 error_at(this->location(),
2468 "iota is only defined in const declarations");
2472 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2473 Expression* ret = Expression::make_integer(&val, NULL,
2479 // Make sure that the constant itself has been lowered.
2480 gogo->lower_constant(this->constant_);
2485 // Return a numeric constant value.
2488 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2493 Expression* e = this->constant_->const_value()->expr();
2497 bool r = e->numeric_constant_value(nc);
2499 this->seen_ = false;
2502 if (this->type_ != NULL)
2503 ctype = this->type_;
2505 ctype = this->constant_->const_value()->type();
2506 if (r && ctype != NULL)
2508 if (!nc->set_type(ctype, false, this->location()))
2516 Const_expression::do_string_constant_value(std::string* val) const
2521 Expression* e = this->constant_->const_value()->expr();
2524 bool ok = e->string_constant_value(val);
2525 this->seen_ = false;
2530 // Return the type of the const reference.
2533 Const_expression::do_type()
2535 if (this->type_ != NULL)
2538 Named_constant* nc = this->constant_->const_value();
2540 if (this->seen_ || nc->lowering())
2542 this->report_error(_("constant refers to itself"));
2543 this->type_ = Type::make_error_type();
2549 Type* ret = nc->type();
2553 this->seen_ = false;
2557 // During parsing, a named constant may have a NULL type, but we
2558 // must not return a NULL type here.
2559 ret = nc->expr()->type();
2561 this->seen_ = false;
2566 // Set the type of the const reference.
2569 Const_expression::do_determine_type(const Type_context* context)
2571 Type* ctype = this->constant_->const_value()->type();
2572 Type* cetype = (ctype != NULL
2574 : this->constant_->const_value()->expr()->type());
2575 if (ctype != NULL && !ctype->is_abstract())
2577 else if (context->type != NULL
2578 && context->type->is_numeric_type()
2579 && cetype->is_numeric_type())
2580 this->type_ = context->type;
2581 else if (context->type != NULL
2582 && context->type->is_string_type()
2583 && cetype->is_string_type())
2584 this->type_ = context->type;
2585 else if (context->type != NULL
2586 && context->type->is_boolean_type()
2587 && cetype->is_boolean_type())
2588 this->type_ = context->type;
2589 else if (!context->may_be_abstract)
2591 if (cetype->is_abstract())
2592 cetype = cetype->make_non_abstract_type();
2593 this->type_ = cetype;
2597 // Check for a loop in which the initializer of a constant refers to
2598 // the constant itself.
2601 Const_expression::check_for_init_loop()
2603 if (this->type_ != NULL && this->type_->is_error())
2608 this->report_error(_("constant refers to itself"));
2609 this->type_ = Type::make_error_type();
2613 Expression* init = this->constant_->const_value()->expr();
2614 Find_named_object find_named_object(this->constant_);
2617 Expression::traverse(&init, &find_named_object);
2618 this->seen_ = false;
2620 if (find_named_object.found())
2622 if (this->type_ == NULL || !this->type_->is_error())
2624 this->report_error(_("constant refers to itself"));
2625 this->type_ = Type::make_error_type();
2631 // Check types of a const reference.
2634 Const_expression::do_check_types(Gogo*)
2636 if (this->type_ != NULL && this->type_->is_error())
2639 this->check_for_init_loop();
2641 // Check that numeric constant fits in type.
2642 if (this->type_ != NULL && this->type_->is_numeric_type())
2644 Numeric_constant nc;
2645 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2647 if (!nc.set_type(this->type_, true, this->location()))
2648 this->set_is_error();
2653 // Return a tree for the const reference.
2656 Const_expression::do_get_tree(Translate_context* context)
2658 Gogo* gogo = context->gogo();
2660 if (this->type_ == NULL)
2661 type_tree = NULL_TREE;
2664 type_tree = type_to_tree(this->type_->get_backend(gogo));
2665 if (type_tree == error_mark_node)
2666 return error_mark_node;
2669 // If the type has been set for this expression, but the underlying
2670 // object is an abstract int or float, we try to get the abstract
2671 // value. Otherwise we may lose something in the conversion.
2672 if (this->type_ != NULL
2673 && this->type_->is_numeric_type()
2674 && (this->constant_->const_value()->type() == NULL
2675 || this->constant_->const_value()->type()->is_abstract()))
2677 Expression* expr = this->constant_->const_value()->expr();
2678 Numeric_constant nc;
2679 if (expr->numeric_constant_value(&nc)
2680 && nc.set_type(this->type_, false, this->location()))
2682 Expression* e = nc.expression(this->location());
2683 return e->get_tree(context);
2687 tree const_tree = this->constant_->get_tree(gogo, context->function());
2688 if (this->type_ == NULL
2689 || const_tree == error_mark_node
2690 || TREE_TYPE(const_tree) == error_mark_node)
2694 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2695 ret = fold_convert(type_tree, const_tree);
2696 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2697 ret = fold(convert_to_integer(type_tree, const_tree));
2698 else if (TREE_CODE(type_tree) == REAL_TYPE)
2699 ret = fold(convert_to_real(type_tree, const_tree));
2700 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2701 ret = fold(convert_to_complex(type_tree, const_tree));
2707 // Dump ast representation for constant expression.
2710 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2712 ast_dump_context->ostream() << this->constant_->name();
2715 // Make a reference to a constant in an expression.
2718 Expression::make_const_reference(Named_object* constant,
2721 return new Const_expression(constant, location);
2724 // Find a named object in an expression.
2727 Find_named_object::expression(Expression** pexpr)
2729 switch ((*pexpr)->classification())
2731 case Expression::EXPRESSION_CONST_REFERENCE:
2733 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2734 if (ce->named_object() == this->no_)
2737 // We need to check a constant initializer explicitly, as
2738 // loops here will not be caught by the loop checking for
2739 // variable initializers.
2740 ce->check_for_init_loop();
2742 return TRAVERSE_CONTINUE;
2745 case Expression::EXPRESSION_VAR_REFERENCE:
2746 if ((*pexpr)->var_expression()->named_object() == this->no_)
2748 return TRAVERSE_CONTINUE;
2749 case Expression::EXPRESSION_FUNC_REFERENCE:
2750 if ((*pexpr)->func_expression()->named_object() == this->no_)
2752 return TRAVERSE_CONTINUE;
2754 return TRAVERSE_CONTINUE;
2756 this->found_ = true;
2757 return TRAVERSE_EXIT;
2762 class Nil_expression : public Expression
2765 Nil_expression(Location location)
2766 : Expression(EXPRESSION_NIL, location)
2774 do_is_constant() const
2779 { return Type::make_nil_type(); }
2782 do_determine_type(const Type_context*)
2790 do_get_tree(Translate_context*)
2791 { return null_pointer_node; }
2794 do_export(Export* exp) const
2795 { exp->write_c_string("nil"); }
2798 do_dump_expression(Ast_dump_context* ast_dump_context) const
2799 { ast_dump_context->ostream() << "nil"; }
2802 // Import a nil expression.
2805 Nil_expression::do_import(Import* imp)
2807 imp->require_c_string("nil");
2808 return Expression::make_nil(imp->location());
2811 // Make a nil expression.
2814 Expression::make_nil(Location location)
2816 return new Nil_expression(location);
2819 // The value of the predeclared constant iota. This is little more
2820 // than a marker. This will be lowered to an integer in
2821 // Const_expression::do_lower, which is where we know the value that
2824 class Iota_expression : public Parser_expression
2827 Iota_expression(Location location)
2828 : Parser_expression(EXPRESSION_IOTA, location)
2833 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2834 { go_unreachable(); }
2836 // There should only ever be one of these.
2839 { go_unreachable(); }
2842 do_dump_expression(Ast_dump_context* ast_dump_context) const
2843 { ast_dump_context->ostream() << "iota"; }
2846 // Make an iota expression. This is only called for one case: the
2847 // value of the predeclared constant iota.
2850 Expression::make_iota()
2852 static Iota_expression iota_expression(Linemap::unknown_location());
2853 return &iota_expression;
2856 // A type conversion expression.
2858 class Type_conversion_expression : public Expression
2861 Type_conversion_expression(Type* type, Expression* expr,
2863 : Expression(EXPRESSION_CONVERSION, location),
2864 type_(type), expr_(expr), may_convert_function_types_(false)
2867 // Return the type to which we are converting.
2870 { return this->type_; }
2872 // Return the expression which we are converting.
2875 { return this->expr_; }
2877 // Permit converting from one function type to another. This is
2878 // used internally for method expressions.
2880 set_may_convert_function_types()
2882 this->may_convert_function_types_ = true;
2885 // Import a type conversion expression.
2891 do_traverse(Traverse* traverse);
2894 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2897 do_is_constant() const
2898 { return this->expr_->is_constant(); }
2901 do_numeric_constant_value(Numeric_constant*) const;
2904 do_string_constant_value(std::string*) const;
2908 { return this->type_; }
2911 do_determine_type(const Type_context*)
2913 Type_context subcontext(this->type_, false);
2914 this->expr_->determine_type(&subcontext);
2918 do_check_types(Gogo*);
2923 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2928 do_get_tree(Translate_context* context);
2931 do_export(Export*) const;
2934 do_dump_expression(Ast_dump_context*) const;
2937 // The type to convert to.
2939 // The expression to convert.
2941 // True if this is permitted to convert function types. This is
2942 // used internally for method expressions.
2943 bool may_convert_function_types_;
2949 Type_conversion_expression::do_traverse(Traverse* traverse)
2951 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2952 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2953 return TRAVERSE_EXIT;
2954 return TRAVERSE_CONTINUE;
2957 // Convert to a constant at lowering time.
2960 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2961 Statement_inserter*, int)
2963 Type* type = this->type_;
2964 Expression* val = this->expr_;
2965 Location location = this->location();
2967 if (type->is_numeric_type())
2969 Numeric_constant nc;
2970 if (val->numeric_constant_value(&nc))
2972 if (!nc.set_type(type, true, location))
2973 return Expression::make_error(location);
2974 return nc.expression(location);
2978 if (type->is_slice_type())
2980 Type* element_type = type->array_type()->element_type()->forwarded();
2981 bool is_byte = (element_type->integer_type() != NULL
2982 && element_type->integer_type()->is_byte());
2983 bool is_rune = (element_type->integer_type() != NULL
2984 && element_type->integer_type()->is_rune());
2985 if (is_byte || is_rune)
2988 if (val->string_constant_value(&s))
2990 Expression_list* vals = new Expression_list();
2993 for (std::string::const_iterator p = s.begin();
2998 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2999 Expression* v = Expression::make_integer(&val,
3008 const char *p = s.data();
3009 const char *pend = s.data() + s.length();
3013 int adv = Lex::fetch_char(p, &c);
3016 warning_at(this->location(), 0,
3017 "invalid UTF-8 encoding");
3022 mpz_init_set_ui(val, c);
3023 Expression* v = Expression::make_integer(&val,
3031 return Expression::make_slice_composite_literal(type, vals,
3040 // Return the constant numeric value if there is one.
3043 Type_conversion_expression::do_numeric_constant_value(
3044 Numeric_constant* nc) const
3046 if (!this->type_->is_numeric_type())
3048 if (!this->expr_->numeric_constant_value(nc))
3050 return nc->set_type(this->type_, false, this->location());
3053 // Return the constant string value if there is one.
3056 Type_conversion_expression::do_string_constant_value(std::string* val) const
3058 if (this->type_->is_string_type()
3059 && this->expr_->type()->integer_type() != NULL)
3061 Numeric_constant nc;
3062 if (this->expr_->numeric_constant_value(&nc))
3065 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3068 Lex::append_char(ival, true, val, this->location());
3074 // FIXME: Could handle conversion from const []int here.
3079 // Check that types are convertible.
3082 Type_conversion_expression::do_check_types(Gogo*)
3084 Type* type = this->type_;
3085 Type* expr_type = this->expr_->type();
3088 if (type->is_error() || expr_type->is_error())
3090 this->set_is_error();
3094 if (this->may_convert_function_types_
3095 && type->function_type() != NULL
3096 && expr_type->function_type() != NULL)
3099 if (Type::are_convertible(type, expr_type, &reason))
3102 error_at(this->location(), "%s", reason.c_str());
3103 this->set_is_error();
3106 // Get a tree for a type conversion.
3109 Type_conversion_expression::do_get_tree(Translate_context* context)
3111 Gogo* gogo = context->gogo();
3112 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3113 tree expr_tree = this->expr_->get_tree(context);
3115 if (type_tree == error_mark_node
3116 || expr_tree == error_mark_node
3117 || TREE_TYPE(expr_tree) == error_mark_node)
3118 return error_mark_node;
3120 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3121 return fold_convert(type_tree, expr_tree);
3123 Type* type = this->type_;
3124 Type* expr_type = this->expr_->type();
3126 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3127 ret = Expression::convert_for_assignment(context, type, expr_type,
3128 expr_tree, this->location());
3129 else if (type->integer_type() != NULL)
3131 if (expr_type->integer_type() != NULL
3132 || expr_type->float_type() != NULL
3133 || expr_type->is_unsafe_pointer_type())
3134 ret = fold(convert_to_integer(type_tree, expr_tree));
3138 else if (type->float_type() != NULL)
3140 if (expr_type->integer_type() != NULL
3141 || expr_type->float_type() != NULL)
3142 ret = fold(convert_to_real(type_tree, expr_tree));
3146 else if (type->complex_type() != NULL)
3148 if (expr_type->complex_type() != NULL)
3149 ret = fold(convert_to_complex(type_tree, expr_tree));
3153 else if (type->is_string_type()
3154 && expr_type->integer_type() != NULL)
3156 expr_tree = fold_convert(integer_type_node, expr_tree);
3157 if (host_integerp(expr_tree, 0))
3159 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3161 Lex::append_char(intval, true, &s, this->location());
3162 Expression* se = Expression::make_string(s, this->location());
3163 return se->get_tree(context);
3166 static tree int_to_string_fndecl;
3167 ret = Gogo::call_builtin(&int_to_string_fndecl,
3169 "__go_int_to_string",
3173 fold_convert(integer_type_node, expr_tree));
3175 else if (type->is_string_type() && expr_type->is_slice_type())
3177 if (!DECL_P(expr_tree))
3178 expr_tree = save_expr(expr_tree);
3179 Array_type* a = expr_type->array_type();
3180 Type* e = a->element_type()->forwarded();
3181 go_assert(e->integer_type() != NULL);
3182 tree valptr = fold_convert(const_ptr_type_node,
3183 a->value_pointer_tree(gogo, expr_tree));
3184 tree len = a->length_tree(gogo, expr_tree);
3185 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3187 if (e->integer_type()->is_byte())
3189 static tree byte_array_to_string_fndecl;
3190 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3192 "__go_byte_array_to_string",
3195 const_ptr_type_node,
3202 go_assert(e->integer_type()->is_rune());
3203 static tree int_array_to_string_fndecl;
3204 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3206 "__go_int_array_to_string",
3209 const_ptr_type_node,
3215 else if (type->is_slice_type() && expr_type->is_string_type())
3217 Type* e = type->array_type()->element_type()->forwarded();
3218 go_assert(e->integer_type() != NULL);
3219 if (e->integer_type()->is_byte())
3221 tree string_to_byte_array_fndecl = NULL_TREE;
3222 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3224 "__go_string_to_byte_array",
3227 TREE_TYPE(expr_tree),
3232 go_assert(e->integer_type()->is_rune());
3233 tree string_to_int_array_fndecl = NULL_TREE;
3234 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3236 "__go_string_to_int_array",
3239 TREE_TYPE(expr_tree),
3243 else if ((type->is_unsafe_pointer_type()
3244 && expr_type->points_to() != NULL)
3245 || (expr_type->is_unsafe_pointer_type()
3246 && type->points_to() != NULL))
3247 ret = fold_convert(type_tree, expr_tree);
3248 else if (type->is_unsafe_pointer_type()
3249 && expr_type->integer_type() != NULL)
3250 ret = convert_to_pointer(type_tree, expr_tree);
3251 else if (this->may_convert_function_types_
3252 && type->function_type() != NULL
3253 && expr_type->function_type() != NULL)
3254 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3257 ret = Expression::convert_for_assignment(context, type, expr_type,
3258 expr_tree, this->location());
3263 // Output a type conversion in a constant expression.
3266 Type_conversion_expression::do_export(Export* exp) const
3268 exp->write_c_string("convert(");
3269 exp->write_type(this->type_);
3270 exp->write_c_string(", ");
3271 this->expr_->export_expression(exp);
3272 exp->write_c_string(")");
3275 // Import a type conversion or a struct construction.
3278 Type_conversion_expression::do_import(Import* imp)
3280 imp->require_c_string("convert(");
3281 Type* type = imp->read_type();
3282 imp->require_c_string(", ");
3283 Expression* val = Expression::import_expression(imp);
3284 imp->require_c_string(")");
3285 return Expression::make_cast(type, val, imp->location());
3288 // Dump ast representation for a type conversion expression.
3291 Type_conversion_expression::do_dump_expression(
3292 Ast_dump_context* ast_dump_context) const
3294 ast_dump_context->dump_type(this->type_);
3295 ast_dump_context->ostream() << "(";
3296 ast_dump_context->dump_expression(this->expr_);
3297 ast_dump_context->ostream() << ") ";
3300 // Make a type cast expression.
3303 Expression::make_cast(Type* type, Expression* val, Location location)
3305 if (type->is_error_type() || val->is_error_expression())
3306 return Expression::make_error(location);
3307 return new Type_conversion_expression(type, val, location);
3310 // An unsafe type conversion, used to pass values to builtin functions.
3312 class Unsafe_type_conversion_expression : public Expression
3315 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3317 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3318 type_(type), expr_(expr)
3323 do_traverse(Traverse* traverse);
3327 { return this->type_; }
3330 do_determine_type(const Type_context*)
3331 { this->expr_->determine_type_no_context(); }
3336 return new Unsafe_type_conversion_expression(this->type_,
3337 this->expr_->copy(),
3342 do_get_tree(Translate_context*);
3345 do_dump_expression(Ast_dump_context*) const;
3348 // The type to convert to.
3350 // The expression to convert.
3357 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3359 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3360 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3361 return TRAVERSE_EXIT;
3362 return TRAVERSE_CONTINUE;
3365 // Convert to backend representation.
3368 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3370 // We are only called for a limited number of cases.
3372 Type* t = this->type_;
3373 Type* et = this->expr_->type();
3375 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3376 tree expr_tree = this->expr_->get_tree(context);
3377 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3378 return error_mark_node;
3380 Location loc = this->location();
3382 bool use_view_convert = false;
3383 if (t->is_slice_type())
3385 go_assert(et->is_slice_type());
3386 use_view_convert = true;
3388 else if (t->map_type() != NULL)
3389 go_assert(et->map_type() != NULL);
3390 else if (t->channel_type() != NULL)
3391 go_assert(et->channel_type() != NULL);
3392 else if (t->points_to() != NULL)
3393 go_assert(et->points_to() != NULL || et->is_nil_type());
3394 else if (et->is_unsafe_pointer_type())
3395 go_assert(t->points_to() != NULL);
3396 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3398 go_assert(et->interface_type() != NULL
3399 && !et->interface_type()->is_empty());
3400 use_view_convert = true;
3402 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3404 go_assert(et->interface_type() != NULL
3405 && et->interface_type()->is_empty());
3406 use_view_convert = true;
3408 else if (t->integer_type() != NULL)
3410 go_assert(et->is_boolean_type()
3411 || et->integer_type() != NULL
3412 || et->function_type() != NULL
3413 || et->points_to() != NULL
3414 || et->map_type() != NULL
3415 || et->channel_type() != NULL);
3416 return convert_to_integer(type_tree, expr_tree);
3421 if (use_view_convert)
3422 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3425 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3428 // Dump ast representation for an unsafe type conversion expression.
3431 Unsafe_type_conversion_expression::do_dump_expression(
3432 Ast_dump_context* ast_dump_context) const
3434 ast_dump_context->dump_type(this->type_);
3435 ast_dump_context->ostream() << "(";
3436 ast_dump_context->dump_expression(this->expr_);
3437 ast_dump_context->ostream() << ") ";
3440 // Make an unsafe type conversion expression.
3443 Expression::make_unsafe_cast(Type* type, Expression* expr,
3446 return new Unsafe_type_conversion_expression(type, expr, location);
3449 // Unary expressions.
3451 class Unary_expression : public Expression
3454 Unary_expression(Operator op, Expression* expr, Location location)
3455 : Expression(EXPRESSION_UNARY, location),
3456 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3459 // Return the operator.
3462 { return this->op_; }
3464 // Return the operand.
3467 { return this->expr_; }
3469 // Record that an address expression does not escape.
3471 set_does_not_escape()
3473 go_assert(this->op_ == OPERATOR_AND);
3474 this->escapes_ = false;
3477 // Record that this is an address expression which should create a
3478 // temporary variable if necessary. This is used for method calls.
3482 go_assert(this->op_ == OPERATOR_AND);
3483 this->create_temp_ = true;
3486 // Apply unary opcode OP to UNC, setting NC. Return true if this
3487 // could be done, false if not. Issue errors for overflow.
3489 eval_constant(Operator op, const Numeric_constant* unc,
3490 Location, Numeric_constant* nc);
3497 do_traverse(Traverse* traverse)
3498 { return Expression::traverse(&this->expr_, traverse); }
3501 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3504 do_is_constant() const;
3507 do_numeric_constant_value(Numeric_constant*) const;
3513 do_determine_type(const Type_context*);
3516 do_check_types(Gogo*);
3521 return Expression::make_unary(this->op_, this->expr_->copy(),
3526 do_must_eval_subexpressions_in_order(int*) const
3527 { return this->op_ == OPERATOR_MULT; }
3530 do_is_addressable() const
3531 { return this->op_ == OPERATOR_MULT; }
3534 do_get_tree(Translate_context*);
3537 do_export(Export*) const;
3540 do_dump_expression(Ast_dump_context*) const;
3543 // The unary operator to apply.
3545 // Normally true. False if this is an address expression which does
3546 // not escape the current function.
3548 // True if this is an address expression which should create a
3549 // temporary variable if necessary.
3555 // If we are taking the address of a composite literal, and the
3556 // contents are not constant, then we want to make a heap composite
3560 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3562 Location loc = this->location();
3563 Operator op = this->op_;
3564 Expression* expr = this->expr_;
3566 if (op == OPERATOR_MULT && expr->is_type_expression())
3567 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3569 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3570 // moving x to the heap. FIXME: Is it worth doing a real escape
3571 // analysis here? This case is found in math/unsafe.go and is
3572 // therefore worth special casing.
3573 if (op == OPERATOR_MULT)
3575 Expression* e = expr;
3576 while (e->classification() == EXPRESSION_CONVERSION)
3578 Type_conversion_expression* te
3579 = static_cast<Type_conversion_expression*>(e);
3583 if (e->classification() == EXPRESSION_UNARY)
3585 Unary_expression* ue = static_cast<Unary_expression*>(e);
3586 if (ue->op_ == OPERATOR_AND)
3593 ue->set_does_not_escape();
3598 // Catching an invalid indirection of unsafe.Pointer here avoid
3599 // having to deal with TYPE_VOID in other places.
3600 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3602 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3603 return Expression::make_error(this->location());
3606 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3608 Numeric_constant nc;
3609 if (expr->numeric_constant_value(&nc))
3611 Numeric_constant result;
3612 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3613 return result.expression(loc);
3620 // Return whether a unary expression is a constant.
3623 Unary_expression::do_is_constant() const
3625 if (this->op_ == OPERATOR_MULT)
3627 // Indirecting through a pointer is only constant if the object
3628 // to which the expression points is constant, but we currently
3629 // have no way to determine that.
3632 else if (this->op_ == OPERATOR_AND)
3634 // Taking the address of a variable is constant if it is a
3635 // global variable, not constant otherwise. In other cases
3636 // taking the address is probably not a constant.
3637 Var_expression* ve = this->expr_->var_expression();
3640 Named_object* no = ve->named_object();
3641 return no->is_variable() && no->var_value()->is_global();
3646 return this->expr_->is_constant();
3649 // Apply unary opcode OP to UNC, setting NC. Return true if this
3650 // could be done, false if not. Issue errors for overflow.
3653 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3654 Location location, Numeric_constant* nc)
3662 case OPERATOR_MINUS:
3663 if (unc->is_int() || unc->is_rune())
3665 else if (unc->is_float())
3668 unc->get_float(&uval);
3671 mpfr_neg(val, uval, GMP_RNDN);
3672 nc->set_float(unc->type(), val);
3677 else if (unc->is_complex())
3679 mpfr_t ureal, uimag;
3680 unc->get_complex(&ureal, &uimag);
3684 mpfr_neg(real, ureal, GMP_RNDN);
3685 mpfr_neg(imag, uimag, GMP_RNDN);
3686 nc->set_complex(unc->type(), real, imag);
3708 if (!unc->is_int() && !unc->is_rune())
3713 unc->get_rune(&uval);
3715 unc->get_int(&uval);
3721 case OPERATOR_MINUS:
3726 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3731 Type* utype = unc->type();
3732 if (utype->integer_type() == NULL
3733 || utype->integer_type()->is_abstract())
3737 // The number of HOST_WIDE_INTs that it takes to represent
3739 size_t count = ((mpz_sizeinbase(uval, 2)
3740 + HOST_BITS_PER_WIDE_INT
3742 / HOST_BITS_PER_WIDE_INT);
3744 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3745 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3747 size_t obits = utype->integer_type()->bits();
3749 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3752 mpz_init_set_ui(adj, 1);
3753 mpz_mul_2exp(adj, adj, obits);
3754 mpz_add(uval, uval, adj);
3759 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3760 go_assert(ecount <= count);
3762 // Trim down to the number of words required by the type.
3763 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3764 / HOST_BITS_PER_WIDE_INT);
3765 go_assert(ocount <= count);
3767 for (size_t i = 0; i < ocount; ++i)
3770 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3772 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3775 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3777 if (!utype->integer_type()->is_unsigned()
3778 && mpz_tstbit(val, obits - 1))
3781 mpz_init_set_ui(adj, 1);
3782 mpz_mul_2exp(adj, adj, obits);
3783 mpz_sub(val, val, adj);
3797 nc->set_rune(NULL, val);
3799 nc->set_int(NULL, val);
3804 return nc->set_type(unc->type(), true, location);
3807 // Return the integral constant value of a unary expression, if it has one.
3810 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3812 Numeric_constant unc;
3813 if (!this->expr_->numeric_constant_value(&unc))
3815 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3819 // Return the type of a unary expression.
3822 Unary_expression::do_type()
3827 case OPERATOR_MINUS:
3830 return this->expr_->type();
3833 return Type::make_pointer_type(this->expr_->type());
3837 Type* subtype = this->expr_->type();
3838 Type* points_to = subtype->points_to();
3839 if (points_to == NULL)
3840 return Type::make_error_type();
3849 // Determine abstract types for a unary expression.
3852 Unary_expression::do_determine_type(const Type_context* context)
3857 case OPERATOR_MINUS:
3860 this->expr_->determine_type(context);
3864 // Taking the address of something.
3866 Type* subtype = (context->type == NULL
3868 : context->type->points_to());
3869 Type_context subcontext(subtype, false);
3870 this->expr_->determine_type(&subcontext);
3875 // Indirecting through a pointer.
3877 Type* subtype = (context->type == NULL
3879 : Type::make_pointer_type(context->type));
3880 Type_context subcontext(subtype, false);
3881 this->expr_->determine_type(&subcontext);
3890 // Check types for a unary expression.
3893 Unary_expression::do_check_types(Gogo*)
3895 Type* type = this->expr_->type();
3896 if (type->is_error())
3898 this->set_is_error();
3905 case OPERATOR_MINUS:
3906 if (type->integer_type() == NULL
3907 && type->float_type() == NULL
3908 && type->complex_type() == NULL)
3909 this->report_error(_("expected numeric type"));
3913 if (!type->is_boolean_type())
3914 this->report_error(_("expected boolean type"));
3918 if (type->integer_type() == NULL
3919 && !type->is_boolean_type())
3920 this->report_error(_("expected integer or boolean type"));
3924 if (!this->expr_->is_addressable())
3926 if (!this->create_temp_)
3927 this->report_error(_("invalid operand for unary %<&%>"));
3930 this->expr_->address_taken(this->escapes_);
3934 // Indirecting through a pointer.
3935 if (type->points_to() == NULL)
3936 this->report_error(_("expected pointer"));
3944 // Get a tree for a unary expression.
3947 Unary_expression::do_get_tree(Translate_context* context)
3949 Location loc = this->location();
3951 // Taking the address of a set-and-use-temporary expression requires
3952 // setting the temporary and then taking the address.
3953 if (this->op_ == OPERATOR_AND)
3955 Set_and_use_temporary_expression* sut =
3956 this->expr_->set_and_use_temporary_expression();
3959 Temporary_statement* temp = sut->temporary();
3960 Bvariable* bvar = temp->get_backend_variable(context);
3961 tree var_tree = var_to_tree(bvar);
3962 Expression* val = sut->expression();
3963 tree val_tree = val->get_tree(context);
3964 if (var_tree == error_mark_node || val_tree == error_mark_node)
3965 return error_mark_node;
3966 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3968 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3969 TREE_TYPE(addr_tree),
3970 build2_loc(sut->location().gcc_location(),
3971 MODIFY_EXPR, void_type_node,
3972 var_tree, val_tree),
3977 tree expr = this->expr_->get_tree(context);
3978 if (expr == error_mark_node)
3979 return error_mark_node;
3986 case OPERATOR_MINUS:
3988 tree type = TREE_TYPE(expr);
3989 tree compute_type = excess_precision_type(type);
3990 if (compute_type != NULL_TREE)
3991 expr = ::convert(compute_type, expr);
3992 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3993 (compute_type != NULL_TREE
3997 if (compute_type != NULL_TREE)
3998 ret = ::convert(type, ret);
4003 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4004 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4005 TREE_TYPE(expr), expr);
4007 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4008 expr, build_int_cst(TREE_TYPE(expr), 0));
4011 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4015 if (!this->create_temp_)
4017 // We should not see a non-constant constructor here; cases
4018 // where we would see one should have been moved onto the
4019 // heap at parse time. Taking the address of a nonconstant
4020 // constructor will not do what the programmer expects.
4021 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4022 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4025 // Build a decl for a constant constructor.
4026 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4028 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4029 create_tmp_var_name("C"), TREE_TYPE(expr));
4030 DECL_EXTERNAL(decl) = 0;
4031 TREE_PUBLIC(decl) = 0;
4032 TREE_READONLY(decl) = 1;
4033 TREE_CONSTANT(decl) = 1;
4034 TREE_STATIC(decl) = 1;
4035 TREE_ADDRESSABLE(decl) = 1;
4036 DECL_ARTIFICIAL(decl) = 1;
4037 DECL_INITIAL(decl) = expr;
4038 rest_of_decl_compilation(decl, 1, 0);
4042 if (this->create_temp_
4043 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4044 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
4045 && TREE_CODE(expr) != INDIRECT_REF
4046 && TREE_CODE(expr) != COMPONENT_REF)
4048 if (current_function_decl != NULL)
4050 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4051 DECL_IGNORED_P(tmp) = 1;
4052 DECL_INITIAL(tmp) = expr;
4053 TREE_ADDRESSABLE(tmp) = 1;
4054 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4055 build_pointer_type(TREE_TYPE(expr)),
4056 build1_loc(loc.gcc_location(), DECL_EXPR,
4057 void_type_node, tmp),
4058 build_fold_addr_expr_loc(loc.gcc_location(),
4063 tree tmp = build_decl(loc.gcc_location(), VAR_DECL,
4064 create_tmp_var_name("A"), TREE_TYPE(expr));
4065 DECL_EXTERNAL(tmp) = 0;
4066 TREE_PUBLIC(tmp) = 0;
4067 TREE_STATIC(tmp) = 1;
4068 DECL_ARTIFICIAL(tmp) = 1;
4069 TREE_ADDRESSABLE(tmp) = 1;
4071 if (!TREE_CONSTANT(expr))
4072 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
4073 void_type_node, tmp, expr);
4076 TREE_READONLY(tmp) = 1;
4077 TREE_CONSTANT(tmp) = 1;
4078 DECL_INITIAL(tmp) = expr;
4079 make_tmp = NULL_TREE;
4081 rest_of_decl_compilation(tmp, 1, 0);
4082 tree addr = build_fold_addr_expr_loc(loc.gcc_location(), tmp);
4083 if (make_tmp == NULL_TREE)
4085 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4086 TREE_TYPE(addr), make_tmp, addr);
4090 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4094 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4096 // If we are dereferencing the pointer to a large struct, we
4097 // need to check for nil. We don't bother to check for small
4098 // structs because we expect the system to crash on a nil
4099 // pointer dereference.
4100 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4101 if (!VOID_TYPE_P(target_type_tree))
4103 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4104 if (s == -1 || s >= 4096)
4107 expr = save_expr(expr);
4108 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4111 fold_convert(TREE_TYPE(expr),
4112 null_pointer_node));
4113 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4115 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4116 TREE_TYPE(expr), build3(COND_EXPR,
4124 // If the type of EXPR is a recursive pointer type, then we
4125 // need to insert a cast before indirecting.
4126 if (VOID_TYPE_P(target_type_tree))
4128 Type* pt = this->expr_->type()->points_to();
4129 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4130 expr = fold_convert_loc(loc.gcc_location(),
4131 build_pointer_type(ind), expr);
4134 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4142 // Export a unary expression.
4145 Unary_expression::do_export(Export* exp) const
4150 exp->write_c_string("+ ");
4152 case OPERATOR_MINUS:
4153 exp->write_c_string("- ");
4156 exp->write_c_string("! ");
4159 exp->write_c_string("^ ");
4166 this->expr_->export_expression(exp);
4169 // Import a unary expression.
4172 Unary_expression::do_import(Import* imp)
4175 switch (imp->get_char())
4181 op = OPERATOR_MINUS;
4192 imp->require_c_string(" ");
4193 Expression* expr = Expression::import_expression(imp);
4194 return Expression::make_unary(op, expr, imp->location());
4197 // Dump ast representation of an unary expression.
4200 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4202 ast_dump_context->dump_operator(this->op_);
4203 ast_dump_context->ostream() << "(";
4204 ast_dump_context->dump_expression(this->expr_);
4205 ast_dump_context->ostream() << ") ";
4208 // Make a unary expression.
4211 Expression::make_unary(Operator op, Expression* expr, Location location)
4213 return new Unary_expression(op, expr, location);
4216 // If this is an indirection through a pointer, return the expression
4217 // being pointed through. Otherwise return this.
4222 if (this->classification_ == EXPRESSION_UNARY)
4224 Unary_expression* ue = static_cast<Unary_expression*>(this);
4225 if (ue->op() == OPERATOR_MULT)
4226 return ue->operand();
4231 // Class Binary_expression.
4236 Binary_expression::do_traverse(Traverse* traverse)
4238 int t = Expression::traverse(&this->left_, traverse);
4239 if (t == TRAVERSE_EXIT)
4240 return TRAVERSE_EXIT;
4241 return Expression::traverse(&this->right_, traverse);
4244 // Return the type to use for a binary operation on operands of
4245 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4246 // such may be NULL or abstract.
4249 Binary_expression::operation_type(Operator op, Type* left_type,
4250 Type* right_type, Type** result_type)
4252 if (left_type != right_type
4253 && !left_type->is_abstract()
4254 && !right_type->is_abstract()
4255 && left_type->base() != right_type->base()
4256 && op != OPERATOR_LSHIFT
4257 && op != OPERATOR_RSHIFT)
4259 // May be a type error--let it be diagnosed elsewhere.
4263 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4265 if (left_type->integer_type() != NULL)
4266 *result_type = left_type;
4268 *result_type = Type::make_abstract_integer_type();
4270 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4271 *result_type = left_type;
4272 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4273 *result_type = right_type;
4274 else if (!left_type->is_abstract())
4275 *result_type = left_type;
4276 else if (!right_type->is_abstract())
4277 *result_type = right_type;
4278 else if (left_type->complex_type() != NULL)
4279 *result_type = left_type;
4280 else if (right_type->complex_type() != NULL)
4281 *result_type = right_type;
4282 else if (left_type->float_type() != NULL)
4283 *result_type = left_type;
4284 else if (right_type->float_type() != NULL)
4285 *result_type = right_type;
4286 else if (left_type->integer_type() != NULL
4287 && left_type->integer_type()->is_rune())
4288 *result_type = left_type;
4289 else if (right_type->integer_type() != NULL
4290 && right_type->integer_type()->is_rune())
4291 *result_type = right_type;
4293 *result_type = left_type;
4298 // Convert an integer comparison code and an operator to a boolean
4302 Binary_expression::cmp_to_bool(Operator op, int cmp)
4309 case OPERATOR_NOTEQ:
4326 // Compare constants according to OP.
4329 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4330 Numeric_constant* right_nc,
4331 Location location, bool* result)
4333 Type* left_type = left_nc->type();
4334 Type* right_type = right_nc->type();
4337 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4340 // When comparing an untyped operand to a typed operand, we are
4341 // effectively coercing the untyped operand to the other operand's
4342 // type, so make sure that is valid.
4343 if (!left_nc->set_type(type, true, location)
4344 || !right_nc->set_type(type, true, location))
4349 if (type->complex_type() != NULL)
4351 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4353 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4355 else if (type->float_type() != NULL)
4356 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4358 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4361 *result = Binary_expression::cmp_to_bool(op, cmp);
4366 // Compare integer constants.
4369 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4370 const Numeric_constant* right_nc,
4374 if (!left_nc->to_int(&left_val))
4377 if (!right_nc->to_int(&right_val))
4379 mpz_clear(left_val);
4383 *cmp = mpz_cmp(left_val, right_val);
4385 mpz_clear(left_val);
4386 mpz_clear(right_val);
4391 // Compare floating point constants.
4394 Binary_expression::compare_float(const Numeric_constant* left_nc,
4395 const Numeric_constant* right_nc,
4399 if (!left_nc->to_float(&left_val))
4402 if (!right_nc->to_float(&right_val))
4404 mpfr_clear(left_val);
4408 // We already coerced both operands to the same type. If that type
4409 // is not an abstract type, we need to round the values accordingly.
4410 Type* type = left_nc->type();
4411 if (!type->is_abstract() && type->float_type() != NULL)
4413 int bits = type->float_type()->bits();
4414 mpfr_prec_round(left_val, bits, GMP_RNDN);
4415 mpfr_prec_round(right_val, bits, GMP_RNDN);
4418 *cmp = mpfr_cmp(left_val, right_val);
4420 mpfr_clear(left_val);
4421 mpfr_clear(right_val);
4426 // Compare complex constants. Complex numbers may only be compared
4430 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4431 const Numeric_constant* right_nc,
4434 mpfr_t left_real, left_imag;
4435 if (!left_nc->to_complex(&left_real, &left_imag))
4437 mpfr_t right_real, right_imag;
4438 if (!right_nc->to_complex(&right_real, &right_imag))
4440 mpfr_clear(left_real);
4441 mpfr_clear(left_imag);
4445 // We already coerced both operands to the same type. If that type
4446 // is not an abstract type, we need to round the values accordingly.
4447 Type* type = left_nc->type();
4448 if (!type->is_abstract() && type->complex_type() != NULL)
4450 int bits = type->complex_type()->bits();
4451 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4452 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4453 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4454 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4457 *cmp = (mpfr_cmp(left_real, right_real) != 0
4458 || mpfr_cmp(left_imag, right_imag) != 0);
4460 mpfr_clear(left_real);
4461 mpfr_clear(left_imag);
4462 mpfr_clear(right_real);
4463 mpfr_clear(right_imag);
4468 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4469 // true if this could be done, false if not. Issue errors at LOCATION
4473 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4474 Numeric_constant* right_nc,
4475 Location location, Numeric_constant* nc)
4480 case OPERATOR_ANDAND:
4482 case OPERATOR_NOTEQ:
4487 // These return boolean values, not numeric.
4493 Type* left_type = left_nc->type();
4494 Type* right_type = right_nc->type();
4497 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4500 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4502 // When combining an untyped operand with a typed operand, we are
4503 // effectively coercing the untyped operand to the other operand's
4504 // type, so make sure that is valid.
4505 if (!left_nc->set_type(type, true, location))
4507 if (!is_shift && !right_nc->set_type(type, true, location))
4511 if (type->complex_type() != NULL)
4512 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4513 else if (type->float_type() != NULL)
4514 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4516 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4519 r = nc->set_type(type, true, location);
4524 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4525 // integer operations. Return true if this could be done, false if
4529 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4530 const Numeric_constant* right_nc,
4531 Location location, Numeric_constant* nc)
4534 if (!left_nc->to_int(&left_val))
4537 if (!right_nc->to_int(&right_val))
4539 mpz_clear(left_val);
4549 mpz_add(val, left_val, right_val);
4551 case OPERATOR_MINUS:
4552 mpz_sub(val, left_val, right_val);
4555 mpz_ior(val, left_val, right_val);
4558 mpz_xor(val, left_val, right_val);
4561 mpz_mul(val, left_val, right_val);
4564 if (mpz_sgn(right_val) != 0)
4565 mpz_tdiv_q(val, left_val, right_val);
4568 error_at(location, "division by zero");
4573 if (mpz_sgn(right_val) != 0)
4574 mpz_tdiv_r(val, left_val, right_val);
4577 error_at(location, "division by zero");
4581 case OPERATOR_LSHIFT:
4583 unsigned long shift = mpz_get_ui(right_val);
4584 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4585 mpz_mul_2exp(val, left_val, shift);
4588 error_at(location, "shift count overflow");
4594 case OPERATOR_RSHIFT:
4596 unsigned long shift = mpz_get_ui(right_val);
4597 if (mpz_cmp_ui(right_val, shift) != 0)
4599 error_at(location, "shift count overflow");
4604 if (mpz_cmp_ui(left_val, 0) >= 0)
4605 mpz_tdiv_q_2exp(val, left_val, shift);
4607 mpz_fdiv_q_2exp(val, left_val, shift);
4613 mpz_and(val, left_val, right_val);
4615 case OPERATOR_BITCLEAR:
4619 mpz_com(tval, right_val);
4620 mpz_and(val, left_val, tval);
4628 mpz_clear(left_val);
4629 mpz_clear(right_val);
4631 if (left_nc->is_rune()
4632 || (op != OPERATOR_LSHIFT
4633 && op != OPERATOR_RSHIFT
4634 && right_nc->is_rune()))
4635 nc->set_rune(NULL, val);
4637 nc->set_int(NULL, val);
4644 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4645 // floating point operations. Return true if this could be done,
4649 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4650 const Numeric_constant* right_nc,
4651 Location location, Numeric_constant* nc)
4654 if (!left_nc->to_float(&left_val))
4657 if (!right_nc->to_float(&right_val))
4659 mpfr_clear(left_val);
4670 mpfr_add(val, left_val, right_val, GMP_RNDN);
4672 case OPERATOR_MINUS:
4673 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4678 case OPERATOR_BITCLEAR:
4680 case OPERATOR_LSHIFT:
4681 case OPERATOR_RSHIFT:
4682 mpfr_set_ui(val, 0, GMP_RNDN);
4686 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4689 if (!mpfr_zero_p(right_val))
4690 mpfr_div(val, left_val, right_val, GMP_RNDN);
4693 error_at(location, "division by zero");
4694 mpfr_set_ui(val, 0, GMP_RNDN);
4701 mpfr_clear(left_val);
4702 mpfr_clear(right_val);
4704 nc->set_float(NULL, val);
4710 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4711 // complex operations. Return true if this could be done, false if
4715 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4716 const Numeric_constant* right_nc,
4717 Location location, Numeric_constant* nc)
4719 mpfr_t left_real, left_imag;
4720 if (!left_nc->to_complex(&left_real, &left_imag))
4722 mpfr_t right_real, right_imag;
4723 if (!right_nc->to_complex(&right_real, &right_imag))
4725 mpfr_clear(left_real);
4726 mpfr_clear(left_imag);
4738 mpfr_add(real, left_real, right_real, GMP_RNDN);
4739 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4741 case OPERATOR_MINUS:
4742 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4743 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4748 case OPERATOR_BITCLEAR:
4750 case OPERATOR_LSHIFT:
4751 case OPERATOR_RSHIFT:
4752 mpfr_set_ui(real, 0, GMP_RNDN);
4753 mpfr_set_ui(imag, 0, GMP_RNDN);
4758 // You might think that multiplying two complex numbers would
4759 // be simple, and you would be right, until you start to think
4760 // about getting the right answer for infinity. If one
4761 // operand here is infinity and the other is anything other
4762 // than zero or NaN, then we are going to wind up subtracting
4763 // two infinity values. That will give us a NaN, but the
4764 // correct answer is infinity.
4768 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4772 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4776 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4780 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4782 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4783 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4785 // If we get NaN on both sides, check whether it should really
4786 // be infinity. The rule is that if either side of the
4787 // complex number is infinity, then the whole value is
4788 // infinity, even if the other side is NaN. So the only case
4789 // we have to fix is the one in which both sides are NaN.
4790 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4791 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4792 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4794 bool is_infinity = false;
4798 mpfr_init_set(lr, left_real, GMP_RNDN);
4799 mpfr_init_set(li, left_imag, GMP_RNDN);
4803 mpfr_init_set(rr, right_real, GMP_RNDN);
4804 mpfr_init_set(ri, right_imag, GMP_RNDN);
4806 // If the left side is infinity, then the result is
4808 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4810 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4811 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4812 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4813 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4816 mpfr_set_ui(rr, 0, GMP_RNDN);
4817 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4821 mpfr_set_ui(ri, 0, GMP_RNDN);
4822 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4827 // If the right side is infinity, then the result is
4829 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4831 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4832 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4833 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4834 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4837 mpfr_set_ui(lr, 0, GMP_RNDN);
4838 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4842 mpfr_set_ui(li, 0, GMP_RNDN);
4843 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4848 // If we got an overflow in the intermediate computations,
4849 // then the result is infinity.
4851 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4852 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4856 mpfr_set_ui(lr, 0, GMP_RNDN);
4857 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4861 mpfr_set_ui(li, 0, GMP_RNDN);
4862 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4866 mpfr_set_ui(rr, 0, GMP_RNDN);
4867 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4871 mpfr_set_ui(ri, 0, GMP_RNDN);
4872 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4879 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4880 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4881 mpfr_mul(lirr, li, rr, GMP_RNDN);
4882 mpfr_mul(liri, li, ri, GMP_RNDN);
4883 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4884 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4885 mpfr_set_inf(real, mpfr_sgn(real));
4886 mpfr_set_inf(imag, mpfr_sgn(imag));
4903 // For complex division we want to avoid having an
4904 // intermediate overflow turn the whole result in a NaN. We
4905 // scale the values to try to avoid this.
4907 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4909 error_at(location, "division by zero");
4910 mpfr_set_ui(real, 0, GMP_RNDN);
4911 mpfr_set_ui(imag, 0, GMP_RNDN);
4919 mpfr_abs(rra, right_real, GMP_RNDN);
4920 mpfr_abs(ria, right_imag, GMP_RNDN);
4923 mpfr_max(t, rra, ria, GMP_RNDN);
4927 mpfr_init_set(rr, right_real, GMP_RNDN);
4928 mpfr_init_set(ri, right_imag, GMP_RNDN);
4930 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4932 ilogbw = mpfr_get_exp(t);
4933 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4934 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4939 mpfr_mul(denom, rr, rr, GMP_RNDN);
4940 mpfr_mul(t, ri, ri, GMP_RNDN);
4941 mpfr_add(denom, denom, t, GMP_RNDN);
4943 mpfr_mul(real, left_real, rr, GMP_RNDN);
4944 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4945 mpfr_add(real, real, t, GMP_RNDN);
4946 mpfr_div(real, real, denom, GMP_RNDN);
4947 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4949 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4950 mpfr_mul(t, left_real, ri, GMP_RNDN);
4951 mpfr_sub(imag, imag, t, GMP_RNDN);
4952 mpfr_div(imag, imag, denom, GMP_RNDN);
4953 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4955 // If we wind up with NaN on both sides, check whether we
4956 // should really have infinity. The rule is that if either
4957 // side of the complex number is infinity, then the whole
4958 // value is infinity, even if the other side is NaN. So the
4959 // only case we have to fix is the one in which both sides are
4961 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4962 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4963 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4965 if (mpfr_zero_p(denom))
4967 mpfr_set_inf(real, mpfr_sgn(rr));
4968 mpfr_mul(real, real, left_real, GMP_RNDN);
4969 mpfr_set_inf(imag, mpfr_sgn(rr));
4970 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4972 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4973 && mpfr_number_p(rr) && mpfr_number_p(ri))
4975 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4976 mpfr_copysign(t, t, left_real, GMP_RNDN);
4979 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4980 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4984 mpfr_mul(t3, t, rr, GMP_RNDN);
4988 mpfr_mul(t4, t2, ri, GMP_RNDN);
4990 mpfr_add(t3, t3, t4, GMP_RNDN);
4991 mpfr_set_inf(real, mpfr_sgn(t3));
4993 mpfr_mul(t3, t2, rr, GMP_RNDN);
4994 mpfr_mul(t4, t, ri, GMP_RNDN);
4995 mpfr_sub(t3, t3, t4, GMP_RNDN);
4996 mpfr_set_inf(imag, mpfr_sgn(t3));
5002 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5003 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5005 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5006 mpfr_copysign(t, t, rr, GMP_RNDN);
5009 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5010 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5014 mpfr_mul(t3, left_real, t, GMP_RNDN);
5018 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5020 mpfr_add(t3, t3, t4, GMP_RNDN);
5021 mpfr_set_ui(real, 0, GMP_RNDN);
5022 mpfr_mul(real, real, t3, GMP_RNDN);
5024 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5025 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5026 mpfr_sub(t3, t3, t4, GMP_RNDN);
5027 mpfr_set_ui(imag, 0, GMP_RNDN);
5028 mpfr_mul(imag, imag, t3, GMP_RNDN);
5048 mpfr_clear(left_real);
5049 mpfr_clear(left_imag);
5050 mpfr_clear(right_real);
5051 mpfr_clear(right_imag);
5053 nc->set_complex(NULL, real, imag);
5060 // Lower a binary expression. We have to evaluate constant
5061 // expressions now, in order to implement Go's unlimited precision
5065 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5066 Statement_inserter* inserter, int)
5068 Location location = this->location();
5069 Operator op = this->op_;
5070 Expression* left = this->left_;
5071 Expression* right = this->right_;
5073 const bool is_comparison = (op == OPERATOR_EQEQ
5074 || op == OPERATOR_NOTEQ
5075 || op == OPERATOR_LT
5076 || op == OPERATOR_LE
5077 || op == OPERATOR_GT
5078 || op == OPERATOR_GE);
5080 // Numeric constant expressions.
5082 Numeric_constant left_nc;
5083 Numeric_constant right_nc;
5084 if (left->numeric_constant_value(&left_nc)
5085 && right->numeric_constant_value(&right_nc))
5090 if (!Binary_expression::compare_constant(op, &left_nc,
5091 &right_nc, location,
5094 return Expression::make_cast(Type::make_boolean_type(),
5095 Expression::make_boolean(result,
5101 Numeric_constant nc;
5102 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5105 return nc.expression(location);
5110 // String constant expressions.
5111 if (left->type()->is_string_type() && right->type()->is_string_type())
5113 std::string left_string;
5114 std::string right_string;
5115 if (left->string_constant_value(&left_string)
5116 && right->string_constant_value(&right_string))
5118 if (op == OPERATOR_PLUS)
5119 return Expression::make_string(left_string + right_string,
5121 else if (is_comparison)
5123 int cmp = left_string.compare(right_string);
5124 bool r = Binary_expression::cmp_to_bool(op, cmp);
5125 return Expression::make_boolean(r, location);
5130 // Lower struct and array comparisons.
5131 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5133 if (left->type()->struct_type() != NULL)
5134 return this->lower_struct_comparison(gogo, inserter);
5135 else if (left->type()->array_type() != NULL
5136 && !left->type()->is_slice_type())
5137 return this->lower_array_comparison(gogo, inserter);
5143 // Lower a struct comparison.
5146 Binary_expression::lower_struct_comparison(Gogo* gogo,
5147 Statement_inserter* inserter)
5149 Struct_type* st = this->left_->type()->struct_type();
5150 Struct_type* st2 = this->right_->type()->struct_type();
5153 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5155 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5156 this->right_->type(), NULL))
5159 // See if we can compare using memcmp. As a heuristic, we use
5160 // memcmp rather than field references and comparisons if there are
5161 // more than two fields.
5162 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5163 return this->lower_compare_to_memcmp(gogo, inserter);
5165 Location loc = this->location();
5167 Expression* left = this->left_;
5168 Temporary_statement* left_temp = NULL;
5169 if (left->var_expression() == NULL
5170 && left->temporary_reference_expression() == NULL)
5172 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5173 inserter->insert(left_temp);
5174 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5177 Expression* right = this->right_;
5178 Temporary_statement* right_temp = NULL;
5179 if (right->var_expression() == NULL
5180 && right->temporary_reference_expression() == NULL)
5182 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5183 inserter->insert(right_temp);
5184 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5187 Expression* ret = Expression::make_boolean(true, loc);
5188 const Struct_field_list* fields = st->fields();
5189 unsigned int field_index = 0;
5190 for (Struct_field_list::const_iterator pf = fields->begin();
5191 pf != fields->end();
5192 ++pf, ++field_index)
5194 if (Gogo::is_sink_name(pf->field_name()))
5197 if (field_index > 0)
5199 if (left_temp == NULL)
5200 left = left->copy();
5202 left = Expression::make_temporary_reference(left_temp, loc);
5203 if (right_temp == NULL)
5204 right = right->copy();
5206 right = Expression::make_temporary_reference(right_temp, loc);
5208 Expression* f1 = Expression::make_field_reference(left, field_index,
5210 Expression* f2 = Expression::make_field_reference(right, field_index,
5212 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5213 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5216 if (this->op_ == OPERATOR_NOTEQ)
5217 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5222 // Lower an array comparison.
5225 Binary_expression::lower_array_comparison(Gogo* gogo,
5226 Statement_inserter* inserter)
5228 Array_type* at = this->left_->type()->array_type();
5229 Array_type* at2 = this->right_->type()->array_type();
5232 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5234 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5235 this->right_->type(), NULL))
5238 // Call memcmp directly if possible. This may let the middle-end
5239 // optimize the call.
5240 if (at->compare_is_identity(gogo))
5241 return this->lower_compare_to_memcmp(gogo, inserter);
5243 // Call the array comparison function.
5244 Named_object* hash_fn;
5245 Named_object* equal_fn;
5246 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5247 &hash_fn, &equal_fn);
5249 Location loc = this->location();
5251 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5253 Expression_list* args = new Expression_list();
5254 args->push_back(this->operand_address(inserter, this->left_));
5255 args->push_back(this->operand_address(inserter, this->right_));
5256 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5258 Expression* ret = Expression::make_call(func, args, false, loc);
5260 if (this->op_ == OPERATOR_NOTEQ)
5261 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5266 // Lower a struct or array comparison to a call to memcmp.
5269 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5271 Location loc = this->location();
5273 Expression* a1 = this->operand_address(inserter, this->left_);
5274 Expression* a2 = this->operand_address(inserter, this->right_);
5275 Expression* len = Expression::make_type_info(this->left_->type(),
5278 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5281 mpz_init_set_ui(zval, 0);
5282 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5285 return Expression::make_binary(this->op_, call, zero, loc);
5288 // Return the address of EXPR, cast to unsafe.Pointer.
5291 Binary_expression::operand_address(Statement_inserter* inserter,
5294 Location loc = this->location();
5296 if (!expr->is_addressable())
5298 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5300 inserter->insert(temp);
5301 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5303 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5304 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5305 Type* void_type = Type::make_void_type();
5306 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5307 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5310 // Return the numeric constant value, if it has one.
5313 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5315 Numeric_constant left_nc;
5316 if (!this->left_->numeric_constant_value(&left_nc))
5318 Numeric_constant right_nc;
5319 if (!this->right_->numeric_constant_value(&right_nc))
5321 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5322 this->location(), nc);
5325 // Note that the value is being discarded.
5328 Binary_expression::do_discarding_value()
5330 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5332 this->right_->discarding_value();
5337 this->unused_value_error();
5345 Binary_expression::do_type()
5347 if (this->classification() == EXPRESSION_ERROR)
5348 return Type::make_error_type();
5353 case OPERATOR_NOTEQ:
5358 if (this->type_ == NULL)
5359 this->type_ = Type::make_boolean_type();
5363 case OPERATOR_MINUS:
5370 case OPERATOR_BITCLEAR:
5372 case OPERATOR_ANDAND:
5375 if (!Binary_expression::operation_type(this->op_,
5376 this->left_->type(),
5377 this->right_->type(),
5379 return Type::make_error_type();
5383 case OPERATOR_LSHIFT:
5384 case OPERATOR_RSHIFT:
5385 return this->left_->type();
5392 // Set type for a binary expression.
5395 Binary_expression::do_determine_type(const Type_context* context)
5397 Type* tleft = this->left_->type();
5398 Type* tright = this->right_->type();
5400 // Both sides should have the same type, except for the shift
5401 // operations. For a comparison, we should ignore the incoming
5404 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5405 || this->op_ == OPERATOR_RSHIFT);
5407 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5408 || this->op_ == OPERATOR_NOTEQ
5409 || this->op_ == OPERATOR_LT
5410 || this->op_ == OPERATOR_LE
5411 || this->op_ == OPERATOR_GT
5412 || this->op_ == OPERATOR_GE);
5414 Type_context subcontext(*context);
5418 // In a comparison, the context does not determine the types of
5420 subcontext.type = NULL;
5423 // Set the context for the left hand operand.
5426 // The right hand operand of a shift plays no role in
5427 // determining the type of the left hand operand.
5429 else if (!tleft->is_abstract())
5430 subcontext.type = tleft;
5431 else if (!tright->is_abstract())
5432 subcontext.type = tright;
5433 else if (subcontext.type == NULL)
5435 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5436 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5437 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5439 // Both sides have an abstract integer, abstract float, or
5440 // abstract complex type. Just let CONTEXT determine
5441 // whether they may remain abstract or not.
5443 else if (tleft->complex_type() != NULL)
5444 subcontext.type = tleft;
5445 else if (tright->complex_type() != NULL)
5446 subcontext.type = tright;
5447 else if (tleft->float_type() != NULL)
5448 subcontext.type = tleft;
5449 else if (tright->float_type() != NULL)
5450 subcontext.type = tright;
5452 subcontext.type = tleft;
5454 if (subcontext.type != NULL && !context->may_be_abstract)
5455 subcontext.type = subcontext.type->make_non_abstract_type();
5458 this->left_->determine_type(&subcontext);
5462 // We may have inherited an unusable type for the shift operand.
5463 // Give a useful error if that happened.
5464 if (tleft->is_abstract()
5465 && subcontext.type != NULL
5466 && (this->left_->type()->integer_type() == NULL
5467 || (subcontext.type->integer_type() == NULL
5468 && subcontext.type->float_type() == NULL
5469 && subcontext.type->complex_type() == NULL
5470 && subcontext.type->interface_type() == NULL)))
5471 this->report_error(("invalid context-determined non-integer type "
5472 "for shift operand"));
5474 // The context for the right hand operand is the same as for the
5475 // left hand operand, except for a shift operator.
5476 subcontext.type = Type::lookup_integer_type("uint");
5477 subcontext.may_be_abstract = false;
5480 this->right_->determine_type(&subcontext);
5484 if (this->type_ != NULL && !this->type_->is_abstract())
5486 else if (context->type != NULL && context->type->is_boolean_type())
5487 this->type_ = context->type;
5488 else if (!context->may_be_abstract)
5489 this->type_ = Type::lookup_bool_type();
5493 // Report an error if the binary operator OP does not support TYPE.
5494 // OTYPE is the type of the other operand. Return whether the
5495 // operation is OK. This should not be used for shift.
5498 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5504 case OPERATOR_ANDAND:
5505 if (!type->is_boolean_type())
5507 error_at(location, "expected boolean type");
5513 case OPERATOR_NOTEQ:
5516 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5518 error_at(location, "%s", reason.c_str());
5530 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5532 error_at(location, "%s", reason.c_str());
5539 case OPERATOR_PLUSEQ:
5540 if (type->integer_type() == NULL
5541 && type->float_type() == NULL
5542 && type->complex_type() == NULL
5543 && !type->is_string_type())
5546 "expected integer, floating, complex, or string type");
5551 case OPERATOR_MINUS:
5552 case OPERATOR_MINUSEQ:
5554 case OPERATOR_MULTEQ:
5556 case OPERATOR_DIVEQ:
5557 if (type->integer_type() == NULL
5558 && type->float_type() == NULL
5559 && type->complex_type() == NULL)
5561 error_at(location, "expected integer, floating, or complex type");
5567 case OPERATOR_MODEQ:
5571 case OPERATOR_ANDEQ:
5573 case OPERATOR_XOREQ:
5574 case OPERATOR_BITCLEAR:
5575 case OPERATOR_BITCLEAREQ:
5576 if (type->integer_type() == NULL)
5578 error_at(location, "expected integer type");
5593 Binary_expression::do_check_types(Gogo*)
5595 if (this->classification() == EXPRESSION_ERROR)
5598 Type* left_type = this->left_->type();
5599 Type* right_type = this->right_->type();
5600 if (left_type->is_error() || right_type->is_error())
5602 this->set_is_error();
5606 if (this->op_ == OPERATOR_EQEQ
5607 || this->op_ == OPERATOR_NOTEQ
5608 || this->op_ == OPERATOR_LT
5609 || this->op_ == OPERATOR_LE
5610 || this->op_ == OPERATOR_GT
5611 || this->op_ == OPERATOR_GE)
5613 if (!Type::are_assignable(left_type, right_type, NULL)
5614 && !Type::are_assignable(right_type, left_type, NULL))
5616 this->report_error(_("incompatible types in binary expression"));
5619 if (!Binary_expression::check_operator_type(this->op_, left_type,
5622 || !Binary_expression::check_operator_type(this->op_, right_type,
5626 this->set_is_error();
5630 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5632 if (!Type::are_compatible_for_binop(left_type, right_type))
5634 this->report_error(_("incompatible types in binary expression"));
5637 if (!Binary_expression::check_operator_type(this->op_, left_type,
5641 this->set_is_error();
5647 if (left_type->integer_type() == NULL)
5648 this->report_error(_("shift of non-integer operand"));
5650 if (!right_type->is_abstract()
5651 && (right_type->integer_type() == NULL
5652 || !right_type->integer_type()->is_unsigned()))
5653 this->report_error(_("shift count not unsigned integer"));
5656 Numeric_constant nc;
5657 if (this->right_->numeric_constant_value(&nc))
5660 if (!nc.to_int(&val))
5661 this->report_error(_("shift count not unsigned integer"));
5664 if (mpz_sgn(val) < 0)
5666 this->report_error(_("negative shift count"));
5668 Location rloc = this->right_->location();
5669 this->right_ = Expression::make_integer(&val, right_type,
5679 // Get a tree for a binary expression.
5682 Binary_expression::do_get_tree(Translate_context* context)
5684 tree left = this->left_->get_tree(context);
5685 tree right = this->right_->get_tree(context);
5687 if (left == error_mark_node || right == error_mark_node)
5688 return error_mark_node;
5690 enum tree_code code;
5691 bool use_left_type = true;
5692 bool is_shift_op = false;
5693 bool is_idiv_op = false;
5697 case OPERATOR_NOTEQ:
5702 return Expression::comparison_tree(context, this->type_, this->op_,
5703 this->left_->type(), left,
5704 this->right_->type(), right,
5708 code = TRUTH_ORIF_EXPR;
5709 use_left_type = false;
5711 case OPERATOR_ANDAND:
5712 code = TRUTH_ANDIF_EXPR;
5713 use_left_type = false;
5718 case OPERATOR_MINUS:
5722 code = BIT_IOR_EXPR;
5725 code = BIT_XOR_EXPR;
5732 Type *t = this->left_->type();
5733 if (t->float_type() != NULL || t->complex_type() != NULL)
5737 code = TRUNC_DIV_EXPR;
5743 code = TRUNC_MOD_EXPR;
5746 case OPERATOR_LSHIFT:
5750 case OPERATOR_RSHIFT:
5755 code = BIT_AND_EXPR;
5757 case OPERATOR_BITCLEAR:
5758 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5759 code = BIT_AND_EXPR;
5765 location_t gccloc = this->location().gcc_location();
5766 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5768 if (this->left_->type()->is_string_type())
5770 go_assert(this->op_ == OPERATOR_PLUS);
5771 Type* st = Type::make_string_type();
5772 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5773 static tree string_plus_decl;
5774 return Gogo::call_builtin(&string_plus_decl,
5785 tree compute_type = excess_precision_type(type);
5786 if (compute_type != NULL_TREE)
5788 left = ::convert(compute_type, left);
5789 right = ::convert(compute_type, right);
5792 tree eval_saved = NULL_TREE;
5794 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5796 // Make sure the values are evaluated.
5799 left = save_expr(left);
5804 right = save_expr(right);
5805 if (eval_saved == NULL_TREE)
5808 eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
5809 void_type_node, eval_saved, right);
5813 tree ret = fold_build2_loc(gccloc, code,
5814 compute_type != NULL_TREE ? compute_type : type,
5817 if (compute_type != NULL_TREE)
5818 ret = ::convert(type, ret);
5820 // In Go, a shift larger than the size of the type is well-defined.
5821 // This is not true in GENERIC, so we need to insert a conditional.
5824 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5825 go_assert(this->left_->type()->integer_type() != NULL);
5826 int bits = TYPE_PRECISION(TREE_TYPE(left));
5828 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5829 build_int_cst_type(TREE_TYPE(right), bits));
5831 tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
5833 if (this->op_ == OPERATOR_RSHIFT
5834 && !this->left_->type()->integer_type()->is_unsigned())
5837 fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
5839 fold_convert_loc(gccloc, TREE_TYPE(left),
5840 integer_zero_node));
5842 fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
5843 fold_convert_loc(gccloc, TREE_TYPE(left),
5845 fold_convert_loc(gccloc, TREE_TYPE(left),
5848 fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5849 neg, neg_one, overflow_result);
5852 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5853 compare, ret, overflow_result);
5855 if (eval_saved != NULL_TREE)
5856 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5860 // Add checks for division by zero and division overflow as needed.
5863 if (go_check_divide_zero)
5866 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5868 fold_convert_loc(gccloc,
5870 integer_zero_node));
5872 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
5873 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5874 tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5875 Gogo::runtime_error(errcode,
5877 fold_convert_loc(gccloc, TREE_TYPE(ret),
5878 integer_zero_node));
5880 // right == 0 ? (__go_runtime_error(...), 0) : ret
5881 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5885 if (go_check_divide_overflow)
5888 // FIXME: It would be nice to say that this test is expected
5890 tree m1 = integer_minus_one_node;
5891 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5893 fold_convert_loc(gccloc,
5898 if (TYPE_UNSIGNED(TREE_TYPE(ret)))
5900 // An unsigned -1 is the largest possible number, so
5901 // dividing is always 1 or 0.
5902 tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5904 if (this->op_ == OPERATOR_DIV)
5905 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5907 fold_convert_loc(gccloc,
5910 fold_convert_loc(gccloc,
5912 integer_zero_node));
5914 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5916 fold_convert_loc(gccloc,
5923 // Computing left / -1 is the same as computing - left,
5924 // which does not overflow since Go sets -fwrapv.
5925 if (this->op_ == OPERATOR_DIV)
5926 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
5929 overflow = integer_zero_node;
5931 overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
5933 // right == -1 ? - left : ret
5934 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5935 check, overflow, ret);
5938 if (eval_saved != NULL_TREE)
5939 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5946 // Export a binary expression.
5949 Binary_expression::do_export(Export* exp) const
5951 exp->write_c_string("(");
5952 this->left_->export_expression(exp);
5956 exp->write_c_string(" || ");
5958 case OPERATOR_ANDAND:
5959 exp->write_c_string(" && ");
5962 exp->write_c_string(" == ");
5964 case OPERATOR_NOTEQ:
5965 exp->write_c_string(" != ");
5968 exp->write_c_string(" < ");
5971 exp->write_c_string(" <= ");
5974 exp->write_c_string(" > ");
5977 exp->write_c_string(" >= ");
5980 exp->write_c_string(" + ");
5982 case OPERATOR_MINUS:
5983 exp->write_c_string(" - ");
5986 exp->write_c_string(" | ");
5989 exp->write_c_string(" ^ ");
5992 exp->write_c_string(" * ");
5995 exp->write_c_string(" / ");
5998 exp->write_c_string(" % ");
6000 case OPERATOR_LSHIFT:
6001 exp->write_c_string(" << ");
6003 case OPERATOR_RSHIFT:
6004 exp->write_c_string(" >> ");
6007 exp->write_c_string(" & ");
6009 case OPERATOR_BITCLEAR:
6010 exp->write_c_string(" &^ ");
6015 this->right_->export_expression(exp);
6016 exp->write_c_string(")");
6019 // Import a binary expression.
6022 Binary_expression::do_import(Import* imp)
6024 imp->require_c_string("(");
6026 Expression* left = Expression::import_expression(imp);
6029 if (imp->match_c_string(" || "))
6034 else if (imp->match_c_string(" && "))
6036 op = OPERATOR_ANDAND;
6039 else if (imp->match_c_string(" == "))
6044 else if (imp->match_c_string(" != "))
6046 op = OPERATOR_NOTEQ;
6049 else if (imp->match_c_string(" < "))
6054 else if (imp->match_c_string(" <= "))
6059 else if (imp->match_c_string(" > "))
6064 else if (imp->match_c_string(" >= "))
6069 else if (imp->match_c_string(" + "))
6074 else if (imp->match_c_string(" - "))
6076 op = OPERATOR_MINUS;
6079 else if (imp->match_c_string(" | "))
6084 else if (imp->match_c_string(" ^ "))
6089 else if (imp->match_c_string(" * "))
6094 else if (imp->match_c_string(" / "))
6099 else if (imp->match_c_string(" % "))
6104 else if (imp->match_c_string(" << "))
6106 op = OPERATOR_LSHIFT;
6109 else if (imp->match_c_string(" >> "))
6111 op = OPERATOR_RSHIFT;
6114 else if (imp->match_c_string(" & "))
6119 else if (imp->match_c_string(" &^ "))
6121 op = OPERATOR_BITCLEAR;
6126 error_at(imp->location(), "unrecognized binary operator");
6127 return Expression::make_error(imp->location());
6130 Expression* right = Expression::import_expression(imp);
6132 imp->require_c_string(")");
6134 return Expression::make_binary(op, left, right, imp->location());
6137 // Dump ast representation of a binary expression.
6140 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6142 ast_dump_context->ostream() << "(";
6143 ast_dump_context->dump_expression(this->left_);
6144 ast_dump_context->ostream() << " ";
6145 ast_dump_context->dump_operator(this->op_);
6146 ast_dump_context->ostream() << " ";
6147 ast_dump_context->dump_expression(this->right_);
6148 ast_dump_context->ostream() << ") ";
6151 // Make a binary expression.
6154 Expression::make_binary(Operator op, Expression* left, Expression* right,
6157 return new Binary_expression(op, left, right, location);
6160 // Implement a comparison.
6163 Expression::comparison_tree(Translate_context* context, Type* result_type,
6164 Operator op, Type* left_type, tree left_tree,
6165 Type* right_type, tree right_tree,
6168 enum tree_code code;
6174 case OPERATOR_NOTEQ:
6193 if (left_type->is_string_type() && right_type->is_string_type())
6195 Type* st = Type::make_string_type();
6196 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6197 static tree string_compare_decl;
6198 left_tree = Gogo::call_builtin(&string_compare_decl,
6207 right_tree = build_int_cst_type(integer_type_node, 0);
6209 else if ((left_type->interface_type() != NULL
6210 && right_type->interface_type() == NULL
6211 && !right_type->is_nil_type())
6212 || (left_type->interface_type() == NULL
6213 && !left_type->is_nil_type()
6214 && right_type->interface_type() != NULL))
6216 // Comparing an interface value to a non-interface value.
6217 if (left_type->interface_type() == NULL)
6219 std::swap(left_type, right_type);
6220 std::swap(left_tree, right_tree);
6223 // The right operand is not an interface. We need to take its
6224 // address if it is not a pointer.
6227 if (right_type->points_to() != NULL)
6229 make_tmp = NULL_TREE;
6232 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree))
6233 || (TREE_CODE(right_tree) != CONST_DECL
6234 && DECL_P(right_tree)))
6236 make_tmp = NULL_TREE;
6237 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6238 if (DECL_P(right_tree))
6239 TREE_ADDRESSABLE(right_tree) = 1;
6243 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6244 get_name(right_tree));
6245 DECL_IGNORED_P(tmp) = 0;
6246 DECL_INITIAL(tmp) = right_tree;
6247 TREE_ADDRESSABLE(tmp) = 1;
6248 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6249 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6250 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6252 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6254 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6257 if (left_type->interface_type()->is_empty())
6259 static tree empty_interface_value_compare_decl;
6260 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6262 "__go_empty_interface_value_compare",
6265 TREE_TYPE(left_tree),
6267 TREE_TYPE(descriptor),
6271 if (left_tree == error_mark_node)
6272 return error_mark_node;
6273 // This can panic if the type is not comparable.
6274 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6278 static tree interface_value_compare_decl;
6279 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6281 "__go_interface_value_compare",
6284 TREE_TYPE(left_tree),
6286 TREE_TYPE(descriptor),
6290 if (left_tree == error_mark_node)
6291 return error_mark_node;
6292 // This can panic if the type is not comparable.
6293 TREE_NOTHROW(interface_value_compare_decl) = 0;
6295 right_tree = build_int_cst_type(integer_type_node, 0);
6297 if (make_tmp != NULL_TREE)
6298 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6301 else if (left_type->interface_type() != NULL
6302 && right_type->interface_type() != NULL)
6304 if (left_type->interface_type()->is_empty()
6305 && right_type->interface_type()->is_empty())
6307 static tree empty_interface_compare_decl;
6308 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6310 "__go_empty_interface_compare",
6313 TREE_TYPE(left_tree),
6315 TREE_TYPE(right_tree),
6317 if (left_tree == error_mark_node)
6318 return error_mark_node;
6319 // This can panic if the type is uncomparable.
6320 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6322 else if (!left_type->interface_type()->is_empty()
6323 && !right_type->interface_type()->is_empty())
6325 static tree interface_compare_decl;
6326 left_tree = Gogo::call_builtin(&interface_compare_decl,
6328 "__go_interface_compare",
6331 TREE_TYPE(left_tree),
6333 TREE_TYPE(right_tree),
6335 if (left_tree == error_mark_node)
6336 return error_mark_node;
6337 // This can panic if the type is uncomparable.
6338 TREE_NOTHROW(interface_compare_decl) = 0;
6342 if (left_type->interface_type()->is_empty())
6344 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6345 std::swap(left_type, right_type);
6346 std::swap(left_tree, right_tree);
6348 go_assert(!left_type->interface_type()->is_empty());
6349 go_assert(right_type->interface_type()->is_empty());
6350 static tree interface_empty_compare_decl;
6351 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6353 "__go_interface_empty_compare",
6356 TREE_TYPE(left_tree),
6358 TREE_TYPE(right_tree),
6360 if (left_tree == error_mark_node)
6361 return error_mark_node;
6362 // This can panic if the type is uncomparable.
6363 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6366 right_tree = build_int_cst_type(integer_type_node, 0);
6369 if (left_type->is_nil_type()
6370 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6372 std::swap(left_type, right_type);
6373 std::swap(left_tree, right_tree);
6376 if (right_type->is_nil_type())
6378 if (left_type->array_type() != NULL
6379 && left_type->array_type()->length() == NULL)
6381 Array_type* at = left_type->array_type();
6382 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6383 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6385 else if (left_type->interface_type() != NULL)
6387 // An interface is nil if the first field is nil.
6388 tree left_type_tree = TREE_TYPE(left_tree);
6389 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6390 tree field = TYPE_FIELDS(left_type_tree);
6391 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6393 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6397 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6398 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6402 if (left_tree == error_mark_node || right_tree == error_mark_node)
6403 return error_mark_node;
6405 tree result_type_tree;
6406 if (result_type == NULL)
6407 result_type_tree = boolean_type_node;
6409 result_type_tree = type_to_tree(result_type->get_backend(context->gogo()));
6411 tree ret = fold_build2(code, result_type_tree, left_tree, right_tree);
6412 if (CAN_HAVE_LOCATION_P(ret))
6413 SET_EXPR_LOCATION(ret, location.gcc_location());
6417 // Class Bound_method_expression.
6422 Bound_method_expression::do_traverse(Traverse* traverse)
6424 return Expression::traverse(&this->expr_, traverse);
6427 // Return the type of a bound method expression. The type of this
6428 // object is really the type of the method with no receiver. We
6429 // should be able to get away with just returning the type of the
6433 Bound_method_expression::do_type()
6435 if (this->method_->is_function())
6436 return this->method_->func_value()->type();
6437 else if (this->method_->is_function_declaration())
6438 return this->method_->func_declaration_value()->type();
6440 return Type::make_error_type();
6443 // Determine the types of a method expression.
6446 Bound_method_expression::do_determine_type(const Type_context*)
6448 Function_type* fntype = this->type()->function_type();
6449 if (fntype == NULL || !fntype->is_method())
6450 this->expr_->determine_type_no_context();
6453 Type_context subcontext(fntype->receiver()->type(), false);
6454 this->expr_->determine_type(&subcontext);
6458 // Check the types of a method expression.
6461 Bound_method_expression::do_check_types(Gogo*)
6463 if (!this->method_->is_function()
6464 && !this->method_->is_function_declaration())
6465 this->report_error(_("object is not a method"));
6468 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6469 Type* etype = (this->expr_type_ != NULL
6471 : this->expr_->type());
6472 etype = etype->deref();
6473 if (!Type::are_identical(rtype, etype, true, NULL))
6474 this->report_error(_("method type does not match object type"));
6478 // Get the tree for a method expression. There is no standard tree
6479 // representation for this. The only places it may currently be used
6480 // are in a Call_expression or a Go_statement, which will take it
6481 // apart directly. So this has nothing to do at present.
6484 Bound_method_expression::do_get_tree(Translate_context*)
6486 error_at(this->location(), "reference to method other than calling it");
6487 return error_mark_node;
6490 // Dump ast representation of a bound method expression.
6493 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6496 if (this->expr_type_ != NULL)
6497 ast_dump_context->ostream() << "(";
6498 ast_dump_context->dump_expression(this->expr_);
6499 if (this->expr_type_ != NULL)
6501 ast_dump_context->ostream() << ":";
6502 ast_dump_context->dump_type(this->expr_type_);
6503 ast_dump_context->ostream() << ")";
6506 ast_dump_context->ostream() << "." << this->method_->name();
6509 // Make a method expression.
6511 Bound_method_expression*
6512 Expression::make_bound_method(Expression* expr, Named_object* method,
6515 return new Bound_method_expression(expr, method, location);
6518 // Class Builtin_call_expression. This is used for a call to a
6519 // builtin function.
6521 class Builtin_call_expression : public Call_expression
6524 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6525 bool is_varargs, Location location);
6528 // This overrides Call_expression::do_lower.
6530 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6533 do_is_constant() const;
6536 do_numeric_constant_value(Numeric_constant*) const;
6539 do_discarding_value();
6545 do_determine_type(const Type_context*);
6548 do_check_types(Gogo*);
6553 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6554 this->args()->copy(),
6560 do_get_tree(Translate_context*);
6563 do_export(Export*) const;
6566 do_is_recover_call() const;
6569 do_set_recover_arg(Expression*);
6572 // The builtin functions.
6573 enum Builtin_function_code
6577 // Predeclared builtin functions.
6594 // Builtin functions from the unsafe package.
6607 real_imag_type(Type*);
6610 complex_type(Type*);
6616 check_int_value(Expression*);
6618 // A pointer back to the general IR structure. This avoids a global
6619 // variable, or passing it around everywhere.
6621 // The builtin function being called.
6622 Builtin_function_code code_;
6623 // Used to stop endless loops when the length of an array uses len
6624 // or cap of the array itself.
6628 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6630 Expression_list* args,
6633 : Call_expression(fn, args, is_varargs, location),
6634 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6636 Func_expression* fnexp = this->fn()->func_expression();
6637 go_assert(fnexp != NULL);
6638 const std::string& name(fnexp->named_object()->name());
6639 if (name == "append")
6640 this->code_ = BUILTIN_APPEND;
6641 else if (name == "cap")
6642 this->code_ = BUILTIN_CAP;
6643 else if (name == "close")
6644 this->code_ = BUILTIN_CLOSE;
6645 else if (name == "complex")
6646 this->code_ = BUILTIN_COMPLEX;
6647 else if (name == "copy")
6648 this->code_ = BUILTIN_COPY;
6649 else if (name == "delete")
6650 this->code_ = BUILTIN_DELETE;
6651 else if (name == "imag")
6652 this->code_ = BUILTIN_IMAG;
6653 else if (name == "len")
6654 this->code_ = BUILTIN_LEN;
6655 else if (name == "make")
6656 this->code_ = BUILTIN_MAKE;
6657 else if (name == "new")
6658 this->code_ = BUILTIN_NEW;
6659 else if (name == "panic")
6660 this->code_ = BUILTIN_PANIC;
6661 else if (name == "print")
6662 this->code_ = BUILTIN_PRINT;
6663 else if (name == "println")
6664 this->code_ = BUILTIN_PRINTLN;
6665 else if (name == "real")
6666 this->code_ = BUILTIN_REAL;
6667 else if (name == "recover")
6668 this->code_ = BUILTIN_RECOVER;
6669 else if (name == "Alignof")
6670 this->code_ = BUILTIN_ALIGNOF;
6671 else if (name == "Offsetof")
6672 this->code_ = BUILTIN_OFFSETOF;
6673 else if (name == "Sizeof")
6674 this->code_ = BUILTIN_SIZEOF;
6679 // Return whether this is a call to recover. This is a virtual
6680 // function called from the parent class.
6683 Builtin_call_expression::do_is_recover_call() const
6685 if (this->classification() == EXPRESSION_ERROR)
6687 return this->code_ == BUILTIN_RECOVER;
6690 // Set the argument for a call to recover.
6693 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6695 const Expression_list* args = this->args();
6696 go_assert(args == NULL || args->empty());
6697 Expression_list* new_args = new Expression_list();
6698 new_args->push_back(arg);
6699 this->set_args(new_args);
6702 // Lower a builtin call expression. This turns new and make into
6703 // specific expressions. We also convert to a constant if we can.
6706 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6707 Statement_inserter* inserter, int)
6709 if (this->classification() == EXPRESSION_ERROR)
6712 Location loc = this->location();
6714 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6716 this->report_error(_("invalid use of %<...%> with builtin function"));
6717 return Expression::make_error(loc);
6720 if (this->is_constant())
6722 Numeric_constant nc;
6723 if (this->numeric_constant_value(&nc))
6724 return nc.expression(loc);
6727 switch (this->code_)
6734 const Expression_list* args = this->args();
6735 if (args == NULL || args->size() < 1)
6736 this->report_error(_("not enough arguments"));
6737 else if (args->size() > 1)
6738 this->report_error(_("too many arguments"));
6741 Expression* arg = args->front();
6742 if (!arg->is_type_expression())
6744 error_at(arg->location(), "expected type");
6745 this->set_is_error();
6748 return Expression::make_allocation(arg->type(), loc);
6754 return this->lower_make();
6756 case BUILTIN_RECOVER:
6757 if (function != NULL)
6758 function->func_value()->set_calls_recover();
6761 // Calling recover outside of a function always returns the
6762 // nil empty interface.
6763 Type* eface = Type::make_empty_interface_type(loc);
6764 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6768 case BUILTIN_APPEND:
6770 // Lower the varargs.
6771 const Expression_list* args = this->args();
6772 if (args == NULL || args->empty())
6774 Type* slice_type = args->front()->type();
6775 if (!slice_type->is_slice_type())
6777 error_at(args->front()->location(), "argument 1 must be a slice");
6778 this->set_is_error();
6781 Type* element_type = slice_type->array_type()->element_type();
6782 this->lower_varargs(gogo, function, inserter,
6783 Type::make_array_type(element_type, NULL),
6788 case BUILTIN_DELETE:
6790 // Lower to a runtime function call.
6791 const Expression_list* args = this->args();
6792 if (args == NULL || args->size() < 2)
6793 this->report_error(_("not enough arguments"));
6794 else if (args->size() > 2)
6795 this->report_error(_("too many arguments"));
6796 else if (args->front()->type()->map_type() == NULL)
6797 this->report_error(_("argument 1 must be a map"));
6800 // Since this function returns no value it must appear in
6801 // a statement by itself, so we don't have to worry about
6802 // order of evaluation of values around it. Evaluate the
6803 // map first to get order of evaluation right.
6804 Map_type* mt = args->front()->type()->map_type();
6805 Temporary_statement* map_temp =
6806 Statement::make_temporary(mt, args->front(), loc);
6807 inserter->insert(map_temp);
6809 Temporary_statement* key_temp =
6810 Statement::make_temporary(mt->key_type(), args->back(), loc);
6811 inserter->insert(key_temp);
6813 Expression* e1 = Expression::make_temporary_reference(map_temp,
6815 Expression* e2 = Expression::make_temporary_reference(key_temp,
6817 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6818 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6828 // Lower a make expression.
6831 Builtin_call_expression::lower_make()
6833 Location loc = this->location();
6835 const Expression_list* args = this->args();
6836 if (args == NULL || args->size() < 1)
6838 this->report_error(_("not enough arguments"));
6839 return Expression::make_error(this->location());
6842 Expression_list::const_iterator parg = args->begin();
6844 Expression* first_arg = *parg;
6845 if (!first_arg->is_type_expression())
6847 error_at(first_arg->location(), "expected type");
6848 this->set_is_error();
6849 return Expression::make_error(this->location());
6851 Type* type = first_arg->type();
6853 bool is_slice = false;
6854 bool is_map = false;
6855 bool is_chan = false;
6856 if (type->is_slice_type())
6858 else if (type->map_type() != NULL)
6860 else if (type->channel_type() != NULL)
6864 this->report_error(_("invalid type for make function"));
6865 return Expression::make_error(this->location());
6868 bool have_big_args = false;
6869 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6870 int uintptr_bits = uintptr_type->integer_type()->bits();
6873 Expression* len_arg;
6874 if (parg == args->end())
6878 this->report_error(_("length required when allocating a slice"));
6879 return Expression::make_error(this->location());
6883 mpz_init_set_ui(zval, 0);
6884 len_arg = Expression::make_integer(&zval, NULL, loc);
6890 if (!this->check_int_value(len_arg))
6892 this->report_error(_("bad size for make"));
6893 return Expression::make_error(this->location());
6895 if (len_arg->type()->integer_type() != NULL
6896 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6897 have_big_args = true;
6901 Expression* cap_arg = NULL;
6902 if (is_slice && parg != args->end())
6905 if (!this->check_int_value(cap_arg))
6907 this->report_error(_("bad capacity when making slice"));
6908 return Expression::make_error(this->location());
6910 if (cap_arg->type()->integer_type() != NULL
6911 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6912 have_big_args = true;
6916 if (parg != args->end())
6918 this->report_error(_("too many arguments to make"));
6919 return Expression::make_error(this->location());
6922 Location type_loc = first_arg->location();
6923 Expression* type_arg;
6924 if (is_slice || is_chan)
6925 type_arg = Expression::make_type_descriptor(type, type_loc);
6927 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6934 if (cap_arg == NULL)
6935 call = Runtime::make_call((have_big_args
6936 ? Runtime::MAKESLICE1BIG
6937 : Runtime::MAKESLICE1),
6938 loc, 2, type_arg, len_arg);
6940 call = Runtime::make_call((have_big_args
6941 ? Runtime::MAKESLICE2BIG
6942 : Runtime::MAKESLICE2),
6943 loc, 3, type_arg, len_arg, cap_arg);
6946 call = Runtime::make_call((have_big_args
6947 ? Runtime::MAKEMAPBIG
6948 : Runtime::MAKEMAP),
6949 loc, 2, type_arg, len_arg);
6951 call = Runtime::make_call((have_big_args
6952 ? Runtime::MAKECHANBIG
6953 : Runtime::MAKECHAN),
6954 loc, 2, type_arg, len_arg);
6958 return Expression::make_unsafe_cast(type, call, loc);
6961 // Return whether an expression has an integer value. Report an error
6962 // if not. This is used when handling calls to the predeclared make
6966 Builtin_call_expression::check_int_value(Expression* e)
6968 if (e->type()->integer_type() != NULL)
6971 // Check for a floating point constant with integer value.
6972 Numeric_constant nc;
6974 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6983 // Return the type of the real or imag functions, given the type of
6984 // the argument. We need to map complex to float, complex64 to
6985 // float32, and complex128 to float64, so it has to be done by name.
6986 // This returns NULL if it can't figure out the type.
6989 Builtin_call_expression::real_imag_type(Type* arg_type)
6991 if (arg_type == NULL || arg_type->is_abstract())
6993 Named_type* nt = arg_type->named_type();
6996 while (nt->real_type()->named_type() != NULL)
6997 nt = nt->real_type()->named_type();
6998 if (nt->name() == "complex64")
6999 return Type::lookup_float_type("float32");
7000 else if (nt->name() == "complex128")
7001 return Type::lookup_float_type("float64");
7006 // Return the type of the complex function, given the type of one of the
7007 // argments. Like real_imag_type, we have to map by name.
7010 Builtin_call_expression::complex_type(Type* arg_type)
7012 if (arg_type == NULL || arg_type->is_abstract())
7014 Named_type* nt = arg_type->named_type();
7017 while (nt->real_type()->named_type() != NULL)
7018 nt = nt->real_type()->named_type();
7019 if (nt->name() == "float32")
7020 return Type::lookup_complex_type("complex64");
7021 else if (nt->name() == "float64")
7022 return Type::lookup_complex_type("complex128");
7027 // Return a single argument, or NULL if there isn't one.
7030 Builtin_call_expression::one_arg() const
7032 const Expression_list* args = this->args();
7033 if (args == NULL || args->size() != 1)
7035 return args->front();
7038 // A traversal class which looks for a call or receive expression.
7040 class Find_call_expression : public Traverse
7043 Find_call_expression()
7044 : Traverse(traverse_expressions),
7049 expression(Expression**);
7053 { return this->found_; }
7060 Find_call_expression::expression(Expression** pexpr)
7062 if ((*pexpr)->call_expression() != NULL
7063 || (*pexpr)->receive_expression() != NULL)
7065 this->found_ = true;
7066 return TRAVERSE_EXIT;
7068 return TRAVERSE_CONTINUE;
7071 // Return whether this is constant: len of a string constant, or len
7072 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7076 Builtin_call_expression::do_is_constant() const
7078 switch (this->code_)
7086 Expression* arg = this->one_arg();
7089 Type* arg_type = arg->type();
7091 if (arg_type->points_to() != NULL
7092 && arg_type->points_to()->array_type() != NULL
7093 && !arg_type->points_to()->is_slice_type())
7094 arg_type = arg_type->points_to();
7096 // The len and cap functions are only constant if there are no
7097 // function calls or channel operations in the arguments.
7098 // Otherwise we have to make the call.
7099 if (!arg->is_constant())
7101 Find_call_expression find_call;
7102 Expression::traverse(&arg, &find_call);
7103 if (find_call.found())
7107 if (arg_type->array_type() != NULL
7108 && arg_type->array_type()->length() != NULL)
7111 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7114 bool ret = arg->is_constant();
7115 this->seen_ = false;
7121 case BUILTIN_SIZEOF:
7122 case BUILTIN_ALIGNOF:
7123 return this->one_arg() != NULL;
7125 case BUILTIN_OFFSETOF:
7127 Expression* arg = this->one_arg();
7130 return arg->field_reference_expression() != NULL;
7133 case BUILTIN_COMPLEX:
7135 const Expression_list* args = this->args();
7136 if (args != NULL && args->size() == 2)
7137 return args->front()->is_constant() && args->back()->is_constant();
7144 Expression* arg = this->one_arg();
7145 return arg != NULL && arg->is_constant();
7155 // Return a numeric constant if possible.
7158 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7160 if (this->code_ == BUILTIN_LEN
7161 || this->code_ == BUILTIN_CAP)
7163 Expression* arg = this->one_arg();
7166 Type* arg_type = arg->type();
7168 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7171 if (arg->string_constant_value(&sval))
7173 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7179 if (arg_type->points_to() != NULL
7180 && arg_type->points_to()->array_type() != NULL
7181 && !arg_type->points_to()->is_slice_type())
7182 arg_type = arg_type->points_to();
7184 if (arg_type->array_type() != NULL
7185 && arg_type->array_type()->length() != NULL)
7189 Expression* e = arg_type->array_type()->length();
7191 bool r = e->numeric_constant_value(nc);
7192 this->seen_ = false;
7195 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7202 else if (this->code_ == BUILTIN_SIZEOF
7203 || this->code_ == BUILTIN_ALIGNOF)
7205 Expression* arg = this->one_arg();
7208 Type* arg_type = arg->type();
7209 if (arg_type->is_error())
7211 if (arg_type->is_abstract())
7213 if (arg_type->named_type() != NULL)
7214 arg_type->named_type()->convert(this->gogo_);
7217 if (this->code_ == BUILTIN_SIZEOF)
7219 if (!arg_type->backend_type_size(this->gogo_, &ret))
7222 else if (this->code_ == BUILTIN_ALIGNOF)
7224 if (arg->field_reference_expression() == NULL)
7226 if (!arg_type->backend_type_align(this->gogo_, &ret))
7231 // Calling unsafe.Alignof(s.f) returns the alignment of
7232 // the type of f when it is used as a field in a struct.
7233 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7240 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7241 static_cast<unsigned long>(ret));
7244 else if (this->code_ == BUILTIN_OFFSETOF)
7246 Expression* arg = this->one_arg();
7249 Field_reference_expression* farg = arg->field_reference_expression();
7252 Expression* struct_expr = farg->expr();
7253 Type* st = struct_expr->type();
7254 if (st->struct_type() == NULL)
7256 if (st->named_type() != NULL)
7257 st->named_type()->convert(this->gogo_);
7258 unsigned int offset;
7259 if (!st->struct_type()->backend_field_offset(this->gogo_,
7260 farg->field_index(),
7263 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7264 static_cast<unsigned long>(offset));
7267 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7269 Expression* arg = this->one_arg();
7273 Numeric_constant argnc;
7274 if (!arg->numeric_constant_value(&argnc))
7279 if (!argnc.to_complex(&real, &imag))
7282 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7283 if (this->code_ == BUILTIN_REAL)
7284 nc->set_float(type, real);
7286 nc->set_float(type, imag);
7289 else if (this->code_ == BUILTIN_COMPLEX)
7291 const Expression_list* args = this->args();
7292 if (args == NULL || args->size() != 2)
7295 Numeric_constant rnc;
7296 if (!args->front()->numeric_constant_value(&rnc))
7298 Numeric_constant inc;
7299 if (!args->back()->numeric_constant_value(&inc))
7302 if (rnc.type() != NULL
7303 && !rnc.type()->is_abstract()
7304 && inc.type() != NULL
7305 && !inc.type()->is_abstract()
7306 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7310 if (!rnc.to_float(&r))
7313 if (!inc.to_float(&i))
7319 Type* arg_type = rnc.type();
7320 if (arg_type == NULL || arg_type->is_abstract())
7321 arg_type = inc.type();
7323 Type* type = Builtin_call_expression::complex_type(arg_type);
7324 nc->set_complex(type, r, i);
7335 // Give an error if we are discarding the value of an expression which
7336 // should not normally be discarded. We don't give an error for
7337 // discarding the value of an ordinary function call, but we do for
7338 // builtin functions, purely for consistency with the gc compiler.
7341 Builtin_call_expression::do_discarding_value()
7343 switch (this->code_)
7345 case BUILTIN_INVALID:
7349 case BUILTIN_APPEND:
7351 case BUILTIN_COMPLEX:
7357 case BUILTIN_ALIGNOF:
7358 case BUILTIN_OFFSETOF:
7359 case BUILTIN_SIZEOF:
7360 this->unused_value_error();
7365 case BUILTIN_DELETE:
7368 case BUILTIN_PRINTLN:
7369 case BUILTIN_RECOVER:
7377 Builtin_call_expression::do_type()
7379 switch (this->code_)
7381 case BUILTIN_INVALID:
7388 const Expression_list* args = this->args();
7389 if (args == NULL || args->empty())
7390 return Type::make_error_type();
7391 return Type::make_pointer_type(args->front()->type());
7397 return Type::lookup_integer_type("int");
7399 case BUILTIN_ALIGNOF:
7400 case BUILTIN_OFFSETOF:
7401 case BUILTIN_SIZEOF:
7402 return Type::lookup_integer_type("uintptr");
7405 case BUILTIN_DELETE:
7408 case BUILTIN_PRINTLN:
7409 return Type::make_void_type();
7411 case BUILTIN_RECOVER:
7412 return Type::make_empty_interface_type(Linemap::predeclared_location());
7414 case BUILTIN_APPEND:
7416 const Expression_list* args = this->args();
7417 if (args == NULL || args->empty())
7418 return Type::make_error_type();
7419 return args->front()->type();
7425 Expression* arg = this->one_arg();
7427 return Type::make_error_type();
7428 Type* t = arg->type();
7429 if (t->is_abstract())
7430 t = t->make_non_abstract_type();
7431 t = Builtin_call_expression::real_imag_type(t);
7433 t = Type::make_error_type();
7437 case BUILTIN_COMPLEX:
7439 const Expression_list* args = this->args();
7440 if (args == NULL || args->size() != 2)
7441 return Type::make_error_type();
7442 Type* t = args->front()->type();
7443 if (t->is_abstract())
7445 t = args->back()->type();
7446 if (t->is_abstract())
7447 t = t->make_non_abstract_type();
7449 t = Builtin_call_expression::complex_type(t);
7451 t = Type::make_error_type();
7457 // Determine the type.
7460 Builtin_call_expression::do_determine_type(const Type_context* context)
7462 if (!this->determining_types())
7465 this->fn()->determine_type_no_context();
7467 const Expression_list* args = this->args();
7470 Type* arg_type = NULL;
7471 switch (this->code_)
7474 case BUILTIN_PRINTLN:
7475 // Do not force a large integer constant to "int".
7481 arg_type = Builtin_call_expression::complex_type(context->type);
7485 case BUILTIN_COMPLEX:
7487 // For the complex function the type of one operand can
7488 // determine the type of the other, as in a binary expression.
7489 arg_type = Builtin_call_expression::real_imag_type(context->type);
7490 if (args != NULL && args->size() == 2)
7492 Type* t1 = args->front()->type();
7493 Type* t2 = args->back()->type();
7494 if (!t1->is_abstract())
7496 else if (!t2->is_abstract())
7510 for (Expression_list::const_iterator pa = args->begin();
7514 Type_context subcontext;
7515 subcontext.type = arg_type;
7519 // We want to print large constants, we so can't just
7520 // use the appropriate nonabstract type. Use uint64 for
7521 // an integer if we know it is nonnegative, otherwise
7522 // use int64 for a integer, otherwise use float64 for a
7523 // float or complex128 for a complex.
7524 Type* want_type = NULL;
7525 Type* atype = (*pa)->type();
7526 if (atype->is_abstract())
7528 if (atype->integer_type() != NULL)
7530 Numeric_constant nc;
7531 if (this->numeric_constant_value(&nc))
7534 if (nc.to_int(&val))
7536 if (mpz_sgn(val) >= 0)
7537 want_type = Type::lookup_integer_type("uint64");
7541 if (want_type == NULL)
7542 want_type = Type::lookup_integer_type("int64");
7544 else if (atype->float_type() != NULL)
7545 want_type = Type::lookup_float_type("float64");
7546 else if (atype->complex_type() != NULL)
7547 want_type = Type::lookup_complex_type("complex128");
7548 else if (atype->is_abstract_string_type())
7549 want_type = Type::lookup_string_type();
7550 else if (atype->is_abstract_boolean_type())
7551 want_type = Type::lookup_bool_type();
7554 subcontext.type = want_type;
7558 (*pa)->determine_type(&subcontext);
7563 // If there is exactly one argument, return true. Otherwise give an
7564 // error message and return false.
7567 Builtin_call_expression::check_one_arg()
7569 const Expression_list* args = this->args();
7570 if (args == NULL || args->size() < 1)
7572 this->report_error(_("not enough arguments"));
7575 else if (args->size() > 1)
7577 this->report_error(_("too many arguments"));
7580 if (args->front()->is_error_expression()
7581 || args->front()->type()->is_error())
7583 this->set_is_error();
7589 // Check argument types for a builtin function.
7592 Builtin_call_expression::do_check_types(Gogo*)
7594 if (this->is_error_expression())
7596 switch (this->code_)
7598 case BUILTIN_INVALID:
7601 case BUILTIN_DELETE:
7607 // The single argument may be either a string or an array or a
7608 // map or a channel, or a pointer to a closed array.
7609 if (this->check_one_arg())
7611 Type* arg_type = this->one_arg()->type();
7612 if (arg_type->points_to() != NULL
7613 && arg_type->points_to()->array_type() != NULL
7614 && !arg_type->points_to()->is_slice_type())
7615 arg_type = arg_type->points_to();
7616 if (this->code_ == BUILTIN_CAP)
7618 if (!arg_type->is_error()
7619 && arg_type->array_type() == NULL
7620 && arg_type->channel_type() == NULL)
7621 this->report_error(_("argument must be array or slice "
7626 if (!arg_type->is_error()
7627 && !arg_type->is_string_type()
7628 && arg_type->array_type() == NULL
7629 && arg_type->map_type() == NULL
7630 && arg_type->channel_type() == NULL)
7631 this->report_error(_("argument must be string or "
7632 "array or slice or map or channel"));
7639 case BUILTIN_PRINTLN:
7641 const Expression_list* args = this->args();
7644 if (this->code_ == BUILTIN_PRINT)
7645 warning_at(this->location(), 0,
7646 "no arguments for builtin function %<%s%>",
7647 (this->code_ == BUILTIN_PRINT
7653 for (Expression_list::const_iterator p = args->begin();
7657 Type* type = (*p)->type();
7658 if (type->is_error()
7659 || type->is_string_type()
7660 || type->integer_type() != NULL
7661 || type->float_type() != NULL
7662 || type->complex_type() != NULL
7663 || type->is_boolean_type()
7664 || type->points_to() != NULL
7665 || type->interface_type() != NULL
7666 || type->channel_type() != NULL
7667 || type->map_type() != NULL
7668 || type->function_type() != NULL
7669 || type->is_slice_type())
7671 else if ((*p)->is_type_expression())
7673 // If this is a type expression it's going to give
7674 // an error anyhow, so we don't need one here.
7677 this->report_error(_("unsupported argument type to "
7678 "builtin function"));
7685 if (this->check_one_arg())
7687 if (this->one_arg()->type()->channel_type() == NULL)
7688 this->report_error(_("argument must be channel"));
7689 else if (!this->one_arg()->type()->channel_type()->may_send())
7690 this->report_error(_("cannot close receive-only channel"));
7695 case BUILTIN_SIZEOF:
7696 case BUILTIN_ALIGNOF:
7697 this->check_one_arg();
7700 case BUILTIN_RECOVER:
7701 if (this->args() != NULL && !this->args()->empty())
7702 this->report_error(_("too many arguments"));
7705 case BUILTIN_OFFSETOF:
7706 if (this->check_one_arg())
7708 Expression* arg = this->one_arg();
7709 if (arg->field_reference_expression() == NULL)
7710 this->report_error(_("argument must be a field reference"));
7716 const Expression_list* args = this->args();
7717 if (args == NULL || args->size() < 2)
7719 this->report_error(_("not enough arguments"));
7722 else if (args->size() > 2)
7724 this->report_error(_("too many arguments"));
7727 Type* arg1_type = args->front()->type();
7728 Type* arg2_type = args->back()->type();
7729 if (arg1_type->is_error() || arg2_type->is_error())
7733 if (arg1_type->is_slice_type())
7734 e1 = arg1_type->array_type()->element_type();
7737 this->report_error(_("left argument must be a slice"));
7741 if (arg2_type->is_slice_type())
7743 Type* e2 = arg2_type->array_type()->element_type();
7744 if (!Type::are_identical(e1, e2, true, NULL))
7745 this->report_error(_("element types must be the same"));
7747 else if (arg2_type->is_string_type())
7749 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7750 this->report_error(_("first argument must be []byte"));
7753 this->report_error(_("second argument must be slice or string"));
7757 case BUILTIN_APPEND:
7759 const Expression_list* args = this->args();
7760 if (args == NULL || args->size() < 2)
7762 this->report_error(_("not enough arguments"));
7765 if (args->size() > 2)
7767 this->report_error(_("too many arguments"));
7770 if (args->front()->type()->is_error()
7771 || args->back()->type()->is_error())
7774 Array_type* at = args->front()->type()->array_type();
7775 Type* e = at->element_type();
7777 // The language permits appending a string to a []byte, as a
7779 if (args->back()->type()->is_string_type())
7781 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7785 // The language says that the second argument must be
7786 // assignable to a slice of the element type of the first
7787 // argument. We already know the first argument is a slice
7789 Type* arg2_type = Type::make_array_type(e, NULL);
7791 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7794 this->report_error(_("argument 2 has invalid type"));
7797 error_at(this->location(), "argument 2 has invalid type (%s)",
7799 this->set_is_error();
7807 if (this->check_one_arg())
7809 if (this->one_arg()->type()->complex_type() == NULL)
7810 this->report_error(_("argument must have complex type"));
7814 case BUILTIN_COMPLEX:
7816 const Expression_list* args = this->args();
7817 if (args == NULL || args->size() < 2)
7818 this->report_error(_("not enough arguments"));
7819 else if (args->size() > 2)
7820 this->report_error(_("too many arguments"));
7821 else if (args->front()->is_error_expression()
7822 || args->front()->type()->is_error()
7823 || args->back()->is_error_expression()
7824 || args->back()->type()->is_error())
7825 this->set_is_error();
7826 else if (!Type::are_identical(args->front()->type(),
7827 args->back()->type(), true, NULL))
7828 this->report_error(_("complex arguments must have identical types"));
7829 else if (args->front()->type()->float_type() == NULL)
7830 this->report_error(_("complex arguments must have "
7831 "floating-point type"));
7840 // Return the tree for a builtin function.
7843 Builtin_call_expression::do_get_tree(Translate_context* context)
7845 Gogo* gogo = context->gogo();
7846 Location location = this->location();
7847 switch (this->code_)
7849 case BUILTIN_INVALID:
7857 const Expression_list* args = this->args();
7858 go_assert(args != NULL && args->size() == 1);
7859 Expression* arg = *args->begin();
7860 Type* arg_type = arg->type();
7864 go_assert(saw_errors());
7865 return error_mark_node;
7869 tree arg_tree = arg->get_tree(context);
7871 this->seen_ = false;
7873 if (arg_tree == error_mark_node)
7874 return error_mark_node;
7876 if (arg_type->points_to() != NULL)
7878 arg_type = arg_type->points_to();
7879 go_assert(arg_type->array_type() != NULL
7880 && !arg_type->is_slice_type());
7881 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7882 arg_tree = build_fold_indirect_ref(arg_tree);
7886 if (this->code_ == BUILTIN_LEN)
7888 if (arg_type->is_string_type())
7889 val_tree = String_type::length_tree(gogo, arg_tree);
7890 else if (arg_type->array_type() != NULL)
7894 go_assert(saw_errors());
7895 return error_mark_node;
7898 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7899 this->seen_ = false;
7901 else if (arg_type->map_type() != NULL)
7903 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7904 static tree map_len_fndecl;
7905 val_tree = Gogo::call_builtin(&map_len_fndecl,
7913 else if (arg_type->channel_type() != NULL)
7915 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7916 static tree chan_len_fndecl;
7917 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7930 if (arg_type->array_type() != NULL)
7934 go_assert(saw_errors());
7935 return error_mark_node;
7938 val_tree = arg_type->array_type()->capacity_tree(gogo,
7940 this->seen_ = false;
7942 else if (arg_type->channel_type() != NULL)
7944 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7945 static tree chan_cap_fndecl;
7946 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7958 if (val_tree == error_mark_node)
7959 return error_mark_node;
7961 Type* int_type = Type::lookup_integer_type("int");
7962 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7963 if (type_tree == TREE_TYPE(val_tree))
7966 return fold(convert_to_integer(type_tree, val_tree));
7970 case BUILTIN_PRINTLN:
7972 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7973 tree stmt_list = NULL_TREE;
7975 const Expression_list* call_args = this->args();
7976 if (call_args != NULL)
7978 for (Expression_list::const_iterator p = call_args->begin();
7979 p != call_args->end();
7982 if (is_ln && p != call_args->begin())
7984 static tree print_space_fndecl;
7985 tree call = Gogo::call_builtin(&print_space_fndecl,
7990 if (call == error_mark_node)
7991 return error_mark_node;
7992 append_to_statement_list(call, &stmt_list);
7995 Type* type = (*p)->type();
7997 tree arg = (*p)->get_tree(context);
7998 if (arg == error_mark_node)
7999 return error_mark_node;
8003 if (type->is_string_type())
8005 static tree print_string_fndecl;
8006 pfndecl = &print_string_fndecl;
8007 fnname = "__go_print_string";
8009 else if (type->integer_type() != NULL
8010 && type->integer_type()->is_unsigned())
8012 static tree print_uint64_fndecl;
8013 pfndecl = &print_uint64_fndecl;
8014 fnname = "__go_print_uint64";
8015 Type* itype = Type::lookup_integer_type("uint64");
8016 Btype* bitype = itype->get_backend(gogo);
8017 arg = fold_convert_loc(location.gcc_location(),
8018 type_to_tree(bitype), arg);
8020 else if (type->integer_type() != NULL)
8022 static tree print_int64_fndecl;
8023 pfndecl = &print_int64_fndecl;
8024 fnname = "__go_print_int64";
8025 Type* itype = Type::lookup_integer_type("int64");
8026 Btype* bitype = itype->get_backend(gogo);
8027 arg = fold_convert_loc(location.gcc_location(),
8028 type_to_tree(bitype), arg);
8030 else if (type->float_type() != NULL)
8032 static tree print_double_fndecl;
8033 pfndecl = &print_double_fndecl;
8034 fnname = "__go_print_double";
8035 arg = fold_convert_loc(location.gcc_location(),
8036 double_type_node, arg);
8038 else if (type->complex_type() != NULL)
8040 static tree print_complex_fndecl;
8041 pfndecl = &print_complex_fndecl;
8042 fnname = "__go_print_complex";
8043 arg = fold_convert_loc(location.gcc_location(),
8044 complex_double_type_node, arg);
8046 else if (type->is_boolean_type())
8048 static tree print_bool_fndecl;
8049 pfndecl = &print_bool_fndecl;
8050 fnname = "__go_print_bool";
8052 else if (type->points_to() != NULL
8053 || type->channel_type() != NULL
8054 || type->map_type() != NULL
8055 || type->function_type() != NULL)
8057 static tree print_pointer_fndecl;
8058 pfndecl = &print_pointer_fndecl;
8059 fnname = "__go_print_pointer";
8060 arg = fold_convert_loc(location.gcc_location(),
8061 ptr_type_node, arg);
8063 else if (type->interface_type() != NULL)
8065 if (type->interface_type()->is_empty())
8067 static tree print_empty_interface_fndecl;
8068 pfndecl = &print_empty_interface_fndecl;
8069 fnname = "__go_print_empty_interface";
8073 static tree print_interface_fndecl;
8074 pfndecl = &print_interface_fndecl;
8075 fnname = "__go_print_interface";
8078 else if (type->is_slice_type())
8080 static tree print_slice_fndecl;
8081 pfndecl = &print_slice_fndecl;
8082 fnname = "__go_print_slice";
8086 go_assert(saw_errors());
8087 return error_mark_node;
8090 tree call = Gogo::call_builtin(pfndecl,
8097 if (call == error_mark_node)
8098 return error_mark_node;
8099 append_to_statement_list(call, &stmt_list);
8105 static tree print_nl_fndecl;
8106 tree call = Gogo::call_builtin(&print_nl_fndecl,
8111 if (call == error_mark_node)
8112 return error_mark_node;
8113 append_to_statement_list(call, &stmt_list);
8121 const Expression_list* args = this->args();
8122 go_assert(args != NULL && args->size() == 1);
8123 Expression* arg = args->front();
8124 tree arg_tree = arg->get_tree(context);
8125 if (arg_tree == error_mark_node)
8126 return error_mark_node;
8128 Type::make_empty_interface_type(Linemap::predeclared_location());
8129 arg_tree = Expression::convert_for_assignment(context, empty,
8131 arg_tree, location);
8132 static tree panic_fndecl;
8133 tree call = Gogo::call_builtin(&panic_fndecl,
8138 TREE_TYPE(arg_tree),
8140 if (call == error_mark_node)
8141 return error_mark_node;
8142 // This function will throw an exception.
8143 TREE_NOTHROW(panic_fndecl) = 0;
8144 // This function will not return.
8145 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8149 case BUILTIN_RECOVER:
8151 // The argument is set when building recover thunks. It's a
8152 // boolean value which is true if we can recover a value now.
8153 const Expression_list* args = this->args();
8154 go_assert(args != NULL && args->size() == 1);
8155 Expression* arg = args->front();
8156 tree arg_tree = arg->get_tree(context);
8157 if (arg_tree == error_mark_node)
8158 return error_mark_node;
8161 Type::make_empty_interface_type(Linemap::predeclared_location());
8162 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8164 Type* nil_type = Type::make_nil_type();
8165 Expression* nil = Expression::make_nil(location);
8166 tree nil_tree = nil->get_tree(context);
8167 tree empty_nil_tree = Expression::convert_for_assignment(context,
8173 // We need to handle a deferred call to recover specially,
8174 // because it changes whether it can recover a panic or not.
8175 // See test7 in test/recover1.go.
8177 if (this->is_deferred())
8179 static tree deferred_recover_fndecl;
8180 call = Gogo::call_builtin(&deferred_recover_fndecl,
8182 "__go_deferred_recover",
8188 static tree recover_fndecl;
8189 call = Gogo::call_builtin(&recover_fndecl,
8195 if (call == error_mark_node)
8196 return error_mark_node;
8197 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8198 arg_tree, call, empty_nil_tree);
8203 const Expression_list* args = this->args();
8204 go_assert(args != NULL && args->size() == 1);
8205 Expression* arg = args->front();
8206 tree arg_tree = arg->get_tree(context);
8207 if (arg_tree == error_mark_node)
8208 return error_mark_node;
8209 static tree close_fndecl;
8210 return Gogo::call_builtin(&close_fndecl,
8212 "__go_builtin_close",
8215 TREE_TYPE(arg_tree),
8219 case BUILTIN_SIZEOF:
8220 case BUILTIN_OFFSETOF:
8221 case BUILTIN_ALIGNOF:
8223 Numeric_constant nc;
8225 if (!this->numeric_constant_value(&nc)
8226 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8228 go_assert(saw_errors());
8229 return error_mark_node;
8231 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8232 tree type = type_to_tree(uintptr_type->get_backend(gogo));
8233 return build_int_cst(type, val);
8238 const Expression_list* args = this->args();
8239 go_assert(args != NULL && args->size() == 2);
8240 Expression* arg1 = args->front();
8241 Expression* arg2 = args->back();
8243 tree arg1_tree = arg1->get_tree(context);
8244 tree arg2_tree = arg2->get_tree(context);
8245 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8246 return error_mark_node;
8248 Type* arg1_type = arg1->type();
8249 Array_type* at = arg1_type->array_type();
8250 arg1_tree = save_expr(arg1_tree);
8251 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8252 tree arg1_len = at->length_tree(gogo, arg1_tree);
8253 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8254 return error_mark_node;
8256 Type* arg2_type = arg2->type();
8259 if (arg2_type->is_slice_type())
8261 at = arg2_type->array_type();
8262 arg2_tree = save_expr(arg2_tree);
8263 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8264 arg2_len = at->length_tree(gogo, arg2_tree);
8268 arg2_tree = save_expr(arg2_tree);
8269 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8270 arg2_len = String_type::length_tree(gogo, arg2_tree);
8272 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8273 return error_mark_node;
8275 arg1_len = save_expr(arg1_len);
8276 arg2_len = save_expr(arg2_len);
8277 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8278 TREE_TYPE(arg1_len),
8279 fold_build2_loc(location.gcc_location(),
8280 LT_EXPR, boolean_type_node,
8281 arg1_len, arg2_len),
8282 arg1_len, arg2_len);
8283 len = save_expr(len);
8285 Type* element_type = at->element_type();
8286 Btype* element_btype = element_type->get_backend(gogo);
8287 tree element_type_tree = type_to_tree(element_btype);
8288 if (element_type_tree == error_mark_node)
8289 return error_mark_node;
8290 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8291 tree bytecount = fold_convert_loc(location.gcc_location(),
8292 TREE_TYPE(element_size), len);
8293 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8294 TREE_TYPE(element_size),
8295 bytecount, element_size);
8296 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8299 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8301 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8304 static tree copy_fndecl;
8305 tree call = Gogo::call_builtin(©_fndecl,
8316 if (call == error_mark_node)
8317 return error_mark_node;
8319 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8320 TREE_TYPE(len), call, len);
8323 case BUILTIN_APPEND:
8325 const Expression_list* args = this->args();
8326 go_assert(args != NULL && args->size() == 2);
8327 Expression* arg1 = args->front();
8328 Expression* arg2 = args->back();
8330 tree arg1_tree = arg1->get_tree(context);
8331 tree arg2_tree = arg2->get_tree(context);
8332 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8333 return error_mark_node;
8335 Array_type* at = arg1->type()->array_type();
8336 Type* element_type = at->element_type()->forwarded();
8341 if (arg2->type()->is_string_type()
8342 && element_type->integer_type() != NULL
8343 && element_type->integer_type()->is_byte())
8345 arg2_tree = save_expr(arg2_tree);
8346 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8347 arg2_len = String_type::length_tree(gogo, arg2_tree);
8348 element_size = size_int(1);
8352 arg2_tree = Expression::convert_for_assignment(context, at,
8356 if (arg2_tree == error_mark_node)
8357 return error_mark_node;
8359 arg2_tree = save_expr(arg2_tree);
8361 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8362 arg2_len = at->length_tree(gogo, arg2_tree);
8364 Btype* element_btype = element_type->get_backend(gogo);
8365 tree element_type_tree = type_to_tree(element_btype);
8366 if (element_type_tree == error_mark_node)
8367 return error_mark_node;
8368 element_size = TYPE_SIZE_UNIT(element_type_tree);
8371 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8373 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8375 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8378 if (arg2_val == error_mark_node
8379 || arg2_len == error_mark_node
8380 || element_size == error_mark_node)
8381 return error_mark_node;
8383 // We rebuild the decl each time since the slice types may
8385 tree append_fndecl = NULL_TREE;
8386 return Gogo::call_builtin(&append_fndecl,
8390 TREE_TYPE(arg1_tree),
8391 TREE_TYPE(arg1_tree),
8404 const Expression_list* args = this->args();
8405 go_assert(args != NULL && args->size() == 1);
8406 Expression* arg = args->front();
8407 tree arg_tree = arg->get_tree(context);
8408 if (arg_tree == error_mark_node)
8409 return error_mark_node;
8410 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8411 if (this->code_ == BUILTIN_REAL)
8412 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8413 TREE_TYPE(TREE_TYPE(arg_tree)),
8416 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8417 TREE_TYPE(TREE_TYPE(arg_tree)),
8421 case BUILTIN_COMPLEX:
8423 const Expression_list* args = this->args();
8424 go_assert(args != NULL && args->size() == 2);
8425 tree r = args->front()->get_tree(context);
8426 tree i = args->back()->get_tree(context);
8427 if (r == error_mark_node || i == error_mark_node)
8428 return error_mark_node;
8429 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8430 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8431 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8432 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8433 build_complex_type(TREE_TYPE(r)),
8442 // We have to support exporting a builtin call expression, because
8443 // code can set a constant to the result of a builtin expression.
8446 Builtin_call_expression::do_export(Export* exp) const
8448 Numeric_constant nc;
8449 if (!this->numeric_constant_value(&nc))
8451 error_at(this->location(), "value is not constant");
8459 Integer_expression::export_integer(exp, val);
8462 else if (nc.is_float())
8465 nc.get_float(&fval);
8466 Float_expression::export_float(exp, fval);
8469 else if (nc.is_complex())
8473 Complex_expression::export_complex(exp, real, imag);
8480 // A trailing space lets us reliably identify the end of the number.
8481 exp->write_c_string(" ");
8484 // Class Call_expression.
8489 Call_expression::do_traverse(Traverse* traverse)
8491 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8492 return TRAVERSE_EXIT;
8493 if (this->args_ != NULL)
8495 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8496 return TRAVERSE_EXIT;
8498 return TRAVERSE_CONTINUE;
8501 // Lower a call statement.
8504 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8505 Statement_inserter* inserter, int)
8507 Location loc = this->location();
8509 // A type cast can look like a function call.
8510 if (this->fn_->is_type_expression()
8511 && this->args_ != NULL
8512 && this->args_->size() == 1)
8513 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8516 // Because do_type will return an error type and thus prevent future
8517 // errors, check for that case now to ensure that the error gets
8519 if (this->get_function_type() == NULL)
8521 if (!this->fn_->type()->is_error())
8522 this->report_error(_("expected function"));
8523 return Expression::make_error(loc);
8526 // Recognize a call to a builtin function.
8527 Func_expression* fne = this->fn_->func_expression();
8529 && fne->named_object()->is_function_declaration()
8530 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8531 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8532 this->is_varargs_, loc);
8534 // Handle an argument which is a call to a function which returns
8535 // multiple results.
8536 if (this->args_ != NULL
8537 && this->args_->size() == 1
8538 && this->args_->front()->call_expression() != NULL
8539 && this->fn_->type()->function_type() != NULL)
8541 Function_type* fntype = this->fn_->type()->function_type();
8542 size_t rc = this->args_->front()->call_expression()->result_count();
8544 && fntype->parameters() != NULL
8545 && (fntype->parameters()->size() == rc
8546 || (fntype->is_varargs()
8547 && fntype->parameters()->size() - 1 <= rc)))
8549 Call_expression* call = this->args_->front()->call_expression();
8550 Expression_list* args = new Expression_list;
8551 for (size_t i = 0; i < rc; ++i)
8552 args->push_back(Expression::make_call_result(call, i));
8553 // We can't return a new call expression here, because this
8554 // one may be referenced by Call_result expressions. We
8555 // also can't delete the old arguments, because we may still
8556 // traverse them somewhere up the call stack. FIXME.
8561 // If this call returns multiple results, create a temporary
8562 // variable for each result.
8563 size_t rc = this->result_count();
8564 if (rc > 1 && this->results_ == NULL)
8566 std::vector<Temporary_statement*>* temps =
8567 new std::vector<Temporary_statement*>;
8569 const Typed_identifier_list* results =
8570 this->fn_->type()->function_type()->results();
8571 for (Typed_identifier_list::const_iterator p = results->begin();
8572 p != results->end();
8575 Temporary_statement* temp = Statement::make_temporary(p->type(),
8577 inserter->insert(temp);
8578 temps->push_back(temp);
8580 this->results_ = temps;
8583 // Handle a call to a varargs function by packaging up the extra
8585 if (this->fn_->type()->function_type() != NULL
8586 && this->fn_->type()->function_type()->is_varargs())
8588 Function_type* fntype = this->fn_->type()->function_type();
8589 const Typed_identifier_list* parameters = fntype->parameters();
8590 go_assert(parameters != NULL && !parameters->empty());
8591 Type* varargs_type = parameters->back().type();
8592 this->lower_varargs(gogo, function, inserter, varargs_type,
8593 parameters->size());
8596 // If this is call to a method, call the method directly passing the
8597 // object as the first parameter.
8598 Bound_method_expression* bme = this->fn_->bound_method_expression();
8601 Named_object* method = bme->method();
8602 Expression* first_arg = bme->first_argument();
8604 // We always pass a pointer when calling a method.
8605 if (first_arg->type()->points_to() == NULL
8606 && !first_arg->type()->is_error())
8608 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8609 // We may need to create a temporary variable so that we can
8610 // take the address. We can't do that here because it will
8611 // mess up the order of evaluation.
8612 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8613 ue->set_create_temp();
8616 // If we are calling a method which was inherited from an
8617 // embedded struct, and the method did not get a stub, then the
8618 // first type may be wrong.
8619 Type* fatype = bme->first_argument_type();
8622 if (fatype->points_to() == NULL)
8623 fatype = Type::make_pointer_type(fatype);
8624 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8627 Expression_list* new_args = new Expression_list();
8628 new_args->push_back(first_arg);
8629 if (this->args_ != NULL)
8631 for (Expression_list::const_iterator p = this->args_->begin();
8632 p != this->args_->end();
8634 new_args->push_back(*p);
8637 // We have to change in place because this structure may be
8638 // referenced by Call_result_expressions. We can't delete the
8639 // old arguments, because we may be traversing them up in some
8641 this->args_ = new_args;
8642 this->fn_ = Expression::make_func_reference(method, NULL,
8649 // Lower a call to a varargs function. FUNCTION is the function in
8650 // which the call occurs--it's not the function we are calling.
8651 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8652 // PARAM_COUNT is the number of parameters of the function we are
8653 // calling; the last of these parameters will be the varargs
8657 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8658 Statement_inserter* inserter,
8659 Type* varargs_type, size_t param_count)
8661 if (this->varargs_are_lowered_)
8664 Location loc = this->location();
8666 go_assert(param_count > 0);
8667 go_assert(varargs_type->is_slice_type());
8669 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8670 if (arg_count < param_count - 1)
8672 // Not enough arguments; will be caught in check_types.
8676 Expression_list* old_args = this->args_;
8677 Expression_list* new_args = new Expression_list();
8678 bool push_empty_arg = false;
8679 if (old_args == NULL || old_args->empty())
8681 go_assert(param_count == 1);
8682 push_empty_arg = true;
8686 Expression_list::const_iterator pa;
8688 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8690 if (static_cast<size_t>(i) == param_count)
8692 new_args->push_back(*pa);
8695 // We have reached the varargs parameter.
8697 bool issued_error = false;
8698 if (pa == old_args->end())
8699 push_empty_arg = true;
8700 else if (pa + 1 == old_args->end() && this->is_varargs_)
8701 new_args->push_back(*pa);
8702 else if (this->is_varargs_)
8704 if ((*pa)->type()->is_slice_type())
8705 this->report_error(_("too many arguments"));
8708 error_at(this->location(),
8709 _("invalid use of %<...%> with non-slice"));
8710 this->set_is_error();
8716 Type* element_type = varargs_type->array_type()->element_type();
8717 Expression_list* vals = new Expression_list;
8718 for (; pa != old_args->end(); ++pa, ++i)
8720 // Check types here so that we get a better message.
8721 Type* patype = (*pa)->type();
8722 Location paloc = (*pa)->location();
8723 if (!this->check_argument_type(i, element_type, patype,
8724 paloc, issued_error))
8726 vals->push_back(*pa);
8729 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8730 gogo->lower_expression(function, inserter, &val);
8731 new_args->push_back(val);
8736 new_args->push_back(Expression::make_nil(loc));
8738 // We can't return a new call expression here, because this one may
8739 // be referenced by Call_result expressions. FIXME. We can't
8740 // delete OLD_ARGS because we may have both a Call_expression and a
8741 // Builtin_call_expression which refer to them. FIXME.
8742 this->args_ = new_args;
8743 this->varargs_are_lowered_ = true;
8746 // Get the function type. This can return NULL in error cases.
8749 Call_expression::get_function_type() const
8751 return this->fn_->type()->function_type();
8754 // Return the number of values which this call will return.
8757 Call_expression::result_count() const
8759 const Function_type* fntype = this->get_function_type();
8762 if (fntype->results() == NULL)
8764 return fntype->results()->size();
8767 // Return the temporary which holds a result.
8769 Temporary_statement*
8770 Call_expression::result(size_t i) const
8772 if (this->results_ == NULL || this->results_->size() <= i)
8774 go_assert(saw_errors());
8777 return (*this->results_)[i];
8780 // Return whether this is a call to the predeclared function recover.
8783 Call_expression::is_recover_call() const
8785 return this->do_is_recover_call();
8788 // Set the argument to the recover function.
8791 Call_expression::set_recover_arg(Expression* arg)
8793 this->do_set_recover_arg(arg);
8796 // Virtual functions also implemented by Builtin_call_expression.
8799 Call_expression::do_is_recover_call() const
8805 Call_expression::do_set_recover_arg(Expression*)
8810 // We have found an error with this call expression; return true if
8811 // we should report it.
8814 Call_expression::issue_error()
8816 if (this->issued_error_)
8820 this->issued_error_ = true;
8828 Call_expression::do_type()
8830 if (this->type_ != NULL)
8834 Function_type* fntype = this->get_function_type();
8836 return Type::make_error_type();
8838 const Typed_identifier_list* results = fntype->results();
8839 if (results == NULL)
8840 ret = Type::make_void_type();
8841 else if (results->size() == 1)
8842 ret = results->begin()->type();
8844 ret = Type::make_call_multiple_result_type(this);
8851 // Determine types for a call expression. We can use the function
8852 // parameter types to set the types of the arguments.
8855 Call_expression::do_determine_type(const Type_context*)
8857 if (!this->determining_types())
8860 this->fn_->determine_type_no_context();
8861 Function_type* fntype = this->get_function_type();
8862 const Typed_identifier_list* parameters = NULL;
8864 parameters = fntype->parameters();
8865 if (this->args_ != NULL)
8867 Typed_identifier_list::const_iterator pt;
8868 if (parameters != NULL)
8869 pt = parameters->begin();
8871 for (Expression_list::const_iterator pa = this->args_->begin();
8872 pa != this->args_->end();
8878 // If this is a method, the first argument is the
8880 if (fntype != NULL && fntype->is_method())
8882 Type* rtype = fntype->receiver()->type();
8883 // The receiver is always passed as a pointer.
8884 if (rtype->points_to() == NULL)
8885 rtype = Type::make_pointer_type(rtype);
8886 Type_context subcontext(rtype, false);
8887 (*pa)->determine_type(&subcontext);
8892 if (parameters != NULL && pt != parameters->end())
8894 Type_context subcontext(pt->type(), false);
8895 (*pa)->determine_type(&subcontext);
8899 (*pa)->determine_type_no_context();
8904 // Called when determining types for a Call_expression. Return true
8905 // if we should go ahead, false if they have already been determined.
8908 Call_expression::determining_types()
8910 if (this->types_are_determined_)
8914 this->types_are_determined_ = true;
8919 // Check types for parameter I.
8922 Call_expression::check_argument_type(int i, const Type* parameter_type,
8923 const Type* argument_type,
8924 Location argument_location,
8929 if (this->are_hidden_fields_ok_)
8930 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8933 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8939 error_at(argument_location, "argument %d has incompatible type", i);
8941 error_at(argument_location,
8942 "argument %d has incompatible type (%s)",
8945 this->set_is_error();
8954 Call_expression::do_check_types(Gogo*)
8956 if (this->classification() == EXPRESSION_ERROR)
8959 Function_type* fntype = this->get_function_type();
8962 if (!this->fn_->type()->is_error())
8963 this->report_error(_("expected function"));
8967 bool is_method = fntype->is_method();
8970 go_assert(this->args_ != NULL && !this->args_->empty());
8971 Type* rtype = fntype->receiver()->type();
8972 Expression* first_arg = this->args_->front();
8973 // The language permits copying hidden fields for a method
8974 // receiver. We dereference the values since receivers are
8975 // always passed as pointers.
8977 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8978 first_arg->type()->deref(),
8982 this->report_error(_("incompatible type for receiver"));
8985 error_at(this->location(),
8986 "incompatible type for receiver (%s)",
8988 this->set_is_error();
8993 // Note that varargs was handled by the lower_varargs() method, so
8994 // we don't have to worry about it here unless something is wrong.
8995 if (this->is_varargs_ && !this->varargs_are_lowered_)
8997 if (!fntype->is_varargs())
8999 error_at(this->location(),
9000 _("invalid use of %<...%> calling non-variadic function"));
9001 this->set_is_error();
9006 const Typed_identifier_list* parameters = fntype->parameters();
9007 if (this->args_ == NULL)
9009 if (parameters != NULL && !parameters->empty())
9010 this->report_error(_("not enough arguments"));
9012 else if (parameters == NULL)
9014 if (!is_method || this->args_->size() > 1)
9015 this->report_error(_("too many arguments"));
9020 Expression_list::const_iterator pa = this->args_->begin();
9023 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9024 pt != parameters->end();
9027 if (pa == this->args_->end())
9029 this->report_error(_("not enough arguments"));
9032 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9033 (*pa)->location(), false);
9035 if (pa != this->args_->end())
9036 this->report_error(_("too many arguments"));
9040 // Return whether we have to use a temporary variable to ensure that
9041 // we evaluate this call expression in order. If the call returns no
9042 // results then it will inevitably be executed last.
9045 Call_expression::do_must_eval_in_order() const
9047 return this->result_count() > 0;
9050 // Get the function and the first argument to use when calling an
9051 // interface method.
9054 Call_expression::interface_method_function(
9055 Translate_context* context,
9056 Interface_field_reference_expression* interface_method,
9057 tree* first_arg_ptr)
9059 tree expr = interface_method->expr()->get_tree(context);
9060 if (expr == error_mark_node)
9061 return error_mark_node;
9062 expr = save_expr(expr);
9063 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9064 if (first_arg == error_mark_node)
9065 return error_mark_node;
9066 *first_arg_ptr = first_arg;
9067 return interface_method->get_function_tree(context, expr);
9070 // Build the call expression.
9073 Call_expression::do_get_tree(Translate_context* context)
9075 if (this->tree_ != NULL_TREE)
9078 Function_type* fntype = this->get_function_type();
9080 return error_mark_node;
9082 if (this->fn_->is_error_expression())
9083 return error_mark_node;
9085 Gogo* gogo = context->gogo();
9086 Location location = this->location();
9088 Func_expression* func = this->fn_->func_expression();
9089 Interface_field_reference_expression* interface_method =
9090 this->fn_->interface_field_reference_expression();
9091 const bool has_closure = func != NULL && func->closure() != NULL;
9092 const bool is_interface_method = interface_method != NULL;
9096 if (this->args_ == NULL || this->args_->empty())
9098 nargs = is_interface_method ? 1 : 0;
9099 args = nargs == 0 ? NULL : new tree[nargs];
9101 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9103 // Passing a receiver parameter.
9104 go_assert(!is_interface_method
9105 && fntype->is_method()
9106 && this->args_->size() == 1);
9108 args = new tree[nargs];
9109 args[0] = this->args_->front()->get_tree(context);
9113 const Typed_identifier_list* params = fntype->parameters();
9115 nargs = this->args_->size();
9116 int i = is_interface_method ? 1 : 0;
9118 args = new tree[nargs];
9120 Typed_identifier_list::const_iterator pp = params->begin();
9121 Expression_list::const_iterator pe = this->args_->begin();
9122 if (!is_interface_method && fntype->is_method())
9124 args[i] = (*pe)->get_tree(context);
9128 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9130 go_assert(pp != params->end());
9131 tree arg_val = (*pe)->get_tree(context);
9132 args[i] = Expression::convert_for_assignment(context,
9137 if (args[i] == error_mark_node)
9140 return error_mark_node;
9143 go_assert(pp == params->end());
9144 go_assert(i == nargs);
9147 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
9148 if (rettype == error_mark_node)
9151 return error_mark_node;
9156 fn = func->get_tree_without_closure(gogo);
9157 else if (!is_interface_method)
9158 fn = this->fn_->get_tree(context);
9160 fn = this->interface_method_function(context, interface_method, &args[0]);
9162 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9165 return error_mark_node;
9169 if (TREE_CODE(fndecl) == ADDR_EXPR)
9170 fndecl = TREE_OPERAND(fndecl, 0);
9172 // Add a type cast in case the type of the function is a recursive
9173 // type which refers to itself.
9174 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9176 tree fnt = type_to_tree(fntype->get_backend(gogo));
9177 if (fnt == error_mark_node)
9178 return error_mark_node;
9179 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9182 // This is to support builtin math functions when using 80387 math.
9183 tree excess_type = NULL_TREE;
9185 && TREE_CODE(fndecl) == FUNCTION_DECL
9186 && DECL_IS_BUILTIN(fndecl)
9187 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9189 && ((SCALAR_FLOAT_TYPE_P(rettype)
9190 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9191 || (COMPLEX_FLOAT_TYPE_P(rettype)
9192 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9194 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9195 if (excess_type != NULL_TREE)
9197 tree excess_fndecl = mathfn_built_in(excess_type,
9198 DECL_FUNCTION_CODE(fndecl));
9199 if (excess_fndecl == NULL_TREE)
9200 excess_type = NULL_TREE;
9203 fn = build_fold_addr_expr_loc(location.gcc_location(),
9205 for (int i = 0; i < nargs; ++i)
9207 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9208 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9209 args[i] = ::convert(excess_type, args[i]);
9218 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9222 SET_EXPR_LOCATION(ret, location.gcc_location());
9226 tree closure_tree = func->closure()->get_tree(context);
9227 if (closure_tree != error_mark_node)
9228 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9231 // If this is a recursive function type which returns itself, as in
9233 // we have used ptr_type_node for the return type. Add a cast here
9234 // to the correct type.
9235 if (TREE_TYPE(ret) == ptr_type_node)
9237 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9238 ret = fold_convert_loc(location.gcc_location(), t, ret);
9241 if (excess_type != NULL_TREE)
9243 // Calling convert here can undo our excess precision change.
9244 // That may or may not be a bug in convert_to_real.
9245 ret = build1(NOP_EXPR, rettype, ret);
9248 if (this->results_ != NULL)
9249 ret = this->set_results(context, ret);
9251 // We can't unwind the stack past a call to nil, so we need to
9252 // insert an explicit check so that the panic can be recovered.
9255 tree compare = fold_build2_loc(location.gcc_location(), EQ_EXPR,
9256 boolean_type_node, fn,
9257 fold_convert_loc(location.gcc_location(),
9259 null_pointer_node));
9260 tree crash = build3_loc(location.gcc_location(), COND_EXPR,
9261 void_type_node, compare,
9262 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
9265 ret = fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
9266 TREE_TYPE(ret), crash, ret);
9274 // Set the result variables if this call returns multiple results.
9277 Call_expression::set_results(Translate_context* context, tree call_tree)
9279 tree stmt_list = NULL_TREE;
9281 call_tree = save_expr(call_tree);
9283 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9285 go_assert(saw_errors());
9289 Location loc = this->location();
9290 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9291 size_t rc = this->result_count();
9292 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9294 go_assert(field != NULL_TREE);
9296 Temporary_statement* temp = this->result(i);
9299 go_assert(saw_errors());
9300 return error_mark_node;
9302 Temporary_reference_expression* ref =
9303 Expression::make_temporary_reference(temp, loc);
9304 ref->set_is_lvalue();
9305 tree temp_tree = ref->get_tree(context);
9306 if (temp_tree == error_mark_node)
9307 return error_mark_node;
9309 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9310 TREE_TYPE(field), call_tree, field, NULL_TREE);
9311 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9312 void_type_node, temp_tree, val_tree);
9314 append_to_statement_list(set_tree, &stmt_list);
9316 go_assert(field == NULL_TREE);
9318 return save_expr(stmt_list);
9321 // Dump ast representation for a call expressin.
9324 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9326 this->fn_->dump_expression(ast_dump_context);
9327 ast_dump_context->ostream() << "(";
9329 ast_dump_context->dump_expression_list(this->args_);
9331 ast_dump_context->ostream() << ") ";
9334 // Make a call expression.
9337 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9340 return new Call_expression(fn, args, is_varargs, location);
9343 // A single result from a call which returns multiple results.
9345 class Call_result_expression : public Expression
9348 Call_result_expression(Call_expression* call, unsigned int index)
9349 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9350 call_(call), index_(index)
9355 do_traverse(Traverse*);
9361 do_determine_type(const Type_context*);
9364 do_check_types(Gogo*);
9369 return new Call_result_expression(this->call_->call_expression(),
9374 do_must_eval_in_order() const
9378 do_get_tree(Translate_context*);
9381 do_dump_expression(Ast_dump_context*) const;
9384 // The underlying call expression.
9386 // Which result we want.
9387 unsigned int index_;
9390 // Traverse a call result.
9393 Call_result_expression::do_traverse(Traverse* traverse)
9395 if (traverse->remember_expression(this->call_))
9397 // We have already traversed the call expression.
9398 return TRAVERSE_CONTINUE;
9400 return Expression::traverse(&this->call_, traverse);
9406 Call_result_expression::do_type()
9408 if (this->classification() == EXPRESSION_ERROR)
9409 return Type::make_error_type();
9411 // THIS->CALL_ can be replaced with a temporary reference due to
9412 // Call_expression::do_must_eval_in_order when there is an error.
9413 Call_expression* ce = this->call_->call_expression();
9416 this->set_is_error();
9417 return Type::make_error_type();
9419 Function_type* fntype = ce->get_function_type();
9422 if (ce->issue_error())
9424 if (!ce->fn()->type()->is_error())
9425 this->report_error(_("expected function"));
9427 this->set_is_error();
9428 return Type::make_error_type();
9430 const Typed_identifier_list* results = fntype->results();
9431 if (results == NULL || results->size() < 2)
9433 if (ce->issue_error())
9434 this->report_error(_("number of results does not match "
9435 "number of values"));
9436 return Type::make_error_type();
9438 Typed_identifier_list::const_iterator pr = results->begin();
9439 for (unsigned int i = 0; i < this->index_; ++i)
9441 if (pr == results->end())
9445 if (pr == results->end())
9447 if (ce->issue_error())
9448 this->report_error(_("number of results does not match "
9449 "number of values"));
9450 return Type::make_error_type();
9455 // Check the type. Just make sure that we trigger the warning in
9459 Call_result_expression::do_check_types(Gogo*)
9464 // Determine the type. We have nothing to do here, but the 0 result
9465 // needs to pass down to the caller.
9468 Call_result_expression::do_determine_type(const Type_context*)
9470 this->call_->determine_type_no_context();
9473 // Return the tree. We just refer to the temporary set by the call
9474 // expression. We don't do this at lowering time because it makes it
9475 // hard to evaluate the call at the right time.
9478 Call_result_expression::do_get_tree(Translate_context* context)
9480 Call_expression* ce = this->call_->call_expression();
9483 go_assert(this->call_->is_error_expression());
9484 return error_mark_node;
9486 Temporary_statement* ts = ce->result(this->index_);
9489 go_assert(saw_errors());
9490 return error_mark_node;
9492 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9493 return ref->get_tree(context);
9496 // Dump ast representation for a call result expression.
9499 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9502 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9503 // (struct) and the fields are referenced instead.
9504 ast_dump_context->ostream() << this->index_ << "@(";
9505 ast_dump_context->dump_expression(this->call_);
9506 ast_dump_context->ostream() << ")";
9509 // Make a reference to a single result of a call which returns
9510 // multiple results.
9513 Expression::make_call_result(Call_expression* call, unsigned int index)
9515 return new Call_result_expression(call, index);
9518 // Class Index_expression.
9523 Index_expression::do_traverse(Traverse* traverse)
9525 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9526 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9527 || (this->end_ != NULL
9528 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9529 return TRAVERSE_EXIT;
9530 return TRAVERSE_CONTINUE;
9533 // Lower an index expression. This converts the generic index
9534 // expression into an array index, a string index, or a map index.
9537 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9539 Location location = this->location();
9540 Expression* left = this->left_;
9541 Expression* start = this->start_;
9542 Expression* end = this->end_;
9544 Type* type = left->type();
9545 if (type->is_error())
9546 return Expression::make_error(location);
9547 else if (left->is_type_expression())
9549 error_at(location, "attempt to index type expression");
9550 return Expression::make_error(location);
9552 else if (type->array_type() != NULL)
9553 return Expression::make_array_index(left, start, end, location);
9554 else if (type->points_to() != NULL
9555 && type->points_to()->array_type() != NULL
9556 && !type->points_to()->is_slice_type())
9558 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9560 return Expression::make_array_index(deref, start, end, location);
9562 else if (type->is_string_type())
9563 return Expression::make_string_index(left, start, end, location);
9564 else if (type->map_type() != NULL)
9568 error_at(location, "invalid slice of map");
9569 return Expression::make_error(location);
9571 Map_index_expression* ret = Expression::make_map_index(left, start,
9573 if (this->is_lvalue_)
9574 ret->set_is_lvalue();
9580 "attempt to index object which is not array, string, or map");
9581 return Expression::make_error(location);
9585 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9589 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9590 const Expression* expr,
9591 const Expression* start,
9592 const Expression* end)
9594 expr->dump_expression(ast_dump_context);
9595 ast_dump_context->ostream() << "[";
9596 start->dump_expression(ast_dump_context);
9599 ast_dump_context->ostream() << ":";
9600 end->dump_expression(ast_dump_context);
9602 ast_dump_context->ostream() << "]";
9605 // Dump ast representation for an index expression.
9608 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9611 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9612 this->start_, this->end_);
9615 // Make an index expression.
9618 Expression::make_index(Expression* left, Expression* start, Expression* end,
9621 return new Index_expression(left, start, end, location);
9624 // An array index. This is used for both indexing and slicing.
9626 class Array_index_expression : public Expression
9629 Array_index_expression(Expression* array, Expression* start,
9630 Expression* end, Location location)
9631 : Expression(EXPRESSION_ARRAY_INDEX, location),
9632 array_(array), start_(start), end_(end), type_(NULL)
9637 do_traverse(Traverse*);
9643 do_determine_type(const Type_context*);
9646 do_check_types(Gogo*);
9651 return Expression::make_array_index(this->array_->copy(),
9652 this->start_->copy(),
9655 : this->end_->copy()),
9660 do_must_eval_subexpressions_in_order(int* skip) const
9667 do_is_addressable() const;
9670 do_address_taken(bool escapes)
9671 { this->array_->address_taken(escapes); }
9674 do_get_tree(Translate_context*);
9677 do_dump_expression(Ast_dump_context*) const;
9680 // The array we are getting a value from.
9682 // The start or only index.
9684 // The end index of a slice. This may be NULL for a simple array
9685 // index, or it may be a nil expression for the length of the array.
9687 // The type of the expression.
9691 // Array index traversal.
9694 Array_index_expression::do_traverse(Traverse* traverse)
9696 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9697 return TRAVERSE_EXIT;
9698 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9699 return TRAVERSE_EXIT;
9700 if (this->end_ != NULL)
9702 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9703 return TRAVERSE_EXIT;
9705 return TRAVERSE_CONTINUE;
9708 // Return the type of an array index.
9711 Array_index_expression::do_type()
9713 if (this->type_ == NULL)
9715 Array_type* type = this->array_->type()->array_type();
9717 this->type_ = Type::make_error_type();
9718 else if (this->end_ == NULL)
9719 this->type_ = type->element_type();
9720 else if (type->is_slice_type())
9722 // A slice of a slice has the same type as the original
9724 this->type_ = this->array_->type()->deref();
9728 // A slice of an array is a slice.
9729 this->type_ = Type::make_array_type(type->element_type(), NULL);
9735 // Set the type of an array index.
9738 Array_index_expression::do_determine_type(const Type_context*)
9740 this->array_->determine_type_no_context();
9741 this->start_->determine_type_no_context();
9742 if (this->end_ != NULL)
9743 this->end_->determine_type_no_context();
9746 // Check types of an array index.
9749 Array_index_expression::do_check_types(Gogo*)
9751 if (this->start_->type()->integer_type() == NULL)
9752 this->report_error(_("index must be integer"));
9753 if (this->end_ != NULL
9754 && this->end_->type()->integer_type() == NULL
9755 && !this->end_->type()->is_error()
9756 && !this->end_->is_nil_expression()
9757 && !this->end_->is_error_expression())
9758 this->report_error(_("slice end must be integer"));
9760 Array_type* array_type = this->array_->type()->array_type();
9761 if (array_type == NULL)
9763 go_assert(this->array_->type()->is_error());
9767 unsigned int int_bits =
9768 Type::lookup_integer_type("int")->integer_type()->bits();
9770 Numeric_constant lvalnc;
9772 bool lval_valid = (array_type->length() != NULL
9773 && array_type->length()->numeric_constant_value(&lvalnc)
9774 && lvalnc.to_int(&lval));
9775 Numeric_constant inc;
9777 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9779 if (mpz_sgn(ival) < 0
9780 || mpz_sizeinbase(ival, 2) >= int_bits
9782 && (this->end_ == NULL
9783 ? mpz_cmp(ival, lval) >= 0
9784 : mpz_cmp(ival, lval) > 0)))
9786 error_at(this->start_->location(), "array index out of bounds");
9787 this->set_is_error();
9791 if (this->end_ != NULL && !this->end_->is_nil_expression())
9793 Numeric_constant enc;
9795 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9797 if (mpz_sgn(eval) < 0
9798 || mpz_sizeinbase(eval, 2) >= int_bits
9799 || (lval_valid && mpz_cmp(eval, lval) > 0))
9801 error_at(this->end_->location(), "array index out of bounds");
9802 this->set_is_error();
9810 // A slice of an array requires an addressable array. A slice of a
9811 // slice is always possible.
9812 if (this->end_ != NULL && !array_type->is_slice_type())
9814 if (!this->array_->is_addressable())
9815 this->report_error(_("slice of unaddressable value"));
9817 this->array_->address_taken(true);
9821 // Return whether this expression is addressable.
9824 Array_index_expression::do_is_addressable() const
9826 // A slice expression is not addressable.
9827 if (this->end_ != NULL)
9830 // An index into a slice is addressable.
9831 if (this->array_->type()->is_slice_type())
9834 // An index into an array is addressable if the array is
9836 return this->array_->is_addressable();
9839 // Get a tree for an array index.
9842 Array_index_expression::do_get_tree(Translate_context* context)
9844 Gogo* gogo = context->gogo();
9845 Location loc = this->location();
9847 Array_type* array_type = this->array_->type()->array_type();
9848 if (array_type == NULL)
9850 go_assert(this->array_->type()->is_error());
9851 return error_mark_node;
9854 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9855 if (type_tree == error_mark_node)
9856 return error_mark_node;
9858 tree array_tree = this->array_->get_tree(context);
9859 if (array_tree == error_mark_node)
9860 return error_mark_node;
9862 if (array_type->length() == NULL && !DECL_P(array_tree))
9863 array_tree = save_expr(array_tree);
9865 tree length_tree = NULL_TREE;
9866 if (this->end_ == NULL || this->end_->is_nil_expression())
9868 length_tree = array_type->length_tree(gogo, array_tree);
9869 if (length_tree == error_mark_node)
9870 return error_mark_node;
9871 length_tree = save_expr(length_tree);
9874 tree capacity_tree = NULL_TREE;
9875 if (this->end_ != NULL)
9877 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9878 if (capacity_tree == error_mark_node)
9879 return error_mark_node;
9880 capacity_tree = save_expr(capacity_tree);
9883 tree length_type = (length_tree != NULL_TREE
9884 ? TREE_TYPE(length_tree)
9885 : TREE_TYPE(capacity_tree));
9887 tree bad_index = boolean_false_node;
9889 tree start_tree = this->start_->get_tree(context);
9890 if (start_tree == error_mark_node)
9891 return error_mark_node;
9892 if (!DECL_P(start_tree))
9893 start_tree = save_expr(start_tree);
9894 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9895 start_tree = convert_to_integer(length_type, start_tree);
9897 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9900 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9901 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9902 boolean_type_node, bad_index,
9903 fold_build2_loc(loc.gcc_location(),
9907 boolean_type_node, start_tree,
9912 int code = (array_type->length() != NULL
9913 ? (this->end_ == NULL
9914 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9915 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9916 : (this->end_ == NULL
9917 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9918 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9919 tree crash = Gogo::runtime_error(code, loc);
9921 if (this->end_ == NULL)
9923 // Simple array indexing. This has to return an l-value, so
9924 // wrap the index check into START_TREE.
9925 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9926 build3(COND_EXPR, void_type_node,
9927 bad_index, crash, NULL_TREE),
9929 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9931 if (array_type->length() != NULL)
9934 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9935 start_tree, NULL_TREE, NULL_TREE);
9940 tree values = array_type->value_pointer_tree(gogo, array_tree);
9941 Type* element_type = array_type->element_type();
9942 Btype* belement_type = element_type->get_backend(gogo);
9943 tree element_type_tree = type_to_tree(belement_type);
9944 if (element_type_tree == error_mark_node)
9945 return error_mark_node;
9946 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9947 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9948 start_tree, element_size);
9949 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9950 TREE_TYPE(values), values, offset);
9951 return build_fold_indirect_ref(ptr);
9958 if (this->end_->is_nil_expression())
9959 end_tree = length_tree;
9962 end_tree = this->end_->get_tree(context);
9963 if (end_tree == error_mark_node)
9964 return error_mark_node;
9965 if (!DECL_P(end_tree))
9966 end_tree = save_expr(end_tree);
9967 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9968 end_tree = convert_to_integer(length_type, end_tree);
9970 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9973 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9975 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9977 fold_build2_loc(loc.gcc_location(),
9978 LT_EXPR, boolean_type_node,
9979 end_tree, start_tree),
9980 fold_build2_loc(loc.gcc_location(),
9981 GT_EXPR, boolean_type_node,
9982 end_tree, capacity_tree));
9983 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9984 boolean_type_node, bad_index, bad_end);
9987 Type* element_type = array_type->element_type();
9988 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9989 if (element_type_tree == error_mark_node)
9990 return error_mark_node;
9991 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9993 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9994 fold_convert_loc(loc.gcc_location(), sizetype,
9998 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9999 if (value_pointer == error_mark_node)
10000 return error_mark_node;
10002 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10003 TREE_TYPE(value_pointer),
10004 value_pointer, offset);
10006 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10007 length_type, end_tree, start_tree);
10009 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10010 length_type, capacity_tree,
10013 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
10014 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
10016 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
10018 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
10019 tree field = TYPE_FIELDS(struct_tree);
10020 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
10021 elt->index = field;
10022 elt->value = value_pointer;
10024 elt = VEC_quick_push(constructor_elt, init, NULL);
10025 field = DECL_CHAIN(field);
10026 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
10027 elt->index = field;
10028 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10029 result_length_tree);
10031 elt = VEC_quick_push(constructor_elt, init, NULL);
10032 field = DECL_CHAIN(field);
10033 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
10034 elt->index = field;
10035 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10036 result_capacity_tree);
10038 tree constructor = build_constructor(struct_tree, init);
10040 if (TREE_CONSTANT(value_pointer)
10041 && TREE_CONSTANT(result_length_tree)
10042 && TREE_CONSTANT(result_capacity_tree))
10043 TREE_CONSTANT(constructor) = 1;
10045 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
10046 TREE_TYPE(constructor),
10047 build3(COND_EXPR, void_type_node,
10048 bad_index, crash, NULL_TREE),
10052 // Dump ast representation for an array index expression.
10055 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10058 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10059 this->start_, this->end_);
10062 // Make an array index expression. END may be NULL.
10065 Expression::make_array_index(Expression* array, Expression* start,
10066 Expression* end, Location location)
10068 return new Array_index_expression(array, start, end, location);
10071 // A string index. This is used for both indexing and slicing.
10073 class String_index_expression : public Expression
10076 String_index_expression(Expression* string, Expression* start,
10077 Expression* end, Location location)
10078 : Expression(EXPRESSION_STRING_INDEX, location),
10079 string_(string), start_(start), end_(end)
10084 do_traverse(Traverse*);
10090 do_determine_type(const Type_context*);
10093 do_check_types(Gogo*);
10098 return Expression::make_string_index(this->string_->copy(),
10099 this->start_->copy(),
10100 (this->end_ == NULL
10102 : this->end_->copy()),
10107 do_must_eval_subexpressions_in_order(int* skip) const
10114 do_get_tree(Translate_context*);
10117 do_dump_expression(Ast_dump_context*) const;
10120 // The string we are getting a value from.
10121 Expression* string_;
10122 // The start or only index.
10123 Expression* start_;
10124 // The end index of a slice. This may be NULL for a single index,
10125 // or it may be a nil expression for the length of the string.
10129 // String index traversal.
10132 String_index_expression::do_traverse(Traverse* traverse)
10134 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10135 return TRAVERSE_EXIT;
10136 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10137 return TRAVERSE_EXIT;
10138 if (this->end_ != NULL)
10140 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10141 return TRAVERSE_EXIT;
10143 return TRAVERSE_CONTINUE;
10146 // Return the type of a string index.
10149 String_index_expression::do_type()
10151 if (this->end_ == NULL)
10152 return Type::lookup_integer_type("uint8");
10154 return this->string_->type();
10157 // Determine the type of a string index.
10160 String_index_expression::do_determine_type(const Type_context*)
10162 this->string_->determine_type_no_context();
10163 this->start_->determine_type_no_context();
10164 if (this->end_ != NULL)
10165 this->end_->determine_type_no_context();
10168 // Check types of a string index.
10171 String_index_expression::do_check_types(Gogo*)
10173 if (this->start_->type()->integer_type() == NULL)
10174 this->report_error(_("index must be integer"));
10175 if (this->end_ != NULL
10176 && this->end_->type()->integer_type() == NULL
10177 && !this->end_->is_nil_expression())
10178 this->report_error(_("slice end must be integer"));
10181 bool sval_valid = this->string_->string_constant_value(&sval);
10183 Numeric_constant inc;
10185 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10187 if (mpz_sgn(ival) < 0
10188 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10190 error_at(this->start_->location(), "string index out of bounds");
10191 this->set_is_error();
10195 if (this->end_ != NULL && !this->end_->is_nil_expression())
10197 Numeric_constant enc;
10199 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10201 if (mpz_sgn(eval) < 0
10202 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10204 error_at(this->end_->location(), "string index out of bounds");
10205 this->set_is_error();
10212 // Get a tree for a string index.
10215 String_index_expression::do_get_tree(Translate_context* context)
10217 Location loc = this->location();
10219 tree string_tree = this->string_->get_tree(context);
10220 if (string_tree == error_mark_node)
10221 return error_mark_node;
10223 if (this->string_->type()->points_to() != NULL)
10224 string_tree = build_fold_indirect_ref(string_tree);
10225 if (!DECL_P(string_tree))
10226 string_tree = save_expr(string_tree);
10227 tree string_type = TREE_TYPE(string_tree);
10229 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10230 length_tree = save_expr(length_tree);
10231 tree length_type = TREE_TYPE(length_tree);
10233 tree bad_index = boolean_false_node;
10235 tree start_tree = this->start_->get_tree(context);
10236 if (start_tree == error_mark_node)
10237 return error_mark_node;
10238 if (!DECL_P(start_tree))
10239 start_tree = save_expr(start_tree);
10240 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10241 start_tree = convert_to_integer(length_type, start_tree);
10243 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10246 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10248 int code = (this->end_ == NULL
10249 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10250 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10251 tree crash = Gogo::runtime_error(code, loc);
10253 if (this->end_ == NULL)
10255 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10256 boolean_type_node, bad_index,
10257 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10259 start_tree, length_tree));
10261 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10262 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10263 TREE_TYPE(bytes_tree),
10265 fold_convert_loc(loc.gcc_location(), sizetype,
10267 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10269 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10270 build3(COND_EXPR, void_type_node,
10271 bad_index, crash, NULL_TREE),
10277 if (this->end_->is_nil_expression())
10278 end_tree = build_int_cst(length_type, -1);
10281 end_tree = this->end_->get_tree(context);
10282 if (end_tree == error_mark_node)
10283 return error_mark_node;
10284 if (!DECL_P(end_tree))
10285 end_tree = save_expr(end_tree);
10286 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10287 end_tree = convert_to_integer(length_type, end_tree);
10289 bad_index = Expression::check_bounds(end_tree, length_type,
10292 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10296 static tree strslice_fndecl;
10297 tree ret = Gogo::call_builtin(&strslice_fndecl,
10299 "__go_string_slice",
10308 if (ret == error_mark_node)
10309 return error_mark_node;
10310 // This will panic if the bounds are out of range for the
10312 TREE_NOTHROW(strslice_fndecl) = 0;
10314 if (bad_index == boolean_false_node)
10317 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10318 build3(COND_EXPR, void_type_node,
10319 bad_index, crash, NULL_TREE),
10324 // Dump ast representation for a string index expression.
10327 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10330 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10331 this->start_, this->end_);
10334 // Make a string index expression. END may be NULL.
10337 Expression::make_string_index(Expression* string, Expression* start,
10338 Expression* end, Location location)
10340 return new String_index_expression(string, start, end, location);
10343 // Class Map_index.
10345 // Get the type of the map.
10348 Map_index_expression::get_map_type() const
10350 Map_type* mt = this->map_->type()->deref()->map_type();
10352 go_assert(saw_errors());
10356 // Map index traversal.
10359 Map_index_expression::do_traverse(Traverse* traverse)
10361 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10362 return TRAVERSE_EXIT;
10363 return Expression::traverse(&this->index_, traverse);
10366 // Return the type of a map index.
10369 Map_index_expression::do_type()
10371 Map_type* mt = this->get_map_type();
10373 return Type::make_error_type();
10374 Type* type = mt->val_type();
10375 // If this map index is in a tuple assignment, we actually return a
10376 // pointer to the value type. Tuple_map_assignment_statement is
10377 // responsible for handling this correctly. We need to get the type
10378 // right in case this gets assigned to a temporary variable.
10379 if (this->is_in_tuple_assignment_)
10380 type = Type::make_pointer_type(type);
10384 // Fix the type of a map index.
10387 Map_index_expression::do_determine_type(const Type_context*)
10389 this->map_->determine_type_no_context();
10390 Map_type* mt = this->get_map_type();
10391 Type* key_type = mt == NULL ? NULL : mt->key_type();
10392 Type_context subcontext(key_type, false);
10393 this->index_->determine_type(&subcontext);
10396 // Check types of a map index.
10399 Map_index_expression::do_check_types(Gogo*)
10401 std::string reason;
10402 Map_type* mt = this->get_map_type();
10405 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10407 if (reason.empty())
10408 this->report_error(_("incompatible type for map index"));
10411 error_at(this->location(), "incompatible type for map index (%s)",
10413 this->set_is_error();
10418 // Get a tree for a map index.
10421 Map_index_expression::do_get_tree(Translate_context* context)
10423 Map_type* type = this->get_map_type();
10425 return error_mark_node;
10427 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10428 if (valptr == error_mark_node)
10429 return error_mark_node;
10430 valptr = save_expr(valptr);
10432 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10434 if (this->is_lvalue_)
10435 return build_fold_indirect_ref(valptr);
10436 else if (this->is_in_tuple_assignment_)
10438 // Tuple_map_assignment_statement is responsible for using this
10444 Gogo* gogo = context->gogo();
10445 Btype* val_btype = type->val_type()->get_backend(gogo);
10446 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10447 return fold_build3(COND_EXPR, val_type_tree,
10448 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10449 fold_convert(TREE_TYPE(valptr),
10450 null_pointer_node)),
10451 expr_to_tree(val_zero),
10452 build_fold_indirect_ref(valptr));
10456 // Get a tree for the map index. This returns a tree which evaluates
10457 // to a pointer to a value. The pointer will be NULL if the key is
10461 Map_index_expression::get_value_pointer(Translate_context* context,
10464 Map_type* type = this->get_map_type();
10466 return error_mark_node;
10468 tree map_tree = this->map_->get_tree(context);
10469 tree index_tree = this->index_->get_tree(context);
10470 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10471 this->index_->type(),
10474 if (map_tree == error_mark_node || index_tree == error_mark_node)
10475 return error_mark_node;
10477 if (this->map_->type()->points_to() != NULL)
10478 map_tree = build_fold_indirect_ref(map_tree);
10480 // We need to pass in a pointer to the key, so stuff it into a
10484 if (current_function_decl != NULL)
10486 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10487 DECL_IGNORED_P(tmp) = 0;
10488 DECL_INITIAL(tmp) = index_tree;
10489 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10490 TREE_ADDRESSABLE(tmp) = 1;
10494 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10495 create_tmp_var_name("M"),
10496 TREE_TYPE(index_tree));
10497 DECL_EXTERNAL(tmp) = 0;
10498 TREE_PUBLIC(tmp) = 0;
10499 TREE_STATIC(tmp) = 1;
10500 DECL_ARTIFICIAL(tmp) = 1;
10501 if (!TREE_CONSTANT(index_tree))
10502 make_tmp = fold_build2_loc(this->location().gcc_location(),
10503 INIT_EXPR, void_type_node,
10507 TREE_READONLY(tmp) = 1;
10508 TREE_CONSTANT(tmp) = 1;
10509 DECL_INITIAL(tmp) = index_tree;
10510 make_tmp = NULL_TREE;
10512 rest_of_decl_compilation(tmp, 1, 0);
10515 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10516 build_fold_addr_expr_loc(this->location().gcc_location(),
10519 static tree map_index_fndecl;
10520 tree call = Gogo::call_builtin(&map_index_fndecl,
10524 const_ptr_type_node,
10525 TREE_TYPE(map_tree),
10527 const_ptr_type_node,
10531 ? boolean_true_node
10532 : boolean_false_node));
10533 if (call == error_mark_node)
10534 return error_mark_node;
10535 // This can panic on a map of interface type if the interface holds
10536 // an uncomparable or unhashable type.
10537 TREE_NOTHROW(map_index_fndecl) = 0;
10539 Type* val_type = type->val_type();
10540 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10541 if (val_type_tree == error_mark_node)
10542 return error_mark_node;
10543 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10545 tree ret = fold_convert_loc(this->location().gcc_location(),
10546 ptr_val_type_tree, call);
10547 if (make_tmp != NULL_TREE)
10548 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10552 // Dump ast representation for a map index expression
10555 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10558 Index_expression::dump_index_expression(ast_dump_context,
10559 this->map_, this->index_, NULL);
10562 // Make a map index expression.
10564 Map_index_expression*
10565 Expression::make_map_index(Expression* map, Expression* index,
10568 return new Map_index_expression(map, index, location);
10571 // Class Field_reference_expression.
10573 // Return the type of a field reference.
10576 Field_reference_expression::do_type()
10578 Type* type = this->expr_->type();
10579 if (type->is_error())
10581 Struct_type* struct_type = type->struct_type();
10582 go_assert(struct_type != NULL);
10583 return struct_type->field(this->field_index_)->type();
10586 // Check the types for a field reference.
10589 Field_reference_expression::do_check_types(Gogo*)
10591 Type* type = this->expr_->type();
10592 if (type->is_error())
10594 Struct_type* struct_type = type->struct_type();
10595 go_assert(struct_type != NULL);
10596 go_assert(struct_type->field(this->field_index_) != NULL);
10599 // Get a tree for a field reference.
10602 Field_reference_expression::do_get_tree(Translate_context* context)
10604 tree struct_tree = this->expr_->get_tree(context);
10605 if (struct_tree == error_mark_node
10606 || TREE_TYPE(struct_tree) == error_mark_node)
10607 return error_mark_node;
10608 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10609 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10610 if (field == NULL_TREE)
10612 // This can happen for a type which refers to itself indirectly
10613 // and then turns out to be erroneous.
10614 go_assert(saw_errors());
10615 return error_mark_node;
10617 for (unsigned int i = this->field_index_; i > 0; --i)
10619 field = DECL_CHAIN(field);
10620 go_assert(field != NULL_TREE);
10622 if (TREE_TYPE(field) == error_mark_node)
10623 return error_mark_node;
10624 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10628 // Dump ast representation for a field reference expression.
10631 Field_reference_expression::do_dump_expression(
10632 Ast_dump_context* ast_dump_context) const
10634 this->expr_->dump_expression(ast_dump_context);
10635 ast_dump_context->ostream() << "." << this->field_index_;
10638 // Make a reference to a qualified identifier in an expression.
10640 Field_reference_expression*
10641 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10644 return new Field_reference_expression(expr, field_index, location);
10647 // Class Interface_field_reference_expression.
10649 // Return a tree for the pointer to the function to call.
10652 Interface_field_reference_expression::get_function_tree(Translate_context*,
10655 if (this->expr_->type()->points_to() != NULL)
10656 expr = build_fold_indirect_ref(expr);
10658 tree expr_type = TREE_TYPE(expr);
10659 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10661 tree field = TYPE_FIELDS(expr_type);
10662 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10664 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10665 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10667 table = build_fold_indirect_ref(table);
10668 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10670 std::string name = Gogo::unpack_hidden_name(this->name_);
10671 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10672 field != NULL_TREE;
10673 field = DECL_CHAIN(field))
10675 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10678 go_assert(field != NULL_TREE);
10680 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10683 // Return a tree for the first argument to pass to the interface
10687 Interface_field_reference_expression::get_underlying_object_tree(
10688 Translate_context*,
10691 if (this->expr_->type()->points_to() != NULL)
10692 expr = build_fold_indirect_ref(expr);
10694 tree expr_type = TREE_TYPE(expr);
10695 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10697 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10698 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10700 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10706 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10708 return Expression::traverse(&this->expr_, traverse);
10711 // Return the type of an interface field reference.
10714 Interface_field_reference_expression::do_type()
10716 Type* expr_type = this->expr_->type();
10718 Type* points_to = expr_type->points_to();
10719 if (points_to != NULL)
10720 expr_type = points_to;
10722 Interface_type* interface_type = expr_type->interface_type();
10723 if (interface_type == NULL)
10724 return Type::make_error_type();
10726 const Typed_identifier* method = interface_type->find_method(this->name_);
10727 if (method == NULL)
10728 return Type::make_error_type();
10730 return method->type();
10733 // Determine types.
10736 Interface_field_reference_expression::do_determine_type(const Type_context*)
10738 this->expr_->determine_type_no_context();
10741 // Check the types for an interface field reference.
10744 Interface_field_reference_expression::do_check_types(Gogo*)
10746 Type* type = this->expr_->type();
10748 Type* points_to = type->points_to();
10749 if (points_to != NULL)
10752 Interface_type* interface_type = type->interface_type();
10753 if (interface_type == NULL)
10755 if (!type->is_error_type())
10756 this->report_error(_("expected interface or pointer to interface"));
10760 const Typed_identifier* method =
10761 interface_type->find_method(this->name_);
10762 if (method == NULL)
10764 error_at(this->location(), "method %qs not in interface",
10765 Gogo::message_name(this->name_).c_str());
10766 this->set_is_error();
10771 // Get a tree for a reference to a field in an interface. There is no
10772 // standard tree type representation for this: it's a function
10773 // attached to its first argument, like a Bound_method_expression.
10774 // The only places it may currently be used are in a Call_expression
10775 // or a Go_statement, which will take it apart directly. So this has
10776 // nothing to do at present.
10779 Interface_field_reference_expression::do_get_tree(Translate_context*)
10781 error_at(this->location(), "reference to method other than calling it");
10782 return error_mark_node;
10785 // Dump ast representation for an interface field reference.
10788 Interface_field_reference_expression::do_dump_expression(
10789 Ast_dump_context* ast_dump_context) const
10791 this->expr_->dump_expression(ast_dump_context);
10792 ast_dump_context->ostream() << "." << this->name_;
10795 // Make a reference to a field in an interface.
10798 Expression::make_interface_field_reference(Expression* expr,
10799 const std::string& field,
10802 return new Interface_field_reference_expression(expr, field, location);
10805 // A general selector. This is a Parser_expression for LEFT.NAME. It
10806 // is lowered after we know the type of the left hand side.
10808 class Selector_expression : public Parser_expression
10811 Selector_expression(Expression* left, const std::string& name,
10813 : Parser_expression(EXPRESSION_SELECTOR, location),
10814 left_(left), name_(name)
10819 do_traverse(Traverse* traverse)
10820 { return Expression::traverse(&this->left_, traverse); }
10823 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10828 return new Selector_expression(this->left_->copy(), this->name_,
10833 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10837 lower_method_expression(Gogo*);
10839 // The expression on the left hand side.
10841 // The name on the right hand side.
10845 // Lower a selector expression once we know the real type of the left
10849 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10852 Expression* left = this->left_;
10853 if (left->is_type_expression())
10854 return this->lower_method_expression(gogo);
10855 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10859 // Lower a method expression T.M or (*T).M. We turn this into a
10860 // function literal.
10863 Selector_expression::lower_method_expression(Gogo* gogo)
10865 Location location = this->location();
10866 Type* type = this->left_->type();
10867 const std::string& name(this->name_);
10870 if (type->points_to() == NULL)
10871 is_pointer = false;
10875 type = type->points_to();
10877 Named_type* nt = type->named_type();
10881 ("method expression requires named type or "
10882 "pointer to named type"));
10883 return Expression::make_error(location);
10887 Method* method = nt->method_function(name, &is_ambiguous);
10888 const Typed_identifier* imethod = NULL;
10889 if (method == NULL && !is_pointer)
10891 Interface_type* it = nt->interface_type();
10893 imethod = it->find_method(name);
10896 if (method == NULL && imethod == NULL)
10899 error_at(location, "type %<%s%s%> has no method %<%s%>",
10900 is_pointer ? "*" : "",
10901 nt->message_name().c_str(),
10902 Gogo::message_name(name).c_str());
10904 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10905 Gogo::message_name(name).c_str(),
10906 is_pointer ? "*" : "",
10907 nt->message_name().c_str());
10908 return Expression::make_error(location);
10911 if (method != NULL && !is_pointer && !method->is_value_method())
10913 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10914 nt->message_name().c_str(),
10915 Gogo::message_name(name).c_str());
10916 return Expression::make_error(location);
10919 // Build a new function type in which the receiver becomes the first
10921 Function_type* method_type;
10922 if (method != NULL)
10924 method_type = method->type();
10925 go_assert(method_type->is_method());
10929 method_type = imethod->type()->function_type();
10930 go_assert(method_type != NULL && !method_type->is_method());
10933 const char* const receiver_name = "$this";
10934 Typed_identifier_list* parameters = new Typed_identifier_list();
10935 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10938 const Typed_identifier_list* method_parameters = method_type->parameters();
10939 if (method_parameters != NULL)
10942 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10943 p != method_parameters->end();
10946 if (!p->name().empty())
10947 parameters->push_back(*p);
10951 snprintf(buf, sizeof buf, "$param%d", i);
10952 parameters->push_back(Typed_identifier(buf, p->type(),
10958 const Typed_identifier_list* method_results = method_type->results();
10959 Typed_identifier_list* results;
10960 if (method_results == NULL)
10964 results = new Typed_identifier_list();
10965 for (Typed_identifier_list::const_iterator p = method_results->begin();
10966 p != method_results->end();
10968 results->push_back(*p);
10971 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10973 if (method_type->is_varargs())
10974 fntype->set_is_varargs();
10976 // We generate methods which always takes a pointer to the receiver
10977 // as their first argument. If this is for a pointer type, we can
10978 // simply reuse the existing function. We use an internal hack to
10979 // get the right type.
10981 if (method != NULL && is_pointer)
10983 Named_object* mno = (method->needs_stub_method()
10984 ? method->stub_object()
10985 : method->named_object());
10986 Expression* f = Expression::make_func_reference(mno, NULL, location);
10987 f = Expression::make_cast(fntype, f, location);
10988 Type_conversion_expression* tce =
10989 static_cast<Type_conversion_expression*>(f);
10990 tce->set_may_convert_function_types();
10994 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10997 Named_object* vno = gogo->lookup(receiver_name, NULL);
10998 go_assert(vno != NULL);
10999 Expression* ve = Expression::make_var_reference(vno, location);
11001 if (method != NULL)
11002 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11004 bm = Expression::make_interface_field_reference(ve, name, location);
11006 // Even though we found the method above, if it has an error type we
11007 // may see an error here.
11008 if (bm->is_error_expression())
11010 gogo->finish_function(location);
11014 Expression_list* args;
11015 if (parameters->size() <= 1)
11019 args = new Expression_list();
11020 Typed_identifier_list::const_iterator p = parameters->begin();
11022 for (; p != parameters->end(); ++p)
11024 vno = gogo->lookup(p->name(), NULL);
11025 go_assert(vno != NULL);
11026 args->push_back(Expression::make_var_reference(vno, location));
11030 gogo->start_block(location);
11032 Call_expression* call = Expression::make_call(bm, args,
11033 method_type->is_varargs(),
11036 size_t count = call->result_count();
11039 s = Statement::make_statement(call, true);
11042 Expression_list* retvals = new Expression_list();
11044 retvals->push_back(call);
11047 for (size_t i = 0; i < count; ++i)
11048 retvals->push_back(Expression::make_call_result(call, i));
11050 s = Statement::make_return_statement(retvals, location);
11052 gogo->add_statement(s);
11054 Block* b = gogo->finish_block(location);
11056 gogo->add_block(b, location);
11058 // Lower the call in case there are multiple results.
11059 gogo->lower_block(no, b);
11061 gogo->finish_function(location);
11063 return Expression::make_func_reference(no, NULL, location);
11066 // Dump the ast for a selector expression.
11069 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11072 ast_dump_context->dump_expression(this->left_);
11073 ast_dump_context->ostream() << ".";
11074 ast_dump_context->ostream() << this->name_;
11077 // Make a selector expression.
11080 Expression::make_selector(Expression* left, const std::string& name,
11083 return new Selector_expression(left, name, location);
11086 // Implement the builtin function new.
11088 class Allocation_expression : public Expression
11091 Allocation_expression(Type* type, Location location)
11092 : Expression(EXPRESSION_ALLOCATION, location),
11098 do_traverse(Traverse* traverse)
11099 { return Type::traverse(this->type_, traverse); }
11103 { return Type::make_pointer_type(this->type_); }
11106 do_determine_type(const Type_context*)
11111 { return new Allocation_expression(this->type_, this->location()); }
11114 do_get_tree(Translate_context*);
11117 do_dump_expression(Ast_dump_context*) const;
11120 // The type we are allocating.
11124 // Return a tree for an allocation expression.
11127 Allocation_expression::do_get_tree(Translate_context* context)
11129 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11130 if (type_tree == error_mark_node)
11131 return error_mark_node;
11132 tree size_tree = TYPE_SIZE_UNIT(type_tree);
11133 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11135 if (space == error_mark_node)
11136 return error_mark_node;
11137 return fold_convert(build_pointer_type(type_tree), space);
11140 // Dump ast representation for an allocation expression.
11143 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11146 ast_dump_context->ostream() << "new(";
11147 ast_dump_context->dump_type(this->type_);
11148 ast_dump_context->ostream() << ")";
11151 // Make an allocation expression.
11154 Expression::make_allocation(Type* type, Location location)
11156 return new Allocation_expression(type, location);
11159 // Construct a struct.
11161 class Struct_construction_expression : public Expression
11164 Struct_construction_expression(Type* type, Expression_list* vals,
11166 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11167 type_(type), vals_(vals), traverse_order_(NULL)
11170 // Set the traversal order, used to ensure that we implement the
11171 // order of evaluation rules. Takes ownership of the argument.
11173 set_traverse_order(std::vector<int>* traverse_order)
11174 { this->traverse_order_ = traverse_order; }
11176 // Return whether this is a constant initializer.
11178 is_constant_struct() const;
11182 do_traverse(Traverse* traverse);
11186 { return this->type_; }
11189 do_determine_type(const Type_context*);
11192 do_check_types(Gogo*);
11197 Struct_construction_expression* ret =
11198 new Struct_construction_expression(this->type_, this->vals_->copy(),
11200 if (this->traverse_order_ != NULL)
11201 ret->set_traverse_order(this->traverse_order_);
11206 do_get_tree(Translate_context*);
11209 do_export(Export*) const;
11212 do_dump_expression(Ast_dump_context*) const;
11215 // The type of the struct to construct.
11217 // The list of values, in order of the fields in the struct. A NULL
11218 // entry means that the field should be zero-initialized.
11219 Expression_list* vals_;
11220 // If not NULL, the order in which to traverse vals_. This is used
11221 // so that we implement the order of evaluation rules correctly.
11222 std::vector<int>* traverse_order_;
11228 Struct_construction_expression::do_traverse(Traverse* traverse)
11230 if (this->vals_ != NULL)
11232 if (this->traverse_order_ == NULL)
11234 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11235 return TRAVERSE_EXIT;
11239 for (std::vector<int>::const_iterator p =
11240 this->traverse_order_->begin();
11241 p != this->traverse_order_->end();
11244 if (Expression::traverse(&this->vals_->at(*p), traverse)
11246 return TRAVERSE_EXIT;
11250 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11251 return TRAVERSE_EXIT;
11252 return TRAVERSE_CONTINUE;
11255 // Return whether this is a constant initializer.
11258 Struct_construction_expression::is_constant_struct() const
11260 if (this->vals_ == NULL)
11262 for (Expression_list::const_iterator pv = this->vals_->begin();
11263 pv != this->vals_->end();
11267 && !(*pv)->is_constant()
11268 && (!(*pv)->is_composite_literal()
11269 || (*pv)->is_nonconstant_composite_literal()))
11273 const Struct_field_list* fields = this->type_->struct_type()->fields();
11274 for (Struct_field_list::const_iterator pf = fields->begin();
11275 pf != fields->end();
11278 // There are no constant constructors for interfaces.
11279 if (pf->type()->interface_type() != NULL)
11286 // Final type determination.
11289 Struct_construction_expression::do_determine_type(const Type_context*)
11291 if (this->vals_ == NULL)
11293 const Struct_field_list* fields = this->type_->struct_type()->fields();
11294 Expression_list::const_iterator pv = this->vals_->begin();
11295 for (Struct_field_list::const_iterator pf = fields->begin();
11296 pf != fields->end();
11299 if (pv == this->vals_->end())
11303 Type_context subcontext(pf->type(), false);
11304 (*pv)->determine_type(&subcontext);
11307 // Extra values are an error we will report elsewhere; we still want
11308 // to determine the type to avoid knockon errors.
11309 for (; pv != this->vals_->end(); ++pv)
11310 (*pv)->determine_type_no_context();
11316 Struct_construction_expression::do_check_types(Gogo*)
11318 if (this->vals_ == NULL)
11321 Struct_type* st = this->type_->struct_type();
11322 if (this->vals_->size() > st->field_count())
11324 this->report_error(_("too many expressions for struct"));
11328 const Struct_field_list* fields = st->fields();
11329 Expression_list::const_iterator pv = this->vals_->begin();
11331 for (Struct_field_list::const_iterator pf = fields->begin();
11332 pf != fields->end();
11335 if (pv == this->vals_->end())
11337 this->report_error(_("too few expressions for struct"));
11344 std::string reason;
11345 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11347 if (reason.empty())
11348 error_at((*pv)->location(),
11349 "incompatible type for field %d in struct construction",
11352 error_at((*pv)->location(),
11353 ("incompatible type for field %d in "
11354 "struct construction (%s)"),
11355 i + 1, reason.c_str());
11356 this->set_is_error();
11359 go_assert(pv == this->vals_->end());
11362 // Return a tree for constructing a struct.
11365 Struct_construction_expression::do_get_tree(Translate_context* context)
11367 Gogo* gogo = context->gogo();
11369 if (this->vals_ == NULL)
11371 Btype* btype = this->type_->get_backend(gogo);
11372 return expr_to_tree(gogo->backend()->zero_expression(btype));
11375 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11376 if (type_tree == error_mark_node)
11377 return error_mark_node;
11378 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11380 bool is_constant = true;
11381 const Struct_field_list* fields = this->type_->struct_type()->fields();
11382 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11384 Struct_field_list::const_iterator pf = fields->begin();
11385 Expression_list::const_iterator pv = this->vals_->begin();
11386 for (tree field = TYPE_FIELDS(type_tree);
11387 field != NULL_TREE;
11388 field = DECL_CHAIN(field), ++pf)
11390 go_assert(pf != fields->end());
11392 Btype* fbtype = pf->type()->get_backend(gogo);
11395 if (pv == this->vals_->end())
11396 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11397 else if (*pv == NULL)
11399 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11404 val = Expression::convert_for_assignment(context, pf->type(),
11406 (*pv)->get_tree(context),
11411 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11412 return error_mark_node;
11414 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11415 elt->index = field;
11417 if (!TREE_CONSTANT(val))
11418 is_constant = false;
11420 go_assert(pf == fields->end());
11422 tree ret = build_constructor(type_tree, elts);
11424 TREE_CONSTANT(ret) = 1;
11428 // Export a struct construction.
11431 Struct_construction_expression::do_export(Export* exp) const
11433 exp->write_c_string("convert(");
11434 exp->write_type(this->type_);
11435 for (Expression_list::const_iterator pv = this->vals_->begin();
11436 pv != this->vals_->end();
11439 exp->write_c_string(", ");
11441 (*pv)->export_expression(exp);
11443 exp->write_c_string(")");
11446 // Dump ast representation of a struct construction expression.
11449 Struct_construction_expression::do_dump_expression(
11450 Ast_dump_context* ast_dump_context) const
11452 ast_dump_context->dump_type(this->type_);
11453 ast_dump_context->ostream() << "{";
11454 ast_dump_context->dump_expression_list(this->vals_);
11455 ast_dump_context->ostream() << "}";
11458 // Make a struct composite literal. This used by the thunk code.
11461 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11464 go_assert(type->struct_type() != NULL);
11465 return new Struct_construction_expression(type, vals, location);
11468 // Construct an array. This class is not used directly; instead we
11469 // use the child classes, Fixed_array_construction_expression and
11470 // Open_array_construction_expression.
11472 class Array_construction_expression : public Expression
11475 Array_construction_expression(Expression_classification classification,
11477 const std::vector<unsigned long>* indexes,
11478 Expression_list* vals, Location location)
11479 : Expression(classification, location),
11480 type_(type), indexes_(indexes), vals_(vals)
11481 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11484 // Return whether this is a constant initializer.
11486 is_constant_array() const;
11488 // Return the number of elements.
11490 element_count() const
11491 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11495 do_traverse(Traverse* traverse);
11499 { return this->type_; }
11502 do_determine_type(const Type_context*);
11505 do_check_types(Gogo*);
11508 do_export(Export*) const;
11511 const std::vector<unsigned long>*
11513 { return this->indexes_; }
11515 // The list of values.
11518 { return this->vals_; }
11520 // Get a constructor tree for the array values.
11522 get_constructor_tree(Translate_context* context, tree type_tree);
11525 do_dump_expression(Ast_dump_context*) const;
11528 // The type of the array to construct.
11530 // The list of indexes into the array, one for each value. This may
11531 // be NULL, in which case the indexes start at zero and increment.
11532 const std::vector<unsigned long>* indexes_;
11533 // The list of values. This may be NULL if there are no values.
11534 Expression_list* vals_;
11540 Array_construction_expression::do_traverse(Traverse* traverse)
11542 if (this->vals_ != NULL
11543 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11544 return TRAVERSE_EXIT;
11545 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11546 return TRAVERSE_EXIT;
11547 return TRAVERSE_CONTINUE;
11550 // Return whether this is a constant initializer.
11553 Array_construction_expression::is_constant_array() const
11555 if (this->vals_ == NULL)
11558 // There are no constant constructors for interfaces.
11559 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11562 for (Expression_list::const_iterator pv = this->vals_->begin();
11563 pv != this->vals_->end();
11567 && !(*pv)->is_constant()
11568 && (!(*pv)->is_composite_literal()
11569 || (*pv)->is_nonconstant_composite_literal()))
11575 // Final type determination.
11578 Array_construction_expression::do_determine_type(const Type_context*)
11580 if (this->vals_ == NULL)
11582 Type_context subcontext(this->type_->array_type()->element_type(), false);
11583 for (Expression_list::const_iterator pv = this->vals_->begin();
11584 pv != this->vals_->end();
11588 (*pv)->determine_type(&subcontext);
11595 Array_construction_expression::do_check_types(Gogo*)
11597 if (this->vals_ == NULL)
11600 Array_type* at = this->type_->array_type();
11602 Type* element_type = at->element_type();
11603 for (Expression_list::const_iterator pv = this->vals_->begin();
11604 pv != this->vals_->end();
11608 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11610 error_at((*pv)->location(),
11611 "incompatible type for element %d in composite literal",
11613 this->set_is_error();
11618 // Get a constructor tree for the array values.
11621 Array_construction_expression::get_constructor_tree(Translate_context* context,
11624 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11625 (this->vals_ == NULL
11627 : this->vals_->size()));
11628 Type* element_type = this->type_->array_type()->element_type();
11629 bool is_constant = true;
11630 if (this->vals_ != NULL)
11633 std::vector<unsigned long>::const_iterator pi;
11634 if (this->indexes_ != NULL)
11635 pi = this->indexes_->begin();
11636 for (Expression_list::const_iterator pv = this->vals_->begin();
11637 pv != this->vals_->end();
11640 if (this->indexes_ != NULL)
11641 go_assert(pi != this->indexes_->end());
11642 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11644 if (this->indexes_ == NULL)
11645 elt->index = size_int(i);
11647 elt->index = size_int(*pi);
11651 Gogo* gogo = context->gogo();
11652 Btype* ebtype = element_type->get_backend(gogo);
11653 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11654 elt->value = expr_to_tree(zv);
11658 tree value_tree = (*pv)->get_tree(context);
11659 elt->value = Expression::convert_for_assignment(context,
11665 if (elt->value == error_mark_node)
11666 return error_mark_node;
11667 if (!TREE_CONSTANT(elt->value))
11668 is_constant = false;
11669 if (this->indexes_ != NULL)
11672 if (this->indexes_ != NULL)
11673 go_assert(pi == this->indexes_->end());
11676 tree ret = build_constructor(type_tree, values);
11678 TREE_CONSTANT(ret) = 1;
11682 // Export an array construction.
11685 Array_construction_expression::do_export(Export* exp) const
11687 exp->write_c_string("convert(");
11688 exp->write_type(this->type_);
11689 if (this->vals_ != NULL)
11691 std::vector<unsigned long>::const_iterator pi;
11692 if (this->indexes_ != NULL)
11693 pi = this->indexes_->begin();
11694 for (Expression_list::const_iterator pv = this->vals_->begin();
11695 pv != this->vals_->end();
11698 exp->write_c_string(", ");
11700 if (this->indexes_ != NULL)
11703 snprintf(buf, sizeof buf, "%lu", *pi);
11704 exp->write_c_string(buf);
11705 exp->write_c_string(":");
11709 (*pv)->export_expression(exp);
11711 if (this->indexes_ != NULL)
11715 exp->write_c_string(")");
11718 // Dump ast representation of an array construction expressin.
11721 Array_construction_expression::do_dump_expression(
11722 Ast_dump_context* ast_dump_context) const
11724 Expression* length = this->type_->array_type()->length();
11726 ast_dump_context->ostream() << "[" ;
11727 if (length != NULL)
11729 ast_dump_context->dump_expression(length);
11731 ast_dump_context->ostream() << "]" ;
11732 ast_dump_context->dump_type(this->type_);
11733 ast_dump_context->ostream() << "{" ;
11734 if (this->indexes_ == NULL)
11735 ast_dump_context->dump_expression_list(this->vals_);
11738 Expression_list::const_iterator pv = this->vals_->begin();
11739 for (std::vector<unsigned long>::const_iterator pi =
11740 this->indexes_->begin();
11741 pi != this->indexes_->end();
11744 if (pi != this->indexes_->begin())
11745 ast_dump_context->ostream() << ", ";
11746 ast_dump_context->ostream() << *pi << ':';
11747 ast_dump_context->dump_expression(*pv);
11750 ast_dump_context->ostream() << "}" ;
11754 // Construct a fixed array.
11756 class Fixed_array_construction_expression :
11757 public Array_construction_expression
11760 Fixed_array_construction_expression(Type* type,
11761 const std::vector<unsigned long>* indexes,
11762 Expression_list* vals, Location location)
11763 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11764 type, indexes, vals, location)
11765 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11771 return new Fixed_array_construction_expression(this->type(),
11773 (this->vals() == NULL
11775 : this->vals()->copy()),
11780 do_get_tree(Translate_context*);
11783 // Return a tree for constructing a fixed array.
11786 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11788 Type* type = this->type();
11789 Btype* btype = type->get_backend(context->gogo());
11790 return this->get_constructor_tree(context, type_to_tree(btype));
11793 // Construct an open array.
11795 class Open_array_construction_expression : public Array_construction_expression
11798 Open_array_construction_expression(Type* type,
11799 const std::vector<unsigned long>* indexes,
11800 Expression_list* vals, Location location)
11801 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11802 type, indexes, vals, location)
11803 { go_assert(type->is_slice_type()); }
11806 // Note that taking the address of an open array literal is invalid.
11811 return new Open_array_construction_expression(this->type(),
11813 (this->vals() == NULL
11815 : this->vals()->copy()),
11820 do_get_tree(Translate_context*);
11823 // Return a tree for constructing an open array.
11826 Open_array_construction_expression::do_get_tree(Translate_context* context)
11828 Array_type* array_type = this->type()->array_type();
11829 if (array_type == NULL)
11831 go_assert(this->type()->is_error());
11832 return error_mark_node;
11835 Type* element_type = array_type->element_type();
11836 Btype* belement_type = element_type->get_backend(context->gogo());
11837 tree element_type_tree = type_to_tree(belement_type);
11838 if (element_type_tree == error_mark_node)
11839 return error_mark_node;
11843 if (this->vals() == NULL || this->vals()->empty())
11845 // We need to create a unique value.
11846 tree max = size_int(0);
11847 tree constructor_type = build_array_type(element_type_tree,
11848 build_index_type(max));
11849 if (constructor_type == error_mark_node)
11850 return error_mark_node;
11851 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11852 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11853 elt->index = size_int(0);
11854 Gogo* gogo = context->gogo();
11855 Btype* btype = element_type->get_backend(gogo);
11856 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11857 values = build_constructor(constructor_type, vec);
11858 if (TREE_CONSTANT(elt->value))
11859 TREE_CONSTANT(values) = 1;
11860 length_tree = size_int(0);
11864 unsigned long max_index;
11865 if (this->indexes() == NULL)
11866 max_index = this->vals()->size() - 1;
11868 max_index = this->indexes()->back();
11869 tree max_tree = size_int(max_index);
11870 tree constructor_type = build_array_type(element_type_tree,
11871 build_index_type(max_tree));
11872 if (constructor_type == error_mark_node)
11873 return error_mark_node;
11874 values = this->get_constructor_tree(context, constructor_type);
11875 length_tree = size_int(max_index + 1);
11878 if (values == error_mark_node)
11879 return error_mark_node;
11881 bool is_constant_initializer = TREE_CONSTANT(values);
11883 // We have to copy the initial values into heap memory if we are in
11884 // a function or if the values are not constants. We also have to
11885 // copy them if they may contain pointers in a non-constant context,
11886 // as otherwise the garbage collector won't see them.
11887 bool copy_to_heap = (context->function() != NULL
11888 || !is_constant_initializer
11889 || (element_type->has_pointer()
11890 && !context->is_const()));
11892 if (is_constant_initializer)
11894 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11895 create_tmp_var_name("C"), TREE_TYPE(values));
11896 DECL_EXTERNAL(tmp) = 0;
11897 TREE_PUBLIC(tmp) = 0;
11898 TREE_STATIC(tmp) = 1;
11899 DECL_ARTIFICIAL(tmp) = 1;
11902 // If we are not copying the value to the heap, we will only
11903 // initialize the value once, so we can use this directly
11904 // rather than copying it. In that case we can't make it
11905 // read-only, because the program is permitted to change it.
11906 TREE_READONLY(tmp) = 1;
11907 TREE_CONSTANT(tmp) = 1;
11909 DECL_INITIAL(tmp) = values;
11910 rest_of_decl_compilation(tmp, 1, 0);
11918 // the initializer will only run once.
11919 space = build_fold_addr_expr(values);
11924 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11925 space = context->gogo()->allocate_memory(element_type, memsize,
11927 space = save_expr(space);
11929 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11930 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11932 TREE_THIS_NOTRAP(ref) = 1;
11933 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11936 // Build a constructor for the open array.
11938 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11939 if (type_tree == error_mark_node)
11940 return error_mark_node;
11941 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11943 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11945 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11946 tree field = TYPE_FIELDS(type_tree);
11947 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11948 elt->index = field;
11949 elt->value = fold_convert(TREE_TYPE(field), space);
11951 elt = VEC_quick_push(constructor_elt, init, NULL);
11952 field = DECL_CHAIN(field);
11953 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11954 elt->index = field;
11955 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11957 elt = VEC_quick_push(constructor_elt, init, NULL);
11958 field = DECL_CHAIN(field);
11959 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11960 elt->index = field;
11961 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11963 tree constructor = build_constructor(type_tree, init);
11964 if (constructor == error_mark_node)
11965 return error_mark_node;
11967 TREE_CONSTANT(constructor) = 1;
11969 if (set == NULL_TREE)
11970 return constructor;
11972 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11975 // Make a slice composite literal. This is used by the type
11976 // descriptor code.
11979 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11982 go_assert(type->is_slice_type());
11983 return new Open_array_construction_expression(type, NULL, vals, location);
11986 // Construct a map.
11988 class Map_construction_expression : public Expression
11991 Map_construction_expression(Type* type, Expression_list* vals,
11993 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11994 type_(type), vals_(vals)
11995 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11999 do_traverse(Traverse* traverse);
12003 { return this->type_; }
12006 do_determine_type(const Type_context*);
12009 do_check_types(Gogo*);
12014 return new Map_construction_expression(this->type_, this->vals_->copy(),
12019 do_get_tree(Translate_context*);
12022 do_export(Export*) const;
12025 do_dump_expression(Ast_dump_context*) const;
12028 // The type of the map to construct.
12030 // The list of values.
12031 Expression_list* vals_;
12037 Map_construction_expression::do_traverse(Traverse* traverse)
12039 if (this->vals_ != NULL
12040 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12041 return TRAVERSE_EXIT;
12042 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12043 return TRAVERSE_EXIT;
12044 return TRAVERSE_CONTINUE;
12047 // Final type determination.
12050 Map_construction_expression::do_determine_type(const Type_context*)
12052 if (this->vals_ == NULL)
12055 Map_type* mt = this->type_->map_type();
12056 Type_context key_context(mt->key_type(), false);
12057 Type_context val_context(mt->val_type(), false);
12058 for (Expression_list::const_iterator pv = this->vals_->begin();
12059 pv != this->vals_->end();
12062 (*pv)->determine_type(&key_context);
12064 (*pv)->determine_type(&val_context);
12071 Map_construction_expression::do_check_types(Gogo*)
12073 if (this->vals_ == NULL)
12076 Map_type* mt = this->type_->map_type();
12078 Type* key_type = mt->key_type();
12079 Type* val_type = mt->val_type();
12080 for (Expression_list::const_iterator pv = this->vals_->begin();
12081 pv != this->vals_->end();
12084 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12086 error_at((*pv)->location(),
12087 "incompatible type for element %d key in map construction",
12089 this->set_is_error();
12092 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12094 error_at((*pv)->location(),
12095 ("incompatible type for element %d value "
12096 "in map construction"),
12098 this->set_is_error();
12103 // Return a tree for constructing a map.
12106 Map_construction_expression::do_get_tree(Translate_context* context)
12108 Gogo* gogo = context->gogo();
12109 Location loc = this->location();
12111 Map_type* mt = this->type_->map_type();
12113 // Build a struct to hold the key and value.
12114 tree struct_type = make_node(RECORD_TYPE);
12116 Type* key_type = mt->key_type();
12117 tree id = get_identifier("__key");
12118 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12119 if (key_type_tree == error_mark_node)
12120 return error_mark_node;
12121 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12123 DECL_CONTEXT(key_field) = struct_type;
12124 TYPE_FIELDS(struct_type) = key_field;
12126 Type* val_type = mt->val_type();
12127 id = get_identifier("__val");
12128 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12129 if (val_type_tree == error_mark_node)
12130 return error_mark_node;
12131 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12133 DECL_CONTEXT(val_field) = struct_type;
12134 DECL_CHAIN(key_field) = val_field;
12136 layout_type(struct_type);
12138 bool is_constant = true;
12143 if (this->vals_ == NULL || this->vals_->empty())
12145 valaddr = null_pointer_node;
12146 make_tmp = NULL_TREE;
12150 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12151 this->vals_->size() / 2);
12153 for (Expression_list::const_iterator pv = this->vals_->begin();
12154 pv != this->vals_->end();
12157 bool one_is_constant = true;
12159 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12161 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12162 elt->index = key_field;
12163 tree val_tree = (*pv)->get_tree(context);
12164 elt->value = Expression::convert_for_assignment(context, key_type,
12167 if (elt->value == error_mark_node)
12168 return error_mark_node;
12169 if (!TREE_CONSTANT(elt->value))
12170 one_is_constant = false;
12174 elt = VEC_quick_push(constructor_elt, one, NULL);
12175 elt->index = val_field;
12176 val_tree = (*pv)->get_tree(context);
12177 elt->value = Expression::convert_for_assignment(context, val_type,
12180 if (elt->value == error_mark_node)
12181 return error_mark_node;
12182 if (!TREE_CONSTANT(elt->value))
12183 one_is_constant = false;
12185 elt = VEC_quick_push(constructor_elt, values, NULL);
12186 elt->index = size_int(i);
12187 elt->value = build_constructor(struct_type, one);
12188 if (one_is_constant)
12189 TREE_CONSTANT(elt->value) = 1;
12191 is_constant = false;
12194 tree index_type = build_index_type(size_int(i - 1));
12195 tree array_type = build_array_type(struct_type, index_type);
12196 tree init = build_constructor(array_type, values);
12198 TREE_CONSTANT(init) = 1;
12200 if (current_function_decl != NULL)
12202 tmp = create_tmp_var(array_type, get_name(array_type));
12203 DECL_INITIAL(tmp) = init;
12204 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12205 void_type_node, tmp);
12206 TREE_ADDRESSABLE(tmp) = 1;
12210 tmp = build_decl(loc.gcc_location(), VAR_DECL,
12211 create_tmp_var_name("M"), array_type);
12212 DECL_EXTERNAL(tmp) = 0;
12213 TREE_PUBLIC(tmp) = 0;
12214 TREE_STATIC(tmp) = 1;
12215 DECL_ARTIFICIAL(tmp) = 1;
12216 if (!TREE_CONSTANT(init))
12217 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
12218 void_type_node, tmp, init);
12221 TREE_READONLY(tmp) = 1;
12222 TREE_CONSTANT(tmp) = 1;
12223 DECL_INITIAL(tmp) = init;
12224 make_tmp = NULL_TREE;
12226 rest_of_decl_compilation(tmp, 1, 0);
12229 valaddr = build_fold_addr_expr(tmp);
12232 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
12234 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12235 if (type_tree == error_mark_node)
12236 return error_mark_node;
12238 static tree construct_map_fndecl;
12239 tree call = Gogo::call_builtin(&construct_map_fndecl,
12241 "__go_construct_map",
12244 TREE_TYPE(descriptor),
12249 TYPE_SIZE_UNIT(struct_type),
12251 byte_position(val_field),
12253 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
12254 const_ptr_type_node,
12255 fold_convert(const_ptr_type_node, valaddr));
12256 if (call == error_mark_node)
12257 return error_mark_node;
12260 if (make_tmp == NULL)
12263 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12268 // Export an array construction.
12271 Map_construction_expression::do_export(Export* exp) const
12273 exp->write_c_string("convert(");
12274 exp->write_type(this->type_);
12275 for (Expression_list::const_iterator pv = this->vals_->begin();
12276 pv != this->vals_->end();
12279 exp->write_c_string(", ");
12280 (*pv)->export_expression(exp);
12282 exp->write_c_string(")");
12285 // Dump ast representation for a map construction expression.
12288 Map_construction_expression::do_dump_expression(
12289 Ast_dump_context* ast_dump_context) const
12291 ast_dump_context->ostream() << "{" ;
12292 ast_dump_context->dump_expression_list(this->vals_, true);
12293 ast_dump_context->ostream() << "}";
12296 // A general composite literal. This is lowered to a type specific
12299 class Composite_literal_expression : public Parser_expression
12302 Composite_literal_expression(Type* type, int depth, bool has_keys,
12303 Expression_list* vals, Location location)
12304 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12305 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12310 do_traverse(Traverse* traverse);
12313 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12318 return new Composite_literal_expression(this->type_, this->depth_,
12320 (this->vals_ == NULL
12322 : this->vals_->copy()),
12327 do_dump_expression(Ast_dump_context*) const;
12331 lower_struct(Gogo*, Type*);
12334 lower_array(Type*);
12337 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12340 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12342 // The type of the composite literal.
12344 // The depth within a list of composite literals within a composite
12345 // literal, when the type is omitted.
12347 // The values to put in the composite literal.
12348 Expression_list* vals_;
12349 // If this is true, then VALS_ is a list of pairs: a key and a
12350 // value. In an array initializer, a missing key will be NULL.
12357 Composite_literal_expression::do_traverse(Traverse* traverse)
12359 if (this->vals_ != NULL
12360 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12361 return TRAVERSE_EXIT;
12362 return Type::traverse(this->type_, traverse);
12365 // Lower a generic composite literal into a specific version based on
12369 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12370 Statement_inserter* inserter, int)
12372 Type* type = this->type_;
12374 for (int depth = this->depth_; depth > 0; --depth)
12376 if (type->array_type() != NULL)
12377 type = type->array_type()->element_type();
12378 else if (type->map_type() != NULL)
12379 type = type->map_type()->val_type();
12382 if (!type->is_error())
12383 error_at(this->location(),
12384 ("may only omit types within composite literals "
12385 "of slice, array, or map type"));
12386 return Expression::make_error(this->location());
12390 Type *pt = type->points_to();
12391 bool is_pointer = false;
12399 if (type->is_error())
12400 return Expression::make_error(this->location());
12401 else if (type->struct_type() != NULL)
12402 ret = this->lower_struct(gogo, type);
12403 else if (type->array_type() != NULL)
12404 ret = this->lower_array(type);
12405 else if (type->map_type() != NULL)
12406 ret = this->lower_map(gogo, function, inserter, type);
12409 error_at(this->location(),
12410 ("expected struct, slice, array, or map type "
12411 "for composite literal"));
12412 return Expression::make_error(this->location());
12416 ret = Expression::make_heap_composite(ret, this->location());
12421 // Lower a struct composite literal.
12424 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12426 Location location = this->location();
12427 Struct_type* st = type->struct_type();
12428 if (this->vals_ == NULL || !this->has_keys_)
12430 if (this->vals_ != NULL
12431 && !this->vals_->empty()
12432 && type->named_type() != NULL
12433 && type->named_type()->named_object()->package() != NULL)
12435 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12436 pf != st->fields()->end();
12439 if (Gogo::is_hidden_name(pf->field_name()))
12440 error_at(this->location(),
12441 "assignment of unexported field %qs in %qs literal",
12442 Gogo::message_name(pf->field_name()).c_str(),
12443 type->named_type()->message_name().c_str());
12447 return new Struct_construction_expression(type, this->vals_, location);
12450 size_t field_count = st->field_count();
12451 std::vector<Expression*> vals(field_count);
12452 std::vector<int>* traverse_order = new(std::vector<int>);
12453 Expression_list::const_iterator p = this->vals_->begin();
12454 while (p != this->vals_->end())
12456 Expression* name_expr = *p;
12459 go_assert(p != this->vals_->end());
12460 Expression* val = *p;
12464 if (name_expr == NULL)
12466 error_at(val->location(), "mixture of field and value initializers");
12467 return Expression::make_error(location);
12470 bool bad_key = false;
12472 const Named_object* no = NULL;
12473 switch (name_expr->classification())
12475 case EXPRESSION_UNKNOWN_REFERENCE:
12476 name = name_expr->unknown_expression()->name();
12479 case EXPRESSION_CONST_REFERENCE:
12480 no = static_cast<Const_expression*>(name_expr)->named_object();
12483 case EXPRESSION_TYPE:
12485 Type* t = name_expr->type();
12486 Named_type* nt = t->named_type();
12490 no = nt->named_object();
12494 case EXPRESSION_VAR_REFERENCE:
12495 no = name_expr->var_expression()->named_object();
12498 case EXPRESSION_FUNC_REFERENCE:
12499 no = name_expr->func_expression()->named_object();
12502 case EXPRESSION_UNARY:
12503 // If there is a local variable around with the same name as
12504 // the field, and this occurs in the closure, then the
12505 // parser may turn the field reference into an indirection
12506 // through the closure. FIXME: This is a mess.
12509 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12510 if (ue->op() == OPERATOR_MULT)
12512 Field_reference_expression* fre =
12513 ue->operand()->field_reference_expression();
12517 fre->expr()->type()->deref()->struct_type();
12520 const Struct_field* sf = st->field(fre->field_index());
12521 name = sf->field_name();
12523 // See below. FIXME.
12524 if (!Gogo::is_hidden_name(name)
12528 if (gogo->lookup_global(name.c_str()) != NULL)
12529 name = gogo->pack_hidden_name(name, false);
12533 snprintf(buf, sizeof buf, "%u", fre->field_index());
12534 size_t buflen = strlen(buf);
12535 if (name.compare(name.length() - buflen, buflen, buf)
12538 name = name.substr(0, name.length() - buflen);
12553 error_at(name_expr->location(), "expected struct field name");
12554 return Expression::make_error(location);
12561 // A predefined name won't be packed. If it starts with a
12562 // lower case letter we need to check for that case, because
12563 // the field name will be packed. FIXME.
12564 if (!Gogo::is_hidden_name(name)
12568 Named_object* gno = gogo->lookup_global(name.c_str());
12570 name = gogo->pack_hidden_name(name, false);
12574 unsigned int index;
12575 const Struct_field* sf = st->find_local_field(name, &index);
12578 error_at(name_expr->location(), "unknown field %qs in %qs",
12579 Gogo::message_name(name).c_str(),
12580 (type->named_type() != NULL
12581 ? type->named_type()->message_name().c_str()
12582 : "unnamed struct"));
12583 return Expression::make_error(location);
12585 if (vals[index] != NULL)
12587 error_at(name_expr->location(),
12588 "duplicate value for field %qs in %qs",
12589 Gogo::message_name(name).c_str(),
12590 (type->named_type() != NULL
12591 ? type->named_type()->message_name().c_str()
12592 : "unnamed struct"));
12593 return Expression::make_error(location);
12596 if (type->named_type() != NULL
12597 && type->named_type()->named_object()->package() != NULL
12598 && Gogo::is_hidden_name(sf->field_name()))
12599 error_at(name_expr->location(),
12600 "assignment of unexported field %qs in %qs literal",
12601 Gogo::message_name(sf->field_name()).c_str(),
12602 type->named_type()->message_name().c_str());
12605 traverse_order->push_back(index);
12608 Expression_list* list = new Expression_list;
12609 list->reserve(field_count);
12610 for (size_t i = 0; i < field_count; ++i)
12611 list->push_back(vals[i]);
12613 Struct_construction_expression* ret =
12614 new Struct_construction_expression(type, list, location);
12615 ret->set_traverse_order(traverse_order);
12619 // Used to sort an index/value array.
12621 class Index_value_compare
12625 operator()(const std::pair<unsigned long, Expression*>& a,
12626 const std::pair<unsigned long, Expression*>& b)
12627 { return a.first < b.first; }
12630 // Lower an array composite literal.
12633 Composite_literal_expression::lower_array(Type* type)
12635 Location location = this->location();
12636 if (this->vals_ == NULL || !this->has_keys_)
12637 return this->make_array(type, NULL, this->vals_);
12639 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12640 indexes->reserve(this->vals_->size());
12641 bool indexes_out_of_order = false;
12642 Expression_list* vals = new Expression_list();
12643 vals->reserve(this->vals_->size());
12644 unsigned long index = 0;
12645 Expression_list::const_iterator p = this->vals_->begin();
12646 while (p != this->vals_->end())
12648 Expression* index_expr = *p;
12651 go_assert(p != this->vals_->end());
12652 Expression* val = *p;
12656 if (index_expr == NULL)
12658 if (!indexes->empty())
12659 indexes->push_back(index);
12663 if (indexes->empty() && !vals->empty())
12665 for (size_t i = 0; i < vals->size(); ++i)
12666 indexes->push_back(i);
12669 Numeric_constant nc;
12670 if (!index_expr->numeric_constant_value(&nc))
12672 error_at(index_expr->location(),
12673 "index expression is not integer constant");
12674 return Expression::make_error(location);
12677 switch (nc.to_unsigned_long(&index))
12679 case Numeric_constant::NC_UL_VALID:
12681 case Numeric_constant::NC_UL_NOTINT:
12682 error_at(index_expr->location(),
12683 "index expression is not integer constant");
12684 return Expression::make_error(location);
12685 case Numeric_constant::NC_UL_NEGATIVE:
12686 error_at(index_expr->location(), "index expression is negative");
12687 return Expression::make_error(location);
12688 case Numeric_constant::NC_UL_BIG:
12689 error_at(index_expr->location(), "index value overflow");
12690 return Expression::make_error(location);
12695 Named_type* ntype = Type::lookup_integer_type("int");
12696 Integer_type* inttype = ntype->integer_type();
12697 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12698 && index >> (inttype->bits() - 1) != 0)
12700 error_at(index_expr->location(), "index value overflow");
12701 return Expression::make_error(location);
12704 if (std::find(indexes->begin(), indexes->end(), index)
12707 error_at(index_expr->location(), "duplicate value for index %lu",
12709 return Expression::make_error(location);
12712 if (!indexes->empty() && index < indexes->back())
12713 indexes_out_of_order = true;
12715 indexes->push_back(index);
12718 vals->push_back(val);
12723 if (indexes->empty())
12729 if (indexes_out_of_order)
12731 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12734 v.reserve(indexes->size());
12735 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12736 for (Expression_list::const_iterator pe = vals->begin();
12739 v.push_back(std::make_pair(*pi, *pe));
12741 std::sort(v.begin(), v.end(), Index_value_compare());
12745 indexes = new std::vector<unsigned long>();
12746 indexes->reserve(v.size());
12747 vals = new Expression_list();
12748 vals->reserve(v.size());
12750 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12752 indexes->push_back(p->first);
12753 vals->push_back(p->second);
12757 return this->make_array(type, indexes, vals);
12760 // Actually build the array composite literal. This handles
12764 Composite_literal_expression::make_array(
12766 const std::vector<unsigned long>* indexes,
12767 Expression_list* vals)
12769 Location location = this->location();
12770 Array_type* at = type->array_type();
12772 if (at->length() != NULL && at->length()->is_nil_expression())
12777 else if (indexes != NULL)
12778 size = indexes->back() + 1;
12781 size = vals->size();
12782 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12783 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12784 && size >> (it->bits() - 1) != 0)
12786 error_at(location, "too many elements in composite literal");
12787 return Expression::make_error(location);
12792 mpz_init_set_ui(vlen, size);
12793 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12795 at = Type::make_array_type(at->element_type(), elen);
12798 else if (at->length() != NULL
12799 && !at->length()->is_error_expression()
12800 && this->vals_ != NULL)
12802 Numeric_constant nc;
12804 if (at->length()->numeric_constant_value(&nc)
12805 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12807 if (indexes == NULL)
12809 if (this->vals_->size() > val)
12811 error_at(location, "too many elements in composite literal");
12812 return Expression::make_error(location);
12817 unsigned long max = indexes->back();
12821 ("some element keys in composite literal "
12822 "are out of range"));
12823 return Expression::make_error(location);
12829 if (at->length() != NULL)
12830 return new Fixed_array_construction_expression(type, indexes, vals,
12833 return new Open_array_construction_expression(type, indexes, vals,
12837 // Lower a map composite literal.
12840 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12841 Statement_inserter* inserter,
12844 Location location = this->location();
12845 if (this->vals_ != NULL)
12847 if (!this->has_keys_)
12849 error_at(location, "map composite literal must have keys");
12850 return Expression::make_error(location);
12853 for (Expression_list::iterator p = this->vals_->begin();
12854 p != this->vals_->end();
12860 error_at((*p)->location(),
12861 "map composite literal must have keys for every value");
12862 return Expression::make_error(location);
12864 // Make sure we have lowered the key; it may not have been
12865 // lowered in order to handle keys for struct composite
12866 // literals. Lower it now to get the right error message.
12867 if ((*p)->unknown_expression() != NULL)
12869 (*p)->unknown_expression()->clear_is_composite_literal_key();
12870 gogo->lower_expression(function, inserter, &*p);
12871 go_assert((*p)->is_error_expression());
12872 return Expression::make_error(location);
12877 return new Map_construction_expression(type, this->vals_, location);
12880 // Dump ast representation for a composite literal expression.
12883 Composite_literal_expression::do_dump_expression(
12884 Ast_dump_context* ast_dump_context) const
12886 ast_dump_context->ostream() << "composite(";
12887 ast_dump_context->dump_type(this->type_);
12888 ast_dump_context->ostream() << ", {";
12889 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12890 ast_dump_context->ostream() << "})";
12893 // Make a composite literal expression.
12896 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12897 Expression_list* vals,
12900 return new Composite_literal_expression(type, depth, has_keys, vals,
12904 // Return whether this expression is a composite literal.
12907 Expression::is_composite_literal() const
12909 switch (this->classification_)
12911 case EXPRESSION_COMPOSITE_LITERAL:
12912 case EXPRESSION_STRUCT_CONSTRUCTION:
12913 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12914 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12915 case EXPRESSION_MAP_CONSTRUCTION:
12922 // Return whether this expression is a composite literal which is not
12926 Expression::is_nonconstant_composite_literal() const
12928 switch (this->classification_)
12930 case EXPRESSION_STRUCT_CONSTRUCTION:
12932 const Struct_construction_expression *psce =
12933 static_cast<const Struct_construction_expression*>(this);
12934 return !psce->is_constant_struct();
12936 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12938 const Fixed_array_construction_expression *pace =
12939 static_cast<const Fixed_array_construction_expression*>(this);
12940 return !pace->is_constant_array();
12942 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12944 const Open_array_construction_expression *pace =
12945 static_cast<const Open_array_construction_expression*>(this);
12946 return !pace->is_constant_array();
12948 case EXPRESSION_MAP_CONSTRUCTION:
12955 // Return true if this is a reference to a local variable.
12958 Expression::is_local_variable() const
12960 const Var_expression* ve = this->var_expression();
12963 const Named_object* no = ve->named_object();
12964 return (no->is_result_variable()
12965 || (no->is_variable() && !no->var_value()->is_global()));
12968 // Class Type_guard_expression.
12973 Type_guard_expression::do_traverse(Traverse* traverse)
12975 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12976 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12977 return TRAVERSE_EXIT;
12978 return TRAVERSE_CONTINUE;
12981 // Check types of a type guard expression. The expression must have
12982 // an interface type, but the actual type conversion is checked at run
12986 Type_guard_expression::do_check_types(Gogo*)
12988 Type* expr_type = this->expr_->type();
12989 if (expr_type->interface_type() == NULL)
12991 if (!expr_type->is_error() && !this->type_->is_error())
12992 this->report_error(_("type assertion only valid for interface types"));
12993 this->set_is_error();
12995 else if (this->type_->interface_type() == NULL)
12997 std::string reason;
12998 if (!expr_type->interface_type()->implements_interface(this->type_,
13001 if (!this->type_->is_error())
13003 if (reason.empty())
13004 this->report_error(_("impossible type assertion: "
13005 "type does not implement interface"));
13007 error_at(this->location(),
13008 ("impossible type assertion: "
13009 "type does not implement interface (%s)"),
13012 this->set_is_error();
13017 // Return a tree for a type guard expression.
13020 Type_guard_expression::do_get_tree(Translate_context* context)
13022 tree expr_tree = this->expr_->get_tree(context);
13023 if (expr_tree == error_mark_node)
13024 return error_mark_node;
13025 if (this->type_->interface_type() != NULL)
13026 return Expression::convert_interface_to_interface(context, this->type_,
13027 this->expr_->type(),
13031 return Expression::convert_for_assignment(context, this->type_,
13032 this->expr_->type(), expr_tree,
13036 // Dump ast representation for a type guard expression.
13039 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13042 this->expr_->dump_expression(ast_dump_context);
13043 ast_dump_context->ostream() << ".";
13044 ast_dump_context->dump_type(this->type_);
13047 // Make a type guard expression.
13050 Expression::make_type_guard(Expression* expr, Type* type,
13053 return new Type_guard_expression(expr, type, location);
13056 // Class Heap_composite_expression.
13058 // When you take the address of a composite literal, it is allocated
13059 // on the heap. This class implements that.
13061 class Heap_composite_expression : public Expression
13064 Heap_composite_expression(Expression* expr, Location location)
13065 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13071 do_traverse(Traverse* traverse)
13072 { return Expression::traverse(&this->expr_, traverse); }
13076 { return Type::make_pointer_type(this->expr_->type()); }
13079 do_determine_type(const Type_context*)
13080 { this->expr_->determine_type_no_context(); }
13085 return Expression::make_heap_composite(this->expr_->copy(),
13090 do_get_tree(Translate_context*);
13092 // We only export global objects, and the parser does not generate
13093 // this in global scope.
13095 do_export(Export*) const
13096 { go_unreachable(); }
13099 do_dump_expression(Ast_dump_context*) const;
13102 // The composite literal which is being put on the heap.
13106 // Return a tree which allocates a composite literal on the heap.
13109 Heap_composite_expression::do_get_tree(Translate_context* context)
13111 tree expr_tree = this->expr_->get_tree(context);
13112 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13113 return error_mark_node;
13114 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13115 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13116 tree space = context->gogo()->allocate_memory(this->expr_->type(),
13117 expr_size, this->location());
13118 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13119 space = save_expr(space);
13120 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13122 TREE_THIS_NOTRAP(ref) = 1;
13123 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13124 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13126 SET_EXPR_LOCATION(ret, this->location().gcc_location());
13130 // Dump ast representation for a heap composite expression.
13133 Heap_composite_expression::do_dump_expression(
13134 Ast_dump_context* ast_dump_context) const
13136 ast_dump_context->ostream() << "&(";
13137 ast_dump_context->dump_expression(this->expr_);
13138 ast_dump_context->ostream() << ")";
13141 // Allocate a composite literal on the heap.
13144 Expression::make_heap_composite(Expression* expr, Location location)
13146 return new Heap_composite_expression(expr, location);
13149 // Class Receive_expression.
13151 // Return the type of a receive expression.
13154 Receive_expression::do_type()
13156 Channel_type* channel_type = this->channel_->type()->channel_type();
13157 if (channel_type == NULL)
13158 return Type::make_error_type();
13159 return channel_type->element_type();
13162 // Check types for a receive expression.
13165 Receive_expression::do_check_types(Gogo*)
13167 Type* type = this->channel_->type();
13168 if (type->is_error())
13170 this->set_is_error();
13173 if (type->channel_type() == NULL)
13175 this->report_error(_("expected channel"));
13178 if (!type->channel_type()->may_receive())
13180 this->report_error(_("invalid receive on send-only channel"));
13185 // Get a tree for a receive expression.
13188 Receive_expression::do_get_tree(Translate_context* context)
13190 Location loc = this->location();
13192 Channel_type* channel_type = this->channel_->type()->channel_type();
13193 if (channel_type == NULL)
13195 go_assert(this->channel_->type()->is_error());
13196 return error_mark_node;
13199 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13200 tree td_tree = td->get_tree(context);
13202 Type* element_type = channel_type->element_type();
13203 Btype* element_type_btype = element_type->get_backend(context->gogo());
13204 tree element_type_tree = type_to_tree(element_type_btype);
13206 tree channel = this->channel_->get_tree(context);
13207 if (element_type_tree == error_mark_node || channel == error_mark_node)
13208 return error_mark_node;
13210 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13213 // Dump ast representation for a receive expression.
13216 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13218 ast_dump_context->ostream() << " <- " ;
13219 ast_dump_context->dump_expression(channel_);
13222 // Make a receive expression.
13224 Receive_expression*
13225 Expression::make_receive(Expression* channel, Location location)
13227 return new Receive_expression(channel, location);
13230 // An expression which evaluates to a pointer to the type descriptor
13233 class Type_descriptor_expression : public Expression
13236 Type_descriptor_expression(Type* type, Location location)
13237 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13244 { return Type::make_type_descriptor_ptr_type(); }
13247 do_determine_type(const Type_context*)
13255 do_get_tree(Translate_context* context)
13257 return this->type_->type_descriptor_pointer(context->gogo(),
13262 do_dump_expression(Ast_dump_context*) const;
13265 // The type for which this is the descriptor.
13269 // Dump ast representation for a type descriptor expression.
13272 Type_descriptor_expression::do_dump_expression(
13273 Ast_dump_context* ast_dump_context) const
13275 ast_dump_context->dump_type(this->type_);
13278 // Make a type descriptor expression.
13281 Expression::make_type_descriptor(Type* type, Location location)
13283 return new Type_descriptor_expression(type, location);
13286 // An expression which evaluates to some characteristic of a type.
13287 // This is only used to initialize fields of a type descriptor. Using
13288 // a new expression class is slightly inefficient but gives us a good
13289 // separation between the frontend and the middle-end with regard to
13290 // how types are laid out.
13292 class Type_info_expression : public Expression
13295 Type_info_expression(Type* type, Type_info type_info)
13296 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13297 type_(type), type_info_(type_info)
13305 do_determine_type(const Type_context*)
13313 do_get_tree(Translate_context* context);
13316 do_dump_expression(Ast_dump_context*) const;
13319 // The type for which we are getting information.
13321 // What information we want.
13322 Type_info type_info_;
13325 // The type is chosen to match what the type descriptor struct
13329 Type_info_expression::do_type()
13331 switch (this->type_info_)
13333 case TYPE_INFO_SIZE:
13334 return Type::lookup_integer_type("uintptr");
13335 case TYPE_INFO_ALIGNMENT:
13336 case TYPE_INFO_FIELD_ALIGNMENT:
13337 return Type::lookup_integer_type("uint8");
13343 // Return type information in GENERIC.
13346 Type_info_expression::do_get_tree(Translate_context* context)
13348 Btype* btype = this->type_->get_backend(context->gogo());
13349 Gogo* gogo = context->gogo();
13351 switch (this->type_info_)
13353 case TYPE_INFO_SIZE:
13354 val = gogo->backend()->type_size(btype);
13356 case TYPE_INFO_ALIGNMENT:
13357 val = gogo->backend()->type_alignment(btype);
13359 case TYPE_INFO_FIELD_ALIGNMENT:
13360 val = gogo->backend()->type_field_alignment(btype);
13365 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13366 go_assert(val_type_tree != error_mark_node);
13367 return build_int_cstu(val_type_tree, val);
13370 // Dump ast representation for a type info expression.
13373 Type_info_expression::do_dump_expression(
13374 Ast_dump_context* ast_dump_context) const
13376 ast_dump_context->ostream() << "typeinfo(";
13377 ast_dump_context->dump_type(this->type_);
13378 ast_dump_context->ostream() << ",";
13379 ast_dump_context->ostream() <<
13380 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13381 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13382 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13384 ast_dump_context->ostream() << ")";
13387 // Make a type info expression.
13390 Expression::make_type_info(Type* type, Type_info type_info)
13392 return new Type_info_expression(type, type_info);
13395 // An expression which evaluates to the offset of a field within a
13396 // struct. This, like Type_info_expression, q.v., is only used to
13397 // initialize fields of a type descriptor.
13399 class Struct_field_offset_expression : public Expression
13402 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13403 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13404 Linemap::predeclared_location()),
13405 type_(type), field_(field)
13411 { return Type::lookup_integer_type("uintptr"); }
13414 do_determine_type(const Type_context*)
13422 do_get_tree(Translate_context* context);
13425 do_dump_expression(Ast_dump_context*) const;
13428 // The type of the struct.
13429 Struct_type* type_;
13431 const Struct_field* field_;
13434 // Return a struct field offset in GENERIC.
13437 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13439 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13440 if (type_tree == error_mark_node)
13441 return error_mark_node;
13443 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13444 go_assert(val_type_tree != error_mark_node);
13446 const Struct_field_list* fields = this->type_->fields();
13447 tree struct_field_tree = TYPE_FIELDS(type_tree);
13448 Struct_field_list::const_iterator p;
13449 for (p = fields->begin();
13450 p != fields->end();
13451 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13453 go_assert(struct_field_tree != NULL_TREE);
13454 if (&*p == this->field_)
13457 go_assert(&*p == this->field_);
13459 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13460 byte_position(struct_field_tree));
13463 // Dump ast representation for a struct field offset expression.
13466 Struct_field_offset_expression::do_dump_expression(
13467 Ast_dump_context* ast_dump_context) const
13469 ast_dump_context->ostream() << "unsafe.Offsetof(";
13470 ast_dump_context->dump_type(this->type_);
13471 ast_dump_context->ostream() << '.';
13472 ast_dump_context->ostream() <<
13473 Gogo::message_name(this->field_->field_name());
13474 ast_dump_context->ostream() << ")";
13477 // Make an expression for a struct field offset.
13480 Expression::make_struct_field_offset(Struct_type* type,
13481 const Struct_field* field)
13483 return new Struct_field_offset_expression(type, field);
13486 // An expression which evaluates to a pointer to the map descriptor of
13489 class Map_descriptor_expression : public Expression
13492 Map_descriptor_expression(Map_type* type, Location location)
13493 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13500 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13503 do_determine_type(const Type_context*)
13511 do_get_tree(Translate_context* context)
13513 return this->type_->map_descriptor_pointer(context->gogo(),
13518 do_dump_expression(Ast_dump_context*) const;
13521 // The type for which this is the descriptor.
13525 // Dump ast representation for a map descriptor expression.
13528 Map_descriptor_expression::do_dump_expression(
13529 Ast_dump_context* ast_dump_context) const
13531 ast_dump_context->ostream() << "map_descriptor(";
13532 ast_dump_context->dump_type(this->type_);
13533 ast_dump_context->ostream() << ")";
13536 // Make a map descriptor expression.
13539 Expression::make_map_descriptor(Map_type* type, Location location)
13541 return new Map_descriptor_expression(type, location);
13544 // An expression which evaluates to the address of an unnamed label.
13546 class Label_addr_expression : public Expression
13549 Label_addr_expression(Label* label, Location location)
13550 : Expression(EXPRESSION_LABEL_ADDR, location),
13557 { return Type::make_pointer_type(Type::make_void_type()); }
13560 do_determine_type(const Type_context*)
13565 { return new Label_addr_expression(this->label_, this->location()); }
13568 do_get_tree(Translate_context* context)
13570 return expr_to_tree(this->label_->get_addr(context, this->location()));
13574 do_dump_expression(Ast_dump_context* ast_dump_context) const
13575 { ast_dump_context->ostream() << this->label_->name(); }
13578 // The label whose address we are taking.
13582 // Make an expression for the address of an unnamed label.
13585 Expression::make_label_addr(Label* label, Location location)
13587 return new Label_addr_expression(label, location);
13590 // Import an expression. This comes at the end in order to see the
13591 // various class definitions.
13594 Expression::import_expression(Import* imp)
13596 int c = imp->peek_char();
13597 if (imp->match_c_string("- ")
13598 || imp->match_c_string("! ")
13599 || imp->match_c_string("^ "))
13600 return Unary_expression::do_import(imp);
13602 return Binary_expression::do_import(imp);
13603 else if (imp->match_c_string("true")
13604 || imp->match_c_string("false"))
13605 return Boolean_expression::do_import(imp);
13607 return String_expression::do_import(imp);
13608 else if (c == '-' || (c >= '0' && c <= '9'))
13610 // This handles integers, floats and complex constants.
13611 return Integer_expression::do_import(imp);
13613 else if (imp->match_c_string("nil"))
13614 return Nil_expression::do_import(imp);
13615 else if (imp->match_c_string("convert"))
13616 return Type_conversion_expression::do_import(imp);
13619 error_at(imp->location(), "import error: expected expression");
13620 return Expression::make_error(imp->location());
13624 // Class Expression_list.
13626 // Traverse the list.
13629 Expression_list::traverse(Traverse* traverse)
13631 for (Expression_list::iterator p = this->begin();
13637 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13638 return TRAVERSE_EXIT;
13641 return TRAVERSE_CONTINUE;
13647 Expression_list::copy()
13649 Expression_list* ret = new Expression_list();
13650 for (Expression_list::iterator p = this->begin();
13655 ret->push_back(NULL);
13657 ret->push_back((*p)->copy());
13662 // Return whether an expression list has an error expression.
13665 Expression_list::contains_error() const
13667 for (Expression_list::const_iterator p = this->begin();
13670 if (*p != NULL && (*p)->is_error_expression())
13675 // Class Numeric_constant.
13679 Numeric_constant::~Numeric_constant()
13684 // Copy constructor.
13686 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13687 : classification_(a.classification_), type_(a.type_)
13689 switch (a.classification_)
13695 mpz_init_set(this->u_.int_val, a.u_.int_val);
13698 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13701 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13703 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13711 // Assignment operator.
13714 Numeric_constant::operator=(const Numeric_constant& a)
13717 this->classification_ = a.classification_;
13718 this->type_ = a.type_;
13719 switch (a.classification_)
13725 mpz_init_set(this->u_.int_val, a.u_.int_val);
13728 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13731 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13733 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13742 // Clear the contents.
13745 Numeric_constant::clear()
13747 switch (this->classification_)
13753 mpz_clear(this->u_.int_val);
13756 mpfr_clear(this->u_.float_val);
13759 mpfr_clear(this->u_.complex_val.real);
13760 mpfr_clear(this->u_.complex_val.imag);
13765 this->classification_ = NC_INVALID;
13768 // Set to an unsigned long value.
13771 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13774 this->classification_ = NC_INT;
13775 this->type_ = type;
13776 mpz_init_set_ui(this->u_.int_val, val);
13779 // Set to an integer value.
13782 Numeric_constant::set_int(Type* type, const mpz_t val)
13785 this->classification_ = NC_INT;
13786 this->type_ = type;
13787 mpz_init_set(this->u_.int_val, val);
13790 // Set to a rune value.
13793 Numeric_constant::set_rune(Type* type, const mpz_t val)
13796 this->classification_ = NC_RUNE;
13797 this->type_ = type;
13798 mpz_init_set(this->u_.int_val, val);
13801 // Set to a floating point value.
13804 Numeric_constant::set_float(Type* type, const mpfr_t val)
13807 this->classification_ = NC_FLOAT;
13808 this->type_ = type;
13809 // Numeric constants do not have negative zero values, so remove
13810 // them here. They also don't have infinity or NaN values, but we
13811 // should never see them here.
13812 if (mpfr_zero_p(val))
13813 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
13815 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13818 // Set to a complex value.
13821 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13824 this->classification_ = NC_COMPLEX;
13825 this->type_ = type;
13826 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13827 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13830 // Get an int value.
13833 Numeric_constant::get_int(mpz_t* val) const
13835 go_assert(this->is_int());
13836 mpz_init_set(*val, this->u_.int_val);
13839 // Get a rune value.
13842 Numeric_constant::get_rune(mpz_t* val) const
13844 go_assert(this->is_rune());
13845 mpz_init_set(*val, this->u_.int_val);
13848 // Get a floating point value.
13851 Numeric_constant::get_float(mpfr_t* val) const
13853 go_assert(this->is_float());
13854 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13857 // Get a complex value.
13860 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13862 go_assert(this->is_complex());
13863 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13864 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13867 // Express value as unsigned long if possible.
13869 Numeric_constant::To_unsigned_long
13870 Numeric_constant::to_unsigned_long(unsigned long* val) const
13872 switch (this->classification_)
13876 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13878 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13880 if (!mpfr_zero_p(this->u_.complex_val.imag))
13881 return NC_UL_NOTINT;
13882 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13888 // Express integer value as unsigned long if possible.
13890 Numeric_constant::To_unsigned_long
13891 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13892 unsigned long *val) const
13894 if (mpz_sgn(ival) < 0)
13895 return NC_UL_NEGATIVE;
13896 unsigned long ui = mpz_get_ui(ival);
13897 if (mpz_cmp_ui(ival, ui) != 0)
13900 return NC_UL_VALID;
13903 // Express floating point value as unsigned long if possible.
13905 Numeric_constant::To_unsigned_long
13906 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13907 unsigned long *val) const
13909 if (!mpfr_integer_p(fval))
13910 return NC_UL_NOTINT;
13913 mpfr_get_z(ival, fval, GMP_RNDN);
13914 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13919 // Convert value to integer if possible.
13922 Numeric_constant::to_int(mpz_t* val) const
13924 switch (this->classification_)
13928 mpz_init_set(*val, this->u_.int_val);
13931 if (!mpfr_integer_p(this->u_.float_val))
13934 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13937 if (!mpfr_zero_p(this->u_.complex_val.imag)
13938 || !mpfr_integer_p(this->u_.complex_val.real))
13941 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13948 // Convert value to floating point if possible.
13951 Numeric_constant::to_float(mpfr_t* val) const
13953 switch (this->classification_)
13957 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13960 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13963 if (!mpfr_zero_p(this->u_.complex_val.imag))
13965 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13972 // Convert value to complex.
13975 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13977 switch (this->classification_)
13981 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13982 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13985 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13986 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13989 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13990 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
14000 Numeric_constant::type() const
14002 if (this->type_ != NULL)
14003 return this->type_;
14004 switch (this->classification_)
14007 return Type::make_abstract_integer_type();
14009 return Type::make_abstract_character_type();
14011 return Type::make_abstract_float_type();
14013 return Type::make_abstract_complex_type();
14019 // If the constant can be expressed in TYPE, then set the type of the
14020 // constant to TYPE and return true. Otherwise return false, and, if
14021 // ISSUE_ERROR is true, report an appropriate error message.
14024 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
14029 else if (type->integer_type() != NULL)
14030 ret = this->check_int_type(type->integer_type(), issue_error, loc);
14031 else if (type->float_type() != NULL)
14032 ret = this->check_float_type(type->float_type(), issue_error, loc);
14033 else if (type->complex_type() != NULL)
14034 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
14038 this->type_ = type;
14042 // Check whether the constant can be expressed in an integer type.
14045 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
14046 Location location) const
14049 switch (this->classification_)
14053 mpz_init_set(val, this->u_.int_val);
14057 if (!mpfr_integer_p(this->u_.float_val))
14060 error_at(location, "floating point constant truncated to integer");
14064 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
14068 if (!mpfr_integer_p(this->u_.complex_val.real)
14069 || !mpfr_zero_p(this->u_.complex_val.imag))
14072 error_at(location, "complex constant truncated to integer");
14076 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
14084 if (type->is_abstract())
14088 int bits = mpz_sizeinbase(val, 2);
14089 if (type->is_unsigned())
14091 // For an unsigned type we can only accept a nonnegative
14092 // number, and we must be able to represents at least BITS.
14093 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
14097 // For a signed type we need an extra bit to indicate the
14098 // sign. We have to handle the most negative integer
14100 ret = (bits + 1 <= type->bits()
14101 || (bits <= type->bits()
14102 && mpz_sgn(val) < 0
14103 && (mpz_scan1(val, 0)
14104 == static_cast<unsigned long>(type->bits() - 1))
14105 && mpz_scan0(val, type->bits()) == ULONG_MAX));
14109 if (!ret && issue_error)
14110 error_at(location, "integer constant overflow");
14115 // Check whether the constant can be expressed in a floating point
14119 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
14123 switch (this->classification_)
14127 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
14131 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
14135 if (!mpfr_zero_p(this->u_.complex_val.imag))
14138 error_at(location, "complex constant truncated to float");
14141 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
14149 if (type->is_abstract())
14151 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
14153 // A NaN or Infinity always fits in the range of the type.
14158 mp_exp_t exp = mpfr_get_exp(val);
14160 switch (type->bits())
14172 ret = exp <= max_exp;
14176 // Round the constant to the desired type.
14179 switch (type->bits())
14182 mpfr_set_prec(t, 24);
14185 mpfr_set_prec(t, 53);
14190 mpfr_set(t, val, GMP_RNDN);
14191 mpfr_set(val, t, GMP_RNDN);
14194 this->set_float(type, val);
14200 if (!ret && issue_error)
14201 error_at(location, "floating point constant overflow");
14206 // Check whether the constant can be expressed in a complex type.
14209 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
14212 if (type->is_abstract())
14216 switch (type->bits())
14230 switch (this->classification_)
14234 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
14235 mpfr_init_set_ui(imag, 0, GMP_RNDN);
14239 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
14240 mpfr_init_set_ui(imag, 0, GMP_RNDN);
14244 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
14245 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
14253 if (!mpfr_nan_p(real)
14254 && !mpfr_inf_p(real)
14255 && !mpfr_zero_p(real)
14256 && mpfr_get_exp(real) > max_exp)
14259 error_at(location, "complex real part overflow");
14263 if (!mpfr_nan_p(imag)
14264 && !mpfr_inf_p(imag)
14265 && !mpfr_zero_p(imag)
14266 && mpfr_get_exp(imag) > max_exp)
14269 error_at(location, "complex imaginary part overflow");
14275 // Round the constant to the desired type.
14278 switch (type->bits())
14281 mpfr_set_prec(t, 24);
14284 mpfr_set_prec(t, 53);
14289 mpfr_set(t, real, GMP_RNDN);
14290 mpfr_set(real, t, GMP_RNDN);
14291 mpfr_set(t, imag, GMP_RNDN);
14292 mpfr_set(imag, t, GMP_RNDN);
14295 this->set_complex(type, real, imag);
14304 // Return an Expression for this value.
14307 Numeric_constant::expression(Location loc) const
14309 switch (this->classification_)
14312 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
14314 return Expression::make_character(&this->u_.int_val, this->type_, loc);
14316 return Expression::make_float(&this->u_.float_val, this->type_, loc);
14318 return Expression::make_complex(&this->u_.complex_val.real,
14319 &this->u_.complex_val.imag,