1 // expressions.cc -- Go frontend expression handling.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
13 #ifndef ENABLE_BUILD_WITH_CXX
22 #include "tree-iterator.h"
27 #ifndef ENABLE_BUILD_WITH_CXX
36 #include "statements.h"
40 #include "expressions.h"
45 Expression::Expression(Expression_classification classification,
47 : classification_(classification), location_(location)
51 Expression::~Expression()
55 // Traverse the expressions.
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
60 Expression* expr = *pexpr;
61 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
63 int t = traverse->expression(pexpr);
64 if (t == TRAVERSE_EXIT)
66 else if (t == TRAVERSE_SKIP_COMPONENTS)
67 return TRAVERSE_CONTINUE;
69 return expr->do_traverse(traverse);
72 // Traverse subexpressions of this expression.
75 Expression::traverse_subexpressions(Traverse* traverse)
77 return this->do_traverse(traverse);
80 // Default implementation for do_traverse for child classes.
83 Expression::do_traverse(Traverse*)
85 return TRAVERSE_CONTINUE;
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded. By default, we give an error.
90 // Expressions with side effects override.
93 Expression::do_discarding_value()
95 this->unused_value_error();
98 // This virtual function is called to export expressions. This will
99 // only be used by expressions which may be constant.
102 Expression::do_export(Export*) const
107 // Give an error saying that the value of the expression is not used.
110 Expression::unused_value_error()
112 error_at(this->location(), "value computed is not used");
115 // Note that this expression is an error. This is called by children
116 // when they discover an error.
119 Expression::set_is_error()
121 this->classification_ = EXPRESSION_ERROR;
124 // For children to call to report an error conveniently.
127 Expression::report_error(const char* msg)
129 error_at(this->location_, "%s", msg);
130 this->set_is_error();
133 // Set types of variables and constants. This is implemented by the
137 Expression::determine_type(const Type_context* context)
139 this->do_determine_type(context);
142 // Set types when there is no context.
145 Expression::determine_type_no_context()
147 Type_context context;
148 this->do_determine_type(&context);
151 // Return a tree handling any conversions which must be done during
155 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
156 Type* rhs_type, tree rhs_tree,
159 if (lhs_type->is_error() || rhs_type->is_error())
160 return error_mark_node;
162 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
163 return error_mark_node;
165 Gogo* gogo = context->gogo();
167 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
168 if (lhs_type_tree == error_mark_node)
169 return error_mark_node;
171 if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
173 if (rhs_type->interface_type() == NULL)
174 return Expression::convert_type_to_interface(context, lhs_type,
178 return Expression::convert_interface_to_interface(context, lhs_type,
182 else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
183 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
185 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
187 // Assigning nil to an open array.
188 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
190 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
192 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
193 tree field = TYPE_FIELDS(lhs_type_tree);
194 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
197 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
199 elt = VEC_quick_push(constructor_elt, init, NULL);
200 field = DECL_CHAIN(field);
201 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
204 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
206 elt = VEC_quick_push(constructor_elt, init, NULL);
207 field = DECL_CHAIN(field);
208 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
211 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
213 tree val = build_constructor(lhs_type_tree, init);
214 TREE_CONSTANT(val) = 1;
218 else if (rhs_type->is_nil_type())
220 // The left hand side should be a pointer type at the tree
222 go_assert(POINTER_TYPE_P(lhs_type_tree));
223 return fold_convert(lhs_type_tree, null_pointer_node);
225 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
227 // No conversion is needed.
230 else if (POINTER_TYPE_P(lhs_type_tree)
231 || INTEGRAL_TYPE_P(lhs_type_tree)
232 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
233 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
234 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
235 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
236 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
237 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
238 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
240 // Avoid confusion from zero sized variables which may be
241 // represented as non-zero-sized.
242 if (int_size_in_bytes(lhs_type_tree) == 0
243 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
246 // This conversion must be permitted by Go, or we wouldn't have
248 go_assert(int_size_in_bytes(lhs_type_tree)
249 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
250 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
251 lhs_type_tree, rhs_tree);
255 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
260 // Return a tree for a conversion from a non-interface type to an
264 Expression::convert_type_to_interface(Translate_context* context,
265 Type* lhs_type, Type* rhs_type,
266 tree rhs_tree, Location location)
268 Gogo* gogo = context->gogo();
269 Interface_type* lhs_interface_type = lhs_type->interface_type();
270 bool lhs_is_empty = lhs_interface_type->is_empty();
272 // Since RHS_TYPE is a static type, we can create the interface
273 // method table at compile time.
275 // When setting an interface to nil, we just set both fields to
277 if (rhs_type->is_nil_type())
279 Btype* lhs_btype = lhs_type->get_backend(gogo);
280 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
283 // This should have been checked already.
284 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
286 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
287 if (lhs_type_tree == error_mark_node)
288 return error_mark_node;
290 // An interface is a tuple. If LHS_TYPE is an empty interface type,
291 // then the first field is the type descriptor for RHS_TYPE.
292 // Otherwise it is the interface method table for RHS_TYPE.
293 tree first_field_value;
295 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
298 // Build the interface method table for this interface and this
299 // object type: a list of function pointers for each interface
301 Named_type* rhs_named_type = rhs_type->named_type();
302 bool is_pointer = false;
303 if (rhs_named_type == NULL)
305 rhs_named_type = rhs_type->deref()->named_type();
309 if (rhs_named_type == NULL)
310 method_table = null_pointer_node;
313 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
315 first_field_value = fold_convert_loc(location.gcc_location(),
316 const_ptr_type_node, method_table);
318 if (first_field_value == error_mark_node)
319 return error_mark_node;
321 // Start building a constructor for the value we will return.
323 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
325 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
326 tree field = TYPE_FIELDS(lhs_type_tree);
327 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
328 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
330 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
333 elt = VEC_quick_push(constructor_elt, init, NULL);
334 field = DECL_CHAIN(field);
335 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
338 if (rhs_type->points_to() != NULL)
340 // We are assigning a pointer to the interface; the interface
341 // holds the pointer itself.
342 elt->value = rhs_tree;
343 return build_constructor(lhs_type_tree, init);
346 // We are assigning a non-pointer value to the interface; the
347 // interface gets a copy of the value in the heap.
349 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
351 tree space = gogo->allocate_memory(rhs_type, object_size, location);
352 space = fold_convert_loc(location.gcc_location(),
353 build_pointer_type(TREE_TYPE(rhs_tree)), space);
354 space = save_expr(space);
356 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
357 TREE_THIS_NOTRAP(ref) = 1;
358 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
359 void_type_node, ref, rhs_tree);
361 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
364 return build2(COMPOUND_EXPR, lhs_type_tree, set,
365 build_constructor(lhs_type_tree, init));
368 // Return a tree for the type descriptor of RHS_TREE, which has
369 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
373 Expression::get_interface_type_descriptor(Translate_context*,
374 Type* rhs_type, tree rhs_tree,
377 tree rhs_type_tree = TREE_TYPE(rhs_tree);
378 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
379 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
380 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
382 if (rhs_type->interface_type()->is_empty())
384 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
385 "__type_descriptor") == 0);
389 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
391 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
393 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
394 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
395 tree f = TYPE_FIELDS(TREE_TYPE(v1));
396 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
398 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
400 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
401 v, fold_convert_loc(location.gcc_location(),
404 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
406 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
410 // Return a tree for the conversion of an interface type to an
414 Expression::convert_interface_to_interface(Translate_context* context,
415 Type *lhs_type, Type *rhs_type,
416 tree rhs_tree, bool for_type_guard,
419 Gogo* gogo = context->gogo();
420 Interface_type* lhs_interface_type = lhs_type->interface_type();
421 bool lhs_is_empty = lhs_interface_type->is_empty();
423 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
424 if (lhs_type_tree == error_mark_node)
425 return error_mark_node;
427 // In the general case this requires runtime examination of the type
428 // method table to match it up with the interface methods.
430 // FIXME: If all of the methods in the right hand side interface
431 // also appear in the left hand side interface, then we don't need
432 // to do a runtime check, although we still need to build a new
435 // Get the type descriptor for the right hand side. This will be
436 // NULL for a nil interface.
438 if (!DECL_P(rhs_tree))
439 rhs_tree = save_expr(rhs_tree);
441 tree rhs_type_descriptor =
442 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
445 // The result is going to be a two element constructor.
447 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
449 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
450 tree field = TYPE_FIELDS(lhs_type_tree);
455 // A type assertion fails when converting a nil interface.
456 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
458 static tree assert_interface_decl;
459 tree call = Gogo::call_builtin(&assert_interface_decl,
461 "__go_assert_interface",
464 TREE_TYPE(lhs_type_descriptor),
466 TREE_TYPE(rhs_type_descriptor),
467 rhs_type_descriptor);
468 if (call == error_mark_node)
469 return error_mark_node;
470 // This will panic if the interface conversion fails.
471 TREE_NOTHROW(assert_interface_decl) = 0;
472 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
475 else if (lhs_is_empty)
477 // A convertion to an empty interface always succeeds, and the
478 // first field is just the type descriptor of the object.
479 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
480 "__type_descriptor") == 0);
481 elt->value = fold_convert_loc(location.gcc_location(),
482 TREE_TYPE(field), rhs_type_descriptor);
486 // A conversion to a non-empty interface may fail, but unlike a
487 // type assertion converting nil will always succeed.
488 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
490 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
492 static tree convert_interface_decl;
493 tree call = Gogo::call_builtin(&convert_interface_decl,
495 "__go_convert_interface",
498 TREE_TYPE(lhs_type_descriptor),
500 TREE_TYPE(rhs_type_descriptor),
501 rhs_type_descriptor);
502 if (call == error_mark_node)
503 return error_mark_node;
504 // This will panic if the interface conversion fails.
505 TREE_NOTHROW(convert_interface_decl) = 0;
506 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
510 // The second field is simply the object pointer.
512 elt = VEC_quick_push(constructor_elt, init, NULL);
513 field = DECL_CHAIN(field);
514 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
517 tree rhs_type_tree = TREE_TYPE(rhs_tree);
518 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
519 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
520 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
521 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
524 return build_constructor(lhs_type_tree, init);
527 // Return a tree for the conversion of an interface type to a
528 // non-interface type.
531 Expression::convert_interface_to_type(Translate_context* context,
532 Type *lhs_type, Type* rhs_type,
533 tree rhs_tree, Location location)
535 Gogo* gogo = context->gogo();
536 tree rhs_type_tree = TREE_TYPE(rhs_tree);
538 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
539 if (lhs_type_tree == error_mark_node)
540 return error_mark_node;
542 // Call a function to check that the type is valid. The function
543 // will panic with an appropriate runtime type error if the type is
546 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
548 if (!DECL_P(rhs_tree))
549 rhs_tree = save_expr(rhs_tree);
551 tree rhs_type_descriptor =
552 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
555 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
558 static tree check_interface_type_decl;
559 tree call = Gogo::call_builtin(&check_interface_type_decl,
561 "__go_check_interface_type",
564 TREE_TYPE(lhs_type_descriptor),
566 TREE_TYPE(rhs_type_descriptor),
568 TREE_TYPE(rhs_inter_descriptor),
569 rhs_inter_descriptor);
570 if (call == error_mark_node)
571 return error_mark_node;
572 // This call will panic if the conversion is invalid.
573 TREE_NOTHROW(check_interface_type_decl) = 0;
575 // If the call succeeds, pull out the value.
576 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
577 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
578 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
579 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
582 // If the value is a pointer, then it is the value we want.
583 // Otherwise it points to the value.
584 if (lhs_type->points_to() == NULL)
586 val = fold_convert_loc(location.gcc_location(),
587 build_pointer_type(lhs_type_tree), val);
588 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
591 return build2(COMPOUND_EXPR, lhs_type_tree, call,
592 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
595 // Convert an expression to a tree. This is implemented by the child
596 // class. Not that it is not in general safe to call this multiple
597 // times for a single expression, but that we don't catch such errors.
600 Expression::get_tree(Translate_context* context)
602 // The child may have marked this expression as having an error.
603 if (this->classification_ == EXPRESSION_ERROR)
604 return error_mark_node;
606 return this->do_get_tree(context);
609 // Return a tree for VAL in TYPE.
612 Expression::integer_constant_tree(mpz_t val, tree type)
614 if (type == error_mark_node)
615 return error_mark_node;
616 else if (TREE_CODE(type) == INTEGER_TYPE)
617 return double_int_to_tree(type,
618 mpz_get_double_int(type, val, true));
619 else if (TREE_CODE(type) == REAL_TYPE)
622 mpfr_init_set_z(fval, val, GMP_RNDN);
623 tree ret = Expression::float_constant_tree(fval, type);
627 else if (TREE_CODE(type) == COMPLEX_TYPE)
630 mpfr_init_set_z(fval, val, GMP_RNDN);
631 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
633 tree imag = build_real_from_int_cst(TREE_TYPE(type),
635 return build_complex(type, real, imag);
641 // Return a tree for VAL in TYPE.
644 Expression::float_constant_tree(mpfr_t val, tree type)
646 if (type == error_mark_node)
647 return error_mark_node;
648 else if (TREE_CODE(type) == INTEGER_TYPE)
652 mpfr_get_z(ival, val, GMP_RNDN);
653 tree ret = Expression::integer_constant_tree(ival, type);
657 else if (TREE_CODE(type) == REAL_TYPE)
660 real_from_mpfr(&r1, val, type, GMP_RNDN);
662 real_convert(&r2, TYPE_MODE(type), &r1);
663 return build_real(type, r2);
665 else if (TREE_CODE(type) == COMPLEX_TYPE)
668 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
670 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
671 tree imag = build_real_from_int_cst(TREE_TYPE(type),
673 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
679 // Return a tree for REAL/IMAG in TYPE.
682 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
684 if (type == error_mark_node)
685 return error_mark_node;
686 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
687 return Expression::float_constant_tree(real, type);
688 else if (TREE_CODE(type) == COMPLEX_TYPE)
691 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
693 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
696 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
698 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
700 return build_complex(type, build_real(TREE_TYPE(type), r2),
701 build_real(TREE_TYPE(type), r4));
707 // Return a tree which evaluates to true if VAL, of arbitrary integer
708 // type, is negative or is more than the maximum value of BOUND_TYPE.
709 // If SOFAR is not NULL, it is or'red into the result. The return
710 // value may be NULL if SOFAR is NULL.
713 Expression::check_bounds(tree val, tree bound_type, tree sofar,
716 tree val_type = TREE_TYPE(val);
717 tree ret = NULL_TREE;
719 if (!TYPE_UNSIGNED(val_type))
721 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
722 build_int_cst(val_type, 0));
723 if (ret == boolean_false_node)
727 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
728 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
729 go_assert(val_type_size != -1 && bound_type_size != -1);
730 if (val_type_size > bound_type_size
731 || (val_type_size == bound_type_size
732 && TYPE_UNSIGNED(val_type)
733 && !TYPE_UNSIGNED(bound_type)))
735 tree max = TYPE_MAX_VALUE(bound_type);
736 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
737 val, fold_convert_loc(loc.gcc_location(),
739 if (big == boolean_false_node)
741 else if (ret == NULL_TREE)
744 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
745 boolean_type_node, ret, big);
748 if (ret == NULL_TREE)
750 else if (sofar == NULL_TREE)
753 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
758 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
760 this->do_dump_expression(ast_dump_context);
763 // Error expressions. This are used to avoid cascading errors.
765 class Error_expression : public Expression
768 Error_expression(Location location)
769 : Expression(EXPRESSION_ERROR, location)
774 do_is_constant() const
778 do_numeric_constant_value(Numeric_constant* nc) const
780 nc->set_unsigned_long(NULL, 0);
785 do_discarding_value()
790 { return Type::make_error_type(); }
793 do_determine_type(const Type_context*)
801 do_is_addressable() const
805 do_get_tree(Translate_context*)
806 { return error_mark_node; }
809 do_dump_expression(Ast_dump_context*) const;
812 // Dump the ast representation for an error expression to a dump context.
815 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
817 ast_dump_context->ostream() << "_Error_" ;
821 Expression::make_error(Location location)
823 return new Error_expression(location);
826 // An expression which is really a type. This is used during parsing.
827 // It is an error if these survive after lowering.
830 Type_expression : public Expression
833 Type_expression(Type* type, Location location)
834 : Expression(EXPRESSION_TYPE, location),
840 do_traverse(Traverse* traverse)
841 { return Type::traverse(this->type_, traverse); }
845 { return this->type_; }
848 do_determine_type(const Type_context*)
852 do_check_types(Gogo*)
853 { this->report_error(_("invalid use of type")); }
860 do_get_tree(Translate_context*)
861 { go_unreachable(); }
863 void do_dump_expression(Ast_dump_context*) const;
866 // The type which we are representing as an expression.
871 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
873 ast_dump_context->dump_type(this->type_);
877 Expression::make_type(Type* type, Location location)
879 return new Type_expression(type, location);
882 // Class Parser_expression.
885 Parser_expression::do_type()
887 // We should never really ask for the type of a Parser_expression.
888 // However, it can happen, at least when we have an invalid const
889 // whose initializer refers to the const itself. In that case we
890 // may ask for the type when lowering the const itself.
891 go_assert(saw_errors());
892 return Type::make_error_type();
895 // Class Var_expression.
897 // Lower a variable expression. Here we just make sure that the
898 // initialization expression of the variable has been lowered. This
899 // ensures that we will be able to determine the type of the variable
903 Var_expression::do_lower(Gogo* gogo, Named_object* function,
904 Statement_inserter* inserter, int)
906 if (this->variable_->is_variable())
908 Variable* var = this->variable_->var_value();
909 // This is either a local variable or a global variable. A
910 // reference to a variable which is local to an enclosing
911 // function will be a reference to a field in a closure.
912 if (var->is_global())
917 var->lower_init_expression(gogo, function, inserter);
922 // Return the type of a reference to a variable.
925 Var_expression::do_type()
927 if (this->variable_->is_variable())
928 return this->variable_->var_value()->type();
929 else if (this->variable_->is_result_variable())
930 return this->variable_->result_var_value()->type();
935 // Determine the type of a reference to a variable.
938 Var_expression::do_determine_type(const Type_context*)
940 if (this->variable_->is_variable())
941 this->variable_->var_value()->determine_type();
944 // Something takes the address of this variable. This means that we
945 // may want to move the variable onto the heap.
948 Var_expression::do_address_taken(bool escapes)
952 if (this->variable_->is_variable())
953 this->variable_->var_value()->set_non_escaping_address_taken();
954 else if (this->variable_->is_result_variable())
955 this->variable_->result_var_value()->set_non_escaping_address_taken();
961 if (this->variable_->is_variable())
962 this->variable_->var_value()->set_address_taken();
963 else if (this->variable_->is_result_variable())
964 this->variable_->result_var_value()->set_address_taken();
970 // Get the tree for a reference to a variable.
973 Var_expression::do_get_tree(Translate_context* context)
975 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
976 context->function());
977 tree ret = var_to_tree(bvar);
978 if (ret == error_mark_node)
979 return error_mark_node;
981 if (this->variable_->is_variable())
982 is_in_heap = this->variable_->var_value()->is_in_heap();
983 else if (this->variable_->is_result_variable())
984 is_in_heap = this->variable_->result_var_value()->is_in_heap();
989 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
990 TREE_THIS_NOTRAP(ret) = 1;
995 // Ast dump for variable expression.
998 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1000 ast_dump_context->ostream() << this->variable_->name() ;
1003 // Make a reference to a variable in an expression.
1006 Expression::make_var_reference(Named_object* var, Location location)
1009 return Expression::make_sink(location);
1011 // FIXME: Creating a new object for each reference to a variable is
1013 return new Var_expression(var, location);
1016 // Class Temporary_reference_expression.
1021 Temporary_reference_expression::do_type()
1023 return this->statement_->type();
1026 // Called if something takes the address of this temporary variable.
1027 // We never have to move temporary variables to the heap, but we do
1028 // need to know that they must live in the stack rather than in a
1032 Temporary_reference_expression::do_address_taken(bool)
1034 this->statement_->set_is_address_taken();
1037 // Get a tree referring to the variable.
1040 Temporary_reference_expression::do_get_tree(Translate_context* context)
1042 Bvariable* bvar = this->statement_->get_backend_variable(context);
1044 // The gcc backend can't represent the same set of recursive types
1045 // that the Go frontend can. In some cases this means that a
1046 // temporary variable won't have the right backend type. Correct
1047 // that here by adding a type cast. We need to use base() to push
1048 // the circularity down one level.
1049 tree ret = var_to_tree(bvar);
1050 if (!this->is_lvalue_
1051 && POINTER_TYPE_P(TREE_TYPE(ret))
1052 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1054 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1055 tree type_tree = type_to_tree(type_btype);
1056 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1061 // Ast dump for temporary reference.
1064 Temporary_reference_expression::do_dump_expression(
1065 Ast_dump_context* ast_dump_context) const
1067 ast_dump_context->dump_temp_variable_name(this->statement_);
1070 // Make a reference to a temporary variable.
1072 Temporary_reference_expression*
1073 Expression::make_temporary_reference(Temporary_statement* statement,
1076 return new Temporary_reference_expression(statement, location);
1079 // Class Set_and_use_temporary_expression.
1084 Set_and_use_temporary_expression::do_type()
1086 return this->statement_->type();
1089 // Take the address.
1092 Set_and_use_temporary_expression::do_address_taken(bool)
1094 this->statement_->set_is_address_taken();
1097 // Return the backend representation.
1100 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1102 Bvariable* bvar = this->statement_->get_backend_variable(context);
1103 tree var_tree = var_to_tree(bvar);
1104 tree expr_tree = this->expr_->get_tree(context);
1105 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1106 return error_mark_node;
1107 Location loc = this->location();
1108 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1109 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1110 var_tree, expr_tree),
1117 Set_and_use_temporary_expression::do_dump_expression(
1118 Ast_dump_context* ast_dump_context) const
1120 ast_dump_context->ostream() << '(';
1121 ast_dump_context->dump_temp_variable_name(this->statement_);
1122 ast_dump_context->ostream() << " = ";
1123 this->expr_->dump_expression(ast_dump_context);
1124 ast_dump_context->ostream() << ')';
1127 // Make a set-and-use temporary.
1129 Set_and_use_temporary_expression*
1130 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1131 Expression* expr, Location location)
1133 return new Set_and_use_temporary_expression(statement, expr, location);
1136 // A sink expression--a use of the blank identifier _.
1138 class Sink_expression : public Expression
1141 Sink_expression(Location location)
1142 : Expression(EXPRESSION_SINK, location),
1143 type_(NULL), var_(NULL_TREE)
1148 do_discarding_value()
1155 do_determine_type(const Type_context*);
1159 { return new Sink_expression(this->location()); }
1162 do_get_tree(Translate_context*);
1165 do_dump_expression(Ast_dump_context*) const;
1168 // The type of this sink variable.
1170 // The temporary variable we generate.
1174 // Return the type of a sink expression.
1177 Sink_expression::do_type()
1179 if (this->type_ == NULL)
1180 return Type::make_sink_type();
1184 // Determine the type of a sink expression.
1187 Sink_expression::do_determine_type(const Type_context* context)
1189 if (context->type != NULL)
1190 this->type_ = context->type;
1193 // Return a temporary variable for a sink expression. This will
1194 // presumably be a write-only variable which the middle-end will drop.
1197 Sink_expression::do_get_tree(Translate_context* context)
1199 if (this->var_ == NULL_TREE)
1201 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1202 Btype* bt = this->type_->get_backend(context->gogo());
1203 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1208 // Ast dump for sink expression.
1211 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1213 ast_dump_context->ostream() << "_" ;
1216 // Make a sink expression.
1219 Expression::make_sink(Location location)
1221 return new Sink_expression(location);
1224 // Class Func_expression.
1226 // FIXME: Can a function expression appear in a constant expression?
1227 // The value is unchanging. Initializing a constant to the address of
1228 // a function seems like it could work, though there might be little
1234 Func_expression::do_traverse(Traverse* traverse)
1236 return (this->closure_ == NULL
1238 : Expression::traverse(&this->closure_, traverse));
1241 // Return the type of a function expression.
1244 Func_expression::do_type()
1246 if (this->function_->is_function())
1247 return this->function_->func_value()->type();
1248 else if (this->function_->is_function_declaration())
1249 return this->function_->func_declaration_value()->type();
1254 // Get the tree for a function expression without evaluating the
1258 Func_expression::get_tree_without_closure(Gogo* gogo)
1260 Function_type* fntype;
1261 if (this->function_->is_function())
1262 fntype = this->function_->func_value()->type();
1263 else if (this->function_->is_function_declaration())
1264 fntype = this->function_->func_declaration_value()->type();
1268 // Builtin functions are handled specially by Call_expression. We
1269 // can't take their address.
1270 if (fntype->is_builtin())
1272 error_at(this->location(),
1273 "invalid use of special builtin function %qs; must be called",
1274 this->function_->name().c_str());
1275 return error_mark_node;
1278 Named_object* no = this->function_;
1280 tree id = no->get_id(gogo);
1281 if (id == error_mark_node)
1282 return error_mark_node;
1285 if (no->is_function())
1286 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1287 else if (no->is_function_declaration())
1288 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1292 if (fndecl == error_mark_node)
1293 return error_mark_node;
1295 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1298 // Get the tree for a function expression. This is used when we take
1299 // the address of a function rather than simply calling it. If the
1300 // function has a closure, we must use a trampoline.
1303 Func_expression::do_get_tree(Translate_context* context)
1305 Gogo* gogo = context->gogo();
1307 tree fnaddr = this->get_tree_without_closure(gogo);
1308 if (fnaddr == error_mark_node)
1309 return error_mark_node;
1311 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1312 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1313 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1315 // For a normal non-nested function call, that is all we have to do.
1316 if (!this->function_->is_function()
1317 || this->function_->func_value()->enclosing() == NULL)
1319 go_assert(this->closure_ == NULL);
1323 // For a nested function call, we have to always allocate a
1324 // trampoline. If we don't always allocate, then closures will not
1325 // be reliably distinct.
1326 Expression* closure = this->closure_;
1328 if (closure == NULL)
1329 closure_tree = null_pointer_node;
1332 // Get the value of the closure. This will be a pointer to
1333 // space allocated on the heap.
1334 closure_tree = closure->get_tree(context);
1335 if (closure_tree == error_mark_node)
1336 return error_mark_node;
1337 go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1340 // Now we need to build some code on the heap. This code will load
1341 // the static chain pointer with the closure and then jump to the
1342 // body of the function. The normal gcc approach is to build the
1343 // code on the stack. Unfortunately we can not do that, as Go
1344 // permits us to return the function pointer.
1346 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1349 // Ast dump for function.
1352 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1354 ast_dump_context->ostream() << this->function_->name();
1355 if (this->closure_ != NULL)
1357 ast_dump_context->ostream() << " {closure = ";
1358 this->closure_->dump_expression(ast_dump_context);
1359 ast_dump_context->ostream() << "}";
1363 // Make a reference to a function in an expression.
1366 Expression::make_func_reference(Named_object* function, Expression* closure,
1369 return new Func_expression(function, closure, location);
1372 // Class Unknown_expression.
1374 // Return the name of an unknown expression.
1377 Unknown_expression::name() const
1379 return this->named_object_->name();
1382 // Lower a reference to an unknown name.
1385 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1387 Location location = this->location();
1388 Named_object* no = this->named_object_;
1390 if (!no->is_unknown())
1394 real = no->unknown_value()->real_named_object();
1397 if (this->is_composite_literal_key_)
1399 if (!this->no_error_message_)
1400 error_at(location, "reference to undefined name %qs",
1401 this->named_object_->message_name().c_str());
1402 return Expression::make_error(location);
1405 switch (real->classification())
1407 case Named_object::NAMED_OBJECT_CONST:
1408 return Expression::make_const_reference(real, location);
1409 case Named_object::NAMED_OBJECT_TYPE:
1410 return Expression::make_type(real->type_value(), location);
1411 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1412 if (this->is_composite_literal_key_)
1414 if (!this->no_error_message_)
1415 error_at(location, "reference to undefined type %qs",
1416 real->message_name().c_str());
1417 return Expression::make_error(location);
1418 case Named_object::NAMED_OBJECT_VAR:
1419 real->var_value()->set_is_used();
1420 return Expression::make_var_reference(real, location);
1421 case Named_object::NAMED_OBJECT_FUNC:
1422 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1423 return Expression::make_func_reference(real, NULL, location);
1424 case Named_object::NAMED_OBJECT_PACKAGE:
1425 if (this->is_composite_literal_key_)
1427 if (!this->no_error_message_)
1428 error_at(location, "unexpected reference to package");
1429 return Expression::make_error(location);
1435 // Dump the ast representation for an unknown expression to a dump context.
1438 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1440 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1444 // Make a reference to an unknown name.
1447 Expression::make_unknown_reference(Named_object* no, Location location)
1449 return new Unknown_expression(no, location);
1452 // A boolean expression.
1454 class Boolean_expression : public Expression
1457 Boolean_expression(bool val, Location location)
1458 : Expression(EXPRESSION_BOOLEAN, location),
1459 val_(val), type_(NULL)
1467 do_is_constant() const
1474 do_determine_type(const Type_context*);
1481 do_get_tree(Translate_context*)
1482 { return this->val_ ? boolean_true_node : boolean_false_node; }
1485 do_export(Export* exp) const
1486 { exp->write_c_string(this->val_ ? "true" : "false"); }
1489 do_dump_expression(Ast_dump_context* ast_dump_context) const
1490 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1495 // The type as determined by context.
1502 Boolean_expression::do_type()
1504 if (this->type_ == NULL)
1505 this->type_ = Type::make_boolean_type();
1509 // Set the type from the context.
1512 Boolean_expression::do_determine_type(const Type_context* context)
1514 if (this->type_ != NULL && !this->type_->is_abstract())
1516 else if (context->type != NULL && context->type->is_boolean_type())
1517 this->type_ = context->type;
1518 else if (!context->may_be_abstract)
1519 this->type_ = Type::lookup_bool_type();
1522 // Import a boolean constant.
1525 Boolean_expression::do_import(Import* imp)
1527 if (imp->peek_char() == 't')
1529 imp->require_c_string("true");
1530 return Expression::make_boolean(true, imp->location());
1534 imp->require_c_string("false");
1535 return Expression::make_boolean(false, imp->location());
1539 // Make a boolean expression.
1542 Expression::make_boolean(bool val, Location location)
1544 return new Boolean_expression(val, location);
1547 // Class String_expression.
1552 String_expression::do_type()
1554 if (this->type_ == NULL)
1555 this->type_ = Type::make_string_type();
1559 // Set the type from the context.
1562 String_expression::do_determine_type(const Type_context* context)
1564 if (this->type_ != NULL && !this->type_->is_abstract())
1566 else if (context->type != NULL && context->type->is_string_type())
1567 this->type_ = context->type;
1568 else if (!context->may_be_abstract)
1569 this->type_ = Type::lookup_string_type();
1572 // Build a string constant.
1575 String_expression::do_get_tree(Translate_context* context)
1577 return context->gogo()->go_string_constant_tree(this->val_);
1580 // Write string literal to string dump.
1583 String_expression::export_string(String_dump* exp,
1584 const String_expression* str)
1587 s.reserve(str->val_.length() * 4 + 2);
1589 for (std::string::const_iterator p = str->val_.begin();
1590 p != str->val_.end();
1593 if (*p == '\\' || *p == '"')
1598 else if (*p >= 0x20 && *p < 0x7f)
1600 else if (*p == '\n')
1602 else if (*p == '\t')
1607 unsigned char c = *p;
1608 unsigned int dig = c >> 4;
1609 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1611 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1615 exp->write_string(s);
1618 // Export a string expression.
1621 String_expression::do_export(Export* exp) const
1623 String_expression::export_string(exp, this);
1626 // Import a string expression.
1629 String_expression::do_import(Import* imp)
1631 imp->require_c_string("\"");
1635 int c = imp->get_char();
1636 if (c == '"' || c == -1)
1639 val += static_cast<char>(c);
1642 c = imp->get_char();
1643 if (c == '\\' || c == '"')
1644 val += static_cast<char>(c);
1651 c = imp->get_char();
1652 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653 c = imp->get_char();
1654 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1655 char v = (vh << 4) | vl;
1660 error_at(imp->location(), "bad string constant");
1661 return Expression::make_error(imp->location());
1665 return Expression::make_string(val, imp->location());
1668 // Ast dump for string expression.
1671 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1673 String_expression::export_string(ast_dump_context, this);
1676 // Make a string expression.
1679 Expression::make_string(const std::string& val, Location location)
1681 return new String_expression(val, location);
1684 // Make an integer expression.
1686 class Integer_expression : public Expression
1689 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1691 : Expression(EXPRESSION_INTEGER, location),
1692 type_(type), is_character_constant_(is_character_constant)
1693 { mpz_init_set(this->val_, *val); }
1698 // Write VAL to string dump.
1700 export_integer(String_dump* exp, const mpz_t val);
1702 // Write VAL to dump context.
1704 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1708 do_is_constant() const
1712 do_numeric_constant_value(Numeric_constant* nc) const;
1718 do_determine_type(const Type_context* context);
1721 do_check_types(Gogo*);
1724 do_get_tree(Translate_context*);
1729 if (this->is_character_constant_)
1730 return Expression::make_character(&this->val_, this->type_,
1733 return Expression::make_integer(&this->val_, this->type_,
1738 do_export(Export*) const;
1741 do_dump_expression(Ast_dump_context*) const;
1744 // The integer value.
1748 // Whether this is a character constant.
1749 bool is_character_constant_;
1752 // Return a numeric constant for this expression. We have to mark
1753 // this as a character when appropriate.
1756 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1758 if (this->is_character_constant_)
1759 nc->set_rune(this->type_, this->val_);
1761 nc->set_int(this->type_, this->val_);
1765 // Return the current type. If we haven't set the type yet, we return
1766 // an abstract integer type.
1769 Integer_expression::do_type()
1771 if (this->type_ == NULL)
1773 if (this->is_character_constant_)
1774 this->type_ = Type::make_abstract_character_type();
1776 this->type_ = Type::make_abstract_integer_type();
1781 // Set the type of the integer value. Here we may switch from an
1782 // abstract type to a real type.
1785 Integer_expression::do_determine_type(const Type_context* context)
1787 if (this->type_ != NULL && !this->type_->is_abstract())
1789 else if (context->type != NULL && context->type->is_numeric_type())
1790 this->type_ = context->type;
1791 else if (!context->may_be_abstract)
1793 if (this->is_character_constant_)
1794 this->type_ = Type::lookup_integer_type("int32");
1796 this->type_ = Type::lookup_integer_type("int");
1800 // Check the type of an integer constant.
1803 Integer_expression::do_check_types(Gogo*)
1805 Type* type = this->type_;
1808 Numeric_constant nc;
1809 if (this->is_character_constant_)
1810 nc.set_rune(NULL, this->val_);
1812 nc.set_int(NULL, this->val_);
1813 if (!nc.set_type(type, true, this->location()))
1814 this->set_is_error();
1817 // Get a tree for an integer constant.
1820 Integer_expression::do_get_tree(Translate_context* context)
1822 Gogo* gogo = context->gogo();
1824 if (this->type_ != NULL && !this->type_->is_abstract())
1825 type = type_to_tree(this->type_->get_backend(gogo));
1826 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1828 // We are converting to an abstract floating point type.
1829 Type* ftype = Type::lookup_float_type("float64");
1830 type = type_to_tree(ftype->get_backend(gogo));
1832 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1834 // We are converting to an abstract complex type.
1835 Type* ctype = Type::lookup_complex_type("complex128");
1836 type = type_to_tree(ctype->get_backend(gogo));
1840 // If we still have an abstract type here, then this is being
1841 // used in a constant expression which didn't get reduced for
1842 // some reason. Use a type which will fit the value. We use <,
1843 // not <=, because we need an extra bit for the sign bit.
1844 int bits = mpz_sizeinbase(this->val_, 2);
1845 if (bits < INT_TYPE_SIZE)
1847 Type* t = Type::lookup_integer_type("int");
1848 type = type_to_tree(t->get_backend(gogo));
1852 Type* t = Type::lookup_integer_type("int64");
1853 type = type_to_tree(t->get_backend(gogo));
1856 type = long_long_integer_type_node;
1858 return Expression::integer_constant_tree(this->val_, type);
1861 // Write VAL to export data.
1864 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1866 char* s = mpz_get_str(NULL, 10, val);
1867 exp->write_c_string(s);
1871 // Export an integer in a constant expression.
1874 Integer_expression::do_export(Export* exp) const
1876 Integer_expression::export_integer(exp, this->val_);
1877 if (this->is_character_constant_)
1878 exp->write_c_string("'");
1879 // A trailing space lets us reliably identify the end of the number.
1880 exp->write_c_string(" ");
1883 // Import an integer, floating point, or complex value. This handles
1884 // all these types because they all start with digits.
1887 Integer_expression::do_import(Import* imp)
1889 std::string num = imp->read_identifier();
1890 imp->require_c_string(" ");
1891 if (!num.empty() && num[num.length() - 1] == 'i')
1894 size_t plus_pos = num.find('+', 1);
1895 size_t minus_pos = num.find('-', 1);
1897 if (plus_pos == std::string::npos)
1899 else if (minus_pos == std::string::npos)
1903 error_at(imp->location(), "bad number in import data: %qs",
1905 return Expression::make_error(imp->location());
1907 if (pos == std::string::npos)
1908 mpfr_set_ui(real, 0, GMP_RNDN);
1911 std::string real_str = num.substr(0, pos);
1912 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1914 error_at(imp->location(), "bad number in import data: %qs",
1916 return Expression::make_error(imp->location());
1920 std::string imag_str;
1921 if (pos == std::string::npos)
1924 imag_str = num.substr(pos);
1925 imag_str = imag_str.substr(0, imag_str.size() - 1);
1927 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1929 error_at(imp->location(), "bad number in import data: %qs",
1931 return Expression::make_error(imp->location());
1933 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1939 else if (num.find('.') == std::string::npos
1940 && num.find('E') == std::string::npos)
1942 bool is_character_constant = (!num.empty()
1943 && num[num.length() - 1] == '\'');
1944 if (is_character_constant)
1945 num = num.substr(0, num.length() - 1);
1947 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1949 error_at(imp->location(), "bad number in import data: %qs",
1951 return Expression::make_error(imp->location());
1954 if (is_character_constant)
1955 ret = Expression::make_character(&val, NULL, imp->location());
1957 ret = Expression::make_integer(&val, NULL, imp->location());
1964 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1966 error_at(imp->location(), "bad number in import data: %qs",
1968 return Expression::make_error(imp->location());
1970 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1975 // Ast dump for integer expression.
1978 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1980 if (this->is_character_constant_)
1981 ast_dump_context->ostream() << '\'';
1982 Integer_expression::export_integer(ast_dump_context, this->val_);
1983 if (this->is_character_constant_)
1984 ast_dump_context->ostream() << '\'';
1987 // Build a new integer value.
1990 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1992 return new Integer_expression(val, type, false, location);
1995 // Build a new character constant value.
1998 Expression::make_character(const mpz_t* val, Type* type, Location location)
2000 return new Integer_expression(val, type, true, location);
2005 class Float_expression : public Expression
2008 Float_expression(const mpfr_t* val, Type* type, Location location)
2009 : Expression(EXPRESSION_FLOAT, location),
2012 mpfr_init_set(this->val_, *val, GMP_RNDN);
2015 // Write VAL to export data.
2017 export_float(String_dump* exp, const mpfr_t val);
2019 // Write VAL to dump file.
2021 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2025 do_is_constant() const
2029 do_numeric_constant_value(Numeric_constant* nc) const
2031 nc->set_float(this->type_, this->val_);
2039 do_determine_type(const Type_context*);
2042 do_check_types(Gogo*);
2046 { return Expression::make_float(&this->val_, this->type_,
2047 this->location()); }
2050 do_get_tree(Translate_context*);
2053 do_export(Export*) const;
2056 do_dump_expression(Ast_dump_context*) const;
2059 // The floating point value.
2065 // Return the current type. If we haven't set the type yet, we return
2066 // an abstract float type.
2069 Float_expression::do_type()
2071 if (this->type_ == NULL)
2072 this->type_ = Type::make_abstract_float_type();
2076 // Set the type of the float value. Here we may switch from an
2077 // abstract type to a real type.
2080 Float_expression::do_determine_type(const Type_context* context)
2082 if (this->type_ != NULL && !this->type_->is_abstract())
2084 else if (context->type != NULL
2085 && (context->type->integer_type() != NULL
2086 || context->type->float_type() != NULL
2087 || context->type->complex_type() != NULL))
2088 this->type_ = context->type;
2089 else if (!context->may_be_abstract)
2090 this->type_ = Type::lookup_float_type("float64");
2093 // Check the type of a float value.
2096 Float_expression::do_check_types(Gogo*)
2098 Type* type = this->type_;
2101 Numeric_constant nc;
2102 nc.set_float(NULL, this->val_);
2103 if (!nc.set_type(this->type_, true, this->location()))
2104 this->set_is_error();
2107 // Get a tree for a float constant.
2110 Float_expression::do_get_tree(Translate_context* context)
2112 Gogo* gogo = context->gogo();
2114 if (this->type_ != NULL && !this->type_->is_abstract())
2115 type = type_to_tree(this->type_->get_backend(gogo));
2116 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2118 // We have an abstract integer type. We just hope for the best.
2119 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2123 // If we still have an abstract type here, then this is being
2124 // used in a constant expression which didn't get reduced. We
2125 // just use float64 and hope for the best.
2126 Type* ft = Type::lookup_float_type("float64");
2127 type = type_to_tree(ft->get_backend(gogo));
2129 return Expression::float_constant_tree(this->val_, type);
2132 // Write a floating point number to a string dump.
2135 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2138 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2140 exp->write_c_string("-");
2141 exp->write_c_string("0.");
2142 exp->write_c_string(*s == '-' ? s + 1 : s);
2145 snprintf(buf, sizeof buf, "E%ld", exponent);
2146 exp->write_c_string(buf);
2149 // Export a floating point number in a constant expression.
2152 Float_expression::do_export(Export* exp) const
2154 Float_expression::export_float(exp, this->val_);
2155 // A trailing space lets us reliably identify the end of the number.
2156 exp->write_c_string(" ");
2159 // Dump a floating point number to the dump file.
2162 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2164 Float_expression::export_float(ast_dump_context, this->val_);
2167 // Make a float expression.
2170 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2172 return new Float_expression(val, type, location);
2177 class Complex_expression : public Expression
2180 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2182 : Expression(EXPRESSION_COMPLEX, location),
2185 mpfr_init_set(this->real_, *real, GMP_RNDN);
2186 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2189 // Write REAL/IMAG to string dump.
2191 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2193 // Write REAL/IMAG to dump context.
2195 dump_complex(Ast_dump_context* ast_dump_context,
2196 const mpfr_t real, const mpfr_t val);
2200 do_is_constant() const
2204 do_numeric_constant_value(Numeric_constant* nc) const
2206 nc->set_complex(this->type_, this->real_, this->imag_);
2214 do_determine_type(const Type_context*);
2217 do_check_types(Gogo*);
2222 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2227 do_get_tree(Translate_context*);
2230 do_export(Export*) const;
2233 do_dump_expression(Ast_dump_context*) const;
2238 // The imaginary part;
2240 // The type if known.
2244 // Return the current type. If we haven't set the type yet, we return
2245 // an abstract complex type.
2248 Complex_expression::do_type()
2250 if (this->type_ == NULL)
2251 this->type_ = Type::make_abstract_complex_type();
2255 // Set the type of the complex value. Here we may switch from an
2256 // abstract type to a real type.
2259 Complex_expression::do_determine_type(const Type_context* context)
2261 if (this->type_ != NULL && !this->type_->is_abstract())
2263 else if (context->type != NULL
2264 && context->type->complex_type() != NULL)
2265 this->type_ = context->type;
2266 else if (!context->may_be_abstract)
2267 this->type_ = Type::lookup_complex_type("complex128");
2270 // Check the type of a complex value.
2273 Complex_expression::do_check_types(Gogo*)
2275 Type* type = this->type_;
2278 Numeric_constant nc;
2279 nc.set_complex(NULL, this->real_, this->imag_);
2280 if (!nc.set_type(this->type_, true, this->location()))
2281 this->set_is_error();
2284 // Get a tree for a complex constant.
2287 Complex_expression::do_get_tree(Translate_context* context)
2289 Gogo* gogo = context->gogo();
2291 if (this->type_ != NULL && !this->type_->is_abstract())
2292 type = type_to_tree(this->type_->get_backend(gogo));
2295 // If we still have an abstract type here, this this is being
2296 // used in a constant expression which didn't get reduced. We
2297 // just use complex128 and hope for the best.
2298 Type* ct = Type::lookup_complex_type("complex128");
2299 type = type_to_tree(ct->get_backend(gogo));
2301 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2304 // Write REAL/IMAG to export data.
2307 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2310 if (!mpfr_zero_p(real))
2312 Float_expression::export_float(exp, real);
2313 if (mpfr_sgn(imag) > 0)
2314 exp->write_c_string("+");
2316 Float_expression::export_float(exp, imag);
2317 exp->write_c_string("i");
2320 // Export a complex number in a constant expression.
2323 Complex_expression::do_export(Export* exp) const
2325 Complex_expression::export_complex(exp, this->real_, this->imag_);
2326 // A trailing space lets us reliably identify the end of the number.
2327 exp->write_c_string(" ");
2330 // Dump a complex expression to the dump file.
2333 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2335 Complex_expression::export_complex(ast_dump_context,
2340 // Make a complex expression.
2343 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2346 return new Complex_expression(real, imag, type, location);
2349 // Find a named object in an expression.
2351 class Find_named_object : public Traverse
2354 Find_named_object(Named_object* no)
2355 : Traverse(traverse_expressions),
2356 no_(no), found_(false)
2359 // Whether we found the object.
2362 { return this->found_; }
2366 expression(Expression**);
2369 // The object we are looking for.
2371 // Whether we found it.
2375 // A reference to a const in an expression.
2377 class Const_expression : public Expression
2380 Const_expression(Named_object* constant, Location location)
2381 : Expression(EXPRESSION_CONST_REFERENCE, location),
2382 constant_(constant), type_(NULL), seen_(false)
2387 { return this->constant_; }
2389 // Check that the initializer does not refer to the constant itself.
2391 check_for_init_loop();
2395 do_traverse(Traverse*);
2398 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2401 do_is_constant() const
2405 do_numeric_constant_value(Numeric_constant* nc) const;
2408 do_string_constant_value(std::string* val) const;
2413 // The type of a const is set by the declaration, not the use.
2415 do_determine_type(const Type_context*);
2418 do_check_types(Gogo*);
2425 do_get_tree(Translate_context* context);
2427 // When exporting a reference to a const as part of a const
2428 // expression, we export the value. We ignore the fact that it has
2431 do_export(Export* exp) const
2432 { this->constant_->const_value()->expr()->export_expression(exp); }
2435 do_dump_expression(Ast_dump_context*) const;
2439 Named_object* constant_;
2440 // The type of this reference. This is used if the constant has an
2443 // Used to prevent infinite recursion when a constant incorrectly
2444 // refers to itself.
2451 Const_expression::do_traverse(Traverse* traverse)
2453 if (this->type_ != NULL)
2454 return Type::traverse(this->type_, traverse);
2455 return TRAVERSE_CONTINUE;
2458 // Lower a constant expression. This is where we convert the
2459 // predeclared constant iota into an integer value.
2462 Const_expression::do_lower(Gogo* gogo, Named_object*,
2463 Statement_inserter*, int iota_value)
2465 if (this->constant_->const_value()->expr()->classification()
2468 if (iota_value == -1)
2470 error_at(this->location(),
2471 "iota is only defined in const declarations");
2475 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2476 Expression* ret = Expression::make_integer(&val, NULL,
2482 // Make sure that the constant itself has been lowered.
2483 gogo->lower_constant(this->constant_);
2488 // Return a numeric constant value.
2491 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2496 Expression* e = this->constant_->const_value()->expr();
2500 bool r = e->numeric_constant_value(nc);
2502 this->seen_ = false;
2505 if (this->type_ != NULL)
2506 ctype = this->type_;
2508 ctype = this->constant_->const_value()->type();
2509 if (r && ctype != NULL)
2511 if (!nc->set_type(ctype, false, this->location()))
2519 Const_expression::do_string_constant_value(std::string* val) const
2524 Expression* e = this->constant_->const_value()->expr();
2527 bool ok = e->string_constant_value(val);
2528 this->seen_ = false;
2533 // Return the type of the const reference.
2536 Const_expression::do_type()
2538 if (this->type_ != NULL)
2541 Named_constant* nc = this->constant_->const_value();
2543 if (this->seen_ || nc->lowering())
2545 this->report_error(_("constant refers to itself"));
2546 this->type_ = Type::make_error_type();
2552 Type* ret = nc->type();
2556 this->seen_ = false;
2560 // During parsing, a named constant may have a NULL type, but we
2561 // must not return a NULL type here.
2562 ret = nc->expr()->type();
2564 this->seen_ = false;
2569 // Set the type of the const reference.
2572 Const_expression::do_determine_type(const Type_context* context)
2574 Type* ctype = this->constant_->const_value()->type();
2575 Type* cetype = (ctype != NULL
2577 : this->constant_->const_value()->expr()->type());
2578 if (ctype != NULL && !ctype->is_abstract())
2580 else if (context->type != NULL
2581 && context->type->is_numeric_type()
2582 && cetype->is_numeric_type())
2583 this->type_ = context->type;
2584 else if (context->type != NULL
2585 && context->type->is_string_type()
2586 && cetype->is_string_type())
2587 this->type_ = context->type;
2588 else if (context->type != NULL
2589 && context->type->is_boolean_type()
2590 && cetype->is_boolean_type())
2591 this->type_ = context->type;
2592 else if (!context->may_be_abstract)
2594 if (cetype->is_abstract())
2595 cetype = cetype->make_non_abstract_type();
2596 this->type_ = cetype;
2600 // Check for a loop in which the initializer of a constant refers to
2601 // the constant itself.
2604 Const_expression::check_for_init_loop()
2606 if (this->type_ != NULL && this->type_->is_error())
2611 this->report_error(_("constant refers to itself"));
2612 this->type_ = Type::make_error_type();
2616 Expression* init = this->constant_->const_value()->expr();
2617 Find_named_object find_named_object(this->constant_);
2620 Expression::traverse(&init, &find_named_object);
2621 this->seen_ = false;
2623 if (find_named_object.found())
2625 if (this->type_ == NULL || !this->type_->is_error())
2627 this->report_error(_("constant refers to itself"));
2628 this->type_ = Type::make_error_type();
2634 // Check types of a const reference.
2637 Const_expression::do_check_types(Gogo*)
2639 if (this->type_ != NULL && this->type_->is_error())
2642 this->check_for_init_loop();
2644 // Check that numeric constant fits in type.
2645 if (this->type_ != NULL && this->type_->is_numeric_type())
2647 Numeric_constant nc;
2648 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2650 if (!nc.set_type(this->type_, true, this->location()))
2651 this->set_is_error();
2656 // Return a tree for the const reference.
2659 Const_expression::do_get_tree(Translate_context* context)
2661 Gogo* gogo = context->gogo();
2663 if (this->type_ == NULL)
2664 type_tree = NULL_TREE;
2667 type_tree = type_to_tree(this->type_->get_backend(gogo));
2668 if (type_tree == error_mark_node)
2669 return error_mark_node;
2672 // If the type has been set for this expression, but the underlying
2673 // object is an abstract int or float, we try to get the abstract
2674 // value. Otherwise we may lose something in the conversion.
2675 if (this->type_ != NULL
2676 && this->type_->is_numeric_type()
2677 && (this->constant_->const_value()->type() == NULL
2678 || this->constant_->const_value()->type()->is_abstract()))
2680 Expression* expr = this->constant_->const_value()->expr();
2681 Numeric_constant nc;
2682 if (expr->numeric_constant_value(&nc)
2683 && nc.set_type(this->type_, false, this->location()))
2685 Expression* e = nc.expression(this->location());
2686 return e->get_tree(context);
2690 tree const_tree = this->constant_->get_tree(gogo, context->function());
2691 if (this->type_ == NULL
2692 || const_tree == error_mark_node
2693 || TREE_TYPE(const_tree) == error_mark_node)
2697 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2698 ret = fold_convert(type_tree, const_tree);
2699 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2700 ret = fold(convert_to_integer(type_tree, const_tree));
2701 else if (TREE_CODE(type_tree) == REAL_TYPE)
2702 ret = fold(convert_to_real(type_tree, const_tree));
2703 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2704 ret = fold(convert_to_complex(type_tree, const_tree));
2710 // Dump ast representation for constant expression.
2713 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2715 ast_dump_context->ostream() << this->constant_->name();
2718 // Make a reference to a constant in an expression.
2721 Expression::make_const_reference(Named_object* constant,
2724 return new Const_expression(constant, location);
2727 // Find a named object in an expression.
2730 Find_named_object::expression(Expression** pexpr)
2732 switch ((*pexpr)->classification())
2734 case Expression::EXPRESSION_CONST_REFERENCE:
2736 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2737 if (ce->named_object() == this->no_)
2740 // We need to check a constant initializer explicitly, as
2741 // loops here will not be caught by the loop checking for
2742 // variable initializers.
2743 ce->check_for_init_loop();
2745 return TRAVERSE_CONTINUE;
2748 case Expression::EXPRESSION_VAR_REFERENCE:
2749 if ((*pexpr)->var_expression()->named_object() == this->no_)
2751 return TRAVERSE_CONTINUE;
2752 case Expression::EXPRESSION_FUNC_REFERENCE:
2753 if ((*pexpr)->func_expression()->named_object() == this->no_)
2755 return TRAVERSE_CONTINUE;
2757 return TRAVERSE_CONTINUE;
2759 this->found_ = true;
2760 return TRAVERSE_EXIT;
2765 class Nil_expression : public Expression
2768 Nil_expression(Location location)
2769 : Expression(EXPRESSION_NIL, location)
2777 do_is_constant() const
2782 { return Type::make_nil_type(); }
2785 do_determine_type(const Type_context*)
2793 do_get_tree(Translate_context*)
2794 { return null_pointer_node; }
2797 do_export(Export* exp) const
2798 { exp->write_c_string("nil"); }
2801 do_dump_expression(Ast_dump_context* ast_dump_context) const
2802 { ast_dump_context->ostream() << "nil"; }
2805 // Import a nil expression.
2808 Nil_expression::do_import(Import* imp)
2810 imp->require_c_string("nil");
2811 return Expression::make_nil(imp->location());
2814 // Make a nil expression.
2817 Expression::make_nil(Location location)
2819 return new Nil_expression(location);
2822 // The value of the predeclared constant iota. This is little more
2823 // than a marker. This will be lowered to an integer in
2824 // Const_expression::do_lower, which is where we know the value that
2827 class Iota_expression : public Parser_expression
2830 Iota_expression(Location location)
2831 : Parser_expression(EXPRESSION_IOTA, location)
2836 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2837 { go_unreachable(); }
2839 // There should only ever be one of these.
2842 { go_unreachable(); }
2845 do_dump_expression(Ast_dump_context* ast_dump_context) const
2846 { ast_dump_context->ostream() << "iota"; }
2849 // Make an iota expression. This is only called for one case: the
2850 // value of the predeclared constant iota.
2853 Expression::make_iota()
2855 static Iota_expression iota_expression(Linemap::unknown_location());
2856 return &iota_expression;
2859 // A type conversion expression.
2861 class Type_conversion_expression : public Expression
2864 Type_conversion_expression(Type* type, Expression* expr,
2866 : Expression(EXPRESSION_CONVERSION, location),
2867 type_(type), expr_(expr), may_convert_function_types_(false)
2870 // Return the type to which we are converting.
2873 { return this->type_; }
2875 // Return the expression which we are converting.
2878 { return this->expr_; }
2880 // Permit converting from one function type to another. This is
2881 // used internally for method expressions.
2883 set_may_convert_function_types()
2885 this->may_convert_function_types_ = true;
2888 // Import a type conversion expression.
2894 do_traverse(Traverse* traverse);
2897 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2900 do_is_constant() const
2901 { return this->expr_->is_constant(); }
2904 do_numeric_constant_value(Numeric_constant*) const;
2907 do_string_constant_value(std::string*) const;
2911 { return this->type_; }
2914 do_determine_type(const Type_context*)
2916 Type_context subcontext(this->type_, false);
2917 this->expr_->determine_type(&subcontext);
2921 do_check_types(Gogo*);
2926 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2931 do_get_tree(Translate_context* context);
2934 do_export(Export*) const;
2937 do_dump_expression(Ast_dump_context*) const;
2940 // The type to convert to.
2942 // The expression to convert.
2944 // True if this is permitted to convert function types. This is
2945 // used internally for method expressions.
2946 bool may_convert_function_types_;
2952 Type_conversion_expression::do_traverse(Traverse* traverse)
2954 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2955 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2956 return TRAVERSE_EXIT;
2957 return TRAVERSE_CONTINUE;
2960 // Convert to a constant at lowering time.
2963 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2964 Statement_inserter*, int)
2966 Type* type = this->type_;
2967 Expression* val = this->expr_;
2968 Location location = this->location();
2970 if (type->is_numeric_type())
2972 Numeric_constant nc;
2973 if (val->numeric_constant_value(&nc))
2975 if (!nc.set_type(type, true, location))
2976 return Expression::make_error(location);
2977 return nc.expression(location);
2981 if (type->is_slice_type())
2983 Type* element_type = type->array_type()->element_type()->forwarded();
2984 bool is_byte = (element_type->integer_type() != NULL
2985 && element_type->integer_type()->is_byte());
2986 bool is_rune = (element_type->integer_type() != NULL
2987 && element_type->integer_type()->is_rune());
2988 if (is_byte || is_rune)
2991 if (val->string_constant_value(&s))
2993 Expression_list* vals = new Expression_list();
2996 for (std::string::const_iterator p = s.begin();
3001 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3002 Expression* v = Expression::make_integer(&val,
3011 const char *p = s.data();
3012 const char *pend = s.data() + s.length();
3016 int adv = Lex::fetch_char(p, &c);
3019 warning_at(this->location(), 0,
3020 "invalid UTF-8 encoding");
3025 mpz_init_set_ui(val, c);
3026 Expression* v = Expression::make_integer(&val,
3034 return Expression::make_slice_composite_literal(type, vals,
3043 // Return the constant numeric value if there is one.
3046 Type_conversion_expression::do_numeric_constant_value(
3047 Numeric_constant* nc) const
3049 if (!this->type_->is_numeric_type())
3051 if (!this->expr_->numeric_constant_value(nc))
3053 return nc->set_type(this->type_, false, this->location());
3056 // Return the constant string value if there is one.
3059 Type_conversion_expression::do_string_constant_value(std::string* val) const
3061 if (this->type_->is_string_type()
3062 && this->expr_->type()->integer_type() != NULL)
3064 Numeric_constant nc;
3065 if (this->expr_->numeric_constant_value(&nc))
3068 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3071 Lex::append_char(ival, true, val, this->location());
3077 // FIXME: Could handle conversion from const []int here.
3082 // Check that types are convertible.
3085 Type_conversion_expression::do_check_types(Gogo*)
3087 Type* type = this->type_;
3088 Type* expr_type = this->expr_->type();
3091 if (type->is_error() || expr_type->is_error())
3093 this->set_is_error();
3097 if (this->may_convert_function_types_
3098 && type->function_type() != NULL
3099 && expr_type->function_type() != NULL)
3102 if (Type::are_convertible(type, expr_type, &reason))
3105 error_at(this->location(), "%s", reason.c_str());
3106 this->set_is_error();
3109 // Get a tree for a type conversion.
3112 Type_conversion_expression::do_get_tree(Translate_context* context)
3114 Gogo* gogo = context->gogo();
3115 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3116 tree expr_tree = this->expr_->get_tree(context);
3118 if (type_tree == error_mark_node
3119 || expr_tree == error_mark_node
3120 || TREE_TYPE(expr_tree) == error_mark_node)
3121 return error_mark_node;
3123 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3124 return fold_convert(type_tree, expr_tree);
3126 Type* type = this->type_;
3127 Type* expr_type = this->expr_->type();
3129 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3130 ret = Expression::convert_for_assignment(context, type, expr_type,
3131 expr_tree, this->location());
3132 else if (type->integer_type() != NULL)
3134 if (expr_type->integer_type() != NULL
3135 || expr_type->float_type() != NULL
3136 || expr_type->is_unsafe_pointer_type())
3137 ret = fold(convert_to_integer(type_tree, expr_tree));
3141 else if (type->float_type() != NULL)
3143 if (expr_type->integer_type() != NULL
3144 || expr_type->float_type() != NULL)
3145 ret = fold(convert_to_real(type_tree, expr_tree));
3149 else if (type->complex_type() != NULL)
3151 if (expr_type->complex_type() != NULL)
3152 ret = fold(convert_to_complex(type_tree, expr_tree));
3156 else if (type->is_string_type()
3157 && expr_type->integer_type() != NULL)
3159 expr_tree = fold_convert(integer_type_node, expr_tree);
3160 if (host_integerp(expr_tree, 0))
3162 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3164 Lex::append_char(intval, true, &s, this->location());
3165 Expression* se = Expression::make_string(s, this->location());
3166 return se->get_tree(context);
3169 static tree int_to_string_fndecl;
3170 ret = Gogo::call_builtin(&int_to_string_fndecl,
3172 "__go_int_to_string",
3176 fold_convert(integer_type_node, expr_tree));
3178 else if (type->is_string_type() && expr_type->is_slice_type())
3180 if (!DECL_P(expr_tree))
3181 expr_tree = save_expr(expr_tree);
3182 Array_type* a = expr_type->array_type();
3183 Type* e = a->element_type()->forwarded();
3184 go_assert(e->integer_type() != NULL);
3185 tree valptr = fold_convert(const_ptr_type_node,
3186 a->value_pointer_tree(gogo, expr_tree));
3187 tree len = a->length_tree(gogo, expr_tree);
3188 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3190 if (e->integer_type()->is_byte())
3192 static tree byte_array_to_string_fndecl;
3193 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3195 "__go_byte_array_to_string",
3198 const_ptr_type_node,
3205 go_assert(e->integer_type()->is_rune());
3206 static tree int_array_to_string_fndecl;
3207 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3209 "__go_int_array_to_string",
3212 const_ptr_type_node,
3218 else if (type->is_slice_type() && expr_type->is_string_type())
3220 Type* e = type->array_type()->element_type()->forwarded();
3221 go_assert(e->integer_type() != NULL);
3222 if (e->integer_type()->is_byte())
3224 tree string_to_byte_array_fndecl = NULL_TREE;
3225 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3227 "__go_string_to_byte_array",
3230 TREE_TYPE(expr_tree),
3235 go_assert(e->integer_type()->is_rune());
3236 tree string_to_int_array_fndecl = NULL_TREE;
3237 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3239 "__go_string_to_int_array",
3242 TREE_TYPE(expr_tree),
3246 else if ((type->is_unsafe_pointer_type()
3247 && expr_type->points_to() != NULL)
3248 || (expr_type->is_unsafe_pointer_type()
3249 && type->points_to() != NULL))
3250 ret = fold_convert(type_tree, expr_tree);
3251 else if (type->is_unsafe_pointer_type()
3252 && expr_type->integer_type() != NULL)
3253 ret = convert_to_pointer(type_tree, expr_tree);
3254 else if (this->may_convert_function_types_
3255 && type->function_type() != NULL
3256 && expr_type->function_type() != NULL)
3257 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3260 ret = Expression::convert_for_assignment(context, type, expr_type,
3261 expr_tree, this->location());
3266 // Output a type conversion in a constant expression.
3269 Type_conversion_expression::do_export(Export* exp) const
3271 exp->write_c_string("convert(");
3272 exp->write_type(this->type_);
3273 exp->write_c_string(", ");
3274 this->expr_->export_expression(exp);
3275 exp->write_c_string(")");
3278 // Import a type conversion or a struct construction.
3281 Type_conversion_expression::do_import(Import* imp)
3283 imp->require_c_string("convert(");
3284 Type* type = imp->read_type();
3285 imp->require_c_string(", ");
3286 Expression* val = Expression::import_expression(imp);
3287 imp->require_c_string(")");
3288 return Expression::make_cast(type, val, imp->location());
3291 // Dump ast representation for a type conversion expression.
3294 Type_conversion_expression::do_dump_expression(
3295 Ast_dump_context* ast_dump_context) const
3297 ast_dump_context->dump_type(this->type_);
3298 ast_dump_context->ostream() << "(";
3299 ast_dump_context->dump_expression(this->expr_);
3300 ast_dump_context->ostream() << ") ";
3303 // Make a type cast expression.
3306 Expression::make_cast(Type* type, Expression* val, Location location)
3308 if (type->is_error_type() || val->is_error_expression())
3309 return Expression::make_error(location);
3310 return new Type_conversion_expression(type, val, location);
3313 // An unsafe type conversion, used to pass values to builtin functions.
3315 class Unsafe_type_conversion_expression : public Expression
3318 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3320 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3321 type_(type), expr_(expr)
3326 do_traverse(Traverse* traverse);
3330 { return this->type_; }
3333 do_determine_type(const Type_context*)
3334 { this->expr_->determine_type_no_context(); }
3339 return new Unsafe_type_conversion_expression(this->type_,
3340 this->expr_->copy(),
3345 do_get_tree(Translate_context*);
3348 do_dump_expression(Ast_dump_context*) const;
3351 // The type to convert to.
3353 // The expression to convert.
3360 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3362 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3363 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3364 return TRAVERSE_EXIT;
3365 return TRAVERSE_CONTINUE;
3368 // Convert to backend representation.
3371 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3373 // We are only called for a limited number of cases.
3375 Type* t = this->type_;
3376 Type* et = this->expr_->type();
3378 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3379 tree expr_tree = this->expr_->get_tree(context);
3380 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3381 return error_mark_node;
3383 Location loc = this->location();
3385 bool use_view_convert = false;
3386 if (t->is_slice_type())
3388 go_assert(et->is_slice_type());
3389 use_view_convert = true;
3391 else if (t->map_type() != NULL)
3392 go_assert(et->map_type() != NULL);
3393 else if (t->channel_type() != NULL)
3394 go_assert(et->channel_type() != NULL);
3395 else if (t->points_to() != NULL)
3396 go_assert(et->points_to() != NULL || et->is_nil_type());
3397 else if (et->is_unsafe_pointer_type())
3398 go_assert(t->points_to() != NULL);
3399 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3401 go_assert(et->interface_type() != NULL
3402 && !et->interface_type()->is_empty());
3403 use_view_convert = true;
3405 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3407 go_assert(et->interface_type() != NULL
3408 && et->interface_type()->is_empty());
3409 use_view_convert = true;
3411 else if (t->integer_type() != NULL)
3413 go_assert(et->is_boolean_type()
3414 || et->integer_type() != NULL
3415 || et->function_type() != NULL
3416 || et->points_to() != NULL
3417 || et->map_type() != NULL
3418 || et->channel_type() != NULL);
3419 return convert_to_integer(type_tree, expr_tree);
3424 if (use_view_convert)
3425 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3428 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3431 // Dump ast representation for an unsafe type conversion expression.
3434 Unsafe_type_conversion_expression::do_dump_expression(
3435 Ast_dump_context* ast_dump_context) const
3437 ast_dump_context->dump_type(this->type_);
3438 ast_dump_context->ostream() << "(";
3439 ast_dump_context->dump_expression(this->expr_);
3440 ast_dump_context->ostream() << ") ";
3443 // Make an unsafe type conversion expression.
3446 Expression::make_unsafe_cast(Type* type, Expression* expr,
3449 return new Unsafe_type_conversion_expression(type, expr, location);
3452 // Unary expressions.
3454 class Unary_expression : public Expression
3457 Unary_expression(Operator op, Expression* expr, Location location)
3458 : Expression(EXPRESSION_UNARY, location),
3459 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3462 // Return the operator.
3465 { return this->op_; }
3467 // Return the operand.
3470 { return this->expr_; }
3472 // Record that an address expression does not escape.
3474 set_does_not_escape()
3476 go_assert(this->op_ == OPERATOR_AND);
3477 this->escapes_ = false;
3480 // Record that this is an address expression which should create a
3481 // temporary variable if necessary. This is used for method calls.
3485 go_assert(this->op_ == OPERATOR_AND);
3486 this->create_temp_ = true;
3489 // Apply unary opcode OP to UNC, setting NC. Return true if this
3490 // could be done, false if not. Issue errors for overflow.
3492 eval_constant(Operator op, const Numeric_constant* unc,
3493 Location, Numeric_constant* nc);
3500 do_traverse(Traverse* traverse)
3501 { return Expression::traverse(&this->expr_, traverse); }
3504 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3507 do_is_constant() const;
3510 do_numeric_constant_value(Numeric_constant*) const;
3516 do_determine_type(const Type_context*);
3519 do_check_types(Gogo*);
3524 return Expression::make_unary(this->op_, this->expr_->copy(),
3529 do_must_eval_subexpressions_in_order(int*) const
3530 { return this->op_ == OPERATOR_MULT; }
3533 do_is_addressable() const
3534 { return this->op_ == OPERATOR_MULT; }
3537 do_get_tree(Translate_context*);
3540 do_export(Export*) const;
3543 do_dump_expression(Ast_dump_context*) const;
3546 // The unary operator to apply.
3548 // Normally true. False if this is an address expression which does
3549 // not escape the current function.
3551 // True if this is an address expression which should create a
3552 // temporary variable if necessary.
3558 // If we are taking the address of a composite literal, and the
3559 // contents are not constant, then we want to make a heap composite
3563 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3565 Location loc = this->location();
3566 Operator op = this->op_;
3567 Expression* expr = this->expr_;
3569 if (op == OPERATOR_MULT && expr->is_type_expression())
3570 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3572 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3573 // moving x to the heap. FIXME: Is it worth doing a real escape
3574 // analysis here? This case is found in math/unsafe.go and is
3575 // therefore worth special casing.
3576 if (op == OPERATOR_MULT)
3578 Expression* e = expr;
3579 while (e->classification() == EXPRESSION_CONVERSION)
3581 Type_conversion_expression* te
3582 = static_cast<Type_conversion_expression*>(e);
3586 if (e->classification() == EXPRESSION_UNARY)
3588 Unary_expression* ue = static_cast<Unary_expression*>(e);
3589 if (ue->op_ == OPERATOR_AND)
3596 ue->set_does_not_escape();
3601 // Catching an invalid indirection of unsafe.Pointer here avoid
3602 // having to deal with TYPE_VOID in other places.
3603 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3605 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3606 return Expression::make_error(this->location());
3609 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3611 Numeric_constant nc;
3612 if (expr->numeric_constant_value(&nc))
3614 Numeric_constant result;
3615 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3616 return result.expression(loc);
3623 // Return whether a unary expression is a constant.
3626 Unary_expression::do_is_constant() const
3628 if (this->op_ == OPERATOR_MULT)
3630 // Indirecting through a pointer is only constant if the object
3631 // to which the expression points is constant, but we currently
3632 // have no way to determine that.
3635 else if (this->op_ == OPERATOR_AND)
3637 // Taking the address of a variable is constant if it is a
3638 // global variable, not constant otherwise. In other cases
3639 // taking the address is probably not a constant.
3640 Var_expression* ve = this->expr_->var_expression();
3643 Named_object* no = ve->named_object();
3644 return no->is_variable() && no->var_value()->is_global();
3649 return this->expr_->is_constant();
3652 // Apply unary opcode OP to UNC, setting NC. Return true if this
3653 // could be done, false if not. Issue errors for overflow.
3656 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3657 Location location, Numeric_constant* nc)
3665 case OPERATOR_MINUS:
3666 if (unc->is_int() || unc->is_rune())
3668 else if (unc->is_float())
3671 unc->get_float(&uval);
3674 mpfr_neg(val, uval, GMP_RNDN);
3675 nc->set_float(unc->type(), val);
3680 else if (unc->is_complex())
3682 mpfr_t ureal, uimag;
3683 unc->get_complex(&ureal, &uimag);
3687 mpfr_neg(real, ureal, GMP_RNDN);
3688 mpfr_neg(imag, uimag, GMP_RNDN);
3689 nc->set_complex(unc->type(), real, imag);
3711 if (!unc->is_int() && !unc->is_rune())
3716 unc->get_rune(&uval);
3718 unc->get_int(&uval);
3724 case OPERATOR_MINUS:
3729 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3734 Type* utype = unc->type();
3735 if (utype->integer_type() == NULL
3736 || utype->integer_type()->is_abstract())
3740 // The number of HOST_WIDE_INTs that it takes to represent
3742 size_t count = ((mpz_sizeinbase(uval, 2)
3743 + HOST_BITS_PER_WIDE_INT
3745 / HOST_BITS_PER_WIDE_INT);
3747 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3748 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3750 size_t obits = utype->integer_type()->bits();
3752 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3755 mpz_init_set_ui(adj, 1);
3756 mpz_mul_2exp(adj, adj, obits);
3757 mpz_add(uval, uval, adj);
3762 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3763 go_assert(ecount <= count);
3765 // Trim down to the number of words required by the type.
3766 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3767 / HOST_BITS_PER_WIDE_INT);
3768 go_assert(ocount <= count);
3770 for (size_t i = 0; i < ocount; ++i)
3773 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3775 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3778 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3780 if (!utype->integer_type()->is_unsigned()
3781 && mpz_tstbit(val, obits - 1))
3784 mpz_init_set_ui(adj, 1);
3785 mpz_mul_2exp(adj, adj, obits);
3786 mpz_sub(val, val, adj);
3800 nc->set_rune(NULL, val);
3802 nc->set_int(NULL, val);
3807 return nc->set_type(unc->type(), true, location);
3810 // Return the integral constant value of a unary expression, if it has one.
3813 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3815 Numeric_constant unc;
3816 if (!this->expr_->numeric_constant_value(&unc))
3818 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3822 // Return the type of a unary expression.
3825 Unary_expression::do_type()
3830 case OPERATOR_MINUS:
3833 return this->expr_->type();
3836 return Type::make_pointer_type(this->expr_->type());
3840 Type* subtype = this->expr_->type();
3841 Type* points_to = subtype->points_to();
3842 if (points_to == NULL)
3843 return Type::make_error_type();
3852 // Determine abstract types for a unary expression.
3855 Unary_expression::do_determine_type(const Type_context* context)
3860 case OPERATOR_MINUS:
3863 this->expr_->determine_type(context);
3867 // Taking the address of something.
3869 Type* subtype = (context->type == NULL
3871 : context->type->points_to());
3872 Type_context subcontext(subtype, false);
3873 this->expr_->determine_type(&subcontext);
3878 // Indirecting through a pointer.
3880 Type* subtype = (context->type == NULL
3882 : Type::make_pointer_type(context->type));
3883 Type_context subcontext(subtype, false);
3884 this->expr_->determine_type(&subcontext);
3893 // Check types for a unary expression.
3896 Unary_expression::do_check_types(Gogo*)
3898 Type* type = this->expr_->type();
3899 if (type->is_error())
3901 this->set_is_error();
3908 case OPERATOR_MINUS:
3909 if (type->integer_type() == NULL
3910 && type->float_type() == NULL
3911 && type->complex_type() == NULL)
3912 this->report_error(_("expected numeric type"));
3916 if (!type->is_boolean_type())
3917 this->report_error(_("expected boolean type"));
3921 if (type->integer_type() == NULL
3922 && !type->is_boolean_type())
3923 this->report_error(_("expected integer or boolean type"));
3927 if (!this->expr_->is_addressable())
3929 if (!this->create_temp_)
3930 this->report_error(_("invalid operand for unary %<&%>"));
3933 this->expr_->address_taken(this->escapes_);
3937 // Indirecting through a pointer.
3938 if (type->points_to() == NULL)
3939 this->report_error(_("expected pointer"));
3947 // Get a tree for a unary expression.
3950 Unary_expression::do_get_tree(Translate_context* context)
3952 Location loc = this->location();
3954 // Taking the address of a set-and-use-temporary expression requires
3955 // setting the temporary and then taking the address.
3956 if (this->op_ == OPERATOR_AND)
3958 Set_and_use_temporary_expression* sut =
3959 this->expr_->set_and_use_temporary_expression();
3962 Temporary_statement* temp = sut->temporary();
3963 Bvariable* bvar = temp->get_backend_variable(context);
3964 tree var_tree = var_to_tree(bvar);
3965 Expression* val = sut->expression();
3966 tree val_tree = val->get_tree(context);
3967 if (var_tree == error_mark_node || val_tree == error_mark_node)
3968 return error_mark_node;
3969 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3971 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3972 TREE_TYPE(addr_tree),
3973 build2_loc(sut->location().gcc_location(),
3974 MODIFY_EXPR, void_type_node,
3975 var_tree, val_tree),
3980 tree expr = this->expr_->get_tree(context);
3981 if (expr == error_mark_node)
3982 return error_mark_node;
3989 case OPERATOR_MINUS:
3991 tree type = TREE_TYPE(expr);
3992 tree compute_type = excess_precision_type(type);
3993 if (compute_type != NULL_TREE)
3994 expr = ::convert(compute_type, expr);
3995 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3996 (compute_type != NULL_TREE
4000 if (compute_type != NULL_TREE)
4001 ret = ::convert(type, ret);
4006 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4007 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4008 TREE_TYPE(expr), expr);
4010 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4011 expr, build_int_cst(TREE_TYPE(expr), 0));
4014 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4018 if (!this->create_temp_)
4020 // We should not see a non-constant constructor here; cases
4021 // where we would see one should have been moved onto the
4022 // heap at parse time. Taking the address of a nonconstant
4023 // constructor will not do what the programmer expects.
4024 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4025 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4028 // Build a decl for a constant constructor.
4029 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4031 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4032 create_tmp_var_name("C"), TREE_TYPE(expr));
4033 DECL_EXTERNAL(decl) = 0;
4034 TREE_PUBLIC(decl) = 0;
4035 TREE_READONLY(decl) = 1;
4036 TREE_CONSTANT(decl) = 1;
4037 TREE_STATIC(decl) = 1;
4038 TREE_ADDRESSABLE(decl) = 1;
4039 DECL_ARTIFICIAL(decl) = 1;
4040 DECL_INITIAL(decl) = expr;
4041 rest_of_decl_compilation(decl, 1, 0);
4045 if (this->create_temp_
4046 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4047 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
4048 && TREE_CODE(expr) != INDIRECT_REF
4049 && TREE_CODE(expr) != COMPONENT_REF)
4051 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4052 DECL_IGNORED_P(tmp) = 1;
4053 DECL_INITIAL(tmp) = expr;
4054 TREE_ADDRESSABLE(tmp) = 1;
4055 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4056 build_pointer_type(TREE_TYPE(expr)),
4057 build1_loc(loc.gcc_location(), DECL_EXPR,
4058 void_type_node, tmp),
4059 build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4062 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4066 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4068 // If we are dereferencing the pointer to a large struct, we
4069 // need to check for nil. We don't bother to check for small
4070 // structs because we expect the system to crash on a nil
4071 // pointer dereference.
4072 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4073 if (!VOID_TYPE_P(target_type_tree))
4075 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4076 if (s == -1 || s >= 4096)
4079 expr = save_expr(expr);
4080 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4083 fold_convert(TREE_TYPE(expr),
4084 null_pointer_node));
4085 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4087 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4088 TREE_TYPE(expr), build3(COND_EXPR,
4096 // If the type of EXPR is a recursive pointer type, then we
4097 // need to insert a cast before indirecting.
4098 if (VOID_TYPE_P(target_type_tree))
4100 Type* pt = this->expr_->type()->points_to();
4101 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4102 expr = fold_convert_loc(loc.gcc_location(),
4103 build_pointer_type(ind), expr);
4106 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4114 // Export a unary expression.
4117 Unary_expression::do_export(Export* exp) const
4122 exp->write_c_string("+ ");
4124 case OPERATOR_MINUS:
4125 exp->write_c_string("- ");
4128 exp->write_c_string("! ");
4131 exp->write_c_string("^ ");
4138 this->expr_->export_expression(exp);
4141 // Import a unary expression.
4144 Unary_expression::do_import(Import* imp)
4147 switch (imp->get_char())
4153 op = OPERATOR_MINUS;
4164 imp->require_c_string(" ");
4165 Expression* expr = Expression::import_expression(imp);
4166 return Expression::make_unary(op, expr, imp->location());
4169 // Dump ast representation of an unary expression.
4172 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4174 ast_dump_context->dump_operator(this->op_);
4175 ast_dump_context->ostream() << "(";
4176 ast_dump_context->dump_expression(this->expr_);
4177 ast_dump_context->ostream() << ") ";
4180 // Make a unary expression.
4183 Expression::make_unary(Operator op, Expression* expr, Location location)
4185 return new Unary_expression(op, expr, location);
4188 // If this is an indirection through a pointer, return the expression
4189 // being pointed through. Otherwise return this.
4194 if (this->classification_ == EXPRESSION_UNARY)
4196 Unary_expression* ue = static_cast<Unary_expression*>(this);
4197 if (ue->op() == OPERATOR_MULT)
4198 return ue->operand();
4203 // Class Binary_expression.
4208 Binary_expression::do_traverse(Traverse* traverse)
4210 int t = Expression::traverse(&this->left_, traverse);
4211 if (t == TRAVERSE_EXIT)
4212 return TRAVERSE_EXIT;
4213 return Expression::traverse(&this->right_, traverse);
4216 // Return the type to use for a binary operation on operands of
4217 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4218 // such may be NULL or abstract.
4221 Binary_expression::operation_type(Operator op, Type* left_type,
4222 Type* right_type, Type** result_type)
4224 if (left_type != right_type
4225 && !left_type->is_abstract()
4226 && !right_type->is_abstract()
4227 && left_type->base() != right_type->base()
4228 && op != OPERATOR_LSHIFT
4229 && op != OPERATOR_RSHIFT)
4231 // May be a type error--let it be diagnosed elsewhere.
4235 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4237 if (left_type->integer_type() != NULL)
4238 *result_type = left_type;
4240 *result_type = Type::make_abstract_integer_type();
4242 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4243 *result_type = left_type;
4244 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4245 *result_type = right_type;
4246 else if (!left_type->is_abstract())
4247 *result_type = left_type;
4248 else if (!right_type->is_abstract())
4249 *result_type = right_type;
4250 else if (left_type->complex_type() != NULL)
4251 *result_type = left_type;
4252 else if (right_type->complex_type() != NULL)
4253 *result_type = right_type;
4254 else if (left_type->float_type() != NULL)
4255 *result_type = left_type;
4256 else if (right_type->float_type() != NULL)
4257 *result_type = right_type;
4258 else if (left_type->integer_type() != NULL
4259 && left_type->integer_type()->is_rune())
4260 *result_type = left_type;
4261 else if (right_type->integer_type() != NULL
4262 && right_type->integer_type()->is_rune())
4263 *result_type = right_type;
4265 *result_type = left_type;
4270 // Convert an integer comparison code and an operator to a boolean
4274 Binary_expression::cmp_to_bool(Operator op, int cmp)
4281 case OPERATOR_NOTEQ:
4298 // Compare constants according to OP.
4301 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4302 Numeric_constant* right_nc,
4303 Location location, bool* result)
4305 Type* left_type = left_nc->type();
4306 Type* right_type = right_nc->type();
4309 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4312 // When comparing an untyped operand to a typed operand, we are
4313 // effectively coercing the untyped operand to the other operand's
4314 // type, so make sure that is valid.
4315 if (!left_nc->set_type(type, true, location)
4316 || !right_nc->set_type(type, true, location))
4321 if (type->complex_type() != NULL)
4323 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4325 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4327 else if (type->float_type() != NULL)
4328 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4330 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4333 *result = Binary_expression::cmp_to_bool(op, cmp);
4338 // Compare integer constants.
4341 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4342 const Numeric_constant* right_nc,
4346 if (!left_nc->to_int(&left_val))
4349 if (!right_nc->to_int(&right_val))
4351 mpz_clear(left_val);
4355 *cmp = mpz_cmp(left_val, right_val);
4357 mpz_clear(left_val);
4358 mpz_clear(right_val);
4363 // Compare floating point constants.
4366 Binary_expression::compare_float(const Numeric_constant* left_nc,
4367 const Numeric_constant* right_nc,
4371 if (!left_nc->to_float(&left_val))
4374 if (!right_nc->to_float(&right_val))
4376 mpfr_clear(left_val);
4380 // We already coerced both operands to the same type. If that type
4381 // is not an abstract type, we need to round the values accordingly.
4382 Type* type = left_nc->type();
4383 if (!type->is_abstract() && type->float_type() != NULL)
4385 int bits = type->float_type()->bits();
4386 mpfr_prec_round(left_val, bits, GMP_RNDN);
4387 mpfr_prec_round(right_val, bits, GMP_RNDN);
4390 *cmp = mpfr_cmp(left_val, right_val);
4392 mpfr_clear(left_val);
4393 mpfr_clear(right_val);
4398 // Compare complex constants. Complex numbers may only be compared
4402 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4403 const Numeric_constant* right_nc,
4406 mpfr_t left_real, left_imag;
4407 if (!left_nc->to_complex(&left_real, &left_imag))
4409 mpfr_t right_real, right_imag;
4410 if (!right_nc->to_complex(&right_real, &right_imag))
4412 mpfr_clear(left_real);
4413 mpfr_clear(left_imag);
4417 // We already coerced both operands to the same type. If that type
4418 // is not an abstract type, we need to round the values accordingly.
4419 Type* type = left_nc->type();
4420 if (!type->is_abstract() && type->complex_type() != NULL)
4422 int bits = type->complex_type()->bits();
4423 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4424 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4425 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4426 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4429 *cmp = (mpfr_cmp(left_real, right_real) != 0
4430 || mpfr_cmp(left_imag, right_imag) != 0);
4432 mpfr_clear(left_real);
4433 mpfr_clear(left_imag);
4434 mpfr_clear(right_real);
4435 mpfr_clear(right_imag);
4440 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4441 // true if this could be done, false if not. Issue errors at LOCATION
4445 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4446 Numeric_constant* right_nc,
4447 Location location, Numeric_constant* nc)
4452 case OPERATOR_ANDAND:
4454 case OPERATOR_NOTEQ:
4459 // These return boolean values and as such must be handled
4466 Type* left_type = left_nc->type();
4467 Type* right_type = right_nc->type();
4470 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4473 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4475 // When combining an untyped operand with a typed operand, we are
4476 // effectively coercing the untyped operand to the other operand's
4477 // type, so make sure that is valid.
4478 if (!left_nc->set_type(type, true, location))
4480 if (!is_shift && !right_nc->set_type(type, true, location))
4484 if (type->complex_type() != NULL)
4485 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4486 else if (type->float_type() != NULL)
4487 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4489 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4492 r = nc->set_type(type, true, location);
4497 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4498 // integer operations. Return true if this could be done, false if
4502 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4503 const Numeric_constant* right_nc,
4504 Location location, Numeric_constant* nc)
4507 if (!left_nc->to_int(&left_val))
4510 if (!right_nc->to_int(&right_val))
4512 mpz_clear(left_val);
4522 mpz_add(val, left_val, right_val);
4524 case OPERATOR_MINUS:
4525 mpz_sub(val, left_val, right_val);
4528 mpz_ior(val, left_val, right_val);
4531 mpz_xor(val, left_val, right_val);
4534 mpz_mul(val, left_val, right_val);
4537 if (mpz_sgn(right_val) != 0)
4538 mpz_tdiv_q(val, left_val, right_val);
4541 error_at(location, "division by zero");
4546 if (mpz_sgn(right_val) != 0)
4547 mpz_tdiv_r(val, left_val, right_val);
4550 error_at(location, "division by zero");
4554 case OPERATOR_LSHIFT:
4556 unsigned long shift = mpz_get_ui(right_val);
4557 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4558 mpz_mul_2exp(val, left_val, shift);
4561 error_at(location, "shift count overflow");
4567 case OPERATOR_RSHIFT:
4569 unsigned long shift = mpz_get_ui(right_val);
4570 if (mpz_cmp_ui(right_val, shift) != 0)
4572 error_at(location, "shift count overflow");
4577 if (mpz_cmp_ui(left_val, 0) >= 0)
4578 mpz_tdiv_q_2exp(val, left_val, shift);
4580 mpz_fdiv_q_2exp(val, left_val, shift);
4586 mpz_and(val, left_val, right_val);
4588 case OPERATOR_BITCLEAR:
4592 mpz_com(tval, right_val);
4593 mpz_and(val, left_val, tval);
4601 mpz_clear(left_val);
4602 mpz_clear(right_val);
4604 if (left_nc->is_rune()
4605 || (op != OPERATOR_LSHIFT
4606 && op != OPERATOR_RSHIFT
4607 && right_nc->is_rune()))
4608 nc->set_rune(NULL, val);
4610 nc->set_int(NULL, val);
4617 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4618 // floating point operations. Return true if this could be done,
4622 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4623 const Numeric_constant* right_nc,
4624 Location location, Numeric_constant* nc)
4627 if (!left_nc->to_float(&left_val))
4630 if (!right_nc->to_float(&right_val))
4632 mpfr_clear(left_val);
4643 mpfr_add(val, left_val, right_val, GMP_RNDN);
4645 case OPERATOR_MINUS:
4646 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4651 case OPERATOR_BITCLEAR:
4653 case OPERATOR_LSHIFT:
4654 case OPERATOR_RSHIFT:
4655 mpfr_set_ui(val, 0, GMP_RNDN);
4659 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4662 if (!mpfr_zero_p(right_val))
4663 mpfr_div(val, left_val, right_val, GMP_RNDN);
4666 error_at(location, "division by zero");
4667 mpfr_set_ui(val, 0, GMP_RNDN);
4674 mpfr_clear(left_val);
4675 mpfr_clear(right_val);
4677 nc->set_float(NULL, val);
4683 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4684 // complex operations. Return true if this could be done, false if
4688 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4689 const Numeric_constant* right_nc,
4690 Location location, Numeric_constant* nc)
4692 mpfr_t left_real, left_imag;
4693 if (!left_nc->to_complex(&left_real, &left_imag))
4695 mpfr_t right_real, right_imag;
4696 if (!right_nc->to_complex(&right_real, &right_imag))
4698 mpfr_clear(left_real);
4699 mpfr_clear(left_imag);
4711 mpfr_add(real, left_real, right_real, GMP_RNDN);
4712 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4714 case OPERATOR_MINUS:
4715 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4716 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4721 case OPERATOR_BITCLEAR:
4723 case OPERATOR_LSHIFT:
4724 case OPERATOR_RSHIFT:
4725 mpfr_set_ui(real, 0, GMP_RNDN);
4726 mpfr_set_ui(imag, 0, GMP_RNDN);
4731 // You might think that multiplying two complex numbers would
4732 // be simple, and you would be right, until you start to think
4733 // about getting the right answer for infinity. If one
4734 // operand here is infinity and the other is anything other
4735 // than zero or NaN, then we are going to wind up subtracting
4736 // two infinity values. That will give us a NaN, but the
4737 // correct answer is infinity.
4741 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4745 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4749 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4753 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4755 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4756 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4758 // If we get NaN on both sides, check whether it should really
4759 // be infinity. The rule is that if either side of the
4760 // complex number is infinity, then the whole value is
4761 // infinity, even if the other side is NaN. So the only case
4762 // we have to fix is the one in which both sides are NaN.
4763 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4764 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4765 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4767 bool is_infinity = false;
4771 mpfr_init_set(lr, left_real, GMP_RNDN);
4772 mpfr_init_set(li, left_imag, GMP_RNDN);
4776 mpfr_init_set(rr, right_real, GMP_RNDN);
4777 mpfr_init_set(ri, right_imag, GMP_RNDN);
4779 // If the left side is infinity, then the result is
4781 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4783 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4784 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4785 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4786 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4789 mpfr_set_ui(rr, 0, GMP_RNDN);
4790 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4794 mpfr_set_ui(ri, 0, GMP_RNDN);
4795 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4800 // If the right side is infinity, then the result is
4802 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4804 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4805 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4806 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4807 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4810 mpfr_set_ui(lr, 0, GMP_RNDN);
4811 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4815 mpfr_set_ui(li, 0, GMP_RNDN);
4816 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4821 // If we got an overflow in the intermediate computations,
4822 // then the result is infinity.
4824 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4825 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4829 mpfr_set_ui(lr, 0, GMP_RNDN);
4830 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4834 mpfr_set_ui(li, 0, GMP_RNDN);
4835 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4839 mpfr_set_ui(rr, 0, GMP_RNDN);
4840 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4844 mpfr_set_ui(ri, 0, GMP_RNDN);
4845 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4852 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4853 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4854 mpfr_mul(lirr, li, rr, GMP_RNDN);
4855 mpfr_mul(liri, li, ri, GMP_RNDN);
4856 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4857 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4858 mpfr_set_inf(real, mpfr_sgn(real));
4859 mpfr_set_inf(imag, mpfr_sgn(imag));
4876 // For complex division we want to avoid having an
4877 // intermediate overflow turn the whole result in a NaN. We
4878 // scale the values to try to avoid this.
4880 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4882 error_at(location, "division by zero");
4883 mpfr_set_ui(real, 0, GMP_RNDN);
4884 mpfr_set_ui(imag, 0, GMP_RNDN);
4892 mpfr_abs(rra, right_real, GMP_RNDN);
4893 mpfr_abs(ria, right_imag, GMP_RNDN);
4896 mpfr_max(t, rra, ria, GMP_RNDN);
4900 mpfr_init_set(rr, right_real, GMP_RNDN);
4901 mpfr_init_set(ri, right_imag, GMP_RNDN);
4903 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4905 ilogbw = mpfr_get_exp(t);
4906 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4907 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4912 mpfr_mul(denom, rr, rr, GMP_RNDN);
4913 mpfr_mul(t, ri, ri, GMP_RNDN);
4914 mpfr_add(denom, denom, t, GMP_RNDN);
4916 mpfr_mul(real, left_real, rr, GMP_RNDN);
4917 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4918 mpfr_add(real, real, t, GMP_RNDN);
4919 mpfr_div(real, real, denom, GMP_RNDN);
4920 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4922 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4923 mpfr_mul(t, left_real, ri, GMP_RNDN);
4924 mpfr_sub(imag, imag, t, GMP_RNDN);
4925 mpfr_div(imag, imag, denom, GMP_RNDN);
4926 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4928 // If we wind up with NaN on both sides, check whether we
4929 // should really have infinity. The rule is that if either
4930 // side of the complex number is infinity, then the whole
4931 // value is infinity, even if the other side is NaN. So the
4932 // only case we have to fix is the one in which both sides are
4934 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4935 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4936 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4938 if (mpfr_zero_p(denom))
4940 mpfr_set_inf(real, mpfr_sgn(rr));
4941 mpfr_mul(real, real, left_real, GMP_RNDN);
4942 mpfr_set_inf(imag, mpfr_sgn(rr));
4943 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4945 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4946 && mpfr_number_p(rr) && mpfr_number_p(ri))
4948 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4949 mpfr_copysign(t, t, left_real, GMP_RNDN);
4952 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4953 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4957 mpfr_mul(t3, t, rr, GMP_RNDN);
4961 mpfr_mul(t4, t2, ri, GMP_RNDN);
4963 mpfr_add(t3, t3, t4, GMP_RNDN);
4964 mpfr_set_inf(real, mpfr_sgn(t3));
4966 mpfr_mul(t3, t2, rr, GMP_RNDN);
4967 mpfr_mul(t4, t, ri, GMP_RNDN);
4968 mpfr_sub(t3, t3, t4, GMP_RNDN);
4969 mpfr_set_inf(imag, mpfr_sgn(t3));
4975 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4976 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4978 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4979 mpfr_copysign(t, t, rr, GMP_RNDN);
4982 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4983 mpfr_copysign(t2, t2, ri, GMP_RNDN);
4987 mpfr_mul(t3, left_real, t, GMP_RNDN);
4991 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
4993 mpfr_add(t3, t3, t4, GMP_RNDN);
4994 mpfr_set_ui(real, 0, GMP_RNDN);
4995 mpfr_mul(real, real, t3, GMP_RNDN);
4997 mpfr_mul(t3, left_imag, t, GMP_RNDN);
4998 mpfr_mul(t4, left_real, t2, GMP_RNDN);
4999 mpfr_sub(t3, t3, t4, GMP_RNDN);
5000 mpfr_set_ui(imag, 0, GMP_RNDN);
5001 mpfr_mul(imag, imag, t3, GMP_RNDN);
5021 mpfr_clear(left_real);
5022 mpfr_clear(left_imag);
5023 mpfr_clear(right_real);
5024 mpfr_clear(right_imag);
5026 nc->set_complex(NULL, real, imag);
5033 // Lower a binary expression. We have to evaluate constant
5034 // expressions now, in order to implement Go's unlimited precision
5038 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5039 Statement_inserter* inserter, int)
5041 Location location = this->location();
5042 Operator op = this->op_;
5043 Expression* left = this->left_;
5044 Expression* right = this->right_;
5046 const bool is_comparison = (op == OPERATOR_EQEQ
5047 || op == OPERATOR_NOTEQ
5048 || op == OPERATOR_LT
5049 || op == OPERATOR_LE
5050 || op == OPERATOR_GT
5051 || op == OPERATOR_GE);
5053 // Numeric constant expressions.
5055 Numeric_constant left_nc;
5056 Numeric_constant right_nc;
5057 if (left->numeric_constant_value(&left_nc)
5058 && right->numeric_constant_value(&right_nc))
5063 if (!Binary_expression::compare_constant(op, &left_nc,
5064 &right_nc, location,
5067 return Expression::make_cast(Type::lookup_bool_type(),
5068 Expression::make_boolean(result,
5074 Numeric_constant nc;
5075 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5078 return nc.expression(location);
5083 // String constant expressions.
5084 if (left->type()->is_string_type() && right->type()->is_string_type())
5086 std::string left_string;
5087 std::string right_string;
5088 if (left->string_constant_value(&left_string)
5089 && right->string_constant_value(&right_string))
5091 if (op == OPERATOR_PLUS)
5092 return Expression::make_string(left_string + right_string,
5094 else if (is_comparison)
5096 int cmp = left_string.compare(right_string);
5097 bool r = Binary_expression::cmp_to_bool(op, cmp);
5098 return Expression::make_cast(Type::lookup_bool_type(),
5099 Expression::make_boolean(r,
5106 // Lower struct and array comparisons.
5107 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5109 if (left->type()->struct_type() != NULL)
5110 return this->lower_struct_comparison(gogo, inserter);
5111 else if (left->type()->array_type() != NULL
5112 && !left->type()->is_slice_type())
5113 return this->lower_array_comparison(gogo, inserter);
5119 // Lower a struct comparison.
5122 Binary_expression::lower_struct_comparison(Gogo* gogo,
5123 Statement_inserter* inserter)
5125 Struct_type* st = this->left_->type()->struct_type();
5126 Struct_type* st2 = this->right_->type()->struct_type();
5129 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5131 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5132 this->right_->type(), NULL))
5135 // See if we can compare using memcmp. As a heuristic, we use
5136 // memcmp rather than field references and comparisons if there are
5137 // more than two fields.
5138 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5139 return this->lower_compare_to_memcmp(gogo, inserter);
5141 Location loc = this->location();
5143 Expression* left = this->left_;
5144 Temporary_statement* left_temp = NULL;
5145 if (left->var_expression() == NULL
5146 && left->temporary_reference_expression() == NULL)
5148 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5149 inserter->insert(left_temp);
5150 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5153 Expression* right = this->right_;
5154 Temporary_statement* right_temp = NULL;
5155 if (right->var_expression() == NULL
5156 && right->temporary_reference_expression() == NULL)
5158 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5159 inserter->insert(right_temp);
5160 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5163 Expression* ret = Expression::make_boolean(true, loc);
5164 const Struct_field_list* fields = st->fields();
5165 unsigned int field_index = 0;
5166 for (Struct_field_list::const_iterator pf = fields->begin();
5167 pf != fields->end();
5168 ++pf, ++field_index)
5170 if (field_index > 0)
5172 if (left_temp == NULL)
5173 left = left->copy();
5175 left = Expression::make_temporary_reference(left_temp, loc);
5176 if (right_temp == NULL)
5177 right = right->copy();
5179 right = Expression::make_temporary_reference(right_temp, loc);
5181 Expression* f1 = Expression::make_field_reference(left, field_index,
5183 Expression* f2 = Expression::make_field_reference(right, field_index,
5185 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5186 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5189 if (this->op_ == OPERATOR_NOTEQ)
5190 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5195 // Lower an array comparison.
5198 Binary_expression::lower_array_comparison(Gogo* gogo,
5199 Statement_inserter* inserter)
5201 Array_type* at = this->left_->type()->array_type();
5202 Array_type* at2 = this->right_->type()->array_type();
5205 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5207 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5208 this->right_->type(), NULL))
5211 // Call memcmp directly if possible. This may let the middle-end
5212 // optimize the call.
5213 if (at->compare_is_identity(gogo))
5214 return this->lower_compare_to_memcmp(gogo, inserter);
5216 // Call the array comparison function.
5217 Named_object* hash_fn;
5218 Named_object* equal_fn;
5219 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5220 &hash_fn, &equal_fn);
5222 Location loc = this->location();
5224 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5226 Expression_list* args = new Expression_list();
5227 args->push_back(this->operand_address(inserter, this->left_));
5228 args->push_back(this->operand_address(inserter, this->right_));
5229 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5231 Expression* ret = Expression::make_call(func, args, false, loc);
5233 if (this->op_ == OPERATOR_NOTEQ)
5234 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5239 // Lower a struct or array comparison to a call to memcmp.
5242 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5244 Location loc = this->location();
5246 Expression* a1 = this->operand_address(inserter, this->left_);
5247 Expression* a2 = this->operand_address(inserter, this->right_);
5248 Expression* len = Expression::make_type_info(this->left_->type(),
5251 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5254 mpz_init_set_ui(zval, 0);
5255 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5258 return Expression::make_binary(this->op_, call, zero, loc);
5261 // Return the address of EXPR, cast to unsafe.Pointer.
5264 Binary_expression::operand_address(Statement_inserter* inserter,
5267 Location loc = this->location();
5269 if (!expr->is_addressable())
5271 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5273 inserter->insert(temp);
5274 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5276 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5277 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5278 Type* void_type = Type::make_void_type();
5279 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5280 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5283 // Return the numeric constant value, if it has one.
5286 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5288 Operator op = this->op_;
5290 if (op == OPERATOR_EQEQ
5291 || op == OPERATOR_NOTEQ
5292 || op == OPERATOR_LT
5293 || op == OPERATOR_LE
5294 || op == OPERATOR_GT
5295 || op == OPERATOR_GE)
5298 Numeric_constant left_nc;
5299 if (!this->left_->numeric_constant_value(&left_nc))
5301 Numeric_constant right_nc;
5302 if (!this->right_->numeric_constant_value(&right_nc))
5305 return Binary_expression::eval_constant(op, &left_nc, &right_nc,
5306 this->location(), nc);
5309 // Note that the value is being discarded.
5312 Binary_expression::do_discarding_value()
5314 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5315 this->right_->discarding_value();
5317 this->unused_value_error();
5323 Binary_expression::do_type()
5325 if (this->classification() == EXPRESSION_ERROR)
5326 return Type::make_error_type();
5331 case OPERATOR_ANDAND:
5333 case OPERATOR_NOTEQ:
5338 return Type::lookup_bool_type();
5341 case OPERATOR_MINUS:
5348 case OPERATOR_BITCLEAR:
5351 if (!Binary_expression::operation_type(this->op_,
5352 this->left_->type(),
5353 this->right_->type(),
5355 return Type::make_error_type();
5359 case OPERATOR_LSHIFT:
5360 case OPERATOR_RSHIFT:
5361 return this->left_->type();
5368 // Set type for a binary expression.
5371 Binary_expression::do_determine_type(const Type_context* context)
5373 Type* tleft = this->left_->type();
5374 Type* tright = this->right_->type();
5376 // Both sides should have the same type, except for the shift
5377 // operations. For a comparison, we should ignore the incoming
5380 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5381 || this->op_ == OPERATOR_RSHIFT);
5383 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5384 || this->op_ == OPERATOR_NOTEQ
5385 || this->op_ == OPERATOR_LT
5386 || this->op_ == OPERATOR_LE
5387 || this->op_ == OPERATOR_GT
5388 || this->op_ == OPERATOR_GE);
5390 Type_context subcontext(*context);
5394 // In a comparison, the context does not determine the types of
5396 subcontext.type = NULL;
5399 // Set the context for the left hand operand.
5402 // The right hand operand of a shift plays no role in
5403 // determining the type of the left hand operand.
5405 else if (!tleft->is_abstract())
5406 subcontext.type = tleft;
5407 else if (!tright->is_abstract())
5408 subcontext.type = tright;
5409 else if (subcontext.type == NULL)
5411 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5412 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5413 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5415 // Both sides have an abstract integer, abstract float, or
5416 // abstract complex type. Just let CONTEXT determine
5417 // whether they may remain abstract or not.
5419 else if (tleft->complex_type() != NULL)
5420 subcontext.type = tleft;
5421 else if (tright->complex_type() != NULL)
5422 subcontext.type = tright;
5423 else if (tleft->float_type() != NULL)
5424 subcontext.type = tleft;
5425 else if (tright->float_type() != NULL)
5426 subcontext.type = tright;
5428 subcontext.type = tleft;
5430 if (subcontext.type != NULL && !context->may_be_abstract)
5431 subcontext.type = subcontext.type->make_non_abstract_type();
5434 this->left_->determine_type(&subcontext);
5438 // We may have inherited an unusable type for the shift operand.
5439 // Give a useful error if that happened.
5440 if (tleft->is_abstract()
5441 && subcontext.type != NULL
5442 && (this->left_->type()->integer_type() == NULL
5443 || (subcontext.type->integer_type() == NULL
5444 && subcontext.type->float_type() == NULL
5445 && subcontext.type->complex_type() == NULL)))
5446 this->report_error(("invalid context-determined non-integer type "
5447 "for shift operand"));
5449 // The context for the right hand operand is the same as for the
5450 // left hand operand, except for a shift operator.
5451 subcontext.type = Type::lookup_integer_type("uint");
5452 subcontext.may_be_abstract = false;
5455 this->right_->determine_type(&subcontext);
5458 // Report an error if the binary operator OP does not support TYPE.
5459 // OTYPE is the type of the other operand. Return whether the
5460 // operation is OK. This should not be used for shift.
5463 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5469 case OPERATOR_ANDAND:
5470 if (!type->is_boolean_type())
5472 error_at(location, "expected boolean type");
5478 case OPERATOR_NOTEQ:
5481 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5483 error_at(location, "%s", reason.c_str());
5495 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5497 error_at(location, "%s", reason.c_str());
5504 case OPERATOR_PLUSEQ:
5505 if (type->integer_type() == NULL
5506 && type->float_type() == NULL
5507 && type->complex_type() == NULL
5508 && !type->is_string_type())
5511 "expected integer, floating, complex, or string type");
5516 case OPERATOR_MINUS:
5517 case OPERATOR_MINUSEQ:
5519 case OPERATOR_MULTEQ:
5521 case OPERATOR_DIVEQ:
5522 if (type->integer_type() == NULL
5523 && type->float_type() == NULL
5524 && type->complex_type() == NULL)
5526 error_at(location, "expected integer, floating, or complex type");
5532 case OPERATOR_MODEQ:
5536 case OPERATOR_ANDEQ:
5538 case OPERATOR_XOREQ:
5539 case OPERATOR_BITCLEAR:
5540 case OPERATOR_BITCLEAREQ:
5541 if (type->integer_type() == NULL)
5543 error_at(location, "expected integer type");
5558 Binary_expression::do_check_types(Gogo*)
5560 if (this->classification() == EXPRESSION_ERROR)
5563 Type* left_type = this->left_->type();
5564 Type* right_type = this->right_->type();
5565 if (left_type->is_error() || right_type->is_error())
5567 this->set_is_error();
5571 if (this->op_ == OPERATOR_EQEQ
5572 || this->op_ == OPERATOR_NOTEQ
5573 || this->op_ == OPERATOR_LT
5574 || this->op_ == OPERATOR_LE
5575 || this->op_ == OPERATOR_GT
5576 || this->op_ == OPERATOR_GE)
5578 if (!Type::are_assignable(left_type, right_type, NULL)
5579 && !Type::are_assignable(right_type, left_type, NULL))
5581 this->report_error(_("incompatible types in binary expression"));
5584 if (!Binary_expression::check_operator_type(this->op_, left_type,
5587 || !Binary_expression::check_operator_type(this->op_, right_type,
5591 this->set_is_error();
5595 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5597 if (!Type::are_compatible_for_binop(left_type, right_type))
5599 this->report_error(_("incompatible types in binary expression"));
5602 if (!Binary_expression::check_operator_type(this->op_, left_type,
5606 this->set_is_error();
5612 if (left_type->integer_type() == NULL)
5613 this->report_error(_("shift of non-integer operand"));
5615 if (!right_type->is_abstract()
5616 && (right_type->integer_type() == NULL
5617 || !right_type->integer_type()->is_unsigned()))
5618 this->report_error(_("shift count not unsigned integer"));
5621 Numeric_constant nc;
5622 if (this->right_->numeric_constant_value(&nc))
5625 if (!nc.to_int(&val))
5626 this->report_error(_("shift count not unsigned integer"));
5629 if (mpz_sgn(val) < 0)
5631 this->report_error(_("negative shift count"));
5633 Location rloc = this->right_->location();
5634 this->right_ = Expression::make_integer(&val, right_type,
5644 // Get a tree for a binary expression.
5647 Binary_expression::do_get_tree(Translate_context* context)
5649 tree left = this->left_->get_tree(context);
5650 tree right = this->right_->get_tree(context);
5652 if (left == error_mark_node || right == error_mark_node)
5653 return error_mark_node;
5655 enum tree_code code;
5656 bool use_left_type = true;
5657 bool is_shift_op = false;
5658 bool is_idiv_op = false;
5662 case OPERATOR_NOTEQ:
5667 return Expression::comparison_tree(context, this->op_,
5668 this->left_->type(), left,
5669 this->right_->type(), right,
5673 code = TRUTH_ORIF_EXPR;
5674 use_left_type = false;
5676 case OPERATOR_ANDAND:
5677 code = TRUTH_ANDIF_EXPR;
5678 use_left_type = false;
5683 case OPERATOR_MINUS:
5687 code = BIT_IOR_EXPR;
5690 code = BIT_XOR_EXPR;
5697 Type *t = this->left_->type();
5698 if (t->float_type() != NULL || t->complex_type() != NULL)
5702 code = TRUNC_DIV_EXPR;
5708 code = TRUNC_MOD_EXPR;
5711 case OPERATOR_LSHIFT:
5715 case OPERATOR_RSHIFT:
5720 code = BIT_AND_EXPR;
5722 case OPERATOR_BITCLEAR:
5723 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5724 code = BIT_AND_EXPR;
5730 location_t gccloc = this->location().gcc_location();
5731 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5733 if (this->left_->type()->is_string_type())
5735 go_assert(this->op_ == OPERATOR_PLUS);
5736 Type* st = Type::make_string_type();
5737 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5738 static tree string_plus_decl;
5739 return Gogo::call_builtin(&string_plus_decl,
5750 tree compute_type = excess_precision_type(type);
5751 if (compute_type != NULL_TREE)
5753 left = ::convert(compute_type, left);
5754 right = ::convert(compute_type, right);
5757 tree eval_saved = NULL_TREE;
5759 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5761 // Make sure the values are evaluated.
5764 left = save_expr(left);
5769 right = save_expr(right);
5770 if (eval_saved == NULL_TREE)
5773 eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
5774 void_type_node, eval_saved, right);
5778 tree ret = fold_build2_loc(gccloc, code,
5779 compute_type != NULL_TREE ? compute_type : type,
5782 if (compute_type != NULL_TREE)
5783 ret = ::convert(type, ret);
5785 // In Go, a shift larger than the size of the type is well-defined.
5786 // This is not true in GENERIC, so we need to insert a conditional.
5789 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5790 go_assert(this->left_->type()->integer_type() != NULL);
5791 int bits = TYPE_PRECISION(TREE_TYPE(left));
5793 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5794 build_int_cst_type(TREE_TYPE(right), bits));
5796 tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
5798 if (this->op_ == OPERATOR_RSHIFT
5799 && !this->left_->type()->integer_type()->is_unsigned())
5802 fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
5804 fold_convert_loc(gccloc, TREE_TYPE(left),
5805 integer_zero_node));
5807 fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
5808 fold_convert_loc(gccloc, TREE_TYPE(left),
5810 fold_convert_loc(gccloc, TREE_TYPE(left),
5813 fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5814 neg, neg_one, overflow_result);
5817 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5818 compare, ret, overflow_result);
5820 if (eval_saved != NULL_TREE)
5821 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5825 // Add checks for division by zero and division overflow as needed.
5828 if (go_check_divide_zero)
5831 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5833 fold_convert_loc(gccloc,
5835 integer_zero_node));
5837 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
5838 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5839 tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5840 Gogo::runtime_error(errcode,
5842 fold_convert_loc(gccloc, TREE_TYPE(ret),
5843 integer_zero_node));
5845 // right == 0 ? (__go_runtime_error(...), 0) : ret
5846 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5850 if (go_check_divide_overflow)
5853 // FIXME: It would be nice to say that this test is expected
5855 tree m1 = integer_minus_one_node;
5856 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5858 fold_convert_loc(gccloc,
5863 if (TYPE_UNSIGNED(TREE_TYPE(ret)))
5865 // An unsigned -1 is the largest possible number, so
5866 // dividing is always 1 or 0.
5867 tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5869 if (this->op_ == OPERATOR_DIV)
5870 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5872 fold_convert_loc(gccloc,
5875 fold_convert_loc(gccloc,
5877 integer_zero_node));
5879 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5881 fold_convert_loc(gccloc,
5888 // Computing left / -1 is the same as computing - left,
5889 // which does not overflow since Go sets -fwrapv.
5890 if (this->op_ == OPERATOR_DIV)
5891 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
5894 overflow = integer_zero_node;
5896 overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
5898 // right == -1 ? - left : ret
5899 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5900 check, overflow, ret);
5903 if (eval_saved != NULL_TREE)
5904 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5911 // Export a binary expression.
5914 Binary_expression::do_export(Export* exp) const
5916 exp->write_c_string("(");
5917 this->left_->export_expression(exp);
5921 exp->write_c_string(" || ");
5923 case OPERATOR_ANDAND:
5924 exp->write_c_string(" && ");
5927 exp->write_c_string(" == ");
5929 case OPERATOR_NOTEQ:
5930 exp->write_c_string(" != ");
5933 exp->write_c_string(" < ");
5936 exp->write_c_string(" <= ");
5939 exp->write_c_string(" > ");
5942 exp->write_c_string(" >= ");
5945 exp->write_c_string(" + ");
5947 case OPERATOR_MINUS:
5948 exp->write_c_string(" - ");
5951 exp->write_c_string(" | ");
5954 exp->write_c_string(" ^ ");
5957 exp->write_c_string(" * ");
5960 exp->write_c_string(" / ");
5963 exp->write_c_string(" % ");
5965 case OPERATOR_LSHIFT:
5966 exp->write_c_string(" << ");
5968 case OPERATOR_RSHIFT:
5969 exp->write_c_string(" >> ");
5972 exp->write_c_string(" & ");
5974 case OPERATOR_BITCLEAR:
5975 exp->write_c_string(" &^ ");
5980 this->right_->export_expression(exp);
5981 exp->write_c_string(")");
5984 // Import a binary expression.
5987 Binary_expression::do_import(Import* imp)
5989 imp->require_c_string("(");
5991 Expression* left = Expression::import_expression(imp);
5994 if (imp->match_c_string(" || "))
5999 else if (imp->match_c_string(" && "))
6001 op = OPERATOR_ANDAND;
6004 else if (imp->match_c_string(" == "))
6009 else if (imp->match_c_string(" != "))
6011 op = OPERATOR_NOTEQ;
6014 else if (imp->match_c_string(" < "))
6019 else if (imp->match_c_string(" <= "))
6024 else if (imp->match_c_string(" > "))
6029 else if (imp->match_c_string(" >= "))
6034 else if (imp->match_c_string(" + "))
6039 else if (imp->match_c_string(" - "))
6041 op = OPERATOR_MINUS;
6044 else if (imp->match_c_string(" | "))
6049 else if (imp->match_c_string(" ^ "))
6054 else if (imp->match_c_string(" * "))
6059 else if (imp->match_c_string(" / "))
6064 else if (imp->match_c_string(" % "))
6069 else if (imp->match_c_string(" << "))
6071 op = OPERATOR_LSHIFT;
6074 else if (imp->match_c_string(" >> "))
6076 op = OPERATOR_RSHIFT;
6079 else if (imp->match_c_string(" & "))
6084 else if (imp->match_c_string(" &^ "))
6086 op = OPERATOR_BITCLEAR;
6091 error_at(imp->location(), "unrecognized binary operator");
6092 return Expression::make_error(imp->location());
6095 Expression* right = Expression::import_expression(imp);
6097 imp->require_c_string(")");
6099 return Expression::make_binary(op, left, right, imp->location());
6102 // Dump ast representation of a binary expression.
6105 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6107 ast_dump_context->ostream() << "(";
6108 ast_dump_context->dump_expression(this->left_);
6109 ast_dump_context->ostream() << " ";
6110 ast_dump_context->dump_operator(this->op_);
6111 ast_dump_context->ostream() << " ";
6112 ast_dump_context->dump_expression(this->right_);
6113 ast_dump_context->ostream() << ") ";
6116 // Make a binary expression.
6119 Expression::make_binary(Operator op, Expression* left, Expression* right,
6122 return new Binary_expression(op, left, right, location);
6125 // Implement a comparison.
6128 Expression::comparison_tree(Translate_context* context, Operator op,
6129 Type* left_type, tree left_tree,
6130 Type* right_type, tree right_tree,
6133 enum tree_code code;
6139 case OPERATOR_NOTEQ:
6158 if (left_type->is_string_type() && right_type->is_string_type())
6160 Type* st = Type::make_string_type();
6161 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6162 static tree string_compare_decl;
6163 left_tree = Gogo::call_builtin(&string_compare_decl,
6172 right_tree = build_int_cst_type(integer_type_node, 0);
6174 else if ((left_type->interface_type() != NULL
6175 && right_type->interface_type() == NULL
6176 && !right_type->is_nil_type())
6177 || (left_type->interface_type() == NULL
6178 && !left_type->is_nil_type()
6179 && right_type->interface_type() != NULL))
6181 // Comparing an interface value to a non-interface value.
6182 if (left_type->interface_type() == NULL)
6184 std::swap(left_type, right_type);
6185 std::swap(left_tree, right_tree);
6188 // The right operand is not an interface. We need to take its
6189 // address if it is not a pointer.
6192 if (right_type->points_to() != NULL)
6194 make_tmp = NULL_TREE;
6197 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree))
6198 || (TREE_CODE(right_tree) != CONST_DECL
6199 && DECL_P(right_tree)))
6201 make_tmp = NULL_TREE;
6202 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6203 if (DECL_P(right_tree))
6204 TREE_ADDRESSABLE(right_tree) = 1;
6208 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6209 get_name(right_tree));
6210 DECL_IGNORED_P(tmp) = 0;
6211 DECL_INITIAL(tmp) = right_tree;
6212 TREE_ADDRESSABLE(tmp) = 1;
6213 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6214 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6215 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6217 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6219 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6222 if (left_type->interface_type()->is_empty())
6224 static tree empty_interface_value_compare_decl;
6225 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6227 "__go_empty_interface_value_compare",
6230 TREE_TYPE(left_tree),
6232 TREE_TYPE(descriptor),
6236 if (left_tree == error_mark_node)
6237 return error_mark_node;
6238 // This can panic if the type is not comparable.
6239 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6243 static tree interface_value_compare_decl;
6244 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6246 "__go_interface_value_compare",
6249 TREE_TYPE(left_tree),
6251 TREE_TYPE(descriptor),
6255 if (left_tree == error_mark_node)
6256 return error_mark_node;
6257 // This can panic if the type is not comparable.
6258 TREE_NOTHROW(interface_value_compare_decl) = 0;
6260 right_tree = build_int_cst_type(integer_type_node, 0);
6262 if (make_tmp != NULL_TREE)
6263 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6266 else if (left_type->interface_type() != NULL
6267 && right_type->interface_type() != NULL)
6269 if (left_type->interface_type()->is_empty()
6270 && right_type->interface_type()->is_empty())
6272 static tree empty_interface_compare_decl;
6273 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6275 "__go_empty_interface_compare",
6278 TREE_TYPE(left_tree),
6280 TREE_TYPE(right_tree),
6282 if (left_tree == error_mark_node)
6283 return error_mark_node;
6284 // This can panic if the type is uncomparable.
6285 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6287 else if (!left_type->interface_type()->is_empty()
6288 && !right_type->interface_type()->is_empty())
6290 static tree interface_compare_decl;
6291 left_tree = Gogo::call_builtin(&interface_compare_decl,
6293 "__go_interface_compare",
6296 TREE_TYPE(left_tree),
6298 TREE_TYPE(right_tree),
6300 if (left_tree == error_mark_node)
6301 return error_mark_node;
6302 // This can panic if the type is uncomparable.
6303 TREE_NOTHROW(interface_compare_decl) = 0;
6307 if (left_type->interface_type()->is_empty())
6309 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6310 std::swap(left_type, right_type);
6311 std::swap(left_tree, right_tree);
6313 go_assert(!left_type->interface_type()->is_empty());
6314 go_assert(right_type->interface_type()->is_empty());
6315 static tree interface_empty_compare_decl;
6316 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6318 "__go_interface_empty_compare",
6321 TREE_TYPE(left_tree),
6323 TREE_TYPE(right_tree),
6325 if (left_tree == error_mark_node)
6326 return error_mark_node;
6327 // This can panic if the type is uncomparable.
6328 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6331 right_tree = build_int_cst_type(integer_type_node, 0);
6334 if (left_type->is_nil_type()
6335 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6337 std::swap(left_type, right_type);
6338 std::swap(left_tree, right_tree);
6341 if (right_type->is_nil_type())
6343 if (left_type->array_type() != NULL
6344 && left_type->array_type()->length() == NULL)
6346 Array_type* at = left_type->array_type();
6347 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6348 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6350 else if (left_type->interface_type() != NULL)
6352 // An interface is nil if the first field is nil.
6353 tree left_type_tree = TREE_TYPE(left_tree);
6354 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6355 tree field = TYPE_FIELDS(left_type_tree);
6356 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6358 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6362 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6363 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6367 if (left_tree == error_mark_node || right_tree == error_mark_node)
6368 return error_mark_node;
6370 tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6371 if (CAN_HAVE_LOCATION_P(ret))
6372 SET_EXPR_LOCATION(ret, location.gcc_location());
6376 // Class Bound_method_expression.
6381 Bound_method_expression::do_traverse(Traverse* traverse)
6383 return Expression::traverse(&this->expr_, traverse);
6386 // Return the type of a bound method expression. The type of this
6387 // object is really the type of the method with no receiver. We
6388 // should be able to get away with just returning the type of the
6392 Bound_method_expression::do_type()
6394 if (this->method_->is_function())
6395 return this->method_->func_value()->type();
6396 else if (this->method_->is_function_declaration())
6397 return this->method_->func_declaration_value()->type();
6399 return Type::make_error_type();
6402 // Determine the types of a method expression.
6405 Bound_method_expression::do_determine_type(const Type_context*)
6407 Function_type* fntype = this->type()->function_type();
6408 if (fntype == NULL || !fntype->is_method())
6409 this->expr_->determine_type_no_context();
6412 Type_context subcontext(fntype->receiver()->type(), false);
6413 this->expr_->determine_type(&subcontext);
6417 // Check the types of a method expression.
6420 Bound_method_expression::do_check_types(Gogo*)
6422 if (!this->method_->is_function()
6423 && !this->method_->is_function_declaration())
6424 this->report_error(_("object is not a method"));
6427 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6428 Type* etype = (this->expr_type_ != NULL
6430 : this->expr_->type());
6431 etype = etype->deref();
6432 if (!Type::are_identical(rtype, etype, true, NULL))
6433 this->report_error(_("method type does not match object type"));
6437 // Get the tree for a method expression. There is no standard tree
6438 // representation for this. The only places it may currently be used
6439 // are in a Call_expression or a Go_statement, which will take it
6440 // apart directly. So this has nothing to do at present.
6443 Bound_method_expression::do_get_tree(Translate_context*)
6445 error_at(this->location(), "reference to method other than calling it");
6446 return error_mark_node;
6449 // Dump ast representation of a bound method expression.
6452 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6455 if (this->expr_type_ != NULL)
6456 ast_dump_context->ostream() << "(";
6457 ast_dump_context->dump_expression(this->expr_);
6458 if (this->expr_type_ != NULL)
6460 ast_dump_context->ostream() << ":";
6461 ast_dump_context->dump_type(this->expr_type_);
6462 ast_dump_context->ostream() << ")";
6465 ast_dump_context->ostream() << "." << this->method_->name();
6468 // Make a method expression.
6470 Bound_method_expression*
6471 Expression::make_bound_method(Expression* expr, Named_object* method,
6474 return new Bound_method_expression(expr, method, location);
6477 // Class Builtin_call_expression. This is used for a call to a
6478 // builtin function.
6480 class Builtin_call_expression : public Call_expression
6483 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6484 bool is_varargs, Location location);
6487 // This overrides Call_expression::do_lower.
6489 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6492 do_is_constant() const;
6495 do_numeric_constant_value(Numeric_constant*) const;
6498 do_discarding_value();
6504 do_determine_type(const Type_context*);
6507 do_check_types(Gogo*);
6512 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6513 this->args()->copy(),
6519 do_get_tree(Translate_context*);
6522 do_export(Export*) const;
6525 do_is_recover_call() const;
6528 do_set_recover_arg(Expression*);
6531 // The builtin functions.
6532 enum Builtin_function_code
6536 // Predeclared builtin functions.
6553 // Builtin functions from the unsafe package.
6566 real_imag_type(Type*);
6569 complex_type(Type*);
6575 check_int_value(Expression*);
6577 // A pointer back to the general IR structure. This avoids a global
6578 // variable, or passing it around everywhere.
6580 // The builtin function being called.
6581 Builtin_function_code code_;
6582 // Used to stop endless loops when the length of an array uses len
6583 // or cap of the array itself.
6587 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6589 Expression_list* args,
6592 : Call_expression(fn, args, is_varargs, location),
6593 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6595 Func_expression* fnexp = this->fn()->func_expression();
6596 go_assert(fnexp != NULL);
6597 const std::string& name(fnexp->named_object()->name());
6598 if (name == "append")
6599 this->code_ = BUILTIN_APPEND;
6600 else if (name == "cap")
6601 this->code_ = BUILTIN_CAP;
6602 else if (name == "close")
6603 this->code_ = BUILTIN_CLOSE;
6604 else if (name == "complex")
6605 this->code_ = BUILTIN_COMPLEX;
6606 else if (name == "copy")
6607 this->code_ = BUILTIN_COPY;
6608 else if (name == "delete")
6609 this->code_ = BUILTIN_DELETE;
6610 else if (name == "imag")
6611 this->code_ = BUILTIN_IMAG;
6612 else if (name == "len")
6613 this->code_ = BUILTIN_LEN;
6614 else if (name == "make")
6615 this->code_ = BUILTIN_MAKE;
6616 else if (name == "new")
6617 this->code_ = BUILTIN_NEW;
6618 else if (name == "panic")
6619 this->code_ = BUILTIN_PANIC;
6620 else if (name == "print")
6621 this->code_ = BUILTIN_PRINT;
6622 else if (name == "println")
6623 this->code_ = BUILTIN_PRINTLN;
6624 else if (name == "real")
6625 this->code_ = BUILTIN_REAL;
6626 else if (name == "recover")
6627 this->code_ = BUILTIN_RECOVER;
6628 else if (name == "Alignof")
6629 this->code_ = BUILTIN_ALIGNOF;
6630 else if (name == "Offsetof")
6631 this->code_ = BUILTIN_OFFSETOF;
6632 else if (name == "Sizeof")
6633 this->code_ = BUILTIN_SIZEOF;
6638 // Return whether this is a call to recover. This is a virtual
6639 // function called from the parent class.
6642 Builtin_call_expression::do_is_recover_call() const
6644 if (this->classification() == EXPRESSION_ERROR)
6646 return this->code_ == BUILTIN_RECOVER;
6649 // Set the argument for a call to recover.
6652 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6654 const Expression_list* args = this->args();
6655 go_assert(args == NULL || args->empty());
6656 Expression_list* new_args = new Expression_list();
6657 new_args->push_back(arg);
6658 this->set_args(new_args);
6661 // A traversal class which looks for a call expression.
6663 class Find_call_expression : public Traverse
6666 Find_call_expression()
6667 : Traverse(traverse_expressions),
6672 expression(Expression**);
6676 { return this->found_; }
6683 Find_call_expression::expression(Expression** pexpr)
6685 if ((*pexpr)->call_expression() != NULL)
6687 this->found_ = true;
6688 return TRAVERSE_EXIT;
6690 return TRAVERSE_CONTINUE;
6693 // Lower a builtin call expression. This turns new and make into
6694 // specific expressions. We also convert to a constant if we can.
6697 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6698 Statement_inserter* inserter, int)
6700 if (this->classification() == EXPRESSION_ERROR)
6703 Location loc = this->location();
6705 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6707 this->report_error(_("invalid use of %<...%> with builtin function"));
6708 return Expression::make_error(loc);
6711 if (this->is_constant())
6713 // We can only lower len and cap if there are no function calls
6714 // in the arguments. Otherwise we have to make the call.
6715 if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6717 Expression* arg = this->one_arg();
6718 if (arg != NULL && !arg->is_constant())
6720 Find_call_expression find_call;
6721 Expression::traverse(&arg, &find_call);
6722 if (find_call.found())
6727 Numeric_constant nc;
6728 if (this->numeric_constant_value(&nc))
6729 return nc.expression(loc);
6732 switch (this->code_)
6739 const Expression_list* args = this->args();
6740 if (args == NULL || args->size() < 1)
6741 this->report_error(_("not enough arguments"));
6742 else if (args->size() > 1)
6743 this->report_error(_("too many arguments"));
6746 Expression* arg = args->front();
6747 if (!arg->is_type_expression())
6749 error_at(arg->location(), "expected type");
6750 this->set_is_error();
6753 return Expression::make_allocation(arg->type(), loc);
6759 return this->lower_make();
6761 case BUILTIN_RECOVER:
6762 if (function != NULL)
6763 function->func_value()->set_calls_recover();
6766 // Calling recover outside of a function always returns the
6767 // nil empty interface.
6768 Type* eface = Type::make_empty_interface_type(loc);
6769 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6773 case BUILTIN_APPEND:
6775 // Lower the varargs.
6776 const Expression_list* args = this->args();
6777 if (args == NULL || args->empty())
6779 Type* slice_type = args->front()->type();
6780 if (!slice_type->is_slice_type())
6782 error_at(args->front()->location(), "argument 1 must be a slice");
6783 this->set_is_error();
6786 Type* element_type = slice_type->array_type()->element_type();
6787 this->lower_varargs(gogo, function, inserter,
6788 Type::make_array_type(element_type, NULL),
6793 case BUILTIN_DELETE:
6795 // Lower to a runtime function call.
6796 const Expression_list* args = this->args();
6797 if (args == NULL || args->size() < 2)
6798 this->report_error(_("not enough arguments"));
6799 else if (args->size() > 2)
6800 this->report_error(_("too many arguments"));
6801 else if (args->front()->type()->map_type() == NULL)
6802 this->report_error(_("argument 1 must be a map"));
6805 // Since this function returns no value it must appear in
6806 // a statement by itself, so we don't have to worry about
6807 // order of evaluation of values around it. Evaluate the
6808 // map first to get order of evaluation right.
6809 Map_type* mt = args->front()->type()->map_type();
6810 Temporary_statement* map_temp =
6811 Statement::make_temporary(mt, args->front(), loc);
6812 inserter->insert(map_temp);
6814 Temporary_statement* key_temp =
6815 Statement::make_temporary(mt->key_type(), args->back(), loc);
6816 inserter->insert(key_temp);
6818 Expression* e1 = Expression::make_temporary_reference(map_temp,
6820 Expression* e2 = Expression::make_temporary_reference(key_temp,
6822 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6823 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6833 // Lower a make expression.
6836 Builtin_call_expression::lower_make()
6838 Location loc = this->location();
6840 const Expression_list* args = this->args();
6841 if (args == NULL || args->size() < 1)
6843 this->report_error(_("not enough arguments"));
6844 return Expression::make_error(this->location());
6847 Expression_list::const_iterator parg = args->begin();
6849 Expression* first_arg = *parg;
6850 if (!first_arg->is_type_expression())
6852 error_at(first_arg->location(), "expected type");
6853 this->set_is_error();
6854 return Expression::make_error(this->location());
6856 Type* type = first_arg->type();
6858 bool is_slice = false;
6859 bool is_map = false;
6860 bool is_chan = false;
6861 if (type->is_slice_type())
6863 else if (type->map_type() != NULL)
6865 else if (type->channel_type() != NULL)
6869 this->report_error(_("invalid type for make function"));
6870 return Expression::make_error(this->location());
6873 bool have_big_args = false;
6874 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6875 int uintptr_bits = uintptr_type->integer_type()->bits();
6878 Expression* len_arg;
6879 if (parg == args->end())
6883 this->report_error(_("length required when allocating a slice"));
6884 return Expression::make_error(this->location());
6888 mpz_init_set_ui(zval, 0);
6889 len_arg = Expression::make_integer(&zval, NULL, loc);
6895 if (!this->check_int_value(len_arg))
6897 this->report_error(_("bad size for make"));
6898 return Expression::make_error(this->location());
6900 if (len_arg->type()->integer_type() != NULL
6901 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6902 have_big_args = true;
6906 Expression* cap_arg = NULL;
6907 if (is_slice && parg != args->end())
6910 if (!this->check_int_value(cap_arg))
6912 this->report_error(_("bad capacity when making slice"));
6913 return Expression::make_error(this->location());
6915 if (cap_arg->type()->integer_type() != NULL
6916 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6917 have_big_args = true;
6921 if (parg != args->end())
6923 this->report_error(_("too many arguments to make"));
6924 return Expression::make_error(this->location());
6927 Location type_loc = first_arg->location();
6928 Expression* type_arg;
6929 if (is_slice || is_chan)
6930 type_arg = Expression::make_type_descriptor(type, type_loc);
6932 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6939 if (cap_arg == NULL)
6940 call = Runtime::make_call((have_big_args
6941 ? Runtime::MAKESLICE1BIG
6942 : Runtime::MAKESLICE1),
6943 loc, 2, type_arg, len_arg);
6945 call = Runtime::make_call((have_big_args
6946 ? Runtime::MAKESLICE2BIG
6947 : Runtime::MAKESLICE2),
6948 loc, 3, type_arg, len_arg, cap_arg);
6951 call = Runtime::make_call((have_big_args
6952 ? Runtime::MAKEMAPBIG
6953 : Runtime::MAKEMAP),
6954 loc, 2, type_arg, len_arg);
6956 call = Runtime::make_call((have_big_args
6957 ? Runtime::MAKECHANBIG
6958 : Runtime::MAKECHAN),
6959 loc, 2, type_arg, len_arg);
6963 return Expression::make_unsafe_cast(type, call, loc);
6966 // Return whether an expression has an integer value. Report an error
6967 // if not. This is used when handling calls to the predeclared make
6971 Builtin_call_expression::check_int_value(Expression* e)
6973 if (e->type()->integer_type() != NULL)
6976 // Check for a floating point constant with integer value.
6977 Numeric_constant nc;
6979 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6988 // Return the type of the real or imag functions, given the type of
6989 // the argument. We need to map complex to float, complex64 to
6990 // float32, and complex128 to float64, so it has to be done by name.
6991 // This returns NULL if it can't figure out the type.
6994 Builtin_call_expression::real_imag_type(Type* arg_type)
6996 if (arg_type == NULL || arg_type->is_abstract())
6998 Named_type* nt = arg_type->named_type();
7001 while (nt->real_type()->named_type() != NULL)
7002 nt = nt->real_type()->named_type();
7003 if (nt->name() == "complex64")
7004 return Type::lookup_float_type("float32");
7005 else if (nt->name() == "complex128")
7006 return Type::lookup_float_type("float64");
7011 // Return the type of the complex function, given the type of one of the
7012 // argments. Like real_imag_type, we have to map by name.
7015 Builtin_call_expression::complex_type(Type* arg_type)
7017 if (arg_type == NULL || arg_type->is_abstract())
7019 Named_type* nt = arg_type->named_type();
7022 while (nt->real_type()->named_type() != NULL)
7023 nt = nt->real_type()->named_type();
7024 if (nt->name() == "float32")
7025 return Type::lookup_complex_type("complex64");
7026 else if (nt->name() == "float64")
7027 return Type::lookup_complex_type("complex128");
7032 // Return a single argument, or NULL if there isn't one.
7035 Builtin_call_expression::one_arg() const
7037 const Expression_list* args = this->args();
7038 if (args == NULL || args->size() != 1)
7040 return args->front();
7043 // Return whether this is constant: len of a string, or len or cap of
7044 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
7047 Builtin_call_expression::do_is_constant() const
7049 switch (this->code_)
7057 Expression* arg = this->one_arg();
7060 Type* arg_type = arg->type();
7062 if (arg_type->points_to() != NULL
7063 && arg_type->points_to()->array_type() != NULL
7064 && !arg_type->points_to()->is_slice_type())
7065 arg_type = arg_type->points_to();
7067 if (arg_type->array_type() != NULL
7068 && arg_type->array_type()->length() != NULL)
7071 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7074 bool ret = arg->is_constant();
7075 this->seen_ = false;
7081 case BUILTIN_SIZEOF:
7082 case BUILTIN_ALIGNOF:
7083 return this->one_arg() != NULL;
7085 case BUILTIN_OFFSETOF:
7087 Expression* arg = this->one_arg();
7090 return arg->field_reference_expression() != NULL;
7093 case BUILTIN_COMPLEX:
7095 const Expression_list* args = this->args();
7096 if (args != NULL && args->size() == 2)
7097 return args->front()->is_constant() && args->back()->is_constant();
7104 Expression* arg = this->one_arg();
7105 return arg != NULL && arg->is_constant();
7115 // Return a numeric constant if possible.
7118 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7120 if (this->code_ == BUILTIN_LEN
7121 || this->code_ == BUILTIN_CAP)
7123 Expression* arg = this->one_arg();
7126 Type* arg_type = arg->type();
7128 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7131 if (arg->string_constant_value(&sval))
7133 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7139 if (arg_type->points_to() != NULL
7140 && arg_type->points_to()->array_type() != NULL
7141 && !arg_type->points_to()->is_slice_type())
7142 arg_type = arg_type->points_to();
7144 if (arg_type->array_type() != NULL
7145 && arg_type->array_type()->length() != NULL)
7149 Expression* e = arg_type->array_type()->length();
7151 bool r = e->numeric_constant_value(nc);
7152 this->seen_ = false;
7155 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7162 else if (this->code_ == BUILTIN_SIZEOF
7163 || this->code_ == BUILTIN_ALIGNOF)
7165 Expression* arg = this->one_arg();
7168 Type* arg_type = arg->type();
7169 if (arg_type->is_error())
7171 if (arg_type->is_abstract())
7173 if (arg_type->named_type() != NULL)
7174 arg_type->named_type()->convert(this->gogo_);
7177 if (this->code_ == BUILTIN_SIZEOF)
7179 if (!arg_type->backend_type_size(this->gogo_, &ret))
7182 else if (this->code_ == BUILTIN_ALIGNOF)
7184 if (arg->field_reference_expression() == NULL)
7186 if (!arg_type->backend_type_align(this->gogo_, &ret))
7191 // Calling unsafe.Alignof(s.f) returns the alignment of
7192 // the type of f when it is used as a field in a struct.
7193 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7200 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7201 static_cast<unsigned long>(ret));
7204 else if (this->code_ == BUILTIN_OFFSETOF)
7206 Expression* arg = this->one_arg();
7209 Field_reference_expression* farg = arg->field_reference_expression();
7212 Expression* struct_expr = farg->expr();
7213 Type* st = struct_expr->type();
7214 if (st->struct_type() == NULL)
7216 if (st->named_type() != NULL)
7217 st->named_type()->convert(this->gogo_);
7218 unsigned int offset;
7219 if (!st->struct_type()->backend_field_offset(this->gogo_,
7220 farg->field_index(),
7223 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7224 static_cast<unsigned long>(offset));
7227 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7229 Expression* arg = this->one_arg();
7233 Numeric_constant argnc;
7234 if (!arg->numeric_constant_value(&argnc))
7239 if (!argnc.to_complex(&real, &imag))
7242 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7243 if (this->code_ == BUILTIN_REAL)
7244 nc->set_float(type, real);
7246 nc->set_float(type, imag);
7249 else if (this->code_ == BUILTIN_COMPLEX)
7251 const Expression_list* args = this->args();
7252 if (args == NULL || args->size() != 2)
7255 Numeric_constant rnc;
7256 if (!args->front()->numeric_constant_value(&rnc))
7258 Numeric_constant inc;
7259 if (!args->back()->numeric_constant_value(&inc))
7262 if (rnc.type() != NULL
7263 && !rnc.type()->is_abstract()
7264 && inc.type() != NULL
7265 && !inc.type()->is_abstract()
7266 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7270 if (!rnc.to_float(&r))
7273 if (!inc.to_float(&i))
7279 Type* arg_type = rnc.type();
7280 if (arg_type == NULL || arg_type->is_abstract())
7281 arg_type = inc.type();
7283 Type* type = Builtin_call_expression::complex_type(arg_type);
7284 nc->set_complex(type, r, i);
7295 // Give an error if we are discarding the value of an expression which
7296 // should not normally be discarded. We don't give an error for
7297 // discarding the value of an ordinary function call, but we do for
7298 // builtin functions, purely for consistency with the gc compiler.
7301 Builtin_call_expression::do_discarding_value()
7303 switch (this->code_)
7305 case BUILTIN_INVALID:
7309 case BUILTIN_APPEND:
7311 case BUILTIN_COMPLEX:
7317 case BUILTIN_ALIGNOF:
7318 case BUILTIN_OFFSETOF:
7319 case BUILTIN_SIZEOF:
7320 this->unused_value_error();
7325 case BUILTIN_DELETE:
7328 case BUILTIN_PRINTLN:
7329 case BUILTIN_RECOVER:
7337 Builtin_call_expression::do_type()
7339 switch (this->code_)
7341 case BUILTIN_INVALID:
7348 const Expression_list* args = this->args();
7349 if (args == NULL || args->empty())
7350 return Type::make_error_type();
7351 return Type::make_pointer_type(args->front()->type());
7357 return Type::lookup_integer_type("int");
7359 case BUILTIN_ALIGNOF:
7360 case BUILTIN_OFFSETOF:
7361 case BUILTIN_SIZEOF:
7362 return Type::lookup_integer_type("uintptr");
7365 case BUILTIN_DELETE:
7368 case BUILTIN_PRINTLN:
7369 return Type::make_void_type();
7371 case BUILTIN_RECOVER:
7372 return Type::make_empty_interface_type(Linemap::predeclared_location());
7374 case BUILTIN_APPEND:
7376 const Expression_list* args = this->args();
7377 if (args == NULL || args->empty())
7378 return Type::make_error_type();
7379 return args->front()->type();
7385 Expression* arg = this->one_arg();
7387 return Type::make_error_type();
7388 Type* t = arg->type();
7389 if (t->is_abstract())
7390 t = t->make_non_abstract_type();
7391 t = Builtin_call_expression::real_imag_type(t);
7393 t = Type::make_error_type();
7397 case BUILTIN_COMPLEX:
7399 const Expression_list* args = this->args();
7400 if (args == NULL || args->size() != 2)
7401 return Type::make_error_type();
7402 Type* t = args->front()->type();
7403 if (t->is_abstract())
7405 t = args->back()->type();
7406 if (t->is_abstract())
7407 t = t->make_non_abstract_type();
7409 t = Builtin_call_expression::complex_type(t);
7411 t = Type::make_error_type();
7417 // Determine the type.
7420 Builtin_call_expression::do_determine_type(const Type_context* context)
7422 if (!this->determining_types())
7425 this->fn()->determine_type_no_context();
7427 const Expression_list* args = this->args();
7430 Type* arg_type = NULL;
7431 switch (this->code_)
7434 case BUILTIN_PRINTLN:
7435 // Do not force a large integer constant to "int".
7441 arg_type = Builtin_call_expression::complex_type(context->type);
7445 case BUILTIN_COMPLEX:
7447 // For the complex function the type of one operand can
7448 // determine the type of the other, as in a binary expression.
7449 arg_type = Builtin_call_expression::real_imag_type(context->type);
7450 if (args != NULL && args->size() == 2)
7452 Type* t1 = args->front()->type();
7453 Type* t2 = args->front()->type();
7454 if (!t1->is_abstract())
7456 else if (!t2->is_abstract())
7470 for (Expression_list::const_iterator pa = args->begin();
7474 Type_context subcontext;
7475 subcontext.type = arg_type;
7479 // We want to print large constants, we so can't just
7480 // use the appropriate nonabstract type. Use uint64 for
7481 // an integer if we know it is nonnegative, otherwise
7482 // use int64 for a integer, otherwise use float64 for a
7483 // float or complex128 for a complex.
7484 Type* want_type = NULL;
7485 Type* atype = (*pa)->type();
7486 if (atype->is_abstract())
7488 if (atype->integer_type() != NULL)
7490 Numeric_constant nc;
7491 if (this->numeric_constant_value(&nc))
7494 if (nc.to_int(&val))
7496 if (mpz_sgn(val) >= 0)
7497 want_type = Type::lookup_integer_type("uint64");
7501 if (want_type == NULL)
7502 want_type = Type::lookup_integer_type("int64");
7504 else if (atype->float_type() != NULL)
7505 want_type = Type::lookup_float_type("float64");
7506 else if (atype->complex_type() != NULL)
7507 want_type = Type::lookup_complex_type("complex128");
7508 else if (atype->is_abstract_string_type())
7509 want_type = Type::lookup_string_type();
7510 else if (atype->is_abstract_boolean_type())
7511 want_type = Type::lookup_bool_type();
7514 subcontext.type = want_type;
7518 (*pa)->determine_type(&subcontext);
7523 // If there is exactly one argument, return true. Otherwise give an
7524 // error message and return false.
7527 Builtin_call_expression::check_one_arg()
7529 const Expression_list* args = this->args();
7530 if (args == NULL || args->size() < 1)
7532 this->report_error(_("not enough arguments"));
7535 else if (args->size() > 1)
7537 this->report_error(_("too many arguments"));
7540 if (args->front()->is_error_expression()
7541 || args->front()->type()->is_error())
7543 this->set_is_error();
7549 // Check argument types for a builtin function.
7552 Builtin_call_expression::do_check_types(Gogo*)
7554 if (this->is_error_expression())
7556 switch (this->code_)
7558 case BUILTIN_INVALID:
7561 case BUILTIN_DELETE:
7567 // The single argument may be either a string or an array or a
7568 // map or a channel, or a pointer to a closed array.
7569 if (this->check_one_arg())
7571 Type* arg_type = this->one_arg()->type();
7572 if (arg_type->points_to() != NULL
7573 && arg_type->points_to()->array_type() != NULL
7574 && !arg_type->points_to()->is_slice_type())
7575 arg_type = arg_type->points_to();
7576 if (this->code_ == BUILTIN_CAP)
7578 if (!arg_type->is_error()
7579 && arg_type->array_type() == NULL
7580 && arg_type->channel_type() == NULL)
7581 this->report_error(_("argument must be array or slice "
7586 if (!arg_type->is_error()
7587 && !arg_type->is_string_type()
7588 && arg_type->array_type() == NULL
7589 && arg_type->map_type() == NULL
7590 && arg_type->channel_type() == NULL)
7591 this->report_error(_("argument must be string or "
7592 "array or slice or map or channel"));
7599 case BUILTIN_PRINTLN:
7601 const Expression_list* args = this->args();
7604 if (this->code_ == BUILTIN_PRINT)
7605 warning_at(this->location(), 0,
7606 "no arguments for builtin function %<%s%>",
7607 (this->code_ == BUILTIN_PRINT
7613 for (Expression_list::const_iterator p = args->begin();
7617 Type* type = (*p)->type();
7618 if (type->is_error()
7619 || type->is_string_type()
7620 || type->integer_type() != NULL
7621 || type->float_type() != NULL
7622 || type->complex_type() != NULL
7623 || type->is_boolean_type()
7624 || type->points_to() != NULL
7625 || type->interface_type() != NULL
7626 || type->channel_type() != NULL
7627 || type->map_type() != NULL
7628 || type->function_type() != NULL
7629 || type->is_slice_type())
7631 else if ((*p)->is_type_expression())
7633 // If this is a type expression it's going to give
7634 // an error anyhow, so we don't need one here.
7637 this->report_error(_("unsupported argument type to "
7638 "builtin function"));
7645 if (this->check_one_arg())
7647 if (this->one_arg()->type()->channel_type() == NULL)
7648 this->report_error(_("argument must be channel"));
7649 else if (!this->one_arg()->type()->channel_type()->may_send())
7650 this->report_error(_("cannot close receive-only channel"));
7655 case BUILTIN_SIZEOF:
7656 case BUILTIN_ALIGNOF:
7657 this->check_one_arg();
7660 case BUILTIN_RECOVER:
7661 if (this->args() != NULL && !this->args()->empty())
7662 this->report_error(_("too many arguments"));
7665 case BUILTIN_OFFSETOF:
7666 if (this->check_one_arg())
7668 Expression* arg = this->one_arg();
7669 if (arg->field_reference_expression() == NULL)
7670 this->report_error(_("argument must be a field reference"));
7676 const Expression_list* args = this->args();
7677 if (args == NULL || args->size() < 2)
7679 this->report_error(_("not enough arguments"));
7682 else if (args->size() > 2)
7684 this->report_error(_("too many arguments"));
7687 Type* arg1_type = args->front()->type();
7688 Type* arg2_type = args->back()->type();
7689 if (arg1_type->is_error() || arg2_type->is_error())
7693 if (arg1_type->is_slice_type())
7694 e1 = arg1_type->array_type()->element_type();
7697 this->report_error(_("left argument must be a slice"));
7701 if (arg2_type->is_slice_type())
7703 Type* e2 = arg2_type->array_type()->element_type();
7704 if (!Type::are_identical(e1, e2, true, NULL))
7705 this->report_error(_("element types must be the same"));
7707 else if (arg2_type->is_string_type())
7709 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7710 this->report_error(_("first argument must be []byte"));
7713 this->report_error(_("second argument must be slice or string"));
7717 case BUILTIN_APPEND:
7719 const Expression_list* args = this->args();
7720 if (args == NULL || args->size() < 2)
7722 this->report_error(_("not enough arguments"));
7725 if (args->size() > 2)
7727 this->report_error(_("too many arguments"));
7730 if (args->front()->type()->is_error()
7731 || args->back()->type()->is_error())
7734 Array_type* at = args->front()->type()->array_type();
7735 Type* e = at->element_type();
7737 // The language permits appending a string to a []byte, as a
7739 if (args->back()->type()->is_string_type())
7741 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7745 // The language says that the second argument must be
7746 // assignable to a slice of the element type of the first
7747 // argument. We already know the first argument is a slice
7749 Type* arg2_type = Type::make_array_type(e, NULL);
7751 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7754 this->report_error(_("argument 2 has invalid type"));
7757 error_at(this->location(), "argument 2 has invalid type (%s)",
7759 this->set_is_error();
7767 if (this->check_one_arg())
7769 if (this->one_arg()->type()->complex_type() == NULL)
7770 this->report_error(_("argument must have complex type"));
7774 case BUILTIN_COMPLEX:
7776 const Expression_list* args = this->args();
7777 if (args == NULL || args->size() < 2)
7778 this->report_error(_("not enough arguments"));
7779 else if (args->size() > 2)
7780 this->report_error(_("too many arguments"));
7781 else if (args->front()->is_error_expression()
7782 || args->front()->type()->is_error()
7783 || args->back()->is_error_expression()
7784 || args->back()->type()->is_error())
7785 this->set_is_error();
7786 else if (!Type::are_identical(args->front()->type(),
7787 args->back()->type(), true, NULL))
7788 this->report_error(_("complex arguments must have identical types"));
7789 else if (args->front()->type()->float_type() == NULL)
7790 this->report_error(_("complex arguments must have "
7791 "floating-point type"));
7800 // Return the tree for a builtin function.
7803 Builtin_call_expression::do_get_tree(Translate_context* context)
7805 Gogo* gogo = context->gogo();
7806 Location location = this->location();
7807 switch (this->code_)
7809 case BUILTIN_INVALID:
7817 const Expression_list* args = this->args();
7818 go_assert(args != NULL && args->size() == 1);
7819 Expression* arg = *args->begin();
7820 Type* arg_type = arg->type();
7824 go_assert(saw_errors());
7825 return error_mark_node;
7829 tree arg_tree = arg->get_tree(context);
7831 this->seen_ = false;
7833 if (arg_tree == error_mark_node)
7834 return error_mark_node;
7836 if (arg_type->points_to() != NULL)
7838 arg_type = arg_type->points_to();
7839 go_assert(arg_type->array_type() != NULL
7840 && !arg_type->is_slice_type());
7841 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7842 arg_tree = build_fold_indirect_ref(arg_tree);
7846 if (this->code_ == BUILTIN_LEN)
7848 if (arg_type->is_string_type())
7849 val_tree = String_type::length_tree(gogo, arg_tree);
7850 else if (arg_type->array_type() != NULL)
7854 go_assert(saw_errors());
7855 return error_mark_node;
7858 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7859 this->seen_ = false;
7861 else if (arg_type->map_type() != NULL)
7863 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7864 static tree map_len_fndecl;
7865 val_tree = Gogo::call_builtin(&map_len_fndecl,
7873 else if (arg_type->channel_type() != NULL)
7875 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7876 static tree chan_len_fndecl;
7877 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7890 if (arg_type->array_type() != NULL)
7894 go_assert(saw_errors());
7895 return error_mark_node;
7898 val_tree = arg_type->array_type()->capacity_tree(gogo,
7900 this->seen_ = false;
7902 else if (arg_type->channel_type() != NULL)
7904 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7905 static tree chan_cap_fndecl;
7906 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7918 if (val_tree == error_mark_node)
7919 return error_mark_node;
7921 Type* int_type = Type::lookup_integer_type("int");
7922 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7923 if (type_tree == TREE_TYPE(val_tree))
7926 return fold(convert_to_integer(type_tree, val_tree));
7930 case BUILTIN_PRINTLN:
7932 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7933 tree stmt_list = NULL_TREE;
7935 const Expression_list* call_args = this->args();
7936 if (call_args != NULL)
7938 for (Expression_list::const_iterator p = call_args->begin();
7939 p != call_args->end();
7942 if (is_ln && p != call_args->begin())
7944 static tree print_space_fndecl;
7945 tree call = Gogo::call_builtin(&print_space_fndecl,
7950 if (call == error_mark_node)
7951 return error_mark_node;
7952 append_to_statement_list(call, &stmt_list);
7955 Type* type = (*p)->type();
7957 tree arg = (*p)->get_tree(context);
7958 if (arg == error_mark_node)
7959 return error_mark_node;
7963 if (type->is_string_type())
7965 static tree print_string_fndecl;
7966 pfndecl = &print_string_fndecl;
7967 fnname = "__go_print_string";
7969 else if (type->integer_type() != NULL
7970 && type->integer_type()->is_unsigned())
7972 static tree print_uint64_fndecl;
7973 pfndecl = &print_uint64_fndecl;
7974 fnname = "__go_print_uint64";
7975 Type* itype = Type::lookup_integer_type("uint64");
7976 Btype* bitype = itype->get_backend(gogo);
7977 arg = fold_convert_loc(location.gcc_location(),
7978 type_to_tree(bitype), arg);
7980 else if (type->integer_type() != NULL)
7982 static tree print_int64_fndecl;
7983 pfndecl = &print_int64_fndecl;
7984 fnname = "__go_print_int64";
7985 Type* itype = Type::lookup_integer_type("int64");
7986 Btype* bitype = itype->get_backend(gogo);
7987 arg = fold_convert_loc(location.gcc_location(),
7988 type_to_tree(bitype), arg);
7990 else if (type->float_type() != NULL)
7992 static tree print_double_fndecl;
7993 pfndecl = &print_double_fndecl;
7994 fnname = "__go_print_double";
7995 arg = fold_convert_loc(location.gcc_location(),
7996 double_type_node, arg);
7998 else if (type->complex_type() != NULL)
8000 static tree print_complex_fndecl;
8001 pfndecl = &print_complex_fndecl;
8002 fnname = "__go_print_complex";
8003 arg = fold_convert_loc(location.gcc_location(),
8004 complex_double_type_node, arg);
8006 else if (type->is_boolean_type())
8008 static tree print_bool_fndecl;
8009 pfndecl = &print_bool_fndecl;
8010 fnname = "__go_print_bool";
8012 else if (type->points_to() != NULL
8013 || type->channel_type() != NULL
8014 || type->map_type() != NULL
8015 || type->function_type() != NULL)
8017 static tree print_pointer_fndecl;
8018 pfndecl = &print_pointer_fndecl;
8019 fnname = "__go_print_pointer";
8020 arg = fold_convert_loc(location.gcc_location(),
8021 ptr_type_node, arg);
8023 else if (type->interface_type() != NULL)
8025 if (type->interface_type()->is_empty())
8027 static tree print_empty_interface_fndecl;
8028 pfndecl = &print_empty_interface_fndecl;
8029 fnname = "__go_print_empty_interface";
8033 static tree print_interface_fndecl;
8034 pfndecl = &print_interface_fndecl;
8035 fnname = "__go_print_interface";
8038 else if (type->is_slice_type())
8040 static tree print_slice_fndecl;
8041 pfndecl = &print_slice_fndecl;
8042 fnname = "__go_print_slice";
8046 go_assert(saw_errors());
8047 return error_mark_node;
8050 tree call = Gogo::call_builtin(pfndecl,
8057 if (call == error_mark_node)
8058 return error_mark_node;
8059 append_to_statement_list(call, &stmt_list);
8065 static tree print_nl_fndecl;
8066 tree call = Gogo::call_builtin(&print_nl_fndecl,
8071 if (call == error_mark_node)
8072 return error_mark_node;
8073 append_to_statement_list(call, &stmt_list);
8081 const Expression_list* args = this->args();
8082 go_assert(args != NULL && args->size() == 1);
8083 Expression* arg = args->front();
8084 tree arg_tree = arg->get_tree(context);
8085 if (arg_tree == error_mark_node)
8086 return error_mark_node;
8088 Type::make_empty_interface_type(Linemap::predeclared_location());
8089 arg_tree = Expression::convert_for_assignment(context, empty,
8091 arg_tree, location);
8092 static tree panic_fndecl;
8093 tree call = Gogo::call_builtin(&panic_fndecl,
8098 TREE_TYPE(arg_tree),
8100 if (call == error_mark_node)
8101 return error_mark_node;
8102 // This function will throw an exception.
8103 TREE_NOTHROW(panic_fndecl) = 0;
8104 // This function will not return.
8105 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8109 case BUILTIN_RECOVER:
8111 // The argument is set when building recover thunks. It's a
8112 // boolean value which is true if we can recover a value now.
8113 const Expression_list* args = this->args();
8114 go_assert(args != NULL && args->size() == 1);
8115 Expression* arg = args->front();
8116 tree arg_tree = arg->get_tree(context);
8117 if (arg_tree == error_mark_node)
8118 return error_mark_node;
8121 Type::make_empty_interface_type(Linemap::predeclared_location());
8122 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8124 Type* nil_type = Type::make_nil_type();
8125 Expression* nil = Expression::make_nil(location);
8126 tree nil_tree = nil->get_tree(context);
8127 tree empty_nil_tree = Expression::convert_for_assignment(context,
8133 // We need to handle a deferred call to recover specially,
8134 // because it changes whether it can recover a panic or not.
8135 // See test7 in test/recover1.go.
8137 if (this->is_deferred())
8139 static tree deferred_recover_fndecl;
8140 call = Gogo::call_builtin(&deferred_recover_fndecl,
8142 "__go_deferred_recover",
8148 static tree recover_fndecl;
8149 call = Gogo::call_builtin(&recover_fndecl,
8155 if (call == error_mark_node)
8156 return error_mark_node;
8157 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8158 arg_tree, call, empty_nil_tree);
8163 const Expression_list* args = this->args();
8164 go_assert(args != NULL && args->size() == 1);
8165 Expression* arg = args->front();
8166 tree arg_tree = arg->get_tree(context);
8167 if (arg_tree == error_mark_node)
8168 return error_mark_node;
8169 static tree close_fndecl;
8170 return Gogo::call_builtin(&close_fndecl,
8172 "__go_builtin_close",
8175 TREE_TYPE(arg_tree),
8179 case BUILTIN_SIZEOF:
8180 case BUILTIN_OFFSETOF:
8181 case BUILTIN_ALIGNOF:
8183 Numeric_constant nc;
8185 if (!this->numeric_constant_value(&nc)
8186 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8188 go_assert(saw_errors());
8189 return error_mark_node;
8191 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8192 tree type = type_to_tree(uintptr_type->get_backend(gogo));
8193 return build_int_cst(type, val);
8198 const Expression_list* args = this->args();
8199 go_assert(args != NULL && args->size() == 2);
8200 Expression* arg1 = args->front();
8201 Expression* arg2 = args->back();
8203 tree arg1_tree = arg1->get_tree(context);
8204 tree arg2_tree = arg2->get_tree(context);
8205 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8206 return error_mark_node;
8208 Type* arg1_type = arg1->type();
8209 Array_type* at = arg1_type->array_type();
8210 arg1_tree = save_expr(arg1_tree);
8211 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8212 tree arg1_len = at->length_tree(gogo, arg1_tree);
8213 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8214 return error_mark_node;
8216 Type* arg2_type = arg2->type();
8219 if (arg2_type->is_slice_type())
8221 at = arg2_type->array_type();
8222 arg2_tree = save_expr(arg2_tree);
8223 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8224 arg2_len = at->length_tree(gogo, arg2_tree);
8228 arg2_tree = save_expr(arg2_tree);
8229 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8230 arg2_len = String_type::length_tree(gogo, arg2_tree);
8232 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8233 return error_mark_node;
8235 arg1_len = save_expr(arg1_len);
8236 arg2_len = save_expr(arg2_len);
8237 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8238 TREE_TYPE(arg1_len),
8239 fold_build2_loc(location.gcc_location(),
8240 LT_EXPR, boolean_type_node,
8241 arg1_len, arg2_len),
8242 arg1_len, arg2_len);
8243 len = save_expr(len);
8245 Type* element_type = at->element_type();
8246 Btype* element_btype = element_type->get_backend(gogo);
8247 tree element_type_tree = type_to_tree(element_btype);
8248 if (element_type_tree == error_mark_node)
8249 return error_mark_node;
8250 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8251 tree bytecount = fold_convert_loc(location.gcc_location(),
8252 TREE_TYPE(element_size), len);
8253 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8254 TREE_TYPE(element_size),
8255 bytecount, element_size);
8256 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8259 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8261 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8264 static tree copy_fndecl;
8265 tree call = Gogo::call_builtin(©_fndecl,
8276 if (call == error_mark_node)
8277 return error_mark_node;
8279 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8280 TREE_TYPE(len), call, len);
8283 case BUILTIN_APPEND:
8285 const Expression_list* args = this->args();
8286 go_assert(args != NULL && args->size() == 2);
8287 Expression* arg1 = args->front();
8288 Expression* arg2 = args->back();
8290 tree arg1_tree = arg1->get_tree(context);
8291 tree arg2_tree = arg2->get_tree(context);
8292 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8293 return error_mark_node;
8295 Array_type* at = arg1->type()->array_type();
8296 Type* element_type = at->element_type()->forwarded();
8301 if (arg2->type()->is_string_type()
8302 && element_type->integer_type() != NULL
8303 && element_type->integer_type()->is_byte())
8305 arg2_tree = save_expr(arg2_tree);
8306 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8307 arg2_len = String_type::length_tree(gogo, arg2_tree);
8308 element_size = size_int(1);
8312 arg2_tree = Expression::convert_for_assignment(context, at,
8316 if (arg2_tree == error_mark_node)
8317 return error_mark_node;
8319 arg2_tree = save_expr(arg2_tree);
8321 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8322 arg2_len = at->length_tree(gogo, arg2_tree);
8324 Btype* element_btype = element_type->get_backend(gogo);
8325 tree element_type_tree = type_to_tree(element_btype);
8326 if (element_type_tree == error_mark_node)
8327 return error_mark_node;
8328 element_size = TYPE_SIZE_UNIT(element_type_tree);
8331 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8333 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8335 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8338 if (arg2_val == error_mark_node
8339 || arg2_len == error_mark_node
8340 || element_size == error_mark_node)
8341 return error_mark_node;
8343 // We rebuild the decl each time since the slice types may
8345 tree append_fndecl = NULL_TREE;
8346 return Gogo::call_builtin(&append_fndecl,
8350 TREE_TYPE(arg1_tree),
8351 TREE_TYPE(arg1_tree),
8364 const Expression_list* args = this->args();
8365 go_assert(args != NULL && args->size() == 1);
8366 Expression* arg = args->front();
8367 tree arg_tree = arg->get_tree(context);
8368 if (arg_tree == error_mark_node)
8369 return error_mark_node;
8370 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8371 if (this->code_ == BUILTIN_REAL)
8372 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8373 TREE_TYPE(TREE_TYPE(arg_tree)),
8376 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8377 TREE_TYPE(TREE_TYPE(arg_tree)),
8381 case BUILTIN_COMPLEX:
8383 const Expression_list* args = this->args();
8384 go_assert(args != NULL && args->size() == 2);
8385 tree r = args->front()->get_tree(context);
8386 tree i = args->back()->get_tree(context);
8387 if (r == error_mark_node || i == error_mark_node)
8388 return error_mark_node;
8389 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8390 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8391 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8392 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8393 build_complex_type(TREE_TYPE(r)),
8402 // We have to support exporting a builtin call expression, because
8403 // code can set a constant to the result of a builtin expression.
8406 Builtin_call_expression::do_export(Export* exp) const
8408 Numeric_constant nc;
8409 if (!this->numeric_constant_value(&nc))
8411 error_at(this->location(), "value is not constant");
8419 Integer_expression::export_integer(exp, val);
8422 else if (nc.is_float())
8425 nc.get_float(&fval);
8426 Float_expression::export_float(exp, fval);
8429 else if (nc.is_complex())
8433 Complex_expression::export_complex(exp, real, imag);
8440 // A trailing space lets us reliably identify the end of the number.
8441 exp->write_c_string(" ");
8444 // Class Call_expression.
8449 Call_expression::do_traverse(Traverse* traverse)
8451 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8452 return TRAVERSE_EXIT;
8453 if (this->args_ != NULL)
8455 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8456 return TRAVERSE_EXIT;
8458 return TRAVERSE_CONTINUE;
8461 // Lower a call statement.
8464 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8465 Statement_inserter* inserter, int)
8467 Location loc = this->location();
8469 // A type cast can look like a function call.
8470 if (this->fn_->is_type_expression()
8471 && this->args_ != NULL
8472 && this->args_->size() == 1)
8473 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8476 // Recognize a call to a builtin function.
8477 Func_expression* fne = this->fn_->func_expression();
8479 && fne->named_object()->is_function_declaration()
8480 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8481 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8482 this->is_varargs_, loc);
8484 // Handle an argument which is a call to a function which returns
8485 // multiple results.
8486 if (this->args_ != NULL
8487 && this->args_->size() == 1
8488 && this->args_->front()->call_expression() != NULL
8489 && this->fn_->type()->function_type() != NULL)
8491 Function_type* fntype = this->fn_->type()->function_type();
8492 size_t rc = this->args_->front()->call_expression()->result_count();
8494 && fntype->parameters() != NULL
8495 && (fntype->parameters()->size() == rc
8496 || (fntype->is_varargs()
8497 && fntype->parameters()->size() - 1 <= rc)))
8499 Call_expression* call = this->args_->front()->call_expression();
8500 Expression_list* args = new Expression_list;
8501 for (size_t i = 0; i < rc; ++i)
8502 args->push_back(Expression::make_call_result(call, i));
8503 // We can't return a new call expression here, because this
8504 // one may be referenced by Call_result expressions. We
8505 // also can't delete the old arguments, because we may still
8506 // traverse them somewhere up the call stack. FIXME.
8511 // If this call returns multiple results, create a temporary
8512 // variable for each result.
8513 size_t rc = this->result_count();
8514 if (rc > 1 && this->results_ == NULL)
8516 std::vector<Temporary_statement*>* temps =
8517 new std::vector<Temporary_statement*>;
8519 const Typed_identifier_list* results =
8520 this->fn_->type()->function_type()->results();
8521 for (Typed_identifier_list::const_iterator p = results->begin();
8522 p != results->end();
8525 Temporary_statement* temp = Statement::make_temporary(p->type(),
8527 inserter->insert(temp);
8528 temps->push_back(temp);
8530 this->results_ = temps;
8533 // Handle a call to a varargs function by packaging up the extra
8535 if (this->fn_->type()->function_type() != NULL
8536 && this->fn_->type()->function_type()->is_varargs())
8538 Function_type* fntype = this->fn_->type()->function_type();
8539 const Typed_identifier_list* parameters = fntype->parameters();
8540 go_assert(parameters != NULL && !parameters->empty());
8541 Type* varargs_type = parameters->back().type();
8542 this->lower_varargs(gogo, function, inserter, varargs_type,
8543 parameters->size());
8546 // If this is call to a method, call the method directly passing the
8547 // object as the first parameter.
8548 Bound_method_expression* bme = this->fn_->bound_method_expression();
8551 Named_object* method = bme->method();
8552 Expression* first_arg = bme->first_argument();
8554 // We always pass a pointer when calling a method.
8555 if (first_arg->type()->points_to() == NULL
8556 && !first_arg->type()->is_error())
8558 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8559 // We may need to create a temporary variable so that we can
8560 // take the address. We can't do that here because it will
8561 // mess up the order of evaluation.
8562 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8563 ue->set_create_temp();
8566 // If we are calling a method which was inherited from an
8567 // embedded struct, and the method did not get a stub, then the
8568 // first type may be wrong.
8569 Type* fatype = bme->first_argument_type();
8572 if (fatype->points_to() == NULL)
8573 fatype = Type::make_pointer_type(fatype);
8574 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8577 Expression_list* new_args = new Expression_list();
8578 new_args->push_back(first_arg);
8579 if (this->args_ != NULL)
8581 for (Expression_list::const_iterator p = this->args_->begin();
8582 p != this->args_->end();
8584 new_args->push_back(*p);
8587 // We have to change in place because this structure may be
8588 // referenced by Call_result_expressions. We can't delete the
8589 // old arguments, because we may be traversing them up in some
8591 this->args_ = new_args;
8592 this->fn_ = Expression::make_func_reference(method, NULL,
8599 // Lower a call to a varargs function. FUNCTION is the function in
8600 // which the call occurs--it's not the function we are calling.
8601 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8602 // PARAM_COUNT is the number of parameters of the function we are
8603 // calling; the last of these parameters will be the varargs
8607 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8608 Statement_inserter* inserter,
8609 Type* varargs_type, size_t param_count)
8611 if (this->varargs_are_lowered_)
8614 Location loc = this->location();
8616 go_assert(param_count > 0);
8617 go_assert(varargs_type->is_slice_type());
8619 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8620 if (arg_count < param_count - 1)
8622 // Not enough arguments; will be caught in check_types.
8626 Expression_list* old_args = this->args_;
8627 Expression_list* new_args = new Expression_list();
8628 bool push_empty_arg = false;
8629 if (old_args == NULL || old_args->empty())
8631 go_assert(param_count == 1);
8632 push_empty_arg = true;
8636 Expression_list::const_iterator pa;
8638 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8640 if (static_cast<size_t>(i) == param_count)
8642 new_args->push_back(*pa);
8645 // We have reached the varargs parameter.
8647 bool issued_error = false;
8648 if (pa == old_args->end())
8649 push_empty_arg = true;
8650 else if (pa + 1 == old_args->end() && this->is_varargs_)
8651 new_args->push_back(*pa);
8652 else if (this->is_varargs_)
8654 if ((*pa)->type()->is_slice_type())
8655 this->report_error(_("too many arguments"));
8658 error_at(this->location(),
8659 _("invalid use of %<...%> with non-slice"));
8660 this->set_is_error();
8666 Type* element_type = varargs_type->array_type()->element_type();
8667 Expression_list* vals = new Expression_list;
8668 for (; pa != old_args->end(); ++pa, ++i)
8670 // Check types here so that we get a better message.
8671 Type* patype = (*pa)->type();
8672 Location paloc = (*pa)->location();
8673 if (!this->check_argument_type(i, element_type, patype,
8674 paloc, issued_error))
8676 vals->push_back(*pa);
8679 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8680 gogo->lower_expression(function, inserter, &val);
8681 new_args->push_back(val);
8686 new_args->push_back(Expression::make_nil(loc));
8688 // We can't return a new call expression here, because this one may
8689 // be referenced by Call_result expressions. FIXME. We can't
8690 // delete OLD_ARGS because we may have both a Call_expression and a
8691 // Builtin_call_expression which refer to them. FIXME.
8692 this->args_ = new_args;
8693 this->varargs_are_lowered_ = true;
8696 // Get the function type. This can return NULL in error cases.
8699 Call_expression::get_function_type() const
8701 return this->fn_->type()->function_type();
8704 // Return the number of values which this call will return.
8707 Call_expression::result_count() const
8709 const Function_type* fntype = this->get_function_type();
8712 if (fntype->results() == NULL)
8714 return fntype->results()->size();
8717 // Return the temporary which holds a result.
8719 Temporary_statement*
8720 Call_expression::result(size_t i) const
8722 if (this->results_ == NULL || this->results_->size() <= i)
8724 go_assert(saw_errors());
8727 return (*this->results_)[i];
8730 // Return whether this is a call to the predeclared function recover.
8733 Call_expression::is_recover_call() const
8735 return this->do_is_recover_call();
8738 // Set the argument to the recover function.
8741 Call_expression::set_recover_arg(Expression* arg)
8743 this->do_set_recover_arg(arg);
8746 // Virtual functions also implemented by Builtin_call_expression.
8749 Call_expression::do_is_recover_call() const
8755 Call_expression::do_set_recover_arg(Expression*)
8760 // We have found an error with this call expression; return true if
8761 // we should report it.
8764 Call_expression::issue_error()
8766 if (this->issued_error_)
8770 this->issued_error_ = true;
8778 Call_expression::do_type()
8780 if (this->type_ != NULL)
8784 Function_type* fntype = this->get_function_type();
8786 return Type::make_error_type();
8788 const Typed_identifier_list* results = fntype->results();
8789 if (results == NULL)
8790 ret = Type::make_void_type();
8791 else if (results->size() == 1)
8792 ret = results->begin()->type();
8794 ret = Type::make_call_multiple_result_type(this);
8801 // Determine types for a call expression. We can use the function
8802 // parameter types to set the types of the arguments.
8805 Call_expression::do_determine_type(const Type_context*)
8807 if (!this->determining_types())
8810 this->fn_->determine_type_no_context();
8811 Function_type* fntype = this->get_function_type();
8812 const Typed_identifier_list* parameters = NULL;
8814 parameters = fntype->parameters();
8815 if (this->args_ != NULL)
8817 Typed_identifier_list::const_iterator pt;
8818 if (parameters != NULL)
8819 pt = parameters->begin();
8821 for (Expression_list::const_iterator pa = this->args_->begin();
8822 pa != this->args_->end();
8828 // If this is a method, the first argument is the
8830 if (fntype != NULL && fntype->is_method())
8832 Type* rtype = fntype->receiver()->type();
8833 // The receiver is always passed as a pointer.
8834 if (rtype->points_to() == NULL)
8835 rtype = Type::make_pointer_type(rtype);
8836 Type_context subcontext(rtype, false);
8837 (*pa)->determine_type(&subcontext);
8842 if (parameters != NULL && pt != parameters->end())
8844 Type_context subcontext(pt->type(), false);
8845 (*pa)->determine_type(&subcontext);
8849 (*pa)->determine_type_no_context();
8854 // Called when determining types for a Call_expression. Return true
8855 // if we should go ahead, false if they have already been determined.
8858 Call_expression::determining_types()
8860 if (this->types_are_determined_)
8864 this->types_are_determined_ = true;
8869 // Check types for parameter I.
8872 Call_expression::check_argument_type(int i, const Type* parameter_type,
8873 const Type* argument_type,
8874 Location argument_location,
8879 if (this->are_hidden_fields_ok_)
8880 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8883 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8889 error_at(argument_location, "argument %d has incompatible type", i);
8891 error_at(argument_location,
8892 "argument %d has incompatible type (%s)",
8895 this->set_is_error();
8904 Call_expression::do_check_types(Gogo*)
8906 if (this->classification() == EXPRESSION_ERROR)
8909 Function_type* fntype = this->get_function_type();
8912 if (!this->fn_->type()->is_error())
8913 this->report_error(_("expected function"));
8917 bool is_method = fntype->is_method();
8920 go_assert(this->args_ != NULL && !this->args_->empty());
8921 Type* rtype = fntype->receiver()->type();
8922 Expression* first_arg = this->args_->front();
8923 // The language permits copying hidden fields for a method
8924 // receiver. We dereference the values since receivers are
8925 // always passed as pointers.
8927 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8928 first_arg->type()->deref(),
8932 this->report_error(_("incompatible type for receiver"));
8935 error_at(this->location(),
8936 "incompatible type for receiver (%s)",
8938 this->set_is_error();
8943 // Note that varargs was handled by the lower_varargs() method, so
8944 // we don't have to worry about it here unless something is wrong.
8945 if (this->is_varargs_ && !this->varargs_are_lowered_)
8947 if (!fntype->is_varargs())
8949 error_at(this->location(),
8950 _("invalid use of %<...%> calling non-variadic function"));
8951 this->set_is_error();
8956 const Typed_identifier_list* parameters = fntype->parameters();
8957 if (this->args_ == NULL)
8959 if (parameters != NULL && !parameters->empty())
8960 this->report_error(_("not enough arguments"));
8962 else if (parameters == NULL)
8964 if (!is_method || this->args_->size() > 1)
8965 this->report_error(_("too many arguments"));
8970 Expression_list::const_iterator pa = this->args_->begin();
8973 for (Typed_identifier_list::const_iterator pt = parameters->begin();
8974 pt != parameters->end();
8977 if (pa == this->args_->end())
8979 this->report_error(_("not enough arguments"));
8982 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8983 (*pa)->location(), false);
8985 if (pa != this->args_->end())
8986 this->report_error(_("too many arguments"));
8990 // Return whether we have to use a temporary variable to ensure that
8991 // we evaluate this call expression in order. If the call returns no
8992 // results then it will inevitably be executed last.
8995 Call_expression::do_must_eval_in_order() const
8997 return this->result_count() > 0;
9000 // Get the function and the first argument to use when calling an
9001 // interface method.
9004 Call_expression::interface_method_function(
9005 Translate_context* context,
9006 Interface_field_reference_expression* interface_method,
9007 tree* first_arg_ptr)
9009 tree expr = interface_method->expr()->get_tree(context);
9010 if (expr == error_mark_node)
9011 return error_mark_node;
9012 expr = save_expr(expr);
9013 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9014 if (first_arg == error_mark_node)
9015 return error_mark_node;
9016 *first_arg_ptr = first_arg;
9017 return interface_method->get_function_tree(context, expr);
9020 // Build the call expression.
9023 Call_expression::do_get_tree(Translate_context* context)
9025 if (this->tree_ != NULL_TREE)
9028 Function_type* fntype = this->get_function_type();
9030 return error_mark_node;
9032 if (this->fn_->is_error_expression())
9033 return error_mark_node;
9035 Gogo* gogo = context->gogo();
9036 Location location = this->location();
9038 Func_expression* func = this->fn_->func_expression();
9039 Interface_field_reference_expression* interface_method =
9040 this->fn_->interface_field_reference_expression();
9041 const bool has_closure = func != NULL && func->closure() != NULL;
9042 const bool is_interface_method = interface_method != NULL;
9046 if (this->args_ == NULL || this->args_->empty())
9048 nargs = is_interface_method ? 1 : 0;
9049 args = nargs == 0 ? NULL : new tree[nargs];
9051 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9053 // Passing a receiver parameter.
9054 go_assert(!is_interface_method
9055 && fntype->is_method()
9056 && this->args_->size() == 1);
9058 args = new tree[nargs];
9059 args[0] = this->args_->front()->get_tree(context);
9063 const Typed_identifier_list* params = fntype->parameters();
9065 nargs = this->args_->size();
9066 int i = is_interface_method ? 1 : 0;
9068 args = new tree[nargs];
9070 Typed_identifier_list::const_iterator pp = params->begin();
9071 Expression_list::const_iterator pe = this->args_->begin();
9072 if (!is_interface_method && fntype->is_method())
9074 args[i] = (*pe)->get_tree(context);
9078 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9080 go_assert(pp != params->end());
9081 tree arg_val = (*pe)->get_tree(context);
9082 args[i] = Expression::convert_for_assignment(context,
9087 if (args[i] == error_mark_node)
9090 return error_mark_node;
9093 go_assert(pp == params->end());
9094 go_assert(i == nargs);
9097 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
9098 if (rettype == error_mark_node)
9101 return error_mark_node;
9106 fn = func->get_tree_without_closure(gogo);
9107 else if (!is_interface_method)
9108 fn = this->fn_->get_tree(context);
9110 fn = this->interface_method_function(context, interface_method, &args[0]);
9112 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9115 return error_mark_node;
9119 if (TREE_CODE(fndecl) == ADDR_EXPR)
9120 fndecl = TREE_OPERAND(fndecl, 0);
9122 // Add a type cast in case the type of the function is a recursive
9123 // type which refers to itself.
9124 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9126 tree fnt = type_to_tree(fntype->get_backend(gogo));
9127 if (fnt == error_mark_node)
9128 return error_mark_node;
9129 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9132 // This is to support builtin math functions when using 80387 math.
9133 tree excess_type = NULL_TREE;
9135 && TREE_CODE(fndecl) == FUNCTION_DECL
9136 && DECL_IS_BUILTIN(fndecl)
9137 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9139 && ((SCALAR_FLOAT_TYPE_P(rettype)
9140 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9141 || (COMPLEX_FLOAT_TYPE_P(rettype)
9142 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9144 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9145 if (excess_type != NULL_TREE)
9147 tree excess_fndecl = mathfn_built_in(excess_type,
9148 DECL_FUNCTION_CODE(fndecl));
9149 if (excess_fndecl == NULL_TREE)
9150 excess_type = NULL_TREE;
9153 fn = build_fold_addr_expr_loc(location.gcc_location(),
9155 for (int i = 0; i < nargs; ++i)
9157 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9158 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9159 args[i] = ::convert(excess_type, args[i]);
9165 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9169 SET_EXPR_LOCATION(ret, location.gcc_location());
9173 tree closure_tree = func->closure()->get_tree(context);
9174 if (closure_tree != error_mark_node)
9175 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9178 // If this is a recursive function type which returns itself, as in
9180 // we have used ptr_type_node for the return type. Add a cast here
9181 // to the correct type.
9182 if (TREE_TYPE(ret) == ptr_type_node)
9184 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9185 ret = fold_convert_loc(location.gcc_location(), t, ret);
9188 if (excess_type != NULL_TREE)
9190 // Calling convert here can undo our excess precision change.
9191 // That may or may not be a bug in convert_to_real.
9192 ret = build1(NOP_EXPR, rettype, ret);
9195 if (this->results_ != NULL)
9196 ret = this->set_results(context, ret);
9203 // Set the result variables if this call returns multiple results.
9206 Call_expression::set_results(Translate_context* context, tree call_tree)
9208 tree stmt_list = NULL_TREE;
9210 call_tree = save_expr(call_tree);
9212 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9214 go_assert(saw_errors());
9218 Location loc = this->location();
9219 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9220 size_t rc = this->result_count();
9221 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9223 go_assert(field != NULL_TREE);
9225 Temporary_statement* temp = this->result(i);
9228 go_assert(saw_errors());
9229 return error_mark_node;
9231 Temporary_reference_expression* ref =
9232 Expression::make_temporary_reference(temp, loc);
9233 ref->set_is_lvalue();
9234 tree temp_tree = ref->get_tree(context);
9235 if (temp_tree == error_mark_node)
9236 return error_mark_node;
9238 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9239 TREE_TYPE(field), call_tree, field, NULL_TREE);
9240 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9241 void_type_node, temp_tree, val_tree);
9243 append_to_statement_list(set_tree, &stmt_list);
9245 go_assert(field == NULL_TREE);
9247 return save_expr(stmt_list);
9250 // Dump ast representation for a call expressin.
9253 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9255 this->fn_->dump_expression(ast_dump_context);
9256 ast_dump_context->ostream() << "(";
9258 ast_dump_context->dump_expression_list(this->args_);
9260 ast_dump_context->ostream() << ") ";
9263 // Make a call expression.
9266 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9269 return new Call_expression(fn, args, is_varargs, location);
9272 // A single result from a call which returns multiple results.
9274 class Call_result_expression : public Expression
9277 Call_result_expression(Call_expression* call, unsigned int index)
9278 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9279 call_(call), index_(index)
9284 do_traverse(Traverse*);
9290 do_determine_type(const Type_context*);
9293 do_check_types(Gogo*);
9298 return new Call_result_expression(this->call_->call_expression(),
9303 do_must_eval_in_order() const
9307 do_get_tree(Translate_context*);
9310 do_dump_expression(Ast_dump_context*) const;
9313 // The underlying call expression.
9315 // Which result we want.
9316 unsigned int index_;
9319 // Traverse a call result.
9322 Call_result_expression::do_traverse(Traverse* traverse)
9324 if (traverse->remember_expression(this->call_))
9326 // We have already traversed the call expression.
9327 return TRAVERSE_CONTINUE;
9329 return Expression::traverse(&this->call_, traverse);
9335 Call_result_expression::do_type()
9337 if (this->classification() == EXPRESSION_ERROR)
9338 return Type::make_error_type();
9340 // THIS->CALL_ can be replaced with a temporary reference due to
9341 // Call_expression::do_must_eval_in_order when there is an error.
9342 Call_expression* ce = this->call_->call_expression();
9345 this->set_is_error();
9346 return Type::make_error_type();
9348 Function_type* fntype = ce->get_function_type();
9351 if (ce->issue_error())
9353 if (!ce->fn()->type()->is_error())
9354 this->report_error(_("expected function"));
9356 this->set_is_error();
9357 return Type::make_error_type();
9359 const Typed_identifier_list* results = fntype->results();
9360 if (results == NULL || results->size() < 2)
9362 if (ce->issue_error())
9363 this->report_error(_("number of results does not match "
9364 "number of values"));
9365 return Type::make_error_type();
9367 Typed_identifier_list::const_iterator pr = results->begin();
9368 for (unsigned int i = 0; i < this->index_; ++i)
9370 if (pr == results->end())
9374 if (pr == results->end())
9376 if (ce->issue_error())
9377 this->report_error(_("number of results does not match "
9378 "number of values"));
9379 return Type::make_error_type();
9384 // Check the type. Just make sure that we trigger the warning in
9388 Call_result_expression::do_check_types(Gogo*)
9393 // Determine the type. We have nothing to do here, but the 0 result
9394 // needs to pass down to the caller.
9397 Call_result_expression::do_determine_type(const Type_context*)
9399 this->call_->determine_type_no_context();
9402 // Return the tree. We just refer to the temporary set by the call
9403 // expression. We don't do this at lowering time because it makes it
9404 // hard to evaluate the call at the right time.
9407 Call_result_expression::do_get_tree(Translate_context* context)
9409 Call_expression* ce = this->call_->call_expression();
9412 go_assert(this->call_->is_error_expression());
9413 return error_mark_node;
9415 Temporary_statement* ts = ce->result(this->index_);
9418 go_assert(saw_errors());
9419 return error_mark_node;
9421 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9422 return ref->get_tree(context);
9425 // Dump ast representation for a call result expression.
9428 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9431 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9432 // (struct) and the fields are referenced instead.
9433 ast_dump_context->ostream() << this->index_ << "@(";
9434 ast_dump_context->dump_expression(this->call_);
9435 ast_dump_context->ostream() << ")";
9438 // Make a reference to a single result of a call which returns
9439 // multiple results.
9442 Expression::make_call_result(Call_expression* call, unsigned int index)
9444 return new Call_result_expression(call, index);
9447 // Class Index_expression.
9452 Index_expression::do_traverse(Traverse* traverse)
9454 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9455 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9456 || (this->end_ != NULL
9457 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9458 return TRAVERSE_EXIT;
9459 return TRAVERSE_CONTINUE;
9462 // Lower an index expression. This converts the generic index
9463 // expression into an array index, a string index, or a map index.
9466 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9468 Location location = this->location();
9469 Expression* left = this->left_;
9470 Expression* start = this->start_;
9471 Expression* end = this->end_;
9473 Type* type = left->type();
9474 if (type->is_error())
9475 return Expression::make_error(location);
9476 else if (left->is_type_expression())
9478 error_at(location, "attempt to index type expression");
9479 return Expression::make_error(location);
9481 else if (type->array_type() != NULL)
9482 return Expression::make_array_index(left, start, end, location);
9483 else if (type->points_to() != NULL
9484 && type->points_to()->array_type() != NULL
9485 && !type->points_to()->is_slice_type())
9487 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9489 return Expression::make_array_index(deref, start, end, location);
9491 else if (type->is_string_type())
9492 return Expression::make_string_index(left, start, end, location);
9493 else if (type->map_type() != NULL)
9497 error_at(location, "invalid slice of map");
9498 return Expression::make_error(location);
9500 Map_index_expression* ret = Expression::make_map_index(left, start,
9502 if (this->is_lvalue_)
9503 ret->set_is_lvalue();
9509 "attempt to index object which is not array, string, or map");
9510 return Expression::make_error(location);
9514 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9518 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9519 const Expression* expr,
9520 const Expression* start,
9521 const Expression* end)
9523 expr->dump_expression(ast_dump_context);
9524 ast_dump_context->ostream() << "[";
9525 start->dump_expression(ast_dump_context);
9528 ast_dump_context->ostream() << ":";
9529 end->dump_expression(ast_dump_context);
9531 ast_dump_context->ostream() << "]";
9534 // Dump ast representation for an index expression.
9537 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9540 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9541 this->start_, this->end_);
9544 // Make an index expression.
9547 Expression::make_index(Expression* left, Expression* start, Expression* end,
9550 return new Index_expression(left, start, end, location);
9553 // An array index. This is used for both indexing and slicing.
9555 class Array_index_expression : public Expression
9558 Array_index_expression(Expression* array, Expression* start,
9559 Expression* end, Location location)
9560 : Expression(EXPRESSION_ARRAY_INDEX, location),
9561 array_(array), start_(start), end_(end), type_(NULL)
9566 do_traverse(Traverse*);
9572 do_determine_type(const Type_context*);
9575 do_check_types(Gogo*);
9580 return Expression::make_array_index(this->array_->copy(),
9581 this->start_->copy(),
9584 : this->end_->copy()),
9589 do_must_eval_subexpressions_in_order(int* skip) const
9596 do_is_addressable() const;
9599 do_address_taken(bool escapes)
9600 { this->array_->address_taken(escapes); }
9603 do_get_tree(Translate_context*);
9606 do_dump_expression(Ast_dump_context*) const;
9609 // The array we are getting a value from.
9611 // The start or only index.
9613 // The end index of a slice. This may be NULL for a simple array
9614 // index, or it may be a nil expression for the length of the array.
9616 // The type of the expression.
9620 // Array index traversal.
9623 Array_index_expression::do_traverse(Traverse* traverse)
9625 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9626 return TRAVERSE_EXIT;
9627 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9628 return TRAVERSE_EXIT;
9629 if (this->end_ != NULL)
9631 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9632 return TRAVERSE_EXIT;
9634 return TRAVERSE_CONTINUE;
9637 // Return the type of an array index.
9640 Array_index_expression::do_type()
9642 if (this->type_ == NULL)
9644 Array_type* type = this->array_->type()->array_type();
9646 this->type_ = Type::make_error_type();
9647 else if (this->end_ == NULL)
9648 this->type_ = type->element_type();
9649 else if (type->is_slice_type())
9651 // A slice of a slice has the same type as the original
9653 this->type_ = this->array_->type()->deref();
9657 // A slice of an array is a slice.
9658 this->type_ = Type::make_array_type(type->element_type(), NULL);
9664 // Set the type of an array index.
9667 Array_index_expression::do_determine_type(const Type_context*)
9669 this->array_->determine_type_no_context();
9670 this->start_->determine_type_no_context();
9671 if (this->end_ != NULL)
9672 this->end_->determine_type_no_context();
9675 // Check types of an array index.
9678 Array_index_expression::do_check_types(Gogo*)
9680 if (this->start_->type()->integer_type() == NULL)
9681 this->report_error(_("index must be integer"));
9682 if (this->end_ != NULL
9683 && this->end_->type()->integer_type() == NULL
9684 && !this->end_->type()->is_error()
9685 && !this->end_->is_nil_expression()
9686 && !this->end_->is_error_expression())
9687 this->report_error(_("slice end must be integer"));
9689 Array_type* array_type = this->array_->type()->array_type();
9690 if (array_type == NULL)
9692 go_assert(this->array_->type()->is_error());
9696 unsigned int int_bits =
9697 Type::lookup_integer_type("int")->integer_type()->bits();
9699 Numeric_constant lvalnc;
9701 bool lval_valid = (array_type->length() != NULL
9702 && array_type->length()->numeric_constant_value(&lvalnc)
9703 && lvalnc.to_int(&lval));
9704 Numeric_constant inc;
9706 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9708 if (mpz_sgn(ival) < 0
9709 || mpz_sizeinbase(ival, 2) >= int_bits
9711 && (this->end_ == NULL
9712 ? mpz_cmp(ival, lval) >= 0
9713 : mpz_cmp(ival, lval) > 0)))
9715 error_at(this->start_->location(), "array index out of bounds");
9716 this->set_is_error();
9720 if (this->end_ != NULL && !this->end_->is_nil_expression())
9722 Numeric_constant enc;
9724 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9726 if (mpz_sgn(eval) < 0
9727 || mpz_sizeinbase(eval, 2) >= int_bits
9728 || (lval_valid && mpz_cmp(eval, lval) > 0))
9730 error_at(this->end_->location(), "array index out of bounds");
9731 this->set_is_error();
9739 // A slice of an array requires an addressable array. A slice of a
9740 // slice is always possible.
9741 if (this->end_ != NULL && !array_type->is_slice_type())
9743 if (!this->array_->is_addressable())
9744 this->report_error(_("slice of unaddressable value"));
9746 this->array_->address_taken(true);
9750 // Return whether this expression is addressable.
9753 Array_index_expression::do_is_addressable() const
9755 // A slice expression is not addressable.
9756 if (this->end_ != NULL)
9759 // An index into a slice is addressable.
9760 if (this->array_->type()->is_slice_type())
9763 // An index into an array is addressable if the array is
9765 return this->array_->is_addressable();
9768 // Get a tree for an array index.
9771 Array_index_expression::do_get_tree(Translate_context* context)
9773 Gogo* gogo = context->gogo();
9774 Location loc = this->location();
9776 Array_type* array_type = this->array_->type()->array_type();
9777 if (array_type == NULL)
9779 go_assert(this->array_->type()->is_error());
9780 return error_mark_node;
9783 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9784 if (type_tree == error_mark_node)
9785 return error_mark_node;
9787 tree array_tree = this->array_->get_tree(context);
9788 if (array_tree == error_mark_node)
9789 return error_mark_node;
9791 if (array_type->length() == NULL && !DECL_P(array_tree))
9792 array_tree = save_expr(array_tree);
9794 tree length_tree = NULL_TREE;
9795 if (this->end_ == NULL || this->end_->is_nil_expression())
9797 length_tree = array_type->length_tree(gogo, array_tree);
9798 if (length_tree == error_mark_node)
9799 return error_mark_node;
9800 length_tree = save_expr(length_tree);
9803 tree capacity_tree = NULL_TREE;
9804 if (this->end_ != NULL)
9806 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9807 if (capacity_tree == error_mark_node)
9808 return error_mark_node;
9809 capacity_tree = save_expr(capacity_tree);
9812 tree length_type = (length_tree != NULL_TREE
9813 ? TREE_TYPE(length_tree)
9814 : TREE_TYPE(capacity_tree));
9816 tree bad_index = boolean_false_node;
9818 tree start_tree = this->start_->get_tree(context);
9819 if (start_tree == error_mark_node)
9820 return error_mark_node;
9821 if (!DECL_P(start_tree))
9822 start_tree = save_expr(start_tree);
9823 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9824 start_tree = convert_to_integer(length_type, start_tree);
9826 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9829 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9830 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9831 boolean_type_node, bad_index,
9832 fold_build2_loc(loc.gcc_location(),
9836 boolean_type_node, start_tree,
9841 int code = (array_type->length() != NULL
9842 ? (this->end_ == NULL
9843 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9844 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9845 : (this->end_ == NULL
9846 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9847 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9848 tree crash = Gogo::runtime_error(code, loc);
9850 if (this->end_ == NULL)
9852 // Simple array indexing. This has to return an l-value, so
9853 // wrap the index check into START_TREE.
9854 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9855 build3(COND_EXPR, void_type_node,
9856 bad_index, crash, NULL_TREE),
9858 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9860 if (array_type->length() != NULL)
9863 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9864 start_tree, NULL_TREE, NULL_TREE);
9869 tree values = array_type->value_pointer_tree(gogo, array_tree);
9870 Type* element_type = array_type->element_type();
9871 Btype* belement_type = element_type->get_backend(gogo);
9872 tree element_type_tree = type_to_tree(belement_type);
9873 if (element_type_tree == error_mark_node)
9874 return error_mark_node;
9875 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9876 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9877 start_tree, element_size);
9878 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9879 TREE_TYPE(values), values, offset);
9880 return build_fold_indirect_ref(ptr);
9887 if (this->end_->is_nil_expression())
9888 end_tree = length_tree;
9891 end_tree = this->end_->get_tree(context);
9892 if (end_tree == error_mark_node)
9893 return error_mark_node;
9894 if (!DECL_P(end_tree))
9895 end_tree = save_expr(end_tree);
9896 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9897 end_tree = convert_to_integer(length_type, end_tree);
9899 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9902 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9904 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9906 fold_build2_loc(loc.gcc_location(),
9907 LT_EXPR, boolean_type_node,
9908 end_tree, start_tree),
9909 fold_build2_loc(loc.gcc_location(),
9910 GT_EXPR, boolean_type_node,
9911 end_tree, capacity_tree));
9912 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9913 boolean_type_node, bad_index, bad_end);
9916 Type* element_type = array_type->element_type();
9917 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9918 if (element_type_tree == error_mark_node)
9919 return error_mark_node;
9920 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9922 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9923 fold_convert_loc(loc.gcc_location(), sizetype,
9927 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9928 if (value_pointer == error_mark_node)
9929 return error_mark_node;
9931 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9932 TREE_TYPE(value_pointer),
9933 value_pointer, offset);
9935 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9936 length_type, end_tree, start_tree);
9938 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9939 length_type, capacity_tree,
9942 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9943 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9945 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9947 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9948 tree field = TYPE_FIELDS(struct_tree);
9949 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9951 elt->value = value_pointer;
9953 elt = VEC_quick_push(constructor_elt, init, NULL);
9954 field = DECL_CHAIN(field);
9955 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9957 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9958 result_length_tree);
9960 elt = VEC_quick_push(constructor_elt, init, NULL);
9961 field = DECL_CHAIN(field);
9962 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9964 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9965 result_capacity_tree);
9967 tree constructor = build_constructor(struct_tree, init);
9969 if (TREE_CONSTANT(value_pointer)
9970 && TREE_CONSTANT(result_length_tree)
9971 && TREE_CONSTANT(result_capacity_tree))
9972 TREE_CONSTANT(constructor) = 1;
9974 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9975 TREE_TYPE(constructor),
9976 build3(COND_EXPR, void_type_node,
9977 bad_index, crash, NULL_TREE),
9981 // Dump ast representation for an array index expression.
9984 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9987 Index_expression::dump_index_expression(ast_dump_context, this->array_,
9988 this->start_, this->end_);
9991 // Make an array index expression. END may be NULL.
9994 Expression::make_array_index(Expression* array, Expression* start,
9995 Expression* end, Location location)
9997 return new Array_index_expression(array, start, end, location);
10000 // A string index. This is used for both indexing and slicing.
10002 class String_index_expression : public Expression
10005 String_index_expression(Expression* string, Expression* start,
10006 Expression* end, Location location)
10007 : Expression(EXPRESSION_STRING_INDEX, location),
10008 string_(string), start_(start), end_(end)
10013 do_traverse(Traverse*);
10019 do_determine_type(const Type_context*);
10022 do_check_types(Gogo*);
10027 return Expression::make_string_index(this->string_->copy(),
10028 this->start_->copy(),
10029 (this->end_ == NULL
10031 : this->end_->copy()),
10036 do_must_eval_subexpressions_in_order(int* skip) const
10043 do_get_tree(Translate_context*);
10046 do_dump_expression(Ast_dump_context*) const;
10049 // The string we are getting a value from.
10050 Expression* string_;
10051 // The start or only index.
10052 Expression* start_;
10053 // The end index of a slice. This may be NULL for a single index,
10054 // or it may be a nil expression for the length of the string.
10058 // String index traversal.
10061 String_index_expression::do_traverse(Traverse* traverse)
10063 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10064 return TRAVERSE_EXIT;
10065 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10066 return TRAVERSE_EXIT;
10067 if (this->end_ != NULL)
10069 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10070 return TRAVERSE_EXIT;
10072 return TRAVERSE_CONTINUE;
10075 // Return the type of a string index.
10078 String_index_expression::do_type()
10080 if (this->end_ == NULL)
10081 return Type::lookup_integer_type("uint8");
10083 return this->string_->type();
10086 // Determine the type of a string index.
10089 String_index_expression::do_determine_type(const Type_context*)
10091 this->string_->determine_type_no_context();
10092 this->start_->determine_type_no_context();
10093 if (this->end_ != NULL)
10094 this->end_->determine_type_no_context();
10097 // Check types of a string index.
10100 String_index_expression::do_check_types(Gogo*)
10102 if (this->start_->type()->integer_type() == NULL)
10103 this->report_error(_("index must be integer"));
10104 if (this->end_ != NULL
10105 && this->end_->type()->integer_type() == NULL
10106 && !this->end_->is_nil_expression())
10107 this->report_error(_("slice end must be integer"));
10110 bool sval_valid = this->string_->string_constant_value(&sval);
10112 Numeric_constant inc;
10114 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10116 if (mpz_sgn(ival) < 0
10117 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10119 error_at(this->start_->location(), "string index out of bounds");
10120 this->set_is_error();
10124 if (this->end_ != NULL && !this->end_->is_nil_expression())
10126 Numeric_constant enc;
10128 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10130 if (mpz_sgn(eval) < 0
10131 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10133 error_at(this->end_->location(), "string index out of bounds");
10134 this->set_is_error();
10141 // Get a tree for a string index.
10144 String_index_expression::do_get_tree(Translate_context* context)
10146 Location loc = this->location();
10148 tree string_tree = this->string_->get_tree(context);
10149 if (string_tree == error_mark_node)
10150 return error_mark_node;
10152 if (this->string_->type()->points_to() != NULL)
10153 string_tree = build_fold_indirect_ref(string_tree);
10154 if (!DECL_P(string_tree))
10155 string_tree = save_expr(string_tree);
10156 tree string_type = TREE_TYPE(string_tree);
10158 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10159 length_tree = save_expr(length_tree);
10160 tree length_type = TREE_TYPE(length_tree);
10162 tree bad_index = boolean_false_node;
10164 tree start_tree = this->start_->get_tree(context);
10165 if (start_tree == error_mark_node)
10166 return error_mark_node;
10167 if (!DECL_P(start_tree))
10168 start_tree = save_expr(start_tree);
10169 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10170 start_tree = convert_to_integer(length_type, start_tree);
10172 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10175 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10177 int code = (this->end_ == NULL
10178 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10179 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10180 tree crash = Gogo::runtime_error(code, loc);
10182 if (this->end_ == NULL)
10184 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10185 boolean_type_node, bad_index,
10186 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10188 start_tree, length_tree));
10190 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10191 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10192 TREE_TYPE(bytes_tree),
10194 fold_convert_loc(loc.gcc_location(), sizetype,
10196 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10198 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10199 build3(COND_EXPR, void_type_node,
10200 bad_index, crash, NULL_TREE),
10206 if (this->end_->is_nil_expression())
10207 end_tree = build_int_cst(length_type, -1);
10210 end_tree = this->end_->get_tree(context);
10211 if (end_tree == error_mark_node)
10212 return error_mark_node;
10213 if (!DECL_P(end_tree))
10214 end_tree = save_expr(end_tree);
10215 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10216 end_tree = convert_to_integer(length_type, end_tree);
10218 bad_index = Expression::check_bounds(end_tree, length_type,
10221 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10225 static tree strslice_fndecl;
10226 tree ret = Gogo::call_builtin(&strslice_fndecl,
10228 "__go_string_slice",
10237 if (ret == error_mark_node)
10238 return error_mark_node;
10239 // This will panic if the bounds are out of range for the
10241 TREE_NOTHROW(strslice_fndecl) = 0;
10243 if (bad_index == boolean_false_node)
10246 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10247 build3(COND_EXPR, void_type_node,
10248 bad_index, crash, NULL_TREE),
10253 // Dump ast representation for a string index expression.
10256 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10259 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10260 this->start_, this->end_);
10263 // Make a string index expression. END may be NULL.
10266 Expression::make_string_index(Expression* string, Expression* start,
10267 Expression* end, Location location)
10269 return new String_index_expression(string, start, end, location);
10272 // Class Map_index.
10274 // Get the type of the map.
10277 Map_index_expression::get_map_type() const
10279 Map_type* mt = this->map_->type()->deref()->map_type();
10281 go_assert(saw_errors());
10285 // Map index traversal.
10288 Map_index_expression::do_traverse(Traverse* traverse)
10290 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10291 return TRAVERSE_EXIT;
10292 return Expression::traverse(&this->index_, traverse);
10295 // Return the type of a map index.
10298 Map_index_expression::do_type()
10300 Map_type* mt = this->get_map_type();
10302 return Type::make_error_type();
10303 Type* type = mt->val_type();
10304 // If this map index is in a tuple assignment, we actually return a
10305 // pointer to the value type. Tuple_map_assignment_statement is
10306 // responsible for handling this correctly. We need to get the type
10307 // right in case this gets assigned to a temporary variable.
10308 if (this->is_in_tuple_assignment_)
10309 type = Type::make_pointer_type(type);
10313 // Fix the type of a map index.
10316 Map_index_expression::do_determine_type(const Type_context*)
10318 this->map_->determine_type_no_context();
10319 Map_type* mt = this->get_map_type();
10320 Type* key_type = mt == NULL ? NULL : mt->key_type();
10321 Type_context subcontext(key_type, false);
10322 this->index_->determine_type(&subcontext);
10325 // Check types of a map index.
10328 Map_index_expression::do_check_types(Gogo*)
10330 std::string reason;
10331 Map_type* mt = this->get_map_type();
10334 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10336 if (reason.empty())
10337 this->report_error(_("incompatible type for map index"));
10340 error_at(this->location(), "incompatible type for map index (%s)",
10342 this->set_is_error();
10347 // Get a tree for a map index.
10350 Map_index_expression::do_get_tree(Translate_context* context)
10352 Map_type* type = this->get_map_type();
10354 return error_mark_node;
10356 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10357 if (valptr == error_mark_node)
10358 return error_mark_node;
10359 valptr = save_expr(valptr);
10361 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10363 if (this->is_lvalue_)
10364 return build_fold_indirect_ref(valptr);
10365 else if (this->is_in_tuple_assignment_)
10367 // Tuple_map_assignment_statement is responsible for using this
10373 Gogo* gogo = context->gogo();
10374 Btype* val_btype = type->val_type()->get_backend(gogo);
10375 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10376 return fold_build3(COND_EXPR, val_type_tree,
10377 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10378 fold_convert(TREE_TYPE(valptr),
10379 null_pointer_node)),
10380 expr_to_tree(val_zero),
10381 build_fold_indirect_ref(valptr));
10385 // Get a tree for the map index. This returns a tree which evaluates
10386 // to a pointer to a value. The pointer will be NULL if the key is
10390 Map_index_expression::get_value_pointer(Translate_context* context,
10393 Map_type* type = this->get_map_type();
10395 return error_mark_node;
10397 tree map_tree = this->map_->get_tree(context);
10398 tree index_tree = this->index_->get_tree(context);
10399 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10400 this->index_->type(),
10403 if (map_tree == error_mark_node || index_tree == error_mark_node)
10404 return error_mark_node;
10406 if (this->map_->type()->points_to() != NULL)
10407 map_tree = build_fold_indirect_ref(map_tree);
10409 // We need to pass in a pointer to the key, so stuff it into a
10413 if (current_function_decl != NULL)
10415 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10416 DECL_IGNORED_P(tmp) = 0;
10417 DECL_INITIAL(tmp) = index_tree;
10418 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10419 TREE_ADDRESSABLE(tmp) = 1;
10423 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10424 create_tmp_var_name("M"),
10425 TREE_TYPE(index_tree));
10426 DECL_EXTERNAL(tmp) = 0;
10427 TREE_PUBLIC(tmp) = 0;
10428 TREE_STATIC(tmp) = 1;
10429 DECL_ARTIFICIAL(tmp) = 1;
10430 if (!TREE_CONSTANT(index_tree))
10431 make_tmp = fold_build2_loc(this->location().gcc_location(),
10432 INIT_EXPR, void_type_node,
10436 TREE_READONLY(tmp) = 1;
10437 TREE_CONSTANT(tmp) = 1;
10438 DECL_INITIAL(tmp) = index_tree;
10439 make_tmp = NULL_TREE;
10441 rest_of_decl_compilation(tmp, 1, 0);
10444 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10445 build_fold_addr_expr_loc(this->location().gcc_location(),
10448 static tree map_index_fndecl;
10449 tree call = Gogo::call_builtin(&map_index_fndecl,
10453 const_ptr_type_node,
10454 TREE_TYPE(map_tree),
10456 const_ptr_type_node,
10460 ? boolean_true_node
10461 : boolean_false_node));
10462 if (call == error_mark_node)
10463 return error_mark_node;
10464 // This can panic on a map of interface type if the interface holds
10465 // an uncomparable or unhashable type.
10466 TREE_NOTHROW(map_index_fndecl) = 0;
10468 Type* val_type = type->val_type();
10469 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10470 if (val_type_tree == error_mark_node)
10471 return error_mark_node;
10472 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10474 tree ret = fold_convert_loc(this->location().gcc_location(),
10475 ptr_val_type_tree, call);
10476 if (make_tmp != NULL_TREE)
10477 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10481 // Dump ast representation for a map index expression
10484 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10487 Index_expression::dump_index_expression(ast_dump_context,
10488 this->map_, this->index_, NULL);
10491 // Make a map index expression.
10493 Map_index_expression*
10494 Expression::make_map_index(Expression* map, Expression* index,
10497 return new Map_index_expression(map, index, location);
10500 // Class Field_reference_expression.
10502 // Return the type of a field reference.
10505 Field_reference_expression::do_type()
10507 Type* type = this->expr_->type();
10508 if (type->is_error())
10510 Struct_type* struct_type = type->struct_type();
10511 go_assert(struct_type != NULL);
10512 return struct_type->field(this->field_index_)->type();
10515 // Check the types for a field reference.
10518 Field_reference_expression::do_check_types(Gogo*)
10520 Type* type = this->expr_->type();
10521 if (type->is_error())
10523 Struct_type* struct_type = type->struct_type();
10524 go_assert(struct_type != NULL);
10525 go_assert(struct_type->field(this->field_index_) != NULL);
10528 // Get a tree for a field reference.
10531 Field_reference_expression::do_get_tree(Translate_context* context)
10533 tree struct_tree = this->expr_->get_tree(context);
10534 if (struct_tree == error_mark_node
10535 || TREE_TYPE(struct_tree) == error_mark_node)
10536 return error_mark_node;
10537 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10538 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10539 if (field == NULL_TREE)
10541 // This can happen for a type which refers to itself indirectly
10542 // and then turns out to be erroneous.
10543 go_assert(saw_errors());
10544 return error_mark_node;
10546 for (unsigned int i = this->field_index_; i > 0; --i)
10548 field = DECL_CHAIN(field);
10549 go_assert(field != NULL_TREE);
10551 if (TREE_TYPE(field) == error_mark_node)
10552 return error_mark_node;
10553 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10557 // Dump ast representation for a field reference expression.
10560 Field_reference_expression::do_dump_expression(
10561 Ast_dump_context* ast_dump_context) const
10563 this->expr_->dump_expression(ast_dump_context);
10564 ast_dump_context->ostream() << "." << this->field_index_;
10567 // Make a reference to a qualified identifier in an expression.
10569 Field_reference_expression*
10570 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10573 return new Field_reference_expression(expr, field_index, location);
10576 // Class Interface_field_reference_expression.
10578 // Return a tree for the pointer to the function to call.
10581 Interface_field_reference_expression::get_function_tree(Translate_context*,
10584 if (this->expr_->type()->points_to() != NULL)
10585 expr = build_fold_indirect_ref(expr);
10587 tree expr_type = TREE_TYPE(expr);
10588 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10590 tree field = TYPE_FIELDS(expr_type);
10591 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10593 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10594 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10596 table = build_fold_indirect_ref(table);
10597 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10599 std::string name = Gogo::unpack_hidden_name(this->name_);
10600 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10601 field != NULL_TREE;
10602 field = DECL_CHAIN(field))
10604 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10607 go_assert(field != NULL_TREE);
10609 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10612 // Return a tree for the first argument to pass to the interface
10616 Interface_field_reference_expression::get_underlying_object_tree(
10617 Translate_context*,
10620 if (this->expr_->type()->points_to() != NULL)
10621 expr = build_fold_indirect_ref(expr);
10623 tree expr_type = TREE_TYPE(expr);
10624 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10626 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10627 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10629 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10635 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10637 return Expression::traverse(&this->expr_, traverse);
10640 // Return the type of an interface field reference.
10643 Interface_field_reference_expression::do_type()
10645 Type* expr_type = this->expr_->type();
10647 Type* points_to = expr_type->points_to();
10648 if (points_to != NULL)
10649 expr_type = points_to;
10651 Interface_type* interface_type = expr_type->interface_type();
10652 if (interface_type == NULL)
10653 return Type::make_error_type();
10655 const Typed_identifier* method = interface_type->find_method(this->name_);
10656 if (method == NULL)
10657 return Type::make_error_type();
10659 return method->type();
10662 // Determine types.
10665 Interface_field_reference_expression::do_determine_type(const Type_context*)
10667 this->expr_->determine_type_no_context();
10670 // Check the types for an interface field reference.
10673 Interface_field_reference_expression::do_check_types(Gogo*)
10675 Type* type = this->expr_->type();
10677 Type* points_to = type->points_to();
10678 if (points_to != NULL)
10681 Interface_type* interface_type = type->interface_type();
10682 if (interface_type == NULL)
10684 if (!type->is_error_type())
10685 this->report_error(_("expected interface or pointer to interface"));
10689 const Typed_identifier* method =
10690 interface_type->find_method(this->name_);
10691 if (method == NULL)
10693 error_at(this->location(), "method %qs not in interface",
10694 Gogo::message_name(this->name_).c_str());
10695 this->set_is_error();
10700 // Get a tree for a reference to a field in an interface. There is no
10701 // standard tree type representation for this: it's a function
10702 // attached to its first argument, like a Bound_method_expression.
10703 // The only places it may currently be used are in a Call_expression
10704 // or a Go_statement, which will take it apart directly. So this has
10705 // nothing to do at present.
10708 Interface_field_reference_expression::do_get_tree(Translate_context*)
10710 error_at(this->location(), "reference to method other than calling it");
10711 return error_mark_node;
10714 // Dump ast representation for an interface field reference.
10717 Interface_field_reference_expression::do_dump_expression(
10718 Ast_dump_context* ast_dump_context) const
10720 this->expr_->dump_expression(ast_dump_context);
10721 ast_dump_context->ostream() << "." << this->name_;
10724 // Make a reference to a field in an interface.
10727 Expression::make_interface_field_reference(Expression* expr,
10728 const std::string& field,
10731 return new Interface_field_reference_expression(expr, field, location);
10734 // A general selector. This is a Parser_expression for LEFT.NAME. It
10735 // is lowered after we know the type of the left hand side.
10737 class Selector_expression : public Parser_expression
10740 Selector_expression(Expression* left, const std::string& name,
10742 : Parser_expression(EXPRESSION_SELECTOR, location),
10743 left_(left), name_(name)
10748 do_traverse(Traverse* traverse)
10749 { return Expression::traverse(&this->left_, traverse); }
10752 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10757 return new Selector_expression(this->left_->copy(), this->name_,
10762 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10766 lower_method_expression(Gogo*);
10768 // The expression on the left hand side.
10770 // The name on the right hand side.
10774 // Lower a selector expression once we know the real type of the left
10778 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10781 Expression* left = this->left_;
10782 if (left->is_type_expression())
10783 return this->lower_method_expression(gogo);
10784 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10788 // Lower a method expression T.M or (*T).M. We turn this into a
10789 // function literal.
10792 Selector_expression::lower_method_expression(Gogo* gogo)
10794 Location location = this->location();
10795 Type* type = this->left_->type();
10796 const std::string& name(this->name_);
10799 if (type->points_to() == NULL)
10800 is_pointer = false;
10804 type = type->points_to();
10806 Named_type* nt = type->named_type();
10810 ("method expression requires named type or "
10811 "pointer to named type"));
10812 return Expression::make_error(location);
10816 Method* method = nt->method_function(name, &is_ambiguous);
10817 const Typed_identifier* imethod = NULL;
10818 if (method == NULL && !is_pointer)
10820 Interface_type* it = nt->interface_type();
10822 imethod = it->find_method(name);
10825 if (method == NULL && imethod == NULL)
10828 error_at(location, "type %<%s%s%> has no method %<%s%>",
10829 is_pointer ? "*" : "",
10830 nt->message_name().c_str(),
10831 Gogo::message_name(name).c_str());
10833 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10834 Gogo::message_name(name).c_str(),
10835 is_pointer ? "*" : "",
10836 nt->message_name().c_str());
10837 return Expression::make_error(location);
10840 if (method != NULL && !is_pointer && !method->is_value_method())
10842 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10843 nt->message_name().c_str(),
10844 Gogo::message_name(name).c_str());
10845 return Expression::make_error(location);
10848 // Build a new function type in which the receiver becomes the first
10850 Function_type* method_type;
10851 if (method != NULL)
10853 method_type = method->type();
10854 go_assert(method_type->is_method());
10858 method_type = imethod->type()->function_type();
10859 go_assert(method_type != NULL && !method_type->is_method());
10862 const char* const receiver_name = "$this";
10863 Typed_identifier_list* parameters = new Typed_identifier_list();
10864 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10867 const Typed_identifier_list* method_parameters = method_type->parameters();
10868 if (method_parameters != NULL)
10871 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10872 p != method_parameters->end();
10875 if (!p->name().empty())
10876 parameters->push_back(*p);
10880 snprintf(buf, sizeof buf, "$param%d", i);
10881 parameters->push_back(Typed_identifier(buf, p->type(),
10887 const Typed_identifier_list* method_results = method_type->results();
10888 Typed_identifier_list* results;
10889 if (method_results == NULL)
10893 results = new Typed_identifier_list();
10894 for (Typed_identifier_list::const_iterator p = method_results->begin();
10895 p != method_results->end();
10897 results->push_back(*p);
10900 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10902 if (method_type->is_varargs())
10903 fntype->set_is_varargs();
10905 // We generate methods which always takes a pointer to the receiver
10906 // as their first argument. If this is for a pointer type, we can
10907 // simply reuse the existing function. We use an internal hack to
10908 // get the right type.
10910 if (method != NULL && is_pointer)
10912 Named_object* mno = (method->needs_stub_method()
10913 ? method->stub_object()
10914 : method->named_object());
10915 Expression* f = Expression::make_func_reference(mno, NULL, location);
10916 f = Expression::make_cast(fntype, f, location);
10917 Type_conversion_expression* tce =
10918 static_cast<Type_conversion_expression*>(f);
10919 tce->set_may_convert_function_types();
10923 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10926 Named_object* vno = gogo->lookup(receiver_name, NULL);
10927 go_assert(vno != NULL);
10928 Expression* ve = Expression::make_var_reference(vno, location);
10930 if (method != NULL)
10931 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10933 bm = Expression::make_interface_field_reference(ve, name, location);
10935 // Even though we found the method above, if it has an error type we
10936 // may see an error here.
10937 if (bm->is_error_expression())
10939 gogo->finish_function(location);
10943 Expression_list* args;
10944 if (parameters->size() <= 1)
10948 args = new Expression_list();
10949 Typed_identifier_list::const_iterator p = parameters->begin();
10951 for (; p != parameters->end(); ++p)
10953 vno = gogo->lookup(p->name(), NULL);
10954 go_assert(vno != NULL);
10955 args->push_back(Expression::make_var_reference(vno, location));
10959 gogo->start_block(location);
10961 Call_expression* call = Expression::make_call(bm, args,
10962 method_type->is_varargs(),
10965 size_t count = call->result_count();
10968 s = Statement::make_statement(call, true);
10971 Expression_list* retvals = new Expression_list();
10973 retvals->push_back(call);
10976 for (size_t i = 0; i < count; ++i)
10977 retvals->push_back(Expression::make_call_result(call, i));
10979 s = Statement::make_return_statement(retvals, location);
10981 gogo->add_statement(s);
10983 Block* b = gogo->finish_block(location);
10985 gogo->add_block(b, location);
10987 // Lower the call in case there are multiple results.
10988 gogo->lower_block(no, b);
10990 gogo->finish_function(location);
10992 return Expression::make_func_reference(no, NULL, location);
10995 // Dump the ast for a selector expression.
10998 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11001 ast_dump_context->dump_expression(this->left_);
11002 ast_dump_context->ostream() << ".";
11003 ast_dump_context->ostream() << this->name_;
11006 // Make a selector expression.
11009 Expression::make_selector(Expression* left, const std::string& name,
11012 return new Selector_expression(left, name, location);
11015 // Implement the builtin function new.
11017 class Allocation_expression : public Expression
11020 Allocation_expression(Type* type, Location location)
11021 : Expression(EXPRESSION_ALLOCATION, location),
11027 do_traverse(Traverse* traverse)
11028 { return Type::traverse(this->type_, traverse); }
11032 { return Type::make_pointer_type(this->type_); }
11035 do_determine_type(const Type_context*)
11040 { return new Allocation_expression(this->type_, this->location()); }
11043 do_get_tree(Translate_context*);
11046 do_dump_expression(Ast_dump_context*) const;
11049 // The type we are allocating.
11053 // Return a tree for an allocation expression.
11056 Allocation_expression::do_get_tree(Translate_context* context)
11058 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11059 if (type_tree == error_mark_node)
11060 return error_mark_node;
11061 tree size_tree = TYPE_SIZE_UNIT(type_tree);
11062 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11064 if (space == error_mark_node)
11065 return error_mark_node;
11066 return fold_convert(build_pointer_type(type_tree), space);
11069 // Dump ast representation for an allocation expression.
11072 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11075 ast_dump_context->ostream() << "new(";
11076 ast_dump_context->dump_type(this->type_);
11077 ast_dump_context->ostream() << ")";
11080 // Make an allocation expression.
11083 Expression::make_allocation(Type* type, Location location)
11085 return new Allocation_expression(type, location);
11088 // Construct a struct.
11090 class Struct_construction_expression : public Expression
11093 Struct_construction_expression(Type* type, Expression_list* vals,
11095 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11096 type_(type), vals_(vals), traverse_order_(NULL)
11099 // Set the traversal order, used to ensure that we implement the
11100 // order of evaluation rules. Takes ownership of the argument.
11102 set_traverse_order(std::vector<int>* traverse_order)
11103 { this->traverse_order_ = traverse_order; }
11105 // Return whether this is a constant initializer.
11107 is_constant_struct() const;
11111 do_traverse(Traverse* traverse);
11115 { return this->type_; }
11118 do_determine_type(const Type_context*);
11121 do_check_types(Gogo*);
11126 Struct_construction_expression* ret =
11127 new Struct_construction_expression(this->type_, this->vals_->copy(),
11129 if (this->traverse_order_ != NULL)
11130 ret->set_traverse_order(this->traverse_order_);
11135 do_get_tree(Translate_context*);
11138 do_export(Export*) const;
11141 do_dump_expression(Ast_dump_context*) const;
11144 // The type of the struct to construct.
11146 // The list of values, in order of the fields in the struct. A NULL
11147 // entry means that the field should be zero-initialized.
11148 Expression_list* vals_;
11149 // If not NULL, the order in which to traverse vals_. This is used
11150 // so that we implement the order of evaluation rules correctly.
11151 std::vector<int>* traverse_order_;
11157 Struct_construction_expression::do_traverse(Traverse* traverse)
11159 if (this->vals_ != NULL)
11161 if (this->traverse_order_ == NULL)
11163 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11164 return TRAVERSE_EXIT;
11168 for (std::vector<int>::const_iterator p =
11169 this->traverse_order_->begin();
11170 p != this->traverse_order_->end();
11173 if (Expression::traverse(&this->vals_->at(*p), traverse)
11175 return TRAVERSE_EXIT;
11179 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11180 return TRAVERSE_EXIT;
11181 return TRAVERSE_CONTINUE;
11184 // Return whether this is a constant initializer.
11187 Struct_construction_expression::is_constant_struct() const
11189 if (this->vals_ == NULL)
11191 for (Expression_list::const_iterator pv = this->vals_->begin();
11192 pv != this->vals_->end();
11196 && !(*pv)->is_constant()
11197 && (!(*pv)->is_composite_literal()
11198 || (*pv)->is_nonconstant_composite_literal()))
11202 const Struct_field_list* fields = this->type_->struct_type()->fields();
11203 for (Struct_field_list::const_iterator pf = fields->begin();
11204 pf != fields->end();
11207 // There are no constant constructors for interfaces.
11208 if (pf->type()->interface_type() != NULL)
11215 // Final type determination.
11218 Struct_construction_expression::do_determine_type(const Type_context*)
11220 if (this->vals_ == NULL)
11222 const Struct_field_list* fields = this->type_->struct_type()->fields();
11223 Expression_list::const_iterator pv = this->vals_->begin();
11224 for (Struct_field_list::const_iterator pf = fields->begin();
11225 pf != fields->end();
11228 if (pv == this->vals_->end())
11232 Type_context subcontext(pf->type(), false);
11233 (*pv)->determine_type(&subcontext);
11236 // Extra values are an error we will report elsewhere; we still want
11237 // to determine the type to avoid knockon errors.
11238 for (; pv != this->vals_->end(); ++pv)
11239 (*pv)->determine_type_no_context();
11245 Struct_construction_expression::do_check_types(Gogo*)
11247 if (this->vals_ == NULL)
11250 Struct_type* st = this->type_->struct_type();
11251 if (this->vals_->size() > st->field_count())
11253 this->report_error(_("too many expressions for struct"));
11257 const Struct_field_list* fields = st->fields();
11258 Expression_list::const_iterator pv = this->vals_->begin();
11260 for (Struct_field_list::const_iterator pf = fields->begin();
11261 pf != fields->end();
11264 if (pv == this->vals_->end())
11266 this->report_error(_("too few expressions for struct"));
11273 std::string reason;
11274 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11276 if (reason.empty())
11277 error_at((*pv)->location(),
11278 "incompatible type for field %d in struct construction",
11281 error_at((*pv)->location(),
11282 ("incompatible type for field %d in "
11283 "struct construction (%s)"),
11284 i + 1, reason.c_str());
11285 this->set_is_error();
11288 go_assert(pv == this->vals_->end());
11291 // Return a tree for constructing a struct.
11294 Struct_construction_expression::do_get_tree(Translate_context* context)
11296 Gogo* gogo = context->gogo();
11298 if (this->vals_ == NULL)
11300 Btype* btype = this->type_->get_backend(gogo);
11301 return expr_to_tree(gogo->backend()->zero_expression(btype));
11304 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11305 if (type_tree == error_mark_node)
11306 return error_mark_node;
11307 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11309 bool is_constant = true;
11310 const Struct_field_list* fields = this->type_->struct_type()->fields();
11311 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11313 Struct_field_list::const_iterator pf = fields->begin();
11314 Expression_list::const_iterator pv = this->vals_->begin();
11315 for (tree field = TYPE_FIELDS(type_tree);
11316 field != NULL_TREE;
11317 field = DECL_CHAIN(field), ++pf)
11319 go_assert(pf != fields->end());
11321 Btype* fbtype = pf->type()->get_backend(gogo);
11324 if (pv == this->vals_->end())
11325 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11326 else if (*pv == NULL)
11328 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11333 val = Expression::convert_for_assignment(context, pf->type(),
11335 (*pv)->get_tree(context),
11340 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11341 return error_mark_node;
11343 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11344 elt->index = field;
11346 if (!TREE_CONSTANT(val))
11347 is_constant = false;
11349 go_assert(pf == fields->end());
11351 tree ret = build_constructor(type_tree, elts);
11353 TREE_CONSTANT(ret) = 1;
11357 // Export a struct construction.
11360 Struct_construction_expression::do_export(Export* exp) const
11362 exp->write_c_string("convert(");
11363 exp->write_type(this->type_);
11364 for (Expression_list::const_iterator pv = this->vals_->begin();
11365 pv != this->vals_->end();
11368 exp->write_c_string(", ");
11370 (*pv)->export_expression(exp);
11372 exp->write_c_string(")");
11375 // Dump ast representation of a struct construction expression.
11378 Struct_construction_expression::do_dump_expression(
11379 Ast_dump_context* ast_dump_context) const
11381 ast_dump_context->dump_type(this->type_);
11382 ast_dump_context->ostream() << "{";
11383 ast_dump_context->dump_expression_list(this->vals_);
11384 ast_dump_context->ostream() << "}";
11387 // Make a struct composite literal. This used by the thunk code.
11390 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11393 go_assert(type->struct_type() != NULL);
11394 return new Struct_construction_expression(type, vals, location);
11397 // Construct an array. This class is not used directly; instead we
11398 // use the child classes, Fixed_array_construction_expression and
11399 // Open_array_construction_expression.
11401 class Array_construction_expression : public Expression
11404 Array_construction_expression(Expression_classification classification,
11406 const std::vector<unsigned long>* indexes,
11407 Expression_list* vals, Location location)
11408 : Expression(classification, location),
11409 type_(type), indexes_(indexes), vals_(vals)
11410 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11413 // Return whether this is a constant initializer.
11415 is_constant_array() const;
11417 // Return the number of elements.
11419 element_count() const
11420 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11424 do_traverse(Traverse* traverse);
11428 { return this->type_; }
11431 do_determine_type(const Type_context*);
11434 do_check_types(Gogo*);
11437 do_export(Export*) const;
11440 const std::vector<unsigned long>*
11442 { return this->indexes_; }
11444 // The list of values.
11447 { return this->vals_; }
11449 // Get a constructor tree for the array values.
11451 get_constructor_tree(Translate_context* context, tree type_tree);
11454 do_dump_expression(Ast_dump_context*) const;
11457 // The type of the array to construct.
11459 // The list of indexes into the array, one for each value. This may
11460 // be NULL, in which case the indexes start at zero and increment.
11461 const std::vector<unsigned long>* indexes_;
11462 // The list of values. This may be NULL if there are no values.
11463 Expression_list* vals_;
11469 Array_construction_expression::do_traverse(Traverse* traverse)
11471 if (this->vals_ != NULL
11472 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11473 return TRAVERSE_EXIT;
11474 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11475 return TRAVERSE_EXIT;
11476 return TRAVERSE_CONTINUE;
11479 // Return whether this is a constant initializer.
11482 Array_construction_expression::is_constant_array() const
11484 if (this->vals_ == NULL)
11487 // There are no constant constructors for interfaces.
11488 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11491 for (Expression_list::const_iterator pv = this->vals_->begin();
11492 pv != this->vals_->end();
11496 && !(*pv)->is_constant()
11497 && (!(*pv)->is_composite_literal()
11498 || (*pv)->is_nonconstant_composite_literal()))
11504 // Final type determination.
11507 Array_construction_expression::do_determine_type(const Type_context*)
11509 if (this->vals_ == NULL)
11511 Type_context subcontext(this->type_->array_type()->element_type(), false);
11512 for (Expression_list::const_iterator pv = this->vals_->begin();
11513 pv != this->vals_->end();
11517 (*pv)->determine_type(&subcontext);
11524 Array_construction_expression::do_check_types(Gogo*)
11526 if (this->vals_ == NULL)
11529 Array_type* at = this->type_->array_type();
11531 Type* element_type = at->element_type();
11532 for (Expression_list::const_iterator pv = this->vals_->begin();
11533 pv != this->vals_->end();
11537 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11539 error_at((*pv)->location(),
11540 "incompatible type for element %d in composite literal",
11542 this->set_is_error();
11547 // Get a constructor tree for the array values.
11550 Array_construction_expression::get_constructor_tree(Translate_context* context,
11553 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11554 (this->vals_ == NULL
11556 : this->vals_->size()));
11557 Type* element_type = this->type_->array_type()->element_type();
11558 bool is_constant = true;
11559 if (this->vals_ != NULL)
11562 std::vector<unsigned long>::const_iterator pi;
11563 if (this->indexes_ != NULL)
11564 pi = this->indexes_->begin();
11565 for (Expression_list::const_iterator pv = this->vals_->begin();
11566 pv != this->vals_->end();
11569 if (this->indexes_ != NULL)
11570 go_assert(pi != this->indexes_->end());
11571 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11573 if (this->indexes_ == NULL)
11574 elt->index = size_int(i);
11576 elt->index = size_int(*pi);
11580 Gogo* gogo = context->gogo();
11581 Btype* ebtype = element_type->get_backend(gogo);
11582 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11583 elt->value = expr_to_tree(zv);
11587 tree value_tree = (*pv)->get_tree(context);
11588 elt->value = Expression::convert_for_assignment(context,
11594 if (elt->value == error_mark_node)
11595 return error_mark_node;
11596 if (!TREE_CONSTANT(elt->value))
11597 is_constant = false;
11598 if (this->indexes_ != NULL)
11601 if (this->indexes_ != NULL)
11602 go_assert(pi == this->indexes_->end());
11605 tree ret = build_constructor(type_tree, values);
11607 TREE_CONSTANT(ret) = 1;
11611 // Export an array construction.
11614 Array_construction_expression::do_export(Export* exp) const
11616 exp->write_c_string("convert(");
11617 exp->write_type(this->type_);
11618 if (this->vals_ != NULL)
11620 std::vector<unsigned long>::const_iterator pi;
11621 if (this->indexes_ != NULL)
11622 pi = this->indexes_->begin();
11623 for (Expression_list::const_iterator pv = this->vals_->begin();
11624 pv != this->vals_->end();
11627 exp->write_c_string(", ");
11629 if (this->indexes_ != NULL)
11632 snprintf(buf, sizeof buf, "%lu", *pi);
11633 exp->write_c_string(buf);
11634 exp->write_c_string(":");
11638 (*pv)->export_expression(exp);
11640 if (this->indexes_ != NULL)
11644 exp->write_c_string(")");
11647 // Dump ast representation of an array construction expressin.
11650 Array_construction_expression::do_dump_expression(
11651 Ast_dump_context* ast_dump_context) const
11653 Expression* length = this->type_->array_type()->length();
11655 ast_dump_context->ostream() << "[" ;
11656 if (length != NULL)
11658 ast_dump_context->dump_expression(length);
11660 ast_dump_context->ostream() << "]" ;
11661 ast_dump_context->dump_type(this->type_);
11662 ast_dump_context->ostream() << "{" ;
11663 if (this->indexes_ == NULL)
11664 ast_dump_context->dump_expression_list(this->vals_);
11667 Expression_list::const_iterator pv = this->vals_->begin();
11668 for (std::vector<unsigned long>::const_iterator pi =
11669 this->indexes_->begin();
11670 pi != this->indexes_->end();
11673 if (pi != this->indexes_->begin())
11674 ast_dump_context->ostream() << ", ";
11675 ast_dump_context->ostream() << *pi << ':';
11676 ast_dump_context->dump_expression(*pv);
11679 ast_dump_context->ostream() << "}" ;
11683 // Construct a fixed array.
11685 class Fixed_array_construction_expression :
11686 public Array_construction_expression
11689 Fixed_array_construction_expression(Type* type,
11690 const std::vector<unsigned long>* indexes,
11691 Expression_list* vals, Location location)
11692 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11693 type, indexes, vals, location)
11694 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11700 return new Fixed_array_construction_expression(this->type(),
11702 (this->vals() == NULL
11704 : this->vals()->copy()),
11709 do_get_tree(Translate_context*);
11712 // Return a tree for constructing a fixed array.
11715 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11717 Type* type = this->type();
11718 Btype* btype = type->get_backend(context->gogo());
11719 return this->get_constructor_tree(context, type_to_tree(btype));
11722 // Construct an open array.
11724 class Open_array_construction_expression : public Array_construction_expression
11727 Open_array_construction_expression(Type* type,
11728 const std::vector<unsigned long>* indexes,
11729 Expression_list* vals, Location location)
11730 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11731 type, indexes, vals, location)
11732 { go_assert(type->is_slice_type()); }
11735 // Note that taking the address of an open array literal is invalid.
11740 return new Open_array_construction_expression(this->type(),
11742 (this->vals() == NULL
11744 : this->vals()->copy()),
11749 do_get_tree(Translate_context*);
11752 // Return a tree for constructing an open array.
11755 Open_array_construction_expression::do_get_tree(Translate_context* context)
11757 Array_type* array_type = this->type()->array_type();
11758 if (array_type == NULL)
11760 go_assert(this->type()->is_error());
11761 return error_mark_node;
11764 Type* element_type = array_type->element_type();
11765 Btype* belement_type = element_type->get_backend(context->gogo());
11766 tree element_type_tree = type_to_tree(belement_type);
11767 if (element_type_tree == error_mark_node)
11768 return error_mark_node;
11772 if (this->vals() == NULL || this->vals()->empty())
11774 // We need to create a unique value.
11775 tree max = size_int(0);
11776 tree constructor_type = build_array_type(element_type_tree,
11777 build_index_type(max));
11778 if (constructor_type == error_mark_node)
11779 return error_mark_node;
11780 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11781 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11782 elt->index = size_int(0);
11783 Gogo* gogo = context->gogo();
11784 Btype* btype = element_type->get_backend(gogo);
11785 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11786 values = build_constructor(constructor_type, vec);
11787 if (TREE_CONSTANT(elt->value))
11788 TREE_CONSTANT(values) = 1;
11789 length_tree = size_int(0);
11793 unsigned long max_index;
11794 if (this->indexes() == NULL)
11795 max_index = this->vals()->size() - 1;
11797 max_index = this->indexes()->back();
11798 tree max_tree = size_int(max_index);
11799 tree constructor_type = build_array_type(element_type_tree,
11800 build_index_type(max_tree));
11801 if (constructor_type == error_mark_node)
11802 return error_mark_node;
11803 values = this->get_constructor_tree(context, constructor_type);
11804 length_tree = size_int(max_index + 1);
11807 if (values == error_mark_node)
11808 return error_mark_node;
11810 bool is_constant_initializer = TREE_CONSTANT(values);
11812 // We have to copy the initial values into heap memory if we are in
11813 // a function or if the values are not constants. We also have to
11814 // copy them if they may contain pointers in a non-constant context,
11815 // as otherwise the garbage collector won't see them.
11816 bool copy_to_heap = (context->function() != NULL
11817 || !is_constant_initializer
11818 || (element_type->has_pointer()
11819 && !context->is_const()));
11821 if (is_constant_initializer)
11823 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11824 create_tmp_var_name("C"), TREE_TYPE(values));
11825 DECL_EXTERNAL(tmp) = 0;
11826 TREE_PUBLIC(tmp) = 0;
11827 TREE_STATIC(tmp) = 1;
11828 DECL_ARTIFICIAL(tmp) = 1;
11831 // If we are not copying the value to the heap, we will only
11832 // initialize the value once, so we can use this directly
11833 // rather than copying it. In that case we can't make it
11834 // read-only, because the program is permitted to change it.
11835 TREE_READONLY(tmp) = 1;
11836 TREE_CONSTANT(tmp) = 1;
11838 DECL_INITIAL(tmp) = values;
11839 rest_of_decl_compilation(tmp, 1, 0);
11847 // the initializer will only run once.
11848 space = build_fold_addr_expr(values);
11853 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11854 space = context->gogo()->allocate_memory(element_type, memsize,
11856 space = save_expr(space);
11858 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11859 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11861 TREE_THIS_NOTRAP(ref) = 1;
11862 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11865 // Build a constructor for the open array.
11867 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11868 if (type_tree == error_mark_node)
11869 return error_mark_node;
11870 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11872 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11874 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11875 tree field = TYPE_FIELDS(type_tree);
11876 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11877 elt->index = field;
11878 elt->value = fold_convert(TREE_TYPE(field), space);
11880 elt = VEC_quick_push(constructor_elt, init, NULL);
11881 field = DECL_CHAIN(field);
11882 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11883 elt->index = field;
11884 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11886 elt = VEC_quick_push(constructor_elt, init, NULL);
11887 field = DECL_CHAIN(field);
11888 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11889 elt->index = field;
11890 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11892 tree constructor = build_constructor(type_tree, init);
11893 if (constructor == error_mark_node)
11894 return error_mark_node;
11896 TREE_CONSTANT(constructor) = 1;
11898 if (set == NULL_TREE)
11899 return constructor;
11901 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11904 // Make a slice composite literal. This is used by the type
11905 // descriptor code.
11908 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11911 go_assert(type->is_slice_type());
11912 return new Open_array_construction_expression(type, NULL, vals, location);
11915 // Construct a map.
11917 class Map_construction_expression : public Expression
11920 Map_construction_expression(Type* type, Expression_list* vals,
11922 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11923 type_(type), vals_(vals)
11924 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11928 do_traverse(Traverse* traverse);
11932 { return this->type_; }
11935 do_determine_type(const Type_context*);
11938 do_check_types(Gogo*);
11943 return new Map_construction_expression(this->type_, this->vals_->copy(),
11948 do_get_tree(Translate_context*);
11951 do_export(Export*) const;
11954 do_dump_expression(Ast_dump_context*) const;
11957 // The type of the map to construct.
11959 // The list of values.
11960 Expression_list* vals_;
11966 Map_construction_expression::do_traverse(Traverse* traverse)
11968 if (this->vals_ != NULL
11969 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11970 return TRAVERSE_EXIT;
11971 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11972 return TRAVERSE_EXIT;
11973 return TRAVERSE_CONTINUE;
11976 // Final type determination.
11979 Map_construction_expression::do_determine_type(const Type_context*)
11981 if (this->vals_ == NULL)
11984 Map_type* mt = this->type_->map_type();
11985 Type_context key_context(mt->key_type(), false);
11986 Type_context val_context(mt->val_type(), false);
11987 for (Expression_list::const_iterator pv = this->vals_->begin();
11988 pv != this->vals_->end();
11991 (*pv)->determine_type(&key_context);
11993 (*pv)->determine_type(&val_context);
12000 Map_construction_expression::do_check_types(Gogo*)
12002 if (this->vals_ == NULL)
12005 Map_type* mt = this->type_->map_type();
12007 Type* key_type = mt->key_type();
12008 Type* val_type = mt->val_type();
12009 for (Expression_list::const_iterator pv = this->vals_->begin();
12010 pv != this->vals_->end();
12013 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12015 error_at((*pv)->location(),
12016 "incompatible type for element %d key in map construction",
12018 this->set_is_error();
12021 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12023 error_at((*pv)->location(),
12024 ("incompatible type for element %d value "
12025 "in map construction"),
12027 this->set_is_error();
12032 // Return a tree for constructing a map.
12035 Map_construction_expression::do_get_tree(Translate_context* context)
12037 Gogo* gogo = context->gogo();
12038 Location loc = this->location();
12040 Map_type* mt = this->type_->map_type();
12042 // Build a struct to hold the key and value.
12043 tree struct_type = make_node(RECORD_TYPE);
12045 Type* key_type = mt->key_type();
12046 tree id = get_identifier("__key");
12047 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12048 if (key_type_tree == error_mark_node)
12049 return error_mark_node;
12050 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12052 DECL_CONTEXT(key_field) = struct_type;
12053 TYPE_FIELDS(struct_type) = key_field;
12055 Type* val_type = mt->val_type();
12056 id = get_identifier("__val");
12057 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12058 if (val_type_tree == error_mark_node)
12059 return error_mark_node;
12060 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12062 DECL_CONTEXT(val_field) = struct_type;
12063 DECL_CHAIN(key_field) = val_field;
12065 layout_type(struct_type);
12067 bool is_constant = true;
12072 if (this->vals_ == NULL || this->vals_->empty())
12074 valaddr = null_pointer_node;
12075 make_tmp = NULL_TREE;
12079 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12080 this->vals_->size() / 2);
12082 for (Expression_list::const_iterator pv = this->vals_->begin();
12083 pv != this->vals_->end();
12086 bool one_is_constant = true;
12088 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12090 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12091 elt->index = key_field;
12092 tree val_tree = (*pv)->get_tree(context);
12093 elt->value = Expression::convert_for_assignment(context, key_type,
12096 if (elt->value == error_mark_node)
12097 return error_mark_node;
12098 if (!TREE_CONSTANT(elt->value))
12099 one_is_constant = false;
12103 elt = VEC_quick_push(constructor_elt, one, NULL);
12104 elt->index = val_field;
12105 val_tree = (*pv)->get_tree(context);
12106 elt->value = Expression::convert_for_assignment(context, val_type,
12109 if (elt->value == error_mark_node)
12110 return error_mark_node;
12111 if (!TREE_CONSTANT(elt->value))
12112 one_is_constant = false;
12114 elt = VEC_quick_push(constructor_elt, values, NULL);
12115 elt->index = size_int(i);
12116 elt->value = build_constructor(struct_type, one);
12117 if (one_is_constant)
12118 TREE_CONSTANT(elt->value) = 1;
12120 is_constant = false;
12123 tree index_type = build_index_type(size_int(i - 1));
12124 tree array_type = build_array_type(struct_type, index_type);
12125 tree init = build_constructor(array_type, values);
12127 TREE_CONSTANT(init) = 1;
12129 if (current_function_decl != NULL)
12131 tmp = create_tmp_var(array_type, get_name(array_type));
12132 DECL_INITIAL(tmp) = init;
12133 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12134 void_type_node, tmp);
12135 TREE_ADDRESSABLE(tmp) = 1;
12139 tmp = build_decl(loc.gcc_location(), VAR_DECL,
12140 create_tmp_var_name("M"), array_type);
12141 DECL_EXTERNAL(tmp) = 0;
12142 TREE_PUBLIC(tmp) = 0;
12143 TREE_STATIC(tmp) = 1;
12144 DECL_ARTIFICIAL(tmp) = 1;
12145 if (!TREE_CONSTANT(init))
12146 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
12147 void_type_node, tmp, init);
12150 TREE_READONLY(tmp) = 1;
12151 TREE_CONSTANT(tmp) = 1;
12152 DECL_INITIAL(tmp) = init;
12153 make_tmp = NULL_TREE;
12155 rest_of_decl_compilation(tmp, 1, 0);
12158 valaddr = build_fold_addr_expr(tmp);
12161 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
12163 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12164 if (type_tree == error_mark_node)
12165 return error_mark_node;
12167 static tree construct_map_fndecl;
12168 tree call = Gogo::call_builtin(&construct_map_fndecl,
12170 "__go_construct_map",
12173 TREE_TYPE(descriptor),
12178 TYPE_SIZE_UNIT(struct_type),
12180 byte_position(val_field),
12182 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
12183 const_ptr_type_node,
12184 fold_convert(const_ptr_type_node, valaddr));
12185 if (call == error_mark_node)
12186 return error_mark_node;
12189 if (make_tmp == NULL)
12192 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12197 // Export an array construction.
12200 Map_construction_expression::do_export(Export* exp) const
12202 exp->write_c_string("convert(");
12203 exp->write_type(this->type_);
12204 for (Expression_list::const_iterator pv = this->vals_->begin();
12205 pv != this->vals_->end();
12208 exp->write_c_string(", ");
12209 (*pv)->export_expression(exp);
12211 exp->write_c_string(")");
12214 // Dump ast representation for a map construction expression.
12217 Map_construction_expression::do_dump_expression(
12218 Ast_dump_context* ast_dump_context) const
12220 ast_dump_context->ostream() << "{" ;
12221 ast_dump_context->dump_expression_list(this->vals_, true);
12222 ast_dump_context->ostream() << "}";
12225 // A general composite literal. This is lowered to a type specific
12228 class Composite_literal_expression : public Parser_expression
12231 Composite_literal_expression(Type* type, int depth, bool has_keys,
12232 Expression_list* vals, Location location)
12233 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12234 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12239 do_traverse(Traverse* traverse);
12242 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12247 return new Composite_literal_expression(this->type_, this->depth_,
12249 (this->vals_ == NULL
12251 : this->vals_->copy()),
12256 do_dump_expression(Ast_dump_context*) const;
12260 lower_struct(Gogo*, Type*);
12263 lower_array(Type*);
12266 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12269 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12271 // The type of the composite literal.
12273 // The depth within a list of composite literals within a composite
12274 // literal, when the type is omitted.
12276 // The values to put in the composite literal.
12277 Expression_list* vals_;
12278 // If this is true, then VALS_ is a list of pairs: a key and a
12279 // value. In an array initializer, a missing key will be NULL.
12286 Composite_literal_expression::do_traverse(Traverse* traverse)
12288 if (this->vals_ != NULL
12289 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12290 return TRAVERSE_EXIT;
12291 return Type::traverse(this->type_, traverse);
12294 // Lower a generic composite literal into a specific version based on
12298 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12299 Statement_inserter* inserter, int)
12301 Type* type = this->type_;
12303 for (int depth = this->depth_; depth > 0; --depth)
12305 if (type->array_type() != NULL)
12306 type = type->array_type()->element_type();
12307 else if (type->map_type() != NULL)
12308 type = type->map_type()->val_type();
12311 if (!type->is_error())
12312 error_at(this->location(),
12313 ("may only omit types within composite literals "
12314 "of slice, array, or map type"));
12315 return Expression::make_error(this->location());
12319 Type *pt = type->points_to();
12320 bool is_pointer = false;
12328 if (type->is_error())
12329 return Expression::make_error(this->location());
12330 else if (type->struct_type() != NULL)
12331 ret = this->lower_struct(gogo, type);
12332 else if (type->array_type() != NULL)
12333 ret = this->lower_array(type);
12334 else if (type->map_type() != NULL)
12335 ret = this->lower_map(gogo, function, inserter, type);
12338 error_at(this->location(),
12339 ("expected struct, slice, array, or map type "
12340 "for composite literal"));
12341 return Expression::make_error(this->location());
12345 ret = Expression::make_heap_composite(ret, this->location());
12350 // Lower a struct composite literal.
12353 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12355 Location location = this->location();
12356 Struct_type* st = type->struct_type();
12357 if (this->vals_ == NULL || !this->has_keys_)
12359 if (this->vals_ != NULL
12360 && !this->vals_->empty()
12361 && type->named_type() != NULL
12362 && type->named_type()->named_object()->package() != NULL)
12364 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12365 pf != st->fields()->end();
12368 if (Gogo::is_hidden_name(pf->field_name()))
12369 error_at(this->location(),
12370 "assignment of unexported field %qs in %qs literal",
12371 Gogo::message_name(pf->field_name()).c_str(),
12372 type->named_type()->message_name().c_str());
12376 return new Struct_construction_expression(type, this->vals_, location);
12379 size_t field_count = st->field_count();
12380 std::vector<Expression*> vals(field_count);
12381 std::vector<int>* traverse_order = new(std::vector<int>);
12382 Expression_list::const_iterator p = this->vals_->begin();
12383 while (p != this->vals_->end())
12385 Expression* name_expr = *p;
12388 go_assert(p != this->vals_->end());
12389 Expression* val = *p;
12393 if (name_expr == NULL)
12395 error_at(val->location(), "mixture of field and value initializers");
12396 return Expression::make_error(location);
12399 bool bad_key = false;
12401 const Named_object* no = NULL;
12402 switch (name_expr->classification())
12404 case EXPRESSION_UNKNOWN_REFERENCE:
12405 name = name_expr->unknown_expression()->name();
12408 case EXPRESSION_CONST_REFERENCE:
12409 no = static_cast<Const_expression*>(name_expr)->named_object();
12412 case EXPRESSION_TYPE:
12414 Type* t = name_expr->type();
12415 Named_type* nt = t->named_type();
12419 no = nt->named_object();
12423 case EXPRESSION_VAR_REFERENCE:
12424 no = name_expr->var_expression()->named_object();
12427 case EXPRESSION_FUNC_REFERENCE:
12428 no = name_expr->func_expression()->named_object();
12431 case EXPRESSION_UNARY:
12432 // If there is a local variable around with the same name as
12433 // the field, and this occurs in the closure, then the
12434 // parser may turn the field reference into an indirection
12435 // through the closure. FIXME: This is a mess.
12438 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12439 if (ue->op() == OPERATOR_MULT)
12441 Field_reference_expression* fre =
12442 ue->operand()->field_reference_expression();
12446 fre->expr()->type()->deref()->struct_type();
12449 const Struct_field* sf = st->field(fre->field_index());
12450 name = sf->field_name();
12452 // See below. FIXME.
12453 if (!Gogo::is_hidden_name(name)
12457 if (gogo->lookup_global(name.c_str()) != NULL)
12458 name = gogo->pack_hidden_name(name, false);
12462 snprintf(buf, sizeof buf, "%u", fre->field_index());
12463 size_t buflen = strlen(buf);
12464 if (name.compare(name.length() - buflen, buflen, buf)
12467 name = name.substr(0, name.length() - buflen);
12482 error_at(name_expr->location(), "expected struct field name");
12483 return Expression::make_error(location);
12490 // A predefined name won't be packed. If it starts with a
12491 // lower case letter we need to check for that case, because
12492 // the field name will be packed. FIXME.
12493 if (!Gogo::is_hidden_name(name)
12497 Named_object* gno = gogo->lookup_global(name.c_str());
12499 name = gogo->pack_hidden_name(name, false);
12503 unsigned int index;
12504 const Struct_field* sf = st->find_local_field(name, &index);
12507 error_at(name_expr->location(), "unknown field %qs in %qs",
12508 Gogo::message_name(name).c_str(),
12509 (type->named_type() != NULL
12510 ? type->named_type()->message_name().c_str()
12511 : "unnamed struct"));
12512 return Expression::make_error(location);
12514 if (vals[index] != NULL)
12516 error_at(name_expr->location(),
12517 "duplicate value for field %qs in %qs",
12518 Gogo::message_name(name).c_str(),
12519 (type->named_type() != NULL
12520 ? type->named_type()->message_name().c_str()
12521 : "unnamed struct"));
12522 return Expression::make_error(location);
12525 if (type->named_type() != NULL
12526 && type->named_type()->named_object()->package() != NULL
12527 && Gogo::is_hidden_name(sf->field_name()))
12528 error_at(name_expr->location(),
12529 "assignment of unexported field %qs in %qs literal",
12530 Gogo::message_name(sf->field_name()).c_str(),
12531 type->named_type()->message_name().c_str());
12534 traverse_order->push_back(index);
12537 Expression_list* list = new Expression_list;
12538 list->reserve(field_count);
12539 for (size_t i = 0; i < field_count; ++i)
12540 list->push_back(vals[i]);
12542 Struct_construction_expression* ret =
12543 new Struct_construction_expression(type, list, location);
12544 ret->set_traverse_order(traverse_order);
12548 // Used to sort an index/value array.
12550 class Index_value_compare
12554 operator()(const std::pair<unsigned long, Expression*>& a,
12555 const std::pair<unsigned long, Expression*>& b)
12556 { return a.first < b.first; }
12559 // Lower an array composite literal.
12562 Composite_literal_expression::lower_array(Type* type)
12564 Location location = this->location();
12565 if (this->vals_ == NULL || !this->has_keys_)
12566 return this->make_array(type, NULL, this->vals_);
12568 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12569 indexes->reserve(this->vals_->size());
12570 bool indexes_out_of_order = false;
12571 Expression_list* vals = new Expression_list();
12572 vals->reserve(this->vals_->size());
12573 unsigned long index = 0;
12574 Expression_list::const_iterator p = this->vals_->begin();
12575 while (p != this->vals_->end())
12577 Expression* index_expr = *p;
12580 go_assert(p != this->vals_->end());
12581 Expression* val = *p;
12585 if (index_expr == NULL)
12587 if (!indexes->empty())
12588 indexes->push_back(index);
12592 if (indexes->empty() && !vals->empty())
12594 for (size_t i = 0; i < vals->size(); ++i)
12595 indexes->push_back(i);
12598 Numeric_constant nc;
12599 if (!index_expr->numeric_constant_value(&nc))
12601 error_at(index_expr->location(),
12602 "index expression is not integer constant");
12603 return Expression::make_error(location);
12606 switch (nc.to_unsigned_long(&index))
12608 case Numeric_constant::NC_UL_VALID:
12610 case Numeric_constant::NC_UL_NOTINT:
12611 error_at(index_expr->location(),
12612 "index expression is not integer constant");
12613 return Expression::make_error(location);
12614 case Numeric_constant::NC_UL_NEGATIVE:
12615 error_at(index_expr->location(), "index expression is negative");
12616 return Expression::make_error(location);
12617 case Numeric_constant::NC_UL_BIG:
12618 error_at(index_expr->location(), "index value overflow");
12619 return Expression::make_error(location);
12624 Named_type* ntype = Type::lookup_integer_type("int");
12625 Integer_type* inttype = ntype->integer_type();
12626 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12627 && index >> (inttype->bits() - 1) != 0)
12629 error_at(index_expr->location(), "index value overflow");
12630 return Expression::make_error(location);
12633 if (std::find(indexes->begin(), indexes->end(), index)
12636 error_at(index_expr->location(), "duplicate value for index %lu",
12638 return Expression::make_error(location);
12641 if (!indexes->empty() && index < indexes->back())
12642 indexes_out_of_order = true;
12644 indexes->push_back(index);
12647 vals->push_back(val);
12652 if (indexes->empty())
12658 if (indexes_out_of_order)
12660 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12663 v.reserve(indexes->size());
12664 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12665 for (Expression_list::const_iterator pe = vals->begin();
12668 v.push_back(std::make_pair(*pi, *pe));
12670 std::sort(v.begin(), v.end(), Index_value_compare());
12674 indexes = new std::vector<unsigned long>();
12675 indexes->reserve(v.size());
12676 vals = new Expression_list();
12677 vals->reserve(v.size());
12679 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12681 indexes->push_back(p->first);
12682 vals->push_back(p->second);
12686 return this->make_array(type, indexes, vals);
12689 // Actually build the array composite literal. This handles
12693 Composite_literal_expression::make_array(
12695 const std::vector<unsigned long>* indexes,
12696 Expression_list* vals)
12698 Location location = this->location();
12699 Array_type* at = type->array_type();
12701 if (at->length() != NULL && at->length()->is_nil_expression())
12706 else if (indexes != NULL)
12707 size = indexes->back() + 1;
12710 size = vals->size();
12711 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12712 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12713 && size >> (it->bits() - 1) != 0)
12715 error_at(location, "too many elements in composite literal");
12716 return Expression::make_error(location);
12721 mpz_init_set_ui(vlen, size);
12722 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12724 at = Type::make_array_type(at->element_type(), elen);
12727 else if (at->length() != NULL
12728 && !at->length()->is_error_expression()
12729 && this->vals_ != NULL)
12731 Numeric_constant nc;
12733 if (at->length()->numeric_constant_value(&nc)
12734 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12736 if (indexes == NULL)
12738 if (this->vals_->size() > val)
12740 error_at(location, "too many elements in composite literal");
12741 return Expression::make_error(location);
12746 unsigned long max = indexes->back();
12750 ("some element keys in composite literal "
12751 "are out of range"));
12752 return Expression::make_error(location);
12758 if (at->length() != NULL)
12759 return new Fixed_array_construction_expression(type, indexes, vals,
12762 return new Open_array_construction_expression(type, indexes, vals,
12766 // Lower a map composite literal.
12769 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12770 Statement_inserter* inserter,
12773 Location location = this->location();
12774 if (this->vals_ != NULL)
12776 if (!this->has_keys_)
12778 error_at(location, "map composite literal must have keys");
12779 return Expression::make_error(location);
12782 for (Expression_list::iterator p = this->vals_->begin();
12783 p != this->vals_->end();
12789 error_at((*p)->location(),
12790 "map composite literal must have keys for every value");
12791 return Expression::make_error(location);
12793 // Make sure we have lowered the key; it may not have been
12794 // lowered in order to handle keys for struct composite
12795 // literals. Lower it now to get the right error message.
12796 if ((*p)->unknown_expression() != NULL)
12798 (*p)->unknown_expression()->clear_is_composite_literal_key();
12799 gogo->lower_expression(function, inserter, &*p);
12800 go_assert((*p)->is_error_expression());
12801 return Expression::make_error(location);
12806 return new Map_construction_expression(type, this->vals_, location);
12809 // Dump ast representation for a composite literal expression.
12812 Composite_literal_expression::do_dump_expression(
12813 Ast_dump_context* ast_dump_context) const
12815 ast_dump_context->ostream() << "composite(";
12816 ast_dump_context->dump_type(this->type_);
12817 ast_dump_context->ostream() << ", {";
12818 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12819 ast_dump_context->ostream() << "})";
12822 // Make a composite literal expression.
12825 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12826 Expression_list* vals,
12829 return new Composite_literal_expression(type, depth, has_keys, vals,
12833 // Return whether this expression is a composite literal.
12836 Expression::is_composite_literal() const
12838 switch (this->classification_)
12840 case EXPRESSION_COMPOSITE_LITERAL:
12841 case EXPRESSION_STRUCT_CONSTRUCTION:
12842 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12843 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12844 case EXPRESSION_MAP_CONSTRUCTION:
12851 // Return whether this expression is a composite literal which is not
12855 Expression::is_nonconstant_composite_literal() const
12857 switch (this->classification_)
12859 case EXPRESSION_STRUCT_CONSTRUCTION:
12861 const Struct_construction_expression *psce =
12862 static_cast<const Struct_construction_expression*>(this);
12863 return !psce->is_constant_struct();
12865 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12867 const Fixed_array_construction_expression *pace =
12868 static_cast<const Fixed_array_construction_expression*>(this);
12869 return !pace->is_constant_array();
12871 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12873 const Open_array_construction_expression *pace =
12874 static_cast<const Open_array_construction_expression*>(this);
12875 return !pace->is_constant_array();
12877 case EXPRESSION_MAP_CONSTRUCTION:
12884 // Return true if this is a reference to a local variable.
12887 Expression::is_local_variable() const
12889 const Var_expression* ve = this->var_expression();
12892 const Named_object* no = ve->named_object();
12893 return (no->is_result_variable()
12894 || (no->is_variable() && !no->var_value()->is_global()));
12897 // Class Type_guard_expression.
12902 Type_guard_expression::do_traverse(Traverse* traverse)
12904 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12905 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12906 return TRAVERSE_EXIT;
12907 return TRAVERSE_CONTINUE;
12910 // Check types of a type guard expression. The expression must have
12911 // an interface type, but the actual type conversion is checked at run
12915 Type_guard_expression::do_check_types(Gogo*)
12917 // 6g permits using a type guard with unsafe.pointer; we are
12919 Type* expr_type = this->expr_->type();
12920 if (expr_type->is_unsafe_pointer_type())
12922 if (this->type_->points_to() == NULL
12923 && (this->type_->integer_type() == NULL
12924 || (this->type_->forwarded()
12925 != Type::lookup_integer_type("uintptr"))))
12926 this->report_error(_("invalid unsafe.Pointer conversion"));
12928 else if (this->type_->is_unsafe_pointer_type())
12930 if (expr_type->points_to() == NULL
12931 && (expr_type->integer_type() == NULL
12932 || (expr_type->forwarded()
12933 != Type::lookup_integer_type("uintptr"))))
12934 this->report_error(_("invalid unsafe.Pointer conversion"));
12936 else if (expr_type->interface_type() == NULL)
12938 if (!expr_type->is_error() && !this->type_->is_error())
12939 this->report_error(_("type assertion only valid for interface types"));
12940 this->set_is_error();
12942 else if (this->type_->interface_type() == NULL)
12944 std::string reason;
12945 if (!expr_type->interface_type()->implements_interface(this->type_,
12948 if (!this->type_->is_error())
12950 if (reason.empty())
12951 this->report_error(_("impossible type assertion: "
12952 "type does not implement interface"));
12954 error_at(this->location(),
12955 ("impossible type assertion: "
12956 "type does not implement interface (%s)"),
12959 this->set_is_error();
12964 // Return a tree for a type guard expression.
12967 Type_guard_expression::do_get_tree(Translate_context* context)
12969 Gogo* gogo = context->gogo();
12970 tree expr_tree = this->expr_->get_tree(context);
12971 if (expr_tree == error_mark_node)
12972 return error_mark_node;
12973 Type* expr_type = this->expr_->type();
12974 if ((this->type_->is_unsafe_pointer_type()
12975 && (expr_type->points_to() != NULL
12976 || expr_type->integer_type() != NULL))
12977 || (expr_type->is_unsafe_pointer_type()
12978 && this->type_->points_to() != NULL))
12979 return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12981 else if (expr_type->is_unsafe_pointer_type()
12982 && this->type_->integer_type() != NULL)
12983 return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12985 else if (this->type_->interface_type() != NULL)
12986 return Expression::convert_interface_to_interface(context, this->type_,
12987 this->expr_->type(),
12991 return Expression::convert_for_assignment(context, this->type_,
12992 this->expr_->type(), expr_tree,
12996 // Dump ast representation for a type guard expression.
12999 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13002 this->expr_->dump_expression(ast_dump_context);
13003 ast_dump_context->ostream() << ".";
13004 ast_dump_context->dump_type(this->type_);
13007 // Make a type guard expression.
13010 Expression::make_type_guard(Expression* expr, Type* type,
13013 return new Type_guard_expression(expr, type, location);
13016 // Class Heap_composite_expression.
13018 // When you take the address of a composite literal, it is allocated
13019 // on the heap. This class implements that.
13021 class Heap_composite_expression : public Expression
13024 Heap_composite_expression(Expression* expr, Location location)
13025 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13031 do_traverse(Traverse* traverse)
13032 { return Expression::traverse(&this->expr_, traverse); }
13036 { return Type::make_pointer_type(this->expr_->type()); }
13039 do_determine_type(const Type_context*)
13040 { this->expr_->determine_type_no_context(); }
13045 return Expression::make_heap_composite(this->expr_->copy(),
13050 do_get_tree(Translate_context*);
13052 // We only export global objects, and the parser does not generate
13053 // this in global scope.
13055 do_export(Export*) const
13056 { go_unreachable(); }
13059 do_dump_expression(Ast_dump_context*) const;
13062 // The composite literal which is being put on the heap.
13066 // Return a tree which allocates a composite literal on the heap.
13069 Heap_composite_expression::do_get_tree(Translate_context* context)
13071 tree expr_tree = this->expr_->get_tree(context);
13072 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13073 return error_mark_node;
13074 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13075 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13076 tree space = context->gogo()->allocate_memory(this->expr_->type(),
13077 expr_size, this->location());
13078 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13079 space = save_expr(space);
13080 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13082 TREE_THIS_NOTRAP(ref) = 1;
13083 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13084 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13086 SET_EXPR_LOCATION(ret, this->location().gcc_location());
13090 // Dump ast representation for a heap composite expression.
13093 Heap_composite_expression::do_dump_expression(
13094 Ast_dump_context* ast_dump_context) const
13096 ast_dump_context->ostream() << "&(";
13097 ast_dump_context->dump_expression(this->expr_);
13098 ast_dump_context->ostream() << ")";
13101 // Allocate a composite literal on the heap.
13104 Expression::make_heap_composite(Expression* expr, Location location)
13106 return new Heap_composite_expression(expr, location);
13109 // Class Receive_expression.
13111 // Return the type of a receive expression.
13114 Receive_expression::do_type()
13116 Channel_type* channel_type = this->channel_->type()->channel_type();
13117 if (channel_type == NULL)
13118 return Type::make_error_type();
13119 return channel_type->element_type();
13122 // Check types for a receive expression.
13125 Receive_expression::do_check_types(Gogo*)
13127 Type* type = this->channel_->type();
13128 if (type->is_error())
13130 this->set_is_error();
13133 if (type->channel_type() == NULL)
13135 this->report_error(_("expected channel"));
13138 if (!type->channel_type()->may_receive())
13140 this->report_error(_("invalid receive on send-only channel"));
13145 // Get a tree for a receive expression.
13148 Receive_expression::do_get_tree(Translate_context* context)
13150 Location loc = this->location();
13152 Channel_type* channel_type = this->channel_->type()->channel_type();
13153 if (channel_type == NULL)
13155 go_assert(this->channel_->type()->is_error());
13156 return error_mark_node;
13159 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13160 tree td_tree = td->get_tree(context);
13162 Type* element_type = channel_type->element_type();
13163 Btype* element_type_btype = element_type->get_backend(context->gogo());
13164 tree element_type_tree = type_to_tree(element_type_btype);
13166 tree channel = this->channel_->get_tree(context);
13167 if (element_type_tree == error_mark_node || channel == error_mark_node)
13168 return error_mark_node;
13170 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13173 // Dump ast representation for a receive expression.
13176 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13178 ast_dump_context->ostream() << " <- " ;
13179 ast_dump_context->dump_expression(channel_);
13182 // Make a receive expression.
13184 Receive_expression*
13185 Expression::make_receive(Expression* channel, Location location)
13187 return new Receive_expression(channel, location);
13190 // An expression which evaluates to a pointer to the type descriptor
13193 class Type_descriptor_expression : public Expression
13196 Type_descriptor_expression(Type* type, Location location)
13197 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13204 { return Type::make_type_descriptor_ptr_type(); }
13207 do_determine_type(const Type_context*)
13215 do_get_tree(Translate_context* context)
13217 return this->type_->type_descriptor_pointer(context->gogo(),
13222 do_dump_expression(Ast_dump_context*) const;
13225 // The type for which this is the descriptor.
13229 // Dump ast representation for a type descriptor expression.
13232 Type_descriptor_expression::do_dump_expression(
13233 Ast_dump_context* ast_dump_context) const
13235 ast_dump_context->dump_type(this->type_);
13238 // Make a type descriptor expression.
13241 Expression::make_type_descriptor(Type* type, Location location)
13243 return new Type_descriptor_expression(type, location);
13246 // An expression which evaluates to some characteristic of a type.
13247 // This is only used to initialize fields of a type descriptor. Using
13248 // a new expression class is slightly inefficient but gives us a good
13249 // separation between the frontend and the middle-end with regard to
13250 // how types are laid out.
13252 class Type_info_expression : public Expression
13255 Type_info_expression(Type* type, Type_info type_info)
13256 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13257 type_(type), type_info_(type_info)
13265 do_determine_type(const Type_context*)
13273 do_get_tree(Translate_context* context);
13276 do_dump_expression(Ast_dump_context*) const;
13279 // The type for which we are getting information.
13281 // What information we want.
13282 Type_info type_info_;
13285 // The type is chosen to match what the type descriptor struct
13289 Type_info_expression::do_type()
13291 switch (this->type_info_)
13293 case TYPE_INFO_SIZE:
13294 return Type::lookup_integer_type("uintptr");
13295 case TYPE_INFO_ALIGNMENT:
13296 case TYPE_INFO_FIELD_ALIGNMENT:
13297 return Type::lookup_integer_type("uint8");
13303 // Return type information in GENERIC.
13306 Type_info_expression::do_get_tree(Translate_context* context)
13308 Btype* btype = this->type_->get_backend(context->gogo());
13309 Gogo* gogo = context->gogo();
13311 switch (this->type_info_)
13313 case TYPE_INFO_SIZE:
13314 val = gogo->backend()->type_size(btype);
13316 case TYPE_INFO_ALIGNMENT:
13317 val = gogo->backend()->type_alignment(btype);
13319 case TYPE_INFO_FIELD_ALIGNMENT:
13320 val = gogo->backend()->type_field_alignment(btype);
13325 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13326 go_assert(val_type_tree != error_mark_node);
13327 return build_int_cstu(val_type_tree, val);
13330 // Dump ast representation for a type info expression.
13333 Type_info_expression::do_dump_expression(
13334 Ast_dump_context* ast_dump_context) const
13336 ast_dump_context->ostream() << "typeinfo(";
13337 ast_dump_context->dump_type(this->type_);
13338 ast_dump_context->ostream() << ",";
13339 ast_dump_context->ostream() <<
13340 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13341 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13342 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13344 ast_dump_context->ostream() << ")";
13347 // Make a type info expression.
13350 Expression::make_type_info(Type* type, Type_info type_info)
13352 return new Type_info_expression(type, type_info);
13355 // An expression which evaluates to the offset of a field within a
13356 // struct. This, like Type_info_expression, q.v., is only used to
13357 // initialize fields of a type descriptor.
13359 class Struct_field_offset_expression : public Expression
13362 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13363 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13364 Linemap::predeclared_location()),
13365 type_(type), field_(field)
13371 { return Type::lookup_integer_type("uintptr"); }
13374 do_determine_type(const Type_context*)
13382 do_get_tree(Translate_context* context);
13385 do_dump_expression(Ast_dump_context*) const;
13388 // The type of the struct.
13389 Struct_type* type_;
13391 const Struct_field* field_;
13394 // Return a struct field offset in GENERIC.
13397 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13399 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13400 if (type_tree == error_mark_node)
13401 return error_mark_node;
13403 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13404 go_assert(val_type_tree != error_mark_node);
13406 const Struct_field_list* fields = this->type_->fields();
13407 tree struct_field_tree = TYPE_FIELDS(type_tree);
13408 Struct_field_list::const_iterator p;
13409 for (p = fields->begin();
13410 p != fields->end();
13411 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13413 go_assert(struct_field_tree != NULL_TREE);
13414 if (&*p == this->field_)
13417 go_assert(&*p == this->field_);
13419 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13420 byte_position(struct_field_tree));
13423 // Dump ast representation for a struct field offset expression.
13426 Struct_field_offset_expression::do_dump_expression(
13427 Ast_dump_context* ast_dump_context) const
13429 ast_dump_context->ostream() << "unsafe.Offsetof(";
13430 ast_dump_context->dump_type(this->type_);
13431 ast_dump_context->ostream() << '.';
13432 ast_dump_context->ostream() <<
13433 Gogo::message_name(this->field_->field_name());
13434 ast_dump_context->ostream() << ")";
13437 // Make an expression for a struct field offset.
13440 Expression::make_struct_field_offset(Struct_type* type,
13441 const Struct_field* field)
13443 return new Struct_field_offset_expression(type, field);
13446 // An expression which evaluates to a pointer to the map descriptor of
13449 class Map_descriptor_expression : public Expression
13452 Map_descriptor_expression(Map_type* type, Location location)
13453 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13460 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13463 do_determine_type(const Type_context*)
13471 do_get_tree(Translate_context* context)
13473 return this->type_->map_descriptor_pointer(context->gogo(),
13478 do_dump_expression(Ast_dump_context*) const;
13481 // The type for which this is the descriptor.
13485 // Dump ast representation for a map descriptor expression.
13488 Map_descriptor_expression::do_dump_expression(
13489 Ast_dump_context* ast_dump_context) const
13491 ast_dump_context->ostream() << "map_descriptor(";
13492 ast_dump_context->dump_type(this->type_);
13493 ast_dump_context->ostream() << ")";
13496 // Make a map descriptor expression.
13499 Expression::make_map_descriptor(Map_type* type, Location location)
13501 return new Map_descriptor_expression(type, location);
13504 // An expression which evaluates to the address of an unnamed label.
13506 class Label_addr_expression : public Expression
13509 Label_addr_expression(Label* label, Location location)
13510 : Expression(EXPRESSION_LABEL_ADDR, location),
13517 { return Type::make_pointer_type(Type::make_void_type()); }
13520 do_determine_type(const Type_context*)
13525 { return new Label_addr_expression(this->label_, this->location()); }
13528 do_get_tree(Translate_context* context)
13530 return expr_to_tree(this->label_->get_addr(context, this->location()));
13534 do_dump_expression(Ast_dump_context* ast_dump_context) const
13535 { ast_dump_context->ostream() << this->label_->name(); }
13538 // The label whose address we are taking.
13542 // Make an expression for the address of an unnamed label.
13545 Expression::make_label_addr(Label* label, Location location)
13547 return new Label_addr_expression(label, location);
13550 // Import an expression. This comes at the end in order to see the
13551 // various class definitions.
13554 Expression::import_expression(Import* imp)
13556 int c = imp->peek_char();
13557 if (imp->match_c_string("- ")
13558 || imp->match_c_string("! ")
13559 || imp->match_c_string("^ "))
13560 return Unary_expression::do_import(imp);
13562 return Binary_expression::do_import(imp);
13563 else if (imp->match_c_string("true")
13564 || imp->match_c_string("false"))
13565 return Boolean_expression::do_import(imp);
13567 return String_expression::do_import(imp);
13568 else if (c == '-' || (c >= '0' && c <= '9'))
13570 // This handles integers, floats and complex constants.
13571 return Integer_expression::do_import(imp);
13573 else if (imp->match_c_string("nil"))
13574 return Nil_expression::do_import(imp);
13575 else if (imp->match_c_string("convert"))
13576 return Type_conversion_expression::do_import(imp);
13579 error_at(imp->location(), "import error: expected expression");
13580 return Expression::make_error(imp->location());
13584 // Class Expression_list.
13586 // Traverse the list.
13589 Expression_list::traverse(Traverse* traverse)
13591 for (Expression_list::iterator p = this->begin();
13597 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13598 return TRAVERSE_EXIT;
13601 return TRAVERSE_CONTINUE;
13607 Expression_list::copy()
13609 Expression_list* ret = new Expression_list();
13610 for (Expression_list::iterator p = this->begin();
13615 ret->push_back(NULL);
13617 ret->push_back((*p)->copy());
13622 // Return whether an expression list has an error expression.
13625 Expression_list::contains_error() const
13627 for (Expression_list::const_iterator p = this->begin();
13630 if (*p != NULL && (*p)->is_error_expression())
13635 // Class Numeric_constant.
13639 Numeric_constant::~Numeric_constant()
13644 // Copy constructor.
13646 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13647 : classification_(a.classification_), type_(a.type_)
13649 switch (a.classification_)
13655 mpz_init_set(this->u_.int_val, a.u_.int_val);
13658 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13661 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13663 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13671 // Assignment operator.
13674 Numeric_constant::operator=(const Numeric_constant& a)
13677 this->classification_ = a.classification_;
13678 this->type_ = a.type_;
13679 switch (a.classification_)
13685 mpz_init_set(this->u_.int_val, a.u_.int_val);
13688 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13691 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13693 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13702 // Clear the contents.
13705 Numeric_constant::clear()
13707 switch (this->classification_)
13713 mpz_clear(this->u_.int_val);
13716 mpfr_clear(this->u_.float_val);
13719 mpfr_clear(this->u_.complex_val.real);
13720 mpfr_clear(this->u_.complex_val.imag);
13725 this->classification_ = NC_INVALID;
13728 // Set to an unsigned long value.
13731 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13734 this->classification_ = NC_INT;
13735 this->type_ = type;
13736 mpz_init_set_ui(this->u_.int_val, val);
13739 // Set to an integer value.
13742 Numeric_constant::set_int(Type* type, const mpz_t val)
13745 this->classification_ = NC_INT;
13746 this->type_ = type;
13747 mpz_init_set(this->u_.int_val, val);
13750 // Set to a rune value.
13753 Numeric_constant::set_rune(Type* type, const mpz_t val)
13756 this->classification_ = NC_RUNE;
13757 this->type_ = type;
13758 mpz_init_set(this->u_.int_val, val);
13761 // Set to a floating point value.
13764 Numeric_constant::set_float(Type* type, const mpfr_t val)
13767 this->classification_ = NC_FLOAT;
13768 this->type_ = type;
13769 // Numeric constants do not have negative zero values, so remove
13770 // them here. They also don't have infinity or NaN values, but we
13771 // should never see them here.
13772 if (mpfr_zero_p(val))
13773 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
13775 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13778 // Set to a complex value.
13781 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13784 this->classification_ = NC_COMPLEX;
13785 this->type_ = type;
13786 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13787 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13790 // Get an int value.
13793 Numeric_constant::get_int(mpz_t* val) const
13795 go_assert(this->is_int());
13796 mpz_init_set(*val, this->u_.int_val);
13799 // Get a rune value.
13802 Numeric_constant::get_rune(mpz_t* val) const
13804 go_assert(this->is_rune());
13805 mpz_init_set(*val, this->u_.int_val);
13808 // Get a floating point value.
13811 Numeric_constant::get_float(mpfr_t* val) const
13813 go_assert(this->is_float());
13814 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13817 // Get a complex value.
13820 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13822 go_assert(this->is_complex());
13823 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13824 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13827 // Express value as unsigned long if possible.
13829 Numeric_constant::To_unsigned_long
13830 Numeric_constant::to_unsigned_long(unsigned long* val) const
13832 switch (this->classification_)
13836 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13838 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13840 if (!mpfr_zero_p(this->u_.complex_val.imag))
13841 return NC_UL_NOTINT;
13842 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13848 // Express integer value as unsigned long if possible.
13850 Numeric_constant::To_unsigned_long
13851 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13852 unsigned long *val) const
13854 if (mpz_sgn(ival) < 0)
13855 return NC_UL_NEGATIVE;
13856 unsigned long ui = mpz_get_ui(ival);
13857 if (mpz_cmp_ui(ival, ui) != 0)
13860 return NC_UL_VALID;
13863 // Express floating point value as unsigned long if possible.
13865 Numeric_constant::To_unsigned_long
13866 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13867 unsigned long *val) const
13869 if (!mpfr_integer_p(fval))
13870 return NC_UL_NOTINT;
13873 mpfr_get_z(ival, fval, GMP_RNDN);
13874 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13879 // Convert value to integer if possible.
13882 Numeric_constant::to_int(mpz_t* val) const
13884 switch (this->classification_)
13888 mpz_init_set(*val, this->u_.int_val);
13891 if (!mpfr_integer_p(this->u_.float_val))
13894 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13897 if (!mpfr_zero_p(this->u_.complex_val.imag)
13898 || !mpfr_integer_p(this->u_.complex_val.real))
13901 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13908 // Convert value to floating point if possible.
13911 Numeric_constant::to_float(mpfr_t* val) const
13913 switch (this->classification_)
13917 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13920 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13923 if (!mpfr_zero_p(this->u_.complex_val.imag))
13925 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13932 // Convert value to complex.
13935 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13937 switch (this->classification_)
13941 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13942 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13945 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13946 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13949 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13950 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13960 Numeric_constant::type() const
13962 if (this->type_ != NULL)
13963 return this->type_;
13964 switch (this->classification_)
13967 return Type::make_abstract_integer_type();
13969 return Type::make_abstract_character_type();
13971 return Type::make_abstract_float_type();
13973 return Type::make_abstract_complex_type();
13979 // If the constant can be expressed in TYPE, then set the type of the
13980 // constant to TYPE and return true. Otherwise return false, and, if
13981 // ISSUE_ERROR is true, report an appropriate error message.
13984 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13989 else if (type->integer_type() != NULL)
13990 ret = this->check_int_type(type->integer_type(), issue_error, loc);
13991 else if (type->float_type() != NULL)
13992 ret = this->check_float_type(type->float_type(), issue_error, loc);
13993 else if (type->complex_type() != NULL)
13994 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
13998 this->type_ = type;
14002 // Check whether the constant can be expressed in an integer type.
14005 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
14006 Location location) const
14009 switch (this->classification_)
14013 mpz_init_set(val, this->u_.int_val);
14017 if (!mpfr_integer_p(this->u_.float_val))
14020 error_at(location, "floating point constant truncated to integer");
14024 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
14028 if (!mpfr_integer_p(this->u_.complex_val.real)
14029 || !mpfr_zero_p(this->u_.complex_val.imag))
14032 error_at(location, "complex constant truncated to integer");
14036 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
14044 if (type->is_abstract())
14048 int bits = mpz_sizeinbase(val, 2);
14049 if (type->is_unsigned())
14051 // For an unsigned type we can only accept a nonnegative
14052 // number, and we must be able to represents at least BITS.
14053 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
14057 // For a signed type we need an extra bit to indicate the
14058 // sign. We have to handle the most negative integer
14060 ret = (bits + 1 <= type->bits()
14061 || (bits <= type->bits()
14062 && mpz_sgn(val) < 0
14063 && (mpz_scan1(val, 0)
14064 == static_cast<unsigned long>(type->bits() - 1))
14065 && mpz_scan0(val, type->bits()) == ULONG_MAX));
14069 if (!ret && issue_error)
14070 error_at(location, "integer constant overflow");
14075 // Check whether the constant can be expressed in a floating point
14079 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
14080 Location location) const
14083 switch (this->classification_)
14087 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
14091 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
14095 if (!mpfr_zero_p(this->u_.complex_val.imag))
14098 error_at(location, "complex constant truncated to float");
14101 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
14109 if (type->is_abstract())
14111 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
14113 // A NaN or Infinity always fits in the range of the type.
14118 mp_exp_t exp = mpfr_get_exp(val);
14120 switch (type->bits())
14132 ret = exp <= max_exp;
14137 if (!ret && issue_error)
14138 error_at(location, "floating point constant overflow");
14143 // Check whether the constant can be expressed in a complex type.
14146 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
14147 Location location) const
14149 if (type->is_abstract())
14153 switch (type->bits())
14166 switch (this->classification_)
14170 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
14174 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
14178 if (!mpfr_nan_p(this->u_.complex_val.imag)
14179 && !mpfr_inf_p(this->u_.complex_val.imag)
14180 && !mpfr_zero_p(this->u_.complex_val.imag))
14182 if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
14185 error_at(location, "complex imaginary part overflow");
14189 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
14197 if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
14200 ret = mpfr_get_exp(real) <= max_exp;
14204 if (!ret && issue_error)
14205 error_at(location, "complex real part overflow");
14210 // Return an Expression for this value.
14213 Numeric_constant::expression(Location loc) const
14215 switch (this->classification_)
14218 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
14220 return Expression::make_character(&this->u_.int_val, this->type_, loc);
14222 return Expression::make_float(&this->u_.float_val, this->type_, loc);
14224 return Expression::make_complex(&this->u_.complex_val.real,
14225 &this->u_.complex_val.imag,