compiler: Use backend interface for set and use temporaries.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blobc52b3968c2c3227de80ea9911c2b4dfd69acbed1
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.
7 #include "go-system.h"
9 #include <algorithm>
11 #include "toplev.h"
12 #include "intl.h"
13 #include "tree.h"
14 #include "stringpool.h"
15 #include "stor-layout.h"
16 #include "gimple-expr.h"
17 #include "tree-iterator.h"
18 #include "convert.h"
19 #include "real.h"
20 #include "realmpfr.h"
22 #include "go-c.h"
23 #include "gogo.h"
24 #include "types.h"
25 #include "export.h"
26 #include "import.h"
27 #include "statements.h"
28 #include "lex.h"
29 #include "runtime.h"
30 #include "backend.h"
31 #include "expressions.h"
32 #include "ast-dump.h"
34 // Class Expression.
36 Expression::Expression(Expression_classification classification,
37 Location location)
38 : classification_(classification), location_(location)
42 Expression::~Expression()
46 // Traverse the expressions.
48 int
49 Expression::traverse(Expression** pexpr, Traverse* traverse)
51 Expression* expr = *pexpr;
52 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
54 int t = traverse->expression(pexpr);
55 if (t == TRAVERSE_EXIT)
56 return TRAVERSE_EXIT;
57 else if (t == TRAVERSE_SKIP_COMPONENTS)
58 return TRAVERSE_CONTINUE;
60 return expr->do_traverse(traverse);
63 // Traverse subexpressions of this expression.
65 int
66 Expression::traverse_subexpressions(Traverse* traverse)
68 return this->do_traverse(traverse);
71 // Default implementation for do_traverse for child classes.
73 int
74 Expression::do_traverse(Traverse*)
76 return TRAVERSE_CONTINUE;
79 // This virtual function is called by the parser if the value of this
80 // expression is being discarded. By default, we give an error.
81 // Expressions with side effects override.
83 bool
84 Expression::do_discarding_value()
86 this->unused_value_error();
87 return false;
90 // This virtual function is called to export expressions. This will
91 // only be used by expressions which may be constant.
93 void
94 Expression::do_export(Export*) const
96 go_unreachable();
99 // Give an error saying that the value of the expression is not used.
101 void
102 Expression::unused_value_error()
104 this->report_error(_("value computed is not used"));
107 // Note that this expression is an error. This is called by children
108 // when they discover an error.
110 void
111 Expression::set_is_error()
113 this->classification_ = EXPRESSION_ERROR;
116 // For children to call to report an error conveniently.
118 void
119 Expression::report_error(const char* msg)
121 error_at(this->location_, "%s", msg);
122 this->set_is_error();
125 // Set types of variables and constants. This is implemented by the
126 // child class.
128 void
129 Expression::determine_type(const Type_context* context)
131 this->do_determine_type(context);
134 // Set types when there is no context.
136 void
137 Expression::determine_type_no_context()
139 Type_context context;
140 this->do_determine_type(&context);
143 // Return an expression handling any conversions which must be done during
144 // assignment.
146 Expression*
147 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
148 Expression* rhs, Location location)
150 Type* rhs_type = rhs->type();
151 if (lhs_type->is_error()
152 || rhs_type->is_error()
153 || rhs->is_error_expression())
154 return Expression::make_error(location);
156 if (lhs_type->forwarded() != rhs_type->forwarded()
157 && lhs_type->interface_type() != NULL)
159 if (rhs_type->interface_type() == NULL)
160 return Expression::convert_type_to_interface(lhs_type, rhs, location);
161 else
162 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
163 location);
165 else if (lhs_type->forwarded() != rhs_type->forwarded()
166 && rhs_type->interface_type() != NULL)
167 return Expression::convert_interface_to_type(lhs_type, rhs, location);
168 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
170 // Assigning nil to a slice.
171 mpz_t zval;
172 mpz_init_set_ui(zval, 0UL);
173 Expression* zero = Expression::make_integer(&zval, NULL, location);
174 mpz_clear(zval);
175 Expression* nil = Expression::make_nil(location);
176 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
178 else if (rhs_type->is_nil_type())
179 return Expression::make_nil(location);
180 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
182 // No conversion is needed.
183 return rhs;
185 else if (lhs_type->points_to() != NULL)
186 return Expression::make_unsafe_cast(lhs_type, rhs, location);
187 else if (lhs_type->is_numeric_type())
188 return Expression::make_cast(lhs_type, rhs, location);
189 else if ((lhs_type->struct_type() != NULL
190 && rhs_type->struct_type() != NULL)
191 || (lhs_type->array_type() != NULL
192 && rhs_type->array_type() != NULL))
194 // Avoid confusion from zero sized variables which may be
195 // represented as non-zero-sized.
196 // TODO(cmang): This check is for a GCC-specific issue, and should be
197 // removed from the frontend. FIXME.
198 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
199 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
200 if (rhs_size == 0 || lhs_size == 0)
201 return rhs;
203 // This conversion must be permitted by Go, or we wouldn't have
204 // gotten here.
205 return Expression::make_unsafe_cast(lhs_type, rhs, location);
207 else
208 return rhs;
211 // Return an expression for a conversion from a non-interface type to an
212 // interface type.
214 Expression*
215 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
216 Location location)
218 Interface_type* lhs_interface_type = lhs_type->interface_type();
219 bool lhs_is_empty = lhs_interface_type->is_empty();
221 // Since RHS_TYPE is a static type, we can create the interface
222 // method table at compile time.
224 // When setting an interface to nil, we just set both fields to
225 // NULL.
226 Type* rhs_type = rhs->type();
227 if (rhs_type->is_nil_type())
229 Expression* nil = Expression::make_nil(location);
230 return Expression::make_interface_value(lhs_type, nil, nil, location);
233 // This should have been checked already.
234 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
236 // An interface is a tuple. If LHS_TYPE is an empty interface type,
237 // then the first field is the type descriptor for RHS_TYPE.
238 // Otherwise it is the interface method table for RHS_TYPE.
239 Expression* first_field;
240 if (lhs_is_empty)
241 first_field = Expression::make_type_descriptor(rhs_type, location);
242 else
244 // Build the interface method table for this interface and this
245 // object type: a list of function pointers for each interface
246 // method.
247 Named_type* rhs_named_type = rhs_type->named_type();
248 Struct_type* rhs_struct_type = rhs_type->struct_type();
249 bool is_pointer = false;
250 if (rhs_named_type == NULL && rhs_struct_type == NULL)
252 rhs_named_type = rhs_type->deref()->named_type();
253 rhs_struct_type = rhs_type->deref()->struct_type();
254 is_pointer = true;
256 if (rhs_named_type != NULL)
257 first_field =
258 rhs_named_type->interface_method_table(lhs_interface_type,
259 is_pointer);
260 else if (rhs_struct_type != NULL)
261 first_field =
262 rhs_struct_type->interface_method_table(lhs_interface_type,
263 is_pointer);
264 else
265 first_field = Expression::make_nil(location);
268 Expression* obj;
269 if (rhs_type->points_to() != NULL)
271 // We are assigning a pointer to the interface; the interface
272 // holds the pointer itself.
273 obj = rhs;
275 else
277 // We are assigning a non-pointer value to the interface; the
278 // interface gets a copy of the value in the heap.
279 obj = Expression::make_heap_expression(rhs, location);
282 return Expression::make_interface_value(lhs_type, first_field, obj, location);
285 // Return an expression for the type descriptor of RHS.
287 Expression*
288 Expression::get_interface_type_descriptor(Expression* rhs)
290 go_assert(rhs->type()->interface_type() != NULL);
291 Location location = rhs->location();
293 // The type descriptor is the first field of an empty interface.
294 if (rhs->type()->interface_type()->is_empty())
295 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
296 location);
298 Expression* mtable =
299 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
301 Expression* descriptor =
302 Expression::make_unary(OPERATOR_MULT, mtable, location);
303 descriptor = Expression::make_field_reference(descriptor, 0, location);
304 Expression* nil = Expression::make_nil(location);
306 Expression* eq =
307 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
308 return Expression::make_conditional(eq, nil, descriptor, location);
311 // Return an expression for the conversion of an interface type to an
312 // interface type.
314 Expression*
315 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
316 bool for_type_guard,
317 Location location)
319 Interface_type* lhs_interface_type = lhs_type->interface_type();
320 bool lhs_is_empty = lhs_interface_type->is_empty();
322 // In the general case this requires runtime examination of the type
323 // method table to match it up with the interface methods.
325 // FIXME: If all of the methods in the right hand side interface
326 // also appear in the left hand side interface, then we don't need
327 // to do a runtime check, although we still need to build a new
328 // method table.
330 // Get the type descriptor for the right hand side. This will be
331 // NULL for a nil interface.
332 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
333 Expression* lhs_type_expr =
334 Expression::make_type_descriptor(lhs_type, location);
336 Expression* first_field;
337 if (for_type_guard)
339 // A type assertion fails when converting a nil interface.
340 first_field =
341 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
344 else if (lhs_is_empty)
346 // A conversion to an empty interface always succeeds, and the
347 // first field is just the type descriptor of the object.
348 first_field = rhs_type_expr;
350 else
352 // A conversion to a non-empty interface may fail, but unlike a
353 // type assertion converting nil will always succeed.
354 first_field =
355 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
356 lhs_type_expr, rhs_type_expr);
359 // The second field is simply the object pointer.
360 Expression* obj =
361 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
362 return Expression::make_interface_value(lhs_type, first_field, obj, location);
365 // Return an expression for the conversion of an interface type to a
366 // non-interface type.
368 Expression*
369 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
370 Location location)
372 // Call a function to check that the type is valid. The function
373 // will panic with an appropriate runtime type error if the type is
374 // not valid.
375 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
376 location);
377 Expression* rhs_descriptor =
378 Expression::get_interface_type_descriptor(rhs);
380 Type* rhs_type = rhs->type();
381 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
382 location);
384 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
385 location, 3, lhs_type_expr,
386 rhs_descriptor, rhs_inter_expr);
388 // If the call succeeds, pull out the value.
389 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
390 location);
392 // If the value is a pointer, then it is the value we want.
393 // Otherwise it points to the value.
394 if (lhs_type->points_to() == NULL)
396 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
397 location);
398 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
400 return Expression::make_compound(check_iface, obj, location);
403 // Convert an expression to a tree. This is implemented by the child
404 // class. Not that it is not in general safe to call this multiple
405 // times for a single expression, but that we don't catch such errors.
407 tree
408 Expression::get_tree(Translate_context* context)
410 // The child may have marked this expression as having an error.
411 if (this->classification_ == EXPRESSION_ERROR)
412 return error_mark_node;
414 return this->do_get_tree(context);
417 // Return a backend expression for VAL.
418 Bexpression*
419 Expression::backend_numeric_constant_expression(Translate_context* context,
420 Numeric_constant* val)
422 Gogo* gogo = context->gogo();
423 Type* type = val->type();
424 if (type == NULL)
425 return gogo->backend()->error_expression();
427 Btype* btype = type->get_backend(gogo);
428 Bexpression* ret;
429 if (type->integer_type() != NULL)
431 mpz_t ival;
432 if (!val->to_int(&ival))
434 go_assert(saw_errors());
435 return gogo->backend()->error_expression();
437 ret = gogo->backend()->integer_constant_expression(btype, ival);
438 mpz_clear(ival);
440 else if (type->float_type() != NULL)
442 mpfr_t fval;
443 if (!val->to_float(&fval))
445 go_assert(saw_errors());
446 return gogo->backend()->error_expression();
448 ret = gogo->backend()->float_constant_expression(btype, fval);
449 mpfr_clear(fval);
451 else if (type->complex_type() != NULL)
453 mpfr_t real;
454 mpfr_t imag;
455 if (!val->to_complex(&real, &imag))
457 go_assert(saw_errors());
458 return gogo->backend()->error_expression();
460 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
461 mpfr_clear(real);
462 mpfr_clear(imag);
464 else
465 go_unreachable();
467 return ret;
470 // Return an expression which evaluates to true if VAL, of arbitrary integer
471 // type, is negative or is more than the maximum value of the Go type "int".
473 Expression*
474 Expression::check_bounds(Expression* val, Location loc)
476 Type* val_type = val->type();
477 Type* bound_type = Type::lookup_integer_type("int");
479 int val_type_size;
480 bool val_is_unsigned = false;
481 if (val_type->integer_type() != NULL)
483 val_type_size = val_type->integer_type()->bits();
484 val_is_unsigned = val_type->integer_type()->is_unsigned();
486 else
488 if (!val_type->is_numeric_type()
489 || !Type::are_convertible(bound_type, val_type, NULL))
491 go_assert(saw_errors());
492 return Expression::make_boolean(true, loc);
495 if (val_type->complex_type() != NULL)
496 val_type_size = val_type->complex_type()->bits();
497 else
498 val_type_size = val_type->float_type()->bits();
501 Expression* negative_index = Expression::make_boolean(false, loc);
502 Expression* index_overflows = Expression::make_boolean(false, loc);
503 if (!val_is_unsigned)
505 mpz_t zval;
506 mpz_init_set_ui(zval, 0UL);
507 Expression* zero = Expression::make_integer(&zval, val_type, loc);
508 mpz_clear(zval);
510 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
513 int bound_type_size = bound_type->integer_type()->bits();
514 if (val_type_size > bound_type_size
515 || (val_type_size == bound_type_size
516 && val_is_unsigned))
518 mpz_t one;
519 mpz_init_set_ui(one, 1UL);
521 // maxval = 2^(bound_type_size - 1) - 1
522 mpz_t maxval;
523 mpz_init(maxval);
524 mpz_mul_2exp(maxval, one, bound_type_size - 1);
525 mpz_sub_ui(maxval, maxval, 1);
526 Expression* max = Expression::make_integer(&maxval, val_type, loc);
527 mpz_clear(one);
528 mpz_clear(maxval);
530 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
533 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
534 loc);
537 void
538 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
540 this->do_dump_expression(ast_dump_context);
543 // Error expressions. This are used to avoid cascading errors.
545 class Error_expression : public Expression
547 public:
548 Error_expression(Location location)
549 : Expression(EXPRESSION_ERROR, location)
552 protected:
553 bool
554 do_is_constant() const
555 { return true; }
557 bool
558 do_is_immutable() const
559 { return true; }
561 bool
562 do_numeric_constant_value(Numeric_constant* nc) const
564 nc->set_unsigned_long(NULL, 0);
565 return true;
568 bool
569 do_discarding_value()
570 { return true; }
572 Type*
573 do_type()
574 { return Type::make_error_type(); }
576 void
577 do_determine_type(const Type_context*)
580 Expression*
581 do_copy()
582 { return this; }
584 bool
585 do_is_addressable() const
586 { return true; }
588 tree
589 do_get_tree(Translate_context*)
590 { return error_mark_node; }
592 void
593 do_dump_expression(Ast_dump_context*) const;
596 // Dump the ast representation for an error expression to a dump context.
598 void
599 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
601 ast_dump_context->ostream() << "_Error_" ;
604 Expression*
605 Expression::make_error(Location location)
607 return new Error_expression(location);
610 // An expression which is really a type. This is used during parsing.
611 // It is an error if these survive after lowering.
613 class
614 Type_expression : public Expression
616 public:
617 Type_expression(Type* type, Location location)
618 : Expression(EXPRESSION_TYPE, location),
619 type_(type)
622 protected:
624 do_traverse(Traverse* traverse)
625 { return Type::traverse(this->type_, traverse); }
627 Type*
628 do_type()
629 { return this->type_; }
631 void
632 do_determine_type(const Type_context*)
635 void
636 do_check_types(Gogo*)
637 { this->report_error(_("invalid use of type")); }
639 Expression*
640 do_copy()
641 { return this; }
643 tree
644 do_get_tree(Translate_context*)
645 { go_unreachable(); }
647 void do_dump_expression(Ast_dump_context*) const;
649 private:
650 // The type which we are representing as an expression.
651 Type* type_;
654 void
655 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
657 ast_dump_context->dump_type(this->type_);
660 Expression*
661 Expression::make_type(Type* type, Location location)
663 return new Type_expression(type, location);
666 // Class Parser_expression.
668 Type*
669 Parser_expression::do_type()
671 // We should never really ask for the type of a Parser_expression.
672 // However, it can happen, at least when we have an invalid const
673 // whose initializer refers to the const itself. In that case we
674 // may ask for the type when lowering the const itself.
675 go_assert(saw_errors());
676 return Type::make_error_type();
679 // Class Var_expression.
681 // Lower a variable expression. Here we just make sure that the
682 // initialization expression of the variable has been lowered. This
683 // ensures that we will be able to determine the type of the variable
684 // if necessary.
686 Expression*
687 Var_expression::do_lower(Gogo* gogo, Named_object* function,
688 Statement_inserter* inserter, int)
690 if (this->variable_->is_variable())
692 Variable* var = this->variable_->var_value();
693 // This is either a local variable or a global variable. A
694 // reference to a variable which is local to an enclosing
695 // function will be a reference to a field in a closure.
696 if (var->is_global())
698 function = NULL;
699 inserter = NULL;
701 var->lower_init_expression(gogo, function, inserter);
703 return this;
706 // Return the type of a reference to a variable.
708 Type*
709 Var_expression::do_type()
711 if (this->variable_->is_variable())
712 return this->variable_->var_value()->type();
713 else if (this->variable_->is_result_variable())
714 return this->variable_->result_var_value()->type();
715 else
716 go_unreachable();
719 // Determine the type of a reference to a variable.
721 void
722 Var_expression::do_determine_type(const Type_context*)
724 if (this->variable_->is_variable())
725 this->variable_->var_value()->determine_type();
728 // Something takes the address of this variable. This means that we
729 // may want to move the variable onto the heap.
731 void
732 Var_expression::do_address_taken(bool escapes)
734 if (!escapes)
736 if (this->variable_->is_variable())
737 this->variable_->var_value()->set_non_escaping_address_taken();
738 else if (this->variable_->is_result_variable())
739 this->variable_->result_var_value()->set_non_escaping_address_taken();
740 else
741 go_unreachable();
743 else
745 if (this->variable_->is_variable())
746 this->variable_->var_value()->set_address_taken();
747 else if (this->variable_->is_result_variable())
748 this->variable_->result_var_value()->set_address_taken();
749 else
750 go_unreachable();
754 // Get the tree for a reference to a variable.
756 tree
757 Var_expression::do_get_tree(Translate_context* context)
759 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
760 context->function());
761 bool is_in_heap;
762 Location loc = this->location();
763 if (this->variable_->is_variable())
764 is_in_heap = this->variable_->var_value()->is_in_heap();
765 else if (this->variable_->is_result_variable())
766 is_in_heap = this->variable_->result_var_value()->is_in_heap();
767 else
768 go_unreachable();
770 Bexpression* ret = context->backend()->var_expression(bvar, loc);
771 if (is_in_heap)
772 ret = context->backend()->indirect_expression(ret, true, loc);
773 return expr_to_tree(ret);
776 // Ast dump for variable expression.
778 void
779 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
781 ast_dump_context->ostream() << this->variable_->name() ;
784 // Make a reference to a variable in an expression.
786 Expression*
787 Expression::make_var_reference(Named_object* var, Location location)
789 if (var->is_sink())
790 return Expression::make_sink(location);
792 // FIXME: Creating a new object for each reference to a variable is
793 // wasteful.
794 return new Var_expression(var, location);
797 // Class Temporary_reference_expression.
799 // The type.
801 Type*
802 Temporary_reference_expression::do_type()
804 return this->statement_->type();
807 // Called if something takes the address of this temporary variable.
808 // We never have to move temporary variables to the heap, but we do
809 // need to know that they must live in the stack rather than in a
810 // register.
812 void
813 Temporary_reference_expression::do_address_taken(bool)
815 this->statement_->set_is_address_taken();
818 // Get a tree referring to the variable.
820 tree
821 Temporary_reference_expression::do_get_tree(Translate_context* context)
823 Gogo* gogo = context->gogo();
824 Bvariable* bvar = this->statement_->get_backend_variable(context);
825 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
827 // The backend can't always represent the same set of recursive types
828 // that the Go frontend can. In some cases this means that a
829 // temporary variable won't have the right backend type. Correct
830 // that here by adding a type cast. We need to use base() to push
831 // the circularity down one level.
832 Type* stype = this->statement_->type();
833 if (!this->is_lvalue_
834 && stype->has_pointer()
835 && stype->deref()->is_void_type())
837 Btype* btype = this->type()->base()->get_backend(gogo);
838 ret = gogo->backend()->convert_expression(btype, ret, this->location());
840 return expr_to_tree(ret);
843 // Ast dump for temporary reference.
845 void
846 Temporary_reference_expression::do_dump_expression(
847 Ast_dump_context* ast_dump_context) const
849 ast_dump_context->dump_temp_variable_name(this->statement_);
852 // Make a reference to a temporary variable.
854 Temporary_reference_expression*
855 Expression::make_temporary_reference(Temporary_statement* statement,
856 Location location)
858 return new Temporary_reference_expression(statement, location);
861 // Class Set_and_use_temporary_expression.
863 // Return the type.
865 Type*
866 Set_and_use_temporary_expression::do_type()
868 return this->statement_->type();
871 // Determine the type of the expression.
873 void
874 Set_and_use_temporary_expression::do_determine_type(
875 const Type_context* context)
877 this->expr_->determine_type(context);
880 // Take the address.
882 void
883 Set_and_use_temporary_expression::do_address_taken(bool)
885 this->statement_->set_is_address_taken();
888 // Return the backend representation.
890 tree
891 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
893 Location loc = this->location();
894 Gogo* gogo = context->gogo();
895 Bvariable* bvar = this->statement_->get_backend_variable(context);
896 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
898 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
899 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
900 var_ref = gogo->backend()->var_expression(bvar, loc);
901 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
902 return expr_to_tree(ret);
905 // Dump.
907 void
908 Set_and_use_temporary_expression::do_dump_expression(
909 Ast_dump_context* ast_dump_context) const
911 ast_dump_context->ostream() << '(';
912 ast_dump_context->dump_temp_variable_name(this->statement_);
913 ast_dump_context->ostream() << " = ";
914 this->expr_->dump_expression(ast_dump_context);
915 ast_dump_context->ostream() << ')';
918 // Make a set-and-use temporary.
920 Set_and_use_temporary_expression*
921 Expression::make_set_and_use_temporary(Temporary_statement* statement,
922 Expression* expr, Location location)
924 return new Set_and_use_temporary_expression(statement, expr, location);
927 // A sink expression--a use of the blank identifier _.
929 class Sink_expression : public Expression
931 public:
932 Sink_expression(Location location)
933 : Expression(EXPRESSION_SINK, location),
934 type_(NULL), var_(NULL_TREE)
937 protected:
938 bool
939 do_discarding_value()
940 { return true; }
942 Type*
943 do_type();
945 void
946 do_determine_type(const Type_context*);
948 Expression*
949 do_copy()
950 { return new Sink_expression(this->location()); }
952 tree
953 do_get_tree(Translate_context*);
955 void
956 do_dump_expression(Ast_dump_context*) const;
958 private:
959 // The type of this sink variable.
960 Type* type_;
961 // The temporary variable we generate.
962 tree var_;
965 // Return the type of a sink expression.
967 Type*
968 Sink_expression::do_type()
970 if (this->type_ == NULL)
971 return Type::make_sink_type();
972 return this->type_;
975 // Determine the type of a sink expression.
977 void
978 Sink_expression::do_determine_type(const Type_context* context)
980 if (context->type != NULL)
981 this->type_ = context->type;
984 // Return a temporary variable for a sink expression. This will
985 // presumably be a write-only variable which the middle-end will drop.
987 tree
988 Sink_expression::do_get_tree(Translate_context* context)
990 if (this->var_ == NULL_TREE)
992 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
993 Btype* bt = this->type_->get_backend(context->gogo());
994 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
996 return this->var_;
999 // Ast dump for sink expression.
1001 void
1002 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1004 ast_dump_context->ostream() << "_" ;
1007 // Make a sink expression.
1009 Expression*
1010 Expression::make_sink(Location location)
1012 return new Sink_expression(location);
1015 // Class Func_expression.
1017 // FIXME: Can a function expression appear in a constant expression?
1018 // The value is unchanging. Initializing a constant to the address of
1019 // a function seems like it could work, though there might be little
1020 // point to it.
1022 // Traversal.
1025 Func_expression::do_traverse(Traverse* traverse)
1027 return (this->closure_ == NULL
1028 ? TRAVERSE_CONTINUE
1029 : Expression::traverse(&this->closure_, traverse));
1032 // Return the type of a function expression.
1034 Type*
1035 Func_expression::do_type()
1037 if (this->function_->is_function())
1038 return this->function_->func_value()->type();
1039 else if (this->function_->is_function_declaration())
1040 return this->function_->func_declaration_value()->type();
1041 else
1042 go_unreachable();
1045 // Get the tree for the code of a function expression.
1047 Bexpression*
1048 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1050 Function_type* fntype;
1051 if (no->is_function())
1052 fntype = no->func_value()->type();
1053 else if (no->is_function_declaration())
1054 fntype = no->func_declaration_value()->type();
1055 else
1056 go_unreachable();
1058 // Builtin functions are handled specially by Call_expression. We
1059 // can't take their address.
1060 if (fntype->is_builtin())
1062 error_at(loc,
1063 "invalid use of special builtin function %qs; must be called",
1064 no->message_name().c_str());
1065 return gogo->backend()->error_expression();
1068 Bfunction* fndecl;
1069 if (no->is_function())
1070 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1071 else if (no->is_function_declaration())
1072 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1073 else
1074 go_unreachable();
1076 return gogo->backend()->function_code_expression(fndecl, loc);
1079 // Get the tree for a function expression. This is used when we take
1080 // the address of a function rather than simply calling it. A func
1081 // value is represented as a pointer to a block of memory. The first
1082 // word of that memory is a pointer to the function code. The
1083 // remaining parts of that memory are the addresses of variables that
1084 // the function closes over.
1086 tree
1087 Func_expression::do_get_tree(Translate_context* context)
1089 // If there is no closure, just use the function descriptor.
1090 if (this->closure_ == NULL)
1092 Gogo* gogo = context->gogo();
1093 Named_object* no = this->function_;
1094 Expression* descriptor;
1095 if (no->is_function())
1096 descriptor = no->func_value()->descriptor(gogo, no);
1097 else if (no->is_function_declaration())
1099 if (no->func_declaration_value()->type()->is_builtin())
1101 error_at(this->location(),
1102 ("invalid use of special builtin function %qs; "
1103 "must be called"),
1104 no->message_name().c_str());
1105 return error_mark_node;
1107 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1109 else
1110 go_unreachable();
1112 tree dtree = descriptor->get_tree(context);
1113 if (dtree == error_mark_node)
1114 return error_mark_node;
1115 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1118 go_assert(this->function_->func_value()->enclosing() != NULL);
1120 // If there is a closure, then the closure is itself the function
1121 // expression. It is a pointer to a struct whose first field points
1122 // to the function code and whose remaining fields are the addresses
1123 // of the closed-over variables.
1124 return this->closure_->get_tree(context);
1127 // Ast dump for function.
1129 void
1130 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1132 ast_dump_context->ostream() << this->function_->name();
1133 if (this->closure_ != NULL)
1135 ast_dump_context->ostream() << " {closure = ";
1136 this->closure_->dump_expression(ast_dump_context);
1137 ast_dump_context->ostream() << "}";
1141 // Make a reference to a function in an expression.
1143 Expression*
1144 Expression::make_func_reference(Named_object* function, Expression* closure,
1145 Location location)
1147 return new Func_expression(function, closure, location);
1150 // Class Func_descriptor_expression.
1152 // Constructor.
1154 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1155 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1156 fn_(fn), dvar_(NULL)
1158 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1161 // Traversal.
1164 Func_descriptor_expression::do_traverse(Traverse*)
1166 return TRAVERSE_CONTINUE;
1169 // All function descriptors have the same type.
1171 Type* Func_descriptor_expression::descriptor_type;
1173 void
1174 Func_descriptor_expression::make_func_descriptor_type()
1176 if (Func_descriptor_expression::descriptor_type != NULL)
1177 return;
1178 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1179 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1180 Func_descriptor_expression::descriptor_type =
1181 Type::make_builtin_named_type("functionDescriptor", struct_type);
1184 Type*
1185 Func_descriptor_expression::do_type()
1187 Func_descriptor_expression::make_func_descriptor_type();
1188 return Func_descriptor_expression::descriptor_type;
1191 // The tree for a function descriptor.
1193 tree
1194 Func_descriptor_expression::do_get_tree(Translate_context* context)
1196 if (this->dvar_ != NULL)
1197 return var_to_tree(this->dvar_);
1199 Gogo* gogo = context->gogo();
1200 Named_object* no = this->fn_;
1201 Location loc = no->location();
1203 std::string var_name;
1204 if (no->package() == NULL)
1205 var_name = gogo->pkgpath_symbol();
1206 else
1207 var_name = no->package()->pkgpath_symbol();
1208 var_name.push_back('.');
1209 var_name.append(Gogo::unpack_hidden_name(no->name()));
1210 var_name.append("$descriptor");
1212 Btype* btype = this->type()->get_backend(gogo);
1214 Bvariable* bvar;
1215 if (no->package() != NULL
1216 || Linemap::is_predeclared_location(no->location()))
1217 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1218 loc);
1219 else
1221 Location bloc = Linemap::predeclared_location();
1222 bool is_hidden = ((no->is_function()
1223 && no->func_value()->enclosing() != NULL)
1224 || Gogo::is_thunk(no));
1225 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1226 btype, bloc);
1227 Expression_list* vals = new Expression_list();
1228 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1229 Expression* init =
1230 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1231 Translate_context bcontext(gogo, NULL, NULL, NULL);
1232 bcontext.set_is_const();
1233 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1234 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1235 false, btype, bloc, binit);
1238 this->dvar_ = bvar;
1239 return var_to_tree(bvar);
1242 // Print a function descriptor expression.
1244 void
1245 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1247 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1250 // Make a function descriptor expression.
1252 Func_descriptor_expression*
1253 Expression::make_func_descriptor(Named_object* fn)
1255 return new Func_descriptor_expression(fn);
1258 // Make the function descriptor type, so that it can be converted.
1260 void
1261 Expression::make_func_descriptor_type()
1263 Func_descriptor_expression::make_func_descriptor_type();
1266 // A reference to just the code of a function.
1268 class Func_code_reference_expression : public Expression
1270 public:
1271 Func_code_reference_expression(Named_object* function, Location location)
1272 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1273 function_(function)
1276 protected:
1278 do_traverse(Traverse*)
1279 { return TRAVERSE_CONTINUE; }
1281 bool
1282 do_is_immutable() const
1283 { return true; }
1285 Type*
1286 do_type()
1287 { return Type::make_pointer_type(Type::make_void_type()); }
1289 void
1290 do_determine_type(const Type_context*)
1293 Expression*
1294 do_copy()
1296 return Expression::make_func_code_reference(this->function_,
1297 this->location());
1300 tree
1301 do_get_tree(Translate_context*);
1303 void
1304 do_dump_expression(Ast_dump_context* context) const
1305 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1307 private:
1308 // The function.
1309 Named_object* function_;
1312 // Get the tree for a reference to function code.
1314 tree
1315 Func_code_reference_expression::do_get_tree(Translate_context* context)
1317 Bexpression* ret =
1318 Func_expression::get_code_pointer(context->gogo(), this->function_,
1319 this->location());
1320 return expr_to_tree(ret);
1323 // Make a reference to the code of a function.
1325 Expression*
1326 Expression::make_func_code_reference(Named_object* function, Location location)
1328 return new Func_code_reference_expression(function, location);
1331 // Class Unknown_expression.
1333 // Return the name of an unknown expression.
1335 const std::string&
1336 Unknown_expression::name() const
1338 return this->named_object_->name();
1341 // Lower a reference to an unknown name.
1343 Expression*
1344 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1346 Location location = this->location();
1347 Named_object* no = this->named_object_;
1348 Named_object* real;
1349 if (!no->is_unknown())
1350 real = no;
1351 else
1353 real = no->unknown_value()->real_named_object();
1354 if (real == NULL)
1356 if (this->is_composite_literal_key_)
1357 return this;
1358 if (!this->no_error_message_)
1359 error_at(location, "reference to undefined name %qs",
1360 this->named_object_->message_name().c_str());
1361 return Expression::make_error(location);
1364 switch (real->classification())
1366 case Named_object::NAMED_OBJECT_CONST:
1367 return Expression::make_const_reference(real, location);
1368 case Named_object::NAMED_OBJECT_TYPE:
1369 return Expression::make_type(real->type_value(), location);
1370 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1371 if (this->is_composite_literal_key_)
1372 return this;
1373 if (!this->no_error_message_)
1374 error_at(location, "reference to undefined type %qs",
1375 real->message_name().c_str());
1376 return Expression::make_error(location);
1377 case Named_object::NAMED_OBJECT_VAR:
1378 real->var_value()->set_is_used();
1379 return Expression::make_var_reference(real, location);
1380 case Named_object::NAMED_OBJECT_FUNC:
1381 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1382 return Expression::make_func_reference(real, NULL, location);
1383 case Named_object::NAMED_OBJECT_PACKAGE:
1384 if (this->is_composite_literal_key_)
1385 return this;
1386 if (!this->no_error_message_)
1387 error_at(location, "unexpected reference to package");
1388 return Expression::make_error(location);
1389 default:
1390 go_unreachable();
1394 // Dump the ast representation for an unknown expression to a dump context.
1396 void
1397 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1399 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1400 << ")";
1403 // Make a reference to an unknown name.
1405 Unknown_expression*
1406 Expression::make_unknown_reference(Named_object* no, Location location)
1408 return new Unknown_expression(no, location);
1411 // A boolean expression.
1413 class Boolean_expression : public Expression
1415 public:
1416 Boolean_expression(bool val, Location location)
1417 : Expression(EXPRESSION_BOOLEAN, location),
1418 val_(val), type_(NULL)
1421 static Expression*
1422 do_import(Import*);
1424 protected:
1425 bool
1426 do_is_constant() const
1427 { return true; }
1429 bool
1430 do_is_immutable() const
1431 { return true; }
1433 Type*
1434 do_type();
1436 void
1437 do_determine_type(const Type_context*);
1439 Expression*
1440 do_copy()
1441 { return this; }
1443 tree
1444 do_get_tree(Translate_context*)
1445 { return this->val_ ? boolean_true_node : boolean_false_node; }
1447 void
1448 do_export(Export* exp) const
1449 { exp->write_c_string(this->val_ ? "true" : "false"); }
1451 void
1452 do_dump_expression(Ast_dump_context* ast_dump_context) const
1453 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1455 private:
1456 // The constant.
1457 bool val_;
1458 // The type as determined by context.
1459 Type* type_;
1462 // Get the type.
1464 Type*
1465 Boolean_expression::do_type()
1467 if (this->type_ == NULL)
1468 this->type_ = Type::make_boolean_type();
1469 return this->type_;
1472 // Set the type from the context.
1474 void
1475 Boolean_expression::do_determine_type(const Type_context* context)
1477 if (this->type_ != NULL && !this->type_->is_abstract())
1479 else if (context->type != NULL && context->type->is_boolean_type())
1480 this->type_ = context->type;
1481 else if (!context->may_be_abstract)
1482 this->type_ = Type::lookup_bool_type();
1485 // Import a boolean constant.
1487 Expression*
1488 Boolean_expression::do_import(Import* imp)
1490 if (imp->peek_char() == 't')
1492 imp->require_c_string("true");
1493 return Expression::make_boolean(true, imp->location());
1495 else
1497 imp->require_c_string("false");
1498 return Expression::make_boolean(false, imp->location());
1502 // Make a boolean expression.
1504 Expression*
1505 Expression::make_boolean(bool val, Location location)
1507 return new Boolean_expression(val, location);
1510 // Class String_expression.
1512 // Get the type.
1514 Type*
1515 String_expression::do_type()
1517 if (this->type_ == NULL)
1518 this->type_ = Type::make_string_type();
1519 return this->type_;
1522 // Set the type from the context.
1524 void
1525 String_expression::do_determine_type(const Type_context* context)
1527 if (this->type_ != NULL && !this->type_->is_abstract())
1529 else if (context->type != NULL && context->type->is_string_type())
1530 this->type_ = context->type;
1531 else if (!context->may_be_abstract)
1532 this->type_ = Type::lookup_string_type();
1535 // Build a string constant.
1537 tree
1538 String_expression::do_get_tree(Translate_context* context)
1540 Gogo* gogo = context->gogo();
1541 Btype* btype = Type::make_string_type()->get_backend(gogo);
1543 Location loc = this->location();
1544 std::vector<Bexpression*> init(2);
1545 Bexpression* str_cst =
1546 gogo->backend()->string_constant_expression(this->val_);
1547 init[0] = gogo->backend()->address_expression(str_cst, loc);
1549 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1550 mpz_t lenval;
1551 mpz_init_set_ui(lenval, this->val_.length());
1552 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1553 mpz_clear(lenval);
1555 Bexpression* ret = gogo->backend()->constructor_expression(btype, init, loc);
1556 return expr_to_tree(ret);
1559 // Write string literal to string dump.
1561 void
1562 String_expression::export_string(String_dump* exp,
1563 const String_expression* str)
1565 std::string s;
1566 s.reserve(str->val_.length() * 4 + 2);
1567 s += '"';
1568 for (std::string::const_iterator p = str->val_.begin();
1569 p != str->val_.end();
1570 ++p)
1572 if (*p == '\\' || *p == '"')
1574 s += '\\';
1575 s += *p;
1577 else if (*p >= 0x20 && *p < 0x7f)
1578 s += *p;
1579 else if (*p == '\n')
1580 s += "\\n";
1581 else if (*p == '\t')
1582 s += "\\t";
1583 else
1585 s += "\\x";
1586 unsigned char c = *p;
1587 unsigned int dig = c >> 4;
1588 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1589 dig = c & 0xf;
1590 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1593 s += '"';
1594 exp->write_string(s);
1597 // Export a string expression.
1599 void
1600 String_expression::do_export(Export* exp) const
1602 String_expression::export_string(exp, this);
1605 // Import a string expression.
1607 Expression*
1608 String_expression::do_import(Import* imp)
1610 imp->require_c_string("\"");
1611 std::string val;
1612 while (true)
1614 int c = imp->get_char();
1615 if (c == '"' || c == -1)
1616 break;
1617 if (c != '\\')
1618 val += static_cast<char>(c);
1619 else
1621 c = imp->get_char();
1622 if (c == '\\' || c == '"')
1623 val += static_cast<char>(c);
1624 else if (c == 'n')
1625 val += '\n';
1626 else if (c == 't')
1627 val += '\t';
1628 else if (c == 'x')
1630 c = imp->get_char();
1631 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1632 c = imp->get_char();
1633 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1634 char v = (vh << 4) | vl;
1635 val += v;
1637 else
1639 error_at(imp->location(), "bad string constant");
1640 return Expression::make_error(imp->location());
1644 return Expression::make_string(val, imp->location());
1647 // Ast dump for string expression.
1649 void
1650 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1652 String_expression::export_string(ast_dump_context, this);
1655 // Make a string expression.
1657 Expression*
1658 Expression::make_string(const std::string& val, Location location)
1660 return new String_expression(val, location);
1663 // An expression that evaluates to some characteristic of a string.
1664 // This is used when indexing, bound-checking, or nil checking a string.
1666 class String_info_expression : public Expression
1668 public:
1669 String_info_expression(Expression* string, String_info string_info,
1670 Location location)
1671 : Expression(EXPRESSION_STRING_INFO, location),
1672 string_(string), string_info_(string_info)
1675 protected:
1676 Type*
1677 do_type();
1679 void
1680 do_determine_type(const Type_context*)
1681 { go_unreachable(); }
1683 Expression*
1684 do_copy()
1686 return new String_info_expression(this->string_->copy(), this->string_info_,
1687 this->location());
1690 tree
1691 do_get_tree(Translate_context* context);
1693 void
1694 do_dump_expression(Ast_dump_context*) const;
1696 void
1697 do_issue_nil_check()
1698 { this->string_->issue_nil_check(); }
1700 private:
1701 // The string for which we are getting information.
1702 Expression* string_;
1703 // What information we want.
1704 String_info string_info_;
1707 // Return the type of the string info.
1709 Type*
1710 String_info_expression::do_type()
1712 switch (this->string_info_)
1714 case STRING_INFO_DATA:
1716 Type* byte_type = Type::lookup_integer_type("uint8");
1717 return Type::make_pointer_type(byte_type);
1719 case STRING_INFO_LENGTH:
1720 return Type::lookup_integer_type("int");
1721 default:
1722 go_unreachable();
1726 // Return string information in GENERIC.
1728 tree
1729 String_info_expression::do_get_tree(Translate_context* context)
1731 Gogo* gogo = context->gogo();
1733 Bexpression* bstring = tree_to_expr(this->string_->get_tree(context));
1734 Bexpression* ret;
1735 switch (this->string_info_)
1737 case STRING_INFO_DATA:
1738 case STRING_INFO_LENGTH:
1739 ret = gogo->backend()->struct_field_expression(bstring, this->string_info_,
1740 this->location());
1741 break;
1742 default:
1743 go_unreachable();
1745 return expr_to_tree(ret);
1748 // Dump ast representation for a type info expression.
1750 void
1751 String_info_expression::do_dump_expression(
1752 Ast_dump_context* ast_dump_context) const
1754 ast_dump_context->ostream() << "stringinfo(";
1755 this->string_->dump_expression(ast_dump_context);
1756 ast_dump_context->ostream() << ",";
1757 ast_dump_context->ostream() <<
1758 (this->string_info_ == STRING_INFO_DATA ? "data"
1759 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1760 : "unknown");
1761 ast_dump_context->ostream() << ")";
1764 // Make a string info expression.
1766 Expression*
1767 Expression::make_string_info(Expression* string, String_info string_info,
1768 Location location)
1770 return new String_info_expression(string, string_info, location);
1773 // Make an integer expression.
1775 class Integer_expression : public Expression
1777 public:
1778 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1779 Location location)
1780 : Expression(EXPRESSION_INTEGER, location),
1781 type_(type), is_character_constant_(is_character_constant)
1782 { mpz_init_set(this->val_, *val); }
1784 static Expression*
1785 do_import(Import*);
1787 // Write VAL to string dump.
1788 static void
1789 export_integer(String_dump* exp, const mpz_t val);
1791 // Write VAL to dump context.
1792 static void
1793 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1795 protected:
1796 bool
1797 do_is_constant() const
1798 { return true; }
1800 bool
1801 do_is_immutable() const
1802 { return true; }
1804 bool
1805 do_numeric_constant_value(Numeric_constant* nc) const;
1807 Type*
1808 do_type();
1810 void
1811 do_determine_type(const Type_context* context);
1813 void
1814 do_check_types(Gogo*);
1816 tree
1817 do_get_tree(Translate_context*);
1819 Expression*
1820 do_copy()
1822 if (this->is_character_constant_)
1823 return Expression::make_character(&this->val_, this->type_,
1824 this->location());
1825 else
1826 return Expression::make_integer(&this->val_, this->type_,
1827 this->location());
1830 void
1831 do_export(Export*) const;
1833 void
1834 do_dump_expression(Ast_dump_context*) const;
1836 private:
1837 // The integer value.
1838 mpz_t val_;
1839 // The type so far.
1840 Type* type_;
1841 // Whether this is a character constant.
1842 bool is_character_constant_;
1845 // Return a numeric constant for this expression. We have to mark
1846 // this as a character when appropriate.
1848 bool
1849 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1851 if (this->is_character_constant_)
1852 nc->set_rune(this->type_, this->val_);
1853 else
1854 nc->set_int(this->type_, this->val_);
1855 return true;
1858 // Return the current type. If we haven't set the type yet, we return
1859 // an abstract integer type.
1861 Type*
1862 Integer_expression::do_type()
1864 if (this->type_ == NULL)
1866 if (this->is_character_constant_)
1867 this->type_ = Type::make_abstract_character_type();
1868 else
1869 this->type_ = Type::make_abstract_integer_type();
1871 return this->type_;
1874 // Set the type of the integer value. Here we may switch from an
1875 // abstract type to a real type.
1877 void
1878 Integer_expression::do_determine_type(const Type_context* context)
1880 if (this->type_ != NULL && !this->type_->is_abstract())
1882 else if (context->type != NULL && context->type->is_numeric_type())
1883 this->type_ = context->type;
1884 else if (!context->may_be_abstract)
1886 if (this->is_character_constant_)
1887 this->type_ = Type::lookup_integer_type("int32");
1888 else
1889 this->type_ = Type::lookup_integer_type("int");
1893 // Check the type of an integer constant.
1895 void
1896 Integer_expression::do_check_types(Gogo*)
1898 Type* type = this->type_;
1899 if (type == NULL)
1900 return;
1901 Numeric_constant nc;
1902 if (this->is_character_constant_)
1903 nc.set_rune(NULL, this->val_);
1904 else
1905 nc.set_int(NULL, this->val_);
1906 if (!nc.set_type(type, true, this->location()))
1907 this->set_is_error();
1910 // Get a tree for an integer constant.
1912 tree
1913 Integer_expression::do_get_tree(Translate_context* context)
1915 Type* resolved_type = NULL;
1916 if (this->type_ != NULL && !this->type_->is_abstract())
1917 resolved_type = this->type_;
1918 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1920 // We are converting to an abstract floating point type.
1921 resolved_type = Type::lookup_float_type("float64");
1923 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1925 // We are converting to an abstract complex type.
1926 resolved_type = Type::lookup_complex_type("complex128");
1928 else
1930 // If we still have an abstract type here, then this is being
1931 // used in a constant expression which didn't get reduced for
1932 // some reason. Use a type which will fit the value. We use <,
1933 // not <=, because we need an extra bit for the sign bit.
1934 int bits = mpz_sizeinbase(this->val_, 2);
1935 Type* int_type = Type::lookup_integer_type("int");
1936 if (bits < int_type->integer_type()->bits())
1937 resolved_type = int_type;
1938 else if (bits < 64)
1939 resolved_type = Type::lookup_integer_type("int64");
1940 else
1942 if (!saw_errors())
1943 error_at(this->location(),
1944 "unknown type for large integer constant");
1945 Bexpression* ret = context->gogo()->backend()->error_expression();
1946 return expr_to_tree(ret);
1949 Numeric_constant nc;
1950 nc.set_int(resolved_type, this->val_);
1951 Bexpression* ret =
1952 Expression::backend_numeric_constant_expression(context, &nc);
1953 return expr_to_tree(ret);
1956 // Write VAL to export data.
1958 void
1959 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1961 char* s = mpz_get_str(NULL, 10, val);
1962 exp->write_c_string(s);
1963 free(s);
1966 // Export an integer in a constant expression.
1968 void
1969 Integer_expression::do_export(Export* exp) const
1971 Integer_expression::export_integer(exp, this->val_);
1972 if (this->is_character_constant_)
1973 exp->write_c_string("'");
1974 // A trailing space lets us reliably identify the end of the number.
1975 exp->write_c_string(" ");
1978 // Import an integer, floating point, or complex value. This handles
1979 // all these types because they all start with digits.
1981 Expression*
1982 Integer_expression::do_import(Import* imp)
1984 std::string num = imp->read_identifier();
1985 imp->require_c_string(" ");
1986 if (!num.empty() && num[num.length() - 1] == 'i')
1988 mpfr_t real;
1989 size_t plus_pos = num.find('+', 1);
1990 size_t minus_pos = num.find('-', 1);
1991 size_t pos;
1992 if (plus_pos == std::string::npos)
1993 pos = minus_pos;
1994 else if (minus_pos == std::string::npos)
1995 pos = plus_pos;
1996 else
1998 error_at(imp->location(), "bad number in import data: %qs",
1999 num.c_str());
2000 return Expression::make_error(imp->location());
2002 if (pos == std::string::npos)
2003 mpfr_set_ui(real, 0, GMP_RNDN);
2004 else
2006 std::string real_str = num.substr(0, pos);
2007 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2009 error_at(imp->location(), "bad number in import data: %qs",
2010 real_str.c_str());
2011 return Expression::make_error(imp->location());
2015 std::string imag_str;
2016 if (pos == std::string::npos)
2017 imag_str = num;
2018 else
2019 imag_str = num.substr(pos);
2020 imag_str = imag_str.substr(0, imag_str.size() - 1);
2021 mpfr_t imag;
2022 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2024 error_at(imp->location(), "bad number in import data: %qs",
2025 imag_str.c_str());
2026 return Expression::make_error(imp->location());
2028 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2029 imp->location());
2030 mpfr_clear(real);
2031 mpfr_clear(imag);
2032 return ret;
2034 else if (num.find('.') == std::string::npos
2035 && num.find('E') == std::string::npos)
2037 bool is_character_constant = (!num.empty()
2038 && num[num.length() - 1] == '\'');
2039 if (is_character_constant)
2040 num = num.substr(0, num.length() - 1);
2041 mpz_t val;
2042 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2044 error_at(imp->location(), "bad number in import data: %qs",
2045 num.c_str());
2046 return Expression::make_error(imp->location());
2048 Expression* ret;
2049 if (is_character_constant)
2050 ret = Expression::make_character(&val, NULL, imp->location());
2051 else
2052 ret = Expression::make_integer(&val, NULL, imp->location());
2053 mpz_clear(val);
2054 return ret;
2056 else
2058 mpfr_t val;
2059 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2061 error_at(imp->location(), "bad number in import data: %qs",
2062 num.c_str());
2063 return Expression::make_error(imp->location());
2065 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2066 mpfr_clear(val);
2067 return ret;
2070 // Ast dump for integer expression.
2072 void
2073 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2075 if (this->is_character_constant_)
2076 ast_dump_context->ostream() << '\'';
2077 Integer_expression::export_integer(ast_dump_context, this->val_);
2078 if (this->is_character_constant_)
2079 ast_dump_context->ostream() << '\'';
2082 // Build a new integer value.
2084 Expression*
2085 Expression::make_integer(const mpz_t* val, Type* type, Location location)
2087 return new Integer_expression(val, type, false, location);
2090 // Build a new character constant value.
2092 Expression*
2093 Expression::make_character(const mpz_t* val, Type* type, Location location)
2095 return new Integer_expression(val, type, true, location);
2098 // Floats.
2100 class Float_expression : public Expression
2102 public:
2103 Float_expression(const mpfr_t* val, Type* type, Location location)
2104 : Expression(EXPRESSION_FLOAT, location),
2105 type_(type)
2107 mpfr_init_set(this->val_, *val, GMP_RNDN);
2110 // Write VAL to export data.
2111 static void
2112 export_float(String_dump* exp, const mpfr_t val);
2114 // Write VAL to dump file.
2115 static void
2116 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2118 protected:
2119 bool
2120 do_is_constant() const
2121 { return true; }
2123 bool
2124 do_is_immutable() const
2125 { return true; }
2127 bool
2128 do_numeric_constant_value(Numeric_constant* nc) const
2130 nc->set_float(this->type_, this->val_);
2131 return true;
2134 Type*
2135 do_type();
2137 void
2138 do_determine_type(const Type_context*);
2140 void
2141 do_check_types(Gogo*);
2143 Expression*
2144 do_copy()
2145 { return Expression::make_float(&this->val_, this->type_,
2146 this->location()); }
2148 tree
2149 do_get_tree(Translate_context*);
2151 void
2152 do_export(Export*) const;
2154 void
2155 do_dump_expression(Ast_dump_context*) const;
2157 private:
2158 // The floating point value.
2159 mpfr_t val_;
2160 // The type so far.
2161 Type* type_;
2164 // Return the current type. If we haven't set the type yet, we return
2165 // an abstract float type.
2167 Type*
2168 Float_expression::do_type()
2170 if (this->type_ == NULL)
2171 this->type_ = Type::make_abstract_float_type();
2172 return this->type_;
2175 // Set the type of the float value. Here we may switch from an
2176 // abstract type to a real type.
2178 void
2179 Float_expression::do_determine_type(const Type_context* context)
2181 if (this->type_ != NULL && !this->type_->is_abstract())
2183 else if (context->type != NULL
2184 && (context->type->integer_type() != NULL
2185 || context->type->float_type() != NULL
2186 || context->type->complex_type() != NULL))
2187 this->type_ = context->type;
2188 else if (!context->may_be_abstract)
2189 this->type_ = Type::lookup_float_type("float64");
2192 // Check the type of a float value.
2194 void
2195 Float_expression::do_check_types(Gogo*)
2197 Type* type = this->type_;
2198 if (type == NULL)
2199 return;
2200 Numeric_constant nc;
2201 nc.set_float(NULL, this->val_);
2202 if (!nc.set_type(this->type_, true, this->location()))
2203 this->set_is_error();
2206 // Get a tree for a float constant.
2208 tree
2209 Float_expression::do_get_tree(Translate_context* context)
2211 Type* resolved_type;
2212 if (this->type_ != NULL && !this->type_->is_abstract())
2213 resolved_type = this->type_;
2214 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2216 // We have an abstract integer type. We just hope for the best.
2217 resolved_type = Type::lookup_integer_type("int");
2219 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2221 // We are converting to an abstract complex type.
2222 resolved_type = Type::lookup_complex_type("complex128");
2224 else
2226 // If we still have an abstract type here, then this is being
2227 // used in a constant expression which didn't get reduced. We
2228 // just use float64 and hope for the best.
2229 resolved_type = Type::lookup_float_type("float64");
2232 Numeric_constant nc;
2233 nc.set_float(resolved_type, this->val_);
2234 Bexpression* ret =
2235 Expression::backend_numeric_constant_expression(context, &nc);
2236 return expr_to_tree(ret);
2239 // Write a floating point number to a string dump.
2241 void
2242 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2244 mp_exp_t exponent;
2245 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2246 if (*s == '-')
2247 exp->write_c_string("-");
2248 exp->write_c_string("0.");
2249 exp->write_c_string(*s == '-' ? s + 1 : s);
2250 mpfr_free_str(s);
2251 char buf[30];
2252 snprintf(buf, sizeof buf, "E%ld", exponent);
2253 exp->write_c_string(buf);
2256 // Export a floating point number in a constant expression.
2258 void
2259 Float_expression::do_export(Export* exp) const
2261 Float_expression::export_float(exp, this->val_);
2262 // A trailing space lets us reliably identify the end of the number.
2263 exp->write_c_string(" ");
2266 // Dump a floating point number to the dump file.
2268 void
2269 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2271 Float_expression::export_float(ast_dump_context, this->val_);
2274 // Make a float expression.
2276 Expression*
2277 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2279 return new Float_expression(val, type, location);
2282 // Complex numbers.
2284 class Complex_expression : public Expression
2286 public:
2287 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2288 Location location)
2289 : Expression(EXPRESSION_COMPLEX, location),
2290 type_(type)
2292 mpfr_init_set(this->real_, *real, GMP_RNDN);
2293 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2296 // Write REAL/IMAG to string dump.
2297 static void
2298 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2300 // Write REAL/IMAG to dump context.
2301 static void
2302 dump_complex(Ast_dump_context* ast_dump_context,
2303 const mpfr_t real, const mpfr_t val);
2305 protected:
2306 bool
2307 do_is_constant() const
2308 { return true; }
2310 bool
2311 do_is_immutable() const
2312 { return true; }
2314 bool
2315 do_numeric_constant_value(Numeric_constant* nc) const
2317 nc->set_complex(this->type_, this->real_, this->imag_);
2318 return true;
2321 Type*
2322 do_type();
2324 void
2325 do_determine_type(const Type_context*);
2327 void
2328 do_check_types(Gogo*);
2330 Expression*
2331 do_copy()
2333 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2334 this->location());
2337 tree
2338 do_get_tree(Translate_context*);
2340 void
2341 do_export(Export*) const;
2343 void
2344 do_dump_expression(Ast_dump_context*) const;
2346 private:
2347 // The real part.
2348 mpfr_t real_;
2349 // The imaginary part;
2350 mpfr_t imag_;
2351 // The type if known.
2352 Type* type_;
2355 // Return the current type. If we haven't set the type yet, we return
2356 // an abstract complex type.
2358 Type*
2359 Complex_expression::do_type()
2361 if (this->type_ == NULL)
2362 this->type_ = Type::make_abstract_complex_type();
2363 return this->type_;
2366 // Set the type of the complex value. Here we may switch from an
2367 // abstract type to a real type.
2369 void
2370 Complex_expression::do_determine_type(const Type_context* context)
2372 if (this->type_ != NULL && !this->type_->is_abstract())
2374 else if (context->type != NULL
2375 && context->type->complex_type() != NULL)
2376 this->type_ = context->type;
2377 else if (!context->may_be_abstract)
2378 this->type_ = Type::lookup_complex_type("complex128");
2381 // Check the type of a complex value.
2383 void
2384 Complex_expression::do_check_types(Gogo*)
2386 Type* type = this->type_;
2387 if (type == NULL)
2388 return;
2389 Numeric_constant nc;
2390 nc.set_complex(NULL, this->real_, this->imag_);
2391 if (!nc.set_type(this->type_, true, this->location()))
2392 this->set_is_error();
2395 // Get a tree for a complex constant.
2397 tree
2398 Complex_expression::do_get_tree(Translate_context* context)
2400 Type* resolved_type;
2401 if (this->type_ != NULL && !this->type_->is_abstract())
2402 resolved_type = this->type_;
2403 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2405 // We are converting to an abstract integer type.
2406 resolved_type = Type::lookup_integer_type("int");
2408 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2410 // We are converting to an abstract float type.
2411 resolved_type = Type::lookup_float_type("float64");
2413 else
2415 // If we still have an abstract type here, this this is being
2416 // used in a constant expression which didn't get reduced. We
2417 // just use complex128 and hope for the best.
2418 resolved_type = Type::lookup_complex_type("complex128");
2421 Numeric_constant nc;
2422 nc.set_complex(resolved_type, this->real_, this->imag_);
2423 Bexpression* ret =
2424 Expression::backend_numeric_constant_expression(context, &nc);
2425 return expr_to_tree(ret);
2428 // Write REAL/IMAG to export data.
2430 void
2431 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2432 const mpfr_t imag)
2434 if (!mpfr_zero_p(real))
2436 Float_expression::export_float(exp, real);
2437 if (mpfr_sgn(imag) > 0)
2438 exp->write_c_string("+");
2440 Float_expression::export_float(exp, imag);
2441 exp->write_c_string("i");
2444 // Export a complex number in a constant expression.
2446 void
2447 Complex_expression::do_export(Export* exp) const
2449 Complex_expression::export_complex(exp, this->real_, this->imag_);
2450 // A trailing space lets us reliably identify the end of the number.
2451 exp->write_c_string(" ");
2454 // Dump a complex expression to the dump file.
2456 void
2457 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2459 Complex_expression::export_complex(ast_dump_context,
2460 this->real_,
2461 this->imag_);
2464 // Make a complex expression.
2466 Expression*
2467 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2468 Location location)
2470 return new Complex_expression(real, imag, type, location);
2473 // Find a named object in an expression.
2475 class Find_named_object : public Traverse
2477 public:
2478 Find_named_object(Named_object* no)
2479 : Traverse(traverse_expressions),
2480 no_(no), found_(false)
2483 // Whether we found the object.
2484 bool
2485 found() const
2486 { return this->found_; }
2488 protected:
2490 expression(Expression**);
2492 private:
2493 // The object we are looking for.
2494 Named_object* no_;
2495 // Whether we found it.
2496 bool found_;
2499 // A reference to a const in an expression.
2501 class Const_expression : public Expression
2503 public:
2504 Const_expression(Named_object* constant, Location location)
2505 : Expression(EXPRESSION_CONST_REFERENCE, location),
2506 constant_(constant), type_(NULL), seen_(false)
2509 Named_object*
2510 named_object()
2511 { return this->constant_; }
2513 // Check that the initializer does not refer to the constant itself.
2514 void
2515 check_for_init_loop();
2517 protected:
2519 do_traverse(Traverse*);
2521 Expression*
2522 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2524 bool
2525 do_is_constant() const
2526 { return true; }
2528 bool
2529 do_is_immutable() const
2530 { return true; }
2532 bool
2533 do_numeric_constant_value(Numeric_constant* nc) const;
2535 bool
2536 do_string_constant_value(std::string* val) const;
2538 Type*
2539 do_type();
2541 // The type of a const is set by the declaration, not the use.
2542 void
2543 do_determine_type(const Type_context*);
2545 void
2546 do_check_types(Gogo*);
2548 Expression*
2549 do_copy()
2550 { return this; }
2552 tree
2553 do_get_tree(Translate_context* context);
2555 // When exporting a reference to a const as part of a const
2556 // expression, we export the value. We ignore the fact that it has
2557 // a name.
2558 void
2559 do_export(Export* exp) const
2560 { this->constant_->const_value()->expr()->export_expression(exp); }
2562 void
2563 do_dump_expression(Ast_dump_context*) const;
2565 private:
2566 // The constant.
2567 Named_object* constant_;
2568 // The type of this reference. This is used if the constant has an
2569 // abstract type.
2570 Type* type_;
2571 // Used to prevent infinite recursion when a constant incorrectly
2572 // refers to itself.
2573 mutable bool seen_;
2576 // Traversal.
2579 Const_expression::do_traverse(Traverse* traverse)
2581 if (this->type_ != NULL)
2582 return Type::traverse(this->type_, traverse);
2583 return TRAVERSE_CONTINUE;
2586 // Lower a constant expression. This is where we convert the
2587 // predeclared constant iota into an integer value.
2589 Expression*
2590 Const_expression::do_lower(Gogo* gogo, Named_object*,
2591 Statement_inserter*, int iota_value)
2593 if (this->constant_->const_value()->expr()->classification()
2594 == EXPRESSION_IOTA)
2596 if (iota_value == -1)
2598 error_at(this->location(),
2599 "iota is only defined in const declarations");
2600 iota_value = 0;
2602 mpz_t val;
2603 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2604 Expression* ret = Expression::make_integer(&val, NULL,
2605 this->location());
2606 mpz_clear(val);
2607 return ret;
2610 // Make sure that the constant itself has been lowered.
2611 gogo->lower_constant(this->constant_);
2613 return this;
2616 // Return a numeric constant value.
2618 bool
2619 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2621 if (this->seen_)
2622 return false;
2624 Expression* e = this->constant_->const_value()->expr();
2626 this->seen_ = true;
2628 bool r = e->numeric_constant_value(nc);
2630 this->seen_ = false;
2632 Type* ctype;
2633 if (this->type_ != NULL)
2634 ctype = this->type_;
2635 else
2636 ctype = this->constant_->const_value()->type();
2637 if (r && ctype != NULL)
2639 if (!nc->set_type(ctype, false, this->location()))
2640 return false;
2643 return r;
2646 bool
2647 Const_expression::do_string_constant_value(std::string* val) const
2649 if (this->seen_)
2650 return false;
2652 Expression* e = this->constant_->const_value()->expr();
2654 this->seen_ = true;
2655 bool ok = e->string_constant_value(val);
2656 this->seen_ = false;
2658 return ok;
2661 // Return the type of the const reference.
2663 Type*
2664 Const_expression::do_type()
2666 if (this->type_ != NULL)
2667 return this->type_;
2669 Named_constant* nc = this->constant_->const_value();
2671 if (this->seen_ || nc->lowering())
2673 this->report_error(_("constant refers to itself"));
2674 this->type_ = Type::make_error_type();
2675 return this->type_;
2678 this->seen_ = true;
2680 Type* ret = nc->type();
2682 if (ret != NULL)
2684 this->seen_ = false;
2685 return ret;
2688 // During parsing, a named constant may have a NULL type, but we
2689 // must not return a NULL type here.
2690 ret = nc->expr()->type();
2692 this->seen_ = false;
2694 return ret;
2697 // Set the type of the const reference.
2699 void
2700 Const_expression::do_determine_type(const Type_context* context)
2702 Type* ctype = this->constant_->const_value()->type();
2703 Type* cetype = (ctype != NULL
2704 ? ctype
2705 : this->constant_->const_value()->expr()->type());
2706 if (ctype != NULL && !ctype->is_abstract())
2708 else if (context->type != NULL
2709 && context->type->is_numeric_type()
2710 && cetype->is_numeric_type())
2711 this->type_ = context->type;
2712 else if (context->type != NULL
2713 && context->type->is_string_type()
2714 && cetype->is_string_type())
2715 this->type_ = context->type;
2716 else if (context->type != NULL
2717 && context->type->is_boolean_type()
2718 && cetype->is_boolean_type())
2719 this->type_ = context->type;
2720 else if (!context->may_be_abstract)
2722 if (cetype->is_abstract())
2723 cetype = cetype->make_non_abstract_type();
2724 this->type_ = cetype;
2728 // Check for a loop in which the initializer of a constant refers to
2729 // the constant itself.
2731 void
2732 Const_expression::check_for_init_loop()
2734 if (this->type_ != NULL && this->type_->is_error())
2735 return;
2737 if (this->seen_)
2739 this->report_error(_("constant refers to itself"));
2740 this->type_ = Type::make_error_type();
2741 return;
2744 Expression* init = this->constant_->const_value()->expr();
2745 Find_named_object find_named_object(this->constant_);
2747 this->seen_ = true;
2748 Expression::traverse(&init, &find_named_object);
2749 this->seen_ = false;
2751 if (find_named_object.found())
2753 if (this->type_ == NULL || !this->type_->is_error())
2755 this->report_error(_("constant refers to itself"));
2756 this->type_ = Type::make_error_type();
2758 return;
2762 // Check types of a const reference.
2764 void
2765 Const_expression::do_check_types(Gogo*)
2767 if (this->type_ != NULL && this->type_->is_error())
2768 return;
2770 this->check_for_init_loop();
2772 // Check that numeric constant fits in type.
2773 if (this->type_ != NULL && this->type_->is_numeric_type())
2775 Numeric_constant nc;
2776 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2778 if (!nc.set_type(this->type_, true, this->location()))
2779 this->set_is_error();
2784 // Return a tree for the const reference.
2786 tree
2787 Const_expression::do_get_tree(Translate_context* context)
2789 if (this->type_ != NULL && this->type_->is_error())
2790 return error_mark_node;
2792 // If the type has been set for this expression, but the underlying
2793 // object is an abstract int or float, we try to get the abstract
2794 // value. Otherwise we may lose something in the conversion.
2795 Expression* expr = this->constant_->const_value()->expr();
2796 if (this->type_ != NULL
2797 && this->type_->is_numeric_type()
2798 && (this->constant_->const_value()->type() == NULL
2799 || this->constant_->const_value()->type()->is_abstract()))
2801 Numeric_constant nc;
2802 if (expr->numeric_constant_value(&nc)
2803 && nc.set_type(this->type_, false, this->location()))
2805 Expression* e = nc.expression(this->location());
2806 return e->get_tree(context);
2810 if (this->type_ != NULL)
2811 expr = Expression::make_cast(this->type_, expr, this->location());
2812 return expr->get_tree(context);
2815 // Dump ast representation for constant expression.
2817 void
2818 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2820 ast_dump_context->ostream() << this->constant_->name();
2823 // Make a reference to a constant in an expression.
2825 Expression*
2826 Expression::make_const_reference(Named_object* constant,
2827 Location location)
2829 return new Const_expression(constant, location);
2832 // Find a named object in an expression.
2835 Find_named_object::expression(Expression** pexpr)
2837 switch ((*pexpr)->classification())
2839 case Expression::EXPRESSION_CONST_REFERENCE:
2841 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2842 if (ce->named_object() == this->no_)
2843 break;
2845 // We need to check a constant initializer explicitly, as
2846 // loops here will not be caught by the loop checking for
2847 // variable initializers.
2848 ce->check_for_init_loop();
2850 return TRAVERSE_CONTINUE;
2853 case Expression::EXPRESSION_VAR_REFERENCE:
2854 if ((*pexpr)->var_expression()->named_object() == this->no_)
2855 break;
2856 return TRAVERSE_CONTINUE;
2857 case Expression::EXPRESSION_FUNC_REFERENCE:
2858 if ((*pexpr)->func_expression()->named_object() == this->no_)
2859 break;
2860 return TRAVERSE_CONTINUE;
2861 default:
2862 return TRAVERSE_CONTINUE;
2864 this->found_ = true;
2865 return TRAVERSE_EXIT;
2868 // The nil value.
2870 class Nil_expression : public Expression
2872 public:
2873 Nil_expression(Location location)
2874 : Expression(EXPRESSION_NIL, location)
2877 static Expression*
2878 do_import(Import*);
2880 protected:
2881 bool
2882 do_is_constant() const
2883 { return true; }
2885 bool
2886 do_is_immutable() const
2887 { return true; }
2889 Type*
2890 do_type()
2891 { return Type::make_nil_type(); }
2893 void
2894 do_determine_type(const Type_context*)
2897 Expression*
2898 do_copy()
2899 { return this; }
2901 tree
2902 do_get_tree(Translate_context*)
2903 { return null_pointer_node; }
2905 void
2906 do_export(Export* exp) const
2907 { exp->write_c_string("nil"); }
2909 void
2910 do_dump_expression(Ast_dump_context* ast_dump_context) const
2911 { ast_dump_context->ostream() << "nil"; }
2914 // Import a nil expression.
2916 Expression*
2917 Nil_expression::do_import(Import* imp)
2919 imp->require_c_string("nil");
2920 return Expression::make_nil(imp->location());
2923 // Make a nil expression.
2925 Expression*
2926 Expression::make_nil(Location location)
2928 return new Nil_expression(location);
2931 // The value of the predeclared constant iota. This is little more
2932 // than a marker. This will be lowered to an integer in
2933 // Const_expression::do_lower, which is where we know the value that
2934 // it should have.
2936 class Iota_expression : public Parser_expression
2938 public:
2939 Iota_expression(Location location)
2940 : Parser_expression(EXPRESSION_IOTA, location)
2943 protected:
2944 Expression*
2945 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2946 { go_unreachable(); }
2948 // There should only ever be one of these.
2949 Expression*
2950 do_copy()
2951 { go_unreachable(); }
2953 void
2954 do_dump_expression(Ast_dump_context* ast_dump_context) const
2955 { ast_dump_context->ostream() << "iota"; }
2958 // Make an iota expression. This is only called for one case: the
2959 // value of the predeclared constant iota.
2961 Expression*
2962 Expression::make_iota()
2964 static Iota_expression iota_expression(Linemap::unknown_location());
2965 return &iota_expression;
2968 // A type conversion expression.
2970 class Type_conversion_expression : public Expression
2972 public:
2973 Type_conversion_expression(Type* type, Expression* expr,
2974 Location location)
2975 : Expression(EXPRESSION_CONVERSION, location),
2976 type_(type), expr_(expr), may_convert_function_types_(false)
2979 // Return the type to which we are converting.
2980 Type*
2981 type() const
2982 { return this->type_; }
2984 // Return the expression which we are converting.
2985 Expression*
2986 expr() const
2987 { return this->expr_; }
2989 // Permit converting from one function type to another. This is
2990 // used internally for method expressions.
2991 void
2992 set_may_convert_function_types()
2994 this->may_convert_function_types_ = true;
2997 // Import a type conversion expression.
2998 static Expression*
2999 do_import(Import*);
3001 protected:
3003 do_traverse(Traverse* traverse);
3005 Expression*
3006 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3008 Expression*
3009 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3011 bool
3012 do_is_constant() const;
3014 bool
3015 do_is_immutable() const;
3017 bool
3018 do_numeric_constant_value(Numeric_constant*) const;
3020 bool
3021 do_string_constant_value(std::string*) const;
3023 Type*
3024 do_type()
3025 { return this->type_; }
3027 void
3028 do_determine_type(const Type_context*)
3030 Type_context subcontext(this->type_, false);
3031 this->expr_->determine_type(&subcontext);
3034 void
3035 do_check_types(Gogo*);
3037 Expression*
3038 do_copy()
3040 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3041 this->location());
3044 tree
3045 do_get_tree(Translate_context* context);
3047 void
3048 do_export(Export*) const;
3050 void
3051 do_dump_expression(Ast_dump_context*) const;
3053 private:
3054 // The type to convert to.
3055 Type* type_;
3056 // The expression to convert.
3057 Expression* expr_;
3058 // True if this is permitted to convert function types. This is
3059 // used internally for method expressions.
3060 bool may_convert_function_types_;
3063 // Traversal.
3066 Type_conversion_expression::do_traverse(Traverse* traverse)
3068 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3069 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3070 return TRAVERSE_EXIT;
3071 return TRAVERSE_CONTINUE;
3074 // Convert to a constant at lowering time.
3076 Expression*
3077 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3078 Statement_inserter*, int)
3080 Type* type = this->type_;
3081 Expression* val = this->expr_;
3082 Location location = this->location();
3084 if (type->is_numeric_type())
3086 Numeric_constant nc;
3087 if (val->numeric_constant_value(&nc))
3089 if (!nc.set_type(type, true, location))
3090 return Expression::make_error(location);
3091 return nc.expression(location);
3095 if (type->is_slice_type())
3097 Type* element_type = type->array_type()->element_type()->forwarded();
3098 bool is_byte = (element_type->integer_type() != NULL
3099 && element_type->integer_type()->is_byte());
3100 bool is_rune = (element_type->integer_type() != NULL
3101 && element_type->integer_type()->is_rune());
3102 if (is_byte || is_rune)
3104 std::string s;
3105 if (val->string_constant_value(&s))
3107 Expression_list* vals = new Expression_list();
3108 if (is_byte)
3110 for (std::string::const_iterator p = s.begin();
3111 p != s.end();
3112 p++)
3114 mpz_t val;
3115 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3116 Expression* v = Expression::make_integer(&val,
3117 element_type,
3118 location);
3119 vals->push_back(v);
3120 mpz_clear(val);
3123 else
3125 const char *p = s.data();
3126 const char *pend = s.data() + s.length();
3127 while (p < pend)
3129 unsigned int c;
3130 int adv = Lex::fetch_char(p, &c);
3131 if (adv == 0)
3133 warning_at(this->location(), 0,
3134 "invalid UTF-8 encoding");
3135 adv = 1;
3137 p += adv;
3138 mpz_t val;
3139 mpz_init_set_ui(val, c);
3140 Expression* v = Expression::make_integer(&val,
3141 element_type,
3142 location);
3143 vals->push_back(v);
3144 mpz_clear(val);
3148 return Expression::make_slice_composite_literal(type, vals,
3149 location);
3154 return this;
3157 // Flatten a type conversion by using a temporary variable for the slice
3158 // in slice to string conversions.
3160 Expression*
3161 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3162 Statement_inserter* inserter)
3164 if (((this->type()->is_string_type()
3165 && this->expr_->type()->is_slice_type())
3166 || (this->type()->interface_type() != NULL
3167 && this->expr_->type()->interface_type() != NULL))
3168 && !this->expr_->is_variable())
3170 Temporary_statement* temp =
3171 Statement::make_temporary(NULL, this->expr_, this->location());
3172 inserter->insert(temp);
3173 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3175 return this;
3178 // Return whether a type conversion is a constant.
3180 bool
3181 Type_conversion_expression::do_is_constant() const
3183 if (!this->expr_->is_constant())
3184 return false;
3186 // A conversion to a type that may not be used as a constant is not
3187 // a constant. For example, []byte(nil).
3188 Type* type = this->type_;
3189 if (type->integer_type() == NULL
3190 && type->float_type() == NULL
3191 && type->complex_type() == NULL
3192 && !type->is_boolean_type()
3193 && !type->is_string_type())
3194 return false;
3196 return true;
3199 // Return whether a type conversion is immutable.
3201 bool
3202 Type_conversion_expression::do_is_immutable() const
3204 Type* type = this->type_;
3205 Type* expr_type = this->expr_->type();
3207 if (type->interface_type() != NULL
3208 || expr_type->interface_type() != NULL)
3209 return false;
3211 if (!this->expr_->is_immutable())
3212 return false;
3214 if (Type::are_identical(type, expr_type, false, NULL))
3215 return true;
3217 return type->is_basic_type() && expr_type->is_basic_type();
3220 // Return the constant numeric value if there is one.
3222 bool
3223 Type_conversion_expression::do_numeric_constant_value(
3224 Numeric_constant* nc) const
3226 if (!this->type_->is_numeric_type())
3227 return false;
3228 if (!this->expr_->numeric_constant_value(nc))
3229 return false;
3230 return nc->set_type(this->type_, false, this->location());
3233 // Return the constant string value if there is one.
3235 bool
3236 Type_conversion_expression::do_string_constant_value(std::string* val) const
3238 if (this->type_->is_string_type()
3239 && this->expr_->type()->integer_type() != NULL)
3241 Numeric_constant nc;
3242 if (this->expr_->numeric_constant_value(&nc))
3244 unsigned long ival;
3245 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3247 val->clear();
3248 Lex::append_char(ival, true, val, this->location());
3249 return true;
3254 // FIXME: Could handle conversion from const []int here.
3256 return false;
3259 // Check that types are convertible.
3261 void
3262 Type_conversion_expression::do_check_types(Gogo*)
3264 Type* type = this->type_;
3265 Type* expr_type = this->expr_->type();
3266 std::string reason;
3268 if (type->is_error() || expr_type->is_error())
3270 this->set_is_error();
3271 return;
3274 if (this->may_convert_function_types_
3275 && type->function_type() != NULL
3276 && expr_type->function_type() != NULL)
3277 return;
3279 if (Type::are_convertible(type, expr_type, &reason))
3280 return;
3282 error_at(this->location(), "%s", reason.c_str());
3283 this->set_is_error();
3286 // Get a tree for a type conversion.
3288 tree
3289 Type_conversion_expression::do_get_tree(Translate_context* context)
3291 Type* type = this->type_;
3292 Type* expr_type = this->expr_->type();
3294 Gogo* gogo = context->gogo();
3295 Btype* btype = type->get_backend(gogo);
3296 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3297 Location loc = this->location();
3299 if (Type::are_identical(type, expr_type, false, NULL))
3301 Bexpression* bconvert =
3302 gogo->backend()->convert_expression(btype, bexpr, loc);
3303 return expr_to_tree(bconvert);
3305 else if (type->interface_type() != NULL
3306 || expr_type->interface_type() != NULL)
3308 Expression* conversion =
3309 Expression::convert_for_assignment(gogo, type, this->expr_,
3310 this->location());
3311 return conversion->get_tree(context);
3313 else if (type->is_string_type()
3314 && expr_type->integer_type() != NULL)
3316 mpz_t intval;
3317 Numeric_constant nc;
3318 if (this->expr_->numeric_constant_value(&nc)
3319 && nc.to_int(&intval)
3320 && mpz_fits_ushort_p(intval))
3322 std::string s;
3323 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3324 mpz_clear(intval);
3325 Expression* se = Expression::make_string(s, loc);
3326 return se->get_tree(context);
3329 Expression* i2s_expr =
3330 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3331 return Expression::make_cast(type, i2s_expr, loc)->get_tree(context);
3333 else if (type->is_string_type() && expr_type->is_slice_type())
3335 Array_type* a = expr_type->array_type();
3336 Type* e = a->element_type()->forwarded();
3337 go_assert(e->integer_type() != NULL);
3338 go_assert(this->expr_->is_variable());
3340 Runtime::Function code;
3341 if (e->integer_type()->is_byte())
3342 code = Runtime::BYTE_ARRAY_TO_STRING;
3343 else
3345 go_assert(e->integer_type()->is_rune());
3346 code = Runtime::INT_ARRAY_TO_STRING;
3348 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3349 Expression* len = a->get_length(gogo, this->expr_);
3350 return Runtime::make_call(code, loc, 2, valptr, len)->get_tree(context);
3352 else if (type->is_slice_type() && expr_type->is_string_type())
3354 Type* e = type->array_type()->element_type()->forwarded();
3355 go_assert(e->integer_type() != NULL);
3357 Runtime::Function code;
3358 if (e->integer_type()->is_byte())
3359 code = Runtime::STRING_TO_BYTE_ARRAY;
3360 else
3362 go_assert(e->integer_type()->is_rune());
3363 code = Runtime::STRING_TO_INT_ARRAY;
3365 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3366 return Expression::make_unsafe_cast(type, s2a, loc)->get_tree(context);
3368 else if (type->is_numeric_type())
3370 go_assert(Type::are_convertible(type, expr_type, NULL));
3371 Bexpression* bconvert =
3372 gogo->backend()->convert_expression(btype, bexpr, loc);
3373 return expr_to_tree(bconvert);
3375 else if ((type->is_unsafe_pointer_type()
3376 && (expr_type->points_to() != NULL
3377 || expr_type->integer_type()))
3378 || (expr_type->is_unsafe_pointer_type()
3379 && type->points_to() != NULL)
3380 || (this->may_convert_function_types_
3381 && type->function_type() != NULL
3382 && expr_type->function_type() != NULL))
3384 Bexpression* bconvert =
3385 gogo->backend()->convert_expression(btype, bexpr, loc);
3386 return expr_to_tree(bconvert);
3388 else
3390 Expression* conversion =
3391 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3392 return conversion->get_tree(context);
3396 // Output a type conversion in a constant expression.
3398 void
3399 Type_conversion_expression::do_export(Export* exp) const
3401 exp->write_c_string("convert(");
3402 exp->write_type(this->type_);
3403 exp->write_c_string(", ");
3404 this->expr_->export_expression(exp);
3405 exp->write_c_string(")");
3408 // Import a type conversion or a struct construction.
3410 Expression*
3411 Type_conversion_expression::do_import(Import* imp)
3413 imp->require_c_string("convert(");
3414 Type* type = imp->read_type();
3415 imp->require_c_string(", ");
3416 Expression* val = Expression::import_expression(imp);
3417 imp->require_c_string(")");
3418 return Expression::make_cast(type, val, imp->location());
3421 // Dump ast representation for a type conversion expression.
3423 void
3424 Type_conversion_expression::do_dump_expression(
3425 Ast_dump_context* ast_dump_context) const
3427 ast_dump_context->dump_type(this->type_);
3428 ast_dump_context->ostream() << "(";
3429 ast_dump_context->dump_expression(this->expr_);
3430 ast_dump_context->ostream() << ") ";
3433 // Make a type cast expression.
3435 Expression*
3436 Expression::make_cast(Type* type, Expression* val, Location location)
3438 if (type->is_error_type() || val->is_error_expression())
3439 return Expression::make_error(location);
3440 return new Type_conversion_expression(type, val, location);
3443 // An unsafe type conversion, used to pass values to builtin functions.
3445 class Unsafe_type_conversion_expression : public Expression
3447 public:
3448 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3449 Location location)
3450 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3451 type_(type), expr_(expr)
3454 protected:
3456 do_traverse(Traverse* traverse);
3458 Type*
3459 do_type()
3460 { return this->type_; }
3462 void
3463 do_determine_type(const Type_context*)
3464 { this->expr_->determine_type_no_context(); }
3466 Expression*
3467 do_copy()
3469 return new Unsafe_type_conversion_expression(this->type_,
3470 this->expr_->copy(),
3471 this->location());
3474 tree
3475 do_get_tree(Translate_context*);
3477 void
3478 do_dump_expression(Ast_dump_context*) const;
3480 private:
3481 // The type to convert to.
3482 Type* type_;
3483 // The expression to convert.
3484 Expression* expr_;
3487 // Traversal.
3490 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3492 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3493 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3494 return TRAVERSE_EXIT;
3495 return TRAVERSE_CONTINUE;
3498 // Convert to backend representation.
3500 tree
3501 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3503 // We are only called for a limited number of cases.
3505 Type* t = this->type_;
3506 Type* et = this->expr_->type();
3507 if (t->array_type() != NULL)
3508 go_assert(et->array_type() != NULL
3509 && t->is_slice_type() == et->is_slice_type());
3510 else if (t->struct_type() != NULL)
3512 if (t->named_type() != NULL
3513 && et->named_type() != NULL
3514 && !Type::are_convertible(t, et, NULL))
3516 go_assert(saw_errors());
3517 return error_mark_node;
3520 go_assert(et->struct_type() != NULL
3521 && Type::are_convertible(t, et, NULL));
3523 else if (t->map_type() != NULL)
3524 go_assert(et->map_type() != NULL);
3525 else if (t->channel_type() != NULL)
3526 go_assert(et->channel_type() != NULL);
3527 else if (t->points_to() != NULL)
3528 go_assert(et->points_to() != NULL
3529 || et->channel_type() != NULL
3530 || et->map_type() != NULL
3531 || et->function_type() != NULL
3532 || et->is_nil_type());
3533 else if (et->is_unsafe_pointer_type())
3534 go_assert(t->points_to() != NULL);
3535 else if (t->interface_type() != NULL)
3537 bool empty_iface = t->interface_type()->is_empty();
3538 go_assert(et->interface_type() != NULL
3539 && et->interface_type()->is_empty() == empty_iface);
3541 else if (t->integer_type() != NULL)
3542 go_assert(et->is_boolean_type()
3543 || et->integer_type() != NULL
3544 || et->function_type() != NULL
3545 || et->points_to() != NULL
3546 || et->map_type() != NULL
3547 || et->channel_type() != NULL);
3548 else
3549 go_unreachable();
3551 Gogo* gogo = context->gogo();
3552 Btype* btype = t->get_backend(gogo);
3553 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3554 Location loc = this->location();
3555 Bexpression* ret =
3556 gogo->backend()->convert_expression(btype, bexpr, loc);
3557 return expr_to_tree(ret);
3560 // Dump ast representation for an unsafe type conversion expression.
3562 void
3563 Unsafe_type_conversion_expression::do_dump_expression(
3564 Ast_dump_context* ast_dump_context) const
3566 ast_dump_context->dump_type(this->type_);
3567 ast_dump_context->ostream() << "(";
3568 ast_dump_context->dump_expression(this->expr_);
3569 ast_dump_context->ostream() << ") ";
3572 // Make an unsafe type conversion expression.
3574 Expression*
3575 Expression::make_unsafe_cast(Type* type, Expression* expr,
3576 Location location)
3578 return new Unsafe_type_conversion_expression(type, expr, location);
3581 // Class Unary_expression.
3583 // If we are taking the address of a composite literal, and the
3584 // contents are not constant, then we want to make a heap expression
3585 // instead.
3587 Expression*
3588 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3590 Location loc = this->location();
3591 Operator op = this->op_;
3592 Expression* expr = this->expr_;
3594 if (op == OPERATOR_MULT && expr->is_type_expression())
3595 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3597 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3598 // moving x to the heap. FIXME: Is it worth doing a real escape
3599 // analysis here? This case is found in math/unsafe.go and is
3600 // therefore worth special casing.
3601 if (op == OPERATOR_MULT)
3603 Expression* e = expr;
3604 while (e->classification() == EXPRESSION_CONVERSION)
3606 Type_conversion_expression* te
3607 = static_cast<Type_conversion_expression*>(e);
3608 e = te->expr();
3611 if (e->classification() == EXPRESSION_UNARY)
3613 Unary_expression* ue = static_cast<Unary_expression*>(e);
3614 if (ue->op_ == OPERATOR_AND)
3616 if (e == expr)
3618 // *&x == x.
3619 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3621 error_at(ue->location(),
3622 "invalid operand for unary %<&%>");
3623 this->set_is_error();
3625 return ue->expr_;
3627 ue->set_does_not_escape();
3632 // Catching an invalid indirection of unsafe.Pointer here avoid
3633 // having to deal with TYPE_VOID in other places.
3634 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3636 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3637 return Expression::make_error(this->location());
3640 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3642 Numeric_constant nc;
3643 if (expr->numeric_constant_value(&nc))
3645 Numeric_constant result;
3646 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3647 return result.expression(loc);
3651 return this;
3654 // Flatten expression if a nil check must be performed and create temporary
3655 // variables if necessary.
3657 Expression*
3658 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3659 Statement_inserter* inserter)
3661 if (this->is_error_expression() || this->expr_->is_error_expression())
3662 return Expression::make_error(this->location());
3664 Location location = this->location();
3665 if (this->op_ == OPERATOR_MULT
3666 && !this->expr_->is_variable())
3668 go_assert(this->expr_->type()->points_to() != NULL);
3669 Type* ptype = this->expr_->type()->points_to();
3670 if (!ptype->is_void_type())
3672 Btype* pbtype = ptype->get_backend(gogo);
3673 size_t s = gogo->backend()->type_size(pbtype);
3674 if (s >= 4096 || this->issue_nil_check_)
3676 Temporary_statement* temp =
3677 Statement::make_temporary(NULL, this->expr_, location);
3678 inserter->insert(temp);
3679 this->expr_ =
3680 Expression::make_temporary_reference(temp, location);
3685 if (this->create_temp_ && !this->expr_->is_variable())
3687 Temporary_statement* temp =
3688 Statement::make_temporary(NULL, this->expr_, location);
3689 inserter->insert(temp);
3690 this->expr_ = Expression::make_temporary_reference(temp, location);
3693 return this;
3696 // Return whether a unary expression is a constant.
3698 bool
3699 Unary_expression::do_is_constant() const
3701 if (this->op_ == OPERATOR_MULT)
3703 // Indirecting through a pointer is only constant if the object
3704 // to which the expression points is constant, but we currently
3705 // have no way to determine that.
3706 return false;
3708 else if (this->op_ == OPERATOR_AND)
3710 // Taking the address of a variable is constant if it is a
3711 // global variable, not constant otherwise. In other cases taking the
3712 // address is probably not a constant.
3713 Var_expression* ve = this->expr_->var_expression();
3714 if (ve != NULL)
3716 Named_object* no = ve->named_object();
3717 return no->is_variable() && no->var_value()->is_global();
3719 return false;
3721 else
3722 return this->expr_->is_constant();
3725 // Apply unary opcode OP to UNC, setting NC. Return true if this
3726 // could be done, false if not. Issue errors for overflow.
3728 bool
3729 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3730 Location location, Numeric_constant* nc)
3732 switch (op)
3734 case OPERATOR_PLUS:
3735 *nc = *unc;
3736 return true;
3738 case OPERATOR_MINUS:
3739 if (unc->is_int() || unc->is_rune())
3740 break;
3741 else if (unc->is_float())
3743 mpfr_t uval;
3744 unc->get_float(&uval);
3745 mpfr_t val;
3746 mpfr_init(val);
3747 mpfr_neg(val, uval, GMP_RNDN);
3748 nc->set_float(unc->type(), val);
3749 mpfr_clear(uval);
3750 mpfr_clear(val);
3751 return true;
3753 else if (unc->is_complex())
3755 mpfr_t ureal, uimag;
3756 unc->get_complex(&ureal, &uimag);
3757 mpfr_t real, imag;
3758 mpfr_init(real);
3759 mpfr_init(imag);
3760 mpfr_neg(real, ureal, GMP_RNDN);
3761 mpfr_neg(imag, uimag, GMP_RNDN);
3762 nc->set_complex(unc->type(), real, imag);
3763 mpfr_clear(ureal);
3764 mpfr_clear(uimag);
3765 mpfr_clear(real);
3766 mpfr_clear(imag);
3767 return true;
3769 else
3770 go_unreachable();
3772 case OPERATOR_XOR:
3773 break;
3775 case OPERATOR_NOT:
3776 case OPERATOR_AND:
3777 case OPERATOR_MULT:
3778 return false;
3780 default:
3781 go_unreachable();
3784 if (!unc->is_int() && !unc->is_rune())
3785 return false;
3787 mpz_t uval;
3788 if (unc->is_rune())
3789 unc->get_rune(&uval);
3790 else
3791 unc->get_int(&uval);
3792 mpz_t val;
3793 mpz_init(val);
3795 switch (op)
3797 case OPERATOR_MINUS:
3798 mpz_neg(val, uval);
3799 break;
3801 case OPERATOR_NOT:
3802 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3803 break;
3805 case OPERATOR_XOR:
3807 Type* utype = unc->type();
3808 if (utype->integer_type() == NULL
3809 || utype->integer_type()->is_abstract())
3810 mpz_com(val, uval);
3811 else
3813 // The number of HOST_WIDE_INTs that it takes to represent
3814 // UVAL.
3815 size_t count = ((mpz_sizeinbase(uval, 2)
3816 + HOST_BITS_PER_WIDE_INT
3817 - 1)
3818 / HOST_BITS_PER_WIDE_INT);
3820 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3821 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3823 size_t obits = utype->integer_type()->bits();
3825 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3827 mpz_t adj;
3828 mpz_init_set_ui(adj, 1);
3829 mpz_mul_2exp(adj, adj, obits);
3830 mpz_add(uval, uval, adj);
3831 mpz_clear(adj);
3834 size_t ecount;
3835 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3836 go_assert(ecount <= count);
3838 // Trim down to the number of words required by the type.
3839 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3840 / HOST_BITS_PER_WIDE_INT);
3841 go_assert(ocount <= count);
3843 for (size_t i = 0; i < ocount; ++i)
3844 phwi[i] = ~phwi[i];
3846 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3847 if (clearbits != 0)
3848 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3849 >> clearbits);
3851 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3853 if (!utype->integer_type()->is_unsigned()
3854 && mpz_tstbit(val, obits - 1))
3856 mpz_t adj;
3857 mpz_init_set_ui(adj, 1);
3858 mpz_mul_2exp(adj, adj, obits);
3859 mpz_sub(val, val, adj);
3860 mpz_clear(adj);
3863 delete[] phwi;
3866 break;
3868 default:
3869 go_unreachable();
3872 if (unc->is_rune())
3873 nc->set_rune(NULL, val);
3874 else
3875 nc->set_int(NULL, val);
3877 mpz_clear(uval);
3878 mpz_clear(val);
3880 return nc->set_type(unc->type(), true, location);
3883 // Return the integral constant value of a unary expression, if it has one.
3885 bool
3886 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3888 Numeric_constant unc;
3889 if (!this->expr_->numeric_constant_value(&unc))
3890 return false;
3891 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3892 nc);
3895 // Return the type of a unary expression.
3897 Type*
3898 Unary_expression::do_type()
3900 switch (this->op_)
3902 case OPERATOR_PLUS:
3903 case OPERATOR_MINUS:
3904 case OPERATOR_NOT:
3905 case OPERATOR_XOR:
3906 return this->expr_->type();
3908 case OPERATOR_AND:
3909 return Type::make_pointer_type(this->expr_->type());
3911 case OPERATOR_MULT:
3913 Type* subtype = this->expr_->type();
3914 Type* points_to = subtype->points_to();
3915 if (points_to == NULL)
3916 return Type::make_error_type();
3917 return points_to;
3920 default:
3921 go_unreachable();
3925 // Determine abstract types for a unary expression.
3927 void
3928 Unary_expression::do_determine_type(const Type_context* context)
3930 switch (this->op_)
3932 case OPERATOR_PLUS:
3933 case OPERATOR_MINUS:
3934 case OPERATOR_NOT:
3935 case OPERATOR_XOR:
3936 this->expr_->determine_type(context);
3937 break;
3939 case OPERATOR_AND:
3940 // Taking the address of something.
3942 Type* subtype = (context->type == NULL
3943 ? NULL
3944 : context->type->points_to());
3945 Type_context subcontext(subtype, false);
3946 this->expr_->determine_type(&subcontext);
3948 break;
3950 case OPERATOR_MULT:
3951 // Indirecting through a pointer.
3953 Type* subtype = (context->type == NULL
3954 ? NULL
3955 : Type::make_pointer_type(context->type));
3956 Type_context subcontext(subtype, false);
3957 this->expr_->determine_type(&subcontext);
3959 break;
3961 default:
3962 go_unreachable();
3966 // Check types for a unary expression.
3968 void
3969 Unary_expression::do_check_types(Gogo*)
3971 Type* type = this->expr_->type();
3972 if (type->is_error())
3974 this->set_is_error();
3975 return;
3978 switch (this->op_)
3980 case OPERATOR_PLUS:
3981 case OPERATOR_MINUS:
3982 if (type->integer_type() == NULL
3983 && type->float_type() == NULL
3984 && type->complex_type() == NULL)
3985 this->report_error(_("expected numeric type"));
3986 break;
3988 case OPERATOR_NOT:
3989 if (!type->is_boolean_type())
3990 this->report_error(_("expected boolean type"));
3991 break;
3993 case OPERATOR_XOR:
3994 if (type->integer_type() == NULL
3995 && !type->is_boolean_type())
3996 this->report_error(_("expected integer or boolean type"));
3997 break;
3999 case OPERATOR_AND:
4000 if (!this->expr_->is_addressable())
4002 if (!this->create_temp_)
4004 error_at(this->location(), "invalid operand for unary %<&%>");
4005 this->set_is_error();
4008 else
4010 this->expr_->address_taken(this->escapes_);
4011 this->expr_->issue_nil_check();
4013 break;
4015 case OPERATOR_MULT:
4016 // Indirecting through a pointer.
4017 if (type->points_to() == NULL)
4018 this->report_error(_("expected pointer"));
4019 break;
4021 default:
4022 go_unreachable();
4026 // Get a tree for a unary expression.
4028 tree
4029 Unary_expression::do_get_tree(Translate_context* context)
4031 Gogo* gogo = context->gogo();
4032 Location loc = this->location();
4034 // Taking the address of a set-and-use-temporary expression requires
4035 // setting the temporary and then taking the address.
4036 if (this->op_ == OPERATOR_AND)
4038 Set_and_use_temporary_expression* sut =
4039 this->expr_->set_and_use_temporary_expression();
4040 if (sut != NULL)
4042 Temporary_statement* temp = sut->temporary();
4043 Bvariable* bvar = temp->get_backend_variable(context);
4044 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4046 Expression* val = sut->expression();
4047 Bexpression* bval = tree_to_expr(val->get_tree(context));
4049 Bstatement* bassign =
4050 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4051 Bexpression* bvar_addr =
4052 gogo->backend()->address_expression(bvar_expr, loc);
4053 Bexpression* ret =
4054 gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4055 return expr_to_tree(ret);
4059 Bexpression* ret;
4060 tree expr = this->expr_->get_tree(context);
4061 Bexpression* bexpr = tree_to_expr(expr);
4062 Btype* btype = this->expr_->type()->get_backend(gogo);
4063 switch (this->op_)
4065 case OPERATOR_PLUS:
4066 ret = bexpr;
4067 break;
4069 case OPERATOR_MINUS:
4070 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4071 ret = gogo->backend()->convert_expression(btype, ret, loc);
4072 break;
4074 case OPERATOR_NOT:
4075 case OPERATOR_XOR:
4076 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4077 break;
4079 case OPERATOR_AND:
4080 if (!this->create_temp_)
4082 // We should not see a non-constant constructor here; cases
4083 // where we would see one should have been moved onto the
4084 // heap at parse time. Taking the address of a nonconstant
4085 // constructor will not do what the programmer expects.
4087 go_assert(!this->expr_->is_composite_literal()
4088 || this->expr_->is_immutable());
4089 if (this->expr_->classification() == EXPRESSION_UNARY)
4091 Unary_expression* ue =
4092 static_cast<Unary_expression*>(this->expr_);
4093 go_assert(ue->op() != OPERATOR_AND);
4097 if (this->is_gc_root_)
4099 // Build a decl for a GC root variable. GC roots are mutable, so they
4100 // cannot be represented as an immutable_struct in the backend.
4101 Bvariable* gc_root = gogo->backend()->gc_root_variable(btype, bexpr);
4102 bexpr = gogo->backend()->var_expression(gc_root, loc);
4104 else if ((this->expr_->is_composite_literal()
4105 || this->expr_->string_expression() != NULL)
4106 && this->expr_->is_immutable())
4108 // Build a decl for a constant constructor.
4109 static unsigned int counter;
4110 char buf[100];
4111 snprintf(buf, sizeof buf, "C%u", counter);
4112 ++counter;
4114 Bvariable* decl =
4115 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4116 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4117 btype, loc, bexpr);
4118 bexpr = gogo->backend()->var_expression(decl, loc);
4121 go_assert(!this->create_temp_ || this->expr_->is_variable());
4122 ret = gogo->backend()->address_expression(bexpr, loc);
4123 break;
4125 case OPERATOR_MULT:
4127 go_assert(this->expr_->type()->points_to() != NULL);
4129 // If we are dereferencing the pointer to a large struct, we
4130 // need to check for nil. We don't bother to check for small
4131 // structs because we expect the system to crash on a nil
4132 // pointer dereference. However, if we know the address of this
4133 // expression is being taken, we must always check for nil.
4135 Type* ptype = this->expr_->type()->points_to();
4136 Btype* pbtype = ptype->get_backend(gogo);
4137 if (!ptype->is_void_type())
4139 size_t s = gogo->backend()->type_size(pbtype);
4140 if (s >= 4096 || this->issue_nil_check_)
4142 go_assert(this->expr_->is_variable());
4144 Expression* nil_expr = Expression::make_nil(loc);
4145 Bexpression* nil = tree_to_expr(nil_expr->get_tree(context));
4146 Bexpression* compare =
4147 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4148 nil, loc);
4150 Expression* crash_expr =
4151 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
4152 Bexpression* crash =
4153 tree_to_expr(crash_expr->get_tree(context));
4154 bexpr = gogo->backend()->conditional_expression(btype, compare,
4155 crash, bexpr,
4156 loc);
4161 // If the type of EXPR is a recursive pointer type, then we
4162 // need to insert a cast before indirecting.
4163 tree expr = expr_to_tree(bexpr);
4164 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4165 if (VOID_TYPE_P(target_type_tree))
4167 tree ind = type_to_tree(pbtype);
4168 expr = fold_convert_loc(loc.gcc_location(),
4169 build_pointer_type(ind), expr);
4170 bexpr = tree_to_expr(expr);
4173 ret = gogo->backend()->indirect_expression(bexpr, false, loc);
4175 break;
4177 default:
4178 go_unreachable();
4181 return expr_to_tree(ret);
4184 // Export a unary expression.
4186 void
4187 Unary_expression::do_export(Export* exp) const
4189 switch (this->op_)
4191 case OPERATOR_PLUS:
4192 exp->write_c_string("+ ");
4193 break;
4194 case OPERATOR_MINUS:
4195 exp->write_c_string("- ");
4196 break;
4197 case OPERATOR_NOT:
4198 exp->write_c_string("! ");
4199 break;
4200 case OPERATOR_XOR:
4201 exp->write_c_string("^ ");
4202 break;
4203 case OPERATOR_AND:
4204 case OPERATOR_MULT:
4205 default:
4206 go_unreachable();
4208 this->expr_->export_expression(exp);
4211 // Import a unary expression.
4213 Expression*
4214 Unary_expression::do_import(Import* imp)
4216 Operator op;
4217 switch (imp->get_char())
4219 case '+':
4220 op = OPERATOR_PLUS;
4221 break;
4222 case '-':
4223 op = OPERATOR_MINUS;
4224 break;
4225 case '!':
4226 op = OPERATOR_NOT;
4227 break;
4228 case '^':
4229 op = OPERATOR_XOR;
4230 break;
4231 default:
4232 go_unreachable();
4234 imp->require_c_string(" ");
4235 Expression* expr = Expression::import_expression(imp);
4236 return Expression::make_unary(op, expr, imp->location());
4239 // Dump ast representation of an unary expression.
4241 void
4242 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4244 ast_dump_context->dump_operator(this->op_);
4245 ast_dump_context->ostream() << "(";
4246 ast_dump_context->dump_expression(this->expr_);
4247 ast_dump_context->ostream() << ") ";
4250 // Make a unary expression.
4252 Expression*
4253 Expression::make_unary(Operator op, Expression* expr, Location location)
4255 return new Unary_expression(op, expr, location);
4258 // If this is an indirection through a pointer, return the expression
4259 // being pointed through. Otherwise return this.
4261 Expression*
4262 Expression::deref()
4264 if (this->classification_ == EXPRESSION_UNARY)
4266 Unary_expression* ue = static_cast<Unary_expression*>(this);
4267 if (ue->op() == OPERATOR_MULT)
4268 return ue->operand();
4270 return this;
4273 // Class Binary_expression.
4275 // Traversal.
4278 Binary_expression::do_traverse(Traverse* traverse)
4280 int t = Expression::traverse(&this->left_, traverse);
4281 if (t == TRAVERSE_EXIT)
4282 return TRAVERSE_EXIT;
4283 return Expression::traverse(&this->right_, traverse);
4286 // Return the type to use for a binary operation on operands of
4287 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4288 // such may be NULL or abstract.
4290 bool
4291 Binary_expression::operation_type(Operator op, Type* left_type,
4292 Type* right_type, Type** result_type)
4294 if (left_type != right_type
4295 && !left_type->is_abstract()
4296 && !right_type->is_abstract()
4297 && left_type->base() != right_type->base()
4298 && op != OPERATOR_LSHIFT
4299 && op != OPERATOR_RSHIFT)
4301 // May be a type error--let it be diagnosed elsewhere.
4302 return false;
4305 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4307 if (left_type->integer_type() != NULL)
4308 *result_type = left_type;
4309 else
4310 *result_type = Type::make_abstract_integer_type();
4312 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4313 *result_type = left_type;
4314 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4315 *result_type = right_type;
4316 else if (!left_type->is_abstract())
4317 *result_type = left_type;
4318 else if (!right_type->is_abstract())
4319 *result_type = right_type;
4320 else if (left_type->complex_type() != NULL)
4321 *result_type = left_type;
4322 else if (right_type->complex_type() != NULL)
4323 *result_type = right_type;
4324 else if (left_type->float_type() != NULL)
4325 *result_type = left_type;
4326 else if (right_type->float_type() != NULL)
4327 *result_type = right_type;
4328 else if (left_type->integer_type() != NULL
4329 && left_type->integer_type()->is_rune())
4330 *result_type = left_type;
4331 else if (right_type->integer_type() != NULL
4332 && right_type->integer_type()->is_rune())
4333 *result_type = right_type;
4334 else
4335 *result_type = left_type;
4337 return true;
4340 // Convert an integer comparison code and an operator to a boolean
4341 // value.
4343 bool
4344 Binary_expression::cmp_to_bool(Operator op, int cmp)
4346 switch (op)
4348 case OPERATOR_EQEQ:
4349 return cmp == 0;
4350 break;
4351 case OPERATOR_NOTEQ:
4352 return cmp != 0;
4353 break;
4354 case OPERATOR_LT:
4355 return cmp < 0;
4356 break;
4357 case OPERATOR_LE:
4358 return cmp <= 0;
4359 case OPERATOR_GT:
4360 return cmp > 0;
4361 case OPERATOR_GE:
4362 return cmp >= 0;
4363 default:
4364 go_unreachable();
4368 // Compare constants according to OP.
4370 bool
4371 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4372 Numeric_constant* right_nc,
4373 Location location, bool* result)
4375 Type* left_type = left_nc->type();
4376 Type* right_type = right_nc->type();
4378 Type* type;
4379 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4380 return false;
4382 // When comparing an untyped operand to a typed operand, we are
4383 // effectively coercing the untyped operand to the other operand's
4384 // type, so make sure that is valid.
4385 if (!left_nc->set_type(type, true, location)
4386 || !right_nc->set_type(type, true, location))
4387 return false;
4389 bool ret;
4390 int cmp;
4391 if (type->complex_type() != NULL)
4393 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4394 return false;
4395 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4397 else if (type->float_type() != NULL)
4398 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4399 else
4400 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4402 if (ret)
4403 *result = Binary_expression::cmp_to_bool(op, cmp);
4405 return ret;
4408 // Compare integer constants.
4410 bool
4411 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4412 const Numeric_constant* right_nc,
4413 int* cmp)
4415 mpz_t left_val;
4416 if (!left_nc->to_int(&left_val))
4417 return false;
4418 mpz_t right_val;
4419 if (!right_nc->to_int(&right_val))
4421 mpz_clear(left_val);
4422 return false;
4425 *cmp = mpz_cmp(left_val, right_val);
4427 mpz_clear(left_val);
4428 mpz_clear(right_val);
4430 return true;
4433 // Compare floating point constants.
4435 bool
4436 Binary_expression::compare_float(const Numeric_constant* left_nc,
4437 const Numeric_constant* right_nc,
4438 int* cmp)
4440 mpfr_t left_val;
4441 if (!left_nc->to_float(&left_val))
4442 return false;
4443 mpfr_t right_val;
4444 if (!right_nc->to_float(&right_val))
4446 mpfr_clear(left_val);
4447 return false;
4450 // We already coerced both operands to the same type. If that type
4451 // is not an abstract type, we need to round the values accordingly.
4452 Type* type = left_nc->type();
4453 if (!type->is_abstract() && type->float_type() != NULL)
4455 int bits = type->float_type()->bits();
4456 mpfr_prec_round(left_val, bits, GMP_RNDN);
4457 mpfr_prec_round(right_val, bits, GMP_RNDN);
4460 *cmp = mpfr_cmp(left_val, right_val);
4462 mpfr_clear(left_val);
4463 mpfr_clear(right_val);
4465 return true;
4468 // Compare complex constants. Complex numbers may only be compared
4469 // for equality.
4471 bool
4472 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4473 const Numeric_constant* right_nc,
4474 int* cmp)
4476 mpfr_t left_real, left_imag;
4477 if (!left_nc->to_complex(&left_real, &left_imag))
4478 return false;
4479 mpfr_t right_real, right_imag;
4480 if (!right_nc->to_complex(&right_real, &right_imag))
4482 mpfr_clear(left_real);
4483 mpfr_clear(left_imag);
4484 return false;
4487 // We already coerced both operands to the same type. If that type
4488 // is not an abstract type, we need to round the values accordingly.
4489 Type* type = left_nc->type();
4490 if (!type->is_abstract() && type->complex_type() != NULL)
4492 int bits = type->complex_type()->bits();
4493 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4494 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4495 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4496 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4499 *cmp = (mpfr_cmp(left_real, right_real) != 0
4500 || mpfr_cmp(left_imag, right_imag) != 0);
4502 mpfr_clear(left_real);
4503 mpfr_clear(left_imag);
4504 mpfr_clear(right_real);
4505 mpfr_clear(right_imag);
4507 return true;
4510 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4511 // true if this could be done, false if not. Issue errors at LOCATION
4512 // as appropriate.
4514 bool
4515 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4516 Numeric_constant* right_nc,
4517 Location location, Numeric_constant* nc)
4519 switch (op)
4521 case OPERATOR_OROR:
4522 case OPERATOR_ANDAND:
4523 case OPERATOR_EQEQ:
4524 case OPERATOR_NOTEQ:
4525 case OPERATOR_LT:
4526 case OPERATOR_LE:
4527 case OPERATOR_GT:
4528 case OPERATOR_GE:
4529 // These return boolean values, not numeric.
4530 return false;
4531 default:
4532 break;
4535 Type* left_type = left_nc->type();
4536 Type* right_type = right_nc->type();
4538 Type* type;
4539 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4540 return false;
4542 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4544 // When combining an untyped operand with a typed operand, we are
4545 // effectively coercing the untyped operand to the other operand's
4546 // type, so make sure that is valid.
4547 if (!left_nc->set_type(type, true, location))
4548 return false;
4549 if (!is_shift && !right_nc->set_type(type, true, location))
4550 return false;
4552 bool r;
4553 if (type->complex_type() != NULL)
4554 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4555 else if (type->float_type() != NULL)
4556 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4557 else
4558 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4560 if (r)
4561 r = nc->set_type(type, true, location);
4563 return r;
4566 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4567 // integer operations. Return true if this could be done, false if
4568 // not.
4570 bool
4571 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4572 const Numeric_constant* right_nc,
4573 Location location, Numeric_constant* nc)
4575 mpz_t left_val;
4576 if (!left_nc->to_int(&left_val))
4577 return false;
4578 mpz_t right_val;
4579 if (!right_nc->to_int(&right_val))
4581 mpz_clear(left_val);
4582 return false;
4585 mpz_t val;
4586 mpz_init(val);
4588 switch (op)
4590 case OPERATOR_PLUS:
4591 mpz_add(val, left_val, right_val);
4592 if (mpz_sizeinbase(val, 2) > 0x100000)
4594 error_at(location, "constant addition overflow");
4595 mpz_set_ui(val, 1);
4597 break;
4598 case OPERATOR_MINUS:
4599 mpz_sub(val, left_val, right_val);
4600 if (mpz_sizeinbase(val, 2) > 0x100000)
4602 error_at(location, "constant subtraction overflow");
4603 mpz_set_ui(val, 1);
4605 break;
4606 case OPERATOR_OR:
4607 mpz_ior(val, left_val, right_val);
4608 break;
4609 case OPERATOR_XOR:
4610 mpz_xor(val, left_val, right_val);
4611 break;
4612 case OPERATOR_MULT:
4613 mpz_mul(val, left_val, right_val);
4614 if (mpz_sizeinbase(val, 2) > 0x100000)
4616 error_at(location, "constant multiplication overflow");
4617 mpz_set_ui(val, 1);
4619 break;
4620 case OPERATOR_DIV:
4621 if (mpz_sgn(right_val) != 0)
4622 mpz_tdiv_q(val, left_val, right_val);
4623 else
4625 error_at(location, "division by zero");
4626 mpz_set_ui(val, 0);
4628 break;
4629 case OPERATOR_MOD:
4630 if (mpz_sgn(right_val) != 0)
4631 mpz_tdiv_r(val, left_val, right_val);
4632 else
4634 error_at(location, "division by zero");
4635 mpz_set_ui(val, 0);
4637 break;
4638 case OPERATOR_LSHIFT:
4640 unsigned long shift = mpz_get_ui(right_val);
4641 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4642 mpz_mul_2exp(val, left_val, shift);
4643 else
4645 error_at(location, "shift count overflow");
4646 mpz_set_ui(val, 1);
4648 break;
4650 break;
4651 case OPERATOR_RSHIFT:
4653 unsigned long shift = mpz_get_ui(right_val);
4654 if (mpz_cmp_ui(right_val, shift) != 0)
4656 error_at(location, "shift count overflow");
4657 mpz_set_ui(val, 1);
4659 else
4661 if (mpz_cmp_ui(left_val, 0) >= 0)
4662 mpz_tdiv_q_2exp(val, left_val, shift);
4663 else
4664 mpz_fdiv_q_2exp(val, left_val, shift);
4666 break;
4668 break;
4669 case OPERATOR_AND:
4670 mpz_and(val, left_val, right_val);
4671 break;
4672 case OPERATOR_BITCLEAR:
4674 mpz_t tval;
4675 mpz_init(tval);
4676 mpz_com(tval, right_val);
4677 mpz_and(val, left_val, tval);
4678 mpz_clear(tval);
4680 break;
4681 default:
4682 go_unreachable();
4685 mpz_clear(left_val);
4686 mpz_clear(right_val);
4688 if (left_nc->is_rune()
4689 || (op != OPERATOR_LSHIFT
4690 && op != OPERATOR_RSHIFT
4691 && right_nc->is_rune()))
4692 nc->set_rune(NULL, val);
4693 else
4694 nc->set_int(NULL, val);
4696 mpz_clear(val);
4698 return true;
4701 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4702 // floating point operations. Return true if this could be done,
4703 // false if not.
4705 bool
4706 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4707 const Numeric_constant* right_nc,
4708 Location location, Numeric_constant* nc)
4710 mpfr_t left_val;
4711 if (!left_nc->to_float(&left_val))
4712 return false;
4713 mpfr_t right_val;
4714 if (!right_nc->to_float(&right_val))
4716 mpfr_clear(left_val);
4717 return false;
4720 mpfr_t val;
4721 mpfr_init(val);
4723 bool ret = true;
4724 switch (op)
4726 case OPERATOR_PLUS:
4727 mpfr_add(val, left_val, right_val, GMP_RNDN);
4728 break;
4729 case OPERATOR_MINUS:
4730 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4731 break;
4732 case OPERATOR_OR:
4733 case OPERATOR_XOR:
4734 case OPERATOR_AND:
4735 case OPERATOR_BITCLEAR:
4736 case OPERATOR_MOD:
4737 case OPERATOR_LSHIFT:
4738 case OPERATOR_RSHIFT:
4739 mpfr_set_ui(val, 0, GMP_RNDN);
4740 ret = false;
4741 break;
4742 case OPERATOR_MULT:
4743 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4744 break;
4745 case OPERATOR_DIV:
4746 if (!mpfr_zero_p(right_val))
4747 mpfr_div(val, left_val, right_val, GMP_RNDN);
4748 else
4750 error_at(location, "division by zero");
4751 mpfr_set_ui(val, 0, GMP_RNDN);
4753 break;
4754 default:
4755 go_unreachable();
4758 mpfr_clear(left_val);
4759 mpfr_clear(right_val);
4761 nc->set_float(NULL, val);
4762 mpfr_clear(val);
4764 return ret;
4767 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4768 // complex operations. Return true if this could be done, false if
4769 // not.
4771 bool
4772 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4773 const Numeric_constant* right_nc,
4774 Location location, Numeric_constant* nc)
4776 mpfr_t left_real, left_imag;
4777 if (!left_nc->to_complex(&left_real, &left_imag))
4778 return false;
4779 mpfr_t right_real, right_imag;
4780 if (!right_nc->to_complex(&right_real, &right_imag))
4782 mpfr_clear(left_real);
4783 mpfr_clear(left_imag);
4784 return false;
4787 mpfr_t real, imag;
4788 mpfr_init(real);
4789 mpfr_init(imag);
4791 bool ret = true;
4792 switch (op)
4794 case OPERATOR_PLUS:
4795 mpfr_add(real, left_real, right_real, GMP_RNDN);
4796 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4797 break;
4798 case OPERATOR_MINUS:
4799 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4800 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4801 break;
4802 case OPERATOR_OR:
4803 case OPERATOR_XOR:
4804 case OPERATOR_AND:
4805 case OPERATOR_BITCLEAR:
4806 case OPERATOR_MOD:
4807 case OPERATOR_LSHIFT:
4808 case OPERATOR_RSHIFT:
4809 mpfr_set_ui(real, 0, GMP_RNDN);
4810 mpfr_set_ui(imag, 0, GMP_RNDN);
4811 ret = false;
4812 break;
4813 case OPERATOR_MULT:
4815 // You might think that multiplying two complex numbers would
4816 // be simple, and you would be right, until you start to think
4817 // about getting the right answer for infinity. If one
4818 // operand here is infinity and the other is anything other
4819 // than zero or NaN, then we are going to wind up subtracting
4820 // two infinity values. That will give us a NaN, but the
4821 // correct answer is infinity.
4823 mpfr_t lrrr;
4824 mpfr_init(lrrr);
4825 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4827 mpfr_t lrri;
4828 mpfr_init(lrri);
4829 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4831 mpfr_t lirr;
4832 mpfr_init(lirr);
4833 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4835 mpfr_t liri;
4836 mpfr_init(liri);
4837 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4839 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4840 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4842 // If we get NaN on both sides, check whether it should really
4843 // be infinity. The rule is that if either side of the
4844 // complex number is infinity, then the whole value is
4845 // infinity, even if the other side is NaN. So the only case
4846 // we have to fix is the one in which both sides are NaN.
4847 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4848 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4849 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4851 bool is_infinity = false;
4853 mpfr_t lr;
4854 mpfr_t li;
4855 mpfr_init_set(lr, left_real, GMP_RNDN);
4856 mpfr_init_set(li, left_imag, GMP_RNDN);
4858 mpfr_t rr;
4859 mpfr_t ri;
4860 mpfr_init_set(rr, right_real, GMP_RNDN);
4861 mpfr_init_set(ri, right_imag, GMP_RNDN);
4863 // If the left side is infinity, then the result is
4864 // infinity.
4865 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4867 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4868 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4869 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4870 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4871 if (mpfr_nan_p(rr))
4873 mpfr_set_ui(rr, 0, GMP_RNDN);
4874 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4876 if (mpfr_nan_p(ri))
4878 mpfr_set_ui(ri, 0, GMP_RNDN);
4879 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4881 is_infinity = true;
4884 // If the right side is infinity, then the result is
4885 // infinity.
4886 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4888 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4889 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4890 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4891 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4892 if (mpfr_nan_p(lr))
4894 mpfr_set_ui(lr, 0, GMP_RNDN);
4895 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4897 if (mpfr_nan_p(li))
4899 mpfr_set_ui(li, 0, GMP_RNDN);
4900 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4902 is_infinity = true;
4905 // If we got an overflow in the intermediate computations,
4906 // then the result is infinity.
4907 if (!is_infinity
4908 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4909 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4911 if (mpfr_nan_p(lr))
4913 mpfr_set_ui(lr, 0, GMP_RNDN);
4914 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4916 if (mpfr_nan_p(li))
4918 mpfr_set_ui(li, 0, GMP_RNDN);
4919 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4921 if (mpfr_nan_p(rr))
4923 mpfr_set_ui(rr, 0, GMP_RNDN);
4924 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4926 if (mpfr_nan_p(ri))
4928 mpfr_set_ui(ri, 0, GMP_RNDN);
4929 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4931 is_infinity = true;
4934 if (is_infinity)
4936 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4937 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4938 mpfr_mul(lirr, li, rr, GMP_RNDN);
4939 mpfr_mul(liri, li, ri, GMP_RNDN);
4940 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4941 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4942 mpfr_set_inf(real, mpfr_sgn(real));
4943 mpfr_set_inf(imag, mpfr_sgn(imag));
4946 mpfr_clear(lr);
4947 mpfr_clear(li);
4948 mpfr_clear(rr);
4949 mpfr_clear(ri);
4952 mpfr_clear(lrrr);
4953 mpfr_clear(lrri);
4954 mpfr_clear(lirr);
4955 mpfr_clear(liri);
4957 break;
4958 case OPERATOR_DIV:
4960 // For complex division we want to avoid having an
4961 // intermediate overflow turn the whole result in a NaN. We
4962 // scale the values to try to avoid this.
4964 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4966 error_at(location, "division by zero");
4967 mpfr_set_ui(real, 0, GMP_RNDN);
4968 mpfr_set_ui(imag, 0, GMP_RNDN);
4969 break;
4972 mpfr_t rra;
4973 mpfr_t ria;
4974 mpfr_init(rra);
4975 mpfr_init(ria);
4976 mpfr_abs(rra, right_real, GMP_RNDN);
4977 mpfr_abs(ria, right_imag, GMP_RNDN);
4978 mpfr_t t;
4979 mpfr_init(t);
4980 mpfr_max(t, rra, ria, GMP_RNDN);
4982 mpfr_t rr;
4983 mpfr_t ri;
4984 mpfr_init_set(rr, right_real, GMP_RNDN);
4985 mpfr_init_set(ri, right_imag, GMP_RNDN);
4986 long ilogbw = 0;
4987 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4989 ilogbw = mpfr_get_exp(t);
4990 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4991 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4994 mpfr_t denom;
4995 mpfr_init(denom);
4996 mpfr_mul(denom, rr, rr, GMP_RNDN);
4997 mpfr_mul(t, ri, ri, GMP_RNDN);
4998 mpfr_add(denom, denom, t, GMP_RNDN);
5000 mpfr_mul(real, left_real, rr, GMP_RNDN);
5001 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5002 mpfr_add(real, real, t, GMP_RNDN);
5003 mpfr_div(real, real, denom, GMP_RNDN);
5004 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5006 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5007 mpfr_mul(t, left_real, ri, GMP_RNDN);
5008 mpfr_sub(imag, imag, t, GMP_RNDN);
5009 mpfr_div(imag, imag, denom, GMP_RNDN);
5010 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5012 // If we wind up with NaN on both sides, check whether we
5013 // should really have infinity. The rule is that if either
5014 // side of the complex number is infinity, then the whole
5015 // value is infinity, even if the other side is NaN. So the
5016 // only case we have to fix is the one in which both sides are
5017 // NaN.
5018 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5019 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5020 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5022 if (mpfr_zero_p(denom))
5024 mpfr_set_inf(real, mpfr_sgn(rr));
5025 mpfr_mul(real, real, left_real, GMP_RNDN);
5026 mpfr_set_inf(imag, mpfr_sgn(rr));
5027 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5029 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5030 && mpfr_number_p(rr) && mpfr_number_p(ri))
5032 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5033 mpfr_copysign(t, t, left_real, GMP_RNDN);
5035 mpfr_t t2;
5036 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5037 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5039 mpfr_t t3;
5040 mpfr_init(t3);
5041 mpfr_mul(t3, t, rr, GMP_RNDN);
5043 mpfr_t t4;
5044 mpfr_init(t4);
5045 mpfr_mul(t4, t2, ri, GMP_RNDN);
5047 mpfr_add(t3, t3, t4, GMP_RNDN);
5048 mpfr_set_inf(real, mpfr_sgn(t3));
5050 mpfr_mul(t3, t2, rr, GMP_RNDN);
5051 mpfr_mul(t4, t, ri, GMP_RNDN);
5052 mpfr_sub(t3, t3, t4, GMP_RNDN);
5053 mpfr_set_inf(imag, mpfr_sgn(t3));
5055 mpfr_clear(t2);
5056 mpfr_clear(t3);
5057 mpfr_clear(t4);
5059 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5060 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5062 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5063 mpfr_copysign(t, t, rr, GMP_RNDN);
5065 mpfr_t t2;
5066 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5067 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5069 mpfr_t t3;
5070 mpfr_init(t3);
5071 mpfr_mul(t3, left_real, t, GMP_RNDN);
5073 mpfr_t t4;
5074 mpfr_init(t4);
5075 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5077 mpfr_add(t3, t3, t4, GMP_RNDN);
5078 mpfr_set_ui(real, 0, GMP_RNDN);
5079 mpfr_mul(real, real, t3, GMP_RNDN);
5081 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5082 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5083 mpfr_sub(t3, t3, t4, GMP_RNDN);
5084 mpfr_set_ui(imag, 0, GMP_RNDN);
5085 mpfr_mul(imag, imag, t3, GMP_RNDN);
5087 mpfr_clear(t2);
5088 mpfr_clear(t3);
5089 mpfr_clear(t4);
5093 mpfr_clear(denom);
5094 mpfr_clear(rr);
5095 mpfr_clear(ri);
5096 mpfr_clear(t);
5097 mpfr_clear(rra);
5098 mpfr_clear(ria);
5100 break;
5101 default:
5102 go_unreachable();
5105 mpfr_clear(left_real);
5106 mpfr_clear(left_imag);
5107 mpfr_clear(right_real);
5108 mpfr_clear(right_imag);
5110 nc->set_complex(NULL, real, imag);
5111 mpfr_clear(real);
5112 mpfr_clear(imag);
5114 return ret;
5117 // Lower a binary expression. We have to evaluate constant
5118 // expressions now, in order to implement Go's unlimited precision
5119 // constants.
5121 Expression*
5122 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5123 Statement_inserter* inserter, int)
5125 Location location = this->location();
5126 Operator op = this->op_;
5127 Expression* left = this->left_;
5128 Expression* right = this->right_;
5130 const bool is_comparison = (op == OPERATOR_EQEQ
5131 || op == OPERATOR_NOTEQ
5132 || op == OPERATOR_LT
5133 || op == OPERATOR_LE
5134 || op == OPERATOR_GT
5135 || op == OPERATOR_GE);
5137 // Numeric constant expressions.
5139 Numeric_constant left_nc;
5140 Numeric_constant right_nc;
5141 if (left->numeric_constant_value(&left_nc)
5142 && right->numeric_constant_value(&right_nc))
5144 if (is_comparison)
5146 bool result;
5147 if (!Binary_expression::compare_constant(op, &left_nc,
5148 &right_nc, location,
5149 &result))
5150 return this;
5151 return Expression::make_cast(Type::make_boolean_type(),
5152 Expression::make_boolean(result,
5153 location),
5154 location);
5156 else
5158 Numeric_constant nc;
5159 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5160 location, &nc))
5161 return this;
5162 return nc.expression(location);
5167 // String constant expressions.
5168 if (left->type()->is_string_type() && right->type()->is_string_type())
5170 std::string left_string;
5171 std::string right_string;
5172 if (left->string_constant_value(&left_string)
5173 && right->string_constant_value(&right_string))
5175 if (op == OPERATOR_PLUS)
5176 return Expression::make_string(left_string + right_string,
5177 location);
5178 else if (is_comparison)
5180 int cmp = left_string.compare(right_string);
5181 bool r = Binary_expression::cmp_to_bool(op, cmp);
5182 return Expression::make_boolean(r, location);
5187 // Lower struct, array, and some interface comparisons.
5188 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5190 if (left->type()->struct_type() != NULL)
5191 return this->lower_struct_comparison(gogo, inserter);
5192 else if (left->type()->array_type() != NULL
5193 && !left->type()->is_slice_type())
5194 return this->lower_array_comparison(gogo, inserter);
5195 else if ((left->type()->interface_type() != NULL
5196 && right->type()->interface_type() == NULL)
5197 || (left->type()->interface_type() == NULL
5198 && right->type()->interface_type() != NULL))
5199 return this->lower_interface_value_comparison(gogo, inserter);
5202 return this;
5205 // Lower a struct comparison.
5207 Expression*
5208 Binary_expression::lower_struct_comparison(Gogo* gogo,
5209 Statement_inserter* inserter)
5211 Struct_type* st = this->left_->type()->struct_type();
5212 Struct_type* st2 = this->right_->type()->struct_type();
5213 if (st2 == NULL)
5214 return this;
5215 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5216 return this;
5217 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5218 this->right_->type(), NULL))
5219 return this;
5221 // See if we can compare using memcmp. As a heuristic, we use
5222 // memcmp rather than field references and comparisons if there are
5223 // more than two fields.
5224 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5225 return this->lower_compare_to_memcmp(gogo, inserter);
5227 Location loc = this->location();
5229 Expression* left = this->left_;
5230 Temporary_statement* left_temp = NULL;
5231 if (left->var_expression() == NULL
5232 && left->temporary_reference_expression() == NULL)
5234 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5235 inserter->insert(left_temp);
5236 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5239 Expression* right = this->right_;
5240 Temporary_statement* right_temp = NULL;
5241 if (right->var_expression() == NULL
5242 && right->temporary_reference_expression() == NULL)
5244 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5245 inserter->insert(right_temp);
5246 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5249 Expression* ret = Expression::make_boolean(true, loc);
5250 const Struct_field_list* fields = st->fields();
5251 unsigned int field_index = 0;
5252 for (Struct_field_list::const_iterator pf = fields->begin();
5253 pf != fields->end();
5254 ++pf, ++field_index)
5256 if (Gogo::is_sink_name(pf->field_name()))
5257 continue;
5259 if (field_index > 0)
5261 if (left_temp == NULL)
5262 left = left->copy();
5263 else
5264 left = Expression::make_temporary_reference(left_temp, loc);
5265 if (right_temp == NULL)
5266 right = right->copy();
5267 else
5268 right = Expression::make_temporary_reference(right_temp, loc);
5270 Expression* f1 = Expression::make_field_reference(left, field_index,
5271 loc);
5272 Expression* f2 = Expression::make_field_reference(right, field_index,
5273 loc);
5274 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5275 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5278 if (this->op_ == OPERATOR_NOTEQ)
5279 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5281 return ret;
5284 // Lower an array comparison.
5286 Expression*
5287 Binary_expression::lower_array_comparison(Gogo* gogo,
5288 Statement_inserter* inserter)
5290 Array_type* at = this->left_->type()->array_type();
5291 Array_type* at2 = this->right_->type()->array_type();
5292 if (at2 == NULL)
5293 return this;
5294 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5295 return this;
5296 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5297 this->right_->type(), NULL))
5298 return this;
5300 // Call memcmp directly if possible. This may let the middle-end
5301 // optimize the call.
5302 if (at->compare_is_identity(gogo))
5303 return this->lower_compare_to_memcmp(gogo, inserter);
5305 // Call the array comparison function.
5306 Named_object* hash_fn;
5307 Named_object* equal_fn;
5308 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5309 &hash_fn, &equal_fn);
5311 Location loc = this->location();
5313 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5315 Expression_list* args = new Expression_list();
5316 args->push_back(this->operand_address(inserter, this->left_));
5317 args->push_back(this->operand_address(inserter, this->right_));
5318 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5320 Expression* ret = Expression::make_call(func, args, false, loc);
5322 if (this->op_ == OPERATOR_NOTEQ)
5323 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5325 return ret;
5328 // Lower an interface to value comparison.
5330 Expression*
5331 Binary_expression::lower_interface_value_comparison(Gogo*,
5332 Statement_inserter* inserter)
5334 Type* left_type = this->left_->type();
5335 Type* right_type = this->right_->type();
5336 Interface_type* ift;
5337 if (left_type->interface_type() != NULL)
5339 ift = left_type->interface_type();
5340 if (!ift->implements_interface(right_type, NULL))
5341 return this;
5343 else
5345 ift = right_type->interface_type();
5346 if (!ift->implements_interface(left_type, NULL))
5347 return this;
5349 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5350 return this;
5352 Location loc = this->location();
5354 if (left_type->interface_type() == NULL
5355 && left_type->points_to() == NULL
5356 && !this->left_->is_addressable())
5358 Temporary_statement* temp =
5359 Statement::make_temporary(left_type, NULL, loc);
5360 inserter->insert(temp);
5361 this->left_ =
5362 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5365 if (right_type->interface_type() == NULL
5366 && right_type->points_to() == NULL
5367 && !this->right_->is_addressable())
5369 Temporary_statement* temp =
5370 Statement::make_temporary(right_type, NULL, loc);
5371 inserter->insert(temp);
5372 this->right_ =
5373 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5376 return this;
5379 // Lower a struct or array comparison to a call to memcmp.
5381 Expression*
5382 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5384 Location loc = this->location();
5386 Expression* a1 = this->operand_address(inserter, this->left_);
5387 Expression* a2 = this->operand_address(inserter, this->right_);
5388 Expression* len = Expression::make_type_info(this->left_->type(),
5389 TYPE_INFO_SIZE);
5391 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5393 mpz_t zval;
5394 mpz_init_set_ui(zval, 0);
5395 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5396 mpz_clear(zval);
5398 return Expression::make_binary(this->op_, call, zero, loc);
5401 Expression*
5402 Binary_expression::do_flatten(Gogo*, Named_object*,
5403 Statement_inserter* inserter)
5405 Location loc = this->location();
5406 Temporary_statement* temp;
5407 if (this->left_->type()->is_string_type()
5408 && this->op_ == OPERATOR_PLUS)
5410 if (!this->left_->is_variable())
5412 temp = Statement::make_temporary(NULL, this->left_, loc);
5413 inserter->insert(temp);
5414 this->left_ = Expression::make_temporary_reference(temp, loc);
5416 if (!this->right_->is_variable())
5418 temp =
5419 Statement::make_temporary(this->left_->type(), this->right_, loc);
5420 this->right_ = Expression::make_temporary_reference(temp, loc);
5421 inserter->insert(temp);
5425 Type* left_type = this->left_->type();
5426 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5427 || this->op_ == OPERATOR_RSHIFT);
5428 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5429 left_type->integer_type() != NULL)
5430 || this->op_ == OPERATOR_MOD);
5432 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5433 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5434 // and accessed from the Gogo* passed to do_flatten.
5435 if (is_shift_op
5436 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5438 if (!this->left_->is_variable())
5440 temp = Statement::make_temporary(NULL, this->left_, loc);
5441 inserter->insert(temp);
5442 this->left_ = Expression::make_temporary_reference(temp, loc);
5444 if (!this->right_->is_variable())
5446 temp =
5447 Statement::make_temporary(NULL, this->right_, loc);
5448 this->right_ = Expression::make_temporary_reference(temp, loc);
5449 inserter->insert(temp);
5452 return this;
5456 // Return the address of EXPR, cast to unsafe.Pointer.
5458 Expression*
5459 Binary_expression::operand_address(Statement_inserter* inserter,
5460 Expression* expr)
5462 Location loc = this->location();
5464 if (!expr->is_addressable())
5466 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5467 loc);
5468 inserter->insert(temp);
5469 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5471 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5472 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5473 Type* void_type = Type::make_void_type();
5474 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5475 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5478 // Return the numeric constant value, if it has one.
5480 bool
5481 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5483 Numeric_constant left_nc;
5484 if (!this->left_->numeric_constant_value(&left_nc))
5485 return false;
5486 Numeric_constant right_nc;
5487 if (!this->right_->numeric_constant_value(&right_nc))
5488 return false;
5489 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5490 this->location(), nc);
5493 // Note that the value is being discarded.
5495 bool
5496 Binary_expression::do_discarding_value()
5498 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5499 return this->right_->discarding_value();
5500 else
5502 this->unused_value_error();
5503 return false;
5507 // Get type.
5509 Type*
5510 Binary_expression::do_type()
5512 if (this->classification() == EXPRESSION_ERROR)
5513 return Type::make_error_type();
5515 switch (this->op_)
5517 case OPERATOR_EQEQ:
5518 case OPERATOR_NOTEQ:
5519 case OPERATOR_LT:
5520 case OPERATOR_LE:
5521 case OPERATOR_GT:
5522 case OPERATOR_GE:
5523 if (this->type_ == NULL)
5524 this->type_ = Type::make_boolean_type();
5525 return this->type_;
5527 case OPERATOR_PLUS:
5528 case OPERATOR_MINUS:
5529 case OPERATOR_OR:
5530 case OPERATOR_XOR:
5531 case OPERATOR_MULT:
5532 case OPERATOR_DIV:
5533 case OPERATOR_MOD:
5534 case OPERATOR_AND:
5535 case OPERATOR_BITCLEAR:
5536 case OPERATOR_OROR:
5537 case OPERATOR_ANDAND:
5539 Type* type;
5540 if (!Binary_expression::operation_type(this->op_,
5541 this->left_->type(),
5542 this->right_->type(),
5543 &type))
5544 return Type::make_error_type();
5545 return type;
5548 case OPERATOR_LSHIFT:
5549 case OPERATOR_RSHIFT:
5550 return this->left_->type();
5552 default:
5553 go_unreachable();
5557 // Set type for a binary expression.
5559 void
5560 Binary_expression::do_determine_type(const Type_context* context)
5562 Type* tleft = this->left_->type();
5563 Type* tright = this->right_->type();
5565 // Both sides should have the same type, except for the shift
5566 // operations. For a comparison, we should ignore the incoming
5567 // type.
5569 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5570 || this->op_ == OPERATOR_RSHIFT);
5572 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5573 || this->op_ == OPERATOR_NOTEQ
5574 || this->op_ == OPERATOR_LT
5575 || this->op_ == OPERATOR_LE
5576 || this->op_ == OPERATOR_GT
5577 || this->op_ == OPERATOR_GE);
5579 Type_context subcontext(*context);
5581 if (is_comparison)
5583 // In a comparison, the context does not determine the types of
5584 // the operands.
5585 subcontext.type = NULL;
5588 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5590 // For a logical operation, the context does not determine the
5591 // types of the operands. The operands must be some boolean
5592 // type but if the context has a boolean type they do not
5593 // inherit it. See http://golang.org/issue/3924.
5594 subcontext.type = NULL;
5597 // Set the context for the left hand operand.
5598 if (is_shift_op)
5600 // The right hand operand of a shift plays no role in
5601 // determining the type of the left hand operand.
5603 else if (!tleft->is_abstract())
5604 subcontext.type = tleft;
5605 else if (!tright->is_abstract())
5606 subcontext.type = tright;
5607 else if (subcontext.type == NULL)
5609 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5610 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5611 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5613 // Both sides have an abstract integer, abstract float, or
5614 // abstract complex type. Just let CONTEXT determine
5615 // whether they may remain abstract or not.
5617 else if (tleft->complex_type() != NULL)
5618 subcontext.type = tleft;
5619 else if (tright->complex_type() != NULL)
5620 subcontext.type = tright;
5621 else if (tleft->float_type() != NULL)
5622 subcontext.type = tleft;
5623 else if (tright->float_type() != NULL)
5624 subcontext.type = tright;
5625 else
5626 subcontext.type = tleft;
5628 if (subcontext.type != NULL && !context->may_be_abstract)
5629 subcontext.type = subcontext.type->make_non_abstract_type();
5632 this->left_->determine_type(&subcontext);
5634 if (is_shift_op)
5636 // We may have inherited an unusable type for the shift operand.
5637 // Give a useful error if that happened.
5638 if (tleft->is_abstract()
5639 && subcontext.type != NULL
5640 && !subcontext.may_be_abstract
5641 && subcontext.type->interface_type() == NULL
5642 && subcontext.type->integer_type() == NULL)
5643 this->report_error(("invalid context-determined non-integer type "
5644 "for left operand of shift"));
5646 // The context for the right hand operand is the same as for the
5647 // left hand operand, except for a shift operator.
5648 subcontext.type = Type::lookup_integer_type("uint");
5649 subcontext.may_be_abstract = false;
5652 this->right_->determine_type(&subcontext);
5654 if (is_comparison)
5656 if (this->type_ != NULL && !this->type_->is_abstract())
5658 else if (context->type != NULL && context->type->is_boolean_type())
5659 this->type_ = context->type;
5660 else if (!context->may_be_abstract)
5661 this->type_ = Type::lookup_bool_type();
5665 // Report an error if the binary operator OP does not support TYPE.
5666 // OTYPE is the type of the other operand. Return whether the
5667 // operation is OK. This should not be used for shift.
5669 bool
5670 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5671 Location location)
5673 switch (op)
5675 case OPERATOR_OROR:
5676 case OPERATOR_ANDAND:
5677 if (!type->is_boolean_type())
5679 error_at(location, "expected boolean type");
5680 return false;
5682 break;
5684 case OPERATOR_EQEQ:
5685 case OPERATOR_NOTEQ:
5687 std::string reason;
5688 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5690 error_at(location, "%s", reason.c_str());
5691 return false;
5694 break;
5696 case OPERATOR_LT:
5697 case OPERATOR_LE:
5698 case OPERATOR_GT:
5699 case OPERATOR_GE:
5701 std::string reason;
5702 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5704 error_at(location, "%s", reason.c_str());
5705 return false;
5708 break;
5710 case OPERATOR_PLUS:
5711 case OPERATOR_PLUSEQ:
5712 if (type->integer_type() == NULL
5713 && type->float_type() == NULL
5714 && type->complex_type() == NULL
5715 && !type->is_string_type())
5717 error_at(location,
5718 "expected integer, floating, complex, or string type");
5719 return false;
5721 break;
5723 case OPERATOR_MINUS:
5724 case OPERATOR_MINUSEQ:
5725 case OPERATOR_MULT:
5726 case OPERATOR_MULTEQ:
5727 case OPERATOR_DIV:
5728 case OPERATOR_DIVEQ:
5729 if (type->integer_type() == NULL
5730 && type->float_type() == NULL
5731 && type->complex_type() == NULL)
5733 error_at(location, "expected integer, floating, or complex type");
5734 return false;
5736 break;
5738 case OPERATOR_MOD:
5739 case OPERATOR_MODEQ:
5740 case OPERATOR_OR:
5741 case OPERATOR_OREQ:
5742 case OPERATOR_AND:
5743 case OPERATOR_ANDEQ:
5744 case OPERATOR_XOR:
5745 case OPERATOR_XOREQ:
5746 case OPERATOR_BITCLEAR:
5747 case OPERATOR_BITCLEAREQ:
5748 if (type->integer_type() == NULL)
5750 error_at(location, "expected integer type");
5751 return false;
5753 break;
5755 default:
5756 go_unreachable();
5759 return true;
5762 // Check types.
5764 void
5765 Binary_expression::do_check_types(Gogo*)
5767 if (this->classification() == EXPRESSION_ERROR)
5768 return;
5770 Type* left_type = this->left_->type();
5771 Type* right_type = this->right_->type();
5772 if (left_type->is_error() || right_type->is_error())
5774 this->set_is_error();
5775 return;
5778 if (this->op_ == OPERATOR_EQEQ
5779 || this->op_ == OPERATOR_NOTEQ
5780 || this->op_ == OPERATOR_LT
5781 || this->op_ == OPERATOR_LE
5782 || this->op_ == OPERATOR_GT
5783 || this->op_ == OPERATOR_GE)
5785 if (left_type->is_nil_type() && right_type->is_nil_type())
5787 this->report_error(_("invalid comparison of nil with nil"));
5788 return;
5790 if (!Type::are_assignable(left_type, right_type, NULL)
5791 && !Type::are_assignable(right_type, left_type, NULL))
5793 this->report_error(_("incompatible types in binary expression"));
5794 return;
5796 if (!Binary_expression::check_operator_type(this->op_, left_type,
5797 right_type,
5798 this->location())
5799 || !Binary_expression::check_operator_type(this->op_, right_type,
5800 left_type,
5801 this->location()))
5803 this->set_is_error();
5804 return;
5807 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5809 if (!Type::are_compatible_for_binop(left_type, right_type))
5811 this->report_error(_("incompatible types in binary expression"));
5812 return;
5814 if (!Binary_expression::check_operator_type(this->op_, left_type,
5815 right_type,
5816 this->location()))
5818 this->set_is_error();
5819 return;
5821 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5823 // Division by a zero integer constant is an error.
5824 Numeric_constant rconst;
5825 unsigned long rval;
5826 if (left_type->integer_type() != NULL
5827 && this->right_->numeric_constant_value(&rconst)
5828 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5829 && rval == 0)
5831 this->report_error(_("integer division by zero"));
5832 return;
5836 else
5838 if (left_type->integer_type() == NULL)
5839 this->report_error(_("shift of non-integer operand"));
5841 if (!right_type->is_abstract()
5842 && (right_type->integer_type() == NULL
5843 || !right_type->integer_type()->is_unsigned()))
5844 this->report_error(_("shift count not unsigned integer"));
5845 else
5847 Numeric_constant nc;
5848 if (this->right_->numeric_constant_value(&nc))
5850 mpz_t val;
5851 if (!nc.to_int(&val))
5852 this->report_error(_("shift count not unsigned integer"));
5853 else
5855 if (mpz_sgn(val) < 0)
5857 this->report_error(_("negative shift count"));
5858 mpz_set_ui(val, 0);
5859 Location rloc = this->right_->location();
5860 this->right_ = Expression::make_integer(&val, right_type,
5861 rloc);
5863 mpz_clear(val);
5870 // Get a tree for a binary expression.
5872 tree
5873 Binary_expression::do_get_tree(Translate_context* context)
5875 Gogo* gogo = context->gogo();
5876 Location loc = this->location();
5877 Type* left_type = this->left_->type();
5878 Type* right_type = this->right_->type();
5880 bool use_left_type = true;
5881 bool is_shift_op = false;
5882 bool is_idiv_op = false;
5883 switch (this->op_)
5885 case OPERATOR_EQEQ:
5886 case OPERATOR_NOTEQ:
5887 case OPERATOR_LT:
5888 case OPERATOR_LE:
5889 case OPERATOR_GT:
5890 case OPERATOR_GE:
5892 Bexpression* ret =
5893 Expression::comparison(context, this->type_, this->op_,
5894 this->left_, this->right_, loc);
5895 return expr_to_tree(ret);
5898 case OPERATOR_OROR:
5899 case OPERATOR_ANDAND:
5900 use_left_type = false;
5901 break;
5902 case OPERATOR_PLUS:
5903 case OPERATOR_MINUS:
5904 case OPERATOR_OR:
5905 case OPERATOR_XOR:
5906 case OPERATOR_MULT:
5907 break;
5908 case OPERATOR_DIV:
5909 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5910 break;
5911 case OPERATOR_MOD:
5912 is_idiv_op = true;
5913 break;
5914 case OPERATOR_LSHIFT:
5915 case OPERATOR_RSHIFT:
5916 is_shift_op = true;
5917 break;
5918 case OPERATOR_BITCLEAR:
5919 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5920 case OPERATOR_AND:
5921 break;
5922 default:
5923 go_unreachable();
5926 if (left_type->is_string_type())
5928 go_assert(this->op_ == OPERATOR_PLUS);
5929 Expression* string_plus =
5930 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5931 this->left_, this->right_);
5932 return string_plus->get_tree(context);
5935 // For complex division Go might want slightly different results than the
5936 // backend implementation provides, so we have our own runtime routine.
5937 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5939 Runtime::Function complex_code;
5940 switch (this->left_->type()->complex_type()->bits())
5942 case 64:
5943 complex_code = Runtime::COMPLEX64_DIV;
5944 break;
5945 case 128:
5946 complex_code = Runtime::COMPLEX128_DIV;
5947 break;
5948 default:
5949 go_unreachable();
5951 Expression* complex_div =
5952 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5953 return complex_div->get_tree(context);
5956 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
5957 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
5959 Type* type = use_left_type ? left_type : right_type;
5960 Btype* btype = type->get_backend(gogo);
5962 Bexpression* ret =
5963 gogo->backend()->binary_expression(this->op_, left, right, loc);
5964 ret = gogo->backend()->convert_expression(btype, ret, loc);
5966 // Initialize overflow constants.
5967 Bexpression* overflow;
5968 mpz_t zero;
5969 mpz_init_set_ui(zero, 0UL);
5970 mpz_t one;
5971 mpz_init_set_ui(one, 1UL);
5972 mpz_t neg_one;
5973 mpz_init_set_si(neg_one, -1);
5975 Btype* left_btype = left_type->get_backend(gogo);
5976 Btype* right_btype = right_type->get_backend(gogo);
5978 // In Go, a shift larger than the size of the type is well-defined.
5979 // This is not true in C, so we need to insert a conditional.
5980 if (is_shift_op)
5982 go_assert(left_type->integer_type() != NULL);
5984 mpz_t bitsval;
5985 int bits = left_type->integer_type()->bits();
5986 mpz_init_set_ui(bitsval, bits);
5987 Bexpression* bits_expr =
5988 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5989 Bexpression* compare =
5990 gogo->backend()->binary_expression(OPERATOR_LT,
5991 right, bits_expr, loc);
5993 Bexpression* zero_expr =
5994 gogo->backend()->integer_constant_expression(left_btype, zero);
5995 overflow = zero_expr;
5996 if (this->op_ == OPERATOR_RSHIFT
5997 && !left_type->integer_type()->is_unsigned())
5999 Bexpression* neg_expr =
6000 gogo->backend()->binary_expression(OPERATOR_LT, left,
6001 zero_expr, loc);
6002 Bexpression* neg_one_expr =
6003 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6004 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6005 neg_one_expr,
6006 zero_expr, loc);
6008 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6009 overflow, loc);
6010 mpz_clear(bitsval);
6013 // Add checks for division by zero and division overflow as needed.
6014 if (is_idiv_op)
6016 if (go_check_divide_zero)
6018 // right == 0
6019 Bexpression* zero_expr =
6020 gogo->backend()->integer_constant_expression(right_btype, zero);
6021 Bexpression* check =
6022 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6023 right, zero_expr, loc);
6025 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6026 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6027 Expression* crash = gogo->runtime_error(errcode, loc);
6028 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
6030 // right == 0 ? (__go_runtime_error(...), 0) : ret
6031 ret = gogo->backend()->conditional_expression(btype, check,
6032 crash_expr, ret, loc);
6035 if (go_check_divide_overflow)
6037 // right == -1
6038 // FIXME: It would be nice to say that this test is expected
6039 // to return false.
6041 Bexpression* neg_one_expr =
6042 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6043 Bexpression* check =
6044 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6045 right, neg_one_expr, loc);
6047 Bexpression* zero_expr =
6048 gogo->backend()->integer_constant_expression(btype, zero);
6049 Bexpression* one_expr =
6050 gogo->backend()->integer_constant_expression(btype, one);
6052 if (type->integer_type()->is_unsigned())
6054 // An unsigned -1 is the largest possible number, so
6055 // dividing is always 1 or 0.
6057 Bexpression* cmp =
6058 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6059 left, right, loc);
6060 if (this->op_ == OPERATOR_DIV)
6061 overflow =
6062 gogo->backend()->conditional_expression(btype, cmp,
6063 one_expr, zero_expr,
6064 loc);
6065 else
6066 overflow =
6067 gogo->backend()->conditional_expression(btype, cmp,
6068 zero_expr, left,
6069 loc);
6071 else
6073 // Computing left / -1 is the same as computing - left,
6074 // which does not overflow since Go sets -fwrapv.
6075 if (this->op_ == OPERATOR_DIV)
6077 Expression* negate_expr =
6078 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6079 overflow = tree_to_expr(negate_expr->get_tree(context));
6081 else
6082 overflow = zero_expr;
6084 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6086 // right == -1 ? - left : ret
6087 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6088 ret, loc);
6092 mpz_clear(zero);
6093 mpz_clear(one);
6094 mpz_clear(neg_one);
6095 return expr_to_tree(ret);
6098 // Export a binary expression.
6100 void
6101 Binary_expression::do_export(Export* exp) const
6103 exp->write_c_string("(");
6104 this->left_->export_expression(exp);
6105 switch (this->op_)
6107 case OPERATOR_OROR:
6108 exp->write_c_string(" || ");
6109 break;
6110 case OPERATOR_ANDAND:
6111 exp->write_c_string(" && ");
6112 break;
6113 case OPERATOR_EQEQ:
6114 exp->write_c_string(" == ");
6115 break;
6116 case OPERATOR_NOTEQ:
6117 exp->write_c_string(" != ");
6118 break;
6119 case OPERATOR_LT:
6120 exp->write_c_string(" < ");
6121 break;
6122 case OPERATOR_LE:
6123 exp->write_c_string(" <= ");
6124 break;
6125 case OPERATOR_GT:
6126 exp->write_c_string(" > ");
6127 break;
6128 case OPERATOR_GE:
6129 exp->write_c_string(" >= ");
6130 break;
6131 case OPERATOR_PLUS:
6132 exp->write_c_string(" + ");
6133 break;
6134 case OPERATOR_MINUS:
6135 exp->write_c_string(" - ");
6136 break;
6137 case OPERATOR_OR:
6138 exp->write_c_string(" | ");
6139 break;
6140 case OPERATOR_XOR:
6141 exp->write_c_string(" ^ ");
6142 break;
6143 case OPERATOR_MULT:
6144 exp->write_c_string(" * ");
6145 break;
6146 case OPERATOR_DIV:
6147 exp->write_c_string(" / ");
6148 break;
6149 case OPERATOR_MOD:
6150 exp->write_c_string(" % ");
6151 break;
6152 case OPERATOR_LSHIFT:
6153 exp->write_c_string(" << ");
6154 break;
6155 case OPERATOR_RSHIFT:
6156 exp->write_c_string(" >> ");
6157 break;
6158 case OPERATOR_AND:
6159 exp->write_c_string(" & ");
6160 break;
6161 case OPERATOR_BITCLEAR:
6162 exp->write_c_string(" &^ ");
6163 break;
6164 default:
6165 go_unreachable();
6167 this->right_->export_expression(exp);
6168 exp->write_c_string(")");
6171 // Import a binary expression.
6173 Expression*
6174 Binary_expression::do_import(Import* imp)
6176 imp->require_c_string("(");
6178 Expression* left = Expression::import_expression(imp);
6180 Operator op;
6181 if (imp->match_c_string(" || "))
6183 op = OPERATOR_OROR;
6184 imp->advance(4);
6186 else if (imp->match_c_string(" && "))
6188 op = OPERATOR_ANDAND;
6189 imp->advance(4);
6191 else if (imp->match_c_string(" == "))
6193 op = OPERATOR_EQEQ;
6194 imp->advance(4);
6196 else if (imp->match_c_string(" != "))
6198 op = OPERATOR_NOTEQ;
6199 imp->advance(4);
6201 else if (imp->match_c_string(" < "))
6203 op = OPERATOR_LT;
6204 imp->advance(3);
6206 else if (imp->match_c_string(" <= "))
6208 op = OPERATOR_LE;
6209 imp->advance(4);
6211 else if (imp->match_c_string(" > "))
6213 op = OPERATOR_GT;
6214 imp->advance(3);
6216 else if (imp->match_c_string(" >= "))
6218 op = OPERATOR_GE;
6219 imp->advance(4);
6221 else if (imp->match_c_string(" + "))
6223 op = OPERATOR_PLUS;
6224 imp->advance(3);
6226 else if (imp->match_c_string(" - "))
6228 op = OPERATOR_MINUS;
6229 imp->advance(3);
6231 else if (imp->match_c_string(" | "))
6233 op = OPERATOR_OR;
6234 imp->advance(3);
6236 else if (imp->match_c_string(" ^ "))
6238 op = OPERATOR_XOR;
6239 imp->advance(3);
6241 else if (imp->match_c_string(" * "))
6243 op = OPERATOR_MULT;
6244 imp->advance(3);
6246 else if (imp->match_c_string(" / "))
6248 op = OPERATOR_DIV;
6249 imp->advance(3);
6251 else if (imp->match_c_string(" % "))
6253 op = OPERATOR_MOD;
6254 imp->advance(3);
6256 else if (imp->match_c_string(" << "))
6258 op = OPERATOR_LSHIFT;
6259 imp->advance(4);
6261 else if (imp->match_c_string(" >> "))
6263 op = OPERATOR_RSHIFT;
6264 imp->advance(4);
6266 else if (imp->match_c_string(" & "))
6268 op = OPERATOR_AND;
6269 imp->advance(3);
6271 else if (imp->match_c_string(" &^ "))
6273 op = OPERATOR_BITCLEAR;
6274 imp->advance(4);
6276 else
6278 error_at(imp->location(), "unrecognized binary operator");
6279 return Expression::make_error(imp->location());
6282 Expression* right = Expression::import_expression(imp);
6284 imp->require_c_string(")");
6286 return Expression::make_binary(op, left, right, imp->location());
6289 // Dump ast representation of a binary expression.
6291 void
6292 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6294 ast_dump_context->ostream() << "(";
6295 ast_dump_context->dump_expression(this->left_);
6296 ast_dump_context->ostream() << " ";
6297 ast_dump_context->dump_operator(this->op_);
6298 ast_dump_context->ostream() << " ";
6299 ast_dump_context->dump_expression(this->right_);
6300 ast_dump_context->ostream() << ") ";
6303 // Make a binary expression.
6305 Expression*
6306 Expression::make_binary(Operator op, Expression* left, Expression* right,
6307 Location location)
6309 return new Binary_expression(op, left, right, location);
6312 // Implement a comparison.
6314 Bexpression*
6315 Expression::comparison(Translate_context* context, Type* result_type,
6316 Operator op, Expression* left, Expression* right,
6317 Location location)
6319 Type* left_type = left->type();
6320 Type* right_type = right->type();
6322 mpz_t zval;
6323 mpz_init_set_ui(zval, 0UL);
6324 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6325 mpz_clear(zval);
6327 if (left_type->is_string_type() && right_type->is_string_type())
6329 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6330 left, right);
6331 right = zexpr;
6333 else if ((left_type->interface_type() != NULL
6334 && right_type->interface_type() == NULL
6335 && !right_type->is_nil_type())
6336 || (left_type->interface_type() == NULL
6337 && !left_type->is_nil_type()
6338 && right_type->interface_type() != NULL))
6340 // Comparing an interface value to a non-interface value.
6341 if (left_type->interface_type() == NULL)
6343 std::swap(left_type, right_type);
6344 std::swap(left, right);
6347 // The right operand is not an interface. We need to take its
6348 // address if it is not a pointer.
6349 Expression* pointer_arg = NULL;
6350 if (right_type->points_to() != NULL)
6351 pointer_arg = right;
6352 else
6354 go_assert(right->is_addressable());
6355 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6356 location);
6359 Expression* descriptor =
6360 Expression::make_type_descriptor(right_type, location);
6361 left =
6362 Runtime::make_call((left_type->interface_type()->is_empty()
6363 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6364 : Runtime::INTERFACE_VALUE_COMPARE),
6365 location, 3, left, descriptor,
6366 pointer_arg);
6367 right = zexpr;
6369 else if (left_type->interface_type() != NULL
6370 && right_type->interface_type() != NULL)
6372 Runtime::Function compare_function;
6373 if (left_type->interface_type()->is_empty()
6374 && right_type->interface_type()->is_empty())
6375 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6376 else if (!left_type->interface_type()->is_empty()
6377 && !right_type->interface_type()->is_empty())
6378 compare_function = Runtime::INTERFACE_COMPARE;
6379 else
6381 if (left_type->interface_type()->is_empty())
6383 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6384 std::swap(left_type, right_type);
6385 std::swap(left, right);
6387 go_assert(!left_type->interface_type()->is_empty());
6388 go_assert(right_type->interface_type()->is_empty());
6389 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6392 left = Runtime::make_call(compare_function, location, 2, left, right);
6393 right = zexpr;
6396 if (left_type->is_nil_type()
6397 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6399 std::swap(left_type, right_type);
6400 std::swap(left, right);
6403 if (right_type->is_nil_type())
6405 right = Expression::make_nil(location);
6406 if (left_type->array_type() != NULL
6407 && left_type->array_type()->length() == NULL)
6409 Array_type* at = left_type->array_type();
6410 left = at->get_value_pointer(context->gogo(), left);
6412 else if (left_type->interface_type() != NULL)
6414 // An interface is nil if the first field is nil.
6415 left = Expression::make_field_reference(left, 0, location);
6419 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6420 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
6422 Gogo* gogo = context->gogo();
6423 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6424 right_bexpr, location);
6425 if (result_type != NULL)
6426 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6427 ret, location);
6428 return ret;
6431 // Class Bound_method_expression.
6433 // Traversal.
6436 Bound_method_expression::do_traverse(Traverse* traverse)
6438 return Expression::traverse(&this->expr_, traverse);
6441 // Lower the expression. If this is a method value rather than being
6442 // called, and the method is accessed via a pointer, we may need to
6443 // add nil checks. Introduce a temporary variable so that those nil
6444 // checks do not cause multiple evaluation.
6446 Expression*
6447 Bound_method_expression::do_lower(Gogo*, Named_object*,
6448 Statement_inserter* inserter, int)
6450 // For simplicity we use a temporary for every call to an embedded
6451 // method, even though some of them might be pure value methods and
6452 // not require a temporary.
6453 if (this->expr_->var_expression() == NULL
6454 && this->expr_->temporary_reference_expression() == NULL
6455 && this->expr_->set_and_use_temporary_expression() == NULL
6456 && (this->method_->field_indexes() != NULL
6457 || (this->method_->is_value_method()
6458 && this->expr_->type()->points_to() != NULL)))
6460 Temporary_statement* temp =
6461 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6462 inserter->insert(temp);
6463 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6464 this->location());
6466 return this;
6469 // Return the type of a bound method expression. The type of this
6470 // object is simply the type of the method with no receiver.
6472 Type*
6473 Bound_method_expression::do_type()
6475 Named_object* fn = this->method_->named_object();
6476 Function_type* fntype;
6477 if (fn->is_function())
6478 fntype = fn->func_value()->type();
6479 else if (fn->is_function_declaration())
6480 fntype = fn->func_declaration_value()->type();
6481 else
6482 return Type::make_error_type();
6483 return fntype->copy_without_receiver();
6486 // Determine the types of a method expression.
6488 void
6489 Bound_method_expression::do_determine_type(const Type_context*)
6491 Named_object* fn = this->method_->named_object();
6492 Function_type* fntype;
6493 if (fn->is_function())
6494 fntype = fn->func_value()->type();
6495 else if (fn->is_function_declaration())
6496 fntype = fn->func_declaration_value()->type();
6497 else
6498 fntype = NULL;
6499 if (fntype == NULL || !fntype->is_method())
6500 this->expr_->determine_type_no_context();
6501 else
6503 Type_context subcontext(fntype->receiver()->type(), false);
6504 this->expr_->determine_type(&subcontext);
6508 // Check the types of a method expression.
6510 void
6511 Bound_method_expression::do_check_types(Gogo*)
6513 Named_object* fn = this->method_->named_object();
6514 if (!fn->is_function() && !fn->is_function_declaration())
6516 this->report_error(_("object is not a method"));
6517 return;
6520 Function_type* fntype;
6521 if (fn->is_function())
6522 fntype = fn->func_value()->type();
6523 else if (fn->is_function_declaration())
6524 fntype = fn->func_declaration_value()->type();
6525 else
6526 go_unreachable();
6527 Type* rtype = fntype->receiver()->type()->deref();
6528 Type* etype = (this->expr_type_ != NULL
6529 ? this->expr_type_
6530 : this->expr_->type());
6531 etype = etype->deref();
6532 if (!Type::are_identical(rtype, etype, true, NULL))
6533 this->report_error(_("method type does not match object type"));
6536 // If a bound method expression is not simply called, then it is
6537 // represented as a closure. The closure will hold a single variable,
6538 // the receiver to pass to the method. The function will be a simple
6539 // thunk that pulls that value from the closure and calls the method
6540 // with the remaining arguments.
6542 // Because method values are not common, we don't build all thunks for
6543 // every methods, but instead only build them as we need them. In
6544 // particular, we even build them on demand for methods defined in
6545 // other packages.
6547 Bound_method_expression::Method_value_thunks
6548 Bound_method_expression::method_value_thunks;
6550 // Find or create the thunk for METHOD.
6552 Named_object*
6553 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6554 Named_object* fn)
6556 std::pair<Named_object*, Named_object*> val(fn, NULL);
6557 std::pair<Method_value_thunks::iterator, bool> ins =
6558 Bound_method_expression::method_value_thunks.insert(val);
6559 if (!ins.second)
6561 // We have seen this method before.
6562 go_assert(ins.first->second != NULL);
6563 return ins.first->second;
6566 Location loc = fn->location();
6568 Function_type* orig_fntype;
6569 if (fn->is_function())
6570 orig_fntype = fn->func_value()->type();
6571 else if (fn->is_function_declaration())
6572 orig_fntype = fn->func_declaration_value()->type();
6573 else
6574 orig_fntype = NULL;
6576 if (orig_fntype == NULL || !orig_fntype->is_method())
6578 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6579 return ins.first->second;
6582 Struct_field_list* sfl = new Struct_field_list();
6583 // The type here is wrong--it should be the C function type. But it
6584 // doesn't really matter.
6585 Type* vt = Type::make_pointer_type(Type::make_void_type());
6586 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6587 sfl->push_back(Struct_field(Typed_identifier("val.1",
6588 orig_fntype->receiver()->type(),
6589 loc)));
6590 Type* closure_type = Type::make_struct_type(sfl, loc);
6591 closure_type = Type::make_pointer_type(closure_type);
6593 Function_type* new_fntype = orig_fntype->copy_with_names();
6595 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6596 false, loc);
6598 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6599 cvar->set_is_used();
6600 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6601 new_no->func_value()->set_closure_var(cp);
6603 gogo->start_block(loc);
6605 // Field 0 of the closure is the function code pointer, field 1 is
6606 // the value on which to invoke the method.
6607 Expression* arg = Expression::make_var_reference(cp, loc);
6608 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6609 arg = Expression::make_field_reference(arg, 1, loc);
6611 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6613 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6614 Expression_list* args;
6615 if (orig_params == NULL || orig_params->empty())
6616 args = NULL;
6617 else
6619 const Typed_identifier_list* new_params = new_fntype->parameters();
6620 args = new Expression_list();
6621 for (Typed_identifier_list::const_iterator p = new_params->begin();
6622 p != new_params->end();
6623 ++p)
6625 Named_object* p_no = gogo->lookup(p->name(), NULL);
6626 go_assert(p_no != NULL
6627 && p_no->is_variable()
6628 && p_no->var_value()->is_parameter());
6629 args->push_back(Expression::make_var_reference(p_no, loc));
6633 Call_expression* call = Expression::make_call(bme, args,
6634 orig_fntype->is_varargs(),
6635 loc);
6636 call->set_varargs_are_lowered();
6638 Statement* s = Statement::make_return_from_call(call, loc);
6639 gogo->add_statement(s);
6640 Block* b = gogo->finish_block(loc);
6641 gogo->add_block(b, loc);
6642 gogo->lower_block(new_no, b);
6643 gogo->flatten_block(new_no, b);
6644 gogo->finish_function(loc);
6646 ins.first->second = new_no;
6647 return new_no;
6650 // Return an expression to check *REF for nil while dereferencing
6651 // according to FIELD_INDEXES. Update *REF to build up the field
6652 // reference. This is a static function so that we don't have to
6653 // worry about declaring Field_indexes in expressions.h.
6655 static Expression*
6656 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6657 Expression** ref)
6659 if (field_indexes == NULL)
6660 return Expression::make_boolean(false, loc);
6661 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6662 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6663 go_assert(stype != NULL
6664 && field_indexes->field_index < stype->field_count());
6665 if ((*ref)->type()->struct_type() == NULL)
6667 go_assert((*ref)->type()->points_to() != NULL);
6668 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6669 Expression::make_nil(loc),
6670 loc);
6671 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6672 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6673 go_assert((*ref)->type()->struct_type() == stype);
6675 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6676 loc);
6677 return cond;
6680 // Get the tree for a method value.
6682 tree
6683 Bound_method_expression::do_get_tree(Translate_context* context)
6685 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6686 this->method_,
6687 this->function_);
6688 if (thunk->is_erroneous())
6690 go_assert(saw_errors());
6691 return error_mark_node;
6694 // FIXME: We should lower this earlier, but we can't lower it in the
6695 // lowering pass because at that point we don't know whether we need
6696 // to create the thunk or not. If the expression is called, we
6697 // don't need the thunk.
6699 Location loc = this->location();
6701 // If the method expects a value, and we have a pointer, we need to
6702 // dereference the pointer.
6704 Named_object* fn = this->method_->named_object();
6705 Function_type* fntype;
6706 if (fn->is_function())
6707 fntype = fn->func_value()->type();
6708 else if (fn->is_function_declaration())
6709 fntype = fn->func_declaration_value()->type();
6710 else
6711 go_unreachable();
6713 Expression* val = this->expr_;
6714 if (fntype->receiver()->type()->points_to() == NULL
6715 && val->type()->points_to() != NULL)
6716 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6718 // Note that we are ignoring this->expr_type_ here. The thunk will
6719 // expect a closure whose second field has type this->expr_type_ (if
6720 // that is not NULL). We are going to pass it a closure whose
6721 // second field has type this->expr_->type(). Since
6722 // this->expr_type_ is only not-NULL for pointer types, we can get
6723 // away with this.
6725 Struct_field_list* fields = new Struct_field_list();
6726 fields->push_back(Struct_field(Typed_identifier("fn.0",
6727 thunk->func_value()->type(),
6728 loc)));
6729 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6730 Struct_type* st = Type::make_struct_type(fields, loc);
6732 Expression_list* vals = new Expression_list();
6733 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6734 vals->push_back(val);
6736 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6737 ret = Expression::make_heap_expression(ret, loc);
6739 // See whether the expression or any embedded pointers are nil.
6741 Expression* nil_check = NULL;
6742 Expression* expr = this->expr_;
6743 if (this->method_->field_indexes() != NULL)
6745 // Note that we are evaluating this->expr_ twice, but that is OK
6746 // because in the lowering pass we forced it into a temporary
6747 // variable.
6748 Expression* ref = expr;
6749 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6750 expr = ref;
6753 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6755 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6756 Expression::make_nil(loc),
6757 loc);
6758 if (nil_check == NULL)
6759 nil_check = n;
6760 else
6761 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6764 Bexpression* bme = tree_to_expr(ret->get_tree(context));
6765 if (nil_check != NULL)
6767 Gogo* gogo = context->gogo();
6768 Expression* crash =
6769 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
6770 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
6771 Btype* btype = ret->type()->get_backend(gogo);
6772 Bexpression* bcheck = tree_to_expr(nil_check->get_tree(context));
6773 bme = gogo->backend()->conditional_expression(btype, bcheck, bcrash,
6774 bme, loc);
6776 return expr_to_tree(bme);
6779 // Dump ast representation of a bound method expression.
6781 void
6782 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6783 const
6785 if (this->expr_type_ != NULL)
6786 ast_dump_context->ostream() << "(";
6787 ast_dump_context->dump_expression(this->expr_);
6788 if (this->expr_type_ != NULL)
6790 ast_dump_context->ostream() << ":";
6791 ast_dump_context->dump_type(this->expr_type_);
6792 ast_dump_context->ostream() << ")";
6795 ast_dump_context->ostream() << "." << this->function_->name();
6798 // Make a method expression.
6800 Bound_method_expression*
6801 Expression::make_bound_method(Expression* expr, const Method* method,
6802 Named_object* function, Location location)
6804 return new Bound_method_expression(expr, method, function, location);
6807 // Class Builtin_call_expression. This is used for a call to a
6808 // builtin function.
6810 class Builtin_call_expression : public Call_expression
6812 public:
6813 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6814 bool is_varargs, Location location);
6816 protected:
6817 // This overrides Call_expression::do_lower.
6818 Expression*
6819 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6821 Expression*
6822 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6824 bool
6825 do_is_constant() const;
6827 bool
6828 do_numeric_constant_value(Numeric_constant*) const;
6830 bool
6831 do_discarding_value();
6833 Type*
6834 do_type();
6836 void
6837 do_determine_type(const Type_context*);
6839 void
6840 do_check_types(Gogo*);
6842 Expression*
6843 do_copy()
6845 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6846 this->args()->copy(),
6847 this->is_varargs(),
6848 this->location());
6851 tree
6852 do_get_tree(Translate_context*);
6854 void
6855 do_export(Export*) const;
6857 virtual bool
6858 do_is_recover_call() const;
6860 virtual void
6861 do_set_recover_arg(Expression*);
6863 private:
6864 // The builtin functions.
6865 enum Builtin_function_code
6867 BUILTIN_INVALID,
6869 // Predeclared builtin functions.
6870 BUILTIN_APPEND,
6871 BUILTIN_CAP,
6872 BUILTIN_CLOSE,
6873 BUILTIN_COMPLEX,
6874 BUILTIN_COPY,
6875 BUILTIN_DELETE,
6876 BUILTIN_IMAG,
6877 BUILTIN_LEN,
6878 BUILTIN_MAKE,
6879 BUILTIN_NEW,
6880 BUILTIN_PANIC,
6881 BUILTIN_PRINT,
6882 BUILTIN_PRINTLN,
6883 BUILTIN_REAL,
6884 BUILTIN_RECOVER,
6886 // Builtin functions from the unsafe package.
6887 BUILTIN_ALIGNOF,
6888 BUILTIN_OFFSETOF,
6889 BUILTIN_SIZEOF
6892 Expression*
6893 one_arg() const;
6895 bool
6896 check_one_arg();
6898 static Type*
6899 real_imag_type(Type*);
6901 static Type*
6902 complex_type(Type*);
6904 Expression*
6905 lower_make();
6907 bool
6908 check_int_value(Expression*, bool is_length);
6910 // A pointer back to the general IR structure. This avoids a global
6911 // variable, or passing it around everywhere.
6912 Gogo* gogo_;
6913 // The builtin function being called.
6914 Builtin_function_code code_;
6915 // Used to stop endless loops when the length of an array uses len
6916 // or cap of the array itself.
6917 mutable bool seen_;
6920 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6921 Expression* fn,
6922 Expression_list* args,
6923 bool is_varargs,
6924 Location location)
6925 : Call_expression(fn, args, is_varargs, location),
6926 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6928 Func_expression* fnexp = this->fn()->func_expression();
6929 go_assert(fnexp != NULL);
6930 const std::string& name(fnexp->named_object()->name());
6931 if (name == "append")
6932 this->code_ = BUILTIN_APPEND;
6933 else if (name == "cap")
6934 this->code_ = BUILTIN_CAP;
6935 else if (name == "close")
6936 this->code_ = BUILTIN_CLOSE;
6937 else if (name == "complex")
6938 this->code_ = BUILTIN_COMPLEX;
6939 else if (name == "copy")
6940 this->code_ = BUILTIN_COPY;
6941 else if (name == "delete")
6942 this->code_ = BUILTIN_DELETE;
6943 else if (name == "imag")
6944 this->code_ = BUILTIN_IMAG;
6945 else if (name == "len")
6946 this->code_ = BUILTIN_LEN;
6947 else if (name == "make")
6948 this->code_ = BUILTIN_MAKE;
6949 else if (name == "new")
6950 this->code_ = BUILTIN_NEW;
6951 else if (name == "panic")
6952 this->code_ = BUILTIN_PANIC;
6953 else if (name == "print")
6954 this->code_ = BUILTIN_PRINT;
6955 else if (name == "println")
6956 this->code_ = BUILTIN_PRINTLN;
6957 else if (name == "real")
6958 this->code_ = BUILTIN_REAL;
6959 else if (name == "recover")
6960 this->code_ = BUILTIN_RECOVER;
6961 else if (name == "Alignof")
6962 this->code_ = BUILTIN_ALIGNOF;
6963 else if (name == "Offsetof")
6964 this->code_ = BUILTIN_OFFSETOF;
6965 else if (name == "Sizeof")
6966 this->code_ = BUILTIN_SIZEOF;
6967 else
6968 go_unreachable();
6971 // Return whether this is a call to recover. This is a virtual
6972 // function called from the parent class.
6974 bool
6975 Builtin_call_expression::do_is_recover_call() const
6977 if (this->classification() == EXPRESSION_ERROR)
6978 return false;
6979 return this->code_ == BUILTIN_RECOVER;
6982 // Set the argument for a call to recover.
6984 void
6985 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6987 const Expression_list* args = this->args();
6988 go_assert(args == NULL || args->empty());
6989 Expression_list* new_args = new Expression_list();
6990 new_args->push_back(arg);
6991 this->set_args(new_args);
6994 // Lower a builtin call expression. This turns new and make into
6995 // specific expressions. We also convert to a constant if we can.
6997 Expression*
6998 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6999 Statement_inserter* inserter, int)
7001 if (this->classification() == EXPRESSION_ERROR)
7002 return this;
7004 Location loc = this->location();
7006 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7008 this->report_error(_("invalid use of %<...%> with builtin function"));
7009 return Expression::make_error(loc);
7012 if (this->code_ == BUILTIN_OFFSETOF)
7014 Expression* arg = this->one_arg();
7016 if (arg->bound_method_expression() != NULL
7017 || arg->interface_field_reference_expression() != NULL)
7019 this->report_error(_("invalid use of method value as argument "
7020 "of Offsetof"));
7021 return this;
7024 Field_reference_expression* farg = arg->field_reference_expression();
7025 while (farg != NULL)
7027 if (!farg->implicit())
7028 break;
7029 // When the selector refers to an embedded field,
7030 // it must not be reached through pointer indirections.
7031 if (farg->expr()->deref() != farg->expr())
7033 this->report_error(_("argument of Offsetof implies "
7034 "indirection of an embedded field"));
7035 return this;
7037 // Go up until we reach the original base.
7038 farg = farg->expr()->field_reference_expression();
7042 if (this->is_constant())
7044 Numeric_constant nc;
7045 if (this->numeric_constant_value(&nc))
7046 return nc.expression(loc);
7049 switch (this->code_)
7051 default:
7052 break;
7054 case BUILTIN_NEW:
7056 const Expression_list* args = this->args();
7057 if (args == NULL || args->size() < 1)
7058 this->report_error(_("not enough arguments"));
7059 else if (args->size() > 1)
7060 this->report_error(_("too many arguments"));
7061 else
7063 Expression* arg = args->front();
7064 if (!arg->is_type_expression())
7066 error_at(arg->location(), "expected type");
7067 this->set_is_error();
7069 else
7070 return Expression::make_allocation(arg->type(), loc);
7073 break;
7075 case BUILTIN_MAKE:
7076 return this->lower_make();
7078 case BUILTIN_RECOVER:
7079 if (function != NULL)
7080 function->func_value()->set_calls_recover();
7081 else
7083 // Calling recover outside of a function always returns the
7084 // nil empty interface.
7085 Type* eface = Type::make_empty_interface_type(loc);
7086 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7088 break;
7090 case BUILTIN_APPEND:
7092 // Lower the varargs.
7093 const Expression_list* args = this->args();
7094 if (args == NULL || args->empty())
7095 return this;
7096 Type* slice_type = args->front()->type();
7097 if (!slice_type->is_slice_type())
7099 if (slice_type->is_nil_type())
7100 error_at(args->front()->location(), "use of untyped nil");
7101 else
7102 error_at(args->front()->location(),
7103 "argument 1 must be a slice");
7104 this->set_is_error();
7105 return this;
7107 Type* element_type = slice_type->array_type()->element_type();
7108 this->lower_varargs(gogo, function, inserter,
7109 Type::make_array_type(element_type, NULL),
7112 break;
7114 case BUILTIN_DELETE:
7116 // Lower to a runtime function call.
7117 const Expression_list* args = this->args();
7118 if (args == NULL || args->size() < 2)
7119 this->report_error(_("not enough arguments"));
7120 else if (args->size() > 2)
7121 this->report_error(_("too many arguments"));
7122 else if (args->front()->type()->map_type() == NULL)
7123 this->report_error(_("argument 1 must be a map"));
7124 else
7126 // Since this function returns no value it must appear in
7127 // a statement by itself, so we don't have to worry about
7128 // order of evaluation of values around it. Evaluate the
7129 // map first to get order of evaluation right.
7130 Map_type* mt = args->front()->type()->map_type();
7131 Temporary_statement* map_temp =
7132 Statement::make_temporary(mt, args->front(), loc);
7133 inserter->insert(map_temp);
7135 Temporary_statement* key_temp =
7136 Statement::make_temporary(mt->key_type(), args->back(), loc);
7137 inserter->insert(key_temp);
7139 Expression* e1 = Expression::make_temporary_reference(map_temp,
7140 loc);
7141 Expression* e2 = Expression::make_temporary_reference(key_temp,
7142 loc);
7143 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7144 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7145 2, e1, e2);
7148 break;
7151 return this;
7154 // Flatten a builtin call expression. This turns the arguments of copy and
7155 // append into temporary expressions.
7157 Expression*
7158 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7159 Statement_inserter* inserter)
7161 if (this->code_ == BUILTIN_APPEND
7162 || this->code_ == BUILTIN_COPY)
7164 Location loc = this->location();
7165 Type* at = this->args()->front()->type();
7166 for (Expression_list::iterator pa = this->args()->begin();
7167 pa != this->args()->end();
7168 ++pa)
7170 if ((*pa)->is_nil_expression())
7171 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7172 if (!(*pa)->is_variable())
7174 Temporary_statement* temp =
7175 Statement::make_temporary(NULL, *pa, loc);
7176 inserter->insert(temp);
7177 *pa = Expression::make_temporary_reference(temp, loc);
7181 return this;
7184 // Lower a make expression.
7186 Expression*
7187 Builtin_call_expression::lower_make()
7189 Location loc = this->location();
7191 const Expression_list* args = this->args();
7192 if (args == NULL || args->size() < 1)
7194 this->report_error(_("not enough arguments"));
7195 return Expression::make_error(this->location());
7198 Expression_list::const_iterator parg = args->begin();
7200 Expression* first_arg = *parg;
7201 if (!first_arg->is_type_expression())
7203 error_at(first_arg->location(), "expected type");
7204 this->set_is_error();
7205 return Expression::make_error(this->location());
7207 Type* type = first_arg->type();
7209 bool is_slice = false;
7210 bool is_map = false;
7211 bool is_chan = false;
7212 if (type->is_slice_type())
7213 is_slice = true;
7214 else if (type->map_type() != NULL)
7215 is_map = true;
7216 else if (type->channel_type() != NULL)
7217 is_chan = true;
7218 else
7220 this->report_error(_("invalid type for make function"));
7221 return Expression::make_error(this->location());
7224 bool have_big_args = false;
7225 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7226 int uintptr_bits = uintptr_type->integer_type()->bits();
7228 Type_context int_context(Type::lookup_integer_type("int"), false);
7230 ++parg;
7231 Expression* len_arg;
7232 if (parg == args->end())
7234 if (is_slice)
7236 this->report_error(_("length required when allocating a slice"));
7237 return Expression::make_error(this->location());
7240 mpz_t zval;
7241 mpz_init_set_ui(zval, 0);
7242 len_arg = Expression::make_integer(&zval, NULL, loc);
7243 mpz_clear(zval);
7245 else
7247 len_arg = *parg;
7248 len_arg->determine_type(&int_context);
7249 if (!this->check_int_value(len_arg, true))
7250 return Expression::make_error(this->location());
7251 if (len_arg->type()->integer_type() != NULL
7252 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7253 have_big_args = true;
7254 ++parg;
7257 Expression* cap_arg = NULL;
7258 if (is_slice && parg != args->end())
7260 cap_arg = *parg;
7261 cap_arg->determine_type(&int_context);
7262 if (!this->check_int_value(cap_arg, false))
7263 return Expression::make_error(this->location());
7265 Numeric_constant nclen;
7266 Numeric_constant nccap;
7267 unsigned long vlen;
7268 unsigned long vcap;
7269 if (len_arg->numeric_constant_value(&nclen)
7270 && cap_arg->numeric_constant_value(&nccap)
7271 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7272 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7273 && vlen > vcap)
7275 this->report_error(_("len larger than cap"));
7276 return Expression::make_error(this->location());
7279 if (cap_arg->type()->integer_type() != NULL
7280 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7281 have_big_args = true;
7282 ++parg;
7285 if (parg != args->end())
7287 this->report_error(_("too many arguments to make"));
7288 return Expression::make_error(this->location());
7291 Location type_loc = first_arg->location();
7292 Expression* type_arg;
7293 if (is_slice || is_chan)
7294 type_arg = Expression::make_type_descriptor(type, type_loc);
7295 else if (is_map)
7296 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7297 else
7298 go_unreachable();
7300 Expression* call;
7301 if (is_slice)
7303 if (cap_arg == NULL)
7304 call = Runtime::make_call((have_big_args
7305 ? Runtime::MAKESLICE1BIG
7306 : Runtime::MAKESLICE1),
7307 loc, 2, type_arg, len_arg);
7308 else
7309 call = Runtime::make_call((have_big_args
7310 ? Runtime::MAKESLICE2BIG
7311 : Runtime::MAKESLICE2),
7312 loc, 3, type_arg, len_arg, cap_arg);
7314 else if (is_map)
7315 call = Runtime::make_call((have_big_args
7316 ? Runtime::MAKEMAPBIG
7317 : Runtime::MAKEMAP),
7318 loc, 2, type_arg, len_arg);
7319 else if (is_chan)
7320 call = Runtime::make_call((have_big_args
7321 ? Runtime::MAKECHANBIG
7322 : Runtime::MAKECHAN),
7323 loc, 2, type_arg, len_arg);
7324 else
7325 go_unreachable();
7327 return Expression::make_unsafe_cast(type, call, loc);
7330 // Return whether an expression has an integer value. Report an error
7331 // if not. This is used when handling calls to the predeclared make
7332 // function.
7334 bool
7335 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7337 Numeric_constant nc;
7338 if (e->numeric_constant_value(&nc))
7340 unsigned long v;
7341 switch (nc.to_unsigned_long(&v))
7343 case Numeric_constant::NC_UL_VALID:
7344 break;
7345 case Numeric_constant::NC_UL_NOTINT:
7346 error_at(e->location(), "non-integer %s argument to make",
7347 is_length ? "len" : "cap");
7348 return false;
7349 case Numeric_constant::NC_UL_NEGATIVE:
7350 error_at(e->location(), "negative %s argument to make",
7351 is_length ? "len" : "cap");
7352 return false;
7353 case Numeric_constant::NC_UL_BIG:
7354 // We don't want to give a compile-time error for a 64-bit
7355 // value on a 32-bit target.
7356 break;
7359 mpz_t val;
7360 if (!nc.to_int(&val))
7361 go_unreachable();
7362 int bits = mpz_sizeinbase(val, 2);
7363 mpz_clear(val);
7364 Type* int_type = Type::lookup_integer_type("int");
7365 if (bits >= int_type->integer_type()->bits())
7367 error_at(e->location(), "%s argument too large for make",
7368 is_length ? "len" : "cap");
7369 return false;
7372 return true;
7375 if (e->type()->integer_type() != NULL)
7376 return true;
7378 error_at(e->location(), "non-integer %s argument to make",
7379 is_length ? "len" : "cap");
7380 return false;
7383 // Return the type of the real or imag functions, given the type of
7384 // the argument. We need to map complex to float, complex64 to
7385 // float32, and complex128 to float64, so it has to be done by name.
7386 // This returns NULL if it can't figure out the type.
7388 Type*
7389 Builtin_call_expression::real_imag_type(Type* arg_type)
7391 if (arg_type == NULL || arg_type->is_abstract())
7392 return NULL;
7393 Named_type* nt = arg_type->named_type();
7394 if (nt == NULL)
7395 return NULL;
7396 while (nt->real_type()->named_type() != NULL)
7397 nt = nt->real_type()->named_type();
7398 if (nt->name() == "complex64")
7399 return Type::lookup_float_type("float32");
7400 else if (nt->name() == "complex128")
7401 return Type::lookup_float_type("float64");
7402 else
7403 return NULL;
7406 // Return the type of the complex function, given the type of one of the
7407 // argments. Like real_imag_type, we have to map by name.
7409 Type*
7410 Builtin_call_expression::complex_type(Type* arg_type)
7412 if (arg_type == NULL || arg_type->is_abstract())
7413 return NULL;
7414 Named_type* nt = arg_type->named_type();
7415 if (nt == NULL)
7416 return NULL;
7417 while (nt->real_type()->named_type() != NULL)
7418 nt = nt->real_type()->named_type();
7419 if (nt->name() == "float32")
7420 return Type::lookup_complex_type("complex64");
7421 else if (nt->name() == "float64")
7422 return Type::lookup_complex_type("complex128");
7423 else
7424 return NULL;
7427 // Return a single argument, or NULL if there isn't one.
7429 Expression*
7430 Builtin_call_expression::one_arg() const
7432 const Expression_list* args = this->args();
7433 if (args == NULL || args->size() != 1)
7434 return NULL;
7435 return args->front();
7438 // A traversal class which looks for a call or receive expression.
7440 class Find_call_expression : public Traverse
7442 public:
7443 Find_call_expression()
7444 : Traverse(traverse_expressions),
7445 found_(false)
7449 expression(Expression**);
7451 bool
7452 found()
7453 { return this->found_; }
7455 private:
7456 bool found_;
7460 Find_call_expression::expression(Expression** pexpr)
7462 if ((*pexpr)->call_expression() != NULL
7463 || (*pexpr)->receive_expression() != NULL)
7465 this->found_ = true;
7466 return TRAVERSE_EXIT;
7468 return TRAVERSE_CONTINUE;
7471 // Return whether this is constant: len of a string constant, or len
7472 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7473 // unsafe.Alignof.
7475 bool
7476 Builtin_call_expression::do_is_constant() const
7478 if (this->is_error_expression())
7479 return true;
7480 switch (this->code_)
7482 case BUILTIN_LEN:
7483 case BUILTIN_CAP:
7485 if (this->seen_)
7486 return false;
7488 Expression* arg = this->one_arg();
7489 if (arg == NULL)
7490 return false;
7491 Type* arg_type = arg->type();
7493 if (arg_type->points_to() != NULL
7494 && arg_type->points_to()->array_type() != NULL
7495 && !arg_type->points_to()->is_slice_type())
7496 arg_type = arg_type->points_to();
7498 // The len and cap functions are only constant if there are no
7499 // function calls or channel operations in the arguments.
7500 // Otherwise we have to make the call.
7501 if (!arg->is_constant())
7503 Find_call_expression find_call;
7504 Expression::traverse(&arg, &find_call);
7505 if (find_call.found())
7506 return false;
7509 if (arg_type->array_type() != NULL
7510 && arg_type->array_type()->length() != NULL)
7511 return true;
7513 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7515 this->seen_ = true;
7516 bool ret = arg->is_constant();
7517 this->seen_ = false;
7518 return ret;
7521 break;
7523 case BUILTIN_SIZEOF:
7524 case BUILTIN_ALIGNOF:
7525 return this->one_arg() != NULL;
7527 case BUILTIN_OFFSETOF:
7529 Expression* arg = this->one_arg();
7530 if (arg == NULL)
7531 return false;
7532 return arg->field_reference_expression() != NULL;
7535 case BUILTIN_COMPLEX:
7537 const Expression_list* args = this->args();
7538 if (args != NULL && args->size() == 2)
7539 return args->front()->is_constant() && args->back()->is_constant();
7541 break;
7543 case BUILTIN_REAL:
7544 case BUILTIN_IMAG:
7546 Expression* arg = this->one_arg();
7547 return arg != NULL && arg->is_constant();
7550 default:
7551 break;
7554 return false;
7557 // Return a numeric constant if possible.
7559 bool
7560 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7562 if (this->code_ == BUILTIN_LEN
7563 || this->code_ == BUILTIN_CAP)
7565 Expression* arg = this->one_arg();
7566 if (arg == NULL)
7567 return false;
7568 Type* arg_type = arg->type();
7570 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7572 std::string sval;
7573 if (arg->string_constant_value(&sval))
7575 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7576 sval.length());
7577 return true;
7581 if (arg_type->points_to() != NULL
7582 && arg_type->points_to()->array_type() != NULL
7583 && !arg_type->points_to()->is_slice_type())
7584 arg_type = arg_type->points_to();
7586 if (arg_type->array_type() != NULL
7587 && arg_type->array_type()->length() != NULL)
7589 if (this->seen_)
7590 return false;
7591 Expression* e = arg_type->array_type()->length();
7592 this->seen_ = true;
7593 bool r = e->numeric_constant_value(nc);
7594 this->seen_ = false;
7595 if (r)
7597 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7598 this->location()))
7599 r = false;
7601 return r;
7604 else if (this->code_ == BUILTIN_SIZEOF
7605 || this->code_ == BUILTIN_ALIGNOF)
7607 Expression* arg = this->one_arg();
7608 if (arg == NULL)
7609 return false;
7610 Type* arg_type = arg->type();
7611 if (arg_type->is_error())
7612 return false;
7613 if (arg_type->is_abstract())
7614 return false;
7615 if (this->seen_)
7616 return false;
7618 unsigned int ret;
7619 if (this->code_ == BUILTIN_SIZEOF)
7621 this->seen_ = true;
7622 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7623 this->seen_ = false;
7624 if (!ok)
7625 return false;
7627 else if (this->code_ == BUILTIN_ALIGNOF)
7629 bool ok;
7630 this->seen_ = true;
7631 if (arg->field_reference_expression() == NULL)
7632 ok = arg_type->backend_type_align(this->gogo_, &ret);
7633 else
7635 // Calling unsafe.Alignof(s.f) returns the alignment of
7636 // the type of f when it is used as a field in a struct.
7637 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7639 this->seen_ = false;
7640 if (!ok)
7641 return false;
7643 else
7644 go_unreachable();
7646 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7647 static_cast<unsigned long>(ret));
7648 return true;
7650 else if (this->code_ == BUILTIN_OFFSETOF)
7652 Expression* arg = this->one_arg();
7653 if (arg == NULL)
7654 return false;
7655 Field_reference_expression* farg = arg->field_reference_expression();
7656 if (farg == NULL)
7657 return false;
7658 if (this->seen_)
7659 return false;
7661 unsigned int total_offset = 0;
7662 while (true)
7664 Expression* struct_expr = farg->expr();
7665 Type* st = struct_expr->type();
7666 if (st->struct_type() == NULL)
7667 return false;
7668 if (st->named_type() != NULL)
7669 st->named_type()->convert(this->gogo_);
7670 unsigned int offset;
7671 this->seen_ = true;
7672 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7673 farg->field_index(),
7674 &offset);
7675 this->seen_ = false;
7676 if (!ok)
7677 return false;
7678 total_offset += offset;
7679 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7681 // Go up until we reach the original base.
7682 farg = struct_expr->field_reference_expression();
7683 continue;
7685 break;
7687 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7688 static_cast<unsigned long>(total_offset));
7689 return true;
7691 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7693 Expression* arg = this->one_arg();
7694 if (arg == NULL)
7695 return false;
7697 Numeric_constant argnc;
7698 if (!arg->numeric_constant_value(&argnc))
7699 return false;
7701 mpfr_t real;
7702 mpfr_t imag;
7703 if (!argnc.to_complex(&real, &imag))
7704 return false;
7706 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7707 if (this->code_ == BUILTIN_REAL)
7708 nc->set_float(type, real);
7709 else
7710 nc->set_float(type, imag);
7711 return true;
7713 else if (this->code_ == BUILTIN_COMPLEX)
7715 const Expression_list* args = this->args();
7716 if (args == NULL || args->size() != 2)
7717 return false;
7719 Numeric_constant rnc;
7720 if (!args->front()->numeric_constant_value(&rnc))
7721 return false;
7722 Numeric_constant inc;
7723 if (!args->back()->numeric_constant_value(&inc))
7724 return false;
7726 if (rnc.type() != NULL
7727 && !rnc.type()->is_abstract()
7728 && inc.type() != NULL
7729 && !inc.type()->is_abstract()
7730 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7731 return false;
7733 mpfr_t r;
7734 if (!rnc.to_float(&r))
7735 return false;
7736 mpfr_t i;
7737 if (!inc.to_float(&i))
7739 mpfr_clear(r);
7740 return false;
7743 Type* arg_type = rnc.type();
7744 if (arg_type == NULL || arg_type->is_abstract())
7745 arg_type = inc.type();
7747 Type* type = Builtin_call_expression::complex_type(arg_type);
7748 nc->set_complex(type, r, i);
7750 mpfr_clear(r);
7751 mpfr_clear(i);
7753 return true;
7756 return false;
7759 // Give an error if we are discarding the value of an expression which
7760 // should not normally be discarded. We don't give an error for
7761 // discarding the value of an ordinary function call, but we do for
7762 // builtin functions, purely for consistency with the gc compiler.
7764 bool
7765 Builtin_call_expression::do_discarding_value()
7767 switch (this->code_)
7769 case BUILTIN_INVALID:
7770 default:
7771 go_unreachable();
7773 case BUILTIN_APPEND:
7774 case BUILTIN_CAP:
7775 case BUILTIN_COMPLEX:
7776 case BUILTIN_IMAG:
7777 case BUILTIN_LEN:
7778 case BUILTIN_MAKE:
7779 case BUILTIN_NEW:
7780 case BUILTIN_REAL:
7781 case BUILTIN_ALIGNOF:
7782 case BUILTIN_OFFSETOF:
7783 case BUILTIN_SIZEOF:
7784 this->unused_value_error();
7785 return false;
7787 case BUILTIN_CLOSE:
7788 case BUILTIN_COPY:
7789 case BUILTIN_DELETE:
7790 case BUILTIN_PANIC:
7791 case BUILTIN_PRINT:
7792 case BUILTIN_PRINTLN:
7793 case BUILTIN_RECOVER:
7794 return true;
7798 // Return the type.
7800 Type*
7801 Builtin_call_expression::do_type()
7803 switch (this->code_)
7805 case BUILTIN_INVALID:
7806 default:
7807 go_unreachable();
7809 case BUILTIN_NEW:
7810 case BUILTIN_MAKE:
7812 const Expression_list* args = this->args();
7813 if (args == NULL || args->empty())
7814 return Type::make_error_type();
7815 return Type::make_pointer_type(args->front()->type());
7818 case BUILTIN_CAP:
7819 case BUILTIN_COPY:
7820 case BUILTIN_LEN:
7821 return Type::lookup_integer_type("int");
7823 case BUILTIN_ALIGNOF:
7824 case BUILTIN_OFFSETOF:
7825 case BUILTIN_SIZEOF:
7826 return Type::lookup_integer_type("uintptr");
7828 case BUILTIN_CLOSE:
7829 case BUILTIN_DELETE:
7830 case BUILTIN_PANIC:
7831 case BUILTIN_PRINT:
7832 case BUILTIN_PRINTLN:
7833 return Type::make_void_type();
7835 case BUILTIN_RECOVER:
7836 return Type::make_empty_interface_type(Linemap::predeclared_location());
7838 case BUILTIN_APPEND:
7840 const Expression_list* args = this->args();
7841 if (args == NULL || args->empty())
7842 return Type::make_error_type();
7843 Type *ret = args->front()->type();
7844 if (!ret->is_slice_type())
7845 return Type::make_error_type();
7846 return ret;
7849 case BUILTIN_REAL:
7850 case BUILTIN_IMAG:
7852 Expression* arg = this->one_arg();
7853 if (arg == NULL)
7854 return Type::make_error_type();
7855 Type* t = arg->type();
7856 if (t->is_abstract())
7857 t = t->make_non_abstract_type();
7858 t = Builtin_call_expression::real_imag_type(t);
7859 if (t == NULL)
7860 t = Type::make_error_type();
7861 return t;
7864 case BUILTIN_COMPLEX:
7866 const Expression_list* args = this->args();
7867 if (args == NULL || args->size() != 2)
7868 return Type::make_error_type();
7869 Type* t = args->front()->type();
7870 if (t->is_abstract())
7872 t = args->back()->type();
7873 if (t->is_abstract())
7874 t = t->make_non_abstract_type();
7876 t = Builtin_call_expression::complex_type(t);
7877 if (t == NULL)
7878 t = Type::make_error_type();
7879 return t;
7884 // Determine the type.
7886 void
7887 Builtin_call_expression::do_determine_type(const Type_context* context)
7889 if (!this->determining_types())
7890 return;
7892 this->fn()->determine_type_no_context();
7894 const Expression_list* args = this->args();
7896 bool is_print;
7897 Type* arg_type = NULL;
7898 switch (this->code_)
7900 case BUILTIN_PRINT:
7901 case BUILTIN_PRINTLN:
7902 // Do not force a large integer constant to "int".
7903 is_print = true;
7904 break;
7906 case BUILTIN_REAL:
7907 case BUILTIN_IMAG:
7908 arg_type = Builtin_call_expression::complex_type(context->type);
7909 if (arg_type == NULL)
7910 arg_type = Type::lookup_complex_type("complex128");
7911 is_print = false;
7912 break;
7914 case BUILTIN_COMPLEX:
7916 // For the complex function the type of one operand can
7917 // determine the type of the other, as in a binary expression.
7918 arg_type = Builtin_call_expression::real_imag_type(context->type);
7919 if (arg_type == NULL)
7920 arg_type = Type::lookup_float_type("float64");
7921 if (args != NULL && args->size() == 2)
7923 Type* t1 = args->front()->type();
7924 Type* t2 = args->back()->type();
7925 if (!t1->is_abstract())
7926 arg_type = t1;
7927 else if (!t2->is_abstract())
7928 arg_type = t2;
7930 is_print = false;
7932 break;
7934 default:
7935 is_print = false;
7936 break;
7939 if (args != NULL)
7941 for (Expression_list::const_iterator pa = args->begin();
7942 pa != args->end();
7943 ++pa)
7945 Type_context subcontext;
7946 subcontext.type = arg_type;
7948 if (is_print)
7950 // We want to print large constants, we so can't just
7951 // use the appropriate nonabstract type. Use uint64 for
7952 // an integer if we know it is nonnegative, otherwise
7953 // use int64 for a integer, otherwise use float64 for a
7954 // float or complex128 for a complex.
7955 Type* want_type = NULL;
7956 Type* atype = (*pa)->type();
7957 if (atype->is_abstract())
7959 if (atype->integer_type() != NULL)
7961 Numeric_constant nc;
7962 if (this->numeric_constant_value(&nc))
7964 mpz_t val;
7965 if (nc.to_int(&val))
7967 if (mpz_sgn(val) >= 0)
7968 want_type = Type::lookup_integer_type("uint64");
7969 mpz_clear(val);
7972 if (want_type == NULL)
7973 want_type = Type::lookup_integer_type("int64");
7975 else if (atype->float_type() != NULL)
7976 want_type = Type::lookup_float_type("float64");
7977 else if (atype->complex_type() != NULL)
7978 want_type = Type::lookup_complex_type("complex128");
7979 else if (atype->is_abstract_string_type())
7980 want_type = Type::lookup_string_type();
7981 else if (atype->is_abstract_boolean_type())
7982 want_type = Type::lookup_bool_type();
7983 else
7984 go_unreachable();
7985 subcontext.type = want_type;
7989 (*pa)->determine_type(&subcontext);
7994 // If there is exactly one argument, return true. Otherwise give an
7995 // error message and return false.
7997 bool
7998 Builtin_call_expression::check_one_arg()
8000 const Expression_list* args = this->args();
8001 if (args == NULL || args->size() < 1)
8003 this->report_error(_("not enough arguments"));
8004 return false;
8006 else if (args->size() > 1)
8008 this->report_error(_("too many arguments"));
8009 return false;
8011 if (args->front()->is_error_expression()
8012 || args->front()->type()->is_error())
8014 this->set_is_error();
8015 return false;
8017 return true;
8020 // Check argument types for a builtin function.
8022 void
8023 Builtin_call_expression::do_check_types(Gogo*)
8025 if (this->is_error_expression())
8026 return;
8027 switch (this->code_)
8029 case BUILTIN_INVALID:
8030 case BUILTIN_NEW:
8031 case BUILTIN_MAKE:
8032 case BUILTIN_DELETE:
8033 return;
8035 case BUILTIN_LEN:
8036 case BUILTIN_CAP:
8038 // The single argument may be either a string or an array or a
8039 // map or a channel, or a pointer to a closed array.
8040 if (this->check_one_arg())
8042 Type* arg_type = this->one_arg()->type();
8043 if (arg_type->points_to() != NULL
8044 && arg_type->points_to()->array_type() != NULL
8045 && !arg_type->points_to()->is_slice_type())
8046 arg_type = arg_type->points_to();
8047 if (this->code_ == BUILTIN_CAP)
8049 if (!arg_type->is_error()
8050 && arg_type->array_type() == NULL
8051 && arg_type->channel_type() == NULL)
8052 this->report_error(_("argument must be array or slice "
8053 "or channel"));
8055 else
8057 if (!arg_type->is_error()
8058 && !arg_type->is_string_type()
8059 && arg_type->array_type() == NULL
8060 && arg_type->map_type() == NULL
8061 && arg_type->channel_type() == NULL)
8062 this->report_error(_("argument must be string or "
8063 "array or slice or map or channel"));
8067 break;
8069 case BUILTIN_PRINT:
8070 case BUILTIN_PRINTLN:
8072 const Expression_list* args = this->args();
8073 if (args == NULL)
8075 if (this->code_ == BUILTIN_PRINT)
8076 warning_at(this->location(), 0,
8077 "no arguments for builtin function %<%s%>",
8078 (this->code_ == BUILTIN_PRINT
8079 ? "print"
8080 : "println"));
8082 else
8084 for (Expression_list::const_iterator p = args->begin();
8085 p != args->end();
8086 ++p)
8088 Type* type = (*p)->type();
8089 if (type->is_error()
8090 || type->is_string_type()
8091 || type->integer_type() != NULL
8092 || type->float_type() != NULL
8093 || type->complex_type() != NULL
8094 || type->is_boolean_type()
8095 || type->points_to() != NULL
8096 || type->interface_type() != NULL
8097 || type->channel_type() != NULL
8098 || type->map_type() != NULL
8099 || type->function_type() != NULL
8100 || type->is_slice_type())
8102 else if ((*p)->is_type_expression())
8104 // If this is a type expression it's going to give
8105 // an error anyhow, so we don't need one here.
8107 else
8108 this->report_error(_("unsupported argument type to "
8109 "builtin function"));
8113 break;
8115 case BUILTIN_CLOSE:
8116 if (this->check_one_arg())
8118 if (this->one_arg()->type()->channel_type() == NULL)
8119 this->report_error(_("argument must be channel"));
8120 else if (!this->one_arg()->type()->channel_type()->may_send())
8121 this->report_error(_("cannot close receive-only channel"));
8123 break;
8125 case BUILTIN_PANIC:
8126 case BUILTIN_SIZEOF:
8127 case BUILTIN_ALIGNOF:
8128 this->check_one_arg();
8129 break;
8131 case BUILTIN_RECOVER:
8132 if (this->args() != NULL && !this->args()->empty())
8133 this->report_error(_("too many arguments"));
8134 break;
8136 case BUILTIN_OFFSETOF:
8137 if (this->check_one_arg())
8139 Expression* arg = this->one_arg();
8140 if (arg->field_reference_expression() == NULL)
8141 this->report_error(_("argument must be a field reference"));
8143 break;
8145 case BUILTIN_COPY:
8147 const Expression_list* args = this->args();
8148 if (args == NULL || args->size() < 2)
8150 this->report_error(_("not enough arguments"));
8151 break;
8153 else if (args->size() > 2)
8155 this->report_error(_("too many arguments"));
8156 break;
8158 Type* arg1_type = args->front()->type();
8159 Type* arg2_type = args->back()->type();
8160 if (arg1_type->is_error() || arg2_type->is_error())
8161 break;
8163 Type* e1;
8164 if (arg1_type->is_slice_type())
8165 e1 = arg1_type->array_type()->element_type();
8166 else
8168 this->report_error(_("left argument must be a slice"));
8169 break;
8172 if (arg2_type->is_slice_type())
8174 Type* e2 = arg2_type->array_type()->element_type();
8175 if (!Type::are_identical(e1, e2, true, NULL))
8176 this->report_error(_("element types must be the same"));
8178 else if (arg2_type->is_string_type())
8180 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8181 this->report_error(_("first argument must be []byte"));
8183 else
8184 this->report_error(_("second argument must be slice or string"));
8186 break;
8188 case BUILTIN_APPEND:
8190 const Expression_list* args = this->args();
8191 if (args == NULL || args->size() < 2)
8193 this->report_error(_("not enough arguments"));
8194 break;
8196 if (args->size() > 2)
8198 this->report_error(_("too many arguments"));
8199 break;
8201 if (args->front()->type()->is_error()
8202 || args->back()->type()->is_error())
8203 break;
8205 Array_type* at = args->front()->type()->array_type();
8206 Type* e = at->element_type();
8208 // The language permits appending a string to a []byte, as a
8209 // special case.
8210 if (args->back()->type()->is_string_type())
8212 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8213 break;
8216 // The language says that the second argument must be
8217 // assignable to a slice of the element type of the first
8218 // argument. We already know the first argument is a slice
8219 // type.
8220 Type* arg2_type = Type::make_array_type(e, NULL);
8221 std::string reason;
8222 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8224 if (reason.empty())
8225 this->report_error(_("argument 2 has invalid type"));
8226 else
8228 error_at(this->location(), "argument 2 has invalid type (%s)",
8229 reason.c_str());
8230 this->set_is_error();
8233 break;
8236 case BUILTIN_REAL:
8237 case BUILTIN_IMAG:
8238 if (this->check_one_arg())
8240 if (this->one_arg()->type()->complex_type() == NULL)
8241 this->report_error(_("argument must have complex type"));
8243 break;
8245 case BUILTIN_COMPLEX:
8247 const Expression_list* args = this->args();
8248 if (args == NULL || args->size() < 2)
8249 this->report_error(_("not enough arguments"));
8250 else if (args->size() > 2)
8251 this->report_error(_("too many arguments"));
8252 else if (args->front()->is_error_expression()
8253 || args->front()->type()->is_error()
8254 || args->back()->is_error_expression()
8255 || args->back()->type()->is_error())
8256 this->set_is_error();
8257 else if (!Type::are_identical(args->front()->type(),
8258 args->back()->type(), true, NULL))
8259 this->report_error(_("complex arguments must have identical types"));
8260 else if (args->front()->type()->float_type() == NULL)
8261 this->report_error(_("complex arguments must have "
8262 "floating-point type"));
8264 break;
8266 default:
8267 go_unreachable();
8271 // Return the tree for a builtin function.
8273 tree
8274 Builtin_call_expression::do_get_tree(Translate_context* context)
8276 Gogo* gogo = context->gogo();
8277 Location location = this->location();
8278 switch (this->code_)
8280 case BUILTIN_INVALID:
8281 case BUILTIN_NEW:
8282 case BUILTIN_MAKE:
8283 go_unreachable();
8285 case BUILTIN_LEN:
8286 case BUILTIN_CAP:
8288 const Expression_list* args = this->args();
8289 go_assert(args != NULL && args->size() == 1);
8290 Expression* arg = args->front();
8291 Type* arg_type = arg->type();
8293 if (this->seen_)
8295 go_assert(saw_errors());
8296 return error_mark_node;
8298 this->seen_ = true;
8299 this->seen_ = false;
8300 if (arg_type->points_to() != NULL)
8302 arg_type = arg_type->points_to();
8303 go_assert(arg_type->array_type() != NULL
8304 && !arg_type->is_slice_type());
8305 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8308 Type* int_type = Type::lookup_integer_type("int");
8309 Expression* val;
8310 if (this->code_ == BUILTIN_LEN)
8312 if (arg_type->is_string_type())
8313 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8314 location);
8315 else if (arg_type->array_type() != NULL)
8317 if (this->seen_)
8319 go_assert(saw_errors());
8320 return error_mark_node;
8322 this->seen_ = true;
8323 val = arg_type->array_type()->get_length(gogo, arg);
8324 this->seen_ = false;
8326 else if (arg_type->map_type() != NULL)
8327 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8328 else if (arg_type->channel_type() != NULL)
8329 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8330 else
8331 go_unreachable();
8333 else
8335 if (arg_type->array_type() != NULL)
8337 if (this->seen_)
8339 go_assert(saw_errors());
8340 return error_mark_node;
8342 this->seen_ = true;
8343 val = arg_type->array_type()->get_capacity(gogo, arg);
8344 this->seen_ = false;
8346 else if (arg_type->channel_type() != NULL)
8347 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8348 else
8349 go_unreachable();
8352 return Expression::make_cast(int_type, val,
8353 location)->get_tree(context);
8356 case BUILTIN_PRINT:
8357 case BUILTIN_PRINTLN:
8359 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8360 Expression* print_stmts = NULL;
8362 const Expression_list* call_args = this->args();
8363 if (call_args != NULL)
8365 for (Expression_list::const_iterator p = call_args->begin();
8366 p != call_args->end();
8367 ++p)
8369 if (is_ln && p != call_args->begin())
8371 Expression* print_space =
8372 Runtime::make_call(Runtime::PRINT_SPACE,
8373 this->location(), 0);
8375 print_stmts =
8376 Expression::make_compound(print_stmts, print_space,
8377 location);
8380 Expression* arg = *p;
8381 Type* type = arg->type();
8382 Runtime::Function code;
8383 if (type->is_string_type())
8384 code = Runtime::PRINT_STRING;
8385 else if (type->integer_type() != NULL
8386 && type->integer_type()->is_unsigned())
8388 Type* itype = Type::lookup_integer_type("uint64");
8389 arg = Expression::make_cast(itype, arg, location);
8390 code = Runtime::PRINT_UINT64;
8392 else if (type->integer_type() != NULL)
8394 Type* itype = Type::lookup_integer_type("int64");
8395 arg = Expression::make_cast(itype, arg, location);
8396 code = Runtime::PRINT_INT64;
8398 else if (type->float_type() != NULL)
8400 Type* dtype = Type::lookup_float_type("float64");
8401 arg = Expression::make_cast(dtype, arg, location);
8402 code = Runtime::PRINT_DOUBLE;
8404 else if (type->complex_type() != NULL)
8406 Type* ctype = Type::lookup_complex_type("complex128");
8407 arg = Expression::make_cast(ctype, arg, location);
8408 code = Runtime::PRINT_COMPLEX;
8410 else if (type->is_boolean_type())
8411 code = Runtime::PRINT_BOOL;
8412 else if (type->points_to() != NULL
8413 || type->channel_type() != NULL
8414 || type->map_type() != NULL
8415 || type->function_type() != NULL)
8417 arg = Expression::make_cast(type, arg, location);
8418 code = Runtime::PRINT_POINTER;
8420 else if (type->interface_type() != NULL)
8422 if (type->interface_type()->is_empty())
8423 code = Runtime::PRINT_EMPTY_INTERFACE;
8424 else
8425 code = Runtime::PRINT_INTERFACE;
8427 else if (type->is_slice_type())
8428 code = Runtime::PRINT_SLICE;
8429 else
8431 go_assert(saw_errors());
8432 return error_mark_node;
8435 Expression* call = Runtime::make_call(code, location, 1, arg);
8436 if (print_stmts == NULL)
8437 print_stmts = call;
8438 else
8439 print_stmts = Expression::make_compound(print_stmts, call,
8440 location);
8444 if (is_ln)
8446 Expression* print_nl =
8447 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8448 if (print_stmts == NULL)
8449 print_stmts = print_nl;
8450 else
8451 print_stmts = Expression::make_compound(print_stmts, print_nl,
8452 location);
8455 return print_stmts->get_tree(context);
8458 case BUILTIN_PANIC:
8460 const Expression_list* args = this->args();
8461 go_assert(args != NULL && args->size() == 1);
8462 Expression* arg = args->front();
8463 Type *empty =
8464 Type::make_empty_interface_type(Linemap::predeclared_location());
8465 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8467 Expression* panic =
8468 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8469 return panic->get_tree(context);
8472 case BUILTIN_RECOVER:
8474 // The argument is set when building recover thunks. It's a
8475 // boolean value which is true if we can recover a value now.
8476 const Expression_list* args = this->args();
8477 go_assert(args != NULL && args->size() == 1);
8478 Expression* arg = args->front();
8479 Type *empty =
8480 Type::make_empty_interface_type(Linemap::predeclared_location());
8482 Expression* nil = Expression::make_nil(location);
8483 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8485 // We need to handle a deferred call to recover specially,
8486 // because it changes whether it can recover a panic or not.
8487 // See test7 in test/recover1.go.
8488 Expression* recover = Runtime::make_call((this->is_deferred()
8489 ? Runtime::DEFERRED_RECOVER
8490 : Runtime::RECOVER),
8491 location, 0);
8492 Expression* cond =
8493 Expression::make_conditional(arg, recover, nil, location);
8494 return cond->get_tree(context);
8497 case BUILTIN_CLOSE:
8499 const Expression_list* args = this->args();
8500 go_assert(args != NULL && args->size() == 1);
8501 Expression* arg = args->front();
8502 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8503 1, arg);
8504 return close->get_tree(context);
8507 case BUILTIN_SIZEOF:
8508 case BUILTIN_OFFSETOF:
8509 case BUILTIN_ALIGNOF:
8511 Numeric_constant nc;
8512 unsigned long val;
8513 if (!this->numeric_constant_value(&nc)
8514 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8516 go_assert(saw_errors());
8517 return error_mark_node;
8519 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8520 mpz_t ival;
8521 nc.get_int(&ival);
8522 Expression* int_cst =
8523 Expression::make_integer(&ival, uintptr_type, location);
8524 mpz_clear(ival);
8525 return int_cst->get_tree(context);
8528 case BUILTIN_COPY:
8530 const Expression_list* args = this->args();
8531 go_assert(args != NULL && args->size() == 2);
8532 Expression* arg1 = args->front();
8533 Expression* arg2 = args->back();
8535 Type* arg1_type = arg1->type();
8536 Array_type* at = arg1_type->array_type();
8537 go_assert(arg1->is_variable());
8538 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8539 Expression* arg1_len = at->get_length(gogo, arg1);
8541 Type* arg2_type = arg2->type();
8542 go_assert(arg2->is_variable());
8543 Expression* arg2_val;
8544 Expression* arg2_len;
8545 if (arg2_type->is_slice_type())
8547 at = arg2_type->array_type();
8548 arg2_val = at->get_value_pointer(gogo, arg2);
8549 arg2_len = at->get_length(gogo, arg2);
8551 else
8553 go_assert(arg2->is_variable());
8554 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8555 location);
8556 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8557 location);
8559 Expression* cond =
8560 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8561 Expression* length =
8562 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8564 Type* element_type = at->element_type();
8565 Btype* element_btype = element_type->get_backend(gogo);
8567 mpz_t size;
8568 size_t element_size = gogo->backend()->type_size(element_btype);
8569 mpz_init_set_ui(size, element_size);
8570 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8571 mpz_clear(size);
8573 Expression* bytecount =
8574 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8575 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8576 arg1_val, arg2_val, bytecount);
8578 Expression* compound = Expression::make_compound(copy, length, location);
8579 return compound->get_tree(context);
8582 case BUILTIN_APPEND:
8584 const Expression_list* args = this->args();
8585 go_assert(args != NULL && args->size() == 2);
8586 Expression* arg1 = args->front();
8587 Expression* arg2 = args->back();
8589 Array_type* at = arg1->type()->array_type();
8590 Type* element_type = at->element_type()->forwarded();
8592 go_assert(arg2->is_variable());
8593 Expression* arg2_val;
8594 Expression* arg2_len;
8595 mpz_t size;
8596 if (arg2->type()->is_string_type()
8597 && element_type->integer_type() != NULL
8598 && element_type->integer_type()->is_byte())
8600 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8601 location);
8602 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8603 location);
8604 mpz_init_set_ui(size, 1UL);
8606 else
8608 arg2_val = at->get_value_pointer(gogo, arg2);
8609 arg2_len = at->get_length(gogo, arg2);
8610 Btype* element_btype = element_type->get_backend(gogo);
8611 size_t element_size = gogo->backend()->type_size(element_btype);
8612 mpz_init_set_ui(size, element_size);
8614 Expression* element_size =
8615 Expression::make_integer(&size, NULL, location);
8616 mpz_clear(size);
8618 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8619 arg1, arg2_val, arg2_len,
8620 element_size);
8621 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8622 return append->get_tree(context);
8625 case BUILTIN_REAL:
8626 case BUILTIN_IMAG:
8628 const Expression_list* args = this->args();
8629 go_assert(args != NULL && args->size() == 1);
8630 Expression* arg = args->front();
8632 Bexpression* ret;
8633 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8634 if (this->code_ == BUILTIN_REAL)
8635 ret = gogo->backend()->real_part_expression(bcomplex, location);
8636 else
8637 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8638 return expr_to_tree(ret);
8641 case BUILTIN_COMPLEX:
8643 const Expression_list* args = this->args();
8644 go_assert(args != NULL && args->size() == 2);
8645 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8646 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8647 Bexpression* ret =
8648 gogo->backend()->complex_expression(breal, bimag, location);
8649 return expr_to_tree(ret);
8652 default:
8653 go_unreachable();
8657 // We have to support exporting a builtin call expression, because
8658 // code can set a constant to the result of a builtin expression.
8660 void
8661 Builtin_call_expression::do_export(Export* exp) const
8663 Numeric_constant nc;
8664 if (!this->numeric_constant_value(&nc))
8666 error_at(this->location(), "value is not constant");
8667 return;
8670 if (nc.is_int())
8672 mpz_t val;
8673 nc.get_int(&val);
8674 Integer_expression::export_integer(exp, val);
8675 mpz_clear(val);
8677 else if (nc.is_float())
8679 mpfr_t fval;
8680 nc.get_float(&fval);
8681 Float_expression::export_float(exp, fval);
8682 mpfr_clear(fval);
8684 else if (nc.is_complex())
8686 mpfr_t real;
8687 mpfr_t imag;
8688 Complex_expression::export_complex(exp, real, imag);
8689 mpfr_clear(real);
8690 mpfr_clear(imag);
8692 else
8693 go_unreachable();
8695 // A trailing space lets us reliably identify the end of the number.
8696 exp->write_c_string(" ");
8699 // Class Call_expression.
8701 // A Go function can be viewed in a couple of different ways. The
8702 // code of a Go function becomes a backend function with parameters
8703 // whose types are simply the backend representation of the Go types.
8704 // If there are multiple results, they are returned as a backend
8705 // struct.
8707 // However, when Go code refers to a function other than simply
8708 // calling it, the backend type of that function is actually a struct.
8709 // The first field of the struct points to the Go function code
8710 // (sometimes a wrapper as described below). The remaining fields
8711 // hold addresses of closed-over variables. This struct is called a
8712 // closure.
8714 // There are a few cases to consider.
8716 // A direct function call of a known function in package scope. In
8717 // this case there are no closed-over variables, and we know the name
8718 // of the function code. We can simply produce a backend call to the
8719 // function directly, and not worry about the closure.
8721 // A direct function call of a known function literal. In this case
8722 // we know the function code and we know the closure. We generate the
8723 // function code such that it expects an additional final argument of
8724 // the closure type. We pass the closure as the last argument, after
8725 // the other arguments.
8727 // An indirect function call. In this case we have a closure. We
8728 // load the pointer to the function code from the first field of the
8729 // closure. We pass the address of the closure as the last argument.
8731 // A call to a method of an interface. Type methods are always at
8732 // package scope, so we call the function directly, and don't worry
8733 // about the closure.
8735 // This means that for a function at package scope we have two cases.
8736 // One is the direct call, which has no closure. The other is the
8737 // indirect call, which does have a closure. We can't simply ignore
8738 // the closure, even though it is the last argument, because that will
8739 // fail on targets where the function pops its arguments. So when
8740 // generating a closure for a package-scope function we set the
8741 // function code pointer in the closure to point to a wrapper
8742 // function. This wrapper function accepts a final argument that
8743 // points to the closure, ignores it, and calls the real function as a
8744 // direct function call. This wrapper will normally be efficient, and
8745 // can often simply be a tail call to the real function.
8747 // We don't use GCC's static chain pointer because 1) we don't need
8748 // it; 2) GCC only permits using a static chain to call a known
8749 // function, so we can't use it for an indirect call anyhow. Since we
8750 // can't use it for an indirect call, we may as well not worry about
8751 // using it for a direct call either.
8753 // We pass the closure last rather than first because it means that
8754 // the function wrapper we put into a closure for a package-scope
8755 // function can normally just be a tail call to the real function.
8757 // For method expressions we generate a wrapper that loads the
8758 // receiver from the closure and then calls the method. This
8759 // unfortunately forces reshuffling the arguments, since there is a
8760 // new first argument, but we can't avoid reshuffling either for
8761 // method expressions or for indirect calls of package-scope
8762 // functions, and since the latter are more common we reshuffle for
8763 // method expressions.
8765 // Note that the Go code retains the Go types. The extra final
8766 // argument only appears when we convert to the backend
8767 // representation.
8769 // Traversal.
8772 Call_expression::do_traverse(Traverse* traverse)
8774 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8775 return TRAVERSE_EXIT;
8776 if (this->args_ != NULL)
8778 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8779 return TRAVERSE_EXIT;
8781 return TRAVERSE_CONTINUE;
8784 // Lower a call statement.
8786 Expression*
8787 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8788 Statement_inserter* inserter, int)
8790 Location loc = this->location();
8792 // A type cast can look like a function call.
8793 if (this->fn_->is_type_expression()
8794 && this->args_ != NULL
8795 && this->args_->size() == 1)
8796 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8797 loc);
8799 // Because do_type will return an error type and thus prevent future
8800 // errors, check for that case now to ensure that the error gets
8801 // reported.
8802 Function_type* fntype = this->get_function_type();
8803 if (fntype == NULL)
8805 if (!this->fn_->type()->is_error())
8806 this->report_error(_("expected function"));
8807 return Expression::make_error(loc);
8810 // Handle an argument which is a call to a function which returns
8811 // multiple results.
8812 if (this->args_ != NULL
8813 && this->args_->size() == 1
8814 && this->args_->front()->call_expression() != NULL)
8816 size_t rc = this->args_->front()->call_expression()->result_count();
8817 if (rc > 1
8818 && ((fntype->parameters() != NULL
8819 && (fntype->parameters()->size() == rc
8820 || (fntype->is_varargs()
8821 && fntype->parameters()->size() - 1 <= rc)))
8822 || fntype->is_builtin()))
8824 Call_expression* call = this->args_->front()->call_expression();
8825 Expression_list* args = new Expression_list;
8826 for (size_t i = 0; i < rc; ++i)
8827 args->push_back(Expression::make_call_result(call, i));
8828 // We can't return a new call expression here, because this
8829 // one may be referenced by Call_result expressions. We
8830 // also can't delete the old arguments, because we may still
8831 // traverse them somewhere up the call stack. FIXME.
8832 this->args_ = args;
8836 // Recognize a call to a builtin function.
8837 if (fntype->is_builtin())
8838 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8839 this->is_varargs_, loc);
8841 // If this call returns multiple results, create a temporary
8842 // variable for each result.
8843 size_t rc = this->result_count();
8844 if (rc > 1 && this->results_ == NULL)
8846 std::vector<Temporary_statement*>* temps =
8847 new std::vector<Temporary_statement*>;
8848 temps->reserve(rc);
8849 const Typed_identifier_list* results = fntype->results();
8850 for (Typed_identifier_list::const_iterator p = results->begin();
8851 p != results->end();
8852 ++p)
8854 Temporary_statement* temp = Statement::make_temporary(p->type(),
8855 NULL, loc);
8856 inserter->insert(temp);
8857 temps->push_back(temp);
8859 this->results_ = temps;
8862 // Handle a call to a varargs function by packaging up the extra
8863 // parameters.
8864 if (fntype->is_varargs())
8866 const Typed_identifier_list* parameters = fntype->parameters();
8867 go_assert(parameters != NULL && !parameters->empty());
8868 Type* varargs_type = parameters->back().type();
8869 this->lower_varargs(gogo, function, inserter, varargs_type,
8870 parameters->size());
8873 // If this is call to a method, call the method directly passing the
8874 // object as the first parameter.
8875 Bound_method_expression* bme = this->fn_->bound_method_expression();
8876 if (bme != NULL)
8878 Named_object* methodfn = bme->function();
8879 Expression* first_arg = bme->first_argument();
8881 // We always pass a pointer when calling a method.
8882 if (first_arg->type()->points_to() == NULL
8883 && !first_arg->type()->is_error())
8885 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8886 // We may need to create a temporary variable so that we can
8887 // take the address. We can't do that here because it will
8888 // mess up the order of evaluation.
8889 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8890 ue->set_create_temp();
8893 // If we are calling a method which was inherited from an
8894 // embedded struct, and the method did not get a stub, then the
8895 // first type may be wrong.
8896 Type* fatype = bme->first_argument_type();
8897 if (fatype != NULL)
8899 if (fatype->points_to() == NULL)
8900 fatype = Type::make_pointer_type(fatype);
8901 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8904 Expression_list* new_args = new Expression_list();
8905 new_args->push_back(first_arg);
8906 if (this->args_ != NULL)
8908 for (Expression_list::const_iterator p = this->args_->begin();
8909 p != this->args_->end();
8910 ++p)
8911 new_args->push_back(*p);
8914 // We have to change in place because this structure may be
8915 // referenced by Call_result_expressions. We can't delete the
8916 // old arguments, because we may be traversing them up in some
8917 // caller. FIXME.
8918 this->args_ = new_args;
8919 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8920 bme->location());
8923 return this;
8926 // Lower a call to a varargs function. FUNCTION is the function in
8927 // which the call occurs--it's not the function we are calling.
8928 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8929 // PARAM_COUNT is the number of parameters of the function we are
8930 // calling; the last of these parameters will be the varargs
8931 // parameter.
8933 void
8934 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8935 Statement_inserter* inserter,
8936 Type* varargs_type, size_t param_count)
8938 if (this->varargs_are_lowered_)
8939 return;
8941 Location loc = this->location();
8943 go_assert(param_count > 0);
8944 go_assert(varargs_type->is_slice_type());
8946 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8947 if (arg_count < param_count - 1)
8949 // Not enough arguments; will be caught in check_types.
8950 return;
8953 Expression_list* old_args = this->args_;
8954 Expression_list* new_args = new Expression_list();
8955 bool push_empty_arg = false;
8956 if (old_args == NULL || old_args->empty())
8958 go_assert(param_count == 1);
8959 push_empty_arg = true;
8961 else
8963 Expression_list::const_iterator pa;
8964 int i = 1;
8965 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8967 if (static_cast<size_t>(i) == param_count)
8968 break;
8969 new_args->push_back(*pa);
8972 // We have reached the varargs parameter.
8974 bool issued_error = false;
8975 if (pa == old_args->end())
8976 push_empty_arg = true;
8977 else if (pa + 1 == old_args->end() && this->is_varargs_)
8978 new_args->push_back(*pa);
8979 else if (this->is_varargs_)
8981 if ((*pa)->type()->is_slice_type())
8982 this->report_error(_("too many arguments"));
8983 else
8985 error_at(this->location(),
8986 _("invalid use of %<...%> with non-slice"));
8987 this->set_is_error();
8989 return;
8991 else
8993 Type* element_type = varargs_type->array_type()->element_type();
8994 Expression_list* vals = new Expression_list;
8995 for (; pa != old_args->end(); ++pa, ++i)
8997 // Check types here so that we get a better message.
8998 Type* patype = (*pa)->type();
8999 Location paloc = (*pa)->location();
9000 if (!this->check_argument_type(i, element_type, patype,
9001 paloc, issued_error))
9002 continue;
9003 vals->push_back(*pa);
9005 Expression* val =
9006 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9007 gogo->lower_expression(function, inserter, &val);
9008 new_args->push_back(val);
9012 if (push_empty_arg)
9013 new_args->push_back(Expression::make_nil(loc));
9015 // We can't return a new call expression here, because this one may
9016 // be referenced by Call_result expressions. FIXME. We can't
9017 // delete OLD_ARGS because we may have both a Call_expression and a
9018 // Builtin_call_expression which refer to them. FIXME.
9019 this->args_ = new_args;
9020 this->varargs_are_lowered_ = true;
9023 // Flatten a call with multiple results into a temporary.
9025 Expression*
9026 Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9028 size_t rc = this->result_count();
9029 if (rc > 1 && this->call_temp_ == NULL)
9031 Struct_field_list* sfl = new Struct_field_list();
9032 Function_type* fntype = this->get_function_type();
9033 const Typed_identifier_list* results = fntype->results();
9034 Location loc = this->location();
9036 int i = 0;
9037 char buf[10];
9038 for (Typed_identifier_list::const_iterator p = results->begin();
9039 p != results->end();
9040 ++p, ++i)
9042 snprintf(buf, sizeof buf, "res%d", i);
9043 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9046 Struct_type* st = Type::make_struct_type(sfl, loc);
9047 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9048 inserter->insert(this->call_temp_);
9051 return this;
9054 // Get the function type. This can return NULL in error cases.
9056 Function_type*
9057 Call_expression::get_function_type() const
9059 return this->fn_->type()->function_type();
9062 // Return the number of values which this call will return.
9064 size_t
9065 Call_expression::result_count() const
9067 const Function_type* fntype = this->get_function_type();
9068 if (fntype == NULL)
9069 return 0;
9070 if (fntype->results() == NULL)
9071 return 0;
9072 return fntype->results()->size();
9075 // Return the temporary which holds a result.
9077 Temporary_statement*
9078 Call_expression::result(size_t i) const
9080 if (this->results_ == NULL || this->results_->size() <= i)
9082 go_assert(saw_errors());
9083 return NULL;
9085 return (*this->results_)[i];
9088 // Return whether this is a call to the predeclared function recover.
9090 bool
9091 Call_expression::is_recover_call() const
9093 return this->do_is_recover_call();
9096 // Set the argument to the recover function.
9098 void
9099 Call_expression::set_recover_arg(Expression* arg)
9101 this->do_set_recover_arg(arg);
9104 // Virtual functions also implemented by Builtin_call_expression.
9106 bool
9107 Call_expression::do_is_recover_call() const
9109 return false;
9112 void
9113 Call_expression::do_set_recover_arg(Expression*)
9115 go_unreachable();
9118 // We have found an error with this call expression; return true if
9119 // we should report it.
9121 bool
9122 Call_expression::issue_error()
9124 if (this->issued_error_)
9125 return false;
9126 else
9128 this->issued_error_ = true;
9129 return true;
9133 // Get the type.
9135 Type*
9136 Call_expression::do_type()
9138 if (this->type_ != NULL)
9139 return this->type_;
9141 Type* ret;
9142 Function_type* fntype = this->get_function_type();
9143 if (fntype == NULL)
9144 return Type::make_error_type();
9146 const Typed_identifier_list* results = fntype->results();
9147 if (results == NULL)
9148 ret = Type::make_void_type();
9149 else if (results->size() == 1)
9150 ret = results->begin()->type();
9151 else
9152 ret = Type::make_call_multiple_result_type(this);
9154 this->type_ = ret;
9156 return this->type_;
9159 // Determine types for a call expression. We can use the function
9160 // parameter types to set the types of the arguments.
9162 void
9163 Call_expression::do_determine_type(const Type_context*)
9165 if (!this->determining_types())
9166 return;
9168 this->fn_->determine_type_no_context();
9169 Function_type* fntype = this->get_function_type();
9170 const Typed_identifier_list* parameters = NULL;
9171 if (fntype != NULL)
9172 parameters = fntype->parameters();
9173 if (this->args_ != NULL)
9175 Typed_identifier_list::const_iterator pt;
9176 if (parameters != NULL)
9177 pt = parameters->begin();
9178 bool first = true;
9179 for (Expression_list::const_iterator pa = this->args_->begin();
9180 pa != this->args_->end();
9181 ++pa)
9183 if (first)
9185 first = false;
9186 // If this is a method, the first argument is the
9187 // receiver.
9188 if (fntype != NULL && fntype->is_method())
9190 Type* rtype = fntype->receiver()->type();
9191 // The receiver is always passed as a pointer.
9192 if (rtype->points_to() == NULL)
9193 rtype = Type::make_pointer_type(rtype);
9194 Type_context subcontext(rtype, false);
9195 (*pa)->determine_type(&subcontext);
9196 continue;
9200 if (parameters != NULL && pt != parameters->end())
9202 Type_context subcontext(pt->type(), false);
9203 (*pa)->determine_type(&subcontext);
9204 ++pt;
9206 else
9207 (*pa)->determine_type_no_context();
9212 // Called when determining types for a Call_expression. Return true
9213 // if we should go ahead, false if they have already been determined.
9215 bool
9216 Call_expression::determining_types()
9218 if (this->types_are_determined_)
9219 return false;
9220 else
9222 this->types_are_determined_ = true;
9223 return true;
9227 // Check types for parameter I.
9229 bool
9230 Call_expression::check_argument_type(int i, const Type* parameter_type,
9231 const Type* argument_type,
9232 Location argument_location,
9233 bool issued_error)
9235 std::string reason;
9236 bool ok;
9237 if (this->are_hidden_fields_ok_)
9238 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9239 &reason);
9240 else
9241 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9242 if (!ok)
9244 if (!issued_error)
9246 if (reason.empty())
9247 error_at(argument_location, "argument %d has incompatible type", i);
9248 else
9249 error_at(argument_location,
9250 "argument %d has incompatible type (%s)",
9251 i, reason.c_str());
9253 this->set_is_error();
9254 return false;
9256 return true;
9259 // Check types.
9261 void
9262 Call_expression::do_check_types(Gogo*)
9264 if (this->classification() == EXPRESSION_ERROR)
9265 return;
9267 Function_type* fntype = this->get_function_type();
9268 if (fntype == NULL)
9270 if (!this->fn_->type()->is_error())
9271 this->report_error(_("expected function"));
9272 return;
9275 bool is_method = fntype->is_method();
9276 if (is_method)
9278 go_assert(this->args_ != NULL && !this->args_->empty());
9279 Type* rtype = fntype->receiver()->type();
9280 Expression* first_arg = this->args_->front();
9281 // The language permits copying hidden fields for a method
9282 // receiver. We dereference the values since receivers are
9283 // always passed as pointers.
9284 std::string reason;
9285 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9286 first_arg->type()->deref(),
9287 &reason))
9289 if (reason.empty())
9290 this->report_error(_("incompatible type for receiver"));
9291 else
9293 error_at(this->location(),
9294 "incompatible type for receiver (%s)",
9295 reason.c_str());
9296 this->set_is_error();
9301 // Note that varargs was handled by the lower_varargs() method, so
9302 // we don't have to worry about it here unless something is wrong.
9303 if (this->is_varargs_ && !this->varargs_are_lowered_)
9305 if (!fntype->is_varargs())
9307 error_at(this->location(),
9308 _("invalid use of %<...%> calling non-variadic function"));
9309 this->set_is_error();
9310 return;
9314 const Typed_identifier_list* parameters = fntype->parameters();
9315 if (this->args_ == NULL)
9317 if (parameters != NULL && !parameters->empty())
9318 this->report_error(_("not enough arguments"));
9320 else if (parameters == NULL)
9322 if (!is_method || this->args_->size() > 1)
9323 this->report_error(_("too many arguments"));
9325 else
9327 int i = 0;
9328 Expression_list::const_iterator pa = this->args_->begin();
9329 if (is_method)
9330 ++pa;
9331 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9332 pt != parameters->end();
9333 ++pt, ++pa, ++i)
9335 if (pa == this->args_->end())
9337 this->report_error(_("not enough arguments"));
9338 return;
9340 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9341 (*pa)->location(), false);
9343 if (pa != this->args_->end())
9344 this->report_error(_("too many arguments"));
9348 // Return whether we have to use a temporary variable to ensure that
9349 // we evaluate this call expression in order. If the call returns no
9350 // results then it will inevitably be executed last.
9352 bool
9353 Call_expression::do_must_eval_in_order() const
9355 return this->result_count() > 0;
9358 // Get the function and the first argument to use when calling an
9359 // interface method.
9361 Expression*
9362 Call_expression::interface_method_function(
9363 Interface_field_reference_expression* interface_method,
9364 Expression** first_arg_ptr)
9366 *first_arg_ptr = interface_method->get_underlying_object();
9367 return interface_method->get_function();
9370 // Build the call expression.
9372 tree
9373 Call_expression::do_get_tree(Translate_context* context)
9375 if (this->call_ != NULL)
9376 return expr_to_tree(this->call_);
9378 Function_type* fntype = this->get_function_type();
9379 if (fntype == NULL)
9380 return error_mark_node;
9382 if (this->fn_->is_error_expression())
9383 return error_mark_node;
9385 Gogo* gogo = context->gogo();
9386 Location location = this->location();
9388 Func_expression* func = this->fn_->func_expression();
9389 Interface_field_reference_expression* interface_method =
9390 this->fn_->interface_field_reference_expression();
9391 const bool has_closure = func != NULL && func->closure() != NULL;
9392 const bool is_interface_method = interface_method != NULL;
9394 bool has_closure_arg;
9395 if (has_closure)
9396 has_closure_arg = true;
9397 else if (func != NULL)
9398 has_closure_arg = false;
9399 else if (is_interface_method)
9400 has_closure_arg = false;
9401 else
9402 has_closure_arg = true;
9404 int nargs;
9405 std::vector<Bexpression*> fn_args;
9406 if (this->args_ == NULL || this->args_->empty())
9408 nargs = is_interface_method ? 1 : 0;
9409 if (nargs > 0)
9410 fn_args.resize(1);
9412 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9414 // Passing a receiver parameter.
9415 go_assert(!is_interface_method
9416 && fntype->is_method()
9417 && this->args_->size() == 1);
9418 nargs = 1;
9419 fn_args.resize(1);
9420 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
9422 else
9424 const Typed_identifier_list* params = fntype->parameters();
9426 nargs = this->args_->size();
9427 int i = is_interface_method ? 1 : 0;
9428 nargs += i;
9429 fn_args.resize(nargs);
9431 Typed_identifier_list::const_iterator pp = params->begin();
9432 Expression_list::const_iterator pe = this->args_->begin();
9433 if (!is_interface_method && fntype->is_method())
9435 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
9436 ++pe;
9437 ++i;
9439 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9441 go_assert(pp != params->end());
9442 Expression* arg =
9443 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9444 location);
9445 fn_args[i] = tree_to_expr(arg->get_tree(context));
9447 go_assert(pp == params->end());
9448 go_assert(i == nargs);
9451 Expression* fn;
9452 Expression* closure = NULL;
9453 if (func != NULL)
9455 Named_object* no = func->named_object();
9456 fn = Expression::make_func_code_reference(no, location);
9457 if (has_closure)
9458 closure = func->closure();
9460 else if (!is_interface_method)
9462 closure = this->fn_;
9464 // The backend representation of this function type is a pointer
9465 // to a struct whose first field is the actual function to call.
9466 Type* pfntype =
9467 Type::make_pointer_type(
9468 Type::make_pointer_type(Type::make_void_type()));
9469 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9470 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9472 else
9474 Expression* first_arg;
9475 fn = this->interface_method_function(interface_method, &first_arg);
9476 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
9479 if (!has_closure_arg)
9480 go_assert(closure == NULL);
9481 else
9483 // Pass the closure argument by calling the function function
9484 // __go_set_closure. In the order_evaluations pass we have
9485 // ensured that if any parameters contain call expressions, they
9486 // will have been moved out to temporary variables.
9487 go_assert(closure != NULL);
9488 Expression* set_closure =
9489 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9490 fn = Expression::make_compound(set_closure, fn, location);
9493 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
9495 // When not calling a named function directly, use a type conversion
9496 // in case the type of the function is a recursive type which refers
9497 // to itself. We don't do this for an interface method because 1)
9498 // an interface method never refers to itself, so we always have a
9499 // function type here; 2) we pass an extra first argument to an
9500 // interface method, so fntype is not correct.
9501 if (func == NULL && !is_interface_method)
9503 Btype* bft = fntype->get_backend_fntype(gogo);
9504 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9507 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
9509 if (this->results_ != NULL)
9511 go_assert(this->call_temp_ != NULL);
9512 Expression* call_ref =
9513 Expression::make_temporary_reference(this->call_temp_, location);
9514 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9515 Bstatement* assn_stmt =
9516 gogo->backend()->assignment_statement(bcall_ref, call, location);
9518 this->call_ = this->set_results(context, bcall_ref);
9520 Bexpression* set_and_call =
9521 gogo->backend()->compound_expression(assn_stmt, this->call_,
9522 location);
9523 return expr_to_tree(set_and_call);
9526 this->call_ = call;
9527 return expr_to_tree(this->call_);
9530 // Set the result variables if this call returns multiple results.
9532 Bexpression*
9533 Call_expression::set_results(Translate_context* context, Bexpression* call)
9535 Gogo* gogo = context->gogo();
9537 Bexpression* results = NULL;
9538 Location loc = this->location();
9540 size_t rc = this->result_count();
9541 for (size_t i = 0; i < rc; ++i)
9543 Temporary_statement* temp = this->result(i);
9544 if (temp == NULL)
9546 go_assert(saw_errors());
9547 return gogo->backend()->error_expression();
9549 Temporary_reference_expression* ref =
9550 Expression::make_temporary_reference(temp, loc);
9551 ref->set_is_lvalue();
9553 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9554 Bexpression* call_result =
9555 gogo->backend()->struct_field_expression(call, i, loc);
9556 Bstatement* assn_stmt =
9557 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9559 Bexpression* result =
9560 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9562 if (results == NULL)
9563 results = result;
9564 else
9566 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9567 results =
9568 gogo->backend()->compound_expression(expr_stmt, results, loc);
9571 return results;
9574 // Dump ast representation for a call expressin.
9576 void
9577 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9579 this->fn_->dump_expression(ast_dump_context);
9580 ast_dump_context->ostream() << "(";
9581 if (args_ != NULL)
9582 ast_dump_context->dump_expression_list(this->args_);
9584 ast_dump_context->ostream() << ") ";
9587 // Make a call expression.
9589 Call_expression*
9590 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9591 Location location)
9593 return new Call_expression(fn, args, is_varargs, location);
9596 // A single result from a call which returns multiple results.
9598 class Call_result_expression : public Expression
9600 public:
9601 Call_result_expression(Call_expression* call, unsigned int index)
9602 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9603 call_(call), index_(index)
9606 protected:
9608 do_traverse(Traverse*);
9610 Type*
9611 do_type();
9613 void
9614 do_determine_type(const Type_context*);
9616 void
9617 do_check_types(Gogo*);
9619 Expression*
9620 do_copy()
9622 return new Call_result_expression(this->call_->call_expression(),
9623 this->index_);
9626 bool
9627 do_must_eval_in_order() const
9628 { return true; }
9630 tree
9631 do_get_tree(Translate_context*);
9633 void
9634 do_dump_expression(Ast_dump_context*) const;
9636 private:
9637 // The underlying call expression.
9638 Expression* call_;
9639 // Which result we want.
9640 unsigned int index_;
9643 // Traverse a call result.
9646 Call_result_expression::do_traverse(Traverse* traverse)
9648 if (traverse->remember_expression(this->call_))
9650 // We have already traversed the call expression.
9651 return TRAVERSE_CONTINUE;
9653 return Expression::traverse(&this->call_, traverse);
9656 // Get the type.
9658 Type*
9659 Call_result_expression::do_type()
9661 if (this->classification() == EXPRESSION_ERROR)
9662 return Type::make_error_type();
9664 // THIS->CALL_ can be replaced with a temporary reference due to
9665 // Call_expression::do_must_eval_in_order when there is an error.
9666 Call_expression* ce = this->call_->call_expression();
9667 if (ce == NULL)
9669 this->set_is_error();
9670 return Type::make_error_type();
9672 Function_type* fntype = ce->get_function_type();
9673 if (fntype == NULL)
9675 if (ce->issue_error())
9677 if (!ce->fn()->type()->is_error())
9678 this->report_error(_("expected function"));
9680 this->set_is_error();
9681 return Type::make_error_type();
9683 const Typed_identifier_list* results = fntype->results();
9684 if (results == NULL || results->size() < 2)
9686 if (ce->issue_error())
9687 this->report_error(_("number of results does not match "
9688 "number of values"));
9689 return Type::make_error_type();
9691 Typed_identifier_list::const_iterator pr = results->begin();
9692 for (unsigned int i = 0; i < this->index_; ++i)
9694 if (pr == results->end())
9695 break;
9696 ++pr;
9698 if (pr == results->end())
9700 if (ce->issue_error())
9701 this->report_error(_("number of results does not match "
9702 "number of values"));
9703 return Type::make_error_type();
9705 return pr->type();
9708 // Check the type. Just make sure that we trigger the warning in
9709 // do_type.
9711 void
9712 Call_result_expression::do_check_types(Gogo*)
9714 this->type();
9717 // Determine the type. We have nothing to do here, but the 0 result
9718 // needs to pass down to the caller.
9720 void
9721 Call_result_expression::do_determine_type(const Type_context*)
9723 this->call_->determine_type_no_context();
9726 // Return the tree. We just refer to the temporary set by the call
9727 // expression. We don't do this at lowering time because it makes it
9728 // hard to evaluate the call at the right time.
9730 tree
9731 Call_result_expression::do_get_tree(Translate_context* context)
9733 Call_expression* ce = this->call_->call_expression();
9734 if (ce == NULL)
9736 go_assert(this->call_->is_error_expression());
9737 return error_mark_node;
9739 Temporary_statement* ts = ce->result(this->index_);
9740 if (ts == NULL)
9742 go_assert(saw_errors());
9743 return error_mark_node;
9745 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9746 return ref->get_tree(context);
9749 // Dump ast representation for a call result expression.
9751 void
9752 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9753 const
9755 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9756 // (struct) and the fields are referenced instead.
9757 ast_dump_context->ostream() << this->index_ << "@(";
9758 ast_dump_context->dump_expression(this->call_);
9759 ast_dump_context->ostream() << ")";
9762 // Make a reference to a single result of a call which returns
9763 // multiple results.
9765 Expression*
9766 Expression::make_call_result(Call_expression* call, unsigned int index)
9768 return new Call_result_expression(call, index);
9771 // Class Index_expression.
9773 // Traversal.
9776 Index_expression::do_traverse(Traverse* traverse)
9778 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9779 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9780 || (this->end_ != NULL
9781 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9782 || (this->cap_ != NULL
9783 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9784 return TRAVERSE_EXIT;
9785 return TRAVERSE_CONTINUE;
9788 // Lower an index expression. This converts the generic index
9789 // expression into an array index, a string index, or a map index.
9791 Expression*
9792 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9794 Location location = this->location();
9795 Expression* left = this->left_;
9796 Expression* start = this->start_;
9797 Expression* end = this->end_;
9798 Expression* cap = this->cap_;
9800 Type* type = left->type();
9801 if (type->is_error())
9802 return Expression::make_error(location);
9803 else if (left->is_type_expression())
9805 error_at(location, "attempt to index type expression");
9806 return Expression::make_error(location);
9808 else if (type->array_type() != NULL)
9809 return Expression::make_array_index(left, start, end, cap, location);
9810 else if (type->points_to() != NULL
9811 && type->points_to()->array_type() != NULL
9812 && !type->points_to()->is_slice_type())
9814 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9815 location);
9817 // For an ordinary index into the array, the pointer will be
9818 // dereferenced. For a slice it will not--the resulting slice
9819 // will simply reuse the pointer, which is incorrect if that
9820 // pointer is nil.
9821 if (end != NULL || cap != NULL)
9822 deref->issue_nil_check();
9824 return Expression::make_array_index(deref, start, end, cap, location);
9826 else if (type->is_string_type())
9828 if (cap != NULL)
9830 error_at(location, "invalid 3-index slice of string");
9831 return Expression::make_error(location);
9833 return Expression::make_string_index(left, start, end, location);
9835 else if (type->map_type() != NULL)
9837 if (end != NULL || cap != NULL)
9839 error_at(location, "invalid slice of map");
9840 return Expression::make_error(location);
9842 Map_index_expression* ret = Expression::make_map_index(left, start,
9843 location);
9844 if (this->is_lvalue_)
9845 ret->set_is_lvalue();
9846 return ret;
9848 else
9850 error_at(location,
9851 "attempt to index object which is not array, string, or map");
9852 return Expression::make_error(location);
9856 // Write an indexed expression
9857 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9859 void
9860 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9861 const Expression* expr,
9862 const Expression* start,
9863 const Expression* end,
9864 const Expression* cap)
9866 expr->dump_expression(ast_dump_context);
9867 ast_dump_context->ostream() << "[";
9868 start->dump_expression(ast_dump_context);
9869 if (end != NULL)
9871 ast_dump_context->ostream() << ":";
9872 end->dump_expression(ast_dump_context);
9874 if (cap != NULL)
9876 ast_dump_context->ostream() << ":";
9877 cap->dump_expression(ast_dump_context);
9879 ast_dump_context->ostream() << "]";
9882 // Dump ast representation for an index expression.
9884 void
9885 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9886 const
9888 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9889 this->start_, this->end_, this->cap_);
9892 // Make an index expression.
9894 Expression*
9895 Expression::make_index(Expression* left, Expression* start, Expression* end,
9896 Expression* cap, Location location)
9898 return new Index_expression(left, start, end, cap, location);
9901 // An array index. This is used for both indexing and slicing.
9903 class Array_index_expression : public Expression
9905 public:
9906 Array_index_expression(Expression* array, Expression* start,
9907 Expression* end, Expression* cap, Location location)
9908 : Expression(EXPRESSION_ARRAY_INDEX, location),
9909 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
9912 protected:
9914 do_traverse(Traverse*);
9916 Expression*
9917 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9919 Type*
9920 do_type();
9922 void
9923 do_determine_type(const Type_context*);
9925 void
9926 do_check_types(Gogo*);
9928 Expression*
9929 do_copy()
9931 return Expression::make_array_index(this->array_->copy(),
9932 this->start_->copy(),
9933 (this->end_ == NULL
9934 ? NULL
9935 : this->end_->copy()),
9936 (this->cap_ == NULL
9937 ? NULL
9938 : this->cap_->copy()),
9939 this->location());
9942 bool
9943 do_must_eval_subexpressions_in_order(int* skip) const
9945 *skip = 1;
9946 return true;
9949 bool
9950 do_is_addressable() const;
9952 void
9953 do_address_taken(bool escapes)
9954 { this->array_->address_taken(escapes); }
9956 void
9957 do_issue_nil_check()
9958 { this->array_->issue_nil_check(); }
9960 tree
9961 do_get_tree(Translate_context*);
9963 void
9964 do_dump_expression(Ast_dump_context*) const;
9966 private:
9967 // The array we are getting a value from.
9968 Expression* array_;
9969 // The start or only index.
9970 Expression* start_;
9971 // The end index of a slice. This may be NULL for a simple array
9972 // index, or it may be a nil expression for the length of the array.
9973 Expression* end_;
9974 // The capacity argument of a slice. This may be NULL for an array index or
9975 // slice.
9976 Expression* cap_;
9977 // The type of the expression.
9978 Type* type_;
9981 // Array index traversal.
9984 Array_index_expression::do_traverse(Traverse* traverse)
9986 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9987 return TRAVERSE_EXIT;
9988 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9989 return TRAVERSE_EXIT;
9990 if (this->end_ != NULL)
9992 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9993 return TRAVERSE_EXIT;
9995 if (this->cap_ != NULL)
9997 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9998 return TRAVERSE_EXIT;
10000 return TRAVERSE_CONTINUE;
10003 // Return the type of an array index.
10005 Type*
10006 Array_index_expression::do_type()
10008 if (this->type_ == NULL)
10010 Array_type* type = this->array_->type()->array_type();
10011 if (type == NULL)
10012 this->type_ = Type::make_error_type();
10013 else if (this->end_ == NULL)
10014 this->type_ = type->element_type();
10015 else if (type->is_slice_type())
10017 // A slice of a slice has the same type as the original
10018 // slice.
10019 this->type_ = this->array_->type()->deref();
10021 else
10023 // A slice of an array is a slice.
10024 this->type_ = Type::make_array_type(type->element_type(), NULL);
10027 return this->type_;
10030 // Set the type of an array index.
10032 void
10033 Array_index_expression::do_determine_type(const Type_context*)
10035 this->array_->determine_type_no_context();
10036 this->start_->determine_type_no_context();
10037 if (this->end_ != NULL)
10038 this->end_->determine_type_no_context();
10039 if (this->cap_ != NULL)
10040 this->cap_->determine_type_no_context();
10043 // Check types of an array index.
10045 void
10046 Array_index_expression::do_check_types(Gogo*)
10048 Numeric_constant nc;
10049 unsigned long v;
10050 if (this->start_->type()->integer_type() == NULL
10051 && !this->start_->type()->is_error()
10052 && (!this->start_->numeric_constant_value(&nc)
10053 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10054 this->report_error(_("index must be integer"));
10055 if (this->end_ != NULL
10056 && this->end_->type()->integer_type() == NULL
10057 && !this->end_->type()->is_error()
10058 && !this->end_->is_nil_expression()
10059 && !this->end_->is_error_expression()
10060 && (!this->end_->numeric_constant_value(&nc)
10061 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10062 this->report_error(_("slice end must be integer"));
10063 if (this->cap_ != NULL
10064 && this->cap_->type()->integer_type() == NULL
10065 && !this->cap_->type()->is_error()
10066 && !this->cap_->is_nil_expression()
10067 && !this->cap_->is_error_expression()
10068 && (!this->cap_->numeric_constant_value(&nc)
10069 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10070 this->report_error(_("slice capacity must be integer"));
10072 Array_type* array_type = this->array_->type()->array_type();
10073 if (array_type == NULL)
10075 go_assert(this->array_->type()->is_error());
10076 return;
10079 unsigned int int_bits =
10080 Type::lookup_integer_type("int")->integer_type()->bits();
10082 Numeric_constant lvalnc;
10083 mpz_t lval;
10084 bool lval_valid = (array_type->length() != NULL
10085 && array_type->length()->numeric_constant_value(&lvalnc)
10086 && lvalnc.to_int(&lval));
10087 Numeric_constant inc;
10088 mpz_t ival;
10089 bool ival_valid = false;
10090 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10092 ival_valid = true;
10093 if (mpz_sgn(ival) < 0
10094 || mpz_sizeinbase(ival, 2) >= int_bits
10095 || (lval_valid
10096 && (this->end_ == NULL
10097 ? mpz_cmp(ival, lval) >= 0
10098 : mpz_cmp(ival, lval) > 0)))
10100 error_at(this->start_->location(), "array index out of bounds");
10101 this->set_is_error();
10104 if (this->end_ != NULL && !this->end_->is_nil_expression())
10106 Numeric_constant enc;
10107 mpz_t eval;
10108 bool eval_valid = false;
10109 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10111 eval_valid = true;
10112 if (mpz_sgn(eval) < 0
10113 || mpz_sizeinbase(eval, 2) >= int_bits
10114 || (lval_valid && mpz_cmp(eval, lval) > 0))
10116 error_at(this->end_->location(), "array index out of bounds");
10117 this->set_is_error();
10119 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10120 this->report_error(_("inverted slice range"));
10123 Numeric_constant cnc;
10124 mpz_t cval;
10125 if (this->cap_ != NULL
10126 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10128 if (mpz_sgn(cval) < 0
10129 || mpz_sizeinbase(cval, 2) >= int_bits
10130 || (lval_valid && mpz_cmp(cval, lval) > 0))
10132 error_at(this->cap_->location(), "array index out of bounds");
10133 this->set_is_error();
10135 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10137 error_at(this->cap_->location(),
10138 "invalid slice index: capacity less than start");
10139 this->set_is_error();
10141 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10143 error_at(this->cap_->location(),
10144 "invalid slice index: capacity less than length");
10145 this->set_is_error();
10147 mpz_clear(cval);
10150 if (eval_valid)
10151 mpz_clear(eval);
10153 if (ival_valid)
10154 mpz_clear(ival);
10155 if (lval_valid)
10156 mpz_clear(lval);
10158 // A slice of an array requires an addressable array. A slice of a
10159 // slice is always possible.
10160 if (this->end_ != NULL && !array_type->is_slice_type())
10162 if (!this->array_->is_addressable())
10163 this->report_error(_("slice of unaddressable value"));
10164 else
10165 this->array_->address_taken(true);
10169 // Flatten array indexing by using temporary variables for slices and indexes.
10171 Expression*
10172 Array_index_expression::do_flatten(Gogo*, Named_object*,
10173 Statement_inserter* inserter)
10175 Location loc = this->location();
10176 Temporary_statement* temp;
10177 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10179 temp = Statement::make_temporary(NULL, this->array_, loc);
10180 inserter->insert(temp);
10181 this->array_ = Expression::make_temporary_reference(temp, loc);
10183 if (!this->start_->is_variable())
10185 temp = Statement::make_temporary(NULL, this->start_, loc);
10186 inserter->insert(temp);
10187 this->start_ = Expression::make_temporary_reference(temp, loc);
10189 if (this->end_ != NULL
10190 && !this->end_->is_nil_expression()
10191 && !this->end_->is_variable())
10193 temp = Statement::make_temporary(NULL, this->end_, loc);
10194 inserter->insert(temp);
10195 this->end_ = Expression::make_temporary_reference(temp, loc);
10197 if (this->cap_ != NULL && !this->cap_->is_variable())
10199 temp = Statement::make_temporary(NULL, this->cap_, loc);
10200 inserter->insert(temp);
10201 this->cap_ = Expression::make_temporary_reference(temp, loc);
10204 return this;
10207 // Return whether this expression is addressable.
10209 bool
10210 Array_index_expression::do_is_addressable() const
10212 // A slice expression is not addressable.
10213 if (this->end_ != NULL)
10214 return false;
10216 // An index into a slice is addressable.
10217 if (this->array_->type()->is_slice_type())
10218 return true;
10220 // An index into an array is addressable if the array is
10221 // addressable.
10222 return this->array_->is_addressable();
10225 // Get a tree for an array index.
10227 tree
10228 Array_index_expression::do_get_tree(Translate_context* context)
10230 Array_type* array_type = this->array_->type()->array_type();
10231 if (array_type == NULL)
10233 go_assert(this->array_->type()->is_error());
10234 return error_mark_node;
10236 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10238 Location loc = this->location();
10239 Gogo* gogo = context->gogo();
10241 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
10243 // We need to convert the length and capacity to the Go "int" type here
10244 // because the length of a fixed-length array could be of type "uintptr"
10245 // and gimple disallows binary operations between "uintptr" and other
10246 // integer types. FIXME.
10247 Bexpression* length = NULL;
10248 if (this->end_ == NULL || this->end_->is_nil_expression())
10250 Expression* len = array_type->get_length(gogo, this->array_);
10251 length = tree_to_expr(len->get_tree(context));
10252 length = gogo->backend()->convert_expression(int_btype, length, loc);
10255 Bexpression* capacity = NULL;
10256 if (this->end_ != NULL)
10258 Expression* cap = array_type->get_capacity(gogo, this->array_);
10259 capacity = tree_to_expr(cap->get_tree(context));
10260 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10263 Bexpression* cap_arg = capacity;
10264 if (this->cap_ != NULL)
10266 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10267 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10270 if (length == NULL)
10271 length = cap_arg;
10273 int code = (array_type->length() != NULL
10274 ? (this->end_ == NULL
10275 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10276 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10277 : (this->end_ == NULL
10278 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10279 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10280 Bexpression* crash =
10281 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10283 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10284 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10286 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10287 start = gogo->backend()->convert_expression(int_btype, start, loc);
10288 Bexpression* start_too_large =
10289 gogo->backend()->binary_expression((this->end_ == NULL
10290 ? OPERATOR_GE
10291 : OPERATOR_GT),
10292 start,
10293 (this->end_ == NULL
10294 ? length
10295 : capacity),
10296 loc);
10297 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10298 bad_index, loc);
10300 if (this->end_ == NULL)
10302 // Simple array indexing. This has to return an l-value, so
10303 // wrap the index check into START.
10304 start =
10305 gogo->backend()->conditional_expression(int_btype, bad_index,
10306 crash, start, loc);
10308 Bexpression* ret;
10309 if (array_type->length() != NULL)
10311 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10312 ret = gogo->backend()->array_index_expression(array, start, loc);
10314 else
10316 // Slice.
10317 Expression* valptr =
10318 array_type->get_value_pointer(gogo, this->array_);
10319 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10320 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10321 ret = gogo->backend()->indirect_expression(ptr, true, loc);
10323 return expr_to_tree(ret);
10326 // Array slice.
10328 if (this->cap_ != NULL)
10330 bounds_check = Expression::check_bounds(this->cap_, loc);
10331 Bexpression* bounds_bcheck =
10332 tree_to_expr(bounds_check->get_tree(context));
10333 bad_index =
10334 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10335 bad_index, loc);
10336 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10338 Bexpression* cap_too_small =
10339 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10340 Bexpression* cap_too_large =
10341 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10342 Bexpression* bad_cap =
10343 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10344 cap_too_large, loc);
10345 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10346 bad_index, loc);
10349 Bexpression* end;
10350 if (this->end_->is_nil_expression())
10351 end = length;
10352 else
10354 bounds_check = Expression::check_bounds(this->end_, loc);
10355 Bexpression* bounds_bcheck =
10356 tree_to_expr(bounds_check->get_tree(context));
10358 bad_index =
10359 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10360 bad_index, loc);
10362 end = tree_to_expr(this->end_->get_tree(context));
10363 end = gogo->backend()->convert_expression(int_btype, end, loc);
10364 Bexpression* end_too_small =
10365 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10366 Bexpression* end_too_large =
10367 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10368 Bexpression* bad_end =
10369 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10370 end_too_large, loc);
10371 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10372 bad_index, loc);
10375 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10376 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10377 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10379 Bexpression* result_length =
10380 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10382 Bexpression* result_capacity =
10383 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10385 Btype* struct_btype = this->type()->get_backend(gogo);
10386 std::vector<Bexpression*> init;
10387 init.push_back(val);
10388 init.push_back(result_length);
10389 init.push_back(result_capacity);
10391 Bexpression* ctor =
10392 gogo->backend()->constructor_expression(struct_btype, init, loc);
10393 Bexpression* ret =
10394 gogo->backend()->conditional_expression(struct_btype, bad_index,
10395 crash, ctor, loc);
10397 return expr_to_tree(ret);
10400 // Dump ast representation for an array index expression.
10402 void
10403 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10404 const
10406 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10407 this->start_, this->end_, this->cap_);
10410 // Make an array index expression. END and CAP may be NULL.
10412 Expression*
10413 Expression::make_array_index(Expression* array, Expression* start,
10414 Expression* end, Expression* cap,
10415 Location location)
10417 return new Array_index_expression(array, start, end, cap, location);
10420 // A string index. This is used for both indexing and slicing.
10422 class String_index_expression : public Expression
10424 public:
10425 String_index_expression(Expression* string, Expression* start,
10426 Expression* end, Location location)
10427 : Expression(EXPRESSION_STRING_INDEX, location),
10428 string_(string), start_(start), end_(end)
10431 protected:
10433 do_traverse(Traverse*);
10435 Expression*
10436 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10438 Type*
10439 do_type();
10441 void
10442 do_determine_type(const Type_context*);
10444 void
10445 do_check_types(Gogo*);
10447 Expression*
10448 do_copy()
10450 return Expression::make_string_index(this->string_->copy(),
10451 this->start_->copy(),
10452 (this->end_ == NULL
10453 ? NULL
10454 : this->end_->copy()),
10455 this->location());
10458 bool
10459 do_must_eval_subexpressions_in_order(int* skip) const
10461 *skip = 1;
10462 return true;
10465 tree
10466 do_get_tree(Translate_context*);
10468 void
10469 do_dump_expression(Ast_dump_context*) const;
10471 private:
10472 // The string we are getting a value from.
10473 Expression* string_;
10474 // The start or only index.
10475 Expression* start_;
10476 // The end index of a slice. This may be NULL for a single index,
10477 // or it may be a nil expression for the length of the string.
10478 Expression* end_;
10481 // String index traversal.
10484 String_index_expression::do_traverse(Traverse* traverse)
10486 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10487 return TRAVERSE_EXIT;
10488 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10489 return TRAVERSE_EXIT;
10490 if (this->end_ != NULL)
10492 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10493 return TRAVERSE_EXIT;
10495 return TRAVERSE_CONTINUE;
10498 Expression*
10499 String_index_expression::do_flatten(Gogo*, Named_object*,
10500 Statement_inserter* inserter)
10502 Temporary_statement* temp;
10503 Location loc = this->location();
10504 if (!this->string_->is_variable())
10506 temp = Statement::make_temporary(NULL, this->string_, loc);
10507 inserter->insert(temp);
10508 this->string_ = Expression::make_temporary_reference(temp, loc);
10510 if (!this->start_->is_variable())
10512 temp = Statement::make_temporary(NULL, this->start_, loc);
10513 inserter->insert(temp);
10514 this->start_ = Expression::make_temporary_reference(temp, loc);
10516 if (this->end_ != NULL
10517 && !this->end_->is_nil_expression()
10518 && !this->end_->is_variable())
10520 temp = Statement::make_temporary(NULL, this->end_, loc);
10521 inserter->insert(temp);
10522 this->end_ = Expression::make_temporary_reference(temp, loc);
10525 return this;
10528 // Return the type of a string index.
10530 Type*
10531 String_index_expression::do_type()
10533 if (this->end_ == NULL)
10534 return Type::lookup_integer_type("uint8");
10535 else
10536 return this->string_->type();
10539 // Determine the type of a string index.
10541 void
10542 String_index_expression::do_determine_type(const Type_context*)
10544 this->string_->determine_type_no_context();
10545 this->start_->determine_type_no_context();
10546 if (this->end_ != NULL)
10547 this->end_->determine_type_no_context();
10550 // Check types of a string index.
10552 void
10553 String_index_expression::do_check_types(Gogo*)
10555 Numeric_constant nc;
10556 unsigned long v;
10557 if (this->start_->type()->integer_type() == NULL
10558 && !this->start_->type()->is_error()
10559 && (!this->start_->numeric_constant_value(&nc)
10560 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10561 this->report_error(_("index must be integer"));
10562 if (this->end_ != NULL
10563 && this->end_->type()->integer_type() == NULL
10564 && !this->end_->type()->is_error()
10565 && !this->end_->is_nil_expression()
10566 && !this->end_->is_error_expression()
10567 && (!this->end_->numeric_constant_value(&nc)
10568 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10569 this->report_error(_("slice end must be integer"));
10571 std::string sval;
10572 bool sval_valid = this->string_->string_constant_value(&sval);
10574 Numeric_constant inc;
10575 mpz_t ival;
10576 bool ival_valid = false;
10577 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10579 ival_valid = true;
10580 if (mpz_sgn(ival) < 0
10581 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10583 error_at(this->start_->location(), "string index out of bounds");
10584 this->set_is_error();
10587 if (this->end_ != NULL && !this->end_->is_nil_expression())
10589 Numeric_constant enc;
10590 mpz_t eval;
10591 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10593 if (mpz_sgn(eval) < 0
10594 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10596 error_at(this->end_->location(), "string index out of bounds");
10597 this->set_is_error();
10599 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10600 this->report_error(_("inverted slice range"));
10601 mpz_clear(eval);
10604 if (ival_valid)
10605 mpz_clear(ival);
10608 // Get a tree for a string index.
10610 tree
10611 String_index_expression::do_get_tree(Translate_context* context)
10613 Location loc = this->location();
10614 Expression* string_arg = this->string_;
10615 if (this->string_->type()->points_to() != NULL)
10616 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10618 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10620 int code = (this->end_ == NULL
10621 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10622 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10624 Gogo* gogo = context->gogo();
10625 Bexpression* crash =
10626 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10628 Type* int_type = Type::lookup_integer_type("int");
10630 // It is possible that an error occurred earlier because the start index
10631 // cannot be represented as an integer type. In this case, we shouldn't
10632 // try casting the starting index into an integer since
10633 // Type_conversion_expression will fail to get the backend representation.
10634 // FIXME.
10635 if (this->start_->type()->integer_type() == NULL
10636 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10638 go_assert(saw_errors());
10639 return error_mark_node;
10642 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10644 if (this->end_ == NULL)
10646 Expression* length =
10647 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10649 Expression* start_too_large =
10650 Expression::make_binary(OPERATOR_GE, start, length, loc);
10651 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10652 bad_index, loc);
10653 Expression* bytes =
10654 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10656 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10657 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10658 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10659 Bexpression* index = gogo->backend()->indirect_expression(ptr, true, loc);
10661 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10662 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10663 Bexpression* ret =
10664 gogo->backend()->conditional_expression(byte_btype, index_error,
10665 crash, index, loc);
10666 return expr_to_tree(ret);
10669 Expression* end = NULL;
10670 if (this->end_->is_nil_expression())
10672 mpz_t neg_one;
10673 mpz_init_set_si(neg_one, -1);
10674 end = Expression::make_integer(&neg_one, int_type, loc);
10675 mpz_clear(neg_one);
10677 else
10679 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10680 bad_index =
10681 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10682 end = Expression::make_cast(int_type, this->end_, loc);
10685 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10686 string_arg, start, end);
10687 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10689 Btype* str_btype = strslice->type()->get_backend(gogo);
10690 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10691 Bexpression* ret =
10692 gogo->backend()->conditional_expression(str_btype, index_error,
10693 crash, bstrslice, loc);
10694 return expr_to_tree(ret);
10697 // Dump ast representation for a string index expression.
10699 void
10700 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10701 const
10703 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10704 this->start_, this->end_, NULL);
10707 // Make a string index expression. END may be NULL.
10709 Expression*
10710 Expression::make_string_index(Expression* string, Expression* start,
10711 Expression* end, Location location)
10713 return new String_index_expression(string, start, end, location);
10716 // Class Map_index.
10718 // Get the type of the map.
10720 Map_type*
10721 Map_index_expression::get_map_type() const
10723 Map_type* mt = this->map_->type()->deref()->map_type();
10724 if (mt == NULL)
10725 go_assert(saw_errors());
10726 return mt;
10729 // Map index traversal.
10732 Map_index_expression::do_traverse(Traverse* traverse)
10734 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10735 return TRAVERSE_EXIT;
10736 return Expression::traverse(&this->index_, traverse);
10739 // We need to pass in a pointer to the key, so flatten the index into a
10740 // temporary variable if it isn't already. The value pointer will be
10741 // dereferenced and checked for nil, so flatten into a temporary to avoid
10742 // recomputation.
10744 Expression*
10745 Map_index_expression::do_flatten(Gogo*, Named_object*,
10746 Statement_inserter* inserter)
10748 Map_type* mt = this->get_map_type();
10749 if (this->index_->type() != mt->key_type())
10750 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10751 this->location());
10753 if (!this->index_->is_variable())
10755 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10756 this->location());
10757 inserter->insert(temp);
10758 this->index_ = Expression::make_temporary_reference(temp,
10759 this->location());
10762 if (this->value_pointer_ == NULL)
10763 this->get_value_pointer(this->is_lvalue_);
10764 if (!this->value_pointer_->is_variable())
10766 Temporary_statement* temp =
10767 Statement::make_temporary(NULL, this->value_pointer_,
10768 this->location());
10769 inserter->insert(temp);
10770 this->value_pointer_ =
10771 Expression::make_temporary_reference(temp, this->location());
10774 return this;
10777 // Return the type of a map index.
10779 Type*
10780 Map_index_expression::do_type()
10782 Map_type* mt = this->get_map_type();
10783 if (mt == NULL)
10784 return Type::make_error_type();
10785 Type* type = mt->val_type();
10786 // If this map index is in a tuple assignment, we actually return a
10787 // pointer to the value type. Tuple_map_assignment_statement is
10788 // responsible for handling this correctly. We need to get the type
10789 // right in case this gets assigned to a temporary variable.
10790 if (this->is_in_tuple_assignment_)
10791 type = Type::make_pointer_type(type);
10792 return type;
10795 // Fix the type of a map index.
10797 void
10798 Map_index_expression::do_determine_type(const Type_context*)
10800 this->map_->determine_type_no_context();
10801 Map_type* mt = this->get_map_type();
10802 Type* key_type = mt == NULL ? NULL : mt->key_type();
10803 Type_context subcontext(key_type, false);
10804 this->index_->determine_type(&subcontext);
10807 // Check types of a map index.
10809 void
10810 Map_index_expression::do_check_types(Gogo*)
10812 std::string reason;
10813 Map_type* mt = this->get_map_type();
10814 if (mt == NULL)
10815 return;
10816 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10818 if (reason.empty())
10819 this->report_error(_("incompatible type for map index"));
10820 else
10822 error_at(this->location(), "incompatible type for map index (%s)",
10823 reason.c_str());
10824 this->set_is_error();
10829 // Get a tree for a map index.
10831 tree
10832 Map_index_expression::do_get_tree(Translate_context* context)
10834 Map_type* type = this->get_map_type();
10835 if (type == NULL)
10837 go_assert(saw_errors());
10838 return error_mark_node;
10841 go_assert(this->value_pointer_ != NULL
10842 && this->value_pointer_->is_variable());
10844 Bexpression* ret;
10845 if (this->is_lvalue_)
10847 Expression* val =
10848 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10849 this->location());
10850 ret = tree_to_expr(val->get_tree(context));
10852 else if (this->is_in_tuple_assignment_)
10854 // Tuple_map_assignment_statement is responsible for using this
10855 // appropriately.
10856 ret = tree_to_expr(this->value_pointer_->get_tree(context));
10858 else
10860 Location loc = this->location();
10862 Expression* nil_check =
10863 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10864 Expression::make_nil(loc), loc);
10865 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10866 Expression* val =
10867 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10868 Bexpression* bval = tree_to_expr(val->get_tree(context));
10870 Gogo* gogo = context->gogo();
10871 Btype* val_btype = type->val_type()->get_backend(gogo);
10872 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10873 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10874 val_zero, bval, loc);
10877 return expr_to_tree(ret);
10880 // Get an expression for the map index. This returns an expression which
10881 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10882 // not in the map.
10884 Expression*
10885 Map_index_expression::get_value_pointer(bool insert)
10887 if (this->value_pointer_ == NULL)
10889 Map_type* type = this->get_map_type();
10890 if (type == NULL)
10892 go_assert(saw_errors());
10893 return Expression::make_error(this->location());
10896 Location loc = this->location();
10897 Expression* map_ref = this->map_;
10898 if (this->map_->type()->points_to() != NULL)
10899 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10901 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10902 loc);
10903 Expression* map_index =
10904 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10905 map_ref, index_ptr,
10906 Expression::make_boolean(insert, loc));
10908 Type* val_type = type->val_type();
10909 this->value_pointer_ =
10910 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10911 map_index, this->location());
10913 return this->value_pointer_;
10916 // Dump ast representation for a map index expression
10918 void
10919 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10920 const
10922 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10923 this->index_, NULL, NULL);
10926 // Make a map index expression.
10928 Map_index_expression*
10929 Expression::make_map_index(Expression* map, Expression* index,
10930 Location location)
10932 return new Map_index_expression(map, index, location);
10935 // Class Field_reference_expression.
10937 // Lower a field reference expression. There is nothing to lower, but
10938 // this is where we generate the tracking information for fields with
10939 // the magic go:"track" tag.
10941 Expression*
10942 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10943 Statement_inserter* inserter, int)
10945 Struct_type* struct_type = this->expr_->type()->struct_type();
10946 if (struct_type == NULL)
10948 // Error will be reported elsewhere.
10949 return this;
10951 const Struct_field* field = struct_type->field(this->field_index_);
10952 if (field == NULL)
10953 return this;
10954 if (!field->has_tag())
10955 return this;
10956 if (field->tag().find("go:\"track\"") == std::string::npos)
10957 return this;
10959 // We have found a reference to a tracked field. Build a call to
10960 // the runtime function __go_fieldtrack with a string that describes
10961 // the field. FIXME: We should only call this once per referenced
10962 // field per function, not once for each reference to the field.
10964 if (this->called_fieldtrack_)
10965 return this;
10966 this->called_fieldtrack_ = true;
10968 Location loc = this->location();
10970 std::string s = "fieldtrack \"";
10971 Named_type* nt = this->expr_->type()->named_type();
10972 if (nt == NULL || nt->named_object()->package() == NULL)
10973 s.append(gogo->pkgpath());
10974 else
10975 s.append(nt->named_object()->package()->pkgpath());
10976 s.push_back('.');
10977 if (nt != NULL)
10978 s.append(Gogo::unpack_hidden_name(nt->name()));
10979 s.push_back('.');
10980 s.append(field->field_name());
10981 s.push_back('"');
10983 // We can't use a string here, because internally a string holds a
10984 // pointer to the actual bytes; when the linker garbage collects the
10985 // string, it won't garbage collect the bytes. So we use a
10986 // [...]byte.
10988 mpz_t val;
10989 mpz_init_set_ui(val, s.length());
10990 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
10991 mpz_clear(val);
10993 Type* byte_type = gogo->lookup_global("byte")->type_value();
10994 Type* array_type = Type::make_array_type(byte_type, length_expr);
10996 Expression_list* bytes = new Expression_list();
10997 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10999 mpz_init_set_ui(val, *p);
11000 Expression* byte = Expression::make_integer(&val, NULL, loc);
11001 mpz_clear(val);
11002 bytes->push_back(byte);
11005 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11006 bytes, false, loc);
11008 Variable* var = new Variable(array_type, e, true, false, false, loc);
11010 static int count;
11011 char buf[50];
11012 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11013 ++count;
11015 Named_object* no = gogo->add_variable(buf, var);
11016 e = Expression::make_var_reference(no, loc);
11017 e = Expression::make_unary(OPERATOR_AND, e, loc);
11019 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11020 inserter->insert(Statement::make_statement(call, false));
11022 // Put this function, and the global variable we just created, into
11023 // unique sections. This will permit the linker to garbage collect
11024 // them if they are not referenced. The effect is that the only
11025 // strings, indicating field references, that will wind up in the
11026 // executable will be those for functions that are actually needed.
11027 if (function != NULL)
11028 function->func_value()->set_in_unique_section();
11029 var->set_in_unique_section();
11031 return this;
11034 // Return the type of a field reference.
11036 Type*
11037 Field_reference_expression::do_type()
11039 Type* type = this->expr_->type();
11040 if (type->is_error())
11041 return type;
11042 Struct_type* struct_type = type->struct_type();
11043 go_assert(struct_type != NULL);
11044 return struct_type->field(this->field_index_)->type();
11047 // Check the types for a field reference.
11049 void
11050 Field_reference_expression::do_check_types(Gogo*)
11052 Type* type = this->expr_->type();
11053 if (type->is_error())
11054 return;
11055 Struct_type* struct_type = type->struct_type();
11056 go_assert(struct_type != NULL);
11057 go_assert(struct_type->field(this->field_index_) != NULL);
11060 // Get a tree for a field reference.
11062 tree
11063 Field_reference_expression::do_get_tree(Translate_context* context)
11065 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11066 Bexpression* ret =
11067 context->gogo()->backend()->struct_field_expression(bstruct,
11068 this->field_index_,
11069 this->location());
11070 return expr_to_tree(ret);
11073 // Dump ast representation for a field reference expression.
11075 void
11076 Field_reference_expression::do_dump_expression(
11077 Ast_dump_context* ast_dump_context) const
11079 this->expr_->dump_expression(ast_dump_context);
11080 ast_dump_context->ostream() << "." << this->field_index_;
11083 // Make a reference to a qualified identifier in an expression.
11085 Field_reference_expression*
11086 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11087 Location location)
11089 return new Field_reference_expression(expr, field_index, location);
11092 // Class Interface_field_reference_expression.
11094 // Return an expression for the pointer to the function to call.
11096 Expression*
11097 Interface_field_reference_expression::get_function()
11099 Expression* ref = this->expr_;
11100 Location loc = this->location();
11101 if (ref->type()->points_to() != NULL)
11102 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11104 Expression* mtable =
11105 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11106 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11108 std::string name = Gogo::unpack_hidden_name(this->name_);
11109 unsigned int index;
11110 const Struct_field* field = mtable_type->find_local_field(name, &index);
11111 go_assert(field != NULL);
11112 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11113 return Expression::make_field_reference(mtable, index, loc);
11116 // Return an expression for the first argument to pass to the interface
11117 // function.
11119 Expression*
11120 Interface_field_reference_expression::get_underlying_object()
11122 Expression* expr = this->expr_;
11123 if (expr->type()->points_to() != NULL)
11124 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11125 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11126 this->location());
11129 // Traversal.
11132 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11134 return Expression::traverse(&this->expr_, traverse);
11137 // Lower the expression. If this expression is not called, we need to
11138 // evaluate the expression twice when converting to the backend
11139 // interface. So introduce a temporary variable if necessary.
11141 Expression*
11142 Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11143 Statement_inserter* inserter,
11144 int)
11146 if (!this->expr_->is_variable())
11148 Temporary_statement* temp =
11149 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11150 inserter->insert(temp);
11151 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11152 this->location());
11154 return this;
11157 // Return the type of an interface field reference.
11159 Type*
11160 Interface_field_reference_expression::do_type()
11162 Type* expr_type = this->expr_->type();
11164 Type* points_to = expr_type->points_to();
11165 if (points_to != NULL)
11166 expr_type = points_to;
11168 Interface_type* interface_type = expr_type->interface_type();
11169 if (interface_type == NULL)
11170 return Type::make_error_type();
11172 const Typed_identifier* method = interface_type->find_method(this->name_);
11173 if (method == NULL)
11174 return Type::make_error_type();
11176 return method->type();
11179 // Determine types.
11181 void
11182 Interface_field_reference_expression::do_determine_type(const Type_context*)
11184 this->expr_->determine_type_no_context();
11187 // Check the types for an interface field reference.
11189 void
11190 Interface_field_reference_expression::do_check_types(Gogo*)
11192 Type* type = this->expr_->type();
11194 Type* points_to = type->points_to();
11195 if (points_to != NULL)
11196 type = points_to;
11198 Interface_type* interface_type = type->interface_type();
11199 if (interface_type == NULL)
11201 if (!type->is_error_type())
11202 this->report_error(_("expected interface or pointer to interface"));
11204 else
11206 const Typed_identifier* method =
11207 interface_type->find_method(this->name_);
11208 if (method == NULL)
11210 error_at(this->location(), "method %qs not in interface",
11211 Gogo::message_name(this->name_).c_str());
11212 this->set_is_error();
11217 // If an interface field reference is not simply called, then it is
11218 // represented as a closure. The closure will hold a single variable,
11219 // the value of the interface on which the method should be called.
11220 // The function will be a simple thunk that pulls the value from the
11221 // closure and calls the method with the remaining arguments.
11223 // Because method values are not common, we don't build all thunks for
11224 // all possible interface methods, but instead only build them as we
11225 // need them. In particular, we even build them on demand for
11226 // interface methods defined in other packages.
11228 Interface_field_reference_expression::Interface_method_thunks
11229 Interface_field_reference_expression::interface_method_thunks;
11231 // Find or create the thunk to call method NAME on TYPE.
11233 Named_object*
11234 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11235 Interface_type* type,
11236 const std::string& name)
11238 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11239 std::pair<Interface_method_thunks::iterator, bool> ins =
11240 Interface_field_reference_expression::interface_method_thunks.insert(val);
11241 if (ins.second)
11243 // This is the first time we have seen this interface.
11244 ins.first->second = new Method_thunks();
11247 for (Method_thunks::const_iterator p = ins.first->second->begin();
11248 p != ins.first->second->end();
11249 p++)
11250 if (p->first == name)
11251 return p->second;
11253 Location loc = type->location();
11255 const Typed_identifier* method_id = type->find_method(name);
11256 if (method_id == NULL)
11257 return Named_object::make_erroneous_name(Gogo::thunk_name());
11259 Function_type* orig_fntype = method_id->type()->function_type();
11260 if (orig_fntype == NULL)
11261 return Named_object::make_erroneous_name(Gogo::thunk_name());
11263 Struct_field_list* sfl = new Struct_field_list();
11264 // The type here is wrong--it should be the C function type. But it
11265 // doesn't really matter.
11266 Type* vt = Type::make_pointer_type(Type::make_void_type());
11267 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11268 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11269 Type* closure_type = Type::make_struct_type(sfl, loc);
11270 closure_type = Type::make_pointer_type(closure_type);
11272 Function_type* new_fntype = orig_fntype->copy_with_names();
11274 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11275 false, loc);
11277 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11278 cvar->set_is_used();
11279 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11280 new_no->func_value()->set_closure_var(cp);
11282 gogo->start_block(loc);
11284 // Field 0 of the closure is the function code pointer, field 1 is
11285 // the value on which to invoke the method.
11286 Expression* arg = Expression::make_var_reference(cp, loc);
11287 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11288 arg = Expression::make_field_reference(arg, 1, loc);
11290 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11291 loc);
11293 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11294 Expression_list* args;
11295 if (orig_params == NULL || orig_params->empty())
11296 args = NULL;
11297 else
11299 const Typed_identifier_list* new_params = new_fntype->parameters();
11300 args = new Expression_list();
11301 for (Typed_identifier_list::const_iterator p = new_params->begin();
11302 p != new_params->end();
11303 ++p)
11305 Named_object* p_no = gogo->lookup(p->name(), NULL);
11306 go_assert(p_no != NULL
11307 && p_no->is_variable()
11308 && p_no->var_value()->is_parameter());
11309 args->push_back(Expression::make_var_reference(p_no, loc));
11313 Call_expression* call = Expression::make_call(ifre, args,
11314 orig_fntype->is_varargs(),
11315 loc);
11316 call->set_varargs_are_lowered();
11318 Statement* s = Statement::make_return_from_call(call, loc);
11319 gogo->add_statement(s);
11320 Block* b = gogo->finish_block(loc);
11321 gogo->add_block(b, loc);
11322 gogo->lower_block(new_no, b);
11323 gogo->flatten_block(new_no, b);
11324 gogo->finish_function(loc);
11326 ins.first->second->push_back(std::make_pair(name, new_no));
11327 return new_no;
11330 // Get a tree for a method value.
11332 tree
11333 Interface_field_reference_expression::do_get_tree(Translate_context* context)
11335 Interface_type* type = this->expr_->type()->interface_type();
11336 if (type == NULL)
11338 go_assert(saw_errors());
11339 return error_mark_node;
11342 Named_object* thunk =
11343 Interface_field_reference_expression::create_thunk(context->gogo(),
11344 type, this->name_);
11345 if (thunk->is_erroneous())
11347 go_assert(saw_errors());
11348 return error_mark_node;
11351 // FIXME: We should lower this earlier, but we can't it lower it in
11352 // the lowering pass because at that point we don't know whether we
11353 // need to create the thunk or not. If the expression is called, we
11354 // don't need the thunk.
11356 Location loc = this->location();
11358 Struct_field_list* fields = new Struct_field_list();
11359 fields->push_back(Struct_field(Typed_identifier("fn.0",
11360 thunk->func_value()->type(),
11361 loc)));
11362 fields->push_back(Struct_field(Typed_identifier("val.1",
11363 this->expr_->type(),
11364 loc)));
11365 Struct_type* st = Type::make_struct_type(fields, loc);
11367 Expression_list* vals = new Expression_list();
11368 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11369 vals->push_back(this->expr_);
11371 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11372 expr = Expression::make_heap_expression(expr, loc);
11374 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11375 Expression* nil_check =
11376 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11377 Expression::make_nil(loc), loc);
11378 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
11380 Gogo* gogo = context->gogo();
11381 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11382 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11384 Bexpression* bcond =
11385 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11386 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11387 Bexpression* ret =
11388 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11389 return expr_to_tree(ret);
11392 // Dump ast representation for an interface field reference.
11394 void
11395 Interface_field_reference_expression::do_dump_expression(
11396 Ast_dump_context* ast_dump_context) const
11398 this->expr_->dump_expression(ast_dump_context);
11399 ast_dump_context->ostream() << "." << this->name_;
11402 // Make a reference to a field in an interface.
11404 Expression*
11405 Expression::make_interface_field_reference(Expression* expr,
11406 const std::string& field,
11407 Location location)
11409 return new Interface_field_reference_expression(expr, field, location);
11412 // A general selector. This is a Parser_expression for LEFT.NAME. It
11413 // is lowered after we know the type of the left hand side.
11415 class Selector_expression : public Parser_expression
11417 public:
11418 Selector_expression(Expression* left, const std::string& name,
11419 Location location)
11420 : Parser_expression(EXPRESSION_SELECTOR, location),
11421 left_(left), name_(name)
11424 protected:
11426 do_traverse(Traverse* traverse)
11427 { return Expression::traverse(&this->left_, traverse); }
11429 Expression*
11430 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11432 Expression*
11433 do_copy()
11435 return new Selector_expression(this->left_->copy(), this->name_,
11436 this->location());
11439 void
11440 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11442 private:
11443 Expression*
11444 lower_method_expression(Gogo*);
11446 // The expression on the left hand side.
11447 Expression* left_;
11448 // The name on the right hand side.
11449 std::string name_;
11452 // Lower a selector expression once we know the real type of the left
11453 // hand side.
11455 Expression*
11456 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11457 int)
11459 Expression* left = this->left_;
11460 if (left->is_type_expression())
11461 return this->lower_method_expression(gogo);
11462 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11463 this->location());
11466 // Lower a method expression T.M or (*T).M. We turn this into a
11467 // function literal.
11469 Expression*
11470 Selector_expression::lower_method_expression(Gogo* gogo)
11472 Location location = this->location();
11473 Type* type = this->left_->type();
11474 const std::string& name(this->name_);
11476 bool is_pointer;
11477 if (type->points_to() == NULL)
11478 is_pointer = false;
11479 else
11481 is_pointer = true;
11482 type = type->points_to();
11484 Named_type* nt = type->named_type();
11485 if (nt == NULL)
11487 error_at(location,
11488 ("method expression requires named type or "
11489 "pointer to named type"));
11490 return Expression::make_error(location);
11493 bool is_ambiguous;
11494 Method* method = nt->method_function(name, &is_ambiguous);
11495 const Typed_identifier* imethod = NULL;
11496 if (method == NULL && !is_pointer)
11498 Interface_type* it = nt->interface_type();
11499 if (it != NULL)
11500 imethod = it->find_method(name);
11503 if (method == NULL && imethod == NULL)
11505 if (!is_ambiguous)
11506 error_at(location, "type %<%s%s%> has no method %<%s%>",
11507 is_pointer ? "*" : "",
11508 nt->message_name().c_str(),
11509 Gogo::message_name(name).c_str());
11510 else
11511 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11512 Gogo::message_name(name).c_str(),
11513 is_pointer ? "*" : "",
11514 nt->message_name().c_str());
11515 return Expression::make_error(location);
11518 if (method != NULL && !is_pointer && !method->is_value_method())
11520 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11521 nt->message_name().c_str(),
11522 Gogo::message_name(name).c_str());
11523 return Expression::make_error(location);
11526 // Build a new function type in which the receiver becomes the first
11527 // argument.
11528 Function_type* method_type;
11529 if (method != NULL)
11531 method_type = method->type();
11532 go_assert(method_type->is_method());
11534 else
11536 method_type = imethod->type()->function_type();
11537 go_assert(method_type != NULL && !method_type->is_method());
11540 const char* const receiver_name = "$this";
11541 Typed_identifier_list* parameters = new Typed_identifier_list();
11542 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11543 location));
11545 const Typed_identifier_list* method_parameters = method_type->parameters();
11546 if (method_parameters != NULL)
11548 int i = 0;
11549 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11550 p != method_parameters->end();
11551 ++p, ++i)
11553 if (!p->name().empty())
11554 parameters->push_back(*p);
11555 else
11557 char buf[20];
11558 snprintf(buf, sizeof buf, "$param%d", i);
11559 parameters->push_back(Typed_identifier(buf, p->type(),
11560 p->location()));
11565 const Typed_identifier_list* method_results = method_type->results();
11566 Typed_identifier_list* results;
11567 if (method_results == NULL)
11568 results = NULL;
11569 else
11571 results = new Typed_identifier_list();
11572 for (Typed_identifier_list::const_iterator p = method_results->begin();
11573 p != method_results->end();
11574 ++p)
11575 results->push_back(*p);
11578 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11579 location);
11580 if (method_type->is_varargs())
11581 fntype->set_is_varargs();
11583 // We generate methods which always takes a pointer to the receiver
11584 // as their first argument. If this is for a pointer type, we can
11585 // simply reuse the existing function. We use an internal hack to
11586 // get the right type.
11587 // FIXME: This optimization is disabled because it doesn't yet work
11588 // with function descriptors when the method expression is not
11589 // directly called.
11590 if (method != NULL && is_pointer && false)
11592 Named_object* mno = (method->needs_stub_method()
11593 ? method->stub_object()
11594 : method->named_object());
11595 Expression* f = Expression::make_func_reference(mno, NULL, location);
11596 f = Expression::make_cast(fntype, f, location);
11597 Type_conversion_expression* tce =
11598 static_cast<Type_conversion_expression*>(f);
11599 tce->set_may_convert_function_types();
11600 return f;
11603 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11604 location);
11606 Named_object* vno = gogo->lookup(receiver_name, NULL);
11607 go_assert(vno != NULL);
11608 Expression* ve = Expression::make_var_reference(vno, location);
11609 Expression* bm;
11610 if (method != NULL)
11611 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11612 else
11613 bm = Expression::make_interface_field_reference(ve, name, location);
11615 // Even though we found the method above, if it has an error type we
11616 // may see an error here.
11617 if (bm->is_error_expression())
11619 gogo->finish_function(location);
11620 return bm;
11623 Expression_list* args;
11624 if (parameters->size() <= 1)
11625 args = NULL;
11626 else
11628 args = new Expression_list();
11629 Typed_identifier_list::const_iterator p = parameters->begin();
11630 ++p;
11631 for (; p != parameters->end(); ++p)
11633 vno = gogo->lookup(p->name(), NULL);
11634 go_assert(vno != NULL);
11635 args->push_back(Expression::make_var_reference(vno, location));
11639 gogo->start_block(location);
11641 Call_expression* call = Expression::make_call(bm, args,
11642 method_type->is_varargs(),
11643 location);
11645 Statement* s = Statement::make_return_from_call(call, location);
11646 gogo->add_statement(s);
11648 Block* b = gogo->finish_block(location);
11650 gogo->add_block(b, location);
11652 // Lower the call in case there are multiple results.
11653 gogo->lower_block(no, b);
11654 gogo->flatten_block(no, b);
11656 gogo->finish_function(location);
11658 return Expression::make_func_reference(no, NULL, location);
11661 // Dump the ast for a selector expression.
11663 void
11664 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11665 const
11667 ast_dump_context->dump_expression(this->left_);
11668 ast_dump_context->ostream() << ".";
11669 ast_dump_context->ostream() << this->name_;
11672 // Make a selector expression.
11674 Expression*
11675 Expression::make_selector(Expression* left, const std::string& name,
11676 Location location)
11678 return new Selector_expression(left, name, location);
11681 // Implement the builtin function new.
11683 class Allocation_expression : public Expression
11685 public:
11686 Allocation_expression(Type* type, Location location)
11687 : Expression(EXPRESSION_ALLOCATION, location),
11688 type_(type)
11691 protected:
11693 do_traverse(Traverse* traverse)
11694 { return Type::traverse(this->type_, traverse); }
11696 Type*
11697 do_type()
11698 { return Type::make_pointer_type(this->type_); }
11700 void
11701 do_determine_type(const Type_context*)
11704 Expression*
11705 do_copy()
11706 { return new Allocation_expression(this->type_, this->location()); }
11708 tree
11709 do_get_tree(Translate_context*);
11711 void
11712 do_dump_expression(Ast_dump_context*) const;
11714 private:
11715 // The type we are allocating.
11716 Type* type_;
11719 // Return a tree for an allocation expression.
11721 tree
11722 Allocation_expression::do_get_tree(Translate_context* context)
11724 Gogo* gogo = context->gogo();
11725 Location loc = this->location();
11726 Expression* space = gogo->allocate_memory(this->type_, loc);
11727 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11728 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11729 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11730 return expr_to_tree(ret);
11733 // Dump ast representation for an allocation expression.
11735 void
11736 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11737 const
11739 ast_dump_context->ostream() << "new(";
11740 ast_dump_context->dump_type(this->type_);
11741 ast_dump_context->ostream() << ")";
11744 // Make an allocation expression.
11746 Expression*
11747 Expression::make_allocation(Type* type, Location location)
11749 return new Allocation_expression(type, location);
11752 // Construct a struct.
11754 class Struct_construction_expression : public Expression
11756 public:
11757 Struct_construction_expression(Type* type, Expression_list* vals,
11758 Location location)
11759 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11760 type_(type), vals_(vals), traverse_order_(NULL)
11763 // Set the traversal order, used to ensure that we implement the
11764 // order of evaluation rules. Takes ownership of the argument.
11765 void
11766 set_traverse_order(std::vector<int>* traverse_order)
11767 { this->traverse_order_ = traverse_order; }
11769 // Return whether this is a constant initializer.
11770 bool
11771 is_constant_struct() const;
11773 protected:
11775 do_traverse(Traverse* traverse);
11777 bool
11778 do_is_immutable() const;
11780 Type*
11781 do_type()
11782 { return this->type_; }
11784 void
11785 do_determine_type(const Type_context*);
11787 void
11788 do_check_types(Gogo*);
11790 Expression*
11791 do_copy()
11793 Struct_construction_expression* ret =
11794 new Struct_construction_expression(this->type_, this->vals_->copy(),
11795 this->location());
11796 if (this->traverse_order_ != NULL)
11797 ret->set_traverse_order(this->traverse_order_);
11798 return ret;
11801 tree
11802 do_get_tree(Translate_context*);
11804 void
11805 do_export(Export*) const;
11807 void
11808 do_dump_expression(Ast_dump_context*) const;
11810 private:
11811 // The type of the struct to construct.
11812 Type* type_;
11813 // The list of values, in order of the fields in the struct. A NULL
11814 // entry means that the field should be zero-initialized.
11815 Expression_list* vals_;
11816 // If not NULL, the order in which to traverse vals_. This is used
11817 // so that we implement the order of evaluation rules correctly.
11818 std::vector<int>* traverse_order_;
11821 // Traversal.
11824 Struct_construction_expression::do_traverse(Traverse* traverse)
11826 if (this->vals_ != NULL)
11828 if (this->traverse_order_ == NULL)
11830 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11831 return TRAVERSE_EXIT;
11833 else
11835 for (std::vector<int>::const_iterator p =
11836 this->traverse_order_->begin();
11837 p != this->traverse_order_->end();
11838 ++p)
11840 if (Expression::traverse(&this->vals_->at(*p), traverse)
11841 == TRAVERSE_EXIT)
11842 return TRAVERSE_EXIT;
11846 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11847 return TRAVERSE_EXIT;
11848 return TRAVERSE_CONTINUE;
11851 // Return whether this is a constant initializer.
11853 bool
11854 Struct_construction_expression::is_constant_struct() const
11856 if (this->vals_ == NULL)
11857 return true;
11858 for (Expression_list::const_iterator pv = this->vals_->begin();
11859 pv != this->vals_->end();
11860 ++pv)
11862 if (*pv != NULL
11863 && !(*pv)->is_constant()
11864 && (!(*pv)->is_composite_literal()
11865 || (*pv)->is_nonconstant_composite_literal()))
11866 return false;
11869 const Struct_field_list* fields = this->type_->struct_type()->fields();
11870 for (Struct_field_list::const_iterator pf = fields->begin();
11871 pf != fields->end();
11872 ++pf)
11874 // There are no constant constructors for interfaces.
11875 if (pf->type()->interface_type() != NULL)
11876 return false;
11879 return true;
11882 // Return whether this struct is immutable.
11884 bool
11885 Struct_construction_expression::do_is_immutable() const
11887 if (this->vals_ == NULL)
11888 return true;
11889 for (Expression_list::const_iterator pv = this->vals_->begin();
11890 pv != this->vals_->end();
11891 ++pv)
11893 if (*pv != NULL && !(*pv)->is_immutable())
11894 return false;
11896 return true;
11899 // Final type determination.
11901 void
11902 Struct_construction_expression::do_determine_type(const Type_context*)
11904 if (this->vals_ == NULL)
11905 return;
11906 const Struct_field_list* fields = this->type_->struct_type()->fields();
11907 Expression_list::const_iterator pv = this->vals_->begin();
11908 for (Struct_field_list::const_iterator pf = fields->begin();
11909 pf != fields->end();
11910 ++pf, ++pv)
11912 if (pv == this->vals_->end())
11913 return;
11914 if (*pv != NULL)
11916 Type_context subcontext(pf->type(), false);
11917 (*pv)->determine_type(&subcontext);
11920 // Extra values are an error we will report elsewhere; we still want
11921 // to determine the type to avoid knockon errors.
11922 for (; pv != this->vals_->end(); ++pv)
11923 (*pv)->determine_type_no_context();
11926 // Check types.
11928 void
11929 Struct_construction_expression::do_check_types(Gogo*)
11931 if (this->vals_ == NULL)
11932 return;
11934 Struct_type* st = this->type_->struct_type();
11935 if (this->vals_->size() > st->field_count())
11937 this->report_error(_("too many expressions for struct"));
11938 return;
11941 const Struct_field_list* fields = st->fields();
11942 Expression_list::const_iterator pv = this->vals_->begin();
11943 int i = 0;
11944 for (Struct_field_list::const_iterator pf = fields->begin();
11945 pf != fields->end();
11946 ++pf, ++pv, ++i)
11948 if (pv == this->vals_->end())
11950 this->report_error(_("too few expressions for struct"));
11951 break;
11954 if (*pv == NULL)
11955 continue;
11957 std::string reason;
11958 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11960 if (reason.empty())
11961 error_at((*pv)->location(),
11962 "incompatible type for field %d in struct construction",
11963 i + 1);
11964 else
11965 error_at((*pv)->location(),
11966 ("incompatible type for field %d in "
11967 "struct construction (%s)"),
11968 i + 1, reason.c_str());
11969 this->set_is_error();
11972 go_assert(pv == this->vals_->end());
11975 // Return a tree for constructing a struct.
11977 tree
11978 Struct_construction_expression::do_get_tree(Translate_context* context)
11980 Gogo* gogo = context->gogo();
11982 Btype* btype = this->type_->get_backend(gogo);
11983 if (this->vals_ == NULL)
11984 return expr_to_tree(gogo->backend()->zero_expression(btype));
11986 const Struct_field_list* fields = this->type_->struct_type()->fields();
11987 Expression_list::const_iterator pv = this->vals_->begin();
11988 std::vector<Bexpression*> init;
11989 for (Struct_field_list::const_iterator pf = fields->begin();
11990 pf != fields->end();
11991 ++pf)
11993 Btype* fbtype = pf->type()->get_backend(gogo);
11994 if (pv == this->vals_->end())
11995 init.push_back(gogo->backend()->zero_expression(fbtype));
11996 else if (*pv == NULL)
11998 init.push_back(gogo->backend()->zero_expression(fbtype));
11999 ++pv;
12001 else
12003 Expression* val =
12004 Expression::convert_for_assignment(gogo, pf->type(),
12005 *pv, this->location());
12006 init.push_back(tree_to_expr(val->get_tree(context)));
12007 ++pv;
12011 Bexpression* ret =
12012 gogo->backend()->constructor_expression(btype, init, this->location());
12013 return expr_to_tree(ret);
12016 // Export a struct construction.
12018 void
12019 Struct_construction_expression::do_export(Export* exp) const
12021 exp->write_c_string("convert(");
12022 exp->write_type(this->type_);
12023 for (Expression_list::const_iterator pv = this->vals_->begin();
12024 pv != this->vals_->end();
12025 ++pv)
12027 exp->write_c_string(", ");
12028 if (*pv != NULL)
12029 (*pv)->export_expression(exp);
12031 exp->write_c_string(")");
12034 // Dump ast representation of a struct construction expression.
12036 void
12037 Struct_construction_expression::do_dump_expression(
12038 Ast_dump_context* ast_dump_context) const
12040 ast_dump_context->dump_type(this->type_);
12041 ast_dump_context->ostream() << "{";
12042 ast_dump_context->dump_expression_list(this->vals_);
12043 ast_dump_context->ostream() << "}";
12046 // Make a struct composite literal. This used by the thunk code.
12048 Expression*
12049 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12050 Location location)
12052 go_assert(type->struct_type() != NULL);
12053 return new Struct_construction_expression(type, vals, location);
12056 // Construct an array. This class is not used directly; instead we
12057 // use the child classes, Fixed_array_construction_expression and
12058 // Slice_construction_expression.
12060 class Array_construction_expression : public Expression
12062 protected:
12063 Array_construction_expression(Expression_classification classification,
12064 Type* type,
12065 const std::vector<unsigned long>* indexes,
12066 Expression_list* vals, Location location)
12067 : Expression(classification, location),
12068 type_(type), indexes_(indexes), vals_(vals)
12069 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
12071 public:
12072 // Return whether this is a constant initializer.
12073 bool
12074 is_constant_array() const;
12076 // Return the number of elements.
12077 size_t
12078 element_count() const
12079 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12081 protected:
12083 do_traverse(Traverse* traverse);
12085 bool
12086 do_is_immutable() const;
12088 Type*
12089 do_type()
12090 { return this->type_; }
12092 void
12093 do_determine_type(const Type_context*);
12095 void
12096 do_check_types(Gogo*);
12098 void
12099 do_export(Export*) const;
12101 // The indexes.
12102 const std::vector<unsigned long>*
12103 indexes()
12104 { return this->indexes_; }
12106 // The list of values.
12107 Expression_list*
12108 vals()
12109 { return this->vals_; }
12111 // Get the backend constructor for the array values.
12112 Bexpression*
12113 get_constructor(Translate_context* context, Btype* btype);
12115 void
12116 do_dump_expression(Ast_dump_context*) const;
12118 private:
12119 // The type of the array to construct.
12120 Type* type_;
12121 // The list of indexes into the array, one for each value. This may
12122 // be NULL, in which case the indexes start at zero and increment.
12123 const std::vector<unsigned long>* indexes_;
12124 // The list of values. This may be NULL if there are no values.
12125 Expression_list* vals_;
12128 // Traversal.
12131 Array_construction_expression::do_traverse(Traverse* traverse)
12133 if (this->vals_ != NULL
12134 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12135 return TRAVERSE_EXIT;
12136 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12137 return TRAVERSE_EXIT;
12138 return TRAVERSE_CONTINUE;
12141 // Return whether this is a constant initializer.
12143 bool
12144 Array_construction_expression::is_constant_array() const
12146 if (this->vals_ == NULL)
12147 return true;
12149 // There are no constant constructors for interfaces.
12150 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12151 return false;
12153 for (Expression_list::const_iterator pv = this->vals_->begin();
12154 pv != this->vals_->end();
12155 ++pv)
12157 if (*pv != NULL
12158 && !(*pv)->is_constant()
12159 && (!(*pv)->is_composite_literal()
12160 || (*pv)->is_nonconstant_composite_literal()))
12161 return false;
12163 return true;
12166 // Return whether this is an immutable array initializer.
12168 bool
12169 Array_construction_expression::do_is_immutable() const
12171 if (this->vals_ == NULL)
12172 return true;
12173 for (Expression_list::const_iterator pv = this->vals_->begin();
12174 pv != this->vals_->end();
12175 ++pv)
12177 if (*pv != NULL && !(*pv)->is_immutable())
12178 return false;
12180 return true;
12183 // Final type determination.
12185 void
12186 Array_construction_expression::do_determine_type(const Type_context*)
12188 if (this->vals_ == NULL)
12189 return;
12190 Type_context subcontext(this->type_->array_type()->element_type(), false);
12191 for (Expression_list::const_iterator pv = this->vals_->begin();
12192 pv != this->vals_->end();
12193 ++pv)
12195 if (*pv != NULL)
12196 (*pv)->determine_type(&subcontext);
12200 // Check types.
12202 void
12203 Array_construction_expression::do_check_types(Gogo*)
12205 if (this->vals_ == NULL)
12206 return;
12208 Array_type* at = this->type_->array_type();
12209 int i = 0;
12210 Type* element_type = at->element_type();
12211 for (Expression_list::const_iterator pv = this->vals_->begin();
12212 pv != this->vals_->end();
12213 ++pv, ++i)
12215 if (*pv != NULL
12216 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12218 error_at((*pv)->location(),
12219 "incompatible type for element %d in composite literal",
12220 i + 1);
12221 this->set_is_error();
12226 // Get a constructor expression for the array values.
12228 Bexpression*
12229 Array_construction_expression::get_constructor(Translate_context* context,
12230 Btype* array_btype)
12232 Type* element_type = this->type_->array_type()->element_type();
12234 std::vector<unsigned long> indexes;
12235 std::vector<Bexpression*> vals;
12236 Gogo* gogo = context->gogo();
12237 if (this->vals_ != NULL)
12239 size_t i = 0;
12240 std::vector<unsigned long>::const_iterator pi;
12241 if (this->indexes_ != NULL)
12242 pi = this->indexes_->begin();
12243 for (Expression_list::const_iterator pv = this->vals_->begin();
12244 pv != this->vals_->end();
12245 ++pv, ++i)
12247 if (this->indexes_ != NULL)
12248 go_assert(pi != this->indexes_->end());
12250 if (this->indexes_ == NULL)
12251 indexes.push_back(i);
12252 else
12253 indexes.push_back(*pi);
12254 if (*pv == NULL)
12256 Btype* ebtype = element_type->get_backend(gogo);
12257 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12258 vals.push_back(zv);
12260 else
12262 Expression* val_expr =
12263 Expression::convert_for_assignment(gogo, element_type, *pv,
12264 this->location());
12265 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
12267 if (this->indexes_ != NULL)
12268 ++pi;
12270 if (this->indexes_ != NULL)
12271 go_assert(pi == this->indexes_->end());
12273 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12274 vals, this->location());
12277 // Export an array construction.
12279 void
12280 Array_construction_expression::do_export(Export* exp) const
12282 exp->write_c_string("convert(");
12283 exp->write_type(this->type_);
12284 if (this->vals_ != NULL)
12286 std::vector<unsigned long>::const_iterator pi;
12287 if (this->indexes_ != NULL)
12288 pi = this->indexes_->begin();
12289 for (Expression_list::const_iterator pv = this->vals_->begin();
12290 pv != this->vals_->end();
12291 ++pv)
12293 exp->write_c_string(", ");
12295 if (this->indexes_ != NULL)
12297 char buf[100];
12298 snprintf(buf, sizeof buf, "%lu", *pi);
12299 exp->write_c_string(buf);
12300 exp->write_c_string(":");
12303 if (*pv != NULL)
12304 (*pv)->export_expression(exp);
12306 if (this->indexes_ != NULL)
12307 ++pi;
12310 exp->write_c_string(")");
12313 // Dump ast representation of an array construction expressin.
12315 void
12316 Array_construction_expression::do_dump_expression(
12317 Ast_dump_context* ast_dump_context) const
12319 Expression* length = this->type_->array_type()->length();
12321 ast_dump_context->ostream() << "[" ;
12322 if (length != NULL)
12324 ast_dump_context->dump_expression(length);
12326 ast_dump_context->ostream() << "]" ;
12327 ast_dump_context->dump_type(this->type_);
12328 ast_dump_context->ostream() << "{" ;
12329 if (this->indexes_ == NULL)
12330 ast_dump_context->dump_expression_list(this->vals_);
12331 else
12333 Expression_list::const_iterator pv = this->vals_->begin();
12334 for (std::vector<unsigned long>::const_iterator pi =
12335 this->indexes_->begin();
12336 pi != this->indexes_->end();
12337 ++pi, ++pv)
12339 if (pi != this->indexes_->begin())
12340 ast_dump_context->ostream() << ", ";
12341 ast_dump_context->ostream() << *pi << ':';
12342 ast_dump_context->dump_expression(*pv);
12345 ast_dump_context->ostream() << "}" ;
12349 // Construct a fixed array.
12351 class Fixed_array_construction_expression :
12352 public Array_construction_expression
12354 public:
12355 Fixed_array_construction_expression(Type* type,
12356 const std::vector<unsigned long>* indexes,
12357 Expression_list* vals, Location location)
12358 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12359 type, indexes, vals, location)
12360 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12362 protected:
12363 Expression*
12364 do_copy()
12366 return new Fixed_array_construction_expression(this->type(),
12367 this->indexes(),
12368 (this->vals() == NULL
12369 ? NULL
12370 : this->vals()->copy()),
12371 this->location());
12374 tree
12375 do_get_tree(Translate_context*);
12378 // Return a tree for constructing a fixed array.
12380 tree
12381 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12383 Type* type = this->type();
12384 Btype* btype = type->get_backend(context->gogo());
12385 return expr_to_tree(this->get_constructor(context, btype));
12388 Expression*
12389 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12390 Location location)
12392 go_assert(type->array_type() != NULL && !type->is_slice_type());
12393 return new Fixed_array_construction_expression(type, NULL, vals, location);
12396 // Construct a slice.
12398 class Slice_construction_expression : public Array_construction_expression
12400 public:
12401 Slice_construction_expression(Type* type,
12402 const std::vector<unsigned long>* indexes,
12403 Expression_list* vals, Location location)
12404 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12405 type, indexes, vals, location),
12406 valtype_(NULL)
12407 { go_assert(type->is_slice_type()); }
12409 protected:
12410 // Note that taking the address of a slice literal is invalid.
12412 Expression*
12413 do_copy()
12415 return new Slice_construction_expression(this->type(), this->indexes(),
12416 (this->vals() == NULL
12417 ? NULL
12418 : this->vals()->copy()),
12419 this->location());
12422 tree
12423 do_get_tree(Translate_context*);
12425 private:
12426 // The type of the values in this slice.
12427 Type* valtype_;
12430 // Return a tree for constructing a slice.
12432 tree
12433 Slice_construction_expression::do_get_tree(Translate_context* context)
12435 Array_type* array_type = this->type()->array_type();
12436 if (array_type == NULL)
12438 go_assert(this->type()->is_error());
12439 return error_mark_node;
12442 Type* element_type = array_type->element_type();
12443 if (this->valtype_ == NULL)
12445 mpz_t lenval;
12446 Expression* length;
12447 if (this->vals() == NULL || this->vals()->empty())
12448 mpz_init_set_ui(lenval, 0);
12449 else
12451 if (this->indexes() == NULL)
12452 mpz_init_set_ui(lenval, this->vals()->size());
12453 else
12454 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12456 Location loc = this->location();
12457 Type* int_type = Type::lookup_integer_type("int");
12458 length = Expression::make_integer(&lenval, int_type, loc);
12459 mpz_clear(lenval);
12460 this->valtype_ = Type::make_array_type(element_type, length);
12463 tree values;
12464 Gogo* gogo = context->gogo();
12465 Btype* val_btype = this->valtype_->get_backend(gogo);
12466 if (this->vals() == NULL || this->vals()->empty())
12468 // We need to create a unique value.
12469 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
12470 Bexpression* zero = gogo->backend()->zero_expression(int_btype);
12471 std::vector<unsigned long> index(1, 0);
12472 std::vector<Bexpression*> val(1, zero);
12473 Bexpression* ctor =
12474 gogo->backend()->array_constructor_expression(val_btype, index, val,
12475 this->location());
12476 values = expr_to_tree(ctor);
12478 else
12479 values = expr_to_tree(this->get_constructor(context, val_btype));
12481 if (values == error_mark_node)
12482 return error_mark_node;
12484 bool is_constant_initializer = TREE_CONSTANT(values);
12486 // We have to copy the initial values into heap memory if we are in
12487 // a function or if the values are not constants. We also have to
12488 // copy them if they may contain pointers in a non-constant context,
12489 // as otherwise the garbage collector won't see them.
12490 bool copy_to_heap = (context->function() != NULL
12491 || !is_constant_initializer
12492 || (element_type->has_pointer()
12493 && !context->is_const()));
12495 if (is_constant_initializer)
12497 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
12498 create_tmp_var_name("C"), TREE_TYPE(values));
12499 DECL_EXTERNAL(tmp) = 0;
12500 TREE_PUBLIC(tmp) = 0;
12501 TREE_STATIC(tmp) = 1;
12502 DECL_ARTIFICIAL(tmp) = 1;
12503 if (copy_to_heap)
12505 // If we are not copying the value to the heap, we will only
12506 // initialize the value once, so we can use this directly
12507 // rather than copying it. In that case we can't make it
12508 // read-only, because the program is permitted to change it.
12509 TREE_READONLY(tmp) = 1;
12510 TREE_CONSTANT(tmp) = 1;
12512 DECL_INITIAL(tmp) = values;
12513 rest_of_decl_compilation(tmp, 1, 0);
12514 values = tmp;
12517 tree space;
12518 tree set;
12519 if (!copy_to_heap)
12521 // the initializer will only run once.
12522 space = build_fold_addr_expr(values);
12523 set = NULL_TREE;
12525 else
12527 Expression* alloc =
12528 context->gogo()->allocate_memory(this->valtype_, this->location());
12529 space = save_expr(alloc->get_tree(context));
12531 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
12532 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12534 TREE_THIS_NOTRAP(ref) = 1;
12535 set = build2(MODIFY_EXPR, void_type_node, ref, values);
12538 // Build a constructor for the slice.
12540 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
12541 if (type_tree == error_mark_node)
12542 return error_mark_node;
12543 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12545 vec<constructor_elt, va_gc> *init;
12546 vec_alloc(init, 3);
12548 constructor_elt empty = {NULL, NULL};
12549 constructor_elt* elt = init->quick_push(empty);
12550 tree field = TYPE_FIELDS(type_tree);
12551 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
12552 elt->index = field;
12553 elt->value = fold_convert(TREE_TYPE(field), space);
12555 tree length_tree = this->valtype_->array_type()->length()->get_tree(context);
12556 elt = init->quick_push(empty);
12557 field = DECL_CHAIN(field);
12558 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
12559 elt->index = field;
12560 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12562 elt = init->quick_push(empty);
12563 field = DECL_CHAIN(field);
12564 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
12565 elt->index = field;
12566 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12568 tree constructor = build_constructor(type_tree, init);
12569 if (constructor == error_mark_node)
12570 return error_mark_node;
12571 if (!copy_to_heap)
12572 TREE_CONSTANT(constructor) = 1;
12574 if (set == NULL_TREE)
12575 return constructor;
12576 else
12577 return build2(COMPOUND_EXPR, type_tree, set, constructor);
12580 // Make a slice composite literal. This is used by the type
12581 // descriptor code.
12583 Expression*
12584 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12585 Location location)
12587 go_assert(type->is_slice_type());
12588 return new Slice_construction_expression(type, NULL, vals, location);
12591 // Construct a map.
12593 class Map_construction_expression : public Expression
12595 public:
12596 Map_construction_expression(Type* type, Expression_list* vals,
12597 Location location)
12598 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12599 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
12600 { go_assert(vals == NULL || vals->size() % 2 == 0); }
12602 protected:
12604 do_traverse(Traverse* traverse);
12606 Expression*
12607 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12609 Type*
12610 do_type()
12611 { return this->type_; }
12613 void
12614 do_determine_type(const Type_context*);
12616 void
12617 do_check_types(Gogo*);
12619 Expression*
12620 do_copy()
12622 return new Map_construction_expression(this->type_, this->vals_->copy(),
12623 this->location());
12626 tree
12627 do_get_tree(Translate_context*);
12629 void
12630 do_export(Export*) const;
12632 void
12633 do_dump_expression(Ast_dump_context*) const;
12635 private:
12636 // The type of the map to construct.
12637 Type* type_;
12638 // The list of values.
12639 Expression_list* vals_;
12640 // The type of the key-value pair struct for each map element.
12641 Struct_type* element_type_;
12642 // A temporary reference to the variable storing the constructor initializer.
12643 Temporary_statement* constructor_temp_;
12646 // Traversal.
12649 Map_construction_expression::do_traverse(Traverse* traverse)
12651 if (this->vals_ != NULL
12652 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12653 return TRAVERSE_EXIT;
12654 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12655 return TRAVERSE_EXIT;
12656 return TRAVERSE_CONTINUE;
12659 // Flatten constructor initializer into a temporary variable since
12660 // we need to take its address for __go_construct_map.
12662 Expression*
12663 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12664 Statement_inserter* inserter)
12666 if (!this->is_error_expression()
12667 && this->vals_ != NULL
12668 && !this->vals_->empty()
12669 && this->constructor_temp_ == NULL)
12671 Map_type* mt = this->type_->map_type();
12672 Type* key_type = mt->key_type();
12673 Type* val_type = mt->val_type();
12674 this->element_type_ = Type::make_builtin_struct_type(2,
12675 "__key", key_type,
12676 "__val", val_type);
12678 Expression_list* value_pairs = new Expression_list();
12679 Location loc = this->location();
12681 size_t i = 0;
12682 for (Expression_list::const_iterator pv = this->vals_->begin();
12683 pv != this->vals_->end();
12684 ++pv, ++i)
12686 Expression_list* key_value_pair = new Expression_list();
12687 Expression* key =
12688 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12690 ++pv;
12691 Expression* val =
12692 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12694 key_value_pair->push_back(key);
12695 key_value_pair->push_back(val);
12696 value_pairs->push_back(
12697 Expression::make_struct_composite_literal(this->element_type_,
12698 key_value_pair, loc));
12701 mpz_t lenval;
12702 mpz_init_set_ui(lenval, i);
12703 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12704 mpz_clear(lenval);
12706 Type* ctor_type =
12707 Type::make_array_type(this->element_type_, element_count);
12708 Expression* constructor =
12709 new Fixed_array_construction_expression(ctor_type, NULL,
12710 value_pairs, loc);
12712 this->constructor_temp_ =
12713 Statement::make_temporary(NULL, constructor, loc);
12714 constructor->issue_nil_check();
12715 this->constructor_temp_->set_is_address_taken();
12716 inserter->insert(this->constructor_temp_);
12719 return this;
12722 // Final type determination.
12724 void
12725 Map_construction_expression::do_determine_type(const Type_context*)
12727 if (this->vals_ == NULL)
12728 return;
12730 Map_type* mt = this->type_->map_type();
12731 Type_context key_context(mt->key_type(), false);
12732 Type_context val_context(mt->val_type(), false);
12733 for (Expression_list::const_iterator pv = this->vals_->begin();
12734 pv != this->vals_->end();
12735 ++pv)
12737 (*pv)->determine_type(&key_context);
12738 ++pv;
12739 (*pv)->determine_type(&val_context);
12743 // Check types.
12745 void
12746 Map_construction_expression::do_check_types(Gogo*)
12748 if (this->vals_ == NULL)
12749 return;
12751 Map_type* mt = this->type_->map_type();
12752 int i = 0;
12753 Type* key_type = mt->key_type();
12754 Type* val_type = mt->val_type();
12755 for (Expression_list::const_iterator pv = this->vals_->begin();
12756 pv != this->vals_->end();
12757 ++pv, ++i)
12759 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12761 error_at((*pv)->location(),
12762 "incompatible type for element %d key in map construction",
12763 i + 1);
12764 this->set_is_error();
12766 ++pv;
12767 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12769 error_at((*pv)->location(),
12770 ("incompatible type for element %d value "
12771 "in map construction"),
12772 i + 1);
12773 this->set_is_error();
12778 // Return a tree for constructing a map.
12780 tree
12781 Map_construction_expression::do_get_tree(Translate_context* context)
12783 if (this->is_error_expression())
12784 return error_mark_node;
12785 Location loc = this->location();
12787 size_t i = 0;
12788 Expression* ventries;
12789 if (this->vals_ == NULL || this->vals_->empty())
12790 ventries = Expression::make_nil(loc);
12791 else
12793 go_assert(this->constructor_temp_ != NULL);
12794 i = this->vals_->size() / 2;
12796 Expression* ctor_ref =
12797 Expression::make_temporary_reference(this->constructor_temp_, loc);
12798 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12801 Map_type* mt = this->type_->map_type();
12802 if (this->element_type_ == NULL)
12803 this->element_type_ =
12804 Type::make_builtin_struct_type(2,
12805 "__key", mt->key_type(),
12806 "__val", mt->val_type());
12807 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12809 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12810 mpz_t countval;
12811 mpz_init_set_ui(countval, i);
12812 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12813 mpz_clear(countval);
12815 Expression* entry_size =
12816 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12818 unsigned int field_index;
12819 const Struct_field* valfield =
12820 this->element_type_->find_local_field("__val", &field_index);
12821 Expression* val_offset =
12822 Expression::make_struct_field_offset(this->element_type_, valfield);
12823 Expression* val_size =
12824 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12826 Expression* map_ctor =
12827 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12828 entry_size, val_offset, val_size, ventries);
12829 return map_ctor->get_tree(context);
12832 // Export an array construction.
12834 void
12835 Map_construction_expression::do_export(Export* exp) const
12837 exp->write_c_string("convert(");
12838 exp->write_type(this->type_);
12839 for (Expression_list::const_iterator pv = this->vals_->begin();
12840 pv != this->vals_->end();
12841 ++pv)
12843 exp->write_c_string(", ");
12844 (*pv)->export_expression(exp);
12846 exp->write_c_string(")");
12849 // Dump ast representation for a map construction expression.
12851 void
12852 Map_construction_expression::do_dump_expression(
12853 Ast_dump_context* ast_dump_context) const
12855 ast_dump_context->ostream() << "{" ;
12856 ast_dump_context->dump_expression_list(this->vals_, true);
12857 ast_dump_context->ostream() << "}";
12860 // A general composite literal. This is lowered to a type specific
12861 // version.
12863 class Composite_literal_expression : public Parser_expression
12865 public:
12866 Composite_literal_expression(Type* type, int depth, bool has_keys,
12867 Expression_list* vals, bool all_are_names,
12868 Location location)
12869 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12870 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12871 all_are_names_(all_are_names)
12874 protected:
12876 do_traverse(Traverse* traverse);
12878 Expression*
12879 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12881 Expression*
12882 do_copy()
12884 return new Composite_literal_expression(this->type_, this->depth_,
12885 this->has_keys_,
12886 (this->vals_ == NULL
12887 ? NULL
12888 : this->vals_->copy()),
12889 this->all_are_names_,
12890 this->location());
12893 void
12894 do_dump_expression(Ast_dump_context*) const;
12896 private:
12897 Expression*
12898 lower_struct(Gogo*, Type*);
12900 Expression*
12901 lower_array(Type*);
12903 Expression*
12904 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12906 Expression*
12907 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12909 // The type of the composite literal.
12910 Type* type_;
12911 // The depth within a list of composite literals within a composite
12912 // literal, when the type is omitted.
12913 int depth_;
12914 // The values to put in the composite literal.
12915 Expression_list* vals_;
12916 // If this is true, then VALS_ is a list of pairs: a key and a
12917 // value. In an array initializer, a missing key will be NULL.
12918 bool has_keys_;
12919 // If this is true, then HAS_KEYS_ is true, and every key is a
12920 // simple identifier.
12921 bool all_are_names_;
12924 // Traversal.
12927 Composite_literal_expression::do_traverse(Traverse* traverse)
12929 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12930 return TRAVERSE_EXIT;
12932 // If this is a struct composite literal with keys, then the keys
12933 // are field names, not expressions. We don't want to traverse them
12934 // in that case. If we do, we can give an erroneous error "variable
12935 // initializer refers to itself." See bug482.go in the testsuite.
12936 if (this->has_keys_ && this->vals_ != NULL)
12938 // The type may not be resolvable at this point.
12939 Type* type = this->type_;
12941 for (int depth = this->depth_; depth > 0; --depth)
12943 if (type->array_type() != NULL)
12944 type = type->array_type()->element_type();
12945 else if (type->map_type() != NULL)
12946 type = type->map_type()->val_type();
12947 else
12949 // This error will be reported during lowering.
12950 return TRAVERSE_CONTINUE;
12954 while (true)
12956 if (type->classification() == Type::TYPE_NAMED)
12957 type = type->named_type()->real_type();
12958 else if (type->classification() == Type::TYPE_FORWARD)
12960 Type* t = type->forwarded();
12961 if (t == type)
12962 break;
12963 type = t;
12965 else
12966 break;
12969 if (type->classification() == Type::TYPE_STRUCT)
12971 Expression_list::iterator p = this->vals_->begin();
12972 while (p != this->vals_->end())
12974 // Skip key.
12975 ++p;
12976 go_assert(p != this->vals_->end());
12977 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12978 return TRAVERSE_EXIT;
12979 ++p;
12981 return TRAVERSE_CONTINUE;
12985 if (this->vals_ != NULL)
12986 return this->vals_->traverse(traverse);
12988 return TRAVERSE_CONTINUE;
12991 // Lower a generic composite literal into a specific version based on
12992 // the type.
12994 Expression*
12995 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12996 Statement_inserter* inserter, int)
12998 Type* type = this->type_;
13000 for (int depth = this->depth_; depth > 0; --depth)
13002 if (type->array_type() != NULL)
13003 type = type->array_type()->element_type();
13004 else if (type->map_type() != NULL)
13005 type = type->map_type()->val_type();
13006 else
13008 if (!type->is_error())
13009 error_at(this->location(),
13010 ("may only omit types within composite literals "
13011 "of slice, array, or map type"));
13012 return Expression::make_error(this->location());
13016 Type *pt = type->points_to();
13017 bool is_pointer = false;
13018 if (pt != NULL)
13020 is_pointer = true;
13021 type = pt;
13024 Expression* ret;
13025 if (type->is_error())
13026 return Expression::make_error(this->location());
13027 else if (type->struct_type() != NULL)
13028 ret = this->lower_struct(gogo, type);
13029 else if (type->array_type() != NULL)
13030 ret = this->lower_array(type);
13031 else if (type->map_type() != NULL)
13032 ret = this->lower_map(gogo, function, inserter, type);
13033 else
13035 error_at(this->location(),
13036 ("expected struct, slice, array, or map type "
13037 "for composite literal"));
13038 return Expression::make_error(this->location());
13041 if (is_pointer)
13042 ret = Expression::make_heap_expression(ret, this->location());
13044 return ret;
13047 // Lower a struct composite literal.
13049 Expression*
13050 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13052 Location location = this->location();
13053 Struct_type* st = type->struct_type();
13054 if (this->vals_ == NULL || !this->has_keys_)
13056 if (this->vals_ != NULL
13057 && !this->vals_->empty()
13058 && type->named_type() != NULL
13059 && type->named_type()->named_object()->package() != NULL)
13061 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13062 pf != st->fields()->end();
13063 ++pf)
13065 if (Gogo::is_hidden_name(pf->field_name()))
13066 error_at(this->location(),
13067 "assignment of unexported field %qs in %qs literal",
13068 Gogo::message_name(pf->field_name()).c_str(),
13069 type->named_type()->message_name().c_str());
13073 return new Struct_construction_expression(type, this->vals_, location);
13076 size_t field_count = st->field_count();
13077 std::vector<Expression*> vals(field_count);
13078 std::vector<int>* traverse_order = new(std::vector<int>);
13079 Expression_list::const_iterator p = this->vals_->begin();
13080 Expression* external_expr = NULL;
13081 const Named_object* external_no = NULL;
13082 while (p != this->vals_->end())
13084 Expression* name_expr = *p;
13086 ++p;
13087 go_assert(p != this->vals_->end());
13088 Expression* val = *p;
13090 ++p;
13092 if (name_expr == NULL)
13094 error_at(val->location(), "mixture of field and value initializers");
13095 return Expression::make_error(location);
13098 bool bad_key = false;
13099 std::string name;
13100 const Named_object* no = NULL;
13101 switch (name_expr->classification())
13103 case EXPRESSION_UNKNOWN_REFERENCE:
13104 name = name_expr->unknown_expression()->name();
13105 break;
13107 case EXPRESSION_CONST_REFERENCE:
13108 no = static_cast<Const_expression*>(name_expr)->named_object();
13109 break;
13111 case EXPRESSION_TYPE:
13113 Type* t = name_expr->type();
13114 Named_type* nt = t->named_type();
13115 if (nt == NULL)
13116 bad_key = true;
13117 else
13118 no = nt->named_object();
13120 break;
13122 case EXPRESSION_VAR_REFERENCE:
13123 no = name_expr->var_expression()->named_object();
13124 break;
13126 case EXPRESSION_FUNC_REFERENCE:
13127 no = name_expr->func_expression()->named_object();
13128 break;
13130 case EXPRESSION_UNARY:
13131 // If there is a local variable around with the same name as
13132 // the field, and this occurs in the closure, then the
13133 // parser may turn the field reference into an indirection
13134 // through the closure. FIXME: This is a mess.
13136 bad_key = true;
13137 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13138 if (ue->op() == OPERATOR_MULT)
13140 Field_reference_expression* fre =
13141 ue->operand()->field_reference_expression();
13142 if (fre != NULL)
13144 Struct_type* st =
13145 fre->expr()->type()->deref()->struct_type();
13146 if (st != NULL)
13148 const Struct_field* sf = st->field(fre->field_index());
13149 name = sf->field_name();
13151 // See below. FIXME.
13152 if (!Gogo::is_hidden_name(name)
13153 && name[0] >= 'a'
13154 && name[0] <= 'z')
13156 if (gogo->lookup_global(name.c_str()) != NULL)
13157 name = gogo->pack_hidden_name(name, false);
13160 char buf[20];
13161 snprintf(buf, sizeof buf, "%u", fre->field_index());
13162 size_t buflen = strlen(buf);
13163 if (name.compare(name.length() - buflen, buflen, buf)
13164 == 0)
13166 name = name.substr(0, name.length() - buflen);
13167 bad_key = false;
13173 break;
13175 default:
13176 bad_key = true;
13177 break;
13179 if (bad_key)
13181 error_at(name_expr->location(), "expected struct field name");
13182 return Expression::make_error(location);
13185 if (no != NULL)
13187 if (no->package() != NULL && external_expr == NULL)
13189 external_expr = name_expr;
13190 external_no = no;
13193 name = no->name();
13195 // A predefined name won't be packed. If it starts with a
13196 // lower case letter we need to check for that case, because
13197 // the field name will be packed. FIXME.
13198 if (!Gogo::is_hidden_name(name)
13199 && name[0] >= 'a'
13200 && name[0] <= 'z')
13202 Named_object* gno = gogo->lookup_global(name.c_str());
13203 if (gno == no)
13204 name = gogo->pack_hidden_name(name, false);
13208 unsigned int index;
13209 const Struct_field* sf = st->find_local_field(name, &index);
13210 if (sf == NULL)
13212 error_at(name_expr->location(), "unknown field %qs in %qs",
13213 Gogo::message_name(name).c_str(),
13214 (type->named_type() != NULL
13215 ? type->named_type()->message_name().c_str()
13216 : "unnamed struct"));
13217 return Expression::make_error(location);
13219 if (vals[index] != NULL)
13221 error_at(name_expr->location(),
13222 "duplicate value for field %qs in %qs",
13223 Gogo::message_name(name).c_str(),
13224 (type->named_type() != NULL
13225 ? type->named_type()->message_name().c_str()
13226 : "unnamed struct"));
13227 return Expression::make_error(location);
13230 if (type->named_type() != NULL
13231 && type->named_type()->named_object()->package() != NULL
13232 && Gogo::is_hidden_name(sf->field_name()))
13233 error_at(name_expr->location(),
13234 "assignment of unexported field %qs in %qs literal",
13235 Gogo::message_name(sf->field_name()).c_str(),
13236 type->named_type()->message_name().c_str());
13238 vals[index] = val;
13239 traverse_order->push_back(index);
13242 if (!this->all_are_names_)
13244 // This is a weird case like bug462 in the testsuite.
13245 if (external_expr == NULL)
13246 error_at(this->location(), "unknown field in %qs literal",
13247 (type->named_type() != NULL
13248 ? type->named_type()->message_name().c_str()
13249 : "unnamed struct"));
13250 else
13251 error_at(external_expr->location(), "unknown field %qs in %qs",
13252 external_no->message_name().c_str(),
13253 (type->named_type() != NULL
13254 ? type->named_type()->message_name().c_str()
13255 : "unnamed struct"));
13256 return Expression::make_error(location);
13259 Expression_list* list = new Expression_list;
13260 list->reserve(field_count);
13261 for (size_t i = 0; i < field_count; ++i)
13262 list->push_back(vals[i]);
13264 Struct_construction_expression* ret =
13265 new Struct_construction_expression(type, list, location);
13266 ret->set_traverse_order(traverse_order);
13267 return ret;
13270 // Used to sort an index/value array.
13272 class Index_value_compare
13274 public:
13275 bool
13276 operator()(const std::pair<unsigned long, Expression*>& a,
13277 const std::pair<unsigned long, Expression*>& b)
13278 { return a.first < b.first; }
13281 // Lower an array composite literal.
13283 Expression*
13284 Composite_literal_expression::lower_array(Type* type)
13286 Location location = this->location();
13287 if (this->vals_ == NULL || !this->has_keys_)
13288 return this->make_array(type, NULL, this->vals_);
13290 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13291 indexes->reserve(this->vals_->size());
13292 bool indexes_out_of_order = false;
13293 Expression_list* vals = new Expression_list();
13294 vals->reserve(this->vals_->size());
13295 unsigned long index = 0;
13296 Expression_list::const_iterator p = this->vals_->begin();
13297 while (p != this->vals_->end())
13299 Expression* index_expr = *p;
13301 ++p;
13302 go_assert(p != this->vals_->end());
13303 Expression* val = *p;
13305 ++p;
13307 if (index_expr == NULL)
13309 if (!indexes->empty())
13310 indexes->push_back(index);
13312 else
13314 if (indexes->empty() && !vals->empty())
13316 for (size_t i = 0; i < vals->size(); ++i)
13317 indexes->push_back(i);
13320 Numeric_constant nc;
13321 if (!index_expr->numeric_constant_value(&nc))
13323 error_at(index_expr->location(),
13324 "index expression is not integer constant");
13325 return Expression::make_error(location);
13328 switch (nc.to_unsigned_long(&index))
13330 case Numeric_constant::NC_UL_VALID:
13331 break;
13332 case Numeric_constant::NC_UL_NOTINT:
13333 error_at(index_expr->location(),
13334 "index expression is not integer constant");
13335 return Expression::make_error(location);
13336 case Numeric_constant::NC_UL_NEGATIVE:
13337 error_at(index_expr->location(), "index expression is negative");
13338 return Expression::make_error(location);
13339 case Numeric_constant::NC_UL_BIG:
13340 error_at(index_expr->location(), "index value overflow");
13341 return Expression::make_error(location);
13342 default:
13343 go_unreachable();
13346 Named_type* ntype = Type::lookup_integer_type("int");
13347 Integer_type* inttype = ntype->integer_type();
13348 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13349 && index >> (inttype->bits() - 1) != 0)
13351 error_at(index_expr->location(), "index value overflow");
13352 return Expression::make_error(location);
13355 if (std::find(indexes->begin(), indexes->end(), index)
13356 != indexes->end())
13358 error_at(index_expr->location(), "duplicate value for index %lu",
13359 index);
13360 return Expression::make_error(location);
13363 if (!indexes->empty() && index < indexes->back())
13364 indexes_out_of_order = true;
13366 indexes->push_back(index);
13369 vals->push_back(val);
13371 ++index;
13374 if (indexes->empty())
13376 delete indexes;
13377 indexes = NULL;
13380 if (indexes_out_of_order)
13382 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13384 V v;
13385 v.reserve(indexes->size());
13386 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13387 for (Expression_list::const_iterator pe = vals->begin();
13388 pe != vals->end();
13389 ++pe, ++pi)
13390 v.push_back(std::make_pair(*pi, *pe));
13392 std::sort(v.begin(), v.end(), Index_value_compare());
13394 delete indexes;
13395 delete vals;
13396 indexes = new std::vector<unsigned long>();
13397 indexes->reserve(v.size());
13398 vals = new Expression_list();
13399 vals->reserve(v.size());
13401 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13403 indexes->push_back(p->first);
13404 vals->push_back(p->second);
13408 return this->make_array(type, indexes, vals);
13411 // Actually build the array composite literal. This handles
13412 // [...]{...}.
13414 Expression*
13415 Composite_literal_expression::make_array(
13416 Type* type,
13417 const std::vector<unsigned long>* indexes,
13418 Expression_list* vals)
13420 Location location = this->location();
13421 Array_type* at = type->array_type();
13423 if (at->length() != NULL && at->length()->is_nil_expression())
13425 size_t size;
13426 if (vals == NULL)
13427 size = 0;
13428 else if (indexes != NULL)
13429 size = indexes->back() + 1;
13430 else
13432 size = vals->size();
13433 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13434 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13435 && size >> (it->bits() - 1) != 0)
13437 error_at(location, "too many elements in composite literal");
13438 return Expression::make_error(location);
13442 mpz_t vlen;
13443 mpz_init_set_ui(vlen, size);
13444 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13445 mpz_clear(vlen);
13446 at = Type::make_array_type(at->element_type(), elen);
13447 type = at;
13449 else if (at->length() != NULL
13450 && !at->length()->is_error_expression()
13451 && this->vals_ != NULL)
13453 Numeric_constant nc;
13454 unsigned long val;
13455 if (at->length()->numeric_constant_value(&nc)
13456 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13458 if (indexes == NULL)
13460 if (this->vals_->size() > val)
13462 error_at(location, "too many elements in composite literal");
13463 return Expression::make_error(location);
13466 else
13468 unsigned long max = indexes->back();
13469 if (max >= val)
13471 error_at(location,
13472 ("some element keys in composite literal "
13473 "are out of range"));
13474 return Expression::make_error(location);
13480 if (at->length() != NULL)
13481 return new Fixed_array_construction_expression(type, indexes, vals,
13482 location);
13483 else
13484 return new Slice_construction_expression(type, indexes, vals, location);
13487 // Lower a map composite literal.
13489 Expression*
13490 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13491 Statement_inserter* inserter,
13492 Type* type)
13494 Location location = this->location();
13495 if (this->vals_ != NULL)
13497 if (!this->has_keys_)
13499 error_at(location, "map composite literal must have keys");
13500 return Expression::make_error(location);
13503 for (Expression_list::iterator p = this->vals_->begin();
13504 p != this->vals_->end();
13505 p += 2)
13507 if (*p == NULL)
13509 ++p;
13510 error_at((*p)->location(),
13511 "map composite literal must have keys for every value");
13512 return Expression::make_error(location);
13514 // Make sure we have lowered the key; it may not have been
13515 // lowered in order to handle keys for struct composite
13516 // literals. Lower it now to get the right error message.
13517 if ((*p)->unknown_expression() != NULL)
13519 (*p)->unknown_expression()->clear_is_composite_literal_key();
13520 gogo->lower_expression(function, inserter, &*p);
13521 go_assert((*p)->is_error_expression());
13522 return Expression::make_error(location);
13527 return new Map_construction_expression(type, this->vals_, location);
13530 // Dump ast representation for a composite literal expression.
13532 void
13533 Composite_literal_expression::do_dump_expression(
13534 Ast_dump_context* ast_dump_context) const
13536 ast_dump_context->ostream() << "composite(";
13537 ast_dump_context->dump_type(this->type_);
13538 ast_dump_context->ostream() << ", {";
13539 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13540 ast_dump_context->ostream() << "})";
13543 // Make a composite literal expression.
13545 Expression*
13546 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13547 Expression_list* vals, bool all_are_names,
13548 Location location)
13550 return new Composite_literal_expression(type, depth, has_keys, vals,
13551 all_are_names, location);
13554 // Return whether this expression is a composite literal.
13556 bool
13557 Expression::is_composite_literal() const
13559 switch (this->classification_)
13561 case EXPRESSION_COMPOSITE_LITERAL:
13562 case EXPRESSION_STRUCT_CONSTRUCTION:
13563 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13564 case EXPRESSION_SLICE_CONSTRUCTION:
13565 case EXPRESSION_MAP_CONSTRUCTION:
13566 return true;
13567 default:
13568 return false;
13572 // Return whether this expression is a composite literal which is not
13573 // constant.
13575 bool
13576 Expression::is_nonconstant_composite_literal() const
13578 switch (this->classification_)
13580 case EXPRESSION_STRUCT_CONSTRUCTION:
13582 const Struct_construction_expression *psce =
13583 static_cast<const Struct_construction_expression*>(this);
13584 return !psce->is_constant_struct();
13586 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13588 const Fixed_array_construction_expression *pace =
13589 static_cast<const Fixed_array_construction_expression*>(this);
13590 return !pace->is_constant_array();
13592 case EXPRESSION_SLICE_CONSTRUCTION:
13594 const Slice_construction_expression *pace =
13595 static_cast<const Slice_construction_expression*>(this);
13596 return !pace->is_constant_array();
13598 case EXPRESSION_MAP_CONSTRUCTION:
13599 return true;
13600 default:
13601 return false;
13605 // Return true if this is a variable or temporary_variable.
13607 bool
13608 Expression::is_variable() const
13610 switch (this->classification_)
13612 case EXPRESSION_VAR_REFERENCE:
13613 case EXPRESSION_TEMPORARY_REFERENCE:
13614 case EXPRESSION_SET_AND_USE_TEMPORARY:
13615 return true;
13616 default:
13617 return false;
13621 // Return true if this is a reference to a local variable.
13623 bool
13624 Expression::is_local_variable() const
13626 const Var_expression* ve = this->var_expression();
13627 if (ve == NULL)
13628 return false;
13629 const Named_object* no = ve->named_object();
13630 return (no->is_result_variable()
13631 || (no->is_variable() && !no->var_value()->is_global()));
13634 // Class Type_guard_expression.
13636 // Traversal.
13639 Type_guard_expression::do_traverse(Traverse* traverse)
13641 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13642 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13643 return TRAVERSE_EXIT;
13644 return TRAVERSE_CONTINUE;
13647 Expression*
13648 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13649 Statement_inserter* inserter)
13651 if (!this->expr_->is_variable())
13653 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13654 this->location());
13655 inserter->insert(temp);
13656 this->expr_ =
13657 Expression::make_temporary_reference(temp, this->location());
13659 return this;
13662 // Check types of a type guard expression. The expression must have
13663 // an interface type, but the actual type conversion is checked at run
13664 // time.
13666 void
13667 Type_guard_expression::do_check_types(Gogo*)
13669 Type* expr_type = this->expr_->type();
13670 if (expr_type->interface_type() == NULL)
13672 if (!expr_type->is_error() && !this->type_->is_error())
13673 this->report_error(_("type assertion only valid for interface types"));
13674 this->set_is_error();
13676 else if (this->type_->interface_type() == NULL)
13678 std::string reason;
13679 if (!expr_type->interface_type()->implements_interface(this->type_,
13680 &reason))
13682 if (!this->type_->is_error())
13684 if (reason.empty())
13685 this->report_error(_("impossible type assertion: "
13686 "type does not implement interface"));
13687 else
13688 error_at(this->location(),
13689 ("impossible type assertion: "
13690 "type does not implement interface (%s)"),
13691 reason.c_str());
13693 this->set_is_error();
13698 // Return a tree for a type guard expression.
13700 tree
13701 Type_guard_expression::do_get_tree(Translate_context* context)
13703 Expression* conversion;
13704 if (this->type_->interface_type() != NULL)
13705 conversion =
13706 Expression::convert_interface_to_interface(this->type_, this->expr_,
13707 true, this->location());
13708 else
13709 conversion =
13710 Expression::convert_for_assignment(context->gogo(), this->type_,
13711 this->expr_, this->location());
13713 return conversion->get_tree(context);
13716 // Dump ast representation for a type guard expression.
13718 void
13719 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13720 const
13722 this->expr_->dump_expression(ast_dump_context);
13723 ast_dump_context->ostream() << ".";
13724 ast_dump_context->dump_type(this->type_);
13727 // Make a type guard expression.
13729 Expression*
13730 Expression::make_type_guard(Expression* expr, Type* type,
13731 Location location)
13733 return new Type_guard_expression(expr, type, location);
13736 // Class Heap_expression.
13738 // When you take the address of an escaping expression, it is allocated
13739 // on the heap. This class implements that.
13741 class Heap_expression : public Expression
13743 public:
13744 Heap_expression(Expression* expr, Location location)
13745 : Expression(EXPRESSION_HEAP, location),
13746 expr_(expr)
13749 protected:
13751 do_traverse(Traverse* traverse)
13752 { return Expression::traverse(&this->expr_, traverse); }
13754 Type*
13755 do_type()
13756 { return Type::make_pointer_type(this->expr_->type()); }
13758 void
13759 do_determine_type(const Type_context*)
13760 { this->expr_->determine_type_no_context(); }
13762 Expression*
13763 do_copy()
13765 return Expression::make_heap_expression(this->expr_->copy(),
13766 this->location());
13769 tree
13770 do_get_tree(Translate_context*);
13772 // We only export global objects, and the parser does not generate
13773 // this in global scope.
13774 void
13775 do_export(Export*) const
13776 { go_unreachable(); }
13778 void
13779 do_dump_expression(Ast_dump_context*) const;
13781 private:
13782 // The expression which is being put on the heap.
13783 Expression* expr_;
13786 // Return a tree which allocates an expression on the heap.
13788 tree
13789 Heap_expression::do_get_tree(Translate_context* context)
13791 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13792 return error_mark_node;
13794 Location loc = this->location();
13795 Gogo* gogo = context->gogo();
13796 Btype* btype = this->type()->get_backend(gogo);
13797 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
13798 Bexpression* space = tree_to_expr(alloc->get_tree(context));
13800 Bstatement* decl;
13801 Named_object* fn = context->function();
13802 go_assert(fn != NULL);
13803 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13804 Bvariable* space_temp =
13805 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13806 space, true, loc, &decl);
13807 space = gogo->backend()->var_expression(space_temp, loc);
13808 Bexpression* ref = gogo->backend()->indirect_expression(space, true, loc);
13810 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
13811 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13812 decl = gogo->backend()->compound_statement(decl, assn);
13813 space = gogo->backend()->var_expression(space_temp, loc);
13814 Bexpression* ret = gogo->backend()->compound_expression(decl, space, loc);
13815 return expr_to_tree(ret);
13818 // Dump ast representation for a heap expression.
13820 void
13821 Heap_expression::do_dump_expression(
13822 Ast_dump_context* ast_dump_context) const
13824 ast_dump_context->ostream() << "&(";
13825 ast_dump_context->dump_expression(this->expr_);
13826 ast_dump_context->ostream() << ")";
13829 // Allocate an expression on the heap.
13831 Expression*
13832 Expression::make_heap_expression(Expression* expr, Location location)
13834 return new Heap_expression(expr, location);
13837 // Class Receive_expression.
13839 // Return the type of a receive expression.
13841 Type*
13842 Receive_expression::do_type()
13844 Channel_type* channel_type = this->channel_->type()->channel_type();
13845 if (channel_type == NULL)
13846 return Type::make_error_type();
13847 return channel_type->element_type();
13850 // Check types for a receive expression.
13852 void
13853 Receive_expression::do_check_types(Gogo*)
13855 Type* type = this->channel_->type();
13856 if (type->is_error())
13858 this->set_is_error();
13859 return;
13861 if (type->channel_type() == NULL)
13863 this->report_error(_("expected channel"));
13864 return;
13866 if (!type->channel_type()->may_receive())
13868 this->report_error(_("invalid receive on send-only channel"));
13869 return;
13873 // Flattening for receive expressions creates a temporary variable to store
13874 // received data in for receives.
13876 Expression*
13877 Receive_expression::do_flatten(Gogo*, Named_object*,
13878 Statement_inserter* inserter)
13880 Channel_type* channel_type = this->channel_->type()->channel_type();
13881 if (channel_type == NULL)
13883 go_assert(saw_errors());
13884 return this;
13887 Type* element_type = channel_type->element_type();
13888 if (this->temp_receiver_ == NULL)
13890 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13891 this->location());
13892 this->temp_receiver_->set_is_address_taken();
13893 inserter->insert(this->temp_receiver_);
13896 return this;
13899 // Get a tree for a receive expression.
13901 tree
13902 Receive_expression::do_get_tree(Translate_context* context)
13904 Location loc = this->location();
13906 Channel_type* channel_type = this->channel_->type()->channel_type();
13907 if (channel_type == NULL)
13909 go_assert(this->channel_->type()->is_error());
13910 return error_mark_node;
13912 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13914 Expression* recv_ref =
13915 Expression::make_temporary_reference(this->temp_receiver_, loc);
13916 Expression* recv_addr =
13917 Expression::make_temporary_reference(this->temp_receiver_, loc);
13918 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13919 Expression* recv =
13920 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13921 td, this->channel_, recv_addr);
13922 recv = Expression::make_compound(recv, recv_ref, loc);
13923 return recv->get_tree(context);
13926 // Dump ast representation for a receive expression.
13928 void
13929 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13931 ast_dump_context->ostream() << " <- " ;
13932 ast_dump_context->dump_expression(channel_);
13935 // Make a receive expression.
13937 Receive_expression*
13938 Expression::make_receive(Expression* channel, Location location)
13940 return new Receive_expression(channel, location);
13943 // An expression which evaluates to a pointer to the type descriptor
13944 // of a type.
13946 class Type_descriptor_expression : public Expression
13948 public:
13949 Type_descriptor_expression(Type* type, Location location)
13950 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13951 type_(type)
13954 protected:
13955 Type*
13956 do_type()
13957 { return Type::make_type_descriptor_ptr_type(); }
13959 bool
13960 do_is_immutable() const
13961 { return true; }
13963 void
13964 do_determine_type(const Type_context*)
13967 Expression*
13968 do_copy()
13969 { return this; }
13971 tree
13972 do_get_tree(Translate_context* context)
13974 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
13975 this->location());
13976 return expr_to_tree(ret);
13979 void
13980 do_dump_expression(Ast_dump_context*) const;
13982 private:
13983 // The type for which this is the descriptor.
13984 Type* type_;
13987 // Dump ast representation for a type descriptor expression.
13989 void
13990 Type_descriptor_expression::do_dump_expression(
13991 Ast_dump_context* ast_dump_context) const
13993 ast_dump_context->dump_type(this->type_);
13996 // Make a type descriptor expression.
13998 Expression*
13999 Expression::make_type_descriptor(Type* type, Location location)
14001 return new Type_descriptor_expression(type, location);
14004 // An expression which evaluates to some characteristic of a type.
14005 // This is only used to initialize fields of a type descriptor. Using
14006 // a new expression class is slightly inefficient but gives us a good
14007 // separation between the frontend and the middle-end with regard to
14008 // how types are laid out.
14010 class Type_info_expression : public Expression
14012 public:
14013 Type_info_expression(Type* type, Type_info type_info)
14014 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14015 type_(type), type_info_(type_info)
14018 protected:
14019 bool
14020 do_is_immutable() const
14021 { return true; }
14023 Type*
14024 do_type();
14026 void
14027 do_determine_type(const Type_context*)
14030 Expression*
14031 do_copy()
14032 { return this; }
14034 tree
14035 do_get_tree(Translate_context* context);
14037 void
14038 do_dump_expression(Ast_dump_context*) const;
14040 private:
14041 // The type for which we are getting information.
14042 Type* type_;
14043 // What information we want.
14044 Type_info type_info_;
14047 // The type is chosen to match what the type descriptor struct
14048 // expects.
14050 Type*
14051 Type_info_expression::do_type()
14053 switch (this->type_info_)
14055 case TYPE_INFO_SIZE:
14056 return Type::lookup_integer_type("uintptr");
14057 case TYPE_INFO_ALIGNMENT:
14058 case TYPE_INFO_FIELD_ALIGNMENT:
14059 return Type::lookup_integer_type("uint8");
14060 default:
14061 go_unreachable();
14065 // Return type information in GENERIC.
14067 tree
14068 Type_info_expression::do_get_tree(Translate_context* context)
14070 Btype* btype = this->type_->get_backend(context->gogo());
14071 Gogo* gogo = context->gogo();
14072 size_t val;
14073 switch (this->type_info_)
14075 case TYPE_INFO_SIZE:
14076 val = gogo->backend()->type_size(btype);
14077 break;
14078 case TYPE_INFO_ALIGNMENT:
14079 val = gogo->backend()->type_alignment(btype);
14080 break;
14081 case TYPE_INFO_FIELD_ALIGNMENT:
14082 val = gogo->backend()->type_field_alignment(btype);
14083 break;
14084 default:
14085 go_unreachable();
14087 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14088 go_assert(val_type_tree != error_mark_node);
14089 return build_int_cstu(val_type_tree, val);
14092 // Dump ast representation for a type info expression.
14094 void
14095 Type_info_expression::do_dump_expression(
14096 Ast_dump_context* ast_dump_context) const
14098 ast_dump_context->ostream() << "typeinfo(";
14099 ast_dump_context->dump_type(this->type_);
14100 ast_dump_context->ostream() << ",";
14101 ast_dump_context->ostream() <<
14102 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14103 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14104 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14105 : "unknown");
14106 ast_dump_context->ostream() << ")";
14109 // Make a type info expression.
14111 Expression*
14112 Expression::make_type_info(Type* type, Type_info type_info)
14114 return new Type_info_expression(type, type_info);
14117 // An expression that evaluates to some characteristic of a slice.
14118 // This is used when indexing, bound-checking, or nil checking a slice.
14120 class Slice_info_expression : public Expression
14122 public:
14123 Slice_info_expression(Expression* slice, Slice_info slice_info,
14124 Location location)
14125 : Expression(EXPRESSION_SLICE_INFO, location),
14126 slice_(slice), slice_info_(slice_info)
14129 protected:
14130 Type*
14131 do_type();
14133 void
14134 do_determine_type(const Type_context*)
14137 Expression*
14138 do_copy()
14140 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14141 this->location());
14144 tree
14145 do_get_tree(Translate_context* context);
14147 void
14148 do_dump_expression(Ast_dump_context*) const;
14150 void
14151 do_issue_nil_check()
14152 { this->slice_->issue_nil_check(); }
14154 private:
14155 // The slice for which we are getting information.
14156 Expression* slice_;
14157 // What information we want.
14158 Slice_info slice_info_;
14161 // Return the type of the slice info.
14163 Type*
14164 Slice_info_expression::do_type()
14166 switch (this->slice_info_)
14168 case SLICE_INFO_VALUE_POINTER:
14169 return Type::make_pointer_type(
14170 this->slice_->type()->array_type()->element_type());
14171 case SLICE_INFO_LENGTH:
14172 case SLICE_INFO_CAPACITY:
14173 return Type::lookup_integer_type("int");
14174 default:
14175 go_unreachable();
14179 // Return slice information in GENERIC.
14181 tree
14182 Slice_info_expression::do_get_tree(Translate_context* context)
14184 Gogo* gogo = context->gogo();
14186 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14187 Bexpression* ret;
14188 switch (this->slice_info_)
14190 case SLICE_INFO_VALUE_POINTER:
14191 case SLICE_INFO_LENGTH:
14192 case SLICE_INFO_CAPACITY:
14193 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14194 this->location());
14195 break;
14196 default:
14197 go_unreachable();
14199 return expr_to_tree(ret);
14202 // Dump ast representation for a type info expression.
14204 void
14205 Slice_info_expression::do_dump_expression(
14206 Ast_dump_context* ast_dump_context) const
14208 ast_dump_context->ostream() << "sliceinfo(";
14209 this->slice_->dump_expression(ast_dump_context);
14210 ast_dump_context->ostream() << ",";
14211 ast_dump_context->ostream() <<
14212 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14213 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14214 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14215 : "unknown");
14216 ast_dump_context->ostream() << ")";
14219 // Make a slice info expression.
14221 Expression*
14222 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14223 Location location)
14225 return new Slice_info_expression(slice, slice_info, location);
14228 // An expression that represents a slice value: a struct with value pointer,
14229 // length, and capacity fields.
14231 class Slice_value_expression : public Expression
14233 public:
14234 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14235 Expression* cap, Location location)
14236 : Expression(EXPRESSION_SLICE_VALUE, location),
14237 type_(type), valptr_(valptr), len_(len), cap_(cap)
14240 protected:
14242 do_traverse(Traverse*);
14244 Type*
14245 do_type()
14246 { return this->type_; }
14248 void
14249 do_determine_type(const Type_context*)
14250 { go_unreachable(); }
14252 Expression*
14253 do_copy()
14255 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14256 this->len_->copy(), this->cap_->copy(),
14257 this->location());
14260 tree
14261 do_get_tree(Translate_context* context);
14263 void
14264 do_dump_expression(Ast_dump_context*) const;
14266 private:
14267 // The type of the slice value.
14268 Type* type_;
14269 // The pointer to the values in the slice.
14270 Expression* valptr_;
14271 // The length of the slice.
14272 Expression* len_;
14273 // The capacity of the slice.
14274 Expression* cap_;
14278 Slice_value_expression::do_traverse(Traverse* traverse)
14280 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14281 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14282 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14283 return TRAVERSE_EXIT;
14284 return TRAVERSE_CONTINUE;
14287 tree
14288 Slice_value_expression::do_get_tree(Translate_context* context)
14290 std::vector<Bexpression*> vals(3);
14291 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14292 vals[1] = tree_to_expr(this->len_->get_tree(context));
14293 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14295 Gogo* gogo = context->gogo();
14296 Btype* btype = this->type_->get_backend(gogo);
14297 Bexpression* ret =
14298 gogo->backend()->constructor_expression(btype, vals, this->location());
14299 return expr_to_tree(ret);
14302 void
14303 Slice_value_expression::do_dump_expression(
14304 Ast_dump_context* ast_dump_context) const
14306 ast_dump_context->ostream() << "slicevalue(";
14307 ast_dump_context->ostream() << "values: ";
14308 this->valptr_->dump_expression(ast_dump_context);
14309 ast_dump_context->ostream() << ", length: ";
14310 this->len_->dump_expression(ast_dump_context);
14311 ast_dump_context->ostream() << ", capacity: ";
14312 this->cap_->dump_expression(ast_dump_context);
14313 ast_dump_context->ostream() << ")";
14316 Expression*
14317 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14318 Expression* cap, Location location)
14320 go_assert(at->is_slice_type());
14321 return new Slice_value_expression(at, valptr, len, cap, location);
14324 // An expression that evaluates to some characteristic of a non-empty interface.
14325 // This is used to access the method table or underlying object of an interface.
14327 class Interface_info_expression : public Expression
14329 public:
14330 Interface_info_expression(Expression* iface, Interface_info iface_info,
14331 Location location)
14332 : Expression(EXPRESSION_INTERFACE_INFO, location),
14333 iface_(iface), iface_info_(iface_info)
14336 protected:
14337 Type*
14338 do_type();
14340 void
14341 do_determine_type(const Type_context*)
14344 Expression*
14345 do_copy()
14347 return new Interface_info_expression(this->iface_->copy(),
14348 this->iface_info_, this->location());
14351 tree
14352 do_get_tree(Translate_context* context);
14354 void
14355 do_dump_expression(Ast_dump_context*) const;
14357 void
14358 do_issue_nil_check()
14359 { this->iface_->issue_nil_check(); }
14361 private:
14362 // The interface for which we are getting information.
14363 Expression* iface_;
14364 // What information we want.
14365 Interface_info iface_info_;
14368 // Return the type of the interface info.
14370 Type*
14371 Interface_info_expression::do_type()
14373 switch (this->iface_info_)
14375 case INTERFACE_INFO_METHODS:
14377 Type* pdt = Type::make_type_descriptor_ptr_type();
14378 if (this->iface_->type()->interface_type()->is_empty())
14379 return pdt;
14381 Location loc = this->location();
14382 Struct_field_list* sfl = new Struct_field_list();
14383 sfl->push_back(
14384 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14386 Interface_type* itype = this->iface_->type()->interface_type();
14387 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14388 p != itype->methods()->end();
14389 ++p)
14391 Function_type* ft = p->type()->function_type();
14392 go_assert(ft->receiver() == NULL);
14394 const Typed_identifier_list* params = ft->parameters();
14395 Typed_identifier_list* mparams = new Typed_identifier_list();
14396 if (params != NULL)
14397 mparams->reserve(params->size() + 1);
14398 Type* vt = Type::make_pointer_type(Type::make_void_type());
14399 mparams->push_back(Typed_identifier("", vt, ft->location()));
14400 if (params != NULL)
14402 for (Typed_identifier_list::const_iterator pp = params->begin();
14403 pp != params->end();
14404 ++pp)
14405 mparams->push_back(*pp);
14408 Typed_identifier_list* mresults = (ft->results() == NULL
14409 ? NULL
14410 : ft->results()->copy());
14411 Backend_function_type* mft =
14412 Type::make_backend_function_type(NULL, mparams, mresults,
14413 ft->location());
14415 std::string fname = Gogo::unpack_hidden_name(p->name());
14416 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14419 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14421 case INTERFACE_INFO_OBJECT:
14422 return Type::make_pointer_type(Type::make_void_type());
14423 default:
14424 go_unreachable();
14428 // Return interface information in GENERIC.
14430 tree
14431 Interface_info_expression::do_get_tree(Translate_context* context)
14433 Gogo* gogo = context->gogo();
14435 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14436 Bexpression* ret;
14437 switch (this->iface_info_)
14439 case INTERFACE_INFO_METHODS:
14440 case INTERFACE_INFO_OBJECT:
14441 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14442 this->location());
14443 break;
14444 default:
14445 go_unreachable();
14447 return expr_to_tree(ret);
14450 // Dump ast representation for an interface info expression.
14452 void
14453 Interface_info_expression::do_dump_expression(
14454 Ast_dump_context* ast_dump_context) const
14456 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14457 ast_dump_context->ostream() << "interfaceinfo(";
14458 this->iface_->dump_expression(ast_dump_context);
14459 ast_dump_context->ostream() << ",";
14460 ast_dump_context->ostream() <<
14461 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14462 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14463 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14464 : "unknown");
14465 ast_dump_context->ostream() << ")";
14468 // Make an interface info expression.
14470 Expression*
14471 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14472 Location location)
14474 return new Interface_info_expression(iface, iface_info, location);
14477 // An expression that represents an interface value. The first field is either
14478 // a type descriptor for an empty interface or a pointer to the interface method
14479 // table for a non-empty interface. The second field is always the object.
14481 class Interface_value_expression : public Expression
14483 public:
14484 Interface_value_expression(Type* type, Expression* first_field,
14485 Expression* obj, Location location)
14486 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14487 type_(type), first_field_(first_field), obj_(obj)
14490 protected:
14492 do_traverse(Traverse*);
14494 Type*
14495 do_type()
14496 { return this->type_; }
14498 void
14499 do_determine_type(const Type_context*)
14500 { go_unreachable(); }
14502 Expression*
14503 do_copy()
14505 return new Interface_value_expression(this->type_,
14506 this->first_field_->copy(),
14507 this->obj_->copy(), this->location());
14510 tree
14511 do_get_tree(Translate_context* context);
14513 void
14514 do_dump_expression(Ast_dump_context*) const;
14516 private:
14517 // The type of the interface value.
14518 Type* type_;
14519 // The first field of the interface (either a type descriptor or a pointer
14520 // to the method table.
14521 Expression* first_field_;
14522 // The underlying object of the interface.
14523 Expression* obj_;
14527 Interface_value_expression::do_traverse(Traverse* traverse)
14529 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14530 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14531 return TRAVERSE_EXIT;
14532 return TRAVERSE_CONTINUE;
14535 tree
14536 Interface_value_expression::do_get_tree(Translate_context* context)
14538 std::vector<Bexpression*> vals(2);
14539 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14540 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14542 Gogo* gogo = context->gogo();
14543 Btype* btype = this->type_->get_backend(gogo);
14544 Bexpression* ret =
14545 gogo->backend()->constructor_expression(btype, vals, this->location());
14546 return expr_to_tree(ret);
14549 void
14550 Interface_value_expression::do_dump_expression(
14551 Ast_dump_context* ast_dump_context) const
14553 ast_dump_context->ostream() << "interfacevalue(";
14554 ast_dump_context->ostream() <<
14555 (this->type_->interface_type()->is_empty()
14556 ? "type_descriptor: "
14557 : "methods: ");
14558 this->first_field_->dump_expression(ast_dump_context);
14559 ast_dump_context->ostream() << ", object: ";
14560 this->obj_->dump_expression(ast_dump_context);
14561 ast_dump_context->ostream() << ")";
14564 Expression*
14565 Expression::make_interface_value(Type* type, Expression* first_value,
14566 Expression* object, Location location)
14568 return new Interface_value_expression(type, first_value, object, location);
14571 // An interface method table for a pair of types: an interface type and a type
14572 // that implements that interface.
14574 class Interface_mtable_expression : public Expression
14576 public:
14577 Interface_mtable_expression(Interface_type* itype, Type* type,
14578 bool is_pointer, Location location)
14579 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14580 itype_(itype), type_(type), is_pointer_(is_pointer),
14581 method_table_type_(NULL), bvar_(NULL)
14584 protected:
14586 do_traverse(Traverse*);
14588 Type*
14589 do_type();
14591 bool
14592 is_immutable() const
14593 { return true; }
14595 void
14596 do_determine_type(const Type_context*)
14597 { go_unreachable(); }
14599 Expression*
14600 do_copy()
14602 return new Interface_mtable_expression(this->itype_, this->type_,
14603 this->is_pointer_, this->location());
14606 bool
14607 do_is_addressable() const
14608 { return true; }
14610 tree
14611 do_get_tree(Translate_context* context);
14613 void
14614 do_dump_expression(Ast_dump_context*) const;
14616 private:
14617 // The interface type for which the methods are defined.
14618 Interface_type* itype_;
14619 // The type to construct the interface method table for.
14620 Type* type_;
14621 // Whether this table contains the method set for the receiver type or the
14622 // pointer receiver type.
14623 bool is_pointer_;
14624 // The type of the method table.
14625 Type* method_table_type_;
14626 // The backend variable that refers to the interface method table.
14627 Bvariable* bvar_;
14631 Interface_mtable_expression::do_traverse(Traverse* traverse)
14633 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14634 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14635 return TRAVERSE_EXIT;
14636 return TRAVERSE_CONTINUE;
14639 Type*
14640 Interface_mtable_expression::do_type()
14642 if (this->method_table_type_ != NULL)
14643 return this->method_table_type_;
14645 const Typed_identifier_list* interface_methods = this->itype_->methods();
14646 go_assert(!interface_methods->empty());
14648 Struct_field_list* sfl = new Struct_field_list;
14649 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14650 this->location());
14651 sfl->push_back(Struct_field(tid));
14652 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14653 p != interface_methods->end();
14654 ++p)
14655 sfl->push_back(Struct_field(*p));
14656 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14657 return this->method_table_type_;
14660 tree
14661 Interface_mtable_expression::do_get_tree(Translate_context* context)
14663 Gogo* gogo = context->gogo();
14664 Bexpression* ret;
14665 Location loc = Linemap::predeclared_location();
14666 if (this->bvar_ != NULL)
14668 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14669 return expr_to_tree(ret);
14672 const Typed_identifier_list* interface_methods = this->itype_->methods();
14673 go_assert(!interface_methods->empty());
14675 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14676 + this->itype_->mangled_name(gogo)
14677 + "__"
14678 + this->type_->mangled_name(gogo));
14680 // See whether this interface has any hidden methods.
14681 bool has_hidden_methods = false;
14682 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14683 p != interface_methods->end();
14684 ++p)
14686 if (Gogo::is_hidden_name(p->name()))
14688 has_hidden_methods = true;
14689 break;
14693 // We already know that the named type is convertible to the
14694 // interface. If the interface has hidden methods, and the named
14695 // type is defined in a different package, then the interface
14696 // conversion table will be defined by that other package.
14697 if (has_hidden_methods
14698 && this->type_->named_type() != NULL
14699 && this->type_->named_type()->named_object()->package() != NULL)
14701 Btype* btype = this->type()->get_backend(gogo);
14702 this->bvar_ =
14703 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14704 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14705 return expr_to_tree(ret);
14708 // The first element is the type descriptor.
14709 Type* td_type;
14710 if (!this->is_pointer_)
14711 td_type = this->type_;
14712 else
14713 td_type = Type::make_pointer_type(this->type_);
14715 // Build an interface method table for a type: a type descriptor followed by a
14716 // list of function pointers, one for each interface method. This is used for
14717 // interfaces.
14718 Expression_list* svals = new Expression_list();
14719 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14721 Named_type* nt = this->type_->named_type();
14722 Struct_type* st = this->type_->struct_type();
14723 go_assert(nt != NULL || st != NULL);
14725 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14726 p != interface_methods->end();
14727 ++p)
14729 bool is_ambiguous;
14730 Method* m;
14731 if (nt != NULL)
14732 m = nt->method_function(p->name(), &is_ambiguous);
14733 else
14734 m = st->method_function(p->name(), &is_ambiguous);
14735 go_assert(m != NULL);
14736 Named_object* no = m->named_object();
14738 go_assert(no->is_function() || no->is_function_declaration());
14739 svals->push_back(Expression::make_func_code_reference(no, loc));
14742 Btype* btype = this->type()->get_backend(gogo);
14743 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14744 svals, loc);
14745 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14747 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14748 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14749 !is_public, btype, loc);
14750 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14751 !is_public, btype, loc, ctor);
14752 ret = gogo->backend()->var_expression(this->bvar_, loc);
14753 return expr_to_tree(ret);
14756 void
14757 Interface_mtable_expression::do_dump_expression(
14758 Ast_dump_context* ast_dump_context) const
14760 ast_dump_context->ostream() << "__go_"
14761 << (this->is_pointer_ ? "pimt__" : "imt_");
14762 ast_dump_context->dump_type(this->itype_);
14763 ast_dump_context->ostream() << "__";
14764 ast_dump_context->dump_type(this->type_);
14767 Expression*
14768 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14769 bool is_pointer, Location location)
14771 return new Interface_mtable_expression(itype, type, is_pointer, location);
14774 // An expression which evaluates to the offset of a field within a
14775 // struct. This, like Type_info_expression, q.v., is only used to
14776 // initialize fields of a type descriptor.
14778 class Struct_field_offset_expression : public Expression
14780 public:
14781 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14782 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14783 Linemap::predeclared_location()),
14784 type_(type), field_(field)
14787 protected:
14788 Type*
14789 do_type()
14790 { return Type::lookup_integer_type("uintptr"); }
14792 void
14793 do_determine_type(const Type_context*)
14796 Expression*
14797 do_copy()
14798 { return this; }
14800 tree
14801 do_get_tree(Translate_context* context);
14803 void
14804 do_dump_expression(Ast_dump_context*) const;
14806 private:
14807 // The type of the struct.
14808 Struct_type* type_;
14809 // The field.
14810 const Struct_field* field_;
14813 // Return a struct field offset in GENERIC.
14815 tree
14816 Struct_field_offset_expression::do_get_tree(Translate_context* context)
14818 const Struct_field_list* fields = this->type_->fields();
14819 Struct_field_list::const_iterator p;
14820 unsigned i = 0;
14821 for (p = fields->begin();
14822 p != fields->end();
14823 ++p, ++i)
14824 if (&*p == this->field_)
14825 break;
14826 go_assert(&*p == this->field_);
14828 Gogo* gogo = context->gogo();
14829 Btype* btype = this->type_->get_backend(gogo);
14831 size_t offset = gogo->backend()->type_field_offset(btype, i);
14832 mpz_t offsetval;
14833 mpz_init_set_ui(offsetval, offset);
14834 Type* uptr_type = Type::lookup_integer_type("uintptr");
14835 Expression* ret = Expression::make_integer(&offsetval, uptr_type,
14836 Linemap::predeclared_location());
14837 mpz_clear(offsetval);
14838 return ret->get_tree(context);
14841 // Dump ast representation for a struct field offset expression.
14843 void
14844 Struct_field_offset_expression::do_dump_expression(
14845 Ast_dump_context* ast_dump_context) const
14847 ast_dump_context->ostream() << "unsafe.Offsetof(";
14848 ast_dump_context->dump_type(this->type_);
14849 ast_dump_context->ostream() << '.';
14850 ast_dump_context->ostream() <<
14851 Gogo::message_name(this->field_->field_name());
14852 ast_dump_context->ostream() << ")";
14855 // Make an expression for a struct field offset.
14857 Expression*
14858 Expression::make_struct_field_offset(Struct_type* type,
14859 const Struct_field* field)
14861 return new Struct_field_offset_expression(type, field);
14864 // An expression which evaluates to a pointer to the map descriptor of
14865 // a map type.
14867 class Map_descriptor_expression : public Expression
14869 public:
14870 Map_descriptor_expression(Map_type* type, Location location)
14871 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14872 type_(type)
14875 protected:
14876 Type*
14877 do_type()
14878 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14880 void
14881 do_determine_type(const Type_context*)
14884 Expression*
14885 do_copy()
14886 { return this; }
14888 tree
14889 do_get_tree(Translate_context* context)
14891 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14892 this->location());
14893 return expr_to_tree(ret);
14896 void
14897 do_dump_expression(Ast_dump_context*) const;
14899 private:
14900 // The type for which this is the descriptor.
14901 Map_type* type_;
14904 // Dump ast representation for a map descriptor expression.
14906 void
14907 Map_descriptor_expression::do_dump_expression(
14908 Ast_dump_context* ast_dump_context) const
14910 ast_dump_context->ostream() << "map_descriptor(";
14911 ast_dump_context->dump_type(this->type_);
14912 ast_dump_context->ostream() << ")";
14915 // Make a map descriptor expression.
14917 Expression*
14918 Expression::make_map_descriptor(Map_type* type, Location location)
14920 return new Map_descriptor_expression(type, location);
14923 // An expression which evaluates to the address of an unnamed label.
14925 class Label_addr_expression : public Expression
14927 public:
14928 Label_addr_expression(Label* label, Location location)
14929 : Expression(EXPRESSION_LABEL_ADDR, location),
14930 label_(label)
14933 protected:
14934 Type*
14935 do_type()
14936 { return Type::make_pointer_type(Type::make_void_type()); }
14938 void
14939 do_determine_type(const Type_context*)
14942 Expression*
14943 do_copy()
14944 { return new Label_addr_expression(this->label_, this->location()); }
14946 tree
14947 do_get_tree(Translate_context* context)
14949 return expr_to_tree(this->label_->get_addr(context, this->location()));
14952 void
14953 do_dump_expression(Ast_dump_context* ast_dump_context) const
14954 { ast_dump_context->ostream() << this->label_->name(); }
14956 private:
14957 // The label whose address we are taking.
14958 Label* label_;
14961 // Make an expression for the address of an unnamed label.
14963 Expression*
14964 Expression::make_label_addr(Label* label, Location location)
14966 return new Label_addr_expression(label, location);
14969 // Conditional expressions.
14971 class Conditional_expression : public Expression
14973 public:
14974 Conditional_expression(Expression* cond, Expression* then_expr,
14975 Expression* else_expr, Location location)
14976 : Expression(EXPRESSION_CONDITIONAL, location),
14977 cond_(cond), then_(then_expr), else_(else_expr)
14980 protected:
14982 do_traverse(Traverse*);
14984 Type*
14985 do_type();
14987 void
14988 do_determine_type(const Type_context*);
14990 Expression*
14991 do_copy()
14993 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14994 this->else_->copy(), this->location());
14997 tree
14998 do_get_tree(Translate_context* context);
15000 void
15001 do_dump_expression(Ast_dump_context*) const;
15003 private:
15004 // The condition to be checked.
15005 Expression* cond_;
15006 // The expression to execute if the condition is true.
15007 Expression* then_;
15008 // The expression to execute if the condition is false.
15009 Expression* else_;
15012 // Traversal.
15015 Conditional_expression::do_traverse(Traverse* traverse)
15017 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15018 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15019 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15020 return TRAVERSE_EXIT;
15021 return TRAVERSE_CONTINUE;
15024 // Return the type of the conditional expression.
15026 Type*
15027 Conditional_expression::do_type()
15029 Type* result_type = Type::make_void_type();
15030 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15031 NULL))
15032 result_type = this->then_->type();
15033 else if (this->then_->is_nil_expression()
15034 || this->else_->is_nil_expression())
15035 result_type = (!this->then_->is_nil_expression()
15036 ? this->then_->type()
15037 : this->else_->type());
15038 return result_type;
15041 // Determine type for a conditional expression.
15043 void
15044 Conditional_expression::do_determine_type(const Type_context* context)
15046 this->cond_->determine_type_no_context();
15047 this->then_->determine_type(context);
15048 this->else_->determine_type(context);
15051 // Get the backend representation of a conditional expression.
15053 tree
15054 Conditional_expression::do_get_tree(Translate_context* context)
15056 Gogo* gogo = context->gogo();
15057 Btype* result_btype = this->type()->get_backend(gogo);
15058 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15059 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15060 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15061 Bexpression* ret =
15062 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15063 this->location());
15064 return expr_to_tree(ret);
15067 // Dump ast representation of a conditional expression.
15069 void
15070 Conditional_expression::do_dump_expression(
15071 Ast_dump_context* ast_dump_context) const
15073 ast_dump_context->ostream() << "(";
15074 ast_dump_context->dump_expression(this->cond_);
15075 ast_dump_context->ostream() << " ? ";
15076 ast_dump_context->dump_expression(this->then_);
15077 ast_dump_context->ostream() << " : ";
15078 ast_dump_context->dump_expression(this->else_);
15079 ast_dump_context->ostream() << ") ";
15082 // Make a conditional expression.
15084 Expression*
15085 Expression::make_conditional(Expression* cond, Expression* then,
15086 Expression* else_expr, Location location)
15088 return new Conditional_expression(cond, then, else_expr, location);
15091 // Compound expressions.
15093 class Compound_expression : public Expression
15095 public:
15096 Compound_expression(Expression* init, Expression* expr, Location location)
15097 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15100 protected:
15102 do_traverse(Traverse*);
15104 Type*
15105 do_type();
15107 void
15108 do_determine_type(const Type_context*);
15110 Expression*
15111 do_copy()
15113 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15114 this->location());
15117 tree
15118 do_get_tree(Translate_context* context);
15120 void
15121 do_dump_expression(Ast_dump_context*) const;
15123 private:
15124 // The expression that is evaluated first and discarded.
15125 Expression* init_;
15126 // The expression that is evaluated and returned.
15127 Expression* expr_;
15130 // Traversal.
15133 Compound_expression::do_traverse(Traverse* traverse)
15135 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15136 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15137 return TRAVERSE_EXIT;
15138 return TRAVERSE_CONTINUE;
15141 // Return the type of the compound expression.
15143 Type*
15144 Compound_expression::do_type()
15146 return this->expr_->type();
15149 // Determine type for a compound expression.
15151 void
15152 Compound_expression::do_determine_type(const Type_context* context)
15154 this->init_->determine_type_no_context();
15155 this->expr_->determine_type(context);
15158 // Get the backend representation of a compound expression.
15160 tree
15161 Compound_expression::do_get_tree(Translate_context* context)
15163 Gogo* gogo = context->gogo();
15164 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15165 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15166 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15167 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15168 this->location());
15169 return expr_to_tree(ret);
15172 // Dump ast representation of a conditional expression.
15174 void
15175 Compound_expression::do_dump_expression(
15176 Ast_dump_context* ast_dump_context) const
15178 ast_dump_context->ostream() << "(";
15179 ast_dump_context->dump_expression(this->init_);
15180 ast_dump_context->ostream() << ",";
15181 ast_dump_context->dump_expression(this->expr_);
15182 ast_dump_context->ostream() << ") ";
15185 // Make a compound expression.
15187 Expression*
15188 Expression::make_compound(Expression* init, Expression* expr, Location location)
15190 return new Compound_expression(init, expr, location);
15193 // Import an expression. This comes at the end in order to see the
15194 // various class definitions.
15196 Expression*
15197 Expression::import_expression(Import* imp)
15199 int c = imp->peek_char();
15200 if (imp->match_c_string("- ")
15201 || imp->match_c_string("! ")
15202 || imp->match_c_string("^ "))
15203 return Unary_expression::do_import(imp);
15204 else if (c == '(')
15205 return Binary_expression::do_import(imp);
15206 else if (imp->match_c_string("true")
15207 || imp->match_c_string("false"))
15208 return Boolean_expression::do_import(imp);
15209 else if (c == '"')
15210 return String_expression::do_import(imp);
15211 else if (c == '-' || (c >= '0' && c <= '9'))
15213 // This handles integers, floats and complex constants.
15214 return Integer_expression::do_import(imp);
15216 else if (imp->match_c_string("nil"))
15217 return Nil_expression::do_import(imp);
15218 else if (imp->match_c_string("convert"))
15219 return Type_conversion_expression::do_import(imp);
15220 else
15222 error_at(imp->location(), "import error: expected expression");
15223 return Expression::make_error(imp->location());
15227 // Class Expression_list.
15229 // Traverse the list.
15232 Expression_list::traverse(Traverse* traverse)
15234 for (Expression_list::iterator p = this->begin();
15235 p != this->end();
15236 ++p)
15238 if (*p != NULL)
15240 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15241 return TRAVERSE_EXIT;
15244 return TRAVERSE_CONTINUE;
15247 // Copy the list.
15249 Expression_list*
15250 Expression_list::copy()
15252 Expression_list* ret = new Expression_list();
15253 for (Expression_list::iterator p = this->begin();
15254 p != this->end();
15255 ++p)
15257 if (*p == NULL)
15258 ret->push_back(NULL);
15259 else
15260 ret->push_back((*p)->copy());
15262 return ret;
15265 // Return whether an expression list has an error expression.
15267 bool
15268 Expression_list::contains_error() const
15270 for (Expression_list::const_iterator p = this->begin();
15271 p != this->end();
15272 ++p)
15273 if (*p != NULL && (*p)->is_error_expression())
15274 return true;
15275 return false;
15278 // Class Numeric_constant.
15280 // Destructor.
15282 Numeric_constant::~Numeric_constant()
15284 this->clear();
15287 // Copy constructor.
15289 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15290 : classification_(a.classification_), type_(a.type_)
15292 switch (a.classification_)
15294 case NC_INVALID:
15295 break;
15296 case NC_INT:
15297 case NC_RUNE:
15298 mpz_init_set(this->u_.int_val, a.u_.int_val);
15299 break;
15300 case NC_FLOAT:
15301 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15302 break;
15303 case NC_COMPLEX:
15304 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15305 GMP_RNDN);
15306 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15307 GMP_RNDN);
15308 break;
15309 default:
15310 go_unreachable();
15314 // Assignment operator.
15316 Numeric_constant&
15317 Numeric_constant::operator=(const Numeric_constant& a)
15319 this->clear();
15320 this->classification_ = a.classification_;
15321 this->type_ = a.type_;
15322 switch (a.classification_)
15324 case NC_INVALID:
15325 break;
15326 case NC_INT:
15327 case NC_RUNE:
15328 mpz_init_set(this->u_.int_val, a.u_.int_val);
15329 break;
15330 case NC_FLOAT:
15331 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15332 break;
15333 case NC_COMPLEX:
15334 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15335 GMP_RNDN);
15336 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15337 GMP_RNDN);
15338 break;
15339 default:
15340 go_unreachable();
15342 return *this;
15345 // Clear the contents.
15347 void
15348 Numeric_constant::clear()
15350 switch (this->classification_)
15352 case NC_INVALID:
15353 break;
15354 case NC_INT:
15355 case NC_RUNE:
15356 mpz_clear(this->u_.int_val);
15357 break;
15358 case NC_FLOAT:
15359 mpfr_clear(this->u_.float_val);
15360 break;
15361 case NC_COMPLEX:
15362 mpfr_clear(this->u_.complex_val.real);
15363 mpfr_clear(this->u_.complex_val.imag);
15364 break;
15365 default:
15366 go_unreachable();
15368 this->classification_ = NC_INVALID;
15371 // Set to an unsigned long value.
15373 void
15374 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15376 this->clear();
15377 this->classification_ = NC_INT;
15378 this->type_ = type;
15379 mpz_init_set_ui(this->u_.int_val, val);
15382 // Set to an integer value.
15384 void
15385 Numeric_constant::set_int(Type* type, const mpz_t val)
15387 this->clear();
15388 this->classification_ = NC_INT;
15389 this->type_ = type;
15390 mpz_init_set(this->u_.int_val, val);
15393 // Set to a rune value.
15395 void
15396 Numeric_constant::set_rune(Type* type, const mpz_t val)
15398 this->clear();
15399 this->classification_ = NC_RUNE;
15400 this->type_ = type;
15401 mpz_init_set(this->u_.int_val, val);
15404 // Set to a floating point value.
15406 void
15407 Numeric_constant::set_float(Type* type, const mpfr_t val)
15409 this->clear();
15410 this->classification_ = NC_FLOAT;
15411 this->type_ = type;
15412 // Numeric constants do not have negative zero values, so remove
15413 // them here. They also don't have infinity or NaN values, but we
15414 // should never see them here.
15415 if (mpfr_zero_p(val))
15416 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15417 else
15418 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15421 // Set to a complex value.
15423 void
15424 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15426 this->clear();
15427 this->classification_ = NC_COMPLEX;
15428 this->type_ = type;
15429 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15430 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15433 // Get an int value.
15435 void
15436 Numeric_constant::get_int(mpz_t* val) const
15438 go_assert(this->is_int());
15439 mpz_init_set(*val, this->u_.int_val);
15442 // Get a rune value.
15444 void
15445 Numeric_constant::get_rune(mpz_t* val) const
15447 go_assert(this->is_rune());
15448 mpz_init_set(*val, this->u_.int_val);
15451 // Get a floating point value.
15453 void
15454 Numeric_constant::get_float(mpfr_t* val) const
15456 go_assert(this->is_float());
15457 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15460 // Get a complex value.
15462 void
15463 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15465 go_assert(this->is_complex());
15466 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15467 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15470 // Express value as unsigned long if possible.
15472 Numeric_constant::To_unsigned_long
15473 Numeric_constant::to_unsigned_long(unsigned long* val) const
15475 switch (this->classification_)
15477 case NC_INT:
15478 case NC_RUNE:
15479 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15480 case NC_FLOAT:
15481 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15482 case NC_COMPLEX:
15483 if (!mpfr_zero_p(this->u_.complex_val.imag))
15484 return NC_UL_NOTINT;
15485 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15486 default:
15487 go_unreachable();
15491 // Express integer value as unsigned long if possible.
15493 Numeric_constant::To_unsigned_long
15494 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15495 unsigned long *val) const
15497 if (mpz_sgn(ival) < 0)
15498 return NC_UL_NEGATIVE;
15499 unsigned long ui = mpz_get_ui(ival);
15500 if (mpz_cmp_ui(ival, ui) != 0)
15501 return NC_UL_BIG;
15502 *val = ui;
15503 return NC_UL_VALID;
15506 // Express floating point value as unsigned long if possible.
15508 Numeric_constant::To_unsigned_long
15509 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15510 unsigned long *val) const
15512 if (!mpfr_integer_p(fval))
15513 return NC_UL_NOTINT;
15514 mpz_t ival;
15515 mpz_init(ival);
15516 mpfr_get_z(ival, fval, GMP_RNDN);
15517 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15518 mpz_clear(ival);
15519 return ret;
15522 // Convert value to integer if possible.
15524 bool
15525 Numeric_constant::to_int(mpz_t* val) const
15527 switch (this->classification_)
15529 case NC_INT:
15530 case NC_RUNE:
15531 mpz_init_set(*val, this->u_.int_val);
15532 return true;
15533 case NC_FLOAT:
15534 if (!mpfr_integer_p(this->u_.float_val))
15535 return false;
15536 mpz_init(*val);
15537 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15538 return true;
15539 case NC_COMPLEX:
15540 if (!mpfr_zero_p(this->u_.complex_val.imag)
15541 || !mpfr_integer_p(this->u_.complex_val.real))
15542 return false;
15543 mpz_init(*val);
15544 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15545 return true;
15546 default:
15547 go_unreachable();
15551 // Convert value to floating point if possible.
15553 bool
15554 Numeric_constant::to_float(mpfr_t* val) const
15556 switch (this->classification_)
15558 case NC_INT:
15559 case NC_RUNE:
15560 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15561 return true;
15562 case NC_FLOAT:
15563 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15564 return true;
15565 case NC_COMPLEX:
15566 if (!mpfr_zero_p(this->u_.complex_val.imag))
15567 return false;
15568 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15569 return true;
15570 default:
15571 go_unreachable();
15575 // Convert value to complex.
15577 bool
15578 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15580 switch (this->classification_)
15582 case NC_INT:
15583 case NC_RUNE:
15584 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15585 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15586 return true;
15587 case NC_FLOAT:
15588 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15589 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15590 return true;
15591 case NC_COMPLEX:
15592 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15593 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15594 return true;
15595 default:
15596 go_unreachable();
15600 // Get the type.
15602 Type*
15603 Numeric_constant::type() const
15605 if (this->type_ != NULL)
15606 return this->type_;
15607 switch (this->classification_)
15609 case NC_INT:
15610 return Type::make_abstract_integer_type();
15611 case NC_RUNE:
15612 return Type::make_abstract_character_type();
15613 case NC_FLOAT:
15614 return Type::make_abstract_float_type();
15615 case NC_COMPLEX:
15616 return Type::make_abstract_complex_type();
15617 default:
15618 go_unreachable();
15622 // If the constant can be expressed in TYPE, then set the type of the
15623 // constant to TYPE and return true. Otherwise return false, and, if
15624 // ISSUE_ERROR is true, report an appropriate error message.
15626 bool
15627 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15629 bool ret;
15630 if (type == NULL)
15631 ret = true;
15632 else if (type->integer_type() != NULL)
15633 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15634 else if (type->float_type() != NULL)
15635 ret = this->check_float_type(type->float_type(), issue_error, loc);
15636 else if (type->complex_type() != NULL)
15637 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15638 else
15639 go_unreachable();
15640 if (ret)
15641 this->type_ = type;
15642 return ret;
15645 // Check whether the constant can be expressed in an integer type.
15647 bool
15648 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15649 Location location) const
15651 mpz_t val;
15652 switch (this->classification_)
15654 case NC_INT:
15655 case NC_RUNE:
15656 mpz_init_set(val, this->u_.int_val);
15657 break;
15659 case NC_FLOAT:
15660 if (!mpfr_integer_p(this->u_.float_val))
15662 if (issue_error)
15663 error_at(location, "floating point constant truncated to integer");
15664 return false;
15666 mpz_init(val);
15667 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15668 break;
15670 case NC_COMPLEX:
15671 if (!mpfr_integer_p(this->u_.complex_val.real)
15672 || !mpfr_zero_p(this->u_.complex_val.imag))
15674 if (issue_error)
15675 error_at(location, "complex constant truncated to integer");
15676 return false;
15678 mpz_init(val);
15679 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15680 break;
15682 default:
15683 go_unreachable();
15686 bool ret;
15687 if (type->is_abstract())
15688 ret = true;
15689 else
15691 int bits = mpz_sizeinbase(val, 2);
15692 if (type->is_unsigned())
15694 // For an unsigned type we can only accept a nonnegative
15695 // number, and we must be able to represents at least BITS.
15696 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15698 else
15700 // For a signed type we need an extra bit to indicate the
15701 // sign. We have to handle the most negative integer
15702 // specially.
15703 ret = (bits + 1 <= type->bits()
15704 || (bits <= type->bits()
15705 && mpz_sgn(val) < 0
15706 && (mpz_scan1(val, 0)
15707 == static_cast<unsigned long>(type->bits() - 1))
15708 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15712 if (!ret && issue_error)
15713 error_at(location, "integer constant overflow");
15715 return ret;
15718 // Check whether the constant can be expressed in a floating point
15719 // type.
15721 bool
15722 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15723 Location location)
15725 mpfr_t val;
15726 switch (this->classification_)
15728 case NC_INT:
15729 case NC_RUNE:
15730 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15731 break;
15733 case NC_FLOAT:
15734 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15735 break;
15737 case NC_COMPLEX:
15738 if (!mpfr_zero_p(this->u_.complex_val.imag))
15740 if (issue_error)
15741 error_at(location, "complex constant truncated to float");
15742 return false;
15744 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15745 break;
15747 default:
15748 go_unreachable();
15751 bool ret;
15752 if (type->is_abstract())
15753 ret = true;
15754 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15756 // A NaN or Infinity always fits in the range of the type.
15757 ret = true;
15759 else
15761 mp_exp_t exp = mpfr_get_exp(val);
15762 mp_exp_t max_exp;
15763 switch (type->bits())
15765 case 32:
15766 max_exp = 128;
15767 break;
15768 case 64:
15769 max_exp = 1024;
15770 break;
15771 default:
15772 go_unreachable();
15775 ret = exp <= max_exp;
15777 if (ret)
15779 // Round the constant to the desired type.
15780 mpfr_t t;
15781 mpfr_init(t);
15782 switch (type->bits())
15784 case 32:
15785 mpfr_set_prec(t, 24);
15786 break;
15787 case 64:
15788 mpfr_set_prec(t, 53);
15789 break;
15790 default:
15791 go_unreachable();
15793 mpfr_set(t, val, GMP_RNDN);
15794 mpfr_set(val, t, GMP_RNDN);
15795 mpfr_clear(t);
15797 this->set_float(type, val);
15801 mpfr_clear(val);
15803 if (!ret && issue_error)
15804 error_at(location, "floating point constant overflow");
15806 return ret;
15809 // Check whether the constant can be expressed in a complex type.
15811 bool
15812 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15813 Location location)
15815 if (type->is_abstract())
15816 return true;
15818 mp_exp_t max_exp;
15819 switch (type->bits())
15821 case 64:
15822 max_exp = 128;
15823 break;
15824 case 128:
15825 max_exp = 1024;
15826 break;
15827 default:
15828 go_unreachable();
15831 mpfr_t real;
15832 mpfr_t imag;
15833 switch (this->classification_)
15835 case NC_INT:
15836 case NC_RUNE:
15837 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
15838 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15839 break;
15841 case NC_FLOAT:
15842 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
15843 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15844 break;
15846 case NC_COMPLEX:
15847 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
15848 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
15849 break;
15851 default:
15852 go_unreachable();
15855 bool ret = true;
15856 if (!mpfr_nan_p(real)
15857 && !mpfr_inf_p(real)
15858 && !mpfr_zero_p(real)
15859 && mpfr_get_exp(real) > max_exp)
15861 if (issue_error)
15862 error_at(location, "complex real part overflow");
15863 ret = false;
15866 if (!mpfr_nan_p(imag)
15867 && !mpfr_inf_p(imag)
15868 && !mpfr_zero_p(imag)
15869 && mpfr_get_exp(imag) > max_exp)
15871 if (issue_error)
15872 error_at(location, "complex imaginary part overflow");
15873 ret = false;
15876 if (ret)
15878 // Round the constant to the desired type.
15879 mpfr_t t;
15880 mpfr_init(t);
15881 switch (type->bits())
15883 case 64:
15884 mpfr_set_prec(t, 24);
15885 break;
15886 case 128:
15887 mpfr_set_prec(t, 53);
15888 break;
15889 default:
15890 go_unreachable();
15892 mpfr_set(t, real, GMP_RNDN);
15893 mpfr_set(real, t, GMP_RNDN);
15894 mpfr_set(t, imag, GMP_RNDN);
15895 mpfr_set(imag, t, GMP_RNDN);
15896 mpfr_clear(t);
15898 this->set_complex(type, real, imag);
15901 mpfr_clear(real);
15902 mpfr_clear(imag);
15904 return ret;
15907 // Return an Expression for this value.
15909 Expression*
15910 Numeric_constant::expression(Location loc) const
15912 switch (this->classification_)
15914 case NC_INT:
15915 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15916 case NC_RUNE:
15917 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15918 case NC_FLOAT:
15919 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15920 case NC_COMPLEX:
15921 return Expression::make_complex(&this->u_.complex_val.real,
15922 &this->u_.complex_val.imag,
15923 this->type_, loc);
15924 default:
15925 go_unreachable();