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.
11 #ifndef ENABLE_BUILD_WITH_CXX
20 #include "tree-iterator.h"
25 #ifndef ENABLE_BUILD_WITH_CXX
34 #include "statements.h"
38 #include "expressions.h"
43 Expression::Expression(Expression_classification classification,
45 : classification_(classification), location_(location)
49 Expression::~Expression()
53 // Traverse the expressions.
56 Expression::traverse(Expression** pexpr, Traverse* traverse)
58 Expression* expr = *pexpr;
59 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
61 int t = traverse->expression(pexpr);
62 if (t == TRAVERSE_EXIT)
64 else if (t == TRAVERSE_SKIP_COMPONENTS)
65 return TRAVERSE_CONTINUE;
67 return expr->do_traverse(traverse);
70 // Traverse subexpressions of this expression.
73 Expression::traverse_subexpressions(Traverse* traverse)
75 return this->do_traverse(traverse);
78 // Default implementation for do_traverse for child classes.
81 Expression::do_traverse(Traverse*)
83 return TRAVERSE_CONTINUE;
86 // This virtual function is called by the parser if the value of this
87 // expression is being discarded. By default, we give an error.
88 // Expressions with side effects override.
91 Expression::do_discarding_value()
93 this->unused_value_error();
96 // This virtual function is called to export expressions. This will
97 // only be used by expressions which may be constant.
100 Expression::do_export(Export*) const
105 // Give an error saying that the value of the expression is not used.
108 Expression::unused_value_error()
110 error_at(this->location(), "value computed is not used");
113 // Note that this expression is an error. This is called by children
114 // when they discover an error.
117 Expression::set_is_error()
119 this->classification_ = EXPRESSION_ERROR;
122 // For children to call to report an error conveniently.
125 Expression::report_error(const char* msg)
127 error_at(this->location_, "%s", msg);
128 this->set_is_error();
131 // Set types of variables and constants. This is implemented by the
135 Expression::determine_type(const Type_context* context)
137 this->do_determine_type(context);
140 // Set types when there is no context.
143 Expression::determine_type_no_context()
145 Type_context context;
146 this->do_determine_type(&context);
149 // Return a tree handling any conversions which must be done during
153 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
154 Type* rhs_type, tree rhs_tree,
157 if (lhs_type->is_error() || rhs_type->is_error())
158 return error_mark_node;
160 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
161 return error_mark_node;
163 Gogo* gogo = context->gogo();
165 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
166 if (lhs_type_tree == error_mark_node)
167 return error_mark_node;
169 if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
171 if (rhs_type->interface_type() == NULL)
172 return Expression::convert_type_to_interface(context, lhs_type,
176 return Expression::convert_interface_to_interface(context, lhs_type,
180 else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
181 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
183 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
185 // Assigning nil to an open array.
186 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
188 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
190 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
191 tree field = TYPE_FIELDS(lhs_type_tree);
192 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
197 elt = VEC_quick_push(constructor_elt, init, NULL);
198 field = DECL_CHAIN(field);
199 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
204 elt = VEC_quick_push(constructor_elt, init, NULL);
205 field = DECL_CHAIN(field);
206 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
209 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
211 tree val = build_constructor(lhs_type_tree, init);
212 TREE_CONSTANT(val) = 1;
216 else if (rhs_type->is_nil_type())
218 // The left hand side should be a pointer type at the tree
220 go_assert(POINTER_TYPE_P(lhs_type_tree));
221 return fold_convert(lhs_type_tree, null_pointer_node);
223 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
225 // No conversion is needed.
228 else if (POINTER_TYPE_P(lhs_type_tree)
229 || INTEGRAL_TYPE_P(lhs_type_tree)
230 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
231 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
232 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
233 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
234 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
235 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
236 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
238 // Avoid confusion from zero sized variables which may be
239 // represented as non-zero-sized.
240 if (int_size_in_bytes(lhs_type_tree) == 0
241 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
244 // This conversion must be permitted by Go, or we wouldn't have
246 go_assert(int_size_in_bytes(lhs_type_tree)
247 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
248 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
249 lhs_type_tree, rhs_tree);
253 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
258 // Return a tree for a conversion from a non-interface type to an
262 Expression::convert_type_to_interface(Translate_context* context,
263 Type* lhs_type, Type* rhs_type,
264 tree rhs_tree, Location location)
266 Gogo* gogo = context->gogo();
267 Interface_type* lhs_interface_type = lhs_type->interface_type();
268 bool lhs_is_empty = lhs_interface_type->is_empty();
270 // Since RHS_TYPE is a static type, we can create the interface
271 // method table at compile time.
273 // When setting an interface to nil, we just set both fields to
275 if (rhs_type->is_nil_type())
277 Btype* lhs_btype = lhs_type->get_backend(gogo);
278 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
281 // This should have been checked already.
282 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
284 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
285 if (lhs_type_tree == error_mark_node)
286 return error_mark_node;
288 // An interface is a tuple. If LHS_TYPE is an empty interface type,
289 // then the first field is the type descriptor for RHS_TYPE.
290 // Otherwise it is the interface method table for RHS_TYPE.
291 tree first_field_value;
293 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
296 // Build the interface method table for this interface and this
297 // object type: a list of function pointers for each interface
299 Named_type* rhs_named_type = rhs_type->named_type();
300 bool is_pointer = false;
301 if (rhs_named_type == NULL)
303 rhs_named_type = rhs_type->deref()->named_type();
307 if (rhs_named_type == NULL)
308 method_table = null_pointer_node;
311 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
313 first_field_value = fold_convert_loc(location.gcc_location(),
314 const_ptr_type_node, method_table);
316 if (first_field_value == error_mark_node)
317 return error_mark_node;
319 // Start building a constructor for the value we will return.
321 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
323 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
324 tree field = TYPE_FIELDS(lhs_type_tree);
325 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
326 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
328 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
331 elt = VEC_quick_push(constructor_elt, init, NULL);
332 field = DECL_CHAIN(field);
333 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
336 if (rhs_type->points_to() != NULL)
338 // We are assigning a pointer to the interface; the interface
339 // holds the pointer itself.
340 elt->value = rhs_tree;
341 return build_constructor(lhs_type_tree, init);
344 // We are assigning a non-pointer value to the interface; the
345 // interface gets a copy of the value in the heap.
347 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
349 tree space = gogo->allocate_memory(rhs_type, object_size, location);
350 space = fold_convert_loc(location.gcc_location(),
351 build_pointer_type(TREE_TYPE(rhs_tree)), space);
352 space = save_expr(space);
354 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
355 TREE_THIS_NOTRAP(ref) = 1;
356 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
357 void_type_node, ref, rhs_tree);
359 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
362 return build2(COMPOUND_EXPR, lhs_type_tree, set,
363 build_constructor(lhs_type_tree, init));
366 // Return a tree for the type descriptor of RHS_TREE, which has
367 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
371 Expression::get_interface_type_descriptor(Translate_context*,
372 Type* rhs_type, tree rhs_tree,
375 tree rhs_type_tree = TREE_TYPE(rhs_tree);
376 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
377 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
378 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
380 if (rhs_type->interface_type()->is_empty())
382 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
383 "__type_descriptor") == 0);
387 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
389 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
391 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
392 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
393 tree f = TYPE_FIELDS(TREE_TYPE(v1));
394 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
396 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
398 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
399 v, fold_convert_loc(location.gcc_location(),
402 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
404 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
408 // Return a tree for the conversion of an interface type to an
412 Expression::convert_interface_to_interface(Translate_context* context,
413 Type *lhs_type, Type *rhs_type,
414 tree rhs_tree, bool for_type_guard,
417 Gogo* gogo = context->gogo();
418 Interface_type* lhs_interface_type = lhs_type->interface_type();
419 bool lhs_is_empty = lhs_interface_type->is_empty();
421 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
422 if (lhs_type_tree == error_mark_node)
423 return error_mark_node;
425 // In the general case this requires runtime examination of the type
426 // method table to match it up with the interface methods.
428 // FIXME: If all of the methods in the right hand side interface
429 // also appear in the left hand side interface, then we don't need
430 // to do a runtime check, although we still need to build a new
433 // Get the type descriptor for the right hand side. This will be
434 // NULL for a nil interface.
436 if (!DECL_P(rhs_tree))
437 rhs_tree = save_expr(rhs_tree);
439 tree rhs_type_descriptor =
440 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
443 // The result is going to be a two element constructor.
445 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
447 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
448 tree field = TYPE_FIELDS(lhs_type_tree);
453 // A type assertion fails when converting a nil interface.
454 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
456 static tree assert_interface_decl;
457 tree call = Gogo::call_builtin(&assert_interface_decl,
459 "__go_assert_interface",
462 TREE_TYPE(lhs_type_descriptor),
464 TREE_TYPE(rhs_type_descriptor),
465 rhs_type_descriptor);
466 if (call == error_mark_node)
467 return error_mark_node;
468 // This will panic if the interface conversion fails.
469 TREE_NOTHROW(assert_interface_decl) = 0;
470 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
473 else if (lhs_is_empty)
475 // A convertion to an empty interface always succeeds, and the
476 // first field is just the type descriptor of the object.
477 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
478 "__type_descriptor") == 0);
479 elt->value = fold_convert_loc(location.gcc_location(),
480 TREE_TYPE(field), rhs_type_descriptor);
484 // A conversion to a non-empty interface may fail, but unlike a
485 // type assertion converting nil will always succeed.
486 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
488 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
490 static tree convert_interface_decl;
491 tree call = Gogo::call_builtin(&convert_interface_decl,
493 "__go_convert_interface",
496 TREE_TYPE(lhs_type_descriptor),
498 TREE_TYPE(rhs_type_descriptor),
499 rhs_type_descriptor);
500 if (call == error_mark_node)
501 return error_mark_node;
502 // This will panic if the interface conversion fails.
503 TREE_NOTHROW(convert_interface_decl) = 0;
504 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
508 // The second field is simply the object pointer.
510 elt = VEC_quick_push(constructor_elt, init, NULL);
511 field = DECL_CHAIN(field);
512 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
515 tree rhs_type_tree = TREE_TYPE(rhs_tree);
516 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
517 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
518 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
519 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
522 return build_constructor(lhs_type_tree, init);
525 // Return a tree for the conversion of an interface type to a
526 // non-interface type.
529 Expression::convert_interface_to_type(Translate_context* context,
530 Type *lhs_type, Type* rhs_type,
531 tree rhs_tree, Location location)
533 Gogo* gogo = context->gogo();
534 tree rhs_type_tree = TREE_TYPE(rhs_tree);
536 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
537 if (lhs_type_tree == error_mark_node)
538 return error_mark_node;
540 // Call a function to check that the type is valid. The function
541 // will panic with an appropriate runtime type error if the type is
544 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
546 if (!DECL_P(rhs_tree))
547 rhs_tree = save_expr(rhs_tree);
549 tree rhs_type_descriptor =
550 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
553 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
556 static tree check_interface_type_decl;
557 tree call = Gogo::call_builtin(&check_interface_type_decl,
559 "__go_check_interface_type",
562 TREE_TYPE(lhs_type_descriptor),
564 TREE_TYPE(rhs_type_descriptor),
566 TREE_TYPE(rhs_inter_descriptor),
567 rhs_inter_descriptor);
568 if (call == error_mark_node)
569 return error_mark_node;
570 // This call will panic if the conversion is invalid.
571 TREE_NOTHROW(check_interface_type_decl) = 0;
573 // If the call succeeds, pull out the value.
574 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
575 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
576 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
577 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
580 // If the value is a pointer, then it is the value we want.
581 // Otherwise it points to the value.
582 if (lhs_type->points_to() == NULL)
584 val = fold_convert_loc(location.gcc_location(),
585 build_pointer_type(lhs_type_tree), val);
586 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
589 return build2(COMPOUND_EXPR, lhs_type_tree, call,
590 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
593 // Convert an expression to a tree. This is implemented by the child
594 // class. Not that it is not in general safe to call this multiple
595 // times for a single expression, but that we don't catch such errors.
598 Expression::get_tree(Translate_context* context)
600 // The child may have marked this expression as having an error.
601 if (this->classification_ == EXPRESSION_ERROR)
602 return error_mark_node;
604 return this->do_get_tree(context);
607 // Return a tree for VAL in TYPE.
610 Expression::integer_constant_tree(mpz_t val, tree type)
612 if (type == error_mark_node)
613 return error_mark_node;
614 else if (TREE_CODE(type) == INTEGER_TYPE)
615 return double_int_to_tree(type,
616 mpz_get_double_int(type, val, true));
617 else if (TREE_CODE(type) == REAL_TYPE)
620 mpfr_init_set_z(fval, val, GMP_RNDN);
621 tree ret = Expression::float_constant_tree(fval, type);
625 else if (TREE_CODE(type) == COMPLEX_TYPE)
628 mpfr_init_set_z(fval, val, GMP_RNDN);
629 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
631 tree imag = build_real_from_int_cst(TREE_TYPE(type),
633 return build_complex(type, real, imag);
639 // Return a tree for VAL in TYPE.
642 Expression::float_constant_tree(mpfr_t val, tree type)
644 if (type == error_mark_node)
645 return error_mark_node;
646 else if (TREE_CODE(type) == INTEGER_TYPE)
650 mpfr_get_z(ival, val, GMP_RNDN);
651 tree ret = Expression::integer_constant_tree(ival, type);
655 else if (TREE_CODE(type) == REAL_TYPE)
658 real_from_mpfr(&r1, val, type, GMP_RNDN);
660 real_convert(&r2, TYPE_MODE(type), &r1);
661 return build_real(type, r2);
663 else if (TREE_CODE(type) == COMPLEX_TYPE)
666 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
668 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
669 tree imag = build_real_from_int_cst(TREE_TYPE(type),
671 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
677 // Return a tree for REAL/IMAG in TYPE.
680 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
682 if (type == error_mark_node)
683 return error_mark_node;
684 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
685 return Expression::float_constant_tree(real, type);
686 else if (TREE_CODE(type) == COMPLEX_TYPE)
689 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
691 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
694 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
696 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
698 return build_complex(type, build_real(TREE_TYPE(type), r2),
699 build_real(TREE_TYPE(type), r4));
705 // Return a tree which evaluates to true if VAL, of arbitrary integer
706 // type, is negative or is more than the maximum value of BOUND_TYPE.
707 // If SOFAR is not NULL, it is or'red into the result. The return
708 // value may be NULL if SOFAR is NULL.
711 Expression::check_bounds(tree val, tree bound_type, tree sofar,
714 tree val_type = TREE_TYPE(val);
715 tree ret = NULL_TREE;
717 if (!TYPE_UNSIGNED(val_type))
719 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
720 build_int_cst(val_type, 0));
721 if (ret == boolean_false_node)
725 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
726 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
727 go_assert(val_type_size != -1 && bound_type_size != -1);
728 if (val_type_size > bound_type_size
729 || (val_type_size == bound_type_size
730 && TYPE_UNSIGNED(val_type)
731 && !TYPE_UNSIGNED(bound_type)))
733 tree max = TYPE_MAX_VALUE(bound_type);
734 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
735 val, fold_convert_loc(loc.gcc_location(),
737 if (big == boolean_false_node)
739 else if (ret == NULL_TREE)
742 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
743 boolean_type_node, ret, big);
746 if (ret == NULL_TREE)
748 else if (sofar == NULL_TREE)
751 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
756 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
758 this->do_dump_expression(ast_dump_context);
761 // Error expressions. This are used to avoid cascading errors.
763 class Error_expression : public Expression
766 Error_expression(Location location)
767 : Expression(EXPRESSION_ERROR, location)
772 do_is_constant() const
776 do_numeric_constant_value(Numeric_constant* nc) const
778 nc->set_unsigned_long(NULL, 0);
783 do_discarding_value()
788 { return Type::make_error_type(); }
791 do_determine_type(const Type_context*)
799 do_is_addressable() const
803 do_get_tree(Translate_context*)
804 { return error_mark_node; }
807 do_dump_expression(Ast_dump_context*) const;
810 // Dump the ast representation for an error expression to a dump context.
813 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
815 ast_dump_context->ostream() << "_Error_" ;
819 Expression::make_error(Location location)
821 return new Error_expression(location);
824 // An expression which is really a type. This is used during parsing.
825 // It is an error if these survive after lowering.
828 Type_expression : public Expression
831 Type_expression(Type* type, Location location)
832 : Expression(EXPRESSION_TYPE, location),
838 do_traverse(Traverse* traverse)
839 { return Type::traverse(this->type_, traverse); }
843 { return this->type_; }
846 do_determine_type(const Type_context*)
850 do_check_types(Gogo*)
851 { this->report_error(_("invalid use of type")); }
858 do_get_tree(Translate_context*)
859 { go_unreachable(); }
861 void do_dump_expression(Ast_dump_context*) const;
864 // The type which we are representing as an expression.
869 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
871 ast_dump_context->dump_type(this->type_);
875 Expression::make_type(Type* type, Location location)
877 return new Type_expression(type, location);
880 // Class Parser_expression.
883 Parser_expression::do_type()
885 // We should never really ask for the type of a Parser_expression.
886 // However, it can happen, at least when we have an invalid const
887 // whose initializer refers to the const itself. In that case we
888 // may ask for the type when lowering the const itself.
889 go_assert(saw_errors());
890 return Type::make_error_type();
893 // Class Var_expression.
895 // Lower a variable expression. Here we just make sure that the
896 // initialization expression of the variable has been lowered. This
897 // ensures that we will be able to determine the type of the variable
901 Var_expression::do_lower(Gogo* gogo, Named_object* function,
902 Statement_inserter* inserter, int)
904 if (this->variable_->is_variable())
906 Variable* var = this->variable_->var_value();
907 // This is either a local variable or a global variable. A
908 // reference to a variable which is local to an enclosing
909 // function will be a reference to a field in a closure.
910 if (var->is_global())
915 var->lower_init_expression(gogo, function, inserter);
920 // Return the type of a reference to a variable.
923 Var_expression::do_type()
925 if (this->variable_->is_variable())
926 return this->variable_->var_value()->type();
927 else if (this->variable_->is_result_variable())
928 return this->variable_->result_var_value()->type();
933 // Determine the type of a reference to a variable.
936 Var_expression::do_determine_type(const Type_context*)
938 if (this->variable_->is_variable())
939 this->variable_->var_value()->determine_type();
942 // Something takes the address of this variable. This means that we
943 // may want to move the variable onto the heap.
946 Var_expression::do_address_taken(bool escapes)
950 if (this->variable_->is_variable())
951 this->variable_->var_value()->set_non_escaping_address_taken();
952 else if (this->variable_->is_result_variable())
953 this->variable_->result_var_value()->set_non_escaping_address_taken();
959 if (this->variable_->is_variable())
960 this->variable_->var_value()->set_address_taken();
961 else if (this->variable_->is_result_variable())
962 this->variable_->result_var_value()->set_address_taken();
968 // Get the tree for a reference to a variable.
971 Var_expression::do_get_tree(Translate_context* context)
973 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
974 context->function());
975 tree ret = var_to_tree(bvar);
976 if (ret == error_mark_node)
977 return error_mark_node;
979 if (this->variable_->is_variable())
980 is_in_heap = this->variable_->var_value()->is_in_heap();
981 else if (this->variable_->is_result_variable())
982 is_in_heap = this->variable_->result_var_value()->is_in_heap();
987 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
988 TREE_THIS_NOTRAP(ret) = 1;
993 // Ast dump for variable expression.
996 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
998 ast_dump_context->ostream() << this->variable_->name() ;
1001 // Make a reference to a variable in an expression.
1004 Expression::make_var_reference(Named_object* var, Location location)
1007 return Expression::make_sink(location);
1009 // FIXME: Creating a new object for each reference to a variable is
1011 return new Var_expression(var, location);
1014 // Class Temporary_reference_expression.
1019 Temporary_reference_expression::do_type()
1021 return this->statement_->type();
1024 // Called if something takes the address of this temporary variable.
1025 // We never have to move temporary variables to the heap, but we do
1026 // need to know that they must live in the stack rather than in a
1030 Temporary_reference_expression::do_address_taken(bool)
1032 this->statement_->set_is_address_taken();
1035 // Get a tree referring to the variable.
1038 Temporary_reference_expression::do_get_tree(Translate_context* context)
1040 Bvariable* bvar = this->statement_->get_backend_variable(context);
1042 // The gcc backend can't represent the same set of recursive types
1043 // that the Go frontend can. In some cases this means that a
1044 // temporary variable won't have the right backend type. Correct
1045 // that here by adding a type cast. We need to use base() to push
1046 // the circularity down one level.
1047 tree ret = var_to_tree(bvar);
1048 if (!this->is_lvalue_
1049 && POINTER_TYPE_P(TREE_TYPE(ret))
1050 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1052 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1053 tree type_tree = type_to_tree(type_btype);
1054 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1059 // Ast dump for temporary reference.
1062 Temporary_reference_expression::do_dump_expression(
1063 Ast_dump_context* ast_dump_context) const
1065 ast_dump_context->dump_temp_variable_name(this->statement_);
1068 // Make a reference to a temporary variable.
1070 Temporary_reference_expression*
1071 Expression::make_temporary_reference(Temporary_statement* statement,
1074 return new Temporary_reference_expression(statement, location);
1077 // Class Set_and_use_temporary_expression.
1082 Set_and_use_temporary_expression::do_type()
1084 return this->statement_->type();
1087 // Take the address.
1090 Set_and_use_temporary_expression::do_address_taken(bool)
1092 this->statement_->set_is_address_taken();
1095 // Return the backend representation.
1098 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1100 Bvariable* bvar = this->statement_->get_backend_variable(context);
1101 tree var_tree = var_to_tree(bvar);
1102 tree expr_tree = this->expr_->get_tree(context);
1103 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1104 return error_mark_node;
1105 Location loc = this->location();
1106 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1107 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1108 var_tree, expr_tree),
1115 Set_and_use_temporary_expression::do_dump_expression(
1116 Ast_dump_context* ast_dump_context) const
1118 ast_dump_context->ostream() << '(';
1119 ast_dump_context->dump_temp_variable_name(this->statement_);
1120 ast_dump_context->ostream() << " = ";
1121 this->expr_->dump_expression(ast_dump_context);
1122 ast_dump_context->ostream() << ')';
1125 // Make a set-and-use temporary.
1127 Set_and_use_temporary_expression*
1128 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1129 Expression* expr, Location location)
1131 return new Set_and_use_temporary_expression(statement, expr, location);
1134 // A sink expression--a use of the blank identifier _.
1136 class Sink_expression : public Expression
1139 Sink_expression(Location location)
1140 : Expression(EXPRESSION_SINK, location),
1141 type_(NULL), var_(NULL_TREE)
1146 do_discarding_value()
1153 do_determine_type(const Type_context*);
1157 { return new Sink_expression(this->location()); }
1160 do_get_tree(Translate_context*);
1163 do_dump_expression(Ast_dump_context*) const;
1166 // The type of this sink variable.
1168 // The temporary variable we generate.
1172 // Return the type of a sink expression.
1175 Sink_expression::do_type()
1177 if (this->type_ == NULL)
1178 return Type::make_sink_type();
1182 // Determine the type of a sink expression.
1185 Sink_expression::do_determine_type(const Type_context* context)
1187 if (context->type != NULL)
1188 this->type_ = context->type;
1191 // Return a temporary variable for a sink expression. This will
1192 // presumably be a write-only variable which the middle-end will drop.
1195 Sink_expression::do_get_tree(Translate_context* context)
1197 if (this->var_ == NULL_TREE)
1199 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1200 Btype* bt = this->type_->get_backend(context->gogo());
1201 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1206 // Ast dump for sink expression.
1209 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1211 ast_dump_context->ostream() << "_" ;
1214 // Make a sink expression.
1217 Expression::make_sink(Location location)
1219 return new Sink_expression(location);
1222 // Class Func_expression.
1224 // FIXME: Can a function expression appear in a constant expression?
1225 // The value is unchanging. Initializing a constant to the address of
1226 // a function seems like it could work, though there might be little
1232 Func_expression::do_traverse(Traverse* traverse)
1234 return (this->closure_ == NULL
1236 : Expression::traverse(&this->closure_, traverse));
1239 // Return the type of a function expression.
1242 Func_expression::do_type()
1244 if (this->function_->is_function())
1245 return this->function_->func_value()->type();
1246 else if (this->function_->is_function_declaration())
1247 return this->function_->func_declaration_value()->type();
1252 // Get the tree for a function expression without evaluating the
1256 Func_expression::get_tree_without_closure(Gogo* gogo)
1258 Function_type* fntype;
1259 if (this->function_->is_function())
1260 fntype = this->function_->func_value()->type();
1261 else if (this->function_->is_function_declaration())
1262 fntype = this->function_->func_declaration_value()->type();
1266 // Builtin functions are handled specially by Call_expression. We
1267 // can't take their address.
1268 if (fntype->is_builtin())
1270 error_at(this->location(),
1271 "invalid use of special builtin function %qs; must be called",
1272 this->function_->name().c_str());
1273 return error_mark_node;
1276 Named_object* no = this->function_;
1278 tree id = no->get_id(gogo);
1279 if (id == error_mark_node)
1280 return error_mark_node;
1283 if (no->is_function())
1284 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1285 else if (no->is_function_declaration())
1286 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1290 if (fndecl == error_mark_node)
1291 return error_mark_node;
1293 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1296 // Get the tree for a function expression. This is used when we take
1297 // the address of a function rather than simply calling it. If the
1298 // function has a closure, we must use a trampoline.
1301 Func_expression::do_get_tree(Translate_context* context)
1303 Gogo* gogo = context->gogo();
1305 tree fnaddr = this->get_tree_without_closure(gogo);
1306 if (fnaddr == error_mark_node)
1307 return error_mark_node;
1309 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1310 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1311 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1313 // For a normal non-nested function call, that is all we have to do.
1314 if (!this->function_->is_function()
1315 || this->function_->func_value()->enclosing() == NULL)
1317 go_assert(this->closure_ == NULL);
1321 // For a nested function call, we have to always allocate a
1322 // trampoline. If we don't always allocate, then closures will not
1323 // be reliably distinct.
1324 Expression* closure = this->closure_;
1326 if (closure == NULL)
1327 closure_tree = null_pointer_node;
1330 // Get the value of the closure. This will be a pointer to
1331 // space allocated on the heap.
1332 closure_tree = 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)));
1338 // Now we need to build some code on the heap. This code will load
1339 // the static chain pointer with the closure and then jump to the
1340 // body of the function. The normal gcc approach is to build the
1341 // code on the stack. Unfortunately we can not do that, as Go
1342 // permits us to return the function pointer.
1344 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1347 // Ast dump for function.
1350 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1352 ast_dump_context->ostream() << this->function_->name();
1353 if (this->closure_ != NULL)
1355 ast_dump_context->ostream() << " {closure = ";
1356 this->closure_->dump_expression(ast_dump_context);
1357 ast_dump_context->ostream() << "}";
1361 // Make a reference to a function in an expression.
1364 Expression::make_func_reference(Named_object* function, Expression* closure,
1367 return new Func_expression(function, closure, location);
1370 // Class Unknown_expression.
1372 // Return the name of an unknown expression.
1375 Unknown_expression::name() const
1377 return this->named_object_->name();
1380 // Lower a reference to an unknown name.
1383 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1385 Location location = this->location();
1386 Named_object* no = this->named_object_;
1388 if (!no->is_unknown())
1392 real = no->unknown_value()->real_named_object();
1395 if (this->is_composite_literal_key_)
1397 if (!this->no_error_message_)
1398 error_at(location, "reference to undefined name %qs",
1399 this->named_object_->message_name().c_str());
1400 return Expression::make_error(location);
1403 switch (real->classification())
1405 case Named_object::NAMED_OBJECT_CONST:
1406 return Expression::make_const_reference(real, location);
1407 case Named_object::NAMED_OBJECT_TYPE:
1408 return Expression::make_type(real->type_value(), location);
1409 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1410 if (this->is_composite_literal_key_)
1412 if (!this->no_error_message_)
1413 error_at(location, "reference to undefined type %qs",
1414 real->message_name().c_str());
1415 return Expression::make_error(location);
1416 case Named_object::NAMED_OBJECT_VAR:
1417 real->var_value()->set_is_used();
1418 return Expression::make_var_reference(real, location);
1419 case Named_object::NAMED_OBJECT_FUNC:
1420 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1421 return Expression::make_func_reference(real, NULL, location);
1422 case Named_object::NAMED_OBJECT_PACKAGE:
1423 if (this->is_composite_literal_key_)
1425 if (!this->no_error_message_)
1426 error_at(location, "unexpected reference to package");
1427 return Expression::make_error(location);
1433 // Dump the ast representation for an unknown expression to a dump context.
1436 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1438 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1442 // Make a reference to an unknown name.
1445 Expression::make_unknown_reference(Named_object* no, Location location)
1447 return new Unknown_expression(no, location);
1450 // A boolean expression.
1452 class Boolean_expression : public Expression
1455 Boolean_expression(bool val, Location location)
1456 : Expression(EXPRESSION_BOOLEAN, location),
1457 val_(val), type_(NULL)
1465 do_is_constant() const
1472 do_determine_type(const Type_context*);
1479 do_get_tree(Translate_context*)
1480 { return this->val_ ? boolean_true_node : boolean_false_node; }
1483 do_export(Export* exp) const
1484 { exp->write_c_string(this->val_ ? "true" : "false"); }
1487 do_dump_expression(Ast_dump_context* ast_dump_context) const
1488 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1493 // The type as determined by context.
1500 Boolean_expression::do_type()
1502 if (this->type_ == NULL)
1503 this->type_ = Type::make_boolean_type();
1507 // Set the type from the context.
1510 Boolean_expression::do_determine_type(const Type_context* context)
1512 if (this->type_ != NULL && !this->type_->is_abstract())
1514 else if (context->type != NULL && context->type->is_boolean_type())
1515 this->type_ = context->type;
1516 else if (!context->may_be_abstract)
1517 this->type_ = Type::lookup_bool_type();
1520 // Import a boolean constant.
1523 Boolean_expression::do_import(Import* imp)
1525 if (imp->peek_char() == 't')
1527 imp->require_c_string("true");
1528 return Expression::make_boolean(true, imp->location());
1532 imp->require_c_string("false");
1533 return Expression::make_boolean(false, imp->location());
1537 // Make a boolean expression.
1540 Expression::make_boolean(bool val, Location location)
1542 return new Boolean_expression(val, location);
1545 // Class String_expression.
1550 String_expression::do_type()
1552 if (this->type_ == NULL)
1553 this->type_ = Type::make_string_type();
1557 // Set the type from the context.
1560 String_expression::do_determine_type(const Type_context* context)
1562 if (this->type_ != NULL && !this->type_->is_abstract())
1564 else if (context->type != NULL && context->type->is_string_type())
1565 this->type_ = context->type;
1566 else if (!context->may_be_abstract)
1567 this->type_ = Type::lookup_string_type();
1570 // Build a string constant.
1573 String_expression::do_get_tree(Translate_context* context)
1575 return context->gogo()->go_string_constant_tree(this->val_);
1578 // Write string literal to string dump.
1581 String_expression::export_string(String_dump* exp,
1582 const String_expression* str)
1585 s.reserve(str->val_.length() * 4 + 2);
1587 for (std::string::const_iterator p = str->val_.begin();
1588 p != str->val_.end();
1591 if (*p == '\\' || *p == '"')
1596 else if (*p >= 0x20 && *p < 0x7f)
1598 else if (*p == '\n')
1600 else if (*p == '\t')
1605 unsigned char c = *p;
1606 unsigned int dig = c >> 4;
1607 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1609 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1613 exp->write_string(s);
1616 // Export a string expression.
1619 String_expression::do_export(Export* exp) const
1621 String_expression::export_string(exp, this);
1624 // Import a string expression.
1627 String_expression::do_import(Import* imp)
1629 imp->require_c_string("\"");
1633 int c = imp->get_char();
1634 if (c == '"' || c == -1)
1637 val += static_cast<char>(c);
1640 c = imp->get_char();
1641 if (c == '\\' || c == '"')
1642 val += static_cast<char>(c);
1649 c = imp->get_char();
1650 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1651 c = imp->get_char();
1652 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653 char v = (vh << 4) | vl;
1658 error_at(imp->location(), "bad string constant");
1659 return Expression::make_error(imp->location());
1663 return Expression::make_string(val, imp->location());
1666 // Ast dump for string expression.
1669 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1671 String_expression::export_string(ast_dump_context, this);
1674 // Make a string expression.
1677 Expression::make_string(const std::string& val, Location location)
1679 return new String_expression(val, location);
1682 // Make an integer expression.
1684 class Integer_expression : public Expression
1687 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1689 : Expression(EXPRESSION_INTEGER, location),
1690 type_(type), is_character_constant_(is_character_constant)
1691 { mpz_init_set(this->val_, *val); }
1696 // Write VAL to string dump.
1698 export_integer(String_dump* exp, const mpz_t val);
1700 // Write VAL to dump context.
1702 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1706 do_is_constant() const
1710 do_numeric_constant_value(Numeric_constant* nc) const;
1716 do_determine_type(const Type_context* context);
1719 do_check_types(Gogo*);
1722 do_get_tree(Translate_context*);
1727 if (this->is_character_constant_)
1728 return Expression::make_character(&this->val_, this->type_,
1731 return Expression::make_integer(&this->val_, this->type_,
1736 do_export(Export*) const;
1739 do_dump_expression(Ast_dump_context*) const;
1742 // The integer value.
1746 // Whether this is a character constant.
1747 bool is_character_constant_;
1750 // Return a numeric constant for this expression. We have to mark
1751 // this as a character when appropriate.
1754 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1756 if (this->is_character_constant_)
1757 nc->set_rune(this->type_, this->val_);
1759 nc->set_int(this->type_, this->val_);
1763 // Return the current type. If we haven't set the type yet, we return
1764 // an abstract integer type.
1767 Integer_expression::do_type()
1769 if (this->type_ == NULL)
1771 if (this->is_character_constant_)
1772 this->type_ = Type::make_abstract_character_type();
1774 this->type_ = Type::make_abstract_integer_type();
1779 // Set the type of the integer value. Here we may switch from an
1780 // abstract type to a real type.
1783 Integer_expression::do_determine_type(const Type_context* context)
1785 if (this->type_ != NULL && !this->type_->is_abstract())
1787 else if (context->type != NULL && context->type->is_numeric_type())
1788 this->type_ = context->type;
1789 else if (!context->may_be_abstract)
1791 if (this->is_character_constant_)
1792 this->type_ = Type::lookup_integer_type("int32");
1794 this->type_ = Type::lookup_integer_type("int");
1798 // Check the type of an integer constant.
1801 Integer_expression::do_check_types(Gogo*)
1803 Type* type = this->type_;
1806 Numeric_constant nc;
1807 if (this->is_character_constant_)
1808 nc.set_rune(NULL, this->val_);
1810 nc.set_int(NULL, this->val_);
1811 if (!nc.set_type(type, true, this->location()))
1812 this->set_is_error();
1815 // Get a tree for an integer constant.
1818 Integer_expression::do_get_tree(Translate_context* context)
1820 Gogo* gogo = context->gogo();
1822 if (this->type_ != NULL && !this->type_->is_abstract())
1823 type = type_to_tree(this->type_->get_backend(gogo));
1824 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1826 // We are converting to an abstract floating point type.
1827 Type* ftype = Type::lookup_float_type("float64");
1828 type = type_to_tree(ftype->get_backend(gogo));
1830 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1832 // We are converting to an abstract complex type.
1833 Type* ctype = Type::lookup_complex_type("complex128");
1834 type = type_to_tree(ctype->get_backend(gogo));
1838 // If we still have an abstract type here, then this is being
1839 // used in a constant expression which didn't get reduced for
1840 // some reason. Use a type which will fit the value. We use <,
1841 // not <=, because we need an extra bit for the sign bit.
1842 int bits = mpz_sizeinbase(this->val_, 2);
1843 if (bits < INT_TYPE_SIZE)
1845 Type* t = Type::lookup_integer_type("int");
1846 type = type_to_tree(t->get_backend(gogo));
1850 Type* t = Type::lookup_integer_type("int64");
1851 type = type_to_tree(t->get_backend(gogo));
1854 type = long_long_integer_type_node;
1856 return Expression::integer_constant_tree(this->val_, type);
1859 // Write VAL to export data.
1862 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1864 char* s = mpz_get_str(NULL, 10, val);
1865 exp->write_c_string(s);
1869 // Export an integer in a constant expression.
1872 Integer_expression::do_export(Export* exp) const
1874 Integer_expression::export_integer(exp, this->val_);
1875 if (this->is_character_constant_)
1876 exp->write_c_string("'");
1877 // A trailing space lets us reliably identify the end of the number.
1878 exp->write_c_string(" ");
1881 // Import an integer, floating point, or complex value. This handles
1882 // all these types because they all start with digits.
1885 Integer_expression::do_import(Import* imp)
1887 std::string num = imp->read_identifier();
1888 imp->require_c_string(" ");
1889 if (!num.empty() && num[num.length() - 1] == 'i')
1892 size_t plus_pos = num.find('+', 1);
1893 size_t minus_pos = num.find('-', 1);
1895 if (plus_pos == std::string::npos)
1897 else if (minus_pos == std::string::npos)
1901 error_at(imp->location(), "bad number in import data: %qs",
1903 return Expression::make_error(imp->location());
1905 if (pos == std::string::npos)
1906 mpfr_set_ui(real, 0, GMP_RNDN);
1909 std::string real_str = num.substr(0, pos);
1910 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1912 error_at(imp->location(), "bad number in import data: %qs",
1914 return Expression::make_error(imp->location());
1918 std::string imag_str;
1919 if (pos == std::string::npos)
1922 imag_str = num.substr(pos);
1923 imag_str = imag_str.substr(0, imag_str.size() - 1);
1925 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1927 error_at(imp->location(), "bad number in import data: %qs",
1929 return Expression::make_error(imp->location());
1931 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1937 else if (num.find('.') == std::string::npos
1938 && num.find('E') == std::string::npos)
1940 bool is_character_constant = (!num.empty()
1941 && num[num.length() - 1] == '\'');
1942 if (is_character_constant)
1943 num = num.substr(0, num.length() - 1);
1945 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1947 error_at(imp->location(), "bad number in import data: %qs",
1949 return Expression::make_error(imp->location());
1952 if (is_character_constant)
1953 ret = Expression::make_character(&val, NULL, imp->location());
1955 ret = Expression::make_integer(&val, NULL, imp->location());
1962 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1964 error_at(imp->location(), "bad number in import data: %qs",
1966 return Expression::make_error(imp->location());
1968 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1973 // Ast dump for integer expression.
1976 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1978 if (this->is_character_constant_)
1979 ast_dump_context->ostream() << '\'';
1980 Integer_expression::export_integer(ast_dump_context, this->val_);
1981 if (this->is_character_constant_)
1982 ast_dump_context->ostream() << '\'';
1985 // Build a new integer value.
1988 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1990 return new Integer_expression(val, type, false, location);
1993 // Build a new character constant value.
1996 Expression::make_character(const mpz_t* val, Type* type, Location location)
1998 return new Integer_expression(val, type, true, location);
2003 class Float_expression : public Expression
2006 Float_expression(const mpfr_t* val, Type* type, Location location)
2007 : Expression(EXPRESSION_FLOAT, location),
2010 mpfr_init_set(this->val_, *val, GMP_RNDN);
2013 // Write VAL to export data.
2015 export_float(String_dump* exp, const mpfr_t val);
2017 // Write VAL to dump file.
2019 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2023 do_is_constant() const
2027 do_numeric_constant_value(Numeric_constant* nc) const
2029 nc->set_float(this->type_, this->val_);
2037 do_determine_type(const Type_context*);
2040 do_check_types(Gogo*);
2044 { return Expression::make_float(&this->val_, this->type_,
2045 this->location()); }
2048 do_get_tree(Translate_context*);
2051 do_export(Export*) const;
2054 do_dump_expression(Ast_dump_context*) const;
2057 // The floating point value.
2063 // Return the current type. If we haven't set the type yet, we return
2064 // an abstract float type.
2067 Float_expression::do_type()
2069 if (this->type_ == NULL)
2070 this->type_ = Type::make_abstract_float_type();
2074 // Set the type of the float value. Here we may switch from an
2075 // abstract type to a real type.
2078 Float_expression::do_determine_type(const Type_context* context)
2080 if (this->type_ != NULL && !this->type_->is_abstract())
2082 else if (context->type != NULL
2083 && (context->type->integer_type() != NULL
2084 || context->type->float_type() != NULL
2085 || context->type->complex_type() != NULL))
2086 this->type_ = context->type;
2087 else if (!context->may_be_abstract)
2088 this->type_ = Type::lookup_float_type("float64");
2091 // Check the type of a float value.
2094 Float_expression::do_check_types(Gogo*)
2096 Type* type = this->type_;
2099 Numeric_constant nc;
2100 nc.set_float(NULL, this->val_);
2101 if (!nc.set_type(this->type_, true, this->location()))
2102 this->set_is_error();
2105 // Get a tree for a float constant.
2108 Float_expression::do_get_tree(Translate_context* context)
2110 Gogo* gogo = context->gogo();
2112 if (this->type_ != NULL && !this->type_->is_abstract())
2113 type = type_to_tree(this->type_->get_backend(gogo));
2114 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2116 // We have an abstract integer type. We just hope for the best.
2117 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2121 // If we still have an abstract type here, then this is being
2122 // used in a constant expression which didn't get reduced. We
2123 // just use float64 and hope for the best.
2124 Type* ft = Type::lookup_float_type("float64");
2125 type = type_to_tree(ft->get_backend(gogo));
2127 return Expression::float_constant_tree(this->val_, type);
2130 // Write a floating point number to a string dump.
2133 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2136 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2138 exp->write_c_string("-");
2139 exp->write_c_string("0.");
2140 exp->write_c_string(*s == '-' ? s + 1 : s);
2143 snprintf(buf, sizeof buf, "E%ld", exponent);
2144 exp->write_c_string(buf);
2147 // Export a floating point number in a constant expression.
2150 Float_expression::do_export(Export* exp) const
2152 Float_expression::export_float(exp, this->val_);
2153 // A trailing space lets us reliably identify the end of the number.
2154 exp->write_c_string(" ");
2157 // Dump a floating point number to the dump file.
2160 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2162 Float_expression::export_float(ast_dump_context, this->val_);
2165 // Make a float expression.
2168 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2170 return new Float_expression(val, type, location);
2175 class Complex_expression : public Expression
2178 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2180 : Expression(EXPRESSION_COMPLEX, location),
2183 mpfr_init_set(this->real_, *real, GMP_RNDN);
2184 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2187 // Write REAL/IMAG to string dump.
2189 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2191 // Write REAL/IMAG to dump context.
2193 dump_complex(Ast_dump_context* ast_dump_context,
2194 const mpfr_t real, const mpfr_t val);
2198 do_is_constant() const
2202 do_numeric_constant_value(Numeric_constant* nc) const
2204 nc->set_complex(this->type_, this->real_, this->imag_);
2212 do_determine_type(const Type_context*);
2215 do_check_types(Gogo*);
2220 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2225 do_get_tree(Translate_context*);
2228 do_export(Export*) const;
2231 do_dump_expression(Ast_dump_context*) const;
2236 // The imaginary part;
2238 // The type if known.
2242 // Return the current type. If we haven't set the type yet, we return
2243 // an abstract complex type.
2246 Complex_expression::do_type()
2248 if (this->type_ == NULL)
2249 this->type_ = Type::make_abstract_complex_type();
2253 // Set the type of the complex value. Here we may switch from an
2254 // abstract type to a real type.
2257 Complex_expression::do_determine_type(const Type_context* context)
2259 if (this->type_ != NULL && !this->type_->is_abstract())
2261 else if (context->type != NULL
2262 && context->type->complex_type() != NULL)
2263 this->type_ = context->type;
2264 else if (!context->may_be_abstract)
2265 this->type_ = Type::lookup_complex_type("complex128");
2268 // Check the type of a complex value.
2271 Complex_expression::do_check_types(Gogo*)
2273 Type* type = this->type_;
2276 Numeric_constant nc;
2277 nc.set_complex(NULL, this->real_, this->imag_);
2278 if (!nc.set_type(this->type_, true, this->location()))
2279 this->set_is_error();
2282 // Get a tree for a complex constant.
2285 Complex_expression::do_get_tree(Translate_context* context)
2287 Gogo* gogo = context->gogo();
2289 if (this->type_ != NULL && !this->type_->is_abstract())
2290 type = type_to_tree(this->type_->get_backend(gogo));
2293 // If we still have an abstract type here, this this is being
2294 // used in a constant expression which didn't get reduced. We
2295 // just use complex128 and hope for the best.
2296 Type* ct = Type::lookup_complex_type("complex128");
2297 type = type_to_tree(ct->get_backend(gogo));
2299 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2302 // Write REAL/IMAG to export data.
2305 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2308 if (!mpfr_zero_p(real))
2310 Float_expression::export_float(exp, real);
2311 if (mpfr_sgn(imag) > 0)
2312 exp->write_c_string("+");
2314 Float_expression::export_float(exp, imag);
2315 exp->write_c_string("i");
2318 // Export a complex number in a constant expression.
2321 Complex_expression::do_export(Export* exp) const
2323 Complex_expression::export_complex(exp, this->real_, this->imag_);
2324 // A trailing space lets us reliably identify the end of the number.
2325 exp->write_c_string(" ");
2328 // Dump a complex expression to the dump file.
2331 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2333 Complex_expression::export_complex(ast_dump_context,
2338 // Make a complex expression.
2341 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2344 return new Complex_expression(real, imag, type, location);
2347 // Find a named object in an expression.
2349 class Find_named_object : public Traverse
2352 Find_named_object(Named_object* no)
2353 : Traverse(traverse_expressions),
2354 no_(no), found_(false)
2357 // Whether we found the object.
2360 { return this->found_; }
2364 expression(Expression**);
2367 // The object we are looking for.
2369 // Whether we found it.
2373 // A reference to a const in an expression.
2375 class Const_expression : public Expression
2378 Const_expression(Named_object* constant, Location location)
2379 : Expression(EXPRESSION_CONST_REFERENCE, location),
2380 constant_(constant), type_(NULL), seen_(false)
2385 { return this->constant_; }
2387 // Check that the initializer does not refer to the constant itself.
2389 check_for_init_loop();
2393 do_traverse(Traverse*);
2396 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2399 do_is_constant() const
2403 do_numeric_constant_value(Numeric_constant* nc) const;
2406 do_string_constant_value(std::string* val) const
2407 { return this->constant_->const_value()->expr()->string_constant_value(val); }
2412 // The type of a const is set by the declaration, not the use.
2414 do_determine_type(const Type_context*);
2417 do_check_types(Gogo*);
2424 do_get_tree(Translate_context* context);
2426 // When exporting a reference to a const as part of a const
2427 // expression, we export the value. We ignore the fact that it has
2430 do_export(Export* exp) const
2431 { this->constant_->const_value()->expr()->export_expression(exp); }
2434 do_dump_expression(Ast_dump_context*) const;
2438 Named_object* constant_;
2439 // The type of this reference. This is used if the constant has an
2442 // Used to prevent infinite recursion when a constant incorrectly
2443 // refers to itself.
2450 Const_expression::do_traverse(Traverse* traverse)
2452 if (this->type_ != NULL)
2453 return Type::traverse(this->type_, traverse);
2454 return TRAVERSE_CONTINUE;
2457 // Lower a constant expression. This is where we convert the
2458 // predeclared constant iota into an integer value.
2461 Const_expression::do_lower(Gogo* gogo, Named_object*,
2462 Statement_inserter*, int iota_value)
2464 if (this->constant_->const_value()->expr()->classification()
2467 if (iota_value == -1)
2469 error_at(this->location(),
2470 "iota is only defined in const declarations");
2474 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2475 Expression* ret = Expression::make_integer(&val, NULL,
2481 // Make sure that the constant itself has been lowered.
2482 gogo->lower_constant(this->constant_);
2487 // Return a numeric constant value.
2490 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2495 Expression* e = this->constant_->const_value()->expr();
2499 bool r = e->numeric_constant_value(nc);
2501 this->seen_ = false;
2504 if (this->type_ != NULL)
2505 ctype = this->type_;
2507 ctype = this->constant_->const_value()->type();
2508 if (r && ctype != NULL)
2510 if (!nc->set_type(ctype, false, this->location()))
2517 // Return the type of the const reference.
2520 Const_expression::do_type()
2522 if (this->type_ != NULL)
2525 Named_constant* nc = this->constant_->const_value();
2527 if (this->seen_ || nc->lowering())
2529 this->report_error(_("constant refers to itself"));
2530 this->type_ = Type::make_error_type();
2536 Type* ret = nc->type();
2540 this->seen_ = false;
2544 // During parsing, a named constant may have a NULL type, but we
2545 // must not return a NULL type here.
2546 ret = nc->expr()->type();
2548 this->seen_ = false;
2553 // Set the type of the const reference.
2556 Const_expression::do_determine_type(const Type_context* context)
2558 Type* ctype = this->constant_->const_value()->type();
2559 Type* cetype = (ctype != NULL
2561 : this->constant_->const_value()->expr()->type());
2562 if (ctype != NULL && !ctype->is_abstract())
2564 else if (context->type != NULL
2565 && context->type->is_numeric_type()
2566 && cetype->is_numeric_type())
2567 this->type_ = context->type;
2568 else if (context->type != NULL
2569 && context->type->is_string_type()
2570 && cetype->is_string_type())
2571 this->type_ = context->type;
2572 else if (context->type != NULL
2573 && context->type->is_boolean_type()
2574 && cetype->is_boolean_type())
2575 this->type_ = context->type;
2576 else if (!context->may_be_abstract)
2578 if (cetype->is_abstract())
2579 cetype = cetype->make_non_abstract_type();
2580 this->type_ = cetype;
2584 // Check for a loop in which the initializer of a constant refers to
2585 // the constant itself.
2588 Const_expression::check_for_init_loop()
2590 if (this->type_ != NULL && this->type_->is_error())
2595 this->report_error(_("constant refers to itself"));
2596 this->type_ = Type::make_error_type();
2600 Expression* init = this->constant_->const_value()->expr();
2601 Find_named_object find_named_object(this->constant_);
2604 Expression::traverse(&init, &find_named_object);
2605 this->seen_ = false;
2607 if (find_named_object.found())
2609 if (this->type_ == NULL || !this->type_->is_error())
2611 this->report_error(_("constant refers to itself"));
2612 this->type_ = Type::make_error_type();
2618 // Check types of a const reference.
2621 Const_expression::do_check_types(Gogo*)
2623 if (this->type_ != NULL && this->type_->is_error())
2626 this->check_for_init_loop();
2628 // Check that numeric constant fits in type.
2629 if (this->type_ != NULL && this->type_->is_numeric_type())
2631 Numeric_constant nc;
2632 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2634 if (!nc.set_type(this->type_, true, this->location()))
2635 this->set_is_error();
2640 // Return a tree for the const reference.
2643 Const_expression::do_get_tree(Translate_context* context)
2645 Gogo* gogo = context->gogo();
2647 if (this->type_ == NULL)
2648 type_tree = NULL_TREE;
2651 type_tree = type_to_tree(this->type_->get_backend(gogo));
2652 if (type_tree == error_mark_node)
2653 return error_mark_node;
2656 // If the type has been set for this expression, but the underlying
2657 // object is an abstract int or float, we try to get the abstract
2658 // value. Otherwise we may lose something in the conversion.
2659 if (this->type_ != NULL
2660 && this->type_->is_numeric_type()
2661 && (this->constant_->const_value()->type() == NULL
2662 || this->constant_->const_value()->type()->is_abstract()))
2664 Expression* expr = this->constant_->const_value()->expr();
2665 Numeric_constant nc;
2666 if (expr->numeric_constant_value(&nc)
2667 && nc.set_type(this->type_, false, this->location()))
2669 Expression* e = nc.expression(this->location());
2670 return e->get_tree(context);
2674 tree const_tree = this->constant_->get_tree(gogo, context->function());
2675 if (this->type_ == NULL
2676 || const_tree == error_mark_node
2677 || TREE_TYPE(const_tree) == error_mark_node)
2681 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2682 ret = fold_convert(type_tree, const_tree);
2683 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2684 ret = fold(convert_to_integer(type_tree, const_tree));
2685 else if (TREE_CODE(type_tree) == REAL_TYPE)
2686 ret = fold(convert_to_real(type_tree, const_tree));
2687 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2688 ret = fold(convert_to_complex(type_tree, const_tree));
2694 // Dump ast representation for constant expression.
2697 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2699 ast_dump_context->ostream() << this->constant_->name();
2702 // Make a reference to a constant in an expression.
2705 Expression::make_const_reference(Named_object* constant,
2708 return new Const_expression(constant, location);
2711 // Find a named object in an expression.
2714 Find_named_object::expression(Expression** pexpr)
2716 switch ((*pexpr)->classification())
2718 case Expression::EXPRESSION_CONST_REFERENCE:
2720 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2721 if (ce->named_object() == this->no_)
2724 // We need to check a constant initializer explicitly, as
2725 // loops here will not be caught by the loop checking for
2726 // variable initializers.
2727 ce->check_for_init_loop();
2729 return TRAVERSE_CONTINUE;
2732 case Expression::EXPRESSION_VAR_REFERENCE:
2733 if ((*pexpr)->var_expression()->named_object() == this->no_)
2735 return TRAVERSE_CONTINUE;
2736 case Expression::EXPRESSION_FUNC_REFERENCE:
2737 if ((*pexpr)->func_expression()->named_object() == this->no_)
2739 return TRAVERSE_CONTINUE;
2741 return TRAVERSE_CONTINUE;
2743 this->found_ = true;
2744 return TRAVERSE_EXIT;
2749 class Nil_expression : public Expression
2752 Nil_expression(Location location)
2753 : Expression(EXPRESSION_NIL, location)
2761 do_is_constant() const
2766 { return Type::make_nil_type(); }
2769 do_determine_type(const Type_context*)
2777 do_get_tree(Translate_context*)
2778 { return null_pointer_node; }
2781 do_export(Export* exp) const
2782 { exp->write_c_string("nil"); }
2785 do_dump_expression(Ast_dump_context* ast_dump_context) const
2786 { ast_dump_context->ostream() << "nil"; }
2789 // Import a nil expression.
2792 Nil_expression::do_import(Import* imp)
2794 imp->require_c_string("nil");
2795 return Expression::make_nil(imp->location());
2798 // Make a nil expression.
2801 Expression::make_nil(Location location)
2803 return new Nil_expression(location);
2806 // The value of the predeclared constant iota. This is little more
2807 // than a marker. This will be lowered to an integer in
2808 // Const_expression::do_lower, which is where we know the value that
2811 class Iota_expression : public Parser_expression
2814 Iota_expression(Location location)
2815 : Parser_expression(EXPRESSION_IOTA, location)
2820 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2821 { go_unreachable(); }
2823 // There should only ever be one of these.
2826 { go_unreachable(); }
2829 do_dump_expression(Ast_dump_context* ast_dump_context) const
2830 { ast_dump_context->ostream() << "iota"; }
2833 // Make an iota expression. This is only called for one case: the
2834 // value of the predeclared constant iota.
2837 Expression::make_iota()
2839 static Iota_expression iota_expression(Linemap::unknown_location());
2840 return &iota_expression;
2843 // A type conversion expression.
2845 class Type_conversion_expression : public Expression
2848 Type_conversion_expression(Type* type, Expression* expr,
2850 : Expression(EXPRESSION_CONVERSION, location),
2851 type_(type), expr_(expr), may_convert_function_types_(false)
2854 // Return the type to which we are converting.
2857 { return this->type_; }
2859 // Return the expression which we are converting.
2862 { return this->expr_; }
2864 // Permit converting from one function type to another. This is
2865 // used internally for method expressions.
2867 set_may_convert_function_types()
2869 this->may_convert_function_types_ = true;
2872 // Import a type conversion expression.
2878 do_traverse(Traverse* traverse);
2881 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2884 do_is_constant() const
2885 { return this->expr_->is_constant(); }
2888 do_numeric_constant_value(Numeric_constant*) const;
2891 do_string_constant_value(std::string*) const;
2895 { return this->type_; }
2898 do_determine_type(const Type_context*)
2900 Type_context subcontext(this->type_, false);
2901 this->expr_->determine_type(&subcontext);
2905 do_check_types(Gogo*);
2910 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2915 do_get_tree(Translate_context* context);
2918 do_export(Export*) const;
2921 do_dump_expression(Ast_dump_context*) const;
2924 // The type to convert to.
2926 // The expression to convert.
2928 // True if this is permitted to convert function types. This is
2929 // used internally for method expressions.
2930 bool may_convert_function_types_;
2936 Type_conversion_expression::do_traverse(Traverse* traverse)
2938 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2939 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2940 return TRAVERSE_EXIT;
2941 return TRAVERSE_CONTINUE;
2944 // Convert to a constant at lowering time.
2947 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2948 Statement_inserter*, int)
2950 Type* type = this->type_;
2951 Expression* val = this->expr_;
2952 Location location = this->location();
2954 if (type->is_numeric_type())
2956 Numeric_constant nc;
2957 if (val->numeric_constant_value(&nc))
2959 if (!nc.set_type(type, true, location))
2960 return Expression::make_error(location);
2961 return nc.expression(location);
2965 if (type->is_slice_type())
2967 Type* element_type = type->array_type()->element_type()->forwarded();
2968 bool is_byte = (element_type->integer_type() != NULL
2969 && element_type->integer_type()->is_byte());
2970 bool is_rune = (element_type->integer_type() != NULL
2971 && element_type->integer_type()->is_rune());
2972 if (is_byte || is_rune)
2975 if (val->string_constant_value(&s))
2977 Expression_list* vals = new Expression_list();
2980 for (std::string::const_iterator p = s.begin();
2985 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2986 Expression* v = Expression::make_integer(&val,
2995 const char *p = s.data();
2996 const char *pend = s.data() + s.length();
3000 int adv = Lex::fetch_char(p, &c);
3003 warning_at(this->location(), 0,
3004 "invalid UTF-8 encoding");
3009 mpz_init_set_ui(val, c);
3010 Expression* v = Expression::make_integer(&val,
3018 return Expression::make_slice_composite_literal(type, vals,
3027 // Return the constant numeric value if there is one.
3030 Type_conversion_expression::do_numeric_constant_value(
3031 Numeric_constant* nc) const
3033 if (!this->type_->is_numeric_type())
3035 if (!this->expr_->numeric_constant_value(nc))
3037 return nc->set_type(this->type_, false, this->location());
3040 // Return the constant string value if there is one.
3043 Type_conversion_expression::do_string_constant_value(std::string* val) const
3045 if (this->type_->is_string_type()
3046 && this->expr_->type()->integer_type() != NULL)
3048 Numeric_constant nc;
3049 if (this->expr_->numeric_constant_value(&nc))
3052 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3055 Lex::append_char(ival, true, val, this->location());
3061 // FIXME: Could handle conversion from const []int here.
3066 // Check that types are convertible.
3069 Type_conversion_expression::do_check_types(Gogo*)
3071 Type* type = this->type_;
3072 Type* expr_type = this->expr_->type();
3075 if (type->is_error() || expr_type->is_error())
3077 this->set_is_error();
3081 if (this->may_convert_function_types_
3082 && type->function_type() != NULL
3083 && expr_type->function_type() != NULL)
3086 if (Type::are_convertible(type, expr_type, &reason))
3089 error_at(this->location(), "%s", reason.c_str());
3090 this->set_is_error();
3093 // Get a tree for a type conversion.
3096 Type_conversion_expression::do_get_tree(Translate_context* context)
3098 Gogo* gogo = context->gogo();
3099 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3100 tree expr_tree = this->expr_->get_tree(context);
3102 if (type_tree == error_mark_node
3103 || expr_tree == error_mark_node
3104 || TREE_TYPE(expr_tree) == error_mark_node)
3105 return error_mark_node;
3107 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3108 return fold_convert(type_tree, expr_tree);
3110 Type* type = this->type_;
3111 Type* expr_type = this->expr_->type();
3113 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3114 ret = Expression::convert_for_assignment(context, type, expr_type,
3115 expr_tree, this->location());
3116 else if (type->integer_type() != NULL)
3118 if (expr_type->integer_type() != NULL
3119 || expr_type->float_type() != NULL
3120 || expr_type->is_unsafe_pointer_type())
3121 ret = fold(convert_to_integer(type_tree, expr_tree));
3125 else if (type->float_type() != NULL)
3127 if (expr_type->integer_type() != NULL
3128 || expr_type->float_type() != NULL)
3129 ret = fold(convert_to_real(type_tree, expr_tree));
3133 else if (type->complex_type() != NULL)
3135 if (expr_type->complex_type() != NULL)
3136 ret = fold(convert_to_complex(type_tree, expr_tree));
3140 else if (type->is_string_type()
3141 && expr_type->integer_type() != NULL)
3143 expr_tree = fold_convert(integer_type_node, expr_tree);
3144 if (host_integerp(expr_tree, 0))
3146 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3148 Lex::append_char(intval, true, &s, this->location());
3149 Expression* se = Expression::make_string(s, this->location());
3150 return se->get_tree(context);
3153 static tree int_to_string_fndecl;
3154 ret = Gogo::call_builtin(&int_to_string_fndecl,
3156 "__go_int_to_string",
3160 fold_convert(integer_type_node, expr_tree));
3162 else if (type->is_string_type() && expr_type->is_slice_type())
3164 if (!DECL_P(expr_tree))
3165 expr_tree = save_expr(expr_tree);
3166 Array_type* a = expr_type->array_type();
3167 Type* e = a->element_type()->forwarded();
3168 go_assert(e->integer_type() != NULL);
3169 tree valptr = fold_convert(const_ptr_type_node,
3170 a->value_pointer_tree(gogo, expr_tree));
3171 tree len = a->length_tree(gogo, expr_tree);
3172 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3174 if (e->integer_type()->is_byte())
3176 static tree byte_array_to_string_fndecl;
3177 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3179 "__go_byte_array_to_string",
3182 const_ptr_type_node,
3189 go_assert(e->integer_type()->is_rune());
3190 static tree int_array_to_string_fndecl;
3191 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3193 "__go_int_array_to_string",
3196 const_ptr_type_node,
3202 else if (type->is_slice_type() && expr_type->is_string_type())
3204 Type* e = type->array_type()->element_type()->forwarded();
3205 go_assert(e->integer_type() != NULL);
3206 if (e->integer_type()->is_byte())
3208 tree string_to_byte_array_fndecl = NULL_TREE;
3209 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3211 "__go_string_to_byte_array",
3214 TREE_TYPE(expr_tree),
3219 go_assert(e->integer_type()->is_rune());
3220 tree string_to_int_array_fndecl = NULL_TREE;
3221 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3223 "__go_string_to_int_array",
3226 TREE_TYPE(expr_tree),
3230 else if ((type->is_unsafe_pointer_type()
3231 && expr_type->points_to() != NULL)
3232 || (expr_type->is_unsafe_pointer_type()
3233 && type->points_to() != NULL))
3234 ret = fold_convert(type_tree, expr_tree);
3235 else if (type->is_unsafe_pointer_type()
3236 && expr_type->integer_type() != NULL)
3237 ret = convert_to_pointer(type_tree, expr_tree);
3238 else if (this->may_convert_function_types_
3239 && type->function_type() != NULL
3240 && expr_type->function_type() != NULL)
3241 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3244 ret = Expression::convert_for_assignment(context, type, expr_type,
3245 expr_tree, this->location());
3250 // Output a type conversion in a constant expression.
3253 Type_conversion_expression::do_export(Export* exp) const
3255 exp->write_c_string("convert(");
3256 exp->write_type(this->type_);
3257 exp->write_c_string(", ");
3258 this->expr_->export_expression(exp);
3259 exp->write_c_string(")");
3262 // Import a type conversion or a struct construction.
3265 Type_conversion_expression::do_import(Import* imp)
3267 imp->require_c_string("convert(");
3268 Type* type = imp->read_type();
3269 imp->require_c_string(", ");
3270 Expression* val = Expression::import_expression(imp);
3271 imp->require_c_string(")");
3272 return Expression::make_cast(type, val, imp->location());
3275 // Dump ast representation for a type conversion expression.
3278 Type_conversion_expression::do_dump_expression(
3279 Ast_dump_context* ast_dump_context) const
3281 ast_dump_context->dump_type(this->type_);
3282 ast_dump_context->ostream() << "(";
3283 ast_dump_context->dump_expression(this->expr_);
3284 ast_dump_context->ostream() << ") ";
3287 // Make a type cast expression.
3290 Expression::make_cast(Type* type, Expression* val, Location location)
3292 if (type->is_error_type() || val->is_error_expression())
3293 return Expression::make_error(location);
3294 return new Type_conversion_expression(type, val, location);
3297 // An unsafe type conversion, used to pass values to builtin functions.
3299 class Unsafe_type_conversion_expression : public Expression
3302 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3304 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3305 type_(type), expr_(expr)
3310 do_traverse(Traverse* traverse);
3314 { return this->type_; }
3317 do_determine_type(const Type_context*)
3318 { this->expr_->determine_type_no_context(); }
3323 return new Unsafe_type_conversion_expression(this->type_,
3324 this->expr_->copy(),
3329 do_get_tree(Translate_context*);
3332 do_dump_expression(Ast_dump_context*) const;
3335 // The type to convert to.
3337 // The expression to convert.
3344 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3346 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3347 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3348 return TRAVERSE_EXIT;
3349 return TRAVERSE_CONTINUE;
3352 // Convert to backend representation.
3355 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3357 // We are only called for a limited number of cases.
3359 Type* t = this->type_;
3360 Type* et = this->expr_->type();
3362 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3363 tree expr_tree = this->expr_->get_tree(context);
3364 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3365 return error_mark_node;
3367 Location loc = this->location();
3369 bool use_view_convert = false;
3370 if (t->is_slice_type())
3372 go_assert(et->is_slice_type());
3373 use_view_convert = true;
3375 else if (t->map_type() != NULL)
3376 go_assert(et->map_type() != NULL);
3377 else if (t->channel_type() != NULL)
3378 go_assert(et->channel_type() != NULL);
3379 else if (t->points_to() != NULL)
3380 go_assert(et->points_to() != NULL || et->is_nil_type());
3381 else if (et->is_unsafe_pointer_type())
3382 go_assert(t->points_to() != NULL);
3383 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3385 go_assert(et->interface_type() != NULL
3386 && !et->interface_type()->is_empty());
3387 use_view_convert = true;
3389 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3391 go_assert(et->interface_type() != NULL
3392 && et->interface_type()->is_empty());
3393 use_view_convert = true;
3395 else if (t->integer_type() != NULL)
3397 go_assert(et->is_boolean_type()
3398 || et->integer_type() != NULL
3399 || et->function_type() != NULL
3400 || et->points_to() != NULL
3401 || et->map_type() != NULL
3402 || et->channel_type() != NULL);
3403 return convert_to_integer(type_tree, expr_tree);
3408 if (use_view_convert)
3409 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3412 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3415 // Dump ast representation for an unsafe type conversion expression.
3418 Unsafe_type_conversion_expression::do_dump_expression(
3419 Ast_dump_context* ast_dump_context) const
3421 ast_dump_context->dump_type(this->type_);
3422 ast_dump_context->ostream() << "(";
3423 ast_dump_context->dump_expression(this->expr_);
3424 ast_dump_context->ostream() << ") ";
3427 // Make an unsafe type conversion expression.
3430 Expression::make_unsafe_cast(Type* type, Expression* expr,
3433 return new Unsafe_type_conversion_expression(type, expr, location);
3436 // Unary expressions.
3438 class Unary_expression : public Expression
3441 Unary_expression(Operator op, Expression* expr, Location location)
3442 : Expression(EXPRESSION_UNARY, location),
3443 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3446 // Return the operator.
3449 { return this->op_; }
3451 // Return the operand.
3454 { return this->expr_; }
3456 // Record that an address expression does not escape.
3458 set_does_not_escape()
3460 go_assert(this->op_ == OPERATOR_AND);
3461 this->escapes_ = false;
3464 // Record that this is an address expression which should create a
3465 // temporary variable if necessary. This is used for method calls.
3469 go_assert(this->op_ == OPERATOR_AND);
3470 this->create_temp_ = true;
3473 // Apply unary opcode OP to UNC, setting NC. Return true if this
3474 // could be done, false if not. Issue errors for overflow.
3476 eval_constant(Operator op, const Numeric_constant* unc,
3477 Location, Numeric_constant* nc);
3484 do_traverse(Traverse* traverse)
3485 { return Expression::traverse(&this->expr_, traverse); }
3488 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3491 do_is_constant() const;
3494 do_numeric_constant_value(Numeric_constant*) const;
3500 do_determine_type(const Type_context*);
3503 do_check_types(Gogo*);
3508 return Expression::make_unary(this->op_, this->expr_->copy(),
3513 do_must_eval_subexpressions_in_order(int*) const
3514 { return this->op_ == OPERATOR_MULT; }
3517 do_is_addressable() const
3518 { return this->op_ == OPERATOR_MULT; }
3521 do_get_tree(Translate_context*);
3524 do_export(Export*) const;
3527 do_dump_expression(Ast_dump_context*) const;
3530 // The unary operator to apply.
3532 // Normally true. False if this is an address expression which does
3533 // not escape the current function.
3535 // True if this is an address expression which should create a
3536 // temporary variable if necessary.
3542 // If we are taking the address of a composite literal, and the
3543 // contents are not constant, then we want to make a heap composite
3547 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3549 Location loc = this->location();
3550 Operator op = this->op_;
3551 Expression* expr = this->expr_;
3553 if (op == OPERATOR_MULT && expr->is_type_expression())
3554 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3556 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3557 // moving x to the heap. FIXME: Is it worth doing a real escape
3558 // analysis here? This case is found in math/unsafe.go and is
3559 // therefore worth special casing.
3560 if (op == OPERATOR_MULT)
3562 Expression* e = expr;
3563 while (e->classification() == EXPRESSION_CONVERSION)
3565 Type_conversion_expression* te
3566 = static_cast<Type_conversion_expression*>(e);
3570 if (e->classification() == EXPRESSION_UNARY)
3572 Unary_expression* ue = static_cast<Unary_expression*>(e);
3573 if (ue->op_ == OPERATOR_AND)
3580 ue->set_does_not_escape();
3585 // Catching an invalid indirection of unsafe.Pointer here avoid
3586 // having to deal with TYPE_VOID in other places.
3587 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3589 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3590 return Expression::make_error(this->location());
3593 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS
3594 || op == OPERATOR_NOT || op == OPERATOR_XOR)
3596 Numeric_constant nc;
3597 if (expr->numeric_constant_value(&nc))
3599 Numeric_constant result;
3600 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3601 return result.expression(loc);
3608 // Return whether a unary expression is a constant.
3611 Unary_expression::do_is_constant() const
3613 if (this->op_ == OPERATOR_MULT)
3615 // Indirecting through a pointer is only constant if the object
3616 // to which the expression points is constant, but we currently
3617 // have no way to determine that.
3620 else if (this->op_ == OPERATOR_AND)
3622 // Taking the address of a variable is constant if it is a
3623 // global variable, not constant otherwise. In other cases
3624 // taking the address is probably not a constant.
3625 Var_expression* ve = this->expr_->var_expression();
3628 Named_object* no = ve->named_object();
3629 return no->is_variable() && no->var_value()->is_global();
3634 return this->expr_->is_constant();
3637 // Apply unary opcode OP to UNC, setting NC. Return true if this
3638 // could be done, false if not. Issue errors for overflow.
3641 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3642 Location location, Numeric_constant* nc)
3650 case OPERATOR_MINUS:
3651 if (unc->is_int() || unc->is_rune())
3653 else if (unc->is_float())
3656 unc->get_float(&uval);
3659 mpfr_neg(val, uval, GMP_RNDN);
3660 nc->set_float(unc->type(), val);
3665 else if (unc->is_complex())
3667 mpfr_t ureal, uimag;
3668 unc->get_complex(&ureal, &uimag);
3672 mpfr_neg(real, ureal, GMP_RNDN);
3673 mpfr_neg(imag, uimag, GMP_RNDN);
3674 nc->set_complex(unc->type(), real, imag);
3696 if (!unc->is_int() && !unc->is_rune())
3700 unc->get_int(&uval);
3706 case OPERATOR_MINUS:
3711 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3716 Type* utype = unc->type();
3717 if (utype->integer_type() == NULL
3718 || utype->integer_type()->is_abstract())
3722 // The number of HOST_WIDE_INTs that it takes to represent
3724 size_t count = ((mpz_sizeinbase(uval, 2)
3725 + HOST_BITS_PER_WIDE_INT
3727 / HOST_BITS_PER_WIDE_INT);
3729 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3730 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3732 size_t obits = utype->integer_type()->bits();
3734 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3737 mpz_init_set_ui(adj, 1);
3738 mpz_mul_2exp(adj, adj, obits);
3739 mpz_add(uval, uval, adj);
3744 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3745 go_assert(ecount <= count);
3747 // Trim down to the number of words required by the type.
3748 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3749 / HOST_BITS_PER_WIDE_INT);
3750 go_assert(ocount <= count);
3752 for (size_t i = 0; i < ocount; ++i)
3755 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3757 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3760 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3762 if (!utype->integer_type()->is_unsigned()
3763 && mpz_tstbit(val, obits - 1))
3766 mpz_init_set_ui(adj, 1);
3767 mpz_mul_2exp(adj, adj, obits);
3768 mpz_sub(val, val, adj);
3782 nc->set_rune(NULL, val);
3784 nc->set_int(NULL, val);
3789 return nc->set_type(unc->type(), true, location);
3792 // Return the integral constant value of a unary expression, if it has one.
3795 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3797 Numeric_constant unc;
3798 if (!this->expr_->numeric_constant_value(&unc))
3800 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3804 // Return the type of a unary expression.
3807 Unary_expression::do_type()
3812 case OPERATOR_MINUS:
3815 return this->expr_->type();
3818 return Type::make_pointer_type(this->expr_->type());
3822 Type* subtype = this->expr_->type();
3823 Type* points_to = subtype->points_to();
3824 if (points_to == NULL)
3825 return Type::make_error_type();
3834 // Determine abstract types for a unary expression.
3837 Unary_expression::do_determine_type(const Type_context* context)
3842 case OPERATOR_MINUS:
3845 this->expr_->determine_type(context);
3849 // Taking the address of something.
3851 Type* subtype = (context->type == NULL
3853 : context->type->points_to());
3854 Type_context subcontext(subtype, false);
3855 this->expr_->determine_type(&subcontext);
3860 // Indirecting through a pointer.
3862 Type* subtype = (context->type == NULL
3864 : Type::make_pointer_type(context->type));
3865 Type_context subcontext(subtype, false);
3866 this->expr_->determine_type(&subcontext);
3875 // Check types for a unary expression.
3878 Unary_expression::do_check_types(Gogo*)
3880 Type* type = this->expr_->type();
3881 if (type->is_error())
3883 this->set_is_error();
3890 case OPERATOR_MINUS:
3891 if (type->integer_type() == NULL
3892 && type->float_type() == NULL
3893 && type->complex_type() == NULL)
3894 this->report_error(_("expected numeric type"));
3899 if (type->integer_type() == NULL
3900 && !type->is_boolean_type())
3901 this->report_error(_("expected integer or boolean type"));
3905 if (!this->expr_->is_addressable())
3907 if (!this->create_temp_)
3908 this->report_error(_("invalid operand for unary %<&%>"));
3911 this->expr_->address_taken(this->escapes_);
3915 // Indirecting through a pointer.
3916 if (type->points_to() == NULL)
3917 this->report_error(_("expected pointer"));
3925 // Get a tree for a unary expression.
3928 Unary_expression::do_get_tree(Translate_context* context)
3930 Location loc = this->location();
3932 // Taking the address of a set-and-use-temporary expression requires
3933 // setting the temporary and then taking the address.
3934 if (this->op_ == OPERATOR_AND)
3936 Set_and_use_temporary_expression* sut =
3937 this->expr_->set_and_use_temporary_expression();
3940 Temporary_statement* temp = sut->temporary();
3941 Bvariable* bvar = temp->get_backend_variable(context);
3942 tree var_tree = var_to_tree(bvar);
3943 Expression* val = sut->expression();
3944 tree val_tree = val->get_tree(context);
3945 if (var_tree == error_mark_node || val_tree == error_mark_node)
3946 return error_mark_node;
3947 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3949 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3950 TREE_TYPE(addr_tree),
3951 build2_loc(sut->location().gcc_location(),
3952 MODIFY_EXPR, void_type_node,
3953 var_tree, val_tree),
3958 tree expr = this->expr_->get_tree(context);
3959 if (expr == error_mark_node)
3960 return error_mark_node;
3967 case OPERATOR_MINUS:
3969 tree type = TREE_TYPE(expr);
3970 tree compute_type = excess_precision_type(type);
3971 if (compute_type != NULL_TREE)
3972 expr = ::convert(compute_type, expr);
3973 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3974 (compute_type != NULL_TREE
3978 if (compute_type != NULL_TREE)
3979 ret = ::convert(type, ret);
3984 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
3985 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
3986 TREE_TYPE(expr), expr);
3988 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
3989 expr, build_int_cst(TREE_TYPE(expr), 0));
3992 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
3996 if (!this->create_temp_)
3998 // We should not see a non-constant constructor here; cases
3999 // where we would see one should have been moved onto the
4000 // heap at parse time. Taking the address of a nonconstant
4001 // constructor will not do what the programmer expects.
4002 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4003 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4006 // Build a decl for a constant constructor.
4007 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4009 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4010 create_tmp_var_name("C"), TREE_TYPE(expr));
4011 DECL_EXTERNAL(decl) = 0;
4012 TREE_PUBLIC(decl) = 0;
4013 TREE_READONLY(decl) = 1;
4014 TREE_CONSTANT(decl) = 1;
4015 TREE_STATIC(decl) = 1;
4016 TREE_ADDRESSABLE(decl) = 1;
4017 DECL_ARTIFICIAL(decl) = 1;
4018 DECL_INITIAL(decl) = expr;
4019 rest_of_decl_compilation(decl, 1, 0);
4023 if (this->create_temp_
4024 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4026 && TREE_CODE(expr) != INDIRECT_REF
4027 && TREE_CODE(expr) != COMPONENT_REF)
4029 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4030 DECL_IGNORED_P(tmp) = 1;
4031 DECL_INITIAL(tmp) = expr;
4032 TREE_ADDRESSABLE(tmp) = 1;
4033 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4034 build_pointer_type(TREE_TYPE(expr)),
4035 build1_loc(loc.gcc_location(), DECL_EXPR,
4036 void_type_node, tmp),
4037 build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4040 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4044 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4046 // If we are dereferencing the pointer to a large struct, we
4047 // need to check for nil. We don't bother to check for small
4048 // structs because we expect the system to crash on a nil
4049 // pointer dereference.
4050 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4051 if (!VOID_TYPE_P(target_type_tree))
4053 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4054 if (s == -1 || s >= 4096)
4057 expr = save_expr(expr);
4058 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4061 fold_convert(TREE_TYPE(expr),
4062 null_pointer_node));
4063 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4065 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4066 TREE_TYPE(expr), build3(COND_EXPR,
4074 // If the type of EXPR is a recursive pointer type, then we
4075 // need to insert a cast before indirecting.
4076 if (VOID_TYPE_P(target_type_tree))
4078 Type* pt = this->expr_->type()->points_to();
4079 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4080 expr = fold_convert_loc(loc.gcc_location(),
4081 build_pointer_type(ind), expr);
4084 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4092 // Export a unary expression.
4095 Unary_expression::do_export(Export* exp) const
4100 exp->write_c_string("+ ");
4102 case OPERATOR_MINUS:
4103 exp->write_c_string("- ");
4106 exp->write_c_string("! ");
4109 exp->write_c_string("^ ");
4116 this->expr_->export_expression(exp);
4119 // Import a unary expression.
4122 Unary_expression::do_import(Import* imp)
4125 switch (imp->get_char())
4131 op = OPERATOR_MINUS;
4142 imp->require_c_string(" ");
4143 Expression* expr = Expression::import_expression(imp);
4144 return Expression::make_unary(op, expr, imp->location());
4147 // Dump ast representation of an unary expression.
4150 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4152 ast_dump_context->dump_operator(this->op_);
4153 ast_dump_context->ostream() << "(";
4154 ast_dump_context->dump_expression(this->expr_);
4155 ast_dump_context->ostream() << ") ";
4158 // Make a unary expression.
4161 Expression::make_unary(Operator op, Expression* expr, Location location)
4163 return new Unary_expression(op, expr, location);
4166 // If this is an indirection through a pointer, return the expression
4167 // being pointed through. Otherwise return this.
4172 if (this->classification_ == EXPRESSION_UNARY)
4174 Unary_expression* ue = static_cast<Unary_expression*>(this);
4175 if (ue->op() == OPERATOR_MULT)
4176 return ue->operand();
4181 // Class Binary_expression.
4186 Binary_expression::do_traverse(Traverse* traverse)
4188 int t = Expression::traverse(&this->left_, traverse);
4189 if (t == TRAVERSE_EXIT)
4190 return TRAVERSE_EXIT;
4191 return Expression::traverse(&this->right_, traverse);
4194 // Return the type to use for a binary operation on operands of
4195 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4196 // such may be NULL or abstract.
4199 Binary_expression::operation_type(Operator op, Type* left_type,
4200 Type* right_type, Type** result_type)
4202 if (left_type != right_type
4203 && !left_type->is_abstract()
4204 && !right_type->is_abstract()
4205 && left_type->base() != right_type->base()
4206 && op != OPERATOR_LSHIFT
4207 && op != OPERATOR_RSHIFT)
4209 // May be a type error--let it be diagnosed elsewhere.
4213 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4215 if (left_type->integer_type() != NULL)
4216 *result_type = left_type;
4218 *result_type = Type::make_abstract_integer_type();
4220 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4221 *result_type = left_type;
4222 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4223 *result_type = right_type;
4224 else if (!left_type->is_abstract())
4225 *result_type = left_type;
4226 else if (!right_type->is_abstract())
4227 *result_type = right_type;
4228 else if (left_type->complex_type() != NULL)
4229 *result_type = left_type;
4230 else if (right_type->complex_type() != NULL)
4231 *result_type = right_type;
4232 else if (left_type->float_type() != NULL)
4233 *result_type = left_type;
4234 else if (right_type->float_type() != NULL)
4235 *result_type = right_type;
4236 else if (left_type->integer_type() != NULL
4237 && left_type->integer_type()->is_rune())
4238 *result_type = left_type;
4239 else if (right_type->integer_type() != NULL
4240 && right_type->integer_type()->is_rune())
4241 *result_type = right_type;
4243 *result_type = left_type;
4248 // Convert an integer comparison code and an operator to a boolean
4252 Binary_expression::cmp_to_bool(Operator op, int cmp)
4259 case OPERATOR_NOTEQ:
4276 // Compare constants according to OP.
4279 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4280 Numeric_constant* right_nc,
4281 Location location, bool* result)
4283 Type* left_type = left_nc->type();
4284 Type* right_type = right_nc->type();
4287 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4290 // When comparing an untyped operand to a typed operand, we are
4291 // effectively coercing the untyped operand to the other operand's
4292 // type, so make sure that is valid.
4293 if (!left_nc->set_type(type, true, location)
4294 || !right_nc->set_type(type, true, location))
4299 if (type->complex_type() != NULL)
4301 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4303 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4305 else if (type->float_type() != NULL)
4306 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4308 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4311 *result = Binary_expression::cmp_to_bool(op, cmp);
4316 // Compare integer constants.
4319 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4320 const Numeric_constant* right_nc,
4324 if (!left_nc->to_int(&left_val))
4327 if (!right_nc->to_int(&right_val))
4329 mpz_clear(left_val);
4333 *cmp = mpz_cmp(left_val, right_val);
4335 mpz_clear(left_val);
4336 mpz_clear(right_val);
4341 // Compare floating point constants.
4344 Binary_expression::compare_float(const Numeric_constant* left_nc,
4345 const Numeric_constant* right_nc,
4349 if (!left_nc->to_float(&left_val))
4352 if (!right_nc->to_float(&right_val))
4354 mpfr_clear(left_val);
4358 // We already coerced both operands to the same type. If that type
4359 // is not an abstract type, we need to round the values accordingly.
4360 Type* type = left_nc->type();
4361 if (!type->is_abstract() && type->float_type() != NULL)
4363 int bits = type->float_type()->bits();
4364 mpfr_prec_round(left_val, bits, GMP_RNDN);
4365 mpfr_prec_round(right_val, bits, GMP_RNDN);
4368 *cmp = mpfr_cmp(left_val, right_val);
4370 mpfr_clear(left_val);
4371 mpfr_clear(right_val);
4376 // Compare complex constants. Complex numbers may only be compared
4380 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4381 const Numeric_constant* right_nc,
4384 mpfr_t left_real, left_imag;
4385 if (!left_nc->to_complex(&left_real, &left_imag))
4387 mpfr_t right_real, right_imag;
4388 if (!right_nc->to_complex(&right_real, &right_imag))
4390 mpfr_clear(left_real);
4391 mpfr_clear(left_imag);
4395 // We already coerced both operands to the same type. If that type
4396 // is not an abstract type, we need to round the values accordingly.
4397 Type* type = left_nc->type();
4398 if (!type->is_abstract() && type->complex_type() != NULL)
4400 int bits = type->complex_type()->bits();
4401 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4402 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4403 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4404 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4407 *cmp = (mpfr_cmp(left_real, right_real) != 0
4408 || mpfr_cmp(left_imag, right_imag) != 0);
4410 mpfr_clear(left_real);
4411 mpfr_clear(left_imag);
4412 mpfr_clear(right_real);
4413 mpfr_clear(right_imag);
4418 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4419 // true if this could be done, false if not. Issue errors at LOCATION
4423 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4424 Numeric_constant* right_nc,
4425 Location location, Numeric_constant* nc)
4430 case OPERATOR_ANDAND:
4432 case OPERATOR_NOTEQ:
4437 // These return boolean values and as such must be handled
4444 Type* left_type = left_nc->type();
4445 Type* right_type = right_nc->type();
4448 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4451 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4453 // When combining an untyped operand with a typed operand, we are
4454 // effectively coercing the untyped operand to the other operand's
4455 // type, so make sure that is valid.
4456 if (!left_nc->set_type(type, true, location))
4458 if (!is_shift && !right_nc->set_type(type, true, location))
4462 if (type->complex_type() != NULL)
4463 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4464 else if (type->float_type() != NULL)
4465 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4467 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4470 r = nc->set_type(type, true, location);
4475 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4476 // integer operations. Return true if this could be done, false if
4480 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4481 const Numeric_constant* right_nc,
4482 Location location, Numeric_constant* nc)
4485 if (!left_nc->to_int(&left_val))
4488 if (!right_nc->to_int(&right_val))
4490 mpz_clear(left_val);
4500 mpz_add(val, left_val, right_val);
4502 case OPERATOR_MINUS:
4503 mpz_sub(val, left_val, right_val);
4506 mpz_ior(val, left_val, right_val);
4509 mpz_xor(val, left_val, right_val);
4512 mpz_mul(val, left_val, right_val);
4515 if (mpz_sgn(right_val) != 0)
4516 mpz_tdiv_q(val, left_val, right_val);
4519 error_at(location, "division by zero");
4524 if (mpz_sgn(right_val) != 0)
4525 mpz_tdiv_r(val, left_val, right_val);
4528 error_at(location, "division by zero");
4532 case OPERATOR_LSHIFT:
4534 unsigned long shift = mpz_get_ui(right_val);
4535 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4536 mpz_mul_2exp(val, left_val, shift);
4539 error_at(location, "shift count overflow");
4545 case OPERATOR_RSHIFT:
4547 unsigned long shift = mpz_get_ui(right_val);
4548 if (mpz_cmp_ui(right_val, shift) != 0)
4550 error_at(location, "shift count overflow");
4555 if (mpz_cmp_ui(left_val, 0) >= 0)
4556 mpz_tdiv_q_2exp(val, left_val, shift);
4558 mpz_fdiv_q_2exp(val, left_val, shift);
4564 mpz_and(val, left_val, right_val);
4566 case OPERATOR_BITCLEAR:
4570 mpz_com(tval, right_val);
4571 mpz_and(val, left_val, tval);
4579 mpz_clear(left_val);
4580 mpz_clear(right_val);
4582 if (left_nc->is_rune()
4583 || (op != OPERATOR_LSHIFT
4584 && op != OPERATOR_RSHIFT
4585 && right_nc->is_rune()))
4586 nc->set_rune(NULL, val);
4588 nc->set_int(NULL, val);
4595 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4596 // floating point operations. Return true if this could be done,
4600 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4601 const Numeric_constant* right_nc,
4602 Location location, Numeric_constant* nc)
4605 if (!left_nc->to_float(&left_val))
4608 if (!right_nc->to_float(&right_val))
4610 mpfr_clear(left_val);
4621 mpfr_add(val, left_val, right_val, GMP_RNDN);
4623 case OPERATOR_MINUS:
4624 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4629 case OPERATOR_BITCLEAR:
4631 case OPERATOR_LSHIFT:
4632 case OPERATOR_RSHIFT:
4633 mpfr_set_ui(val, 0, GMP_RNDN);
4637 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4640 if (!mpfr_zero_p(right_val))
4641 mpfr_div(val, left_val, right_val, GMP_RNDN);
4644 error_at(location, "division by zero");
4645 mpfr_set_ui(val, 0, GMP_RNDN);
4652 mpfr_clear(left_val);
4653 mpfr_clear(right_val);
4655 nc->set_float(NULL, val);
4661 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4662 // complex operations. Return true if this could be done, false if
4666 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4667 const Numeric_constant* right_nc,
4668 Location location, Numeric_constant* nc)
4670 mpfr_t left_real, left_imag;
4671 if (!left_nc->to_complex(&left_real, &left_imag))
4673 mpfr_t right_real, right_imag;
4674 if (!right_nc->to_complex(&right_real, &right_imag))
4676 mpfr_clear(left_real);
4677 mpfr_clear(left_imag);
4689 mpfr_add(real, left_real, right_real, GMP_RNDN);
4690 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4692 case OPERATOR_MINUS:
4693 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4694 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4699 case OPERATOR_BITCLEAR:
4701 case OPERATOR_LSHIFT:
4702 case OPERATOR_RSHIFT:
4703 mpfr_set_ui(real, 0, GMP_RNDN);
4704 mpfr_set_ui(imag, 0, GMP_RNDN);
4709 // You might think that multiplying two complex numbers would
4710 // be simple, and you would be right, until you start to think
4711 // about getting the right answer for infinity. If one
4712 // operand here is infinity and the other is anything other
4713 // than zero or NaN, then we are going to wind up subtracting
4714 // two infinity values. That will give us a NaN, but the
4715 // correct answer is infinity.
4719 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4723 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4727 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4731 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4733 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4734 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4736 // If we get NaN on both sides, check whether it should really
4737 // be infinity. The rule is that if either side of the
4738 // complex number is infinity, then the whole value is
4739 // infinity, even if the other side is NaN. So the only case
4740 // we have to fix is the one in which both sides are NaN.
4741 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4742 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4743 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4745 bool is_infinity = false;
4749 mpfr_init_set(lr, left_real, GMP_RNDN);
4750 mpfr_init_set(li, left_imag, GMP_RNDN);
4754 mpfr_init_set(rr, right_real, GMP_RNDN);
4755 mpfr_init_set(ri, right_imag, GMP_RNDN);
4757 // If the left side is infinity, then the result is
4759 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4761 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4762 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4763 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4764 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4767 mpfr_set_ui(rr, 0, GMP_RNDN);
4768 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4772 mpfr_set_ui(ri, 0, GMP_RNDN);
4773 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4778 // If the right side is infinity, then the result is
4780 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4782 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4783 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4784 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4785 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4788 mpfr_set_ui(lr, 0, GMP_RNDN);
4789 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4793 mpfr_set_ui(li, 0, GMP_RNDN);
4794 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4799 // If we got an overflow in the intermediate computations,
4800 // then the result is infinity.
4802 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4803 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4807 mpfr_set_ui(lr, 0, GMP_RNDN);
4808 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4812 mpfr_set_ui(li, 0, GMP_RNDN);
4813 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4817 mpfr_set_ui(rr, 0, GMP_RNDN);
4818 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4822 mpfr_set_ui(ri, 0, GMP_RNDN);
4823 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4830 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4831 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4832 mpfr_mul(lirr, li, rr, GMP_RNDN);
4833 mpfr_mul(liri, li, ri, GMP_RNDN);
4834 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4835 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4836 mpfr_set_inf(real, mpfr_sgn(real));
4837 mpfr_set_inf(imag, mpfr_sgn(imag));
4854 // For complex division we want to avoid having an
4855 // intermediate overflow turn the whole result in a NaN. We
4856 // scale the values to try to avoid this.
4858 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4860 error_at(location, "division by zero");
4861 mpfr_set_ui(real, 0, GMP_RNDN);
4862 mpfr_set_ui(imag, 0, GMP_RNDN);
4870 mpfr_abs(rra, right_real, GMP_RNDN);
4871 mpfr_abs(ria, right_imag, GMP_RNDN);
4874 mpfr_max(t, rra, ria, GMP_RNDN);
4878 mpfr_init_set(rr, right_real, GMP_RNDN);
4879 mpfr_init_set(ri, right_imag, GMP_RNDN);
4881 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4883 ilogbw = mpfr_get_exp(t);
4884 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4885 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4890 mpfr_mul(denom, rr, rr, GMP_RNDN);
4891 mpfr_mul(t, ri, ri, GMP_RNDN);
4892 mpfr_add(denom, denom, t, GMP_RNDN);
4894 mpfr_mul(real, left_real, rr, GMP_RNDN);
4895 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4896 mpfr_add(real, real, t, GMP_RNDN);
4897 mpfr_div(real, real, denom, GMP_RNDN);
4898 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4900 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4901 mpfr_mul(t, left_real, ri, GMP_RNDN);
4902 mpfr_sub(imag, imag, t, GMP_RNDN);
4903 mpfr_div(imag, imag, denom, GMP_RNDN);
4904 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4906 // If we wind up with NaN on both sides, check whether we
4907 // should really have infinity. The rule is that if either
4908 // side of the complex number is infinity, then the whole
4909 // value is infinity, even if the other side is NaN. So the
4910 // only case we have to fix is the one in which both sides are
4912 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4913 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4914 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4916 if (mpfr_zero_p(denom))
4918 mpfr_set_inf(real, mpfr_sgn(rr));
4919 mpfr_mul(real, real, left_real, GMP_RNDN);
4920 mpfr_set_inf(imag, mpfr_sgn(rr));
4921 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4923 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4924 && mpfr_number_p(rr) && mpfr_number_p(ri))
4926 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4927 mpfr_copysign(t, t, left_real, GMP_RNDN);
4930 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4931 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4935 mpfr_mul(t3, t, rr, GMP_RNDN);
4939 mpfr_mul(t4, t2, ri, GMP_RNDN);
4941 mpfr_add(t3, t3, t4, GMP_RNDN);
4942 mpfr_set_inf(real, mpfr_sgn(t3));
4944 mpfr_mul(t3, t2, rr, GMP_RNDN);
4945 mpfr_mul(t4, t, ri, GMP_RNDN);
4946 mpfr_sub(t3, t3, t4, GMP_RNDN);
4947 mpfr_set_inf(imag, mpfr_sgn(t3));
4953 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4954 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4956 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4957 mpfr_copysign(t, t, rr, GMP_RNDN);
4960 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4961 mpfr_copysign(t2, t2, ri, GMP_RNDN);
4965 mpfr_mul(t3, left_real, t, GMP_RNDN);
4969 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
4971 mpfr_add(t3, t3, t4, GMP_RNDN);
4972 mpfr_set_ui(real, 0, GMP_RNDN);
4973 mpfr_mul(real, real, t3, GMP_RNDN);
4975 mpfr_mul(t3, left_imag, t, GMP_RNDN);
4976 mpfr_mul(t4, left_real, t2, GMP_RNDN);
4977 mpfr_sub(t3, t3, t4, GMP_RNDN);
4978 mpfr_set_ui(imag, 0, GMP_RNDN);
4979 mpfr_mul(imag, imag, t3, GMP_RNDN);
4999 mpfr_clear(left_real);
5000 mpfr_clear(left_imag);
5001 mpfr_clear(right_real);
5002 mpfr_clear(right_imag);
5004 nc->set_complex(NULL, real, imag);
5011 // Lower a binary expression. We have to evaluate constant
5012 // expressions now, in order to implement Go's unlimited precision
5016 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5017 Statement_inserter* inserter, int)
5019 Location location = this->location();
5020 Operator op = this->op_;
5021 Expression* left = this->left_;
5022 Expression* right = this->right_;
5024 const bool is_comparison = (op == OPERATOR_EQEQ
5025 || op == OPERATOR_NOTEQ
5026 || op == OPERATOR_LT
5027 || op == OPERATOR_LE
5028 || op == OPERATOR_GT
5029 || op == OPERATOR_GE);
5031 // Numeric constant expressions.
5033 Numeric_constant left_nc;
5034 Numeric_constant right_nc;
5035 if (left->numeric_constant_value(&left_nc)
5036 && right->numeric_constant_value(&right_nc))
5041 if (!Binary_expression::compare_constant(op, &left_nc,
5042 &right_nc, location,
5045 return Expression::make_cast(Type::lookup_bool_type(),
5046 Expression::make_boolean(result,
5052 Numeric_constant nc;
5053 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5056 return nc.expression(location);
5061 // String constant expressions.
5062 if (left->type()->is_string_type() && right->type()->is_string_type())
5064 std::string left_string;
5065 std::string right_string;
5066 if (left->string_constant_value(&left_string)
5067 && right->string_constant_value(&right_string))
5069 if (op == OPERATOR_PLUS)
5070 return Expression::make_string(left_string + right_string,
5072 else if (is_comparison)
5074 int cmp = left_string.compare(right_string);
5075 bool r = Binary_expression::cmp_to_bool(op, cmp);
5076 return Expression::make_cast(Type::lookup_bool_type(),
5077 Expression::make_boolean(r,
5084 // Lower struct and array comparisons.
5085 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5087 if (left->type()->struct_type() != NULL)
5088 return this->lower_struct_comparison(gogo, inserter);
5089 else if (left->type()->array_type() != NULL
5090 && !left->type()->is_slice_type())
5091 return this->lower_array_comparison(gogo, inserter);
5097 // Lower a struct comparison.
5100 Binary_expression::lower_struct_comparison(Gogo* gogo,
5101 Statement_inserter* inserter)
5103 Struct_type* st = this->left_->type()->struct_type();
5104 Struct_type* st2 = this->right_->type()->struct_type();
5107 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5109 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5110 this->right_->type(), NULL))
5113 // See if we can compare using memcmp. As a heuristic, we use
5114 // memcmp rather than field references and comparisons if there are
5115 // more than two fields.
5116 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5117 return this->lower_compare_to_memcmp(gogo, inserter);
5119 Location loc = this->location();
5121 Expression* left = this->left_;
5122 Temporary_statement* left_temp = NULL;
5123 if (left->var_expression() == NULL
5124 && left->temporary_reference_expression() == NULL)
5126 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5127 inserter->insert(left_temp);
5128 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5131 Expression* right = this->right_;
5132 Temporary_statement* right_temp = NULL;
5133 if (right->var_expression() == NULL
5134 && right->temporary_reference_expression() == NULL)
5136 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5137 inserter->insert(right_temp);
5138 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5141 Expression* ret = Expression::make_boolean(true, loc);
5142 const Struct_field_list* fields = st->fields();
5143 unsigned int field_index = 0;
5144 for (Struct_field_list::const_iterator pf = fields->begin();
5145 pf != fields->end();
5146 ++pf, ++field_index)
5148 if (field_index > 0)
5150 if (left_temp == NULL)
5151 left = left->copy();
5153 left = Expression::make_temporary_reference(left_temp, loc);
5154 if (right_temp == NULL)
5155 right = right->copy();
5157 right = Expression::make_temporary_reference(right_temp, loc);
5159 Expression* f1 = Expression::make_field_reference(left, field_index,
5161 Expression* f2 = Expression::make_field_reference(right, field_index,
5163 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5164 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5167 if (this->op_ == OPERATOR_NOTEQ)
5168 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5173 // Lower an array comparison.
5176 Binary_expression::lower_array_comparison(Gogo* gogo,
5177 Statement_inserter* inserter)
5179 Array_type* at = this->left_->type()->array_type();
5180 Array_type* at2 = this->right_->type()->array_type();
5183 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5185 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5186 this->right_->type(), NULL))
5189 // Call memcmp directly if possible. This may let the middle-end
5190 // optimize the call.
5191 if (at->compare_is_identity(gogo))
5192 return this->lower_compare_to_memcmp(gogo, inserter);
5194 // Call the array comparison function.
5195 Named_object* hash_fn;
5196 Named_object* equal_fn;
5197 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5198 &hash_fn, &equal_fn);
5200 Location loc = this->location();
5202 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5204 Expression_list* args = new Expression_list();
5205 args->push_back(this->operand_address(inserter, this->left_));
5206 args->push_back(this->operand_address(inserter, this->right_));
5207 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5209 Expression* ret = Expression::make_call(func, args, false, loc);
5211 if (this->op_ == OPERATOR_NOTEQ)
5212 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5217 // Lower a struct or array comparison to a call to memcmp.
5220 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5222 Location loc = this->location();
5224 Expression* a1 = this->operand_address(inserter, this->left_);
5225 Expression* a2 = this->operand_address(inserter, this->right_);
5226 Expression* len = Expression::make_type_info(this->left_->type(),
5229 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5232 mpz_init_set_ui(zval, 0);
5233 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5236 return Expression::make_binary(this->op_, call, zero, loc);
5239 // Return the address of EXPR, cast to unsafe.Pointer.
5242 Binary_expression::operand_address(Statement_inserter* inserter,
5245 Location loc = this->location();
5247 if (!expr->is_addressable())
5249 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5251 inserter->insert(temp);
5252 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5254 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5255 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5256 Type* void_type = Type::make_void_type();
5257 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5258 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5261 // Return the numeric constant value, if it has one.
5264 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5266 Operator op = this->op_;
5268 if (op == OPERATOR_EQEQ
5269 || op == OPERATOR_NOTEQ
5270 || op == OPERATOR_LT
5271 || op == OPERATOR_LE
5272 || op == OPERATOR_GT
5273 || op == OPERATOR_GE)
5276 Numeric_constant left_nc;
5277 if (!this->left_->numeric_constant_value(&left_nc))
5279 Numeric_constant right_nc;
5280 if (!this->right_->numeric_constant_value(&right_nc))
5283 return Binary_expression::eval_constant(op, &left_nc, &right_nc,
5284 this->location(), nc);
5287 // Note that the value is being discarded.
5290 Binary_expression::do_discarding_value()
5292 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5293 this->right_->discarding_value();
5295 this->unused_value_error();
5301 Binary_expression::do_type()
5303 if (this->classification() == EXPRESSION_ERROR)
5304 return Type::make_error_type();
5309 case OPERATOR_ANDAND:
5311 case OPERATOR_NOTEQ:
5316 return Type::lookup_bool_type();
5319 case OPERATOR_MINUS:
5326 case OPERATOR_BITCLEAR:
5329 if (!Binary_expression::operation_type(this->op_,
5330 this->left_->type(),
5331 this->right_->type(),
5333 return Type::make_error_type();
5337 case OPERATOR_LSHIFT:
5338 case OPERATOR_RSHIFT:
5339 return this->left_->type();
5346 // Set type for a binary expression.
5349 Binary_expression::do_determine_type(const Type_context* context)
5351 Type* tleft = this->left_->type();
5352 Type* tright = this->right_->type();
5354 // Both sides should have the same type, except for the shift
5355 // operations. For a comparison, we should ignore the incoming
5358 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5359 || this->op_ == OPERATOR_RSHIFT);
5361 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5362 || this->op_ == OPERATOR_NOTEQ
5363 || this->op_ == OPERATOR_LT
5364 || this->op_ == OPERATOR_LE
5365 || this->op_ == OPERATOR_GT
5366 || this->op_ == OPERATOR_GE);
5368 Type_context subcontext(*context);
5372 // In a comparison, the context does not determine the types of
5374 subcontext.type = NULL;
5377 // Set the context for the left hand operand.
5380 // The right hand operand of a shift plays no role in
5381 // determining the type of the left hand operand.
5383 else if (!tleft->is_abstract())
5384 subcontext.type = tleft;
5385 else if (!tright->is_abstract())
5386 subcontext.type = tright;
5387 else if (subcontext.type == NULL)
5389 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5390 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5391 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5393 // Both sides have an abstract integer, abstract float, or
5394 // abstract complex type. Just let CONTEXT determine
5395 // whether they may remain abstract or not.
5397 else if (tleft->complex_type() != NULL)
5398 subcontext.type = tleft;
5399 else if (tright->complex_type() != NULL)
5400 subcontext.type = tright;
5401 else if (tleft->float_type() != NULL)
5402 subcontext.type = tleft;
5403 else if (tright->float_type() != NULL)
5404 subcontext.type = tright;
5406 subcontext.type = tleft;
5408 if (subcontext.type != NULL && !context->may_be_abstract)
5409 subcontext.type = subcontext.type->make_non_abstract_type();
5412 this->left_->determine_type(&subcontext);
5416 // We may have inherited an unusable type for the shift operand.
5417 // Give a useful error if that happened.
5418 if (tleft->is_abstract()
5419 && subcontext.type != NULL
5420 && (this->left_->type()->integer_type() == NULL
5421 || (subcontext.type->integer_type() == NULL
5422 && subcontext.type->float_type() == NULL
5423 && subcontext.type->complex_type() == NULL)))
5424 this->report_error(("invalid context-determined non-integer type "
5425 "for shift operand"));
5427 // The context for the right hand operand is the same as for the
5428 // left hand operand, except for a shift operator.
5429 subcontext.type = Type::lookup_integer_type("uint");
5430 subcontext.may_be_abstract = false;
5433 this->right_->determine_type(&subcontext);
5436 // Report an error if the binary operator OP does not support TYPE.
5437 // OTYPE is the type of the other operand. Return whether the
5438 // operation is OK. This should not be used for shift.
5441 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5447 case OPERATOR_ANDAND:
5448 if (!type->is_boolean_type())
5450 error_at(location, "expected boolean type");
5456 case OPERATOR_NOTEQ:
5459 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5461 error_at(location, "%s", reason.c_str());
5473 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5475 error_at(location, "%s", reason.c_str());
5482 case OPERATOR_PLUSEQ:
5483 if (type->integer_type() == NULL
5484 && type->float_type() == NULL
5485 && type->complex_type() == NULL
5486 && !type->is_string_type())
5489 "expected integer, floating, complex, or string type");
5494 case OPERATOR_MINUS:
5495 case OPERATOR_MINUSEQ:
5497 case OPERATOR_MULTEQ:
5499 case OPERATOR_DIVEQ:
5500 if (type->integer_type() == NULL
5501 && type->float_type() == NULL
5502 && type->complex_type() == NULL)
5504 error_at(location, "expected integer, floating, or complex type");
5510 case OPERATOR_MODEQ:
5514 case OPERATOR_ANDEQ:
5516 case OPERATOR_XOREQ:
5517 case OPERATOR_BITCLEAR:
5518 case OPERATOR_BITCLEAREQ:
5519 if (type->integer_type() == NULL)
5521 error_at(location, "expected integer type");
5536 Binary_expression::do_check_types(Gogo*)
5538 if (this->classification() == EXPRESSION_ERROR)
5541 Type* left_type = this->left_->type();
5542 Type* right_type = this->right_->type();
5543 if (left_type->is_error() || right_type->is_error())
5545 this->set_is_error();
5549 if (this->op_ == OPERATOR_EQEQ
5550 || this->op_ == OPERATOR_NOTEQ
5551 || this->op_ == OPERATOR_LT
5552 || this->op_ == OPERATOR_LE
5553 || this->op_ == OPERATOR_GT
5554 || this->op_ == OPERATOR_GE)
5556 if (!Type::are_assignable(left_type, right_type, NULL)
5557 && !Type::are_assignable(right_type, left_type, NULL))
5559 this->report_error(_("incompatible types in binary expression"));
5562 if (!Binary_expression::check_operator_type(this->op_, left_type,
5565 || !Binary_expression::check_operator_type(this->op_, right_type,
5569 this->set_is_error();
5573 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5575 if (!Type::are_compatible_for_binop(left_type, right_type))
5577 this->report_error(_("incompatible types in binary expression"));
5580 if (!Binary_expression::check_operator_type(this->op_, left_type,
5584 this->set_is_error();
5590 if (left_type->integer_type() == NULL)
5591 this->report_error(_("shift of non-integer operand"));
5593 if (!right_type->is_abstract()
5594 && (right_type->integer_type() == NULL
5595 || !right_type->integer_type()->is_unsigned()))
5596 this->report_error(_("shift count not unsigned integer"));
5599 Numeric_constant nc;
5600 if (this->right_->numeric_constant_value(&nc))
5603 if (!nc.to_int(&val))
5604 this->report_error(_("shift count not unsigned integer"));
5607 if (mpz_sgn(val) < 0)
5609 this->report_error(_("negative shift count"));
5611 Location rloc = this->right_->location();
5612 this->right_ = Expression::make_integer(&val, right_type,
5622 // Get a tree for a binary expression.
5625 Binary_expression::do_get_tree(Translate_context* context)
5627 tree left = this->left_->get_tree(context);
5628 tree right = this->right_->get_tree(context);
5630 if (left == error_mark_node || right == error_mark_node)
5631 return error_mark_node;
5633 enum tree_code code;
5634 bool use_left_type = true;
5635 bool is_shift_op = false;
5639 case OPERATOR_NOTEQ:
5644 return Expression::comparison_tree(context, this->op_,
5645 this->left_->type(), left,
5646 this->right_->type(), right,
5650 code = TRUTH_ORIF_EXPR;
5651 use_left_type = false;
5653 case OPERATOR_ANDAND:
5654 code = TRUTH_ANDIF_EXPR;
5655 use_left_type = false;
5660 case OPERATOR_MINUS:
5664 code = BIT_IOR_EXPR;
5667 code = BIT_XOR_EXPR;
5674 Type *t = this->left_->type();
5675 if (t->float_type() != NULL || t->complex_type() != NULL)
5678 code = TRUNC_DIV_EXPR;
5682 code = TRUNC_MOD_EXPR;
5684 case OPERATOR_LSHIFT:
5688 case OPERATOR_RSHIFT:
5693 code = BIT_AND_EXPR;
5695 case OPERATOR_BITCLEAR:
5696 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5697 code = BIT_AND_EXPR;
5703 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5705 if (this->left_->type()->is_string_type())
5707 go_assert(this->op_ == OPERATOR_PLUS);
5708 Type* st = Type::make_string_type();
5709 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5710 static tree string_plus_decl;
5711 return Gogo::call_builtin(&string_plus_decl,
5722 tree compute_type = excess_precision_type(type);
5723 if (compute_type != NULL_TREE)
5725 left = ::convert(compute_type, left);
5726 right = ::convert(compute_type, right);
5729 tree eval_saved = NULL_TREE;
5732 // Make sure the values are evaluated.
5733 if (!DECL_P(left) && TREE_SIDE_EFFECTS(left))
5735 left = save_expr(left);
5738 if (!DECL_P(right) && TREE_SIDE_EFFECTS(right))
5740 right = save_expr(right);
5741 if (eval_saved == NULL_TREE)
5744 eval_saved = fold_build2_loc(this->location().gcc_location(),
5746 void_type_node, eval_saved, right);
5750 tree ret = fold_build2_loc(this->location().gcc_location(),
5752 compute_type != NULL_TREE ? compute_type : type,
5755 if (compute_type != NULL_TREE)
5756 ret = ::convert(type, ret);
5758 // In Go, a shift larger than the size of the type is well-defined.
5759 // This is not true in GENERIC, so we need to insert a conditional.
5762 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5763 go_assert(this->left_->type()->integer_type() != NULL);
5764 int bits = TYPE_PRECISION(TREE_TYPE(left));
5766 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5767 build_int_cst_type(TREE_TYPE(right), bits));
5769 tree overflow_result = fold_convert_loc(this->location().gcc_location(),
5772 if (this->op_ == OPERATOR_RSHIFT
5773 && !this->left_->type()->integer_type()->is_unsigned())
5776 fold_build2_loc(this->location().gcc_location(), LT_EXPR,
5777 boolean_type_node, left,
5778 fold_convert_loc(this->location().gcc_location(),
5780 integer_zero_node));
5782 fold_build2_loc(this->location().gcc_location(),
5783 MINUS_EXPR, TREE_TYPE(left),
5784 fold_convert_loc(this->location().gcc_location(),
5787 fold_convert_loc(this->location().gcc_location(),
5791 fold_build3_loc(this->location().gcc_location(), COND_EXPR,
5792 TREE_TYPE(left), neg, neg_one,
5796 ret = fold_build3_loc(this->location().gcc_location(), COND_EXPR,
5797 TREE_TYPE(left), compare, ret, overflow_result);
5799 if (eval_saved != NULL_TREE)
5800 ret = fold_build2_loc(this->location().gcc_location(), COMPOUND_EXPR,
5801 TREE_TYPE(ret), eval_saved, ret);
5807 // Export a binary expression.
5810 Binary_expression::do_export(Export* exp) const
5812 exp->write_c_string("(");
5813 this->left_->export_expression(exp);
5817 exp->write_c_string(" || ");
5819 case OPERATOR_ANDAND:
5820 exp->write_c_string(" && ");
5823 exp->write_c_string(" == ");
5825 case OPERATOR_NOTEQ:
5826 exp->write_c_string(" != ");
5829 exp->write_c_string(" < ");
5832 exp->write_c_string(" <= ");
5835 exp->write_c_string(" > ");
5838 exp->write_c_string(" >= ");
5841 exp->write_c_string(" + ");
5843 case OPERATOR_MINUS:
5844 exp->write_c_string(" - ");
5847 exp->write_c_string(" | ");
5850 exp->write_c_string(" ^ ");
5853 exp->write_c_string(" * ");
5856 exp->write_c_string(" / ");
5859 exp->write_c_string(" % ");
5861 case OPERATOR_LSHIFT:
5862 exp->write_c_string(" << ");
5864 case OPERATOR_RSHIFT:
5865 exp->write_c_string(" >> ");
5868 exp->write_c_string(" & ");
5870 case OPERATOR_BITCLEAR:
5871 exp->write_c_string(" &^ ");
5876 this->right_->export_expression(exp);
5877 exp->write_c_string(")");
5880 // Import a binary expression.
5883 Binary_expression::do_import(Import* imp)
5885 imp->require_c_string("(");
5887 Expression* left = Expression::import_expression(imp);
5890 if (imp->match_c_string(" || "))
5895 else if (imp->match_c_string(" && "))
5897 op = OPERATOR_ANDAND;
5900 else if (imp->match_c_string(" == "))
5905 else if (imp->match_c_string(" != "))
5907 op = OPERATOR_NOTEQ;
5910 else if (imp->match_c_string(" < "))
5915 else if (imp->match_c_string(" <= "))
5920 else if (imp->match_c_string(" > "))
5925 else if (imp->match_c_string(" >= "))
5930 else if (imp->match_c_string(" + "))
5935 else if (imp->match_c_string(" - "))
5937 op = OPERATOR_MINUS;
5940 else if (imp->match_c_string(" | "))
5945 else if (imp->match_c_string(" ^ "))
5950 else if (imp->match_c_string(" * "))
5955 else if (imp->match_c_string(" / "))
5960 else if (imp->match_c_string(" % "))
5965 else if (imp->match_c_string(" << "))
5967 op = OPERATOR_LSHIFT;
5970 else if (imp->match_c_string(" >> "))
5972 op = OPERATOR_RSHIFT;
5975 else if (imp->match_c_string(" & "))
5980 else if (imp->match_c_string(" &^ "))
5982 op = OPERATOR_BITCLEAR;
5987 error_at(imp->location(), "unrecognized binary operator");
5988 return Expression::make_error(imp->location());
5991 Expression* right = Expression::import_expression(imp);
5993 imp->require_c_string(")");
5995 return Expression::make_binary(op, left, right, imp->location());
5998 // Dump ast representation of a binary expression.
6001 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6003 ast_dump_context->ostream() << "(";
6004 ast_dump_context->dump_expression(this->left_);
6005 ast_dump_context->ostream() << " ";
6006 ast_dump_context->dump_operator(this->op_);
6007 ast_dump_context->ostream() << " ";
6008 ast_dump_context->dump_expression(this->right_);
6009 ast_dump_context->ostream() << ") ";
6012 // Make a binary expression.
6015 Expression::make_binary(Operator op, Expression* left, Expression* right,
6018 return new Binary_expression(op, left, right, location);
6021 // Implement a comparison.
6024 Expression::comparison_tree(Translate_context* context, Operator op,
6025 Type* left_type, tree left_tree,
6026 Type* right_type, tree right_tree,
6029 enum tree_code code;
6035 case OPERATOR_NOTEQ:
6054 if (left_type->is_string_type() && right_type->is_string_type())
6056 Type* st = Type::make_string_type();
6057 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6058 static tree string_compare_decl;
6059 left_tree = Gogo::call_builtin(&string_compare_decl,
6068 right_tree = build_int_cst_type(integer_type_node, 0);
6070 else if ((left_type->interface_type() != NULL
6071 && right_type->interface_type() == NULL
6072 && !right_type->is_nil_type())
6073 || (left_type->interface_type() == NULL
6074 && !left_type->is_nil_type()
6075 && right_type->interface_type() != NULL))
6077 // Comparing an interface value to a non-interface value.
6078 if (left_type->interface_type() == NULL)
6080 std::swap(left_type, right_type);
6081 std::swap(left_tree, right_tree);
6084 // The right operand is not an interface. We need to take its
6085 // address if it is not a pointer.
6088 if (right_type->points_to() != NULL)
6090 make_tmp = NULL_TREE;
6093 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree))
6095 make_tmp = NULL_TREE;
6096 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6097 if (DECL_P(right_tree))
6098 TREE_ADDRESSABLE(right_tree) = 1;
6102 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6103 get_name(right_tree));
6104 DECL_IGNORED_P(tmp) = 0;
6105 DECL_INITIAL(tmp) = right_tree;
6106 TREE_ADDRESSABLE(tmp) = 1;
6107 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6108 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6109 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6111 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6113 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6116 if (left_type->interface_type()->is_empty())
6118 static tree empty_interface_value_compare_decl;
6119 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6121 "__go_empty_interface_value_compare",
6124 TREE_TYPE(left_tree),
6126 TREE_TYPE(descriptor),
6130 if (left_tree == error_mark_node)
6131 return error_mark_node;
6132 // This can panic if the type is not comparable.
6133 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6137 static tree interface_value_compare_decl;
6138 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6140 "__go_interface_value_compare",
6143 TREE_TYPE(left_tree),
6145 TREE_TYPE(descriptor),
6149 if (left_tree == error_mark_node)
6150 return error_mark_node;
6151 // This can panic if the type is not comparable.
6152 TREE_NOTHROW(interface_value_compare_decl) = 0;
6154 right_tree = build_int_cst_type(integer_type_node, 0);
6156 if (make_tmp != NULL_TREE)
6157 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6160 else if (left_type->interface_type() != NULL
6161 && right_type->interface_type() != NULL)
6163 if (left_type->interface_type()->is_empty()
6164 && right_type->interface_type()->is_empty())
6166 static tree empty_interface_compare_decl;
6167 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6169 "__go_empty_interface_compare",
6172 TREE_TYPE(left_tree),
6174 TREE_TYPE(right_tree),
6176 if (left_tree == error_mark_node)
6177 return error_mark_node;
6178 // This can panic if the type is uncomparable.
6179 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6181 else if (!left_type->interface_type()->is_empty()
6182 && !right_type->interface_type()->is_empty())
6184 static tree interface_compare_decl;
6185 left_tree = Gogo::call_builtin(&interface_compare_decl,
6187 "__go_interface_compare",
6190 TREE_TYPE(left_tree),
6192 TREE_TYPE(right_tree),
6194 if (left_tree == error_mark_node)
6195 return error_mark_node;
6196 // This can panic if the type is uncomparable.
6197 TREE_NOTHROW(interface_compare_decl) = 0;
6201 if (left_type->interface_type()->is_empty())
6203 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6204 std::swap(left_type, right_type);
6205 std::swap(left_tree, right_tree);
6207 go_assert(!left_type->interface_type()->is_empty());
6208 go_assert(right_type->interface_type()->is_empty());
6209 static tree interface_empty_compare_decl;
6210 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6212 "__go_interface_empty_compare",
6215 TREE_TYPE(left_tree),
6217 TREE_TYPE(right_tree),
6219 if (left_tree == error_mark_node)
6220 return error_mark_node;
6221 // This can panic if the type is uncomparable.
6222 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6225 right_tree = build_int_cst_type(integer_type_node, 0);
6228 if (left_type->is_nil_type()
6229 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6231 std::swap(left_type, right_type);
6232 std::swap(left_tree, right_tree);
6235 if (right_type->is_nil_type())
6237 if (left_type->array_type() != NULL
6238 && left_type->array_type()->length() == NULL)
6240 Array_type* at = left_type->array_type();
6241 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6242 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6244 else if (left_type->interface_type() != NULL)
6246 // An interface is nil if the first field is nil.
6247 tree left_type_tree = TREE_TYPE(left_tree);
6248 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6249 tree field = TYPE_FIELDS(left_type_tree);
6250 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6252 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6256 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6257 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6261 if (left_tree == error_mark_node || right_tree == error_mark_node)
6262 return error_mark_node;
6264 tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6265 if (CAN_HAVE_LOCATION_P(ret))
6266 SET_EXPR_LOCATION(ret, location.gcc_location());
6270 // Class Bound_method_expression.
6275 Bound_method_expression::do_traverse(Traverse* traverse)
6277 return Expression::traverse(&this->expr_, traverse);
6280 // Return the type of a bound method expression. The type of this
6281 // object is really the type of the method with no receiver. We
6282 // should be able to get away with just returning the type of the
6286 Bound_method_expression::do_type()
6288 if (this->method_->is_function())
6289 return this->method_->func_value()->type();
6290 else if (this->method_->is_function_declaration())
6291 return this->method_->func_declaration_value()->type();
6293 return Type::make_error_type();
6296 // Determine the types of a method expression.
6299 Bound_method_expression::do_determine_type(const Type_context*)
6301 Function_type* fntype = this->type()->function_type();
6302 if (fntype == NULL || !fntype->is_method())
6303 this->expr_->determine_type_no_context();
6306 Type_context subcontext(fntype->receiver()->type(), false);
6307 this->expr_->determine_type(&subcontext);
6311 // Check the types of a method expression.
6314 Bound_method_expression::do_check_types(Gogo*)
6316 if (!this->method_->is_function()
6317 && !this->method_->is_function_declaration())
6318 this->report_error(_("object is not a method"));
6321 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6322 Type* etype = (this->expr_type_ != NULL
6324 : this->expr_->type());
6325 etype = etype->deref();
6326 if (!Type::are_identical(rtype, etype, true, NULL))
6327 this->report_error(_("method type does not match object type"));
6331 // Get the tree for a method expression. There is no standard tree
6332 // representation for this. The only places it may currently be used
6333 // are in a Call_expression or a Go_statement, which will take it
6334 // apart directly. So this has nothing to do at present.
6337 Bound_method_expression::do_get_tree(Translate_context*)
6339 error_at(this->location(), "reference to method other than calling it");
6340 return error_mark_node;
6343 // Dump ast representation of a bound method expression.
6346 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6349 if (this->expr_type_ != NULL)
6350 ast_dump_context->ostream() << "(";
6351 ast_dump_context->dump_expression(this->expr_);
6352 if (this->expr_type_ != NULL)
6354 ast_dump_context->ostream() << ":";
6355 ast_dump_context->dump_type(this->expr_type_);
6356 ast_dump_context->ostream() << ")";
6359 ast_dump_context->ostream() << "." << this->method_->name();
6362 // Make a method expression.
6364 Bound_method_expression*
6365 Expression::make_bound_method(Expression* expr, Named_object* method,
6368 return new Bound_method_expression(expr, method, location);
6371 // Class Builtin_call_expression. This is used for a call to a
6372 // builtin function.
6374 class Builtin_call_expression : public Call_expression
6377 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6378 bool is_varargs, Location location);
6381 // This overrides Call_expression::do_lower.
6383 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6386 do_is_constant() const;
6389 do_numeric_constant_value(Numeric_constant*) const;
6392 do_discarding_value();
6398 do_determine_type(const Type_context*);
6401 do_check_types(Gogo*);
6406 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6407 this->args()->copy(),
6413 do_get_tree(Translate_context*);
6416 do_export(Export*) const;
6419 do_is_recover_call() const;
6422 do_set_recover_arg(Expression*);
6425 // The builtin functions.
6426 enum Builtin_function_code
6430 // Predeclared builtin functions.
6447 // Builtin functions from the unsafe package.
6460 real_imag_type(Type*);
6463 complex_type(Type*);
6469 check_int_value(Expression*);
6471 // A pointer back to the general IR structure. This avoids a global
6472 // variable, or passing it around everywhere.
6474 // The builtin function being called.
6475 Builtin_function_code code_;
6476 // Used to stop endless loops when the length of an array uses len
6477 // or cap of the array itself.
6481 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6483 Expression_list* args,
6486 : Call_expression(fn, args, is_varargs, location),
6487 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6489 Func_expression* fnexp = this->fn()->func_expression();
6490 go_assert(fnexp != NULL);
6491 const std::string& name(fnexp->named_object()->name());
6492 if (name == "append")
6493 this->code_ = BUILTIN_APPEND;
6494 else if (name == "cap")
6495 this->code_ = BUILTIN_CAP;
6496 else if (name == "close")
6497 this->code_ = BUILTIN_CLOSE;
6498 else if (name == "complex")
6499 this->code_ = BUILTIN_COMPLEX;
6500 else if (name == "copy")
6501 this->code_ = BUILTIN_COPY;
6502 else if (name == "delete")
6503 this->code_ = BUILTIN_DELETE;
6504 else if (name == "imag")
6505 this->code_ = BUILTIN_IMAG;
6506 else if (name == "len")
6507 this->code_ = BUILTIN_LEN;
6508 else if (name == "make")
6509 this->code_ = BUILTIN_MAKE;
6510 else if (name == "new")
6511 this->code_ = BUILTIN_NEW;
6512 else if (name == "panic")
6513 this->code_ = BUILTIN_PANIC;
6514 else if (name == "print")
6515 this->code_ = BUILTIN_PRINT;
6516 else if (name == "println")
6517 this->code_ = BUILTIN_PRINTLN;
6518 else if (name == "real")
6519 this->code_ = BUILTIN_REAL;
6520 else if (name == "recover")
6521 this->code_ = BUILTIN_RECOVER;
6522 else if (name == "Alignof")
6523 this->code_ = BUILTIN_ALIGNOF;
6524 else if (name == "Offsetof")
6525 this->code_ = BUILTIN_OFFSETOF;
6526 else if (name == "Sizeof")
6527 this->code_ = BUILTIN_SIZEOF;
6532 // Return whether this is a call to recover. This is a virtual
6533 // function called from the parent class.
6536 Builtin_call_expression::do_is_recover_call() const
6538 if (this->classification() == EXPRESSION_ERROR)
6540 return this->code_ == BUILTIN_RECOVER;
6543 // Set the argument for a call to recover.
6546 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6548 const Expression_list* args = this->args();
6549 go_assert(args == NULL || args->empty());
6550 Expression_list* new_args = new Expression_list();
6551 new_args->push_back(arg);
6552 this->set_args(new_args);
6555 // A traversal class which looks for a call expression.
6557 class Find_call_expression : public Traverse
6560 Find_call_expression()
6561 : Traverse(traverse_expressions),
6566 expression(Expression**);
6570 { return this->found_; }
6577 Find_call_expression::expression(Expression** pexpr)
6579 if ((*pexpr)->call_expression() != NULL)
6581 this->found_ = true;
6582 return TRAVERSE_EXIT;
6584 return TRAVERSE_CONTINUE;
6587 // Lower a builtin call expression. This turns new and make into
6588 // specific expressions. We also convert to a constant if we can.
6591 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6592 Statement_inserter* inserter, int)
6594 if (this->classification() == EXPRESSION_ERROR)
6597 Location loc = this->location();
6599 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6601 this->report_error(_("invalid use of %<...%> with builtin function"));
6602 return Expression::make_error(loc);
6605 if (this->is_constant())
6607 // We can only lower len and cap if there are no function calls
6608 // in the arguments. Otherwise we have to make the call.
6609 if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6611 Expression* arg = this->one_arg();
6612 if (!arg->is_constant())
6614 Find_call_expression find_call;
6615 Expression::traverse(&arg, &find_call);
6616 if (find_call.found())
6621 Numeric_constant nc;
6622 if (this->numeric_constant_value(&nc))
6623 return nc.expression(loc);
6626 switch (this->code_)
6633 const Expression_list* args = this->args();
6634 if (args == NULL || args->size() < 1)
6635 this->report_error(_("not enough arguments"));
6636 else if (args->size() > 1)
6637 this->report_error(_("too many arguments"));
6640 Expression* arg = args->front();
6641 if (!arg->is_type_expression())
6643 error_at(arg->location(), "expected type");
6644 this->set_is_error();
6647 return Expression::make_allocation(arg->type(), loc);
6653 return this->lower_make();
6655 case BUILTIN_RECOVER:
6656 if (function != NULL)
6657 function->func_value()->set_calls_recover();
6660 // Calling recover outside of a function always returns the
6661 // nil empty interface.
6662 Type* eface = Type::make_empty_interface_type(loc);
6663 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6667 case BUILTIN_APPEND:
6669 // Lower the varargs.
6670 const Expression_list* args = this->args();
6671 if (args == NULL || args->empty())
6673 Type* slice_type = args->front()->type();
6674 if (!slice_type->is_slice_type())
6676 error_at(args->front()->location(), "argument 1 must be a slice");
6677 this->set_is_error();
6680 Type* element_type = slice_type->array_type()->element_type();
6681 this->lower_varargs(gogo, function, inserter,
6682 Type::make_array_type(element_type, NULL),
6687 case BUILTIN_DELETE:
6689 // Lower to a runtime function call.
6690 const Expression_list* args = this->args();
6691 if (args == NULL || args->size() < 2)
6692 this->report_error(_("not enough arguments"));
6693 else if (args->size() > 2)
6694 this->report_error(_("too many arguments"));
6695 else if (args->front()->type()->map_type() == NULL)
6696 this->report_error(_("argument 1 must be a map"));
6699 // Since this function returns no value it must appear in
6700 // a statement by itself, so we don't have to worry about
6701 // order of evaluation of values around it. Evaluate the
6702 // map first to get order of evaluation right.
6703 Map_type* mt = args->front()->type()->map_type();
6704 Temporary_statement* map_temp =
6705 Statement::make_temporary(mt, args->front(), loc);
6706 inserter->insert(map_temp);
6708 Temporary_statement* key_temp =
6709 Statement::make_temporary(mt->key_type(), args->back(), loc);
6710 inserter->insert(key_temp);
6712 Expression* e1 = Expression::make_temporary_reference(map_temp,
6714 Expression* e2 = Expression::make_temporary_reference(key_temp,
6716 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6717 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6727 // Lower a make expression.
6730 Builtin_call_expression::lower_make()
6732 Location loc = this->location();
6734 const Expression_list* args = this->args();
6735 if (args == NULL || args->size() < 1)
6737 this->report_error(_("not enough arguments"));
6738 return Expression::make_error(this->location());
6741 Expression_list::const_iterator parg = args->begin();
6743 Expression* first_arg = *parg;
6744 if (!first_arg->is_type_expression())
6746 error_at(first_arg->location(), "expected type");
6747 this->set_is_error();
6748 return Expression::make_error(this->location());
6750 Type* type = first_arg->type();
6752 bool is_slice = false;
6753 bool is_map = false;
6754 bool is_chan = false;
6755 if (type->is_slice_type())
6757 else if (type->map_type() != NULL)
6759 else if (type->channel_type() != NULL)
6763 this->report_error(_("invalid type for make function"));
6764 return Expression::make_error(this->location());
6767 bool have_big_args = false;
6768 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6769 int uintptr_bits = uintptr_type->integer_type()->bits();
6772 Expression* len_arg;
6773 if (parg == args->end())
6777 this->report_error(_("length required when allocating a slice"));
6778 return Expression::make_error(this->location());
6782 mpz_init_set_ui(zval, 0);
6783 len_arg = Expression::make_integer(&zval, NULL, loc);
6789 if (!this->check_int_value(len_arg))
6791 this->report_error(_("bad size for make"));
6792 return Expression::make_error(this->location());
6794 if (len_arg->type()->integer_type() != NULL
6795 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6796 have_big_args = true;
6800 Expression* cap_arg = NULL;
6801 if (is_slice && parg != args->end())
6804 if (!this->check_int_value(cap_arg))
6806 this->report_error(_("bad capacity when making slice"));
6807 return Expression::make_error(this->location());
6809 if (cap_arg->type()->integer_type() != NULL
6810 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6811 have_big_args = true;
6815 if (parg != args->end())
6817 this->report_error(_("too many arguments to make"));
6818 return Expression::make_error(this->location());
6821 Location type_loc = first_arg->location();
6822 Expression* type_arg;
6823 if (is_slice || is_chan)
6824 type_arg = Expression::make_type_descriptor(type, type_loc);
6826 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6833 if (cap_arg == NULL)
6834 call = Runtime::make_call((have_big_args
6835 ? Runtime::MAKESLICE1BIG
6836 : Runtime::MAKESLICE1),
6837 loc, 2, type_arg, len_arg);
6839 call = Runtime::make_call((have_big_args
6840 ? Runtime::MAKESLICE2BIG
6841 : Runtime::MAKESLICE2),
6842 loc, 3, type_arg, len_arg, cap_arg);
6845 call = Runtime::make_call((have_big_args
6846 ? Runtime::MAKEMAPBIG
6847 : Runtime::MAKEMAP),
6848 loc, 2, type_arg, len_arg);
6850 call = Runtime::make_call((have_big_args
6851 ? Runtime::MAKECHANBIG
6852 : Runtime::MAKECHAN),
6853 loc, 2, type_arg, len_arg);
6857 return Expression::make_unsafe_cast(type, call, loc);
6860 // Return whether an expression has an integer value. Report an error
6861 // if not. This is used when handling calls to the predeclared make
6865 Builtin_call_expression::check_int_value(Expression* e)
6867 if (e->type()->integer_type() != NULL)
6870 // Check for a floating point constant with integer value.
6871 Numeric_constant nc;
6873 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6882 // Return the type of the real or imag functions, given the type of
6883 // the argument. We need to map complex to float, complex64 to
6884 // float32, and complex128 to float64, so it has to be done by name.
6885 // This returns NULL if it can't figure out the type.
6888 Builtin_call_expression::real_imag_type(Type* arg_type)
6890 if (arg_type == NULL || arg_type->is_abstract())
6892 Named_type* nt = arg_type->named_type();
6895 while (nt->real_type()->named_type() != NULL)
6896 nt = nt->real_type()->named_type();
6897 if (nt->name() == "complex64")
6898 return Type::lookup_float_type("float32");
6899 else if (nt->name() == "complex128")
6900 return Type::lookup_float_type("float64");
6905 // Return the type of the complex function, given the type of one of the
6906 // argments. Like real_imag_type, we have to map by name.
6909 Builtin_call_expression::complex_type(Type* arg_type)
6911 if (arg_type == NULL || arg_type->is_abstract())
6913 Named_type* nt = arg_type->named_type();
6916 while (nt->real_type()->named_type() != NULL)
6917 nt = nt->real_type()->named_type();
6918 if (nt->name() == "float32")
6919 return Type::lookup_complex_type("complex64");
6920 else if (nt->name() == "float64")
6921 return Type::lookup_complex_type("complex128");
6926 // Return a single argument, or NULL if there isn't one.
6929 Builtin_call_expression::one_arg() const
6931 const Expression_list* args = this->args();
6932 if (args->size() != 1)
6934 return args->front();
6937 // Return whether this is constant: len of a string, or len or cap of
6938 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
6941 Builtin_call_expression::do_is_constant() const
6943 switch (this->code_)
6951 Expression* arg = this->one_arg();
6954 Type* arg_type = arg->type();
6956 if (arg_type->points_to() != NULL
6957 && arg_type->points_to()->array_type() != NULL
6958 && !arg_type->points_to()->is_slice_type())
6959 arg_type = arg_type->points_to();
6961 if (arg_type->array_type() != NULL
6962 && arg_type->array_type()->length() != NULL)
6965 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
6968 bool ret = arg->is_constant();
6969 this->seen_ = false;
6975 case BUILTIN_SIZEOF:
6976 case BUILTIN_ALIGNOF:
6977 return this->one_arg() != NULL;
6979 case BUILTIN_OFFSETOF:
6981 Expression* arg = this->one_arg();
6984 return arg->field_reference_expression() != NULL;
6987 case BUILTIN_COMPLEX:
6989 const Expression_list* args = this->args();
6990 if (args != NULL && args->size() == 2)
6991 return args->front()->is_constant() && args->back()->is_constant();
6998 Expression* arg = this->one_arg();
6999 return arg != NULL && arg->is_constant();
7009 // Return a numeric constant if possible.
7012 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7014 if (this->code_ == BUILTIN_LEN
7015 || this->code_ == BUILTIN_CAP)
7017 Expression* arg = this->one_arg();
7020 Type* arg_type = arg->type();
7022 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7025 if (arg->string_constant_value(&sval))
7027 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7033 if (arg_type->points_to() != NULL
7034 && arg_type->points_to()->array_type() != NULL
7035 && !arg_type->points_to()->is_slice_type())
7036 arg_type = arg_type->points_to();
7038 if (arg_type->array_type() != NULL
7039 && arg_type->array_type()->length() != NULL)
7043 Expression* e = arg_type->array_type()->length();
7045 bool r = e->numeric_constant_value(nc);
7046 this->seen_ = false;
7049 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7056 else if (this->code_ == BUILTIN_SIZEOF
7057 || this->code_ == BUILTIN_ALIGNOF)
7059 Expression* arg = this->one_arg();
7062 Type* arg_type = arg->type();
7063 if (arg_type->is_error())
7065 if (arg_type->is_abstract())
7067 if (arg_type->named_type() != NULL)
7068 arg_type->named_type()->convert(this->gogo_);
7071 if (this->code_ == BUILTIN_SIZEOF)
7073 if (!arg_type->backend_type_size(this->gogo_, &ret))
7076 else if (this->code_ == BUILTIN_ALIGNOF)
7078 if (arg->field_reference_expression() == NULL)
7080 if (!arg_type->backend_type_align(this->gogo_, &ret))
7085 // Calling unsafe.Alignof(s.f) returns the alignment of
7086 // the type of f when it is used as a field in a struct.
7087 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7094 nc->set_unsigned_long(NULL, static_cast<unsigned long>(ret));
7097 else if (this->code_ == BUILTIN_OFFSETOF)
7099 Expression* arg = this->one_arg();
7102 Field_reference_expression* farg = arg->field_reference_expression();
7105 Expression* struct_expr = farg->expr();
7106 Type* st = struct_expr->type();
7107 if (st->struct_type() == NULL)
7109 if (st->named_type() != NULL)
7110 st->named_type()->convert(this->gogo_);
7111 unsigned int offset;
7112 if (!st->struct_type()->backend_field_offset(this->gogo_,
7113 farg->field_index(),
7116 nc->set_unsigned_long(NULL, static_cast<unsigned long>(offset));
7119 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7121 Expression* arg = this->one_arg();
7125 Numeric_constant argnc;
7126 if (!arg->numeric_constant_value(&argnc))
7131 if (!argnc.to_complex(&real, &imag))
7134 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7135 if (this->code_ == BUILTIN_REAL)
7136 nc->set_float(type, real);
7138 nc->set_float(type, imag);
7141 else if (this->code_ == BUILTIN_COMPLEX)
7143 const Expression_list* args = this->args();
7144 if (args == NULL || args->size() != 2)
7147 Numeric_constant rnc;
7148 if (!args->front()->numeric_constant_value(&rnc))
7150 Numeric_constant inc;
7151 if (!args->back()->numeric_constant_value(&inc))
7154 if (rnc.type() != NULL
7155 && !rnc.type()->is_abstract()
7156 && inc.type() != NULL
7157 && !inc.type()->is_abstract()
7158 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7162 if (!rnc.to_float(&r))
7165 if (!inc.to_float(&i))
7171 Type* arg_type = rnc.type();
7172 if (arg_type == NULL || arg_type->is_abstract())
7173 arg_type = inc.type();
7175 Type* type = Builtin_call_expression::complex_type(arg_type);
7176 nc->set_complex(type, r, i);
7187 // Give an error if we are discarding the value of an expression which
7188 // should not normally be discarded. We don't give an error for
7189 // discarding the value of an ordinary function call, but we do for
7190 // builtin functions, purely for consistency with the gc compiler.
7193 Builtin_call_expression::do_discarding_value()
7195 switch (this->code_)
7197 case BUILTIN_INVALID:
7201 case BUILTIN_APPEND:
7203 case BUILTIN_COMPLEX:
7209 case BUILTIN_ALIGNOF:
7210 case BUILTIN_OFFSETOF:
7211 case BUILTIN_SIZEOF:
7212 this->unused_value_error();
7217 case BUILTIN_DELETE:
7220 case BUILTIN_PRINTLN:
7221 case BUILTIN_RECOVER:
7229 Builtin_call_expression::do_type()
7231 switch (this->code_)
7233 case BUILTIN_INVALID:
7240 const Expression_list* args = this->args();
7241 if (args == NULL || args->empty())
7242 return Type::make_error_type();
7243 return Type::make_pointer_type(args->front()->type());
7249 case BUILTIN_ALIGNOF:
7250 case BUILTIN_OFFSETOF:
7251 case BUILTIN_SIZEOF:
7252 return Type::lookup_integer_type("int");
7255 case BUILTIN_DELETE:
7258 case BUILTIN_PRINTLN:
7259 return Type::make_void_type();
7261 case BUILTIN_RECOVER:
7262 return Type::make_empty_interface_type(Linemap::predeclared_location());
7264 case BUILTIN_APPEND:
7266 const Expression_list* args = this->args();
7267 if (args == NULL || args->empty())
7268 return Type::make_error_type();
7269 return args->front()->type();
7275 Expression* arg = this->one_arg();
7277 return Type::make_error_type();
7278 Type* t = arg->type();
7279 if (t->is_abstract())
7280 t = t->make_non_abstract_type();
7281 t = Builtin_call_expression::real_imag_type(t);
7283 t = Type::make_error_type();
7287 case BUILTIN_COMPLEX:
7289 const Expression_list* args = this->args();
7290 if (args == NULL || args->size() != 2)
7291 return Type::make_error_type();
7292 Type* t = args->front()->type();
7293 if (t->is_abstract())
7295 t = args->back()->type();
7296 if (t->is_abstract())
7297 t = t->make_non_abstract_type();
7299 t = Builtin_call_expression::complex_type(t);
7301 t = Type::make_error_type();
7307 // Determine the type.
7310 Builtin_call_expression::do_determine_type(const Type_context* context)
7312 if (!this->determining_types())
7315 this->fn()->determine_type_no_context();
7317 const Expression_list* args = this->args();
7320 Type* arg_type = NULL;
7321 switch (this->code_)
7324 case BUILTIN_PRINTLN:
7325 // Do not force a large integer constant to "int".
7331 arg_type = Builtin_call_expression::complex_type(context->type);
7335 case BUILTIN_COMPLEX:
7337 // For the complex function the type of one operand can
7338 // determine the type of the other, as in a binary expression.
7339 arg_type = Builtin_call_expression::real_imag_type(context->type);
7340 if (args != NULL && args->size() == 2)
7342 Type* t1 = args->front()->type();
7343 Type* t2 = args->front()->type();
7344 if (!t1->is_abstract())
7346 else if (!t2->is_abstract())
7360 for (Expression_list::const_iterator pa = args->begin();
7364 Type_context subcontext;
7365 subcontext.type = arg_type;
7369 // We want to print large constants, we so can't just
7370 // use the appropriate nonabstract type. Use uint64 for
7371 // an integer if we know it is nonnegative, otherwise
7372 // use int64 for a integer, otherwise use float64 for a
7373 // float or complex128 for a complex.
7374 Type* want_type = NULL;
7375 Type* atype = (*pa)->type();
7376 if (atype->is_abstract())
7378 if (atype->integer_type() != NULL)
7380 Numeric_constant nc;
7381 if (this->numeric_constant_value(&nc))
7384 if (nc.to_int(&val))
7386 if (mpz_sgn(val) >= 0)
7387 want_type = Type::lookup_integer_type("uint64");
7391 if (want_type == NULL)
7392 want_type = Type::lookup_integer_type("int64");
7394 else if (atype->float_type() != NULL)
7395 want_type = Type::lookup_float_type("float64");
7396 else if (atype->complex_type() != NULL)
7397 want_type = Type::lookup_complex_type("complex128");
7398 else if (atype->is_abstract_string_type())
7399 want_type = Type::lookup_string_type();
7400 else if (atype->is_abstract_boolean_type())
7401 want_type = Type::lookup_bool_type();
7404 subcontext.type = want_type;
7408 (*pa)->determine_type(&subcontext);
7413 // If there is exactly one argument, return true. Otherwise give an
7414 // error message and return false.
7417 Builtin_call_expression::check_one_arg()
7419 const Expression_list* args = this->args();
7420 if (args == NULL || args->size() < 1)
7422 this->report_error(_("not enough arguments"));
7425 else if (args->size() > 1)
7427 this->report_error(_("too many arguments"));
7430 if (args->front()->is_error_expression()
7431 || args->front()->type()->is_error())
7433 this->set_is_error();
7439 // Check argument types for a builtin function.
7442 Builtin_call_expression::do_check_types(Gogo*)
7444 switch (this->code_)
7446 case BUILTIN_INVALID:
7449 case BUILTIN_DELETE:
7455 // The single argument may be either a string or an array or a
7456 // map or a channel, or a pointer to a closed array.
7457 if (this->check_one_arg())
7459 Type* arg_type = this->one_arg()->type();
7460 if (arg_type->points_to() != NULL
7461 && arg_type->points_to()->array_type() != NULL
7462 && !arg_type->points_to()->is_slice_type())
7463 arg_type = arg_type->points_to();
7464 if (this->code_ == BUILTIN_CAP)
7466 if (!arg_type->is_error()
7467 && arg_type->array_type() == NULL
7468 && arg_type->channel_type() == NULL)
7469 this->report_error(_("argument must be array or slice "
7474 if (!arg_type->is_error()
7475 && !arg_type->is_string_type()
7476 && arg_type->array_type() == NULL
7477 && arg_type->map_type() == NULL
7478 && arg_type->channel_type() == NULL)
7479 this->report_error(_("argument must be string or "
7480 "array or slice or map or channel"));
7487 case BUILTIN_PRINTLN:
7489 const Expression_list* args = this->args();
7492 if (this->code_ == BUILTIN_PRINT)
7493 warning_at(this->location(), 0,
7494 "no arguments for builtin function %<%s%>",
7495 (this->code_ == BUILTIN_PRINT
7501 for (Expression_list::const_iterator p = args->begin();
7505 Type* type = (*p)->type();
7506 if (type->is_error()
7507 || type->is_string_type()
7508 || type->integer_type() != NULL
7509 || type->float_type() != NULL
7510 || type->complex_type() != NULL
7511 || type->is_boolean_type()
7512 || type->points_to() != NULL
7513 || type->interface_type() != NULL
7514 || type->channel_type() != NULL
7515 || type->map_type() != NULL
7516 || type->function_type() != NULL
7517 || type->is_slice_type())
7519 else if ((*p)->is_type_expression())
7521 // If this is a type expression it's going to give
7522 // an error anyhow, so we don't need one here.
7525 this->report_error(_("unsupported argument type to "
7526 "builtin function"));
7533 if (this->check_one_arg())
7535 if (this->one_arg()->type()->channel_type() == NULL)
7536 this->report_error(_("argument must be channel"));
7537 else if (!this->one_arg()->type()->channel_type()->may_send())
7538 this->report_error(_("cannot close receive-only channel"));
7543 case BUILTIN_SIZEOF:
7544 case BUILTIN_ALIGNOF:
7545 this->check_one_arg();
7548 case BUILTIN_RECOVER:
7549 if (this->args() != NULL && !this->args()->empty())
7550 this->report_error(_("too many arguments"));
7553 case BUILTIN_OFFSETOF:
7554 if (this->check_one_arg())
7556 Expression* arg = this->one_arg();
7557 if (arg->field_reference_expression() == NULL)
7558 this->report_error(_("argument must be a field reference"));
7564 const Expression_list* args = this->args();
7565 if (args == NULL || args->size() < 2)
7567 this->report_error(_("not enough arguments"));
7570 else if (args->size() > 2)
7572 this->report_error(_("too many arguments"));
7575 Type* arg1_type = args->front()->type();
7576 Type* arg2_type = args->back()->type();
7577 if (arg1_type->is_error() || arg2_type->is_error())
7581 if (arg1_type->is_slice_type())
7582 e1 = arg1_type->array_type()->element_type();
7585 this->report_error(_("left argument must be a slice"));
7589 if (arg2_type->is_slice_type())
7591 Type* e2 = arg2_type->array_type()->element_type();
7592 if (!Type::are_identical(e1, e2, true, NULL))
7593 this->report_error(_("element types must be the same"));
7595 else if (arg2_type->is_string_type())
7597 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7598 this->report_error(_("first argument must be []byte"));
7601 this->report_error(_("second argument must be slice or string"));
7605 case BUILTIN_APPEND:
7607 const Expression_list* args = this->args();
7608 if (args == NULL || args->size() < 2)
7610 this->report_error(_("not enough arguments"));
7613 if (args->size() > 2)
7615 this->report_error(_("too many arguments"));
7618 if (args->front()->type()->is_error()
7619 || args->back()->type()->is_error())
7622 Array_type* at = args->front()->type()->array_type();
7623 Type* e = at->element_type();
7625 // The language permits appending a string to a []byte, as a
7627 if (args->back()->type()->is_string_type())
7629 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7633 // The language says that the second argument must be
7634 // assignable to a slice of the element type of the first
7635 // argument. We already know the first argument is a slice
7637 Type* arg2_type = Type::make_array_type(e, NULL);
7639 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7642 this->report_error(_("argument 2 has invalid type"));
7645 error_at(this->location(), "argument 2 has invalid type (%s)",
7647 this->set_is_error();
7655 if (this->check_one_arg())
7657 if (this->one_arg()->type()->complex_type() == NULL)
7658 this->report_error(_("argument must have complex type"));
7662 case BUILTIN_COMPLEX:
7664 const Expression_list* args = this->args();
7665 if (args == NULL || args->size() < 2)
7666 this->report_error(_("not enough arguments"));
7667 else if (args->size() > 2)
7668 this->report_error(_("too many arguments"));
7669 else if (args->front()->is_error_expression()
7670 || args->front()->type()->is_error()
7671 || args->back()->is_error_expression()
7672 || args->back()->type()->is_error())
7673 this->set_is_error();
7674 else if (!Type::are_identical(args->front()->type(),
7675 args->back()->type(), true, NULL))
7676 this->report_error(_("complex arguments must have identical types"));
7677 else if (args->front()->type()->float_type() == NULL)
7678 this->report_error(_("complex arguments must have "
7679 "floating-point type"));
7688 // Return the tree for a builtin function.
7691 Builtin_call_expression::do_get_tree(Translate_context* context)
7693 Gogo* gogo = context->gogo();
7694 Location location = this->location();
7695 switch (this->code_)
7697 case BUILTIN_INVALID:
7705 const Expression_list* args = this->args();
7706 go_assert(args != NULL && args->size() == 1);
7707 Expression* arg = *args->begin();
7708 Type* arg_type = arg->type();
7712 go_assert(saw_errors());
7713 return error_mark_node;
7717 tree arg_tree = arg->get_tree(context);
7719 this->seen_ = false;
7721 if (arg_tree == error_mark_node)
7722 return error_mark_node;
7724 if (arg_type->points_to() != NULL)
7726 arg_type = arg_type->points_to();
7727 go_assert(arg_type->array_type() != NULL
7728 && !arg_type->is_slice_type());
7729 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7730 arg_tree = build_fold_indirect_ref(arg_tree);
7734 if (this->code_ == BUILTIN_LEN)
7736 if (arg_type->is_string_type())
7737 val_tree = String_type::length_tree(gogo, arg_tree);
7738 else if (arg_type->array_type() != NULL)
7742 go_assert(saw_errors());
7743 return error_mark_node;
7746 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7747 this->seen_ = false;
7749 else if (arg_type->map_type() != NULL)
7751 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7752 static tree map_len_fndecl;
7753 val_tree = Gogo::call_builtin(&map_len_fndecl,
7761 else if (arg_type->channel_type() != NULL)
7763 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7764 static tree chan_len_fndecl;
7765 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7778 if (arg_type->array_type() != NULL)
7782 go_assert(saw_errors());
7783 return error_mark_node;
7786 val_tree = arg_type->array_type()->capacity_tree(gogo,
7788 this->seen_ = false;
7790 else if (arg_type->channel_type() != NULL)
7792 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7793 static tree chan_cap_fndecl;
7794 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7806 if (val_tree == error_mark_node)
7807 return error_mark_node;
7809 Type* int_type = Type::lookup_integer_type("int");
7810 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7811 if (type_tree == TREE_TYPE(val_tree))
7814 return fold(convert_to_integer(type_tree, val_tree));
7818 case BUILTIN_PRINTLN:
7820 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7821 tree stmt_list = NULL_TREE;
7823 const Expression_list* call_args = this->args();
7824 if (call_args != NULL)
7826 for (Expression_list::const_iterator p = call_args->begin();
7827 p != call_args->end();
7830 if (is_ln && p != call_args->begin())
7832 static tree print_space_fndecl;
7833 tree call = Gogo::call_builtin(&print_space_fndecl,
7838 if (call == error_mark_node)
7839 return error_mark_node;
7840 append_to_statement_list(call, &stmt_list);
7843 Type* type = (*p)->type();
7845 tree arg = (*p)->get_tree(context);
7846 if (arg == error_mark_node)
7847 return error_mark_node;
7851 if (type->is_string_type())
7853 static tree print_string_fndecl;
7854 pfndecl = &print_string_fndecl;
7855 fnname = "__go_print_string";
7857 else if (type->integer_type() != NULL
7858 && type->integer_type()->is_unsigned())
7860 static tree print_uint64_fndecl;
7861 pfndecl = &print_uint64_fndecl;
7862 fnname = "__go_print_uint64";
7863 Type* itype = Type::lookup_integer_type("uint64");
7864 Btype* bitype = itype->get_backend(gogo);
7865 arg = fold_convert_loc(location.gcc_location(),
7866 type_to_tree(bitype), arg);
7868 else if (type->integer_type() != NULL)
7870 static tree print_int64_fndecl;
7871 pfndecl = &print_int64_fndecl;
7872 fnname = "__go_print_int64";
7873 Type* itype = Type::lookup_integer_type("int64");
7874 Btype* bitype = itype->get_backend(gogo);
7875 arg = fold_convert_loc(location.gcc_location(),
7876 type_to_tree(bitype), arg);
7878 else if (type->float_type() != NULL)
7880 static tree print_double_fndecl;
7881 pfndecl = &print_double_fndecl;
7882 fnname = "__go_print_double";
7883 arg = fold_convert_loc(location.gcc_location(),
7884 double_type_node, arg);
7886 else if (type->complex_type() != NULL)
7888 static tree print_complex_fndecl;
7889 pfndecl = &print_complex_fndecl;
7890 fnname = "__go_print_complex";
7891 arg = fold_convert_loc(location.gcc_location(),
7892 complex_double_type_node, arg);
7894 else if (type->is_boolean_type())
7896 static tree print_bool_fndecl;
7897 pfndecl = &print_bool_fndecl;
7898 fnname = "__go_print_bool";
7900 else if (type->points_to() != NULL
7901 || type->channel_type() != NULL
7902 || type->map_type() != NULL
7903 || type->function_type() != NULL)
7905 static tree print_pointer_fndecl;
7906 pfndecl = &print_pointer_fndecl;
7907 fnname = "__go_print_pointer";
7908 arg = fold_convert_loc(location.gcc_location(),
7909 ptr_type_node, arg);
7911 else if (type->interface_type() != NULL)
7913 if (type->interface_type()->is_empty())
7915 static tree print_empty_interface_fndecl;
7916 pfndecl = &print_empty_interface_fndecl;
7917 fnname = "__go_print_empty_interface";
7921 static tree print_interface_fndecl;
7922 pfndecl = &print_interface_fndecl;
7923 fnname = "__go_print_interface";
7926 else if (type->is_slice_type())
7928 static tree print_slice_fndecl;
7929 pfndecl = &print_slice_fndecl;
7930 fnname = "__go_print_slice";
7934 go_assert(saw_errors());
7935 return error_mark_node;
7938 tree call = Gogo::call_builtin(pfndecl,
7945 if (call == error_mark_node)
7946 return error_mark_node;
7947 append_to_statement_list(call, &stmt_list);
7953 static tree print_nl_fndecl;
7954 tree call = Gogo::call_builtin(&print_nl_fndecl,
7959 if (call == error_mark_node)
7960 return error_mark_node;
7961 append_to_statement_list(call, &stmt_list);
7969 const Expression_list* args = this->args();
7970 go_assert(args != NULL && args->size() == 1);
7971 Expression* arg = args->front();
7972 tree arg_tree = arg->get_tree(context);
7973 if (arg_tree == error_mark_node)
7974 return error_mark_node;
7976 Type::make_empty_interface_type(Linemap::predeclared_location());
7977 arg_tree = Expression::convert_for_assignment(context, empty,
7979 arg_tree, location);
7980 static tree panic_fndecl;
7981 tree call = Gogo::call_builtin(&panic_fndecl,
7986 TREE_TYPE(arg_tree),
7988 if (call == error_mark_node)
7989 return error_mark_node;
7990 // This function will throw an exception.
7991 TREE_NOTHROW(panic_fndecl) = 0;
7992 // This function will not return.
7993 TREE_THIS_VOLATILE(panic_fndecl) = 1;
7997 case BUILTIN_RECOVER:
7999 // The argument is set when building recover thunks. It's a
8000 // boolean value which is true if we can recover a value now.
8001 const Expression_list* args = this->args();
8002 go_assert(args != NULL && args->size() == 1);
8003 Expression* arg = args->front();
8004 tree arg_tree = arg->get_tree(context);
8005 if (arg_tree == error_mark_node)
8006 return error_mark_node;
8009 Type::make_empty_interface_type(Linemap::predeclared_location());
8010 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8012 Type* nil_type = Type::make_nil_type();
8013 Expression* nil = Expression::make_nil(location);
8014 tree nil_tree = nil->get_tree(context);
8015 tree empty_nil_tree = Expression::convert_for_assignment(context,
8021 // We need to handle a deferred call to recover specially,
8022 // because it changes whether it can recover a panic or not.
8023 // See test7 in test/recover1.go.
8025 if (this->is_deferred())
8027 static tree deferred_recover_fndecl;
8028 call = Gogo::call_builtin(&deferred_recover_fndecl,
8030 "__go_deferred_recover",
8036 static tree recover_fndecl;
8037 call = Gogo::call_builtin(&recover_fndecl,
8043 if (call == error_mark_node)
8044 return error_mark_node;
8045 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8046 arg_tree, call, empty_nil_tree);
8051 const Expression_list* args = this->args();
8052 go_assert(args != NULL && args->size() == 1);
8053 Expression* arg = args->front();
8054 tree arg_tree = arg->get_tree(context);
8055 if (arg_tree == error_mark_node)
8056 return error_mark_node;
8057 static tree close_fndecl;
8058 return Gogo::call_builtin(&close_fndecl,
8060 "__go_builtin_close",
8063 TREE_TYPE(arg_tree),
8067 case BUILTIN_SIZEOF:
8068 case BUILTIN_OFFSETOF:
8069 case BUILTIN_ALIGNOF:
8071 Numeric_constant nc;
8073 if (!this->numeric_constant_value(&nc)
8074 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8076 go_assert(saw_errors());
8077 return error_mark_node;
8079 Type* int_type = Type::lookup_integer_type("int");
8080 tree type = type_to_tree(int_type->get_backend(gogo));
8081 return build_int_cst(type, val);
8086 const Expression_list* args = this->args();
8087 go_assert(args != NULL && args->size() == 2);
8088 Expression* arg1 = args->front();
8089 Expression* arg2 = args->back();
8091 tree arg1_tree = arg1->get_tree(context);
8092 tree arg2_tree = arg2->get_tree(context);
8093 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8094 return error_mark_node;
8096 Type* arg1_type = arg1->type();
8097 Array_type* at = arg1_type->array_type();
8098 arg1_tree = save_expr(arg1_tree);
8099 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8100 tree arg1_len = at->length_tree(gogo, arg1_tree);
8101 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8102 return error_mark_node;
8104 Type* arg2_type = arg2->type();
8107 if (arg2_type->is_slice_type())
8109 at = arg2_type->array_type();
8110 arg2_tree = save_expr(arg2_tree);
8111 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8112 arg2_len = at->length_tree(gogo, arg2_tree);
8116 arg2_tree = save_expr(arg2_tree);
8117 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8118 arg2_len = String_type::length_tree(gogo, arg2_tree);
8120 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8121 return error_mark_node;
8123 arg1_len = save_expr(arg1_len);
8124 arg2_len = save_expr(arg2_len);
8125 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8126 TREE_TYPE(arg1_len),
8127 fold_build2_loc(location.gcc_location(),
8128 LT_EXPR, boolean_type_node,
8129 arg1_len, arg2_len),
8130 arg1_len, arg2_len);
8131 len = save_expr(len);
8133 Type* element_type = at->element_type();
8134 Btype* element_btype = element_type->get_backend(gogo);
8135 tree element_type_tree = type_to_tree(element_btype);
8136 if (element_type_tree == error_mark_node)
8137 return error_mark_node;
8138 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8139 tree bytecount = fold_convert_loc(location.gcc_location(),
8140 TREE_TYPE(element_size), len);
8141 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8142 TREE_TYPE(element_size),
8143 bytecount, element_size);
8144 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8147 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8149 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8152 static tree copy_fndecl;
8153 tree call = Gogo::call_builtin(©_fndecl,
8164 if (call == error_mark_node)
8165 return error_mark_node;
8167 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8168 TREE_TYPE(len), call, len);
8171 case BUILTIN_APPEND:
8173 const Expression_list* args = this->args();
8174 go_assert(args != NULL && args->size() == 2);
8175 Expression* arg1 = args->front();
8176 Expression* arg2 = args->back();
8178 tree arg1_tree = arg1->get_tree(context);
8179 tree arg2_tree = arg2->get_tree(context);
8180 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8181 return error_mark_node;
8183 Array_type* at = arg1->type()->array_type();
8184 Type* element_type = at->element_type()->forwarded();
8189 if (arg2->type()->is_string_type()
8190 && element_type->integer_type() != NULL
8191 && element_type->integer_type()->is_byte())
8193 arg2_tree = save_expr(arg2_tree);
8194 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8195 arg2_len = String_type::length_tree(gogo, arg2_tree);
8196 element_size = size_int(1);
8200 arg2_tree = Expression::convert_for_assignment(context, at,
8204 if (arg2_tree == error_mark_node)
8205 return error_mark_node;
8207 arg2_tree = save_expr(arg2_tree);
8209 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8210 arg2_len = at->length_tree(gogo, arg2_tree);
8212 Btype* element_btype = element_type->get_backend(gogo);
8213 tree element_type_tree = type_to_tree(element_btype);
8214 if (element_type_tree == error_mark_node)
8215 return error_mark_node;
8216 element_size = TYPE_SIZE_UNIT(element_type_tree);
8219 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8221 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8223 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8226 if (arg2_val == error_mark_node
8227 || arg2_len == error_mark_node
8228 || element_size == error_mark_node)
8229 return error_mark_node;
8231 // We rebuild the decl each time since the slice types may
8233 tree append_fndecl = NULL_TREE;
8234 return Gogo::call_builtin(&append_fndecl,
8238 TREE_TYPE(arg1_tree),
8239 TREE_TYPE(arg1_tree),
8252 const Expression_list* args = this->args();
8253 go_assert(args != NULL && args->size() == 1);
8254 Expression* arg = args->front();
8255 tree arg_tree = arg->get_tree(context);
8256 if (arg_tree == error_mark_node)
8257 return error_mark_node;
8258 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8259 if (this->code_ == BUILTIN_REAL)
8260 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8261 TREE_TYPE(TREE_TYPE(arg_tree)),
8264 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8265 TREE_TYPE(TREE_TYPE(arg_tree)),
8269 case BUILTIN_COMPLEX:
8271 const Expression_list* args = this->args();
8272 go_assert(args != NULL && args->size() == 2);
8273 tree r = args->front()->get_tree(context);
8274 tree i = args->back()->get_tree(context);
8275 if (r == error_mark_node || i == error_mark_node)
8276 return error_mark_node;
8277 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8278 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8279 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8280 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8281 build_complex_type(TREE_TYPE(r)),
8290 // We have to support exporting a builtin call expression, because
8291 // code can set a constant to the result of a builtin expression.
8294 Builtin_call_expression::do_export(Export* exp) const
8296 Numeric_constant nc;
8297 if (!this->numeric_constant_value(&nc))
8299 error_at(this->location(), "value is not constant");
8307 Integer_expression::export_integer(exp, val);
8310 else if (nc.is_float())
8313 nc.get_float(&fval);
8314 Float_expression::export_float(exp, fval);
8317 else if (nc.is_complex())
8321 Complex_expression::export_complex(exp, real, imag);
8328 // A trailing space lets us reliably identify the end of the number.
8329 exp->write_c_string(" ");
8332 // Class Call_expression.
8337 Call_expression::do_traverse(Traverse* traverse)
8339 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8340 return TRAVERSE_EXIT;
8341 if (this->args_ != NULL)
8343 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8344 return TRAVERSE_EXIT;
8346 return TRAVERSE_CONTINUE;
8349 // Lower a call statement.
8352 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8353 Statement_inserter* inserter, int)
8355 Location loc = this->location();
8357 // A type cast can look like a function call.
8358 if (this->fn_->is_type_expression()
8359 && this->args_ != NULL
8360 && this->args_->size() == 1)
8361 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8364 // Recognize a call to a builtin function.
8365 Func_expression* fne = this->fn_->func_expression();
8367 && fne->named_object()->is_function_declaration()
8368 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8369 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8370 this->is_varargs_, loc);
8372 // Handle an argument which is a call to a function which returns
8373 // multiple results.
8374 if (this->args_ != NULL
8375 && this->args_->size() == 1
8376 && this->args_->front()->call_expression() != NULL
8377 && this->fn_->type()->function_type() != NULL)
8379 Function_type* fntype = this->fn_->type()->function_type();
8380 size_t rc = this->args_->front()->call_expression()->result_count();
8382 && fntype->parameters() != NULL
8383 && (fntype->parameters()->size() == rc
8384 || (fntype->is_varargs()
8385 && fntype->parameters()->size() - 1 <= rc)))
8387 Call_expression* call = this->args_->front()->call_expression();
8388 Expression_list* args = new Expression_list;
8389 for (size_t i = 0; i < rc; ++i)
8390 args->push_back(Expression::make_call_result(call, i));
8391 // We can't return a new call expression here, because this
8392 // one may be referenced by Call_result expressions. We
8393 // also can't delete the old arguments, because we may still
8394 // traverse them somewhere up the call stack. FIXME.
8399 // If this call returns multiple results, create a temporary
8400 // variable for each result.
8401 size_t rc = this->result_count();
8402 if (rc > 1 && this->results_ == NULL)
8404 std::vector<Temporary_statement*>* temps =
8405 new std::vector<Temporary_statement*>;
8407 const Typed_identifier_list* results =
8408 this->fn_->type()->function_type()->results();
8409 for (Typed_identifier_list::const_iterator p = results->begin();
8410 p != results->end();
8413 Temporary_statement* temp = Statement::make_temporary(p->type(),
8415 inserter->insert(temp);
8416 temps->push_back(temp);
8418 this->results_ = temps;
8421 // Handle a call to a varargs function by packaging up the extra
8423 if (this->fn_->type()->function_type() != NULL
8424 && this->fn_->type()->function_type()->is_varargs())
8426 Function_type* fntype = this->fn_->type()->function_type();
8427 const Typed_identifier_list* parameters = fntype->parameters();
8428 go_assert(parameters != NULL && !parameters->empty());
8429 Type* varargs_type = parameters->back().type();
8430 this->lower_varargs(gogo, function, inserter, varargs_type,
8431 parameters->size());
8434 // If this is call to a method, call the method directly passing the
8435 // object as the first parameter.
8436 Bound_method_expression* bme = this->fn_->bound_method_expression();
8439 Named_object* method = bme->method();
8440 Expression* first_arg = bme->first_argument();
8442 // We always pass a pointer when calling a method.
8443 if (first_arg->type()->points_to() == NULL
8444 && !first_arg->type()->is_error())
8446 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8447 // We may need to create a temporary variable so that we can
8448 // take the address. We can't do that here because it will
8449 // mess up the order of evaluation.
8450 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8451 ue->set_create_temp();
8454 // If we are calling a method which was inherited from an
8455 // embedded struct, and the method did not get a stub, then the
8456 // first type may be wrong.
8457 Type* fatype = bme->first_argument_type();
8460 if (fatype->points_to() == NULL)
8461 fatype = Type::make_pointer_type(fatype);
8462 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8465 Expression_list* new_args = new Expression_list();
8466 new_args->push_back(first_arg);
8467 if (this->args_ != NULL)
8469 for (Expression_list::const_iterator p = this->args_->begin();
8470 p != this->args_->end();
8472 new_args->push_back(*p);
8475 // We have to change in place because this structure may be
8476 // referenced by Call_result_expressions. We can't delete the
8477 // old arguments, because we may be traversing them up in some
8479 this->args_ = new_args;
8480 this->fn_ = Expression::make_func_reference(method, NULL,
8487 // Lower a call to a varargs function. FUNCTION is the function in
8488 // which the call occurs--it's not the function we are calling.
8489 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8490 // PARAM_COUNT is the number of parameters of the function we are
8491 // calling; the last of these parameters will be the varargs
8495 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8496 Statement_inserter* inserter,
8497 Type* varargs_type, size_t param_count)
8499 if (this->varargs_are_lowered_)
8502 Location loc = this->location();
8504 go_assert(param_count > 0);
8505 go_assert(varargs_type->is_slice_type());
8507 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8508 if (arg_count < param_count - 1)
8510 // Not enough arguments; will be caught in check_types.
8514 Expression_list* old_args = this->args_;
8515 Expression_list* new_args = new Expression_list();
8516 bool push_empty_arg = false;
8517 if (old_args == NULL || old_args->empty())
8519 go_assert(param_count == 1);
8520 push_empty_arg = true;
8524 Expression_list::const_iterator pa;
8526 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8528 if (static_cast<size_t>(i) == param_count)
8530 new_args->push_back(*pa);
8533 // We have reached the varargs parameter.
8535 bool issued_error = false;
8536 if (pa == old_args->end())
8537 push_empty_arg = true;
8538 else if (pa + 1 == old_args->end() && this->is_varargs_)
8539 new_args->push_back(*pa);
8540 else if (this->is_varargs_)
8542 this->report_error(_("too many arguments"));
8547 Type* element_type = varargs_type->array_type()->element_type();
8548 Expression_list* vals = new Expression_list;
8549 for (; pa != old_args->end(); ++pa, ++i)
8551 // Check types here so that we get a better message.
8552 Type* patype = (*pa)->type();
8553 Location paloc = (*pa)->location();
8554 if (!this->check_argument_type(i, element_type, patype,
8555 paloc, issued_error))
8557 vals->push_back(*pa);
8560 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8561 gogo->lower_expression(function, inserter, &val);
8562 new_args->push_back(val);
8567 new_args->push_back(Expression::make_nil(loc));
8569 // We can't return a new call expression here, because this one may
8570 // be referenced by Call_result expressions. FIXME. We can't
8571 // delete OLD_ARGS because we may have both a Call_expression and a
8572 // Builtin_call_expression which refer to them. FIXME.
8573 this->args_ = new_args;
8574 this->varargs_are_lowered_ = true;
8577 // Get the function type. This can return NULL in error cases.
8580 Call_expression::get_function_type() const
8582 return this->fn_->type()->function_type();
8585 // Return the number of values which this call will return.
8588 Call_expression::result_count() const
8590 const Function_type* fntype = this->get_function_type();
8593 if (fntype->results() == NULL)
8595 return fntype->results()->size();
8598 // Return the temporary which holds a result.
8600 Temporary_statement*
8601 Call_expression::result(size_t i) const
8603 if (this->results_ == NULL || this->results_->size() <= i)
8605 go_assert(saw_errors());
8608 return (*this->results_)[i];
8611 // Return whether this is a call to the predeclared function recover.
8614 Call_expression::is_recover_call() const
8616 return this->do_is_recover_call();
8619 // Set the argument to the recover function.
8622 Call_expression::set_recover_arg(Expression* arg)
8624 this->do_set_recover_arg(arg);
8627 // Virtual functions also implemented by Builtin_call_expression.
8630 Call_expression::do_is_recover_call() const
8636 Call_expression::do_set_recover_arg(Expression*)
8641 // We have found an error with this call expression; return true if
8642 // we should report it.
8645 Call_expression::issue_error()
8647 if (this->issued_error_)
8651 this->issued_error_ = true;
8659 Call_expression::do_type()
8661 if (this->type_ != NULL)
8665 Function_type* fntype = this->get_function_type();
8667 return Type::make_error_type();
8669 const Typed_identifier_list* results = fntype->results();
8670 if (results == NULL)
8671 ret = Type::make_void_type();
8672 else if (results->size() == 1)
8673 ret = results->begin()->type();
8675 ret = Type::make_call_multiple_result_type(this);
8682 // Determine types for a call expression. We can use the function
8683 // parameter types to set the types of the arguments.
8686 Call_expression::do_determine_type(const Type_context*)
8688 if (!this->determining_types())
8691 this->fn_->determine_type_no_context();
8692 Function_type* fntype = this->get_function_type();
8693 const Typed_identifier_list* parameters = NULL;
8695 parameters = fntype->parameters();
8696 if (this->args_ != NULL)
8698 Typed_identifier_list::const_iterator pt;
8699 if (parameters != NULL)
8700 pt = parameters->begin();
8702 for (Expression_list::const_iterator pa = this->args_->begin();
8703 pa != this->args_->end();
8709 // If this is a method, the first argument is the
8711 if (fntype != NULL && fntype->is_method())
8713 Type* rtype = fntype->receiver()->type();
8714 // The receiver is always passed as a pointer.
8715 if (rtype->points_to() == NULL)
8716 rtype = Type::make_pointer_type(rtype);
8717 Type_context subcontext(rtype, false);
8718 (*pa)->determine_type(&subcontext);
8723 if (parameters != NULL && pt != parameters->end())
8725 Type_context subcontext(pt->type(), false);
8726 (*pa)->determine_type(&subcontext);
8730 (*pa)->determine_type_no_context();
8735 // Called when determining types for a Call_expression. Return true
8736 // if we should go ahead, false if they have already been determined.
8739 Call_expression::determining_types()
8741 if (this->types_are_determined_)
8745 this->types_are_determined_ = true;
8750 // Check types for parameter I.
8753 Call_expression::check_argument_type(int i, const Type* parameter_type,
8754 const Type* argument_type,
8755 Location argument_location,
8760 if (this->are_hidden_fields_ok_)
8761 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8764 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8770 error_at(argument_location, "argument %d has incompatible type", i);
8772 error_at(argument_location,
8773 "argument %d has incompatible type (%s)",
8776 this->set_is_error();
8785 Call_expression::do_check_types(Gogo*)
8787 Function_type* fntype = this->get_function_type();
8790 if (!this->fn_->type()->is_error())
8791 this->report_error(_("expected function"));
8795 bool is_method = fntype->is_method();
8798 go_assert(this->args_ != NULL && !this->args_->empty());
8799 Type* rtype = fntype->receiver()->type();
8800 Expression* first_arg = this->args_->front();
8801 // The language permits copying hidden fields for a method
8802 // receiver. We dereference the values since receivers are
8803 // always passed as pointers.
8805 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8806 first_arg->type()->deref(),
8810 this->report_error(_("incompatible type for receiver"));
8813 error_at(this->location(),
8814 "incompatible type for receiver (%s)",
8816 this->set_is_error();
8821 // Note that varargs was handled by the lower_varargs() method, so
8822 // we don't have to worry about it here.
8824 const Typed_identifier_list* parameters = fntype->parameters();
8825 if (this->args_ == NULL)
8827 if (parameters != NULL && !parameters->empty())
8828 this->report_error(_("not enough arguments"));
8830 else if (parameters == NULL)
8832 if (!is_method || this->args_->size() > 1)
8833 this->report_error(_("too many arguments"));
8838 Expression_list::const_iterator pa = this->args_->begin();
8841 for (Typed_identifier_list::const_iterator pt = parameters->begin();
8842 pt != parameters->end();
8845 if (pa == this->args_->end())
8847 this->report_error(_("not enough arguments"));
8850 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8851 (*pa)->location(), false);
8853 if (pa != this->args_->end())
8854 this->report_error(_("too many arguments"));
8858 // Return whether we have to use a temporary variable to ensure that
8859 // we evaluate this call expression in order. If the call returns no
8860 // results then it will inevitably be executed last.
8863 Call_expression::do_must_eval_in_order() const
8865 return this->result_count() > 0;
8868 // Get the function and the first argument to use when calling an
8869 // interface method.
8872 Call_expression::interface_method_function(
8873 Translate_context* context,
8874 Interface_field_reference_expression* interface_method,
8875 tree* first_arg_ptr)
8877 tree expr = interface_method->expr()->get_tree(context);
8878 if (expr == error_mark_node)
8879 return error_mark_node;
8880 expr = save_expr(expr);
8881 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
8882 if (first_arg == error_mark_node)
8883 return error_mark_node;
8884 *first_arg_ptr = first_arg;
8885 return interface_method->get_function_tree(context, expr);
8888 // Build the call expression.
8891 Call_expression::do_get_tree(Translate_context* context)
8893 if (this->tree_ != NULL_TREE)
8896 Function_type* fntype = this->get_function_type();
8898 return error_mark_node;
8900 if (this->fn_->is_error_expression())
8901 return error_mark_node;
8903 Gogo* gogo = context->gogo();
8904 Location location = this->location();
8906 Func_expression* func = this->fn_->func_expression();
8907 Interface_field_reference_expression* interface_method =
8908 this->fn_->interface_field_reference_expression();
8909 const bool has_closure = func != NULL && func->closure() != NULL;
8910 const bool is_interface_method = interface_method != NULL;
8914 if (this->args_ == NULL || this->args_->empty())
8916 nargs = is_interface_method ? 1 : 0;
8917 args = nargs == 0 ? NULL : new tree[nargs];
8919 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
8921 // Passing a receiver parameter.
8922 go_assert(!is_interface_method
8923 && fntype->is_method()
8924 && this->args_->size() == 1);
8926 args = new tree[nargs];
8927 args[0] = this->args_->front()->get_tree(context);
8931 const Typed_identifier_list* params = fntype->parameters();
8933 nargs = this->args_->size();
8934 int i = is_interface_method ? 1 : 0;
8936 args = new tree[nargs];
8938 Typed_identifier_list::const_iterator pp = params->begin();
8939 Expression_list::const_iterator pe = this->args_->begin();
8940 if (!is_interface_method && fntype->is_method())
8942 args[i] = (*pe)->get_tree(context);
8946 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
8948 go_assert(pp != params->end());
8949 tree arg_val = (*pe)->get_tree(context);
8950 args[i] = Expression::convert_for_assignment(context,
8955 if (args[i] == error_mark_node)
8958 return error_mark_node;
8961 go_assert(pp == params->end());
8962 go_assert(i == nargs);
8965 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
8966 if (rettype == error_mark_node)
8969 return error_mark_node;
8974 fn = func->get_tree_without_closure(gogo);
8975 else if (!is_interface_method)
8976 fn = this->fn_->get_tree(context);
8978 fn = this->interface_method_function(context, interface_method, &args[0]);
8980 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
8983 return error_mark_node;
8987 if (TREE_CODE(fndecl) == ADDR_EXPR)
8988 fndecl = TREE_OPERAND(fndecl, 0);
8990 // Add a type cast in case the type of the function is a recursive
8991 // type which refers to itself.
8992 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
8994 tree fnt = type_to_tree(fntype->get_backend(gogo));
8995 if (fnt == error_mark_node)
8996 return error_mark_node;
8997 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9000 // This is to support builtin math functions when using 80387 math.
9001 tree excess_type = NULL_TREE;
9003 && TREE_CODE(fndecl) == FUNCTION_DECL
9004 && DECL_IS_BUILTIN(fndecl)
9005 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9007 && ((SCALAR_FLOAT_TYPE_P(rettype)
9008 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9009 || (COMPLEX_FLOAT_TYPE_P(rettype)
9010 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9012 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9013 if (excess_type != NULL_TREE)
9015 tree excess_fndecl = mathfn_built_in(excess_type,
9016 DECL_FUNCTION_CODE(fndecl));
9017 if (excess_fndecl == NULL_TREE)
9018 excess_type = NULL_TREE;
9021 fn = build_fold_addr_expr_loc(location.gcc_location(),
9023 for (int i = 0; i < nargs; ++i)
9025 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9026 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9027 args[i] = ::convert(excess_type, args[i]);
9033 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9037 SET_EXPR_LOCATION(ret, location.gcc_location());
9041 tree closure_tree = func->closure()->get_tree(context);
9042 if (closure_tree != error_mark_node)
9043 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9046 // If this is a recursive function type which returns itself, as in
9048 // we have used ptr_type_node for the return type. Add a cast here
9049 // to the correct type.
9050 if (TREE_TYPE(ret) == ptr_type_node)
9052 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9053 ret = fold_convert_loc(location.gcc_location(), t, ret);
9056 if (excess_type != NULL_TREE)
9058 // Calling convert here can undo our excess precision change.
9059 // That may or may not be a bug in convert_to_real.
9060 ret = build1(NOP_EXPR, rettype, ret);
9063 if (this->results_ != NULL)
9064 ret = this->set_results(context, ret);
9071 // Set the result variables if this call returns multiple results.
9074 Call_expression::set_results(Translate_context* context, tree call_tree)
9076 tree stmt_list = NULL_TREE;
9078 call_tree = save_expr(call_tree);
9080 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9082 go_assert(saw_errors());
9086 Location loc = this->location();
9087 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9088 size_t rc = this->result_count();
9089 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9091 go_assert(field != NULL_TREE);
9093 Temporary_statement* temp = this->result(i);
9096 go_assert(saw_errors());
9097 return error_mark_node;
9099 Temporary_reference_expression* ref =
9100 Expression::make_temporary_reference(temp, loc);
9101 ref->set_is_lvalue();
9102 tree temp_tree = ref->get_tree(context);
9103 if (temp_tree == error_mark_node)
9106 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9107 TREE_TYPE(field), call_tree, field, NULL_TREE);
9108 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9109 void_type_node, temp_tree, val_tree);
9111 append_to_statement_list(set_tree, &stmt_list);
9113 go_assert(field == NULL_TREE);
9115 return save_expr(stmt_list);
9118 // Dump ast representation for a call expressin.
9121 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9123 this->fn_->dump_expression(ast_dump_context);
9124 ast_dump_context->ostream() << "(";
9126 ast_dump_context->dump_expression_list(this->args_);
9128 ast_dump_context->ostream() << ") ";
9131 // Make a call expression.
9134 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9137 return new Call_expression(fn, args, is_varargs, location);
9140 // A single result from a call which returns multiple results.
9142 class Call_result_expression : public Expression
9145 Call_result_expression(Call_expression* call, unsigned int index)
9146 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9147 call_(call), index_(index)
9152 do_traverse(Traverse*);
9158 do_determine_type(const Type_context*);
9161 do_check_types(Gogo*);
9166 return new Call_result_expression(this->call_->call_expression(),
9171 do_must_eval_in_order() const
9175 do_get_tree(Translate_context*);
9178 do_dump_expression(Ast_dump_context*) const;
9181 // The underlying call expression.
9183 // Which result we want.
9184 unsigned int index_;
9187 // Traverse a call result.
9190 Call_result_expression::do_traverse(Traverse* traverse)
9192 if (traverse->remember_expression(this->call_))
9194 // We have already traversed the call expression.
9195 return TRAVERSE_CONTINUE;
9197 return Expression::traverse(&this->call_, traverse);
9203 Call_result_expression::do_type()
9205 if (this->classification() == EXPRESSION_ERROR)
9206 return Type::make_error_type();
9208 // THIS->CALL_ can be replaced with a temporary reference due to
9209 // Call_expression::do_must_eval_in_order when there is an error.
9210 Call_expression* ce = this->call_->call_expression();
9213 this->set_is_error();
9214 return Type::make_error_type();
9216 Function_type* fntype = ce->get_function_type();
9219 if (ce->issue_error())
9221 if (!ce->fn()->type()->is_error())
9222 this->report_error(_("expected function"));
9224 this->set_is_error();
9225 return Type::make_error_type();
9227 const Typed_identifier_list* results = fntype->results();
9228 if (results == NULL || results->size() < 2)
9230 if (ce->issue_error())
9231 this->report_error(_("number of results does not match "
9232 "number of values"));
9233 return Type::make_error_type();
9235 Typed_identifier_list::const_iterator pr = results->begin();
9236 for (unsigned int i = 0; i < this->index_; ++i)
9238 if (pr == results->end())
9242 if (pr == results->end())
9244 if (ce->issue_error())
9245 this->report_error(_("number of results does not match "
9246 "number of values"));
9247 return Type::make_error_type();
9252 // Check the type. Just make sure that we trigger the warning in
9256 Call_result_expression::do_check_types(Gogo*)
9261 // Determine the type. We have nothing to do here, but the 0 result
9262 // needs to pass down to the caller.
9265 Call_result_expression::do_determine_type(const Type_context*)
9267 this->call_->determine_type_no_context();
9270 // Return the tree. We just refer to the temporary set by the call
9271 // expression. We don't do this at lowering time because it makes it
9272 // hard to evaluate the call at the right time.
9275 Call_result_expression::do_get_tree(Translate_context* context)
9277 Call_expression* ce = this->call_->call_expression();
9280 go_assert(this->call_->is_error_expression());
9281 return error_mark_node;
9283 Temporary_statement* ts = ce->result(this->index_);
9286 go_assert(saw_errors());
9287 return error_mark_node;
9289 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9290 return ref->get_tree(context);
9293 // Dump ast representation for a call result expression.
9296 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9299 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9300 // (struct) and the fields are referenced instead.
9301 ast_dump_context->ostream() << this->index_ << "@(";
9302 ast_dump_context->dump_expression(this->call_);
9303 ast_dump_context->ostream() << ")";
9306 // Make a reference to a single result of a call which returns
9307 // multiple results.
9310 Expression::make_call_result(Call_expression* call, unsigned int index)
9312 return new Call_result_expression(call, index);
9315 // Class Index_expression.
9320 Index_expression::do_traverse(Traverse* traverse)
9322 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9323 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9324 || (this->end_ != NULL
9325 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9326 return TRAVERSE_EXIT;
9327 return TRAVERSE_CONTINUE;
9330 // Lower an index expression. This converts the generic index
9331 // expression into an array index, a string index, or a map index.
9334 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9336 Location location = this->location();
9337 Expression* left = this->left_;
9338 Expression* start = this->start_;
9339 Expression* end = this->end_;
9341 Type* type = left->type();
9342 if (type->is_error())
9343 return Expression::make_error(location);
9344 else if (left->is_type_expression())
9346 error_at(location, "attempt to index type expression");
9347 return Expression::make_error(location);
9349 else if (type->array_type() != NULL)
9350 return Expression::make_array_index(left, start, end, location);
9351 else if (type->points_to() != NULL
9352 && type->points_to()->array_type() != NULL
9353 && !type->points_to()->is_slice_type())
9355 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9357 return Expression::make_array_index(deref, start, end, location);
9359 else if (type->is_string_type())
9360 return Expression::make_string_index(left, start, end, location);
9361 else if (type->map_type() != NULL)
9365 error_at(location, "invalid slice of map");
9366 return Expression::make_error(location);
9368 Map_index_expression* ret = Expression::make_map_index(left, start,
9370 if (this->is_lvalue_)
9371 ret->set_is_lvalue();
9377 "attempt to index object which is not array, string, or map");
9378 return Expression::make_error(location);
9382 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9386 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9387 const Expression* expr,
9388 const Expression* start,
9389 const Expression* end)
9391 expr->dump_expression(ast_dump_context);
9392 ast_dump_context->ostream() << "[";
9393 start->dump_expression(ast_dump_context);
9396 ast_dump_context->ostream() << ":";
9397 end->dump_expression(ast_dump_context);
9399 ast_dump_context->ostream() << "]";
9402 // Dump ast representation for an index expression.
9405 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9408 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9409 this->start_, this->end_);
9412 // Make an index expression.
9415 Expression::make_index(Expression* left, Expression* start, Expression* end,
9418 return new Index_expression(left, start, end, location);
9421 // An array index. This is used for both indexing and slicing.
9423 class Array_index_expression : public Expression
9426 Array_index_expression(Expression* array, Expression* start,
9427 Expression* end, Location location)
9428 : Expression(EXPRESSION_ARRAY_INDEX, location),
9429 array_(array), start_(start), end_(end), type_(NULL)
9434 do_traverse(Traverse*);
9440 do_determine_type(const Type_context*);
9443 do_check_types(Gogo*);
9448 return Expression::make_array_index(this->array_->copy(),
9449 this->start_->copy(),
9452 : this->end_->copy()),
9457 do_must_eval_subexpressions_in_order(int* skip) const
9464 do_is_addressable() const;
9467 do_address_taken(bool escapes)
9468 { this->array_->address_taken(escapes); }
9471 do_get_tree(Translate_context*);
9474 do_dump_expression(Ast_dump_context*) const;
9477 // The array we are getting a value from.
9479 // The start or only index.
9481 // The end index of a slice. This may be NULL for a simple array
9482 // index, or it may be a nil expression for the length of the array.
9484 // The type of the expression.
9488 // Array index traversal.
9491 Array_index_expression::do_traverse(Traverse* traverse)
9493 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9494 return TRAVERSE_EXIT;
9495 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9496 return TRAVERSE_EXIT;
9497 if (this->end_ != NULL)
9499 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9500 return TRAVERSE_EXIT;
9502 return TRAVERSE_CONTINUE;
9505 // Return the type of an array index.
9508 Array_index_expression::do_type()
9510 if (this->type_ == NULL)
9512 Array_type* type = this->array_->type()->array_type();
9514 this->type_ = Type::make_error_type();
9515 else if (this->end_ == NULL)
9516 this->type_ = type->element_type();
9517 else if (type->is_slice_type())
9519 // A slice of a slice has the same type as the original
9521 this->type_ = this->array_->type()->deref();
9525 // A slice of an array is a slice.
9526 this->type_ = Type::make_array_type(type->element_type(), NULL);
9532 // Set the type of an array index.
9535 Array_index_expression::do_determine_type(const Type_context*)
9537 this->array_->determine_type_no_context();
9538 this->start_->determine_type_no_context();
9539 if (this->end_ != NULL)
9540 this->end_->determine_type_no_context();
9543 // Check types of an array index.
9546 Array_index_expression::do_check_types(Gogo*)
9548 if (this->start_->type()->integer_type() == NULL)
9549 this->report_error(_("index must be integer"));
9550 if (this->end_ != NULL
9551 && this->end_->type()->integer_type() == NULL
9552 && !this->end_->type()->is_error()
9553 && !this->end_->is_nil_expression()
9554 && !this->end_->is_error_expression())
9555 this->report_error(_("slice end must be integer"));
9557 Array_type* array_type = this->array_->type()->array_type();
9558 if (array_type == NULL)
9560 go_assert(this->array_->type()->is_error());
9564 unsigned int int_bits =
9565 Type::lookup_integer_type("int")->integer_type()->bits();
9567 Numeric_constant lvalnc;
9569 bool lval_valid = (array_type->length() != NULL
9570 && array_type->length()->numeric_constant_value(&lvalnc)
9571 && lvalnc.to_int(&lval));
9572 Numeric_constant inc;
9574 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9576 if (mpz_sgn(ival) < 0
9577 || mpz_sizeinbase(ival, 2) >= int_bits
9579 && (this->end_ == NULL
9580 ? mpz_cmp(ival, lval) >= 0
9581 : mpz_cmp(ival, lval) > 0)))
9583 error_at(this->start_->location(), "array index out of bounds");
9584 this->set_is_error();
9588 if (this->end_ != NULL && !this->end_->is_nil_expression())
9590 Numeric_constant enc;
9592 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9594 if (mpz_sgn(eval) < 0
9595 || mpz_sizeinbase(eval, 2) >= int_bits
9596 || (lval_valid && mpz_cmp(eval, lval) > 0))
9598 error_at(this->end_->location(), "array index out of bounds");
9599 this->set_is_error();
9607 // A slice of an array requires an addressable array. A slice of a
9608 // slice is always possible.
9609 if (this->end_ != NULL && !array_type->is_slice_type())
9611 if (!this->array_->is_addressable())
9612 this->report_error(_("slice of unaddressable value"));
9614 this->array_->address_taken(true);
9618 // Return whether this expression is addressable.
9621 Array_index_expression::do_is_addressable() const
9623 // A slice expression is not addressable.
9624 if (this->end_ != NULL)
9627 // An index into a slice is addressable.
9628 if (this->array_->type()->is_slice_type())
9631 // An index into an array is addressable if the array is
9633 return this->array_->is_addressable();
9636 // Get a tree for an array index.
9639 Array_index_expression::do_get_tree(Translate_context* context)
9641 Gogo* gogo = context->gogo();
9642 Location loc = this->location();
9644 Array_type* array_type = this->array_->type()->array_type();
9645 if (array_type == NULL)
9647 go_assert(this->array_->type()->is_error());
9648 return error_mark_node;
9651 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9652 if (type_tree == error_mark_node)
9653 return error_mark_node;
9655 tree array_tree = this->array_->get_tree(context);
9656 if (array_tree == error_mark_node)
9657 return error_mark_node;
9659 if (array_type->length() == NULL && !DECL_P(array_tree))
9660 array_tree = save_expr(array_tree);
9662 tree length_tree = NULL_TREE;
9663 if (this->end_ == NULL || this->end_->is_nil_expression())
9665 length_tree = array_type->length_tree(gogo, array_tree);
9666 if (length_tree == error_mark_node)
9667 return error_mark_node;
9668 length_tree = save_expr(length_tree);
9671 tree capacity_tree = NULL_TREE;
9672 if (this->end_ != NULL)
9674 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9675 if (capacity_tree == error_mark_node)
9676 return error_mark_node;
9677 capacity_tree = save_expr(capacity_tree);
9680 tree length_type = (length_tree != NULL_TREE
9681 ? TREE_TYPE(length_tree)
9682 : TREE_TYPE(capacity_tree));
9684 tree bad_index = boolean_false_node;
9686 tree start_tree = this->start_->get_tree(context);
9687 if (start_tree == error_mark_node)
9688 return error_mark_node;
9689 if (!DECL_P(start_tree))
9690 start_tree = save_expr(start_tree);
9691 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9692 start_tree = convert_to_integer(length_type, start_tree);
9694 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9697 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9698 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9699 boolean_type_node, bad_index,
9700 fold_build2_loc(loc.gcc_location(),
9704 boolean_type_node, start_tree,
9709 int code = (array_type->length() != NULL
9710 ? (this->end_ == NULL
9711 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9712 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9713 : (this->end_ == NULL
9714 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9715 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9716 tree crash = Gogo::runtime_error(code, loc);
9718 if (this->end_ == NULL)
9720 // Simple array indexing. This has to return an l-value, so
9721 // wrap the index check into START_TREE.
9722 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9723 build3(COND_EXPR, void_type_node,
9724 bad_index, crash, NULL_TREE),
9726 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9728 if (array_type->length() != NULL)
9731 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9732 start_tree, NULL_TREE, NULL_TREE);
9737 tree values = array_type->value_pointer_tree(gogo, array_tree);
9738 Type* element_type = array_type->element_type();
9739 Btype* belement_type = element_type->get_backend(gogo);
9740 tree element_type_tree = type_to_tree(belement_type);
9741 if (element_type_tree == error_mark_node)
9742 return error_mark_node;
9743 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9744 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9745 start_tree, element_size);
9746 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9747 TREE_TYPE(values), values, offset);
9748 return build_fold_indirect_ref(ptr);
9755 if (this->end_->is_nil_expression())
9756 end_tree = length_tree;
9759 end_tree = this->end_->get_tree(context);
9760 if (end_tree == error_mark_node)
9761 return error_mark_node;
9762 if (!DECL_P(end_tree))
9763 end_tree = save_expr(end_tree);
9764 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9765 end_tree = convert_to_integer(length_type, end_tree);
9767 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9770 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9772 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9774 fold_build2_loc(loc.gcc_location(),
9775 LT_EXPR, boolean_type_node,
9776 end_tree, start_tree),
9777 fold_build2_loc(loc.gcc_location(),
9778 GT_EXPR, boolean_type_node,
9779 end_tree, capacity_tree));
9780 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9781 boolean_type_node, bad_index, bad_end);
9784 Type* element_type = array_type->element_type();
9785 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9786 if (element_type_tree == error_mark_node)
9787 return error_mark_node;
9788 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9790 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9791 fold_convert_loc(loc.gcc_location(), sizetype,
9795 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9796 if (value_pointer == error_mark_node)
9797 return error_mark_node;
9799 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9800 TREE_TYPE(value_pointer),
9801 value_pointer, offset);
9803 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9804 length_type, end_tree, start_tree);
9806 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9807 length_type, capacity_tree,
9810 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9811 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9813 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9815 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9816 tree field = TYPE_FIELDS(struct_tree);
9817 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9819 elt->value = value_pointer;
9821 elt = VEC_quick_push(constructor_elt, init, NULL);
9822 field = DECL_CHAIN(field);
9823 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9825 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9826 result_length_tree);
9828 elt = VEC_quick_push(constructor_elt, init, NULL);
9829 field = DECL_CHAIN(field);
9830 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9832 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9833 result_capacity_tree);
9835 tree constructor = build_constructor(struct_tree, init);
9837 if (TREE_CONSTANT(value_pointer)
9838 && TREE_CONSTANT(result_length_tree)
9839 && TREE_CONSTANT(result_capacity_tree))
9840 TREE_CONSTANT(constructor) = 1;
9842 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9843 TREE_TYPE(constructor),
9844 build3(COND_EXPR, void_type_node,
9845 bad_index, crash, NULL_TREE),
9849 // Dump ast representation for an array index expression.
9852 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9855 Index_expression::dump_index_expression(ast_dump_context, this->array_,
9856 this->start_, this->end_);
9859 // Make an array index expression. END may be NULL.
9862 Expression::make_array_index(Expression* array, Expression* start,
9863 Expression* end, Location location)
9865 return new Array_index_expression(array, start, end, location);
9868 // A string index. This is used for both indexing and slicing.
9870 class String_index_expression : public Expression
9873 String_index_expression(Expression* string, Expression* start,
9874 Expression* end, Location location)
9875 : Expression(EXPRESSION_STRING_INDEX, location),
9876 string_(string), start_(start), end_(end)
9881 do_traverse(Traverse*);
9887 do_determine_type(const Type_context*);
9890 do_check_types(Gogo*);
9895 return Expression::make_string_index(this->string_->copy(),
9896 this->start_->copy(),
9899 : this->end_->copy()),
9904 do_must_eval_subexpressions_in_order(int* skip) const
9911 do_get_tree(Translate_context*);
9914 do_dump_expression(Ast_dump_context*) const;
9917 // The string we are getting a value from.
9918 Expression* string_;
9919 // The start or only index.
9921 // The end index of a slice. This may be NULL for a single index,
9922 // or it may be a nil expression for the length of the string.
9926 // String index traversal.
9929 String_index_expression::do_traverse(Traverse* traverse)
9931 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
9932 return TRAVERSE_EXIT;
9933 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9934 return TRAVERSE_EXIT;
9935 if (this->end_ != NULL)
9937 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9938 return TRAVERSE_EXIT;
9940 return TRAVERSE_CONTINUE;
9943 // Return the type of a string index.
9946 String_index_expression::do_type()
9948 if (this->end_ == NULL)
9949 return Type::lookup_integer_type("uint8");
9951 return this->string_->type();
9954 // Determine the type of a string index.
9957 String_index_expression::do_determine_type(const Type_context*)
9959 this->string_->determine_type_no_context();
9960 this->start_->determine_type_no_context();
9961 if (this->end_ != NULL)
9962 this->end_->determine_type_no_context();
9965 // Check types of a string index.
9968 String_index_expression::do_check_types(Gogo*)
9970 if (this->start_->type()->integer_type() == NULL)
9971 this->report_error(_("index must be integer"));
9972 if (this->end_ != NULL
9973 && this->end_->type()->integer_type() == NULL
9974 && !this->end_->is_nil_expression())
9975 this->report_error(_("slice end must be integer"));
9978 bool sval_valid = this->string_->string_constant_value(&sval);
9980 Numeric_constant inc;
9982 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9984 if (mpz_sgn(ival) < 0
9985 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
9987 error_at(this->start_->location(), "string index out of bounds");
9988 this->set_is_error();
9992 if (this->end_ != NULL && !this->end_->is_nil_expression())
9994 Numeric_constant enc;
9996 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9998 if (mpz_sgn(eval) < 0
9999 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10001 error_at(this->end_->location(), "string index out of bounds");
10002 this->set_is_error();
10009 // Get a tree for a string index.
10012 String_index_expression::do_get_tree(Translate_context* context)
10014 Location loc = this->location();
10016 tree string_tree = this->string_->get_tree(context);
10017 if (string_tree == error_mark_node)
10018 return error_mark_node;
10020 if (this->string_->type()->points_to() != NULL)
10021 string_tree = build_fold_indirect_ref(string_tree);
10022 if (!DECL_P(string_tree))
10023 string_tree = save_expr(string_tree);
10024 tree string_type = TREE_TYPE(string_tree);
10026 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10027 length_tree = save_expr(length_tree);
10028 tree length_type = TREE_TYPE(length_tree);
10030 tree bad_index = boolean_false_node;
10032 tree start_tree = this->start_->get_tree(context);
10033 if (start_tree == error_mark_node)
10034 return error_mark_node;
10035 if (!DECL_P(start_tree))
10036 start_tree = save_expr(start_tree);
10037 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10038 start_tree = convert_to_integer(length_type, start_tree);
10040 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10043 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10045 int code = (this->end_ == NULL
10046 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10047 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10048 tree crash = Gogo::runtime_error(code, loc);
10050 if (this->end_ == NULL)
10052 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10053 boolean_type_node, bad_index,
10054 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10056 start_tree, length_tree));
10058 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10059 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10060 TREE_TYPE(bytes_tree),
10062 fold_convert_loc(loc.gcc_location(), sizetype,
10064 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10066 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10067 build3(COND_EXPR, void_type_node,
10068 bad_index, crash, NULL_TREE),
10074 if (this->end_->is_nil_expression())
10075 end_tree = build_int_cst(length_type, -1);
10078 end_tree = this->end_->get_tree(context);
10079 if (end_tree == error_mark_node)
10080 return error_mark_node;
10081 if (!DECL_P(end_tree))
10082 end_tree = save_expr(end_tree);
10083 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10084 end_tree = convert_to_integer(length_type, end_tree);
10086 bad_index = Expression::check_bounds(end_tree, length_type,
10089 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10093 static tree strslice_fndecl;
10094 tree ret = Gogo::call_builtin(&strslice_fndecl,
10096 "__go_string_slice",
10105 if (ret == error_mark_node)
10106 return error_mark_node;
10107 // This will panic if the bounds are out of range for the
10109 TREE_NOTHROW(strslice_fndecl) = 0;
10111 if (bad_index == boolean_false_node)
10114 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10115 build3(COND_EXPR, void_type_node,
10116 bad_index, crash, NULL_TREE),
10121 // Dump ast representation for a string index expression.
10124 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10127 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10128 this->start_, this->end_);
10131 // Make a string index expression. END may be NULL.
10134 Expression::make_string_index(Expression* string, Expression* start,
10135 Expression* end, Location location)
10137 return new String_index_expression(string, start, end, location);
10140 // Class Map_index.
10142 // Get the type of the map.
10145 Map_index_expression::get_map_type() const
10147 Map_type* mt = this->map_->type()->deref()->map_type();
10149 go_assert(saw_errors());
10153 // Map index traversal.
10156 Map_index_expression::do_traverse(Traverse* traverse)
10158 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10159 return TRAVERSE_EXIT;
10160 return Expression::traverse(&this->index_, traverse);
10163 // Return the type of a map index.
10166 Map_index_expression::do_type()
10168 Map_type* mt = this->get_map_type();
10170 return Type::make_error_type();
10171 Type* type = mt->val_type();
10172 // If this map index is in a tuple assignment, we actually return a
10173 // pointer to the value type. Tuple_map_assignment_statement is
10174 // responsible for handling this correctly. We need to get the type
10175 // right in case this gets assigned to a temporary variable.
10176 if (this->is_in_tuple_assignment_)
10177 type = Type::make_pointer_type(type);
10181 // Fix the type of a map index.
10184 Map_index_expression::do_determine_type(const Type_context*)
10186 this->map_->determine_type_no_context();
10187 Map_type* mt = this->get_map_type();
10188 Type* key_type = mt == NULL ? NULL : mt->key_type();
10189 Type_context subcontext(key_type, false);
10190 this->index_->determine_type(&subcontext);
10193 // Check types of a map index.
10196 Map_index_expression::do_check_types(Gogo*)
10198 std::string reason;
10199 Map_type* mt = this->get_map_type();
10202 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10204 if (reason.empty())
10205 this->report_error(_("incompatible type for map index"));
10208 error_at(this->location(), "incompatible type for map index (%s)",
10210 this->set_is_error();
10215 // Get a tree for a map index.
10218 Map_index_expression::do_get_tree(Translate_context* context)
10220 Map_type* type = this->get_map_type();
10222 return error_mark_node;
10224 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10225 if (valptr == error_mark_node)
10226 return error_mark_node;
10227 valptr = save_expr(valptr);
10229 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10231 if (this->is_lvalue_)
10232 return build_fold_indirect_ref(valptr);
10233 else if (this->is_in_tuple_assignment_)
10235 // Tuple_map_assignment_statement is responsible for using this
10241 Gogo* gogo = context->gogo();
10242 Btype* val_btype = type->val_type()->get_backend(gogo);
10243 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10244 return fold_build3(COND_EXPR, val_type_tree,
10245 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10246 fold_convert(TREE_TYPE(valptr),
10247 null_pointer_node)),
10248 expr_to_tree(val_zero),
10249 build_fold_indirect_ref(valptr));
10253 // Get a tree for the map index. This returns a tree which evaluates
10254 // to a pointer to a value. The pointer will be NULL if the key is
10258 Map_index_expression::get_value_pointer(Translate_context* context,
10261 Map_type* type = this->get_map_type();
10263 return error_mark_node;
10265 tree map_tree = this->map_->get_tree(context);
10266 tree index_tree = this->index_->get_tree(context);
10267 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10268 this->index_->type(),
10271 if (map_tree == error_mark_node || index_tree == error_mark_node)
10272 return error_mark_node;
10274 if (this->map_->type()->points_to() != NULL)
10275 map_tree = build_fold_indirect_ref(map_tree);
10277 // We need to pass in a pointer to the key, so stuff it into a
10281 if (current_function_decl != NULL)
10283 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10284 DECL_IGNORED_P(tmp) = 0;
10285 DECL_INITIAL(tmp) = index_tree;
10286 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10287 TREE_ADDRESSABLE(tmp) = 1;
10291 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10292 create_tmp_var_name("M"),
10293 TREE_TYPE(index_tree));
10294 DECL_EXTERNAL(tmp) = 0;
10295 TREE_PUBLIC(tmp) = 0;
10296 TREE_STATIC(tmp) = 1;
10297 DECL_ARTIFICIAL(tmp) = 1;
10298 if (!TREE_CONSTANT(index_tree))
10299 make_tmp = fold_build2_loc(this->location().gcc_location(),
10300 INIT_EXPR, void_type_node,
10304 TREE_READONLY(tmp) = 1;
10305 TREE_CONSTANT(tmp) = 1;
10306 DECL_INITIAL(tmp) = index_tree;
10307 make_tmp = NULL_TREE;
10309 rest_of_decl_compilation(tmp, 1, 0);
10312 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10313 build_fold_addr_expr_loc(this->location().gcc_location(),
10316 static tree map_index_fndecl;
10317 tree call = Gogo::call_builtin(&map_index_fndecl,
10321 const_ptr_type_node,
10322 TREE_TYPE(map_tree),
10324 const_ptr_type_node,
10328 ? boolean_true_node
10329 : boolean_false_node));
10330 if (call == error_mark_node)
10331 return error_mark_node;
10332 // This can panic on a map of interface type if the interface holds
10333 // an uncomparable or unhashable type.
10334 TREE_NOTHROW(map_index_fndecl) = 0;
10336 Type* val_type = type->val_type();
10337 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10338 if (val_type_tree == error_mark_node)
10339 return error_mark_node;
10340 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10342 tree ret = fold_convert_loc(this->location().gcc_location(),
10343 ptr_val_type_tree, call);
10344 if (make_tmp != NULL_TREE)
10345 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10349 // Dump ast representation for a map index expression
10352 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10355 Index_expression::dump_index_expression(ast_dump_context,
10356 this->map_, this->index_, NULL);
10359 // Make a map index expression.
10361 Map_index_expression*
10362 Expression::make_map_index(Expression* map, Expression* index,
10365 return new Map_index_expression(map, index, location);
10368 // Class Field_reference_expression.
10370 // Return the type of a field reference.
10373 Field_reference_expression::do_type()
10375 Type* type = this->expr_->type();
10376 if (type->is_error())
10378 Struct_type* struct_type = type->struct_type();
10379 go_assert(struct_type != NULL);
10380 return struct_type->field(this->field_index_)->type();
10383 // Check the types for a field reference.
10386 Field_reference_expression::do_check_types(Gogo*)
10388 Type* type = this->expr_->type();
10389 if (type->is_error())
10391 Struct_type* struct_type = type->struct_type();
10392 go_assert(struct_type != NULL);
10393 go_assert(struct_type->field(this->field_index_) != NULL);
10396 // Get a tree for a field reference.
10399 Field_reference_expression::do_get_tree(Translate_context* context)
10401 tree struct_tree = this->expr_->get_tree(context);
10402 if (struct_tree == error_mark_node
10403 || TREE_TYPE(struct_tree) == error_mark_node)
10404 return error_mark_node;
10405 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10406 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10407 if (field == NULL_TREE)
10409 // This can happen for a type which refers to itself indirectly
10410 // and then turns out to be erroneous.
10411 go_assert(saw_errors());
10412 return error_mark_node;
10414 for (unsigned int i = this->field_index_; i > 0; --i)
10416 field = DECL_CHAIN(field);
10417 go_assert(field != NULL_TREE);
10419 if (TREE_TYPE(field) == error_mark_node)
10420 return error_mark_node;
10421 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10425 // Dump ast representation for a field reference expression.
10428 Field_reference_expression::do_dump_expression(
10429 Ast_dump_context* ast_dump_context) const
10431 this->expr_->dump_expression(ast_dump_context);
10432 ast_dump_context->ostream() << "." << this->field_index_;
10435 // Make a reference to a qualified identifier in an expression.
10437 Field_reference_expression*
10438 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10441 return new Field_reference_expression(expr, field_index, location);
10444 // Class Interface_field_reference_expression.
10446 // Return a tree for the pointer to the function to call.
10449 Interface_field_reference_expression::get_function_tree(Translate_context*,
10452 if (this->expr_->type()->points_to() != NULL)
10453 expr = build_fold_indirect_ref(expr);
10455 tree expr_type = TREE_TYPE(expr);
10456 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10458 tree field = TYPE_FIELDS(expr_type);
10459 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10461 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10462 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10464 table = build_fold_indirect_ref(table);
10465 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10467 std::string name = Gogo::unpack_hidden_name(this->name_);
10468 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10469 field != NULL_TREE;
10470 field = DECL_CHAIN(field))
10472 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10475 go_assert(field != NULL_TREE);
10477 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10480 // Return a tree for the first argument to pass to the interface
10484 Interface_field_reference_expression::get_underlying_object_tree(
10485 Translate_context*,
10488 if (this->expr_->type()->points_to() != NULL)
10489 expr = build_fold_indirect_ref(expr);
10491 tree expr_type = TREE_TYPE(expr);
10492 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10494 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10495 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10497 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10503 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10505 return Expression::traverse(&this->expr_, traverse);
10508 // Return the type of an interface field reference.
10511 Interface_field_reference_expression::do_type()
10513 Type* expr_type = this->expr_->type();
10515 Type* points_to = expr_type->points_to();
10516 if (points_to != NULL)
10517 expr_type = points_to;
10519 Interface_type* interface_type = expr_type->interface_type();
10520 if (interface_type == NULL)
10521 return Type::make_error_type();
10523 const Typed_identifier* method = interface_type->find_method(this->name_);
10524 if (method == NULL)
10525 return Type::make_error_type();
10527 return method->type();
10530 // Determine types.
10533 Interface_field_reference_expression::do_determine_type(const Type_context*)
10535 this->expr_->determine_type_no_context();
10538 // Check the types for an interface field reference.
10541 Interface_field_reference_expression::do_check_types(Gogo*)
10543 Type* type = this->expr_->type();
10545 Type* points_to = type->points_to();
10546 if (points_to != NULL)
10549 Interface_type* interface_type = type->interface_type();
10550 if (interface_type == NULL)
10552 if (!type->is_error_type())
10553 this->report_error(_("expected interface or pointer to interface"));
10557 const Typed_identifier* method =
10558 interface_type->find_method(this->name_);
10559 if (method == NULL)
10561 error_at(this->location(), "method %qs not in interface",
10562 Gogo::message_name(this->name_).c_str());
10563 this->set_is_error();
10568 // Get a tree for a reference to a field in an interface. There is no
10569 // standard tree type representation for this: it's a function
10570 // attached to its first argument, like a Bound_method_expression.
10571 // The only places it may currently be used are in a Call_expression
10572 // or a Go_statement, which will take it apart directly. So this has
10573 // nothing to do at present.
10576 Interface_field_reference_expression::do_get_tree(Translate_context*)
10581 // Dump ast representation for an interface field reference.
10584 Interface_field_reference_expression::do_dump_expression(
10585 Ast_dump_context* ast_dump_context) const
10587 this->expr_->dump_expression(ast_dump_context);
10588 ast_dump_context->ostream() << "." << this->name_;
10591 // Make a reference to a field in an interface.
10594 Expression::make_interface_field_reference(Expression* expr,
10595 const std::string& field,
10598 return new Interface_field_reference_expression(expr, field, location);
10601 // A general selector. This is a Parser_expression for LEFT.NAME. It
10602 // is lowered after we know the type of the left hand side.
10604 class Selector_expression : public Parser_expression
10607 Selector_expression(Expression* left, const std::string& name,
10609 : Parser_expression(EXPRESSION_SELECTOR, location),
10610 left_(left), name_(name)
10615 do_traverse(Traverse* traverse)
10616 { return Expression::traverse(&this->left_, traverse); }
10619 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10624 return new Selector_expression(this->left_->copy(), this->name_,
10629 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10633 lower_method_expression(Gogo*);
10635 // The expression on the left hand side.
10637 // The name on the right hand side.
10641 // Lower a selector expression once we know the real type of the left
10645 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10648 Expression* left = this->left_;
10649 if (left->is_type_expression())
10650 return this->lower_method_expression(gogo);
10651 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10655 // Lower a method expression T.M or (*T).M. We turn this into a
10656 // function literal.
10659 Selector_expression::lower_method_expression(Gogo* gogo)
10661 Location location = this->location();
10662 Type* type = this->left_->type();
10663 const std::string& name(this->name_);
10666 if (type->points_to() == NULL)
10667 is_pointer = false;
10671 type = type->points_to();
10673 Named_type* nt = type->named_type();
10677 ("method expression requires named type or "
10678 "pointer to named type"));
10679 return Expression::make_error(location);
10683 Method* method = nt->method_function(name, &is_ambiguous);
10684 const Typed_identifier* imethod = NULL;
10685 if (method == NULL && !is_pointer)
10687 Interface_type* it = nt->interface_type();
10689 imethod = it->find_method(name);
10692 if (method == NULL && imethod == NULL)
10695 error_at(location, "type %<%s%s%> has no method %<%s%>",
10696 is_pointer ? "*" : "",
10697 nt->message_name().c_str(),
10698 Gogo::message_name(name).c_str());
10700 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10701 Gogo::message_name(name).c_str(),
10702 is_pointer ? "*" : "",
10703 nt->message_name().c_str());
10704 return Expression::make_error(location);
10707 if (method != NULL && !is_pointer && !method->is_value_method())
10709 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10710 nt->message_name().c_str(),
10711 Gogo::message_name(name).c_str());
10712 return Expression::make_error(location);
10715 // Build a new function type in which the receiver becomes the first
10717 Function_type* method_type;
10718 if (method != NULL)
10720 method_type = method->type();
10721 go_assert(method_type->is_method());
10725 method_type = imethod->type()->function_type();
10726 go_assert(method_type != NULL && !method_type->is_method());
10729 const char* const receiver_name = "$this";
10730 Typed_identifier_list* parameters = new Typed_identifier_list();
10731 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10734 const Typed_identifier_list* method_parameters = method_type->parameters();
10735 if (method_parameters != NULL)
10738 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10739 p != method_parameters->end();
10742 if (!p->name().empty())
10743 parameters->push_back(*p);
10747 snprintf(buf, sizeof buf, "$param%d", i);
10748 parameters->push_back(Typed_identifier(buf, p->type(),
10754 const Typed_identifier_list* method_results = method_type->results();
10755 Typed_identifier_list* results;
10756 if (method_results == NULL)
10760 results = new Typed_identifier_list();
10761 for (Typed_identifier_list::const_iterator p = method_results->begin();
10762 p != method_results->end();
10764 results->push_back(*p);
10767 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10769 if (method_type->is_varargs())
10770 fntype->set_is_varargs();
10772 // We generate methods which always takes a pointer to the receiver
10773 // as their first argument. If this is for a pointer type, we can
10774 // simply reuse the existing function. We use an internal hack to
10775 // get the right type.
10777 if (method != NULL && is_pointer)
10779 Named_object* mno = (method->needs_stub_method()
10780 ? method->stub_object()
10781 : method->named_object());
10782 Expression* f = Expression::make_func_reference(mno, NULL, location);
10783 f = Expression::make_cast(fntype, f, location);
10784 Type_conversion_expression* tce =
10785 static_cast<Type_conversion_expression*>(f);
10786 tce->set_may_convert_function_types();
10790 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10793 Named_object* vno = gogo->lookup(receiver_name, NULL);
10794 go_assert(vno != NULL);
10795 Expression* ve = Expression::make_var_reference(vno, location);
10797 if (method != NULL)
10798 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10800 bm = Expression::make_interface_field_reference(ve, name, location);
10802 // Even though we found the method above, if it has an error type we
10803 // may see an error here.
10804 if (bm->is_error_expression())
10806 gogo->finish_function(location);
10810 Expression_list* args;
10811 if (parameters->size() <= 1)
10815 args = new Expression_list();
10816 Typed_identifier_list::const_iterator p = parameters->begin();
10818 for (; p != parameters->end(); ++p)
10820 vno = gogo->lookup(p->name(), NULL);
10821 go_assert(vno != NULL);
10822 args->push_back(Expression::make_var_reference(vno, location));
10826 gogo->start_block(location);
10828 Call_expression* call = Expression::make_call(bm, args,
10829 method_type->is_varargs(),
10832 size_t count = call->result_count();
10835 s = Statement::make_statement(call, true);
10838 Expression_list* retvals = new Expression_list();
10840 retvals->push_back(call);
10843 for (size_t i = 0; i < count; ++i)
10844 retvals->push_back(Expression::make_call_result(call, i));
10846 s = Statement::make_return_statement(retvals, location);
10848 gogo->add_statement(s);
10850 Block* b = gogo->finish_block(location);
10852 gogo->add_block(b, location);
10854 // Lower the call in case there are multiple results.
10855 gogo->lower_block(no, b);
10857 gogo->finish_function(location);
10859 return Expression::make_func_reference(no, NULL, location);
10862 // Dump the ast for a selector expression.
10865 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10868 ast_dump_context->dump_expression(this->left_);
10869 ast_dump_context->ostream() << ".";
10870 ast_dump_context->ostream() << this->name_;
10873 // Make a selector expression.
10876 Expression::make_selector(Expression* left, const std::string& name,
10879 return new Selector_expression(left, name, location);
10882 // Implement the builtin function new.
10884 class Allocation_expression : public Expression
10887 Allocation_expression(Type* type, Location location)
10888 : Expression(EXPRESSION_ALLOCATION, location),
10894 do_traverse(Traverse* traverse)
10895 { return Type::traverse(this->type_, traverse); }
10899 { return Type::make_pointer_type(this->type_); }
10902 do_determine_type(const Type_context*)
10907 { return new Allocation_expression(this->type_, this->location()); }
10910 do_get_tree(Translate_context*);
10913 do_dump_expression(Ast_dump_context*) const;
10916 // The type we are allocating.
10920 // Return a tree for an allocation expression.
10923 Allocation_expression::do_get_tree(Translate_context* context)
10925 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
10926 if (type_tree == error_mark_node)
10927 return error_mark_node;
10928 tree size_tree = TYPE_SIZE_UNIT(type_tree);
10929 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
10931 if (space == error_mark_node)
10932 return error_mark_node;
10933 return fold_convert(build_pointer_type(type_tree), space);
10936 // Dump ast representation for an allocation expression.
10939 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10942 ast_dump_context->ostream() << "new(";
10943 ast_dump_context->dump_type(this->type_);
10944 ast_dump_context->ostream() << ")";
10947 // Make an allocation expression.
10950 Expression::make_allocation(Type* type, Location location)
10952 return new Allocation_expression(type, location);
10955 // Construct a struct.
10957 class Struct_construction_expression : public Expression
10960 Struct_construction_expression(Type* type, Expression_list* vals,
10962 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
10963 type_(type), vals_(vals)
10966 // Return whether this is a constant initializer.
10968 is_constant_struct() const;
10972 do_traverse(Traverse* traverse);
10976 { return this->type_; }
10979 do_determine_type(const Type_context*);
10982 do_check_types(Gogo*);
10987 return new Struct_construction_expression(this->type_, this->vals_->copy(),
10992 do_get_tree(Translate_context*);
10995 do_export(Export*) const;
10998 do_dump_expression(Ast_dump_context*) const;
11001 // The type of the struct to construct.
11003 // The list of values, in order of the fields in the struct. A NULL
11004 // entry means that the field should be zero-initialized.
11005 Expression_list* vals_;
11011 Struct_construction_expression::do_traverse(Traverse* traverse)
11013 if (this->vals_ != NULL
11014 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11015 return TRAVERSE_EXIT;
11016 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11017 return TRAVERSE_EXIT;
11018 return TRAVERSE_CONTINUE;
11021 // Return whether this is a constant initializer.
11024 Struct_construction_expression::is_constant_struct() const
11026 if (this->vals_ == NULL)
11028 for (Expression_list::const_iterator pv = this->vals_->begin();
11029 pv != this->vals_->end();
11033 && !(*pv)->is_constant()
11034 && (!(*pv)->is_composite_literal()
11035 || (*pv)->is_nonconstant_composite_literal()))
11039 const Struct_field_list* fields = this->type_->struct_type()->fields();
11040 for (Struct_field_list::const_iterator pf = fields->begin();
11041 pf != fields->end();
11044 // There are no constant constructors for interfaces.
11045 if (pf->type()->interface_type() != NULL)
11052 // Final type determination.
11055 Struct_construction_expression::do_determine_type(const Type_context*)
11057 if (this->vals_ == NULL)
11059 const Struct_field_list* fields = this->type_->struct_type()->fields();
11060 Expression_list::const_iterator pv = this->vals_->begin();
11061 for (Struct_field_list::const_iterator pf = fields->begin();
11062 pf != fields->end();
11065 if (pv == this->vals_->end())
11069 Type_context subcontext(pf->type(), false);
11070 (*pv)->determine_type(&subcontext);
11073 // Extra values are an error we will report elsewhere; we still want
11074 // to determine the type to avoid knockon errors.
11075 for (; pv != this->vals_->end(); ++pv)
11076 (*pv)->determine_type_no_context();
11082 Struct_construction_expression::do_check_types(Gogo*)
11084 if (this->vals_ == NULL)
11087 Struct_type* st = this->type_->struct_type();
11088 if (this->vals_->size() > st->field_count())
11090 this->report_error(_("too many expressions for struct"));
11094 const Struct_field_list* fields = st->fields();
11095 Expression_list::const_iterator pv = this->vals_->begin();
11097 for (Struct_field_list::const_iterator pf = fields->begin();
11098 pf != fields->end();
11101 if (pv == this->vals_->end())
11103 this->report_error(_("too few expressions for struct"));
11110 std::string reason;
11111 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11113 if (reason.empty())
11114 error_at((*pv)->location(),
11115 "incompatible type for field %d in struct construction",
11118 error_at((*pv)->location(),
11119 ("incompatible type for field %d in "
11120 "struct construction (%s)"),
11121 i + 1, reason.c_str());
11122 this->set_is_error();
11125 go_assert(pv == this->vals_->end());
11128 // Return a tree for constructing a struct.
11131 Struct_construction_expression::do_get_tree(Translate_context* context)
11133 Gogo* gogo = context->gogo();
11135 if (this->vals_ == NULL)
11137 Btype* btype = this->type_->get_backend(gogo);
11138 return expr_to_tree(gogo->backend()->zero_expression(btype));
11141 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11142 if (type_tree == error_mark_node)
11143 return error_mark_node;
11144 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11146 bool is_constant = true;
11147 const Struct_field_list* fields = this->type_->struct_type()->fields();
11148 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11150 Struct_field_list::const_iterator pf = fields->begin();
11151 Expression_list::const_iterator pv = this->vals_->begin();
11152 for (tree field = TYPE_FIELDS(type_tree);
11153 field != NULL_TREE;
11154 field = DECL_CHAIN(field), ++pf)
11156 go_assert(pf != fields->end());
11158 Btype* fbtype = pf->type()->get_backend(gogo);
11161 if (pv == this->vals_->end())
11162 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11163 else if (*pv == NULL)
11165 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11170 val = Expression::convert_for_assignment(context, pf->type(),
11172 (*pv)->get_tree(context),
11177 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11178 return error_mark_node;
11180 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11181 elt->index = field;
11183 if (!TREE_CONSTANT(val))
11184 is_constant = false;
11186 go_assert(pf == fields->end());
11188 tree ret = build_constructor(type_tree, elts);
11190 TREE_CONSTANT(ret) = 1;
11194 // Export a struct construction.
11197 Struct_construction_expression::do_export(Export* exp) const
11199 exp->write_c_string("convert(");
11200 exp->write_type(this->type_);
11201 for (Expression_list::const_iterator pv = this->vals_->begin();
11202 pv != this->vals_->end();
11205 exp->write_c_string(", ");
11207 (*pv)->export_expression(exp);
11209 exp->write_c_string(")");
11212 // Dump ast representation of a struct construction expression.
11215 Struct_construction_expression::do_dump_expression(
11216 Ast_dump_context* ast_dump_context) const
11218 ast_dump_context->dump_type(this->type_);
11219 ast_dump_context->ostream() << "{";
11220 ast_dump_context->dump_expression_list(this->vals_);
11221 ast_dump_context->ostream() << "}";
11224 // Make a struct composite literal. This used by the thunk code.
11227 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11230 go_assert(type->struct_type() != NULL);
11231 return new Struct_construction_expression(type, vals, location);
11234 // Construct an array. This class is not used directly; instead we
11235 // use the child classes, Fixed_array_construction_expression and
11236 // Open_array_construction_expression.
11238 class Array_construction_expression : public Expression
11241 Array_construction_expression(Expression_classification classification,
11242 Type* type, Expression_list* vals,
11244 : Expression(classification, location),
11245 type_(type), vals_(vals)
11249 // Return whether this is a constant initializer.
11251 is_constant_array() const;
11253 // Return the number of elements.
11255 element_count() const
11256 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11260 do_traverse(Traverse* traverse);
11264 { return this->type_; }
11267 do_determine_type(const Type_context*);
11270 do_check_types(Gogo*);
11273 do_export(Export*) const;
11275 // The list of values.
11278 { return this->vals_; }
11280 // Get a constructor tree for the array values.
11282 get_constructor_tree(Translate_context* context, tree type_tree);
11285 do_dump_expression(Ast_dump_context*) const;
11288 // The type of the array to construct.
11290 // The list of values.
11291 Expression_list* vals_;
11297 Array_construction_expression::do_traverse(Traverse* traverse)
11299 if (this->vals_ != NULL
11300 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11301 return TRAVERSE_EXIT;
11302 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11303 return TRAVERSE_EXIT;
11304 return TRAVERSE_CONTINUE;
11307 // Return whether this is a constant initializer.
11310 Array_construction_expression::is_constant_array() const
11312 if (this->vals_ == NULL)
11315 // There are no constant constructors for interfaces.
11316 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11319 for (Expression_list::const_iterator pv = this->vals_->begin();
11320 pv != this->vals_->end();
11324 && !(*pv)->is_constant()
11325 && (!(*pv)->is_composite_literal()
11326 || (*pv)->is_nonconstant_composite_literal()))
11332 // Final type determination.
11335 Array_construction_expression::do_determine_type(const Type_context*)
11337 if (this->vals_ == NULL)
11339 Type_context subcontext(this->type_->array_type()->element_type(), false);
11340 for (Expression_list::const_iterator pv = this->vals_->begin();
11341 pv != this->vals_->end();
11345 (*pv)->determine_type(&subcontext);
11352 Array_construction_expression::do_check_types(Gogo*)
11354 if (this->vals_ == NULL)
11357 Array_type* at = this->type_->array_type();
11359 Type* element_type = at->element_type();
11360 for (Expression_list::const_iterator pv = this->vals_->begin();
11361 pv != this->vals_->end();
11365 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11367 error_at((*pv)->location(),
11368 "incompatible type for element %d in composite literal",
11370 this->set_is_error();
11374 Expression* length = at->length();
11375 Numeric_constant nc;
11378 && !length->is_error_expression()
11379 && length->numeric_constant_value(&nc)
11380 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
11382 if (this->vals_->size() > val)
11383 this->report_error(_("too many elements in composite literal"));
11387 // Get a constructor tree for the array values.
11390 Array_construction_expression::get_constructor_tree(Translate_context* context,
11393 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11394 (this->vals_ == NULL
11396 : this->vals_->size()));
11397 Type* element_type = this->type_->array_type()->element_type();
11398 bool is_constant = true;
11399 if (this->vals_ != NULL)
11402 for (Expression_list::const_iterator pv = this->vals_->begin();
11403 pv != this->vals_->end();
11406 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11407 elt->index = size_int(i);
11410 Gogo* gogo = context->gogo();
11411 Btype* ebtype = element_type->get_backend(gogo);
11412 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11413 elt->value = expr_to_tree(zv);
11417 tree value_tree = (*pv)->get_tree(context);
11418 elt->value = Expression::convert_for_assignment(context,
11424 if (elt->value == error_mark_node)
11425 return error_mark_node;
11426 if (!TREE_CONSTANT(elt->value))
11427 is_constant = false;
11431 tree ret = build_constructor(type_tree, values);
11433 TREE_CONSTANT(ret) = 1;
11437 // Export an array construction.
11440 Array_construction_expression::do_export(Export* exp) const
11442 exp->write_c_string("convert(");
11443 exp->write_type(this->type_);
11444 if (this->vals_ != NULL)
11446 for (Expression_list::const_iterator pv = this->vals_->begin();
11447 pv != this->vals_->end();
11450 exp->write_c_string(", ");
11452 (*pv)->export_expression(exp);
11455 exp->write_c_string(")");
11458 // Dump ast representation of an array construction expressin.
11461 Array_construction_expression::do_dump_expression(
11462 Ast_dump_context* ast_dump_context) const
11464 Expression* length = this->type_->array_type() != NULL ?
11465 this->type_->array_type()->length() : NULL;
11467 ast_dump_context->ostream() << "[" ;
11468 if (length != NULL)
11470 ast_dump_context->dump_expression(length);
11472 ast_dump_context->ostream() << "]" ;
11473 ast_dump_context->dump_type(this->type_);
11474 ast_dump_context->ostream() << "{" ;
11475 ast_dump_context->dump_expression_list(this->vals_);
11476 ast_dump_context->ostream() << "}" ;
11480 // Construct a fixed array.
11482 class Fixed_array_construction_expression :
11483 public Array_construction_expression
11486 Fixed_array_construction_expression(Type* type, Expression_list* vals,
11488 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11489 type, vals, location)
11491 go_assert(type->array_type() != NULL
11492 && type->array_type()->length() != NULL);
11499 return new Fixed_array_construction_expression(this->type(),
11500 (this->vals() == NULL
11502 : this->vals()->copy()),
11507 do_get_tree(Translate_context*);
11510 do_dump_expression(Ast_dump_context*);
11513 // Return a tree for constructing a fixed array.
11516 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11518 Type* type = this->type();
11519 Btype* btype = type->get_backend(context->gogo());
11520 return this->get_constructor_tree(context, type_to_tree(btype));
11523 // Dump ast representation of an array construction expressin.
11526 Fixed_array_construction_expression::do_dump_expression(
11527 Ast_dump_context* ast_dump_context)
11530 ast_dump_context->ostream() << "[";
11531 ast_dump_context->dump_expression (this->type()->array_type()->length());
11532 ast_dump_context->ostream() << "]";
11533 ast_dump_context->dump_type(this->type());
11534 ast_dump_context->ostream() << "{";
11535 ast_dump_context->dump_expression_list(this->vals());
11536 ast_dump_context->ostream() << "}";
11539 // Construct an open array.
11541 class Open_array_construction_expression : public Array_construction_expression
11544 Open_array_construction_expression(Type* type, Expression_list* vals,
11546 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11547 type, vals, location)
11549 go_assert(type->array_type() != NULL
11550 && type->array_type()->length() == NULL);
11554 // Note that taking the address of an open array literal is invalid.
11559 return new Open_array_construction_expression(this->type(),
11560 (this->vals() == NULL
11562 : this->vals()->copy()),
11567 do_get_tree(Translate_context*);
11570 // Return a tree for constructing an open array.
11573 Open_array_construction_expression::do_get_tree(Translate_context* context)
11575 Array_type* array_type = this->type()->array_type();
11576 if (array_type == NULL)
11578 go_assert(this->type()->is_error());
11579 return error_mark_node;
11582 Type* element_type = array_type->element_type();
11583 Btype* belement_type = element_type->get_backend(context->gogo());
11584 tree element_type_tree = type_to_tree(belement_type);
11585 if (element_type_tree == error_mark_node)
11586 return error_mark_node;
11590 if (this->vals() == NULL || this->vals()->empty())
11592 // We need to create a unique value.
11593 tree max = size_int(0);
11594 tree constructor_type = build_array_type(element_type_tree,
11595 build_index_type(max));
11596 if (constructor_type == error_mark_node)
11597 return error_mark_node;
11598 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11599 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11600 elt->index = size_int(0);
11601 Gogo* gogo = context->gogo();
11602 Btype* btype = element_type->get_backend(gogo);
11603 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11604 values = build_constructor(constructor_type, vec);
11605 if (TREE_CONSTANT(elt->value))
11606 TREE_CONSTANT(values) = 1;
11607 length_tree = size_int(0);
11611 tree max = size_int(this->vals()->size() - 1);
11612 tree constructor_type = build_array_type(element_type_tree,
11613 build_index_type(max));
11614 if (constructor_type == error_mark_node)
11615 return error_mark_node;
11616 values = this->get_constructor_tree(context, constructor_type);
11617 length_tree = size_int(this->vals()->size());
11620 if (values == error_mark_node)
11621 return error_mark_node;
11623 bool is_constant_initializer = TREE_CONSTANT(values);
11625 // We have to copy the initial values into heap memory if we are in
11626 // a function or if the values are not constants. We also have to
11627 // copy them if they may contain pointers in a non-constant context,
11628 // as otherwise the garbage collector won't see them.
11629 bool copy_to_heap = (context->function() != NULL
11630 || !is_constant_initializer
11631 || (element_type->has_pointer()
11632 && !context->is_const()));
11634 if (is_constant_initializer)
11636 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11637 create_tmp_var_name("C"), TREE_TYPE(values));
11638 DECL_EXTERNAL(tmp) = 0;
11639 TREE_PUBLIC(tmp) = 0;
11640 TREE_STATIC(tmp) = 1;
11641 DECL_ARTIFICIAL(tmp) = 1;
11644 // If we are not copying the value to the heap, we will only
11645 // initialize the value once, so we can use this directly
11646 // rather than copying it. In that case we can't make it
11647 // read-only, because the program is permitted to change it.
11648 TREE_READONLY(tmp) = 1;
11649 TREE_CONSTANT(tmp) = 1;
11651 DECL_INITIAL(tmp) = values;
11652 rest_of_decl_compilation(tmp, 1, 0);
11660 // the initializer will only run once.
11661 space = build_fold_addr_expr(values);
11666 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11667 space = context->gogo()->allocate_memory(element_type, memsize,
11669 space = save_expr(space);
11671 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11672 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11674 TREE_THIS_NOTRAP(ref) = 1;
11675 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11678 // Build a constructor for the open array.
11680 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11681 if (type_tree == error_mark_node)
11682 return error_mark_node;
11683 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11685 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11687 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11688 tree field = TYPE_FIELDS(type_tree);
11689 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11690 elt->index = field;
11691 elt->value = fold_convert(TREE_TYPE(field), space);
11693 elt = VEC_quick_push(constructor_elt, init, NULL);
11694 field = DECL_CHAIN(field);
11695 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11696 elt->index = field;
11697 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11699 elt = VEC_quick_push(constructor_elt, init, NULL);
11700 field = DECL_CHAIN(field);
11701 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11702 elt->index = field;
11703 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11705 tree constructor = build_constructor(type_tree, init);
11706 if (constructor == error_mark_node)
11707 return error_mark_node;
11709 TREE_CONSTANT(constructor) = 1;
11711 if (set == NULL_TREE)
11712 return constructor;
11714 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11717 // Make a slice composite literal. This is used by the type
11718 // descriptor code.
11721 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11724 go_assert(type->is_slice_type());
11725 return new Open_array_construction_expression(type, vals, location);
11728 // Construct a map.
11730 class Map_construction_expression : public Expression
11733 Map_construction_expression(Type* type, Expression_list* vals,
11735 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11736 type_(type), vals_(vals)
11737 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11741 do_traverse(Traverse* traverse);
11745 { return this->type_; }
11748 do_determine_type(const Type_context*);
11751 do_check_types(Gogo*);
11756 return new Map_construction_expression(this->type_, this->vals_->copy(),
11761 do_get_tree(Translate_context*);
11764 do_export(Export*) const;
11767 do_dump_expression(Ast_dump_context*) const;
11770 // The type of the map to construct.
11772 // The list of values.
11773 Expression_list* vals_;
11779 Map_construction_expression::do_traverse(Traverse* traverse)
11781 if (this->vals_ != NULL
11782 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11783 return TRAVERSE_EXIT;
11784 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11785 return TRAVERSE_EXIT;
11786 return TRAVERSE_CONTINUE;
11789 // Final type determination.
11792 Map_construction_expression::do_determine_type(const Type_context*)
11794 if (this->vals_ == NULL)
11797 Map_type* mt = this->type_->map_type();
11798 Type_context key_context(mt->key_type(), false);
11799 Type_context val_context(mt->val_type(), false);
11800 for (Expression_list::const_iterator pv = this->vals_->begin();
11801 pv != this->vals_->end();
11804 (*pv)->determine_type(&key_context);
11806 (*pv)->determine_type(&val_context);
11813 Map_construction_expression::do_check_types(Gogo*)
11815 if (this->vals_ == NULL)
11818 Map_type* mt = this->type_->map_type();
11820 Type* key_type = mt->key_type();
11821 Type* val_type = mt->val_type();
11822 for (Expression_list::const_iterator pv = this->vals_->begin();
11823 pv != this->vals_->end();
11826 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
11828 error_at((*pv)->location(),
11829 "incompatible type for element %d key in map construction",
11831 this->set_is_error();
11834 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
11836 error_at((*pv)->location(),
11837 ("incompatible type for element %d value "
11838 "in map construction"),
11840 this->set_is_error();
11845 // Return a tree for constructing a map.
11848 Map_construction_expression::do_get_tree(Translate_context* context)
11850 Gogo* gogo = context->gogo();
11851 Location loc = this->location();
11853 Map_type* mt = this->type_->map_type();
11855 // Build a struct to hold the key and value.
11856 tree struct_type = make_node(RECORD_TYPE);
11858 Type* key_type = mt->key_type();
11859 tree id = get_identifier("__key");
11860 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
11861 if (key_type_tree == error_mark_node)
11862 return error_mark_node;
11863 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
11865 DECL_CONTEXT(key_field) = struct_type;
11866 TYPE_FIELDS(struct_type) = key_field;
11868 Type* val_type = mt->val_type();
11869 id = get_identifier("__val");
11870 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
11871 if (val_type_tree == error_mark_node)
11872 return error_mark_node;
11873 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
11875 DECL_CONTEXT(val_field) = struct_type;
11876 DECL_CHAIN(key_field) = val_field;
11878 layout_type(struct_type);
11880 bool is_constant = true;
11885 if (this->vals_ == NULL || this->vals_->empty())
11887 valaddr = null_pointer_node;
11888 make_tmp = NULL_TREE;
11892 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11893 this->vals_->size() / 2);
11895 for (Expression_list::const_iterator pv = this->vals_->begin();
11896 pv != this->vals_->end();
11899 bool one_is_constant = true;
11901 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
11903 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
11904 elt->index = key_field;
11905 tree val_tree = (*pv)->get_tree(context);
11906 elt->value = Expression::convert_for_assignment(context, key_type,
11909 if (elt->value == error_mark_node)
11910 return error_mark_node;
11911 if (!TREE_CONSTANT(elt->value))
11912 one_is_constant = false;
11916 elt = VEC_quick_push(constructor_elt, one, NULL);
11917 elt->index = val_field;
11918 val_tree = (*pv)->get_tree(context);
11919 elt->value = Expression::convert_for_assignment(context, val_type,
11922 if (elt->value == error_mark_node)
11923 return error_mark_node;
11924 if (!TREE_CONSTANT(elt->value))
11925 one_is_constant = false;
11927 elt = VEC_quick_push(constructor_elt, values, NULL);
11928 elt->index = size_int(i);
11929 elt->value = build_constructor(struct_type, one);
11930 if (one_is_constant)
11931 TREE_CONSTANT(elt->value) = 1;
11933 is_constant = false;
11936 tree index_type = build_index_type(size_int(i - 1));
11937 tree array_type = build_array_type(struct_type, index_type);
11938 tree init = build_constructor(array_type, values);
11940 TREE_CONSTANT(init) = 1;
11942 if (current_function_decl != NULL)
11944 tmp = create_tmp_var(array_type, get_name(array_type));
11945 DECL_INITIAL(tmp) = init;
11946 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
11947 void_type_node, tmp);
11948 TREE_ADDRESSABLE(tmp) = 1;
11952 tmp = build_decl(loc.gcc_location(), VAR_DECL,
11953 create_tmp_var_name("M"), array_type);
11954 DECL_EXTERNAL(tmp) = 0;
11955 TREE_PUBLIC(tmp) = 0;
11956 TREE_STATIC(tmp) = 1;
11957 DECL_ARTIFICIAL(tmp) = 1;
11958 if (!TREE_CONSTANT(init))
11959 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
11960 void_type_node, tmp, init);
11963 TREE_READONLY(tmp) = 1;
11964 TREE_CONSTANT(tmp) = 1;
11965 DECL_INITIAL(tmp) = init;
11966 make_tmp = NULL_TREE;
11968 rest_of_decl_compilation(tmp, 1, 0);
11971 valaddr = build_fold_addr_expr(tmp);
11974 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
11976 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11977 if (type_tree == error_mark_node)
11978 return error_mark_node;
11980 static tree construct_map_fndecl;
11981 tree call = Gogo::call_builtin(&construct_map_fndecl,
11983 "__go_construct_map",
11986 TREE_TYPE(descriptor),
11991 TYPE_SIZE_UNIT(struct_type),
11993 byte_position(val_field),
11995 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
11996 const_ptr_type_node,
11997 fold_convert(const_ptr_type_node, valaddr));
11998 if (call == error_mark_node)
11999 return error_mark_node;
12002 if (make_tmp == NULL)
12005 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12010 // Export an array construction.
12013 Map_construction_expression::do_export(Export* exp) const
12015 exp->write_c_string("convert(");
12016 exp->write_type(this->type_);
12017 for (Expression_list::const_iterator pv = this->vals_->begin();
12018 pv != this->vals_->end();
12021 exp->write_c_string(", ");
12022 (*pv)->export_expression(exp);
12024 exp->write_c_string(")");
12027 // Dump ast representation for a map construction expression.
12030 Map_construction_expression::do_dump_expression(
12031 Ast_dump_context* ast_dump_context) const
12033 ast_dump_context->ostream() << "{" ;
12034 ast_dump_context->dump_expression_list(this->vals_, true);
12035 ast_dump_context->ostream() << "}";
12038 // A general composite literal. This is lowered to a type specific
12041 class Composite_literal_expression : public Parser_expression
12044 Composite_literal_expression(Type* type, int depth, bool has_keys,
12045 Expression_list* vals, Location location)
12046 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12047 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12052 do_traverse(Traverse* traverse);
12055 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12060 return new Composite_literal_expression(this->type_, this->depth_,
12062 (this->vals_ == NULL
12064 : this->vals_->copy()),
12069 do_dump_expression(Ast_dump_context*) const;
12073 lower_struct(Gogo*, Type*);
12076 lower_array(Type*);
12079 make_array(Type*, Expression_list*);
12082 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12084 // The type of the composite literal.
12086 // The depth within a list of composite literals within a composite
12087 // literal, when the type is omitted.
12089 // The values to put in the composite literal.
12090 Expression_list* vals_;
12091 // If this is true, then VALS_ is a list of pairs: a key and a
12092 // value. In an array initializer, a missing key will be NULL.
12099 Composite_literal_expression::do_traverse(Traverse* traverse)
12101 if (this->vals_ != NULL
12102 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12103 return TRAVERSE_EXIT;
12104 return Type::traverse(this->type_, traverse);
12107 // Lower a generic composite literal into a specific version based on
12111 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12112 Statement_inserter* inserter, int)
12114 Type* type = this->type_;
12116 for (int depth = this->depth_; depth > 0; --depth)
12118 if (type->array_type() != NULL)
12119 type = type->array_type()->element_type();
12120 else if (type->map_type() != NULL)
12121 type = type->map_type()->val_type();
12124 if (!type->is_error())
12125 error_at(this->location(),
12126 ("may only omit types within composite literals "
12127 "of slice, array, or map type"));
12128 return Expression::make_error(this->location());
12132 Type *pt = type->points_to();
12133 bool is_pointer = false;
12141 if (type->is_error())
12142 return Expression::make_error(this->location());
12143 else if (type->struct_type() != NULL)
12144 ret = this->lower_struct(gogo, type);
12145 else if (type->array_type() != NULL)
12146 ret = this->lower_array(type);
12147 else if (type->map_type() != NULL)
12148 ret = this->lower_map(gogo, function, inserter, type);
12151 error_at(this->location(),
12152 ("expected struct, slice, array, or map type "
12153 "for composite literal"));
12154 return Expression::make_error(this->location());
12158 ret = Expression::make_heap_composite(ret, this->location());
12163 // Lower a struct composite literal.
12166 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12168 Location location = this->location();
12169 Struct_type* st = type->struct_type();
12170 if (this->vals_ == NULL || !this->has_keys_)
12172 if (this->vals_ != NULL
12173 && !this->vals_->empty()
12174 && type->named_type() != NULL
12175 && type->named_type()->named_object()->package() != NULL)
12177 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12178 pf != st->fields()->end();
12181 if (Gogo::is_hidden_name(pf->field_name()))
12182 error_at(this->location(),
12183 "assignment of unexported field %qs in %qs literal",
12184 Gogo::message_name(pf->field_name()).c_str(),
12185 type->named_type()->message_name().c_str());
12189 return new Struct_construction_expression(type, this->vals_, location);
12192 size_t field_count = st->field_count();
12193 std::vector<Expression*> vals(field_count);
12194 Expression_list::const_iterator p = this->vals_->begin();
12195 while (p != this->vals_->end())
12197 Expression* name_expr = *p;
12200 go_assert(p != this->vals_->end());
12201 Expression* val = *p;
12205 if (name_expr == NULL)
12207 error_at(val->location(), "mixture of field and value initializers");
12208 return Expression::make_error(location);
12211 bool bad_key = false;
12213 const Named_object* no = NULL;
12214 switch (name_expr->classification())
12216 case EXPRESSION_UNKNOWN_REFERENCE:
12217 name = name_expr->unknown_expression()->name();
12220 case EXPRESSION_CONST_REFERENCE:
12221 no = static_cast<Const_expression*>(name_expr)->named_object();
12224 case EXPRESSION_TYPE:
12226 Type* t = name_expr->type();
12227 Named_type* nt = t->named_type();
12231 no = nt->named_object();
12235 case EXPRESSION_VAR_REFERENCE:
12236 no = name_expr->var_expression()->named_object();
12239 case EXPRESSION_FUNC_REFERENCE:
12240 no = name_expr->func_expression()->named_object();
12243 case EXPRESSION_UNARY:
12244 // If there is a local variable around with the same name as
12245 // the field, and this occurs in the closure, then the
12246 // parser may turn the field reference into an indirection
12247 // through the closure. FIXME: This is a mess.
12250 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12251 if (ue->op() == OPERATOR_MULT)
12253 Field_reference_expression* fre =
12254 ue->operand()->field_reference_expression();
12258 fre->expr()->type()->deref()->struct_type();
12261 const Struct_field* sf = st->field(fre->field_index());
12262 name = sf->field_name();
12264 // See below. FIXME.
12265 if (!Gogo::is_hidden_name(name)
12269 if (gogo->lookup_global(name.c_str()) != NULL)
12270 name = gogo->pack_hidden_name(name, false);
12274 snprintf(buf, sizeof buf, "%u", fre->field_index());
12275 size_t buflen = strlen(buf);
12276 if (name.compare(name.length() - buflen, buflen, buf)
12279 name = name.substr(0, name.length() - buflen);
12294 error_at(name_expr->location(), "expected struct field name");
12295 return Expression::make_error(location);
12302 // A predefined name won't be packed. If it starts with a
12303 // lower case letter we need to check for that case, because
12304 // the field name will be packed. FIXME.
12305 if (!Gogo::is_hidden_name(name)
12309 Named_object* gno = gogo->lookup_global(name.c_str());
12311 name = gogo->pack_hidden_name(name, false);
12315 unsigned int index;
12316 const Struct_field* sf = st->find_local_field(name, &index);
12319 error_at(name_expr->location(), "unknown field %qs in %qs",
12320 Gogo::message_name(name).c_str(),
12321 (type->named_type() != NULL
12322 ? type->named_type()->message_name().c_str()
12323 : "unnamed struct"));
12324 return Expression::make_error(location);
12326 if (vals[index] != NULL)
12328 error_at(name_expr->location(),
12329 "duplicate value for field %qs in %qs",
12330 Gogo::message_name(name).c_str(),
12331 (type->named_type() != NULL
12332 ? type->named_type()->message_name().c_str()
12333 : "unnamed struct"));
12334 return Expression::make_error(location);
12337 if (type->named_type() != NULL
12338 && type->named_type()->named_object()->package() != NULL
12339 && Gogo::is_hidden_name(sf->field_name()))
12340 error_at(name_expr->location(),
12341 "assignment of unexported field %qs in %qs literal",
12342 Gogo::message_name(sf->field_name()).c_str(),
12343 type->named_type()->message_name().c_str());
12348 Expression_list* list = new Expression_list;
12349 list->reserve(field_count);
12350 for (size_t i = 0; i < field_count; ++i)
12351 list->push_back(vals[i]);
12353 return new Struct_construction_expression(type, list, location);
12356 // Lower an array composite literal.
12359 Composite_literal_expression::lower_array(Type* type)
12361 Location location = this->location();
12362 if (this->vals_ == NULL || !this->has_keys_)
12363 return this->make_array(type, this->vals_);
12365 std::vector<Expression*> vals;
12366 vals.reserve(this->vals_->size());
12367 unsigned long index = 0;
12368 Expression_list::const_iterator p = this->vals_->begin();
12369 while (p != this->vals_->end())
12371 Expression* index_expr = *p;
12374 go_assert(p != this->vals_->end());
12375 Expression* val = *p;
12379 if (index_expr != NULL)
12381 Numeric_constant nc;
12382 if (!index_expr->numeric_constant_value(&nc))
12384 error_at(index_expr->location(),
12385 "index expression is not integer constant");
12386 return Expression::make_error(location);
12389 switch (nc.to_unsigned_long(&index))
12391 case Numeric_constant::NC_UL_VALID:
12393 case Numeric_constant::NC_UL_NOTINT:
12394 error_at(index_expr->location(),
12395 "index expression is not integer constant");
12396 return Expression::make_error(location);
12397 case Numeric_constant::NC_UL_NEGATIVE:
12398 error_at(index_expr->location(), "index expression is negative");
12399 return Expression::make_error(location);
12400 case Numeric_constant::NC_UL_BIG:
12401 error_at(index_expr->location(), "index value overflow");
12402 return Expression::make_error(location);
12407 Named_type* ntype = Type::lookup_integer_type("int");
12408 Integer_type* inttype = ntype->integer_type();
12409 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12410 && index >> (inttype->bits() - 1) != 0)
12412 error_at(index_expr->location(), "index value overflow");
12413 return Expression::make_error(location);
12416 // FIXME: Our representation isn't very good; this avoids
12418 if (index > 0x1000000)
12420 error_at(index_expr->location(), "index too large for compiler");
12421 return Expression::make_error(location);
12425 if (index == vals.size())
12426 vals.push_back(val);
12429 if (index > vals.size())
12431 vals.reserve(index + 32);
12432 vals.resize(index + 1, static_cast<Expression*>(NULL));
12434 if (vals[index] != NULL)
12436 error_at((index_expr != NULL
12437 ? index_expr->location()
12438 : val->location()),
12439 "duplicate value for index %lu",
12441 return Expression::make_error(location);
12449 size_t size = vals.size();
12450 Expression_list* list = new Expression_list;
12451 list->reserve(size);
12452 for (size_t i = 0; i < size; ++i)
12453 list->push_back(vals[i]);
12455 return this->make_array(type, list);
12458 // Actually build the array composite literal. This handles
12462 Composite_literal_expression::make_array(Type* type, Expression_list* vals)
12464 Location location = this->location();
12465 Array_type* at = type->array_type();
12466 if (at->length() != NULL && at->length()->is_nil_expression())
12468 size_t size = vals == NULL ? 0 : vals->size();
12470 mpz_init_set_ui(vlen, size);
12471 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12473 at = Type::make_array_type(at->element_type(), elen);
12476 if (at->length() != NULL)
12477 return new Fixed_array_construction_expression(type, vals, location);
12479 return new Open_array_construction_expression(type, vals, location);
12482 // Lower a map composite literal.
12485 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12486 Statement_inserter* inserter,
12489 Location location = this->location();
12490 if (this->vals_ != NULL)
12492 if (!this->has_keys_)
12494 error_at(location, "map composite literal must have keys");
12495 return Expression::make_error(location);
12498 for (Expression_list::iterator p = this->vals_->begin();
12499 p != this->vals_->end();
12505 error_at((*p)->location(),
12506 "map composite literal must have keys for every value");
12507 return Expression::make_error(location);
12509 // Make sure we have lowered the key; it may not have been
12510 // lowered in order to handle keys for struct composite
12511 // literals. Lower it now to get the right error message.
12512 if ((*p)->unknown_expression() != NULL)
12514 (*p)->unknown_expression()->clear_is_composite_literal_key();
12515 gogo->lower_expression(function, inserter, &*p);
12516 go_assert((*p)->is_error_expression());
12517 return Expression::make_error(location);
12522 return new Map_construction_expression(type, this->vals_, location);
12525 // Dump ast representation for a composite literal expression.
12528 Composite_literal_expression::do_dump_expression(
12529 Ast_dump_context* ast_dump_context) const
12531 ast_dump_context->ostream() << "composite(";
12532 ast_dump_context->dump_type(this->type_);
12533 ast_dump_context->ostream() << ", {";
12534 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12535 ast_dump_context->ostream() << "})";
12538 // Make a composite literal expression.
12541 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12542 Expression_list* vals,
12545 return new Composite_literal_expression(type, depth, has_keys, vals,
12549 // Return whether this expression is a composite literal.
12552 Expression::is_composite_literal() const
12554 switch (this->classification_)
12556 case EXPRESSION_COMPOSITE_LITERAL:
12557 case EXPRESSION_STRUCT_CONSTRUCTION:
12558 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12559 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12560 case EXPRESSION_MAP_CONSTRUCTION:
12567 // Return whether this expression is a composite literal which is not
12571 Expression::is_nonconstant_composite_literal() const
12573 switch (this->classification_)
12575 case EXPRESSION_STRUCT_CONSTRUCTION:
12577 const Struct_construction_expression *psce =
12578 static_cast<const Struct_construction_expression*>(this);
12579 return !psce->is_constant_struct();
12581 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12583 const Fixed_array_construction_expression *pace =
12584 static_cast<const Fixed_array_construction_expression*>(this);
12585 return !pace->is_constant_array();
12587 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12589 const Open_array_construction_expression *pace =
12590 static_cast<const Open_array_construction_expression*>(this);
12591 return !pace->is_constant_array();
12593 case EXPRESSION_MAP_CONSTRUCTION:
12600 // Return true if this is a reference to a local variable.
12603 Expression::is_local_variable() const
12605 const Var_expression* ve = this->var_expression();
12608 const Named_object* no = ve->named_object();
12609 return (no->is_result_variable()
12610 || (no->is_variable() && !no->var_value()->is_global()));
12613 // Class Type_guard_expression.
12618 Type_guard_expression::do_traverse(Traverse* traverse)
12620 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12621 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12622 return TRAVERSE_EXIT;
12623 return TRAVERSE_CONTINUE;
12626 // Check types of a type guard expression. The expression must have
12627 // an interface type, but the actual type conversion is checked at run
12631 Type_guard_expression::do_check_types(Gogo*)
12633 // 6g permits using a type guard with unsafe.pointer; we are
12635 Type* expr_type = this->expr_->type();
12636 if (expr_type->is_unsafe_pointer_type())
12638 if (this->type_->points_to() == NULL
12639 && (this->type_->integer_type() == NULL
12640 || (this->type_->forwarded()
12641 != Type::lookup_integer_type("uintptr"))))
12642 this->report_error(_("invalid unsafe.Pointer conversion"));
12644 else if (this->type_->is_unsafe_pointer_type())
12646 if (expr_type->points_to() == NULL
12647 && (expr_type->integer_type() == NULL
12648 || (expr_type->forwarded()
12649 != Type::lookup_integer_type("uintptr"))))
12650 this->report_error(_("invalid unsafe.Pointer conversion"));
12652 else if (expr_type->interface_type() == NULL)
12654 if (!expr_type->is_error() && !this->type_->is_error())
12655 this->report_error(_("type assertion only valid for interface types"));
12656 this->set_is_error();
12658 else if (this->type_->interface_type() == NULL)
12660 std::string reason;
12661 if (!expr_type->interface_type()->implements_interface(this->type_,
12664 if (!this->type_->is_error())
12666 if (reason.empty())
12667 this->report_error(_("impossible type assertion: "
12668 "type does not implement interface"));
12670 error_at(this->location(),
12671 ("impossible type assertion: "
12672 "type does not implement interface (%s)"),
12675 this->set_is_error();
12680 // Return a tree for a type guard expression.
12683 Type_guard_expression::do_get_tree(Translate_context* context)
12685 Gogo* gogo = context->gogo();
12686 tree expr_tree = this->expr_->get_tree(context);
12687 if (expr_tree == error_mark_node)
12688 return error_mark_node;
12689 Type* expr_type = this->expr_->type();
12690 if ((this->type_->is_unsafe_pointer_type()
12691 && (expr_type->points_to() != NULL
12692 || expr_type->integer_type() != NULL))
12693 || (expr_type->is_unsafe_pointer_type()
12694 && this->type_->points_to() != NULL))
12695 return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12697 else if (expr_type->is_unsafe_pointer_type()
12698 && this->type_->integer_type() != NULL)
12699 return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12701 else if (this->type_->interface_type() != NULL)
12702 return Expression::convert_interface_to_interface(context, this->type_,
12703 this->expr_->type(),
12707 return Expression::convert_for_assignment(context, this->type_,
12708 this->expr_->type(), expr_tree,
12712 // Dump ast representation for a type guard expression.
12715 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12718 this->expr_->dump_expression(ast_dump_context);
12719 ast_dump_context->ostream() << ".";
12720 ast_dump_context->dump_type(this->type_);
12723 // Make a type guard expression.
12726 Expression::make_type_guard(Expression* expr, Type* type,
12729 return new Type_guard_expression(expr, type, location);
12732 // Class Heap_composite_expression.
12734 // When you take the address of a composite literal, it is allocated
12735 // on the heap. This class implements that.
12737 class Heap_composite_expression : public Expression
12740 Heap_composite_expression(Expression* expr, Location location)
12741 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
12747 do_traverse(Traverse* traverse)
12748 { return Expression::traverse(&this->expr_, traverse); }
12752 { return Type::make_pointer_type(this->expr_->type()); }
12755 do_determine_type(const Type_context*)
12756 { this->expr_->determine_type_no_context(); }
12761 return Expression::make_heap_composite(this->expr_->copy(),
12766 do_get_tree(Translate_context*);
12768 // We only export global objects, and the parser does not generate
12769 // this in global scope.
12771 do_export(Export*) const
12772 { go_unreachable(); }
12775 do_dump_expression(Ast_dump_context*) const;
12778 // The composite literal which is being put on the heap.
12782 // Return a tree which allocates a composite literal on the heap.
12785 Heap_composite_expression::do_get_tree(Translate_context* context)
12787 tree expr_tree = this->expr_->get_tree(context);
12788 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
12789 return error_mark_node;
12790 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
12791 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
12792 tree space = context->gogo()->allocate_memory(this->expr_->type(),
12793 expr_size, this->location());
12794 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
12795 space = save_expr(space);
12796 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12798 TREE_THIS_NOTRAP(ref) = 1;
12799 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
12800 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
12802 SET_EXPR_LOCATION(ret, this->location().gcc_location());
12806 // Dump ast representation for a heap composite expression.
12809 Heap_composite_expression::do_dump_expression(
12810 Ast_dump_context* ast_dump_context) const
12812 ast_dump_context->ostream() << "&(";
12813 ast_dump_context->dump_expression(this->expr_);
12814 ast_dump_context->ostream() << ")";
12817 // Allocate a composite literal on the heap.
12820 Expression::make_heap_composite(Expression* expr, Location location)
12822 return new Heap_composite_expression(expr, location);
12825 // Class Receive_expression.
12827 // Return the type of a receive expression.
12830 Receive_expression::do_type()
12832 Channel_type* channel_type = this->channel_->type()->channel_type();
12833 if (channel_type == NULL)
12834 return Type::make_error_type();
12835 return channel_type->element_type();
12838 // Check types for a receive expression.
12841 Receive_expression::do_check_types(Gogo*)
12843 Type* type = this->channel_->type();
12844 if (type->is_error())
12846 this->set_is_error();
12849 if (type->channel_type() == NULL)
12851 this->report_error(_("expected channel"));
12854 if (!type->channel_type()->may_receive())
12856 this->report_error(_("invalid receive on send-only channel"));
12861 // Get a tree for a receive expression.
12864 Receive_expression::do_get_tree(Translate_context* context)
12866 Location loc = this->location();
12868 Channel_type* channel_type = this->channel_->type()->channel_type();
12869 if (channel_type == NULL)
12871 go_assert(this->channel_->type()->is_error());
12872 return error_mark_node;
12875 Expression* td = Expression::make_type_descriptor(channel_type, loc);
12876 tree td_tree = td->get_tree(context);
12878 Type* element_type = channel_type->element_type();
12879 Btype* element_type_btype = element_type->get_backend(context->gogo());
12880 tree element_type_tree = type_to_tree(element_type_btype);
12882 tree channel = this->channel_->get_tree(context);
12883 if (element_type_tree == error_mark_node || channel == error_mark_node)
12884 return error_mark_node;
12886 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
12889 // Dump ast representation for a receive expression.
12892 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12894 ast_dump_context->ostream() << " <- " ;
12895 ast_dump_context->dump_expression(channel_);
12898 // Make a receive expression.
12900 Receive_expression*
12901 Expression::make_receive(Expression* channel, Location location)
12903 return new Receive_expression(channel, location);
12906 // An expression which evaluates to a pointer to the type descriptor
12909 class Type_descriptor_expression : public Expression
12912 Type_descriptor_expression(Type* type, Location location)
12913 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
12920 { return Type::make_type_descriptor_ptr_type(); }
12923 do_determine_type(const Type_context*)
12931 do_get_tree(Translate_context* context)
12933 return this->type_->type_descriptor_pointer(context->gogo(),
12938 do_dump_expression(Ast_dump_context*) const;
12941 // The type for which this is the descriptor.
12945 // Dump ast representation for a type descriptor expression.
12948 Type_descriptor_expression::do_dump_expression(
12949 Ast_dump_context* ast_dump_context) const
12951 ast_dump_context->dump_type(this->type_);
12954 // Make a type descriptor expression.
12957 Expression::make_type_descriptor(Type* type, Location location)
12959 return new Type_descriptor_expression(type, location);
12962 // An expression which evaluates to some characteristic of a type.
12963 // This is only used to initialize fields of a type descriptor. Using
12964 // a new expression class is slightly inefficient but gives us a good
12965 // separation between the frontend and the middle-end with regard to
12966 // how types are laid out.
12968 class Type_info_expression : public Expression
12971 Type_info_expression(Type* type, Type_info type_info)
12972 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
12973 type_(type), type_info_(type_info)
12981 do_determine_type(const Type_context*)
12989 do_get_tree(Translate_context* context);
12992 do_dump_expression(Ast_dump_context*) const;
12995 // The type for which we are getting information.
12997 // What information we want.
12998 Type_info type_info_;
13001 // The type is chosen to match what the type descriptor struct
13005 Type_info_expression::do_type()
13007 switch (this->type_info_)
13009 case TYPE_INFO_SIZE:
13010 return Type::lookup_integer_type("uintptr");
13011 case TYPE_INFO_ALIGNMENT:
13012 case TYPE_INFO_FIELD_ALIGNMENT:
13013 return Type::lookup_integer_type("uint8");
13019 // Return type information in GENERIC.
13022 Type_info_expression::do_get_tree(Translate_context* context)
13024 Btype* btype = this->type_->get_backend(context->gogo());
13025 Gogo* gogo = context->gogo();
13027 switch (this->type_info_)
13029 case TYPE_INFO_SIZE:
13030 val = gogo->backend()->type_size(btype);
13032 case TYPE_INFO_ALIGNMENT:
13033 val = gogo->backend()->type_alignment(btype);
13035 case TYPE_INFO_FIELD_ALIGNMENT:
13036 val = gogo->backend()->type_field_alignment(btype);
13041 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13042 go_assert(val_type_tree != error_mark_node);
13043 return build_int_cstu(val_type_tree, val);
13046 // Dump ast representation for a type info expression.
13049 Type_info_expression::do_dump_expression(
13050 Ast_dump_context* ast_dump_context) const
13052 ast_dump_context->ostream() << "typeinfo(";
13053 ast_dump_context->dump_type(this->type_);
13054 ast_dump_context->ostream() << ",";
13055 ast_dump_context->ostream() <<
13056 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13057 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13058 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13060 ast_dump_context->ostream() << ")";
13063 // Make a type info expression.
13066 Expression::make_type_info(Type* type, Type_info type_info)
13068 return new Type_info_expression(type, type_info);
13071 // An expression which evaluates to the offset of a field within a
13072 // struct. This, like Type_info_expression, q.v., is only used to
13073 // initialize fields of a type descriptor.
13075 class Struct_field_offset_expression : public Expression
13078 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13079 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13080 Linemap::predeclared_location()),
13081 type_(type), field_(field)
13087 { return Type::lookup_integer_type("uintptr"); }
13090 do_determine_type(const Type_context*)
13098 do_get_tree(Translate_context* context);
13101 do_dump_expression(Ast_dump_context*) const;
13104 // The type of the struct.
13105 Struct_type* type_;
13107 const Struct_field* field_;
13110 // Return a struct field offset in GENERIC.
13113 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13115 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13116 if (type_tree == error_mark_node)
13117 return error_mark_node;
13119 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13120 go_assert(val_type_tree != error_mark_node);
13122 const Struct_field_list* fields = this->type_->fields();
13123 tree struct_field_tree = TYPE_FIELDS(type_tree);
13124 Struct_field_list::const_iterator p;
13125 for (p = fields->begin();
13126 p != fields->end();
13127 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13129 go_assert(struct_field_tree != NULL_TREE);
13130 if (&*p == this->field_)
13133 go_assert(&*p == this->field_);
13135 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13136 byte_position(struct_field_tree));
13139 // Dump ast representation for a struct field offset expression.
13142 Struct_field_offset_expression::do_dump_expression(
13143 Ast_dump_context* ast_dump_context) const
13145 ast_dump_context->ostream() << "unsafe.Offsetof(";
13146 ast_dump_context->dump_type(this->type_);
13147 ast_dump_context->ostream() << '.';
13148 ast_dump_context->ostream() <<
13149 Gogo::message_name(this->field_->field_name());
13150 ast_dump_context->ostream() << ")";
13153 // Make an expression for a struct field offset.
13156 Expression::make_struct_field_offset(Struct_type* type,
13157 const Struct_field* field)
13159 return new Struct_field_offset_expression(type, field);
13162 // An expression which evaluates to a pointer to the map descriptor of
13165 class Map_descriptor_expression : public Expression
13168 Map_descriptor_expression(Map_type* type, Location location)
13169 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13176 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13179 do_determine_type(const Type_context*)
13187 do_get_tree(Translate_context* context)
13189 return this->type_->map_descriptor_pointer(context->gogo(),
13194 do_dump_expression(Ast_dump_context*) const;
13197 // The type for which this is the descriptor.
13201 // Dump ast representation for a map descriptor expression.
13204 Map_descriptor_expression::do_dump_expression(
13205 Ast_dump_context* ast_dump_context) const
13207 ast_dump_context->ostream() << "map_descriptor(";
13208 ast_dump_context->dump_type(this->type_);
13209 ast_dump_context->ostream() << ")";
13212 // Make a map descriptor expression.
13215 Expression::make_map_descriptor(Map_type* type, Location location)
13217 return new Map_descriptor_expression(type, location);
13220 // An expression which evaluates to the address of an unnamed label.
13222 class Label_addr_expression : public Expression
13225 Label_addr_expression(Label* label, Location location)
13226 : Expression(EXPRESSION_LABEL_ADDR, location),
13233 { return Type::make_pointer_type(Type::make_void_type()); }
13236 do_determine_type(const Type_context*)
13241 { return new Label_addr_expression(this->label_, this->location()); }
13244 do_get_tree(Translate_context* context)
13246 return expr_to_tree(this->label_->get_addr(context, this->location()));
13250 do_dump_expression(Ast_dump_context* ast_dump_context) const
13251 { ast_dump_context->ostream() << this->label_->name(); }
13254 // The label whose address we are taking.
13258 // Make an expression for the address of an unnamed label.
13261 Expression::make_label_addr(Label* label, Location location)
13263 return new Label_addr_expression(label, location);
13266 // Import an expression. This comes at the end in order to see the
13267 // various class definitions.
13270 Expression::import_expression(Import* imp)
13272 int c = imp->peek_char();
13273 if (imp->match_c_string("- ")
13274 || imp->match_c_string("! ")
13275 || imp->match_c_string("^ "))
13276 return Unary_expression::do_import(imp);
13278 return Binary_expression::do_import(imp);
13279 else if (imp->match_c_string("true")
13280 || imp->match_c_string("false"))
13281 return Boolean_expression::do_import(imp);
13283 return String_expression::do_import(imp);
13284 else if (c == '-' || (c >= '0' && c <= '9'))
13286 // This handles integers, floats and complex constants.
13287 return Integer_expression::do_import(imp);
13289 else if (imp->match_c_string("nil"))
13290 return Nil_expression::do_import(imp);
13291 else if (imp->match_c_string("convert"))
13292 return Type_conversion_expression::do_import(imp);
13295 error_at(imp->location(), "import error: expected expression");
13296 return Expression::make_error(imp->location());
13300 // Class Expression_list.
13302 // Traverse the list.
13305 Expression_list::traverse(Traverse* traverse)
13307 for (Expression_list::iterator p = this->begin();
13313 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13314 return TRAVERSE_EXIT;
13317 return TRAVERSE_CONTINUE;
13323 Expression_list::copy()
13325 Expression_list* ret = new Expression_list();
13326 for (Expression_list::iterator p = this->begin();
13331 ret->push_back(NULL);
13333 ret->push_back((*p)->copy());
13338 // Return whether an expression list has an error expression.
13341 Expression_list::contains_error() const
13343 for (Expression_list::const_iterator p = this->begin();
13346 if (*p != NULL && (*p)->is_error_expression())
13351 // Class Numeric_constant.
13355 Numeric_constant::~Numeric_constant()
13360 // Copy constructor.
13362 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13363 : classification_(a.classification_), type_(a.type_)
13365 switch (a.classification_)
13371 mpz_init_set(this->u_.int_val, a.u_.int_val);
13374 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13377 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13379 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13387 // Assignment operator.
13390 Numeric_constant::operator=(const Numeric_constant& a)
13393 this->classification_ = a.classification_;
13394 this->type_ = a.type_;
13395 switch (a.classification_)
13401 mpz_init_set(this->u_.int_val, a.u_.int_val);
13404 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13407 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13409 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13418 // Clear the contents.
13421 Numeric_constant::clear()
13423 switch (this->classification_)
13429 mpz_clear(this->u_.int_val);
13432 mpfr_clear(this->u_.float_val);
13435 mpfr_clear(this->u_.complex_val.real);
13436 mpfr_clear(this->u_.complex_val.imag);
13441 this->classification_ = NC_INVALID;
13444 // Set to an unsigned long value.
13447 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13450 this->classification_ = NC_INT;
13451 this->type_ = type;
13452 mpz_init_set_ui(this->u_.int_val, val);
13455 // Set to an integer value.
13458 Numeric_constant::set_int(Type* type, const mpz_t val)
13461 this->classification_ = NC_INT;
13462 this->type_ = type;
13463 mpz_init_set(this->u_.int_val, val);
13466 // Set to a rune value.
13469 Numeric_constant::set_rune(Type* type, const mpz_t val)
13472 this->classification_ = NC_RUNE;
13473 this->type_ = type;
13474 mpz_init_set(this->u_.int_val, val);
13477 // Set to a floating point value.
13480 Numeric_constant::set_float(Type* type, const mpfr_t val)
13483 this->classification_ = NC_FLOAT;
13484 this->type_ = type;
13485 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13488 // Set to a complex value.
13491 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13494 this->classification_ = NC_COMPLEX;
13495 this->type_ = type;
13496 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13497 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13500 // Get an int value.
13503 Numeric_constant::get_int(mpz_t* val) const
13505 go_assert(this->is_int());
13506 mpz_init_set(*val, this->u_.int_val);
13509 // Get a rune value.
13512 Numeric_constant::get_rune(mpz_t* val) const
13514 go_assert(this->is_rune());
13515 mpz_init_set(*val, this->u_.int_val);
13518 // Get a floating point value.
13521 Numeric_constant::get_float(mpfr_t* val) const
13523 go_assert(this->is_float());
13524 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13527 // Get a complex value.
13530 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13532 go_assert(this->is_complex());
13533 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13534 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13537 // Express value as unsigned long if possible.
13539 Numeric_constant::To_unsigned_long
13540 Numeric_constant::to_unsigned_long(unsigned long* val) const
13542 switch (this->classification_)
13546 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13548 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13550 if (!mpfr_zero_p(this->u_.complex_val.imag))
13551 return NC_UL_NOTINT;
13552 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13558 // Express integer value as unsigned long if possible.
13560 Numeric_constant::To_unsigned_long
13561 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13562 unsigned long *val) const
13564 if (mpz_sgn(ival) < 0)
13565 return NC_UL_NEGATIVE;
13566 unsigned long ui = mpz_get_ui(ival);
13567 if (mpz_cmp_ui(ival, ui) != 0)
13570 return NC_UL_VALID;
13573 // Express floating point value as unsigned long if possible.
13575 Numeric_constant::To_unsigned_long
13576 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13577 unsigned long *val) const
13579 if (!mpfr_integer_p(fval))
13580 return NC_UL_NOTINT;
13583 mpfr_get_z(ival, fval, GMP_RNDN);
13584 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13589 // Convert value to integer if possible.
13592 Numeric_constant::to_int(mpz_t* val) const
13594 switch (this->classification_)
13598 mpz_init_set(*val, this->u_.int_val);
13601 if (!mpfr_integer_p(this->u_.float_val))
13604 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13607 if (!mpfr_zero_p(this->u_.complex_val.imag)
13608 || !mpfr_integer_p(this->u_.complex_val.real))
13611 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13618 // Convert value to floating point if possible.
13621 Numeric_constant::to_float(mpfr_t* val) const
13623 switch (this->classification_)
13627 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13630 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13633 if (!mpfr_zero_p(this->u_.complex_val.imag))
13635 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13642 // Convert value to complex.
13645 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13647 switch (this->classification_)
13651 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13652 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13655 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13656 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13659 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13660 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13670 Numeric_constant::type() const
13672 if (this->type_ != NULL)
13673 return this->type_;
13674 switch (this->classification_)
13677 return Type::make_abstract_integer_type();
13679 return Type::make_abstract_character_type();
13681 return Type::make_abstract_float_type();
13683 return Type::make_abstract_complex_type();
13689 // If the constant can be expressed in TYPE, then set the type of the
13690 // constant to TYPE and return true. Otherwise return false, and, if
13691 // ISSUE_ERROR is true, report an appropriate error message.
13694 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13699 else if (type->integer_type() != NULL)
13700 ret = this->check_int_type(type->integer_type(), issue_error, loc);
13701 else if (type->float_type() != NULL)
13702 ret = this->check_float_type(type->float_type(), issue_error, loc);
13703 else if (type->complex_type() != NULL)
13704 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
13708 this->type_ = type;
13712 // Check whether the constant can be expressed in an integer type.
13715 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
13716 Location location) const
13719 switch (this->classification_)
13723 mpz_init_set(val, this->u_.int_val);
13727 if (!mpfr_integer_p(this->u_.float_val))
13730 error_at(location, "floating point constant truncated to integer");
13734 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
13738 if (!mpfr_integer_p(this->u_.complex_val.real)
13739 || !mpfr_zero_p(this->u_.complex_val.imag))
13742 error_at(location, "complex constant truncated to integer");
13746 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
13754 if (type->is_abstract())
13758 int bits = mpz_sizeinbase(val, 2);
13759 if (type->is_unsigned())
13761 // For an unsigned type we can only accept a nonnegative
13762 // number, and we must be able to represents at least BITS.
13763 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
13767 // For a signed type we need an extra bit to indicate the
13768 // sign. We have to handle the most negative integer
13770 ret = (bits + 1 <= type->bits()
13771 || (bits <= type->bits()
13772 && mpz_sgn(val) < 0
13773 && (mpz_scan1(val, 0)
13774 == static_cast<unsigned long>(type->bits() - 1))
13775 && mpz_scan0(val, type->bits()) == ULONG_MAX));
13779 if (!ret && issue_error)
13780 error_at(location, "integer constant overflow");
13785 // Check whether the constant can be expressed in a floating point
13789 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
13790 Location location) const
13793 switch (this->classification_)
13797 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
13801 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
13805 if (!mpfr_zero_p(this->u_.complex_val.imag))
13808 error_at(location, "complex constant truncated to float");
13811 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
13819 if (type->is_abstract())
13821 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
13823 // A NaN or Infinity always fits in the range of the type.
13828 mp_exp_t exp = mpfr_get_exp(val);
13830 switch (type->bits())
13842 ret = exp <= max_exp;
13847 if (!ret && issue_error)
13848 error_at(location, "floating point constant overflow");
13853 // Check whether the constant can be expressed in a complex type.
13856 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
13857 Location location) const
13859 if (type->is_abstract())
13863 switch (type->bits())
13876 switch (this->classification_)
13880 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
13884 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
13888 if (!mpfr_nan_p(this->u_.complex_val.imag)
13889 && !mpfr_inf_p(this->u_.complex_val.imag)
13890 && !mpfr_zero_p(this->u_.complex_val.imag))
13892 if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
13895 error_at(location, "complex imaginary part overflow");
13899 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
13907 if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
13910 ret = mpfr_get_exp(real) <= max_exp;
13914 if (!ret && issue_error)
13915 error_at(location, "complex real part overflow");
13920 // Return an Expression for this value.
13923 Numeric_constant::expression(Location loc) const
13925 switch (this->classification_)
13928 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
13930 return Expression::make_character(&this->u_.int_val, this->type_, loc);
13932 return Expression::make_float(&this->u_.float_val, this->type_, loc);
13934 return Expression::make_complex(&this->u_.complex_val.real,
13935 &this->u_.complex_val.imag,