compiler: Don't crash on append with single argument.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob83ee6d923bb2803c5679d554e2d4e6505eae2652
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 "go-c.h"
12 #include "gogo.h"
13 #include "types.h"
14 #include "export.h"
15 #include "import.h"
16 #include "statements.h"
17 #include "lex.h"
18 #include "runtime.h"
19 #include "backend.h"
20 #include "expressions.h"
21 #include "ast-dump.h"
23 // Class Expression.
25 Expression::Expression(Expression_classification classification,
26 Location location)
27 : classification_(classification), location_(location)
31 Expression::~Expression()
35 // Traverse the expressions.
37 int
38 Expression::traverse(Expression** pexpr, Traverse* traverse)
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
49 return expr->do_traverse(traverse);
52 // Traverse subexpressions of this expression.
54 int
55 Expression::traverse_subexpressions(Traverse* traverse)
57 return this->do_traverse(traverse);
60 // Default implementation for do_traverse for child classes.
62 int
63 Expression::do_traverse(Traverse*)
65 return TRAVERSE_CONTINUE;
68 // This virtual function is called by the parser if the value of this
69 // expression is being discarded. By default, we give an error.
70 // Expressions with side effects override.
72 bool
73 Expression::do_discarding_value()
75 this->unused_value_error();
76 return false;
79 // This virtual function is called to export expressions. This will
80 // only be used by expressions which may be constant.
82 void
83 Expression::do_export(Export*) const
85 go_unreachable();
88 // Give an error saying that the value of the expression is not used.
90 void
91 Expression::unused_value_error()
93 this->report_error(_("value computed is not used"));
96 // Note that this expression is an error. This is called by children
97 // when they discover an error.
99 void
100 Expression::set_is_error()
102 this->classification_ = EXPRESSION_ERROR;
105 // For children to call to report an error conveniently.
107 void
108 Expression::report_error(const char* msg)
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
114 // Set types of variables and constants. This is implemented by the
115 // child class.
117 void
118 Expression::determine_type(const Type_context* context)
120 this->do_determine_type(context);
123 // Set types when there is no context.
125 void
126 Expression::determine_type_no_context()
128 Type_context context;
129 this->do_determine_type(&context);
132 // Return an expression handling any conversions which must be done during
133 // assignment.
135 Expression*
136 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
137 Expression* rhs, Location location)
139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
148 if (rhs_type->interface_type() == NULL)
149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
150 else
151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
159 // Assigning nil to a slice.
160 Expression* nil = Expression::make_nil(location);
161 Expression* zero = Expression::make_integer_ul(0, NULL, location);
162 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
164 else if (rhs_type->is_nil_type())
165 return Expression::make_nil(location);
166 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
168 // No conversion is needed.
169 return rhs;
171 else if (lhs_type->points_to() != NULL)
172 return Expression::make_unsafe_cast(lhs_type, rhs, location);
173 else if (lhs_type->is_numeric_type())
174 return Expression::make_cast(lhs_type, rhs, location);
175 else if ((lhs_type->struct_type() != NULL
176 && rhs_type->struct_type() != NULL)
177 || (lhs_type->array_type() != NULL
178 && rhs_type->array_type() != NULL))
180 // Avoid confusion from zero sized variables which may be
181 // represented as non-zero-sized.
182 // TODO(cmang): This check is for a GCC-specific issue, and should be
183 // removed from the frontend. FIXME.
184 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
185 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
186 if (rhs_size == 0 || lhs_size == 0)
187 return rhs;
189 // This conversion must be permitted by Go, or we wouldn't have
190 // gotten here.
191 return Expression::make_unsafe_cast(lhs_type, rhs, location);
193 else
194 return rhs;
197 // Return an expression for a conversion from a non-interface type to an
198 // interface type.
200 Expression*
201 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
202 Location location)
204 Interface_type* lhs_interface_type = lhs_type->interface_type();
205 bool lhs_is_empty = lhs_interface_type->is_empty();
207 // Since RHS_TYPE is a static type, we can create the interface
208 // method table at compile time.
210 // When setting an interface to nil, we just set both fields to
211 // NULL.
212 Type* rhs_type = rhs->type();
213 if (rhs_type->is_nil_type())
215 Expression* nil = Expression::make_nil(location);
216 return Expression::make_interface_value(lhs_type, nil, nil, location);
219 // This should have been checked already.
220 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
222 // An interface is a tuple. If LHS_TYPE is an empty interface type,
223 // then the first field is the type descriptor for RHS_TYPE.
224 // Otherwise it is the interface method table for RHS_TYPE.
225 Expression* first_field;
226 if (lhs_is_empty)
227 first_field = Expression::make_type_descriptor(rhs_type, location);
228 else
230 // Build the interface method table for this interface and this
231 // object type: a list of function pointers for each interface
232 // method.
233 Named_type* rhs_named_type = rhs_type->named_type();
234 Struct_type* rhs_struct_type = rhs_type->struct_type();
235 bool is_pointer = false;
236 if (rhs_named_type == NULL && rhs_struct_type == NULL)
238 rhs_named_type = rhs_type->deref()->named_type();
239 rhs_struct_type = rhs_type->deref()->struct_type();
240 is_pointer = true;
242 if (rhs_named_type != NULL)
243 first_field =
244 rhs_named_type->interface_method_table(lhs_interface_type,
245 is_pointer);
246 else if (rhs_struct_type != NULL)
247 first_field =
248 rhs_struct_type->interface_method_table(lhs_interface_type,
249 is_pointer);
250 else
251 first_field = Expression::make_nil(location);
254 Expression* obj;
255 if (rhs_type->points_to() != NULL)
257 // We are assigning a pointer to the interface; the interface
258 // holds the pointer itself.
259 obj = rhs;
261 else
263 // We are assigning a non-pointer value to the interface; the
264 // interface gets a copy of the value in the heap.
265 obj = Expression::make_heap_expression(rhs, location);
268 return Expression::make_interface_value(lhs_type, first_field, obj, location);
271 // Return an expression for the type descriptor of RHS.
273 Expression*
274 Expression::get_interface_type_descriptor(Expression* rhs)
276 go_assert(rhs->type()->interface_type() != NULL);
277 Location location = rhs->location();
279 // The type descriptor is the first field of an empty interface.
280 if (rhs->type()->interface_type()->is_empty())
281 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
282 location);
284 Expression* mtable =
285 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
287 Expression* descriptor =
288 Expression::make_unary(OPERATOR_MULT, mtable, location);
289 descriptor = Expression::make_field_reference(descriptor, 0, location);
290 Expression* nil = Expression::make_nil(location);
292 Expression* eq =
293 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
294 return Expression::make_conditional(eq, nil, descriptor, location);
297 // Return an expression for the conversion of an interface type to an
298 // interface type.
300 Expression*
301 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
302 bool for_type_guard,
303 Location location)
305 Interface_type* lhs_interface_type = lhs_type->interface_type();
306 bool lhs_is_empty = lhs_interface_type->is_empty();
308 // In the general case this requires runtime examination of the type
309 // method table to match it up with the interface methods.
311 // FIXME: If all of the methods in the right hand side interface
312 // also appear in the left hand side interface, then we don't need
313 // to do a runtime check, although we still need to build a new
314 // method table.
316 // Get the type descriptor for the right hand side. This will be
317 // NULL for a nil interface.
318 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
319 Expression* lhs_type_expr =
320 Expression::make_type_descriptor(lhs_type, location);
322 Expression* first_field;
323 if (for_type_guard)
325 // A type assertion fails when converting a nil interface.
326 first_field =
327 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
328 lhs_type_expr, rhs_type_expr);
330 else if (lhs_is_empty)
332 // A conversion to an empty interface always succeeds, and the
333 // first field is just the type descriptor of the object.
334 first_field = rhs_type_expr;
336 else
338 // A conversion to a non-empty interface may fail, but unlike a
339 // type assertion converting nil will always succeed.
340 first_field =
341 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
345 // The second field is simply the object pointer.
346 Expression* obj =
347 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
348 return Expression::make_interface_value(lhs_type, first_field, obj, location);
351 // Return an expression for the conversion of an interface type to a
352 // non-interface type.
354 Expression*
355 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
356 Location location)
358 // Call a function to check that the type is valid. The function
359 // will panic with an appropriate runtime type error if the type is
360 // not valid.
361 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
362 location);
363 Expression* rhs_descriptor =
364 Expression::get_interface_type_descriptor(rhs);
366 Type* rhs_type = rhs->type();
367 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
368 location);
370 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
371 location, 3, lhs_type_expr,
372 rhs_descriptor, rhs_inter_expr);
374 // If the call succeeds, pull out the value.
375 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
376 location);
378 // If the value is a pointer, then it is the value we want.
379 // Otherwise it points to the value.
380 if (lhs_type->points_to() == NULL)
382 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
383 location);
384 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
386 return Expression::make_compound(check_iface, obj, location);
389 // Convert an expression to its backend representation. This is implemented by
390 // the child class. Not that it is not in general safe to call this multiple
391 // times for a single expression, but that we don't catch such errors.
393 Bexpression*
394 Expression::get_backend(Translate_context* context)
396 // The child may have marked this expression as having an error.
397 if (this->classification_ == EXPRESSION_ERROR)
398 return context->backend()->error_expression();
400 return this->do_get_backend(context);
403 // Return a backend expression for VAL.
404 Bexpression*
405 Expression::backend_numeric_constant_expression(Translate_context* context,
406 Numeric_constant* val)
408 Gogo* gogo = context->gogo();
409 Type* type = val->type();
410 if (type == NULL)
411 return gogo->backend()->error_expression();
413 Btype* btype = type->get_backend(gogo);
414 Bexpression* ret;
415 if (type->integer_type() != NULL)
417 mpz_t ival;
418 if (!val->to_int(&ival))
420 go_assert(saw_errors());
421 return gogo->backend()->error_expression();
423 ret = gogo->backend()->integer_constant_expression(btype, ival);
424 mpz_clear(ival);
426 else if (type->float_type() != NULL)
428 mpfr_t fval;
429 if (!val->to_float(&fval))
431 go_assert(saw_errors());
432 return gogo->backend()->error_expression();
434 ret = gogo->backend()->float_constant_expression(btype, fval);
435 mpfr_clear(fval);
437 else if (type->complex_type() != NULL)
439 mpc_t cval;
440 if (!val->to_complex(&cval))
442 go_assert(saw_errors());
443 return gogo->backend()->error_expression();
445 ret = gogo->backend()->complex_constant_expression(btype, cval);
446 mpc_clear(cval);
448 else
449 go_unreachable();
451 return ret;
454 // Return an expression which evaluates to true if VAL, of arbitrary integer
455 // type, is negative or is more than the maximum value of the Go type "int".
457 Expression*
458 Expression::check_bounds(Expression* val, Location loc)
460 Type* val_type = val->type();
461 Type* bound_type = Type::lookup_integer_type("int");
463 int val_type_size;
464 bool val_is_unsigned = false;
465 if (val_type->integer_type() != NULL)
467 val_type_size = val_type->integer_type()->bits();
468 val_is_unsigned = val_type->integer_type()->is_unsigned();
470 else
472 if (!val_type->is_numeric_type()
473 || !Type::are_convertible(bound_type, val_type, NULL))
475 go_assert(saw_errors());
476 return Expression::make_boolean(true, loc);
479 if (val_type->complex_type() != NULL)
480 val_type_size = val_type->complex_type()->bits();
481 else
482 val_type_size = val_type->float_type()->bits();
485 Expression* negative_index = Expression::make_boolean(false, loc);
486 Expression* index_overflows = Expression::make_boolean(false, loc);
487 if (!val_is_unsigned)
489 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
490 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
493 int bound_type_size = bound_type->integer_type()->bits();
494 if (val_type_size > bound_type_size
495 || (val_type_size == bound_type_size
496 && val_is_unsigned))
498 mpz_t one;
499 mpz_init_set_ui(one, 1UL);
501 // maxval = 2^(bound_type_size - 1) - 1
502 mpz_t maxval;
503 mpz_init(maxval);
504 mpz_mul_2exp(maxval, one, bound_type_size - 1);
505 mpz_sub_ui(maxval, maxval, 1);
506 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
507 mpz_clear(one);
508 mpz_clear(maxval);
510 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
513 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
514 loc);
517 void
518 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
520 this->do_dump_expression(ast_dump_context);
523 // Error expressions. This are used to avoid cascading errors.
525 class Error_expression : public Expression
527 public:
528 Error_expression(Location location)
529 : Expression(EXPRESSION_ERROR, location)
532 protected:
533 bool
534 do_is_constant() const
535 { return true; }
537 bool
538 do_is_immutable() const
539 { return true; }
541 bool
542 do_numeric_constant_value(Numeric_constant* nc) const
544 nc->set_unsigned_long(NULL, 0);
545 return true;
548 bool
549 do_discarding_value()
550 { return true; }
552 Type*
553 do_type()
554 { return Type::make_error_type(); }
556 void
557 do_determine_type(const Type_context*)
560 Expression*
561 do_copy()
562 { return this; }
564 bool
565 do_is_addressable() const
566 { return true; }
568 Bexpression*
569 do_get_backend(Translate_context* context)
570 { return context->backend()->error_expression(); }
572 void
573 do_dump_expression(Ast_dump_context*) const;
576 // Dump the ast representation for an error expression to a dump context.
578 void
579 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
581 ast_dump_context->ostream() << "_Error_" ;
584 Expression*
585 Expression::make_error(Location location)
587 return new Error_expression(location);
590 // An expression which is really a type. This is used during parsing.
591 // It is an error if these survive after lowering.
593 class
594 Type_expression : public Expression
596 public:
597 Type_expression(Type* type, Location location)
598 : Expression(EXPRESSION_TYPE, location),
599 type_(type)
602 protected:
604 do_traverse(Traverse* traverse)
605 { return Type::traverse(this->type_, traverse); }
607 Type*
608 do_type()
609 { return this->type_; }
611 void
612 do_determine_type(const Type_context*)
615 void
616 do_check_types(Gogo*)
617 { this->report_error(_("invalid use of type")); }
619 Expression*
620 do_copy()
621 { return this; }
623 Bexpression*
624 do_get_backend(Translate_context*)
625 { go_unreachable(); }
627 void do_dump_expression(Ast_dump_context*) const;
629 private:
630 // The type which we are representing as an expression.
631 Type* type_;
634 void
635 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
637 ast_dump_context->dump_type(this->type_);
640 Expression*
641 Expression::make_type(Type* type, Location location)
643 return new Type_expression(type, location);
646 // Class Parser_expression.
648 Type*
649 Parser_expression::do_type()
651 // We should never really ask for the type of a Parser_expression.
652 // However, it can happen, at least when we have an invalid const
653 // whose initializer refers to the const itself. In that case we
654 // may ask for the type when lowering the const itself.
655 go_assert(saw_errors());
656 return Type::make_error_type();
659 // Class Var_expression.
661 // Lower a variable expression. Here we just make sure that the
662 // initialization expression of the variable has been lowered. This
663 // ensures that we will be able to determine the type of the variable
664 // if necessary.
666 Expression*
667 Var_expression::do_lower(Gogo* gogo, Named_object* function,
668 Statement_inserter* inserter, int)
670 if (this->variable_->is_variable())
672 Variable* var = this->variable_->var_value();
673 // This is either a local variable or a global variable. A
674 // reference to a variable which is local to an enclosing
675 // function will be a reference to a field in a closure.
676 if (var->is_global())
678 function = NULL;
679 inserter = NULL;
681 var->lower_init_expression(gogo, function, inserter);
683 return this;
686 // Return the type of a reference to a variable.
688 Type*
689 Var_expression::do_type()
691 if (this->variable_->is_variable())
692 return this->variable_->var_value()->type();
693 else if (this->variable_->is_result_variable())
694 return this->variable_->result_var_value()->type();
695 else
696 go_unreachable();
699 // Determine the type of a reference to a variable.
701 void
702 Var_expression::do_determine_type(const Type_context*)
704 if (this->variable_->is_variable())
705 this->variable_->var_value()->determine_type();
708 // Something takes the address of this variable. This means that we
709 // may want to move the variable onto the heap.
711 void
712 Var_expression::do_address_taken(bool escapes)
714 if (!escapes)
716 if (this->variable_->is_variable())
717 this->variable_->var_value()->set_non_escaping_address_taken();
718 else if (this->variable_->is_result_variable())
719 this->variable_->result_var_value()->set_non_escaping_address_taken();
720 else
721 go_unreachable();
723 else
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_address_taken();
729 else
730 go_unreachable();
734 // Get the backend representation for a reference to a variable.
736 Bexpression*
737 Var_expression::do_get_backend(Translate_context* context)
739 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
740 context->function());
741 bool is_in_heap;
742 Location loc = this->location();
743 Btype* btype;
744 Gogo* gogo = context->gogo();
745 if (this->variable_->is_variable())
747 is_in_heap = this->variable_->var_value()->is_in_heap();
748 btype = this->variable_->var_value()->type()->get_backend(gogo);
750 else if (this->variable_->is_result_variable())
752 is_in_heap = this->variable_->result_var_value()->is_in_heap();
753 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
755 else
756 go_unreachable();
758 Bexpression* ret = context->backend()->var_expression(bvar, loc);
759 if (is_in_heap)
760 ret = context->backend()->indirect_expression(btype, ret, true, loc);
761 return ret;
764 // Ast dump for variable expression.
766 void
767 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
769 ast_dump_context->ostream() << this->variable_->name() ;
772 // Make a reference to a variable in an expression.
774 Expression*
775 Expression::make_var_reference(Named_object* var, Location location)
777 if (var->is_sink())
778 return Expression::make_sink(location);
780 // FIXME: Creating a new object for each reference to a variable is
781 // wasteful.
782 return new Var_expression(var, location);
785 // Class Temporary_reference_expression.
787 // The type.
789 Type*
790 Temporary_reference_expression::do_type()
792 return this->statement_->type();
795 // Called if something takes the address of this temporary variable.
796 // We never have to move temporary variables to the heap, but we do
797 // need to know that they must live in the stack rather than in a
798 // register.
800 void
801 Temporary_reference_expression::do_address_taken(bool)
803 this->statement_->set_is_address_taken();
806 // Get a backend expression referring to the variable.
808 Bexpression*
809 Temporary_reference_expression::do_get_backend(Translate_context* context)
811 Gogo* gogo = context->gogo();
812 Bvariable* bvar = this->statement_->get_backend_variable(context);
813 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
815 // The backend can't always represent the same set of recursive types
816 // that the Go frontend can. In some cases this means that a
817 // temporary variable won't have the right backend type. Correct
818 // that here by adding a type cast. We need to use base() to push
819 // the circularity down one level.
820 Type* stype = this->statement_->type();
821 if (!this->is_lvalue_
822 && stype->has_pointer()
823 && stype->deref()->is_void_type())
825 Btype* btype = this->type()->base()->get_backend(gogo);
826 ret = gogo->backend()->convert_expression(btype, ret, this->location());
828 return ret;
831 // Ast dump for temporary reference.
833 void
834 Temporary_reference_expression::do_dump_expression(
835 Ast_dump_context* ast_dump_context) const
837 ast_dump_context->dump_temp_variable_name(this->statement_);
840 // Make a reference to a temporary variable.
842 Temporary_reference_expression*
843 Expression::make_temporary_reference(Temporary_statement* statement,
844 Location location)
846 return new Temporary_reference_expression(statement, location);
849 // Class Set_and_use_temporary_expression.
851 // Return the type.
853 Type*
854 Set_and_use_temporary_expression::do_type()
856 return this->statement_->type();
859 // Determine the type of the expression.
861 void
862 Set_and_use_temporary_expression::do_determine_type(
863 const Type_context* context)
865 this->expr_->determine_type(context);
868 // Take the address.
870 void
871 Set_and_use_temporary_expression::do_address_taken(bool)
873 this->statement_->set_is_address_taken();
876 // Return the backend representation.
878 Bexpression*
879 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
881 Location loc = this->location();
882 Gogo* gogo = context->gogo();
883 Bvariable* bvar = this->statement_->get_backend_variable(context);
884 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
886 Bexpression* bexpr = this->expr_->get_backend(context);
887 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
888 var_ref = gogo->backend()->var_expression(bvar, loc);
889 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
890 return ret;
893 // Dump.
895 void
896 Set_and_use_temporary_expression::do_dump_expression(
897 Ast_dump_context* ast_dump_context) const
899 ast_dump_context->ostream() << '(';
900 ast_dump_context->dump_temp_variable_name(this->statement_);
901 ast_dump_context->ostream() << " = ";
902 this->expr_->dump_expression(ast_dump_context);
903 ast_dump_context->ostream() << ')';
906 // Make a set-and-use temporary.
908 Set_and_use_temporary_expression*
909 Expression::make_set_and_use_temporary(Temporary_statement* statement,
910 Expression* expr, Location location)
912 return new Set_and_use_temporary_expression(statement, expr, location);
915 // A sink expression--a use of the blank identifier _.
917 class Sink_expression : public Expression
919 public:
920 Sink_expression(Location location)
921 : Expression(EXPRESSION_SINK, location),
922 type_(NULL), bvar_(NULL)
925 protected:
926 bool
927 do_discarding_value()
928 { return true; }
930 Type*
931 do_type();
933 void
934 do_determine_type(const Type_context*);
936 Expression*
937 do_copy()
938 { return new Sink_expression(this->location()); }
940 Bexpression*
941 do_get_backend(Translate_context*);
943 void
944 do_dump_expression(Ast_dump_context*) const;
946 private:
947 // The type of this sink variable.
948 Type* type_;
949 // The temporary variable we generate.
950 Bvariable* bvar_;
953 // Return the type of a sink expression.
955 Type*
956 Sink_expression::do_type()
958 if (this->type_ == NULL)
959 return Type::make_sink_type();
960 return this->type_;
963 // Determine the type of a sink expression.
965 void
966 Sink_expression::do_determine_type(const Type_context* context)
968 if (context->type != NULL)
969 this->type_ = context->type;
972 // Return a temporary variable for a sink expression. This will
973 // presumably be a write-only variable which the middle-end will drop.
975 Bexpression*
976 Sink_expression::do_get_backend(Translate_context* context)
978 Location loc = this->location();
979 Gogo* gogo = context->gogo();
980 if (this->bvar_ == NULL)
982 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
983 Named_object* fn = context->function();
984 go_assert(fn != NULL);
985 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
986 Btype* bt = this->type_->get_backend(context->gogo());
987 Bstatement* decl;
988 this->bvar_ =
989 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
990 false, loc, &decl);
991 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
992 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
993 return var_ref;
995 return gogo->backend()->var_expression(this->bvar_, loc);
998 // Ast dump for sink expression.
1000 void
1001 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1003 ast_dump_context->ostream() << "_" ;
1006 // Make a sink expression.
1008 Expression*
1009 Expression::make_sink(Location location)
1011 return new Sink_expression(location);
1014 // Class Func_expression.
1016 // FIXME: Can a function expression appear in a constant expression?
1017 // The value is unchanging. Initializing a constant to the address of
1018 // a function seems like it could work, though there might be little
1019 // point to it.
1021 // Traversal.
1024 Func_expression::do_traverse(Traverse* traverse)
1026 return (this->closure_ == NULL
1027 ? TRAVERSE_CONTINUE
1028 : Expression::traverse(&this->closure_, traverse));
1031 // Return the type of a function expression.
1033 Type*
1034 Func_expression::do_type()
1036 if (this->function_->is_function())
1037 return this->function_->func_value()->type();
1038 else if (this->function_->is_function_declaration())
1039 return this->function_->func_declaration_value()->type();
1040 else
1041 go_unreachable();
1044 // Get the backend representation for the code of a function expression.
1046 Bexpression*
1047 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1049 Function_type* fntype;
1050 if (no->is_function())
1051 fntype = no->func_value()->type();
1052 else if (no->is_function_declaration())
1053 fntype = no->func_declaration_value()->type();
1054 else
1055 go_unreachable();
1057 // Builtin functions are handled specially by Call_expression. We
1058 // can't take their address.
1059 if (fntype->is_builtin())
1061 error_at(loc,
1062 "invalid use of special builtin function %qs; must be called",
1063 no->message_name().c_str());
1064 return gogo->backend()->error_expression();
1067 Bfunction* fndecl;
1068 if (no->is_function())
1069 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1070 else if (no->is_function_declaration())
1071 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1072 else
1073 go_unreachable();
1075 return gogo->backend()->function_code_expression(fndecl, loc);
1078 // Get the backend representation for a function expression. This is used when
1079 // we take the address of a function rather than simply calling it. A func
1080 // value is represented as a pointer to a block of memory. The first
1081 // word of that memory is a pointer to the function code. The
1082 // remaining parts of that memory are the addresses of variables that
1083 // the function closes over.
1085 Bexpression*
1086 Func_expression::do_get_backend(Translate_context* context)
1088 // If there is no closure, just use the function descriptor.
1089 if (this->closure_ == NULL)
1091 Gogo* gogo = context->gogo();
1092 Named_object* no = this->function_;
1093 Expression* descriptor;
1094 if (no->is_function())
1095 descriptor = no->func_value()->descriptor(gogo, no);
1096 else if (no->is_function_declaration())
1098 if (no->func_declaration_value()->type()->is_builtin())
1100 error_at(this->location(),
1101 ("invalid use of special builtin function %qs; "
1102 "must be called"),
1103 no->message_name().c_str());
1104 return gogo->backend()->error_expression();
1106 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1108 else
1109 go_unreachable();
1111 Bexpression* bdesc = descriptor->get_backend(context);
1112 return gogo->backend()->address_expression(bdesc, this->location());
1115 go_assert(this->function_->func_value()->enclosing() != NULL);
1117 // If there is a closure, then the closure is itself the function
1118 // expression. It is a pointer to a struct whose first field points
1119 // to the function code and whose remaining fields are the addresses
1120 // of the closed-over variables.
1121 return this->closure_->get_backend(context);
1124 // Ast dump for function.
1126 void
1127 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1129 ast_dump_context->ostream() << this->function_->name();
1130 if (this->closure_ != NULL)
1132 ast_dump_context->ostream() << " {closure = ";
1133 this->closure_->dump_expression(ast_dump_context);
1134 ast_dump_context->ostream() << "}";
1138 // Make a reference to a function in an expression.
1140 Expression*
1141 Expression::make_func_reference(Named_object* function, Expression* closure,
1142 Location location)
1144 return new Func_expression(function, closure, location);
1147 // Class Func_descriptor_expression.
1149 // Constructor.
1151 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1152 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1153 fn_(fn), dvar_(NULL)
1155 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1158 // Traversal.
1161 Func_descriptor_expression::do_traverse(Traverse*)
1163 return TRAVERSE_CONTINUE;
1166 // All function descriptors have the same type.
1168 Type* Func_descriptor_expression::descriptor_type;
1170 void
1171 Func_descriptor_expression::make_func_descriptor_type()
1173 if (Func_descriptor_expression::descriptor_type != NULL)
1174 return;
1175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1176 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1177 Func_descriptor_expression::descriptor_type =
1178 Type::make_builtin_named_type("functionDescriptor", struct_type);
1181 Type*
1182 Func_descriptor_expression::do_type()
1184 Func_descriptor_expression::make_func_descriptor_type();
1185 return Func_descriptor_expression::descriptor_type;
1188 // The backend representation for a function descriptor.
1190 Bexpression*
1191 Func_descriptor_expression::do_get_backend(Translate_context* context)
1193 Named_object* no = this->fn_;
1194 Location loc = no->location();
1195 if (this->dvar_ != NULL)
1196 return context->backend()->var_expression(this->dvar_, loc);
1198 Gogo* gogo = context->gogo();
1199 std::string var_name;
1200 if (no->package() == NULL)
1201 var_name = gogo->pkgpath_symbol();
1202 else
1203 var_name = no->package()->pkgpath_symbol();
1204 var_name.push_back('.');
1205 var_name.append(Gogo::unpack_hidden_name(no->name()));
1206 var_name.append("$descriptor");
1208 Btype* btype = this->type()->get_backend(gogo);
1210 Bvariable* bvar;
1211 if (no->package() != NULL
1212 || Linemap::is_predeclared_location(no->location()))
1213 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1214 loc);
1215 else
1217 Location bloc = Linemap::predeclared_location();
1218 bool is_hidden = ((no->is_function()
1219 && no->func_value()->enclosing() != NULL)
1220 || Gogo::is_thunk(no));
1221 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1222 btype, bloc);
1223 Expression_list* vals = new Expression_list();
1224 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1225 Expression* init =
1226 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1227 Translate_context bcontext(gogo, NULL, NULL, NULL);
1228 bcontext.set_is_const();
1229 Bexpression* binit = init->get_backend(&bcontext);
1230 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1231 false, btype, bloc, binit);
1234 this->dvar_ = bvar;
1235 return gogo->backend()->var_expression(bvar, loc);
1238 // Print a function descriptor expression.
1240 void
1241 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1243 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1246 // Make a function descriptor expression.
1248 Func_descriptor_expression*
1249 Expression::make_func_descriptor(Named_object* fn)
1251 return new Func_descriptor_expression(fn);
1254 // Make the function descriptor type, so that it can be converted.
1256 void
1257 Expression::make_func_descriptor_type()
1259 Func_descriptor_expression::make_func_descriptor_type();
1262 // A reference to just the code of a function.
1264 class Func_code_reference_expression : public Expression
1266 public:
1267 Func_code_reference_expression(Named_object* function, Location location)
1268 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1269 function_(function)
1272 protected:
1274 do_traverse(Traverse*)
1275 { return TRAVERSE_CONTINUE; }
1277 bool
1278 do_is_immutable() const
1279 { return true; }
1281 Type*
1282 do_type()
1283 { return Type::make_pointer_type(Type::make_void_type()); }
1285 void
1286 do_determine_type(const Type_context*)
1289 Expression*
1290 do_copy()
1292 return Expression::make_func_code_reference(this->function_,
1293 this->location());
1296 Bexpression*
1297 do_get_backend(Translate_context*);
1299 void
1300 do_dump_expression(Ast_dump_context* context) const
1301 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1303 private:
1304 // The function.
1305 Named_object* function_;
1308 // Get the backend representation for a reference to function code.
1310 Bexpression*
1311 Func_code_reference_expression::do_get_backend(Translate_context* context)
1313 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1314 this->location());
1317 // Make a reference to the code of a function.
1319 Expression*
1320 Expression::make_func_code_reference(Named_object* function, Location location)
1322 return new Func_code_reference_expression(function, location);
1325 // Class Unknown_expression.
1327 // Return the name of an unknown expression.
1329 const std::string&
1330 Unknown_expression::name() const
1332 return this->named_object_->name();
1335 // Lower a reference to an unknown name.
1337 Expression*
1338 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1340 Location location = this->location();
1341 Named_object* no = this->named_object_;
1342 Named_object* real;
1343 if (!no->is_unknown())
1344 real = no;
1345 else
1347 real = no->unknown_value()->real_named_object();
1348 if (real == NULL)
1350 if (this->is_composite_literal_key_)
1351 return this;
1352 if (!this->no_error_message_)
1353 error_at(location, "reference to undefined name %qs",
1354 this->named_object_->message_name().c_str());
1355 return Expression::make_error(location);
1358 switch (real->classification())
1360 case Named_object::NAMED_OBJECT_CONST:
1361 return Expression::make_const_reference(real, location);
1362 case Named_object::NAMED_OBJECT_TYPE:
1363 return Expression::make_type(real->type_value(), location);
1364 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1365 if (this->is_composite_literal_key_)
1366 return this;
1367 if (!this->no_error_message_)
1368 error_at(location, "reference to undefined type %qs",
1369 real->message_name().c_str());
1370 return Expression::make_error(location);
1371 case Named_object::NAMED_OBJECT_VAR:
1372 real->var_value()->set_is_used();
1373 return Expression::make_var_reference(real, location);
1374 case Named_object::NAMED_OBJECT_FUNC:
1375 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1376 return Expression::make_func_reference(real, NULL, location);
1377 case Named_object::NAMED_OBJECT_PACKAGE:
1378 if (this->is_composite_literal_key_)
1379 return this;
1380 if (!this->no_error_message_)
1381 error_at(location, "unexpected reference to package");
1382 return Expression::make_error(location);
1383 default:
1384 go_unreachable();
1388 // Dump the ast representation for an unknown expression to a dump context.
1390 void
1391 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1393 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1394 << ")";
1397 // Make a reference to an unknown name.
1399 Unknown_expression*
1400 Expression::make_unknown_reference(Named_object* no, Location location)
1402 return new Unknown_expression(no, location);
1405 // A boolean expression.
1407 class Boolean_expression : public Expression
1409 public:
1410 Boolean_expression(bool val, Location location)
1411 : Expression(EXPRESSION_BOOLEAN, location),
1412 val_(val), type_(NULL)
1415 static Expression*
1416 do_import(Import*);
1418 protected:
1419 bool
1420 do_is_constant() const
1421 { return true; }
1423 bool
1424 do_is_immutable() const
1425 { return true; }
1427 Type*
1428 do_type();
1430 void
1431 do_determine_type(const Type_context*);
1433 Expression*
1434 do_copy()
1435 { return this; }
1437 Bexpression*
1438 do_get_backend(Translate_context* context)
1439 { return context->backend()->boolean_constant_expression(this->val_); }
1441 void
1442 do_export(Export* exp) const
1443 { exp->write_c_string(this->val_ ? "true" : "false"); }
1445 void
1446 do_dump_expression(Ast_dump_context* ast_dump_context) const
1447 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1449 private:
1450 // The constant.
1451 bool val_;
1452 // The type as determined by context.
1453 Type* type_;
1456 // Get the type.
1458 Type*
1459 Boolean_expression::do_type()
1461 if (this->type_ == NULL)
1462 this->type_ = Type::make_boolean_type();
1463 return this->type_;
1466 // Set the type from the context.
1468 void
1469 Boolean_expression::do_determine_type(const Type_context* context)
1471 if (this->type_ != NULL && !this->type_->is_abstract())
1473 else if (context->type != NULL && context->type->is_boolean_type())
1474 this->type_ = context->type;
1475 else if (!context->may_be_abstract)
1476 this->type_ = Type::lookup_bool_type();
1479 // Import a boolean constant.
1481 Expression*
1482 Boolean_expression::do_import(Import* imp)
1484 if (imp->peek_char() == 't')
1486 imp->require_c_string("true");
1487 return Expression::make_boolean(true, imp->location());
1489 else
1491 imp->require_c_string("false");
1492 return Expression::make_boolean(false, imp->location());
1496 // Make a boolean expression.
1498 Expression*
1499 Expression::make_boolean(bool val, Location location)
1501 return new Boolean_expression(val, location);
1504 // Class String_expression.
1506 // Get the type.
1508 Type*
1509 String_expression::do_type()
1511 if (this->type_ == NULL)
1512 this->type_ = Type::make_string_type();
1513 return this->type_;
1516 // Set the type from the context.
1518 void
1519 String_expression::do_determine_type(const Type_context* context)
1521 if (this->type_ != NULL && !this->type_->is_abstract())
1523 else if (context->type != NULL && context->type->is_string_type())
1524 this->type_ = context->type;
1525 else if (!context->may_be_abstract)
1526 this->type_ = Type::lookup_string_type();
1529 // Build a string constant.
1531 Bexpression*
1532 String_expression::do_get_backend(Translate_context* context)
1534 Gogo* gogo = context->gogo();
1535 Btype* btype = Type::make_string_type()->get_backend(gogo);
1537 Location loc = this->location();
1538 std::vector<Bexpression*> init(2);
1539 Bexpression* str_cst =
1540 gogo->backend()->string_constant_expression(this->val_);
1541 init[0] = gogo->backend()->address_expression(str_cst, loc);
1543 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1544 mpz_t lenval;
1545 mpz_init_set_ui(lenval, this->val_.length());
1546 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1547 mpz_clear(lenval);
1549 return gogo->backend()->constructor_expression(btype, init, loc);
1552 // Write string literal to string dump.
1554 void
1555 String_expression::export_string(String_dump* exp,
1556 const String_expression* str)
1558 std::string s;
1559 s.reserve(str->val_.length() * 4 + 2);
1560 s += '"';
1561 for (std::string::const_iterator p = str->val_.begin();
1562 p != str->val_.end();
1563 ++p)
1565 if (*p == '\\' || *p == '"')
1567 s += '\\';
1568 s += *p;
1570 else if (*p >= 0x20 && *p < 0x7f)
1571 s += *p;
1572 else if (*p == '\n')
1573 s += "\\n";
1574 else if (*p == '\t')
1575 s += "\\t";
1576 else
1578 s += "\\x";
1579 unsigned char c = *p;
1580 unsigned int dig = c >> 4;
1581 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1582 dig = c & 0xf;
1583 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1586 s += '"';
1587 exp->write_string(s);
1590 // Export a string expression.
1592 void
1593 String_expression::do_export(Export* exp) const
1595 String_expression::export_string(exp, this);
1598 // Import a string expression.
1600 Expression*
1601 String_expression::do_import(Import* imp)
1603 imp->require_c_string("\"");
1604 std::string val;
1605 while (true)
1607 int c = imp->get_char();
1608 if (c == '"' || c == -1)
1609 break;
1610 if (c != '\\')
1611 val += static_cast<char>(c);
1612 else
1614 c = imp->get_char();
1615 if (c == '\\' || c == '"')
1616 val += static_cast<char>(c);
1617 else if (c == 'n')
1618 val += '\n';
1619 else if (c == 't')
1620 val += '\t';
1621 else if (c == 'x')
1623 c = imp->get_char();
1624 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1625 c = imp->get_char();
1626 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1627 char v = (vh << 4) | vl;
1628 val += v;
1630 else
1632 error_at(imp->location(), "bad string constant");
1633 return Expression::make_error(imp->location());
1637 return Expression::make_string(val, imp->location());
1640 // Ast dump for string expression.
1642 void
1643 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1645 String_expression::export_string(ast_dump_context, this);
1648 // Make a string expression.
1650 Expression*
1651 Expression::make_string(const std::string& val, Location location)
1653 return new String_expression(val, location);
1656 // An expression that evaluates to some characteristic of a string.
1657 // This is used when indexing, bound-checking, or nil checking a string.
1659 class String_info_expression : public Expression
1661 public:
1662 String_info_expression(Expression* string, String_info string_info,
1663 Location location)
1664 : Expression(EXPRESSION_STRING_INFO, location),
1665 string_(string), string_info_(string_info)
1668 protected:
1669 Type*
1670 do_type();
1672 void
1673 do_determine_type(const Type_context*)
1674 { go_unreachable(); }
1676 Expression*
1677 do_copy()
1679 return new String_info_expression(this->string_->copy(), this->string_info_,
1680 this->location());
1683 Bexpression*
1684 do_get_backend(Translate_context* context);
1686 void
1687 do_dump_expression(Ast_dump_context*) const;
1689 void
1690 do_issue_nil_check()
1691 { this->string_->issue_nil_check(); }
1693 private:
1694 // The string for which we are getting information.
1695 Expression* string_;
1696 // What information we want.
1697 String_info string_info_;
1700 // Return the type of the string info.
1702 Type*
1703 String_info_expression::do_type()
1705 switch (this->string_info_)
1707 case STRING_INFO_DATA:
1709 Type* byte_type = Type::lookup_integer_type("uint8");
1710 return Type::make_pointer_type(byte_type);
1712 case STRING_INFO_LENGTH:
1713 return Type::lookup_integer_type("int");
1714 default:
1715 go_unreachable();
1719 // Return string information in GENERIC.
1721 Bexpression*
1722 String_info_expression::do_get_backend(Translate_context* context)
1724 Gogo* gogo = context->gogo();
1726 Bexpression* bstring = this->string_->get_backend(context);
1727 switch (this->string_info_)
1729 case STRING_INFO_DATA:
1730 case STRING_INFO_LENGTH:
1731 return gogo->backend()->struct_field_expression(bstring,
1732 this->string_info_,
1733 this->location());
1734 break;
1735 default:
1736 go_unreachable();
1740 // Dump ast representation for a type info expression.
1742 void
1743 String_info_expression::do_dump_expression(
1744 Ast_dump_context* ast_dump_context) const
1746 ast_dump_context->ostream() << "stringinfo(";
1747 this->string_->dump_expression(ast_dump_context);
1748 ast_dump_context->ostream() << ",";
1749 ast_dump_context->ostream() <<
1750 (this->string_info_ == STRING_INFO_DATA ? "data"
1751 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1752 : "unknown");
1753 ast_dump_context->ostream() << ")";
1756 // Make a string info expression.
1758 Expression*
1759 Expression::make_string_info(Expression* string, String_info string_info,
1760 Location location)
1762 return new String_info_expression(string, string_info, location);
1765 // Make an integer expression.
1767 class Integer_expression : public Expression
1769 public:
1770 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1771 Location location)
1772 : Expression(EXPRESSION_INTEGER, location),
1773 type_(type), is_character_constant_(is_character_constant)
1774 { mpz_init_set(this->val_, *val); }
1776 static Expression*
1777 do_import(Import*);
1779 // Write VAL to string dump.
1780 static void
1781 export_integer(String_dump* exp, const mpz_t val);
1783 // Write VAL to dump context.
1784 static void
1785 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1787 protected:
1788 bool
1789 do_is_constant() const
1790 { return true; }
1792 bool
1793 do_is_immutable() const
1794 { return true; }
1796 bool
1797 do_numeric_constant_value(Numeric_constant* nc) const;
1799 Type*
1800 do_type();
1802 void
1803 do_determine_type(const Type_context* context);
1805 void
1806 do_check_types(Gogo*);
1808 Bexpression*
1809 do_get_backend(Translate_context*);
1811 Expression*
1812 do_copy()
1814 if (this->is_character_constant_)
1815 return Expression::make_character(&this->val_, this->type_,
1816 this->location());
1817 else
1818 return Expression::make_integer_z(&this->val_, this->type_,
1819 this->location());
1822 void
1823 do_export(Export*) const;
1825 void
1826 do_dump_expression(Ast_dump_context*) const;
1828 private:
1829 // The integer value.
1830 mpz_t val_;
1831 // The type so far.
1832 Type* type_;
1833 // Whether this is a character constant.
1834 bool is_character_constant_;
1837 // Return a numeric constant for this expression. We have to mark
1838 // this as a character when appropriate.
1840 bool
1841 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1843 if (this->is_character_constant_)
1844 nc->set_rune(this->type_, this->val_);
1845 else
1846 nc->set_int(this->type_, this->val_);
1847 return true;
1850 // Return the current type. If we haven't set the type yet, we return
1851 // an abstract integer type.
1853 Type*
1854 Integer_expression::do_type()
1856 if (this->type_ == NULL)
1858 if (this->is_character_constant_)
1859 this->type_ = Type::make_abstract_character_type();
1860 else
1861 this->type_ = Type::make_abstract_integer_type();
1863 return this->type_;
1866 // Set the type of the integer value. Here we may switch from an
1867 // abstract type to a real type.
1869 void
1870 Integer_expression::do_determine_type(const Type_context* context)
1872 if (this->type_ != NULL && !this->type_->is_abstract())
1874 else if (context->type != NULL && context->type->is_numeric_type())
1875 this->type_ = context->type;
1876 else if (!context->may_be_abstract)
1878 if (this->is_character_constant_)
1879 this->type_ = Type::lookup_integer_type("int32");
1880 else
1881 this->type_ = Type::lookup_integer_type("int");
1885 // Check the type of an integer constant.
1887 void
1888 Integer_expression::do_check_types(Gogo*)
1890 Type* type = this->type_;
1891 if (type == NULL)
1892 return;
1893 Numeric_constant nc;
1894 if (this->is_character_constant_)
1895 nc.set_rune(NULL, this->val_);
1896 else
1897 nc.set_int(NULL, this->val_);
1898 if (!nc.set_type(type, true, this->location()))
1899 this->set_is_error();
1902 // Get the backend representation for an integer constant.
1904 Bexpression*
1905 Integer_expression::do_get_backend(Translate_context* context)
1907 Type* resolved_type = NULL;
1908 if (this->type_ != NULL && !this->type_->is_abstract())
1909 resolved_type = this->type_;
1910 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1912 // We are converting to an abstract floating point type.
1913 resolved_type = Type::lookup_float_type("float64");
1915 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1917 // We are converting to an abstract complex type.
1918 resolved_type = Type::lookup_complex_type("complex128");
1920 else
1922 // If we still have an abstract type here, then this is being
1923 // used in a constant expression which didn't get reduced for
1924 // some reason. Use a type which will fit the value. We use <,
1925 // not <=, because we need an extra bit for the sign bit.
1926 int bits = mpz_sizeinbase(this->val_, 2);
1927 Type* int_type = Type::lookup_integer_type("int");
1928 if (bits < int_type->integer_type()->bits())
1929 resolved_type = int_type;
1930 else if (bits < 64)
1931 resolved_type = Type::lookup_integer_type("int64");
1932 else
1934 if (!saw_errors())
1935 error_at(this->location(),
1936 "unknown type for large integer constant");
1937 return context->gogo()->backend()->error_expression();
1940 Numeric_constant nc;
1941 nc.set_int(resolved_type, this->val_);
1942 return Expression::backend_numeric_constant_expression(context, &nc);
1945 // Write VAL to export data.
1947 void
1948 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1950 char* s = mpz_get_str(NULL, 10, val);
1951 exp->write_c_string(s);
1952 free(s);
1955 // Export an integer in a constant expression.
1957 void
1958 Integer_expression::do_export(Export* exp) const
1960 Integer_expression::export_integer(exp, this->val_);
1961 if (this->is_character_constant_)
1962 exp->write_c_string("'");
1963 // A trailing space lets us reliably identify the end of the number.
1964 exp->write_c_string(" ");
1967 // Import an integer, floating point, or complex value. This handles
1968 // all these types because they all start with digits.
1970 Expression*
1971 Integer_expression::do_import(Import* imp)
1973 std::string num = imp->read_identifier();
1974 imp->require_c_string(" ");
1975 if (!num.empty() && num[num.length() - 1] == 'i')
1977 mpfr_t real;
1978 size_t plus_pos = num.find('+', 1);
1979 size_t minus_pos = num.find('-', 1);
1980 size_t pos;
1981 if (plus_pos == std::string::npos)
1982 pos = minus_pos;
1983 else if (minus_pos == std::string::npos)
1984 pos = plus_pos;
1985 else
1987 error_at(imp->location(), "bad number in import data: %qs",
1988 num.c_str());
1989 return Expression::make_error(imp->location());
1991 if (pos == std::string::npos)
1992 mpfr_set_ui(real, 0, GMP_RNDN);
1993 else
1995 std::string real_str = num.substr(0, pos);
1996 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1998 error_at(imp->location(), "bad number in import data: %qs",
1999 real_str.c_str());
2000 return Expression::make_error(imp->location());
2004 std::string imag_str;
2005 if (pos == std::string::npos)
2006 imag_str = num;
2007 else
2008 imag_str = num.substr(pos);
2009 imag_str = imag_str.substr(0, imag_str.size() - 1);
2010 mpfr_t imag;
2011 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2013 error_at(imp->location(), "bad number in import data: %qs",
2014 imag_str.c_str());
2015 return Expression::make_error(imp->location());
2017 mpc_t cval;
2018 mpc_init2(cval, mpc_precision);
2019 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2020 mpfr_clear(real);
2021 mpfr_clear(imag);
2022 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2023 mpc_clear(cval);
2024 return ret;
2026 else if (num.find('.') == std::string::npos
2027 && num.find('E') == std::string::npos)
2029 bool is_character_constant = (!num.empty()
2030 && num[num.length() - 1] == '\'');
2031 if (is_character_constant)
2032 num = num.substr(0, num.length() - 1);
2033 mpz_t val;
2034 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2036 error_at(imp->location(), "bad number in import data: %qs",
2037 num.c_str());
2038 return Expression::make_error(imp->location());
2040 Expression* ret;
2041 if (is_character_constant)
2042 ret = Expression::make_character(&val, NULL, imp->location());
2043 else
2044 ret = Expression::make_integer_z(&val, NULL, imp->location());
2045 mpz_clear(val);
2046 return ret;
2048 else
2050 mpfr_t val;
2051 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2053 error_at(imp->location(), "bad number in import data: %qs",
2054 num.c_str());
2055 return Expression::make_error(imp->location());
2057 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2058 mpfr_clear(val);
2059 return ret;
2062 // Ast dump for integer expression.
2064 void
2065 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2067 if (this->is_character_constant_)
2068 ast_dump_context->ostream() << '\'';
2069 Integer_expression::export_integer(ast_dump_context, this->val_);
2070 if (this->is_character_constant_)
2071 ast_dump_context->ostream() << '\'';
2074 // Build a new integer value from a multi-precision integer.
2076 Expression*
2077 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2079 return new Integer_expression(val, type, false, location);
2082 // Build a new integer value from an unsigned long.
2084 Expression*
2085 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2087 mpz_t zval;
2088 mpz_init_set_ui(zval, val);
2089 Expression* ret = Expression::make_integer_z(&zval, type, location);
2090 mpz_clear(zval);
2091 return ret;
2094 // Build a new integer value from a signed long.
2096 Expression*
2097 Expression::make_integer_sl(long val, Type *type, Location location)
2099 mpz_t zval;
2100 mpz_init_set_si(zval, val);
2101 Expression* ret = Expression::make_integer_z(&zval, type, location);
2102 mpz_clear(zval);
2103 return ret;
2106 // Build a new character constant value.
2108 Expression*
2109 Expression::make_character(const mpz_t* val, Type* type, Location location)
2111 return new Integer_expression(val, type, true, location);
2114 // Floats.
2116 class Float_expression : public Expression
2118 public:
2119 Float_expression(const mpfr_t* val, Type* type, Location location)
2120 : Expression(EXPRESSION_FLOAT, location),
2121 type_(type)
2123 mpfr_init_set(this->val_, *val, GMP_RNDN);
2126 // Write VAL to export data.
2127 static void
2128 export_float(String_dump* exp, const mpfr_t val);
2130 // Write VAL to dump file.
2131 static void
2132 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2134 protected:
2135 bool
2136 do_is_constant() const
2137 { return true; }
2139 bool
2140 do_is_immutable() const
2141 { return true; }
2143 bool
2144 do_numeric_constant_value(Numeric_constant* nc) const
2146 nc->set_float(this->type_, this->val_);
2147 return true;
2150 Type*
2151 do_type();
2153 void
2154 do_determine_type(const Type_context*);
2156 void
2157 do_check_types(Gogo*);
2159 Expression*
2160 do_copy()
2161 { return Expression::make_float(&this->val_, this->type_,
2162 this->location()); }
2164 Bexpression*
2165 do_get_backend(Translate_context*);
2167 void
2168 do_export(Export*) const;
2170 void
2171 do_dump_expression(Ast_dump_context*) const;
2173 private:
2174 // The floating point value.
2175 mpfr_t val_;
2176 // The type so far.
2177 Type* type_;
2180 // Return the current type. If we haven't set the type yet, we return
2181 // an abstract float type.
2183 Type*
2184 Float_expression::do_type()
2186 if (this->type_ == NULL)
2187 this->type_ = Type::make_abstract_float_type();
2188 return this->type_;
2191 // Set the type of the float value. Here we may switch from an
2192 // abstract type to a real type.
2194 void
2195 Float_expression::do_determine_type(const Type_context* context)
2197 if (this->type_ != NULL && !this->type_->is_abstract())
2199 else if (context->type != NULL
2200 && (context->type->integer_type() != NULL
2201 || context->type->float_type() != NULL
2202 || context->type->complex_type() != NULL))
2203 this->type_ = context->type;
2204 else if (!context->may_be_abstract)
2205 this->type_ = Type::lookup_float_type("float64");
2208 // Check the type of a float value.
2210 void
2211 Float_expression::do_check_types(Gogo*)
2213 Type* type = this->type_;
2214 if (type == NULL)
2215 return;
2216 Numeric_constant nc;
2217 nc.set_float(NULL, this->val_);
2218 if (!nc.set_type(this->type_, true, this->location()))
2219 this->set_is_error();
2222 // Get the backend representation for a float constant.
2224 Bexpression*
2225 Float_expression::do_get_backend(Translate_context* context)
2227 Type* resolved_type;
2228 if (this->type_ != NULL && !this->type_->is_abstract())
2229 resolved_type = this->type_;
2230 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2232 // We have an abstract integer type. We just hope for the best.
2233 resolved_type = Type::lookup_integer_type("int");
2235 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2237 // We are converting to an abstract complex type.
2238 resolved_type = Type::lookup_complex_type("complex128");
2240 else
2242 // If we still have an abstract type here, then this is being
2243 // used in a constant expression which didn't get reduced. We
2244 // just use float64 and hope for the best.
2245 resolved_type = Type::lookup_float_type("float64");
2248 Numeric_constant nc;
2249 nc.set_float(resolved_type, this->val_);
2250 return Expression::backend_numeric_constant_expression(context, &nc);
2253 // Write a floating point number to a string dump.
2255 void
2256 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2258 mp_exp_t exponent;
2259 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2260 if (*s == '-')
2261 exp->write_c_string("-");
2262 exp->write_c_string("0.");
2263 exp->write_c_string(*s == '-' ? s + 1 : s);
2264 mpfr_free_str(s);
2265 char buf[30];
2266 snprintf(buf, sizeof buf, "E%ld", exponent);
2267 exp->write_c_string(buf);
2270 // Export a floating point number in a constant expression.
2272 void
2273 Float_expression::do_export(Export* exp) const
2275 Float_expression::export_float(exp, this->val_);
2276 // A trailing space lets us reliably identify the end of the number.
2277 exp->write_c_string(" ");
2280 // Dump a floating point number to the dump file.
2282 void
2283 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2285 Float_expression::export_float(ast_dump_context, this->val_);
2288 // Make a float expression.
2290 Expression*
2291 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2293 return new Float_expression(val, type, location);
2296 // Complex numbers.
2298 class Complex_expression : public Expression
2300 public:
2301 Complex_expression(const mpc_t* val, Type* type, Location location)
2302 : Expression(EXPRESSION_COMPLEX, location),
2303 type_(type)
2305 mpc_init2(this->val_, mpc_precision);
2306 mpc_set(this->val_, *val, MPC_RNDNN);
2309 // Write VAL to string dump.
2310 static void
2311 export_complex(String_dump* exp, const mpc_t val);
2313 // Write REAL/IMAG to dump context.
2314 static void
2315 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2317 protected:
2318 bool
2319 do_is_constant() const
2320 { return true; }
2322 bool
2323 do_is_immutable() const
2324 { return true; }
2326 bool
2327 do_numeric_constant_value(Numeric_constant* nc) const
2329 nc->set_complex(this->type_, this->val_);
2330 return true;
2333 Type*
2334 do_type();
2336 void
2337 do_determine_type(const Type_context*);
2339 void
2340 do_check_types(Gogo*);
2342 Expression*
2343 do_copy()
2345 return Expression::make_complex(&this->val_, this->type_,
2346 this->location());
2349 Bexpression*
2350 do_get_backend(Translate_context*);
2352 void
2353 do_export(Export*) const;
2355 void
2356 do_dump_expression(Ast_dump_context*) const;
2358 private:
2359 // The complex value.
2360 mpc_t val_;
2361 // The type if known.
2362 Type* type_;
2365 // Return the current type. If we haven't set the type yet, we return
2366 // an abstract complex type.
2368 Type*
2369 Complex_expression::do_type()
2371 if (this->type_ == NULL)
2372 this->type_ = Type::make_abstract_complex_type();
2373 return this->type_;
2376 // Set the type of the complex value. Here we may switch from an
2377 // abstract type to a real type.
2379 void
2380 Complex_expression::do_determine_type(const Type_context* context)
2382 if (this->type_ != NULL && !this->type_->is_abstract())
2384 else if (context->type != NULL
2385 && context->type->complex_type() != NULL)
2386 this->type_ = context->type;
2387 else if (!context->may_be_abstract)
2388 this->type_ = Type::lookup_complex_type("complex128");
2391 // Check the type of a complex value.
2393 void
2394 Complex_expression::do_check_types(Gogo*)
2396 Type* type = this->type_;
2397 if (type == NULL)
2398 return;
2399 Numeric_constant nc;
2400 nc.set_complex(NULL, this->val_);
2401 if (!nc.set_type(this->type_, true, this->location()))
2402 this->set_is_error();
2405 // Get the backend representation for a complex constant.
2407 Bexpression*
2408 Complex_expression::do_get_backend(Translate_context* context)
2410 Type* resolved_type;
2411 if (this->type_ != NULL && !this->type_->is_abstract())
2412 resolved_type = this->type_;
2413 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2415 // We are converting to an abstract integer type.
2416 resolved_type = Type::lookup_integer_type("int");
2418 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2420 // We are converting to an abstract float type.
2421 resolved_type = Type::lookup_float_type("float64");
2423 else
2425 // If we still have an abstract type here, this this is being
2426 // used in a constant expression which didn't get reduced. We
2427 // just use complex128 and hope for the best.
2428 resolved_type = Type::lookup_complex_type("complex128");
2431 Numeric_constant nc;
2432 nc.set_complex(resolved_type, this->val_);
2433 return Expression::backend_numeric_constant_expression(context, &nc);
2436 // Write REAL/IMAG to export data.
2438 void
2439 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2441 if (!mpfr_zero_p(mpc_realref(val)))
2443 Float_expression::export_float(exp, mpc_realref(val));
2444 if (mpfr_sgn(mpc_imagref(val)) > 0)
2445 exp->write_c_string("+");
2447 Float_expression::export_float(exp, mpc_imagref(val));
2448 exp->write_c_string("i");
2451 // Export a complex number in a constant expression.
2453 void
2454 Complex_expression::do_export(Export* exp) const
2456 Complex_expression::export_complex(exp, this->val_);
2457 // A trailing space lets us reliably identify the end of the number.
2458 exp->write_c_string(" ");
2461 // Dump a complex expression to the dump file.
2463 void
2464 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2466 Complex_expression::export_complex(ast_dump_context, this->val_);
2469 // Make a complex expression.
2471 Expression*
2472 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2474 return new Complex_expression(val, type, location);
2477 // Find a named object in an expression.
2479 class Find_named_object : public Traverse
2481 public:
2482 Find_named_object(Named_object* no)
2483 : Traverse(traverse_expressions),
2484 no_(no), found_(false)
2487 // Whether we found the object.
2488 bool
2489 found() const
2490 { return this->found_; }
2492 protected:
2494 expression(Expression**);
2496 private:
2497 // The object we are looking for.
2498 Named_object* no_;
2499 // Whether we found it.
2500 bool found_;
2503 // A reference to a const in an expression.
2505 class Const_expression : public Expression
2507 public:
2508 Const_expression(Named_object* constant, Location location)
2509 : Expression(EXPRESSION_CONST_REFERENCE, location),
2510 constant_(constant), type_(NULL), seen_(false)
2513 Named_object*
2514 named_object()
2515 { return this->constant_; }
2517 // Check that the initializer does not refer to the constant itself.
2518 void
2519 check_for_init_loop();
2521 protected:
2523 do_traverse(Traverse*);
2525 Expression*
2526 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2528 bool
2529 do_is_constant() const
2530 { return true; }
2532 bool
2533 do_is_immutable() const
2534 { return true; }
2536 bool
2537 do_numeric_constant_value(Numeric_constant* nc) const;
2539 bool
2540 do_string_constant_value(std::string* val) const;
2542 Type*
2543 do_type();
2545 // The type of a const is set by the declaration, not the use.
2546 void
2547 do_determine_type(const Type_context*);
2549 void
2550 do_check_types(Gogo*);
2552 Expression*
2553 do_copy()
2554 { return this; }
2556 Bexpression*
2557 do_get_backend(Translate_context* context);
2559 // When exporting a reference to a const as part of a const
2560 // expression, we export the value. We ignore the fact that it has
2561 // a name.
2562 void
2563 do_export(Export* exp) const
2564 { this->constant_->const_value()->expr()->export_expression(exp); }
2566 void
2567 do_dump_expression(Ast_dump_context*) const;
2569 private:
2570 // The constant.
2571 Named_object* constant_;
2572 // The type of this reference. This is used if the constant has an
2573 // abstract type.
2574 Type* type_;
2575 // Used to prevent infinite recursion when a constant incorrectly
2576 // refers to itself.
2577 mutable bool seen_;
2580 // Traversal.
2583 Const_expression::do_traverse(Traverse* traverse)
2585 if (this->type_ != NULL)
2586 return Type::traverse(this->type_, traverse);
2587 return TRAVERSE_CONTINUE;
2590 // Lower a constant expression. This is where we convert the
2591 // predeclared constant iota into an integer value.
2593 Expression*
2594 Const_expression::do_lower(Gogo* gogo, Named_object*,
2595 Statement_inserter*, int iota_value)
2597 if (this->constant_->const_value()->expr()->classification()
2598 == EXPRESSION_IOTA)
2600 if (iota_value == -1)
2602 error_at(this->location(),
2603 "iota is only defined in const declarations");
2604 iota_value = 0;
2606 return Expression::make_integer_ul(iota_value, NULL, this->location());
2609 // Make sure that the constant itself has been lowered.
2610 gogo->lower_constant(this->constant_);
2612 return this;
2615 // Return a numeric constant value.
2617 bool
2618 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2620 if (this->seen_)
2621 return false;
2623 Expression* e = this->constant_->const_value()->expr();
2625 this->seen_ = true;
2627 bool r = e->numeric_constant_value(nc);
2629 this->seen_ = false;
2631 Type* ctype;
2632 if (this->type_ != NULL)
2633 ctype = this->type_;
2634 else
2635 ctype = this->constant_->const_value()->type();
2636 if (r && ctype != NULL)
2638 if (!nc->set_type(ctype, false, this->location()))
2639 return false;
2642 return r;
2645 bool
2646 Const_expression::do_string_constant_value(std::string* val) const
2648 if (this->seen_)
2649 return false;
2651 Expression* e = this->constant_->const_value()->expr();
2653 this->seen_ = true;
2654 bool ok = e->string_constant_value(val);
2655 this->seen_ = false;
2657 return ok;
2660 // Return the type of the const reference.
2662 Type*
2663 Const_expression::do_type()
2665 if (this->type_ != NULL)
2666 return this->type_;
2668 Named_constant* nc = this->constant_->const_value();
2670 if (this->seen_ || nc->lowering())
2672 this->report_error(_("constant refers to itself"));
2673 this->type_ = Type::make_error_type();
2674 return this->type_;
2677 this->seen_ = true;
2679 Type* ret = nc->type();
2681 if (ret != NULL)
2683 this->seen_ = false;
2684 return ret;
2687 // During parsing, a named constant may have a NULL type, but we
2688 // must not return a NULL type here.
2689 ret = nc->expr()->type();
2691 this->seen_ = false;
2693 return ret;
2696 // Set the type of the const reference.
2698 void
2699 Const_expression::do_determine_type(const Type_context* context)
2701 Type* ctype = this->constant_->const_value()->type();
2702 Type* cetype = (ctype != NULL
2703 ? ctype
2704 : this->constant_->const_value()->expr()->type());
2705 if (ctype != NULL && !ctype->is_abstract())
2707 else if (context->type != NULL
2708 && context->type->is_numeric_type()
2709 && cetype->is_numeric_type())
2710 this->type_ = context->type;
2711 else if (context->type != NULL
2712 && context->type->is_string_type()
2713 && cetype->is_string_type())
2714 this->type_ = context->type;
2715 else if (context->type != NULL
2716 && context->type->is_boolean_type()
2717 && cetype->is_boolean_type())
2718 this->type_ = context->type;
2719 else if (!context->may_be_abstract)
2721 if (cetype->is_abstract())
2722 cetype = cetype->make_non_abstract_type();
2723 this->type_ = cetype;
2727 // Check for a loop in which the initializer of a constant refers to
2728 // the constant itself.
2730 void
2731 Const_expression::check_for_init_loop()
2733 if (this->type_ != NULL && this->type_->is_error())
2734 return;
2736 if (this->seen_)
2738 this->report_error(_("constant refers to itself"));
2739 this->type_ = Type::make_error_type();
2740 return;
2743 Expression* init = this->constant_->const_value()->expr();
2744 Find_named_object find_named_object(this->constant_);
2746 this->seen_ = true;
2747 Expression::traverse(&init, &find_named_object);
2748 this->seen_ = false;
2750 if (find_named_object.found())
2752 if (this->type_ == NULL || !this->type_->is_error())
2754 this->report_error(_("constant refers to itself"));
2755 this->type_ = Type::make_error_type();
2757 return;
2761 // Check types of a const reference.
2763 void
2764 Const_expression::do_check_types(Gogo*)
2766 if (this->type_ != NULL && this->type_->is_error())
2767 return;
2769 this->check_for_init_loop();
2771 // Check that numeric constant fits in type.
2772 if (this->type_ != NULL && this->type_->is_numeric_type())
2774 Numeric_constant nc;
2775 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2777 if (!nc.set_type(this->type_, true, this->location()))
2778 this->set_is_error();
2783 // Return the backend representation for a const reference.
2785 Bexpression*
2786 Const_expression::do_get_backend(Translate_context* context)
2788 if (this->type_ != NULL && this->type_->is_error())
2789 return context->backend()->error_expression();
2791 // If the type has been set for this expression, but the underlying
2792 // object is an abstract int or float, we try to get the abstract
2793 // value. Otherwise we may lose something in the conversion.
2794 Expression* expr = this->constant_->const_value()->expr();
2795 if (this->type_ != NULL
2796 && this->type_->is_numeric_type()
2797 && (this->constant_->const_value()->type() == NULL
2798 || this->constant_->const_value()->type()->is_abstract()))
2800 Numeric_constant nc;
2801 if (expr->numeric_constant_value(&nc)
2802 && nc.set_type(this->type_, false, this->location()))
2804 Expression* e = nc.expression(this->location());
2805 return e->get_backend(context);
2809 if (this->type_ != NULL)
2810 expr = Expression::make_cast(this->type_, expr, this->location());
2811 return expr->get_backend(context);
2814 // Dump ast representation for constant expression.
2816 void
2817 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2819 ast_dump_context->ostream() << this->constant_->name();
2822 // Make a reference to a constant in an expression.
2824 Expression*
2825 Expression::make_const_reference(Named_object* constant,
2826 Location location)
2828 return new Const_expression(constant, location);
2831 // Find a named object in an expression.
2834 Find_named_object::expression(Expression** pexpr)
2836 switch ((*pexpr)->classification())
2838 case Expression::EXPRESSION_CONST_REFERENCE:
2840 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2841 if (ce->named_object() == this->no_)
2842 break;
2844 // We need to check a constant initializer explicitly, as
2845 // loops here will not be caught by the loop checking for
2846 // variable initializers.
2847 ce->check_for_init_loop();
2849 return TRAVERSE_CONTINUE;
2852 case Expression::EXPRESSION_VAR_REFERENCE:
2853 if ((*pexpr)->var_expression()->named_object() == this->no_)
2854 break;
2855 return TRAVERSE_CONTINUE;
2856 case Expression::EXPRESSION_FUNC_REFERENCE:
2857 if ((*pexpr)->func_expression()->named_object() == this->no_)
2858 break;
2859 return TRAVERSE_CONTINUE;
2860 default:
2861 return TRAVERSE_CONTINUE;
2863 this->found_ = true;
2864 return TRAVERSE_EXIT;
2867 // The nil value.
2869 class Nil_expression : public Expression
2871 public:
2872 Nil_expression(Location location)
2873 : Expression(EXPRESSION_NIL, location)
2876 static Expression*
2877 do_import(Import*);
2879 protected:
2880 bool
2881 do_is_constant() const
2882 { return true; }
2884 bool
2885 do_is_immutable() const
2886 { return true; }
2888 Type*
2889 do_type()
2890 { return Type::make_nil_type(); }
2892 void
2893 do_determine_type(const Type_context*)
2896 Expression*
2897 do_copy()
2898 { return this; }
2900 Bexpression*
2901 do_get_backend(Translate_context* context)
2902 { return context->backend()->nil_pointer_expression(); }
2904 void
2905 do_export(Export* exp) const
2906 { exp->write_c_string("nil"); }
2908 void
2909 do_dump_expression(Ast_dump_context* ast_dump_context) const
2910 { ast_dump_context->ostream() << "nil"; }
2913 // Import a nil expression.
2915 Expression*
2916 Nil_expression::do_import(Import* imp)
2918 imp->require_c_string("nil");
2919 return Expression::make_nil(imp->location());
2922 // Make a nil expression.
2924 Expression*
2925 Expression::make_nil(Location location)
2927 return new Nil_expression(location);
2930 // The value of the predeclared constant iota. This is little more
2931 // than a marker. This will be lowered to an integer in
2932 // Const_expression::do_lower, which is where we know the value that
2933 // it should have.
2935 class Iota_expression : public Parser_expression
2937 public:
2938 Iota_expression(Location location)
2939 : Parser_expression(EXPRESSION_IOTA, location)
2942 protected:
2943 Expression*
2944 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2945 { go_unreachable(); }
2947 // There should only ever be one of these.
2948 Expression*
2949 do_copy()
2950 { go_unreachable(); }
2952 void
2953 do_dump_expression(Ast_dump_context* ast_dump_context) const
2954 { ast_dump_context->ostream() << "iota"; }
2957 // Make an iota expression. This is only called for one case: the
2958 // value of the predeclared constant iota.
2960 Expression*
2961 Expression::make_iota()
2963 static Iota_expression iota_expression(Linemap::unknown_location());
2964 return &iota_expression;
2967 // A type conversion expression.
2969 class Type_conversion_expression : public Expression
2971 public:
2972 Type_conversion_expression(Type* type, Expression* expr,
2973 Location location)
2974 : Expression(EXPRESSION_CONVERSION, location),
2975 type_(type), expr_(expr), may_convert_function_types_(false)
2978 // Return the type to which we are converting.
2979 Type*
2980 type() const
2981 { return this->type_; }
2983 // Return the expression which we are converting.
2984 Expression*
2985 expr() const
2986 { return this->expr_; }
2988 // Permit converting from one function type to another. This is
2989 // used internally for method expressions.
2990 void
2991 set_may_convert_function_types()
2993 this->may_convert_function_types_ = true;
2996 // Import a type conversion expression.
2997 static Expression*
2998 do_import(Import*);
3000 protected:
3002 do_traverse(Traverse* traverse);
3004 Expression*
3005 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3007 Expression*
3008 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3010 bool
3011 do_is_constant() const;
3013 bool
3014 do_is_immutable() const;
3016 bool
3017 do_numeric_constant_value(Numeric_constant*) const;
3019 bool
3020 do_string_constant_value(std::string*) const;
3022 Type*
3023 do_type()
3024 { return this->type_; }
3026 void
3027 do_determine_type(const Type_context*)
3029 Type_context subcontext(this->type_, false);
3030 this->expr_->determine_type(&subcontext);
3033 void
3034 do_check_types(Gogo*);
3036 Expression*
3037 do_copy()
3039 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3040 this->location());
3043 Bexpression*
3044 do_get_backend(Translate_context* context);
3046 void
3047 do_export(Export*) const;
3049 void
3050 do_dump_expression(Ast_dump_context*) const;
3052 private:
3053 // The type to convert to.
3054 Type* type_;
3055 // The expression to convert.
3056 Expression* expr_;
3057 // True if this is permitted to convert function types. This is
3058 // used internally for method expressions.
3059 bool may_convert_function_types_;
3062 // Traversal.
3065 Type_conversion_expression::do_traverse(Traverse* traverse)
3067 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3068 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3069 return TRAVERSE_EXIT;
3070 return TRAVERSE_CONTINUE;
3073 // Convert to a constant at lowering time.
3075 Expression*
3076 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3077 Statement_inserter*, int)
3079 Type* type = this->type_;
3080 Expression* val = this->expr_;
3081 Location location = this->location();
3083 if (type->is_numeric_type())
3085 Numeric_constant nc;
3086 if (val->numeric_constant_value(&nc))
3088 if (!nc.set_type(type, true, location))
3089 return Expression::make_error(location);
3090 return nc.expression(location);
3094 if (type->is_slice_type())
3096 Type* element_type = type->array_type()->element_type()->forwarded();
3097 bool is_byte = (element_type->integer_type() != NULL
3098 && element_type->integer_type()->is_byte());
3099 bool is_rune = (element_type->integer_type() != NULL
3100 && element_type->integer_type()->is_rune());
3101 if (is_byte || is_rune)
3103 std::string s;
3104 if (val->string_constant_value(&s))
3106 Expression_list* vals = new Expression_list();
3107 if (is_byte)
3109 for (std::string::const_iterator p = s.begin();
3110 p != s.end();
3111 p++)
3113 unsigned char c = static_cast<unsigned char>(*p);
3114 vals->push_back(Expression::make_integer_ul(c,
3115 element_type,
3116 location));
3119 else
3121 const char *p = s.data();
3122 const char *pend = s.data() + s.length();
3123 while (p < pend)
3125 unsigned int c;
3126 int adv = Lex::fetch_char(p, &c);
3127 if (adv == 0)
3129 warning_at(this->location(), 0,
3130 "invalid UTF-8 encoding");
3131 adv = 1;
3133 p += adv;
3134 vals->push_back(Expression::make_integer_ul(c,
3135 element_type,
3136 location));
3140 return Expression::make_slice_composite_literal(type, vals,
3141 location);
3146 return this;
3149 // Flatten a type conversion by using a temporary variable for the slice
3150 // in slice to string conversions.
3152 Expression*
3153 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3154 Statement_inserter* inserter)
3156 if (((this->type()->is_string_type()
3157 && this->expr_->type()->is_slice_type())
3158 || (this->type()->interface_type() != NULL
3159 && this->expr_->type()->interface_type() != NULL))
3160 && !this->expr_->is_variable())
3162 Temporary_statement* temp =
3163 Statement::make_temporary(NULL, this->expr_, this->location());
3164 inserter->insert(temp);
3165 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3167 return this;
3170 // Return whether a type conversion is a constant.
3172 bool
3173 Type_conversion_expression::do_is_constant() const
3175 if (!this->expr_->is_constant())
3176 return false;
3178 // A conversion to a type that may not be used as a constant is not
3179 // a constant. For example, []byte(nil).
3180 Type* type = this->type_;
3181 if (type->integer_type() == NULL
3182 && type->float_type() == NULL
3183 && type->complex_type() == NULL
3184 && !type->is_boolean_type()
3185 && !type->is_string_type())
3186 return false;
3188 return true;
3191 // Return whether a type conversion is immutable.
3193 bool
3194 Type_conversion_expression::do_is_immutable() const
3196 Type* type = this->type_;
3197 Type* expr_type = this->expr_->type();
3199 if (type->interface_type() != NULL
3200 || expr_type->interface_type() != NULL)
3201 return false;
3203 if (!this->expr_->is_immutable())
3204 return false;
3206 if (Type::are_identical(type, expr_type, false, NULL))
3207 return true;
3209 return type->is_basic_type() && expr_type->is_basic_type();
3212 // Return the constant numeric value if there is one.
3214 bool
3215 Type_conversion_expression::do_numeric_constant_value(
3216 Numeric_constant* nc) const
3218 if (!this->type_->is_numeric_type())
3219 return false;
3220 if (!this->expr_->numeric_constant_value(nc))
3221 return false;
3222 return nc->set_type(this->type_, false, this->location());
3225 // Return the constant string value if there is one.
3227 bool
3228 Type_conversion_expression::do_string_constant_value(std::string* val) const
3230 if (this->type_->is_string_type()
3231 && this->expr_->type()->integer_type() != NULL)
3233 Numeric_constant nc;
3234 if (this->expr_->numeric_constant_value(&nc))
3236 unsigned long ival;
3237 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3239 val->clear();
3240 Lex::append_char(ival, true, val, this->location());
3241 return true;
3246 // FIXME: Could handle conversion from const []int here.
3248 return false;
3251 // Check that types are convertible.
3253 void
3254 Type_conversion_expression::do_check_types(Gogo*)
3256 Type* type = this->type_;
3257 Type* expr_type = this->expr_->type();
3258 std::string reason;
3260 if (type->is_error() || expr_type->is_error())
3262 this->set_is_error();
3263 return;
3266 if (this->may_convert_function_types_
3267 && type->function_type() != NULL
3268 && expr_type->function_type() != NULL)
3269 return;
3271 if (Type::are_convertible(type, expr_type, &reason))
3272 return;
3274 error_at(this->location(), "%s", reason.c_str());
3275 this->set_is_error();
3278 // Get the backend representation for a type conversion.
3280 Bexpression*
3281 Type_conversion_expression::do_get_backend(Translate_context* context)
3283 Type* type = this->type_;
3284 Type* expr_type = this->expr_->type();
3286 Gogo* gogo = context->gogo();
3287 Btype* btype = type->get_backend(gogo);
3288 Bexpression* bexpr = this->expr_->get_backend(context);
3289 Location loc = this->location();
3291 if (Type::are_identical(type, expr_type, false, NULL))
3292 return gogo->backend()->convert_expression(btype, bexpr, loc);
3293 else if (type->interface_type() != NULL
3294 || expr_type->interface_type() != NULL)
3296 Expression* conversion =
3297 Expression::convert_for_assignment(gogo, type, this->expr_,
3298 this->location());
3299 return conversion->get_backend(context);
3301 else if (type->is_string_type()
3302 && expr_type->integer_type() != NULL)
3304 mpz_t intval;
3305 Numeric_constant nc;
3306 if (this->expr_->numeric_constant_value(&nc)
3307 && nc.to_int(&intval)
3308 && mpz_fits_ushort_p(intval))
3310 std::string s;
3311 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3312 mpz_clear(intval);
3313 Expression* se = Expression::make_string(s, loc);
3314 return se->get_backend(context);
3317 Expression* i2s_expr =
3318 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3319 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3321 else if (type->is_string_type() && expr_type->is_slice_type())
3323 Array_type* a = expr_type->array_type();
3324 Type* e = a->element_type()->forwarded();
3325 go_assert(e->integer_type() != NULL);
3326 go_assert(this->expr_->is_variable());
3328 Runtime::Function code;
3329 if (e->integer_type()->is_byte())
3330 code = Runtime::BYTE_ARRAY_TO_STRING;
3331 else
3333 go_assert(e->integer_type()->is_rune());
3334 code = Runtime::INT_ARRAY_TO_STRING;
3336 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3337 Expression* len = a->get_length(gogo, this->expr_);
3338 return Runtime::make_call(code, loc, 2, valptr,
3339 len)->get_backend(context);
3341 else if (type->is_slice_type() && expr_type->is_string_type())
3343 Type* e = type->array_type()->element_type()->forwarded();
3344 go_assert(e->integer_type() != NULL);
3346 Runtime::Function code;
3347 if (e->integer_type()->is_byte())
3348 code = Runtime::STRING_TO_BYTE_ARRAY;
3349 else
3351 go_assert(e->integer_type()->is_rune());
3352 code = Runtime::STRING_TO_INT_ARRAY;
3354 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3355 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3357 else if (type->is_numeric_type())
3359 go_assert(Type::are_convertible(type, expr_type, NULL));
3360 return gogo->backend()->convert_expression(btype, bexpr, loc);
3362 else if ((type->is_unsafe_pointer_type()
3363 && (expr_type->points_to() != NULL
3364 || expr_type->integer_type()))
3365 || (expr_type->is_unsafe_pointer_type()
3366 && type->points_to() != NULL)
3367 || (this->may_convert_function_types_
3368 && type->function_type() != NULL
3369 && expr_type->function_type() != NULL))
3370 return gogo->backend()->convert_expression(btype, bexpr, loc);
3371 else
3373 Expression* conversion =
3374 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3375 return conversion->get_backend(context);
3379 // Output a type conversion in a constant expression.
3381 void
3382 Type_conversion_expression::do_export(Export* exp) const
3384 exp->write_c_string("convert(");
3385 exp->write_type(this->type_);
3386 exp->write_c_string(", ");
3387 this->expr_->export_expression(exp);
3388 exp->write_c_string(")");
3391 // Import a type conversion or a struct construction.
3393 Expression*
3394 Type_conversion_expression::do_import(Import* imp)
3396 imp->require_c_string("convert(");
3397 Type* type = imp->read_type();
3398 imp->require_c_string(", ");
3399 Expression* val = Expression::import_expression(imp);
3400 imp->require_c_string(")");
3401 return Expression::make_cast(type, val, imp->location());
3404 // Dump ast representation for a type conversion expression.
3406 void
3407 Type_conversion_expression::do_dump_expression(
3408 Ast_dump_context* ast_dump_context) const
3410 ast_dump_context->dump_type(this->type_);
3411 ast_dump_context->ostream() << "(";
3412 ast_dump_context->dump_expression(this->expr_);
3413 ast_dump_context->ostream() << ") ";
3416 // Make a type cast expression.
3418 Expression*
3419 Expression::make_cast(Type* type, Expression* val, Location location)
3421 if (type->is_error_type() || val->is_error_expression())
3422 return Expression::make_error(location);
3423 return new Type_conversion_expression(type, val, location);
3426 // An unsafe type conversion, used to pass values to builtin functions.
3428 class Unsafe_type_conversion_expression : public Expression
3430 public:
3431 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3432 Location location)
3433 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3434 type_(type), expr_(expr)
3437 protected:
3439 do_traverse(Traverse* traverse);
3441 bool
3442 do_is_immutable() const;
3444 Type*
3445 do_type()
3446 { return this->type_; }
3448 void
3449 do_determine_type(const Type_context*)
3450 { this->expr_->determine_type_no_context(); }
3452 Expression*
3453 do_copy()
3455 return new Unsafe_type_conversion_expression(this->type_,
3456 this->expr_->copy(),
3457 this->location());
3460 Bexpression*
3461 do_get_backend(Translate_context*);
3463 void
3464 do_dump_expression(Ast_dump_context*) const;
3466 private:
3467 // The type to convert to.
3468 Type* type_;
3469 // The expression to convert.
3470 Expression* expr_;
3473 // Traversal.
3476 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3478 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3479 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3480 return TRAVERSE_EXIT;
3481 return TRAVERSE_CONTINUE;
3484 // Return whether an unsafe type conversion is immutable.
3486 bool
3487 Unsafe_type_conversion_expression::do_is_immutable() const
3489 Type* type = this->type_;
3490 Type* expr_type = this->expr_->type();
3492 if (type->interface_type() != NULL
3493 || expr_type->interface_type() != NULL)
3494 return false;
3496 if (!this->expr_->is_immutable())
3497 return false;
3499 if (Type::are_convertible(type, expr_type, NULL))
3500 return true;
3502 return type->is_basic_type() && expr_type->is_basic_type();
3505 // Convert to backend representation.
3507 Bexpression*
3508 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3510 // We are only called for a limited number of cases.
3512 Type* t = this->type_;
3513 Type* et = this->expr_->type();
3514 if (t->array_type() != NULL)
3515 go_assert(et->array_type() != NULL
3516 && t->is_slice_type() == et->is_slice_type());
3517 else if (t->struct_type() != NULL)
3519 if (t->named_type() != NULL
3520 && et->named_type() != NULL
3521 && !Type::are_convertible(t, et, NULL))
3523 go_assert(saw_errors());
3524 return context->backend()->error_expression();
3527 go_assert(et->struct_type() != NULL
3528 && Type::are_convertible(t, et, NULL));
3530 else if (t->map_type() != NULL)
3531 go_assert(et->map_type() != NULL);
3532 else if (t->channel_type() != NULL)
3533 go_assert(et->channel_type() != NULL);
3534 else if (t->points_to() != NULL)
3535 go_assert(et->points_to() != NULL
3536 || et->channel_type() != NULL
3537 || et->map_type() != NULL
3538 || et->function_type() != NULL
3539 || et->is_nil_type());
3540 else if (et->is_unsafe_pointer_type())
3541 go_assert(t->points_to() != NULL);
3542 else if (t->interface_type() != NULL)
3544 bool empty_iface = t->interface_type()->is_empty();
3545 go_assert(et->interface_type() != NULL
3546 && et->interface_type()->is_empty() == empty_iface);
3548 else if (t->integer_type() != NULL)
3549 go_assert(et->is_boolean_type()
3550 || et->integer_type() != NULL
3551 || et->function_type() != NULL
3552 || et->points_to() != NULL
3553 || et->map_type() != NULL
3554 || et->channel_type() != NULL);
3555 else
3556 go_unreachable();
3558 Gogo* gogo = context->gogo();
3559 Btype* btype = t->get_backend(gogo);
3560 Bexpression* bexpr = this->expr_->get_backend(context);
3561 Location loc = this->location();
3562 return gogo->backend()->convert_expression(btype, bexpr, loc);
3565 // Dump ast representation for an unsafe type conversion expression.
3567 void
3568 Unsafe_type_conversion_expression::do_dump_expression(
3569 Ast_dump_context* ast_dump_context) const
3571 ast_dump_context->dump_type(this->type_);
3572 ast_dump_context->ostream() << "(";
3573 ast_dump_context->dump_expression(this->expr_);
3574 ast_dump_context->ostream() << ") ";
3577 // Make an unsafe type conversion expression.
3579 Expression*
3580 Expression::make_unsafe_cast(Type* type, Expression* expr,
3581 Location location)
3583 return new Unsafe_type_conversion_expression(type, expr, location);
3586 // Class Unary_expression.
3588 // If we are taking the address of a composite literal, and the
3589 // contents are not constant, then we want to make a heap expression
3590 // instead.
3592 Expression*
3593 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3595 Location loc = this->location();
3596 Operator op = this->op_;
3597 Expression* expr = this->expr_;
3599 if (op == OPERATOR_MULT && expr->is_type_expression())
3600 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3602 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3603 // moving x to the heap. FIXME: Is it worth doing a real escape
3604 // analysis here? This case is found in math/unsafe.go and is
3605 // therefore worth special casing.
3606 if (op == OPERATOR_MULT)
3608 Expression* e = expr;
3609 while (e->classification() == EXPRESSION_CONVERSION)
3611 Type_conversion_expression* te
3612 = static_cast<Type_conversion_expression*>(e);
3613 e = te->expr();
3616 if (e->classification() == EXPRESSION_UNARY)
3618 Unary_expression* ue = static_cast<Unary_expression*>(e);
3619 if (ue->op_ == OPERATOR_AND)
3621 if (e == expr)
3623 // *&x == x.
3624 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3626 error_at(ue->location(),
3627 "invalid operand for unary %<&%>");
3628 this->set_is_error();
3630 return ue->expr_;
3632 ue->set_does_not_escape();
3637 // Catching an invalid indirection of unsafe.Pointer here avoid
3638 // having to deal with TYPE_VOID in other places.
3639 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3641 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3642 return Expression::make_error(this->location());
3645 // Check for an invalid pointer dereference. We need to do this
3646 // here because Unary_expression::do_type will return an error type
3647 // in this case. That can cause code to appear erroneous, and
3648 // therefore disappear at lowering time, without any error message.
3649 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3651 this->report_error(_("expected pointer"));
3652 return Expression::make_error(this->location());
3655 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3657 Numeric_constant nc;
3658 if (expr->numeric_constant_value(&nc))
3660 Numeric_constant result;
3661 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3662 return result.expression(loc);
3666 return this;
3669 // Flatten expression if a nil check must be performed and create temporary
3670 // variables if necessary.
3672 Expression*
3673 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3674 Statement_inserter* inserter)
3676 if (this->is_error_expression() || this->expr_->is_error_expression())
3677 return Expression::make_error(this->location());
3679 Location location = this->location();
3680 if (this->op_ == OPERATOR_MULT
3681 && !this->expr_->is_variable())
3683 go_assert(this->expr_->type()->points_to() != NULL);
3684 Type* ptype = this->expr_->type()->points_to();
3685 if (!ptype->is_void_type())
3687 Btype* pbtype = ptype->get_backend(gogo);
3688 size_t s = gogo->backend()->type_size(pbtype);
3689 if (s >= 4096 || this->issue_nil_check_)
3691 Temporary_statement* temp =
3692 Statement::make_temporary(NULL, this->expr_, location);
3693 inserter->insert(temp);
3694 this->expr_ =
3695 Expression::make_temporary_reference(temp, location);
3700 if (this->create_temp_ && !this->expr_->is_variable())
3702 Temporary_statement* temp =
3703 Statement::make_temporary(NULL, this->expr_, location);
3704 inserter->insert(temp);
3705 this->expr_ = Expression::make_temporary_reference(temp, location);
3708 return this;
3711 // Return whether a unary expression is a constant.
3713 bool
3714 Unary_expression::do_is_constant() const
3716 if (this->op_ == OPERATOR_MULT)
3718 // Indirecting through a pointer is only constant if the object
3719 // to which the expression points is constant, but we currently
3720 // have no way to determine that.
3721 return false;
3723 else if (this->op_ == OPERATOR_AND)
3725 // Taking the address of a variable is constant if it is a
3726 // global variable, not constant otherwise. In other cases taking the
3727 // address is probably not a constant.
3728 Var_expression* ve = this->expr_->var_expression();
3729 if (ve != NULL)
3731 Named_object* no = ve->named_object();
3732 return no->is_variable() && no->var_value()->is_global();
3734 return false;
3736 else
3737 return this->expr_->is_constant();
3740 // Apply unary opcode OP to UNC, setting NC. Return true if this
3741 // could be done, false if not. Issue errors for overflow.
3743 bool
3744 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3745 Location location, Numeric_constant* nc)
3747 switch (op)
3749 case OPERATOR_PLUS:
3750 *nc = *unc;
3751 return true;
3753 case OPERATOR_MINUS:
3754 if (unc->is_int() || unc->is_rune())
3755 break;
3756 else if (unc->is_float())
3758 mpfr_t uval;
3759 unc->get_float(&uval);
3760 mpfr_t val;
3761 mpfr_init(val);
3762 mpfr_neg(val, uval, GMP_RNDN);
3763 nc->set_float(unc->type(), val);
3764 mpfr_clear(uval);
3765 mpfr_clear(val);
3766 return true;
3768 else if (unc->is_complex())
3770 mpc_t uval;
3771 unc->get_complex(&uval);
3772 mpc_t val;
3773 mpc_init2(val, mpc_precision);
3774 mpc_neg(val, uval, MPC_RNDNN);
3775 nc->set_complex(unc->type(), val);
3776 mpc_clear(uval);
3777 mpc_clear(val);
3778 return true;
3780 else
3781 go_unreachable();
3783 case OPERATOR_XOR:
3784 break;
3786 case OPERATOR_NOT:
3787 case OPERATOR_AND:
3788 case OPERATOR_MULT:
3789 return false;
3791 default:
3792 go_unreachable();
3795 if (!unc->is_int() && !unc->is_rune())
3796 return false;
3798 mpz_t uval;
3799 if (unc->is_rune())
3800 unc->get_rune(&uval);
3801 else
3802 unc->get_int(&uval);
3803 mpz_t val;
3804 mpz_init(val);
3806 switch (op)
3808 case OPERATOR_MINUS:
3809 mpz_neg(val, uval);
3810 break;
3812 case OPERATOR_NOT:
3813 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3814 break;
3816 case OPERATOR_XOR:
3818 Type* utype = unc->type();
3819 if (utype->integer_type() == NULL
3820 || utype->integer_type()->is_abstract())
3821 mpz_com(val, uval);
3822 else
3824 // The number of HOST_WIDE_INTs that it takes to represent
3825 // UVAL.
3826 size_t count = ((mpz_sizeinbase(uval, 2)
3827 + HOST_BITS_PER_WIDE_INT
3828 - 1)
3829 / HOST_BITS_PER_WIDE_INT);
3831 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3832 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3834 size_t obits = utype->integer_type()->bits();
3836 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3838 mpz_t adj;
3839 mpz_init_set_ui(adj, 1);
3840 mpz_mul_2exp(adj, adj, obits);
3841 mpz_add(uval, uval, adj);
3842 mpz_clear(adj);
3845 size_t ecount;
3846 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3847 go_assert(ecount <= count);
3849 // Trim down to the number of words required by the type.
3850 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3851 / HOST_BITS_PER_WIDE_INT);
3852 go_assert(ocount <= count);
3854 for (size_t i = 0; i < ocount; ++i)
3855 phwi[i] = ~phwi[i];
3857 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3858 if (clearbits != 0)
3859 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3860 >> clearbits);
3862 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3864 if (!utype->integer_type()->is_unsigned()
3865 && mpz_tstbit(val, obits - 1))
3867 mpz_t adj;
3868 mpz_init_set_ui(adj, 1);
3869 mpz_mul_2exp(adj, adj, obits);
3870 mpz_sub(val, val, adj);
3871 mpz_clear(adj);
3874 delete[] phwi;
3877 break;
3879 default:
3880 go_unreachable();
3883 if (unc->is_rune())
3884 nc->set_rune(NULL, val);
3885 else
3886 nc->set_int(NULL, val);
3888 mpz_clear(uval);
3889 mpz_clear(val);
3891 return nc->set_type(unc->type(), true, location);
3894 // Return the integral constant value of a unary expression, if it has one.
3896 bool
3897 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3899 Numeric_constant unc;
3900 if (!this->expr_->numeric_constant_value(&unc))
3901 return false;
3902 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3903 nc);
3906 // Return the type of a unary expression.
3908 Type*
3909 Unary_expression::do_type()
3911 switch (this->op_)
3913 case OPERATOR_PLUS:
3914 case OPERATOR_MINUS:
3915 case OPERATOR_NOT:
3916 case OPERATOR_XOR:
3917 return this->expr_->type();
3919 case OPERATOR_AND:
3920 return Type::make_pointer_type(this->expr_->type());
3922 case OPERATOR_MULT:
3924 Type* subtype = this->expr_->type();
3925 Type* points_to = subtype->points_to();
3926 if (points_to == NULL)
3927 return Type::make_error_type();
3928 return points_to;
3931 default:
3932 go_unreachable();
3936 // Determine abstract types for a unary expression.
3938 void
3939 Unary_expression::do_determine_type(const Type_context* context)
3941 switch (this->op_)
3943 case OPERATOR_PLUS:
3944 case OPERATOR_MINUS:
3945 case OPERATOR_NOT:
3946 case OPERATOR_XOR:
3947 this->expr_->determine_type(context);
3948 break;
3950 case OPERATOR_AND:
3951 // Taking the address of something.
3953 Type* subtype = (context->type == NULL
3954 ? NULL
3955 : context->type->points_to());
3956 Type_context subcontext(subtype, false);
3957 this->expr_->determine_type(&subcontext);
3959 break;
3961 case OPERATOR_MULT:
3962 // Indirecting through a pointer.
3964 Type* subtype = (context->type == NULL
3965 ? NULL
3966 : Type::make_pointer_type(context->type));
3967 Type_context subcontext(subtype, false);
3968 this->expr_->determine_type(&subcontext);
3970 break;
3972 default:
3973 go_unreachable();
3977 // Check types for a unary expression.
3979 void
3980 Unary_expression::do_check_types(Gogo*)
3982 Type* type = this->expr_->type();
3983 if (type->is_error())
3985 this->set_is_error();
3986 return;
3989 switch (this->op_)
3991 case OPERATOR_PLUS:
3992 case OPERATOR_MINUS:
3993 if (type->integer_type() == NULL
3994 && type->float_type() == NULL
3995 && type->complex_type() == NULL)
3996 this->report_error(_("expected numeric type"));
3997 break;
3999 case OPERATOR_NOT:
4000 if (!type->is_boolean_type())
4001 this->report_error(_("expected boolean type"));
4002 break;
4004 case OPERATOR_XOR:
4005 if (type->integer_type() == NULL
4006 && !type->is_boolean_type())
4007 this->report_error(_("expected integer or boolean type"));
4008 break;
4010 case OPERATOR_AND:
4011 if (!this->expr_->is_addressable())
4013 if (!this->create_temp_)
4015 error_at(this->location(), "invalid operand for unary %<&%>");
4016 this->set_is_error();
4019 else
4021 this->expr_->address_taken(this->escapes_);
4022 this->expr_->issue_nil_check();
4024 break;
4026 case OPERATOR_MULT:
4027 // Indirecting through a pointer.
4028 if (type->points_to() == NULL)
4029 this->report_error(_("expected pointer"));
4030 break;
4032 default:
4033 go_unreachable();
4037 // Get the backend representation for a unary expression.
4039 Bexpression*
4040 Unary_expression::do_get_backend(Translate_context* context)
4042 Gogo* gogo = context->gogo();
4043 Location loc = this->location();
4045 // Taking the address of a set-and-use-temporary expression requires
4046 // setting the temporary and then taking the address.
4047 if (this->op_ == OPERATOR_AND)
4049 Set_and_use_temporary_expression* sut =
4050 this->expr_->set_and_use_temporary_expression();
4051 if (sut != NULL)
4053 Temporary_statement* temp = sut->temporary();
4054 Bvariable* bvar = temp->get_backend_variable(context);
4055 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4056 Bexpression* bval = sut->expression()->get_backend(context);
4058 Bstatement* bassign =
4059 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4060 Bexpression* bvar_addr =
4061 gogo->backend()->address_expression(bvar_expr, loc);
4062 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4066 Bexpression* ret;
4067 Bexpression* bexpr = this->expr_->get_backend(context);
4068 Btype* btype = this->expr_->type()->get_backend(gogo);
4069 switch (this->op_)
4071 case OPERATOR_PLUS:
4072 ret = bexpr;
4073 break;
4075 case OPERATOR_MINUS:
4076 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4077 ret = gogo->backend()->convert_expression(btype, ret, loc);
4078 break;
4080 case OPERATOR_NOT:
4081 case OPERATOR_XOR:
4082 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4083 break;
4085 case OPERATOR_AND:
4086 if (!this->create_temp_)
4088 // We should not see a non-constant constructor here; cases
4089 // where we would see one should have been moved onto the
4090 // heap at parse time. Taking the address of a nonconstant
4091 // constructor will not do what the programmer expects.
4093 go_assert(!this->expr_->is_composite_literal()
4094 || this->expr_->is_immutable());
4095 if (this->expr_->classification() == EXPRESSION_UNARY)
4097 Unary_expression* ue =
4098 static_cast<Unary_expression*>(this->expr_);
4099 go_assert(ue->op() != OPERATOR_AND);
4103 static unsigned int counter;
4104 char buf[100];
4105 if (this->is_gc_root_ || this->is_slice_init_)
4107 bool copy_to_heap = false;
4108 if (this->is_gc_root_)
4110 // Build a decl for a GC root variable. GC roots are mutable, so
4111 // they cannot be represented as an immutable_struct in the
4112 // backend.
4113 static unsigned int root_counter;
4114 snprintf(buf, sizeof buf, "gc%u", root_counter);
4115 ++root_counter;
4117 else
4119 // Build a decl for a slice value initializer. An immutable slice
4120 // value initializer may have to be copied to the heap if it
4121 // contains pointers in a non-constant context.
4122 snprintf(buf, sizeof buf, "C%u", counter);
4123 ++counter;
4125 Array_type* at = this->expr_->type()->array_type();
4126 go_assert(at != NULL);
4128 // If we are not copying the value to the heap, we will only
4129 // initialize the value once, so we can use this directly
4130 // rather than copying it. In that case we can't make it
4131 // read-only, because the program is permitted to change it.
4132 copy_to_heap = (at->element_type()->has_pointer()
4133 && !context->is_const());
4135 Bvariable* implicit =
4136 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
4137 false, 0);
4138 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4139 true, copy_to_heap, false,
4140 bexpr);
4141 bexpr = gogo->backend()->var_expression(implicit, loc);
4143 else if ((this->expr_->is_composite_literal()
4144 || this->expr_->string_expression() != NULL)
4145 && this->expr_->is_immutable())
4147 // Build a decl for a constant constructor.
4148 snprintf(buf, sizeof buf, "C%u", counter);
4149 ++counter;
4151 Bvariable* decl =
4152 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4153 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4154 btype, loc, bexpr);
4155 bexpr = gogo->backend()->var_expression(decl, loc);
4158 go_assert(!this->create_temp_ || this->expr_->is_variable());
4159 ret = gogo->backend()->address_expression(bexpr, loc);
4160 break;
4162 case OPERATOR_MULT:
4164 go_assert(this->expr_->type()->points_to() != NULL);
4166 // If we are dereferencing the pointer to a large struct, we
4167 // need to check for nil. We don't bother to check for small
4168 // structs because we expect the system to crash on a nil
4169 // pointer dereference. However, if we know the address of this
4170 // expression is being taken, we must always check for nil.
4172 Type* ptype = this->expr_->type()->points_to();
4173 Btype* pbtype = ptype->get_backend(gogo);
4174 if (!ptype->is_void_type())
4176 size_t s = gogo->backend()->type_size(pbtype);
4177 if (s >= 4096 || this->issue_nil_check_)
4179 go_assert(this->expr_->is_variable());
4180 Bexpression* nil =
4181 Expression::make_nil(loc)->get_backend(context);
4182 Bexpression* compare =
4183 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4184 nil, loc);
4185 Bexpression* crash =
4186 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4187 loc)->get_backend(context);
4188 bexpr = gogo->backend()->conditional_expression(btype, compare,
4189 crash, bexpr,
4190 loc);
4194 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4196 break;
4198 default:
4199 go_unreachable();
4202 return ret;
4205 // Export a unary expression.
4207 void
4208 Unary_expression::do_export(Export* exp) const
4210 switch (this->op_)
4212 case OPERATOR_PLUS:
4213 exp->write_c_string("+ ");
4214 break;
4215 case OPERATOR_MINUS:
4216 exp->write_c_string("- ");
4217 break;
4218 case OPERATOR_NOT:
4219 exp->write_c_string("! ");
4220 break;
4221 case OPERATOR_XOR:
4222 exp->write_c_string("^ ");
4223 break;
4224 case OPERATOR_AND:
4225 case OPERATOR_MULT:
4226 default:
4227 go_unreachable();
4229 this->expr_->export_expression(exp);
4232 // Import a unary expression.
4234 Expression*
4235 Unary_expression::do_import(Import* imp)
4237 Operator op;
4238 switch (imp->get_char())
4240 case '+':
4241 op = OPERATOR_PLUS;
4242 break;
4243 case '-':
4244 op = OPERATOR_MINUS;
4245 break;
4246 case '!':
4247 op = OPERATOR_NOT;
4248 break;
4249 case '^':
4250 op = OPERATOR_XOR;
4251 break;
4252 default:
4253 go_unreachable();
4255 imp->require_c_string(" ");
4256 Expression* expr = Expression::import_expression(imp);
4257 return Expression::make_unary(op, expr, imp->location());
4260 // Dump ast representation of an unary expression.
4262 void
4263 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4265 ast_dump_context->dump_operator(this->op_);
4266 ast_dump_context->ostream() << "(";
4267 ast_dump_context->dump_expression(this->expr_);
4268 ast_dump_context->ostream() << ") ";
4271 // Make a unary expression.
4273 Expression*
4274 Expression::make_unary(Operator op, Expression* expr, Location location)
4276 return new Unary_expression(op, expr, location);
4279 // If this is an indirection through a pointer, return the expression
4280 // being pointed through. Otherwise return this.
4282 Expression*
4283 Expression::deref()
4285 if (this->classification_ == EXPRESSION_UNARY)
4287 Unary_expression* ue = static_cast<Unary_expression*>(this);
4288 if (ue->op() == OPERATOR_MULT)
4289 return ue->operand();
4291 return this;
4294 // Class Binary_expression.
4296 // Traversal.
4299 Binary_expression::do_traverse(Traverse* traverse)
4301 int t = Expression::traverse(&this->left_, traverse);
4302 if (t == TRAVERSE_EXIT)
4303 return TRAVERSE_EXIT;
4304 return Expression::traverse(&this->right_, traverse);
4307 // Return the type to use for a binary operation on operands of
4308 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4309 // such may be NULL or abstract.
4311 bool
4312 Binary_expression::operation_type(Operator op, Type* left_type,
4313 Type* right_type, Type** result_type)
4315 if (left_type != right_type
4316 && !left_type->is_abstract()
4317 && !right_type->is_abstract()
4318 && left_type->base() != right_type->base()
4319 && op != OPERATOR_LSHIFT
4320 && op != OPERATOR_RSHIFT)
4322 // May be a type error--let it be diagnosed elsewhere.
4323 return false;
4326 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4328 if (left_type->integer_type() != NULL)
4329 *result_type = left_type;
4330 else
4331 *result_type = Type::make_abstract_integer_type();
4333 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4334 *result_type = left_type;
4335 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4336 *result_type = right_type;
4337 else if (!left_type->is_abstract())
4338 *result_type = left_type;
4339 else if (!right_type->is_abstract())
4340 *result_type = right_type;
4341 else if (left_type->complex_type() != NULL)
4342 *result_type = left_type;
4343 else if (right_type->complex_type() != NULL)
4344 *result_type = right_type;
4345 else if (left_type->float_type() != NULL)
4346 *result_type = left_type;
4347 else if (right_type->float_type() != NULL)
4348 *result_type = right_type;
4349 else if (left_type->integer_type() != NULL
4350 && left_type->integer_type()->is_rune())
4351 *result_type = left_type;
4352 else if (right_type->integer_type() != NULL
4353 && right_type->integer_type()->is_rune())
4354 *result_type = right_type;
4355 else
4356 *result_type = left_type;
4358 return true;
4361 // Convert an integer comparison code and an operator to a boolean
4362 // value.
4364 bool
4365 Binary_expression::cmp_to_bool(Operator op, int cmp)
4367 switch (op)
4369 case OPERATOR_EQEQ:
4370 return cmp == 0;
4371 break;
4372 case OPERATOR_NOTEQ:
4373 return cmp != 0;
4374 break;
4375 case OPERATOR_LT:
4376 return cmp < 0;
4377 break;
4378 case OPERATOR_LE:
4379 return cmp <= 0;
4380 case OPERATOR_GT:
4381 return cmp > 0;
4382 case OPERATOR_GE:
4383 return cmp >= 0;
4384 default:
4385 go_unreachable();
4389 // Compare constants according to OP.
4391 bool
4392 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4393 Numeric_constant* right_nc,
4394 Location location, bool* result)
4396 Type* left_type = left_nc->type();
4397 Type* right_type = right_nc->type();
4399 Type* type;
4400 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4401 return false;
4403 // When comparing an untyped operand to a typed operand, we are
4404 // effectively coercing the untyped operand to the other operand's
4405 // type, so make sure that is valid.
4406 if (!left_nc->set_type(type, true, location)
4407 || !right_nc->set_type(type, true, location))
4408 return false;
4410 bool ret;
4411 int cmp;
4412 if (type->complex_type() != NULL)
4414 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4415 return false;
4416 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4418 else if (type->float_type() != NULL)
4419 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4420 else
4421 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4423 if (ret)
4424 *result = Binary_expression::cmp_to_bool(op, cmp);
4426 return ret;
4429 // Compare integer constants.
4431 bool
4432 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4433 const Numeric_constant* right_nc,
4434 int* cmp)
4436 mpz_t left_val;
4437 if (!left_nc->to_int(&left_val))
4438 return false;
4439 mpz_t right_val;
4440 if (!right_nc->to_int(&right_val))
4442 mpz_clear(left_val);
4443 return false;
4446 *cmp = mpz_cmp(left_val, right_val);
4448 mpz_clear(left_val);
4449 mpz_clear(right_val);
4451 return true;
4454 // Compare floating point constants.
4456 bool
4457 Binary_expression::compare_float(const Numeric_constant* left_nc,
4458 const Numeric_constant* right_nc,
4459 int* cmp)
4461 mpfr_t left_val;
4462 if (!left_nc->to_float(&left_val))
4463 return false;
4464 mpfr_t right_val;
4465 if (!right_nc->to_float(&right_val))
4467 mpfr_clear(left_val);
4468 return false;
4471 // We already coerced both operands to the same type. If that type
4472 // is not an abstract type, we need to round the values accordingly.
4473 Type* type = left_nc->type();
4474 if (!type->is_abstract() && type->float_type() != NULL)
4476 int bits = type->float_type()->bits();
4477 mpfr_prec_round(left_val, bits, GMP_RNDN);
4478 mpfr_prec_round(right_val, bits, GMP_RNDN);
4481 *cmp = mpfr_cmp(left_val, right_val);
4483 mpfr_clear(left_val);
4484 mpfr_clear(right_val);
4486 return true;
4489 // Compare complex constants. Complex numbers may only be compared
4490 // for equality.
4492 bool
4493 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4494 const Numeric_constant* right_nc,
4495 int* cmp)
4497 mpc_t left_val;
4498 if (!left_nc->to_complex(&left_val))
4499 return false;
4500 mpc_t right_val;
4501 if (!right_nc->to_complex(&right_val))
4503 mpc_clear(left_val);
4504 return false;
4507 // We already coerced both operands to the same type. If that type
4508 // is not an abstract type, we need to round the values accordingly.
4509 Type* type = left_nc->type();
4510 if (!type->is_abstract() && type->complex_type() != NULL)
4512 int bits = type->complex_type()->bits();
4513 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4514 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4515 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4516 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4519 *cmp = mpc_cmp(left_val, right_val) != 0;
4521 mpc_clear(left_val);
4522 mpc_clear(right_val);
4524 return true;
4527 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4528 // true if this could be done, false if not. Issue errors at LOCATION
4529 // as appropriate.
4531 bool
4532 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4533 Numeric_constant* right_nc,
4534 Location location, Numeric_constant* nc)
4536 switch (op)
4538 case OPERATOR_OROR:
4539 case OPERATOR_ANDAND:
4540 case OPERATOR_EQEQ:
4541 case OPERATOR_NOTEQ:
4542 case OPERATOR_LT:
4543 case OPERATOR_LE:
4544 case OPERATOR_GT:
4545 case OPERATOR_GE:
4546 // These return boolean values, not numeric.
4547 return false;
4548 default:
4549 break;
4552 Type* left_type = left_nc->type();
4553 Type* right_type = right_nc->type();
4555 Type* type;
4556 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4557 return false;
4559 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4561 // When combining an untyped operand with a typed operand, we are
4562 // effectively coercing the untyped operand to the other operand's
4563 // type, so make sure that is valid.
4564 if (!left_nc->set_type(type, true, location))
4565 return false;
4566 if (!is_shift && !right_nc->set_type(type, true, location))
4567 return false;
4569 bool r;
4570 if (type->complex_type() != NULL)
4571 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4572 else if (type->float_type() != NULL)
4573 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4574 else
4575 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4577 if (r)
4578 r = nc->set_type(type, true, location);
4580 return r;
4583 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4584 // integer operations. Return true if this could be done, false if
4585 // not.
4587 bool
4588 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4589 const Numeric_constant* right_nc,
4590 Location location, Numeric_constant* nc)
4592 mpz_t left_val;
4593 if (!left_nc->to_int(&left_val))
4594 return false;
4595 mpz_t right_val;
4596 if (!right_nc->to_int(&right_val))
4598 mpz_clear(left_val);
4599 return false;
4602 mpz_t val;
4603 mpz_init(val);
4605 switch (op)
4607 case OPERATOR_PLUS:
4608 mpz_add(val, left_val, right_val);
4609 if (mpz_sizeinbase(val, 2) > 0x100000)
4611 error_at(location, "constant addition overflow");
4612 mpz_set_ui(val, 1);
4614 break;
4615 case OPERATOR_MINUS:
4616 mpz_sub(val, left_val, right_val);
4617 if (mpz_sizeinbase(val, 2) > 0x100000)
4619 error_at(location, "constant subtraction overflow");
4620 mpz_set_ui(val, 1);
4622 break;
4623 case OPERATOR_OR:
4624 mpz_ior(val, left_val, right_val);
4625 break;
4626 case OPERATOR_XOR:
4627 mpz_xor(val, left_val, right_val);
4628 break;
4629 case OPERATOR_MULT:
4630 mpz_mul(val, left_val, right_val);
4631 if (mpz_sizeinbase(val, 2) > 0x100000)
4633 error_at(location, "constant multiplication overflow");
4634 mpz_set_ui(val, 1);
4636 break;
4637 case OPERATOR_DIV:
4638 if (mpz_sgn(right_val) != 0)
4639 mpz_tdiv_q(val, left_val, right_val);
4640 else
4642 error_at(location, "division by zero");
4643 mpz_set_ui(val, 0);
4645 break;
4646 case OPERATOR_MOD:
4647 if (mpz_sgn(right_val) != 0)
4648 mpz_tdiv_r(val, left_val, right_val);
4649 else
4651 error_at(location, "division by zero");
4652 mpz_set_ui(val, 0);
4654 break;
4655 case OPERATOR_LSHIFT:
4657 unsigned long shift = mpz_get_ui(right_val);
4658 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4659 mpz_mul_2exp(val, left_val, shift);
4660 else
4662 error_at(location, "shift count overflow");
4663 mpz_set_ui(val, 1);
4665 break;
4667 break;
4668 case OPERATOR_RSHIFT:
4670 unsigned long shift = mpz_get_ui(right_val);
4671 if (mpz_cmp_ui(right_val, shift) != 0)
4673 error_at(location, "shift count overflow");
4674 mpz_set_ui(val, 1);
4676 else
4678 if (mpz_cmp_ui(left_val, 0) >= 0)
4679 mpz_tdiv_q_2exp(val, left_val, shift);
4680 else
4681 mpz_fdiv_q_2exp(val, left_val, shift);
4683 break;
4685 break;
4686 case OPERATOR_AND:
4687 mpz_and(val, left_val, right_val);
4688 break;
4689 case OPERATOR_BITCLEAR:
4691 mpz_t tval;
4692 mpz_init(tval);
4693 mpz_com(tval, right_val);
4694 mpz_and(val, left_val, tval);
4695 mpz_clear(tval);
4697 break;
4698 default:
4699 go_unreachable();
4702 mpz_clear(left_val);
4703 mpz_clear(right_val);
4705 if (left_nc->is_rune()
4706 || (op != OPERATOR_LSHIFT
4707 && op != OPERATOR_RSHIFT
4708 && right_nc->is_rune()))
4709 nc->set_rune(NULL, val);
4710 else
4711 nc->set_int(NULL, val);
4713 mpz_clear(val);
4715 return true;
4718 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4719 // floating point operations. Return true if this could be done,
4720 // false if not.
4722 bool
4723 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4724 const Numeric_constant* right_nc,
4725 Location location, Numeric_constant* nc)
4727 mpfr_t left_val;
4728 if (!left_nc->to_float(&left_val))
4729 return false;
4730 mpfr_t right_val;
4731 if (!right_nc->to_float(&right_val))
4733 mpfr_clear(left_val);
4734 return false;
4737 mpfr_t val;
4738 mpfr_init(val);
4740 bool ret = true;
4741 switch (op)
4743 case OPERATOR_PLUS:
4744 mpfr_add(val, left_val, right_val, GMP_RNDN);
4745 break;
4746 case OPERATOR_MINUS:
4747 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4748 break;
4749 case OPERATOR_OR:
4750 case OPERATOR_XOR:
4751 case OPERATOR_AND:
4752 case OPERATOR_BITCLEAR:
4753 case OPERATOR_MOD:
4754 case OPERATOR_LSHIFT:
4755 case OPERATOR_RSHIFT:
4756 mpfr_set_ui(val, 0, GMP_RNDN);
4757 ret = false;
4758 break;
4759 case OPERATOR_MULT:
4760 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4761 break;
4762 case OPERATOR_DIV:
4763 if (!mpfr_zero_p(right_val))
4764 mpfr_div(val, left_val, right_val, GMP_RNDN);
4765 else
4767 error_at(location, "division by zero");
4768 mpfr_set_ui(val, 0, GMP_RNDN);
4770 break;
4771 default:
4772 go_unreachable();
4775 mpfr_clear(left_val);
4776 mpfr_clear(right_val);
4778 nc->set_float(NULL, val);
4779 mpfr_clear(val);
4781 return ret;
4784 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4785 // complex operations. Return true if this could be done, false if
4786 // not.
4788 bool
4789 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4790 const Numeric_constant* right_nc,
4791 Location location, Numeric_constant* nc)
4793 mpc_t left_val;
4794 if (!left_nc->to_complex(&left_val))
4795 return false;
4796 mpc_t right_val;
4797 if (!right_nc->to_complex(&right_val))
4799 mpc_clear(left_val);
4800 return false;
4803 mpc_t val;
4804 mpc_init2(val, mpc_precision);
4806 bool ret = true;
4807 switch (op)
4809 case OPERATOR_PLUS:
4810 mpc_add(val, left_val, right_val, MPC_RNDNN);
4811 break;
4812 case OPERATOR_MINUS:
4813 mpc_sub(val, left_val, right_val, MPC_RNDNN);
4814 break;
4815 case OPERATOR_OR:
4816 case OPERATOR_XOR:
4817 case OPERATOR_AND:
4818 case OPERATOR_BITCLEAR:
4819 case OPERATOR_MOD:
4820 case OPERATOR_LSHIFT:
4821 case OPERATOR_RSHIFT:
4822 mpc_set_ui(val, 0, MPC_RNDNN);
4823 ret = false;
4824 break;
4825 case OPERATOR_MULT:
4826 mpc_mul(val, left_val, right_val, MPC_RNDNN);
4827 break;
4828 case OPERATOR_DIV:
4829 if (mpc_cmp_si(right_val, 0) == 0)
4831 error_at(location, "division by zero");
4832 mpc_set_ui(val, 0, MPC_RNDNN);
4833 break;
4835 mpc_div(val, left_val, right_val, MPC_RNDNN);
4836 break;
4837 default:
4838 go_unreachable();
4841 mpc_clear(left_val);
4842 mpc_clear(right_val);
4844 nc->set_complex(NULL, val);
4845 mpc_clear(val);
4847 return ret;
4850 // Lower a binary expression. We have to evaluate constant
4851 // expressions now, in order to implement Go's unlimited precision
4852 // constants.
4854 Expression*
4855 Binary_expression::do_lower(Gogo* gogo, Named_object*,
4856 Statement_inserter* inserter, int)
4858 Location location = this->location();
4859 Operator op = this->op_;
4860 Expression* left = this->left_;
4861 Expression* right = this->right_;
4863 const bool is_comparison = (op == OPERATOR_EQEQ
4864 || op == OPERATOR_NOTEQ
4865 || op == OPERATOR_LT
4866 || op == OPERATOR_LE
4867 || op == OPERATOR_GT
4868 || op == OPERATOR_GE);
4870 // Numeric constant expressions.
4872 Numeric_constant left_nc;
4873 Numeric_constant right_nc;
4874 if (left->numeric_constant_value(&left_nc)
4875 && right->numeric_constant_value(&right_nc))
4877 if (is_comparison)
4879 bool result;
4880 if (!Binary_expression::compare_constant(op, &left_nc,
4881 &right_nc, location,
4882 &result))
4883 return this;
4884 return Expression::make_cast(Type::make_boolean_type(),
4885 Expression::make_boolean(result,
4886 location),
4887 location);
4889 else
4891 Numeric_constant nc;
4892 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
4893 location, &nc))
4894 return this;
4895 return nc.expression(location);
4900 // String constant expressions.
4901 if (left->type()->is_string_type() && right->type()->is_string_type())
4903 std::string left_string;
4904 std::string right_string;
4905 if (left->string_constant_value(&left_string)
4906 && right->string_constant_value(&right_string))
4908 if (op == OPERATOR_PLUS)
4909 return Expression::make_string(left_string + right_string,
4910 location);
4911 else if (is_comparison)
4913 int cmp = left_string.compare(right_string);
4914 bool r = Binary_expression::cmp_to_bool(op, cmp);
4915 return Expression::make_boolean(r, location);
4920 // Lower struct, array, and some interface comparisons.
4921 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
4923 if (left->type()->struct_type() != NULL
4924 && right->type()->struct_type() != NULL)
4925 return this->lower_struct_comparison(gogo, inserter);
4926 else if (left->type()->array_type() != NULL
4927 && !left->type()->is_slice_type()
4928 && right->type()->array_type() != NULL
4929 && !right->type()->is_slice_type())
4930 return this->lower_array_comparison(gogo, inserter);
4931 else if ((left->type()->interface_type() != NULL
4932 && right->type()->interface_type() == NULL)
4933 || (left->type()->interface_type() == NULL
4934 && right->type()->interface_type() != NULL))
4935 return this->lower_interface_value_comparison(gogo, inserter);
4938 return this;
4941 // Lower a struct comparison.
4943 Expression*
4944 Binary_expression::lower_struct_comparison(Gogo* gogo,
4945 Statement_inserter* inserter)
4947 Struct_type* st = this->left_->type()->struct_type();
4948 Struct_type* st2 = this->right_->type()->struct_type();
4949 if (st2 == NULL)
4950 return this;
4951 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
4952 return this;
4953 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4954 this->right_->type(), NULL))
4955 return this;
4957 // See if we can compare using memcmp. As a heuristic, we use
4958 // memcmp rather than field references and comparisons if there are
4959 // more than two fields.
4960 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
4961 return this->lower_compare_to_memcmp(gogo, inserter);
4963 Location loc = this->location();
4965 Expression* left = this->left_;
4966 Temporary_statement* left_temp = NULL;
4967 if (left->var_expression() == NULL
4968 && left->temporary_reference_expression() == NULL)
4970 left_temp = Statement::make_temporary(left->type(), NULL, loc);
4971 inserter->insert(left_temp);
4972 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
4975 Expression* right = this->right_;
4976 Temporary_statement* right_temp = NULL;
4977 if (right->var_expression() == NULL
4978 && right->temporary_reference_expression() == NULL)
4980 right_temp = Statement::make_temporary(right->type(), NULL, loc);
4981 inserter->insert(right_temp);
4982 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
4985 Expression* ret = Expression::make_boolean(true, loc);
4986 const Struct_field_list* fields = st->fields();
4987 unsigned int field_index = 0;
4988 for (Struct_field_list::const_iterator pf = fields->begin();
4989 pf != fields->end();
4990 ++pf, ++field_index)
4992 if (Gogo::is_sink_name(pf->field_name()))
4993 continue;
4995 if (field_index > 0)
4997 if (left_temp == NULL)
4998 left = left->copy();
4999 else
5000 left = Expression::make_temporary_reference(left_temp, loc);
5001 if (right_temp == NULL)
5002 right = right->copy();
5003 else
5004 right = Expression::make_temporary_reference(right_temp, loc);
5006 Expression* f1 = Expression::make_field_reference(left, field_index,
5007 loc);
5008 Expression* f2 = Expression::make_field_reference(right, field_index,
5009 loc);
5010 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5011 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5014 if (this->op_ == OPERATOR_NOTEQ)
5015 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5017 return ret;
5020 // Lower an array comparison.
5022 Expression*
5023 Binary_expression::lower_array_comparison(Gogo* gogo,
5024 Statement_inserter* inserter)
5026 Array_type* at = this->left_->type()->array_type();
5027 Array_type* at2 = this->right_->type()->array_type();
5028 if (at2 == NULL)
5029 return this;
5030 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5031 return this;
5032 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5033 this->right_->type(), NULL))
5034 return this;
5036 // Call memcmp directly if possible. This may let the middle-end
5037 // optimize the call.
5038 if (at->compare_is_identity(gogo))
5039 return this->lower_compare_to_memcmp(gogo, inserter);
5041 // Call the array comparison function.
5042 Named_object* hash_fn;
5043 Named_object* equal_fn;
5044 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5045 &hash_fn, &equal_fn);
5047 Location loc = this->location();
5049 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5051 Expression_list* args = new Expression_list();
5052 args->push_back(this->operand_address(inserter, this->left_));
5053 args->push_back(this->operand_address(inserter, this->right_));
5054 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5056 Expression* ret = Expression::make_call(func, args, false, loc);
5058 if (this->op_ == OPERATOR_NOTEQ)
5059 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5061 return ret;
5064 // Lower an interface to value comparison.
5066 Expression*
5067 Binary_expression::lower_interface_value_comparison(Gogo*,
5068 Statement_inserter* inserter)
5070 Type* left_type = this->left_->type();
5071 Type* right_type = this->right_->type();
5072 Interface_type* ift;
5073 if (left_type->interface_type() != NULL)
5075 ift = left_type->interface_type();
5076 if (!ift->implements_interface(right_type, NULL))
5077 return this;
5079 else
5081 ift = right_type->interface_type();
5082 if (!ift->implements_interface(left_type, NULL))
5083 return this;
5085 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5086 return this;
5088 Location loc = this->location();
5090 if (left_type->interface_type() == NULL
5091 && left_type->points_to() == NULL
5092 && !this->left_->is_addressable())
5094 Temporary_statement* temp =
5095 Statement::make_temporary(left_type, NULL, loc);
5096 inserter->insert(temp);
5097 this->left_ =
5098 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5101 if (right_type->interface_type() == NULL
5102 && right_type->points_to() == NULL
5103 && !this->right_->is_addressable())
5105 Temporary_statement* temp =
5106 Statement::make_temporary(right_type, NULL, loc);
5107 inserter->insert(temp);
5108 this->right_ =
5109 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5112 return this;
5115 // Lower a struct or array comparison to a call to memcmp.
5117 Expression*
5118 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5120 Location loc = this->location();
5122 Expression* a1 = this->operand_address(inserter, this->left_);
5123 Expression* a2 = this->operand_address(inserter, this->right_);
5124 Expression* len = Expression::make_type_info(this->left_->type(),
5125 TYPE_INFO_SIZE);
5127 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5128 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5129 return Expression::make_binary(this->op_, call, zero, loc);
5132 Expression*
5133 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5134 Statement_inserter* inserter)
5136 Location loc = this->location();
5137 Temporary_statement* temp;
5138 if (this->left_->type()->is_string_type()
5139 && this->op_ == OPERATOR_PLUS)
5141 if (!this->left_->is_variable())
5143 temp = Statement::make_temporary(NULL, this->left_, loc);
5144 inserter->insert(temp);
5145 this->left_ = Expression::make_temporary_reference(temp, loc);
5147 if (!this->right_->is_variable())
5149 temp =
5150 Statement::make_temporary(this->left_->type(), this->right_, loc);
5151 this->right_ = Expression::make_temporary_reference(temp, loc);
5152 inserter->insert(temp);
5156 Type* left_type = this->left_->type();
5157 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5158 || this->op_ == OPERATOR_RSHIFT);
5159 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5160 left_type->integer_type() != NULL)
5161 || this->op_ == OPERATOR_MOD);
5163 if (is_shift_op
5164 || (is_idiv_op
5165 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5167 if (!this->left_->is_variable())
5169 temp = Statement::make_temporary(NULL, this->left_, loc);
5170 inserter->insert(temp);
5171 this->left_ = Expression::make_temporary_reference(temp, loc);
5173 if (!this->right_->is_variable())
5175 temp =
5176 Statement::make_temporary(NULL, this->right_, loc);
5177 this->right_ = Expression::make_temporary_reference(temp, loc);
5178 inserter->insert(temp);
5181 return this;
5185 // Return the address of EXPR, cast to unsafe.Pointer.
5187 Expression*
5188 Binary_expression::operand_address(Statement_inserter* inserter,
5189 Expression* expr)
5191 Location loc = this->location();
5193 if (!expr->is_addressable())
5195 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5196 loc);
5197 inserter->insert(temp);
5198 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5200 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5201 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5202 Type* void_type = Type::make_void_type();
5203 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5204 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5207 // Return the numeric constant value, if it has one.
5209 bool
5210 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5212 Numeric_constant left_nc;
5213 if (!this->left_->numeric_constant_value(&left_nc))
5214 return false;
5215 Numeric_constant right_nc;
5216 if (!this->right_->numeric_constant_value(&right_nc))
5217 return false;
5218 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5219 this->location(), nc);
5222 // Note that the value is being discarded.
5224 bool
5225 Binary_expression::do_discarding_value()
5227 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5228 return this->right_->discarding_value();
5229 else
5231 this->unused_value_error();
5232 return false;
5236 // Get type.
5238 Type*
5239 Binary_expression::do_type()
5241 if (this->classification() == EXPRESSION_ERROR)
5242 return Type::make_error_type();
5244 switch (this->op_)
5246 case OPERATOR_EQEQ:
5247 case OPERATOR_NOTEQ:
5248 case OPERATOR_LT:
5249 case OPERATOR_LE:
5250 case OPERATOR_GT:
5251 case OPERATOR_GE:
5252 if (this->type_ == NULL)
5253 this->type_ = Type::make_boolean_type();
5254 return this->type_;
5256 case OPERATOR_PLUS:
5257 case OPERATOR_MINUS:
5258 case OPERATOR_OR:
5259 case OPERATOR_XOR:
5260 case OPERATOR_MULT:
5261 case OPERATOR_DIV:
5262 case OPERATOR_MOD:
5263 case OPERATOR_AND:
5264 case OPERATOR_BITCLEAR:
5265 case OPERATOR_OROR:
5266 case OPERATOR_ANDAND:
5268 Type* type;
5269 if (!Binary_expression::operation_type(this->op_,
5270 this->left_->type(),
5271 this->right_->type(),
5272 &type))
5273 return Type::make_error_type();
5274 return type;
5277 case OPERATOR_LSHIFT:
5278 case OPERATOR_RSHIFT:
5279 return this->left_->type();
5281 default:
5282 go_unreachable();
5286 // Set type for a binary expression.
5288 void
5289 Binary_expression::do_determine_type(const Type_context* context)
5291 Type* tleft = this->left_->type();
5292 Type* tright = this->right_->type();
5294 // Both sides should have the same type, except for the shift
5295 // operations. For a comparison, we should ignore the incoming
5296 // type.
5298 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5299 || this->op_ == OPERATOR_RSHIFT);
5301 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5302 || this->op_ == OPERATOR_NOTEQ
5303 || this->op_ == OPERATOR_LT
5304 || this->op_ == OPERATOR_LE
5305 || this->op_ == OPERATOR_GT
5306 || this->op_ == OPERATOR_GE);
5308 Type_context subcontext(*context);
5310 if (is_comparison)
5312 // In a comparison, the context does not determine the types of
5313 // the operands.
5314 subcontext.type = NULL;
5317 // Set the context for the left hand operand.
5318 if (is_shift_op)
5320 // The right hand operand of a shift plays no role in
5321 // determining the type of the left hand operand.
5323 else if (!tleft->is_abstract())
5324 subcontext.type = tleft;
5325 else if (!tright->is_abstract())
5326 subcontext.type = tright;
5327 else if (subcontext.type == NULL)
5329 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5330 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5331 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5333 // Both sides have an abstract integer, abstract float, or
5334 // abstract complex type. Just let CONTEXT determine
5335 // whether they may remain abstract or not.
5337 else if (tleft->complex_type() != NULL)
5338 subcontext.type = tleft;
5339 else if (tright->complex_type() != NULL)
5340 subcontext.type = tright;
5341 else if (tleft->float_type() != NULL)
5342 subcontext.type = tleft;
5343 else if (tright->float_type() != NULL)
5344 subcontext.type = tright;
5345 else
5346 subcontext.type = tleft;
5348 if (subcontext.type != NULL && !context->may_be_abstract)
5349 subcontext.type = subcontext.type->make_non_abstract_type();
5352 this->left_->determine_type(&subcontext);
5354 if (is_shift_op)
5356 // We may have inherited an unusable type for the shift operand.
5357 // Give a useful error if that happened.
5358 if (tleft->is_abstract()
5359 && subcontext.type != NULL
5360 && !subcontext.may_be_abstract
5361 && subcontext.type->interface_type() == NULL
5362 && subcontext.type->integer_type() == NULL)
5363 this->report_error(("invalid context-determined non-integer type "
5364 "for left operand of shift"));
5366 // The context for the right hand operand is the same as for the
5367 // left hand operand, except for a shift operator.
5368 subcontext.type = Type::lookup_integer_type("uint");
5369 subcontext.may_be_abstract = false;
5372 this->right_->determine_type(&subcontext);
5374 if (is_comparison)
5376 if (this->type_ != NULL && !this->type_->is_abstract())
5378 else if (context->type != NULL && context->type->is_boolean_type())
5379 this->type_ = context->type;
5380 else if (!context->may_be_abstract)
5381 this->type_ = Type::lookup_bool_type();
5385 // Report an error if the binary operator OP does not support TYPE.
5386 // OTYPE is the type of the other operand. Return whether the
5387 // operation is OK. This should not be used for shift.
5389 bool
5390 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5391 Location location)
5393 switch (op)
5395 case OPERATOR_OROR:
5396 case OPERATOR_ANDAND:
5397 if (!type->is_boolean_type())
5399 error_at(location, "expected boolean type");
5400 return false;
5402 break;
5404 case OPERATOR_EQEQ:
5405 case OPERATOR_NOTEQ:
5407 std::string reason;
5408 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5410 error_at(location, "%s", reason.c_str());
5411 return false;
5414 break;
5416 case OPERATOR_LT:
5417 case OPERATOR_LE:
5418 case OPERATOR_GT:
5419 case OPERATOR_GE:
5421 std::string reason;
5422 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5424 error_at(location, "%s", reason.c_str());
5425 return false;
5428 break;
5430 case OPERATOR_PLUS:
5431 case OPERATOR_PLUSEQ:
5432 if (type->integer_type() == NULL
5433 && type->float_type() == NULL
5434 && type->complex_type() == NULL
5435 && !type->is_string_type())
5437 error_at(location,
5438 "expected integer, floating, complex, or string type");
5439 return false;
5441 break;
5443 case OPERATOR_MINUS:
5444 case OPERATOR_MINUSEQ:
5445 case OPERATOR_MULT:
5446 case OPERATOR_MULTEQ:
5447 case OPERATOR_DIV:
5448 case OPERATOR_DIVEQ:
5449 if (type->integer_type() == NULL
5450 && type->float_type() == NULL
5451 && type->complex_type() == NULL)
5453 error_at(location, "expected integer, floating, or complex type");
5454 return false;
5456 break;
5458 case OPERATOR_MOD:
5459 case OPERATOR_MODEQ:
5460 case OPERATOR_OR:
5461 case OPERATOR_OREQ:
5462 case OPERATOR_AND:
5463 case OPERATOR_ANDEQ:
5464 case OPERATOR_XOR:
5465 case OPERATOR_XOREQ:
5466 case OPERATOR_BITCLEAR:
5467 case OPERATOR_BITCLEAREQ:
5468 if (type->integer_type() == NULL)
5470 error_at(location, "expected integer type");
5471 return false;
5473 break;
5475 default:
5476 go_unreachable();
5479 return true;
5482 // Check types.
5484 void
5485 Binary_expression::do_check_types(Gogo*)
5487 if (this->classification() == EXPRESSION_ERROR)
5488 return;
5490 Type* left_type = this->left_->type();
5491 Type* right_type = this->right_->type();
5492 if (left_type->is_error() || right_type->is_error())
5494 this->set_is_error();
5495 return;
5498 if (this->op_ == OPERATOR_EQEQ
5499 || this->op_ == OPERATOR_NOTEQ
5500 || this->op_ == OPERATOR_LT
5501 || this->op_ == OPERATOR_LE
5502 || this->op_ == OPERATOR_GT
5503 || this->op_ == OPERATOR_GE)
5505 if (left_type->is_nil_type() && right_type->is_nil_type())
5507 this->report_error(_("invalid comparison of nil with nil"));
5508 return;
5510 if (!Type::are_assignable(left_type, right_type, NULL)
5511 && !Type::are_assignable(right_type, left_type, NULL))
5513 this->report_error(_("incompatible types in binary expression"));
5514 return;
5516 if (!Binary_expression::check_operator_type(this->op_, left_type,
5517 right_type,
5518 this->location())
5519 || !Binary_expression::check_operator_type(this->op_, right_type,
5520 left_type,
5521 this->location()))
5523 this->set_is_error();
5524 return;
5527 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5529 if (!Type::are_compatible_for_binop(left_type, right_type))
5531 this->report_error(_("incompatible types in binary expression"));
5532 return;
5534 if (!Binary_expression::check_operator_type(this->op_, left_type,
5535 right_type,
5536 this->location()))
5538 this->set_is_error();
5539 return;
5541 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5543 // Division by a zero integer constant is an error.
5544 Numeric_constant rconst;
5545 unsigned long rval;
5546 if (left_type->integer_type() != NULL
5547 && this->right_->numeric_constant_value(&rconst)
5548 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5549 && rval == 0)
5551 this->report_error(_("integer division by zero"));
5552 return;
5556 else
5558 if (left_type->integer_type() == NULL)
5559 this->report_error(_("shift of non-integer operand"));
5561 if (!right_type->is_abstract()
5562 && (right_type->integer_type() == NULL
5563 || !right_type->integer_type()->is_unsigned()))
5564 this->report_error(_("shift count not unsigned integer"));
5565 else
5567 Numeric_constant nc;
5568 if (this->right_->numeric_constant_value(&nc))
5570 mpz_t val;
5571 if (!nc.to_int(&val))
5572 this->report_error(_("shift count not unsigned integer"));
5573 else
5575 if (mpz_sgn(val) < 0)
5577 this->report_error(_("negative shift count"));
5578 Location rloc = this->right_->location();
5579 this->right_ = Expression::make_integer_ul(0, right_type,
5580 rloc);
5582 mpz_clear(val);
5589 // Get the backend representation for a binary expression.
5591 Bexpression*
5592 Binary_expression::do_get_backend(Translate_context* context)
5594 Gogo* gogo = context->gogo();
5595 Location loc = this->location();
5596 Type* left_type = this->left_->type();
5597 Type* right_type = this->right_->type();
5599 bool use_left_type = true;
5600 bool is_shift_op = false;
5601 bool is_idiv_op = false;
5602 switch (this->op_)
5604 case OPERATOR_EQEQ:
5605 case OPERATOR_NOTEQ:
5606 case OPERATOR_LT:
5607 case OPERATOR_LE:
5608 case OPERATOR_GT:
5609 case OPERATOR_GE:
5610 return Expression::comparison(context, this->type_, this->op_,
5611 this->left_, this->right_, loc);
5613 case OPERATOR_OROR:
5614 case OPERATOR_ANDAND:
5615 use_left_type = false;
5616 break;
5617 case OPERATOR_PLUS:
5618 case OPERATOR_MINUS:
5619 case OPERATOR_OR:
5620 case OPERATOR_XOR:
5621 case OPERATOR_MULT:
5622 break;
5623 case OPERATOR_DIV:
5624 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5625 break;
5626 case OPERATOR_MOD:
5627 is_idiv_op = true;
5628 break;
5629 case OPERATOR_LSHIFT:
5630 case OPERATOR_RSHIFT:
5631 is_shift_op = true;
5632 break;
5633 case OPERATOR_BITCLEAR:
5634 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5635 case OPERATOR_AND:
5636 break;
5637 default:
5638 go_unreachable();
5641 if (left_type->is_string_type())
5643 go_assert(this->op_ == OPERATOR_PLUS);
5644 Expression* string_plus =
5645 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5646 this->left_, this->right_);
5647 return string_plus->get_backend(context);
5650 // For complex division Go might want slightly different results than the
5651 // backend implementation provides, so we have our own runtime routine.
5652 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5654 Runtime::Function complex_code;
5655 switch (this->left_->type()->complex_type()->bits())
5657 case 64:
5658 complex_code = Runtime::COMPLEX64_DIV;
5659 break;
5660 case 128:
5661 complex_code = Runtime::COMPLEX128_DIV;
5662 break;
5663 default:
5664 go_unreachable();
5666 Expression* complex_div =
5667 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5668 return complex_div->get_backend(context);
5671 Bexpression* left = this->left_->get_backend(context);
5672 Bexpression* right = this->right_->get_backend(context);
5674 Type* type = use_left_type ? left_type : right_type;
5675 Btype* btype = type->get_backend(gogo);
5677 Bexpression* ret =
5678 gogo->backend()->binary_expression(this->op_, left, right, loc);
5679 ret = gogo->backend()->convert_expression(btype, ret, loc);
5681 // Initialize overflow constants.
5682 Bexpression* overflow;
5683 mpz_t zero;
5684 mpz_init_set_ui(zero, 0UL);
5685 mpz_t one;
5686 mpz_init_set_ui(one, 1UL);
5687 mpz_t neg_one;
5688 mpz_init_set_si(neg_one, -1);
5690 Btype* left_btype = left_type->get_backend(gogo);
5691 Btype* right_btype = right_type->get_backend(gogo);
5693 // In Go, a shift larger than the size of the type is well-defined.
5694 // This is not true in C, so we need to insert a conditional.
5695 if (is_shift_op)
5697 go_assert(left_type->integer_type() != NULL);
5699 mpz_t bitsval;
5700 int bits = left_type->integer_type()->bits();
5701 mpz_init_set_ui(bitsval, bits);
5702 Bexpression* bits_expr =
5703 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5704 Bexpression* compare =
5705 gogo->backend()->binary_expression(OPERATOR_LT,
5706 right, bits_expr, loc);
5708 Bexpression* zero_expr =
5709 gogo->backend()->integer_constant_expression(left_btype, zero);
5710 overflow = zero_expr;
5711 if (this->op_ == OPERATOR_RSHIFT
5712 && !left_type->integer_type()->is_unsigned())
5714 Bexpression* neg_expr =
5715 gogo->backend()->binary_expression(OPERATOR_LT, left,
5716 zero_expr, loc);
5717 Bexpression* neg_one_expr =
5718 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5719 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5720 neg_one_expr,
5721 zero_expr, loc);
5723 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5724 overflow, loc);
5725 mpz_clear(bitsval);
5728 // Add checks for division by zero and division overflow as needed.
5729 if (is_idiv_op)
5731 if (gogo->check_divide_by_zero())
5733 // right == 0
5734 Bexpression* zero_expr =
5735 gogo->backend()->integer_constant_expression(right_btype, zero);
5736 Bexpression* check =
5737 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5738 right, zero_expr, loc);
5740 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
5741 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5742 Bexpression* crash = gogo->runtime_error(errcode,
5743 loc)->get_backend(context);
5745 // right == 0 ? (__go_runtime_error(...), 0) : ret
5746 ret = gogo->backend()->conditional_expression(btype, check, crash,
5747 ret, loc);
5750 if (gogo->check_divide_overflow())
5752 // right == -1
5753 // FIXME: It would be nice to say that this test is expected
5754 // to return false.
5756 Bexpression* neg_one_expr =
5757 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5758 Bexpression* check =
5759 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5760 right, neg_one_expr, loc);
5762 Bexpression* zero_expr =
5763 gogo->backend()->integer_constant_expression(btype, zero);
5764 Bexpression* one_expr =
5765 gogo->backend()->integer_constant_expression(btype, one);
5767 if (type->integer_type()->is_unsigned())
5769 // An unsigned -1 is the largest possible number, so
5770 // dividing is always 1 or 0.
5772 Bexpression* cmp =
5773 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5774 left, right, loc);
5775 if (this->op_ == OPERATOR_DIV)
5776 overflow =
5777 gogo->backend()->conditional_expression(btype, cmp,
5778 one_expr, zero_expr,
5779 loc);
5780 else
5781 overflow =
5782 gogo->backend()->conditional_expression(btype, cmp,
5783 zero_expr, left,
5784 loc);
5786 else
5788 // Computing left / -1 is the same as computing - left,
5789 // which does not overflow since Go sets -fwrapv.
5790 if (this->op_ == OPERATOR_DIV)
5792 Expression* negate_expr =
5793 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
5794 overflow = negate_expr->get_backend(context);
5796 else
5797 overflow = zero_expr;
5799 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
5801 // right == -1 ? - left : ret
5802 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5803 ret, loc);
5807 mpz_clear(zero);
5808 mpz_clear(one);
5809 mpz_clear(neg_one);
5810 return ret;
5813 // Export a binary expression.
5815 void
5816 Binary_expression::do_export(Export* exp) const
5818 exp->write_c_string("(");
5819 this->left_->export_expression(exp);
5820 switch (this->op_)
5822 case OPERATOR_OROR:
5823 exp->write_c_string(" || ");
5824 break;
5825 case OPERATOR_ANDAND:
5826 exp->write_c_string(" && ");
5827 break;
5828 case OPERATOR_EQEQ:
5829 exp->write_c_string(" == ");
5830 break;
5831 case OPERATOR_NOTEQ:
5832 exp->write_c_string(" != ");
5833 break;
5834 case OPERATOR_LT:
5835 exp->write_c_string(" < ");
5836 break;
5837 case OPERATOR_LE:
5838 exp->write_c_string(" <= ");
5839 break;
5840 case OPERATOR_GT:
5841 exp->write_c_string(" > ");
5842 break;
5843 case OPERATOR_GE:
5844 exp->write_c_string(" >= ");
5845 break;
5846 case OPERATOR_PLUS:
5847 exp->write_c_string(" + ");
5848 break;
5849 case OPERATOR_MINUS:
5850 exp->write_c_string(" - ");
5851 break;
5852 case OPERATOR_OR:
5853 exp->write_c_string(" | ");
5854 break;
5855 case OPERATOR_XOR:
5856 exp->write_c_string(" ^ ");
5857 break;
5858 case OPERATOR_MULT:
5859 exp->write_c_string(" * ");
5860 break;
5861 case OPERATOR_DIV:
5862 exp->write_c_string(" / ");
5863 break;
5864 case OPERATOR_MOD:
5865 exp->write_c_string(" % ");
5866 break;
5867 case OPERATOR_LSHIFT:
5868 exp->write_c_string(" << ");
5869 break;
5870 case OPERATOR_RSHIFT:
5871 exp->write_c_string(" >> ");
5872 break;
5873 case OPERATOR_AND:
5874 exp->write_c_string(" & ");
5875 break;
5876 case OPERATOR_BITCLEAR:
5877 exp->write_c_string(" &^ ");
5878 break;
5879 default:
5880 go_unreachable();
5882 this->right_->export_expression(exp);
5883 exp->write_c_string(")");
5886 // Import a binary expression.
5888 Expression*
5889 Binary_expression::do_import(Import* imp)
5891 imp->require_c_string("(");
5893 Expression* left = Expression::import_expression(imp);
5895 Operator op;
5896 if (imp->match_c_string(" || "))
5898 op = OPERATOR_OROR;
5899 imp->advance(4);
5901 else if (imp->match_c_string(" && "))
5903 op = OPERATOR_ANDAND;
5904 imp->advance(4);
5906 else if (imp->match_c_string(" == "))
5908 op = OPERATOR_EQEQ;
5909 imp->advance(4);
5911 else if (imp->match_c_string(" != "))
5913 op = OPERATOR_NOTEQ;
5914 imp->advance(4);
5916 else if (imp->match_c_string(" < "))
5918 op = OPERATOR_LT;
5919 imp->advance(3);
5921 else if (imp->match_c_string(" <= "))
5923 op = OPERATOR_LE;
5924 imp->advance(4);
5926 else if (imp->match_c_string(" > "))
5928 op = OPERATOR_GT;
5929 imp->advance(3);
5931 else if (imp->match_c_string(" >= "))
5933 op = OPERATOR_GE;
5934 imp->advance(4);
5936 else if (imp->match_c_string(" + "))
5938 op = OPERATOR_PLUS;
5939 imp->advance(3);
5941 else if (imp->match_c_string(" - "))
5943 op = OPERATOR_MINUS;
5944 imp->advance(3);
5946 else if (imp->match_c_string(" | "))
5948 op = OPERATOR_OR;
5949 imp->advance(3);
5951 else if (imp->match_c_string(" ^ "))
5953 op = OPERATOR_XOR;
5954 imp->advance(3);
5956 else if (imp->match_c_string(" * "))
5958 op = OPERATOR_MULT;
5959 imp->advance(3);
5961 else if (imp->match_c_string(" / "))
5963 op = OPERATOR_DIV;
5964 imp->advance(3);
5966 else if (imp->match_c_string(" % "))
5968 op = OPERATOR_MOD;
5969 imp->advance(3);
5971 else if (imp->match_c_string(" << "))
5973 op = OPERATOR_LSHIFT;
5974 imp->advance(4);
5976 else if (imp->match_c_string(" >> "))
5978 op = OPERATOR_RSHIFT;
5979 imp->advance(4);
5981 else if (imp->match_c_string(" & "))
5983 op = OPERATOR_AND;
5984 imp->advance(3);
5986 else if (imp->match_c_string(" &^ "))
5988 op = OPERATOR_BITCLEAR;
5989 imp->advance(4);
5991 else
5993 error_at(imp->location(), "unrecognized binary operator");
5994 return Expression::make_error(imp->location());
5997 Expression* right = Expression::import_expression(imp);
5999 imp->require_c_string(")");
6001 return Expression::make_binary(op, left, right, imp->location());
6004 // Dump ast representation of a binary expression.
6006 void
6007 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6009 ast_dump_context->ostream() << "(";
6010 ast_dump_context->dump_expression(this->left_);
6011 ast_dump_context->ostream() << " ";
6012 ast_dump_context->dump_operator(this->op_);
6013 ast_dump_context->ostream() << " ";
6014 ast_dump_context->dump_expression(this->right_);
6015 ast_dump_context->ostream() << ") ";
6018 // Make a binary expression.
6020 Expression*
6021 Expression::make_binary(Operator op, Expression* left, Expression* right,
6022 Location location)
6024 return new Binary_expression(op, left, right, location);
6027 // Implement a comparison.
6029 Bexpression*
6030 Expression::comparison(Translate_context* context, Type* result_type,
6031 Operator op, Expression* left, Expression* right,
6032 Location location)
6034 Type* left_type = left->type();
6035 Type* right_type = right->type();
6037 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6039 if (left_type->is_string_type() && right_type->is_string_type())
6041 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6042 left, right);
6043 right = zexpr;
6045 else if ((left_type->interface_type() != NULL
6046 && right_type->interface_type() == NULL
6047 && !right_type->is_nil_type())
6048 || (left_type->interface_type() == NULL
6049 && !left_type->is_nil_type()
6050 && right_type->interface_type() != NULL))
6052 // Comparing an interface value to a non-interface value.
6053 if (left_type->interface_type() == NULL)
6055 std::swap(left_type, right_type);
6056 std::swap(left, right);
6059 // The right operand is not an interface. We need to take its
6060 // address if it is not a pointer.
6061 Expression* pointer_arg = NULL;
6062 if (right_type->points_to() != NULL)
6063 pointer_arg = right;
6064 else
6066 go_assert(right->is_addressable());
6067 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6068 location);
6071 Expression* descriptor =
6072 Expression::make_type_descriptor(right_type, location);
6073 left =
6074 Runtime::make_call((left_type->interface_type()->is_empty()
6075 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6076 : Runtime::INTERFACE_VALUE_COMPARE),
6077 location, 3, left, descriptor,
6078 pointer_arg);
6079 right = zexpr;
6081 else if (left_type->interface_type() != NULL
6082 && right_type->interface_type() != NULL)
6084 Runtime::Function compare_function;
6085 if (left_type->interface_type()->is_empty()
6086 && right_type->interface_type()->is_empty())
6087 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6088 else if (!left_type->interface_type()->is_empty()
6089 && !right_type->interface_type()->is_empty())
6090 compare_function = Runtime::INTERFACE_COMPARE;
6091 else
6093 if (left_type->interface_type()->is_empty())
6095 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6096 std::swap(left_type, right_type);
6097 std::swap(left, right);
6099 go_assert(!left_type->interface_type()->is_empty());
6100 go_assert(right_type->interface_type()->is_empty());
6101 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6104 left = Runtime::make_call(compare_function, location, 2, left, right);
6105 right = zexpr;
6108 if (left_type->is_nil_type()
6109 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6111 std::swap(left_type, right_type);
6112 std::swap(left, right);
6115 if (right_type->is_nil_type())
6117 right = Expression::make_nil(location);
6118 if (left_type->array_type() != NULL
6119 && left_type->array_type()->length() == NULL)
6121 Array_type* at = left_type->array_type();
6122 left = at->get_value_pointer(context->gogo(), left);
6124 else if (left_type->interface_type() != NULL)
6126 // An interface is nil if the first field is nil.
6127 left = Expression::make_field_reference(left, 0, location);
6131 Bexpression* left_bexpr = left->get_backend(context);
6132 Bexpression* right_bexpr = right->get_backend(context);
6134 Gogo* gogo = context->gogo();
6135 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6136 right_bexpr, location);
6137 if (result_type != NULL)
6138 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6139 ret, location);
6140 return ret;
6143 // Class Bound_method_expression.
6145 // Traversal.
6148 Bound_method_expression::do_traverse(Traverse* traverse)
6150 return Expression::traverse(&this->expr_, traverse);
6153 // Lower the expression. If this is a method value rather than being
6154 // called, and the method is accessed via a pointer, we may need to
6155 // add nil checks. Introduce a temporary variable so that those nil
6156 // checks do not cause multiple evaluation.
6158 Expression*
6159 Bound_method_expression::do_lower(Gogo*, Named_object*,
6160 Statement_inserter* inserter, int)
6162 // For simplicity we use a temporary for every call to an embedded
6163 // method, even though some of them might be pure value methods and
6164 // not require a temporary.
6165 if (this->expr_->var_expression() == NULL
6166 && this->expr_->temporary_reference_expression() == NULL
6167 && this->expr_->set_and_use_temporary_expression() == NULL
6168 && (this->method_->field_indexes() != NULL
6169 || (this->method_->is_value_method()
6170 && this->expr_->type()->points_to() != NULL)))
6172 Temporary_statement* temp =
6173 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6174 inserter->insert(temp);
6175 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6176 this->location());
6178 return this;
6181 // Return the type of a bound method expression. The type of this
6182 // object is simply the type of the method with no receiver.
6184 Type*
6185 Bound_method_expression::do_type()
6187 Named_object* fn = this->method_->named_object();
6188 Function_type* fntype;
6189 if (fn->is_function())
6190 fntype = fn->func_value()->type();
6191 else if (fn->is_function_declaration())
6192 fntype = fn->func_declaration_value()->type();
6193 else
6194 return Type::make_error_type();
6195 return fntype->copy_without_receiver();
6198 // Determine the types of a method expression.
6200 void
6201 Bound_method_expression::do_determine_type(const Type_context*)
6203 Named_object* fn = this->method_->named_object();
6204 Function_type* fntype;
6205 if (fn->is_function())
6206 fntype = fn->func_value()->type();
6207 else if (fn->is_function_declaration())
6208 fntype = fn->func_declaration_value()->type();
6209 else
6210 fntype = NULL;
6211 if (fntype == NULL || !fntype->is_method())
6212 this->expr_->determine_type_no_context();
6213 else
6215 Type_context subcontext(fntype->receiver()->type(), false);
6216 this->expr_->determine_type(&subcontext);
6220 // Check the types of a method expression.
6222 void
6223 Bound_method_expression::do_check_types(Gogo*)
6225 Named_object* fn = this->method_->named_object();
6226 if (!fn->is_function() && !fn->is_function_declaration())
6228 this->report_error(_("object is not a method"));
6229 return;
6232 Function_type* fntype;
6233 if (fn->is_function())
6234 fntype = fn->func_value()->type();
6235 else if (fn->is_function_declaration())
6236 fntype = fn->func_declaration_value()->type();
6237 else
6238 go_unreachable();
6239 Type* rtype = fntype->receiver()->type()->deref();
6240 Type* etype = (this->expr_type_ != NULL
6241 ? this->expr_type_
6242 : this->expr_->type());
6243 etype = etype->deref();
6244 if (!Type::are_identical(rtype, etype, true, NULL))
6245 this->report_error(_("method type does not match object type"));
6248 // If a bound method expression is not simply called, then it is
6249 // represented as a closure. The closure will hold a single variable,
6250 // the receiver to pass to the method. The function will be a simple
6251 // thunk that pulls that value from the closure and calls the method
6252 // with the remaining arguments.
6254 // Because method values are not common, we don't build all thunks for
6255 // every methods, but instead only build them as we need them. In
6256 // particular, we even build them on demand for methods defined in
6257 // other packages.
6259 Bound_method_expression::Method_value_thunks
6260 Bound_method_expression::method_value_thunks;
6262 // Find or create the thunk for METHOD.
6264 Named_object*
6265 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6266 Named_object* fn)
6268 std::pair<Named_object*, Named_object*> val(fn, NULL);
6269 std::pair<Method_value_thunks::iterator, bool> ins =
6270 Bound_method_expression::method_value_thunks.insert(val);
6271 if (!ins.second)
6273 // We have seen this method before.
6274 go_assert(ins.first->second != NULL);
6275 return ins.first->second;
6278 Location loc = fn->location();
6280 Function_type* orig_fntype;
6281 if (fn->is_function())
6282 orig_fntype = fn->func_value()->type();
6283 else if (fn->is_function_declaration())
6284 orig_fntype = fn->func_declaration_value()->type();
6285 else
6286 orig_fntype = NULL;
6288 if (orig_fntype == NULL || !orig_fntype->is_method())
6290 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6291 return ins.first->second;
6294 Struct_field_list* sfl = new Struct_field_list();
6295 // The type here is wrong--it should be the C function type. But it
6296 // doesn't really matter.
6297 Type* vt = Type::make_pointer_type(Type::make_void_type());
6298 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6299 sfl->push_back(Struct_field(Typed_identifier("val.1",
6300 orig_fntype->receiver()->type(),
6301 loc)));
6302 Type* closure_type = Type::make_struct_type(sfl, loc);
6303 closure_type = Type::make_pointer_type(closure_type);
6305 Function_type* new_fntype = orig_fntype->copy_with_names();
6307 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6308 false, loc);
6310 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6311 cvar->set_is_used();
6312 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6313 new_no->func_value()->set_closure_var(cp);
6315 gogo->start_block(loc);
6317 // Field 0 of the closure is the function code pointer, field 1 is
6318 // the value on which to invoke the method.
6319 Expression* arg = Expression::make_var_reference(cp, loc);
6320 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6321 arg = Expression::make_field_reference(arg, 1, loc);
6323 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6325 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6326 Expression_list* args;
6327 if (orig_params == NULL || orig_params->empty())
6328 args = NULL;
6329 else
6331 const Typed_identifier_list* new_params = new_fntype->parameters();
6332 args = new Expression_list();
6333 for (Typed_identifier_list::const_iterator p = new_params->begin();
6334 p != new_params->end();
6335 ++p)
6337 Named_object* p_no = gogo->lookup(p->name(), NULL);
6338 go_assert(p_no != NULL
6339 && p_no->is_variable()
6340 && p_no->var_value()->is_parameter());
6341 args->push_back(Expression::make_var_reference(p_no, loc));
6345 Call_expression* call = Expression::make_call(bme, args,
6346 orig_fntype->is_varargs(),
6347 loc);
6348 call->set_varargs_are_lowered();
6350 Statement* s = Statement::make_return_from_call(call, loc);
6351 gogo->add_statement(s);
6352 Block* b = gogo->finish_block(loc);
6353 gogo->add_block(b, loc);
6354 gogo->lower_block(new_no, b);
6355 gogo->flatten_block(new_no, b);
6356 gogo->finish_function(loc);
6358 ins.first->second = new_no;
6359 return new_no;
6362 // Return an expression to check *REF for nil while dereferencing
6363 // according to FIELD_INDEXES. Update *REF to build up the field
6364 // reference. This is a static function so that we don't have to
6365 // worry about declaring Field_indexes in expressions.h.
6367 static Expression*
6368 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6369 Expression** ref)
6371 if (field_indexes == NULL)
6372 return Expression::make_boolean(false, loc);
6373 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6374 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6375 go_assert(stype != NULL
6376 && field_indexes->field_index < stype->field_count());
6377 if ((*ref)->type()->struct_type() == NULL)
6379 go_assert((*ref)->type()->points_to() != NULL);
6380 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6381 Expression::make_nil(loc),
6382 loc);
6383 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6384 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6385 go_assert((*ref)->type()->struct_type() == stype);
6387 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6388 loc);
6389 return cond;
6392 // Get the backend representation for a method value.
6394 Bexpression*
6395 Bound_method_expression::do_get_backend(Translate_context* context)
6397 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6398 this->method_,
6399 this->function_);
6400 if (thunk->is_erroneous())
6402 go_assert(saw_errors());
6403 return context->backend()->error_expression();
6406 // FIXME: We should lower this earlier, but we can't lower it in the
6407 // lowering pass because at that point we don't know whether we need
6408 // to create the thunk or not. If the expression is called, we
6409 // don't need the thunk.
6411 Location loc = this->location();
6413 // If the method expects a value, and we have a pointer, we need to
6414 // dereference the pointer.
6416 Named_object* fn = this->method_->named_object();
6417 Function_type* fntype;
6418 if (fn->is_function())
6419 fntype = fn->func_value()->type();
6420 else if (fn->is_function_declaration())
6421 fntype = fn->func_declaration_value()->type();
6422 else
6423 go_unreachable();
6425 Expression* val = this->expr_;
6426 if (fntype->receiver()->type()->points_to() == NULL
6427 && val->type()->points_to() != NULL)
6428 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6430 // Note that we are ignoring this->expr_type_ here. The thunk will
6431 // expect a closure whose second field has type this->expr_type_ (if
6432 // that is not NULL). We are going to pass it a closure whose
6433 // second field has type this->expr_->type(). Since
6434 // this->expr_type_ is only not-NULL for pointer types, we can get
6435 // away with this.
6437 Struct_field_list* fields = new Struct_field_list();
6438 fields->push_back(Struct_field(Typed_identifier("fn.0",
6439 thunk->func_value()->type(),
6440 loc)));
6441 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6442 Struct_type* st = Type::make_struct_type(fields, loc);
6444 Expression_list* vals = new Expression_list();
6445 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6446 vals->push_back(val);
6448 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6449 ret = Expression::make_heap_expression(ret, loc);
6451 // See whether the expression or any embedded pointers are nil.
6453 Expression* nil_check = NULL;
6454 Expression* expr = this->expr_;
6455 if (this->method_->field_indexes() != NULL)
6457 // Note that we are evaluating this->expr_ twice, but that is OK
6458 // because in the lowering pass we forced it into a temporary
6459 // variable.
6460 Expression* ref = expr;
6461 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6462 expr = ref;
6465 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6467 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6468 Expression::make_nil(loc),
6469 loc);
6470 if (nil_check == NULL)
6471 nil_check = n;
6472 else
6473 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6476 Bexpression* bme = ret->get_backend(context);
6477 if (nil_check != NULL)
6479 Gogo* gogo = context->gogo();
6480 Bexpression* crash =
6481 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6482 loc)->get_backend(context);
6483 Btype* btype = ret->type()->get_backend(gogo);
6484 Bexpression* bcheck = nil_check->get_backend(context);
6485 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6486 bme, loc);
6488 return bme;
6491 // Dump ast representation of a bound method expression.
6493 void
6494 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6495 const
6497 if (this->expr_type_ != NULL)
6498 ast_dump_context->ostream() << "(";
6499 ast_dump_context->dump_expression(this->expr_);
6500 if (this->expr_type_ != NULL)
6502 ast_dump_context->ostream() << ":";
6503 ast_dump_context->dump_type(this->expr_type_);
6504 ast_dump_context->ostream() << ")";
6507 ast_dump_context->ostream() << "." << this->function_->name();
6510 // Make a method expression.
6512 Bound_method_expression*
6513 Expression::make_bound_method(Expression* expr, const Method* method,
6514 Named_object* function, Location location)
6516 return new Bound_method_expression(expr, method, function, location);
6519 // Class Builtin_call_expression. This is used for a call to a
6520 // builtin function.
6522 class Builtin_call_expression : public Call_expression
6524 public:
6525 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6526 bool is_varargs, Location location);
6528 protected:
6529 // This overrides Call_expression::do_lower.
6530 Expression*
6531 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6533 Expression*
6534 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6536 bool
6537 do_is_constant() const;
6539 bool
6540 do_numeric_constant_value(Numeric_constant*) const;
6542 bool
6543 do_discarding_value();
6545 Type*
6546 do_type();
6548 void
6549 do_determine_type(const Type_context*);
6551 void
6552 do_check_types(Gogo*);
6554 Expression*
6555 do_copy();
6557 Bexpression*
6558 do_get_backend(Translate_context*);
6560 void
6561 do_export(Export*) const;
6563 virtual bool
6564 do_is_recover_call() const;
6566 virtual void
6567 do_set_recover_arg(Expression*);
6569 private:
6570 // The builtin functions.
6571 enum Builtin_function_code
6573 BUILTIN_INVALID,
6575 // Predeclared builtin functions.
6576 BUILTIN_APPEND,
6577 BUILTIN_CAP,
6578 BUILTIN_CLOSE,
6579 BUILTIN_COMPLEX,
6580 BUILTIN_COPY,
6581 BUILTIN_DELETE,
6582 BUILTIN_IMAG,
6583 BUILTIN_LEN,
6584 BUILTIN_MAKE,
6585 BUILTIN_NEW,
6586 BUILTIN_PANIC,
6587 BUILTIN_PRINT,
6588 BUILTIN_PRINTLN,
6589 BUILTIN_REAL,
6590 BUILTIN_RECOVER,
6592 // Builtin functions from the unsafe package.
6593 BUILTIN_ALIGNOF,
6594 BUILTIN_OFFSETOF,
6595 BUILTIN_SIZEOF
6598 Expression*
6599 one_arg() const;
6601 bool
6602 check_one_arg();
6604 static Type*
6605 real_imag_type(Type*);
6607 static Type*
6608 complex_type(Type*);
6610 Expression*
6611 lower_make();
6613 bool
6614 check_int_value(Expression*, bool is_length);
6616 // A pointer back to the general IR structure. This avoids a global
6617 // variable, or passing it around everywhere.
6618 Gogo* gogo_;
6619 // The builtin function being called.
6620 Builtin_function_code code_;
6621 // Used to stop endless loops when the length of an array uses len
6622 // or cap of the array itself.
6623 mutable bool seen_;
6624 // Whether the argument is set for calls to BUILTIN_RECOVER.
6625 bool recover_arg_is_set_;
6628 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6629 Expression* fn,
6630 Expression_list* args,
6631 bool is_varargs,
6632 Location location)
6633 : Call_expression(fn, args, is_varargs, location),
6634 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6635 recover_arg_is_set_(false)
6637 Func_expression* fnexp = this->fn()->func_expression();
6638 go_assert(fnexp != NULL);
6639 const std::string& name(fnexp->named_object()->name());
6640 if (name == "append")
6641 this->code_ = BUILTIN_APPEND;
6642 else if (name == "cap")
6643 this->code_ = BUILTIN_CAP;
6644 else if (name == "close")
6645 this->code_ = BUILTIN_CLOSE;
6646 else if (name == "complex")
6647 this->code_ = BUILTIN_COMPLEX;
6648 else if (name == "copy")
6649 this->code_ = BUILTIN_COPY;
6650 else if (name == "delete")
6651 this->code_ = BUILTIN_DELETE;
6652 else if (name == "imag")
6653 this->code_ = BUILTIN_IMAG;
6654 else if (name == "len")
6655 this->code_ = BUILTIN_LEN;
6656 else if (name == "make")
6657 this->code_ = BUILTIN_MAKE;
6658 else if (name == "new")
6659 this->code_ = BUILTIN_NEW;
6660 else if (name == "panic")
6661 this->code_ = BUILTIN_PANIC;
6662 else if (name == "print")
6663 this->code_ = BUILTIN_PRINT;
6664 else if (name == "println")
6665 this->code_ = BUILTIN_PRINTLN;
6666 else if (name == "real")
6667 this->code_ = BUILTIN_REAL;
6668 else if (name == "recover")
6669 this->code_ = BUILTIN_RECOVER;
6670 else if (name == "Alignof")
6671 this->code_ = BUILTIN_ALIGNOF;
6672 else if (name == "Offsetof")
6673 this->code_ = BUILTIN_OFFSETOF;
6674 else if (name == "Sizeof")
6675 this->code_ = BUILTIN_SIZEOF;
6676 else
6677 go_unreachable();
6680 // Return whether this is a call to recover. This is a virtual
6681 // function called from the parent class.
6683 bool
6684 Builtin_call_expression::do_is_recover_call() const
6686 if (this->classification() == EXPRESSION_ERROR)
6687 return false;
6688 return this->code_ == BUILTIN_RECOVER;
6691 // Set the argument for a call to recover.
6693 void
6694 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6696 const Expression_list* args = this->args();
6697 go_assert(args == NULL || args->empty());
6698 Expression_list* new_args = new Expression_list();
6699 new_args->push_back(arg);
6700 this->set_args(new_args);
6701 this->recover_arg_is_set_ = true;
6704 // Lower a builtin call expression. This turns new and make into
6705 // specific expressions. We also convert to a constant if we can.
6707 Expression*
6708 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6709 Statement_inserter* inserter, int)
6711 if (this->classification() == EXPRESSION_ERROR)
6712 return this;
6714 Location loc = this->location();
6716 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6718 this->report_error(_("invalid use of %<...%> with builtin function"));
6719 return Expression::make_error(loc);
6722 if (this->code_ == BUILTIN_OFFSETOF)
6724 Expression* arg = this->one_arg();
6726 if (arg->bound_method_expression() != NULL
6727 || arg->interface_field_reference_expression() != NULL)
6729 this->report_error(_("invalid use of method value as argument "
6730 "of Offsetof"));
6731 return this;
6734 Field_reference_expression* farg = arg->field_reference_expression();
6735 while (farg != NULL)
6737 if (!farg->implicit())
6738 break;
6739 // When the selector refers to an embedded field,
6740 // it must not be reached through pointer indirections.
6741 if (farg->expr()->deref() != farg->expr())
6743 this->report_error(_("argument of Offsetof implies "
6744 "indirection of an embedded field"));
6745 return this;
6747 // Go up until we reach the original base.
6748 farg = farg->expr()->field_reference_expression();
6752 if (this->is_constant())
6754 Numeric_constant nc;
6755 if (this->numeric_constant_value(&nc))
6756 return nc.expression(loc);
6759 switch (this->code_)
6761 default:
6762 break;
6764 case BUILTIN_NEW:
6766 const Expression_list* args = this->args();
6767 if (args == NULL || args->size() < 1)
6768 this->report_error(_("not enough arguments"));
6769 else if (args->size() > 1)
6770 this->report_error(_("too many arguments"));
6771 else
6773 Expression* arg = args->front();
6774 if (!arg->is_type_expression())
6776 error_at(arg->location(), "expected type");
6777 this->set_is_error();
6779 else
6780 return Expression::make_allocation(arg->type(), loc);
6783 break;
6785 case BUILTIN_MAKE:
6786 return this->lower_make();
6788 case BUILTIN_RECOVER:
6789 if (function != NULL)
6790 function->func_value()->set_calls_recover();
6791 else
6793 // Calling recover outside of a function always returns the
6794 // nil empty interface.
6795 Type* eface = Type::make_empty_interface_type(loc);
6796 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6798 break;
6800 case BUILTIN_APPEND:
6802 // Lower the varargs.
6803 const Expression_list* args = this->args();
6804 if (args == NULL || args->empty())
6805 return this;
6806 Type* slice_type = args->front()->type();
6807 if (!slice_type->is_slice_type())
6809 if (slice_type->is_nil_type())
6810 error_at(args->front()->location(), "use of untyped nil");
6811 else
6812 error_at(args->front()->location(),
6813 "argument 1 must be a slice");
6814 this->set_is_error();
6815 return this;
6817 Type* element_type = slice_type->array_type()->element_type();
6818 this->lower_varargs(gogo, function, inserter,
6819 Type::make_array_type(element_type, NULL),
6822 break;
6824 case BUILTIN_DELETE:
6826 // Lower to a runtime function call.
6827 const Expression_list* args = this->args();
6828 if (args == NULL || args->size() < 2)
6829 this->report_error(_("not enough arguments"));
6830 else if (args->size() > 2)
6831 this->report_error(_("too many arguments"));
6832 else if (args->front()->type()->map_type() == NULL)
6833 this->report_error(_("argument 1 must be a map"));
6834 else
6836 // Since this function returns no value it must appear in
6837 // a statement by itself, so we don't have to worry about
6838 // order of evaluation of values around it. Evaluate the
6839 // map first to get order of evaluation right.
6840 Map_type* mt = args->front()->type()->map_type();
6841 Temporary_statement* map_temp =
6842 Statement::make_temporary(mt, args->front(), loc);
6843 inserter->insert(map_temp);
6845 Temporary_statement* key_temp =
6846 Statement::make_temporary(mt->key_type(), args->back(), loc);
6847 inserter->insert(key_temp);
6849 Expression* e1 = Expression::make_temporary_reference(map_temp,
6850 loc);
6851 Expression* e2 = Expression::make_temporary_reference(key_temp,
6852 loc);
6853 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6854 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6855 2, e1, e2);
6858 break;
6861 return this;
6864 // Flatten a builtin call expression. This turns the arguments of copy and
6865 // append into temporary expressions.
6867 Expression*
6868 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
6869 Statement_inserter* inserter)
6871 if (this->code_ == BUILTIN_APPEND
6872 || this->code_ == BUILTIN_COPY)
6874 Location loc = this->location();
6875 Type* at = this->args()->front()->type();
6876 for (Expression_list::iterator pa = this->args()->begin();
6877 pa != this->args()->end();
6878 ++pa)
6880 if ((*pa)->is_nil_expression())
6882 Expression* nil = Expression::make_nil(loc);
6883 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
6884 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
6886 if (!(*pa)->is_variable())
6888 Temporary_statement* temp =
6889 Statement::make_temporary(NULL, *pa, loc);
6890 inserter->insert(temp);
6891 *pa = Expression::make_temporary_reference(temp, loc);
6895 return this;
6898 // Lower a make expression.
6900 Expression*
6901 Builtin_call_expression::lower_make()
6903 Location loc = this->location();
6905 const Expression_list* args = this->args();
6906 if (args == NULL || args->size() < 1)
6908 this->report_error(_("not enough arguments"));
6909 return Expression::make_error(this->location());
6912 Expression_list::const_iterator parg = args->begin();
6914 Expression* first_arg = *parg;
6915 if (!first_arg->is_type_expression())
6917 error_at(first_arg->location(), "expected type");
6918 this->set_is_error();
6919 return Expression::make_error(this->location());
6921 Type* type = first_arg->type();
6923 bool is_slice = false;
6924 bool is_map = false;
6925 bool is_chan = false;
6926 if (type->is_slice_type())
6927 is_slice = true;
6928 else if (type->map_type() != NULL)
6929 is_map = true;
6930 else if (type->channel_type() != NULL)
6931 is_chan = true;
6932 else
6934 this->report_error(_("invalid type for make function"));
6935 return Expression::make_error(this->location());
6938 bool have_big_args = false;
6939 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6940 int uintptr_bits = uintptr_type->integer_type()->bits();
6942 Type_context int_context(Type::lookup_integer_type("int"), false);
6944 ++parg;
6945 Expression* len_arg;
6946 if (parg == args->end())
6948 if (is_slice)
6950 this->report_error(_("length required when allocating a slice"));
6951 return Expression::make_error(this->location());
6953 len_arg = Expression::make_integer_ul(0, NULL, loc);
6955 else
6957 len_arg = *parg;
6958 len_arg->determine_type(&int_context);
6959 if (!this->check_int_value(len_arg, true))
6960 return Expression::make_error(this->location());
6961 if (len_arg->type()->integer_type() != NULL
6962 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6963 have_big_args = true;
6964 ++parg;
6967 Expression* cap_arg = NULL;
6968 if (is_slice && parg != args->end())
6970 cap_arg = *parg;
6971 cap_arg->determine_type(&int_context);
6972 if (!this->check_int_value(cap_arg, false))
6973 return Expression::make_error(this->location());
6975 Numeric_constant nclen;
6976 Numeric_constant nccap;
6977 unsigned long vlen;
6978 unsigned long vcap;
6979 if (len_arg->numeric_constant_value(&nclen)
6980 && cap_arg->numeric_constant_value(&nccap)
6981 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
6982 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
6983 && vlen > vcap)
6985 this->report_error(_("len larger than cap"));
6986 return Expression::make_error(this->location());
6989 if (cap_arg->type()->integer_type() != NULL
6990 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6991 have_big_args = true;
6992 ++parg;
6995 if (parg != args->end())
6997 this->report_error(_("too many arguments to make"));
6998 return Expression::make_error(this->location());
7001 Location type_loc = first_arg->location();
7002 Expression* type_arg;
7003 if (is_slice || is_chan)
7004 type_arg = Expression::make_type_descriptor(type, type_loc);
7005 else if (is_map)
7006 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7007 else
7008 go_unreachable();
7010 Expression* call;
7011 if (is_slice)
7013 if (cap_arg == NULL)
7014 call = Runtime::make_call((have_big_args
7015 ? Runtime::MAKESLICE1BIG
7016 : Runtime::MAKESLICE1),
7017 loc, 2, type_arg, len_arg);
7018 else
7019 call = Runtime::make_call((have_big_args
7020 ? Runtime::MAKESLICE2BIG
7021 : Runtime::MAKESLICE2),
7022 loc, 3, type_arg, len_arg, cap_arg);
7024 else if (is_map)
7025 call = Runtime::make_call((have_big_args
7026 ? Runtime::MAKEMAPBIG
7027 : Runtime::MAKEMAP),
7028 loc, 2, type_arg, len_arg);
7029 else if (is_chan)
7030 call = Runtime::make_call((have_big_args
7031 ? Runtime::MAKECHANBIG
7032 : Runtime::MAKECHAN),
7033 loc, 2, type_arg, len_arg);
7034 else
7035 go_unreachable();
7037 return Expression::make_unsafe_cast(type, call, loc);
7040 // Return whether an expression has an integer value. Report an error
7041 // if not. This is used when handling calls to the predeclared make
7042 // function.
7044 bool
7045 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7047 Numeric_constant nc;
7048 if (e->numeric_constant_value(&nc))
7050 unsigned long v;
7051 switch (nc.to_unsigned_long(&v))
7053 case Numeric_constant::NC_UL_VALID:
7054 break;
7055 case Numeric_constant::NC_UL_NOTINT:
7056 error_at(e->location(), "non-integer %s argument to make",
7057 is_length ? "len" : "cap");
7058 return false;
7059 case Numeric_constant::NC_UL_NEGATIVE:
7060 error_at(e->location(), "negative %s argument to make",
7061 is_length ? "len" : "cap");
7062 return false;
7063 case Numeric_constant::NC_UL_BIG:
7064 // We don't want to give a compile-time error for a 64-bit
7065 // value on a 32-bit target.
7066 break;
7069 mpz_t val;
7070 if (!nc.to_int(&val))
7071 go_unreachable();
7072 int bits = mpz_sizeinbase(val, 2);
7073 mpz_clear(val);
7074 Type* int_type = Type::lookup_integer_type("int");
7075 if (bits >= int_type->integer_type()->bits())
7077 error_at(e->location(), "%s argument too large for make",
7078 is_length ? "len" : "cap");
7079 return false;
7082 return true;
7085 if (e->type()->integer_type() != NULL)
7086 return true;
7088 error_at(e->location(), "non-integer %s argument to make",
7089 is_length ? "len" : "cap");
7090 return false;
7093 // Return the type of the real or imag functions, given the type of
7094 // the argument. We need to map complex64 to float32 and complex128
7095 // to float64, so it has to be done by name. This returns NULL if it
7096 // can't figure out the type.
7098 Type*
7099 Builtin_call_expression::real_imag_type(Type* arg_type)
7101 if (arg_type == NULL || arg_type->is_abstract())
7102 return NULL;
7103 Named_type* nt = arg_type->named_type();
7104 if (nt == NULL)
7105 return NULL;
7106 while (nt->real_type()->named_type() != NULL)
7107 nt = nt->real_type()->named_type();
7108 if (nt->name() == "complex64")
7109 return Type::lookup_float_type("float32");
7110 else if (nt->name() == "complex128")
7111 return Type::lookup_float_type("float64");
7112 else
7113 return NULL;
7116 // Return the type of the complex function, given the type of one of the
7117 // argments. Like real_imag_type, we have to map by name.
7119 Type*
7120 Builtin_call_expression::complex_type(Type* arg_type)
7122 if (arg_type == NULL || arg_type->is_abstract())
7123 return NULL;
7124 Named_type* nt = arg_type->named_type();
7125 if (nt == NULL)
7126 return NULL;
7127 while (nt->real_type()->named_type() != NULL)
7128 nt = nt->real_type()->named_type();
7129 if (nt->name() == "float32")
7130 return Type::lookup_complex_type("complex64");
7131 else if (nt->name() == "float64")
7132 return Type::lookup_complex_type("complex128");
7133 else
7134 return NULL;
7137 // Return a single argument, or NULL if there isn't one.
7139 Expression*
7140 Builtin_call_expression::one_arg() const
7142 const Expression_list* args = this->args();
7143 if (args == NULL || args->size() != 1)
7144 return NULL;
7145 return args->front();
7148 // A traversal class which looks for a call or receive expression.
7150 class Find_call_expression : public Traverse
7152 public:
7153 Find_call_expression()
7154 : Traverse(traverse_expressions),
7155 found_(false)
7159 expression(Expression**);
7161 bool
7162 found()
7163 { return this->found_; }
7165 private:
7166 bool found_;
7170 Find_call_expression::expression(Expression** pexpr)
7172 if ((*pexpr)->call_expression() != NULL
7173 || (*pexpr)->receive_expression() != NULL)
7175 this->found_ = true;
7176 return TRAVERSE_EXIT;
7178 return TRAVERSE_CONTINUE;
7181 // Return whether this is constant: len of a string constant, or len
7182 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7183 // unsafe.Alignof.
7185 bool
7186 Builtin_call_expression::do_is_constant() const
7188 if (this->is_error_expression())
7189 return true;
7190 switch (this->code_)
7192 case BUILTIN_LEN:
7193 case BUILTIN_CAP:
7195 if (this->seen_)
7196 return false;
7198 Expression* arg = this->one_arg();
7199 if (arg == NULL)
7200 return false;
7201 Type* arg_type = arg->type();
7203 if (arg_type->points_to() != NULL
7204 && arg_type->points_to()->array_type() != NULL
7205 && !arg_type->points_to()->is_slice_type())
7206 arg_type = arg_type->points_to();
7208 // The len and cap functions are only constant if there are no
7209 // function calls or channel operations in the arguments.
7210 // Otherwise we have to make the call.
7211 if (!arg->is_constant())
7213 Find_call_expression find_call;
7214 Expression::traverse(&arg, &find_call);
7215 if (find_call.found())
7216 return false;
7219 if (arg_type->array_type() != NULL
7220 && arg_type->array_type()->length() != NULL)
7221 return true;
7223 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7225 this->seen_ = true;
7226 bool ret = arg->is_constant();
7227 this->seen_ = false;
7228 return ret;
7231 break;
7233 case BUILTIN_SIZEOF:
7234 case BUILTIN_ALIGNOF:
7235 return this->one_arg() != NULL;
7237 case BUILTIN_OFFSETOF:
7239 Expression* arg = this->one_arg();
7240 if (arg == NULL)
7241 return false;
7242 return arg->field_reference_expression() != NULL;
7245 case BUILTIN_COMPLEX:
7247 const Expression_list* args = this->args();
7248 if (args != NULL && args->size() == 2)
7249 return args->front()->is_constant() && args->back()->is_constant();
7251 break;
7253 case BUILTIN_REAL:
7254 case BUILTIN_IMAG:
7256 Expression* arg = this->one_arg();
7257 return arg != NULL && arg->is_constant();
7260 default:
7261 break;
7264 return false;
7267 // Return a numeric constant if possible.
7269 bool
7270 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7272 if (this->code_ == BUILTIN_LEN
7273 || this->code_ == BUILTIN_CAP)
7275 Expression* arg = this->one_arg();
7276 if (arg == NULL)
7277 return false;
7278 Type* arg_type = arg->type();
7280 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7282 std::string sval;
7283 if (arg->string_constant_value(&sval))
7285 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7286 sval.length());
7287 return true;
7291 if (arg_type->points_to() != NULL
7292 && arg_type->points_to()->array_type() != NULL
7293 && !arg_type->points_to()->is_slice_type())
7294 arg_type = arg_type->points_to();
7296 if (arg_type->array_type() != NULL
7297 && arg_type->array_type()->length() != NULL)
7299 if (this->seen_)
7300 return false;
7301 Expression* e = arg_type->array_type()->length();
7302 this->seen_ = true;
7303 bool r = e->numeric_constant_value(nc);
7304 this->seen_ = false;
7305 if (r)
7307 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7308 this->location()))
7309 r = false;
7311 return r;
7314 else if (this->code_ == BUILTIN_SIZEOF
7315 || this->code_ == BUILTIN_ALIGNOF)
7317 Expression* arg = this->one_arg();
7318 if (arg == NULL)
7319 return false;
7320 Type* arg_type = arg->type();
7321 if (arg_type->is_error())
7322 return false;
7323 if (arg_type->is_abstract())
7324 return false;
7325 if (this->seen_)
7326 return false;
7328 unsigned long ret;
7329 if (this->code_ == BUILTIN_SIZEOF)
7331 this->seen_ = true;
7332 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7333 this->seen_ = false;
7334 if (!ok)
7335 return false;
7337 else if (this->code_ == BUILTIN_ALIGNOF)
7339 bool ok;
7340 this->seen_ = true;
7341 if (arg->field_reference_expression() == NULL)
7342 ok = arg_type->backend_type_align(this->gogo_, &ret);
7343 else
7345 // Calling unsafe.Alignof(s.f) returns the alignment of
7346 // the type of f when it is used as a field in a struct.
7347 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7349 this->seen_ = false;
7350 if (!ok)
7351 return false;
7353 else
7354 go_unreachable();
7356 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"), ret);
7357 return true;
7359 else if (this->code_ == BUILTIN_OFFSETOF)
7361 Expression* arg = this->one_arg();
7362 if (arg == NULL)
7363 return false;
7364 Field_reference_expression* farg = arg->field_reference_expression();
7365 if (farg == NULL)
7366 return false;
7367 if (this->seen_)
7368 return false;
7370 unsigned int total_offset = 0;
7371 while (true)
7373 Expression* struct_expr = farg->expr();
7374 Type* st = struct_expr->type();
7375 if (st->struct_type() == NULL)
7376 return false;
7377 if (st->named_type() != NULL)
7378 st->named_type()->convert(this->gogo_);
7379 unsigned int offset;
7380 this->seen_ = true;
7381 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7382 farg->field_index(),
7383 &offset);
7384 this->seen_ = false;
7385 if (!ok)
7386 return false;
7387 total_offset += offset;
7388 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7390 // Go up until we reach the original base.
7391 farg = struct_expr->field_reference_expression();
7392 continue;
7394 break;
7396 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7397 static_cast<unsigned long>(total_offset));
7398 return true;
7400 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7402 Expression* arg = this->one_arg();
7403 if (arg == NULL)
7404 return false;
7406 Numeric_constant argnc;
7407 if (!arg->numeric_constant_value(&argnc))
7408 return false;
7410 mpc_t val;
7411 if (!argnc.to_complex(&val))
7412 return false;
7414 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7415 if (this->code_ == BUILTIN_REAL)
7416 nc->set_float(type, mpc_realref(val));
7417 else
7418 nc->set_float(type, mpc_imagref(val));
7419 mpc_clear(val);
7420 return true;
7422 else if (this->code_ == BUILTIN_COMPLEX)
7424 const Expression_list* args = this->args();
7425 if (args == NULL || args->size() != 2)
7426 return false;
7428 Numeric_constant rnc;
7429 if (!args->front()->numeric_constant_value(&rnc))
7430 return false;
7431 Numeric_constant inc;
7432 if (!args->back()->numeric_constant_value(&inc))
7433 return false;
7435 if (rnc.type() != NULL
7436 && !rnc.type()->is_abstract()
7437 && inc.type() != NULL
7438 && !inc.type()->is_abstract()
7439 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7440 return false;
7442 mpfr_t r;
7443 if (!rnc.to_float(&r))
7444 return false;
7445 mpfr_t i;
7446 if (!inc.to_float(&i))
7448 mpfr_clear(r);
7449 return false;
7452 Type* arg_type = rnc.type();
7453 if (arg_type == NULL || arg_type->is_abstract())
7454 arg_type = inc.type();
7456 mpc_t val;
7457 mpc_init2(val, mpc_precision);
7458 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
7459 mpfr_clear(r);
7460 mpfr_clear(i);
7462 Type* type = Builtin_call_expression::complex_type(arg_type);
7463 nc->set_complex(type, val);
7465 mpc_clear(val);
7467 return true;
7470 return false;
7473 // Give an error if we are discarding the value of an expression which
7474 // should not normally be discarded. We don't give an error for
7475 // discarding the value of an ordinary function call, but we do for
7476 // builtin functions, purely for consistency with the gc compiler.
7478 bool
7479 Builtin_call_expression::do_discarding_value()
7481 switch (this->code_)
7483 case BUILTIN_INVALID:
7484 default:
7485 go_unreachable();
7487 case BUILTIN_APPEND:
7488 case BUILTIN_CAP:
7489 case BUILTIN_COMPLEX:
7490 case BUILTIN_IMAG:
7491 case BUILTIN_LEN:
7492 case BUILTIN_MAKE:
7493 case BUILTIN_NEW:
7494 case BUILTIN_REAL:
7495 case BUILTIN_ALIGNOF:
7496 case BUILTIN_OFFSETOF:
7497 case BUILTIN_SIZEOF:
7498 this->unused_value_error();
7499 return false;
7501 case BUILTIN_CLOSE:
7502 case BUILTIN_COPY:
7503 case BUILTIN_DELETE:
7504 case BUILTIN_PANIC:
7505 case BUILTIN_PRINT:
7506 case BUILTIN_PRINTLN:
7507 case BUILTIN_RECOVER:
7508 return true;
7512 // Return the type.
7514 Type*
7515 Builtin_call_expression::do_type()
7517 switch (this->code_)
7519 case BUILTIN_INVALID:
7520 default:
7521 go_unreachable();
7523 case BUILTIN_NEW:
7524 case BUILTIN_MAKE:
7526 const Expression_list* args = this->args();
7527 if (args == NULL || args->empty())
7528 return Type::make_error_type();
7529 return Type::make_pointer_type(args->front()->type());
7532 case BUILTIN_CAP:
7533 case BUILTIN_COPY:
7534 case BUILTIN_LEN:
7535 return Type::lookup_integer_type("int");
7537 case BUILTIN_ALIGNOF:
7538 case BUILTIN_OFFSETOF:
7539 case BUILTIN_SIZEOF:
7540 return Type::lookup_integer_type("uintptr");
7542 case BUILTIN_CLOSE:
7543 case BUILTIN_DELETE:
7544 case BUILTIN_PANIC:
7545 case BUILTIN_PRINT:
7546 case BUILTIN_PRINTLN:
7547 return Type::make_void_type();
7549 case BUILTIN_RECOVER:
7550 return Type::make_empty_interface_type(Linemap::predeclared_location());
7552 case BUILTIN_APPEND:
7554 const Expression_list* args = this->args();
7555 if (args == NULL || args->empty())
7556 return Type::make_error_type();
7557 Type *ret = args->front()->type();
7558 if (!ret->is_slice_type())
7559 return Type::make_error_type();
7560 return ret;
7563 case BUILTIN_REAL:
7564 case BUILTIN_IMAG:
7566 Expression* arg = this->one_arg();
7567 if (arg == NULL)
7568 return Type::make_error_type();
7569 Type* t = arg->type();
7570 if (t->is_abstract())
7571 t = t->make_non_abstract_type();
7572 t = Builtin_call_expression::real_imag_type(t);
7573 if (t == NULL)
7574 t = Type::make_error_type();
7575 return t;
7578 case BUILTIN_COMPLEX:
7580 const Expression_list* args = this->args();
7581 if (args == NULL || args->size() != 2)
7582 return Type::make_error_type();
7583 Type* t = args->front()->type();
7584 if (t->is_abstract())
7586 t = args->back()->type();
7587 if (t->is_abstract())
7588 t = t->make_non_abstract_type();
7590 t = Builtin_call_expression::complex_type(t);
7591 if (t == NULL)
7592 t = Type::make_error_type();
7593 return t;
7598 // Determine the type.
7600 void
7601 Builtin_call_expression::do_determine_type(const Type_context* context)
7603 if (!this->determining_types())
7604 return;
7606 this->fn()->determine_type_no_context();
7608 const Expression_list* args = this->args();
7610 bool is_print;
7611 Type* arg_type = NULL;
7612 switch (this->code_)
7614 case BUILTIN_PRINT:
7615 case BUILTIN_PRINTLN:
7616 // Do not force a large integer constant to "int".
7617 is_print = true;
7618 break;
7620 case BUILTIN_REAL:
7621 case BUILTIN_IMAG:
7622 arg_type = Builtin_call_expression::complex_type(context->type);
7623 if (arg_type == NULL)
7624 arg_type = Type::lookup_complex_type("complex128");
7625 is_print = false;
7626 break;
7628 case BUILTIN_COMPLEX:
7630 // For the complex function the type of one operand can
7631 // determine the type of the other, as in a binary expression.
7632 arg_type = Builtin_call_expression::real_imag_type(context->type);
7633 if (arg_type == NULL)
7634 arg_type = Type::lookup_float_type("float64");
7635 if (args != NULL && args->size() == 2)
7637 Type* t1 = args->front()->type();
7638 Type* t2 = args->back()->type();
7639 if (!t1->is_abstract())
7640 arg_type = t1;
7641 else if (!t2->is_abstract())
7642 arg_type = t2;
7644 is_print = false;
7646 break;
7648 default:
7649 is_print = false;
7650 break;
7653 if (args != NULL)
7655 for (Expression_list::const_iterator pa = args->begin();
7656 pa != args->end();
7657 ++pa)
7659 Type_context subcontext;
7660 subcontext.type = arg_type;
7662 if (is_print)
7664 // We want to print large constants, we so can't just
7665 // use the appropriate nonabstract type. Use uint64 for
7666 // an integer if we know it is nonnegative, otherwise
7667 // use int64 for a integer, otherwise use float64 for a
7668 // float or complex128 for a complex.
7669 Type* want_type = NULL;
7670 Type* atype = (*pa)->type();
7671 if (atype->is_abstract())
7673 if (atype->integer_type() != NULL)
7675 Numeric_constant nc;
7676 if (this->numeric_constant_value(&nc))
7678 mpz_t val;
7679 if (nc.to_int(&val))
7681 if (mpz_sgn(val) >= 0)
7682 want_type = Type::lookup_integer_type("uint64");
7683 mpz_clear(val);
7686 if (want_type == NULL)
7687 want_type = Type::lookup_integer_type("int64");
7689 else if (atype->float_type() != NULL)
7690 want_type = Type::lookup_float_type("float64");
7691 else if (atype->complex_type() != NULL)
7692 want_type = Type::lookup_complex_type("complex128");
7693 else if (atype->is_abstract_string_type())
7694 want_type = Type::lookup_string_type();
7695 else if (atype->is_abstract_boolean_type())
7696 want_type = Type::lookup_bool_type();
7697 else
7698 go_unreachable();
7699 subcontext.type = want_type;
7703 (*pa)->determine_type(&subcontext);
7708 // If there is exactly one argument, return true. Otherwise give an
7709 // error message and return false.
7711 bool
7712 Builtin_call_expression::check_one_arg()
7714 const Expression_list* args = this->args();
7715 if (args == NULL || args->size() < 1)
7717 this->report_error(_("not enough arguments"));
7718 return false;
7720 else if (args->size() > 1)
7722 this->report_error(_("too many arguments"));
7723 return false;
7725 if (args->front()->is_error_expression()
7726 || args->front()->type()->is_error())
7728 this->set_is_error();
7729 return false;
7731 return true;
7734 // Check argument types for a builtin function.
7736 void
7737 Builtin_call_expression::do_check_types(Gogo*)
7739 if (this->is_error_expression())
7740 return;
7741 switch (this->code_)
7743 case BUILTIN_INVALID:
7744 case BUILTIN_NEW:
7745 case BUILTIN_MAKE:
7746 case BUILTIN_DELETE:
7747 return;
7749 case BUILTIN_LEN:
7750 case BUILTIN_CAP:
7752 // The single argument may be either a string or an array or a
7753 // map or a channel, or a pointer to a closed array.
7754 if (this->check_one_arg())
7756 Type* arg_type = this->one_arg()->type();
7757 if (arg_type->points_to() != NULL
7758 && arg_type->points_to()->array_type() != NULL
7759 && !arg_type->points_to()->is_slice_type())
7760 arg_type = arg_type->points_to();
7761 if (this->code_ == BUILTIN_CAP)
7763 if (!arg_type->is_error()
7764 && arg_type->array_type() == NULL
7765 && arg_type->channel_type() == NULL)
7766 this->report_error(_("argument must be array or slice "
7767 "or channel"));
7769 else
7771 if (!arg_type->is_error()
7772 && !arg_type->is_string_type()
7773 && arg_type->array_type() == NULL
7774 && arg_type->map_type() == NULL
7775 && arg_type->channel_type() == NULL)
7776 this->report_error(_("argument must be string or "
7777 "array or slice or map or channel"));
7781 break;
7783 case BUILTIN_PRINT:
7784 case BUILTIN_PRINTLN:
7786 const Expression_list* args = this->args();
7787 if (args == NULL)
7789 if (this->code_ == BUILTIN_PRINT)
7790 warning_at(this->location(), 0,
7791 "no arguments for builtin function %<%s%>",
7792 (this->code_ == BUILTIN_PRINT
7793 ? "print"
7794 : "println"));
7796 else
7798 for (Expression_list::const_iterator p = args->begin();
7799 p != args->end();
7800 ++p)
7802 Type* type = (*p)->type();
7803 if (type->is_error()
7804 || type->is_string_type()
7805 || type->integer_type() != NULL
7806 || type->float_type() != NULL
7807 || type->complex_type() != NULL
7808 || type->is_boolean_type()
7809 || type->points_to() != NULL
7810 || type->interface_type() != NULL
7811 || type->channel_type() != NULL
7812 || type->map_type() != NULL
7813 || type->function_type() != NULL
7814 || type->is_slice_type())
7816 else if ((*p)->is_type_expression())
7818 // If this is a type expression it's going to give
7819 // an error anyhow, so we don't need one here.
7821 else
7822 this->report_error(_("unsupported argument type to "
7823 "builtin function"));
7827 break;
7829 case BUILTIN_CLOSE:
7830 if (this->check_one_arg())
7832 if (this->one_arg()->type()->channel_type() == NULL)
7833 this->report_error(_("argument must be channel"));
7834 else if (!this->one_arg()->type()->channel_type()->may_send())
7835 this->report_error(_("cannot close receive-only channel"));
7837 break;
7839 case BUILTIN_PANIC:
7840 case BUILTIN_SIZEOF:
7841 case BUILTIN_ALIGNOF:
7842 this->check_one_arg();
7843 break;
7845 case BUILTIN_RECOVER:
7846 if (this->args() != NULL
7847 && !this->args()->empty()
7848 && !this->recover_arg_is_set_)
7849 this->report_error(_("too many arguments"));
7850 break;
7852 case BUILTIN_OFFSETOF:
7853 if (this->check_one_arg())
7855 Expression* arg = this->one_arg();
7856 if (arg->field_reference_expression() == NULL)
7857 this->report_error(_("argument must be a field reference"));
7859 break;
7861 case BUILTIN_COPY:
7863 const Expression_list* args = this->args();
7864 if (args == NULL || args->size() < 2)
7866 this->report_error(_("not enough arguments"));
7867 break;
7869 else if (args->size() > 2)
7871 this->report_error(_("too many arguments"));
7872 break;
7874 Type* arg1_type = args->front()->type();
7875 Type* arg2_type = args->back()->type();
7876 if (arg1_type->is_error() || arg2_type->is_error())
7877 break;
7879 Type* e1;
7880 if (arg1_type->is_slice_type())
7881 e1 = arg1_type->array_type()->element_type();
7882 else
7884 this->report_error(_("left argument must be a slice"));
7885 break;
7888 if (arg2_type->is_slice_type())
7890 Type* e2 = arg2_type->array_type()->element_type();
7891 if (!Type::are_identical(e1, e2, true, NULL))
7892 this->report_error(_("element types must be the same"));
7894 else if (arg2_type->is_string_type())
7896 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7897 this->report_error(_("first argument must be []byte"));
7899 else
7900 this->report_error(_("second argument must be slice or string"));
7902 break;
7904 case BUILTIN_APPEND:
7906 const Expression_list* args = this->args();
7907 if (args == NULL || args->size() < 2)
7909 this->report_error(_("not enough arguments"));
7910 break;
7912 if (args->size() > 2)
7914 this->report_error(_("too many arguments"));
7915 break;
7917 if (args->front()->type()->is_error()
7918 || args->back()->type()->is_error())
7919 break;
7921 Array_type* at = args->front()->type()->array_type();
7922 Type* e = at->element_type();
7924 // The language permits appending a string to a []byte, as a
7925 // special case.
7926 if (args->back()->type()->is_string_type())
7928 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7929 break;
7932 // The language says that the second argument must be
7933 // assignable to a slice of the element type of the first
7934 // argument. We already know the first argument is a slice
7935 // type.
7936 Type* arg2_type = Type::make_array_type(e, NULL);
7937 std::string reason;
7938 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7940 if (reason.empty())
7941 this->report_error(_("argument 2 has invalid type"));
7942 else
7944 error_at(this->location(), "argument 2 has invalid type (%s)",
7945 reason.c_str());
7946 this->set_is_error();
7949 break;
7952 case BUILTIN_REAL:
7953 case BUILTIN_IMAG:
7954 if (this->check_one_arg())
7956 if (this->one_arg()->type()->complex_type() == NULL)
7957 this->report_error(_("argument must have complex type"));
7959 break;
7961 case BUILTIN_COMPLEX:
7963 const Expression_list* args = this->args();
7964 if (args == NULL || args->size() < 2)
7965 this->report_error(_("not enough arguments"));
7966 else if (args->size() > 2)
7967 this->report_error(_("too many arguments"));
7968 else if (args->front()->is_error_expression()
7969 || args->front()->type()->is_error()
7970 || args->back()->is_error_expression()
7971 || args->back()->type()->is_error())
7972 this->set_is_error();
7973 else if (!Type::are_identical(args->front()->type(),
7974 args->back()->type(), true, NULL))
7975 this->report_error(_("complex arguments must have identical types"));
7976 else if (args->front()->type()->float_type() == NULL)
7977 this->report_error(_("complex arguments must have "
7978 "floating-point type"));
7980 break;
7982 default:
7983 go_unreachable();
7987 Expression*
7988 Builtin_call_expression::do_copy()
7990 Call_expression* bce =
7991 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7992 this->args()->copy(),
7993 this->is_varargs(),
7994 this->location());
7996 if (this->varargs_are_lowered())
7997 bce->set_varargs_are_lowered();
7998 return bce;
8001 // Return the backend representation for a builtin function.
8003 Bexpression*
8004 Builtin_call_expression::do_get_backend(Translate_context* context)
8006 Gogo* gogo = context->gogo();
8007 Location location = this->location();
8008 switch (this->code_)
8010 case BUILTIN_INVALID:
8011 case BUILTIN_NEW:
8012 case BUILTIN_MAKE:
8013 go_unreachable();
8015 case BUILTIN_LEN:
8016 case BUILTIN_CAP:
8018 const Expression_list* args = this->args();
8019 go_assert(args != NULL && args->size() == 1);
8020 Expression* arg = args->front();
8021 Type* arg_type = arg->type();
8023 if (this->seen_)
8025 go_assert(saw_errors());
8026 return context->backend()->error_expression();
8028 this->seen_ = true;
8029 this->seen_ = false;
8030 if (arg_type->points_to() != NULL)
8032 arg_type = arg_type->points_to();
8033 go_assert(arg_type->array_type() != NULL
8034 && !arg_type->is_slice_type());
8035 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8038 Type* int_type = Type::lookup_integer_type("int");
8039 Expression* val;
8040 if (this->code_ == BUILTIN_LEN)
8042 if (arg_type->is_string_type())
8043 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8044 location);
8045 else if (arg_type->array_type() != NULL)
8047 if (this->seen_)
8049 go_assert(saw_errors());
8050 return context->backend()->error_expression();
8052 this->seen_ = true;
8053 val = arg_type->array_type()->get_length(gogo, arg);
8054 this->seen_ = false;
8056 else if (arg_type->map_type() != NULL)
8057 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8058 else if (arg_type->channel_type() != NULL)
8059 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8060 else
8061 go_unreachable();
8063 else
8065 if (arg_type->array_type() != NULL)
8067 if (this->seen_)
8069 go_assert(saw_errors());
8070 return context->backend()->error_expression();
8072 this->seen_ = true;
8073 val = arg_type->array_type()->get_capacity(gogo, arg);
8074 this->seen_ = false;
8076 else if (arg_type->channel_type() != NULL)
8077 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8078 else
8079 go_unreachable();
8082 return Expression::make_cast(int_type, val,
8083 location)->get_backend(context);
8086 case BUILTIN_PRINT:
8087 case BUILTIN_PRINTLN:
8089 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8090 Expression* print_stmts = NULL;
8092 const Expression_list* call_args = this->args();
8093 if (call_args != NULL)
8095 for (Expression_list::const_iterator p = call_args->begin();
8096 p != call_args->end();
8097 ++p)
8099 if (is_ln && p != call_args->begin())
8101 Expression* print_space =
8102 Runtime::make_call(Runtime::PRINT_SPACE,
8103 this->location(), 0);
8105 print_stmts =
8106 Expression::make_compound(print_stmts, print_space,
8107 location);
8110 Expression* arg = *p;
8111 Type* type = arg->type();
8112 Runtime::Function code;
8113 if (type->is_string_type())
8114 code = Runtime::PRINT_STRING;
8115 else if (type->integer_type() != NULL
8116 && type->integer_type()->is_unsigned())
8118 Type* itype = Type::lookup_integer_type("uint64");
8119 arg = Expression::make_cast(itype, arg, location);
8120 code = Runtime::PRINT_UINT64;
8122 else if (type->integer_type() != NULL)
8124 Type* itype = Type::lookup_integer_type("int64");
8125 arg = Expression::make_cast(itype, arg, location);
8126 code = Runtime::PRINT_INT64;
8128 else if (type->float_type() != NULL)
8130 Type* dtype = Type::lookup_float_type("float64");
8131 arg = Expression::make_cast(dtype, arg, location);
8132 code = Runtime::PRINT_DOUBLE;
8134 else if (type->complex_type() != NULL)
8136 Type* ctype = Type::lookup_complex_type("complex128");
8137 arg = Expression::make_cast(ctype, arg, location);
8138 code = Runtime::PRINT_COMPLEX;
8140 else if (type->is_boolean_type())
8141 code = Runtime::PRINT_BOOL;
8142 else if (type->points_to() != NULL
8143 || type->channel_type() != NULL
8144 || type->map_type() != NULL
8145 || type->function_type() != NULL)
8147 arg = Expression::make_cast(type, arg, location);
8148 code = Runtime::PRINT_POINTER;
8150 else if (type->interface_type() != NULL)
8152 if (type->interface_type()->is_empty())
8153 code = Runtime::PRINT_EMPTY_INTERFACE;
8154 else
8155 code = Runtime::PRINT_INTERFACE;
8157 else if (type->is_slice_type())
8158 code = Runtime::PRINT_SLICE;
8159 else
8161 go_assert(saw_errors());
8162 return context->backend()->error_expression();
8165 Expression* call = Runtime::make_call(code, location, 1, arg);
8166 if (print_stmts == NULL)
8167 print_stmts = call;
8168 else
8169 print_stmts = Expression::make_compound(print_stmts, call,
8170 location);
8174 if (is_ln)
8176 Expression* print_nl =
8177 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8178 if (print_stmts == NULL)
8179 print_stmts = print_nl;
8180 else
8181 print_stmts = Expression::make_compound(print_stmts, print_nl,
8182 location);
8185 return print_stmts->get_backend(context);
8188 case BUILTIN_PANIC:
8190 const Expression_list* args = this->args();
8191 go_assert(args != NULL && args->size() == 1);
8192 Expression* arg = args->front();
8193 Type *empty =
8194 Type::make_empty_interface_type(Linemap::predeclared_location());
8195 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8197 Expression* panic =
8198 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8199 return panic->get_backend(context);
8202 case BUILTIN_RECOVER:
8204 // The argument is set when building recover thunks. It's a
8205 // boolean value which is true if we can recover a value now.
8206 const Expression_list* args = this->args();
8207 go_assert(args != NULL && args->size() == 1);
8208 Expression* arg = args->front();
8209 Type *empty =
8210 Type::make_empty_interface_type(Linemap::predeclared_location());
8212 Expression* nil = Expression::make_nil(location);
8213 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8215 // We need to handle a deferred call to recover specially,
8216 // because it changes whether it can recover a panic or not.
8217 // See test7 in test/recover1.go.
8218 Expression* recover = Runtime::make_call((this->is_deferred()
8219 ? Runtime::DEFERRED_RECOVER
8220 : Runtime::RECOVER),
8221 location, 0);
8222 Expression* cond =
8223 Expression::make_conditional(arg, recover, nil, location);
8224 return cond->get_backend(context);
8227 case BUILTIN_CLOSE:
8229 const Expression_list* args = this->args();
8230 go_assert(args != NULL && args->size() == 1);
8231 Expression* arg = args->front();
8232 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8233 1, arg);
8234 return close->get_backend(context);
8237 case BUILTIN_SIZEOF:
8238 case BUILTIN_OFFSETOF:
8239 case BUILTIN_ALIGNOF:
8241 Numeric_constant nc;
8242 unsigned long val;
8243 if (!this->numeric_constant_value(&nc)
8244 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8246 go_assert(saw_errors());
8247 return context->backend()->error_expression();
8249 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8250 mpz_t ival;
8251 nc.get_int(&ival);
8252 Expression* int_cst =
8253 Expression::make_integer_z(&ival, uintptr_type, location);
8254 mpz_clear(ival);
8255 return int_cst->get_backend(context);
8258 case BUILTIN_COPY:
8260 const Expression_list* args = this->args();
8261 go_assert(args != NULL && args->size() == 2);
8262 Expression* arg1 = args->front();
8263 Expression* arg2 = args->back();
8265 Type* arg1_type = arg1->type();
8266 Array_type* at = arg1_type->array_type();
8267 go_assert(arg1->is_variable());
8268 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8269 Expression* arg1_len = at->get_length(gogo, arg1);
8271 Type* arg2_type = arg2->type();
8272 go_assert(arg2->is_variable());
8273 Expression* arg2_val;
8274 Expression* arg2_len;
8275 if (arg2_type->is_slice_type())
8277 at = arg2_type->array_type();
8278 arg2_val = at->get_value_pointer(gogo, arg2);
8279 arg2_len = at->get_length(gogo, arg2);
8281 else
8283 go_assert(arg2->is_variable());
8284 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8285 location);
8286 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8287 location);
8289 Expression* cond =
8290 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8291 Expression* length =
8292 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8294 Type* element_type = at->element_type();
8295 Btype* element_btype = element_type->get_backend(gogo);
8296 size_t element_size = gogo->backend()->type_size(element_btype);
8297 Expression* size_expr = Expression::make_integer_ul(element_size,
8298 length->type(),
8299 location);
8300 Expression* bytecount =
8301 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8302 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8303 arg1_val, arg2_val, bytecount);
8305 Expression* compound = Expression::make_compound(copy, length, location);
8306 return compound->get_backend(context);
8309 case BUILTIN_APPEND:
8311 const Expression_list* args = this->args();
8312 go_assert(args != NULL && args->size() == 2);
8313 Expression* arg1 = args->front();
8314 Expression* arg2 = args->back();
8316 Array_type* at = arg1->type()->array_type();
8317 Type* element_type = at->element_type()->forwarded();
8319 go_assert(arg2->is_variable());
8320 Expression* arg2_val;
8321 Expression* arg2_len;
8322 unsigned long size;
8323 if (arg2->type()->is_string_type()
8324 && element_type->integer_type() != NULL
8325 && element_type->integer_type()->is_byte())
8327 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8328 location);
8329 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8330 location);
8331 size = 1;
8333 else
8335 arg2_val = at->get_value_pointer(gogo, arg2);
8336 arg2_len = at->get_length(gogo, arg2);
8337 Btype* element_btype = element_type->get_backend(gogo);
8338 size = gogo->backend()->type_size(element_btype);
8340 Expression* element_size =
8341 Expression::make_integer_ul(size, NULL, location);
8343 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8344 arg1, arg2_val, arg2_len,
8345 element_size);
8346 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8347 return append->get_backend(context);
8350 case BUILTIN_REAL:
8351 case BUILTIN_IMAG:
8353 const Expression_list* args = this->args();
8354 go_assert(args != NULL && args->size() == 1);
8356 Bexpression* ret;
8357 Bexpression* bcomplex = args->front()->get_backend(context);
8358 if (this->code_ == BUILTIN_REAL)
8359 ret = gogo->backend()->real_part_expression(bcomplex, location);
8360 else
8361 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8362 return ret;
8365 case BUILTIN_COMPLEX:
8367 const Expression_list* args = this->args();
8368 go_assert(args != NULL && args->size() == 2);
8369 Bexpression* breal = args->front()->get_backend(context);
8370 Bexpression* bimag = args->back()->get_backend(context);
8371 return gogo->backend()->complex_expression(breal, bimag, location);
8374 default:
8375 go_unreachable();
8379 // We have to support exporting a builtin call expression, because
8380 // code can set a constant to the result of a builtin expression.
8382 void
8383 Builtin_call_expression::do_export(Export* exp) const
8385 Numeric_constant nc;
8386 if (!this->numeric_constant_value(&nc))
8388 error_at(this->location(), "value is not constant");
8389 return;
8392 if (nc.is_int())
8394 mpz_t val;
8395 nc.get_int(&val);
8396 Integer_expression::export_integer(exp, val);
8397 mpz_clear(val);
8399 else if (nc.is_float())
8401 mpfr_t fval;
8402 nc.get_float(&fval);
8403 Float_expression::export_float(exp, fval);
8404 mpfr_clear(fval);
8406 else if (nc.is_complex())
8408 mpc_t cval;
8409 nc.get_complex(&cval);
8410 Complex_expression::export_complex(exp, cval);
8411 mpc_clear(cval);
8413 else
8414 go_unreachable();
8416 // A trailing space lets us reliably identify the end of the number.
8417 exp->write_c_string(" ");
8420 // Class Call_expression.
8422 // A Go function can be viewed in a couple of different ways. The
8423 // code of a Go function becomes a backend function with parameters
8424 // whose types are simply the backend representation of the Go types.
8425 // If there are multiple results, they are returned as a backend
8426 // struct.
8428 // However, when Go code refers to a function other than simply
8429 // calling it, the backend type of that function is actually a struct.
8430 // The first field of the struct points to the Go function code
8431 // (sometimes a wrapper as described below). The remaining fields
8432 // hold addresses of closed-over variables. This struct is called a
8433 // closure.
8435 // There are a few cases to consider.
8437 // A direct function call of a known function in package scope. In
8438 // this case there are no closed-over variables, and we know the name
8439 // of the function code. We can simply produce a backend call to the
8440 // function directly, and not worry about the closure.
8442 // A direct function call of a known function literal. In this case
8443 // we know the function code and we know the closure. We generate the
8444 // function code such that it expects an additional final argument of
8445 // the closure type. We pass the closure as the last argument, after
8446 // the other arguments.
8448 // An indirect function call. In this case we have a closure. We
8449 // load the pointer to the function code from the first field of the
8450 // closure. We pass the address of the closure as the last argument.
8452 // A call to a method of an interface. Type methods are always at
8453 // package scope, so we call the function directly, and don't worry
8454 // about the closure.
8456 // This means that for a function at package scope we have two cases.
8457 // One is the direct call, which has no closure. The other is the
8458 // indirect call, which does have a closure. We can't simply ignore
8459 // the closure, even though it is the last argument, because that will
8460 // fail on targets where the function pops its arguments. So when
8461 // generating a closure for a package-scope function we set the
8462 // function code pointer in the closure to point to a wrapper
8463 // function. This wrapper function accepts a final argument that
8464 // points to the closure, ignores it, and calls the real function as a
8465 // direct function call. This wrapper will normally be efficient, and
8466 // can often simply be a tail call to the real function.
8468 // We don't use GCC's static chain pointer because 1) we don't need
8469 // it; 2) GCC only permits using a static chain to call a known
8470 // function, so we can't use it for an indirect call anyhow. Since we
8471 // can't use it for an indirect call, we may as well not worry about
8472 // using it for a direct call either.
8474 // We pass the closure last rather than first because it means that
8475 // the function wrapper we put into a closure for a package-scope
8476 // function can normally just be a tail call to the real function.
8478 // For method expressions we generate a wrapper that loads the
8479 // receiver from the closure and then calls the method. This
8480 // unfortunately forces reshuffling the arguments, since there is a
8481 // new first argument, but we can't avoid reshuffling either for
8482 // method expressions or for indirect calls of package-scope
8483 // functions, and since the latter are more common we reshuffle for
8484 // method expressions.
8486 // Note that the Go code retains the Go types. The extra final
8487 // argument only appears when we convert to the backend
8488 // representation.
8490 // Traversal.
8493 Call_expression::do_traverse(Traverse* traverse)
8495 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8496 return TRAVERSE_EXIT;
8497 if (this->args_ != NULL)
8499 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8500 return TRAVERSE_EXIT;
8502 return TRAVERSE_CONTINUE;
8505 // Lower a call statement.
8507 Expression*
8508 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8509 Statement_inserter* inserter, int)
8511 Location loc = this->location();
8513 // A type cast can look like a function call.
8514 if (this->fn_->is_type_expression()
8515 && this->args_ != NULL
8516 && this->args_->size() == 1)
8517 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8518 loc);
8520 // Because do_type will return an error type and thus prevent future
8521 // errors, check for that case now to ensure that the error gets
8522 // reported.
8523 Function_type* fntype = this->get_function_type();
8524 if (fntype == NULL)
8526 if (!this->fn_->type()->is_error())
8527 this->report_error(_("expected function"));
8528 return Expression::make_error(loc);
8531 // Handle an argument which is a call to a function which returns
8532 // multiple results.
8533 if (this->args_ != NULL
8534 && this->args_->size() == 1
8535 && this->args_->front()->call_expression() != NULL)
8537 size_t rc = this->args_->front()->call_expression()->result_count();
8538 if (rc > 1
8539 && ((fntype->parameters() != NULL
8540 && (fntype->parameters()->size() == rc
8541 || (fntype->is_varargs()
8542 && fntype->parameters()->size() - 1 <= rc)))
8543 || fntype->is_builtin()))
8545 Call_expression* call = this->args_->front()->call_expression();
8546 call->set_is_multi_value_arg();
8547 Expression_list* args = new Expression_list;
8548 for (size_t i = 0; i < rc; ++i)
8549 args->push_back(Expression::make_call_result(call, i));
8550 // We can't return a new call expression here, because this
8551 // one may be referenced by Call_result expressions. We
8552 // also can't delete the old arguments, because we may still
8553 // traverse them somewhere up the call stack. FIXME.
8554 this->args_ = args;
8558 // Recognize a call to a builtin function.
8559 if (fntype->is_builtin())
8560 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8561 this->is_varargs_, loc);
8563 // If this call returns multiple results, create a temporary
8564 // variable for each result.
8565 size_t rc = this->result_count();
8566 if (rc > 1 && this->results_ == NULL)
8568 std::vector<Temporary_statement*>* temps =
8569 new std::vector<Temporary_statement*>;
8570 temps->reserve(rc);
8571 const Typed_identifier_list* results = fntype->results();
8572 for (Typed_identifier_list::const_iterator p = results->begin();
8573 p != results->end();
8574 ++p)
8576 Temporary_statement* temp = Statement::make_temporary(p->type(),
8577 NULL, loc);
8578 inserter->insert(temp);
8579 temps->push_back(temp);
8581 this->results_ = temps;
8584 // Handle a call to a varargs function by packaging up the extra
8585 // parameters.
8586 if (fntype->is_varargs())
8588 const Typed_identifier_list* parameters = fntype->parameters();
8589 go_assert(parameters != NULL && !parameters->empty());
8590 Type* varargs_type = parameters->back().type();
8591 this->lower_varargs(gogo, function, inserter, varargs_type,
8592 parameters->size());
8595 // If this is call to a method, call the method directly passing the
8596 // object as the first parameter.
8597 Bound_method_expression* bme = this->fn_->bound_method_expression();
8598 if (bme != NULL)
8600 Named_object* methodfn = bme->function();
8601 Expression* first_arg = bme->first_argument();
8603 // We always pass a pointer when calling a method.
8604 if (first_arg->type()->points_to() == NULL
8605 && !first_arg->type()->is_error())
8607 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8608 // We may need to create a temporary variable so that we can
8609 // take the address. We can't do that here because it will
8610 // mess up the order of evaluation.
8611 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8612 ue->set_create_temp();
8615 // If we are calling a method which was inherited from an
8616 // embedded struct, and the method did not get a stub, then the
8617 // first type may be wrong.
8618 Type* fatype = bme->first_argument_type();
8619 if (fatype != NULL)
8621 if (fatype->points_to() == NULL)
8622 fatype = Type::make_pointer_type(fatype);
8623 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8626 Expression_list* new_args = new Expression_list();
8627 new_args->push_back(first_arg);
8628 if (this->args_ != NULL)
8630 for (Expression_list::const_iterator p = this->args_->begin();
8631 p != this->args_->end();
8632 ++p)
8633 new_args->push_back(*p);
8636 // We have to change in place because this structure may be
8637 // referenced by Call_result_expressions. We can't delete the
8638 // old arguments, because we may be traversing them up in some
8639 // caller. FIXME.
8640 this->args_ = new_args;
8641 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8642 bme->location());
8645 return this;
8648 // Lower a call to a varargs function. FUNCTION is the function in
8649 // which the call occurs--it's not the function we are calling.
8650 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8651 // PARAM_COUNT is the number of parameters of the function we are
8652 // calling; the last of these parameters will be the varargs
8653 // parameter.
8655 void
8656 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8657 Statement_inserter* inserter,
8658 Type* varargs_type, size_t param_count)
8660 if (this->varargs_are_lowered_)
8661 return;
8663 Location loc = this->location();
8665 go_assert(param_count > 0);
8666 go_assert(varargs_type->is_slice_type());
8668 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8669 if (arg_count < param_count - 1)
8671 // Not enough arguments; will be caught in check_types.
8672 return;
8675 Expression_list* old_args = this->args_;
8676 Expression_list* new_args = new Expression_list();
8677 bool push_empty_arg = false;
8678 if (old_args == NULL || old_args->empty())
8680 go_assert(param_count == 1);
8681 push_empty_arg = true;
8683 else
8685 Expression_list::const_iterator pa;
8686 int i = 1;
8687 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8689 if (static_cast<size_t>(i) == param_count)
8690 break;
8691 new_args->push_back(*pa);
8694 // We have reached the varargs parameter.
8696 bool issued_error = false;
8697 if (pa == old_args->end())
8698 push_empty_arg = true;
8699 else if (pa + 1 == old_args->end() && this->is_varargs_)
8700 new_args->push_back(*pa);
8701 else if (this->is_varargs_)
8703 if ((*pa)->type()->is_slice_type())
8704 this->report_error(_("too many arguments"));
8705 else
8707 error_at(this->location(),
8708 _("invalid use of %<...%> with non-slice"));
8709 this->set_is_error();
8711 return;
8713 else
8715 Type* element_type = varargs_type->array_type()->element_type();
8716 Expression_list* vals = new Expression_list;
8717 for (; pa != old_args->end(); ++pa, ++i)
8719 // Check types here so that we get a better message.
8720 Type* patype = (*pa)->type();
8721 Location paloc = (*pa)->location();
8722 if (!this->check_argument_type(i, element_type, patype,
8723 paloc, issued_error))
8724 continue;
8725 vals->push_back(*pa);
8727 Expression* val =
8728 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8729 gogo->lower_expression(function, inserter, &val);
8730 new_args->push_back(val);
8734 if (push_empty_arg)
8735 new_args->push_back(Expression::make_nil(loc));
8737 // We can't return a new call expression here, because this one may
8738 // be referenced by Call_result expressions. FIXME. We can't
8739 // delete OLD_ARGS because we may have both a Call_expression and a
8740 // Builtin_call_expression which refer to them. FIXME.
8741 this->args_ = new_args;
8742 this->varargs_are_lowered_ = true;
8745 // Flatten a call with multiple results into a temporary.
8747 Expression*
8748 Call_expression::do_flatten(Gogo* gogo, Named_object*,
8749 Statement_inserter* inserter)
8751 if (this->classification() == EXPRESSION_ERROR)
8752 return this;
8754 // Add temporary variables for all arguments that require type
8755 // conversion.
8756 Function_type* fntype = this->get_function_type();
8757 if (fntype == NULL)
8759 go_assert(saw_errors());
8760 return this;
8762 if (this->args_ != NULL && !this->args_->empty()
8763 && fntype->parameters() != NULL && !fntype->parameters()->empty())
8765 bool is_interface_method =
8766 this->fn_->interface_field_reference_expression() != NULL;
8768 Expression_list *args = new Expression_list();
8769 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
8770 Expression_list::const_iterator pa = this->args_->begin();
8771 if (!is_interface_method && fntype->is_method())
8773 // The receiver argument.
8774 args->push_back(*pa);
8775 ++pa;
8777 for (; pa != this->args_->end(); ++pa, ++pp)
8779 go_assert(pp != fntype->parameters()->end());
8780 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
8781 args->push_back(*pa);
8782 else
8784 Location loc = (*pa)->location();
8785 Expression* arg =
8786 Expression::convert_for_assignment(gogo, pp->type(), *pa, loc);
8787 Temporary_statement* temp =
8788 Statement::make_temporary(pp->type(), arg, loc);
8789 inserter->insert(temp);
8790 args->push_back(Expression::make_temporary_reference(temp, loc));
8793 delete this->args_;
8794 this->args_ = args;
8797 size_t rc = this->result_count();
8798 if (rc > 1 && this->call_temp_ == NULL)
8800 Struct_field_list* sfl = new Struct_field_list();
8801 Function_type* fntype = this->get_function_type();
8802 const Typed_identifier_list* results = fntype->results();
8803 Location loc = this->location();
8805 int i = 0;
8806 char buf[10];
8807 for (Typed_identifier_list::const_iterator p = results->begin();
8808 p != results->end();
8809 ++p, ++i)
8811 snprintf(buf, sizeof buf, "res%d", i);
8812 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
8815 Struct_type* st = Type::make_struct_type(sfl, loc);
8816 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
8817 inserter->insert(this->call_temp_);
8820 return this;
8823 // Get the function type. This can return NULL in error cases.
8825 Function_type*
8826 Call_expression::get_function_type() const
8828 return this->fn_->type()->function_type();
8831 // Return the number of values which this call will return.
8833 size_t
8834 Call_expression::result_count() const
8836 const Function_type* fntype = this->get_function_type();
8837 if (fntype == NULL)
8838 return 0;
8839 if (fntype->results() == NULL)
8840 return 0;
8841 return fntype->results()->size();
8844 // Return the temporary which holds a result.
8846 Temporary_statement*
8847 Call_expression::result(size_t i) const
8849 if (this->results_ == NULL || this->results_->size() <= i)
8851 go_assert(saw_errors());
8852 return NULL;
8854 return (*this->results_)[i];
8857 // Set the number of results expected from a call expression.
8859 void
8860 Call_expression::set_expected_result_count(size_t count)
8862 go_assert(this->expected_result_count_ == 0);
8863 this->expected_result_count_ = count;
8866 // Return whether this is a call to the predeclared function recover.
8868 bool
8869 Call_expression::is_recover_call() const
8871 return this->do_is_recover_call();
8874 // Set the argument to the recover function.
8876 void
8877 Call_expression::set_recover_arg(Expression* arg)
8879 this->do_set_recover_arg(arg);
8882 // Virtual functions also implemented by Builtin_call_expression.
8884 bool
8885 Call_expression::do_is_recover_call() const
8887 return false;
8890 void
8891 Call_expression::do_set_recover_arg(Expression*)
8893 go_unreachable();
8896 // We have found an error with this call expression; return true if
8897 // we should report it.
8899 bool
8900 Call_expression::issue_error()
8902 if (this->issued_error_)
8903 return false;
8904 else
8906 this->issued_error_ = true;
8907 return true;
8911 // Get the type.
8913 Type*
8914 Call_expression::do_type()
8916 if (this->type_ != NULL)
8917 return this->type_;
8919 Type* ret;
8920 Function_type* fntype = this->get_function_type();
8921 if (fntype == NULL)
8922 return Type::make_error_type();
8924 const Typed_identifier_list* results = fntype->results();
8925 if (results == NULL)
8926 ret = Type::make_void_type();
8927 else if (results->size() == 1)
8928 ret = results->begin()->type();
8929 else
8930 ret = Type::make_call_multiple_result_type(this);
8932 this->type_ = ret;
8934 return this->type_;
8937 // Determine types for a call expression. We can use the function
8938 // parameter types to set the types of the arguments.
8940 void
8941 Call_expression::do_determine_type(const Type_context*)
8943 if (!this->determining_types())
8944 return;
8946 this->fn_->determine_type_no_context();
8947 Function_type* fntype = this->get_function_type();
8948 const Typed_identifier_list* parameters = NULL;
8949 if (fntype != NULL)
8950 parameters = fntype->parameters();
8951 if (this->args_ != NULL)
8953 Typed_identifier_list::const_iterator pt;
8954 if (parameters != NULL)
8955 pt = parameters->begin();
8956 bool first = true;
8957 for (Expression_list::const_iterator pa = this->args_->begin();
8958 pa != this->args_->end();
8959 ++pa)
8961 if (first)
8963 first = false;
8964 // If this is a method, the first argument is the
8965 // receiver.
8966 if (fntype != NULL && fntype->is_method())
8968 Type* rtype = fntype->receiver()->type();
8969 // The receiver is always passed as a pointer.
8970 if (rtype->points_to() == NULL)
8971 rtype = Type::make_pointer_type(rtype);
8972 Type_context subcontext(rtype, false);
8973 (*pa)->determine_type(&subcontext);
8974 continue;
8978 if (parameters != NULL && pt != parameters->end())
8980 Type_context subcontext(pt->type(), false);
8981 (*pa)->determine_type(&subcontext);
8982 ++pt;
8984 else
8985 (*pa)->determine_type_no_context();
8990 // Called when determining types for a Call_expression. Return true
8991 // if we should go ahead, false if they have already been determined.
8993 bool
8994 Call_expression::determining_types()
8996 if (this->types_are_determined_)
8997 return false;
8998 else
9000 this->types_are_determined_ = true;
9001 return true;
9005 // Check types for parameter I.
9007 bool
9008 Call_expression::check_argument_type(int i, const Type* parameter_type,
9009 const Type* argument_type,
9010 Location argument_location,
9011 bool issued_error)
9013 std::string reason;
9014 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9016 if (!issued_error)
9018 if (reason.empty())
9019 error_at(argument_location, "argument %d has incompatible type", i);
9020 else
9021 error_at(argument_location,
9022 "argument %d has incompatible type (%s)",
9023 i, reason.c_str());
9025 this->set_is_error();
9026 return false;
9028 return true;
9031 // Check types.
9033 void
9034 Call_expression::do_check_types(Gogo*)
9036 if (this->classification() == EXPRESSION_ERROR)
9037 return;
9039 Function_type* fntype = this->get_function_type();
9040 if (fntype == NULL)
9042 if (!this->fn_->type()->is_error())
9043 this->report_error(_("expected function"));
9044 return;
9047 if (this->expected_result_count_ != 0
9048 && this->expected_result_count_ != this->result_count())
9050 if (this->issue_error())
9051 this->report_error(_("function result count mismatch"));
9052 this->set_is_error();
9053 return;
9056 bool is_method = fntype->is_method();
9057 if (is_method)
9059 go_assert(this->args_ != NULL && !this->args_->empty());
9060 Type* rtype = fntype->receiver()->type();
9061 Expression* first_arg = this->args_->front();
9062 // We dereference the values since receivers are always passed
9063 // as pointers.
9064 std::string reason;
9065 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9066 &reason))
9068 if (reason.empty())
9069 this->report_error(_("incompatible type for receiver"));
9070 else
9072 error_at(this->location(),
9073 "incompatible type for receiver (%s)",
9074 reason.c_str());
9075 this->set_is_error();
9080 // Note that varargs was handled by the lower_varargs() method, so
9081 // we don't have to worry about it here unless something is wrong.
9082 if (this->is_varargs_ && !this->varargs_are_lowered_)
9084 if (!fntype->is_varargs())
9086 error_at(this->location(),
9087 _("invalid use of %<...%> calling non-variadic function"));
9088 this->set_is_error();
9089 return;
9093 const Typed_identifier_list* parameters = fntype->parameters();
9094 if (this->args_ == NULL)
9096 if (parameters != NULL && !parameters->empty())
9097 this->report_error(_("not enough arguments"));
9099 else if (parameters == NULL)
9101 if (!is_method || this->args_->size() > 1)
9102 this->report_error(_("too many arguments"));
9104 else if (this->args_->size() == 1
9105 && this->args_->front()->call_expression() != NULL
9106 && this->args_->front()->call_expression()->result_count() > 1)
9108 // This is F(G()) when G returns more than one result. If the
9109 // results can be matched to parameters, it would have been
9110 // lowered in do_lower. If we get here we know there is a
9111 // mismatch.
9112 if (this->args_->front()->call_expression()->result_count()
9113 < parameters->size())
9114 this->report_error(_("not enough arguments"));
9115 else
9116 this->report_error(_("too many arguments"));
9118 else
9120 int i = 0;
9121 Expression_list::const_iterator pa = this->args_->begin();
9122 if (is_method)
9123 ++pa;
9124 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9125 pt != parameters->end();
9126 ++pt, ++pa, ++i)
9128 if (pa == this->args_->end())
9130 this->report_error(_("not enough arguments"));
9131 return;
9133 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9134 (*pa)->location(), false);
9136 if (pa != this->args_->end())
9137 this->report_error(_("too many arguments"));
9141 Expression*
9142 Call_expression::do_copy()
9144 Call_expression* call =
9145 Expression::make_call(this->fn_->copy(),
9146 (this->args_ == NULL
9147 ? NULL
9148 : this->args_->copy()),
9149 this->is_varargs_, this->location());
9151 if (this->varargs_are_lowered_)
9152 call->set_varargs_are_lowered();
9153 return call;
9156 // Return whether we have to use a temporary variable to ensure that
9157 // we evaluate this call expression in order. If the call returns no
9158 // results then it will inevitably be executed last.
9160 bool
9161 Call_expression::do_must_eval_in_order() const
9163 return this->result_count() > 0;
9166 // Get the function and the first argument to use when calling an
9167 // interface method.
9169 Expression*
9170 Call_expression::interface_method_function(
9171 Interface_field_reference_expression* interface_method,
9172 Expression** first_arg_ptr)
9174 *first_arg_ptr = interface_method->get_underlying_object();
9175 return interface_method->get_function();
9178 // Build the call expression.
9180 Bexpression*
9181 Call_expression::do_get_backend(Translate_context* context)
9183 if (this->call_ != NULL)
9184 return this->call_;
9186 Function_type* fntype = this->get_function_type();
9187 if (fntype == NULL)
9188 return context->backend()->error_expression();
9190 if (this->fn_->is_error_expression())
9191 return context->backend()->error_expression();
9193 Gogo* gogo = context->gogo();
9194 Location location = this->location();
9196 Func_expression* func = this->fn_->func_expression();
9197 Interface_field_reference_expression* interface_method =
9198 this->fn_->interface_field_reference_expression();
9199 const bool has_closure = func != NULL && func->closure() != NULL;
9200 const bool is_interface_method = interface_method != NULL;
9202 bool has_closure_arg;
9203 if (has_closure)
9204 has_closure_arg = true;
9205 else if (func != NULL)
9206 has_closure_arg = false;
9207 else if (is_interface_method)
9208 has_closure_arg = false;
9209 else
9210 has_closure_arg = true;
9212 int nargs;
9213 std::vector<Bexpression*> fn_args;
9214 if (this->args_ == NULL || this->args_->empty())
9216 nargs = is_interface_method ? 1 : 0;
9217 if (nargs > 0)
9218 fn_args.resize(1);
9220 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9222 // Passing a receiver parameter.
9223 go_assert(!is_interface_method
9224 && fntype->is_method()
9225 && this->args_->size() == 1);
9226 nargs = 1;
9227 fn_args.resize(1);
9228 fn_args[0] = this->args_->front()->get_backend(context);
9230 else
9232 const Typed_identifier_list* params = fntype->parameters();
9234 nargs = this->args_->size();
9235 int i = is_interface_method ? 1 : 0;
9236 nargs += i;
9237 fn_args.resize(nargs);
9239 Typed_identifier_list::const_iterator pp = params->begin();
9240 Expression_list::const_iterator pe = this->args_->begin();
9241 if (!is_interface_method && fntype->is_method())
9243 fn_args[i] = (*pe)->get_backend(context);
9244 ++pe;
9245 ++i;
9247 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9249 go_assert(pp != params->end());
9250 Expression* arg =
9251 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9252 location);
9253 fn_args[i] = arg->get_backend(context);
9255 go_assert(pp == params->end());
9256 go_assert(i == nargs);
9259 Expression* fn;
9260 Expression* closure = NULL;
9261 if (func != NULL)
9263 Named_object* no = func->named_object();
9264 fn = Expression::make_func_code_reference(no, location);
9265 if (has_closure)
9266 closure = func->closure();
9268 else if (!is_interface_method)
9270 closure = this->fn_;
9272 // The backend representation of this function type is a pointer
9273 // to a struct whose first field is the actual function to call.
9274 Type* pfntype =
9275 Type::make_pointer_type(
9276 Type::make_pointer_type(Type::make_void_type()));
9277 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9278 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9280 else
9282 Expression* first_arg;
9283 fn = this->interface_method_function(interface_method, &first_arg);
9284 fn_args[0] = first_arg->get_backend(context);
9287 if (!has_closure_arg)
9288 go_assert(closure == NULL);
9289 else
9291 // Pass the closure argument by calling the function function
9292 // __go_set_closure. In the order_evaluations pass we have
9293 // ensured that if any parameters contain call expressions, they
9294 // will have been moved out to temporary variables.
9295 go_assert(closure != NULL);
9296 Expression* set_closure =
9297 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9298 fn = Expression::make_compound(set_closure, fn, location);
9301 Bexpression* bfn = fn->get_backend(context);
9303 // When not calling a named function directly, use a type conversion
9304 // in case the type of the function is a recursive type which refers
9305 // to itself. We don't do this for an interface method because 1)
9306 // an interface method never refers to itself, so we always have a
9307 // function type here; 2) we pass an extra first argument to an
9308 // interface method, so fntype is not correct.
9309 if (func == NULL && !is_interface_method)
9311 Btype* bft = fntype->get_backend_fntype(gogo);
9312 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9315 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
9317 if (this->results_ != NULL)
9319 go_assert(this->call_temp_ != NULL);
9320 Expression* call_ref =
9321 Expression::make_temporary_reference(this->call_temp_, location);
9322 Bexpression* bcall_ref = call_ref->get_backend(context);
9323 Bstatement* assn_stmt =
9324 gogo->backend()->assignment_statement(bcall_ref, call, location);
9326 this->call_ = this->set_results(context, bcall_ref);
9328 Bexpression* set_and_call =
9329 gogo->backend()->compound_expression(assn_stmt, this->call_,
9330 location);
9331 return set_and_call;
9334 this->call_ = call;
9335 return this->call_;
9338 // Set the result variables if this call returns multiple results.
9340 Bexpression*
9341 Call_expression::set_results(Translate_context* context, Bexpression* call)
9343 Gogo* gogo = context->gogo();
9345 Bexpression* results = NULL;
9346 Location loc = this->location();
9348 size_t rc = this->result_count();
9349 for (size_t i = 0; i < rc; ++i)
9351 Temporary_statement* temp = this->result(i);
9352 if (temp == NULL)
9354 go_assert(saw_errors());
9355 return gogo->backend()->error_expression();
9357 Temporary_reference_expression* ref =
9358 Expression::make_temporary_reference(temp, loc);
9359 ref->set_is_lvalue();
9361 Bexpression* result_ref = ref->get_backend(context);
9362 Bexpression* call_result =
9363 gogo->backend()->struct_field_expression(call, i, loc);
9364 Bstatement* assn_stmt =
9365 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9367 Bexpression* result =
9368 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9370 if (results == NULL)
9371 results = result;
9372 else
9374 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9375 results =
9376 gogo->backend()->compound_expression(expr_stmt, results, loc);
9379 return results;
9382 // Dump ast representation for a call expressin.
9384 void
9385 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9387 this->fn_->dump_expression(ast_dump_context);
9388 ast_dump_context->ostream() << "(";
9389 if (args_ != NULL)
9390 ast_dump_context->dump_expression_list(this->args_);
9392 ast_dump_context->ostream() << ") ";
9395 // Make a call expression.
9397 Call_expression*
9398 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9399 Location location)
9401 return new Call_expression(fn, args, is_varargs, location);
9404 // A single result from a call which returns multiple results.
9406 class Call_result_expression : public Expression
9408 public:
9409 Call_result_expression(Call_expression* call, unsigned int index)
9410 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9411 call_(call), index_(index)
9414 protected:
9416 do_traverse(Traverse*);
9418 Type*
9419 do_type();
9421 void
9422 do_determine_type(const Type_context*);
9424 void
9425 do_check_types(Gogo*);
9427 Expression*
9428 do_copy()
9430 return new Call_result_expression(this->call_->call_expression(),
9431 this->index_);
9434 bool
9435 do_must_eval_in_order() const
9436 { return true; }
9438 Bexpression*
9439 do_get_backend(Translate_context*);
9441 void
9442 do_dump_expression(Ast_dump_context*) const;
9444 private:
9445 // The underlying call expression.
9446 Expression* call_;
9447 // Which result we want.
9448 unsigned int index_;
9451 // Traverse a call result.
9454 Call_result_expression::do_traverse(Traverse* traverse)
9456 if (traverse->remember_expression(this->call_))
9458 // We have already traversed the call expression.
9459 return TRAVERSE_CONTINUE;
9461 return Expression::traverse(&this->call_, traverse);
9464 // Get the type.
9466 Type*
9467 Call_result_expression::do_type()
9469 if (this->classification() == EXPRESSION_ERROR)
9470 return Type::make_error_type();
9472 // THIS->CALL_ can be replaced with a temporary reference due to
9473 // Call_expression::do_must_eval_in_order when there is an error.
9474 Call_expression* ce = this->call_->call_expression();
9475 if (ce == NULL)
9477 this->set_is_error();
9478 return Type::make_error_type();
9480 Function_type* fntype = ce->get_function_type();
9481 if (fntype == NULL)
9483 if (ce->issue_error())
9485 if (!ce->fn()->type()->is_error())
9486 this->report_error(_("expected function"));
9488 this->set_is_error();
9489 return Type::make_error_type();
9491 const Typed_identifier_list* results = fntype->results();
9492 if (results == NULL || results->size() < 2)
9494 if (ce->issue_error())
9495 this->report_error(_("number of results does not match "
9496 "number of values"));
9497 return Type::make_error_type();
9499 Typed_identifier_list::const_iterator pr = results->begin();
9500 for (unsigned int i = 0; i < this->index_; ++i)
9502 if (pr == results->end())
9503 break;
9504 ++pr;
9506 if (pr == results->end())
9508 if (ce->issue_error())
9509 this->report_error(_("number of results does not match "
9510 "number of values"));
9511 return Type::make_error_type();
9513 return pr->type();
9516 // Check the type. Just make sure that we trigger the warning in
9517 // do_type.
9519 void
9520 Call_result_expression::do_check_types(Gogo*)
9522 this->type();
9525 // Determine the type. We have nothing to do here, but the 0 result
9526 // needs to pass down to the caller.
9528 void
9529 Call_result_expression::do_determine_type(const Type_context*)
9531 this->call_->determine_type_no_context();
9534 // Return the backend representation. We just refer to the temporary set by the
9535 // call expression. We don't do this at lowering time because it makes it
9536 // hard to evaluate the call at the right time.
9538 Bexpression*
9539 Call_result_expression::do_get_backend(Translate_context* context)
9541 Call_expression* ce = this->call_->call_expression();
9542 if (ce == NULL)
9544 go_assert(this->call_->is_error_expression());
9545 return context->backend()->error_expression();
9547 Temporary_statement* ts = ce->result(this->index_);
9548 if (ts == NULL)
9550 go_assert(saw_errors());
9551 return context->backend()->error_expression();
9553 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9554 return ref->get_backend(context);
9557 // Dump ast representation for a call result expression.
9559 void
9560 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9561 const
9563 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9564 // (struct) and the fields are referenced instead.
9565 ast_dump_context->ostream() << this->index_ << "@(";
9566 ast_dump_context->dump_expression(this->call_);
9567 ast_dump_context->ostream() << ")";
9570 // Make a reference to a single result of a call which returns
9571 // multiple results.
9573 Expression*
9574 Expression::make_call_result(Call_expression* call, unsigned int index)
9576 return new Call_result_expression(call, index);
9579 // Class Index_expression.
9581 // Traversal.
9584 Index_expression::do_traverse(Traverse* traverse)
9586 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9587 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9588 || (this->end_ != NULL
9589 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9590 || (this->cap_ != NULL
9591 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9592 return TRAVERSE_EXIT;
9593 return TRAVERSE_CONTINUE;
9596 // Lower an index expression. This converts the generic index
9597 // expression into an array index, a string index, or a map index.
9599 Expression*
9600 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9602 Location location = this->location();
9603 Expression* left = this->left_;
9604 Expression* start = this->start_;
9605 Expression* end = this->end_;
9606 Expression* cap = this->cap_;
9608 Type* type = left->type();
9609 if (type->is_error())
9611 go_assert(saw_errors());
9612 return Expression::make_error(location);
9614 else if (left->is_type_expression())
9616 error_at(location, "attempt to index type expression");
9617 return Expression::make_error(location);
9619 else if (type->array_type() != NULL)
9620 return Expression::make_array_index(left, start, end, cap, location);
9621 else if (type->points_to() != NULL
9622 && type->points_to()->array_type() != NULL
9623 && !type->points_to()->is_slice_type())
9625 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9626 location);
9628 // For an ordinary index into the array, the pointer will be
9629 // dereferenced. For a slice it will not--the resulting slice
9630 // will simply reuse the pointer, which is incorrect if that
9631 // pointer is nil.
9632 if (end != NULL || cap != NULL)
9633 deref->issue_nil_check();
9635 return Expression::make_array_index(deref, start, end, cap, location);
9637 else if (type->is_string_type())
9639 if (cap != NULL)
9641 error_at(location, "invalid 3-index slice of string");
9642 return Expression::make_error(location);
9644 return Expression::make_string_index(left, start, end, location);
9646 else if (type->map_type() != NULL)
9648 if (end != NULL || cap != NULL)
9650 error_at(location, "invalid slice of map");
9651 return Expression::make_error(location);
9653 Map_index_expression* ret = Expression::make_map_index(left, start,
9654 location);
9655 if (this->is_lvalue_)
9656 ret->set_is_lvalue();
9657 return ret;
9659 else
9661 error_at(location,
9662 "attempt to index object which is not array, string, or map");
9663 return Expression::make_error(location);
9667 // Write an indexed expression
9668 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9670 void
9671 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9672 const Expression* expr,
9673 const Expression* start,
9674 const Expression* end,
9675 const Expression* cap)
9677 expr->dump_expression(ast_dump_context);
9678 ast_dump_context->ostream() << "[";
9679 start->dump_expression(ast_dump_context);
9680 if (end != NULL)
9682 ast_dump_context->ostream() << ":";
9683 end->dump_expression(ast_dump_context);
9685 if (cap != NULL)
9687 ast_dump_context->ostream() << ":";
9688 cap->dump_expression(ast_dump_context);
9690 ast_dump_context->ostream() << "]";
9693 // Dump ast representation for an index expression.
9695 void
9696 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9697 const
9699 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9700 this->start_, this->end_, this->cap_);
9703 // Make an index expression.
9705 Expression*
9706 Expression::make_index(Expression* left, Expression* start, Expression* end,
9707 Expression* cap, Location location)
9709 return new Index_expression(left, start, end, cap, location);
9712 // An array index. This is used for both indexing and slicing.
9714 class Array_index_expression : public Expression
9716 public:
9717 Array_index_expression(Expression* array, Expression* start,
9718 Expression* end, Expression* cap, Location location)
9719 : Expression(EXPRESSION_ARRAY_INDEX, location),
9720 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
9723 protected:
9725 do_traverse(Traverse*);
9727 Expression*
9728 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9730 Type*
9731 do_type();
9733 void
9734 do_determine_type(const Type_context*);
9736 void
9737 do_check_types(Gogo*);
9739 Expression*
9740 do_copy()
9742 return Expression::make_array_index(this->array_->copy(),
9743 this->start_->copy(),
9744 (this->end_ == NULL
9745 ? NULL
9746 : this->end_->copy()),
9747 (this->cap_ == NULL
9748 ? NULL
9749 : this->cap_->copy()),
9750 this->location());
9753 bool
9754 do_must_eval_subexpressions_in_order(int* skip) const
9756 *skip = 1;
9757 return true;
9760 bool
9761 do_is_addressable() const;
9763 void
9764 do_address_taken(bool escapes)
9765 { this->array_->address_taken(escapes); }
9767 void
9768 do_issue_nil_check()
9769 { this->array_->issue_nil_check(); }
9771 Bexpression*
9772 do_get_backend(Translate_context*);
9774 void
9775 do_dump_expression(Ast_dump_context*) const;
9777 private:
9778 // The array we are getting a value from.
9779 Expression* array_;
9780 // The start or only index.
9781 Expression* start_;
9782 // The end index of a slice. This may be NULL for a simple array
9783 // index, or it may be a nil expression for the length of the array.
9784 Expression* end_;
9785 // The capacity argument of a slice. This may be NULL for an array index or
9786 // slice.
9787 Expression* cap_;
9788 // The type of the expression.
9789 Type* type_;
9792 // Array index traversal.
9795 Array_index_expression::do_traverse(Traverse* traverse)
9797 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9798 return TRAVERSE_EXIT;
9799 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9800 return TRAVERSE_EXIT;
9801 if (this->end_ != NULL)
9803 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9804 return TRAVERSE_EXIT;
9806 if (this->cap_ != NULL)
9808 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9809 return TRAVERSE_EXIT;
9811 return TRAVERSE_CONTINUE;
9814 // Return the type of an array index.
9816 Type*
9817 Array_index_expression::do_type()
9819 if (this->type_ == NULL)
9821 Array_type* type = this->array_->type()->array_type();
9822 if (type == NULL)
9823 this->type_ = Type::make_error_type();
9824 else if (this->end_ == NULL)
9825 this->type_ = type->element_type();
9826 else if (type->is_slice_type())
9828 // A slice of a slice has the same type as the original
9829 // slice.
9830 this->type_ = this->array_->type()->deref();
9832 else
9834 // A slice of an array is a slice.
9835 this->type_ = Type::make_array_type(type->element_type(), NULL);
9838 return this->type_;
9841 // Set the type of an array index.
9843 void
9844 Array_index_expression::do_determine_type(const Type_context*)
9846 this->array_->determine_type_no_context();
9847 this->start_->determine_type_no_context();
9848 if (this->end_ != NULL)
9849 this->end_->determine_type_no_context();
9850 if (this->cap_ != NULL)
9851 this->cap_->determine_type_no_context();
9854 // Check types of an array index.
9856 void
9857 Array_index_expression::do_check_types(Gogo*)
9859 Numeric_constant nc;
9860 unsigned long v;
9861 if (this->start_->type()->integer_type() == NULL
9862 && !this->start_->type()->is_error()
9863 && (!this->start_->numeric_constant_value(&nc)
9864 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9865 this->report_error(_("index must be integer"));
9866 if (this->end_ != NULL
9867 && this->end_->type()->integer_type() == NULL
9868 && !this->end_->type()->is_error()
9869 && !this->end_->is_nil_expression()
9870 && !this->end_->is_error_expression()
9871 && (!this->end_->numeric_constant_value(&nc)
9872 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9873 this->report_error(_("slice end must be integer"));
9874 if (this->cap_ != NULL
9875 && this->cap_->type()->integer_type() == NULL
9876 && !this->cap_->type()->is_error()
9877 && !this->cap_->is_nil_expression()
9878 && !this->cap_->is_error_expression()
9879 && (!this->cap_->numeric_constant_value(&nc)
9880 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9881 this->report_error(_("slice capacity must be integer"));
9883 Array_type* array_type = this->array_->type()->array_type();
9884 if (array_type == NULL)
9886 go_assert(this->array_->type()->is_error());
9887 return;
9890 unsigned int int_bits =
9891 Type::lookup_integer_type("int")->integer_type()->bits();
9893 Numeric_constant lvalnc;
9894 mpz_t lval;
9895 bool lval_valid = (array_type->length() != NULL
9896 && array_type->length()->numeric_constant_value(&lvalnc)
9897 && lvalnc.to_int(&lval));
9898 Numeric_constant inc;
9899 mpz_t ival;
9900 bool ival_valid = false;
9901 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9903 ival_valid = true;
9904 if (mpz_sgn(ival) < 0
9905 || mpz_sizeinbase(ival, 2) >= int_bits
9906 || (lval_valid
9907 && (this->end_ == NULL
9908 ? mpz_cmp(ival, lval) >= 0
9909 : mpz_cmp(ival, lval) > 0)))
9911 error_at(this->start_->location(), "array index out of bounds");
9912 this->set_is_error();
9915 if (this->end_ != NULL && !this->end_->is_nil_expression())
9917 Numeric_constant enc;
9918 mpz_t eval;
9919 bool eval_valid = false;
9920 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9922 eval_valid = true;
9923 if (mpz_sgn(eval) < 0
9924 || mpz_sizeinbase(eval, 2) >= int_bits
9925 || (lval_valid && mpz_cmp(eval, lval) > 0))
9927 error_at(this->end_->location(), "array index out of bounds");
9928 this->set_is_error();
9930 else if (ival_valid && mpz_cmp(ival, eval) > 0)
9931 this->report_error(_("inverted slice range"));
9934 Numeric_constant cnc;
9935 mpz_t cval;
9936 if (this->cap_ != NULL
9937 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
9939 if (mpz_sgn(cval) < 0
9940 || mpz_sizeinbase(cval, 2) >= int_bits
9941 || (lval_valid && mpz_cmp(cval, lval) > 0))
9943 error_at(this->cap_->location(), "array index out of bounds");
9944 this->set_is_error();
9946 else if (ival_valid && mpz_cmp(ival, cval) > 0)
9948 error_at(this->cap_->location(),
9949 "invalid slice index: capacity less than start");
9950 this->set_is_error();
9952 else if (eval_valid && mpz_cmp(eval, cval) > 0)
9954 error_at(this->cap_->location(),
9955 "invalid slice index: capacity less than length");
9956 this->set_is_error();
9958 mpz_clear(cval);
9961 if (eval_valid)
9962 mpz_clear(eval);
9964 if (ival_valid)
9965 mpz_clear(ival);
9966 if (lval_valid)
9967 mpz_clear(lval);
9969 // A slice of an array requires an addressable array. A slice of a
9970 // slice is always possible.
9971 if (this->end_ != NULL && !array_type->is_slice_type())
9973 if (!this->array_->is_addressable())
9974 this->report_error(_("slice of unaddressable value"));
9975 else
9976 this->array_->address_taken(true);
9980 // Flatten array indexing by using temporary variables for slices and indexes.
9982 Expression*
9983 Array_index_expression::do_flatten(Gogo*, Named_object*,
9984 Statement_inserter* inserter)
9986 Location loc = this->location();
9987 Temporary_statement* temp;
9988 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
9990 temp = Statement::make_temporary(NULL, this->array_, loc);
9991 inserter->insert(temp);
9992 this->array_ = Expression::make_temporary_reference(temp, loc);
9994 if (!this->start_->is_variable())
9996 temp = Statement::make_temporary(NULL, this->start_, loc);
9997 inserter->insert(temp);
9998 this->start_ = Expression::make_temporary_reference(temp, loc);
10000 if (this->end_ != NULL
10001 && !this->end_->is_nil_expression()
10002 && !this->end_->is_variable())
10004 temp = Statement::make_temporary(NULL, this->end_, loc);
10005 inserter->insert(temp);
10006 this->end_ = Expression::make_temporary_reference(temp, loc);
10008 if (this->cap_ != NULL && !this->cap_->is_variable())
10010 temp = Statement::make_temporary(NULL, this->cap_, loc);
10011 inserter->insert(temp);
10012 this->cap_ = Expression::make_temporary_reference(temp, loc);
10015 return this;
10018 // Return whether this expression is addressable.
10020 bool
10021 Array_index_expression::do_is_addressable() const
10023 // A slice expression is not addressable.
10024 if (this->end_ != NULL)
10025 return false;
10027 // An index into a slice is addressable.
10028 if (this->array_->type()->is_slice_type())
10029 return true;
10031 // An index into an array is addressable if the array is
10032 // addressable.
10033 return this->array_->is_addressable();
10036 // Get the backend representation for an array index.
10038 Bexpression*
10039 Array_index_expression::do_get_backend(Translate_context* context)
10041 Array_type* array_type = this->array_->type()->array_type();
10042 if (array_type == NULL)
10044 go_assert(this->array_->type()->is_error());
10045 return context->backend()->error_expression();
10047 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10049 Location loc = this->location();
10050 Gogo* gogo = context->gogo();
10052 Type* int_type = Type::lookup_integer_type("int");
10053 Btype* int_btype = int_type->get_backend(gogo);
10055 // We need to convert the length and capacity to the Go "int" type here
10056 // because the length of a fixed-length array could be of type "uintptr"
10057 // and gimple disallows binary operations between "uintptr" and other
10058 // integer types. FIXME.
10059 Bexpression* length = NULL;
10060 if (this->end_ == NULL || this->end_->is_nil_expression())
10062 Expression* len = array_type->get_length(gogo, this->array_);
10063 length = len->get_backend(context);
10064 length = gogo->backend()->convert_expression(int_btype, length, loc);
10067 Bexpression* capacity = NULL;
10068 if (this->end_ != NULL)
10070 Expression* cap = array_type->get_capacity(gogo, this->array_);
10071 capacity = cap->get_backend(context);
10072 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10075 Bexpression* cap_arg = capacity;
10076 if (this->cap_ != NULL)
10078 cap_arg = this->cap_->get_backend(context);
10079 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10082 if (length == NULL)
10083 length = cap_arg;
10085 int code = (array_type->length() != NULL
10086 ? (this->end_ == NULL
10087 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10088 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10089 : (this->end_ == NULL
10090 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10091 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10092 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10094 if (this->start_->type()->integer_type() == NULL
10095 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10097 go_assert(saw_errors());
10098 return context->backend()->error_expression();
10101 Bexpression* bad_index =
10102 Expression::check_bounds(this->start_, loc)->get_backend(context);
10104 Bexpression* start = this->start_->get_backend(context);
10105 start = gogo->backend()->convert_expression(int_btype, start, loc);
10106 Bexpression* start_too_large =
10107 gogo->backend()->binary_expression((this->end_ == NULL
10108 ? OPERATOR_GE
10109 : OPERATOR_GT),
10110 start,
10111 (this->end_ == NULL
10112 ? length
10113 : capacity),
10114 loc);
10115 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10116 bad_index, loc);
10118 if (this->end_ == NULL)
10120 // Simple array indexing. This has to return an l-value, so
10121 // wrap the index check into START.
10122 start =
10123 gogo->backend()->conditional_expression(int_btype, bad_index,
10124 crash, start, loc);
10126 Bexpression* ret;
10127 if (array_type->length() != NULL)
10129 Bexpression* array = this->array_->get_backend(context);
10130 ret = gogo->backend()->array_index_expression(array, start, loc);
10132 else
10134 // Slice.
10135 Expression* valptr =
10136 array_type->get_value_pointer(gogo, this->array_);
10137 Bexpression* ptr = valptr->get_backend(context);
10138 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10140 Type* ele_type = this->array_->type()->array_type()->element_type();
10141 Btype* ele_btype = ele_type->get_backend(gogo);
10142 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10144 return ret;
10147 // Array slice.
10149 if (this->cap_ != NULL)
10151 Bexpression* bounds_bcheck =
10152 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10153 bad_index =
10154 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10155 bad_index, loc);
10156 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10158 Bexpression* cap_too_small =
10159 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10160 Bexpression* cap_too_large =
10161 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10162 Bexpression* bad_cap =
10163 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10164 cap_too_large, loc);
10165 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10166 bad_index, loc);
10169 Bexpression* end;
10170 if (this->end_->is_nil_expression())
10171 end = length;
10172 else
10174 Bexpression* bounds_bcheck =
10175 Expression::check_bounds(this->end_, loc)->get_backend(context);
10177 bad_index =
10178 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10179 bad_index, loc);
10181 end = this->end_->get_backend(context);
10182 end = gogo->backend()->convert_expression(int_btype, end, loc);
10183 Bexpression* end_too_small =
10184 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10185 Bexpression* end_too_large =
10186 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10187 Bexpression* bad_end =
10188 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10189 end_too_large, loc);
10190 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10191 bad_index, loc);
10194 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10195 Bexpression* val = valptr->get_backend(context);
10196 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10198 Bexpression* result_length =
10199 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10201 Bexpression* result_capacity =
10202 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10204 Btype* struct_btype = this->type()->get_backend(gogo);
10205 std::vector<Bexpression*> init;
10206 init.push_back(val);
10207 init.push_back(result_length);
10208 init.push_back(result_capacity);
10210 Bexpression* ctor =
10211 gogo->backend()->constructor_expression(struct_btype, init, loc);
10212 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10213 crash, ctor, loc);
10216 // Dump ast representation for an array index expression.
10218 void
10219 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10220 const
10222 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10223 this->start_, this->end_, this->cap_);
10226 // Make an array index expression. END and CAP may be NULL.
10228 Expression*
10229 Expression::make_array_index(Expression* array, Expression* start,
10230 Expression* end, Expression* cap,
10231 Location location)
10233 return new Array_index_expression(array, start, end, cap, location);
10236 // A string index. This is used for both indexing and slicing.
10238 class String_index_expression : public Expression
10240 public:
10241 String_index_expression(Expression* string, Expression* start,
10242 Expression* end, Location location)
10243 : Expression(EXPRESSION_STRING_INDEX, location),
10244 string_(string), start_(start), end_(end)
10247 protected:
10249 do_traverse(Traverse*);
10251 Expression*
10252 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10254 Type*
10255 do_type();
10257 void
10258 do_determine_type(const Type_context*);
10260 void
10261 do_check_types(Gogo*);
10263 Expression*
10264 do_copy()
10266 return Expression::make_string_index(this->string_->copy(),
10267 this->start_->copy(),
10268 (this->end_ == NULL
10269 ? NULL
10270 : this->end_->copy()),
10271 this->location());
10274 bool
10275 do_must_eval_subexpressions_in_order(int* skip) const
10277 *skip = 1;
10278 return true;
10281 Bexpression*
10282 do_get_backend(Translate_context*);
10284 void
10285 do_dump_expression(Ast_dump_context*) const;
10287 private:
10288 // The string we are getting a value from.
10289 Expression* string_;
10290 // The start or only index.
10291 Expression* start_;
10292 // The end index of a slice. This may be NULL for a single index,
10293 // or it may be a nil expression for the length of the string.
10294 Expression* end_;
10297 // String index traversal.
10300 String_index_expression::do_traverse(Traverse* traverse)
10302 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10303 return TRAVERSE_EXIT;
10304 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10305 return TRAVERSE_EXIT;
10306 if (this->end_ != NULL)
10308 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10309 return TRAVERSE_EXIT;
10311 return TRAVERSE_CONTINUE;
10314 Expression*
10315 String_index_expression::do_flatten(Gogo*, Named_object*,
10316 Statement_inserter* inserter)
10318 Temporary_statement* temp;
10319 Location loc = this->location();
10320 if (!this->string_->is_variable())
10322 temp = Statement::make_temporary(NULL, this->string_, loc);
10323 inserter->insert(temp);
10324 this->string_ = Expression::make_temporary_reference(temp, loc);
10326 if (!this->start_->is_variable())
10328 temp = Statement::make_temporary(NULL, this->start_, loc);
10329 inserter->insert(temp);
10330 this->start_ = Expression::make_temporary_reference(temp, loc);
10332 if (this->end_ != NULL
10333 && !this->end_->is_nil_expression()
10334 && !this->end_->is_variable())
10336 temp = Statement::make_temporary(NULL, this->end_, loc);
10337 inserter->insert(temp);
10338 this->end_ = Expression::make_temporary_reference(temp, loc);
10341 return this;
10344 // Return the type of a string index.
10346 Type*
10347 String_index_expression::do_type()
10349 if (this->end_ == NULL)
10350 return Type::lookup_integer_type("uint8");
10351 else
10352 return this->string_->type();
10355 // Determine the type of a string index.
10357 void
10358 String_index_expression::do_determine_type(const Type_context*)
10360 this->string_->determine_type_no_context();
10361 this->start_->determine_type_no_context();
10362 if (this->end_ != NULL)
10363 this->end_->determine_type_no_context();
10366 // Check types of a string index.
10368 void
10369 String_index_expression::do_check_types(Gogo*)
10371 Numeric_constant nc;
10372 unsigned long v;
10373 if (this->start_->type()->integer_type() == NULL
10374 && !this->start_->type()->is_error()
10375 && (!this->start_->numeric_constant_value(&nc)
10376 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10377 this->report_error(_("index must be integer"));
10378 if (this->end_ != NULL
10379 && this->end_->type()->integer_type() == NULL
10380 && !this->end_->type()->is_error()
10381 && !this->end_->is_nil_expression()
10382 && !this->end_->is_error_expression()
10383 && (!this->end_->numeric_constant_value(&nc)
10384 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10385 this->report_error(_("slice end must be integer"));
10387 std::string sval;
10388 bool sval_valid = this->string_->string_constant_value(&sval);
10390 Numeric_constant inc;
10391 mpz_t ival;
10392 bool ival_valid = false;
10393 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10395 ival_valid = true;
10396 if (mpz_sgn(ival) < 0
10397 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10399 error_at(this->start_->location(), "string index out of bounds");
10400 this->set_is_error();
10403 if (this->end_ != NULL && !this->end_->is_nil_expression())
10405 Numeric_constant enc;
10406 mpz_t eval;
10407 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10409 if (mpz_sgn(eval) < 0
10410 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10412 error_at(this->end_->location(), "string index out of bounds");
10413 this->set_is_error();
10415 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10416 this->report_error(_("inverted slice range"));
10417 mpz_clear(eval);
10420 if (ival_valid)
10421 mpz_clear(ival);
10424 // Get the backend representation for a string index.
10426 Bexpression*
10427 String_index_expression::do_get_backend(Translate_context* context)
10429 Location loc = this->location();
10430 Expression* string_arg = this->string_;
10431 if (this->string_->type()->points_to() != NULL)
10432 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10434 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10436 int code = (this->end_ == NULL
10437 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10438 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10440 Gogo* gogo = context->gogo();
10441 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10443 Type* int_type = Type::lookup_integer_type("int");
10445 // It is possible that an error occurred earlier because the start index
10446 // cannot be represented as an integer type. In this case, we shouldn't
10447 // try casting the starting index into an integer since
10448 // Type_conversion_expression will fail to get the backend representation.
10449 // FIXME.
10450 if (this->start_->type()->integer_type() == NULL
10451 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10453 go_assert(saw_errors());
10454 return context->backend()->error_expression();
10457 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10459 if (this->end_ == NULL)
10461 Expression* length =
10462 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10464 Expression* start_too_large =
10465 Expression::make_binary(OPERATOR_GE, start, length, loc);
10466 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10467 bad_index, loc);
10468 Expression* bytes =
10469 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10471 Bexpression* bstart = start->get_backend(context);
10472 Bexpression* ptr = bytes->get_backend(context);
10473 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10474 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10475 Bexpression* index =
10476 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10478 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10479 Bexpression* index_error = bad_index->get_backend(context);
10480 return gogo->backend()->conditional_expression(byte_btype, index_error,
10481 crash, index, loc);
10484 Expression* end = NULL;
10485 if (this->end_->is_nil_expression())
10486 end = Expression::make_integer_sl(-1, int_type, loc);
10487 else
10489 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10490 bad_index =
10491 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10492 end = Expression::make_cast(int_type, this->end_, loc);
10495 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10496 string_arg, start, end);
10497 Bexpression* bstrslice = strslice->get_backend(context);
10499 Btype* str_btype = strslice->type()->get_backend(gogo);
10500 Bexpression* index_error = bad_index->get_backend(context);
10501 return gogo->backend()->conditional_expression(str_btype, index_error,
10502 crash, bstrslice, loc);
10505 // Dump ast representation for a string index expression.
10507 void
10508 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10509 const
10511 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10512 this->start_, this->end_, NULL);
10515 // Make a string index expression. END may be NULL.
10517 Expression*
10518 Expression::make_string_index(Expression* string, Expression* start,
10519 Expression* end, Location location)
10521 return new String_index_expression(string, start, end, location);
10524 // Class Map_index.
10526 // Get the type of the map.
10528 Map_type*
10529 Map_index_expression::get_map_type() const
10531 Map_type* mt = this->map_->type()->deref()->map_type();
10532 if (mt == NULL)
10533 go_assert(saw_errors());
10534 return mt;
10537 // Map index traversal.
10540 Map_index_expression::do_traverse(Traverse* traverse)
10542 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10543 return TRAVERSE_EXIT;
10544 return Expression::traverse(&this->index_, traverse);
10547 // We need to pass in a pointer to the key, so flatten the index into a
10548 // temporary variable if it isn't already. The value pointer will be
10549 // dereferenced and checked for nil, so flatten into a temporary to avoid
10550 // recomputation.
10552 Expression*
10553 Map_index_expression::do_flatten(Gogo*, Named_object*,
10554 Statement_inserter* inserter)
10556 Map_type* mt = this->get_map_type();
10557 if (this->index_->type() != mt->key_type())
10558 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10559 this->location());
10561 if (!this->index_->is_variable())
10563 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10564 this->location());
10565 inserter->insert(temp);
10566 this->index_ = Expression::make_temporary_reference(temp,
10567 this->location());
10570 if (this->value_pointer_ == NULL)
10571 this->get_value_pointer(this->is_lvalue_);
10572 if (!this->value_pointer_->is_variable())
10574 Temporary_statement* temp =
10575 Statement::make_temporary(NULL, this->value_pointer_,
10576 this->location());
10577 inserter->insert(temp);
10578 this->value_pointer_ =
10579 Expression::make_temporary_reference(temp, this->location());
10582 return this;
10585 // Return the type of a map index.
10587 Type*
10588 Map_index_expression::do_type()
10590 Map_type* mt = this->get_map_type();
10591 if (mt == NULL)
10592 return Type::make_error_type();
10593 Type* type = mt->val_type();
10594 // If this map index is in a tuple assignment, we actually return a
10595 // pointer to the value type. Tuple_map_assignment_statement is
10596 // responsible for handling this correctly. We need to get the type
10597 // right in case this gets assigned to a temporary variable.
10598 if (this->is_in_tuple_assignment_)
10599 type = Type::make_pointer_type(type);
10600 return type;
10603 // Fix the type of a map index.
10605 void
10606 Map_index_expression::do_determine_type(const Type_context*)
10608 this->map_->determine_type_no_context();
10609 Map_type* mt = this->get_map_type();
10610 Type* key_type = mt == NULL ? NULL : mt->key_type();
10611 Type_context subcontext(key_type, false);
10612 this->index_->determine_type(&subcontext);
10615 // Check types of a map index.
10617 void
10618 Map_index_expression::do_check_types(Gogo*)
10620 std::string reason;
10621 Map_type* mt = this->get_map_type();
10622 if (mt == NULL)
10623 return;
10624 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10626 if (reason.empty())
10627 this->report_error(_("incompatible type for map index"));
10628 else
10630 error_at(this->location(), "incompatible type for map index (%s)",
10631 reason.c_str());
10632 this->set_is_error();
10637 // Get the backend representation for a map index.
10639 Bexpression*
10640 Map_index_expression::do_get_backend(Translate_context* context)
10642 Map_type* type = this->get_map_type();
10643 if (type == NULL)
10645 go_assert(saw_errors());
10646 return context->backend()->error_expression();
10649 go_assert(this->value_pointer_ != NULL
10650 && this->value_pointer_->is_variable());
10652 Bexpression* ret;
10653 if (this->is_lvalue_)
10655 Expression* val =
10656 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10657 this->location());
10658 ret = val->get_backend(context);
10660 else if (this->is_in_tuple_assignment_)
10662 // Tuple_map_assignment_statement is responsible for using this
10663 // appropriately.
10664 ret = this->value_pointer_->get_backend(context);
10666 else
10668 Location loc = this->location();
10670 Expression* nil_check =
10671 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10672 Expression::make_nil(loc), loc);
10673 Bexpression* bnil_check = nil_check->get_backend(context);
10674 Expression* val =
10675 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10676 Bexpression* bval = val->get_backend(context);
10678 Gogo* gogo = context->gogo();
10679 Btype* val_btype = type->val_type()->get_backend(gogo);
10680 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10681 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10682 val_zero, bval, loc);
10684 return ret;
10687 // Get an expression for the map index. This returns an expression which
10688 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10689 // not in the map.
10691 Expression*
10692 Map_index_expression::get_value_pointer(bool insert)
10694 if (this->value_pointer_ == NULL)
10696 Map_type* type = this->get_map_type();
10697 if (type == NULL)
10699 go_assert(saw_errors());
10700 return Expression::make_error(this->location());
10703 Location loc = this->location();
10704 Expression* map_ref = this->map_;
10705 if (this->map_->type()->points_to() != NULL)
10706 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10708 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10709 loc);
10710 Expression* map_index =
10711 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10712 map_ref, index_ptr,
10713 Expression::make_boolean(insert, loc));
10715 Type* val_type = type->val_type();
10716 this->value_pointer_ =
10717 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10718 map_index, this->location());
10720 return this->value_pointer_;
10723 // Dump ast representation for a map index expression
10725 void
10726 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10727 const
10729 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10730 this->index_, NULL, NULL);
10733 // Make a map index expression.
10735 Map_index_expression*
10736 Expression::make_map_index(Expression* map, Expression* index,
10737 Location location)
10739 return new Map_index_expression(map, index, location);
10742 // Class Field_reference_expression.
10744 // Lower a field reference expression. There is nothing to lower, but
10745 // this is where we generate the tracking information for fields with
10746 // the magic go:"track" tag.
10748 Expression*
10749 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10750 Statement_inserter* inserter, int)
10752 Struct_type* struct_type = this->expr_->type()->struct_type();
10753 if (struct_type == NULL)
10755 // Error will be reported elsewhere.
10756 return this;
10758 const Struct_field* field = struct_type->field(this->field_index_);
10759 if (field == NULL)
10760 return this;
10761 if (!field->has_tag())
10762 return this;
10763 if (field->tag().find("go:\"track\"") == std::string::npos)
10764 return this;
10766 // References from functions generated by the compiler don't count.
10767 if (function != NULL && function->func_value()->is_type_specific_function())
10768 return this;
10770 // We have found a reference to a tracked field. Build a call to
10771 // the runtime function __go_fieldtrack with a string that describes
10772 // the field. FIXME: We should only call this once per referenced
10773 // field per function, not once for each reference to the field.
10775 if (this->called_fieldtrack_)
10776 return this;
10777 this->called_fieldtrack_ = true;
10779 Location loc = this->location();
10781 std::string s = "fieldtrack \"";
10782 Named_type* nt = this->expr_->type()->named_type();
10783 if (nt == NULL || nt->named_object()->package() == NULL)
10784 s.append(gogo->pkgpath());
10785 else
10786 s.append(nt->named_object()->package()->pkgpath());
10787 s.push_back('.');
10788 if (nt != NULL)
10789 s.append(Gogo::unpack_hidden_name(nt->name()));
10790 s.push_back('.');
10791 s.append(field->field_name());
10792 s.push_back('"');
10794 // We can't use a string here, because internally a string holds a
10795 // pointer to the actual bytes; when the linker garbage collects the
10796 // string, it won't garbage collect the bytes. So we use a
10797 // [...]byte.
10799 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
10801 Type* byte_type = gogo->lookup_global("byte")->type_value();
10802 Type* array_type = Type::make_array_type(byte_type, length_expr);
10804 Expression_list* bytes = new Expression_list();
10805 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10807 unsigned char c = static_cast<unsigned char>(*p);
10808 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
10811 Expression* e = Expression::make_composite_literal(array_type, 0, false,
10812 bytes, false, loc);
10814 Variable* var = new Variable(array_type, e, true, false, false, loc);
10816 static int count;
10817 char buf[50];
10818 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10819 ++count;
10821 Named_object* no = gogo->add_variable(buf, var);
10822 e = Expression::make_var_reference(no, loc);
10823 e = Expression::make_unary(OPERATOR_AND, e, loc);
10825 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
10826 gogo->lower_expression(function, inserter, &call);
10827 inserter->insert(Statement::make_statement(call, false));
10829 // Put this function, and the global variable we just created, into
10830 // unique sections. This will permit the linker to garbage collect
10831 // them if they are not referenced. The effect is that the only
10832 // strings, indicating field references, that will wind up in the
10833 // executable will be those for functions that are actually needed.
10834 if (function != NULL)
10835 function->func_value()->set_in_unique_section();
10836 var->set_in_unique_section();
10838 return this;
10841 // Return the type of a field reference.
10843 Type*
10844 Field_reference_expression::do_type()
10846 Type* type = this->expr_->type();
10847 if (type->is_error())
10848 return type;
10849 Struct_type* struct_type = type->struct_type();
10850 go_assert(struct_type != NULL);
10851 return struct_type->field(this->field_index_)->type();
10854 // Check the types for a field reference.
10856 void
10857 Field_reference_expression::do_check_types(Gogo*)
10859 Type* type = this->expr_->type();
10860 if (type->is_error())
10861 return;
10862 Struct_type* struct_type = type->struct_type();
10863 go_assert(struct_type != NULL);
10864 go_assert(struct_type->field(this->field_index_) != NULL);
10867 // Get the backend representation for a field reference.
10869 Bexpression*
10870 Field_reference_expression::do_get_backend(Translate_context* context)
10872 Bexpression* bstruct = this->expr_->get_backend(context);
10873 return context->gogo()->backend()->struct_field_expression(bstruct,
10874 this->field_index_,
10875 this->location());
10878 // Dump ast representation for a field reference expression.
10880 void
10881 Field_reference_expression::do_dump_expression(
10882 Ast_dump_context* ast_dump_context) const
10884 this->expr_->dump_expression(ast_dump_context);
10885 ast_dump_context->ostream() << "." << this->field_index_;
10888 // Make a reference to a qualified identifier in an expression.
10890 Field_reference_expression*
10891 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10892 Location location)
10894 return new Field_reference_expression(expr, field_index, location);
10897 // Class Interface_field_reference_expression.
10899 // Return an expression for the pointer to the function to call.
10901 Expression*
10902 Interface_field_reference_expression::get_function()
10904 Expression* ref = this->expr_;
10905 Location loc = this->location();
10906 if (ref->type()->points_to() != NULL)
10907 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
10909 Expression* mtable =
10910 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
10911 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
10913 std::string name = Gogo::unpack_hidden_name(this->name_);
10914 unsigned int index;
10915 const Struct_field* field = mtable_type->find_local_field(name, &index);
10916 go_assert(field != NULL);
10917 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
10918 return Expression::make_field_reference(mtable, index, loc);
10921 // Return an expression for the first argument to pass to the interface
10922 // function.
10924 Expression*
10925 Interface_field_reference_expression::get_underlying_object()
10927 Expression* expr = this->expr_;
10928 if (expr->type()->points_to() != NULL)
10929 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
10930 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
10931 this->location());
10934 // Traversal.
10937 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10939 return Expression::traverse(&this->expr_, traverse);
10942 // Lower the expression. If this expression is not called, we need to
10943 // evaluate the expression twice when converting to the backend
10944 // interface. So introduce a temporary variable if necessary.
10946 Expression*
10947 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
10948 Statement_inserter* inserter)
10950 if (!this->expr_->is_variable())
10952 Temporary_statement* temp =
10953 Statement::make_temporary(this->expr_->type(), NULL, this->location());
10954 inserter->insert(temp);
10955 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
10956 this->location());
10958 return this;
10961 // Return the type of an interface field reference.
10963 Type*
10964 Interface_field_reference_expression::do_type()
10966 Type* expr_type = this->expr_->type();
10968 Type* points_to = expr_type->points_to();
10969 if (points_to != NULL)
10970 expr_type = points_to;
10972 Interface_type* interface_type = expr_type->interface_type();
10973 if (interface_type == NULL)
10974 return Type::make_error_type();
10976 const Typed_identifier* method = interface_type->find_method(this->name_);
10977 if (method == NULL)
10978 return Type::make_error_type();
10980 return method->type();
10983 // Determine types.
10985 void
10986 Interface_field_reference_expression::do_determine_type(const Type_context*)
10988 this->expr_->determine_type_no_context();
10991 // Check the types for an interface field reference.
10993 void
10994 Interface_field_reference_expression::do_check_types(Gogo*)
10996 Type* type = this->expr_->type();
10998 Type* points_to = type->points_to();
10999 if (points_to != NULL)
11000 type = points_to;
11002 Interface_type* interface_type = type->interface_type();
11003 if (interface_type == NULL)
11005 if (!type->is_error_type())
11006 this->report_error(_("expected interface or pointer to interface"));
11008 else
11010 const Typed_identifier* method =
11011 interface_type->find_method(this->name_);
11012 if (method == NULL)
11014 error_at(this->location(), "method %qs not in interface",
11015 Gogo::message_name(this->name_).c_str());
11016 this->set_is_error();
11021 // If an interface field reference is not simply called, then it is
11022 // represented as a closure. The closure will hold a single variable,
11023 // the value of the interface on which the method should be called.
11024 // The function will be a simple thunk that pulls the value from the
11025 // closure and calls the method with the remaining arguments.
11027 // Because method values are not common, we don't build all thunks for
11028 // all possible interface methods, but instead only build them as we
11029 // need them. In particular, we even build them on demand for
11030 // interface methods defined in other packages.
11032 Interface_field_reference_expression::Interface_method_thunks
11033 Interface_field_reference_expression::interface_method_thunks;
11035 // Find or create the thunk to call method NAME on TYPE.
11037 Named_object*
11038 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11039 Interface_type* type,
11040 const std::string& name)
11042 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11043 std::pair<Interface_method_thunks::iterator, bool> ins =
11044 Interface_field_reference_expression::interface_method_thunks.insert(val);
11045 if (ins.second)
11047 // This is the first time we have seen this interface.
11048 ins.first->second = new Method_thunks();
11051 for (Method_thunks::const_iterator p = ins.first->second->begin();
11052 p != ins.first->second->end();
11053 p++)
11054 if (p->first == name)
11055 return p->second;
11057 Location loc = type->location();
11059 const Typed_identifier* method_id = type->find_method(name);
11060 if (method_id == NULL)
11061 return Named_object::make_erroneous_name(Gogo::thunk_name());
11063 Function_type* orig_fntype = method_id->type()->function_type();
11064 if (orig_fntype == NULL)
11065 return Named_object::make_erroneous_name(Gogo::thunk_name());
11067 Struct_field_list* sfl = new Struct_field_list();
11068 // The type here is wrong--it should be the C function type. But it
11069 // doesn't really matter.
11070 Type* vt = Type::make_pointer_type(Type::make_void_type());
11071 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11072 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11073 Type* closure_type = Type::make_struct_type(sfl, loc);
11074 closure_type = Type::make_pointer_type(closure_type);
11076 Function_type* new_fntype = orig_fntype->copy_with_names();
11078 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11079 false, loc);
11081 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11082 cvar->set_is_used();
11083 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11084 new_no->func_value()->set_closure_var(cp);
11086 gogo->start_block(loc);
11088 // Field 0 of the closure is the function code pointer, field 1 is
11089 // the value on which to invoke the method.
11090 Expression* arg = Expression::make_var_reference(cp, loc);
11091 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11092 arg = Expression::make_field_reference(arg, 1, loc);
11094 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11095 loc);
11097 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11098 Expression_list* args;
11099 if (orig_params == NULL || orig_params->empty())
11100 args = NULL;
11101 else
11103 const Typed_identifier_list* new_params = new_fntype->parameters();
11104 args = new Expression_list();
11105 for (Typed_identifier_list::const_iterator p = new_params->begin();
11106 p != new_params->end();
11107 ++p)
11109 Named_object* p_no = gogo->lookup(p->name(), NULL);
11110 go_assert(p_no != NULL
11111 && p_no->is_variable()
11112 && p_no->var_value()->is_parameter());
11113 args->push_back(Expression::make_var_reference(p_no, loc));
11117 Call_expression* call = Expression::make_call(ifre, args,
11118 orig_fntype->is_varargs(),
11119 loc);
11120 call->set_varargs_are_lowered();
11122 Statement* s = Statement::make_return_from_call(call, loc);
11123 gogo->add_statement(s);
11124 Block* b = gogo->finish_block(loc);
11125 gogo->add_block(b, loc);
11126 gogo->lower_block(new_no, b);
11127 gogo->flatten_block(new_no, b);
11128 gogo->finish_function(loc);
11130 ins.first->second->push_back(std::make_pair(name, new_no));
11131 return new_no;
11134 // Get the backend representation for a method value.
11136 Bexpression*
11137 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11139 Interface_type* type = this->expr_->type()->interface_type();
11140 if (type == NULL)
11142 go_assert(saw_errors());
11143 return context->backend()->error_expression();
11146 Named_object* thunk =
11147 Interface_field_reference_expression::create_thunk(context->gogo(),
11148 type, this->name_);
11149 if (thunk->is_erroneous())
11151 go_assert(saw_errors());
11152 return context->backend()->error_expression();
11155 // FIXME: We should lower this earlier, but we can't it lower it in
11156 // the lowering pass because at that point we don't know whether we
11157 // need to create the thunk or not. If the expression is called, we
11158 // don't need the thunk.
11160 Location loc = this->location();
11162 Struct_field_list* fields = new Struct_field_list();
11163 fields->push_back(Struct_field(Typed_identifier("fn.0",
11164 thunk->func_value()->type(),
11165 loc)));
11166 fields->push_back(Struct_field(Typed_identifier("val.1",
11167 this->expr_->type(),
11168 loc)));
11169 Struct_type* st = Type::make_struct_type(fields, loc);
11171 Expression_list* vals = new Expression_list();
11172 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11173 vals->push_back(this->expr_);
11175 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11176 Bexpression* bclosure =
11177 Expression::make_heap_expression(expr, loc)->get_backend(context);
11179 Expression* nil_check =
11180 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11181 Expression::make_nil(loc), loc);
11182 Bexpression* bnil_check = nil_check->get_backend(context);
11184 Gogo* gogo = context->gogo();
11185 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11186 loc)->get_backend(context);
11188 Bexpression* bcond =
11189 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11190 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11191 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11194 // Dump ast representation for an interface field reference.
11196 void
11197 Interface_field_reference_expression::do_dump_expression(
11198 Ast_dump_context* ast_dump_context) const
11200 this->expr_->dump_expression(ast_dump_context);
11201 ast_dump_context->ostream() << "." << this->name_;
11204 // Make a reference to a field in an interface.
11206 Expression*
11207 Expression::make_interface_field_reference(Expression* expr,
11208 const std::string& field,
11209 Location location)
11211 return new Interface_field_reference_expression(expr, field, location);
11214 // A general selector. This is a Parser_expression for LEFT.NAME. It
11215 // is lowered after we know the type of the left hand side.
11217 class Selector_expression : public Parser_expression
11219 public:
11220 Selector_expression(Expression* left, const std::string& name,
11221 Location location)
11222 : Parser_expression(EXPRESSION_SELECTOR, location),
11223 left_(left), name_(name)
11226 protected:
11228 do_traverse(Traverse* traverse)
11229 { return Expression::traverse(&this->left_, traverse); }
11231 Expression*
11232 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11234 Expression*
11235 do_copy()
11237 return new Selector_expression(this->left_->copy(), this->name_,
11238 this->location());
11241 void
11242 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11244 private:
11245 Expression*
11246 lower_method_expression(Gogo*);
11248 // The expression on the left hand side.
11249 Expression* left_;
11250 // The name on the right hand side.
11251 std::string name_;
11254 // Lower a selector expression once we know the real type of the left
11255 // hand side.
11257 Expression*
11258 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11259 int)
11261 Expression* left = this->left_;
11262 if (left->is_type_expression())
11263 return this->lower_method_expression(gogo);
11264 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11265 this->location());
11268 // Lower a method expression T.M or (*T).M. We turn this into a
11269 // function literal.
11271 Expression*
11272 Selector_expression::lower_method_expression(Gogo* gogo)
11274 Location location = this->location();
11275 Type* type = this->left_->type();
11276 const std::string& name(this->name_);
11278 bool is_pointer;
11279 if (type->points_to() == NULL)
11280 is_pointer = false;
11281 else
11283 is_pointer = true;
11284 type = type->points_to();
11286 Named_type* nt = type->named_type();
11287 if (nt == NULL)
11289 error_at(location,
11290 ("method expression requires named type or "
11291 "pointer to named type"));
11292 return Expression::make_error(location);
11295 bool is_ambiguous;
11296 Method* method = nt->method_function(name, &is_ambiguous);
11297 const Typed_identifier* imethod = NULL;
11298 if (method == NULL && !is_pointer)
11300 Interface_type* it = nt->interface_type();
11301 if (it != NULL)
11302 imethod = it->find_method(name);
11305 if (method == NULL && imethod == NULL)
11307 if (!is_ambiguous)
11308 error_at(location, "type %<%s%s%> has no method %<%s%>",
11309 is_pointer ? "*" : "",
11310 nt->message_name().c_str(),
11311 Gogo::message_name(name).c_str());
11312 else
11313 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11314 Gogo::message_name(name).c_str(),
11315 is_pointer ? "*" : "",
11316 nt->message_name().c_str());
11317 return Expression::make_error(location);
11320 if (method != NULL && !is_pointer && !method->is_value_method())
11322 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11323 nt->message_name().c_str(),
11324 Gogo::message_name(name).c_str());
11325 return Expression::make_error(location);
11328 // Build a new function type in which the receiver becomes the first
11329 // argument.
11330 Function_type* method_type;
11331 if (method != NULL)
11333 method_type = method->type();
11334 go_assert(method_type->is_method());
11336 else
11338 method_type = imethod->type()->function_type();
11339 go_assert(method_type != NULL && !method_type->is_method());
11342 const char* const receiver_name = "$this";
11343 Typed_identifier_list* parameters = new Typed_identifier_list();
11344 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11345 location));
11347 const Typed_identifier_list* method_parameters = method_type->parameters();
11348 if (method_parameters != NULL)
11350 int i = 0;
11351 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11352 p != method_parameters->end();
11353 ++p, ++i)
11355 if (!p->name().empty())
11356 parameters->push_back(*p);
11357 else
11359 char buf[20];
11360 snprintf(buf, sizeof buf, "$param%d", i);
11361 parameters->push_back(Typed_identifier(buf, p->type(),
11362 p->location()));
11367 const Typed_identifier_list* method_results = method_type->results();
11368 Typed_identifier_list* results;
11369 if (method_results == NULL)
11370 results = NULL;
11371 else
11373 results = new Typed_identifier_list();
11374 for (Typed_identifier_list::const_iterator p = method_results->begin();
11375 p != method_results->end();
11376 ++p)
11377 results->push_back(*p);
11380 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11381 location);
11382 if (method_type->is_varargs())
11383 fntype->set_is_varargs();
11385 // We generate methods which always takes a pointer to the receiver
11386 // as their first argument. If this is for a pointer type, we can
11387 // simply reuse the existing function. We use an internal hack to
11388 // get the right type.
11389 // FIXME: This optimization is disabled because it doesn't yet work
11390 // with function descriptors when the method expression is not
11391 // directly called.
11392 if (method != NULL && is_pointer && false)
11394 Named_object* mno = (method->needs_stub_method()
11395 ? method->stub_object()
11396 : method->named_object());
11397 Expression* f = Expression::make_func_reference(mno, NULL, location);
11398 f = Expression::make_cast(fntype, f, location);
11399 Type_conversion_expression* tce =
11400 static_cast<Type_conversion_expression*>(f);
11401 tce->set_may_convert_function_types();
11402 return f;
11405 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11406 location);
11408 Named_object* vno = gogo->lookup(receiver_name, NULL);
11409 go_assert(vno != NULL);
11410 Expression* ve = Expression::make_var_reference(vno, location);
11411 Expression* bm;
11412 if (method != NULL)
11413 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11414 else
11415 bm = Expression::make_interface_field_reference(ve, name, location);
11417 // Even though we found the method above, if it has an error type we
11418 // may see an error here.
11419 if (bm->is_error_expression())
11421 gogo->finish_function(location);
11422 return bm;
11425 Expression_list* args;
11426 if (parameters->size() <= 1)
11427 args = NULL;
11428 else
11430 args = new Expression_list();
11431 Typed_identifier_list::const_iterator p = parameters->begin();
11432 ++p;
11433 for (; p != parameters->end(); ++p)
11435 vno = gogo->lookup(p->name(), NULL);
11436 go_assert(vno != NULL);
11437 args->push_back(Expression::make_var_reference(vno, location));
11441 gogo->start_block(location);
11443 Call_expression* call = Expression::make_call(bm, args,
11444 method_type->is_varargs(),
11445 location);
11447 Statement* s = Statement::make_return_from_call(call, location);
11448 gogo->add_statement(s);
11450 Block* b = gogo->finish_block(location);
11452 gogo->add_block(b, location);
11454 // Lower the call in case there are multiple results.
11455 gogo->lower_block(no, b);
11456 gogo->flatten_block(no, b);
11458 gogo->finish_function(location);
11460 return Expression::make_func_reference(no, NULL, location);
11463 // Dump the ast for a selector expression.
11465 void
11466 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11467 const
11469 ast_dump_context->dump_expression(this->left_);
11470 ast_dump_context->ostream() << ".";
11471 ast_dump_context->ostream() << this->name_;
11474 // Make a selector expression.
11476 Expression*
11477 Expression::make_selector(Expression* left, const std::string& name,
11478 Location location)
11480 return new Selector_expression(left, name, location);
11483 // Implement the builtin function new.
11485 class Allocation_expression : public Expression
11487 public:
11488 Allocation_expression(Type* type, Location location)
11489 : Expression(EXPRESSION_ALLOCATION, location),
11490 type_(type)
11493 protected:
11495 do_traverse(Traverse* traverse)
11496 { return Type::traverse(this->type_, traverse); }
11498 Type*
11499 do_type()
11500 { return Type::make_pointer_type(this->type_); }
11502 void
11503 do_determine_type(const Type_context*)
11506 Expression*
11507 do_copy()
11508 { return new Allocation_expression(this->type_, this->location()); }
11510 Bexpression*
11511 do_get_backend(Translate_context*);
11513 void
11514 do_dump_expression(Ast_dump_context*) const;
11516 private:
11517 // The type we are allocating.
11518 Type* type_;
11521 // Return the backend representation for an allocation expression.
11523 Bexpression*
11524 Allocation_expression::do_get_backend(Translate_context* context)
11526 Gogo* gogo = context->gogo();
11527 Location loc = this->location();
11528 Bexpression* space =
11529 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11530 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11531 return gogo->backend()->convert_expression(pbtype, space, loc);
11534 // Dump ast representation for an allocation expression.
11536 void
11537 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11538 const
11540 ast_dump_context->ostream() << "new(";
11541 ast_dump_context->dump_type(this->type_);
11542 ast_dump_context->ostream() << ")";
11545 // Make an allocation expression.
11547 Expression*
11548 Expression::make_allocation(Type* type, Location location)
11550 return new Allocation_expression(type, location);
11553 // Construct a struct.
11555 class Struct_construction_expression : public Expression
11557 public:
11558 Struct_construction_expression(Type* type, Expression_list* vals,
11559 Location location)
11560 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11561 type_(type), vals_(vals), traverse_order_(NULL)
11564 // Set the traversal order, used to ensure that we implement the
11565 // order of evaluation rules. Takes ownership of the argument.
11566 void
11567 set_traverse_order(std::vector<int>* traverse_order)
11568 { this->traverse_order_ = traverse_order; }
11570 // Return whether this is a constant initializer.
11571 bool
11572 is_constant_struct() const;
11574 protected:
11576 do_traverse(Traverse* traverse);
11578 bool
11579 do_is_immutable() const;
11581 Type*
11582 do_type()
11583 { return this->type_; }
11585 void
11586 do_determine_type(const Type_context*);
11588 void
11589 do_check_types(Gogo*);
11591 Expression*
11592 do_copy()
11594 Struct_construction_expression* ret =
11595 new Struct_construction_expression(this->type_,
11596 (this->vals_ == NULL
11597 ? NULL
11598 : this->vals_->copy()),
11599 this->location());
11600 if (this->traverse_order_ != NULL)
11601 ret->set_traverse_order(this->traverse_order_);
11602 return ret;
11605 Bexpression*
11606 do_get_backend(Translate_context*);
11608 void
11609 do_export(Export*) const;
11611 void
11612 do_dump_expression(Ast_dump_context*) const;
11614 private:
11615 // The type of the struct to construct.
11616 Type* type_;
11617 // The list of values, in order of the fields in the struct. A NULL
11618 // entry means that the field should be zero-initialized.
11619 Expression_list* vals_;
11620 // If not NULL, the order in which to traverse vals_. This is used
11621 // so that we implement the order of evaluation rules correctly.
11622 std::vector<int>* traverse_order_;
11625 // Traversal.
11628 Struct_construction_expression::do_traverse(Traverse* traverse)
11630 if (this->vals_ != NULL)
11632 if (this->traverse_order_ == NULL)
11634 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11635 return TRAVERSE_EXIT;
11637 else
11639 for (std::vector<int>::const_iterator p =
11640 this->traverse_order_->begin();
11641 p != this->traverse_order_->end();
11642 ++p)
11644 if (Expression::traverse(&this->vals_->at(*p), traverse)
11645 == TRAVERSE_EXIT)
11646 return TRAVERSE_EXIT;
11650 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11651 return TRAVERSE_EXIT;
11652 return TRAVERSE_CONTINUE;
11655 // Return whether this is a constant initializer.
11657 bool
11658 Struct_construction_expression::is_constant_struct() const
11660 if (this->vals_ == NULL)
11661 return true;
11662 for (Expression_list::const_iterator pv = this->vals_->begin();
11663 pv != this->vals_->end();
11664 ++pv)
11666 if (*pv != NULL
11667 && !(*pv)->is_constant()
11668 && (!(*pv)->is_composite_literal()
11669 || (*pv)->is_nonconstant_composite_literal()))
11670 return false;
11673 const Struct_field_list* fields = this->type_->struct_type()->fields();
11674 for (Struct_field_list::const_iterator pf = fields->begin();
11675 pf != fields->end();
11676 ++pf)
11678 // There are no constant constructors for interfaces.
11679 if (pf->type()->interface_type() != NULL)
11680 return false;
11683 return true;
11686 // Return whether this struct is immutable.
11688 bool
11689 Struct_construction_expression::do_is_immutable() const
11691 if (this->vals_ == NULL)
11692 return true;
11693 for (Expression_list::const_iterator pv = this->vals_->begin();
11694 pv != this->vals_->end();
11695 ++pv)
11697 if (*pv != NULL && !(*pv)->is_immutable())
11698 return false;
11700 return true;
11703 // Final type determination.
11705 void
11706 Struct_construction_expression::do_determine_type(const Type_context*)
11708 if (this->vals_ == NULL)
11709 return;
11710 const Struct_field_list* fields = this->type_->struct_type()->fields();
11711 Expression_list::const_iterator pv = this->vals_->begin();
11712 for (Struct_field_list::const_iterator pf = fields->begin();
11713 pf != fields->end();
11714 ++pf, ++pv)
11716 if (pv == this->vals_->end())
11717 return;
11718 if (*pv != NULL)
11720 Type_context subcontext(pf->type(), false);
11721 (*pv)->determine_type(&subcontext);
11724 // Extra values are an error we will report elsewhere; we still want
11725 // to determine the type to avoid knockon errors.
11726 for (; pv != this->vals_->end(); ++pv)
11727 (*pv)->determine_type_no_context();
11730 // Check types.
11732 void
11733 Struct_construction_expression::do_check_types(Gogo*)
11735 if (this->vals_ == NULL)
11736 return;
11738 Struct_type* st = this->type_->struct_type();
11739 if (this->vals_->size() > st->field_count())
11741 this->report_error(_("too many expressions for struct"));
11742 return;
11745 const Struct_field_list* fields = st->fields();
11746 Expression_list::const_iterator pv = this->vals_->begin();
11747 int i = 0;
11748 for (Struct_field_list::const_iterator pf = fields->begin();
11749 pf != fields->end();
11750 ++pf, ++pv, ++i)
11752 if (pv == this->vals_->end())
11754 this->report_error(_("too few expressions for struct"));
11755 break;
11758 if (*pv == NULL)
11759 continue;
11761 std::string reason;
11762 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11764 if (reason.empty())
11765 error_at((*pv)->location(),
11766 "incompatible type for field %d in struct construction",
11767 i + 1);
11768 else
11769 error_at((*pv)->location(),
11770 ("incompatible type for field %d in "
11771 "struct construction (%s)"),
11772 i + 1, reason.c_str());
11773 this->set_is_error();
11776 go_assert(pv == this->vals_->end());
11779 // Return the backend representation for constructing a struct.
11781 Bexpression*
11782 Struct_construction_expression::do_get_backend(Translate_context* context)
11784 Gogo* gogo = context->gogo();
11786 Btype* btype = this->type_->get_backend(gogo);
11787 if (this->vals_ == NULL)
11788 return gogo->backend()->zero_expression(btype);
11790 const Struct_field_list* fields = this->type_->struct_type()->fields();
11791 Expression_list::const_iterator pv = this->vals_->begin();
11792 std::vector<Bexpression*> init;
11793 for (Struct_field_list::const_iterator pf = fields->begin();
11794 pf != fields->end();
11795 ++pf)
11797 Btype* fbtype = pf->type()->get_backend(gogo);
11798 if (pv == this->vals_->end())
11799 init.push_back(gogo->backend()->zero_expression(fbtype));
11800 else if (*pv == NULL)
11802 init.push_back(gogo->backend()->zero_expression(fbtype));
11803 ++pv;
11805 else
11807 Expression* val =
11808 Expression::convert_for_assignment(gogo, pf->type(),
11809 *pv, this->location());
11810 init.push_back(val->get_backend(context));
11811 ++pv;
11814 return gogo->backend()->constructor_expression(btype, init, this->location());
11817 // Export a struct construction.
11819 void
11820 Struct_construction_expression::do_export(Export* exp) const
11822 exp->write_c_string("convert(");
11823 exp->write_type(this->type_);
11824 for (Expression_list::const_iterator pv = this->vals_->begin();
11825 pv != this->vals_->end();
11826 ++pv)
11828 exp->write_c_string(", ");
11829 if (*pv != NULL)
11830 (*pv)->export_expression(exp);
11832 exp->write_c_string(")");
11835 // Dump ast representation of a struct construction expression.
11837 void
11838 Struct_construction_expression::do_dump_expression(
11839 Ast_dump_context* ast_dump_context) const
11841 ast_dump_context->dump_type(this->type_);
11842 ast_dump_context->ostream() << "{";
11843 ast_dump_context->dump_expression_list(this->vals_);
11844 ast_dump_context->ostream() << "}";
11847 // Make a struct composite literal. This used by the thunk code.
11849 Expression*
11850 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11851 Location location)
11853 go_assert(type->struct_type() != NULL);
11854 return new Struct_construction_expression(type, vals, location);
11857 // Construct an array. This class is not used directly; instead we
11858 // use the child classes, Fixed_array_construction_expression and
11859 // Slice_construction_expression.
11861 class Array_construction_expression : public Expression
11863 protected:
11864 Array_construction_expression(Expression_classification classification,
11865 Type* type,
11866 const std::vector<unsigned long>* indexes,
11867 Expression_list* vals, Location location)
11868 : Expression(classification, location),
11869 type_(type), indexes_(indexes), vals_(vals)
11870 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11872 public:
11873 // Return whether this is a constant initializer.
11874 bool
11875 is_constant_array() const;
11877 // Return the number of elements.
11878 size_t
11879 element_count() const
11880 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11882 protected:
11883 virtual int
11884 do_traverse(Traverse* traverse);
11886 bool
11887 do_is_immutable() const;
11889 Type*
11890 do_type()
11891 { return this->type_; }
11893 void
11894 do_determine_type(const Type_context*);
11896 void
11897 do_check_types(Gogo*);
11899 void
11900 do_export(Export*) const;
11902 // The indexes.
11903 const std::vector<unsigned long>*
11904 indexes()
11905 { return this->indexes_; }
11907 // The list of values.
11908 Expression_list*
11909 vals()
11910 { return this->vals_; }
11912 // Get the backend constructor for the array values.
11913 Bexpression*
11914 get_constructor(Translate_context* context, Btype* btype);
11916 void
11917 do_dump_expression(Ast_dump_context*) const;
11919 private:
11920 // The type of the array to construct.
11921 Type* type_;
11922 // The list of indexes into the array, one for each value. This may
11923 // be NULL, in which case the indexes start at zero and increment.
11924 const std::vector<unsigned long>* indexes_;
11925 // The list of values. This may be NULL if there are no values.
11926 Expression_list* vals_;
11929 // Traversal.
11932 Array_construction_expression::do_traverse(Traverse* traverse)
11934 if (this->vals_ != NULL
11935 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11936 return TRAVERSE_EXIT;
11937 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11938 return TRAVERSE_EXIT;
11939 return TRAVERSE_CONTINUE;
11942 // Return whether this is a constant initializer.
11944 bool
11945 Array_construction_expression::is_constant_array() const
11947 if (this->vals_ == NULL)
11948 return true;
11950 // There are no constant constructors for interfaces.
11951 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11952 return false;
11954 for (Expression_list::const_iterator pv = this->vals_->begin();
11955 pv != this->vals_->end();
11956 ++pv)
11958 if (*pv != NULL
11959 && !(*pv)->is_constant()
11960 && (!(*pv)->is_composite_literal()
11961 || (*pv)->is_nonconstant_composite_literal()))
11962 return false;
11964 return true;
11967 // Return whether this is an immutable array initializer.
11969 bool
11970 Array_construction_expression::do_is_immutable() const
11972 if (this->vals_ == NULL)
11973 return true;
11974 for (Expression_list::const_iterator pv = this->vals_->begin();
11975 pv != this->vals_->end();
11976 ++pv)
11978 if (*pv != NULL && !(*pv)->is_immutable())
11979 return false;
11981 return true;
11984 // Final type determination.
11986 void
11987 Array_construction_expression::do_determine_type(const Type_context*)
11989 if (this->vals_ == NULL)
11990 return;
11991 Type_context subcontext(this->type_->array_type()->element_type(), false);
11992 for (Expression_list::const_iterator pv = this->vals_->begin();
11993 pv != this->vals_->end();
11994 ++pv)
11996 if (*pv != NULL)
11997 (*pv)->determine_type(&subcontext);
12001 // Check types.
12003 void
12004 Array_construction_expression::do_check_types(Gogo*)
12006 if (this->vals_ == NULL)
12007 return;
12009 Array_type* at = this->type_->array_type();
12010 int i = 0;
12011 Type* element_type = at->element_type();
12012 for (Expression_list::const_iterator pv = this->vals_->begin();
12013 pv != this->vals_->end();
12014 ++pv, ++i)
12016 if (*pv != NULL
12017 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12019 error_at((*pv)->location(),
12020 "incompatible type for element %d in composite literal",
12021 i + 1);
12022 this->set_is_error();
12027 // Get a constructor expression for the array values.
12029 Bexpression*
12030 Array_construction_expression::get_constructor(Translate_context* context,
12031 Btype* array_btype)
12033 Type* element_type = this->type_->array_type()->element_type();
12035 std::vector<unsigned long> indexes;
12036 std::vector<Bexpression*> vals;
12037 Gogo* gogo = context->gogo();
12038 if (this->vals_ != NULL)
12040 size_t i = 0;
12041 std::vector<unsigned long>::const_iterator pi;
12042 if (this->indexes_ != NULL)
12043 pi = this->indexes_->begin();
12044 for (Expression_list::const_iterator pv = this->vals_->begin();
12045 pv != this->vals_->end();
12046 ++pv, ++i)
12048 if (this->indexes_ != NULL)
12049 go_assert(pi != this->indexes_->end());
12051 if (this->indexes_ == NULL)
12052 indexes.push_back(i);
12053 else
12054 indexes.push_back(*pi);
12055 if (*pv == NULL)
12057 Btype* ebtype = element_type->get_backend(gogo);
12058 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12059 vals.push_back(zv);
12061 else
12063 Expression* val_expr =
12064 Expression::convert_for_assignment(gogo, element_type, *pv,
12065 this->location());
12066 vals.push_back(val_expr->get_backend(context));
12068 if (this->indexes_ != NULL)
12069 ++pi;
12071 if (this->indexes_ != NULL)
12072 go_assert(pi == this->indexes_->end());
12074 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12075 vals, this->location());
12078 // Export an array construction.
12080 void
12081 Array_construction_expression::do_export(Export* exp) const
12083 exp->write_c_string("convert(");
12084 exp->write_type(this->type_);
12085 if (this->vals_ != NULL)
12087 std::vector<unsigned long>::const_iterator pi;
12088 if (this->indexes_ != NULL)
12089 pi = this->indexes_->begin();
12090 for (Expression_list::const_iterator pv = this->vals_->begin();
12091 pv != this->vals_->end();
12092 ++pv)
12094 exp->write_c_string(", ");
12096 if (this->indexes_ != NULL)
12098 char buf[100];
12099 snprintf(buf, sizeof buf, "%lu", *pi);
12100 exp->write_c_string(buf);
12101 exp->write_c_string(":");
12104 if (*pv != NULL)
12105 (*pv)->export_expression(exp);
12107 if (this->indexes_ != NULL)
12108 ++pi;
12111 exp->write_c_string(")");
12114 // Dump ast representation of an array construction expressin.
12116 void
12117 Array_construction_expression::do_dump_expression(
12118 Ast_dump_context* ast_dump_context) const
12120 Expression* length = this->type_->array_type()->length();
12122 ast_dump_context->ostream() << "[" ;
12123 if (length != NULL)
12125 ast_dump_context->dump_expression(length);
12127 ast_dump_context->ostream() << "]" ;
12128 ast_dump_context->dump_type(this->type_);
12129 ast_dump_context->ostream() << "{" ;
12130 if (this->indexes_ == NULL)
12131 ast_dump_context->dump_expression_list(this->vals_);
12132 else
12134 Expression_list::const_iterator pv = this->vals_->begin();
12135 for (std::vector<unsigned long>::const_iterator pi =
12136 this->indexes_->begin();
12137 pi != this->indexes_->end();
12138 ++pi, ++pv)
12140 if (pi != this->indexes_->begin())
12141 ast_dump_context->ostream() << ", ";
12142 ast_dump_context->ostream() << *pi << ':';
12143 ast_dump_context->dump_expression(*pv);
12146 ast_dump_context->ostream() << "}" ;
12150 // Construct a fixed array.
12152 class Fixed_array_construction_expression :
12153 public Array_construction_expression
12155 public:
12156 Fixed_array_construction_expression(Type* type,
12157 const std::vector<unsigned long>* indexes,
12158 Expression_list* vals, Location location)
12159 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12160 type, indexes, vals, location)
12161 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12163 protected:
12164 Expression*
12165 do_copy()
12167 return new Fixed_array_construction_expression(this->type(),
12168 this->indexes(),
12169 (this->vals() == NULL
12170 ? NULL
12171 : this->vals()->copy()),
12172 this->location());
12175 Bexpression*
12176 do_get_backend(Translate_context*);
12179 // Return the backend representation for constructing a fixed array.
12181 Bexpression*
12182 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12184 Type* type = this->type();
12185 Btype* btype = type->get_backend(context->gogo());
12186 return this->get_constructor(context, btype);
12189 Expression*
12190 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12191 Location location)
12193 go_assert(type->array_type() != NULL && !type->is_slice_type());
12194 return new Fixed_array_construction_expression(type, NULL, vals, location);
12197 // Construct a slice.
12199 class Slice_construction_expression : public Array_construction_expression
12201 public:
12202 Slice_construction_expression(Type* type,
12203 const std::vector<unsigned long>* indexes,
12204 Expression_list* vals, Location location)
12205 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12206 type, indexes, vals, location),
12207 valtype_(NULL)
12209 go_assert(type->is_slice_type());
12211 unsigned long lenval;
12212 Expression* length;
12213 if (vals == NULL || vals->empty())
12214 lenval = 0;
12215 else
12217 if (this->indexes() == NULL)
12218 lenval = vals->size();
12219 else
12220 lenval = indexes->back() + 1;
12222 Type* int_type = Type::lookup_integer_type("int");
12223 length = Expression::make_integer_ul(lenval, int_type, location);
12224 Type* element_type = type->array_type()->element_type();
12225 this->valtype_ = Type::make_array_type(element_type, length);
12228 protected:
12229 // Note that taking the address of a slice literal is invalid.
12232 do_traverse(Traverse* traverse);
12234 Expression*
12235 do_copy()
12237 return new Slice_construction_expression(this->type(), this->indexes(),
12238 (this->vals() == NULL
12239 ? NULL
12240 : this->vals()->copy()),
12241 this->location());
12244 Bexpression*
12245 do_get_backend(Translate_context*);
12247 private:
12248 // The type of the values in this slice.
12249 Type* valtype_;
12252 // Traversal.
12255 Slice_construction_expression::do_traverse(Traverse* traverse)
12257 if (this->Array_construction_expression::do_traverse(traverse)
12258 == TRAVERSE_EXIT)
12259 return TRAVERSE_EXIT;
12260 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12261 return TRAVERSE_EXIT;
12262 return TRAVERSE_CONTINUE;
12265 // Return the backend representation for constructing a slice.
12267 Bexpression*
12268 Slice_construction_expression::do_get_backend(Translate_context* context)
12270 Array_type* array_type = this->type()->array_type();
12271 if (array_type == NULL)
12273 go_assert(this->type()->is_error());
12274 return context->backend()->error_expression();
12277 Location loc = this->location();
12278 Type* element_type = array_type->element_type();
12279 go_assert(this->valtype_ != NULL);
12281 Expression_list* vals = this->vals();
12282 if (this->vals() == NULL || this->vals()->empty())
12284 // We need to create a unique value for the empty array literal.
12285 vals = new Expression_list;
12286 vals->push_back(NULL);
12288 Expression* array_val =
12289 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12290 vals, loc);
12292 bool is_constant_initializer = array_val->is_immutable();
12294 // We have to copy the initial values into heap memory if we are in
12295 // a function or if the values are not constants. We also have to
12296 // copy them if they may contain pointers in a non-constant context,
12297 // as otherwise the garbage collector won't see them.
12298 bool copy_to_heap = (context->function() != NULL
12299 || !is_constant_initializer
12300 || (element_type->has_pointer()
12301 && !context->is_const()));
12303 Expression* space;
12304 if (!copy_to_heap)
12306 // The initializer will only run once.
12307 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12308 space->unary_expression()->set_is_slice_init();
12310 else
12311 space = Expression::make_heap_expression(array_val, loc);
12313 // Build a constructor for the slice.
12315 Expression* len = this->valtype_->array_type()->length();
12316 Expression* slice_val =
12317 Expression::make_slice_value(this->type(), space, len, len, loc);
12318 return slice_val->get_backend(context);
12321 // Make a slice composite literal. This is used by the type
12322 // descriptor code.
12324 Expression*
12325 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12326 Location location)
12328 go_assert(type->is_slice_type());
12329 return new Slice_construction_expression(type, NULL, vals, location);
12332 // Construct a map.
12334 class Map_construction_expression : public Expression
12336 public:
12337 Map_construction_expression(Type* type, Expression_list* vals,
12338 Location location)
12339 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12340 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
12341 { go_assert(vals == NULL || vals->size() % 2 == 0); }
12343 protected:
12345 do_traverse(Traverse* traverse);
12347 Expression*
12348 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12350 Type*
12351 do_type()
12352 { return this->type_; }
12354 void
12355 do_determine_type(const Type_context*);
12357 void
12358 do_check_types(Gogo*);
12360 Expression*
12361 do_copy()
12363 return new Map_construction_expression(this->type_,
12364 (this->vals_ == NULL
12365 ? NULL
12366 : this->vals_->copy()),
12367 this->location());
12370 Bexpression*
12371 do_get_backend(Translate_context*);
12373 void
12374 do_export(Export*) const;
12376 void
12377 do_dump_expression(Ast_dump_context*) const;
12379 private:
12380 // The type of the map to construct.
12381 Type* type_;
12382 // The list of values.
12383 Expression_list* vals_;
12384 // The type of the key-value pair struct for each map element.
12385 Struct_type* element_type_;
12386 // A temporary reference to the variable storing the constructor initializer.
12387 Temporary_statement* constructor_temp_;
12390 // Traversal.
12393 Map_construction_expression::do_traverse(Traverse* traverse)
12395 if (this->vals_ != NULL
12396 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12397 return TRAVERSE_EXIT;
12398 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12399 return TRAVERSE_EXIT;
12400 return TRAVERSE_CONTINUE;
12403 // Flatten constructor initializer into a temporary variable since
12404 // we need to take its address for __go_construct_map.
12406 Expression*
12407 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12408 Statement_inserter* inserter)
12410 if (!this->is_error_expression()
12411 && this->vals_ != NULL
12412 && !this->vals_->empty()
12413 && this->constructor_temp_ == NULL)
12415 Map_type* mt = this->type_->map_type();
12416 Type* key_type = mt->key_type();
12417 Type* val_type = mt->val_type();
12418 this->element_type_ = Type::make_builtin_struct_type(2,
12419 "__key", key_type,
12420 "__val", val_type);
12422 Expression_list* value_pairs = new Expression_list();
12423 Location loc = this->location();
12425 size_t i = 0;
12426 for (Expression_list::const_iterator pv = this->vals_->begin();
12427 pv != this->vals_->end();
12428 ++pv, ++i)
12430 Expression_list* key_value_pair = new Expression_list();
12431 Expression* key =
12432 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12434 ++pv;
12435 Expression* val =
12436 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12438 key_value_pair->push_back(key);
12439 key_value_pair->push_back(val);
12440 value_pairs->push_back(
12441 Expression::make_struct_composite_literal(this->element_type_,
12442 key_value_pair, loc));
12445 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
12446 Type* ctor_type =
12447 Type::make_array_type(this->element_type_, element_count);
12448 Expression* constructor =
12449 new Fixed_array_construction_expression(ctor_type, NULL,
12450 value_pairs, loc);
12452 this->constructor_temp_ =
12453 Statement::make_temporary(NULL, constructor, loc);
12454 constructor->issue_nil_check();
12455 this->constructor_temp_->set_is_address_taken();
12456 inserter->insert(this->constructor_temp_);
12459 return this;
12462 // Final type determination.
12464 void
12465 Map_construction_expression::do_determine_type(const Type_context*)
12467 if (this->vals_ == NULL)
12468 return;
12470 Map_type* mt = this->type_->map_type();
12471 Type_context key_context(mt->key_type(), false);
12472 Type_context val_context(mt->val_type(), false);
12473 for (Expression_list::const_iterator pv = this->vals_->begin();
12474 pv != this->vals_->end();
12475 ++pv)
12477 (*pv)->determine_type(&key_context);
12478 ++pv;
12479 (*pv)->determine_type(&val_context);
12483 // Check types.
12485 void
12486 Map_construction_expression::do_check_types(Gogo*)
12488 if (this->vals_ == NULL)
12489 return;
12491 Map_type* mt = this->type_->map_type();
12492 int i = 0;
12493 Type* key_type = mt->key_type();
12494 Type* val_type = mt->val_type();
12495 for (Expression_list::const_iterator pv = this->vals_->begin();
12496 pv != this->vals_->end();
12497 ++pv, ++i)
12499 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12501 error_at((*pv)->location(),
12502 "incompatible type for element %d key in map construction",
12503 i + 1);
12504 this->set_is_error();
12506 ++pv;
12507 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12509 error_at((*pv)->location(),
12510 ("incompatible type for element %d value "
12511 "in map construction"),
12512 i + 1);
12513 this->set_is_error();
12518 // Return the backend representation for constructing a map.
12520 Bexpression*
12521 Map_construction_expression::do_get_backend(Translate_context* context)
12523 if (this->is_error_expression())
12524 return context->backend()->error_expression();
12525 Location loc = this->location();
12527 size_t i = 0;
12528 Expression* ventries;
12529 if (this->vals_ == NULL || this->vals_->empty())
12530 ventries = Expression::make_nil(loc);
12531 else
12533 go_assert(this->constructor_temp_ != NULL);
12534 i = this->vals_->size() / 2;
12536 Expression* ctor_ref =
12537 Expression::make_temporary_reference(this->constructor_temp_, loc);
12538 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12541 Map_type* mt = this->type_->map_type();
12542 if (this->element_type_ == NULL)
12543 this->element_type_ =
12544 Type::make_builtin_struct_type(2,
12545 "__key", mt->key_type(),
12546 "__val", mt->val_type());
12547 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12549 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12550 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
12552 Expression* entry_size =
12553 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12555 unsigned int field_index;
12556 const Struct_field* valfield =
12557 this->element_type_->find_local_field("__val", &field_index);
12558 Expression* val_offset =
12559 Expression::make_struct_field_offset(this->element_type_, valfield);
12560 Expression* val_size =
12561 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12563 Expression* map_ctor =
12564 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12565 entry_size, val_offset, val_size, ventries);
12566 return map_ctor->get_backend(context);
12569 // Export an array construction.
12571 void
12572 Map_construction_expression::do_export(Export* exp) const
12574 exp->write_c_string("convert(");
12575 exp->write_type(this->type_);
12576 for (Expression_list::const_iterator pv = this->vals_->begin();
12577 pv != this->vals_->end();
12578 ++pv)
12580 exp->write_c_string(", ");
12581 (*pv)->export_expression(exp);
12583 exp->write_c_string(")");
12586 // Dump ast representation for a map construction expression.
12588 void
12589 Map_construction_expression::do_dump_expression(
12590 Ast_dump_context* ast_dump_context) const
12592 ast_dump_context->ostream() << "{" ;
12593 ast_dump_context->dump_expression_list(this->vals_, true);
12594 ast_dump_context->ostream() << "}";
12597 // A general composite literal. This is lowered to a type specific
12598 // version.
12600 class Composite_literal_expression : public Parser_expression
12602 public:
12603 Composite_literal_expression(Type* type, int depth, bool has_keys,
12604 Expression_list* vals, bool all_are_names,
12605 Location location)
12606 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12607 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12608 all_are_names_(all_are_names)
12611 protected:
12613 do_traverse(Traverse* traverse);
12615 Expression*
12616 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12618 Expression*
12619 do_copy()
12621 return new Composite_literal_expression(this->type_, this->depth_,
12622 this->has_keys_,
12623 (this->vals_ == NULL
12624 ? NULL
12625 : this->vals_->copy()),
12626 this->all_are_names_,
12627 this->location());
12630 void
12631 do_dump_expression(Ast_dump_context*) const;
12633 private:
12634 Expression*
12635 lower_struct(Gogo*, Type*);
12637 Expression*
12638 lower_array(Type*);
12640 Expression*
12641 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12643 Expression*
12644 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12646 // The type of the composite literal.
12647 Type* type_;
12648 // The depth within a list of composite literals within a composite
12649 // literal, when the type is omitted.
12650 int depth_;
12651 // The values to put in the composite literal.
12652 Expression_list* vals_;
12653 // If this is true, then VALS_ is a list of pairs: a key and a
12654 // value. In an array initializer, a missing key will be NULL.
12655 bool has_keys_;
12656 // If this is true, then HAS_KEYS_ is true, and every key is a
12657 // simple identifier.
12658 bool all_are_names_;
12661 // Traversal.
12664 Composite_literal_expression::do_traverse(Traverse* traverse)
12666 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12667 return TRAVERSE_EXIT;
12669 // If this is a struct composite literal with keys, then the keys
12670 // are field names, not expressions. We don't want to traverse them
12671 // in that case. If we do, we can give an erroneous error "variable
12672 // initializer refers to itself." See bug482.go in the testsuite.
12673 if (this->has_keys_ && this->vals_ != NULL)
12675 // The type may not be resolvable at this point.
12676 Type* type = this->type_;
12678 for (int depth = this->depth_; depth > 0; --depth)
12680 if (type->array_type() != NULL)
12681 type = type->array_type()->element_type();
12682 else if (type->map_type() != NULL)
12683 type = type->map_type()->val_type();
12684 else
12686 // This error will be reported during lowering.
12687 return TRAVERSE_CONTINUE;
12691 while (true)
12693 if (type->classification() == Type::TYPE_NAMED)
12694 type = type->named_type()->real_type();
12695 else if (type->classification() == Type::TYPE_FORWARD)
12697 Type* t = type->forwarded();
12698 if (t == type)
12699 break;
12700 type = t;
12702 else
12703 break;
12706 if (type->classification() == Type::TYPE_STRUCT)
12708 Expression_list::iterator p = this->vals_->begin();
12709 while (p != this->vals_->end())
12711 // Skip key.
12712 ++p;
12713 go_assert(p != this->vals_->end());
12714 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12715 return TRAVERSE_EXIT;
12716 ++p;
12718 return TRAVERSE_CONTINUE;
12722 if (this->vals_ != NULL)
12723 return this->vals_->traverse(traverse);
12725 return TRAVERSE_CONTINUE;
12728 // Lower a generic composite literal into a specific version based on
12729 // the type.
12731 Expression*
12732 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12733 Statement_inserter* inserter, int)
12735 Type* type = this->type_;
12737 for (int depth = this->depth_; depth > 0; --depth)
12739 if (type->array_type() != NULL)
12740 type = type->array_type()->element_type();
12741 else if (type->map_type() != NULL)
12742 type = type->map_type()->val_type();
12743 else
12745 if (!type->is_error())
12746 error_at(this->location(),
12747 ("may only omit types within composite literals "
12748 "of slice, array, or map type"));
12749 return Expression::make_error(this->location());
12753 Type *pt = type->points_to();
12754 bool is_pointer = false;
12755 if (pt != NULL)
12757 is_pointer = true;
12758 type = pt;
12761 Expression* ret;
12762 if (type->is_error())
12763 return Expression::make_error(this->location());
12764 else if (type->struct_type() != NULL)
12765 ret = this->lower_struct(gogo, type);
12766 else if (type->array_type() != NULL)
12767 ret = this->lower_array(type);
12768 else if (type->map_type() != NULL)
12769 ret = this->lower_map(gogo, function, inserter, type);
12770 else
12772 error_at(this->location(),
12773 ("expected struct, slice, array, or map type "
12774 "for composite literal"));
12775 return Expression::make_error(this->location());
12778 if (is_pointer)
12779 ret = Expression::make_heap_expression(ret, this->location());
12781 return ret;
12784 // Lower a struct composite literal.
12786 Expression*
12787 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12789 Location location = this->location();
12790 Struct_type* st = type->struct_type();
12791 if (this->vals_ == NULL || !this->has_keys_)
12793 if (this->vals_ != NULL
12794 && !this->vals_->empty()
12795 && type->named_type() != NULL
12796 && type->named_type()->named_object()->package() != NULL)
12798 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12799 pf != st->fields()->end();
12800 ++pf)
12802 if (Gogo::is_hidden_name(pf->field_name()))
12803 error_at(this->location(),
12804 "assignment of unexported field %qs in %qs literal",
12805 Gogo::message_name(pf->field_name()).c_str(),
12806 type->named_type()->message_name().c_str());
12810 return new Struct_construction_expression(type, this->vals_, location);
12813 size_t field_count = st->field_count();
12814 std::vector<Expression*> vals(field_count);
12815 std::vector<int>* traverse_order = new(std::vector<int>);
12816 Expression_list::const_iterator p = this->vals_->begin();
12817 Expression* external_expr = NULL;
12818 const Named_object* external_no = NULL;
12819 while (p != this->vals_->end())
12821 Expression* name_expr = *p;
12823 ++p;
12824 go_assert(p != this->vals_->end());
12825 Expression* val = *p;
12827 ++p;
12829 if (name_expr == NULL)
12831 error_at(val->location(), "mixture of field and value initializers");
12832 return Expression::make_error(location);
12835 bool bad_key = false;
12836 std::string name;
12837 const Named_object* no = NULL;
12838 switch (name_expr->classification())
12840 case EXPRESSION_UNKNOWN_REFERENCE:
12841 name = name_expr->unknown_expression()->name();
12842 if (type->named_type() != NULL)
12844 // If the named object found for this field name comes from a
12845 // different package than the struct it is a part of, do not count
12846 // this incorrect lookup as a usage of the object's package.
12847 no = name_expr->unknown_expression()->named_object();
12848 if (no->package() != NULL
12849 && no->package() != type->named_type()->named_object()->package())
12850 no->package()->forget_usage(name_expr);
12852 break;
12854 case EXPRESSION_CONST_REFERENCE:
12855 no = static_cast<Const_expression*>(name_expr)->named_object();
12856 break;
12858 case EXPRESSION_TYPE:
12860 Type* t = name_expr->type();
12861 Named_type* nt = t->named_type();
12862 if (nt == NULL)
12863 bad_key = true;
12864 else
12865 no = nt->named_object();
12867 break;
12869 case EXPRESSION_VAR_REFERENCE:
12870 no = name_expr->var_expression()->named_object();
12871 break;
12873 case EXPRESSION_FUNC_REFERENCE:
12874 no = name_expr->func_expression()->named_object();
12875 break;
12877 case EXPRESSION_UNARY:
12878 // If there is a local variable around with the same name as
12879 // the field, and this occurs in the closure, then the
12880 // parser may turn the field reference into an indirection
12881 // through the closure. FIXME: This is a mess.
12883 bad_key = true;
12884 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12885 if (ue->op() == OPERATOR_MULT)
12887 Field_reference_expression* fre =
12888 ue->operand()->field_reference_expression();
12889 if (fre != NULL)
12891 Struct_type* st =
12892 fre->expr()->type()->deref()->struct_type();
12893 if (st != NULL)
12895 const Struct_field* sf = st->field(fre->field_index());
12896 name = sf->field_name();
12898 // See below. FIXME.
12899 if (!Gogo::is_hidden_name(name)
12900 && name[0] >= 'a'
12901 && name[0] <= 'z')
12903 if (gogo->lookup_global(name.c_str()) != NULL)
12904 name = gogo->pack_hidden_name(name, false);
12907 char buf[20];
12908 snprintf(buf, sizeof buf, "%u", fre->field_index());
12909 size_t buflen = strlen(buf);
12910 if (name.compare(name.length() - buflen, buflen, buf)
12911 == 0)
12913 name = name.substr(0, name.length() - buflen);
12914 bad_key = false;
12920 break;
12922 default:
12923 bad_key = true;
12924 break;
12926 if (bad_key)
12928 error_at(name_expr->location(), "expected struct field name");
12929 return Expression::make_error(location);
12932 if (no != NULL)
12934 if (no->package() != NULL && external_expr == NULL)
12936 external_expr = name_expr;
12937 external_no = no;
12940 name = no->name();
12942 // A predefined name won't be packed. If it starts with a
12943 // lower case letter we need to check for that case, because
12944 // the field name will be packed. FIXME.
12945 if (!Gogo::is_hidden_name(name)
12946 && name[0] >= 'a'
12947 && name[0] <= 'z')
12949 Named_object* gno = gogo->lookup_global(name.c_str());
12950 if (gno == no)
12951 name = gogo->pack_hidden_name(name, false);
12955 unsigned int index;
12956 const Struct_field* sf = st->find_local_field(name, &index);
12957 if (sf == NULL)
12959 error_at(name_expr->location(), "unknown field %qs in %qs",
12960 Gogo::message_name(name).c_str(),
12961 (type->named_type() != NULL
12962 ? type->named_type()->message_name().c_str()
12963 : "unnamed struct"));
12964 return Expression::make_error(location);
12966 if (vals[index] != NULL)
12968 error_at(name_expr->location(),
12969 "duplicate value for field %qs in %qs",
12970 Gogo::message_name(name).c_str(),
12971 (type->named_type() != NULL
12972 ? type->named_type()->message_name().c_str()
12973 : "unnamed struct"));
12974 return Expression::make_error(location);
12977 if (type->named_type() != NULL
12978 && type->named_type()->named_object()->package() != NULL
12979 && Gogo::is_hidden_name(sf->field_name()))
12980 error_at(name_expr->location(),
12981 "assignment of unexported field %qs in %qs literal",
12982 Gogo::message_name(sf->field_name()).c_str(),
12983 type->named_type()->message_name().c_str());
12985 vals[index] = val;
12986 traverse_order->push_back(index);
12989 if (!this->all_are_names_)
12991 // This is a weird case like bug462 in the testsuite.
12992 if (external_expr == NULL)
12993 error_at(this->location(), "unknown field in %qs literal",
12994 (type->named_type() != NULL
12995 ? type->named_type()->message_name().c_str()
12996 : "unnamed struct"));
12997 else
12998 error_at(external_expr->location(), "unknown field %qs in %qs",
12999 external_no->message_name().c_str(),
13000 (type->named_type() != NULL
13001 ? type->named_type()->message_name().c_str()
13002 : "unnamed struct"));
13003 return Expression::make_error(location);
13006 Expression_list* list = new Expression_list;
13007 list->reserve(field_count);
13008 for (size_t i = 0; i < field_count; ++i)
13009 list->push_back(vals[i]);
13011 Struct_construction_expression* ret =
13012 new Struct_construction_expression(type, list, location);
13013 ret->set_traverse_order(traverse_order);
13014 return ret;
13017 // Used to sort an index/value array.
13019 class Index_value_compare
13021 public:
13022 bool
13023 operator()(const std::pair<unsigned long, Expression*>& a,
13024 const std::pair<unsigned long, Expression*>& b)
13025 { return a.first < b.first; }
13028 // Lower an array composite literal.
13030 Expression*
13031 Composite_literal_expression::lower_array(Type* type)
13033 Location location = this->location();
13034 if (this->vals_ == NULL || !this->has_keys_)
13035 return this->make_array(type, NULL, this->vals_);
13037 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13038 indexes->reserve(this->vals_->size());
13039 bool indexes_out_of_order = false;
13040 Expression_list* vals = new Expression_list();
13041 vals->reserve(this->vals_->size());
13042 unsigned long index = 0;
13043 Expression_list::const_iterator p = this->vals_->begin();
13044 while (p != this->vals_->end())
13046 Expression* index_expr = *p;
13048 ++p;
13049 go_assert(p != this->vals_->end());
13050 Expression* val = *p;
13052 ++p;
13054 if (index_expr == NULL)
13056 if (!indexes->empty())
13057 indexes->push_back(index);
13059 else
13061 if (indexes->empty() && !vals->empty())
13063 for (size_t i = 0; i < vals->size(); ++i)
13064 indexes->push_back(i);
13067 Numeric_constant nc;
13068 if (!index_expr->numeric_constant_value(&nc))
13070 error_at(index_expr->location(),
13071 "index expression is not integer constant");
13072 return Expression::make_error(location);
13075 switch (nc.to_unsigned_long(&index))
13077 case Numeric_constant::NC_UL_VALID:
13078 break;
13079 case Numeric_constant::NC_UL_NOTINT:
13080 error_at(index_expr->location(),
13081 "index expression is not integer constant");
13082 return Expression::make_error(location);
13083 case Numeric_constant::NC_UL_NEGATIVE:
13084 error_at(index_expr->location(), "index expression is negative");
13085 return Expression::make_error(location);
13086 case Numeric_constant::NC_UL_BIG:
13087 error_at(index_expr->location(), "index value overflow");
13088 return Expression::make_error(location);
13089 default:
13090 go_unreachable();
13093 Named_type* ntype = Type::lookup_integer_type("int");
13094 Integer_type* inttype = ntype->integer_type();
13095 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13096 && index >> (inttype->bits() - 1) != 0)
13098 error_at(index_expr->location(), "index value overflow");
13099 return Expression::make_error(location);
13102 if (std::find(indexes->begin(), indexes->end(), index)
13103 != indexes->end())
13105 error_at(index_expr->location(), "duplicate value for index %lu",
13106 index);
13107 return Expression::make_error(location);
13110 if (!indexes->empty() && index < indexes->back())
13111 indexes_out_of_order = true;
13113 indexes->push_back(index);
13116 vals->push_back(val);
13118 ++index;
13121 if (indexes->empty())
13123 delete indexes;
13124 indexes = NULL;
13127 if (indexes_out_of_order)
13129 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13131 V v;
13132 v.reserve(indexes->size());
13133 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13134 for (Expression_list::const_iterator pe = vals->begin();
13135 pe != vals->end();
13136 ++pe, ++pi)
13137 v.push_back(std::make_pair(*pi, *pe));
13139 std::sort(v.begin(), v.end(), Index_value_compare());
13141 delete indexes;
13142 delete vals;
13143 indexes = new std::vector<unsigned long>();
13144 indexes->reserve(v.size());
13145 vals = new Expression_list();
13146 vals->reserve(v.size());
13148 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13150 indexes->push_back(p->first);
13151 vals->push_back(p->second);
13155 return this->make_array(type, indexes, vals);
13158 // Actually build the array composite literal. This handles
13159 // [...]{...}.
13161 Expression*
13162 Composite_literal_expression::make_array(
13163 Type* type,
13164 const std::vector<unsigned long>* indexes,
13165 Expression_list* vals)
13167 Location location = this->location();
13168 Array_type* at = type->array_type();
13170 if (at->length() != NULL && at->length()->is_nil_expression())
13172 size_t size;
13173 if (vals == NULL)
13174 size = 0;
13175 else if (indexes != NULL)
13176 size = indexes->back() + 1;
13177 else
13179 size = vals->size();
13180 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13181 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13182 && size >> (it->bits() - 1) != 0)
13184 error_at(location, "too many elements in composite literal");
13185 return Expression::make_error(location);
13189 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13190 at = Type::make_array_type(at->element_type(), elen);
13191 type = at;
13193 else if (at->length() != NULL
13194 && !at->length()->is_error_expression()
13195 && this->vals_ != NULL)
13197 Numeric_constant nc;
13198 unsigned long val;
13199 if (at->length()->numeric_constant_value(&nc)
13200 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13202 if (indexes == NULL)
13204 if (this->vals_->size() > val)
13206 error_at(location, "too many elements in composite literal");
13207 return Expression::make_error(location);
13210 else
13212 unsigned long max = indexes->back();
13213 if (max >= val)
13215 error_at(location,
13216 ("some element keys in composite literal "
13217 "are out of range"));
13218 return Expression::make_error(location);
13224 if (at->length() != NULL)
13225 return new Fixed_array_construction_expression(type, indexes, vals,
13226 location);
13227 else
13228 return new Slice_construction_expression(type, indexes, vals, location);
13231 // Lower a map composite literal.
13233 Expression*
13234 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13235 Statement_inserter* inserter,
13236 Type* type)
13238 Location location = this->location();
13239 if (this->vals_ != NULL)
13241 if (!this->has_keys_)
13243 error_at(location, "map composite literal must have keys");
13244 return Expression::make_error(location);
13247 for (Expression_list::iterator p = this->vals_->begin();
13248 p != this->vals_->end();
13249 p += 2)
13251 if (*p == NULL)
13253 ++p;
13254 error_at((*p)->location(),
13255 "map composite literal must have keys for every value");
13256 return Expression::make_error(location);
13258 // Make sure we have lowered the key; it may not have been
13259 // lowered in order to handle keys for struct composite
13260 // literals. Lower it now to get the right error message.
13261 if ((*p)->unknown_expression() != NULL)
13263 (*p)->unknown_expression()->clear_is_composite_literal_key();
13264 gogo->lower_expression(function, inserter, &*p);
13265 go_assert((*p)->is_error_expression());
13266 return Expression::make_error(location);
13271 return new Map_construction_expression(type, this->vals_, location);
13274 // Dump ast representation for a composite literal expression.
13276 void
13277 Composite_literal_expression::do_dump_expression(
13278 Ast_dump_context* ast_dump_context) const
13280 ast_dump_context->ostream() << "composite(";
13281 ast_dump_context->dump_type(this->type_);
13282 ast_dump_context->ostream() << ", {";
13283 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13284 ast_dump_context->ostream() << "})";
13287 // Make a composite literal expression.
13289 Expression*
13290 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13291 Expression_list* vals, bool all_are_names,
13292 Location location)
13294 return new Composite_literal_expression(type, depth, has_keys, vals,
13295 all_are_names, location);
13298 // Return whether this expression is a composite literal.
13300 bool
13301 Expression::is_composite_literal() const
13303 switch (this->classification_)
13305 case EXPRESSION_COMPOSITE_LITERAL:
13306 case EXPRESSION_STRUCT_CONSTRUCTION:
13307 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13308 case EXPRESSION_SLICE_CONSTRUCTION:
13309 case EXPRESSION_MAP_CONSTRUCTION:
13310 return true;
13311 default:
13312 return false;
13316 // Return whether this expression is a composite literal which is not
13317 // constant.
13319 bool
13320 Expression::is_nonconstant_composite_literal() const
13322 switch (this->classification_)
13324 case EXPRESSION_STRUCT_CONSTRUCTION:
13326 const Struct_construction_expression *psce =
13327 static_cast<const Struct_construction_expression*>(this);
13328 return !psce->is_constant_struct();
13330 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13332 const Fixed_array_construction_expression *pace =
13333 static_cast<const Fixed_array_construction_expression*>(this);
13334 return !pace->is_constant_array();
13336 case EXPRESSION_SLICE_CONSTRUCTION:
13338 const Slice_construction_expression *pace =
13339 static_cast<const Slice_construction_expression*>(this);
13340 return !pace->is_constant_array();
13342 case EXPRESSION_MAP_CONSTRUCTION:
13343 return true;
13344 default:
13345 return false;
13349 // Return true if this is a variable or temporary_variable.
13351 bool
13352 Expression::is_variable() const
13354 switch (this->classification_)
13356 case EXPRESSION_VAR_REFERENCE:
13357 case EXPRESSION_TEMPORARY_REFERENCE:
13358 case EXPRESSION_SET_AND_USE_TEMPORARY:
13359 return true;
13360 default:
13361 return false;
13365 // Return true if this is a reference to a local variable.
13367 bool
13368 Expression::is_local_variable() const
13370 const Var_expression* ve = this->var_expression();
13371 if (ve == NULL)
13372 return false;
13373 const Named_object* no = ve->named_object();
13374 return (no->is_result_variable()
13375 || (no->is_variable() && !no->var_value()->is_global()));
13378 // Class Type_guard_expression.
13380 // Traversal.
13383 Type_guard_expression::do_traverse(Traverse* traverse)
13385 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13386 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13387 return TRAVERSE_EXIT;
13388 return TRAVERSE_CONTINUE;
13391 Expression*
13392 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13393 Statement_inserter* inserter)
13395 if (!this->expr_->is_variable())
13397 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13398 this->location());
13399 inserter->insert(temp);
13400 this->expr_ =
13401 Expression::make_temporary_reference(temp, this->location());
13403 return this;
13406 // Check types of a type guard expression. The expression must have
13407 // an interface type, but the actual type conversion is checked at run
13408 // time.
13410 void
13411 Type_guard_expression::do_check_types(Gogo*)
13413 Type* expr_type = this->expr_->type();
13414 if (expr_type->interface_type() == NULL)
13416 if (!expr_type->is_error() && !this->type_->is_error())
13417 this->report_error(_("type assertion only valid for interface types"));
13418 this->set_is_error();
13420 else if (this->type_->interface_type() == NULL)
13422 std::string reason;
13423 if (!expr_type->interface_type()->implements_interface(this->type_,
13424 &reason))
13426 if (!this->type_->is_error())
13428 if (reason.empty())
13429 this->report_error(_("impossible type assertion: "
13430 "type does not implement interface"));
13431 else
13432 error_at(this->location(),
13433 ("impossible type assertion: "
13434 "type does not implement interface (%s)"),
13435 reason.c_str());
13437 this->set_is_error();
13442 // Return the backend representation for a type guard expression.
13444 Bexpression*
13445 Type_guard_expression::do_get_backend(Translate_context* context)
13447 Expression* conversion;
13448 if (this->type_->interface_type() != NULL)
13449 conversion =
13450 Expression::convert_interface_to_interface(this->type_, this->expr_,
13451 true, this->location());
13452 else
13453 conversion =
13454 Expression::convert_for_assignment(context->gogo(), this->type_,
13455 this->expr_, this->location());
13457 return conversion->get_backend(context);
13460 // Dump ast representation for a type guard expression.
13462 void
13463 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13464 const
13466 this->expr_->dump_expression(ast_dump_context);
13467 ast_dump_context->ostream() << ".";
13468 ast_dump_context->dump_type(this->type_);
13471 // Make a type guard expression.
13473 Expression*
13474 Expression::make_type_guard(Expression* expr, Type* type,
13475 Location location)
13477 return new Type_guard_expression(expr, type, location);
13480 // Class Heap_expression.
13482 // When you take the address of an escaping expression, it is allocated
13483 // on the heap. This class implements that.
13485 class Heap_expression : public Expression
13487 public:
13488 Heap_expression(Expression* expr, Location location)
13489 : Expression(EXPRESSION_HEAP, location),
13490 expr_(expr)
13493 protected:
13495 do_traverse(Traverse* traverse)
13496 { return Expression::traverse(&this->expr_, traverse); }
13498 Type*
13499 do_type()
13500 { return Type::make_pointer_type(this->expr_->type()); }
13502 void
13503 do_determine_type(const Type_context*)
13504 { this->expr_->determine_type_no_context(); }
13506 Expression*
13507 do_copy()
13509 return Expression::make_heap_expression(this->expr_->copy(),
13510 this->location());
13513 Bexpression*
13514 do_get_backend(Translate_context*);
13516 // We only export global objects, and the parser does not generate
13517 // this in global scope.
13518 void
13519 do_export(Export*) const
13520 { go_unreachable(); }
13522 void
13523 do_dump_expression(Ast_dump_context*) const;
13525 private:
13526 // The expression which is being put on the heap.
13527 Expression* expr_;
13530 // Return the backend representation for allocating an expression on the heap.
13532 Bexpression*
13533 Heap_expression::do_get_backend(Translate_context* context)
13535 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13536 return context->backend()->error_expression();
13538 Location loc = this->location();
13539 Gogo* gogo = context->gogo();
13540 Btype* btype = this->type()->get_backend(gogo);
13541 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13542 loc)->get_backend(context);
13544 Bstatement* decl;
13545 Named_object* fn = context->function();
13546 go_assert(fn != NULL);
13547 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13548 Bvariable* space_temp =
13549 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13550 space, true, loc, &decl);
13551 space = gogo->backend()->var_expression(space_temp, loc);
13552 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13553 Bexpression* ref =
13554 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13556 Bexpression* bexpr = this->expr_->get_backend(context);
13557 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13558 decl = gogo->backend()->compound_statement(decl, assn);
13559 space = gogo->backend()->var_expression(space_temp, loc);
13560 return gogo->backend()->compound_expression(decl, space, loc);
13563 // Dump ast representation for a heap expression.
13565 void
13566 Heap_expression::do_dump_expression(
13567 Ast_dump_context* ast_dump_context) const
13569 ast_dump_context->ostream() << "&(";
13570 ast_dump_context->dump_expression(this->expr_);
13571 ast_dump_context->ostream() << ")";
13574 // Allocate an expression on the heap.
13576 Expression*
13577 Expression::make_heap_expression(Expression* expr, Location location)
13579 return new Heap_expression(expr, location);
13582 // Class Receive_expression.
13584 // Return the type of a receive expression.
13586 Type*
13587 Receive_expression::do_type()
13589 Channel_type* channel_type = this->channel_->type()->channel_type();
13590 if (channel_type == NULL)
13591 return Type::make_error_type();
13592 return channel_type->element_type();
13595 // Check types for a receive expression.
13597 void
13598 Receive_expression::do_check_types(Gogo*)
13600 Type* type = this->channel_->type();
13601 if (type->is_error())
13603 this->set_is_error();
13604 return;
13606 if (type->channel_type() == NULL)
13608 this->report_error(_("expected channel"));
13609 return;
13611 if (!type->channel_type()->may_receive())
13613 this->report_error(_("invalid receive on send-only channel"));
13614 return;
13618 // Flattening for receive expressions creates a temporary variable to store
13619 // received data in for receives.
13621 Expression*
13622 Receive_expression::do_flatten(Gogo*, Named_object*,
13623 Statement_inserter* inserter)
13625 Channel_type* channel_type = this->channel_->type()->channel_type();
13626 if (channel_type == NULL)
13628 go_assert(saw_errors());
13629 return this;
13632 Type* element_type = channel_type->element_type();
13633 if (this->temp_receiver_ == NULL)
13635 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13636 this->location());
13637 this->temp_receiver_->set_is_address_taken();
13638 inserter->insert(this->temp_receiver_);
13641 return this;
13644 // Get the backend representation for a receive expression.
13646 Bexpression*
13647 Receive_expression::do_get_backend(Translate_context* context)
13649 Location loc = this->location();
13651 Channel_type* channel_type = this->channel_->type()->channel_type();
13652 if (channel_type == NULL)
13654 go_assert(this->channel_->type()->is_error());
13655 return context->backend()->error_expression();
13657 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13659 Expression* recv_ref =
13660 Expression::make_temporary_reference(this->temp_receiver_, loc);
13661 Expression* recv_addr =
13662 Expression::make_temporary_reference(this->temp_receiver_, loc);
13663 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13664 Expression* recv =
13665 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13666 td, this->channel_, recv_addr);
13667 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13670 // Dump ast representation for a receive expression.
13672 void
13673 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13675 ast_dump_context->ostream() << " <- " ;
13676 ast_dump_context->dump_expression(channel_);
13679 // Make a receive expression.
13681 Receive_expression*
13682 Expression::make_receive(Expression* channel, Location location)
13684 return new Receive_expression(channel, location);
13687 // An expression which evaluates to a pointer to the type descriptor
13688 // of a type.
13690 class Type_descriptor_expression : public Expression
13692 public:
13693 Type_descriptor_expression(Type* type, Location location)
13694 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13695 type_(type)
13698 protected:
13700 do_traverse(Traverse*);
13702 Type*
13703 do_type()
13704 { return Type::make_type_descriptor_ptr_type(); }
13706 bool
13707 do_is_immutable() const
13708 { return true; }
13710 void
13711 do_determine_type(const Type_context*)
13714 Expression*
13715 do_copy()
13716 { return this; }
13718 Bexpression*
13719 do_get_backend(Translate_context* context)
13721 return this->type_->type_descriptor_pointer(context->gogo(),
13722 this->location());
13725 void
13726 do_dump_expression(Ast_dump_context*) const;
13728 private:
13729 // The type for which this is the descriptor.
13730 Type* type_;
13734 Type_descriptor_expression::do_traverse(Traverse* traverse)
13736 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13737 return TRAVERSE_EXIT;
13738 return TRAVERSE_CONTINUE;
13741 // Dump ast representation for a type descriptor expression.
13743 void
13744 Type_descriptor_expression::do_dump_expression(
13745 Ast_dump_context* ast_dump_context) const
13747 ast_dump_context->dump_type(this->type_);
13750 // Make a type descriptor expression.
13752 Expression*
13753 Expression::make_type_descriptor(Type* type, Location location)
13755 return new Type_descriptor_expression(type, location);
13758 // An expression which evaluates to a pointer to the Garbage Collection symbol
13759 // of a type.
13761 class GC_symbol_expression : public Expression
13763 public:
13764 GC_symbol_expression(Type* type)
13765 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
13766 type_(type)
13769 protected:
13770 Type*
13771 do_type()
13772 { return Type::lookup_integer_type("uintptr"); }
13774 bool
13775 do_is_immutable() const
13776 { return true; }
13778 void
13779 do_determine_type(const Type_context*)
13782 Expression*
13783 do_copy()
13784 { return this; }
13786 Bexpression*
13787 do_get_backend(Translate_context* context)
13788 { return this->type_->gc_symbol_pointer(context->gogo()); }
13790 void
13791 do_dump_expression(Ast_dump_context*) const;
13793 private:
13794 // The type which this gc symbol describes.
13795 Type* type_;
13798 // Dump ast representation for a gc symbol expression.
13800 void
13801 GC_symbol_expression::do_dump_expression(
13802 Ast_dump_context* ast_dump_context) const
13804 ast_dump_context->ostream() << "gcdata(";
13805 ast_dump_context->dump_type(this->type_);
13806 ast_dump_context->ostream() << ")";
13809 // Make a gc symbol expression.
13811 Expression*
13812 Expression::make_gc_symbol(Type* type)
13814 return new GC_symbol_expression(type);
13817 // An expression which evaluates to some characteristic of a type.
13818 // This is only used to initialize fields of a type descriptor. Using
13819 // a new expression class is slightly inefficient but gives us a good
13820 // separation between the frontend and the middle-end with regard to
13821 // how types are laid out.
13823 class Type_info_expression : public Expression
13825 public:
13826 Type_info_expression(Type* type, Type_info type_info)
13827 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13828 type_(type), type_info_(type_info)
13831 protected:
13832 bool
13833 do_is_immutable() const
13834 { return true; }
13836 Type*
13837 do_type();
13839 void
13840 do_determine_type(const Type_context*)
13843 Expression*
13844 do_copy()
13845 { return this; }
13847 Bexpression*
13848 do_get_backend(Translate_context* context);
13850 void
13851 do_dump_expression(Ast_dump_context*) const;
13853 private:
13854 // The type for which we are getting information.
13855 Type* type_;
13856 // What information we want.
13857 Type_info type_info_;
13860 // The type is chosen to match what the type descriptor struct
13861 // expects.
13863 Type*
13864 Type_info_expression::do_type()
13866 switch (this->type_info_)
13868 case TYPE_INFO_SIZE:
13869 return Type::lookup_integer_type("uintptr");
13870 case TYPE_INFO_ALIGNMENT:
13871 case TYPE_INFO_FIELD_ALIGNMENT:
13872 return Type::lookup_integer_type("uint8");
13873 default:
13874 go_unreachable();
13878 // Return the backend representation for type information.
13880 Bexpression*
13881 Type_info_expression::do_get_backend(Translate_context* context)
13883 Btype* btype = this->type_->get_backend(context->gogo());
13884 Gogo* gogo = context->gogo();
13885 size_t val;
13886 switch (this->type_info_)
13888 case TYPE_INFO_SIZE:
13889 val = gogo->backend()->type_size(btype);
13890 break;
13891 case TYPE_INFO_ALIGNMENT:
13892 val = gogo->backend()->type_alignment(btype);
13893 break;
13894 case TYPE_INFO_FIELD_ALIGNMENT:
13895 val = gogo->backend()->type_field_alignment(btype);
13896 break;
13897 default:
13898 go_unreachable();
13900 mpz_t cst;
13901 mpz_init_set_ui(cst, val);
13902 Btype* int_btype = this->type()->get_backend(gogo);
13903 Bexpression* ret =
13904 gogo->backend()->integer_constant_expression(int_btype, cst);
13905 mpz_clear(cst);
13906 return ret;
13909 // Dump ast representation for a type info expression.
13911 void
13912 Type_info_expression::do_dump_expression(
13913 Ast_dump_context* ast_dump_context) const
13915 ast_dump_context->ostream() << "typeinfo(";
13916 ast_dump_context->dump_type(this->type_);
13917 ast_dump_context->ostream() << ",";
13918 ast_dump_context->ostream() <<
13919 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13920 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13921 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13922 : "unknown");
13923 ast_dump_context->ostream() << ")";
13926 // Make a type info expression.
13928 Expression*
13929 Expression::make_type_info(Type* type, Type_info type_info)
13931 return new Type_info_expression(type, type_info);
13934 // An expression that evaluates to some characteristic of a slice.
13935 // This is used when indexing, bound-checking, or nil checking a slice.
13937 class Slice_info_expression : public Expression
13939 public:
13940 Slice_info_expression(Expression* slice, Slice_info slice_info,
13941 Location location)
13942 : Expression(EXPRESSION_SLICE_INFO, location),
13943 slice_(slice), slice_info_(slice_info)
13946 protected:
13947 Type*
13948 do_type();
13950 void
13951 do_determine_type(const Type_context*)
13954 Expression*
13955 do_copy()
13957 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
13958 this->location());
13961 Bexpression*
13962 do_get_backend(Translate_context* context);
13964 void
13965 do_dump_expression(Ast_dump_context*) const;
13967 void
13968 do_issue_nil_check()
13969 { this->slice_->issue_nil_check(); }
13971 private:
13972 // The slice for which we are getting information.
13973 Expression* slice_;
13974 // What information we want.
13975 Slice_info slice_info_;
13978 // Return the type of the slice info.
13980 Type*
13981 Slice_info_expression::do_type()
13983 switch (this->slice_info_)
13985 case SLICE_INFO_VALUE_POINTER:
13986 return Type::make_pointer_type(
13987 this->slice_->type()->array_type()->element_type());
13988 case SLICE_INFO_LENGTH:
13989 case SLICE_INFO_CAPACITY:
13990 return Type::lookup_integer_type("int");
13991 default:
13992 go_unreachable();
13996 // Return the backend information for slice information.
13998 Bexpression*
13999 Slice_info_expression::do_get_backend(Translate_context* context)
14001 Gogo* gogo = context->gogo();
14002 Bexpression* bslice = this->slice_->get_backend(context);
14003 switch (this->slice_info_)
14005 case SLICE_INFO_VALUE_POINTER:
14006 case SLICE_INFO_LENGTH:
14007 case SLICE_INFO_CAPACITY:
14008 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14009 this->location());
14010 break;
14011 default:
14012 go_unreachable();
14016 // Dump ast representation for a type info expression.
14018 void
14019 Slice_info_expression::do_dump_expression(
14020 Ast_dump_context* ast_dump_context) const
14022 ast_dump_context->ostream() << "sliceinfo(";
14023 this->slice_->dump_expression(ast_dump_context);
14024 ast_dump_context->ostream() << ",";
14025 ast_dump_context->ostream() <<
14026 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14027 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14028 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14029 : "unknown");
14030 ast_dump_context->ostream() << ")";
14033 // Make a slice info expression.
14035 Expression*
14036 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14037 Location location)
14039 return new Slice_info_expression(slice, slice_info, location);
14042 // An expression that represents a slice value: a struct with value pointer,
14043 // length, and capacity fields.
14045 class Slice_value_expression : public Expression
14047 public:
14048 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14049 Expression* cap, Location location)
14050 : Expression(EXPRESSION_SLICE_VALUE, location),
14051 type_(type), valptr_(valptr), len_(len), cap_(cap)
14054 protected:
14056 do_traverse(Traverse*);
14058 Type*
14059 do_type()
14060 { return this->type_; }
14062 void
14063 do_determine_type(const Type_context*)
14064 { go_unreachable(); }
14066 Expression*
14067 do_copy()
14069 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14070 this->len_->copy(), this->cap_->copy(),
14071 this->location());
14074 Bexpression*
14075 do_get_backend(Translate_context* context);
14077 void
14078 do_dump_expression(Ast_dump_context*) const;
14080 private:
14081 // The type of the slice value.
14082 Type* type_;
14083 // The pointer to the values in the slice.
14084 Expression* valptr_;
14085 // The length of the slice.
14086 Expression* len_;
14087 // The capacity of the slice.
14088 Expression* cap_;
14092 Slice_value_expression::do_traverse(Traverse* traverse)
14094 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14095 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14096 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14097 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14098 return TRAVERSE_EXIT;
14099 return TRAVERSE_CONTINUE;
14102 Bexpression*
14103 Slice_value_expression::do_get_backend(Translate_context* context)
14105 std::vector<Bexpression*> vals(3);
14106 vals[0] = this->valptr_->get_backend(context);
14107 vals[1] = this->len_->get_backend(context);
14108 vals[2] = this->cap_->get_backend(context);
14110 Gogo* gogo = context->gogo();
14111 Btype* btype = this->type_->get_backend(gogo);
14112 return gogo->backend()->constructor_expression(btype, vals, this->location());
14115 void
14116 Slice_value_expression::do_dump_expression(
14117 Ast_dump_context* ast_dump_context) const
14119 ast_dump_context->ostream() << "slicevalue(";
14120 ast_dump_context->ostream() << "values: ";
14121 this->valptr_->dump_expression(ast_dump_context);
14122 ast_dump_context->ostream() << ", length: ";
14123 this->len_->dump_expression(ast_dump_context);
14124 ast_dump_context->ostream() << ", capacity: ";
14125 this->cap_->dump_expression(ast_dump_context);
14126 ast_dump_context->ostream() << ")";
14129 Expression*
14130 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14131 Expression* cap, Location location)
14133 go_assert(at->is_slice_type());
14134 return new Slice_value_expression(at, valptr, len, cap, location);
14137 // An expression that evaluates to some characteristic of a non-empty interface.
14138 // This is used to access the method table or underlying object of an interface.
14140 class Interface_info_expression : public Expression
14142 public:
14143 Interface_info_expression(Expression* iface, Interface_info iface_info,
14144 Location location)
14145 : Expression(EXPRESSION_INTERFACE_INFO, location),
14146 iface_(iface), iface_info_(iface_info)
14149 protected:
14150 Type*
14151 do_type();
14153 void
14154 do_determine_type(const Type_context*)
14157 Expression*
14158 do_copy()
14160 return new Interface_info_expression(this->iface_->copy(),
14161 this->iface_info_, this->location());
14164 Bexpression*
14165 do_get_backend(Translate_context* context);
14167 void
14168 do_dump_expression(Ast_dump_context*) const;
14170 void
14171 do_issue_nil_check()
14172 { this->iface_->issue_nil_check(); }
14174 private:
14175 // The interface for which we are getting information.
14176 Expression* iface_;
14177 // What information we want.
14178 Interface_info iface_info_;
14181 // Return the type of the interface info.
14183 Type*
14184 Interface_info_expression::do_type()
14186 switch (this->iface_info_)
14188 case INTERFACE_INFO_METHODS:
14190 Type* pdt = Type::make_type_descriptor_ptr_type();
14191 if (this->iface_->type()->interface_type()->is_empty())
14192 return pdt;
14194 Location loc = this->location();
14195 Struct_field_list* sfl = new Struct_field_list();
14196 sfl->push_back(
14197 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14199 Interface_type* itype = this->iface_->type()->interface_type();
14200 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14201 p != itype->methods()->end();
14202 ++p)
14204 Function_type* ft = p->type()->function_type();
14205 go_assert(ft->receiver() == NULL);
14207 const Typed_identifier_list* params = ft->parameters();
14208 Typed_identifier_list* mparams = new Typed_identifier_list();
14209 if (params != NULL)
14210 mparams->reserve(params->size() + 1);
14211 Type* vt = Type::make_pointer_type(Type::make_void_type());
14212 mparams->push_back(Typed_identifier("", vt, ft->location()));
14213 if (params != NULL)
14215 for (Typed_identifier_list::const_iterator pp = params->begin();
14216 pp != params->end();
14217 ++pp)
14218 mparams->push_back(*pp);
14221 Typed_identifier_list* mresults = (ft->results() == NULL
14222 ? NULL
14223 : ft->results()->copy());
14224 Backend_function_type* mft =
14225 Type::make_backend_function_type(NULL, mparams, mresults,
14226 ft->location());
14228 std::string fname = Gogo::unpack_hidden_name(p->name());
14229 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14232 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14234 case INTERFACE_INFO_OBJECT:
14235 return Type::make_pointer_type(Type::make_void_type());
14236 default:
14237 go_unreachable();
14241 // Return the backend representation for interface information.
14243 Bexpression*
14244 Interface_info_expression::do_get_backend(Translate_context* context)
14246 Gogo* gogo = context->gogo();
14247 Bexpression* biface = this->iface_->get_backend(context);
14248 switch (this->iface_info_)
14250 case INTERFACE_INFO_METHODS:
14251 case INTERFACE_INFO_OBJECT:
14252 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14253 this->location());
14254 break;
14255 default:
14256 go_unreachable();
14260 // Dump ast representation for an interface info expression.
14262 void
14263 Interface_info_expression::do_dump_expression(
14264 Ast_dump_context* ast_dump_context) const
14266 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14267 ast_dump_context->ostream() << "interfaceinfo(";
14268 this->iface_->dump_expression(ast_dump_context);
14269 ast_dump_context->ostream() << ",";
14270 ast_dump_context->ostream() <<
14271 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14272 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14273 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14274 : "unknown");
14275 ast_dump_context->ostream() << ")";
14278 // Make an interface info expression.
14280 Expression*
14281 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14282 Location location)
14284 return new Interface_info_expression(iface, iface_info, location);
14287 // An expression that represents an interface value. The first field is either
14288 // a type descriptor for an empty interface or a pointer to the interface method
14289 // table for a non-empty interface. The second field is always the object.
14291 class Interface_value_expression : public Expression
14293 public:
14294 Interface_value_expression(Type* type, Expression* first_field,
14295 Expression* obj, Location location)
14296 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14297 type_(type), first_field_(first_field), obj_(obj)
14300 protected:
14302 do_traverse(Traverse*);
14304 Type*
14305 do_type()
14306 { return this->type_; }
14308 void
14309 do_determine_type(const Type_context*)
14310 { go_unreachable(); }
14312 Expression*
14313 do_copy()
14315 return new Interface_value_expression(this->type_,
14316 this->first_field_->copy(),
14317 this->obj_->copy(), this->location());
14320 Bexpression*
14321 do_get_backend(Translate_context* context);
14323 void
14324 do_dump_expression(Ast_dump_context*) const;
14326 private:
14327 // The type of the interface value.
14328 Type* type_;
14329 // The first field of the interface (either a type descriptor or a pointer
14330 // to the method table.
14331 Expression* first_field_;
14332 // The underlying object of the interface.
14333 Expression* obj_;
14337 Interface_value_expression::do_traverse(Traverse* traverse)
14339 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14340 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14341 return TRAVERSE_EXIT;
14342 return TRAVERSE_CONTINUE;
14345 Bexpression*
14346 Interface_value_expression::do_get_backend(Translate_context* context)
14348 std::vector<Bexpression*> vals(2);
14349 vals[0] = this->first_field_->get_backend(context);
14350 vals[1] = this->obj_->get_backend(context);
14352 Gogo* gogo = context->gogo();
14353 Btype* btype = this->type_->get_backend(gogo);
14354 return gogo->backend()->constructor_expression(btype, vals, this->location());
14357 void
14358 Interface_value_expression::do_dump_expression(
14359 Ast_dump_context* ast_dump_context) const
14361 ast_dump_context->ostream() << "interfacevalue(";
14362 ast_dump_context->ostream() <<
14363 (this->type_->interface_type()->is_empty()
14364 ? "type_descriptor: "
14365 : "methods: ");
14366 this->first_field_->dump_expression(ast_dump_context);
14367 ast_dump_context->ostream() << ", object: ";
14368 this->obj_->dump_expression(ast_dump_context);
14369 ast_dump_context->ostream() << ")";
14372 Expression*
14373 Expression::make_interface_value(Type* type, Expression* first_value,
14374 Expression* object, Location location)
14376 return new Interface_value_expression(type, first_value, object, location);
14379 // An interface method table for a pair of types: an interface type and a type
14380 // that implements that interface.
14382 class Interface_mtable_expression : public Expression
14384 public:
14385 Interface_mtable_expression(Interface_type* itype, Type* type,
14386 bool is_pointer, Location location)
14387 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14388 itype_(itype), type_(type), is_pointer_(is_pointer),
14389 method_table_type_(NULL), bvar_(NULL)
14392 protected:
14394 do_traverse(Traverse*);
14396 Type*
14397 do_type();
14399 bool
14400 is_immutable() const
14401 { return true; }
14403 void
14404 do_determine_type(const Type_context*)
14405 { go_unreachable(); }
14407 Expression*
14408 do_copy()
14410 return new Interface_mtable_expression(this->itype_, this->type_,
14411 this->is_pointer_, this->location());
14414 bool
14415 do_is_addressable() const
14416 { return true; }
14418 Bexpression*
14419 do_get_backend(Translate_context* context);
14421 void
14422 do_dump_expression(Ast_dump_context*) const;
14424 private:
14425 // The interface type for which the methods are defined.
14426 Interface_type* itype_;
14427 // The type to construct the interface method table for.
14428 Type* type_;
14429 // Whether this table contains the method set for the receiver type or the
14430 // pointer receiver type.
14431 bool is_pointer_;
14432 // The type of the method table.
14433 Type* method_table_type_;
14434 // The backend variable that refers to the interface method table.
14435 Bvariable* bvar_;
14439 Interface_mtable_expression::do_traverse(Traverse* traverse)
14441 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14442 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14443 return TRAVERSE_EXIT;
14444 return TRAVERSE_CONTINUE;
14447 Type*
14448 Interface_mtable_expression::do_type()
14450 if (this->method_table_type_ != NULL)
14451 return this->method_table_type_;
14453 const Typed_identifier_list* interface_methods = this->itype_->methods();
14454 go_assert(!interface_methods->empty());
14456 Struct_field_list* sfl = new Struct_field_list;
14457 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14458 this->location());
14459 sfl->push_back(Struct_field(tid));
14460 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14461 p != interface_methods->end();
14462 ++p)
14463 sfl->push_back(Struct_field(*p));
14464 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14465 return this->method_table_type_;
14468 Bexpression*
14469 Interface_mtable_expression::do_get_backend(Translate_context* context)
14471 Gogo* gogo = context->gogo();
14472 Location loc = Linemap::predeclared_location();
14473 if (this->bvar_ != NULL)
14474 return gogo->backend()->var_expression(this->bvar_, this->location());
14476 const Typed_identifier_list* interface_methods = this->itype_->methods();
14477 go_assert(!interface_methods->empty());
14479 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14480 + this->itype_->mangled_name(gogo)
14481 + "__"
14482 + this->type_->mangled_name(gogo));
14484 // See whether this interface has any hidden methods.
14485 bool has_hidden_methods = false;
14486 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14487 p != interface_methods->end();
14488 ++p)
14490 if (Gogo::is_hidden_name(p->name()))
14492 has_hidden_methods = true;
14493 break;
14497 // We already know that the named type is convertible to the
14498 // interface. If the interface has hidden methods, and the named
14499 // type is defined in a different package, then the interface
14500 // conversion table will be defined by that other package.
14501 if (has_hidden_methods
14502 && this->type_->named_type() != NULL
14503 && this->type_->named_type()->named_object()->package() != NULL)
14505 Btype* btype = this->type()->get_backend(gogo);
14506 this->bvar_ =
14507 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14508 return gogo->backend()->var_expression(this->bvar_, this->location());
14511 // The first element is the type descriptor.
14512 Type* td_type;
14513 if (!this->is_pointer_)
14514 td_type = this->type_;
14515 else
14516 td_type = Type::make_pointer_type(this->type_);
14518 // Build an interface method table for a type: a type descriptor followed by a
14519 // list of function pointers, one for each interface method. This is used for
14520 // interfaces.
14521 Expression_list* svals = new Expression_list();
14522 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14524 Named_type* nt = this->type_->named_type();
14525 Struct_type* st = this->type_->struct_type();
14526 go_assert(nt != NULL || st != NULL);
14528 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14529 p != interface_methods->end();
14530 ++p)
14532 bool is_ambiguous;
14533 Method* m;
14534 if (nt != NULL)
14535 m = nt->method_function(p->name(), &is_ambiguous);
14536 else
14537 m = st->method_function(p->name(), &is_ambiguous);
14538 go_assert(m != NULL);
14539 Named_object* no = m->named_object();
14541 go_assert(no->is_function() || no->is_function_declaration());
14542 svals->push_back(Expression::make_func_code_reference(no, loc));
14545 Btype* btype = this->type()->get_backend(gogo);
14546 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14547 svals, loc);
14548 Bexpression* ctor = mtable->get_backend(context);
14550 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14551 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14552 !is_public, btype, loc);
14553 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14554 !is_public, btype, loc, ctor);
14555 return gogo->backend()->var_expression(this->bvar_, loc);
14558 void
14559 Interface_mtable_expression::do_dump_expression(
14560 Ast_dump_context* ast_dump_context) const
14562 ast_dump_context->ostream() << "__go_"
14563 << (this->is_pointer_ ? "pimt__" : "imt_");
14564 ast_dump_context->dump_type(this->itype_);
14565 ast_dump_context->ostream() << "__";
14566 ast_dump_context->dump_type(this->type_);
14569 Expression*
14570 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14571 bool is_pointer, Location location)
14573 return new Interface_mtable_expression(itype, type, is_pointer, location);
14576 // An expression which evaluates to the offset of a field within a
14577 // struct. This, like Type_info_expression, q.v., is only used to
14578 // initialize fields of a type descriptor.
14580 class Struct_field_offset_expression : public Expression
14582 public:
14583 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14584 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14585 Linemap::predeclared_location()),
14586 type_(type), field_(field)
14589 protected:
14590 bool
14591 do_is_immutable() const
14592 { return true; }
14594 Type*
14595 do_type()
14596 { return Type::lookup_integer_type("uintptr"); }
14598 void
14599 do_determine_type(const Type_context*)
14602 Expression*
14603 do_copy()
14604 { return this; }
14606 Bexpression*
14607 do_get_backend(Translate_context* context);
14609 void
14610 do_dump_expression(Ast_dump_context*) const;
14612 private:
14613 // The type of the struct.
14614 Struct_type* type_;
14615 // The field.
14616 const Struct_field* field_;
14619 // Return the backend representation for a struct field offset.
14621 Bexpression*
14622 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14624 const Struct_field_list* fields = this->type_->fields();
14625 Struct_field_list::const_iterator p;
14626 unsigned i = 0;
14627 for (p = fields->begin();
14628 p != fields->end();
14629 ++p, ++i)
14630 if (&*p == this->field_)
14631 break;
14632 go_assert(&*p == this->field_);
14634 Gogo* gogo = context->gogo();
14635 Btype* btype = this->type_->get_backend(gogo);
14637 size_t offset = gogo->backend()->type_field_offset(btype, i);
14638 Type* uptr_type = Type::lookup_integer_type("uintptr");
14639 Expression* ret =
14640 Expression::make_integer_ul(offset, uptr_type,
14641 Linemap::predeclared_location());
14642 return ret->get_backend(context);
14645 // Dump ast representation for a struct field offset expression.
14647 void
14648 Struct_field_offset_expression::do_dump_expression(
14649 Ast_dump_context* ast_dump_context) const
14651 ast_dump_context->ostream() << "unsafe.Offsetof(";
14652 ast_dump_context->dump_type(this->type_);
14653 ast_dump_context->ostream() << '.';
14654 ast_dump_context->ostream() <<
14655 Gogo::message_name(this->field_->field_name());
14656 ast_dump_context->ostream() << ")";
14659 // Make an expression for a struct field offset.
14661 Expression*
14662 Expression::make_struct_field_offset(Struct_type* type,
14663 const Struct_field* field)
14665 return new Struct_field_offset_expression(type, field);
14668 // An expression which evaluates to a pointer to the map descriptor of
14669 // a map type.
14671 class Map_descriptor_expression : public Expression
14673 public:
14674 Map_descriptor_expression(Map_type* type, Location location)
14675 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14676 type_(type)
14679 protected:
14680 Type*
14681 do_type()
14682 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14684 void
14685 do_determine_type(const Type_context*)
14688 Expression*
14689 do_copy()
14690 { return this; }
14692 Bexpression*
14693 do_get_backend(Translate_context* context)
14695 return this->type_->map_descriptor_pointer(context->gogo(),
14696 this->location());
14699 void
14700 do_dump_expression(Ast_dump_context*) const;
14702 private:
14703 // The type for which this is the descriptor.
14704 Map_type* type_;
14707 // Dump ast representation for a map descriptor expression.
14709 void
14710 Map_descriptor_expression::do_dump_expression(
14711 Ast_dump_context* ast_dump_context) const
14713 ast_dump_context->ostream() << "map_descriptor(";
14714 ast_dump_context->dump_type(this->type_);
14715 ast_dump_context->ostream() << ")";
14718 // Make a map descriptor expression.
14720 Expression*
14721 Expression::make_map_descriptor(Map_type* type, Location location)
14723 return new Map_descriptor_expression(type, location);
14726 // An expression which evaluates to the address of an unnamed label.
14728 class Label_addr_expression : public Expression
14730 public:
14731 Label_addr_expression(Label* label, Location location)
14732 : Expression(EXPRESSION_LABEL_ADDR, location),
14733 label_(label)
14736 protected:
14737 Type*
14738 do_type()
14739 { return Type::make_pointer_type(Type::make_void_type()); }
14741 void
14742 do_determine_type(const Type_context*)
14745 Expression*
14746 do_copy()
14747 { return new Label_addr_expression(this->label_, this->location()); }
14749 Bexpression*
14750 do_get_backend(Translate_context* context)
14751 { return this->label_->get_addr(context, this->location()); }
14753 void
14754 do_dump_expression(Ast_dump_context* ast_dump_context) const
14755 { ast_dump_context->ostream() << this->label_->name(); }
14757 private:
14758 // The label whose address we are taking.
14759 Label* label_;
14762 // Make an expression for the address of an unnamed label.
14764 Expression*
14765 Expression::make_label_addr(Label* label, Location location)
14767 return new Label_addr_expression(label, location);
14770 // Conditional expressions.
14772 class Conditional_expression : public Expression
14774 public:
14775 Conditional_expression(Expression* cond, Expression* then_expr,
14776 Expression* else_expr, Location location)
14777 : Expression(EXPRESSION_CONDITIONAL, location),
14778 cond_(cond), then_(then_expr), else_(else_expr)
14781 protected:
14783 do_traverse(Traverse*);
14785 Type*
14786 do_type();
14788 void
14789 do_determine_type(const Type_context*);
14791 Expression*
14792 do_copy()
14794 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14795 this->else_->copy(), this->location());
14798 Bexpression*
14799 do_get_backend(Translate_context* context);
14801 void
14802 do_dump_expression(Ast_dump_context*) const;
14804 private:
14805 // The condition to be checked.
14806 Expression* cond_;
14807 // The expression to execute if the condition is true.
14808 Expression* then_;
14809 // The expression to execute if the condition is false.
14810 Expression* else_;
14813 // Traversal.
14816 Conditional_expression::do_traverse(Traverse* traverse)
14818 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14819 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14820 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14821 return TRAVERSE_EXIT;
14822 return TRAVERSE_CONTINUE;
14825 // Return the type of the conditional expression.
14827 Type*
14828 Conditional_expression::do_type()
14830 Type* result_type = Type::make_void_type();
14831 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14832 NULL))
14833 result_type = this->then_->type();
14834 else if (this->then_->is_nil_expression()
14835 || this->else_->is_nil_expression())
14836 result_type = (!this->then_->is_nil_expression()
14837 ? this->then_->type()
14838 : this->else_->type());
14839 return result_type;
14842 // Determine type for a conditional expression.
14844 void
14845 Conditional_expression::do_determine_type(const Type_context* context)
14847 this->cond_->determine_type_no_context();
14848 this->then_->determine_type(context);
14849 this->else_->determine_type(context);
14852 // Get the backend representation of a conditional expression.
14854 Bexpression*
14855 Conditional_expression::do_get_backend(Translate_context* context)
14857 Gogo* gogo = context->gogo();
14858 Btype* result_btype = this->type()->get_backend(gogo);
14859 Bexpression* cond = this->cond_->get_backend(context);
14860 Bexpression* then = this->then_->get_backend(context);
14861 Bexpression* belse = this->else_->get_backend(context);
14862 return gogo->backend()->conditional_expression(result_btype, cond, then,
14863 belse, this->location());
14866 // Dump ast representation of a conditional expression.
14868 void
14869 Conditional_expression::do_dump_expression(
14870 Ast_dump_context* ast_dump_context) const
14872 ast_dump_context->ostream() << "(";
14873 ast_dump_context->dump_expression(this->cond_);
14874 ast_dump_context->ostream() << " ? ";
14875 ast_dump_context->dump_expression(this->then_);
14876 ast_dump_context->ostream() << " : ";
14877 ast_dump_context->dump_expression(this->else_);
14878 ast_dump_context->ostream() << ") ";
14881 // Make a conditional expression.
14883 Expression*
14884 Expression::make_conditional(Expression* cond, Expression* then,
14885 Expression* else_expr, Location location)
14887 return new Conditional_expression(cond, then, else_expr, location);
14890 // Compound expressions.
14892 class Compound_expression : public Expression
14894 public:
14895 Compound_expression(Expression* init, Expression* expr, Location location)
14896 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
14899 protected:
14901 do_traverse(Traverse*);
14903 Type*
14904 do_type();
14906 void
14907 do_determine_type(const Type_context*);
14909 Expression*
14910 do_copy()
14912 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
14913 this->location());
14916 Bexpression*
14917 do_get_backend(Translate_context* context);
14919 void
14920 do_dump_expression(Ast_dump_context*) const;
14922 private:
14923 // The expression that is evaluated first and discarded.
14924 Expression* init_;
14925 // The expression that is evaluated and returned.
14926 Expression* expr_;
14929 // Traversal.
14932 Compound_expression::do_traverse(Traverse* traverse)
14934 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
14935 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
14936 return TRAVERSE_EXIT;
14937 return TRAVERSE_CONTINUE;
14940 // Return the type of the compound expression.
14942 Type*
14943 Compound_expression::do_type()
14945 return this->expr_->type();
14948 // Determine type for a compound expression.
14950 void
14951 Compound_expression::do_determine_type(const Type_context* context)
14953 this->init_->determine_type_no_context();
14954 this->expr_->determine_type(context);
14957 // Get the backend representation of a compound expression.
14959 Bexpression*
14960 Compound_expression::do_get_backend(Translate_context* context)
14962 Gogo* gogo = context->gogo();
14963 Bexpression* binit = this->init_->get_backend(context);
14964 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
14965 Bexpression* bexpr = this->expr_->get_backend(context);
14966 return gogo->backend()->compound_expression(init_stmt, bexpr,
14967 this->location());
14970 // Dump ast representation of a conditional expression.
14972 void
14973 Compound_expression::do_dump_expression(
14974 Ast_dump_context* ast_dump_context) const
14976 ast_dump_context->ostream() << "(";
14977 ast_dump_context->dump_expression(this->init_);
14978 ast_dump_context->ostream() << ",";
14979 ast_dump_context->dump_expression(this->expr_);
14980 ast_dump_context->ostream() << ") ";
14983 // Make a compound expression.
14985 Expression*
14986 Expression::make_compound(Expression* init, Expression* expr, Location location)
14988 return new Compound_expression(init, expr, location);
14991 // Import an expression. This comes at the end in order to see the
14992 // various class definitions.
14994 Expression*
14995 Expression::import_expression(Import* imp)
14997 int c = imp->peek_char();
14998 if (imp->match_c_string("- ")
14999 || imp->match_c_string("! ")
15000 || imp->match_c_string("^ "))
15001 return Unary_expression::do_import(imp);
15002 else if (c == '(')
15003 return Binary_expression::do_import(imp);
15004 else if (imp->match_c_string("true")
15005 || imp->match_c_string("false"))
15006 return Boolean_expression::do_import(imp);
15007 else if (c == '"')
15008 return String_expression::do_import(imp);
15009 else if (c == '-' || (c >= '0' && c <= '9'))
15011 // This handles integers, floats and complex constants.
15012 return Integer_expression::do_import(imp);
15014 else if (imp->match_c_string("nil"))
15015 return Nil_expression::do_import(imp);
15016 else if (imp->match_c_string("convert"))
15017 return Type_conversion_expression::do_import(imp);
15018 else
15020 error_at(imp->location(), "import error: expected expression");
15021 return Expression::make_error(imp->location());
15025 // Class Expression_list.
15027 // Traverse the list.
15030 Expression_list::traverse(Traverse* traverse)
15032 for (Expression_list::iterator p = this->begin();
15033 p != this->end();
15034 ++p)
15036 if (*p != NULL)
15038 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15039 return TRAVERSE_EXIT;
15042 return TRAVERSE_CONTINUE;
15045 // Copy the list.
15047 Expression_list*
15048 Expression_list::copy()
15050 Expression_list* ret = new Expression_list();
15051 for (Expression_list::iterator p = this->begin();
15052 p != this->end();
15053 ++p)
15055 if (*p == NULL)
15056 ret->push_back(NULL);
15057 else
15058 ret->push_back((*p)->copy());
15060 return ret;
15063 // Return whether an expression list has an error expression.
15065 bool
15066 Expression_list::contains_error() const
15068 for (Expression_list::const_iterator p = this->begin();
15069 p != this->end();
15070 ++p)
15071 if (*p != NULL && (*p)->is_error_expression())
15072 return true;
15073 return false;
15076 // Class Numeric_constant.
15078 // Destructor.
15080 Numeric_constant::~Numeric_constant()
15082 this->clear();
15085 // Copy constructor.
15087 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15088 : classification_(a.classification_), type_(a.type_)
15090 switch (a.classification_)
15092 case NC_INVALID:
15093 break;
15094 case NC_INT:
15095 case NC_RUNE:
15096 mpz_init_set(this->u_.int_val, a.u_.int_val);
15097 break;
15098 case NC_FLOAT:
15099 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15100 break;
15101 case NC_COMPLEX:
15102 mpc_init2(this->u_.complex_val, mpc_precision);
15103 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15104 break;
15105 default:
15106 go_unreachable();
15110 // Assignment operator.
15112 Numeric_constant&
15113 Numeric_constant::operator=(const Numeric_constant& a)
15115 this->clear();
15116 this->classification_ = a.classification_;
15117 this->type_ = a.type_;
15118 switch (a.classification_)
15120 case NC_INVALID:
15121 break;
15122 case NC_INT:
15123 case NC_RUNE:
15124 mpz_init_set(this->u_.int_val, a.u_.int_val);
15125 break;
15126 case NC_FLOAT:
15127 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15128 break;
15129 case NC_COMPLEX:
15130 mpc_init2(this->u_.complex_val, mpc_precision);
15131 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15132 break;
15133 default:
15134 go_unreachable();
15136 return *this;
15139 // Clear the contents.
15141 void
15142 Numeric_constant::clear()
15144 switch (this->classification_)
15146 case NC_INVALID:
15147 break;
15148 case NC_INT:
15149 case NC_RUNE:
15150 mpz_clear(this->u_.int_val);
15151 break;
15152 case NC_FLOAT:
15153 mpfr_clear(this->u_.float_val);
15154 break;
15155 case NC_COMPLEX:
15156 mpc_clear(this->u_.complex_val);
15157 break;
15158 default:
15159 go_unreachable();
15161 this->classification_ = NC_INVALID;
15164 // Set to an unsigned long value.
15166 void
15167 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15169 this->clear();
15170 this->classification_ = NC_INT;
15171 this->type_ = type;
15172 mpz_init_set_ui(this->u_.int_val, val);
15175 // Set to an integer value.
15177 void
15178 Numeric_constant::set_int(Type* type, const mpz_t val)
15180 this->clear();
15181 this->classification_ = NC_INT;
15182 this->type_ = type;
15183 mpz_init_set(this->u_.int_val, val);
15186 // Set to a rune value.
15188 void
15189 Numeric_constant::set_rune(Type* type, const mpz_t val)
15191 this->clear();
15192 this->classification_ = NC_RUNE;
15193 this->type_ = type;
15194 mpz_init_set(this->u_.int_val, val);
15197 // Set to a floating point value.
15199 void
15200 Numeric_constant::set_float(Type* type, const mpfr_t val)
15202 this->clear();
15203 this->classification_ = NC_FLOAT;
15204 this->type_ = type;
15205 // Numeric constants do not have negative zero values, so remove
15206 // them here. They also don't have infinity or NaN values, but we
15207 // should never see them here.
15208 if (mpfr_zero_p(val))
15209 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15210 else
15211 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15214 // Set to a complex value.
15216 void
15217 Numeric_constant::set_complex(Type* type, const mpc_t val)
15219 this->clear();
15220 this->classification_ = NC_COMPLEX;
15221 this->type_ = type;
15222 mpc_init2(this->u_.complex_val, mpc_precision);
15223 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
15226 // Get an int value.
15228 void
15229 Numeric_constant::get_int(mpz_t* val) const
15231 go_assert(this->is_int());
15232 mpz_init_set(*val, this->u_.int_val);
15235 // Get a rune value.
15237 void
15238 Numeric_constant::get_rune(mpz_t* val) const
15240 go_assert(this->is_rune());
15241 mpz_init_set(*val, this->u_.int_val);
15244 // Get a floating point value.
15246 void
15247 Numeric_constant::get_float(mpfr_t* val) const
15249 go_assert(this->is_float());
15250 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15253 // Get a complex value.
15255 void
15256 Numeric_constant::get_complex(mpc_t* val) const
15258 go_assert(this->is_complex());
15259 mpc_init2(*val, mpc_precision);
15260 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15263 // Express value as unsigned long if possible.
15265 Numeric_constant::To_unsigned_long
15266 Numeric_constant::to_unsigned_long(unsigned long* val) const
15268 switch (this->classification_)
15270 case NC_INT:
15271 case NC_RUNE:
15272 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15273 case NC_FLOAT:
15274 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15275 case NC_COMPLEX:
15276 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15277 return NC_UL_NOTINT;
15278 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15279 val);
15280 default:
15281 go_unreachable();
15285 // Express integer value as unsigned long if possible.
15287 Numeric_constant::To_unsigned_long
15288 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15289 unsigned long *val) const
15291 if (mpz_sgn(ival) < 0)
15292 return NC_UL_NEGATIVE;
15293 unsigned long ui = mpz_get_ui(ival);
15294 if (mpz_cmp_ui(ival, ui) != 0)
15295 return NC_UL_BIG;
15296 *val = ui;
15297 return NC_UL_VALID;
15300 // Express floating point value as unsigned long if possible.
15302 Numeric_constant::To_unsigned_long
15303 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15304 unsigned long *val) const
15306 if (!mpfr_integer_p(fval))
15307 return NC_UL_NOTINT;
15308 mpz_t ival;
15309 mpz_init(ival);
15310 mpfr_get_z(ival, fval, GMP_RNDN);
15311 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15312 mpz_clear(ival);
15313 return ret;
15316 // Convert value to integer if possible.
15318 bool
15319 Numeric_constant::to_int(mpz_t* val) const
15321 switch (this->classification_)
15323 case NC_INT:
15324 case NC_RUNE:
15325 mpz_init_set(*val, this->u_.int_val);
15326 return true;
15327 case NC_FLOAT:
15328 if (!mpfr_integer_p(this->u_.float_val))
15329 return false;
15330 mpz_init(*val);
15331 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15332 return true;
15333 case NC_COMPLEX:
15334 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15335 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
15336 return false;
15337 mpz_init(*val);
15338 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15339 return true;
15340 default:
15341 go_unreachable();
15345 // Convert value to floating point if possible.
15347 bool
15348 Numeric_constant::to_float(mpfr_t* val) const
15350 switch (this->classification_)
15352 case NC_INT:
15353 case NC_RUNE:
15354 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15355 return true;
15356 case NC_FLOAT:
15357 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15358 return true;
15359 case NC_COMPLEX:
15360 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15361 return false;
15362 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15363 return true;
15364 default:
15365 go_unreachable();
15369 // Convert value to complex.
15371 bool
15372 Numeric_constant::to_complex(mpc_t* val) const
15374 mpc_init2(*val, mpc_precision);
15375 switch (this->classification_)
15377 case NC_INT:
15378 case NC_RUNE:
15379 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
15380 return true;
15381 case NC_FLOAT:
15382 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
15383 return true;
15384 case NC_COMPLEX:
15385 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15386 return true;
15387 default:
15388 go_unreachable();
15392 // Get the type.
15394 Type*
15395 Numeric_constant::type() const
15397 if (this->type_ != NULL)
15398 return this->type_;
15399 switch (this->classification_)
15401 case NC_INT:
15402 return Type::make_abstract_integer_type();
15403 case NC_RUNE:
15404 return Type::make_abstract_character_type();
15405 case NC_FLOAT:
15406 return Type::make_abstract_float_type();
15407 case NC_COMPLEX:
15408 return Type::make_abstract_complex_type();
15409 default:
15410 go_unreachable();
15414 // If the constant can be expressed in TYPE, then set the type of the
15415 // constant to TYPE and return true. Otherwise return false, and, if
15416 // ISSUE_ERROR is true, report an appropriate error message.
15418 bool
15419 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15421 bool ret;
15422 if (type == NULL)
15423 ret = true;
15424 else if (type->integer_type() != NULL)
15425 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15426 else if (type->float_type() != NULL)
15427 ret = this->check_float_type(type->float_type(), issue_error, loc);
15428 else if (type->complex_type() != NULL)
15429 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15430 else
15431 go_unreachable();
15432 if (ret)
15433 this->type_ = type;
15434 return ret;
15437 // Check whether the constant can be expressed in an integer type.
15439 bool
15440 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15441 Location location) const
15443 mpz_t val;
15444 switch (this->classification_)
15446 case NC_INT:
15447 case NC_RUNE:
15448 mpz_init_set(val, this->u_.int_val);
15449 break;
15451 case NC_FLOAT:
15452 if (!mpfr_integer_p(this->u_.float_val))
15454 if (issue_error)
15455 error_at(location, "floating point constant truncated to integer");
15456 return false;
15458 mpz_init(val);
15459 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15460 break;
15462 case NC_COMPLEX:
15463 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15464 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15466 if (issue_error)
15467 error_at(location, "complex constant truncated to integer");
15468 return false;
15470 mpz_init(val);
15471 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15472 break;
15474 default:
15475 go_unreachable();
15478 bool ret;
15479 if (type->is_abstract())
15480 ret = true;
15481 else
15483 int bits = mpz_sizeinbase(val, 2);
15484 if (type->is_unsigned())
15486 // For an unsigned type we can only accept a nonnegative
15487 // number, and we must be able to represents at least BITS.
15488 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15490 else
15492 // For a signed type we need an extra bit to indicate the
15493 // sign. We have to handle the most negative integer
15494 // specially.
15495 ret = (bits + 1 <= type->bits()
15496 || (bits <= type->bits()
15497 && mpz_sgn(val) < 0
15498 && (mpz_scan1(val, 0)
15499 == static_cast<unsigned long>(type->bits() - 1))
15500 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15504 if (!ret && issue_error)
15505 error_at(location, "integer constant overflow");
15507 return ret;
15510 // Check whether the constant can be expressed in a floating point
15511 // type.
15513 bool
15514 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15515 Location location)
15517 mpfr_t val;
15518 switch (this->classification_)
15520 case NC_INT:
15521 case NC_RUNE:
15522 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15523 break;
15525 case NC_FLOAT:
15526 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15527 break;
15529 case NC_COMPLEX:
15530 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15532 if (issue_error)
15533 error_at(location, "complex constant truncated to float");
15534 return false;
15536 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15537 break;
15539 default:
15540 go_unreachable();
15543 bool ret;
15544 if (type->is_abstract())
15545 ret = true;
15546 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15548 // A NaN or Infinity always fits in the range of the type.
15549 ret = true;
15551 else
15553 mp_exp_t exp = mpfr_get_exp(val);
15554 mp_exp_t max_exp;
15555 switch (type->bits())
15557 case 32:
15558 max_exp = 128;
15559 break;
15560 case 64:
15561 max_exp = 1024;
15562 break;
15563 default:
15564 go_unreachable();
15567 ret = exp <= max_exp;
15569 if (ret)
15571 // Round the constant to the desired type.
15572 mpfr_t t;
15573 mpfr_init(t);
15574 switch (type->bits())
15576 case 32:
15577 mpfr_set_prec(t, 24);
15578 break;
15579 case 64:
15580 mpfr_set_prec(t, 53);
15581 break;
15582 default:
15583 go_unreachable();
15585 mpfr_set(t, val, GMP_RNDN);
15586 mpfr_set(val, t, GMP_RNDN);
15587 mpfr_clear(t);
15589 this->set_float(type, val);
15593 mpfr_clear(val);
15595 if (!ret && issue_error)
15596 error_at(location, "floating point constant overflow");
15598 return ret;
15601 // Check whether the constant can be expressed in a complex type.
15603 bool
15604 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15605 Location location)
15607 if (type->is_abstract())
15608 return true;
15610 mp_exp_t max_exp;
15611 switch (type->bits())
15613 case 64:
15614 max_exp = 128;
15615 break;
15616 case 128:
15617 max_exp = 1024;
15618 break;
15619 default:
15620 go_unreachable();
15623 mpc_t val;
15624 mpc_init2(val, mpc_precision);
15625 switch (this->classification_)
15627 case NC_INT:
15628 case NC_RUNE:
15629 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
15630 break;
15632 case NC_FLOAT:
15633 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
15634 break;
15636 case NC_COMPLEX:
15637 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
15638 break;
15640 default:
15641 go_unreachable();
15644 bool ret = true;
15645 if (!mpfr_nan_p(mpc_realref(val))
15646 && !mpfr_inf_p(mpc_realref(val))
15647 && !mpfr_zero_p(mpc_realref(val))
15648 && mpfr_get_exp(mpc_realref(val)) > max_exp)
15650 if (issue_error)
15651 error_at(location, "complex real part overflow");
15652 ret = false;
15655 if (!mpfr_nan_p(mpc_imagref(val))
15656 && !mpfr_inf_p(mpc_imagref(val))
15657 && !mpfr_zero_p(mpc_imagref(val))
15658 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
15660 if (issue_error)
15661 error_at(location, "complex imaginary part overflow");
15662 ret = false;
15665 if (ret)
15667 // Round the constant to the desired type.
15668 mpc_t t;
15669 switch (type->bits())
15671 case 64:
15672 mpc_init2(t, 24);
15673 break;
15674 case 128:
15675 mpc_init2(t, 53);
15676 break;
15677 default:
15678 go_unreachable();
15680 mpc_set(t, val, MPC_RNDNN);
15681 mpc_set(val, t, MPC_RNDNN);
15682 mpc_clear(t);
15684 this->set_complex(type, val);
15687 mpc_clear(val);
15689 return ret;
15692 // Return an Expression for this value.
15694 Expression*
15695 Numeric_constant::expression(Location loc) const
15697 switch (this->classification_)
15699 case NC_INT:
15700 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
15701 case NC_RUNE:
15702 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15703 case NC_FLOAT:
15704 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15705 case NC_COMPLEX:
15706 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
15707 default:
15708 go_unreachable();