compiler: avoid negative zero in float constants
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob03f8c68cace113dcd98769e6081de1abe7da4cd4
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 "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
25 // Class Expression.
27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
33 Expression::~Expression()
37 // Traverse the expressions.
39 int
40 Expression::traverse(Expression** pexpr, Traverse* traverse)
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
51 return expr->do_traverse(traverse);
54 // Traverse subexpressions of this expression.
56 int
57 Expression::traverse_subexpressions(Traverse* traverse)
59 return this->do_traverse(traverse);
62 // Default implementation for do_traverse for child classes.
64 int
65 Expression::do_traverse(Traverse*)
67 return TRAVERSE_CONTINUE;
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded. By default, we give an error.
72 // Expressions with side effects override.
74 bool
75 Expression::do_discarding_value()
77 this->unused_value_error();
78 return false;
81 // This virtual function is called to export expressions. This will
82 // only be used by expressions which may be constant.
84 void
85 Expression::do_export(Export*) const
87 go_unreachable();
90 // Give an error saying that the value of the expression is not used.
92 void
93 Expression::unused_value_error()
95 this->report_error(_("value computed is not used"));
98 // Note that this expression is an error. This is called by children
99 // when they discover an error.
101 void
102 Expression::set_is_error()
104 this->classification_ = EXPRESSION_ERROR;
107 // For children to call to report an error conveniently.
109 void
110 Expression::report_error(const char* msg)
112 go_error_at(this->location_, "%s", msg);
113 this->set_is_error();
116 // Set types of variables and constants. This is implemented by the
117 // child class.
119 void
120 Expression::determine_type(const Type_context* context)
122 this->do_determine_type(context);
125 // Set types when there is no context.
127 void
128 Expression::determine_type_no_context()
130 Type_context context;
131 this->do_determine_type(&context);
134 // Return an expression handling any conversions which must be done during
135 // assignment.
137 Expression*
138 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
139 Expression* rhs, Location location)
141 Type* rhs_type = rhs->type();
142 if (lhs_type->is_error()
143 || rhs_type->is_error()
144 || rhs->is_error_expression())
145 return Expression::make_error(location);
147 bool are_identical = Type::are_identical(lhs_type, rhs_type, false, NULL);
148 if (!are_identical && lhs_type->interface_type() != NULL)
150 if (rhs_type->interface_type() == NULL)
151 return Expression::convert_type_to_interface(lhs_type, rhs, location);
152 else
153 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154 location);
156 else if (!are_identical && rhs_type->interface_type() != NULL)
157 return Expression::convert_interface_to_type(lhs_type, rhs, location);
158 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
160 // Assigning nil to a slice.
161 Expression* nil = Expression::make_nil(location);
162 Expression* zero = Expression::make_integer_ul(0, NULL, location);
163 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
165 else if (rhs_type->is_nil_type())
166 return Expression::make_nil(location);
167 else if (are_identical)
169 if (lhs_type->forwarded() != rhs_type->forwarded())
171 // Different but identical types require an explicit
172 // conversion. This happens with type aliases.
173 return Expression::make_cast(lhs_type, rhs, location);
176 // No conversion is needed.
177 return rhs;
179 else if (lhs_type->points_to() != NULL)
180 return Expression::make_unsafe_cast(lhs_type, rhs, location);
181 else if (lhs_type->is_numeric_type())
182 return Expression::make_cast(lhs_type, rhs, location);
183 else if ((lhs_type->struct_type() != NULL
184 && rhs_type->struct_type() != NULL)
185 || (lhs_type->array_type() != NULL
186 && rhs_type->array_type() != NULL))
188 // This conversion must be permitted by Go, or we wouldn't have
189 // gotten here.
190 return Expression::make_unsafe_cast(lhs_type, rhs, location);
192 else
193 return rhs;
196 // Return an expression for a conversion from a non-interface type to an
197 // interface type.
199 Expression*
200 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
201 Location location)
203 Interface_type* lhs_interface_type = lhs_type->interface_type();
204 bool lhs_is_empty = lhs_interface_type->is_empty();
206 // Since RHS_TYPE is a static type, we can create the interface
207 // method table at compile time.
209 // When setting an interface to nil, we just set both fields to
210 // NULL.
211 Type* rhs_type = rhs->type();
212 if (rhs_type->is_nil_type())
214 Expression* nil = Expression::make_nil(location);
215 return Expression::make_interface_value(lhs_type, nil, nil, location);
218 // This should have been checked already.
219 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
221 go_assert(saw_errors());
222 return Expression::make_error(location);
225 // An interface is a tuple. If LHS_TYPE is an empty interface type,
226 // then the first field is the type descriptor for RHS_TYPE.
227 // Otherwise it is the interface method table for RHS_TYPE.
228 Expression* first_field;
229 if (lhs_is_empty)
230 first_field = Expression::make_type_descriptor(rhs_type, location);
231 else
233 // Build the interface method table for this interface and this
234 // object type: a list of function pointers for each interface
235 // method.
236 Named_type* rhs_named_type = rhs_type->named_type();
237 Struct_type* rhs_struct_type = rhs_type->struct_type();
238 bool is_pointer = false;
239 if (rhs_named_type == NULL && rhs_struct_type == NULL)
241 rhs_named_type = rhs_type->deref()->named_type();
242 rhs_struct_type = rhs_type->deref()->struct_type();
243 is_pointer = true;
245 if (rhs_named_type != NULL)
246 first_field =
247 rhs_named_type->interface_method_table(lhs_interface_type,
248 is_pointer);
249 else if (rhs_struct_type != NULL)
250 first_field =
251 rhs_struct_type->interface_method_table(lhs_interface_type,
252 is_pointer);
253 else
254 first_field = Expression::make_nil(location);
257 Expression* obj;
258 if (rhs_type->points_to() != NULL)
260 // We are assigning a pointer to the interface; the interface
261 // holds the pointer itself.
262 obj = rhs;
264 else
266 // We are assigning a non-pointer value to the interface; the
267 // interface gets a copy of the value in the heap if it escapes.
268 // TODO(cmang): Associate escape state state of RHS with newly
269 // created OBJ.
270 obj = Expression::make_heap_expression(rhs, location);
273 return Expression::make_interface_value(lhs_type, first_field, obj, location);
276 // Return an expression for the type descriptor of RHS.
278 Expression*
279 Expression::get_interface_type_descriptor(Expression* rhs)
281 go_assert(rhs->type()->interface_type() != NULL);
282 Location location = rhs->location();
284 // The type descriptor is the first field of an empty interface.
285 if (rhs->type()->interface_type()->is_empty())
286 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
287 location);
289 Expression* mtable =
290 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
292 Expression* descriptor =
293 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
294 descriptor = Expression::make_field_reference(descriptor, 0, location);
295 Expression* nil = Expression::make_nil(location);
297 Expression* eq =
298 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
299 return Expression::make_conditional(eq, nil, descriptor, location);
302 // Return an expression for the conversion of an interface type to an
303 // interface type.
305 Expression*
306 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
307 bool for_type_guard,
308 Location location)
310 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
311 return rhs;
313 Interface_type* lhs_interface_type = lhs_type->interface_type();
314 bool lhs_is_empty = lhs_interface_type->is_empty();
316 // In the general case this requires runtime examination of the type
317 // method table to match it up with the interface methods.
319 // FIXME: If all of the methods in the right hand side interface
320 // also appear in the left hand side interface, then we don't need
321 // to do a runtime check, although we still need to build a new
322 // method table.
324 // We are going to evaluate RHS multiple times.
325 go_assert(rhs->is_variable());
327 // Get the type descriptor for the right hand side. This will be
328 // NULL for a nil interface.
329 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
330 Expression* lhs_type_expr =
331 Expression::make_type_descriptor(lhs_type, location);
333 Expression* first_field;
334 if (for_type_guard)
336 // A type assertion fails when converting a nil interface.
337 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
338 lhs_type_expr, rhs_type_expr);
340 else if (lhs_is_empty)
342 // A conversion to an empty interface always succeeds, and the
343 // first field is just the type descriptor of the object.
344 first_field = rhs_type_expr;
346 else
348 // A conversion to a non-empty interface may fail, but unlike a
349 // type assertion converting nil will always succeed.
350 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
351 lhs_type_expr, rhs_type_expr);
354 // The second field is simply the object pointer.
355 Expression* obj =
356 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
357 return Expression::make_interface_value(lhs_type, first_field, obj, location);
360 // Return an expression for the conversion of an interface type to a
361 // non-interface type.
363 Expression*
364 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
365 Location location)
367 // We are going to evaluate RHS multiple times.
368 go_assert(rhs->is_variable());
370 // Call a function to check that the type is valid. The function
371 // will panic with an appropriate runtime type error if the type is
372 // not valid.
373 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
374 location);
375 Expression* rhs_descriptor =
376 Expression::get_interface_type_descriptor(rhs);
378 Type* rhs_type = rhs->type();
379 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
380 location);
382 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
383 location, 3, lhs_type_expr,
384 rhs_descriptor, rhs_inter_expr);
386 // If the call succeeds, pull out the value.
387 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
388 location);
390 // If the value is a pointer, then it is the value we want.
391 // Otherwise it points to the value.
392 if (lhs_type->points_to() == NULL)
394 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
395 location);
396 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
397 location);
399 return Expression::make_compound(check_iface, obj, location);
402 // Convert an expression to its backend representation. This is implemented by
403 // the child class. Not that it is not in general safe to call this multiple
404 // times for a single expression, but that we don't catch such errors.
406 Bexpression*
407 Expression::get_backend(Translate_context* context)
409 // The child may have marked this expression as having an error.
410 if (this->classification_ == EXPRESSION_ERROR)
411 return context->backend()->error_expression();
413 return this->do_get_backend(context);
416 // Return a backend expression for VAL.
417 Bexpression*
418 Expression::backend_numeric_constant_expression(Translate_context* context,
419 Numeric_constant* val)
421 Gogo* gogo = context->gogo();
422 Type* type = val->type();
423 if (type == NULL)
424 return gogo->backend()->error_expression();
426 Btype* btype = type->get_backend(gogo);
427 Bexpression* ret;
428 if (type->integer_type() != NULL)
430 mpz_t ival;
431 if (!val->to_int(&ival))
433 go_assert(saw_errors());
434 return gogo->backend()->error_expression();
436 ret = gogo->backend()->integer_constant_expression(btype, ival);
437 mpz_clear(ival);
439 else if (type->float_type() != NULL)
441 mpfr_t fval;
442 if (!val->to_float(&fval))
444 go_assert(saw_errors());
445 return gogo->backend()->error_expression();
447 ret = gogo->backend()->float_constant_expression(btype, fval);
448 mpfr_clear(fval);
450 else if (type->complex_type() != NULL)
452 mpc_t cval;
453 if (!val->to_complex(&cval))
455 go_assert(saw_errors());
456 return gogo->backend()->error_expression();
458 ret = gogo->backend()->complex_constant_expression(btype, cval);
459 mpc_clear(cval);
461 else
462 go_unreachable();
464 return ret;
467 // Return an expression which evaluates to true if VAL, of arbitrary integer
468 // type, is negative or is more than the maximum value of the Go type "int".
470 Expression*
471 Expression::check_bounds(Expression* val, Location loc)
473 Type* val_type = val->type();
474 Type* bound_type = Type::lookup_integer_type("int");
476 int val_type_size;
477 bool val_is_unsigned = false;
478 if (val_type->integer_type() != NULL)
480 val_type_size = val_type->integer_type()->bits();
481 val_is_unsigned = val_type->integer_type()->is_unsigned();
483 else
485 if (!val_type->is_numeric_type()
486 || !Type::are_convertible(bound_type, val_type, NULL))
488 go_assert(saw_errors());
489 return Expression::make_boolean(true, loc);
492 if (val_type->complex_type() != NULL)
493 val_type_size = val_type->complex_type()->bits();
494 else
495 val_type_size = val_type->float_type()->bits();
498 Expression* negative_index = Expression::make_boolean(false, loc);
499 Expression* index_overflows = Expression::make_boolean(false, loc);
500 if (!val_is_unsigned)
502 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
503 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
506 int bound_type_size = bound_type->integer_type()->bits();
507 if (val_type_size > bound_type_size
508 || (val_type_size == bound_type_size
509 && val_is_unsigned))
511 mpz_t one;
512 mpz_init_set_ui(one, 1UL);
514 // maxval = 2^(bound_type_size - 1) - 1
515 mpz_t maxval;
516 mpz_init(maxval);
517 mpz_mul_2exp(maxval, one, bound_type_size - 1);
518 mpz_sub_ui(maxval, maxval, 1);
519 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
520 mpz_clear(one);
521 mpz_clear(maxval);
523 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
526 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
527 loc);
530 void
531 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
533 this->do_dump_expression(ast_dump_context);
536 // Error expressions. This are used to avoid cascading errors.
538 class Error_expression : public Expression
540 public:
541 Error_expression(Location location)
542 : Expression(EXPRESSION_ERROR, location)
545 protected:
546 bool
547 do_is_constant() const
548 { return true; }
550 bool
551 do_numeric_constant_value(Numeric_constant* nc) const
553 nc->set_unsigned_long(NULL, 0);
554 return true;
557 bool
558 do_discarding_value()
559 { return true; }
561 Type*
562 do_type()
563 { return Type::make_error_type(); }
565 void
566 do_determine_type(const Type_context*)
569 Expression*
570 do_copy()
571 { return this; }
573 bool
574 do_is_addressable() const
575 { return true; }
577 Bexpression*
578 do_get_backend(Translate_context* context)
579 { return context->backend()->error_expression(); }
581 void
582 do_dump_expression(Ast_dump_context*) const;
585 // Dump the ast representation for an error expression to a dump context.
587 void
588 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
590 ast_dump_context->ostream() << "_Error_" ;
593 Expression*
594 Expression::make_error(Location location)
596 return new Error_expression(location);
599 // An expression which is really a type. This is used during parsing.
600 // It is an error if these survive after lowering.
602 class
603 Type_expression : public Expression
605 public:
606 Type_expression(Type* type, Location location)
607 : Expression(EXPRESSION_TYPE, location),
608 type_(type)
611 protected:
613 do_traverse(Traverse* traverse)
614 { return Type::traverse(this->type_, traverse); }
616 Type*
617 do_type()
618 { return this->type_; }
620 void
621 do_determine_type(const Type_context*)
624 void
625 do_check_types(Gogo*)
626 { this->report_error(_("invalid use of type")); }
628 Expression*
629 do_copy()
630 { return this; }
632 Bexpression*
633 do_get_backend(Translate_context*)
634 { go_unreachable(); }
636 void do_dump_expression(Ast_dump_context*) const;
638 private:
639 // The type which we are representing as an expression.
640 Type* type_;
643 void
644 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
646 ast_dump_context->dump_type(this->type_);
649 Expression*
650 Expression::make_type(Type* type, Location location)
652 return new Type_expression(type, location);
655 // Class Parser_expression.
657 Type*
658 Parser_expression::do_type()
660 // We should never really ask for the type of a Parser_expression.
661 // However, it can happen, at least when we have an invalid const
662 // whose initializer refers to the const itself. In that case we
663 // may ask for the type when lowering the const itself.
664 go_assert(saw_errors());
665 return Type::make_error_type();
668 // Class Var_expression.
670 // Lower a variable expression. Here we just make sure that the
671 // initialization expression of the variable has been lowered. This
672 // ensures that we will be able to determine the type of the variable
673 // if necessary.
675 Expression*
676 Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 Statement_inserter* inserter, int)
679 if (this->variable_->is_variable())
681 Variable* var = this->variable_->var_value();
682 // This is either a local variable or a global variable. A
683 // reference to a variable which is local to an enclosing
684 // function will be a reference to a field in a closure.
685 if (var->is_global())
687 function = NULL;
688 inserter = NULL;
690 var->lower_init_expression(gogo, function, inserter);
692 return this;
695 // Return the type of a reference to a variable.
697 Type*
698 Var_expression::do_type()
700 if (this->variable_->is_variable())
701 return this->variable_->var_value()->type();
702 else if (this->variable_->is_result_variable())
703 return this->variable_->result_var_value()->type();
704 else
705 go_unreachable();
708 // Determine the type of a reference to a variable.
710 void
711 Var_expression::do_determine_type(const Type_context*)
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->determine_type();
717 // Something takes the address of this variable. This means that we
718 // may want to move the variable onto the heap.
720 void
721 Var_expression::do_address_taken(bool escapes)
723 if (!escapes)
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_non_escaping_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_non_escaping_address_taken();
729 else
730 go_unreachable();
732 else
734 if (this->variable_->is_variable())
735 this->variable_->var_value()->set_address_taken();
736 else if (this->variable_->is_result_variable())
737 this->variable_->result_var_value()->set_address_taken();
738 else
739 go_unreachable();
742 if (this->variable_->is_variable()
743 && this->variable_->var_value()->is_in_heap())
745 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
746 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
750 // Get the backend representation for a reference to a variable.
752 Bexpression*
753 Var_expression::do_get_backend(Translate_context* context)
755 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
756 context->function());
757 bool is_in_heap;
758 Location loc = this->location();
759 Btype* btype;
760 Gogo* gogo = context->gogo();
761 if (this->variable_->is_variable())
763 is_in_heap = this->variable_->var_value()->is_in_heap();
764 btype = this->variable_->var_value()->type()->get_backend(gogo);
766 else if (this->variable_->is_result_variable())
768 is_in_heap = this->variable_->result_var_value()->is_in_heap();
769 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
771 else
772 go_unreachable();
774 Bexpression* ret =
775 context->backend()->var_expression(bvar, loc);
776 if (is_in_heap)
777 ret = context->backend()->indirect_expression(btype, ret, true, loc);
778 return ret;
781 // Ast dump for variable expression.
783 void
784 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
786 ast_dump_context->ostream() << this->variable_->message_name() ;
789 // Make a reference to a variable in an expression.
791 Expression*
792 Expression::make_var_reference(Named_object* var, Location location)
794 if (var->is_sink())
795 return Expression::make_sink(location);
797 // FIXME: Creating a new object for each reference to a variable is
798 // wasteful.
799 return new Var_expression(var, location);
802 // Class Enclosed_var_expression.
805 Enclosed_var_expression::do_traverse(Traverse*)
807 return TRAVERSE_CONTINUE;
810 // Lower the reference to the enclosed variable.
812 Expression*
813 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
814 Statement_inserter* inserter, int)
816 gogo->lower_expression(function, inserter, &this->reference_);
817 return this;
820 // Flatten the reference to the enclosed variable.
822 Expression*
823 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
824 Statement_inserter* inserter)
826 gogo->flatten_expression(function, inserter, &this->reference_);
827 return this;
830 void
831 Enclosed_var_expression::do_address_taken(bool escapes)
833 if (!escapes)
835 if (this->variable_->is_variable())
836 this->variable_->var_value()->set_non_escaping_address_taken();
837 else if (this->variable_->is_result_variable())
838 this->variable_->result_var_value()->set_non_escaping_address_taken();
839 else
840 go_unreachable();
842 else
844 if (this->variable_->is_variable())
845 this->variable_->var_value()->set_address_taken();
846 else if (this->variable_->is_result_variable())
847 this->variable_->result_var_value()->set_address_taken();
848 else
849 go_unreachable();
852 if (this->variable_->is_variable()
853 && this->variable_->var_value()->is_in_heap())
854 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
857 // Ast dump for enclosed variable expression.
859 void
860 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
862 adc->ostream() << this->variable_->message_name();
865 // Make a reference to a variable within an enclosing function.
867 Expression*
868 Expression::make_enclosing_var_reference(Expression* reference,
869 Named_object* var, Location location)
871 return new Enclosed_var_expression(reference, var, location);
874 // Class Temporary_reference_expression.
876 // The type.
878 Type*
879 Temporary_reference_expression::do_type()
881 return this->statement_->type();
884 // Called if something takes the address of this temporary variable.
885 // We never have to move temporary variables to the heap, but we do
886 // need to know that they must live in the stack rather than in a
887 // register.
889 void
890 Temporary_reference_expression::do_address_taken(bool)
892 this->statement_->set_is_address_taken();
895 // Get a backend expression referring to the variable.
897 Bexpression*
898 Temporary_reference_expression::do_get_backend(Translate_context* context)
900 Gogo* gogo = context->gogo();
901 Bvariable* bvar = this->statement_->get_backend_variable(context);
902 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
904 // The backend can't always represent the same set of recursive types
905 // that the Go frontend can. In some cases this means that a
906 // temporary variable won't have the right backend type. Correct
907 // that here by adding a type cast. We need to use base() to push
908 // the circularity down one level.
909 Type* stype = this->statement_->type();
910 if (!this->is_lvalue_
911 && stype->points_to() != NULL
912 && stype->points_to()->is_void_type())
914 Btype* btype = this->type()->base()->get_backend(gogo);
915 ret = gogo->backend()->convert_expression(btype, ret, this->location());
917 return ret;
920 // Ast dump for temporary reference.
922 void
923 Temporary_reference_expression::do_dump_expression(
924 Ast_dump_context* ast_dump_context) const
926 ast_dump_context->dump_temp_variable_name(this->statement_);
929 // Make a reference to a temporary variable.
931 Temporary_reference_expression*
932 Expression::make_temporary_reference(Temporary_statement* statement,
933 Location location)
935 return new Temporary_reference_expression(statement, location);
938 // Class Set_and_use_temporary_expression.
940 // Return the type.
942 Type*
943 Set_and_use_temporary_expression::do_type()
945 return this->statement_->type();
948 // Determine the type of the expression.
950 void
951 Set_and_use_temporary_expression::do_determine_type(
952 const Type_context* context)
954 this->expr_->determine_type(context);
957 // Take the address.
959 void
960 Set_and_use_temporary_expression::do_address_taken(bool)
962 this->statement_->set_is_address_taken();
965 // Return the backend representation.
967 Bexpression*
968 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
970 Location loc = this->location();
971 Gogo* gogo = context->gogo();
972 Bvariable* bvar = this->statement_->get_backend_variable(context);
973 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
975 Named_object* fn = context->function();
976 go_assert(fn != NULL);
977 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
978 Bexpression* bexpr = this->expr_->get_backend(context);
979 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
980 bexpr, loc);
981 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
982 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
983 return ret;
986 // Dump.
988 void
989 Set_and_use_temporary_expression::do_dump_expression(
990 Ast_dump_context* ast_dump_context) const
992 ast_dump_context->ostream() << '(';
993 ast_dump_context->dump_temp_variable_name(this->statement_);
994 ast_dump_context->ostream() << " = ";
995 this->expr_->dump_expression(ast_dump_context);
996 ast_dump_context->ostream() << ')';
999 // Make a set-and-use temporary.
1001 Set_and_use_temporary_expression*
1002 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1003 Expression* expr, Location location)
1005 return new Set_and_use_temporary_expression(statement, expr, location);
1008 // A sink expression--a use of the blank identifier _.
1010 class Sink_expression : public Expression
1012 public:
1013 Sink_expression(Location location)
1014 : Expression(EXPRESSION_SINK, location),
1015 type_(NULL), bvar_(NULL)
1018 protected:
1019 bool
1020 do_discarding_value()
1021 { return true; }
1023 Type*
1024 do_type();
1026 void
1027 do_determine_type(const Type_context*);
1029 Expression*
1030 do_copy()
1031 { return new Sink_expression(this->location()); }
1033 Bexpression*
1034 do_get_backend(Translate_context*);
1036 void
1037 do_dump_expression(Ast_dump_context*) const;
1039 private:
1040 // The type of this sink variable.
1041 Type* type_;
1042 // The temporary variable we generate.
1043 Bvariable* bvar_;
1046 // Return the type of a sink expression.
1048 Type*
1049 Sink_expression::do_type()
1051 if (this->type_ == NULL)
1052 return Type::make_sink_type();
1053 return this->type_;
1056 // Determine the type of a sink expression.
1058 void
1059 Sink_expression::do_determine_type(const Type_context* context)
1061 if (context->type != NULL)
1062 this->type_ = context->type;
1065 // Return a temporary variable for a sink expression. This will
1066 // presumably be a write-only variable which the middle-end will drop.
1068 Bexpression*
1069 Sink_expression::do_get_backend(Translate_context* context)
1071 Location loc = this->location();
1072 Gogo* gogo = context->gogo();
1073 if (this->bvar_ == NULL)
1075 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1076 Named_object* fn = context->function();
1077 go_assert(fn != NULL);
1078 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1079 Btype* bt = this->type_->get_backend(context->gogo());
1080 Bstatement* decl;
1081 this->bvar_ =
1082 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1083 false, loc, &decl);
1084 Bexpression* var_ref =
1085 gogo->backend()->var_expression(this->bvar_, loc);
1086 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1087 return var_ref;
1089 return gogo->backend()->var_expression(this->bvar_, loc);
1092 // Ast dump for sink expression.
1094 void
1095 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1097 ast_dump_context->ostream() << "_" ;
1100 // Make a sink expression.
1102 Expression*
1103 Expression::make_sink(Location location)
1105 return new Sink_expression(location);
1108 // Class Func_expression.
1110 // FIXME: Can a function expression appear in a constant expression?
1111 // The value is unchanging. Initializing a constant to the address of
1112 // a function seems like it could work, though there might be little
1113 // point to it.
1115 // Traversal.
1118 Func_expression::do_traverse(Traverse* traverse)
1120 return (this->closure_ == NULL
1121 ? TRAVERSE_CONTINUE
1122 : Expression::traverse(&this->closure_, traverse));
1125 // Return the type of a function expression.
1127 Type*
1128 Func_expression::do_type()
1130 if (this->function_->is_function())
1131 return this->function_->func_value()->type();
1132 else if (this->function_->is_function_declaration())
1133 return this->function_->func_declaration_value()->type();
1134 else
1135 go_unreachable();
1138 // Get the backend representation for the code of a function expression.
1140 Bexpression*
1141 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1143 Function_type* fntype;
1144 if (no->is_function())
1145 fntype = no->func_value()->type();
1146 else if (no->is_function_declaration())
1147 fntype = no->func_declaration_value()->type();
1148 else
1149 go_unreachable();
1151 // Builtin functions are handled specially by Call_expression. We
1152 // can't take their address.
1153 if (fntype->is_builtin())
1155 go_error_at(loc,
1156 "invalid use of special builtin function %qs; must be called",
1157 no->message_name().c_str());
1158 return gogo->backend()->error_expression();
1161 Bfunction* fndecl;
1162 if (no->is_function())
1163 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1164 else if (no->is_function_declaration())
1165 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1166 else
1167 go_unreachable();
1169 return gogo->backend()->function_code_expression(fndecl, loc);
1172 // Get the backend representation for a function expression. This is used when
1173 // we take the address of a function rather than simply calling it. A func
1174 // value is represented as a pointer to a block of memory. The first
1175 // word of that memory is a pointer to the function code. The
1176 // remaining parts of that memory are the addresses of variables that
1177 // the function closes over.
1179 Bexpression*
1180 Func_expression::do_get_backend(Translate_context* context)
1182 // If there is no closure, just use the function descriptor.
1183 if (this->closure_ == NULL)
1185 Gogo* gogo = context->gogo();
1186 Named_object* no = this->function_;
1187 Expression* descriptor;
1188 if (no->is_function())
1189 descriptor = no->func_value()->descriptor(gogo, no);
1190 else if (no->is_function_declaration())
1192 if (no->func_declaration_value()->type()->is_builtin())
1194 go_error_at(this->location(),
1195 ("invalid use of special builtin function %qs; "
1196 "must be called"),
1197 no->message_name().c_str());
1198 return gogo->backend()->error_expression();
1200 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1202 else
1203 go_unreachable();
1205 Bexpression* bdesc = descriptor->get_backend(context);
1206 return gogo->backend()->address_expression(bdesc, this->location());
1209 go_assert(this->function_->func_value()->enclosing() != NULL);
1211 // If there is a closure, then the closure is itself the function
1212 // expression. It is a pointer to a struct whose first field points
1213 // to the function code and whose remaining fields are the addresses
1214 // of the closed-over variables.
1215 Bexpression *bexpr = this->closure_->get_backend(context);
1217 // Introduce a backend type conversion, to account for any differences
1218 // between the argument type (function descriptor, struct with a
1219 // single field) and the closure (struct with multiple fields).
1220 Gogo* gogo = context->gogo();
1221 Btype *btype = this->type()->get_backend(gogo);
1222 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1225 // Ast dump for function.
1227 void
1228 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1230 ast_dump_context->ostream() << this->function_->name();
1231 if (this->closure_ != NULL)
1233 ast_dump_context->ostream() << " {closure = ";
1234 this->closure_->dump_expression(ast_dump_context);
1235 ast_dump_context->ostream() << "}";
1239 // Make a reference to a function in an expression.
1241 Expression*
1242 Expression::make_func_reference(Named_object* function, Expression* closure,
1243 Location location)
1245 Func_expression* fe = new Func_expression(function, closure, location);
1247 // Detect references to builtin functions and set the runtime code if
1248 // appropriate.
1249 if (function->is_function_declaration())
1250 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1251 return fe;
1254 // Class Func_descriptor_expression.
1256 // Constructor.
1258 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1259 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1260 fn_(fn), dvar_(NULL)
1262 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1265 // Traversal.
1268 Func_descriptor_expression::do_traverse(Traverse*)
1270 return TRAVERSE_CONTINUE;
1273 // All function descriptors have the same type.
1275 Type* Func_descriptor_expression::descriptor_type;
1277 void
1278 Func_descriptor_expression::make_func_descriptor_type()
1280 if (Func_descriptor_expression::descriptor_type != NULL)
1281 return;
1282 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1283 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1284 Func_descriptor_expression::descriptor_type =
1285 Type::make_builtin_named_type("functionDescriptor", struct_type);
1288 Type*
1289 Func_descriptor_expression::do_type()
1291 Func_descriptor_expression::make_func_descriptor_type();
1292 return Func_descriptor_expression::descriptor_type;
1295 // The backend representation for a function descriptor.
1297 Bexpression*
1298 Func_descriptor_expression::do_get_backend(Translate_context* context)
1300 Named_object* no = this->fn_;
1301 Location loc = no->location();
1302 if (this->dvar_ != NULL)
1303 return context->backend()->var_expression(this->dvar_, loc);
1305 Gogo* gogo = context->gogo();
1306 std::string var_name(gogo->function_descriptor_name(no));
1307 bool is_descriptor = false;
1308 if (no->is_function_declaration()
1309 && !no->func_declaration_value()->asm_name().empty()
1310 && Linemap::is_predeclared_location(no->location()))
1311 is_descriptor = true;
1313 // The runtime package implements some functions defined in the
1314 // syscall package. Let the syscall package define the descriptor
1315 // in this case.
1316 if (gogo->compiling_runtime()
1317 && gogo->package_name() == "runtime"
1318 && no->is_function()
1319 && !no->func_value()->asm_name().empty()
1320 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1321 is_descriptor = true;
1323 Btype* btype = this->type()->get_backend(gogo);
1325 Bvariable* bvar;
1326 std::string asm_name(go_selectively_encode_id(var_name));
1327 if (no->package() != NULL || is_descriptor)
1328 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1329 btype, loc);
1330 else
1332 Location bloc = Linemap::predeclared_location();
1333 bool is_hidden = ((no->is_function()
1334 && no->func_value()->enclosing() != NULL)
1335 || Gogo::is_thunk(no));
1336 bvar = context->backend()->immutable_struct(var_name, asm_name,
1337 is_hidden, false,
1338 btype, bloc);
1339 Expression_list* vals = new Expression_list();
1340 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1341 Expression* init =
1342 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1343 Translate_context bcontext(gogo, NULL, NULL, NULL);
1344 bcontext.set_is_const();
1345 Bexpression* binit = init->get_backend(&bcontext);
1346 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1347 false, btype, bloc, binit);
1350 this->dvar_ = bvar;
1351 return gogo->backend()->var_expression(bvar, loc);
1354 // Print a function descriptor expression.
1356 void
1357 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1359 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1362 // Make a function descriptor expression.
1364 Func_descriptor_expression*
1365 Expression::make_func_descriptor(Named_object* fn)
1367 return new Func_descriptor_expression(fn);
1370 // Make the function descriptor type, so that it can be converted.
1372 void
1373 Expression::make_func_descriptor_type()
1375 Func_descriptor_expression::make_func_descriptor_type();
1378 // A reference to just the code of a function.
1380 class Func_code_reference_expression : public Expression
1382 public:
1383 Func_code_reference_expression(Named_object* function, Location location)
1384 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1385 function_(function)
1388 protected:
1390 do_traverse(Traverse*)
1391 { return TRAVERSE_CONTINUE; }
1393 bool
1394 do_is_static_initializer() const
1395 { return true; }
1397 Type*
1398 do_type()
1399 { return Type::make_pointer_type(Type::make_void_type()); }
1401 void
1402 do_determine_type(const Type_context*)
1405 Expression*
1406 do_copy()
1408 return Expression::make_func_code_reference(this->function_,
1409 this->location());
1412 Bexpression*
1413 do_get_backend(Translate_context*);
1415 void
1416 do_dump_expression(Ast_dump_context* context) const
1417 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1419 private:
1420 // The function.
1421 Named_object* function_;
1424 // Get the backend representation for a reference to function code.
1426 Bexpression*
1427 Func_code_reference_expression::do_get_backend(Translate_context* context)
1429 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1430 this->location());
1433 // Make a reference to the code of a function.
1435 Expression*
1436 Expression::make_func_code_reference(Named_object* function, Location location)
1438 return new Func_code_reference_expression(function, location);
1441 // Class Unknown_expression.
1443 // Return the name of an unknown expression.
1445 const std::string&
1446 Unknown_expression::name() const
1448 return this->named_object_->name();
1451 // Lower a reference to an unknown name.
1453 Expression*
1454 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1456 Location location = this->location();
1457 Named_object* no = this->named_object_;
1458 Named_object* real;
1459 if (!no->is_unknown())
1460 real = no;
1461 else
1463 real = no->unknown_value()->real_named_object();
1464 if (real == NULL)
1466 if (this->is_composite_literal_key_)
1467 return this;
1468 if (!this->no_error_message_)
1469 go_error_at(location, "reference to undefined name %qs",
1470 this->named_object_->message_name().c_str());
1471 return Expression::make_error(location);
1474 switch (real->classification())
1476 case Named_object::NAMED_OBJECT_CONST:
1477 return Expression::make_const_reference(real, location);
1478 case Named_object::NAMED_OBJECT_TYPE:
1479 return Expression::make_type(real->type_value(), location);
1480 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1481 if (this->is_composite_literal_key_)
1482 return this;
1483 if (!this->no_error_message_)
1484 go_error_at(location, "reference to undefined type %qs",
1485 real->message_name().c_str());
1486 return Expression::make_error(location);
1487 case Named_object::NAMED_OBJECT_VAR:
1488 real->var_value()->set_is_used();
1489 return Expression::make_var_reference(real, location);
1490 case Named_object::NAMED_OBJECT_FUNC:
1491 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1492 return Expression::make_func_reference(real, NULL, location);
1493 case Named_object::NAMED_OBJECT_PACKAGE:
1494 if (this->is_composite_literal_key_)
1495 return this;
1496 if (!this->no_error_message_)
1497 go_error_at(location, "unexpected reference to package");
1498 return Expression::make_error(location);
1499 default:
1500 go_unreachable();
1504 // Dump the ast representation for an unknown expression to a dump context.
1506 void
1507 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1509 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1510 << ")";
1513 // Make a reference to an unknown name.
1515 Unknown_expression*
1516 Expression::make_unknown_reference(Named_object* no, Location location)
1518 return new Unknown_expression(no, location);
1521 // A boolean expression.
1523 class Boolean_expression : public Expression
1525 public:
1526 Boolean_expression(bool val, Location location)
1527 : Expression(EXPRESSION_BOOLEAN, location),
1528 val_(val), type_(NULL)
1531 static Expression*
1532 do_import(Import*);
1534 protected:
1535 bool
1536 do_is_constant() const
1537 { return true; }
1539 bool
1540 do_is_static_initializer() const
1541 { return true; }
1543 Type*
1544 do_type();
1546 void
1547 do_determine_type(const Type_context*);
1549 Expression*
1550 do_copy()
1551 { return this; }
1553 Bexpression*
1554 do_get_backend(Translate_context* context)
1555 { return context->backend()->boolean_constant_expression(this->val_); }
1557 void
1558 do_export(Export* exp) const
1559 { exp->write_c_string(this->val_ ? "true" : "false"); }
1561 void
1562 do_dump_expression(Ast_dump_context* ast_dump_context) const
1563 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1565 private:
1566 // The constant.
1567 bool val_;
1568 // The type as determined by context.
1569 Type* type_;
1572 // Get the type.
1574 Type*
1575 Boolean_expression::do_type()
1577 if (this->type_ == NULL)
1578 this->type_ = Type::make_boolean_type();
1579 return this->type_;
1582 // Set the type from the context.
1584 void
1585 Boolean_expression::do_determine_type(const Type_context* context)
1587 if (this->type_ != NULL && !this->type_->is_abstract())
1589 else if (context->type != NULL && context->type->is_boolean_type())
1590 this->type_ = context->type;
1591 else if (!context->may_be_abstract)
1592 this->type_ = Type::lookup_bool_type();
1595 // Import a boolean constant.
1597 Expression*
1598 Boolean_expression::do_import(Import* imp)
1600 if (imp->peek_char() == 't')
1602 imp->require_c_string("true");
1603 return Expression::make_boolean(true, imp->location());
1605 else
1607 imp->require_c_string("false");
1608 return Expression::make_boolean(false, imp->location());
1612 // Make a boolean expression.
1614 Expression*
1615 Expression::make_boolean(bool val, Location location)
1617 return new Boolean_expression(val, location);
1620 // Class String_expression.
1622 // Get the type.
1624 Type*
1625 String_expression::do_type()
1627 if (this->type_ == NULL)
1628 this->type_ = Type::make_string_type();
1629 return this->type_;
1632 // Set the type from the context.
1634 void
1635 String_expression::do_determine_type(const Type_context* context)
1637 if (this->type_ != NULL && !this->type_->is_abstract())
1639 else if (context->type != NULL && context->type->is_string_type())
1640 this->type_ = context->type;
1641 else if (!context->may_be_abstract)
1642 this->type_ = Type::lookup_string_type();
1645 // Build a string constant.
1647 Bexpression*
1648 String_expression::do_get_backend(Translate_context* context)
1650 Gogo* gogo = context->gogo();
1651 Btype* btype = Type::make_string_type()->get_backend(gogo);
1653 Location loc = this->location();
1654 std::vector<Bexpression*> init(2);
1655 Bexpression* str_cst =
1656 gogo->backend()->string_constant_expression(this->val_);
1657 init[0] = gogo->backend()->address_expression(str_cst, loc);
1659 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1660 mpz_t lenval;
1661 mpz_init_set_ui(lenval, this->val_.length());
1662 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1663 mpz_clear(lenval);
1665 return gogo->backend()->constructor_expression(btype, init, loc);
1668 // Write string literal to string dump.
1670 void
1671 String_expression::export_string(String_dump* exp,
1672 const String_expression* str)
1674 std::string s;
1675 s.reserve(str->val_.length() * 4 + 2);
1676 s += '"';
1677 for (std::string::const_iterator p = str->val_.begin();
1678 p != str->val_.end();
1679 ++p)
1681 if (*p == '\\' || *p == '"')
1683 s += '\\';
1684 s += *p;
1686 else if (*p >= 0x20 && *p < 0x7f)
1687 s += *p;
1688 else if (*p == '\n')
1689 s += "\\n";
1690 else if (*p == '\t')
1691 s += "\\t";
1692 else
1694 s += "\\x";
1695 unsigned char c = *p;
1696 unsigned int dig = c >> 4;
1697 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1698 dig = c & 0xf;
1699 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1702 s += '"';
1703 exp->write_string(s);
1706 // Export a string expression.
1708 void
1709 String_expression::do_export(Export* exp) const
1711 String_expression::export_string(exp, this);
1714 // Import a string expression.
1716 Expression*
1717 String_expression::do_import(Import* imp)
1719 imp->require_c_string("\"");
1720 std::string val;
1721 while (true)
1723 int c = imp->get_char();
1724 if (c == '"' || c == -1)
1725 break;
1726 if (c != '\\')
1727 val += static_cast<char>(c);
1728 else
1730 c = imp->get_char();
1731 if (c == '\\' || c == '"')
1732 val += static_cast<char>(c);
1733 else if (c == 'n')
1734 val += '\n';
1735 else if (c == 't')
1736 val += '\t';
1737 else if (c == 'x')
1739 c = imp->get_char();
1740 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1741 c = imp->get_char();
1742 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1743 char v = (vh << 4) | vl;
1744 val += v;
1746 else
1748 go_error_at(imp->location(), "bad string constant");
1749 return Expression::make_error(imp->location());
1753 return Expression::make_string(val, imp->location());
1756 // Ast dump for string expression.
1758 void
1759 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1761 String_expression::export_string(ast_dump_context, this);
1764 // Make a string expression.
1766 Expression*
1767 Expression::make_string(const std::string& val, Location location)
1769 return new String_expression(val, location);
1772 // An expression that evaluates to some characteristic of a string.
1773 // This is used when indexing, bound-checking, or nil checking a string.
1775 class String_info_expression : public Expression
1777 public:
1778 String_info_expression(Expression* string, String_info string_info,
1779 Location location)
1780 : Expression(EXPRESSION_STRING_INFO, location),
1781 string_(string), string_info_(string_info)
1784 protected:
1785 Type*
1786 do_type();
1788 void
1789 do_determine_type(const Type_context*)
1790 { go_unreachable(); }
1792 Expression*
1793 do_copy()
1795 return new String_info_expression(this->string_->copy(), this->string_info_,
1796 this->location());
1799 Bexpression*
1800 do_get_backend(Translate_context* context);
1802 void
1803 do_dump_expression(Ast_dump_context*) const;
1805 void
1806 do_issue_nil_check()
1807 { this->string_->issue_nil_check(); }
1809 private:
1810 // The string for which we are getting information.
1811 Expression* string_;
1812 // What information we want.
1813 String_info string_info_;
1816 // Return the type of the string info.
1818 Type*
1819 String_info_expression::do_type()
1821 switch (this->string_info_)
1823 case STRING_INFO_DATA:
1825 Type* byte_type = Type::lookup_integer_type("uint8");
1826 return Type::make_pointer_type(byte_type);
1828 case STRING_INFO_LENGTH:
1829 return Type::lookup_integer_type("int");
1830 default:
1831 go_unreachable();
1835 // Return string information in GENERIC.
1837 Bexpression*
1838 String_info_expression::do_get_backend(Translate_context* context)
1840 Gogo* gogo = context->gogo();
1842 Bexpression* bstring = this->string_->get_backend(context);
1843 switch (this->string_info_)
1845 case STRING_INFO_DATA:
1846 case STRING_INFO_LENGTH:
1847 return gogo->backend()->struct_field_expression(bstring,
1848 this->string_info_,
1849 this->location());
1850 break;
1851 default:
1852 go_unreachable();
1856 // Dump ast representation for a type info expression.
1858 void
1859 String_info_expression::do_dump_expression(
1860 Ast_dump_context* ast_dump_context) const
1862 ast_dump_context->ostream() << "stringinfo(";
1863 this->string_->dump_expression(ast_dump_context);
1864 ast_dump_context->ostream() << ",";
1865 ast_dump_context->ostream() <<
1866 (this->string_info_ == STRING_INFO_DATA ? "data"
1867 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1868 : "unknown");
1869 ast_dump_context->ostream() << ")";
1872 // Make a string info expression.
1874 Expression*
1875 Expression::make_string_info(Expression* string, String_info string_info,
1876 Location location)
1878 return new String_info_expression(string, string_info, location);
1881 // Make an integer expression.
1883 class Integer_expression : public Expression
1885 public:
1886 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1887 Location location)
1888 : Expression(EXPRESSION_INTEGER, location),
1889 type_(type), is_character_constant_(is_character_constant)
1890 { mpz_init_set(this->val_, *val); }
1892 static Expression*
1893 do_import(Import*);
1895 // Write VAL to string dump.
1896 static void
1897 export_integer(String_dump* exp, const mpz_t val);
1899 // Write VAL to dump context.
1900 static void
1901 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1903 protected:
1904 bool
1905 do_is_constant() const
1906 { return true; }
1908 bool
1909 do_is_static_initializer() const
1910 { return true; }
1912 bool
1913 do_numeric_constant_value(Numeric_constant* nc) const;
1915 Type*
1916 do_type();
1918 void
1919 do_determine_type(const Type_context* context);
1921 void
1922 do_check_types(Gogo*);
1924 Bexpression*
1925 do_get_backend(Translate_context*);
1927 Expression*
1928 do_copy()
1930 if (this->is_character_constant_)
1931 return Expression::make_character(&this->val_,
1932 (this->type_ == NULL
1933 ? NULL
1934 : this->type_->copy_expressions()),
1935 this->location());
1936 else
1937 return Expression::make_integer_z(&this->val_,
1938 (this->type_ == NULL
1939 ? NULL
1940 : this->type_->copy_expressions()),
1941 this->location());
1944 void
1945 do_export(Export*) const;
1947 void
1948 do_dump_expression(Ast_dump_context*) const;
1950 private:
1951 // The integer value.
1952 mpz_t val_;
1953 // The type so far.
1954 Type* type_;
1955 // Whether this is a character constant.
1956 bool is_character_constant_;
1959 // Return a numeric constant for this expression. We have to mark
1960 // this as a character when appropriate.
1962 bool
1963 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1965 if (this->is_character_constant_)
1966 nc->set_rune(this->type_, this->val_);
1967 else
1968 nc->set_int(this->type_, this->val_);
1969 return true;
1972 // Return the current type. If we haven't set the type yet, we return
1973 // an abstract integer type.
1975 Type*
1976 Integer_expression::do_type()
1978 if (this->type_ == NULL)
1980 if (this->is_character_constant_)
1981 this->type_ = Type::make_abstract_character_type();
1982 else
1983 this->type_ = Type::make_abstract_integer_type();
1985 return this->type_;
1988 // Set the type of the integer value. Here we may switch from an
1989 // abstract type to a real type.
1991 void
1992 Integer_expression::do_determine_type(const Type_context* context)
1994 if (this->type_ != NULL && !this->type_->is_abstract())
1996 else if (context->type != NULL && context->type->is_numeric_type())
1997 this->type_ = context->type;
1998 else if (!context->may_be_abstract)
2000 if (this->is_character_constant_)
2001 this->type_ = Type::lookup_integer_type("int32");
2002 else
2003 this->type_ = Type::lookup_integer_type("int");
2007 // Check the type of an integer constant.
2009 void
2010 Integer_expression::do_check_types(Gogo*)
2012 Type* type = this->type_;
2013 if (type == NULL)
2014 return;
2015 Numeric_constant nc;
2016 if (this->is_character_constant_)
2017 nc.set_rune(NULL, this->val_);
2018 else
2019 nc.set_int(NULL, this->val_);
2020 if (!nc.set_type(type, true, this->location()))
2021 this->set_is_error();
2024 // Get the backend representation for an integer constant.
2026 Bexpression*
2027 Integer_expression::do_get_backend(Translate_context* context)
2029 if (this->is_error_expression()
2030 || (this->type_ != NULL && this->type_->is_error_type()))
2032 go_assert(saw_errors());
2033 return context->gogo()->backend()->error_expression();
2036 Type* resolved_type = NULL;
2037 if (this->type_ != NULL && !this->type_->is_abstract())
2038 resolved_type = this->type_;
2039 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2041 // We are converting to an abstract floating point type.
2042 resolved_type = Type::lookup_float_type("float64");
2044 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2046 // We are converting to an abstract complex type.
2047 resolved_type = Type::lookup_complex_type("complex128");
2049 else
2051 // If we still have an abstract type here, then this is being
2052 // used in a constant expression which didn't get reduced for
2053 // some reason. Use a type which will fit the value. We use <,
2054 // not <=, because we need an extra bit for the sign bit.
2055 int bits = mpz_sizeinbase(this->val_, 2);
2056 Type* int_type = Type::lookup_integer_type("int");
2057 if (bits < int_type->integer_type()->bits())
2058 resolved_type = int_type;
2059 else if (bits < 64)
2060 resolved_type = Type::lookup_integer_type("int64");
2061 else
2063 if (!saw_errors())
2064 go_error_at(this->location(),
2065 "unknown type for large integer constant");
2066 return context->gogo()->backend()->error_expression();
2069 Numeric_constant nc;
2070 nc.set_int(resolved_type, this->val_);
2071 return Expression::backend_numeric_constant_expression(context, &nc);
2074 // Write VAL to export data.
2076 void
2077 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2079 char* s = mpz_get_str(NULL, 10, val);
2080 exp->write_c_string(s);
2081 free(s);
2084 // Export an integer in a constant expression.
2086 void
2087 Integer_expression::do_export(Export* exp) const
2089 Integer_expression::export_integer(exp, this->val_);
2090 if (this->is_character_constant_)
2091 exp->write_c_string("'");
2092 // A trailing space lets us reliably identify the end of the number.
2093 exp->write_c_string(" ");
2096 // Import an integer, floating point, or complex value. This handles
2097 // all these types because they all start with digits.
2099 Expression*
2100 Integer_expression::do_import(Import* imp)
2102 std::string num = imp->read_identifier();
2103 imp->require_c_string(" ");
2104 if (!num.empty() && num[num.length() - 1] == 'i')
2106 mpfr_t real;
2107 size_t plus_pos = num.find('+', 1);
2108 size_t minus_pos = num.find('-', 1);
2109 size_t pos;
2110 if (plus_pos == std::string::npos)
2111 pos = minus_pos;
2112 else if (minus_pos == std::string::npos)
2113 pos = plus_pos;
2114 else
2116 go_error_at(imp->location(), "bad number in import data: %qs",
2117 num.c_str());
2118 return Expression::make_error(imp->location());
2120 if (pos == std::string::npos)
2121 mpfr_set_ui(real, 0, GMP_RNDN);
2122 else
2124 std::string real_str = num.substr(0, pos);
2125 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2127 go_error_at(imp->location(), "bad number in import data: %qs",
2128 real_str.c_str());
2129 return Expression::make_error(imp->location());
2133 std::string imag_str;
2134 if (pos == std::string::npos)
2135 imag_str = num;
2136 else
2137 imag_str = num.substr(pos);
2138 imag_str = imag_str.substr(0, imag_str.size() - 1);
2139 mpfr_t imag;
2140 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2142 go_error_at(imp->location(), "bad number in import data: %qs",
2143 imag_str.c_str());
2144 return Expression::make_error(imp->location());
2146 mpc_t cval;
2147 mpc_init2(cval, mpc_precision);
2148 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2149 mpfr_clear(real);
2150 mpfr_clear(imag);
2151 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2152 mpc_clear(cval);
2153 return ret;
2155 else if (num.find('.') == std::string::npos
2156 && num.find('E') == std::string::npos)
2158 bool is_character_constant = (!num.empty()
2159 && num[num.length() - 1] == '\'');
2160 if (is_character_constant)
2161 num = num.substr(0, num.length() - 1);
2162 mpz_t val;
2163 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2165 go_error_at(imp->location(), "bad number in import data: %qs",
2166 num.c_str());
2167 return Expression::make_error(imp->location());
2169 Expression* ret;
2170 if (is_character_constant)
2171 ret = Expression::make_character(&val, NULL, imp->location());
2172 else
2173 ret = Expression::make_integer_z(&val, NULL, imp->location());
2174 mpz_clear(val);
2175 return ret;
2177 else
2179 mpfr_t val;
2180 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2182 go_error_at(imp->location(), "bad number in import data: %qs",
2183 num.c_str());
2184 return Expression::make_error(imp->location());
2186 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2187 mpfr_clear(val);
2188 return ret;
2191 // Ast dump for integer expression.
2193 void
2194 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2196 if (this->is_character_constant_)
2197 ast_dump_context->ostream() << '\'';
2198 Integer_expression::export_integer(ast_dump_context, this->val_);
2199 if (this->is_character_constant_)
2200 ast_dump_context->ostream() << '\'';
2203 // Build a new integer value from a multi-precision integer.
2205 Expression*
2206 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2208 return new Integer_expression(val, type, false, location);
2211 // Build a new integer value from an unsigned long.
2213 Expression*
2214 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2216 mpz_t zval;
2217 mpz_init_set_ui(zval, val);
2218 Expression* ret = Expression::make_integer_z(&zval, type, location);
2219 mpz_clear(zval);
2220 return ret;
2223 // Build a new integer value from a signed long.
2225 Expression*
2226 Expression::make_integer_sl(long val, Type *type, Location location)
2228 mpz_t zval;
2229 mpz_init_set_si(zval, val);
2230 Expression* ret = Expression::make_integer_z(&zval, type, location);
2231 mpz_clear(zval);
2232 return ret;
2235 // Store an int64_t in an uninitialized mpz_t.
2237 static void
2238 set_mpz_from_int64(mpz_t* zval, int64_t val)
2240 if (val >= 0)
2242 unsigned long ul = static_cast<unsigned long>(val);
2243 if (static_cast<int64_t>(ul) == val)
2245 mpz_init_set_ui(*zval, ul);
2246 return;
2249 uint64_t uv;
2250 if (val >= 0)
2251 uv = static_cast<uint64_t>(val);
2252 else
2253 uv = static_cast<uint64_t>(- val);
2254 unsigned long ul = uv & 0xffffffffUL;
2255 mpz_init_set_ui(*zval, ul);
2256 mpz_t hval;
2257 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2258 mpz_mul_2exp(hval, hval, 32);
2259 mpz_add(*zval, *zval, hval);
2260 mpz_clear(hval);
2261 if (val < 0)
2262 mpz_neg(*zval, *zval);
2265 // Build a new integer value from an int64_t.
2267 Expression*
2268 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2270 mpz_t zval;
2271 set_mpz_from_int64(&zval, val);
2272 Expression* ret = Expression::make_integer_z(&zval, type, location);
2273 mpz_clear(zval);
2274 return ret;
2277 // Build a new character constant value.
2279 Expression*
2280 Expression::make_character(const mpz_t* val, Type* type, Location location)
2282 return new Integer_expression(val, type, true, location);
2285 // Floats.
2287 class Float_expression : public Expression
2289 public:
2290 Float_expression(const mpfr_t* val, Type* type, Location location)
2291 : Expression(EXPRESSION_FLOAT, location),
2292 type_(type)
2294 mpfr_init_set(this->val_, *val, GMP_RNDN);
2297 // Write VAL to export data.
2298 static void
2299 export_float(String_dump* exp, const mpfr_t val);
2301 // Write VAL to dump file.
2302 static void
2303 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2305 protected:
2306 bool
2307 do_is_constant() const
2308 { return true; }
2310 bool
2311 do_is_static_initializer() const
2312 { return true; }
2314 bool
2315 do_numeric_constant_value(Numeric_constant* nc) const
2317 nc->set_float(this->type_, this->val_);
2318 return true;
2321 Type*
2322 do_type();
2324 void
2325 do_determine_type(const Type_context*);
2327 void
2328 do_check_types(Gogo*);
2330 Expression*
2331 do_copy()
2332 { return Expression::make_float(&this->val_,
2333 (this->type_ == NULL
2334 ? NULL
2335 : this->type_->copy_expressions()),
2336 this->location()); }
2338 Bexpression*
2339 do_get_backend(Translate_context*);
2341 void
2342 do_export(Export*) const;
2344 void
2345 do_dump_expression(Ast_dump_context*) const;
2347 private:
2348 // The floating point value.
2349 mpfr_t val_;
2350 // The type so far.
2351 Type* type_;
2354 // Return the current type. If we haven't set the type yet, we return
2355 // an abstract float type.
2357 Type*
2358 Float_expression::do_type()
2360 if (this->type_ == NULL)
2361 this->type_ = Type::make_abstract_float_type();
2362 return this->type_;
2365 // Set the type of the float value. Here we may switch from an
2366 // abstract type to a real type.
2368 void
2369 Float_expression::do_determine_type(const Type_context* context)
2371 if (this->type_ != NULL && !this->type_->is_abstract())
2373 else if (context->type != NULL
2374 && (context->type->integer_type() != NULL
2375 || context->type->float_type() != NULL
2376 || context->type->complex_type() != NULL))
2377 this->type_ = context->type;
2378 else if (!context->may_be_abstract)
2379 this->type_ = Type::lookup_float_type("float64");
2382 // Check the type of a float value.
2384 void
2385 Float_expression::do_check_types(Gogo*)
2387 Type* type = this->type_;
2388 if (type == NULL)
2389 return;
2390 Numeric_constant nc;
2391 nc.set_float(NULL, this->val_);
2392 if (!nc.set_type(this->type_, true, this->location()))
2393 this->set_is_error();
2396 // Get the backend representation for a float constant.
2398 Bexpression*
2399 Float_expression::do_get_backend(Translate_context* context)
2401 if (this->is_error_expression()
2402 || (this->type_ != NULL && this->type_->is_error_type()))
2404 go_assert(saw_errors());
2405 return context->gogo()->backend()->error_expression();
2408 Type* resolved_type;
2409 if (this->type_ != NULL && !this->type_->is_abstract())
2410 resolved_type = this->type_;
2411 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2413 // We have an abstract integer type. We just hope for the best.
2414 resolved_type = Type::lookup_integer_type("int");
2416 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2418 // We are converting to an abstract complex type.
2419 resolved_type = Type::lookup_complex_type("complex128");
2421 else
2423 // If we still have an abstract type here, then this is being
2424 // used in a constant expression which didn't get reduced. We
2425 // just use float64 and hope for the best.
2426 resolved_type = Type::lookup_float_type("float64");
2429 Numeric_constant nc;
2430 nc.set_float(resolved_type, this->val_);
2431 return Expression::backend_numeric_constant_expression(context, &nc);
2434 // Write a floating point number to a string dump.
2436 void
2437 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2439 mp_exp_t exponent;
2440 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2441 if (*s == '-')
2442 exp->write_c_string("-");
2443 exp->write_c_string("0.");
2444 exp->write_c_string(*s == '-' ? s + 1 : s);
2445 mpfr_free_str(s);
2446 char buf[30];
2447 snprintf(buf, sizeof buf, "E%ld", exponent);
2448 exp->write_c_string(buf);
2451 // Export a floating point number in a constant expression.
2453 void
2454 Float_expression::do_export(Export* exp) const
2456 Float_expression::export_float(exp, this->val_);
2457 // A trailing space lets us reliably identify the end of the number.
2458 exp->write_c_string(" ");
2461 // Dump a floating point number to the dump file.
2463 void
2464 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2466 Float_expression::export_float(ast_dump_context, this->val_);
2469 // Make a float expression.
2471 Expression*
2472 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2474 return new Float_expression(val, type, location);
2477 // Complex numbers.
2479 class Complex_expression : public Expression
2481 public:
2482 Complex_expression(const mpc_t* val, Type* type, Location location)
2483 : Expression(EXPRESSION_COMPLEX, location),
2484 type_(type)
2486 mpc_init2(this->val_, mpc_precision);
2487 mpc_set(this->val_, *val, MPC_RNDNN);
2490 // Write VAL to string dump.
2491 static void
2492 export_complex(String_dump* exp, const mpc_t val);
2494 // Write REAL/IMAG to dump context.
2495 static void
2496 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2498 protected:
2499 bool
2500 do_is_constant() const
2501 { return true; }
2503 bool
2504 do_is_static_initializer() const
2505 { return true; }
2507 bool
2508 do_numeric_constant_value(Numeric_constant* nc) const
2510 nc->set_complex(this->type_, this->val_);
2511 return true;
2514 Type*
2515 do_type();
2517 void
2518 do_determine_type(const Type_context*);
2520 void
2521 do_check_types(Gogo*);
2523 Expression*
2524 do_copy()
2526 return Expression::make_complex(&this->val_,
2527 (this->type_ == NULL
2528 ? NULL
2529 : this->type_->copy_expressions()),
2530 this->location());
2533 Bexpression*
2534 do_get_backend(Translate_context*);
2536 void
2537 do_export(Export*) const;
2539 void
2540 do_dump_expression(Ast_dump_context*) const;
2542 private:
2543 // The complex value.
2544 mpc_t val_;
2545 // The type if known.
2546 Type* type_;
2549 // Return the current type. If we haven't set the type yet, we return
2550 // an abstract complex type.
2552 Type*
2553 Complex_expression::do_type()
2555 if (this->type_ == NULL)
2556 this->type_ = Type::make_abstract_complex_type();
2557 return this->type_;
2560 // Set the type of the complex value. Here we may switch from an
2561 // abstract type to a real type.
2563 void
2564 Complex_expression::do_determine_type(const Type_context* context)
2566 if (this->type_ != NULL && !this->type_->is_abstract())
2568 else if (context->type != NULL && context->type->is_numeric_type())
2569 this->type_ = context->type;
2570 else if (!context->may_be_abstract)
2571 this->type_ = Type::lookup_complex_type("complex128");
2574 // Check the type of a complex value.
2576 void
2577 Complex_expression::do_check_types(Gogo*)
2579 Type* type = this->type_;
2580 if (type == NULL)
2581 return;
2582 Numeric_constant nc;
2583 nc.set_complex(NULL, this->val_);
2584 if (!nc.set_type(this->type_, true, this->location()))
2585 this->set_is_error();
2588 // Get the backend representation for a complex constant.
2590 Bexpression*
2591 Complex_expression::do_get_backend(Translate_context* context)
2593 if (this->is_error_expression()
2594 || (this->type_ != NULL && this->type_->is_error_type()))
2596 go_assert(saw_errors());
2597 return context->gogo()->backend()->error_expression();
2600 Type* resolved_type;
2601 if (this->type_ != NULL && !this->type_->is_abstract())
2602 resolved_type = this->type_;
2603 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2605 // We are converting to an abstract integer type.
2606 resolved_type = Type::lookup_integer_type("int");
2608 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2610 // We are converting to an abstract float type.
2611 resolved_type = Type::lookup_float_type("float64");
2613 else
2615 // If we still have an abstract type here, this is being
2616 // used in a constant expression which didn't get reduced. We
2617 // just use complex128 and hope for the best.
2618 resolved_type = Type::lookup_complex_type("complex128");
2621 Numeric_constant nc;
2622 nc.set_complex(resolved_type, this->val_);
2623 return Expression::backend_numeric_constant_expression(context, &nc);
2626 // Write REAL/IMAG to export data.
2628 void
2629 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2631 if (!mpfr_zero_p(mpc_realref(val)))
2633 Float_expression::export_float(exp, mpc_realref(val));
2634 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2635 exp->write_c_string("+");
2637 Float_expression::export_float(exp, mpc_imagref(val));
2638 exp->write_c_string("i");
2641 // Export a complex number in a constant expression.
2643 void
2644 Complex_expression::do_export(Export* exp) const
2646 Complex_expression::export_complex(exp, this->val_);
2647 // A trailing space lets us reliably identify the end of the number.
2648 exp->write_c_string(" ");
2651 // Dump a complex expression to the dump file.
2653 void
2654 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2656 Complex_expression::export_complex(ast_dump_context, this->val_);
2659 // Make a complex expression.
2661 Expression*
2662 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2664 return new Complex_expression(val, type, location);
2667 // Find a named object in an expression.
2669 class Find_named_object : public Traverse
2671 public:
2672 Find_named_object(Named_object* no)
2673 : Traverse(traverse_expressions),
2674 no_(no), found_(false)
2677 // Whether we found the object.
2678 bool
2679 found() const
2680 { return this->found_; }
2682 protected:
2684 expression(Expression**);
2686 private:
2687 // The object we are looking for.
2688 Named_object* no_;
2689 // Whether we found it.
2690 bool found_;
2693 // A reference to a const in an expression.
2695 class Const_expression : public Expression
2697 public:
2698 Const_expression(Named_object* constant, Location location)
2699 : Expression(EXPRESSION_CONST_REFERENCE, location),
2700 constant_(constant), type_(NULL), seen_(false)
2703 Named_object*
2704 named_object()
2705 { return this->constant_; }
2707 // Check that the initializer does not refer to the constant itself.
2708 void
2709 check_for_init_loop();
2711 protected:
2713 do_traverse(Traverse*);
2715 Expression*
2716 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2718 bool
2719 do_is_constant() const
2720 { return true; }
2722 bool
2723 do_is_static_initializer() const
2724 { return true; }
2726 bool
2727 do_numeric_constant_value(Numeric_constant* nc) const;
2729 bool
2730 do_string_constant_value(std::string* val) const;
2732 Type*
2733 do_type();
2735 // The type of a const is set by the declaration, not the use.
2736 void
2737 do_determine_type(const Type_context*);
2739 void
2740 do_check_types(Gogo*);
2742 Expression*
2743 do_copy()
2744 { return this; }
2746 Bexpression*
2747 do_get_backend(Translate_context* context);
2749 // When exporting a reference to a const as part of a const
2750 // expression, we export the value. We ignore the fact that it has
2751 // a name.
2752 void
2753 do_export(Export* exp) const
2754 { this->constant_->const_value()->expr()->export_expression(exp); }
2756 void
2757 do_dump_expression(Ast_dump_context*) const;
2759 private:
2760 // The constant.
2761 Named_object* constant_;
2762 // The type of this reference. This is used if the constant has an
2763 // abstract type.
2764 Type* type_;
2765 // Used to prevent infinite recursion when a constant incorrectly
2766 // refers to itself.
2767 mutable bool seen_;
2770 // Traversal.
2773 Const_expression::do_traverse(Traverse* traverse)
2775 if (this->type_ != NULL)
2776 return Type::traverse(this->type_, traverse);
2777 return TRAVERSE_CONTINUE;
2780 // Lower a constant expression. This is where we convert the
2781 // predeclared constant iota into an integer value.
2783 Expression*
2784 Const_expression::do_lower(Gogo* gogo, Named_object*,
2785 Statement_inserter*, int iota_value)
2787 if (this->constant_->const_value()->expr()->classification()
2788 == EXPRESSION_IOTA)
2790 if (iota_value == -1)
2792 go_error_at(this->location(),
2793 "iota is only defined in const declarations");
2794 iota_value = 0;
2796 return Expression::make_integer_ul(iota_value, NULL, this->location());
2799 // Make sure that the constant itself has been lowered.
2800 gogo->lower_constant(this->constant_);
2802 return this;
2805 // Return a numeric constant value.
2807 bool
2808 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2810 if (this->seen_)
2811 return false;
2813 Expression* e = this->constant_->const_value()->expr();
2815 this->seen_ = true;
2817 bool r = e->numeric_constant_value(nc);
2819 this->seen_ = false;
2821 Type* ctype;
2822 if (this->type_ != NULL)
2823 ctype = this->type_;
2824 else
2825 ctype = this->constant_->const_value()->type();
2826 if (r && ctype != NULL)
2828 if (!nc->set_type(ctype, false, this->location()))
2829 return false;
2832 return r;
2835 bool
2836 Const_expression::do_string_constant_value(std::string* val) const
2838 if (this->seen_)
2839 return false;
2841 Expression* e = this->constant_->const_value()->expr();
2843 this->seen_ = true;
2844 bool ok = e->string_constant_value(val);
2845 this->seen_ = false;
2847 return ok;
2850 // Return the type of the const reference.
2852 Type*
2853 Const_expression::do_type()
2855 if (this->type_ != NULL)
2856 return this->type_;
2858 Named_constant* nc = this->constant_->const_value();
2860 if (this->seen_ || nc->lowering())
2862 if (nc->type() == NULL || !nc->type()->is_error_type())
2864 Location loc = this->location();
2865 if (!this->seen_)
2866 loc = nc->location();
2867 go_error_at(loc, "constant refers to itself");
2869 this->set_is_error();
2870 this->type_ = Type::make_error_type();
2871 nc->set_type(this->type_);
2872 return this->type_;
2875 this->seen_ = true;
2877 Type* ret = nc->type();
2879 if (ret != NULL)
2881 this->seen_ = false;
2882 return ret;
2885 // During parsing, a named constant may have a NULL type, but we
2886 // must not return a NULL type here.
2887 ret = nc->expr()->type();
2889 this->seen_ = false;
2891 if (ret->is_error_type())
2892 nc->set_type(ret);
2894 return ret;
2897 // Set the type of the const reference.
2899 void
2900 Const_expression::do_determine_type(const Type_context* context)
2902 Type* ctype = this->constant_->const_value()->type();
2903 Type* cetype = (ctype != NULL
2904 ? ctype
2905 : this->constant_->const_value()->expr()->type());
2906 if (ctype != NULL && !ctype->is_abstract())
2908 else if (context->type != NULL
2909 && context->type->is_numeric_type()
2910 && cetype->is_numeric_type())
2911 this->type_ = context->type;
2912 else if (context->type != NULL
2913 && context->type->is_string_type()
2914 && cetype->is_string_type())
2915 this->type_ = context->type;
2916 else if (context->type != NULL
2917 && context->type->is_boolean_type()
2918 && cetype->is_boolean_type())
2919 this->type_ = context->type;
2920 else if (!context->may_be_abstract)
2922 if (cetype->is_abstract())
2923 cetype = cetype->make_non_abstract_type();
2924 this->type_ = cetype;
2928 // Check for a loop in which the initializer of a constant refers to
2929 // the constant itself.
2931 void
2932 Const_expression::check_for_init_loop()
2934 if (this->type_ != NULL && this->type_->is_error())
2935 return;
2937 if (this->seen_)
2939 this->report_error(_("constant refers to itself"));
2940 this->type_ = Type::make_error_type();
2941 return;
2944 Expression* init = this->constant_->const_value()->expr();
2945 Find_named_object find_named_object(this->constant_);
2947 this->seen_ = true;
2948 Expression::traverse(&init, &find_named_object);
2949 this->seen_ = false;
2951 if (find_named_object.found())
2953 if (this->type_ == NULL || !this->type_->is_error())
2955 this->report_error(_("constant refers to itself"));
2956 this->type_ = Type::make_error_type();
2958 return;
2962 // Check types of a const reference.
2964 void
2965 Const_expression::do_check_types(Gogo*)
2967 if (this->type_ != NULL && this->type_->is_error())
2968 return;
2970 this->check_for_init_loop();
2972 // Check that numeric constant fits in type.
2973 if (this->type_ != NULL && this->type_->is_numeric_type())
2975 Numeric_constant nc;
2976 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2978 if (!nc.set_type(this->type_, true, this->location()))
2979 this->set_is_error();
2984 // Return the backend representation for a const reference.
2986 Bexpression*
2987 Const_expression::do_get_backend(Translate_context* context)
2989 if (this->is_error_expression()
2990 || (this->type_ != NULL && this->type_->is_error()))
2992 go_assert(saw_errors());
2993 return context->backend()->error_expression();
2996 // If the type has been set for this expression, but the underlying
2997 // object is an abstract int or float, we try to get the abstract
2998 // value. Otherwise we may lose something in the conversion.
2999 Expression* expr = this->constant_->const_value()->expr();
3000 if (this->type_ != NULL
3001 && this->type_->is_numeric_type()
3002 && (this->constant_->const_value()->type() == NULL
3003 || this->constant_->const_value()->type()->is_abstract()))
3005 Numeric_constant nc;
3006 if (expr->numeric_constant_value(&nc)
3007 && nc.set_type(this->type_, false, this->location()))
3009 Expression* e = nc.expression(this->location());
3010 return e->get_backend(context);
3014 if (this->type_ != NULL)
3015 expr = Expression::make_cast(this->type_, expr, this->location());
3016 return expr->get_backend(context);
3019 // Dump ast representation for constant expression.
3021 void
3022 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3024 ast_dump_context->ostream() << this->constant_->name();
3027 // Make a reference to a constant in an expression.
3029 Expression*
3030 Expression::make_const_reference(Named_object* constant,
3031 Location location)
3033 return new Const_expression(constant, location);
3036 // Find a named object in an expression.
3039 Find_named_object::expression(Expression** pexpr)
3041 switch ((*pexpr)->classification())
3043 case Expression::EXPRESSION_CONST_REFERENCE:
3045 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3046 if (ce->named_object() == this->no_)
3047 break;
3049 // We need to check a constant initializer explicitly, as
3050 // loops here will not be caught by the loop checking for
3051 // variable initializers.
3052 ce->check_for_init_loop();
3054 return TRAVERSE_CONTINUE;
3057 case Expression::EXPRESSION_VAR_REFERENCE:
3058 if ((*pexpr)->var_expression()->named_object() == this->no_)
3059 break;
3060 return TRAVERSE_CONTINUE;
3061 case Expression::EXPRESSION_FUNC_REFERENCE:
3062 if ((*pexpr)->func_expression()->named_object() == this->no_)
3063 break;
3064 return TRAVERSE_CONTINUE;
3065 default:
3066 return TRAVERSE_CONTINUE;
3068 this->found_ = true;
3069 return TRAVERSE_EXIT;
3072 // The nil value.
3074 class Nil_expression : public Expression
3076 public:
3077 Nil_expression(Location location)
3078 : Expression(EXPRESSION_NIL, location)
3081 static Expression*
3082 do_import(Import*);
3084 protected:
3085 bool
3086 do_is_constant() const
3087 { return true; }
3089 bool
3090 do_is_static_initializer() const
3091 { return true; }
3093 Type*
3094 do_type()
3095 { return Type::make_nil_type(); }
3097 void
3098 do_determine_type(const Type_context*)
3101 Expression*
3102 do_copy()
3103 { return this; }
3105 Bexpression*
3106 do_get_backend(Translate_context* context)
3107 { return context->backend()->nil_pointer_expression(); }
3109 void
3110 do_export(Export* exp) const
3111 { exp->write_c_string("nil"); }
3113 void
3114 do_dump_expression(Ast_dump_context* ast_dump_context) const
3115 { ast_dump_context->ostream() << "nil"; }
3118 // Import a nil expression.
3120 Expression*
3121 Nil_expression::do_import(Import* imp)
3123 imp->require_c_string("nil");
3124 return Expression::make_nil(imp->location());
3127 // Make a nil expression.
3129 Expression*
3130 Expression::make_nil(Location location)
3132 return new Nil_expression(location);
3135 // The value of the predeclared constant iota. This is little more
3136 // than a marker. This will be lowered to an integer in
3137 // Const_expression::do_lower, which is where we know the value that
3138 // it should have.
3140 class Iota_expression : public Parser_expression
3142 public:
3143 Iota_expression(Location location)
3144 : Parser_expression(EXPRESSION_IOTA, location)
3147 protected:
3148 Expression*
3149 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3150 { go_unreachable(); }
3152 // There should only ever be one of these.
3153 Expression*
3154 do_copy()
3155 { go_unreachable(); }
3157 void
3158 do_dump_expression(Ast_dump_context* ast_dump_context) const
3159 { ast_dump_context->ostream() << "iota"; }
3162 // Make an iota expression. This is only called for one case: the
3163 // value of the predeclared constant iota.
3165 Expression*
3166 Expression::make_iota()
3168 static Iota_expression iota_expression(Linemap::unknown_location());
3169 return &iota_expression;
3172 // Class Type_conversion_expression.
3174 // Traversal.
3177 Type_conversion_expression::do_traverse(Traverse* traverse)
3179 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3180 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3181 return TRAVERSE_EXIT;
3182 return TRAVERSE_CONTINUE;
3185 // Convert to a constant at lowering time.
3187 Expression*
3188 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3189 Statement_inserter*, int)
3191 Type* type = this->type_;
3192 Expression* val = this->expr_;
3193 Location location = this->location();
3195 if (type->is_numeric_type())
3197 Numeric_constant nc;
3198 if (val->numeric_constant_value(&nc))
3200 if (!nc.set_type(type, true, location))
3201 return Expression::make_error(location);
3202 return nc.expression(location);
3206 // According to the language specification on string conversions
3207 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3208 // When converting an integer into a string, the string will be a UTF-8
3209 // representation of the integer and integers "outside the range of valid
3210 // Unicode code points are converted to '\uFFFD'."
3211 if (type->is_string_type())
3213 Numeric_constant nc;
3214 if (val->numeric_constant_value(&nc) && nc.is_int())
3216 // An integer value doesn't fit in the Unicode code point range if it
3217 // overflows the Go "int" type or is negative.
3218 unsigned long ul;
3219 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3220 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3221 return Expression::make_string("\ufffd", location);
3225 if (type->is_slice_type())
3227 Type* element_type = type->array_type()->element_type()->forwarded();
3228 bool is_byte = (element_type->integer_type() != NULL
3229 && element_type->integer_type()->is_byte());
3230 bool is_rune = (element_type->integer_type() != NULL
3231 && element_type->integer_type()->is_rune());
3232 if (is_byte || is_rune)
3234 std::string s;
3235 if (val->string_constant_value(&s))
3237 Expression_list* vals = new Expression_list();
3238 if (is_byte)
3240 for (std::string::const_iterator p = s.begin();
3241 p != s.end();
3242 p++)
3244 unsigned char c = static_cast<unsigned char>(*p);
3245 vals->push_back(Expression::make_integer_ul(c,
3246 element_type,
3247 location));
3250 else
3252 const char *p = s.data();
3253 const char *pend = s.data() + s.length();
3254 while (p < pend)
3256 unsigned int c;
3257 int adv = Lex::fetch_char(p, &c);
3258 if (adv == 0)
3260 go_warning_at(this->location(), 0,
3261 "invalid UTF-8 encoding");
3262 adv = 1;
3264 p += adv;
3265 vals->push_back(Expression::make_integer_ul(c,
3266 element_type,
3267 location));
3271 return Expression::make_slice_composite_literal(type, vals,
3272 location);
3277 return this;
3280 // Flatten a type conversion by using a temporary variable for the slice
3281 // in slice to string conversions.
3283 Expression*
3284 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3285 Statement_inserter* inserter)
3287 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3289 go_assert(saw_errors());
3290 return Expression::make_error(this->location());
3293 if (((this->type()->is_string_type()
3294 && this->expr_->type()->is_slice_type())
3295 || this->expr_->type()->interface_type() != NULL)
3296 && !this->expr_->is_variable())
3298 Temporary_statement* temp =
3299 Statement::make_temporary(NULL, this->expr_, this->location());
3300 inserter->insert(temp);
3301 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3303 return this;
3306 // Return whether a type conversion is a constant.
3308 bool
3309 Type_conversion_expression::do_is_constant() const
3311 if (!this->expr_->is_constant())
3312 return false;
3314 // A conversion to a type that may not be used as a constant is not
3315 // a constant. For example, []byte(nil).
3316 Type* type = this->type_;
3317 if (type->integer_type() == NULL
3318 && type->float_type() == NULL
3319 && type->complex_type() == NULL
3320 && !type->is_boolean_type()
3321 && !type->is_string_type())
3322 return false;
3324 return true;
3327 // Return whether a type conversion can be used in a constant
3328 // initializer.
3330 bool
3331 Type_conversion_expression::do_is_static_initializer() const
3333 Type* type = this->type_;
3334 Type* expr_type = this->expr_->type();
3336 if (type->interface_type() != NULL
3337 || expr_type->interface_type() != NULL)
3338 return false;
3340 if (!this->expr_->is_static_initializer())
3341 return false;
3343 if (Type::are_identical(type, expr_type, false, NULL))
3344 return true;
3346 if (type->is_string_type() && expr_type->is_string_type())
3347 return true;
3349 if ((type->is_numeric_type()
3350 || type->is_boolean_type()
3351 || type->points_to() != NULL)
3352 && (expr_type->is_numeric_type()
3353 || expr_type->is_boolean_type()
3354 || expr_type->points_to() != NULL))
3355 return true;
3357 return false;
3360 // Return the constant numeric value if there is one.
3362 bool
3363 Type_conversion_expression::do_numeric_constant_value(
3364 Numeric_constant* nc) const
3366 if (!this->type_->is_numeric_type())
3367 return false;
3368 if (!this->expr_->numeric_constant_value(nc))
3369 return false;
3370 return nc->set_type(this->type_, false, this->location());
3373 // Return the constant string value if there is one.
3375 bool
3376 Type_conversion_expression::do_string_constant_value(std::string* val) const
3378 if (this->type_->is_string_type()
3379 && this->expr_->type()->integer_type() != NULL)
3381 Numeric_constant nc;
3382 if (this->expr_->numeric_constant_value(&nc))
3384 unsigned long ival;
3385 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3387 val->clear();
3388 Lex::append_char(ival, true, val, this->location());
3389 return true;
3394 // FIXME: Could handle conversion from const []int here.
3396 return false;
3399 // Determine the resulting type of the conversion.
3401 void
3402 Type_conversion_expression::do_determine_type(const Type_context*)
3404 Type_context subcontext(this->type_, false);
3405 this->expr_->determine_type(&subcontext);
3408 // Check that types are convertible.
3410 void
3411 Type_conversion_expression::do_check_types(Gogo*)
3413 Type* type = this->type_;
3414 Type* expr_type = this->expr_->type();
3415 std::string reason;
3417 if (type->is_error() || expr_type->is_error())
3419 this->set_is_error();
3420 return;
3423 if (this->may_convert_function_types_
3424 && type->function_type() != NULL
3425 && expr_type->function_type() != NULL)
3426 return;
3428 if (Type::are_convertible(type, expr_type, &reason))
3429 return;
3431 go_error_at(this->location(), "%s", reason.c_str());
3432 this->set_is_error();
3435 // Copy.
3437 Expression*
3438 Type_conversion_expression::do_copy()
3440 return new Type_conversion_expression(this->type_->copy_expressions(),
3441 this->expr_->copy(),
3442 this->location());
3445 // Get the backend representation for a type conversion.
3447 Bexpression*
3448 Type_conversion_expression::do_get_backend(Translate_context* context)
3450 Type* type = this->type_;
3451 Type* expr_type = this->expr_->type();
3453 Gogo* gogo = context->gogo();
3454 Btype* btype = type->get_backend(gogo);
3455 Location loc = this->location();
3457 if (Type::are_identical(type, expr_type, false, NULL))
3459 Bexpression* bexpr = this->expr_->get_backend(context);
3460 return gogo->backend()->convert_expression(btype, bexpr, loc);
3462 else if (type->interface_type() != NULL
3463 || expr_type->interface_type() != NULL)
3465 Expression* conversion =
3466 Expression::convert_for_assignment(gogo, type, this->expr_,
3467 this->location());
3468 return conversion->get_backend(context);
3470 else if (type->is_string_type()
3471 && expr_type->integer_type() != NULL)
3473 mpz_t intval;
3474 Numeric_constant nc;
3475 if (this->expr_->numeric_constant_value(&nc)
3476 && nc.to_int(&intval)
3477 && mpz_fits_ushort_p(intval))
3479 std::string s;
3480 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3481 mpz_clear(intval);
3482 Expression* se = Expression::make_string(s, loc);
3483 return se->get_backend(context);
3486 Expression* i2s_expr =
3487 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3488 Expression::make_nil(loc), this->expr_);
3489 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3491 else if (type->is_string_type() && expr_type->is_slice_type())
3493 Array_type* a = expr_type->array_type();
3494 Type* e = a->element_type()->forwarded();
3495 go_assert(e->integer_type() != NULL);
3496 go_assert(this->expr_->is_variable());
3498 Runtime::Function code;
3499 if (e->integer_type()->is_byte())
3500 code = Runtime::SLICEBYTETOSTRING;
3501 else
3503 go_assert(e->integer_type()->is_rune());
3504 code = Runtime::SLICERUNETOSTRING;
3506 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3507 this->expr_)->get_backend(context);
3509 else if (type->is_slice_type() && expr_type->is_string_type())
3511 Type* e = type->array_type()->element_type()->forwarded();
3512 go_assert(e->integer_type() != NULL);
3514 Runtime::Function code;
3515 if (e->integer_type()->is_byte())
3516 code = Runtime::STRINGTOSLICEBYTE;
3517 else
3519 go_assert(e->integer_type()->is_rune());
3520 code = Runtime::STRINGTOSLICERUNE;
3522 Expression* s2a = Runtime::make_call(code, loc, 2,
3523 Expression::make_nil(loc),
3524 this->expr_);
3525 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3527 else if (type->is_numeric_type())
3529 go_assert(Type::are_convertible(type, expr_type, NULL));
3530 Bexpression* bexpr = this->expr_->get_backend(context);
3531 return gogo->backend()->convert_expression(btype, bexpr, loc);
3533 else if ((type->is_unsafe_pointer_type()
3534 && (expr_type->points_to() != NULL
3535 || expr_type->integer_type()))
3536 || (expr_type->is_unsafe_pointer_type()
3537 && type->points_to() != NULL)
3538 || (this->may_convert_function_types_
3539 && type->function_type() != NULL
3540 && expr_type->function_type() != NULL))
3542 Bexpression* bexpr = this->expr_->get_backend(context);
3543 return gogo->backend()->convert_expression(btype, bexpr, loc);
3545 else
3547 Expression* conversion =
3548 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3549 return conversion->get_backend(context);
3553 // Output a type conversion in a constant expression.
3555 void
3556 Type_conversion_expression::do_export(Export* exp) const
3558 exp->write_c_string("convert(");
3559 exp->write_type(this->type_);
3560 exp->write_c_string(", ");
3561 this->expr_->export_expression(exp);
3562 exp->write_c_string(")");
3565 // Import a type conversion or a struct construction.
3567 Expression*
3568 Type_conversion_expression::do_import(Import* imp)
3570 imp->require_c_string("convert(");
3571 Type* type = imp->read_type();
3572 imp->require_c_string(", ");
3573 Expression* val = Expression::import_expression(imp);
3574 imp->require_c_string(")");
3575 return Expression::make_cast(type, val, imp->location());
3578 // Dump ast representation for a type conversion expression.
3580 void
3581 Type_conversion_expression::do_dump_expression(
3582 Ast_dump_context* ast_dump_context) const
3584 ast_dump_context->dump_type(this->type_);
3585 ast_dump_context->ostream() << "(";
3586 ast_dump_context->dump_expression(this->expr_);
3587 ast_dump_context->ostream() << ") ";
3590 // Make a type cast expression.
3592 Expression*
3593 Expression::make_cast(Type* type, Expression* val, Location location)
3595 if (type->is_error_type() || val->is_error_expression())
3596 return Expression::make_error(location);
3597 return new Type_conversion_expression(type, val, location);
3600 // Class Unsafe_type_conversion_expression.
3602 // Traversal.
3605 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3607 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3608 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3609 return TRAVERSE_EXIT;
3610 return TRAVERSE_CONTINUE;
3613 // Return whether an unsafe type conversion can be used as a constant
3614 // initializer.
3616 bool
3617 Unsafe_type_conversion_expression::do_is_static_initializer() const
3619 Type* type = this->type_;
3620 Type* expr_type = this->expr_->type();
3622 if (type->interface_type() != NULL
3623 || expr_type->interface_type() != NULL)
3624 return false;
3626 if (!this->expr_->is_static_initializer())
3627 return false;
3629 if (Type::are_convertible(type, expr_type, NULL))
3630 return true;
3632 if (type->is_string_type() && expr_type->is_string_type())
3633 return true;
3635 if ((type->is_numeric_type()
3636 || type->is_boolean_type()
3637 || type->points_to() != NULL)
3638 && (expr_type->is_numeric_type()
3639 || expr_type->is_boolean_type()
3640 || expr_type->points_to() != NULL))
3641 return true;
3643 return false;
3646 // Copy.
3648 Expression*
3649 Unsafe_type_conversion_expression::do_copy()
3651 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
3652 this->expr_->copy(),
3653 this->location());
3656 // Convert to backend representation.
3658 Bexpression*
3659 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3661 // We are only called for a limited number of cases.
3663 Type* t = this->type_;
3664 Type* et = this->expr_->type();
3666 if (t->is_error_type()
3667 || this->expr_->is_error_expression()
3668 || et->is_error_type())
3670 go_assert(saw_errors());
3671 return context->backend()->error_expression();
3674 if (t->array_type() != NULL)
3675 go_assert(et->array_type() != NULL
3676 && t->is_slice_type() == et->is_slice_type());
3677 else if (t->struct_type() != NULL)
3679 if (t->named_type() != NULL
3680 && et->named_type() != NULL
3681 && !Type::are_convertible(t, et, NULL))
3683 go_assert(saw_errors());
3684 return context->backend()->error_expression();
3687 go_assert(et->struct_type() != NULL
3688 && Type::are_convertible(t, et, NULL));
3690 else if (t->map_type() != NULL)
3691 go_assert(et->map_type() != NULL);
3692 else if (t->channel_type() != NULL)
3693 go_assert(et->channel_type() != NULL);
3694 else if (t->points_to() != NULL)
3695 go_assert(et->points_to() != NULL
3696 || et->channel_type() != NULL
3697 || et->map_type() != NULL
3698 || et->function_type() != NULL
3699 || et->integer_type() != NULL
3700 || et->is_nil_type());
3701 else if (et->is_unsafe_pointer_type())
3702 go_assert(t->points_to() != NULL);
3703 else if (t->interface_type() != NULL)
3705 bool empty_iface = t->interface_type()->is_empty();
3706 go_assert(et->interface_type() != NULL
3707 && et->interface_type()->is_empty() == empty_iface);
3709 else if (t->integer_type() != NULL)
3710 go_assert(et->is_boolean_type()
3711 || et->integer_type() != NULL
3712 || et->function_type() != NULL
3713 || et->points_to() != NULL
3714 || et->map_type() != NULL
3715 || et->channel_type() != NULL
3716 || et->is_nil_type());
3717 else if (t->function_type() != NULL)
3718 go_assert(et->points_to() != NULL);
3719 else
3720 go_unreachable();
3722 Gogo* gogo = context->gogo();
3723 Btype* btype = t->get_backend(gogo);
3724 Bexpression* bexpr = this->expr_->get_backend(context);
3725 Location loc = this->location();
3726 return gogo->backend()->convert_expression(btype, bexpr, loc);
3729 // Dump ast representation for an unsafe type conversion expression.
3731 void
3732 Unsafe_type_conversion_expression::do_dump_expression(
3733 Ast_dump_context* ast_dump_context) const
3735 ast_dump_context->dump_type(this->type_);
3736 ast_dump_context->ostream() << "(";
3737 ast_dump_context->dump_expression(this->expr_);
3738 ast_dump_context->ostream() << ") ";
3741 // Make an unsafe type conversion expression.
3743 Expression*
3744 Expression::make_unsafe_cast(Type* type, Expression* expr,
3745 Location location)
3747 return new Unsafe_type_conversion_expression(type, expr, location);
3750 // Class Unary_expression.
3752 // Call the address_taken method of the operand if needed. This is
3753 // called after escape analysis but before inserting write barriers.
3755 void
3756 Unary_expression::check_operand_address_taken(Gogo*)
3758 if (this->op_ != OPERATOR_AND)
3759 return;
3761 // If this->escapes_ is false at this point, then it was set to
3762 // false by an explicit call to set_does_not_escape, and the value
3763 // does not escape. If this->escapes_ is true, we may be able to
3764 // set it to false if taking the address of a variable that does not
3765 // escape.
3766 Node* n = Node::make_node(this);
3767 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3768 this->escapes_ = false;
3770 Named_object* var = NULL;
3771 if (this->expr_->var_expression() != NULL)
3772 var = this->expr_->var_expression()->named_object();
3773 else if (this->expr_->enclosed_var_expression() != NULL)
3774 var = this->expr_->enclosed_var_expression()->variable();
3776 if (this->escapes_ && var != NULL)
3778 if (var->is_variable())
3779 this->escapes_ = var->var_value()->escapes();
3780 if (var->is_result_variable())
3781 this->escapes_ = var->result_var_value()->escapes();
3784 this->expr_->address_taken(this->escapes_);
3787 // If we are taking the address of a composite literal, and the
3788 // contents are not constant, then we want to make a heap expression
3789 // instead.
3791 Expression*
3792 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3794 Location loc = this->location();
3795 Operator op = this->op_;
3796 Expression* expr = this->expr_;
3798 if (op == OPERATOR_MULT && expr->is_type_expression())
3799 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3801 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3802 // moving x to the heap. FIXME: Is it worth doing a real escape
3803 // analysis here? This case is found in math/unsafe.go and is
3804 // therefore worth special casing.
3805 if (op == OPERATOR_MULT)
3807 Expression* e = expr;
3808 while (e->classification() == EXPRESSION_CONVERSION)
3810 Type_conversion_expression* te
3811 = static_cast<Type_conversion_expression*>(e);
3812 e = te->expr();
3815 if (e->classification() == EXPRESSION_UNARY)
3817 Unary_expression* ue = static_cast<Unary_expression*>(e);
3818 if (ue->op_ == OPERATOR_AND)
3820 if (e == expr)
3822 // *&x == x.
3823 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3825 go_error_at(ue->location(),
3826 "invalid operand for unary %<&%>");
3827 this->set_is_error();
3829 return ue->expr_;
3831 ue->set_does_not_escape();
3836 // Catching an invalid indirection of unsafe.Pointer here avoid
3837 // having to deal with TYPE_VOID in other places.
3838 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3840 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3841 return Expression::make_error(this->location());
3844 // Check for an invalid pointer dereference. We need to do this
3845 // here because Unary_expression::do_type will return an error type
3846 // in this case. That can cause code to appear erroneous, and
3847 // therefore disappear at lowering time, without any error message.
3848 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3850 this->report_error(_("expected pointer"));
3851 return Expression::make_error(this->location());
3854 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3856 Numeric_constant nc;
3857 if (expr->numeric_constant_value(&nc))
3859 Numeric_constant result;
3860 bool issued_error;
3861 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3862 &issued_error))
3863 return result.expression(loc);
3864 else if (issued_error)
3865 return Expression::make_error(this->location());
3869 return this;
3872 // Flatten expression if a nil check must be performed and create temporary
3873 // variables if necessary.
3875 Expression*
3876 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3877 Statement_inserter* inserter)
3879 if (this->is_error_expression()
3880 || this->expr_->is_error_expression()
3881 || this->expr_->type()->is_error_type())
3883 go_assert(saw_errors());
3884 return Expression::make_error(this->location());
3887 Location location = this->location();
3888 if (this->op_ == OPERATOR_MULT
3889 && !this->expr_->is_variable())
3891 go_assert(this->expr_->type()->points_to() != NULL);
3892 switch (this->requires_nil_check(gogo))
3894 case NIL_CHECK_ERROR_ENCOUNTERED:
3896 go_assert(saw_errors());
3897 return Expression::make_error(this->location());
3899 case NIL_CHECK_NOT_NEEDED:
3900 break;
3901 case NIL_CHECK_NEEDED:
3902 this->create_temp_ = true;
3903 break;
3904 case NIL_CHECK_DEFAULT:
3905 go_unreachable();
3909 if (this->create_temp_ && !this->expr_->is_variable())
3911 Temporary_statement* temp =
3912 Statement::make_temporary(NULL, this->expr_, location);
3913 inserter->insert(temp);
3914 this->expr_ = Expression::make_temporary_reference(temp, location);
3917 return this;
3920 // Return whether a unary expression is a constant.
3922 bool
3923 Unary_expression::do_is_constant() const
3925 if (this->op_ == OPERATOR_MULT)
3927 // Indirecting through a pointer is only constant if the object
3928 // to which the expression points is constant, but we currently
3929 // have no way to determine that.
3930 return false;
3932 else if (this->op_ == OPERATOR_AND)
3934 // Taking the address of a variable is constant if it is a
3935 // global variable, not constant otherwise. In other cases taking the
3936 // address is probably not a constant.
3937 Var_expression* ve = this->expr_->var_expression();
3938 if (ve != NULL)
3940 Named_object* no = ve->named_object();
3941 return no->is_variable() && no->var_value()->is_global();
3943 return false;
3945 else
3946 return this->expr_->is_constant();
3949 // Return whether a unary expression can be used as a constant
3950 // initializer.
3952 bool
3953 Unary_expression::do_is_static_initializer() const
3955 if (this->op_ == OPERATOR_MULT)
3956 return false;
3957 else if (this->op_ == OPERATOR_AND)
3958 return Unary_expression::base_is_static_initializer(this->expr_);
3959 else
3960 return this->expr_->is_static_initializer();
3963 // Return whether the address of EXPR can be used as a static
3964 // initializer.
3966 bool
3967 Unary_expression::base_is_static_initializer(Expression* expr)
3969 // The address of a field reference can be a static initializer if
3970 // the base can be a static initializer.
3971 Field_reference_expression* fre = expr->field_reference_expression();
3972 if (fre != NULL)
3973 return Unary_expression::base_is_static_initializer(fre->expr());
3975 // The address of an index expression can be a static initializer if
3976 // the base can be a static initializer and the index is constant.
3977 Array_index_expression* aind = expr->array_index_expression();
3978 if (aind != NULL)
3979 return (aind->end() == NULL
3980 && aind->start()->is_constant()
3981 && Unary_expression::base_is_static_initializer(aind->array()));
3983 // The address of a global variable can be a static initializer.
3984 Var_expression* ve = expr->var_expression();
3985 if (ve != NULL)
3987 Named_object* no = ve->named_object();
3988 return no->is_variable() && no->var_value()->is_global();
3991 // The address of a composite literal can be used as a static
3992 // initializer if the composite literal is itself usable as a
3993 // static initializer.
3994 if (expr->is_composite_literal() && expr->is_static_initializer())
3995 return true;
3997 // The address of a string constant can be used as a static
3998 // initializer. This can not be written in Go itself but this is
3999 // used when building a type descriptor.
4000 if (expr->string_expression() != NULL)
4001 return true;
4003 return false;
4006 // Return whether this dereference expression requires an explicit nil
4007 // check. If we are dereferencing the pointer to a large struct
4008 // (greater than the specified size threshold), we need to check for
4009 // nil. We don't bother to check for small structs because we expect
4010 // the system to crash on a nil pointer dereference. However, if we
4011 // know the address of this expression is being taken, we must always
4012 // check for nil.
4013 Unary_expression::Nil_check_classification
4014 Unary_expression::requires_nil_check(Gogo* gogo)
4016 go_assert(this->op_ == OPERATOR_MULT);
4017 go_assert(this->expr_->type()->points_to() != NULL);
4019 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4020 return NIL_CHECK_NEEDED;
4021 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4022 return NIL_CHECK_NOT_NEEDED;
4024 Type* ptype = this->expr_->type()->points_to();
4025 int64_t type_size = -1;
4026 if (!ptype->is_void_type())
4028 bool ok = ptype->backend_type_size(gogo, &type_size);
4029 if (!ok)
4030 return NIL_CHECK_ERROR_ENCOUNTERED;
4033 int64_t size_cutoff = gogo->nil_check_size_threshold();
4034 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4035 this->issue_nil_check_ = NIL_CHECK_NEEDED;
4036 else
4037 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4038 return this->issue_nil_check_;
4041 // Apply unary opcode OP to UNC, setting NC. Return true if this
4042 // could be done, false if not. On overflow, issues an error and sets
4043 // *ISSUED_ERROR.
4045 bool
4046 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4047 Location location, Numeric_constant* nc,
4048 bool* issued_error)
4050 *issued_error = false;
4051 switch (op)
4053 case OPERATOR_PLUS:
4054 *nc = *unc;
4055 return true;
4057 case OPERATOR_MINUS:
4058 if (unc->is_int() || unc->is_rune())
4059 break;
4060 else if (unc->is_float())
4062 mpfr_t uval;
4063 unc->get_float(&uval);
4064 mpfr_t val;
4065 mpfr_init(val);
4066 mpfr_neg(val, uval, GMP_RNDN);
4067 nc->set_float(unc->type(), val);
4068 mpfr_clear(uval);
4069 mpfr_clear(val);
4070 return true;
4072 else if (unc->is_complex())
4074 mpc_t uval;
4075 unc->get_complex(&uval);
4076 mpc_t val;
4077 mpc_init2(val, mpc_precision);
4078 mpc_neg(val, uval, MPC_RNDNN);
4079 nc->set_complex(unc->type(), val);
4080 mpc_clear(uval);
4081 mpc_clear(val);
4082 return true;
4084 else
4085 go_unreachable();
4087 case OPERATOR_XOR:
4088 break;
4090 case OPERATOR_NOT:
4091 case OPERATOR_AND:
4092 case OPERATOR_MULT:
4093 return false;
4095 default:
4096 go_unreachable();
4099 if (!unc->is_int() && !unc->is_rune())
4100 return false;
4102 mpz_t uval;
4103 if (unc->is_rune())
4104 unc->get_rune(&uval);
4105 else
4106 unc->get_int(&uval);
4107 mpz_t val;
4108 mpz_init(val);
4110 switch (op)
4112 case OPERATOR_MINUS:
4113 mpz_neg(val, uval);
4114 break;
4116 case OPERATOR_NOT:
4117 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4118 break;
4120 case OPERATOR_XOR:
4122 Type* utype = unc->type();
4123 if (utype->integer_type() == NULL
4124 || utype->integer_type()->is_abstract())
4125 mpz_com(val, uval);
4126 else
4128 // The number of HOST_WIDE_INTs that it takes to represent
4129 // UVAL.
4130 size_t count = ((mpz_sizeinbase(uval, 2)
4131 + HOST_BITS_PER_WIDE_INT
4132 - 1)
4133 / HOST_BITS_PER_WIDE_INT);
4135 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4136 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4138 size_t obits = utype->integer_type()->bits();
4140 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4142 mpz_t adj;
4143 mpz_init_set_ui(adj, 1);
4144 mpz_mul_2exp(adj, adj, obits);
4145 mpz_add(uval, uval, adj);
4146 mpz_clear(adj);
4149 size_t ecount;
4150 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4151 go_assert(ecount <= count);
4153 // Trim down to the number of words required by the type.
4154 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4155 / HOST_BITS_PER_WIDE_INT);
4156 go_assert(ocount <= count);
4158 for (size_t i = 0; i < ocount; ++i)
4159 phwi[i] = ~phwi[i];
4161 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4162 if (clearbits != 0)
4163 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4164 >> clearbits);
4166 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4168 if (!utype->integer_type()->is_unsigned()
4169 && mpz_tstbit(val, obits - 1))
4171 mpz_t adj;
4172 mpz_init_set_ui(adj, 1);
4173 mpz_mul_2exp(adj, adj, obits);
4174 mpz_sub(val, val, adj);
4175 mpz_clear(adj);
4178 delete[] phwi;
4181 break;
4183 default:
4184 go_unreachable();
4187 if (unc->is_rune())
4188 nc->set_rune(NULL, val);
4189 else
4190 nc->set_int(NULL, val);
4192 mpz_clear(uval);
4193 mpz_clear(val);
4195 if (!nc->set_type(unc->type(), true, location))
4197 *issued_error = true;
4198 return false;
4200 return true;
4203 // Return the integral constant value of a unary expression, if it has one.
4205 bool
4206 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4208 Numeric_constant unc;
4209 if (!this->expr_->numeric_constant_value(&unc))
4210 return false;
4211 bool issued_error;
4212 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4213 nc, &issued_error);
4216 // Return the type of a unary expression.
4218 Type*
4219 Unary_expression::do_type()
4221 switch (this->op_)
4223 case OPERATOR_PLUS:
4224 case OPERATOR_MINUS:
4225 case OPERATOR_NOT:
4226 case OPERATOR_XOR:
4227 return this->expr_->type();
4229 case OPERATOR_AND:
4230 return Type::make_pointer_type(this->expr_->type());
4232 case OPERATOR_MULT:
4234 Type* subtype = this->expr_->type();
4235 Type* points_to = subtype->points_to();
4236 if (points_to == NULL)
4237 return Type::make_error_type();
4238 return points_to;
4241 default:
4242 go_unreachable();
4246 // Determine abstract types for a unary expression.
4248 void
4249 Unary_expression::do_determine_type(const Type_context* context)
4251 switch (this->op_)
4253 case OPERATOR_PLUS:
4254 case OPERATOR_MINUS:
4255 case OPERATOR_NOT:
4256 case OPERATOR_XOR:
4257 this->expr_->determine_type(context);
4258 break;
4260 case OPERATOR_AND:
4261 // Taking the address of something.
4263 Type* subtype = (context->type == NULL
4264 ? NULL
4265 : context->type->points_to());
4266 Type_context subcontext(subtype, false);
4267 this->expr_->determine_type(&subcontext);
4269 break;
4271 case OPERATOR_MULT:
4272 // Indirecting through a pointer.
4274 Type* subtype = (context->type == NULL
4275 ? NULL
4276 : Type::make_pointer_type(context->type));
4277 Type_context subcontext(subtype, false);
4278 this->expr_->determine_type(&subcontext);
4280 break;
4282 default:
4283 go_unreachable();
4287 // Check types for a unary expression.
4289 void
4290 Unary_expression::do_check_types(Gogo*)
4292 Type* type = this->expr_->type();
4293 if (type->is_error())
4295 this->set_is_error();
4296 return;
4299 switch (this->op_)
4301 case OPERATOR_PLUS:
4302 case OPERATOR_MINUS:
4303 if (type->integer_type() == NULL
4304 && type->float_type() == NULL
4305 && type->complex_type() == NULL)
4306 this->report_error(_("expected numeric type"));
4307 break;
4309 case OPERATOR_NOT:
4310 if (!type->is_boolean_type())
4311 this->report_error(_("expected boolean type"));
4312 break;
4314 case OPERATOR_XOR:
4315 if (type->integer_type() == NULL)
4316 this->report_error(_("expected integer"));
4317 break;
4319 case OPERATOR_AND:
4320 if (!this->expr_->is_addressable())
4322 if (!this->create_temp_)
4324 go_error_at(this->location(), "invalid operand for unary %<&%>");
4325 this->set_is_error();
4328 else
4329 this->expr_->issue_nil_check();
4330 break;
4332 case OPERATOR_MULT:
4333 // Indirecting through a pointer.
4334 if (type->points_to() == NULL)
4335 this->report_error(_("expected pointer"));
4336 if (type->points_to()->is_error())
4337 this->set_is_error();
4338 break;
4340 default:
4341 go_unreachable();
4345 // Get the backend representation for a unary expression.
4347 Bexpression*
4348 Unary_expression::do_get_backend(Translate_context* context)
4350 Gogo* gogo = context->gogo();
4351 Location loc = this->location();
4353 // Taking the address of a set-and-use-temporary expression requires
4354 // setting the temporary and then taking the address.
4355 if (this->op_ == OPERATOR_AND)
4357 Set_and_use_temporary_expression* sut =
4358 this->expr_->set_and_use_temporary_expression();
4359 if (sut != NULL)
4361 Temporary_statement* temp = sut->temporary();
4362 Bvariable* bvar = temp->get_backend_variable(context);
4363 Bexpression* bvar_expr =
4364 gogo->backend()->var_expression(bvar, loc);
4365 Bexpression* bval = sut->expression()->get_backend(context);
4367 Named_object* fn = context->function();
4368 go_assert(fn != NULL);
4369 Bfunction* bfn =
4370 fn->func_value()->get_or_make_decl(gogo, fn);
4371 Bstatement* bassign =
4372 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4373 Bexpression* bvar_addr =
4374 gogo->backend()->address_expression(bvar_expr, loc);
4375 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4379 Bexpression* ret;
4380 Bexpression* bexpr = this->expr_->get_backend(context);
4381 Btype* btype = this->expr_->type()->get_backend(gogo);
4382 switch (this->op_)
4384 case OPERATOR_PLUS:
4385 ret = bexpr;
4386 break;
4388 case OPERATOR_MINUS:
4389 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4390 ret = gogo->backend()->convert_expression(btype, ret, loc);
4391 break;
4393 case OPERATOR_NOT:
4394 case OPERATOR_XOR:
4395 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4396 break;
4398 case OPERATOR_AND:
4399 if (!this->create_temp_)
4401 // We should not see a non-constant constructor here; cases
4402 // where we would see one should have been moved onto the
4403 // heap at parse time. Taking the address of a nonconstant
4404 // constructor will not do what the programmer expects.
4406 go_assert(!this->expr_->is_composite_literal()
4407 || this->expr_->is_static_initializer());
4408 if (this->expr_->classification() == EXPRESSION_UNARY)
4410 Unary_expression* ue =
4411 static_cast<Unary_expression*>(this->expr_);
4412 go_assert(ue->op() != OPERATOR_AND);
4416 if (this->is_gc_root_ || this->is_slice_init_)
4418 std::string var_name;
4419 bool copy_to_heap = false;
4420 if (this->is_gc_root_)
4422 // Build a decl for a GC root variable. GC roots are mutable, so
4423 // they cannot be represented as an immutable_struct in the
4424 // backend.
4425 var_name = gogo->gc_root_name();
4427 else
4429 // Build a decl for a slice value initializer. An immutable slice
4430 // value initializer may have to be copied to the heap if it
4431 // contains pointers in a non-constant context.
4432 var_name = gogo->initializer_name();
4434 Array_type* at = this->expr_->type()->array_type();
4435 go_assert(at != NULL);
4437 // If we are not copying the value to the heap, we will only
4438 // initialize the value once, so we can use this directly
4439 // rather than copying it. In that case we can't make it
4440 // read-only, because the program is permitted to change it.
4441 copy_to_heap = context->function() != NULL;
4443 std::string asm_name(go_selectively_encode_id(var_name));
4444 Bvariable* implicit =
4445 gogo->backend()->implicit_variable(var_name, asm_name,
4446 btype, true, copy_to_heap,
4447 false, 0);
4448 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4449 true, copy_to_heap, false,
4450 bexpr);
4451 bexpr = gogo->backend()->var_expression(implicit, loc);
4453 // If we are not copying a slice initializer to the heap,
4454 // then it can be changed by the program, so if it can
4455 // contain pointers we must register it as a GC root.
4456 if (this->is_slice_init_
4457 && !copy_to_heap
4458 && this->expr_->type()->has_pointer())
4460 Bexpression* root =
4461 gogo->backend()->var_expression(implicit, loc);
4462 root = gogo->backend()->address_expression(root, loc);
4463 Type* type = Type::make_pointer_type(this->expr_->type());
4464 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4467 else if ((this->expr_->is_composite_literal()
4468 || this->expr_->string_expression() != NULL)
4469 && this->expr_->is_static_initializer())
4471 std::string var_name(gogo->initializer_name());
4472 std::string asm_name(go_selectively_encode_id(var_name));
4473 Bvariable* decl =
4474 gogo->backend()->immutable_struct(var_name, asm_name,
4475 true, false, btype, loc);
4476 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4477 false, btype, loc, bexpr);
4478 bexpr = gogo->backend()->var_expression(decl, loc);
4481 go_assert(!this->create_temp_ || this->expr_->is_variable());
4482 ret = gogo->backend()->address_expression(bexpr, loc);
4483 break;
4485 case OPERATOR_MULT:
4487 go_assert(this->expr_->type()->points_to() != NULL);
4489 bool known_valid = false;
4490 Type* ptype = this->expr_->type()->points_to();
4491 Btype* pbtype = ptype->get_backend(gogo);
4492 switch (this->requires_nil_check(gogo))
4494 case NIL_CHECK_NOT_NEEDED:
4495 break;
4496 case NIL_CHECK_ERROR_ENCOUNTERED:
4498 go_assert(saw_errors());
4499 return gogo->backend()->error_expression();
4501 case NIL_CHECK_NEEDED:
4503 go_assert(this->expr_->is_variable());
4505 // If we're nil-checking the result of a set-and-use-temporary
4506 // expression, then pick out the target temp and use that
4507 // for the final result of the conditional.
4508 Bexpression* tbexpr = bexpr;
4509 Bexpression* ubexpr = bexpr;
4510 Set_and_use_temporary_expression* sut =
4511 this->expr_->set_and_use_temporary_expression();
4512 if (sut != NULL) {
4513 Temporary_statement* temp = sut->temporary();
4514 Bvariable* bvar = temp->get_backend_variable(context);
4515 ubexpr = gogo->backend()->var_expression(bvar, loc);
4517 Bexpression* nil =
4518 Expression::make_nil(loc)->get_backend(context);
4519 Bexpression* compare =
4520 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4521 nil, loc);
4522 Bexpression* crash =
4523 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4524 loc)->get_backend(context);
4525 Bfunction* bfn = context->function()->func_value()->get_decl();
4526 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4527 compare,
4528 crash, ubexpr,
4529 loc);
4530 known_valid = true;
4531 break;
4533 case NIL_CHECK_DEFAULT:
4534 go_unreachable();
4536 ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4537 known_valid, loc);
4539 break;
4541 default:
4542 go_unreachable();
4545 return ret;
4548 // Export a unary expression.
4550 void
4551 Unary_expression::do_export(Export* exp) const
4553 switch (this->op_)
4555 case OPERATOR_PLUS:
4556 exp->write_c_string("+ ");
4557 break;
4558 case OPERATOR_MINUS:
4559 exp->write_c_string("- ");
4560 break;
4561 case OPERATOR_NOT:
4562 exp->write_c_string("! ");
4563 break;
4564 case OPERATOR_XOR:
4565 exp->write_c_string("^ ");
4566 break;
4567 case OPERATOR_AND:
4568 case OPERATOR_MULT:
4569 default:
4570 go_unreachable();
4572 this->expr_->export_expression(exp);
4575 // Import a unary expression.
4577 Expression*
4578 Unary_expression::do_import(Import* imp)
4580 Operator op;
4581 switch (imp->get_char())
4583 case '+':
4584 op = OPERATOR_PLUS;
4585 break;
4586 case '-':
4587 op = OPERATOR_MINUS;
4588 break;
4589 case '!':
4590 op = OPERATOR_NOT;
4591 break;
4592 case '^':
4593 op = OPERATOR_XOR;
4594 break;
4595 default:
4596 go_unreachable();
4598 imp->require_c_string(" ");
4599 Expression* expr = Expression::import_expression(imp);
4600 return Expression::make_unary(op, expr, imp->location());
4603 // Dump ast representation of an unary expression.
4605 void
4606 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4608 ast_dump_context->dump_operator(this->op_);
4609 ast_dump_context->ostream() << "(";
4610 ast_dump_context->dump_expression(this->expr_);
4611 ast_dump_context->ostream() << ") ";
4614 // Make a unary expression.
4616 Expression*
4617 Expression::make_unary(Operator op, Expression* expr, Location location)
4619 return new Unary_expression(op, expr, location);
4622 Expression*
4623 Expression::make_dereference(Expression* ptr,
4624 Nil_check_classification docheck,
4625 Location location)
4627 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4628 if (docheck == NIL_CHECK_NEEDED)
4629 deref->unary_expression()->set_requires_nil_check(true);
4630 else if (docheck == NIL_CHECK_NOT_NEEDED)
4631 deref->unary_expression()->set_requires_nil_check(false);
4632 return deref;
4635 // If this is an indirection through a pointer, return the expression
4636 // being pointed through. Otherwise return this.
4638 Expression*
4639 Expression::deref()
4641 if (this->classification_ == EXPRESSION_UNARY)
4643 Unary_expression* ue = static_cast<Unary_expression*>(this);
4644 if (ue->op() == OPERATOR_MULT)
4645 return ue->operand();
4647 return this;
4650 // Class Binary_expression.
4652 // Traversal.
4655 Binary_expression::do_traverse(Traverse* traverse)
4657 int t = Expression::traverse(&this->left_, traverse);
4658 if (t == TRAVERSE_EXIT)
4659 return TRAVERSE_EXIT;
4660 return Expression::traverse(&this->right_, traverse);
4663 // Return whether this expression may be used as a static initializer.
4665 bool
4666 Binary_expression::do_is_static_initializer() const
4668 if (!this->left_->is_static_initializer()
4669 || !this->right_->is_static_initializer())
4670 return false;
4672 // Addresses can be static initializers, but we can't implement
4673 // arbitray binary expressions of them.
4674 Unary_expression* lu = this->left_->unary_expression();
4675 Unary_expression* ru = this->right_->unary_expression();
4676 if (lu != NULL && lu->op() == OPERATOR_AND)
4678 if (ru != NULL && ru->op() == OPERATOR_AND)
4679 return this->op_ == OPERATOR_MINUS;
4680 else
4681 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4683 else if (ru != NULL && ru->op() == OPERATOR_AND)
4684 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4686 // Other cases should resolve in the backend.
4687 return true;
4690 // Return the type to use for a binary operation on operands of
4691 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4692 // such may be NULL or abstract.
4694 bool
4695 Binary_expression::operation_type(Operator op, Type* left_type,
4696 Type* right_type, Type** result_type)
4698 if (left_type != right_type
4699 && !left_type->is_abstract()
4700 && !right_type->is_abstract()
4701 && left_type->base() != right_type->base()
4702 && op != OPERATOR_LSHIFT
4703 && op != OPERATOR_RSHIFT)
4705 // May be a type error--let it be diagnosed elsewhere.
4706 return false;
4709 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4711 if (left_type->integer_type() != NULL)
4712 *result_type = left_type;
4713 else
4714 *result_type = Type::make_abstract_integer_type();
4716 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4717 *result_type = left_type;
4718 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4719 *result_type = right_type;
4720 else if (!left_type->is_abstract())
4721 *result_type = left_type;
4722 else if (!right_type->is_abstract())
4723 *result_type = right_type;
4724 else if (left_type->complex_type() != NULL)
4725 *result_type = left_type;
4726 else if (right_type->complex_type() != NULL)
4727 *result_type = right_type;
4728 else if (left_type->float_type() != NULL)
4729 *result_type = left_type;
4730 else if (right_type->float_type() != NULL)
4731 *result_type = right_type;
4732 else if (left_type->integer_type() != NULL
4733 && left_type->integer_type()->is_rune())
4734 *result_type = left_type;
4735 else if (right_type->integer_type() != NULL
4736 && right_type->integer_type()->is_rune())
4737 *result_type = right_type;
4738 else
4739 *result_type = left_type;
4741 return true;
4744 // Convert an integer comparison code and an operator to a boolean
4745 // value.
4747 bool
4748 Binary_expression::cmp_to_bool(Operator op, int cmp)
4750 switch (op)
4752 case OPERATOR_EQEQ:
4753 return cmp == 0;
4754 break;
4755 case OPERATOR_NOTEQ:
4756 return cmp != 0;
4757 break;
4758 case OPERATOR_LT:
4759 return cmp < 0;
4760 break;
4761 case OPERATOR_LE:
4762 return cmp <= 0;
4763 case OPERATOR_GT:
4764 return cmp > 0;
4765 case OPERATOR_GE:
4766 return cmp >= 0;
4767 default:
4768 go_unreachable();
4772 // Compare constants according to OP.
4774 bool
4775 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4776 Numeric_constant* right_nc,
4777 Location location, bool* result)
4779 Type* left_type = left_nc->type();
4780 Type* right_type = right_nc->type();
4782 Type* type;
4783 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4784 return false;
4786 // When comparing an untyped operand to a typed operand, we are
4787 // effectively coercing the untyped operand to the other operand's
4788 // type, so make sure that is valid.
4789 if (!left_nc->set_type(type, true, location)
4790 || !right_nc->set_type(type, true, location))
4791 return false;
4793 bool ret;
4794 int cmp;
4795 if (type->complex_type() != NULL)
4797 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4798 return false;
4799 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4801 else if (type->float_type() != NULL)
4802 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4803 else
4804 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4806 if (ret)
4807 *result = Binary_expression::cmp_to_bool(op, cmp);
4809 return ret;
4812 // Compare integer constants.
4814 bool
4815 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4816 const Numeric_constant* right_nc,
4817 int* cmp)
4819 mpz_t left_val;
4820 if (!left_nc->to_int(&left_val))
4821 return false;
4822 mpz_t right_val;
4823 if (!right_nc->to_int(&right_val))
4825 mpz_clear(left_val);
4826 return false;
4829 *cmp = mpz_cmp(left_val, right_val);
4831 mpz_clear(left_val);
4832 mpz_clear(right_val);
4834 return true;
4837 // Compare floating point constants.
4839 bool
4840 Binary_expression::compare_float(const Numeric_constant* left_nc,
4841 const Numeric_constant* right_nc,
4842 int* cmp)
4844 mpfr_t left_val;
4845 if (!left_nc->to_float(&left_val))
4846 return false;
4847 mpfr_t right_val;
4848 if (!right_nc->to_float(&right_val))
4850 mpfr_clear(left_val);
4851 return false;
4854 // We already coerced both operands to the same type. If that type
4855 // is not an abstract type, we need to round the values accordingly.
4856 Type* type = left_nc->type();
4857 if (!type->is_abstract() && type->float_type() != NULL)
4859 int bits = type->float_type()->bits();
4860 mpfr_prec_round(left_val, bits, GMP_RNDN);
4861 mpfr_prec_round(right_val, bits, GMP_RNDN);
4864 *cmp = mpfr_cmp(left_val, right_val);
4866 mpfr_clear(left_val);
4867 mpfr_clear(right_val);
4869 return true;
4872 // Compare complex constants. Complex numbers may only be compared
4873 // for equality.
4875 bool
4876 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4877 const Numeric_constant* right_nc,
4878 int* cmp)
4880 mpc_t left_val;
4881 if (!left_nc->to_complex(&left_val))
4882 return false;
4883 mpc_t right_val;
4884 if (!right_nc->to_complex(&right_val))
4886 mpc_clear(left_val);
4887 return false;
4890 // We already coerced both operands to the same type. If that type
4891 // is not an abstract type, we need to round the values accordingly.
4892 Type* type = left_nc->type();
4893 if (!type->is_abstract() && type->complex_type() != NULL)
4895 int bits = type->complex_type()->bits();
4896 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4897 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4898 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4899 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4902 *cmp = mpc_cmp(left_val, right_val) != 0;
4904 mpc_clear(left_val);
4905 mpc_clear(right_val);
4907 return true;
4910 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4911 // true if this could be done, false if not. Issue errors at LOCATION
4912 // as appropriate, and sets *ISSUED_ERROR if it did.
4914 bool
4915 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4916 Numeric_constant* right_nc,
4917 Location location, Numeric_constant* nc,
4918 bool* issued_error)
4920 *issued_error = false;
4921 switch (op)
4923 case OPERATOR_OROR:
4924 case OPERATOR_ANDAND:
4925 case OPERATOR_EQEQ:
4926 case OPERATOR_NOTEQ:
4927 case OPERATOR_LT:
4928 case OPERATOR_LE:
4929 case OPERATOR_GT:
4930 case OPERATOR_GE:
4931 // These return boolean values, not numeric.
4932 return false;
4933 default:
4934 break;
4937 Type* left_type = left_nc->type();
4938 Type* right_type = right_nc->type();
4940 Type* type;
4941 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4942 return false;
4944 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4946 // When combining an untyped operand with a typed operand, we are
4947 // effectively coercing the untyped operand to the other operand's
4948 // type, so make sure that is valid.
4949 if (!left_nc->set_type(type, true, location))
4950 return false;
4951 if (!is_shift && !right_nc->set_type(type, true, location))
4952 return false;
4953 if (is_shift
4954 && ((left_type->integer_type() == NULL
4955 && !left_type->is_abstract())
4956 || (right_type->integer_type() == NULL
4957 && !right_type->is_abstract())))
4958 return false;
4960 bool r;
4961 if (type->complex_type() != NULL)
4962 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4963 else if (type->float_type() != NULL)
4964 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4965 else
4966 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4968 if (r)
4970 r = nc->set_type(type, true, location);
4971 if (!r)
4972 *issued_error = true;
4975 return r;
4978 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4979 // integer operations. Return true if this could be done, false if
4980 // not.
4982 bool
4983 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4984 const Numeric_constant* right_nc,
4985 Location location, Numeric_constant* nc)
4987 mpz_t left_val;
4988 if (!left_nc->to_int(&left_val))
4989 return false;
4990 mpz_t right_val;
4991 if (!right_nc->to_int(&right_val))
4993 mpz_clear(left_val);
4994 return false;
4997 mpz_t val;
4998 mpz_init(val);
5000 switch (op)
5002 case OPERATOR_PLUS:
5003 mpz_add(val, left_val, right_val);
5004 if (mpz_sizeinbase(val, 2) > 0x100000)
5006 go_error_at(location, "constant addition overflow");
5007 nc->set_invalid();
5008 mpz_set_ui(val, 1);
5010 break;
5011 case OPERATOR_MINUS:
5012 mpz_sub(val, left_val, right_val);
5013 if (mpz_sizeinbase(val, 2) > 0x100000)
5015 go_error_at(location, "constant subtraction overflow");
5016 nc->set_invalid();
5017 mpz_set_ui(val, 1);
5019 break;
5020 case OPERATOR_OR:
5021 mpz_ior(val, left_val, right_val);
5022 break;
5023 case OPERATOR_XOR:
5024 mpz_xor(val, left_val, right_val);
5025 break;
5026 case OPERATOR_MULT:
5027 mpz_mul(val, left_val, right_val);
5028 if (mpz_sizeinbase(val, 2) > 0x100000)
5030 go_error_at(location, "constant multiplication overflow");
5031 nc->set_invalid();
5032 mpz_set_ui(val, 1);
5034 break;
5035 case OPERATOR_DIV:
5036 if (mpz_sgn(right_val) != 0)
5037 mpz_tdiv_q(val, left_val, right_val);
5038 else
5040 go_error_at(location, "division by zero");
5041 nc->set_invalid();
5042 mpz_set_ui(val, 0);
5044 break;
5045 case OPERATOR_MOD:
5046 if (mpz_sgn(right_val) != 0)
5047 mpz_tdiv_r(val, left_val, right_val);
5048 else
5050 go_error_at(location, "division by zero");
5051 nc->set_invalid();
5052 mpz_set_ui(val, 0);
5054 break;
5055 case OPERATOR_LSHIFT:
5057 unsigned long shift = mpz_get_ui(right_val);
5058 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5059 mpz_mul_2exp(val, left_val, shift);
5060 else
5062 go_error_at(location, "shift count overflow");
5063 nc->set_invalid();
5064 mpz_set_ui(val, 1);
5066 break;
5068 break;
5069 case OPERATOR_RSHIFT:
5071 unsigned long shift = mpz_get_ui(right_val);
5072 if (mpz_cmp_ui(right_val, shift) != 0)
5074 go_error_at(location, "shift count overflow");
5075 nc->set_invalid();
5076 mpz_set_ui(val, 1);
5078 else
5080 if (mpz_cmp_ui(left_val, 0) >= 0)
5081 mpz_tdiv_q_2exp(val, left_val, shift);
5082 else
5083 mpz_fdiv_q_2exp(val, left_val, shift);
5085 break;
5087 break;
5088 case OPERATOR_AND:
5089 mpz_and(val, left_val, right_val);
5090 break;
5091 case OPERATOR_BITCLEAR:
5093 mpz_t tval;
5094 mpz_init(tval);
5095 mpz_com(tval, right_val);
5096 mpz_and(val, left_val, tval);
5097 mpz_clear(tval);
5099 break;
5100 default:
5101 go_unreachable();
5104 mpz_clear(left_val);
5105 mpz_clear(right_val);
5107 if (left_nc->is_rune()
5108 || (op != OPERATOR_LSHIFT
5109 && op != OPERATOR_RSHIFT
5110 && right_nc->is_rune()))
5111 nc->set_rune(NULL, val);
5112 else
5113 nc->set_int(NULL, val);
5115 mpz_clear(val);
5117 return true;
5120 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5121 // floating point operations. Return true if this could be done,
5122 // false if not.
5124 bool
5125 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5126 const Numeric_constant* right_nc,
5127 Location location, Numeric_constant* nc)
5129 mpfr_t left_val;
5130 if (!left_nc->to_float(&left_val))
5131 return false;
5132 mpfr_t right_val;
5133 if (!right_nc->to_float(&right_val))
5135 mpfr_clear(left_val);
5136 return false;
5139 mpfr_t val;
5140 mpfr_init(val);
5142 bool ret = true;
5143 switch (op)
5145 case OPERATOR_PLUS:
5146 mpfr_add(val, left_val, right_val, GMP_RNDN);
5147 break;
5148 case OPERATOR_MINUS:
5149 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5150 break;
5151 case OPERATOR_OR:
5152 case OPERATOR_XOR:
5153 case OPERATOR_AND:
5154 case OPERATOR_BITCLEAR:
5155 case OPERATOR_MOD:
5156 case OPERATOR_LSHIFT:
5157 case OPERATOR_RSHIFT:
5158 mpfr_set_ui(val, 0, GMP_RNDN);
5159 ret = false;
5160 break;
5161 case OPERATOR_MULT:
5162 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5163 break;
5164 case OPERATOR_DIV:
5165 if (!mpfr_zero_p(right_val))
5166 mpfr_div(val, left_val, right_val, GMP_RNDN);
5167 else
5169 go_error_at(location, "division by zero");
5170 nc->set_invalid();
5171 mpfr_set_ui(val, 0, GMP_RNDN);
5173 break;
5174 default:
5175 go_unreachable();
5178 mpfr_clear(left_val);
5179 mpfr_clear(right_val);
5181 nc->set_float(NULL, val);
5182 mpfr_clear(val);
5184 return ret;
5187 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5188 // complex operations. Return true if this could be done, false if
5189 // not.
5191 bool
5192 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5193 const Numeric_constant* right_nc,
5194 Location location, Numeric_constant* nc)
5196 mpc_t left_val;
5197 if (!left_nc->to_complex(&left_val))
5198 return false;
5199 mpc_t right_val;
5200 if (!right_nc->to_complex(&right_val))
5202 mpc_clear(left_val);
5203 return false;
5206 mpc_t val;
5207 mpc_init2(val, mpc_precision);
5209 bool ret = true;
5210 switch (op)
5212 case OPERATOR_PLUS:
5213 mpc_add(val, left_val, right_val, MPC_RNDNN);
5214 break;
5215 case OPERATOR_MINUS:
5216 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5217 break;
5218 case OPERATOR_OR:
5219 case OPERATOR_XOR:
5220 case OPERATOR_AND:
5221 case OPERATOR_BITCLEAR:
5222 case OPERATOR_MOD:
5223 case OPERATOR_LSHIFT:
5224 case OPERATOR_RSHIFT:
5225 mpc_set_ui(val, 0, MPC_RNDNN);
5226 ret = false;
5227 break;
5228 case OPERATOR_MULT:
5229 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5230 break;
5231 case OPERATOR_DIV:
5232 if (mpc_cmp_si(right_val, 0) == 0)
5234 go_error_at(location, "division by zero");
5235 nc->set_invalid();
5236 mpc_set_ui(val, 0, MPC_RNDNN);
5237 break;
5239 mpc_div(val, left_val, right_val, MPC_RNDNN);
5240 break;
5241 default:
5242 go_unreachable();
5245 mpc_clear(left_val);
5246 mpc_clear(right_val);
5248 nc->set_complex(NULL, val);
5249 mpc_clear(val);
5251 return ret;
5254 // Lower a binary expression. We have to evaluate constant
5255 // expressions now, in order to implement Go's unlimited precision
5256 // constants.
5258 Expression*
5259 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5260 Statement_inserter* inserter, int)
5262 Location location = this->location();
5263 Operator op = this->op_;
5264 Expression* left = this->left_;
5265 Expression* right = this->right_;
5267 const bool is_comparison = (op == OPERATOR_EQEQ
5268 || op == OPERATOR_NOTEQ
5269 || op == OPERATOR_LT
5270 || op == OPERATOR_LE
5271 || op == OPERATOR_GT
5272 || op == OPERATOR_GE);
5274 // Numeric constant expressions.
5276 Numeric_constant left_nc;
5277 Numeric_constant right_nc;
5278 if (left->numeric_constant_value(&left_nc)
5279 && right->numeric_constant_value(&right_nc))
5281 if (is_comparison)
5283 bool result;
5284 if (!Binary_expression::compare_constant(op, &left_nc,
5285 &right_nc, location,
5286 &result))
5287 return this;
5288 return Expression::make_cast(Type::make_boolean_type(),
5289 Expression::make_boolean(result,
5290 location),
5291 location);
5293 else
5295 Numeric_constant nc;
5296 bool issued_error;
5297 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5298 location, &nc,
5299 &issued_error))
5301 if (issued_error)
5302 return Expression::make_error(location);
5303 return this;
5305 return nc.expression(location);
5310 // String constant expressions.
5311 if (left->type()->is_string_type() && right->type()->is_string_type())
5313 std::string left_string;
5314 std::string right_string;
5315 if (left->string_constant_value(&left_string)
5316 && right->string_constant_value(&right_string))
5318 if (op == OPERATOR_PLUS)
5319 return Expression::make_string(left_string + right_string,
5320 location);
5321 else if (is_comparison)
5323 int cmp = left_string.compare(right_string);
5324 bool r = Binary_expression::cmp_to_bool(op, cmp);
5325 return Expression::make_boolean(r, location);
5330 // Lower struct, array, and some interface comparisons.
5331 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5333 if (left->type()->struct_type() != NULL
5334 && right->type()->struct_type() != NULL)
5335 return this->lower_struct_comparison(gogo, inserter);
5336 else if (left->type()->array_type() != NULL
5337 && !left->type()->is_slice_type()
5338 && right->type()->array_type() != NULL
5339 && !right->type()->is_slice_type())
5340 return this->lower_array_comparison(gogo, inserter);
5341 else if ((left->type()->interface_type() != NULL
5342 && right->type()->interface_type() == NULL)
5343 || (left->type()->interface_type() == NULL
5344 && right->type()->interface_type() != NULL))
5345 return this->lower_interface_value_comparison(gogo, inserter);
5348 // Lower string concatenation to String_concat_expression, so that
5349 // we can group sequences of string additions.
5350 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5352 Expression_list* exprs;
5353 String_concat_expression* left_sce =
5354 this->left_->string_concat_expression();
5355 if (left_sce != NULL)
5356 exprs = left_sce->exprs();
5357 else
5359 exprs = new Expression_list();
5360 exprs->push_back(this->left_);
5363 String_concat_expression* right_sce =
5364 this->right_->string_concat_expression();
5365 if (right_sce != NULL)
5366 exprs->append(right_sce->exprs());
5367 else
5368 exprs->push_back(this->right_);
5370 return Expression::make_string_concat(exprs);
5373 return this;
5376 // Lower a struct comparison.
5378 Expression*
5379 Binary_expression::lower_struct_comparison(Gogo* gogo,
5380 Statement_inserter* inserter)
5382 Struct_type* st = this->left_->type()->struct_type();
5383 Struct_type* st2 = this->right_->type()->struct_type();
5384 if (st2 == NULL)
5385 return this;
5386 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5387 return this;
5388 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5389 this->right_->type(), NULL))
5390 return this;
5392 // See if we can compare using memcmp. As a heuristic, we use
5393 // memcmp rather than field references and comparisons if there are
5394 // more than two fields.
5395 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5396 return this->lower_compare_to_memcmp(gogo, inserter);
5398 Location loc = this->location();
5400 Expression* left = this->left_;
5401 Temporary_statement* left_temp = NULL;
5402 if (left->var_expression() == NULL
5403 && left->temporary_reference_expression() == NULL)
5405 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5406 inserter->insert(left_temp);
5407 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5410 Expression* right = this->right_;
5411 Temporary_statement* right_temp = NULL;
5412 if (right->var_expression() == NULL
5413 && right->temporary_reference_expression() == NULL)
5415 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5416 inserter->insert(right_temp);
5417 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5420 Expression* ret = Expression::make_boolean(true, loc);
5421 const Struct_field_list* fields = st->fields();
5422 unsigned int field_index = 0;
5423 for (Struct_field_list::const_iterator pf = fields->begin();
5424 pf != fields->end();
5425 ++pf, ++field_index)
5427 if (Gogo::is_sink_name(pf->field_name()))
5428 continue;
5430 if (field_index > 0)
5432 if (left_temp == NULL)
5433 left = left->copy();
5434 else
5435 left = Expression::make_temporary_reference(left_temp, loc);
5436 if (right_temp == NULL)
5437 right = right->copy();
5438 else
5439 right = Expression::make_temporary_reference(right_temp, loc);
5441 Expression* f1 = Expression::make_field_reference(left, field_index,
5442 loc);
5443 Expression* f2 = Expression::make_field_reference(right, field_index,
5444 loc);
5445 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5446 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5449 if (this->op_ == OPERATOR_NOTEQ)
5450 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5452 return ret;
5455 // Lower an array comparison.
5457 Expression*
5458 Binary_expression::lower_array_comparison(Gogo* gogo,
5459 Statement_inserter* inserter)
5461 Array_type* at = this->left_->type()->array_type();
5462 Array_type* at2 = this->right_->type()->array_type();
5463 if (at2 == NULL)
5464 return this;
5465 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5466 return this;
5467 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5468 this->right_->type(), NULL))
5469 return this;
5471 // Call memcmp directly if possible. This may let the middle-end
5472 // optimize the call.
5473 if (at->compare_is_identity(gogo))
5474 return this->lower_compare_to_memcmp(gogo, inserter);
5476 // Call the array comparison function.
5477 Named_object* hash_fn;
5478 Named_object* equal_fn;
5479 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5480 &hash_fn, &equal_fn);
5482 Location loc = this->location();
5484 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5486 Expression_list* args = new Expression_list();
5487 args->push_back(this->operand_address(inserter, this->left_));
5488 args->push_back(this->operand_address(inserter, this->right_));
5490 Expression* ret = Expression::make_call(func, args, false, loc);
5492 if (this->op_ == OPERATOR_NOTEQ)
5493 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5495 return ret;
5498 // Lower an interface to value comparison.
5500 Expression*
5501 Binary_expression::lower_interface_value_comparison(Gogo*,
5502 Statement_inserter* inserter)
5504 Type* left_type = this->left_->type();
5505 Type* right_type = this->right_->type();
5506 Interface_type* ift;
5507 if (left_type->interface_type() != NULL)
5509 ift = left_type->interface_type();
5510 if (!ift->implements_interface(right_type, NULL))
5511 return this;
5513 else
5515 ift = right_type->interface_type();
5516 if (!ift->implements_interface(left_type, NULL))
5517 return this;
5519 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5520 return this;
5522 Location loc = this->location();
5524 if (left_type->interface_type() == NULL
5525 && left_type->points_to() == NULL
5526 && !this->left_->is_addressable())
5528 Temporary_statement* temp =
5529 Statement::make_temporary(left_type, NULL, loc);
5530 inserter->insert(temp);
5531 this->left_ =
5532 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5535 if (right_type->interface_type() == NULL
5536 && right_type->points_to() == NULL
5537 && !this->right_->is_addressable())
5539 Temporary_statement* temp =
5540 Statement::make_temporary(right_type, NULL, loc);
5541 inserter->insert(temp);
5542 this->right_ =
5543 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5546 return this;
5549 // Lower a struct or array comparison to a call to memcmp.
5551 Expression*
5552 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5554 Location loc = this->location();
5556 Expression* a1 = this->operand_address(inserter, this->left_);
5557 Expression* a2 = this->operand_address(inserter, this->right_);
5558 Expression* len = Expression::make_type_info(this->left_->type(),
5559 TYPE_INFO_SIZE);
5561 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5562 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5563 return Expression::make_binary(this->op_, call, zero, loc);
5566 Expression*
5567 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5568 Statement_inserter* inserter)
5570 Location loc = this->location();
5571 if (this->left_->type()->is_error_type()
5572 || this->right_->type()->is_error_type()
5573 || this->left_->is_error_expression()
5574 || this->right_->is_error_expression())
5576 go_assert(saw_errors());
5577 return Expression::make_error(loc);
5580 Temporary_statement* temp;
5582 Type* left_type = this->left_->type();
5583 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5584 || this->op_ == OPERATOR_RSHIFT);
5585 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5586 left_type->integer_type() != NULL)
5587 || this->op_ == OPERATOR_MOD);
5589 if (is_shift_op
5590 || (is_idiv_op
5591 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5593 if (!this->left_->is_variable() && !this->left_->is_constant())
5595 temp = Statement::make_temporary(NULL, this->left_, loc);
5596 inserter->insert(temp);
5597 this->left_ = Expression::make_temporary_reference(temp, loc);
5599 if (!this->right_->is_variable() && !this->right_->is_constant())
5601 temp =
5602 Statement::make_temporary(NULL, this->right_, loc);
5603 this->right_ = Expression::make_temporary_reference(temp, loc);
5604 inserter->insert(temp);
5607 return this;
5611 // Return the address of EXPR, cast to unsafe.Pointer.
5613 Expression*
5614 Binary_expression::operand_address(Statement_inserter* inserter,
5615 Expression* expr)
5617 Location loc = this->location();
5619 if (!expr->is_addressable())
5621 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5622 loc);
5623 inserter->insert(temp);
5624 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5626 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5627 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5628 Type* void_type = Type::make_void_type();
5629 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5630 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5633 // Return the numeric constant value, if it has one.
5635 bool
5636 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5638 Numeric_constant left_nc;
5639 if (!this->left_->numeric_constant_value(&left_nc))
5640 return false;
5641 Numeric_constant right_nc;
5642 if (!this->right_->numeric_constant_value(&right_nc))
5643 return false;
5644 bool issued_error;
5645 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5646 this->location(), nc, &issued_error);
5649 // Note that the value is being discarded.
5651 bool
5652 Binary_expression::do_discarding_value()
5654 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5655 return this->right_->discarding_value();
5656 else
5658 this->unused_value_error();
5659 return false;
5663 // Get type.
5665 Type*
5666 Binary_expression::do_type()
5668 if (this->classification() == EXPRESSION_ERROR)
5669 return Type::make_error_type();
5671 switch (this->op_)
5673 case OPERATOR_EQEQ:
5674 case OPERATOR_NOTEQ:
5675 case OPERATOR_LT:
5676 case OPERATOR_LE:
5677 case OPERATOR_GT:
5678 case OPERATOR_GE:
5679 if (this->type_ == NULL)
5680 this->type_ = Type::make_boolean_type();
5681 return this->type_;
5683 case OPERATOR_PLUS:
5684 case OPERATOR_MINUS:
5685 case OPERATOR_OR:
5686 case OPERATOR_XOR:
5687 case OPERATOR_MULT:
5688 case OPERATOR_DIV:
5689 case OPERATOR_MOD:
5690 case OPERATOR_AND:
5691 case OPERATOR_BITCLEAR:
5692 case OPERATOR_OROR:
5693 case OPERATOR_ANDAND:
5695 Type* type;
5696 if (!Binary_expression::operation_type(this->op_,
5697 this->left_->type(),
5698 this->right_->type(),
5699 &type))
5700 return Type::make_error_type();
5701 return type;
5704 case OPERATOR_LSHIFT:
5705 case OPERATOR_RSHIFT:
5706 return this->left_->type();
5708 default:
5709 go_unreachable();
5713 // Set type for a binary expression.
5715 void
5716 Binary_expression::do_determine_type(const Type_context* context)
5718 Type* tleft = this->left_->type();
5719 Type* tright = this->right_->type();
5721 // Both sides should have the same type, except for the shift
5722 // operations. For a comparison, we should ignore the incoming
5723 // type.
5725 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5726 || this->op_ == OPERATOR_RSHIFT);
5728 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5729 || this->op_ == OPERATOR_NOTEQ
5730 || this->op_ == OPERATOR_LT
5731 || this->op_ == OPERATOR_LE
5732 || this->op_ == OPERATOR_GT
5733 || this->op_ == OPERATOR_GE);
5735 // For constant expressions, the context of the result is not useful in
5736 // determining the types of the operands. It is only legal to use abstract
5737 // boolean, numeric, and string constants as operands where it is legal to
5738 // use non-abstract boolean, numeric, and string constants, respectively.
5739 // Any issues with the operation will be resolved in the check_types pass.
5740 bool is_constant_expr = (this->left_->is_constant()
5741 && this->right_->is_constant());
5743 Type_context subcontext(*context);
5745 if (is_constant_expr && !is_shift_op)
5747 subcontext.type = NULL;
5748 subcontext.may_be_abstract = true;
5750 else if (is_comparison)
5752 // In a comparison, the context does not determine the types of
5753 // the operands.
5754 subcontext.type = NULL;
5757 // Set the context for the left hand operand.
5758 if (is_shift_op)
5760 // The right hand operand of a shift plays no role in
5761 // determining the type of the left hand operand.
5763 else if (!tleft->is_abstract())
5764 subcontext.type = tleft;
5765 else if (!tright->is_abstract())
5766 subcontext.type = tright;
5767 else if (subcontext.type == NULL)
5769 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5770 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5771 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5773 // Both sides have an abstract integer, abstract float, or
5774 // abstract complex type. Just let CONTEXT determine
5775 // whether they may remain abstract or not.
5777 else if (tleft->complex_type() != NULL)
5778 subcontext.type = tleft;
5779 else if (tright->complex_type() != NULL)
5780 subcontext.type = tright;
5781 else if (tleft->float_type() != NULL)
5782 subcontext.type = tleft;
5783 else if (tright->float_type() != NULL)
5784 subcontext.type = tright;
5785 else
5786 subcontext.type = tleft;
5788 if (subcontext.type != NULL && !context->may_be_abstract)
5789 subcontext.type = subcontext.type->make_non_abstract_type();
5792 this->left_->determine_type(&subcontext);
5794 if (is_shift_op)
5796 // We may have inherited an unusable type for the shift operand.
5797 // Give a useful error if that happened.
5798 if (tleft->is_abstract()
5799 && subcontext.type != NULL
5800 && !subcontext.may_be_abstract
5801 && subcontext.type->interface_type() == NULL
5802 && subcontext.type->integer_type() == NULL)
5803 this->report_error(("invalid context-determined non-integer type "
5804 "for left operand of shift"));
5806 // The context for the right hand operand is the same as for the
5807 // left hand operand, except for a shift operator.
5808 subcontext.type = Type::lookup_integer_type("uint");
5809 subcontext.may_be_abstract = false;
5812 this->right_->determine_type(&subcontext);
5814 if (is_comparison)
5816 if (this->type_ != NULL && !this->type_->is_abstract())
5818 else if (context->type != NULL && context->type->is_boolean_type())
5819 this->type_ = context->type;
5820 else if (!context->may_be_abstract)
5821 this->type_ = Type::lookup_bool_type();
5825 // Report an error if the binary operator OP does not support TYPE.
5826 // OTYPE is the type of the other operand. Return whether the
5827 // operation is OK. This should not be used for shift.
5829 bool
5830 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5831 Location location)
5833 switch (op)
5835 case OPERATOR_OROR:
5836 case OPERATOR_ANDAND:
5837 if (!type->is_boolean_type()
5838 || !otype->is_boolean_type())
5840 go_error_at(location, "expected boolean type");
5841 return false;
5843 break;
5845 case OPERATOR_EQEQ:
5846 case OPERATOR_NOTEQ:
5848 std::string reason;
5849 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5851 go_error_at(location, "%s", reason.c_str());
5852 return false;
5855 break;
5857 case OPERATOR_LT:
5858 case OPERATOR_LE:
5859 case OPERATOR_GT:
5860 case OPERATOR_GE:
5862 std::string reason;
5863 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5865 go_error_at(location, "%s", reason.c_str());
5866 return false;
5869 break;
5871 case OPERATOR_PLUS:
5872 case OPERATOR_PLUSEQ:
5873 if ((!type->is_numeric_type() && !type->is_string_type())
5874 || (!otype->is_numeric_type() && !otype->is_string_type()))
5876 go_error_at(location,
5877 "expected integer, floating, complex, or string type");
5878 return false;
5880 break;
5882 case OPERATOR_MINUS:
5883 case OPERATOR_MINUSEQ:
5884 case OPERATOR_MULT:
5885 case OPERATOR_MULTEQ:
5886 case OPERATOR_DIV:
5887 case OPERATOR_DIVEQ:
5888 if (!type->is_numeric_type() || !otype->is_numeric_type())
5890 go_error_at(location, "expected integer, floating, or complex type");
5891 return false;
5893 break;
5895 case OPERATOR_MOD:
5896 case OPERATOR_MODEQ:
5897 case OPERATOR_OR:
5898 case OPERATOR_OREQ:
5899 case OPERATOR_AND:
5900 case OPERATOR_ANDEQ:
5901 case OPERATOR_XOR:
5902 case OPERATOR_XOREQ:
5903 case OPERATOR_BITCLEAR:
5904 case OPERATOR_BITCLEAREQ:
5905 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5907 go_error_at(location, "expected integer type");
5908 return false;
5910 break;
5912 default:
5913 go_unreachable();
5916 return true;
5919 // Check types.
5921 void
5922 Binary_expression::do_check_types(Gogo*)
5924 if (this->classification() == EXPRESSION_ERROR)
5925 return;
5927 Type* left_type = this->left_->type();
5928 Type* right_type = this->right_->type();
5929 if (left_type->is_error() || right_type->is_error())
5931 this->set_is_error();
5932 return;
5935 if (this->op_ == OPERATOR_EQEQ
5936 || this->op_ == OPERATOR_NOTEQ
5937 || this->op_ == OPERATOR_LT
5938 || this->op_ == OPERATOR_LE
5939 || this->op_ == OPERATOR_GT
5940 || this->op_ == OPERATOR_GE)
5942 if (left_type->is_nil_type() && right_type->is_nil_type())
5944 this->report_error(_("invalid comparison of nil with nil"));
5945 return;
5947 if (!Type::are_assignable(left_type, right_type, NULL)
5948 && !Type::are_assignable(right_type, left_type, NULL))
5950 this->report_error(_("incompatible types in binary expression"));
5951 return;
5953 if (!Binary_expression::check_operator_type(this->op_, left_type,
5954 right_type,
5955 this->location())
5956 || !Binary_expression::check_operator_type(this->op_, right_type,
5957 left_type,
5958 this->location()))
5960 this->set_is_error();
5961 return;
5964 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5966 if (!Type::are_compatible_for_binop(left_type, right_type))
5968 this->report_error(_("incompatible types in binary expression"));
5969 return;
5971 if (!Binary_expression::check_operator_type(this->op_, left_type,
5972 right_type,
5973 this->location()))
5975 this->set_is_error();
5976 return;
5978 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5980 // Division by a zero integer constant is an error.
5981 Numeric_constant rconst;
5982 unsigned long rval;
5983 if (left_type->integer_type() != NULL
5984 && this->right_->numeric_constant_value(&rconst)
5985 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5986 && rval == 0)
5988 this->report_error(_("integer division by zero"));
5989 return;
5993 else
5995 if (left_type->integer_type() == NULL)
5996 this->report_error(_("shift of non-integer operand"));
5998 if (right_type->is_string_type())
5999 this->report_error(_("shift count not unsigned integer"));
6000 else if (!right_type->is_abstract()
6001 && (right_type->integer_type() == NULL
6002 || !right_type->integer_type()->is_unsigned()))
6003 this->report_error(_("shift count not unsigned integer"));
6004 else
6006 Numeric_constant nc;
6007 if (this->right_->numeric_constant_value(&nc))
6009 mpz_t val;
6010 if (!nc.to_int(&val))
6011 this->report_error(_("shift count not unsigned integer"));
6012 else
6014 if (mpz_sgn(val) < 0)
6016 this->report_error(_("negative shift count"));
6017 Location rloc = this->right_->location();
6018 this->right_ = Expression::make_integer_ul(0, right_type,
6019 rloc);
6021 mpz_clear(val);
6028 // Get the backend representation for a binary expression.
6030 Bexpression*
6031 Binary_expression::do_get_backend(Translate_context* context)
6033 Gogo* gogo = context->gogo();
6034 Location loc = this->location();
6035 Type* left_type = this->left_->type();
6036 Type* right_type = this->right_->type();
6038 bool use_left_type = true;
6039 bool is_shift_op = false;
6040 bool is_idiv_op = false;
6041 switch (this->op_)
6043 case OPERATOR_EQEQ:
6044 case OPERATOR_NOTEQ:
6045 case OPERATOR_LT:
6046 case OPERATOR_LE:
6047 case OPERATOR_GT:
6048 case OPERATOR_GE:
6049 return Expression::comparison(context, this->type_, this->op_,
6050 this->left_, this->right_, loc);
6052 case OPERATOR_OROR:
6053 case OPERATOR_ANDAND:
6054 use_left_type = false;
6055 break;
6056 case OPERATOR_PLUS:
6057 case OPERATOR_MINUS:
6058 case OPERATOR_OR:
6059 case OPERATOR_XOR:
6060 case OPERATOR_MULT:
6061 break;
6062 case OPERATOR_DIV:
6063 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6064 break;
6065 // Fall through.
6066 case OPERATOR_MOD:
6067 is_idiv_op = true;
6068 break;
6069 case OPERATOR_LSHIFT:
6070 case OPERATOR_RSHIFT:
6071 is_shift_op = true;
6072 break;
6073 case OPERATOR_BITCLEAR:
6074 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6075 case OPERATOR_AND:
6076 break;
6077 default:
6078 go_unreachable();
6081 // The only binary operation for string is +, and that should have
6082 // been converted to a String_concat_expression in do_lower.
6083 go_assert(!left_type->is_string_type());
6085 // For complex division Go might want slightly different results than the
6086 // backend implementation provides, so we have our own runtime routine.
6087 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6089 Runtime::Function complex_code;
6090 switch (this->left_->type()->complex_type()->bits())
6092 case 64:
6093 complex_code = Runtime::COMPLEX64_DIV;
6094 break;
6095 case 128:
6096 complex_code = Runtime::COMPLEX128_DIV;
6097 break;
6098 default:
6099 go_unreachable();
6101 Expression* complex_div =
6102 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6103 return complex_div->get_backend(context);
6106 Bexpression* left = this->left_->get_backend(context);
6107 Bexpression* right = this->right_->get_backend(context);
6109 Type* type = use_left_type ? left_type : right_type;
6110 Btype* btype = type->get_backend(gogo);
6112 Bexpression* ret =
6113 gogo->backend()->binary_expression(this->op_, left, right, loc);
6114 ret = gogo->backend()->convert_expression(btype, ret, loc);
6116 // Initialize overflow constants.
6117 Bexpression* overflow;
6118 mpz_t zero;
6119 mpz_init_set_ui(zero, 0UL);
6120 mpz_t one;
6121 mpz_init_set_ui(one, 1UL);
6122 mpz_t neg_one;
6123 mpz_init_set_si(neg_one, -1);
6125 Btype* left_btype = left_type->get_backend(gogo);
6126 Btype* right_btype = right_type->get_backend(gogo);
6128 // In Go, a shift larger than the size of the type is well-defined.
6129 // This is not true in C, so we need to insert a conditional.
6130 if (is_shift_op)
6132 go_assert(left_type->integer_type() != NULL);
6134 int bits = left_type->integer_type()->bits();
6136 Numeric_constant nc;
6137 unsigned long ul;
6138 if (!this->right_->numeric_constant_value(&nc)
6139 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6140 || ul >= static_cast<unsigned long>(bits))
6142 mpz_t bitsval;
6143 mpz_init_set_ui(bitsval, bits);
6144 Bexpression* bits_expr =
6145 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6146 Bexpression* compare =
6147 gogo->backend()->binary_expression(OPERATOR_LT,
6148 right, bits_expr, loc);
6150 Bexpression* zero_expr =
6151 gogo->backend()->integer_constant_expression(left_btype, zero);
6152 overflow = zero_expr;
6153 Bfunction* bfn = context->function()->func_value()->get_decl();
6154 if (this->op_ == OPERATOR_RSHIFT
6155 && !left_type->integer_type()->is_unsigned())
6157 Bexpression* neg_expr =
6158 gogo->backend()->binary_expression(OPERATOR_LT, left,
6159 zero_expr, loc);
6160 Bexpression* neg_one_expr =
6161 gogo->backend()->integer_constant_expression(left_btype,
6162 neg_one);
6163 overflow = gogo->backend()->conditional_expression(bfn,
6164 btype,
6165 neg_expr,
6166 neg_one_expr,
6167 zero_expr,
6168 loc);
6170 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6171 ret, overflow, loc);
6172 mpz_clear(bitsval);
6176 // Add checks for division by zero and division overflow as needed.
6177 if (is_idiv_op)
6179 if (gogo->check_divide_by_zero())
6181 // right == 0
6182 Bexpression* zero_expr =
6183 gogo->backend()->integer_constant_expression(right_btype, zero);
6184 Bexpression* check =
6185 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6186 right, zero_expr, loc);
6188 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6189 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6190 Bexpression* crash = gogo->runtime_error(errcode,
6191 loc)->get_backend(context);
6193 // right == 0 ? (__go_runtime_error(...), 0) : ret
6194 Bfunction* bfn = context->function()->func_value()->get_decl();
6195 ret = gogo->backend()->conditional_expression(bfn, btype,
6196 check, crash,
6197 ret, loc);
6200 if (gogo->check_divide_overflow())
6202 // right == -1
6203 // FIXME: It would be nice to say that this test is expected
6204 // to return false.
6206 Bexpression* neg_one_expr =
6207 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6208 Bexpression* check =
6209 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6210 right, neg_one_expr, loc);
6212 Bexpression* zero_expr =
6213 gogo->backend()->integer_constant_expression(btype, zero);
6214 Bexpression* one_expr =
6215 gogo->backend()->integer_constant_expression(btype, one);
6216 Bfunction* bfn = context->function()->func_value()->get_decl();
6218 if (type->integer_type()->is_unsigned())
6220 // An unsigned -1 is the largest possible number, so
6221 // dividing is always 1 or 0.
6223 Bexpression* cmp =
6224 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6225 left, right, loc);
6226 if (this->op_ == OPERATOR_DIV)
6227 overflow =
6228 gogo->backend()->conditional_expression(bfn, btype, cmp,
6229 one_expr, zero_expr,
6230 loc);
6231 else
6232 overflow =
6233 gogo->backend()->conditional_expression(bfn, btype, cmp,
6234 zero_expr, left,
6235 loc);
6237 else
6239 // Computing left / -1 is the same as computing - left,
6240 // which does not overflow since Go sets -fwrapv.
6241 if (this->op_ == OPERATOR_DIV)
6243 Expression* negate_expr =
6244 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6245 overflow = negate_expr->get_backend(context);
6247 else
6248 overflow = zero_expr;
6250 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6252 // right == -1 ? - left : ret
6253 ret = gogo->backend()->conditional_expression(bfn, btype,
6254 check, overflow,
6255 ret, loc);
6259 mpz_clear(zero);
6260 mpz_clear(one);
6261 mpz_clear(neg_one);
6262 return ret;
6265 // Export a binary expression.
6267 void
6268 Binary_expression::do_export(Export* exp) const
6270 exp->write_c_string("(");
6271 this->left_->export_expression(exp);
6272 switch (this->op_)
6274 case OPERATOR_OROR:
6275 exp->write_c_string(" || ");
6276 break;
6277 case OPERATOR_ANDAND:
6278 exp->write_c_string(" && ");
6279 break;
6280 case OPERATOR_EQEQ:
6281 exp->write_c_string(" == ");
6282 break;
6283 case OPERATOR_NOTEQ:
6284 exp->write_c_string(" != ");
6285 break;
6286 case OPERATOR_LT:
6287 exp->write_c_string(" < ");
6288 break;
6289 case OPERATOR_LE:
6290 exp->write_c_string(" <= ");
6291 break;
6292 case OPERATOR_GT:
6293 exp->write_c_string(" > ");
6294 break;
6295 case OPERATOR_GE:
6296 exp->write_c_string(" >= ");
6297 break;
6298 case OPERATOR_PLUS:
6299 exp->write_c_string(" + ");
6300 break;
6301 case OPERATOR_MINUS:
6302 exp->write_c_string(" - ");
6303 break;
6304 case OPERATOR_OR:
6305 exp->write_c_string(" | ");
6306 break;
6307 case OPERATOR_XOR:
6308 exp->write_c_string(" ^ ");
6309 break;
6310 case OPERATOR_MULT:
6311 exp->write_c_string(" * ");
6312 break;
6313 case OPERATOR_DIV:
6314 exp->write_c_string(" / ");
6315 break;
6316 case OPERATOR_MOD:
6317 exp->write_c_string(" % ");
6318 break;
6319 case OPERATOR_LSHIFT:
6320 exp->write_c_string(" << ");
6321 break;
6322 case OPERATOR_RSHIFT:
6323 exp->write_c_string(" >> ");
6324 break;
6325 case OPERATOR_AND:
6326 exp->write_c_string(" & ");
6327 break;
6328 case OPERATOR_BITCLEAR:
6329 exp->write_c_string(" &^ ");
6330 break;
6331 default:
6332 go_unreachable();
6334 this->right_->export_expression(exp);
6335 exp->write_c_string(")");
6338 // Import a binary expression.
6340 Expression*
6341 Binary_expression::do_import(Import* imp)
6343 imp->require_c_string("(");
6345 Expression* left = Expression::import_expression(imp);
6347 Operator op;
6348 if (imp->match_c_string(" || "))
6350 op = OPERATOR_OROR;
6351 imp->advance(4);
6353 else if (imp->match_c_string(" && "))
6355 op = OPERATOR_ANDAND;
6356 imp->advance(4);
6358 else if (imp->match_c_string(" == "))
6360 op = OPERATOR_EQEQ;
6361 imp->advance(4);
6363 else if (imp->match_c_string(" != "))
6365 op = OPERATOR_NOTEQ;
6366 imp->advance(4);
6368 else if (imp->match_c_string(" < "))
6370 op = OPERATOR_LT;
6371 imp->advance(3);
6373 else if (imp->match_c_string(" <= "))
6375 op = OPERATOR_LE;
6376 imp->advance(4);
6378 else if (imp->match_c_string(" > "))
6380 op = OPERATOR_GT;
6381 imp->advance(3);
6383 else if (imp->match_c_string(" >= "))
6385 op = OPERATOR_GE;
6386 imp->advance(4);
6388 else if (imp->match_c_string(" + "))
6390 op = OPERATOR_PLUS;
6391 imp->advance(3);
6393 else if (imp->match_c_string(" - "))
6395 op = OPERATOR_MINUS;
6396 imp->advance(3);
6398 else if (imp->match_c_string(" | "))
6400 op = OPERATOR_OR;
6401 imp->advance(3);
6403 else if (imp->match_c_string(" ^ "))
6405 op = OPERATOR_XOR;
6406 imp->advance(3);
6408 else if (imp->match_c_string(" * "))
6410 op = OPERATOR_MULT;
6411 imp->advance(3);
6413 else if (imp->match_c_string(" / "))
6415 op = OPERATOR_DIV;
6416 imp->advance(3);
6418 else if (imp->match_c_string(" % "))
6420 op = OPERATOR_MOD;
6421 imp->advance(3);
6423 else if (imp->match_c_string(" << "))
6425 op = OPERATOR_LSHIFT;
6426 imp->advance(4);
6428 else if (imp->match_c_string(" >> "))
6430 op = OPERATOR_RSHIFT;
6431 imp->advance(4);
6433 else if (imp->match_c_string(" & "))
6435 op = OPERATOR_AND;
6436 imp->advance(3);
6438 else if (imp->match_c_string(" &^ "))
6440 op = OPERATOR_BITCLEAR;
6441 imp->advance(4);
6443 else
6445 go_error_at(imp->location(), "unrecognized binary operator");
6446 return Expression::make_error(imp->location());
6449 Expression* right = Expression::import_expression(imp);
6451 imp->require_c_string(")");
6453 return Expression::make_binary(op, left, right, imp->location());
6456 // Dump ast representation of a binary expression.
6458 void
6459 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6461 ast_dump_context->ostream() << "(";
6462 ast_dump_context->dump_expression(this->left_);
6463 ast_dump_context->ostream() << " ";
6464 ast_dump_context->dump_operator(this->op_);
6465 ast_dump_context->ostream() << " ";
6466 ast_dump_context->dump_expression(this->right_);
6467 ast_dump_context->ostream() << ") ";
6470 // Make a binary expression.
6472 Expression*
6473 Expression::make_binary(Operator op, Expression* left, Expression* right,
6474 Location location)
6476 return new Binary_expression(op, left, right, location);
6479 // Implement a comparison.
6481 Bexpression*
6482 Expression::comparison(Translate_context* context, Type* result_type,
6483 Operator op, Expression* left, Expression* right,
6484 Location location)
6486 Type* left_type = left->type();
6487 Type* right_type = right->type();
6489 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6491 if (left_type->is_string_type() && right_type->is_string_type())
6493 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6495 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6496 left, right);
6497 right = Expression::make_boolean(true, location);
6499 else
6501 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6502 left, right);
6503 right = zexpr;
6506 else if ((left_type->interface_type() != NULL
6507 && right_type->interface_type() == NULL
6508 && !right_type->is_nil_type())
6509 || (left_type->interface_type() == NULL
6510 && !left_type->is_nil_type()
6511 && right_type->interface_type() != NULL))
6513 // Comparing an interface value to a non-interface value.
6514 if (left_type->interface_type() == NULL)
6516 std::swap(left_type, right_type);
6517 std::swap(left, right);
6520 // The right operand is not an interface. We need to take its
6521 // address if it is not a pointer.
6522 Expression* pointer_arg = NULL;
6523 if (right_type->points_to() != NULL)
6524 pointer_arg = right;
6525 else
6527 go_assert(right->is_addressable());
6528 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6529 location);
6532 Expression* descriptor =
6533 Expression::make_type_descriptor(right_type, location);
6534 left =
6535 Runtime::make_call((left_type->interface_type()->is_empty()
6536 ? Runtime::EFACEVALEQ
6537 : Runtime::IFACEVALEQ),
6538 location, 3, left, descriptor,
6539 pointer_arg);
6540 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6541 right = Expression::make_boolean(true, location);
6543 else if (left_type->interface_type() != NULL
6544 && right_type->interface_type() != NULL)
6546 Runtime::Function compare_function;
6547 if (left_type->interface_type()->is_empty()
6548 && right_type->interface_type()->is_empty())
6549 compare_function = Runtime::EFACEEQ;
6550 else if (!left_type->interface_type()->is_empty()
6551 && !right_type->interface_type()->is_empty())
6552 compare_function = Runtime::IFACEEQ;
6553 else
6555 if (left_type->interface_type()->is_empty())
6557 std::swap(left_type, right_type);
6558 std::swap(left, right);
6560 go_assert(!left_type->interface_type()->is_empty());
6561 go_assert(right_type->interface_type()->is_empty());
6562 compare_function = Runtime::IFACEEFACEEQ;
6565 left = Runtime::make_call(compare_function, location, 2, left, right);
6566 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6567 right = Expression::make_boolean(true, location);
6570 if (left_type->is_nil_type()
6571 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6573 std::swap(left_type, right_type);
6574 std::swap(left, right);
6577 if (right_type->is_nil_type())
6579 right = Expression::make_nil(location);
6580 if (left_type->array_type() != NULL
6581 && left_type->array_type()->length() == NULL)
6583 Array_type* at = left_type->array_type();
6584 bool is_lvalue = false;
6585 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6587 else if (left_type->interface_type() != NULL)
6589 // An interface is nil if the first field is nil.
6590 left = Expression::make_field_reference(left, 0, location);
6594 Bexpression* left_bexpr = left->get_backend(context);
6595 Bexpression* right_bexpr = right->get_backend(context);
6597 Gogo* gogo = context->gogo();
6598 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6599 right_bexpr, location);
6600 if (result_type != NULL)
6601 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6602 ret, location);
6603 return ret;
6606 // Class String_concat_expression.
6608 bool
6609 String_concat_expression::do_is_constant() const
6611 for (Expression_list::const_iterator pe = this->exprs_->begin();
6612 pe != this->exprs_->end();
6613 ++pe)
6615 if (!(*pe)->is_constant())
6616 return false;
6618 return true;
6621 bool
6622 String_concat_expression::do_is_static_initializer() const
6624 for (Expression_list::const_iterator pe = this->exprs_->begin();
6625 pe != this->exprs_->end();
6626 ++pe)
6628 if (!(*pe)->is_static_initializer())
6629 return false;
6631 return true;
6634 Type*
6635 String_concat_expression::do_type()
6637 Type* t = this->exprs_->front()->type();
6638 Expression_list::iterator pe = this->exprs_->begin();
6639 ++pe;
6640 for (; pe != this->exprs_->end(); ++pe)
6642 Type* t1;
6643 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6644 (*pe)->type(),
6645 &t1))
6646 return Type::make_error_type();
6647 t = t1;
6649 return t;
6652 void
6653 String_concat_expression::do_determine_type(const Type_context* context)
6655 Type_context subcontext(*context);
6656 for (Expression_list::iterator pe = this->exprs_->begin();
6657 pe != this->exprs_->end();
6658 ++pe)
6660 Type* t = (*pe)->type();
6661 if (!t->is_abstract())
6663 subcontext.type = t;
6664 break;
6667 if (subcontext.type == NULL)
6668 subcontext.type = this->exprs_->front()->type();
6669 for (Expression_list::iterator pe = this->exprs_->begin();
6670 pe != this->exprs_->end();
6671 ++pe)
6672 (*pe)->determine_type(&subcontext);
6675 void
6676 String_concat_expression::do_check_types(Gogo*)
6678 if (this->is_error_expression())
6679 return;
6680 Type* t = this->exprs_->front()->type();
6681 if (t->is_error())
6683 this->set_is_error();
6684 return;
6686 Expression_list::iterator pe = this->exprs_->begin();
6687 ++pe;
6688 for (; pe != this->exprs_->end(); ++pe)
6690 Type* t1 = (*pe)->type();
6691 if (!Type::are_compatible_for_binop(t, t1))
6693 this->report_error("incompatible types in binary expression");
6694 return;
6696 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6697 this->location()))
6699 this->set_is_error();
6700 return;
6705 Expression*
6706 String_concat_expression::do_flatten(Gogo*, Named_object*,
6707 Statement_inserter*)
6709 if (this->is_error_expression())
6710 return this;
6711 Location loc = this->location();
6712 Type* type = this->type();
6713 Expression* nil_arg = Expression::make_nil(loc);
6714 Expression* call;
6715 switch (this->exprs_->size())
6717 case 0: case 1:
6718 go_unreachable();
6720 case 2: case 3: case 4: case 5:
6722 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6723 NULL, loc);
6724 Array_type* arg_type = Type::make_array_type(type, len);
6725 arg_type->set_is_array_incomparable();
6726 Expression* arg =
6727 Expression::make_array_composite_literal(arg_type, this->exprs_,
6728 loc);
6729 Runtime::Function code;
6730 switch (this->exprs_->size())
6732 default:
6733 go_unreachable();
6734 case 2:
6735 code = Runtime::CONCATSTRING2;
6736 break;
6737 case 3:
6738 code = Runtime::CONCATSTRING3;
6739 break;
6740 case 4:
6741 code = Runtime::CONCATSTRING4;
6742 break;
6743 case 5:
6744 code = Runtime::CONCATSTRING5;
6745 break;
6747 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6749 break;
6751 default:
6753 Type* arg_type = Type::make_array_type(type, NULL);
6754 Slice_construction_expression* sce =
6755 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6756 loc);
6757 sce->set_storage_does_not_escape();
6758 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6759 sce);
6761 break;
6764 return Expression::make_cast(type, call, loc);
6767 void
6768 String_concat_expression::do_dump_expression(
6769 Ast_dump_context* ast_dump_context) const
6771 ast_dump_context->ostream() << "concat(";
6772 ast_dump_context->dump_expression_list(this->exprs_, false);
6773 ast_dump_context->ostream() << ")";
6776 Expression*
6777 Expression::make_string_concat(Expression_list* exprs)
6779 return new String_concat_expression(exprs);
6782 // Class Bound_method_expression.
6784 // Traversal.
6787 Bound_method_expression::do_traverse(Traverse* traverse)
6789 return Expression::traverse(&this->expr_, traverse);
6792 // Return the type of a bound method expression. The type of this
6793 // object is simply the type of the method with no receiver.
6795 Type*
6796 Bound_method_expression::do_type()
6798 Named_object* fn = this->method_->named_object();
6799 Function_type* fntype;
6800 if (fn->is_function())
6801 fntype = fn->func_value()->type();
6802 else if (fn->is_function_declaration())
6803 fntype = fn->func_declaration_value()->type();
6804 else
6805 return Type::make_error_type();
6806 return fntype->copy_without_receiver();
6809 // Determine the types of a method expression.
6811 void
6812 Bound_method_expression::do_determine_type(const Type_context*)
6814 Named_object* fn = this->method_->named_object();
6815 Function_type* fntype;
6816 if (fn->is_function())
6817 fntype = fn->func_value()->type();
6818 else if (fn->is_function_declaration())
6819 fntype = fn->func_declaration_value()->type();
6820 else
6821 fntype = NULL;
6822 if (fntype == NULL || !fntype->is_method())
6823 this->expr_->determine_type_no_context();
6824 else
6826 Type_context subcontext(fntype->receiver()->type(), false);
6827 this->expr_->determine_type(&subcontext);
6831 // Check the types of a method expression.
6833 void
6834 Bound_method_expression::do_check_types(Gogo*)
6836 Named_object* fn = this->method_->named_object();
6837 if (!fn->is_function() && !fn->is_function_declaration())
6839 this->report_error(_("object is not a method"));
6840 return;
6843 Function_type* fntype;
6844 if (fn->is_function())
6845 fntype = fn->func_value()->type();
6846 else if (fn->is_function_declaration())
6847 fntype = fn->func_declaration_value()->type();
6848 else
6849 go_unreachable();
6850 Type* rtype = fntype->receiver()->type()->deref();
6851 Type* etype = (this->expr_type_ != NULL
6852 ? this->expr_type_
6853 : this->expr_->type());
6854 etype = etype->deref();
6855 if (!Type::are_identical(rtype, etype, true, NULL))
6856 this->report_error(_("method type does not match object type"));
6859 // If a bound method expression is not simply called, then it is
6860 // represented as a closure. The closure will hold a single variable,
6861 // the receiver to pass to the method. The function will be a simple
6862 // thunk that pulls that value from the closure and calls the method
6863 // with the remaining arguments.
6865 // Because method values are not common, we don't build all thunks for
6866 // every methods, but instead only build them as we need them. In
6867 // particular, we even build them on demand for methods defined in
6868 // other packages.
6870 Bound_method_expression::Method_value_thunks
6871 Bound_method_expression::method_value_thunks;
6873 // Find or create the thunk for METHOD.
6875 Named_object*
6876 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6877 Named_object* fn)
6879 std::pair<Named_object*, Named_object*> val(fn, NULL);
6880 std::pair<Method_value_thunks::iterator, bool> ins =
6881 Bound_method_expression::method_value_thunks.insert(val);
6882 if (!ins.second)
6884 // We have seen this method before.
6885 go_assert(ins.first->second != NULL);
6886 return ins.first->second;
6889 Location loc = fn->location();
6891 Function_type* orig_fntype;
6892 if (fn->is_function())
6893 orig_fntype = fn->func_value()->type();
6894 else if (fn->is_function_declaration())
6895 orig_fntype = fn->func_declaration_value()->type();
6896 else
6897 orig_fntype = NULL;
6899 if (orig_fntype == NULL || !orig_fntype->is_method())
6901 ins.first->second =
6902 Named_object::make_erroneous_name(gogo->thunk_name());
6903 return ins.first->second;
6906 Struct_field_list* sfl = new Struct_field_list();
6907 // The type here is wrong--it should be the C function type. But it
6908 // doesn't really matter.
6909 Type* vt = Type::make_pointer_type(Type::make_void_type());
6910 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
6911 sfl->push_back(Struct_field(Typed_identifier("val",
6912 orig_fntype->receiver()->type(),
6913 loc)));
6914 Struct_type* st = Type::make_struct_type(sfl, loc);
6915 st->set_is_struct_incomparable();
6916 Type* closure_type = Type::make_pointer_type(st);
6918 Function_type* new_fntype = orig_fntype->copy_with_names();
6920 std::string thunk_name = gogo->thunk_name();
6921 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6922 false, loc);
6924 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6925 cvar->set_is_used();
6926 cvar->set_is_closure();
6927 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6928 NULL, cvar);
6929 new_no->func_value()->set_closure_var(cp);
6931 gogo->start_block(loc);
6933 // Field 0 of the closure is the function code pointer, field 1 is
6934 // the value on which to invoke the method.
6935 Expression* arg = Expression::make_var_reference(cp, loc);
6936 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
6937 arg = Expression::make_field_reference(arg, 1, loc);
6939 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6941 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6942 Expression_list* args;
6943 if (orig_params == NULL || orig_params->empty())
6944 args = NULL;
6945 else
6947 const Typed_identifier_list* new_params = new_fntype->parameters();
6948 args = new Expression_list();
6949 for (Typed_identifier_list::const_iterator p = new_params->begin();
6950 p != new_params->end();
6951 ++p)
6953 Named_object* p_no = gogo->lookup(p->name(), NULL);
6954 go_assert(p_no != NULL
6955 && p_no->is_variable()
6956 && p_no->var_value()->is_parameter());
6957 args->push_back(Expression::make_var_reference(p_no, loc));
6961 Call_expression* call = Expression::make_call(bme, args,
6962 orig_fntype->is_varargs(),
6963 loc);
6964 call->set_varargs_are_lowered();
6966 Statement* s = Statement::make_return_from_call(call, loc);
6967 gogo->add_statement(s);
6968 Block* b = gogo->finish_block(loc);
6969 gogo->add_block(b, loc);
6970 gogo->lower_block(new_no, b);
6971 gogo->flatten_block(new_no, b);
6972 gogo->finish_function(loc);
6974 ins.first->second = new_no;
6975 return new_no;
6978 // Return an expression to check *REF for nil while dereferencing
6979 // according to FIELD_INDEXES. Update *REF to build up the field
6980 // reference. This is a static function so that we don't have to
6981 // worry about declaring Field_indexes in expressions.h.
6983 static Expression*
6984 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6985 Expression** ref)
6987 if (field_indexes == NULL)
6988 return Expression::make_boolean(false, loc);
6989 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6990 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6991 go_assert(stype != NULL
6992 && field_indexes->field_index < stype->field_count());
6993 if ((*ref)->type()->struct_type() == NULL)
6995 go_assert((*ref)->type()->points_to() != NULL);
6996 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6997 Expression::make_nil(loc),
6998 loc);
6999 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7000 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7001 loc);
7002 go_assert((*ref)->type()->struct_type() == stype);
7004 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7005 loc);
7006 return cond;
7009 // Flatten a method value into a struct with nil checks. We can't do
7010 // this in the lowering phase, because if the method value is called
7011 // directly we don't need a thunk. That case will have been handled
7012 // by Call_expression::do_lower, so if we get here then we do need a
7013 // thunk.
7015 Expression*
7016 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7017 Statement_inserter* inserter)
7019 Location loc = this->location();
7021 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7022 this->method_,
7023 this->function_);
7024 if (thunk->is_erroneous())
7026 go_assert(saw_errors());
7027 return Expression::make_error(loc);
7030 // Force the expression into a variable. This is only necessary if
7031 // we are going to do nil checks below, but it's easy enough to
7032 // always do it.
7033 Expression* expr = this->expr_;
7034 if (!expr->is_variable())
7036 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7037 inserter->insert(etemp);
7038 expr = Expression::make_temporary_reference(etemp, loc);
7041 // If the method expects a value, and we have a pointer, we need to
7042 // dereference the pointer.
7044 Named_object* fn = this->method_->named_object();
7045 Function_type *fntype;
7046 if (fn->is_function())
7047 fntype = fn->func_value()->type();
7048 else if (fn->is_function_declaration())
7049 fntype = fn->func_declaration_value()->type();
7050 else
7051 go_unreachable();
7053 Expression* val = expr;
7054 if (fntype->receiver()->type()->points_to() == NULL
7055 && val->type()->points_to() != NULL)
7056 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7058 // Note that we are ignoring this->expr_type_ here. The thunk will
7059 // expect a closure whose second field has type this->expr_type_ (if
7060 // that is not NULL). We are going to pass it a closure whose
7061 // second field has type this->expr_->type(). Since
7062 // this->expr_type_ is only not-NULL for pointer types, we can get
7063 // away with this.
7065 Struct_field_list* fields = new Struct_field_list();
7066 fields->push_back(Struct_field(Typed_identifier("fn",
7067 thunk->func_value()->type(),
7068 loc)));
7069 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
7070 Struct_type* st = Type::make_struct_type(fields, loc);
7071 st->set_is_struct_incomparable();
7073 Expression_list* vals = new Expression_list();
7074 vals->push_back(Expression::make_func_code_reference(thunk, loc));
7075 vals->push_back(val);
7077 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7078 ret = Expression::make_heap_expression(ret, loc);
7080 Node* n = Node::make_node(this);
7081 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7082 ret->heap_expression()->set_allocate_on_stack();
7083 else if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
7084 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
7085 n->ast_format(gogo).c_str());
7087 // If necessary, check whether the expression or any embedded
7088 // pointers are nil.
7090 Expression* nil_check = NULL;
7091 if (this->method_->field_indexes() != NULL)
7093 Expression* ref = expr;
7094 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7095 expr = ref;
7098 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7100 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7101 Expression::make_nil(loc),
7102 loc);
7103 if (nil_check == NULL)
7104 nil_check = n;
7105 else
7106 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7109 if (nil_check != NULL)
7111 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7112 loc);
7113 // Fix the type of the conditional expression by pretending to
7114 // evaluate to RET either way through the conditional.
7115 crash = Expression::make_compound(crash, ret, loc);
7116 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7119 // RET is a pointer to a struct, but we want a function type.
7120 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7122 return ret;
7125 // Dump ast representation of a bound method expression.
7127 void
7128 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7129 const
7131 if (this->expr_type_ != NULL)
7132 ast_dump_context->ostream() << "(";
7133 ast_dump_context->dump_expression(this->expr_);
7134 if (this->expr_type_ != NULL)
7136 ast_dump_context->ostream() << ":";
7137 ast_dump_context->dump_type(this->expr_type_);
7138 ast_dump_context->ostream() << ")";
7141 ast_dump_context->ostream() << "." << this->function_->name();
7144 // Make a method expression.
7146 Bound_method_expression*
7147 Expression::make_bound_method(Expression* expr, const Method* method,
7148 Named_object* function, Location location)
7150 return new Bound_method_expression(expr, method, function, location);
7153 // Class Builtin_call_expression. This is used for a call to a
7154 // builtin function.
7156 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7157 Expression* fn,
7158 Expression_list* args,
7159 bool is_varargs,
7160 Location location)
7161 : Call_expression(fn, args, is_varargs, location),
7162 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7163 recover_arg_is_set_(false)
7165 Func_expression* fnexp = this->fn()->func_expression();
7166 if (fnexp == NULL)
7168 this->code_ = BUILTIN_INVALID;
7169 return;
7171 const std::string& name(fnexp->named_object()->name());
7172 if (name == "append")
7173 this->code_ = BUILTIN_APPEND;
7174 else if (name == "cap")
7175 this->code_ = BUILTIN_CAP;
7176 else if (name == "close")
7177 this->code_ = BUILTIN_CLOSE;
7178 else if (name == "complex")
7179 this->code_ = BUILTIN_COMPLEX;
7180 else if (name == "copy")
7181 this->code_ = BUILTIN_COPY;
7182 else if (name == "delete")
7183 this->code_ = BUILTIN_DELETE;
7184 else if (name == "imag")
7185 this->code_ = BUILTIN_IMAG;
7186 else if (name == "len")
7187 this->code_ = BUILTIN_LEN;
7188 else if (name == "make")
7189 this->code_ = BUILTIN_MAKE;
7190 else if (name == "new")
7191 this->code_ = BUILTIN_NEW;
7192 else if (name == "panic")
7193 this->code_ = BUILTIN_PANIC;
7194 else if (name == "print")
7195 this->code_ = BUILTIN_PRINT;
7196 else if (name == "println")
7197 this->code_ = BUILTIN_PRINTLN;
7198 else if (name == "real")
7199 this->code_ = BUILTIN_REAL;
7200 else if (name == "recover")
7201 this->code_ = BUILTIN_RECOVER;
7202 else if (name == "Alignof")
7203 this->code_ = BUILTIN_ALIGNOF;
7204 else if (name == "Offsetof")
7205 this->code_ = BUILTIN_OFFSETOF;
7206 else if (name == "Sizeof")
7207 this->code_ = BUILTIN_SIZEOF;
7208 else
7209 go_unreachable();
7212 // Return whether this is a call to recover. This is a virtual
7213 // function called from the parent class.
7215 bool
7216 Builtin_call_expression::do_is_recover_call() const
7218 if (this->classification() == EXPRESSION_ERROR)
7219 return false;
7220 return this->code_ == BUILTIN_RECOVER;
7223 // Set the argument for a call to recover.
7225 void
7226 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7228 const Expression_list* args = this->args();
7229 go_assert(args == NULL || args->empty());
7230 Expression_list* new_args = new Expression_list();
7231 new_args->push_back(arg);
7232 this->set_args(new_args);
7233 this->recover_arg_is_set_ = true;
7236 // Lower a builtin call expression. This turns new and make into
7237 // specific expressions. We also convert to a constant if we can.
7239 Expression*
7240 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7241 Statement_inserter* inserter, int)
7243 if (this->is_error_expression())
7244 return this;
7246 Location loc = this->location();
7248 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7250 this->report_error(_("invalid use of %<...%> with builtin function"));
7251 return Expression::make_error(loc);
7254 if (this->code_ == BUILTIN_OFFSETOF)
7256 Expression* arg = this->one_arg();
7258 if (arg->bound_method_expression() != NULL
7259 || arg->interface_field_reference_expression() != NULL)
7261 this->report_error(_("invalid use of method value as argument "
7262 "of Offsetof"));
7263 return this;
7266 Field_reference_expression* farg = arg->field_reference_expression();
7267 while (farg != NULL)
7269 if (!farg->implicit())
7270 break;
7271 // When the selector refers to an embedded field,
7272 // it must not be reached through pointer indirections.
7273 if (farg->expr()->deref() != farg->expr())
7275 this->report_error(_("argument of Offsetof implies "
7276 "indirection of an embedded field"));
7277 return this;
7279 // Go up until we reach the original base.
7280 farg = farg->expr()->field_reference_expression();
7284 if (this->is_constant())
7286 Numeric_constant nc;
7287 if (this->numeric_constant_value(&nc))
7288 return nc.expression(loc);
7291 switch (this->code_)
7293 default:
7294 break;
7296 case BUILTIN_NEW:
7298 const Expression_list* args = this->args();
7299 if (args == NULL || args->size() < 1)
7300 this->report_error(_("not enough arguments"));
7301 else if (args->size() > 1)
7302 this->report_error(_("too many arguments"));
7303 else
7305 Expression* arg = args->front();
7306 if (!arg->is_type_expression())
7308 go_error_at(arg->location(), "expected type");
7309 this->set_is_error();
7311 else
7312 return Expression::make_allocation(arg->type(), loc);
7315 break;
7317 case BUILTIN_MAKE:
7318 return this->lower_make(inserter);
7320 case BUILTIN_RECOVER:
7321 if (function != NULL)
7322 function->func_value()->set_calls_recover();
7323 else
7325 // Calling recover outside of a function always returns the
7326 // nil empty interface.
7327 Type* eface = Type::make_empty_interface_type(loc);
7328 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7330 break;
7332 case BUILTIN_DELETE:
7334 // Lower to a runtime function call.
7335 const Expression_list* args = this->args();
7336 if (args == NULL || args->size() < 2)
7337 this->report_error(_("not enough arguments"));
7338 else if (args->size() > 2)
7339 this->report_error(_("too many arguments"));
7340 else if (args->front()->type()->map_type() == NULL)
7341 this->report_error(_("argument 1 must be a map"));
7342 else
7344 // Since this function returns no value it must appear in
7345 // a statement by itself, so we don't have to worry about
7346 // order of evaluation of values around it. Evaluate the
7347 // map first to get order of evaluation right.
7348 Map_type* mt = args->front()->type()->map_type();
7349 Temporary_statement* map_temp =
7350 Statement::make_temporary(mt, args->front(), loc);
7351 inserter->insert(map_temp);
7353 Temporary_statement* key_temp =
7354 Statement::make_temporary(mt->key_type(), args->back(), loc);
7355 inserter->insert(key_temp);
7357 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7358 Expression* e2 = Expression::make_temporary_reference(map_temp,
7359 loc);
7360 Expression* e3 = Expression::make_temporary_reference(key_temp,
7361 loc);
7362 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7363 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7364 3, e1, e2, e3);
7367 break;
7369 case BUILTIN_PRINT:
7370 case BUILTIN_PRINTLN:
7371 // Force all the arguments into temporary variables, so that we
7372 // don't try to evaluate something while holding the print lock.
7373 if (this->args() == NULL)
7374 break;
7375 for (Expression_list::iterator pa = this->args()->begin();
7376 pa != this->args()->end();
7377 ++pa)
7379 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7381 Temporary_statement* temp =
7382 Statement::make_temporary(NULL, *pa, loc);
7383 inserter->insert(temp);
7384 *pa = Expression::make_temporary_reference(temp, loc);
7387 break;
7390 return this;
7393 // Flatten a builtin call expression. This turns the arguments of copy and
7394 // append into temporary expressions.
7396 Expression*
7397 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7398 Statement_inserter* inserter)
7400 Location loc = this->location();
7402 switch (this->code_)
7404 default:
7405 break;
7407 case BUILTIN_APPEND:
7408 return this->flatten_append(gogo, function, inserter);
7410 case BUILTIN_COPY:
7412 Type* at = this->args()->front()->type();
7413 for (Expression_list::iterator pa = this->args()->begin();
7414 pa != this->args()->end();
7415 ++pa)
7417 if ((*pa)->is_nil_expression())
7419 Expression* nil = Expression::make_nil(loc);
7420 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7421 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7423 if (!(*pa)->is_variable())
7425 Temporary_statement* temp =
7426 Statement::make_temporary(NULL, *pa, loc);
7427 inserter->insert(temp);
7428 *pa = Expression::make_temporary_reference(temp, loc);
7432 break;
7434 case BUILTIN_PANIC:
7435 for (Expression_list::iterator pa = this->args()->begin();
7436 pa != this->args()->end();
7437 ++pa)
7439 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7441 Temporary_statement* temp =
7442 Statement::make_temporary(NULL, *pa, loc);
7443 inserter->insert(temp);
7444 *pa = Expression::make_temporary_reference(temp, loc);
7447 break;
7449 case BUILTIN_LEN:
7450 case BUILTIN_CAP:
7452 Expression_list::iterator pa = this->args()->begin();
7453 if (!(*pa)->is_variable()
7454 && ((*pa)->type()->map_type() != NULL
7455 || (*pa)->type()->channel_type() != NULL))
7457 Temporary_statement* temp =
7458 Statement::make_temporary(NULL, *pa, loc);
7459 inserter->insert(temp);
7460 *pa = Expression::make_temporary_reference(temp, loc);
7463 break;
7466 return this;
7469 // Lower a make expression.
7471 Expression*
7472 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7474 Location loc = this->location();
7476 const Expression_list* args = this->args();
7477 if (args == NULL || args->size() < 1)
7479 this->report_error(_("not enough arguments"));
7480 return Expression::make_error(this->location());
7483 Expression_list::const_iterator parg = args->begin();
7485 Expression* first_arg = *parg;
7486 if (!first_arg->is_type_expression())
7488 go_error_at(first_arg->location(), "expected type");
7489 this->set_is_error();
7490 return Expression::make_error(this->location());
7492 Type* type = first_arg->type();
7494 if (!type->in_heap())
7495 go_error_at(first_arg->location(),
7496 "can't make slice of go:notinheap type");
7498 bool is_slice = false;
7499 bool is_map = false;
7500 bool is_chan = false;
7501 if (type->is_slice_type())
7502 is_slice = true;
7503 else if (type->map_type() != NULL)
7504 is_map = true;
7505 else if (type->channel_type() != NULL)
7506 is_chan = true;
7507 else
7509 this->report_error(_("invalid type for make function"));
7510 return Expression::make_error(this->location());
7513 Type_context int_context(Type::lookup_integer_type("int"), false);
7515 ++parg;
7516 Expression* len_arg;
7517 bool len_small = false;
7518 if (parg == args->end())
7520 if (is_slice)
7522 this->report_error(_("length required when allocating a slice"));
7523 return Expression::make_error(this->location());
7525 len_arg = Expression::make_integer_ul(0, NULL, loc);
7526 len_small = true;
7528 else
7530 len_arg = *parg;
7531 len_arg->determine_type(&int_context);
7532 if (len_arg->type()->integer_type() == NULL)
7534 go_error_at(len_arg->location(), "non-integer len argument in make");
7535 return Expression::make_error(this->location());
7537 if (!this->check_int_value(len_arg, true, &len_small))
7538 return Expression::make_error(this->location());
7539 ++parg;
7542 Expression* cap_arg = NULL;
7543 bool cap_small = false;
7544 Numeric_constant nclen;
7545 Numeric_constant nccap;
7546 unsigned long vlen;
7547 unsigned long vcap;
7548 if (is_slice && parg != args->end())
7550 cap_arg = *parg;
7551 cap_arg->determine_type(&int_context);
7552 if (cap_arg->type()->integer_type() == NULL)
7554 go_error_at(cap_arg->location(), "non-integer cap argument in make");
7555 return Expression::make_error(this->location());
7557 if (!this->check_int_value(cap_arg, false, &cap_small))
7558 return Expression::make_error(this->location());
7560 if (len_arg->numeric_constant_value(&nclen)
7561 && cap_arg->numeric_constant_value(&nccap)
7562 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7563 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7564 && vlen > vcap)
7566 this->report_error(_("len larger than cap"));
7567 return Expression::make_error(this->location());
7570 ++parg;
7573 if (parg != args->end())
7575 this->report_error(_("too many arguments to make"));
7576 return Expression::make_error(this->location());
7579 Location type_loc = first_arg->location();
7581 Expression* call;
7582 if (is_slice)
7584 if (cap_arg == NULL)
7586 cap_small = len_small;
7587 if (len_arg->numeric_constant_value(&nclen)
7588 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID)
7589 cap_arg = Expression::make_integer_ul(vlen, len_arg->type(), loc);
7590 else
7592 Temporary_statement* temp = Statement::make_temporary(NULL,
7593 len_arg,
7594 loc);
7595 inserter->insert(temp);
7596 len_arg = Expression::make_temporary_reference(temp, loc);
7597 cap_arg = Expression::make_temporary_reference(temp, loc);
7601 Type* et = type->array_type()->element_type();
7602 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7603 Runtime::Function code = Runtime::MAKESLICE;
7604 if (!len_small || !cap_small)
7605 code = Runtime::MAKESLICE64;
7606 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7608 else if (is_map)
7610 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7611 if (!len_small)
7612 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7613 len_arg,
7614 Expression::make_nil(loc));
7615 else
7617 Numeric_constant nclen;
7618 unsigned long vlen;
7619 if (len_arg->numeric_constant_value(&nclen)
7620 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7621 && vlen <= Map_type::bucket_size)
7622 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7623 else
7624 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7625 len_arg,
7626 Expression::make_nil(loc));
7629 else if (is_chan)
7631 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7632 Runtime::Function code = Runtime::MAKECHAN;
7633 if (!len_small)
7634 code = Runtime::MAKECHAN64;
7635 call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
7637 else
7638 go_unreachable();
7640 return Expression::make_unsafe_cast(type, call, loc);
7643 // Flatten a call to the predeclared append function. We do this in
7644 // the flatten phase, not the lowering phase, so that we run after
7645 // type checking and after order_evaluations.
7647 Expression*
7648 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7649 Statement_inserter* inserter)
7651 if (this->is_error_expression())
7652 return this;
7654 Location loc = this->location();
7656 const Expression_list* args = this->args();
7657 go_assert(args != NULL && !args->empty());
7659 Type* slice_type = args->front()->type();
7660 go_assert(slice_type->is_slice_type());
7661 Type* element_type = slice_type->array_type()->element_type();
7663 if (args->size() == 1)
7665 // append(s) evaluates to s.
7666 return args->front();
7669 Type* int_type = Type::lookup_integer_type("int");
7670 Type* uint_type = Type::lookup_integer_type("uint");
7672 // Implementing
7673 // append(s1, s2...)
7674 // or
7675 // append(s1, a1, a2, a3, ...)
7677 // s1tmp := s1
7678 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7679 loc);
7680 inserter->insert(s1tmp);
7682 // l1tmp := len(s1tmp)
7683 Named_object* lenfn = gogo->lookup_global("len");
7684 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7685 Expression_list* call_args = new Expression_list();
7686 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7687 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7688 gogo->lower_expression(function, inserter, &len);
7689 gogo->flatten_expression(function, inserter, &len);
7690 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7691 inserter->insert(l1tmp);
7693 Temporary_statement* s2tmp = NULL;
7694 Temporary_statement* l2tmp = NULL;
7695 Expression_list* add = NULL;
7696 Expression* len2;
7697 if (this->is_varargs())
7699 go_assert(args->size() == 2);
7701 // s2tmp := s2
7702 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7703 inserter->insert(s2tmp);
7705 // l2tmp := len(s2tmp)
7706 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7707 call_args = new Expression_list();
7708 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7709 len = Expression::make_call(lenref, call_args, false, loc);
7710 gogo->lower_expression(function, inserter, &len);
7711 gogo->flatten_expression(function, inserter, &len);
7712 l2tmp = Statement::make_temporary(int_type, len, loc);
7713 inserter->insert(l2tmp);
7715 // len2 = l2tmp
7716 len2 = Expression::make_temporary_reference(l2tmp, loc);
7718 else
7720 // We have to ensure that all the arguments are in variables
7721 // now, because otherwise if one of them is an index expression
7722 // into the current slice we could overwrite it before we fetch
7723 // it.
7724 add = new Expression_list();
7725 Expression_list::const_iterator pa = args->begin();
7726 for (++pa; pa != args->end(); ++pa)
7728 if ((*pa)->is_variable())
7729 add->push_back(*pa);
7730 else
7732 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7733 loc);
7734 inserter->insert(tmp);
7735 add->push_back(Expression::make_temporary_reference(tmp, loc));
7739 // len2 = len(add)
7740 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7743 // ntmp := l1tmp + len2
7744 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7745 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7746 gogo->lower_expression(function, inserter, &sum);
7747 gogo->flatten_expression(function, inserter, &sum);
7748 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7749 inserter->insert(ntmp);
7751 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7752 // growslice(type, s1tmp, ntmp) :
7753 // s1tmp[:ntmp]
7754 // Using uint here means that if the computation of ntmp overflowed,
7755 // we will call growslice which will panic.
7757 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7758 left = Expression::make_cast(uint_type, left, loc);
7760 Named_object* capfn = gogo->lookup_global("cap");
7761 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7762 call_args = new Expression_list();
7763 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7764 Expression* right = Expression::make_call(capref, call_args, false, loc);
7765 right = Expression::make_cast(uint_type, right, loc);
7767 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7769 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7770 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7771 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7772 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7773 a1, a2, a3);
7774 call = Expression::make_unsafe_cast(slice_type, call, loc);
7776 ref = Expression::make_temporary_reference(s1tmp, loc);
7777 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7778 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7779 // FIXME: Mark this index as not requiring bounds checks.
7780 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7782 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7784 gogo->lower_expression(function, inserter, &rhs);
7785 gogo->flatten_expression(function, inserter, &rhs);
7787 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7788 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7789 inserter->insert(assign);
7791 if (this->is_varargs())
7793 // copy(s1tmp[l1tmp:], s2tmp)
7794 a1 = Expression::make_temporary_reference(s1tmp, loc);
7795 ref = Expression::make_temporary_reference(l1tmp, loc);
7796 Expression* nil = Expression::make_nil(loc);
7797 // FIXME: Mark this index as not requiring bounds checks.
7798 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7800 a2 = Expression::make_temporary_reference(s2tmp, loc);
7802 Named_object* copyfn = gogo->lookup_global("copy");
7803 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7804 call_args = new Expression_list();
7805 call_args->push_back(a1);
7806 call_args->push_back(a2);
7807 call = Expression::make_call(copyref, call_args, false, loc);
7808 gogo->lower_expression(function, inserter, &call);
7809 gogo->flatten_expression(function, inserter, &call);
7810 inserter->insert(Statement::make_statement(call, false));
7812 else
7814 // For each argument:
7815 // s1tmp[l1tmp+i] = a
7816 unsigned long i = 0;
7817 for (Expression_list::const_iterator pa = add->begin();
7818 pa != add->end();
7819 ++pa, ++i)
7821 ref = Expression::make_temporary_reference(s1tmp, loc);
7822 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7823 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7824 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7825 // FIXME: Mark this index as not requiring bounds checks.
7826 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7827 gogo->lower_expression(function, inserter, &lhs);
7828 gogo->flatten_expression(function, inserter, &lhs);
7829 // The flatten pass runs after the write barrier pass, so we
7830 // need to insert a write barrier here if necessary.
7831 if (!gogo->assign_needs_write_barrier(lhs))
7832 assign = Statement::make_assignment(lhs, *pa, loc);
7833 else
7835 Function* f = function == NULL ? NULL : function->func_value();
7836 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7837 lhs, *pa, loc);
7839 inserter->insert(assign);
7843 return Expression::make_temporary_reference(s1tmp, loc);
7846 // Return whether an expression has an integer value. Report an error
7847 // if not. This is used when handling calls to the predeclared make
7848 // function. Set *SMALL if the value is known to fit in type "int".
7850 bool
7851 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7852 bool *small)
7854 *small = false;
7856 Numeric_constant nc;
7857 if (e->numeric_constant_value(&nc))
7859 unsigned long v;
7860 switch (nc.to_unsigned_long(&v))
7862 case Numeric_constant::NC_UL_VALID:
7863 break;
7864 case Numeric_constant::NC_UL_NOTINT:
7865 go_error_at(e->location(), "non-integer %s argument to make",
7866 is_length ? "len" : "cap");
7867 return false;
7868 case Numeric_constant::NC_UL_NEGATIVE:
7869 go_error_at(e->location(), "negative %s argument to make",
7870 is_length ? "len" : "cap");
7871 return false;
7872 case Numeric_constant::NC_UL_BIG:
7873 // We don't want to give a compile-time error for a 64-bit
7874 // value on a 32-bit target.
7875 break;
7878 mpz_t val;
7879 if (!nc.to_int(&val))
7880 go_unreachable();
7881 int bits = mpz_sizeinbase(val, 2);
7882 mpz_clear(val);
7883 Type* int_type = Type::lookup_integer_type("int");
7884 if (bits >= int_type->integer_type()->bits())
7886 go_error_at(e->location(), "%s argument too large for make",
7887 is_length ? "len" : "cap");
7888 return false;
7891 *small = true;
7892 return true;
7895 if (e->type()->integer_type() != NULL)
7897 int ebits = e->type()->integer_type()->bits();
7898 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7900 // We can treat ebits == intbits as small even for an unsigned
7901 // integer type, because we will convert the value to int and
7902 // then reject it in the runtime if it is negative.
7903 *small = ebits <= intbits;
7905 return true;
7908 go_error_at(e->location(), "non-integer %s argument to make",
7909 is_length ? "len" : "cap");
7910 return false;
7913 // Return the type of the real or imag functions, given the type of
7914 // the argument. We need to map complex64 to float32 and complex128
7915 // to float64, so it has to be done by name. This returns NULL if it
7916 // can't figure out the type.
7918 Type*
7919 Builtin_call_expression::real_imag_type(Type* arg_type)
7921 if (arg_type == NULL || arg_type->is_abstract())
7922 return NULL;
7923 Named_type* nt = arg_type->named_type();
7924 if (nt == NULL)
7925 return NULL;
7926 while (nt->real_type()->named_type() != NULL)
7927 nt = nt->real_type()->named_type();
7928 if (nt->name() == "complex64")
7929 return Type::lookup_float_type("float32");
7930 else if (nt->name() == "complex128")
7931 return Type::lookup_float_type("float64");
7932 else
7933 return NULL;
7936 // Return the type of the complex function, given the type of one of the
7937 // argments. Like real_imag_type, we have to map by name.
7939 Type*
7940 Builtin_call_expression::complex_type(Type* arg_type)
7942 if (arg_type == NULL || arg_type->is_abstract())
7943 return NULL;
7944 Named_type* nt = arg_type->named_type();
7945 if (nt == NULL)
7946 return NULL;
7947 while (nt->real_type()->named_type() != NULL)
7948 nt = nt->real_type()->named_type();
7949 if (nt->name() == "float32")
7950 return Type::lookup_complex_type("complex64");
7951 else if (nt->name() == "float64")
7952 return Type::lookup_complex_type("complex128");
7953 else
7954 return NULL;
7957 // Return a single argument, or NULL if there isn't one.
7959 Expression*
7960 Builtin_call_expression::one_arg() const
7962 const Expression_list* args = this->args();
7963 if (args == NULL || args->size() != 1)
7964 return NULL;
7965 return args->front();
7968 // A traversal class which looks for a call or receive expression.
7970 class Find_call_expression : public Traverse
7972 public:
7973 Find_call_expression()
7974 : Traverse(traverse_expressions),
7975 found_(false)
7979 expression(Expression**);
7981 bool
7982 found()
7983 { return this->found_; }
7985 private:
7986 bool found_;
7990 Find_call_expression::expression(Expression** pexpr)
7992 Expression* expr = *pexpr;
7993 if (!expr->is_constant()
7994 && (expr->call_expression() != NULL
7995 || expr->receive_expression() != NULL))
7997 this->found_ = true;
7998 return TRAVERSE_EXIT;
8000 return TRAVERSE_CONTINUE;
8003 // Return whether calling len or cap on EXPR, of array type, is a
8004 // constant. The language spec says "the expressions len(s) and
8005 // cap(s) are constants if the type of s is an array or pointer to an
8006 // array and the expression s does not contain channel receives or
8007 // (non-constant) function calls."
8009 bool
8010 Builtin_call_expression::array_len_is_constant(Expression* expr)
8012 go_assert(expr->type()->deref()->array_type() != NULL
8013 && !expr->type()->deref()->is_slice_type());
8014 if (expr->is_constant())
8015 return true;
8016 Find_call_expression find_call;
8017 Expression::traverse(&expr, &find_call);
8018 return !find_call.found();
8021 // Return whether this is constant: len of a string constant, or len
8022 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
8023 // unsafe.Alignof.
8025 bool
8026 Builtin_call_expression::do_is_constant() const
8028 if (this->is_error_expression())
8029 return true;
8030 switch (this->code_)
8032 case BUILTIN_LEN:
8033 case BUILTIN_CAP:
8035 if (this->seen_)
8036 return false;
8038 Expression* arg = this->one_arg();
8039 if (arg == NULL)
8040 return false;
8041 Type* arg_type = arg->type();
8043 if (arg_type->points_to() != NULL
8044 && arg_type->points_to()->array_type() != NULL
8045 && !arg_type->points_to()->is_slice_type())
8046 arg_type = arg_type->points_to();
8048 if (arg_type->array_type() != NULL
8049 && arg_type->array_type()->length() != NULL
8050 && Builtin_call_expression::array_len_is_constant(arg))
8051 return true;
8053 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8055 this->seen_ = true;
8056 bool ret = arg->is_constant();
8057 this->seen_ = false;
8058 return ret;
8061 break;
8063 case BUILTIN_SIZEOF:
8064 case BUILTIN_ALIGNOF:
8065 return this->one_arg() != NULL;
8067 case BUILTIN_OFFSETOF:
8069 Expression* arg = this->one_arg();
8070 if (arg == NULL)
8071 return false;
8072 return arg->field_reference_expression() != NULL;
8075 case BUILTIN_COMPLEX:
8077 const Expression_list* args = this->args();
8078 if (args != NULL && args->size() == 2)
8079 return args->front()->is_constant() && args->back()->is_constant();
8081 break;
8083 case BUILTIN_REAL:
8084 case BUILTIN_IMAG:
8086 Expression* arg = this->one_arg();
8087 return arg != NULL && arg->is_constant();
8090 default:
8091 break;
8094 return false;
8097 // Return a numeric constant if possible.
8099 bool
8100 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8102 if (this->code_ == BUILTIN_LEN
8103 || this->code_ == BUILTIN_CAP)
8105 Expression* arg = this->one_arg();
8106 if (arg == NULL)
8107 return false;
8108 Type* arg_type = arg->type();
8110 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8112 std::string sval;
8113 if (arg->string_constant_value(&sval))
8115 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8116 sval.length());
8117 return true;
8121 if (arg_type->points_to() != NULL
8122 && arg_type->points_to()->array_type() != NULL
8123 && !arg_type->points_to()->is_slice_type())
8124 arg_type = arg_type->points_to();
8126 if (arg_type->array_type() != NULL
8127 && arg_type->array_type()->length() != NULL)
8129 if (this->seen_)
8130 return false;
8131 Expression* e = arg_type->array_type()->length();
8132 this->seen_ = true;
8133 bool r = e->numeric_constant_value(nc);
8134 this->seen_ = false;
8135 if (r)
8137 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8138 this->location()))
8139 r = false;
8141 return r;
8144 else if (this->code_ == BUILTIN_SIZEOF
8145 || this->code_ == BUILTIN_ALIGNOF)
8147 Expression* arg = this->one_arg();
8148 if (arg == NULL)
8149 return false;
8150 Type* arg_type = arg->type();
8151 if (arg_type->is_error())
8152 return false;
8153 if (arg_type->is_abstract())
8154 return false;
8155 if (this->seen_)
8156 return false;
8158 int64_t ret;
8159 if (this->code_ == BUILTIN_SIZEOF)
8161 this->seen_ = true;
8162 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8163 this->seen_ = false;
8164 if (!ok)
8165 return false;
8167 else if (this->code_ == BUILTIN_ALIGNOF)
8169 bool ok;
8170 this->seen_ = true;
8171 if (arg->field_reference_expression() == NULL)
8172 ok = arg_type->backend_type_align(this->gogo_, &ret);
8173 else
8175 // Calling unsafe.Alignof(s.f) returns the alignment of
8176 // the type of f when it is used as a field in a struct.
8177 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8179 this->seen_ = false;
8180 if (!ok)
8181 return false;
8183 else
8184 go_unreachable();
8186 mpz_t zval;
8187 set_mpz_from_int64(&zval, ret);
8188 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8189 mpz_clear(zval);
8190 return true;
8192 else if (this->code_ == BUILTIN_OFFSETOF)
8194 Expression* arg = this->one_arg();
8195 if (arg == NULL)
8196 return false;
8197 Field_reference_expression* farg = arg->field_reference_expression();
8198 if (farg == NULL)
8199 return false;
8200 if (this->seen_)
8201 return false;
8203 int64_t total_offset = 0;
8204 while (true)
8206 Expression* struct_expr = farg->expr();
8207 Type* st = struct_expr->type();
8208 if (st->struct_type() == NULL)
8209 return false;
8210 if (st->named_type() != NULL)
8211 st->named_type()->convert(this->gogo_);
8212 int64_t offset;
8213 this->seen_ = true;
8214 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8215 farg->field_index(),
8216 &offset);
8217 this->seen_ = false;
8218 if (!ok)
8219 return false;
8220 total_offset += offset;
8221 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8223 // Go up until we reach the original base.
8224 farg = struct_expr->field_reference_expression();
8225 continue;
8227 break;
8229 mpz_t zval;
8230 set_mpz_from_int64(&zval, total_offset);
8231 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8232 mpz_clear(zval);
8233 return true;
8235 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8237 Expression* arg = this->one_arg();
8238 if (arg == NULL)
8239 return false;
8241 Numeric_constant argnc;
8242 if (!arg->numeric_constant_value(&argnc))
8243 return false;
8245 mpc_t val;
8246 if (!argnc.to_complex(&val))
8247 return false;
8249 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8250 if (this->code_ == BUILTIN_REAL)
8251 nc->set_float(type, mpc_realref(val));
8252 else
8253 nc->set_float(type, mpc_imagref(val));
8254 mpc_clear(val);
8255 return true;
8257 else if (this->code_ == BUILTIN_COMPLEX)
8259 const Expression_list* args = this->args();
8260 if (args == NULL || args->size() != 2)
8261 return false;
8263 Numeric_constant rnc;
8264 if (!args->front()->numeric_constant_value(&rnc))
8265 return false;
8266 Numeric_constant inc;
8267 if (!args->back()->numeric_constant_value(&inc))
8268 return false;
8270 if (rnc.type() != NULL
8271 && !rnc.type()->is_abstract()
8272 && inc.type() != NULL
8273 && !inc.type()->is_abstract()
8274 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8275 return false;
8277 mpfr_t r;
8278 if (!rnc.to_float(&r))
8279 return false;
8280 mpfr_t i;
8281 if (!inc.to_float(&i))
8283 mpfr_clear(r);
8284 return false;
8287 Type* arg_type = rnc.type();
8288 if (arg_type == NULL || arg_type->is_abstract())
8289 arg_type = inc.type();
8291 mpc_t val;
8292 mpc_init2(val, mpc_precision);
8293 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8294 mpfr_clear(r);
8295 mpfr_clear(i);
8297 Type* type = Builtin_call_expression::complex_type(arg_type);
8298 nc->set_complex(type, val);
8300 mpc_clear(val);
8302 return true;
8305 return false;
8308 // Give an error if we are discarding the value of an expression which
8309 // should not normally be discarded. We don't give an error for
8310 // discarding the value of an ordinary function call, but we do for
8311 // builtin functions, purely for consistency with the gc compiler.
8313 bool
8314 Builtin_call_expression::do_discarding_value()
8316 switch (this->code_)
8318 case BUILTIN_INVALID:
8319 default:
8320 go_unreachable();
8322 case BUILTIN_APPEND:
8323 case BUILTIN_CAP:
8324 case BUILTIN_COMPLEX:
8325 case BUILTIN_IMAG:
8326 case BUILTIN_LEN:
8327 case BUILTIN_MAKE:
8328 case BUILTIN_NEW:
8329 case BUILTIN_REAL:
8330 case BUILTIN_ALIGNOF:
8331 case BUILTIN_OFFSETOF:
8332 case BUILTIN_SIZEOF:
8333 this->unused_value_error();
8334 return false;
8336 case BUILTIN_CLOSE:
8337 case BUILTIN_COPY:
8338 case BUILTIN_DELETE:
8339 case BUILTIN_PANIC:
8340 case BUILTIN_PRINT:
8341 case BUILTIN_PRINTLN:
8342 case BUILTIN_RECOVER:
8343 return true;
8347 // Return the type.
8349 Type*
8350 Builtin_call_expression::do_type()
8352 if (this->is_error_expression())
8353 return Type::make_error_type();
8354 switch (this->code_)
8356 case BUILTIN_INVALID:
8357 default:
8358 return Type::make_error_type();
8360 case BUILTIN_NEW:
8362 const Expression_list* args = this->args();
8363 if (args == NULL || args->empty())
8364 return Type::make_error_type();
8365 return Type::make_pointer_type(args->front()->type());
8368 case BUILTIN_MAKE:
8370 const Expression_list* args = this->args();
8371 if (args == NULL || args->empty())
8372 return Type::make_error_type();
8373 return args->front()->type();
8376 case BUILTIN_CAP:
8377 case BUILTIN_COPY:
8378 case BUILTIN_LEN:
8379 return Type::lookup_integer_type("int");
8381 case BUILTIN_ALIGNOF:
8382 case BUILTIN_OFFSETOF:
8383 case BUILTIN_SIZEOF:
8384 return Type::lookup_integer_type("uintptr");
8386 case BUILTIN_CLOSE:
8387 case BUILTIN_DELETE:
8388 case BUILTIN_PANIC:
8389 case BUILTIN_PRINT:
8390 case BUILTIN_PRINTLN:
8391 return Type::make_void_type();
8393 case BUILTIN_RECOVER:
8394 return Type::make_empty_interface_type(Linemap::predeclared_location());
8396 case BUILTIN_APPEND:
8398 const Expression_list* args = this->args();
8399 if (args == NULL || args->empty())
8400 return Type::make_error_type();
8401 Type *ret = args->front()->type();
8402 if (!ret->is_slice_type())
8403 return Type::make_error_type();
8404 return ret;
8407 case BUILTIN_REAL:
8408 case BUILTIN_IMAG:
8410 Expression* arg = this->one_arg();
8411 if (arg == NULL)
8412 return Type::make_error_type();
8413 Type* t = arg->type();
8414 if (t->is_abstract())
8415 t = t->make_non_abstract_type();
8416 t = Builtin_call_expression::real_imag_type(t);
8417 if (t == NULL)
8418 t = Type::make_error_type();
8419 return t;
8422 case BUILTIN_COMPLEX:
8424 const Expression_list* args = this->args();
8425 if (args == NULL || args->size() != 2)
8426 return Type::make_error_type();
8427 Type* t = args->front()->type();
8428 if (t->is_abstract())
8430 t = args->back()->type();
8431 if (t->is_abstract())
8432 t = t->make_non_abstract_type();
8434 t = Builtin_call_expression::complex_type(t);
8435 if (t == NULL)
8436 t = Type::make_error_type();
8437 return t;
8442 // Determine the type.
8444 void
8445 Builtin_call_expression::do_determine_type(const Type_context* context)
8447 if (!this->determining_types())
8448 return;
8450 this->fn()->determine_type_no_context();
8452 const Expression_list* args = this->args();
8454 bool is_print;
8455 Type* arg_type = NULL;
8456 Type* trailing_arg_types = NULL;
8457 switch (this->code_)
8459 case BUILTIN_PRINT:
8460 case BUILTIN_PRINTLN:
8461 // Do not force a large integer constant to "int".
8462 is_print = true;
8463 break;
8465 case BUILTIN_REAL:
8466 case BUILTIN_IMAG:
8467 arg_type = Builtin_call_expression::complex_type(context->type);
8468 if (arg_type == NULL)
8469 arg_type = Type::lookup_complex_type("complex128");
8470 is_print = false;
8471 break;
8473 case BUILTIN_COMPLEX:
8475 // For the complex function the type of one operand can
8476 // determine the type of the other, as in a binary expression.
8477 arg_type = Builtin_call_expression::real_imag_type(context->type);
8478 if (arg_type == NULL)
8479 arg_type = Type::lookup_float_type("float64");
8480 if (args != NULL && args->size() == 2)
8482 Type* t1 = args->front()->type();
8483 Type* t2 = args->back()->type();
8484 if (!t1->is_abstract())
8485 arg_type = t1;
8486 else if (!t2->is_abstract())
8487 arg_type = t2;
8489 is_print = false;
8491 break;
8493 case BUILTIN_APPEND:
8494 if (!this->is_varargs()
8495 && args != NULL
8496 && !args->empty()
8497 && args->front()->type()->is_slice_type())
8498 trailing_arg_types =
8499 args->front()->type()->array_type()->element_type();
8500 is_print = false;
8501 break;
8503 default:
8504 is_print = false;
8505 break;
8508 if (args != NULL)
8510 for (Expression_list::const_iterator pa = args->begin();
8511 pa != args->end();
8512 ++pa)
8514 Type_context subcontext;
8515 subcontext.type = arg_type;
8517 if (is_print)
8519 // We want to print large constants, we so can't just
8520 // use the appropriate nonabstract type. Use uint64 for
8521 // an integer if we know it is nonnegative, otherwise
8522 // use int64 for a integer, otherwise use float64 for a
8523 // float or complex128 for a complex.
8524 Type* want_type = NULL;
8525 Type* atype = (*pa)->type();
8526 if (atype->is_abstract())
8528 if (atype->integer_type() != NULL)
8530 Numeric_constant nc;
8531 if (this->numeric_constant_value(&nc))
8533 mpz_t val;
8534 if (nc.to_int(&val))
8536 if (mpz_sgn(val) >= 0)
8537 want_type = Type::lookup_integer_type("uint64");
8538 mpz_clear(val);
8541 if (want_type == NULL)
8542 want_type = Type::lookup_integer_type("int64");
8544 else if (atype->float_type() != NULL)
8545 want_type = Type::lookup_float_type("float64");
8546 else if (atype->complex_type() != NULL)
8547 want_type = Type::lookup_complex_type("complex128");
8548 else if (atype->is_abstract_string_type())
8549 want_type = Type::lookup_string_type();
8550 else if (atype->is_abstract_boolean_type())
8551 want_type = Type::lookup_bool_type();
8552 else
8553 go_unreachable();
8554 subcontext.type = want_type;
8558 (*pa)->determine_type(&subcontext);
8560 if (trailing_arg_types != NULL)
8562 arg_type = trailing_arg_types;
8563 trailing_arg_types = NULL;
8569 // If there is exactly one argument, return true. Otherwise give an
8570 // error message and return false.
8572 bool
8573 Builtin_call_expression::check_one_arg()
8575 const Expression_list* args = this->args();
8576 if (args == NULL || args->size() < 1)
8578 this->report_error(_("not enough arguments"));
8579 return false;
8581 else if (args->size() > 1)
8583 this->report_error(_("too many arguments"));
8584 return false;
8586 if (args->front()->is_error_expression()
8587 || args->front()->type()->is_error())
8589 this->set_is_error();
8590 return false;
8592 return true;
8595 // Check argument types for a builtin function.
8597 void
8598 Builtin_call_expression::do_check_types(Gogo*)
8600 if (this->is_error_expression())
8601 return;
8602 switch (this->code_)
8604 case BUILTIN_INVALID:
8605 case BUILTIN_NEW:
8606 case BUILTIN_MAKE:
8607 case BUILTIN_DELETE:
8608 return;
8610 case BUILTIN_LEN:
8611 case BUILTIN_CAP:
8613 // The single argument may be either a string or an array or a
8614 // map or a channel, or a pointer to a closed array.
8615 if (this->check_one_arg())
8617 Type* arg_type = this->one_arg()->type();
8618 if (arg_type->points_to() != NULL
8619 && arg_type->points_to()->array_type() != NULL
8620 && !arg_type->points_to()->is_slice_type())
8621 arg_type = arg_type->points_to();
8622 if (this->code_ == BUILTIN_CAP)
8624 if (!arg_type->is_error()
8625 && arg_type->array_type() == NULL
8626 && arg_type->channel_type() == NULL)
8627 this->report_error(_("argument must be array or slice "
8628 "or channel"));
8630 else
8632 if (!arg_type->is_error()
8633 && !arg_type->is_string_type()
8634 && arg_type->array_type() == NULL
8635 && arg_type->map_type() == NULL
8636 && arg_type->channel_type() == NULL)
8637 this->report_error(_("argument must be string or "
8638 "array or slice or map or channel"));
8642 break;
8644 case BUILTIN_PRINT:
8645 case BUILTIN_PRINTLN:
8647 const Expression_list* args = this->args();
8648 if (args == NULL)
8650 if (this->code_ == BUILTIN_PRINT)
8651 go_warning_at(this->location(), 0,
8652 "no arguments for builtin function %<%s%>",
8653 (this->code_ == BUILTIN_PRINT
8654 ? "print"
8655 : "println"));
8657 else
8659 for (Expression_list::const_iterator p = args->begin();
8660 p != args->end();
8661 ++p)
8663 Type* type = (*p)->type();
8664 if (type->is_error()
8665 || type->is_string_type()
8666 || type->integer_type() != NULL
8667 || type->float_type() != NULL
8668 || type->complex_type() != NULL
8669 || type->is_boolean_type()
8670 || type->points_to() != NULL
8671 || type->interface_type() != NULL
8672 || type->channel_type() != NULL
8673 || type->map_type() != NULL
8674 || type->function_type() != NULL
8675 || type->is_slice_type())
8677 else if ((*p)->is_type_expression())
8679 // If this is a type expression it's going to give
8680 // an error anyhow, so we don't need one here.
8682 else
8683 this->report_error(_("unsupported argument type to "
8684 "builtin function"));
8688 break;
8690 case BUILTIN_CLOSE:
8691 if (this->check_one_arg())
8693 if (this->one_arg()->type()->channel_type() == NULL)
8694 this->report_error(_("argument must be channel"));
8695 else if (!this->one_arg()->type()->channel_type()->may_send())
8696 this->report_error(_("cannot close receive-only channel"));
8698 break;
8700 case BUILTIN_PANIC:
8701 case BUILTIN_SIZEOF:
8702 case BUILTIN_ALIGNOF:
8703 this->check_one_arg();
8704 break;
8706 case BUILTIN_RECOVER:
8707 if (this->args() != NULL
8708 && !this->args()->empty()
8709 && !this->recover_arg_is_set_)
8710 this->report_error(_("too many arguments"));
8711 break;
8713 case BUILTIN_OFFSETOF:
8714 if (this->check_one_arg())
8716 Expression* arg = this->one_arg();
8717 if (arg->field_reference_expression() == NULL)
8718 this->report_error(_("argument must be a field reference"));
8720 break;
8722 case BUILTIN_COPY:
8724 const Expression_list* args = this->args();
8725 if (args == NULL || args->size() < 2)
8727 this->report_error(_("not enough arguments"));
8728 break;
8730 else if (args->size() > 2)
8732 this->report_error(_("too many arguments"));
8733 break;
8735 Type* arg1_type = args->front()->type();
8736 Type* arg2_type = args->back()->type();
8737 if (arg1_type->is_error() || arg2_type->is_error())
8739 this->set_is_error();
8740 break;
8743 Type* e1;
8744 if (arg1_type->is_slice_type())
8745 e1 = arg1_type->array_type()->element_type();
8746 else
8748 this->report_error(_("left argument must be a slice"));
8749 break;
8752 if (arg2_type->is_slice_type())
8754 Type* e2 = arg2_type->array_type()->element_type();
8755 if (!Type::are_identical(e1, e2, true, NULL))
8756 this->report_error(_("element types must be the same"));
8758 else if (arg2_type->is_string_type())
8760 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8761 this->report_error(_("first argument must be []byte"));
8763 else
8764 this->report_error(_("second argument must be slice or string"));
8766 break;
8768 case BUILTIN_APPEND:
8770 const Expression_list* args = this->args();
8771 if (args == NULL || args->empty())
8773 this->report_error(_("not enough arguments"));
8774 break;
8777 Type* slice_type = args->front()->type();
8778 if (!slice_type->is_slice_type())
8780 if (slice_type->is_error_type())
8781 break;
8782 if (slice_type->is_nil_type())
8783 go_error_at(args->front()->location(), "use of untyped nil");
8784 else
8785 go_error_at(args->front()->location(),
8786 "argument 1 must be a slice");
8787 this->set_is_error();
8788 break;
8791 Type* element_type = slice_type->array_type()->element_type();
8792 if (!element_type->in_heap())
8793 go_error_at(args->front()->location(),
8794 "can't append to slice of go:notinheap type");
8795 if (this->is_varargs())
8797 if (!args->back()->type()->is_slice_type()
8798 && !args->back()->type()->is_string_type())
8800 go_error_at(args->back()->location(),
8801 "invalid use of %<...%> with non-slice/non-string");
8802 this->set_is_error();
8803 break;
8806 if (args->size() < 2)
8808 this->report_error(_("not enough arguments"));
8809 break;
8811 if (args->size() > 2)
8813 this->report_error(_("too many arguments"));
8814 break;
8817 if (args->back()->type()->is_string_type()
8818 && element_type->integer_type() != NULL
8819 && element_type->integer_type()->is_byte())
8821 // Permit append(s1, s2...) when s1 is a slice of
8822 // bytes and s2 is a string type.
8824 else
8826 // We have to test for assignment compatibility to a
8827 // slice of the element type, which is not necessarily
8828 // the same as the type of the first argument: the
8829 // first argument might have a named type.
8830 Type* check_type = Type::make_array_type(element_type, NULL);
8831 std::string reason;
8832 if (!Type::are_assignable(check_type, args->back()->type(),
8833 &reason))
8835 if (reason.empty())
8836 go_error_at(args->back()->location(),
8837 "argument 2 has invalid type");
8838 else
8839 go_error_at(args->back()->location(),
8840 "argument 2 has invalid type (%s)",
8841 reason.c_str());
8842 this->set_is_error();
8843 break;
8847 else
8849 Expression_list::const_iterator pa = args->begin();
8850 int i = 2;
8851 for (++pa; pa != args->end(); ++pa, ++i)
8853 std::string reason;
8854 if (!Type::are_assignable(element_type, (*pa)->type(),
8855 &reason))
8857 if (reason.empty())
8858 go_error_at((*pa)->location(),
8859 "argument %d has incompatible type", i);
8860 else
8861 go_error_at((*pa)->location(),
8862 "argument %d has incompatible type (%s)",
8863 i, reason.c_str());
8864 this->set_is_error();
8869 break;
8871 case BUILTIN_REAL:
8872 case BUILTIN_IMAG:
8873 if (this->check_one_arg())
8875 if (this->one_arg()->type()->complex_type() == NULL)
8876 this->report_error(_("argument must have complex type"));
8878 break;
8880 case BUILTIN_COMPLEX:
8882 const Expression_list* args = this->args();
8883 if (args == NULL || args->size() < 2)
8884 this->report_error(_("not enough arguments"));
8885 else if (args->size() > 2)
8886 this->report_error(_("too many arguments"));
8887 else if (args->front()->is_error_expression()
8888 || args->front()->type()->is_error()
8889 || args->back()->is_error_expression()
8890 || args->back()->type()->is_error())
8891 this->set_is_error();
8892 else if (!Type::are_identical(args->front()->type(),
8893 args->back()->type(), true, NULL))
8894 this->report_error(_("complex arguments must have identical types"));
8895 else if (args->front()->type()->float_type() == NULL)
8896 this->report_error(_("complex arguments must have "
8897 "floating-point type"));
8899 break;
8901 default:
8902 go_unreachable();
8906 Expression*
8907 Builtin_call_expression::do_copy()
8909 Call_expression* bce =
8910 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8911 (this->args() == NULL
8912 ? NULL
8913 : this->args()->copy()),
8914 this->is_varargs(),
8915 this->location());
8917 if (this->varargs_are_lowered())
8918 bce->set_varargs_are_lowered();
8919 return bce;
8922 // Return the backend representation for a builtin function.
8924 Bexpression*
8925 Builtin_call_expression::do_get_backend(Translate_context* context)
8927 Gogo* gogo = context->gogo();
8928 Location location = this->location();
8930 if (this->is_erroneous_call())
8932 go_assert(saw_errors());
8933 return gogo->backend()->error_expression();
8936 switch (this->code_)
8938 case BUILTIN_INVALID:
8939 case BUILTIN_NEW:
8940 case BUILTIN_MAKE:
8941 go_unreachable();
8943 case BUILTIN_LEN:
8944 case BUILTIN_CAP:
8946 const Expression_list* args = this->args();
8947 go_assert(args != NULL && args->size() == 1);
8948 Expression* arg = args->front();
8949 Type* arg_type = arg->type();
8951 if (this->seen_)
8953 go_assert(saw_errors());
8954 return context->backend()->error_expression();
8956 this->seen_ = true;
8957 this->seen_ = false;
8958 if (arg_type->points_to() != NULL)
8960 arg_type = arg_type->points_to();
8961 go_assert(arg_type->array_type() != NULL
8962 && !arg_type->is_slice_type());
8963 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
8964 location);
8967 Type* int_type = Type::lookup_integer_type("int");
8968 Expression* val;
8969 if (this->code_ == BUILTIN_LEN)
8971 if (arg_type->is_string_type())
8972 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8973 location);
8974 else if (arg_type->array_type() != NULL)
8976 if (this->seen_)
8978 go_assert(saw_errors());
8979 return context->backend()->error_expression();
8981 this->seen_ = true;
8982 val = arg_type->array_type()->get_length(gogo, arg);
8983 this->seen_ = false;
8985 else if (arg_type->map_type() != NULL
8986 || arg_type->channel_type() != NULL)
8988 // The first field is the length. If the pointer is
8989 // nil, the length is zero.
8990 Type* pint_type = Type::make_pointer_type(int_type);
8991 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8992 Expression* nil = Expression::make_nil(location);
8993 nil = Expression::make_cast(pint_type, nil, location);
8994 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8995 arg, nil, location);
8996 Expression* zero = Expression::make_integer_ul(0, int_type,
8997 location);
8998 Expression* indir =
8999 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
9000 location);
9001 val = Expression::make_conditional(cmp, zero, indir, location);
9003 else
9004 go_unreachable();
9006 else
9008 if (arg_type->array_type() != NULL)
9010 if (this->seen_)
9012 go_assert(saw_errors());
9013 return context->backend()->error_expression();
9015 this->seen_ = true;
9016 val = arg_type->array_type()->get_capacity(gogo, arg);
9017 this->seen_ = false;
9019 else if (arg_type->channel_type() != NULL)
9021 // The second field is the capacity. If the pointer
9022 // is nil, the capacity is zero.
9023 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9024 Type* pint_type = Type::make_pointer_type(int_type);
9025 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
9026 arg,
9027 location);
9028 int off = int_type->integer_type()->bits() / 8;
9029 Expression* eoff = Expression::make_integer_ul(off,
9030 uintptr_type,
9031 location);
9032 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
9033 location);
9034 parg = Expression::make_unsafe_cast(pint_type, parg, location);
9035 Expression* nil = Expression::make_nil(location);
9036 nil = Expression::make_cast(pint_type, nil, location);
9037 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9038 arg, nil, location);
9039 Expression* zero = Expression::make_integer_ul(0, int_type,
9040 location);
9041 Expression* indir =
9042 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
9043 location);
9044 val = Expression::make_conditional(cmp, zero, indir, location);
9046 else
9047 go_unreachable();
9050 return Expression::make_cast(int_type, val,
9051 location)->get_backend(context);
9054 case BUILTIN_PRINT:
9055 case BUILTIN_PRINTLN:
9057 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
9059 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9060 location, 0);
9062 const Expression_list* call_args = this->args();
9063 if (call_args != NULL)
9065 for (Expression_list::const_iterator p = call_args->begin();
9066 p != call_args->end();
9067 ++p)
9069 if (is_ln && p != call_args->begin())
9071 Expression* print_space =
9072 Runtime::make_call(Runtime::PRINTSP, location, 0);
9074 print_stmts =
9075 Expression::make_compound(print_stmts, print_space,
9076 location);
9079 Expression* arg = *p;
9080 Type* type = arg->type();
9081 Runtime::Function code;
9082 if (type->is_string_type())
9083 code = Runtime::PRINTSTRING;
9084 else if (type->integer_type() != NULL
9085 && type->integer_type()->is_unsigned())
9087 Type* itype = Type::lookup_integer_type("uint64");
9088 arg = Expression::make_cast(itype, arg, location);
9089 code = Runtime::PRINTUINT;
9091 else if (type->integer_type() != NULL)
9093 Type* itype = Type::lookup_integer_type("int64");
9094 arg = Expression::make_cast(itype, arg, location);
9095 code = Runtime::PRINTINT;
9097 else if (type->float_type() != NULL)
9099 Type* dtype = Type::lookup_float_type("float64");
9100 arg = Expression::make_cast(dtype, arg, location);
9101 code = Runtime::PRINTFLOAT;
9103 else if (type->complex_type() != NULL)
9105 Type* ctype = Type::lookup_complex_type("complex128");
9106 arg = Expression::make_cast(ctype, arg, location);
9107 code = Runtime::PRINTCOMPLEX;
9109 else if (type->is_boolean_type())
9110 code = Runtime::PRINTBOOL;
9111 else if (type->points_to() != NULL
9112 || type->channel_type() != NULL
9113 || type->map_type() != NULL
9114 || type->function_type() != NULL)
9116 arg = Expression::make_cast(type, arg, location);
9117 code = Runtime::PRINTPOINTER;
9119 else if (type->interface_type() != NULL)
9121 if (type->interface_type()->is_empty())
9122 code = Runtime::PRINTEFACE;
9123 else
9124 code = Runtime::PRINTIFACE;
9126 else if (type->is_slice_type())
9127 code = Runtime::PRINTSLICE;
9128 else
9130 go_assert(saw_errors());
9131 return context->backend()->error_expression();
9134 Expression* call = Runtime::make_call(code, location, 1, arg);
9135 print_stmts = Expression::make_compound(print_stmts, call,
9136 location);
9140 if (is_ln)
9142 Expression* print_nl =
9143 Runtime::make_call(Runtime::PRINTNL, location, 0);
9144 print_stmts = Expression::make_compound(print_stmts, print_nl,
9145 location);
9148 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9149 location, 0);
9150 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9152 return print_stmts->get_backend(context);
9155 case BUILTIN_PANIC:
9157 const Expression_list* args = this->args();
9158 go_assert(args != NULL && args->size() == 1);
9159 Expression* arg = args->front();
9160 Type *empty =
9161 Type::make_empty_interface_type(Linemap::predeclared_location());
9162 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9164 Expression* panic =
9165 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9166 return panic->get_backend(context);
9169 case BUILTIN_RECOVER:
9171 // The argument is set when building recover thunks. It's a
9172 // boolean value which is true if we can recover a value now.
9173 const Expression_list* args = this->args();
9174 go_assert(args != NULL && args->size() == 1);
9175 Expression* arg = args->front();
9176 Type *empty =
9177 Type::make_empty_interface_type(Linemap::predeclared_location());
9179 Expression* nil = Expression::make_nil(location);
9180 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9182 // We need to handle a deferred call to recover specially,
9183 // because it changes whether it can recover a panic or not.
9184 // See test7 in test/recover1.go.
9185 Expression* recover = Runtime::make_call((this->is_deferred()
9186 ? Runtime::DEFERREDRECOVER
9187 : Runtime::GORECOVER),
9188 location, 0);
9189 Expression* cond =
9190 Expression::make_conditional(arg, recover, nil, location);
9191 return cond->get_backend(context);
9194 case BUILTIN_CLOSE:
9196 const Expression_list* args = this->args();
9197 go_assert(args != NULL && args->size() == 1);
9198 Expression* arg = args->front();
9199 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9200 1, arg);
9201 return close->get_backend(context);
9204 case BUILTIN_SIZEOF:
9205 case BUILTIN_OFFSETOF:
9206 case BUILTIN_ALIGNOF:
9208 Numeric_constant nc;
9209 unsigned long val;
9210 if (!this->numeric_constant_value(&nc)
9211 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9213 go_assert(saw_errors());
9214 return context->backend()->error_expression();
9216 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9217 mpz_t ival;
9218 nc.get_int(&ival);
9219 Expression* int_cst =
9220 Expression::make_integer_z(&ival, uintptr_type, location);
9221 mpz_clear(ival);
9222 return int_cst->get_backend(context);
9225 case BUILTIN_COPY:
9227 const Expression_list* args = this->args();
9228 go_assert(args != NULL && args->size() == 2);
9229 Expression* arg1 = args->front();
9230 Expression* arg2 = args->back();
9232 Type* arg1_type = arg1->type();
9233 Array_type* at = arg1_type->array_type();
9234 go_assert(arg1->is_variable());
9236 Expression* call;
9238 Type* arg2_type = arg2->type();
9239 go_assert(arg2->is_variable());
9240 if (arg2_type->is_string_type())
9241 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9242 2, arg1, arg2);
9243 else
9245 Type* et = at->element_type();
9246 if (et->has_pointer())
9248 Expression* td = Expression::make_type_descriptor(et,
9249 location);
9250 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9251 3, td, arg1, arg2);
9253 else
9255 Expression* sz = Expression::make_type_info(et,
9256 TYPE_INFO_SIZE);
9257 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9258 arg1, arg2, sz);
9262 return call->get_backend(context);
9265 case BUILTIN_APPEND:
9266 // Handled in Builtin_call_expression::flatten_append.
9267 go_unreachable();
9269 case BUILTIN_REAL:
9270 case BUILTIN_IMAG:
9272 const Expression_list* args = this->args();
9273 go_assert(args != NULL && args->size() == 1);
9275 Bexpression* ret;
9276 Bexpression* bcomplex = args->front()->get_backend(context);
9277 if (this->code_ == BUILTIN_REAL)
9278 ret = gogo->backend()->real_part_expression(bcomplex, location);
9279 else
9280 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9281 return ret;
9284 case BUILTIN_COMPLEX:
9286 const Expression_list* args = this->args();
9287 go_assert(args != NULL && args->size() == 2);
9288 Bexpression* breal = args->front()->get_backend(context);
9289 Bexpression* bimag = args->back()->get_backend(context);
9290 return gogo->backend()->complex_expression(breal, bimag, location);
9293 default:
9294 go_unreachable();
9298 // We have to support exporting a builtin call expression, because
9299 // code can set a constant to the result of a builtin expression.
9301 void
9302 Builtin_call_expression::do_export(Export* exp) const
9304 Numeric_constant nc;
9305 if (!this->numeric_constant_value(&nc))
9307 go_error_at(this->location(), "value is not constant");
9308 return;
9311 if (nc.is_int())
9313 mpz_t val;
9314 nc.get_int(&val);
9315 Integer_expression::export_integer(exp, val);
9316 mpz_clear(val);
9318 else if (nc.is_float())
9320 mpfr_t fval;
9321 nc.get_float(&fval);
9322 Float_expression::export_float(exp, fval);
9323 mpfr_clear(fval);
9325 else if (nc.is_complex())
9327 mpc_t cval;
9328 nc.get_complex(&cval);
9329 Complex_expression::export_complex(exp, cval);
9330 mpc_clear(cval);
9332 else
9333 go_unreachable();
9335 // A trailing space lets us reliably identify the end of the number.
9336 exp->write_c_string(" ");
9339 // Class Call_expression.
9341 // A Go function can be viewed in a couple of different ways. The
9342 // code of a Go function becomes a backend function with parameters
9343 // whose types are simply the backend representation of the Go types.
9344 // If there are multiple results, they are returned as a backend
9345 // struct.
9347 // However, when Go code refers to a function other than simply
9348 // calling it, the backend type of that function is actually a struct.
9349 // The first field of the struct points to the Go function code
9350 // (sometimes a wrapper as described below). The remaining fields
9351 // hold addresses of closed-over variables. This struct is called a
9352 // closure.
9354 // There are a few cases to consider.
9356 // A direct function call of a known function in package scope. In
9357 // this case there are no closed-over variables, and we know the name
9358 // of the function code. We can simply produce a backend call to the
9359 // function directly, and not worry about the closure.
9361 // A direct function call of a known function literal. In this case
9362 // we know the function code and we know the closure. We generate the
9363 // function code such that it expects an additional final argument of
9364 // the closure type. We pass the closure as the last argument, after
9365 // the other arguments.
9367 // An indirect function call. In this case we have a closure. We
9368 // load the pointer to the function code from the first field of the
9369 // closure. We pass the address of the closure as the last argument.
9371 // A call to a method of an interface. Type methods are always at
9372 // package scope, so we call the function directly, and don't worry
9373 // about the closure.
9375 // This means that for a function at package scope we have two cases.
9376 // One is the direct call, which has no closure. The other is the
9377 // indirect call, which does have a closure. We can't simply ignore
9378 // the closure, even though it is the last argument, because that will
9379 // fail on targets where the function pops its arguments. So when
9380 // generating a closure for a package-scope function we set the
9381 // function code pointer in the closure to point to a wrapper
9382 // function. This wrapper function accepts a final argument that
9383 // points to the closure, ignores it, and calls the real function as a
9384 // direct function call. This wrapper will normally be efficient, and
9385 // can often simply be a tail call to the real function.
9387 // We don't use GCC's static chain pointer because 1) we don't need
9388 // it; 2) GCC only permits using a static chain to call a known
9389 // function, so we can't use it for an indirect call anyhow. Since we
9390 // can't use it for an indirect call, we may as well not worry about
9391 // using it for a direct call either.
9393 // We pass the closure last rather than first because it means that
9394 // the function wrapper we put into a closure for a package-scope
9395 // function can normally just be a tail call to the real function.
9397 // For method expressions we generate a wrapper that loads the
9398 // receiver from the closure and then calls the method. This
9399 // unfortunately forces reshuffling the arguments, since there is a
9400 // new first argument, but we can't avoid reshuffling either for
9401 // method expressions or for indirect calls of package-scope
9402 // functions, and since the latter are more common we reshuffle for
9403 // method expressions.
9405 // Note that the Go code retains the Go types. The extra final
9406 // argument only appears when we convert to the backend
9407 // representation.
9409 // Traversal.
9412 Call_expression::do_traverse(Traverse* traverse)
9414 // If we are calling a function in a different package that returns
9415 // an unnamed type, this may be the only chance we get to traverse
9416 // that type. We don't traverse this->type_ because it may be a
9417 // Call_multiple_result_type that will just lead back here.
9418 if (this->type_ != NULL && !this->type_->is_error_type())
9420 Function_type *fntype = this->get_function_type();
9421 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9422 return TRAVERSE_EXIT;
9424 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9425 return TRAVERSE_EXIT;
9426 if (this->args_ != NULL)
9428 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9429 return TRAVERSE_EXIT;
9431 return TRAVERSE_CONTINUE;
9434 // Lower a call statement.
9436 Expression*
9437 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9438 Statement_inserter* inserter, int)
9440 Location loc = this->location();
9442 // A type cast can look like a function call.
9443 if (this->fn_->is_type_expression()
9444 && this->args_ != NULL
9445 && this->args_->size() == 1)
9446 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9447 loc);
9449 // Because do_type will return an error type and thus prevent future
9450 // errors, check for that case now to ensure that the error gets
9451 // reported.
9452 Function_type* fntype = this->get_function_type();
9453 if (fntype == NULL)
9455 if (!this->fn_->type()->is_error())
9456 this->report_error(_("expected function"));
9457 this->set_is_error();
9458 return this;
9461 // Handle an argument which is a call to a function which returns
9462 // multiple results.
9463 if (this->args_ != NULL
9464 && this->args_->size() == 1
9465 && this->args_->front()->call_expression() != NULL)
9467 size_t rc = this->args_->front()->call_expression()->result_count();
9468 if (rc > 1
9469 && ((fntype->parameters() != NULL
9470 && (fntype->parameters()->size() == rc
9471 || (fntype->is_varargs()
9472 && fntype->parameters()->size() - 1 <= rc)))
9473 || fntype->is_builtin()))
9475 Call_expression* call = this->args_->front()->call_expression();
9476 call->set_is_multi_value_arg();
9477 if (this->is_varargs_)
9479 // It is not clear which result of a multiple result call
9480 // the ellipsis operator should be applied to. If we unpack the
9481 // the call into its individual results here, the ellipsis will be
9482 // applied to the last result.
9483 go_error_at(call->location(),
9484 _("multiple-value argument in single-value context"));
9485 return Expression::make_error(call->location());
9488 Expression_list* args = new Expression_list;
9489 for (size_t i = 0; i < rc; ++i)
9490 args->push_back(Expression::make_call_result(call, i));
9491 // We can't return a new call expression here, because this
9492 // one may be referenced by Call_result expressions. We
9493 // also can't delete the old arguments, because we may still
9494 // traverse them somewhere up the call stack. FIXME.
9495 this->args_ = args;
9499 // Recognize a call to a builtin function.
9500 if (fntype->is_builtin())
9501 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9502 this->is_varargs_, loc);
9504 // If this call returns multiple results, create a temporary
9505 // variable to hold them.
9506 if (this->result_count() > 1 && this->call_temp_ == NULL)
9508 Struct_field_list* sfl = new Struct_field_list();
9509 Function_type* fntype = this->get_function_type();
9510 const Typed_identifier_list* results = fntype->results();
9511 Location loc = this->location();
9513 int i = 0;
9514 char buf[20];
9515 for (Typed_identifier_list::const_iterator p = results->begin();
9516 p != results->end();
9517 ++p, ++i)
9519 snprintf(buf, sizeof buf, "res%d", i);
9520 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9523 Struct_type* st = Type::make_struct_type(sfl, loc);
9524 st->set_is_struct_incomparable();
9525 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9526 inserter->insert(this->call_temp_);
9529 // Handle a call to a varargs function by packaging up the extra
9530 // parameters.
9531 if (fntype->is_varargs())
9533 const Typed_identifier_list* parameters = fntype->parameters();
9534 go_assert(parameters != NULL && !parameters->empty());
9535 Type* varargs_type = parameters->back().type();
9536 this->lower_varargs(gogo, function, inserter, varargs_type,
9537 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9540 // If this is call to a method, call the method directly passing the
9541 // object as the first parameter.
9542 Bound_method_expression* bme = this->fn_->bound_method_expression();
9543 if (bme != NULL)
9545 Named_object* methodfn = bme->function();
9546 Expression* first_arg = bme->first_argument();
9548 // We always pass a pointer when calling a method.
9549 if (first_arg->type()->points_to() == NULL
9550 && !first_arg->type()->is_error())
9552 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9553 // We may need to create a temporary variable so that we can
9554 // take the address. We can't do that here because it will
9555 // mess up the order of evaluation.
9556 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9557 ue->set_create_temp();
9560 // If we are calling a method which was inherited from an
9561 // embedded struct, and the method did not get a stub, then the
9562 // first type may be wrong.
9563 Type* fatype = bme->first_argument_type();
9564 if (fatype != NULL)
9566 if (fatype->points_to() == NULL)
9567 fatype = Type::make_pointer_type(fatype);
9568 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9571 Expression_list* new_args = new Expression_list();
9572 new_args->push_back(first_arg);
9573 if (this->args_ != NULL)
9575 for (Expression_list::const_iterator p = this->args_->begin();
9576 p != this->args_->end();
9577 ++p)
9578 new_args->push_back(*p);
9581 // We have to change in place because this structure may be
9582 // referenced by Call_result_expressions. We can't delete the
9583 // old arguments, because we may be traversing them up in some
9584 // caller. FIXME.
9585 this->args_ = new_args;
9586 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9587 bme->location());
9590 // Handle a couple of special runtime functions. In the runtime
9591 // package, getcallerpc returns the PC of the caller, and
9592 // getcallersp returns the frame pointer of the caller. Implement
9593 // these by turning them into calls to GCC builtin functions. We
9594 // could implement them in normal code, but then we would have to
9595 // explicitly unwind the stack. These functions are intended to be
9596 // efficient. Note that this technique obviously only works for
9597 // direct calls, but that is the only way they are used.
9598 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9600 Func_expression* fe = this->fn_->func_expression();
9601 if (fe != NULL
9602 && fe->named_object()->is_function_declaration()
9603 && fe->named_object()->package() == NULL)
9605 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9606 if ((this->args_ == NULL || this->args_->size() == 0)
9607 && n == "getcallerpc")
9609 static Named_object* builtin_return_address;
9610 return this->lower_to_builtin(&builtin_return_address,
9611 "__builtin_return_address",
9614 else if (this->args_ != NULL
9615 && this->args_->size() == 1
9616 && n == "getcallersp")
9618 // The actual argument to getcallersp is always the
9619 // address of a parameter; we don't need that for the
9620 // GCC builtin function, so we just ignore it.
9621 static Named_object* builtin_frame_address;
9622 return this->lower_to_builtin(&builtin_frame_address,
9623 "__builtin_frame_address",
9629 return this;
9632 // Lower a call to a varargs function. FUNCTION is the function in
9633 // which the call occurs--it's not the function we are calling.
9634 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9635 // PARAM_COUNT is the number of parameters of the function we are
9636 // calling; the last of these parameters will be the varargs
9637 // parameter.
9639 void
9640 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9641 Statement_inserter* inserter,
9642 Type* varargs_type, size_t param_count,
9643 Slice_storage_escape_disp escape_disp)
9645 if (this->varargs_are_lowered_)
9646 return;
9648 Location loc = this->location();
9650 go_assert(param_count > 0);
9651 go_assert(varargs_type->is_slice_type());
9653 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9654 if (arg_count < param_count - 1)
9656 // Not enough arguments; will be caught in check_types.
9657 return;
9660 Expression_list* old_args = this->args_;
9661 Expression_list* new_args = new Expression_list();
9662 bool push_empty_arg = false;
9663 if (old_args == NULL || old_args->empty())
9665 go_assert(param_count == 1);
9666 push_empty_arg = true;
9668 else
9670 Expression_list::const_iterator pa;
9671 int i = 1;
9672 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9674 if (static_cast<size_t>(i) == param_count)
9675 break;
9676 new_args->push_back(*pa);
9679 // We have reached the varargs parameter.
9681 bool issued_error = false;
9682 if (pa == old_args->end())
9683 push_empty_arg = true;
9684 else if (pa + 1 == old_args->end() && this->is_varargs_)
9685 new_args->push_back(*pa);
9686 else if (this->is_varargs_)
9688 if ((*pa)->type()->is_slice_type())
9689 this->report_error(_("too many arguments"));
9690 else
9692 go_error_at(this->location(),
9693 _("invalid use of %<...%> with non-slice"));
9694 this->set_is_error();
9696 return;
9698 else
9700 Type* element_type = varargs_type->array_type()->element_type();
9701 Expression_list* vals = new Expression_list;
9702 for (; pa != old_args->end(); ++pa, ++i)
9704 // Check types here so that we get a better message.
9705 Type* patype = (*pa)->type();
9706 Location paloc = (*pa)->location();
9707 if (!this->check_argument_type(i, element_type, patype,
9708 paloc, issued_error))
9709 continue;
9710 vals->push_back(*pa);
9712 Slice_construction_expression* sce =
9713 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9714 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9715 sce->set_storage_does_not_escape();
9716 Expression* val = sce;
9717 gogo->lower_expression(function, inserter, &val);
9718 new_args->push_back(val);
9722 if (push_empty_arg)
9723 new_args->push_back(Expression::make_nil(loc));
9725 // We can't return a new call expression here, because this one may
9726 // be referenced by Call_result expressions. FIXME. We can't
9727 // delete OLD_ARGS because we may have both a Call_expression and a
9728 // Builtin_call_expression which refer to them. FIXME.
9729 this->args_ = new_args;
9730 this->varargs_are_lowered_ = true;
9733 // Return a call to __builtin_return_address or __builtin_frame_address.
9735 Expression*
9736 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9737 int arg)
9739 if (*pno == NULL)
9740 *pno = Gogo::declare_builtin_rf_address(name);
9742 Location loc = this->location();
9744 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9745 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9746 Expression_list *args = new Expression_list();
9747 args->push_back(a);
9748 Expression* call = Expression::make_call(fn, args, false, loc);
9750 // The builtin functions return void*, but the Go functions return uintptr.
9751 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9752 return Expression::make_cast(uintptr_type, call, loc);
9755 // Flatten a call with multiple results into a temporary.
9757 Expression*
9758 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9759 Statement_inserter* inserter)
9761 if (this->is_erroneous_call())
9763 go_assert(saw_errors());
9764 return Expression::make_error(this->location());
9767 if (this->is_flattened_)
9768 return this;
9769 this->is_flattened_ = true;
9771 // Add temporary variables for all arguments that require type
9772 // conversion.
9773 Function_type* fntype = this->get_function_type();
9774 if (fntype == NULL)
9776 go_assert(saw_errors());
9777 return this;
9779 if (this->args_ != NULL && !this->args_->empty()
9780 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9782 bool is_interface_method =
9783 this->fn_->interface_field_reference_expression() != NULL;
9785 Expression_list *args = new Expression_list();
9786 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9787 Expression_list::const_iterator pa = this->args_->begin();
9788 if (!is_interface_method && fntype->is_method())
9790 // The receiver argument.
9791 args->push_back(*pa);
9792 ++pa;
9794 for (; pa != this->args_->end(); ++pa, ++pp)
9796 go_assert(pp != fntype->parameters()->end());
9797 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9798 args->push_back(*pa);
9799 else
9801 Location loc = (*pa)->location();
9802 Expression* arg = *pa;
9803 if (!arg->is_variable())
9805 Temporary_statement *temp =
9806 Statement::make_temporary(NULL, arg, loc);
9807 inserter->insert(temp);
9808 arg = Expression::make_temporary_reference(temp, loc);
9810 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9811 loc);
9812 args->push_back(arg);
9815 delete this->args_;
9816 this->args_ = args;
9819 return this;
9822 // Get the function type. This can return NULL in error cases.
9824 Function_type*
9825 Call_expression::get_function_type() const
9827 return this->fn_->type()->function_type();
9830 // Return the number of values which this call will return.
9832 size_t
9833 Call_expression::result_count() const
9835 const Function_type* fntype = this->get_function_type();
9836 if (fntype == NULL)
9837 return 0;
9838 if (fntype->results() == NULL)
9839 return 0;
9840 return fntype->results()->size();
9843 // Return the temporary that holds the result for a call with multiple
9844 // results.
9846 Temporary_statement*
9847 Call_expression::results() const
9849 if (this->call_temp_ == NULL)
9851 go_assert(saw_errors());
9852 return NULL;
9854 return this->call_temp_;
9857 // Set the number of results expected from a call expression.
9859 void
9860 Call_expression::set_expected_result_count(size_t count)
9862 go_assert(this->expected_result_count_ == 0);
9863 this->expected_result_count_ = count;
9866 // Return whether this is a call to the predeclared function recover.
9868 bool
9869 Call_expression::is_recover_call() const
9871 return this->do_is_recover_call();
9874 // Set the argument to the recover function.
9876 void
9877 Call_expression::set_recover_arg(Expression* arg)
9879 this->do_set_recover_arg(arg);
9882 // Virtual functions also implemented by Builtin_call_expression.
9884 bool
9885 Call_expression::do_is_recover_call() const
9887 return false;
9890 void
9891 Call_expression::do_set_recover_arg(Expression*)
9893 go_unreachable();
9896 // We have found an error with this call expression; return true if
9897 // we should report it.
9899 bool
9900 Call_expression::issue_error()
9902 if (this->issued_error_)
9903 return false;
9904 else
9906 this->issued_error_ = true;
9907 return true;
9911 // Whether or not this call contains errors, either in the call or the
9912 // arguments to the call.
9914 bool
9915 Call_expression::is_erroneous_call()
9917 if (this->is_error_expression() || this->fn()->is_error_expression())
9918 return true;
9920 if (this->args() == NULL)
9921 return false;
9922 for (Expression_list::iterator pa = this->args()->begin();
9923 pa != this->args()->end();
9924 ++pa)
9926 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9927 return true;
9929 return false;
9932 // Get the type.
9934 Type*
9935 Call_expression::do_type()
9937 if (this->type_ != NULL)
9938 return this->type_;
9940 Type* ret;
9941 Function_type* fntype = this->get_function_type();
9942 if (fntype == NULL)
9943 return Type::make_error_type();
9945 const Typed_identifier_list* results = fntype->results();
9946 if (results == NULL)
9947 ret = Type::make_void_type();
9948 else if (results->size() == 1)
9949 ret = results->begin()->type();
9950 else
9951 ret = Type::make_call_multiple_result_type(this);
9953 this->type_ = ret;
9955 return this->type_;
9958 // Determine types for a call expression. We can use the function
9959 // parameter types to set the types of the arguments.
9961 void
9962 Call_expression::do_determine_type(const Type_context*)
9964 if (!this->determining_types())
9965 return;
9967 this->fn_->determine_type_no_context();
9968 Function_type* fntype = this->get_function_type();
9969 const Typed_identifier_list* parameters = NULL;
9970 if (fntype != NULL)
9971 parameters = fntype->parameters();
9972 if (this->args_ != NULL)
9974 Typed_identifier_list::const_iterator pt;
9975 if (parameters != NULL)
9976 pt = parameters->begin();
9977 bool first = true;
9978 for (Expression_list::const_iterator pa = this->args_->begin();
9979 pa != this->args_->end();
9980 ++pa)
9982 if (first)
9984 first = false;
9985 // If this is a method, the first argument is the
9986 // receiver.
9987 if (fntype != NULL && fntype->is_method())
9989 Type* rtype = fntype->receiver()->type();
9990 // The receiver is always passed as a pointer.
9991 if (rtype->points_to() == NULL)
9992 rtype = Type::make_pointer_type(rtype);
9993 Type_context subcontext(rtype, false);
9994 (*pa)->determine_type(&subcontext);
9995 continue;
9999 if (parameters != NULL && pt != parameters->end())
10001 Type_context subcontext(pt->type(), false);
10002 (*pa)->determine_type(&subcontext);
10003 ++pt;
10005 else
10006 (*pa)->determine_type_no_context();
10011 // Called when determining types for a Call_expression. Return true
10012 // if we should go ahead, false if they have already been determined.
10014 bool
10015 Call_expression::determining_types()
10017 if (this->types_are_determined_)
10018 return false;
10019 else
10021 this->types_are_determined_ = true;
10022 return true;
10026 // Check types for parameter I.
10028 bool
10029 Call_expression::check_argument_type(int i, const Type* parameter_type,
10030 const Type* argument_type,
10031 Location argument_location,
10032 bool issued_error)
10034 std::string reason;
10035 if (!Type::are_assignable(parameter_type, argument_type, &reason))
10037 if (!issued_error)
10039 if (reason.empty())
10040 go_error_at(argument_location, "argument %d has incompatible type", i);
10041 else
10042 go_error_at(argument_location,
10043 "argument %d has incompatible type (%s)",
10044 i, reason.c_str());
10046 this->set_is_error();
10047 return false;
10049 return true;
10052 // Check types.
10054 void
10055 Call_expression::do_check_types(Gogo*)
10057 if (this->classification() == EXPRESSION_ERROR)
10058 return;
10060 Function_type* fntype = this->get_function_type();
10061 if (fntype == NULL)
10063 if (!this->fn_->type()->is_error())
10064 this->report_error(_("expected function"));
10065 return;
10068 if (this->expected_result_count_ != 0
10069 && this->expected_result_count_ != this->result_count())
10071 if (this->issue_error())
10072 this->report_error(_("function result count mismatch"));
10073 this->set_is_error();
10074 return;
10077 bool is_method = fntype->is_method();
10078 if (is_method)
10080 go_assert(this->args_ != NULL && !this->args_->empty());
10081 Type* rtype = fntype->receiver()->type();
10082 Expression* first_arg = this->args_->front();
10083 // We dereference the values since receivers are always passed
10084 // as pointers.
10085 std::string reason;
10086 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10087 &reason))
10089 if (reason.empty())
10090 this->report_error(_("incompatible type for receiver"));
10091 else
10093 go_error_at(this->location(),
10094 "incompatible type for receiver (%s)",
10095 reason.c_str());
10096 this->set_is_error();
10101 // Note that varargs was handled by the lower_varargs() method, so
10102 // we don't have to worry about it here unless something is wrong.
10103 if (this->is_varargs_ && !this->varargs_are_lowered_)
10105 if (!fntype->is_varargs())
10107 go_error_at(this->location(),
10108 _("invalid use of %<...%> calling non-variadic function"));
10109 this->set_is_error();
10110 return;
10114 const Typed_identifier_list* parameters = fntype->parameters();
10115 if (this->args_ == NULL || this->args_->size() == 0)
10117 if (parameters != NULL && !parameters->empty())
10118 this->report_error(_("not enough arguments"));
10120 else if (parameters == NULL)
10122 if (!is_method || this->args_->size() > 1)
10123 this->report_error(_("too many arguments"));
10125 else if (this->args_->size() == 1
10126 && this->args_->front()->call_expression() != NULL
10127 && this->args_->front()->call_expression()->result_count() > 1)
10129 // This is F(G()) when G returns more than one result. If the
10130 // results can be matched to parameters, it would have been
10131 // lowered in do_lower. If we get here we know there is a
10132 // mismatch.
10133 if (this->args_->front()->call_expression()->result_count()
10134 < parameters->size())
10135 this->report_error(_("not enough arguments"));
10136 else
10137 this->report_error(_("too many arguments"));
10139 else
10141 int i = 0;
10142 Expression_list::const_iterator pa = this->args_->begin();
10143 if (is_method)
10144 ++pa;
10145 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10146 pt != parameters->end();
10147 ++pt, ++pa, ++i)
10149 if (pa == this->args_->end())
10151 this->report_error(_("not enough arguments"));
10152 return;
10154 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10155 (*pa)->location(), false);
10157 if (pa != this->args_->end())
10158 this->report_error(_("too many arguments"));
10162 Expression*
10163 Call_expression::do_copy()
10165 Call_expression* call =
10166 Expression::make_call(this->fn_->copy(),
10167 (this->args_ == NULL
10168 ? NULL
10169 : this->args_->copy()),
10170 this->is_varargs_, this->location());
10172 if (this->varargs_are_lowered_)
10173 call->set_varargs_are_lowered();
10174 return call;
10177 // Return whether we have to use a temporary variable to ensure that
10178 // we evaluate this call expression in order. If the call returns no
10179 // results then it will inevitably be executed last.
10181 bool
10182 Call_expression::do_must_eval_in_order() const
10184 return this->result_count() > 0;
10187 // Get the function and the first argument to use when calling an
10188 // interface method.
10190 Expression*
10191 Call_expression::interface_method_function(
10192 Interface_field_reference_expression* interface_method,
10193 Expression** first_arg_ptr,
10194 Location location)
10196 Expression* object = interface_method->get_underlying_object();
10197 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10198 *first_arg_ptr =
10199 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10200 return interface_method->get_function();
10203 // Build the call expression.
10205 Bexpression*
10206 Call_expression::do_get_backend(Translate_context* context)
10208 Location location = this->location();
10210 if (this->call_ != NULL)
10212 // If the call returns multiple results, make a new reference to
10213 // the temporary.
10214 if (this->call_temp_ != NULL)
10216 Expression* ref =
10217 Expression::make_temporary_reference(this->call_temp_, location);
10218 return ref->get_backend(context);
10221 return this->call_;
10224 Function_type* fntype = this->get_function_type();
10225 if (fntype == NULL)
10226 return context->backend()->error_expression();
10228 if (this->fn_->is_error_expression())
10229 return context->backend()->error_expression();
10231 Gogo* gogo = context->gogo();
10233 Func_expression* func = this->fn_->func_expression();
10234 Interface_field_reference_expression* interface_method =
10235 this->fn_->interface_field_reference_expression();
10236 const bool has_closure = func != NULL && func->closure() != NULL;
10237 const bool is_interface_method = interface_method != NULL;
10239 bool has_closure_arg;
10240 if (has_closure)
10241 has_closure_arg = true;
10242 else if (func != NULL)
10243 has_closure_arg = false;
10244 else if (is_interface_method)
10245 has_closure_arg = false;
10246 else
10247 has_closure_arg = true;
10249 int nargs;
10250 std::vector<Bexpression*> fn_args;
10251 if (this->args_ == NULL || this->args_->empty())
10253 nargs = is_interface_method ? 1 : 0;
10254 if (nargs > 0)
10255 fn_args.resize(1);
10257 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10259 // Passing a receiver parameter.
10260 go_assert(!is_interface_method
10261 && fntype->is_method()
10262 && this->args_->size() == 1);
10263 nargs = 1;
10264 fn_args.resize(1);
10265 fn_args[0] = this->args_->front()->get_backend(context);
10267 else
10269 const Typed_identifier_list* params = fntype->parameters();
10271 nargs = this->args_->size();
10272 int i = is_interface_method ? 1 : 0;
10273 nargs += i;
10274 fn_args.resize(nargs);
10276 Typed_identifier_list::const_iterator pp = params->begin();
10277 Expression_list::const_iterator pe = this->args_->begin();
10278 if (!is_interface_method && fntype->is_method())
10280 fn_args[i] = (*pe)->get_backend(context);
10281 ++pe;
10282 ++i;
10284 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10286 go_assert(pp != params->end());
10287 Expression* arg =
10288 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10289 location);
10290 fn_args[i] = arg->get_backend(context);
10292 go_assert(pp == params->end());
10293 go_assert(i == nargs);
10296 Expression* fn;
10297 Expression* closure = NULL;
10298 if (func != NULL)
10300 Named_object* no = func->named_object();
10301 fn = Expression::make_func_code_reference(no, location);
10302 if (has_closure)
10303 closure = func->closure();
10305 else if (!is_interface_method)
10307 closure = this->fn_;
10309 // The backend representation of this function type is a pointer
10310 // to a struct whose first field is the actual function to call.
10311 Type* pfntype =
10312 Type::make_pointer_type(
10313 Type::make_pointer_type(Type::make_void_type()));
10314 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10315 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10317 else
10319 Expression* first_arg;
10320 fn = this->interface_method_function(interface_method, &first_arg,
10321 location);
10322 fn_args[0] = first_arg->get_backend(context);
10325 Bexpression* bclosure = NULL;
10326 if (has_closure_arg)
10327 bclosure = closure->get_backend(context);
10328 else
10329 go_assert(closure == NULL);
10331 Bexpression* bfn = fn->get_backend(context);
10333 // When not calling a named function directly, use a type conversion
10334 // in case the type of the function is a recursive type which refers
10335 // to itself. We don't do this for an interface method because 1)
10336 // an interface method never refers to itself, so we always have a
10337 // function type here; 2) we pass an extra first argument to an
10338 // interface method, so fntype is not correct.
10339 if (func == NULL && !is_interface_method)
10341 Btype* bft = fntype->get_backend_fntype(gogo);
10342 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10345 Bfunction* bfunction = NULL;
10346 if (context->function())
10347 bfunction = context->function()->func_value()->get_decl();
10348 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10349 fn_args, bclosure,
10350 location);
10352 if (this->call_temp_ != NULL)
10354 // This case occurs when the call returns multiple results.
10356 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10357 location);
10358 Bexpression* bref = ref->get_backend(context);
10359 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10360 bref, call,
10361 location);
10363 ref = Expression::make_temporary_reference(this->call_temp_, location);
10364 this->call_ = ref->get_backend(context);
10366 return gogo->backend()->compound_expression(bassn, this->call_,
10367 location);
10370 this->call_ = call;
10371 return this->call_;
10374 // Dump ast representation for a call expressin.
10376 void
10377 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10379 this->fn_->dump_expression(ast_dump_context);
10380 ast_dump_context->ostream() << "(";
10381 if (args_ != NULL)
10382 ast_dump_context->dump_expression_list(this->args_);
10384 ast_dump_context->ostream() << ") ";
10387 // Make a call expression.
10389 Call_expression*
10390 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10391 Location location)
10393 return new Call_expression(fn, args, is_varargs, location);
10396 // Class Call_result_expression.
10398 // Traverse a call result.
10401 Call_result_expression::do_traverse(Traverse* traverse)
10403 if (traverse->remember_expression(this->call_))
10405 // We have already traversed the call expression.
10406 return TRAVERSE_CONTINUE;
10408 return Expression::traverse(&this->call_, traverse);
10411 // Get the type.
10413 Type*
10414 Call_result_expression::do_type()
10416 if (this->classification() == EXPRESSION_ERROR)
10417 return Type::make_error_type();
10419 // THIS->CALL_ can be replaced with a temporary reference due to
10420 // Call_expression::do_must_eval_in_order when there is an error.
10421 Call_expression* ce = this->call_->call_expression();
10422 if (ce == NULL)
10424 this->set_is_error();
10425 return Type::make_error_type();
10427 Function_type* fntype = ce->get_function_type();
10428 if (fntype == NULL)
10430 if (ce->issue_error())
10432 if (!ce->fn()->type()->is_error())
10433 this->report_error(_("expected function"));
10435 this->set_is_error();
10436 return Type::make_error_type();
10438 const Typed_identifier_list* results = fntype->results();
10439 if (results == NULL || results->size() < 2)
10441 if (ce->issue_error())
10442 this->report_error(_("number of results does not match "
10443 "number of values"));
10444 return Type::make_error_type();
10446 Typed_identifier_list::const_iterator pr = results->begin();
10447 for (unsigned int i = 0; i < this->index_; ++i)
10449 if (pr == results->end())
10450 break;
10451 ++pr;
10453 if (pr == results->end())
10455 if (ce->issue_error())
10456 this->report_error(_("number of results does not match "
10457 "number of values"));
10458 return Type::make_error_type();
10460 return pr->type();
10463 // Check the type. Just make sure that we trigger the warning in
10464 // do_type.
10466 void
10467 Call_result_expression::do_check_types(Gogo*)
10469 this->type();
10472 // Determine the type. We have nothing to do here, but the 0 result
10473 // needs to pass down to the caller.
10475 void
10476 Call_result_expression::do_determine_type(const Type_context*)
10478 this->call_->determine_type_no_context();
10481 // Return the backend representation. We just refer to the temporary set by the
10482 // call expression. We don't do this at lowering time because it makes it
10483 // hard to evaluate the call at the right time.
10485 Bexpression*
10486 Call_result_expression::do_get_backend(Translate_context* context)
10488 Call_expression* ce = this->call_->call_expression();
10489 if (ce == NULL)
10491 go_assert(this->call_->is_error_expression());
10492 return context->backend()->error_expression();
10494 Temporary_statement* ts = ce->results();
10495 if (ts == NULL)
10497 go_assert(saw_errors());
10498 return context->backend()->error_expression();
10500 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10501 ref = Expression::make_field_reference(ref, this->index_, this->location());
10502 return ref->get_backend(context);
10505 // Dump ast representation for a call result expression.
10507 void
10508 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10509 const
10511 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10512 // (struct) and the fields are referenced instead.
10513 ast_dump_context->ostream() << this->index_ << "@(";
10514 ast_dump_context->dump_expression(this->call_);
10515 ast_dump_context->ostream() << ")";
10518 // Make a reference to a single result of a call which returns
10519 // multiple results.
10521 Expression*
10522 Expression::make_call_result(Call_expression* call, unsigned int index)
10524 return new Call_result_expression(call, index);
10527 // Class Index_expression.
10529 // Traversal.
10532 Index_expression::do_traverse(Traverse* traverse)
10534 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10535 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10536 || (this->end_ != NULL
10537 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10538 || (this->cap_ != NULL
10539 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10540 return TRAVERSE_EXIT;
10541 return TRAVERSE_CONTINUE;
10544 // Lower an index expression. This converts the generic index
10545 // expression into an array index, a string index, or a map index.
10547 Expression*
10548 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10550 Location location = this->location();
10551 Expression* left = this->left_;
10552 Expression* start = this->start_;
10553 Expression* end = this->end_;
10554 Expression* cap = this->cap_;
10556 Type* type = left->type();
10557 if (type->is_error())
10559 go_assert(saw_errors());
10560 return Expression::make_error(location);
10562 else if (left->is_type_expression())
10564 go_error_at(location, "attempt to index type expression");
10565 return Expression::make_error(location);
10567 else if (type->array_type() != NULL)
10568 return Expression::make_array_index(left, start, end, cap, location);
10569 else if (type->points_to() != NULL
10570 && type->points_to()->array_type() != NULL
10571 && !type->points_to()->is_slice_type())
10573 Expression* deref =
10574 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10576 // For an ordinary index into the array, the pointer will be
10577 // dereferenced. For a slice it will not--the resulting slice
10578 // will simply reuse the pointer, which is incorrect if that
10579 // pointer is nil.
10580 if (end != NULL || cap != NULL)
10581 deref->issue_nil_check();
10583 return Expression::make_array_index(deref, start, end, cap, location);
10585 else if (type->is_string_type())
10587 if (cap != NULL)
10589 go_error_at(location, "invalid 3-index slice of string");
10590 return Expression::make_error(location);
10592 return Expression::make_string_index(left, start, end, location);
10594 else if (type->map_type() != NULL)
10596 if (end != NULL || cap != NULL)
10598 go_error_at(location, "invalid slice of map");
10599 return Expression::make_error(location);
10601 return Expression::make_map_index(left, start, location);
10603 else if (cap != NULL)
10605 go_error_at(location,
10606 "invalid 3-index slice of object that is not a slice");
10607 return Expression::make_error(location);
10609 else if (end != NULL)
10611 go_error_at(location,
10612 ("attempt to slice object that is not "
10613 "array, slice, or string"));
10614 return Expression::make_error(location);
10616 else
10618 go_error_at(location,
10619 ("attempt to index object that is not "
10620 "array, slice, string, or map"));
10621 return Expression::make_error(location);
10625 // Write an indexed expression
10626 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10628 void
10629 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10630 const Expression* expr,
10631 const Expression* start,
10632 const Expression* end,
10633 const Expression* cap)
10635 expr->dump_expression(ast_dump_context);
10636 ast_dump_context->ostream() << "[";
10637 start->dump_expression(ast_dump_context);
10638 if (end != NULL)
10640 ast_dump_context->ostream() << ":";
10641 end->dump_expression(ast_dump_context);
10643 if (cap != NULL)
10645 ast_dump_context->ostream() << ":";
10646 cap->dump_expression(ast_dump_context);
10648 ast_dump_context->ostream() << "]";
10651 // Dump ast representation for an index expression.
10653 void
10654 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10655 const
10657 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10658 this->start_, this->end_, this->cap_);
10661 // Make an index expression.
10663 Expression*
10664 Expression::make_index(Expression* left, Expression* start, Expression* end,
10665 Expression* cap, Location location)
10667 return new Index_expression(left, start, end, cap, location);
10670 // Class Array_index_expression.
10672 // Array index traversal.
10675 Array_index_expression::do_traverse(Traverse* traverse)
10677 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10678 return TRAVERSE_EXIT;
10679 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10680 return TRAVERSE_EXIT;
10681 if (this->end_ != NULL)
10683 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10684 return TRAVERSE_EXIT;
10686 if (this->cap_ != NULL)
10688 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10689 return TRAVERSE_EXIT;
10691 return TRAVERSE_CONTINUE;
10694 // Return the type of an array index.
10696 Type*
10697 Array_index_expression::do_type()
10699 if (this->type_ == NULL)
10701 Array_type* type = this->array_->type()->array_type();
10702 if (type == NULL)
10703 this->type_ = Type::make_error_type();
10704 else if (this->end_ == NULL)
10705 this->type_ = type->element_type();
10706 else if (type->is_slice_type())
10708 // A slice of a slice has the same type as the original
10709 // slice.
10710 this->type_ = this->array_->type()->deref();
10712 else
10714 // A slice of an array is a slice.
10715 this->type_ = Type::make_array_type(type->element_type(), NULL);
10718 return this->type_;
10721 // Set the type of an array index.
10723 void
10724 Array_index_expression::do_determine_type(const Type_context*)
10726 this->array_->determine_type_no_context();
10728 Type_context index_context(Type::lookup_integer_type("int"), false);
10729 if (this->start_->is_constant())
10730 this->start_->determine_type(&index_context);
10731 else
10732 this->start_->determine_type_no_context();
10733 if (this->end_ != NULL)
10735 if (this->end_->is_constant())
10736 this->end_->determine_type(&index_context);
10737 else
10738 this->end_->determine_type_no_context();
10740 if (this->cap_ != NULL)
10742 if (this->cap_->is_constant())
10743 this->cap_->determine_type(&index_context);
10744 else
10745 this->cap_->determine_type_no_context();
10749 // Check types of an array index.
10751 void
10752 Array_index_expression::do_check_types(Gogo*)
10754 Numeric_constant nc;
10755 unsigned long v;
10756 if (this->start_->type()->integer_type() == NULL
10757 && !this->start_->type()->is_error()
10758 && (!this->start_->numeric_constant_value(&nc)
10759 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10760 this->report_error(_("index must be integer"));
10761 if (this->end_ != NULL
10762 && this->end_->type()->integer_type() == NULL
10763 && !this->end_->type()->is_error()
10764 && !this->end_->is_nil_expression()
10765 && !this->end_->is_error_expression()
10766 && (!this->end_->numeric_constant_value(&nc)
10767 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10768 this->report_error(_("slice end must be integer"));
10769 if (this->cap_ != NULL
10770 && this->cap_->type()->integer_type() == NULL
10771 && !this->cap_->type()->is_error()
10772 && !this->cap_->is_nil_expression()
10773 && !this->cap_->is_error_expression()
10774 && (!this->cap_->numeric_constant_value(&nc)
10775 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10776 this->report_error(_("slice capacity must be integer"));
10778 Array_type* array_type = this->array_->type()->array_type();
10779 if (array_type == NULL)
10781 go_assert(this->array_->type()->is_error());
10782 return;
10785 unsigned int int_bits =
10786 Type::lookup_integer_type("int")->integer_type()->bits();
10788 Numeric_constant lvalnc;
10789 mpz_t lval;
10790 bool lval_valid = (array_type->length() != NULL
10791 && array_type->length()->numeric_constant_value(&lvalnc)
10792 && lvalnc.to_int(&lval));
10793 Numeric_constant inc;
10794 mpz_t ival;
10795 bool ival_valid = false;
10796 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10798 ival_valid = true;
10799 if (mpz_sgn(ival) < 0
10800 || mpz_sizeinbase(ival, 2) >= int_bits
10801 || (lval_valid
10802 && (this->end_ == NULL
10803 ? mpz_cmp(ival, lval) >= 0
10804 : mpz_cmp(ival, lval) > 0)))
10806 go_error_at(this->start_->location(), "array index out of bounds");
10807 this->set_is_error();
10810 if (this->end_ != NULL && !this->end_->is_nil_expression())
10812 Numeric_constant enc;
10813 mpz_t eval;
10814 bool eval_valid = false;
10815 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10817 eval_valid = true;
10818 if (mpz_sgn(eval) < 0
10819 || mpz_sizeinbase(eval, 2) >= int_bits
10820 || (lval_valid && mpz_cmp(eval, lval) > 0))
10822 go_error_at(this->end_->location(), "array index out of bounds");
10823 this->set_is_error();
10825 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10826 this->report_error(_("inverted slice range"));
10829 Numeric_constant cnc;
10830 mpz_t cval;
10831 if (this->cap_ != NULL
10832 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10834 if (mpz_sgn(cval) < 0
10835 || mpz_sizeinbase(cval, 2) >= int_bits
10836 || (lval_valid && mpz_cmp(cval, lval) > 0))
10838 go_error_at(this->cap_->location(), "array index out of bounds");
10839 this->set_is_error();
10841 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10843 go_error_at(this->cap_->location(),
10844 "invalid slice index: capacity less than start");
10845 this->set_is_error();
10847 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10849 go_error_at(this->cap_->location(),
10850 "invalid slice index: capacity less than length");
10851 this->set_is_error();
10853 mpz_clear(cval);
10856 if (eval_valid)
10857 mpz_clear(eval);
10859 if (ival_valid)
10860 mpz_clear(ival);
10861 if (lval_valid)
10862 mpz_clear(lval);
10864 // A slice of an array requires an addressable array. A slice of a
10865 // slice is always possible.
10866 if (this->end_ != NULL && !array_type->is_slice_type())
10868 if (!this->array_->is_addressable())
10869 this->report_error(_("slice of unaddressable value"));
10870 else
10871 // Set the array address taken but not escape. The escape
10872 // analysis will make it escape to heap when needed.
10873 this->array_->address_taken(false);
10877 // Flatten array indexing by using temporary variables for slices and indexes.
10879 Expression*
10880 Array_index_expression::do_flatten(Gogo*, Named_object*,
10881 Statement_inserter* inserter)
10883 Location loc = this->location();
10884 Expression* array = this->array_;
10885 Expression* start = this->start_;
10886 Expression* end = this->end_;
10887 Expression* cap = this->cap_;
10888 if (array->is_error_expression()
10889 || array->type()->is_error_type()
10890 || start->is_error_expression()
10891 || start->type()->is_error_type()
10892 || (end != NULL
10893 && (end->is_error_expression() || end->type()->is_error_type()))
10894 || (cap != NULL
10895 && (cap->is_error_expression() || cap->type()->is_error_type())))
10897 go_assert(saw_errors());
10898 return Expression::make_error(loc);
10901 Temporary_statement* temp;
10902 if (array->type()->is_slice_type() && !array->is_variable())
10904 temp = Statement::make_temporary(NULL, array, loc);
10905 inserter->insert(temp);
10906 this->array_ = Expression::make_temporary_reference(temp, loc);
10908 if (!start->is_variable())
10910 temp = Statement::make_temporary(NULL, start, loc);
10911 inserter->insert(temp);
10912 this->start_ = Expression::make_temporary_reference(temp, loc);
10914 if (end != NULL
10915 && !end->is_nil_expression()
10916 && !end->is_variable())
10918 temp = Statement::make_temporary(NULL, end, loc);
10919 inserter->insert(temp);
10920 this->end_ = Expression::make_temporary_reference(temp, loc);
10922 if (cap != NULL && !cap->is_variable())
10924 temp = Statement::make_temporary(NULL, cap, loc);
10925 inserter->insert(temp);
10926 this->cap_ = Expression::make_temporary_reference(temp, loc);
10929 return this;
10932 // Return whether this expression is addressable.
10934 bool
10935 Array_index_expression::do_is_addressable() const
10937 // A slice expression is not addressable.
10938 if (this->end_ != NULL)
10939 return false;
10941 // An index into a slice is addressable.
10942 if (this->array_->type()->is_slice_type())
10943 return true;
10945 // An index into an array is addressable if the array is
10946 // addressable.
10947 return this->array_->is_addressable();
10950 void
10951 Array_index_expression::do_address_taken(bool escapes)
10953 // In &x[0], if x is a slice, then x's address is not taken.
10954 if (!this->array_->type()->is_slice_type())
10955 this->array_->address_taken(escapes);
10958 // Get the backend representation for an array index.
10960 Bexpression*
10961 Array_index_expression::do_get_backend(Translate_context* context)
10963 Array_type* array_type = this->array_->type()->array_type();
10964 if (array_type == NULL)
10966 go_assert(this->array_->type()->is_error());
10967 return context->backend()->error_expression();
10969 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10971 Location loc = this->location();
10972 Gogo* gogo = context->gogo();
10974 Type* int_type = Type::lookup_integer_type("int");
10975 Btype* int_btype = int_type->get_backend(gogo);
10977 // We need to convert the length and capacity to the Go "int" type here
10978 // because the length of a fixed-length array could be of type "uintptr"
10979 // and gimple disallows binary operations between "uintptr" and other
10980 // integer types. FIXME.
10981 Bexpression* length = NULL;
10982 if (this->end_ == NULL || this->end_->is_nil_expression())
10984 Expression* len = array_type->get_length(gogo, this->array_);
10985 length = len->get_backend(context);
10986 length = gogo->backend()->convert_expression(int_btype, length, loc);
10989 Bexpression* capacity = NULL;
10990 if (this->end_ != NULL)
10992 Expression* cap = array_type->get_capacity(gogo, this->array_);
10993 capacity = cap->get_backend(context);
10994 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10997 Bexpression* cap_arg = capacity;
10998 if (this->cap_ != NULL)
11000 cap_arg = this->cap_->get_backend(context);
11001 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11004 if (length == NULL)
11005 length = cap_arg;
11007 int code = (array_type->length() != NULL
11008 ? (this->end_ == NULL
11009 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
11010 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
11011 : (this->end_ == NULL
11012 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
11013 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
11014 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11016 if (this->start_->type()->integer_type() == NULL
11017 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11019 go_assert(saw_errors());
11020 return context->backend()->error_expression();
11023 Bexpression* bad_index =
11024 Expression::check_bounds(this->start_, loc)->get_backend(context);
11026 Bexpression* start = this->start_->get_backend(context);
11027 start = gogo->backend()->convert_expression(int_btype, start, loc);
11028 Bexpression* start_too_large =
11029 gogo->backend()->binary_expression((this->end_ == NULL
11030 ? OPERATOR_GE
11031 : OPERATOR_GT),
11032 start,
11033 (this->end_ == NULL
11034 ? length
11035 : capacity),
11036 loc);
11037 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
11038 bad_index, loc);
11040 Bfunction* bfn = context->function()->func_value()->get_decl();
11041 if (this->end_ == NULL)
11043 // Simple array indexing. This has to return an l-value, so
11044 // wrap the index check into START.
11045 start =
11046 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
11047 crash, start, loc);
11049 Bexpression* ret;
11050 if (array_type->length() != NULL)
11052 Bexpression* array = this->array_->get_backend(context);
11053 ret = gogo->backend()->array_index_expression(array, start, loc);
11055 else
11057 // Slice.
11058 Expression* valptr =
11059 array_type->get_value_pointer(gogo, this->array_,
11060 this->is_lvalue_);
11061 Bexpression* ptr = valptr->get_backend(context);
11062 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11064 Type* ele_type = this->array_->type()->array_type()->element_type();
11065 Btype* ele_btype = ele_type->get_backend(gogo);
11066 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11068 return ret;
11071 // Array slice.
11073 if (this->cap_ != NULL)
11075 Bexpression* bounds_bcheck =
11076 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11077 bad_index =
11078 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11079 bad_index, loc);
11080 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11082 Bexpression* cap_too_small =
11083 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11084 Bexpression* cap_too_large =
11085 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11086 Bexpression* bad_cap =
11087 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11088 cap_too_large, loc);
11089 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11090 bad_index, loc);
11093 Bexpression* end;
11094 if (this->end_->is_nil_expression())
11095 end = length;
11096 else
11098 Bexpression* bounds_bcheck =
11099 Expression::check_bounds(this->end_, loc)->get_backend(context);
11101 bad_index =
11102 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11103 bad_index, loc);
11105 end = this->end_->get_backend(context);
11106 end = gogo->backend()->convert_expression(int_btype, end, loc);
11107 Bexpression* end_too_small =
11108 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11109 Bexpression* end_too_large =
11110 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11111 Bexpression* bad_end =
11112 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11113 end_too_large, loc);
11114 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11115 bad_index, loc);
11118 Bexpression* result_length =
11119 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11121 Bexpression* result_capacity =
11122 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11124 // If the new capacity is zero, don't change val. Otherwise we can
11125 // get a pointer to the next object in memory, keeping it live
11126 // unnecessarily. When the capacity is zero, the actual pointer
11127 // value doesn't matter.
11128 Bexpression* zero =
11129 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11130 Bexpression* cond =
11131 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11132 loc);
11133 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11134 cond, zero,
11135 start, loc);
11136 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11137 this->is_lvalue_);
11138 Bexpression* val = valptr->get_backend(context);
11139 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11141 Btype* struct_btype = this->type()->get_backend(gogo);
11142 std::vector<Bexpression*> init;
11143 init.push_back(val);
11144 init.push_back(result_length);
11145 init.push_back(result_capacity);
11147 Bexpression* ctor =
11148 gogo->backend()->constructor_expression(struct_btype, init, loc);
11149 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11150 crash, ctor, loc);
11153 // Dump ast representation for an array index expression.
11155 void
11156 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11157 const
11159 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11160 this->start_, this->end_, this->cap_);
11163 // Make an array index expression. END and CAP may be NULL.
11165 Expression*
11166 Expression::make_array_index(Expression* array, Expression* start,
11167 Expression* end, Expression* cap,
11168 Location location)
11170 return new Array_index_expression(array, start, end, cap, location);
11173 // Class String_index_expression.
11175 // String index traversal.
11178 String_index_expression::do_traverse(Traverse* traverse)
11180 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11181 return TRAVERSE_EXIT;
11182 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11183 return TRAVERSE_EXIT;
11184 if (this->end_ != NULL)
11186 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11187 return TRAVERSE_EXIT;
11189 return TRAVERSE_CONTINUE;
11192 Expression*
11193 String_index_expression::do_flatten(Gogo*, Named_object*,
11194 Statement_inserter* inserter)
11196 Location loc = this->location();
11197 Expression* string = this->string_;
11198 Expression* start = this->start_;
11199 Expression* end = this->end_;
11200 if (string->is_error_expression()
11201 || string->type()->is_error_type()
11202 || start->is_error_expression()
11203 || start->type()->is_error_type()
11204 || (end != NULL
11205 && (end->is_error_expression() || end->type()->is_error_type())))
11207 go_assert(saw_errors());
11208 return Expression::make_error(loc);
11211 Temporary_statement* temp;
11212 if (!this->string_->is_variable())
11214 temp = Statement::make_temporary(NULL, this->string_, loc);
11215 inserter->insert(temp);
11216 this->string_ = Expression::make_temporary_reference(temp, loc);
11218 if (!this->start_->is_variable())
11220 temp = Statement::make_temporary(NULL, this->start_, loc);
11221 inserter->insert(temp);
11222 this->start_ = Expression::make_temporary_reference(temp, loc);
11224 if (this->end_ != NULL
11225 && !this->end_->is_nil_expression()
11226 && !this->end_->is_variable())
11228 temp = Statement::make_temporary(NULL, this->end_, loc);
11229 inserter->insert(temp);
11230 this->end_ = Expression::make_temporary_reference(temp, loc);
11233 return this;
11236 // Return the type of a string index.
11238 Type*
11239 String_index_expression::do_type()
11241 if (this->end_ == NULL)
11242 return Type::lookup_integer_type("uint8");
11243 else
11244 return this->string_->type();
11247 // Determine the type of a string index.
11249 void
11250 String_index_expression::do_determine_type(const Type_context*)
11252 this->string_->determine_type_no_context();
11254 Type_context index_context(Type::lookup_integer_type("int"), false);
11255 if (this->start_->is_constant())
11256 this->start_->determine_type(&index_context);
11257 else
11258 this->start_->determine_type_no_context();
11259 if (this->end_ != NULL)
11261 if (this->end_->is_constant())
11262 this->end_->determine_type(&index_context);
11263 else
11264 this->end_->determine_type_no_context();
11268 // Check types of a string index.
11270 void
11271 String_index_expression::do_check_types(Gogo*)
11273 Numeric_constant nc;
11274 unsigned long v;
11275 if (this->start_->type()->integer_type() == NULL
11276 && !this->start_->type()->is_error()
11277 && (!this->start_->numeric_constant_value(&nc)
11278 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11279 this->report_error(_("index must be integer"));
11280 if (this->end_ != NULL
11281 && this->end_->type()->integer_type() == NULL
11282 && !this->end_->type()->is_error()
11283 && !this->end_->is_nil_expression()
11284 && !this->end_->is_error_expression()
11285 && (!this->end_->numeric_constant_value(&nc)
11286 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11287 this->report_error(_("slice end must be integer"));
11289 std::string sval;
11290 bool sval_valid = this->string_->string_constant_value(&sval);
11292 Numeric_constant inc;
11293 mpz_t ival;
11294 bool ival_valid = false;
11295 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11297 ival_valid = true;
11298 if (mpz_sgn(ival) < 0
11299 || (sval_valid
11300 && (this->end_ == NULL
11301 ? mpz_cmp_ui(ival, sval.length()) >= 0
11302 : mpz_cmp_ui(ival, sval.length()) > 0)))
11304 go_error_at(this->start_->location(), "string index out of bounds");
11305 this->set_is_error();
11308 if (this->end_ != NULL && !this->end_->is_nil_expression())
11310 Numeric_constant enc;
11311 mpz_t eval;
11312 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11314 if (mpz_sgn(eval) < 0
11315 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11317 go_error_at(this->end_->location(), "string index out of bounds");
11318 this->set_is_error();
11320 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11321 this->report_error(_("inverted slice range"));
11322 mpz_clear(eval);
11325 if (ival_valid)
11326 mpz_clear(ival);
11329 // Get the backend representation for a string index.
11331 Bexpression*
11332 String_index_expression::do_get_backend(Translate_context* context)
11334 Location loc = this->location();
11335 Expression* string_arg = this->string_;
11336 if (this->string_->type()->points_to() != NULL)
11337 string_arg = Expression::make_dereference(this->string_,
11338 NIL_CHECK_NOT_NEEDED, loc);
11340 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11342 int code = (this->end_ == NULL
11343 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11344 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11346 Gogo* gogo = context->gogo();
11347 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11349 Type* int_type = Type::lookup_integer_type("int");
11351 // It is possible that an error occurred earlier because the start index
11352 // cannot be represented as an integer type. In this case, we shouldn't
11353 // try casting the starting index into an integer since
11354 // Type_conversion_expression will fail to get the backend representation.
11355 // FIXME.
11356 if (this->start_->type()->integer_type() == NULL
11357 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11359 go_assert(saw_errors());
11360 return context->backend()->error_expression();
11363 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11364 Bfunction* bfn = context->function()->func_value()->get_decl();
11366 if (this->end_ == NULL)
11368 Expression* length =
11369 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11371 Expression* start_too_large =
11372 Expression::make_binary(OPERATOR_GE, start, length, loc);
11373 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11374 bad_index, loc);
11375 Expression* bytes =
11376 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11378 Bexpression* bstart = start->get_backend(context);
11379 Bexpression* ptr = bytes->get_backend(context);
11380 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11381 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11382 Bexpression* index =
11383 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11385 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11386 Bexpression* index_error = bad_index->get_backend(context);
11387 return gogo->backend()->conditional_expression(bfn, byte_btype,
11388 index_error, crash,
11389 index, loc);
11392 Expression* end = NULL;
11393 if (this->end_->is_nil_expression())
11394 end = Expression::make_integer_sl(-1, int_type, loc);
11395 else
11397 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11398 bad_index =
11399 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11400 end = Expression::make_cast(int_type, this->end_, loc);
11403 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11404 string_arg, start, end);
11405 Bexpression* bstrslice = strslice->get_backend(context);
11407 Btype* str_btype = strslice->type()->get_backend(gogo);
11408 Bexpression* index_error = bad_index->get_backend(context);
11409 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11410 crash, bstrslice, loc);
11413 // Dump ast representation for a string index expression.
11415 void
11416 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11417 const
11419 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11420 this->start_, this->end_, NULL);
11423 // Make a string index expression. END may be NULL.
11425 Expression*
11426 Expression::make_string_index(Expression* string, Expression* start,
11427 Expression* end, Location location)
11429 return new String_index_expression(string, start, end, location);
11432 // Class Map_index.
11434 // Get the type of the map.
11436 Map_type*
11437 Map_index_expression::get_map_type() const
11439 Map_type* mt = this->map_->type()->map_type();
11440 if (mt == NULL)
11441 go_assert(saw_errors());
11442 return mt;
11445 // Map index traversal.
11448 Map_index_expression::do_traverse(Traverse* traverse)
11450 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11451 return TRAVERSE_EXIT;
11452 return Expression::traverse(&this->index_, traverse);
11455 // We need to pass in a pointer to the key, so flatten the index into a
11456 // temporary variable if it isn't already. The value pointer will be
11457 // dereferenced and checked for nil, so flatten into a temporary to avoid
11458 // recomputation.
11460 Expression*
11461 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11462 Statement_inserter* inserter)
11464 Location loc = this->location();
11465 Map_type* mt = this->get_map_type();
11466 if (this->index()->is_error_expression()
11467 || this->index()->type()->is_error_type()
11468 || mt->is_error_type())
11470 go_assert(saw_errors());
11471 return Expression::make_error(loc);
11474 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11476 if (this->index_->type()->interface_type() != NULL
11477 && !this->index_->is_variable())
11479 Temporary_statement* temp =
11480 Statement::make_temporary(NULL, this->index_, loc);
11481 inserter->insert(temp);
11482 this->index_ = Expression::make_temporary_reference(temp, loc);
11484 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11485 this->index_, loc);
11488 if (!this->index_->is_variable())
11490 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11491 loc);
11492 inserter->insert(temp);
11493 this->index_ = Expression::make_temporary_reference(temp, loc);
11496 if (this->value_pointer_ == NULL)
11497 this->get_value_pointer(gogo);
11498 if (this->value_pointer_->is_error_expression()
11499 || this->value_pointer_->type()->is_error_type())
11500 return Expression::make_error(loc);
11501 if (!this->value_pointer_->is_variable())
11503 Temporary_statement* temp =
11504 Statement::make_temporary(NULL, this->value_pointer_, loc);
11505 inserter->insert(temp);
11506 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11509 return this;
11512 // Return the type of a map index.
11514 Type*
11515 Map_index_expression::do_type()
11517 Map_type* mt = this->get_map_type();
11518 if (mt == NULL)
11519 return Type::make_error_type();
11520 return mt->val_type();
11523 // Fix the type of a map index.
11525 void
11526 Map_index_expression::do_determine_type(const Type_context*)
11528 this->map_->determine_type_no_context();
11529 Map_type* mt = this->get_map_type();
11530 Type* key_type = mt == NULL ? NULL : mt->key_type();
11531 Type_context subcontext(key_type, false);
11532 this->index_->determine_type(&subcontext);
11535 // Check types of a map index.
11537 void
11538 Map_index_expression::do_check_types(Gogo*)
11540 std::string reason;
11541 Map_type* mt = this->get_map_type();
11542 if (mt == NULL)
11543 return;
11544 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11546 if (reason.empty())
11547 this->report_error(_("incompatible type for map index"));
11548 else
11550 go_error_at(this->location(), "incompatible type for map index (%s)",
11551 reason.c_str());
11552 this->set_is_error();
11557 // Get the backend representation for a map index.
11559 Bexpression*
11560 Map_index_expression::do_get_backend(Translate_context* context)
11562 Map_type* type = this->get_map_type();
11563 if (type == NULL)
11565 go_assert(saw_errors());
11566 return context->backend()->error_expression();
11569 go_assert(this->value_pointer_ != NULL
11570 && this->value_pointer_->is_variable());
11572 Expression* val = Expression::make_dereference(this->value_pointer_,
11573 NIL_CHECK_NOT_NEEDED,
11574 this->location());
11575 return val->get_backend(context);
11578 // Get an expression for the map index. This returns an expression
11579 // that evaluates to a pointer to a value. If the key is not in the
11580 // map, the pointer will point to a zero value.
11582 Expression*
11583 Map_index_expression::get_value_pointer(Gogo* gogo)
11585 if (this->value_pointer_ == NULL)
11587 Map_type* type = this->get_map_type();
11588 if (type == NULL)
11590 go_assert(saw_errors());
11591 return Expression::make_error(this->location());
11594 Location loc = this->location();
11595 Expression* map_ref = this->map_;
11597 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11598 this->index_,
11599 loc);
11601 Expression* zero = type->fat_zero_value(gogo);
11603 Expression* map_index;
11605 if (zero == NULL)
11606 map_index =
11607 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11608 Expression::make_type_descriptor(type, loc),
11609 map_ref, index_ptr);
11610 else
11611 map_index =
11612 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11613 Expression::make_type_descriptor(type, loc),
11614 map_ref, index_ptr, zero);
11616 Type* val_type = type->val_type();
11617 this->value_pointer_ =
11618 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11619 map_index, this->location());
11622 return this->value_pointer_;
11625 // Dump ast representation for a map index expression
11627 void
11628 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11629 const
11631 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11632 this->index_, NULL, NULL);
11635 // Make a map index expression.
11637 Map_index_expression*
11638 Expression::make_map_index(Expression* map, Expression* index,
11639 Location location)
11641 return new Map_index_expression(map, index, location);
11644 // Class Field_reference_expression.
11646 // Lower a field reference expression. There is nothing to lower, but
11647 // this is where we generate the tracking information for fields with
11648 // the magic go:"track" tag.
11650 Expression*
11651 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11652 Statement_inserter* inserter, int)
11654 Struct_type* struct_type = this->expr_->type()->struct_type();
11655 if (struct_type == NULL)
11657 // Error will be reported elsewhere.
11658 return this;
11660 const Struct_field* field = struct_type->field(this->field_index_);
11661 if (field == NULL)
11662 return this;
11663 if (!field->has_tag())
11664 return this;
11665 if (field->tag().find("go:\"track\"") == std::string::npos)
11666 return this;
11668 // References from functions generated by the compiler don't count.
11669 if (function != NULL && function->func_value()->is_type_specific_function())
11670 return this;
11672 // We have found a reference to a tracked field. Build a call to
11673 // the runtime function __go_fieldtrack with a string that describes
11674 // the field. FIXME: We should only call this once per referenced
11675 // field per function, not once for each reference to the field.
11677 if (this->called_fieldtrack_)
11678 return this;
11679 this->called_fieldtrack_ = true;
11681 Location loc = this->location();
11683 std::string s = "fieldtrack \"";
11684 Named_type* nt = this->expr_->type()->named_type();
11685 if (nt == NULL || nt->named_object()->package() == NULL)
11686 s.append(gogo->pkgpath());
11687 else
11688 s.append(nt->named_object()->package()->pkgpath());
11689 s.push_back('.');
11690 if (nt != NULL)
11691 s.append(Gogo::unpack_hidden_name(nt->name()));
11692 s.push_back('.');
11693 s.append(field->field_name());
11694 s.push_back('"');
11696 // We can't use a string here, because internally a string holds a
11697 // pointer to the actual bytes; when the linker garbage collects the
11698 // string, it won't garbage collect the bytes. So we use a
11699 // [...]byte.
11701 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11703 Type* byte_type = gogo->lookup_global("byte")->type_value();
11704 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11705 array_type->set_is_array_incomparable();
11707 Expression_list* bytes = new Expression_list();
11708 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11710 unsigned char c = static_cast<unsigned char>(*p);
11711 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11714 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11715 bytes, false, loc);
11717 Variable* var = new Variable(array_type, e, true, false, false, loc);
11719 static int count;
11720 char buf[50];
11721 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11722 ++count;
11724 Named_object* no = gogo->add_variable(buf, var);
11725 e = Expression::make_var_reference(no, loc);
11726 e = Expression::make_unary(OPERATOR_AND, e, loc);
11728 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11729 gogo->lower_expression(function, inserter, &call);
11730 inserter->insert(Statement::make_statement(call, false));
11732 // Put this function, and the global variable we just created, into
11733 // unique sections. This will permit the linker to garbage collect
11734 // them if they are not referenced. The effect is that the only
11735 // strings, indicating field references, that will wind up in the
11736 // executable will be those for functions that are actually needed.
11737 if (function != NULL)
11738 function->func_value()->set_in_unique_section();
11739 var->set_in_unique_section();
11741 return this;
11744 // Return the type of a field reference.
11746 Type*
11747 Field_reference_expression::do_type()
11749 Type* type = this->expr_->type();
11750 if (type->is_error())
11751 return type;
11752 Struct_type* struct_type = type->struct_type();
11753 go_assert(struct_type != NULL);
11754 return struct_type->field(this->field_index_)->type();
11757 // Check the types for a field reference.
11759 void
11760 Field_reference_expression::do_check_types(Gogo*)
11762 Type* type = this->expr_->type();
11763 if (type->is_error())
11764 return;
11765 Struct_type* struct_type = type->struct_type();
11766 go_assert(struct_type != NULL);
11767 go_assert(struct_type->field(this->field_index_) != NULL);
11770 // Get the backend representation for a field reference.
11772 Bexpression*
11773 Field_reference_expression::do_get_backend(Translate_context* context)
11775 Bexpression* bstruct = this->expr_->get_backend(context);
11776 return context->gogo()->backend()->struct_field_expression(bstruct,
11777 this->field_index_,
11778 this->location());
11781 // Dump ast representation for a field reference expression.
11783 void
11784 Field_reference_expression::do_dump_expression(
11785 Ast_dump_context* ast_dump_context) const
11787 this->expr_->dump_expression(ast_dump_context);
11788 ast_dump_context->ostream() << "." << this->field_index_;
11791 // Make a reference to a qualified identifier in an expression.
11793 Field_reference_expression*
11794 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11795 Location location)
11797 return new Field_reference_expression(expr, field_index, location);
11800 // Class Interface_field_reference_expression.
11802 // Return an expression for the pointer to the function to call.
11804 Expression*
11805 Interface_field_reference_expression::get_function()
11807 Expression* ref = this->expr_;
11808 Location loc = this->location();
11809 if (ref->type()->points_to() != NULL)
11810 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
11812 Expression* mtable =
11813 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11814 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11816 std::string name = Gogo::unpack_hidden_name(this->name_);
11817 unsigned int index;
11818 const Struct_field* field = mtable_type->find_local_field(name, &index);
11819 go_assert(field != NULL);
11821 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
11822 return Expression::make_field_reference(mtable, index, loc);
11825 // Return an expression for the first argument to pass to the interface
11826 // function.
11828 Expression*
11829 Interface_field_reference_expression::get_underlying_object()
11831 Expression* expr = this->expr_;
11832 if (expr->type()->points_to() != NULL)
11833 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
11834 this->location());
11835 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11836 this->location());
11839 // Traversal.
11842 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11844 return Expression::traverse(&this->expr_, traverse);
11847 // Lower the expression. If this expression is not called, we need to
11848 // evaluate the expression twice when converting to the backend
11849 // interface. So introduce a temporary variable if necessary.
11851 Expression*
11852 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11853 Statement_inserter* inserter)
11855 if (this->expr_->is_error_expression()
11856 || this->expr_->type()->is_error_type())
11858 go_assert(saw_errors());
11859 return Expression::make_error(this->location());
11862 if (!this->expr_->is_variable())
11864 Temporary_statement* temp =
11865 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11866 inserter->insert(temp);
11867 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11868 this->location());
11870 return this;
11873 // Return the type of an interface field reference.
11875 Type*
11876 Interface_field_reference_expression::do_type()
11878 Type* expr_type = this->expr_->type();
11880 Type* points_to = expr_type->points_to();
11881 if (points_to != NULL)
11882 expr_type = points_to;
11884 Interface_type* interface_type = expr_type->interface_type();
11885 if (interface_type == NULL)
11886 return Type::make_error_type();
11888 const Typed_identifier* method = interface_type->find_method(this->name_);
11889 if (method == NULL)
11890 return Type::make_error_type();
11892 return method->type();
11895 // Determine types.
11897 void
11898 Interface_field_reference_expression::do_determine_type(const Type_context*)
11900 this->expr_->determine_type_no_context();
11903 // Check the types for an interface field reference.
11905 void
11906 Interface_field_reference_expression::do_check_types(Gogo*)
11908 Type* type = this->expr_->type();
11910 Type* points_to = type->points_to();
11911 if (points_to != NULL)
11912 type = points_to;
11914 Interface_type* interface_type = type->interface_type();
11915 if (interface_type == NULL)
11917 if (!type->is_error_type())
11918 this->report_error(_("expected interface or pointer to interface"));
11920 else
11922 const Typed_identifier* method =
11923 interface_type->find_method(this->name_);
11924 if (method == NULL)
11926 go_error_at(this->location(), "method %qs not in interface",
11927 Gogo::message_name(this->name_).c_str());
11928 this->set_is_error();
11933 // If an interface field reference is not simply called, then it is
11934 // represented as a closure. The closure will hold a single variable,
11935 // the value of the interface on which the method should be called.
11936 // The function will be a simple thunk that pulls the value from the
11937 // closure and calls the method with the remaining arguments.
11939 // Because method values are not common, we don't build all thunks for
11940 // all possible interface methods, but instead only build them as we
11941 // need them. In particular, we even build them on demand for
11942 // interface methods defined in other packages.
11944 Interface_field_reference_expression::Interface_method_thunks
11945 Interface_field_reference_expression::interface_method_thunks;
11947 // Find or create the thunk to call method NAME on TYPE.
11949 Named_object*
11950 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11951 Interface_type* type,
11952 const std::string& name)
11954 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11955 std::pair<Interface_method_thunks::iterator, bool> ins =
11956 Interface_field_reference_expression::interface_method_thunks.insert(val);
11957 if (ins.second)
11959 // This is the first time we have seen this interface.
11960 ins.first->second = new Method_thunks();
11963 for (Method_thunks::const_iterator p = ins.first->second->begin();
11964 p != ins.first->second->end();
11965 p++)
11966 if (p->first == name)
11967 return p->second;
11969 Location loc = type->location();
11971 const Typed_identifier* method_id = type->find_method(name);
11972 if (method_id == NULL)
11973 return Named_object::make_erroneous_name(gogo->thunk_name());
11975 Function_type* orig_fntype = method_id->type()->function_type();
11976 if (orig_fntype == NULL)
11977 return Named_object::make_erroneous_name(gogo->thunk_name());
11979 Struct_field_list* sfl = new Struct_field_list();
11980 // The type here is wrong--it should be the C function type. But it
11981 // doesn't really matter.
11982 Type* vt = Type::make_pointer_type(Type::make_void_type());
11983 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
11984 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
11985 Struct_type* st = Type::make_struct_type(sfl, loc);
11986 st->set_is_struct_incomparable();
11987 Type* closure_type = Type::make_pointer_type(st);
11989 Function_type* new_fntype = orig_fntype->copy_with_names();
11991 std::string thunk_name = gogo->thunk_name();
11992 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11993 false, loc);
11995 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11996 cvar->set_is_used();
11997 cvar->set_is_closure();
11998 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11999 NULL, cvar);
12000 new_no->func_value()->set_closure_var(cp);
12002 gogo->start_block(loc);
12004 // Field 0 of the closure is the function code pointer, field 1 is
12005 // the value on which to invoke the method.
12006 Expression* arg = Expression::make_var_reference(cp, loc);
12007 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
12008 arg = Expression::make_field_reference(arg, 1, loc);
12010 Expression *ifre = Expression::make_interface_field_reference(arg, name,
12011 loc);
12013 const Typed_identifier_list* orig_params = orig_fntype->parameters();
12014 Expression_list* args;
12015 if (orig_params == NULL || orig_params->empty())
12016 args = NULL;
12017 else
12019 const Typed_identifier_list* new_params = new_fntype->parameters();
12020 args = new Expression_list();
12021 for (Typed_identifier_list::const_iterator p = new_params->begin();
12022 p != new_params->end();
12023 ++p)
12025 Named_object* p_no = gogo->lookup(p->name(), NULL);
12026 go_assert(p_no != NULL
12027 && p_no->is_variable()
12028 && p_no->var_value()->is_parameter());
12029 args->push_back(Expression::make_var_reference(p_no, loc));
12033 Call_expression* call = Expression::make_call(ifre, args,
12034 orig_fntype->is_varargs(),
12035 loc);
12036 call->set_varargs_are_lowered();
12038 Statement* s = Statement::make_return_from_call(call, loc);
12039 gogo->add_statement(s);
12040 Block* b = gogo->finish_block(loc);
12041 gogo->add_block(b, loc);
12042 gogo->lower_block(new_no, b);
12043 gogo->flatten_block(new_no, b);
12044 gogo->finish_function(loc);
12046 ins.first->second->push_back(std::make_pair(name, new_no));
12047 return new_no;
12050 // Get the backend representation for a method value.
12052 Bexpression*
12053 Interface_field_reference_expression::do_get_backend(Translate_context* context)
12055 Interface_type* type = this->expr_->type()->interface_type();
12056 if (type == NULL)
12058 go_assert(saw_errors());
12059 return context->backend()->error_expression();
12062 Named_object* thunk =
12063 Interface_field_reference_expression::create_thunk(context->gogo(),
12064 type, this->name_);
12065 if (thunk->is_erroneous())
12067 go_assert(saw_errors());
12068 return context->backend()->error_expression();
12071 // FIXME: We should lower this earlier, but we can't it lower it in
12072 // the lowering pass because at that point we don't know whether we
12073 // need to create the thunk or not. If the expression is called, we
12074 // don't need the thunk.
12076 Location loc = this->location();
12078 Struct_field_list* fields = new Struct_field_list();
12079 fields->push_back(Struct_field(Typed_identifier("fn",
12080 thunk->func_value()->type(),
12081 loc)));
12082 fields->push_back(Struct_field(Typed_identifier("val",
12083 this->expr_->type(),
12084 loc)));
12085 Struct_type* st = Type::make_struct_type(fields, loc);
12086 st->set_is_struct_incomparable();
12088 Expression_list* vals = new Expression_list();
12089 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12090 vals->push_back(this->expr_);
12092 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12093 Bexpression* bclosure =
12094 Expression::make_heap_expression(expr, loc)->get_backend(context);
12096 Gogo* gogo = context->gogo();
12097 Btype* btype = this->type()->get_backend(gogo);
12098 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12100 Expression* nil_check =
12101 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12102 Expression::make_nil(loc), loc);
12103 Bexpression* bnil_check = nil_check->get_backend(context);
12105 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12106 loc)->get_backend(context);
12108 Bfunction* bfn = context->function()->func_value()->get_decl();
12109 Bexpression* bcond =
12110 gogo->backend()->conditional_expression(bfn, NULL,
12111 bnil_check, bcrash, NULL, loc);
12112 Bfunction* bfunction = context->function()->func_value()->get_decl();
12113 Bstatement* cond_statement =
12114 gogo->backend()->expression_statement(bfunction, bcond);
12115 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12118 // Dump ast representation for an interface field reference.
12120 void
12121 Interface_field_reference_expression::do_dump_expression(
12122 Ast_dump_context* ast_dump_context) const
12124 this->expr_->dump_expression(ast_dump_context);
12125 ast_dump_context->ostream() << "." << this->name_;
12128 // Make a reference to a field in an interface.
12130 Expression*
12131 Expression::make_interface_field_reference(Expression* expr,
12132 const std::string& field,
12133 Location location)
12135 return new Interface_field_reference_expression(expr, field, location);
12138 // A general selector. This is a Parser_expression for LEFT.NAME. It
12139 // is lowered after we know the type of the left hand side.
12141 class Selector_expression : public Parser_expression
12143 public:
12144 Selector_expression(Expression* left, const std::string& name,
12145 Location location)
12146 : Parser_expression(EXPRESSION_SELECTOR, location),
12147 left_(left), name_(name)
12150 protected:
12152 do_traverse(Traverse* traverse)
12153 { return Expression::traverse(&this->left_, traverse); }
12155 Expression*
12156 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12158 Expression*
12159 do_copy()
12161 return new Selector_expression(this->left_->copy(), this->name_,
12162 this->location());
12165 void
12166 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12168 private:
12169 Expression*
12170 lower_method_expression(Gogo*);
12172 // The expression on the left hand side.
12173 Expression* left_;
12174 // The name on the right hand side.
12175 std::string name_;
12178 // Lower a selector expression once we know the real type of the left
12179 // hand side.
12181 Expression*
12182 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12183 int)
12185 Expression* left = this->left_;
12186 if (left->is_type_expression())
12187 return this->lower_method_expression(gogo);
12188 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12189 this->location());
12192 // Lower a method expression T.M or (*T).M. We turn this into a
12193 // function literal.
12195 Expression*
12196 Selector_expression::lower_method_expression(Gogo* gogo)
12198 Location location = this->location();
12199 Type* left_type = this->left_->type();
12200 Type* type = left_type;
12201 const std::string& name(this->name_);
12203 bool is_pointer;
12204 if (type->points_to() == NULL)
12205 is_pointer = false;
12206 else
12208 is_pointer = true;
12209 type = type->points_to();
12211 Named_type* nt = type->named_type();
12212 if (nt == NULL)
12214 go_error_at(location,
12215 ("method expression requires named type or "
12216 "pointer to named type"));
12217 return Expression::make_error(location);
12220 bool is_ambiguous;
12221 Method* method = nt->method_function(name, &is_ambiguous);
12222 const Typed_identifier* imethod = NULL;
12223 if (method == NULL && !is_pointer)
12225 Interface_type* it = nt->interface_type();
12226 if (it != NULL)
12227 imethod = it->find_method(name);
12230 if ((method == NULL && imethod == NULL)
12231 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12233 if (!is_ambiguous)
12234 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12235 is_pointer ? "*" : "",
12236 nt->message_name().c_str(),
12237 Gogo::message_name(name).c_str());
12238 else
12239 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12240 Gogo::message_name(name).c_str(),
12241 is_pointer ? "*" : "",
12242 nt->message_name().c_str());
12243 return Expression::make_error(location);
12246 if (method != NULL && !is_pointer && !method->is_value_method())
12248 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12249 nt->message_name().c_str(),
12250 Gogo::message_name(name).c_str());
12251 return Expression::make_error(location);
12254 // Build a new function type in which the receiver becomes the first
12255 // argument.
12256 Function_type* method_type;
12257 if (method != NULL)
12259 method_type = method->type();
12260 go_assert(method_type->is_method());
12262 else
12264 method_type = imethod->type()->function_type();
12265 go_assert(method_type != NULL && !method_type->is_method());
12268 const char* const receiver_name = "$this";
12269 Typed_identifier_list* parameters = new Typed_identifier_list();
12270 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12271 location));
12273 const Typed_identifier_list* method_parameters = method_type->parameters();
12274 if (method_parameters != NULL)
12276 int i = 0;
12277 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12278 p != method_parameters->end();
12279 ++p, ++i)
12281 if (!p->name().empty())
12282 parameters->push_back(*p);
12283 else
12285 char buf[20];
12286 snprintf(buf, sizeof buf, "$param%d", i);
12287 parameters->push_back(Typed_identifier(buf, p->type(),
12288 p->location()));
12293 const Typed_identifier_list* method_results = method_type->results();
12294 Typed_identifier_list* results;
12295 if (method_results == NULL)
12296 results = NULL;
12297 else
12299 results = new Typed_identifier_list();
12300 for (Typed_identifier_list::const_iterator p = method_results->begin();
12301 p != method_results->end();
12302 ++p)
12303 results->push_back(*p);
12306 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12307 location);
12308 if (method_type->is_varargs())
12309 fntype->set_is_varargs();
12311 // We generate methods which always takes a pointer to the receiver
12312 // as their first argument. If this is for a pointer type, we can
12313 // simply reuse the existing function. We use an internal hack to
12314 // get the right type.
12315 // FIXME: This optimization is disabled because it doesn't yet work
12316 // with function descriptors when the method expression is not
12317 // directly called.
12318 if (method != NULL && is_pointer && false)
12320 Named_object* mno = (method->needs_stub_method()
12321 ? method->stub_object()
12322 : method->named_object());
12323 Expression* f = Expression::make_func_reference(mno, NULL, location);
12324 f = Expression::make_cast(fntype, f, location);
12325 Type_conversion_expression* tce =
12326 static_cast<Type_conversion_expression*>(f);
12327 tce->set_may_convert_function_types();
12328 return f;
12331 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
12332 location);
12334 Named_object* vno = gogo->lookup(receiver_name, NULL);
12335 go_assert(vno != NULL);
12336 Expression* ve = Expression::make_var_reference(vno, location);
12337 Expression* bm;
12338 if (method != NULL)
12339 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12340 else
12341 bm = Expression::make_interface_field_reference(ve, name, location);
12343 // Even though we found the method above, if it has an error type we
12344 // may see an error here.
12345 if (bm->is_error_expression())
12347 gogo->finish_function(location);
12348 return bm;
12351 Expression_list* args;
12352 if (parameters->size() <= 1)
12353 args = NULL;
12354 else
12356 args = new Expression_list();
12357 Typed_identifier_list::const_iterator p = parameters->begin();
12358 ++p;
12359 for (; p != parameters->end(); ++p)
12361 vno = gogo->lookup(p->name(), NULL);
12362 go_assert(vno != NULL);
12363 args->push_back(Expression::make_var_reference(vno, location));
12367 gogo->start_block(location);
12369 Call_expression* call = Expression::make_call(bm, args,
12370 method_type->is_varargs(),
12371 location);
12373 Statement* s = Statement::make_return_from_call(call, location);
12374 gogo->add_statement(s);
12376 Block* b = gogo->finish_block(location);
12378 gogo->add_block(b, location);
12380 // Lower the call in case there are multiple results.
12381 gogo->lower_block(no, b);
12382 gogo->flatten_block(no, b);
12384 gogo->finish_function(location);
12386 return Expression::make_func_reference(no, NULL, location);
12389 // Dump the ast for a selector expression.
12391 void
12392 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12393 const
12395 ast_dump_context->dump_expression(this->left_);
12396 ast_dump_context->ostream() << ".";
12397 ast_dump_context->ostream() << this->name_;
12400 // Make a selector expression.
12402 Expression*
12403 Expression::make_selector(Expression* left, const std::string& name,
12404 Location location)
12406 return new Selector_expression(left, name, location);
12409 // Class Allocation_expression.
12412 Allocation_expression::do_traverse(Traverse* traverse)
12414 return Type::traverse(this->type_, traverse);
12417 Type*
12418 Allocation_expression::do_type()
12420 return Type::make_pointer_type(this->type_);
12423 void
12424 Allocation_expression::do_check_types(Gogo*)
12426 if (!this->type_->in_heap())
12427 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12430 // Make a copy of an allocation expression.
12432 Expression*
12433 Allocation_expression::do_copy()
12435 Allocation_expression* alloc =
12436 new Allocation_expression(this->type_->copy_expressions(),
12437 this->location());
12438 if (this->allocate_on_stack_)
12439 alloc->set_allocate_on_stack();
12440 return alloc;
12443 // Return the backend representation for an allocation expression.
12445 Bexpression*
12446 Allocation_expression::do_get_backend(Translate_context* context)
12448 Gogo* gogo = context->gogo();
12449 Location loc = this->location();
12450 Btype* btype = this->type_->get_backend(gogo);
12452 if (this->allocate_on_stack_)
12454 int64_t size;
12455 bool ok = this->type_->backend_type_size(gogo, &size);
12456 if (!ok)
12458 go_assert(saw_errors());
12459 return gogo->backend()->error_expression();
12461 Bstatement* decl;
12462 Named_object* fn = context->function();
12463 go_assert(fn != NULL);
12464 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
12465 Bexpression* zero = gogo->backend()->zero_expression(btype);
12466 Bvariable* temp =
12467 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
12468 zero, true, loc, &decl);
12469 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
12470 ret = gogo->backend()->address_expression(ret, loc);
12471 ret = gogo->backend()->compound_expression(decl, ret, loc);
12472 return ret;
12475 Bexpression* space =
12476 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12477 Btype* pbtype = gogo->backend()->pointer_type(btype);
12478 return gogo->backend()->convert_expression(pbtype, space, loc);
12481 // Dump ast representation for an allocation expression.
12483 void
12484 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12485 const
12487 ast_dump_context->ostream() << "new(";
12488 ast_dump_context->dump_type(this->type_);
12489 ast_dump_context->ostream() << ")";
12492 // Make an allocation expression.
12494 Expression*
12495 Expression::make_allocation(Type* type, Location location)
12497 return new Allocation_expression(type, location);
12500 // Class Ordered_value_list.
12503 Ordered_value_list::traverse_vals(Traverse* traverse)
12505 if (this->vals_ != NULL)
12507 if (this->traverse_order_ == NULL)
12509 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12510 return TRAVERSE_EXIT;
12512 else
12514 for (std::vector<unsigned long>::const_iterator p =
12515 this->traverse_order_->begin();
12516 p != this->traverse_order_->end();
12517 ++p)
12519 if (Expression::traverse(&this->vals_->at(*p), traverse)
12520 == TRAVERSE_EXIT)
12521 return TRAVERSE_EXIT;
12525 return TRAVERSE_CONTINUE;
12528 // Class Struct_construction_expression.
12530 // Traversal.
12533 Struct_construction_expression::do_traverse(Traverse* traverse)
12535 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12536 return TRAVERSE_EXIT;
12537 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12538 return TRAVERSE_EXIT;
12539 return TRAVERSE_CONTINUE;
12542 // Return whether this is a constant initializer.
12544 bool
12545 Struct_construction_expression::is_constant_struct() const
12547 if (this->vals() == NULL)
12548 return true;
12549 for (Expression_list::const_iterator pv = this->vals()->begin();
12550 pv != this->vals()->end();
12551 ++pv)
12553 if (*pv != NULL
12554 && !(*pv)->is_constant()
12555 && (!(*pv)->is_composite_literal()
12556 || (*pv)->is_nonconstant_composite_literal()))
12557 return false;
12560 const Struct_field_list* fields = this->type_->struct_type()->fields();
12561 for (Struct_field_list::const_iterator pf = fields->begin();
12562 pf != fields->end();
12563 ++pf)
12565 // There are no constant constructors for interfaces.
12566 if (pf->type()->interface_type() != NULL)
12567 return false;
12570 return true;
12573 // Return whether this struct can be used as a constant initializer.
12575 bool
12576 Struct_construction_expression::do_is_static_initializer() const
12578 if (this->vals() == NULL)
12579 return true;
12580 for (Expression_list::const_iterator pv = this->vals()->begin();
12581 pv != this->vals()->end();
12582 ++pv)
12584 if (*pv != NULL && !(*pv)->is_static_initializer())
12585 return false;
12588 const Struct_field_list* fields = this->type_->struct_type()->fields();
12589 for (Struct_field_list::const_iterator pf = fields->begin();
12590 pf != fields->end();
12591 ++pf)
12593 // There are no constant constructors for interfaces.
12594 if (pf->type()->interface_type() != NULL)
12595 return false;
12598 return true;
12601 // Final type determination.
12603 void
12604 Struct_construction_expression::do_determine_type(const Type_context*)
12606 if (this->vals() == NULL)
12607 return;
12608 const Struct_field_list* fields = this->type_->struct_type()->fields();
12609 Expression_list::const_iterator pv = this->vals()->begin();
12610 for (Struct_field_list::const_iterator pf = fields->begin();
12611 pf != fields->end();
12612 ++pf, ++pv)
12614 if (pv == this->vals()->end())
12615 return;
12616 if (*pv != NULL)
12618 Type_context subcontext(pf->type(), false);
12619 (*pv)->determine_type(&subcontext);
12622 // Extra values are an error we will report elsewhere; we still want
12623 // to determine the type to avoid knockon errors.
12624 for (; pv != this->vals()->end(); ++pv)
12625 (*pv)->determine_type_no_context();
12628 // Check types.
12630 void
12631 Struct_construction_expression::do_check_types(Gogo*)
12633 if (this->vals() == NULL)
12634 return;
12636 Struct_type* st = this->type_->struct_type();
12637 if (this->vals()->size() > st->field_count())
12639 this->report_error(_("too many expressions for struct"));
12640 return;
12643 const Struct_field_list* fields = st->fields();
12644 Expression_list::const_iterator pv = this->vals()->begin();
12645 int i = 0;
12646 for (Struct_field_list::const_iterator pf = fields->begin();
12647 pf != fields->end();
12648 ++pf, ++pv, ++i)
12650 if (pv == this->vals()->end())
12652 this->report_error(_("too few expressions for struct"));
12653 break;
12656 if (*pv == NULL)
12657 continue;
12659 std::string reason;
12660 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12662 if (reason.empty())
12663 go_error_at((*pv)->location(),
12664 "incompatible type for field %d in struct construction",
12665 i + 1);
12666 else
12667 go_error_at((*pv)->location(),
12668 ("incompatible type for field %d in "
12669 "struct construction (%s)"),
12670 i + 1, reason.c_str());
12671 this->set_is_error();
12674 go_assert(pv == this->vals()->end());
12677 // Copy.
12679 Expression*
12680 Struct_construction_expression::do_copy()
12682 Struct_construction_expression* ret =
12683 new Struct_construction_expression(this->type_->copy_expressions(),
12684 (this->vals() == NULL
12685 ? NULL
12686 : this->vals()->copy()),
12687 this->location());
12688 if (this->traverse_order() != NULL)
12689 ret->set_traverse_order(this->traverse_order());
12690 return ret;
12693 // Flatten a struct construction expression. Store the values into
12694 // temporaries in case they need interface conversion.
12696 Expression*
12697 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12698 Statement_inserter* inserter)
12700 if (this->vals() == NULL)
12701 return this;
12703 // If this is a constant struct, we don't need temporaries.
12704 if (this->is_constant_struct() || this->is_static_initializer())
12705 return this;
12707 Location loc = this->location();
12708 for (Expression_list::iterator pv = this->vals()->begin();
12709 pv != this->vals()->end();
12710 ++pv)
12712 if (*pv != NULL)
12714 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12716 go_assert(saw_errors());
12717 return Expression::make_error(loc);
12719 if (!(*pv)->is_variable())
12721 Temporary_statement* temp =
12722 Statement::make_temporary(NULL, *pv, loc);
12723 inserter->insert(temp);
12724 *pv = Expression::make_temporary_reference(temp, loc);
12728 return this;
12731 // Return the backend representation for constructing a struct.
12733 Bexpression*
12734 Struct_construction_expression::do_get_backend(Translate_context* context)
12736 Gogo* gogo = context->gogo();
12738 Btype* btype = this->type_->get_backend(gogo);
12739 if (this->vals() == NULL)
12740 return gogo->backend()->zero_expression(btype);
12742 const Struct_field_list* fields = this->type_->struct_type()->fields();
12743 Expression_list::const_iterator pv = this->vals()->begin();
12744 std::vector<Bexpression*> init;
12745 for (Struct_field_list::const_iterator pf = fields->begin();
12746 pf != fields->end();
12747 ++pf)
12749 Btype* fbtype = pf->type()->get_backend(gogo);
12750 if (pv == this->vals()->end())
12751 init.push_back(gogo->backend()->zero_expression(fbtype));
12752 else if (*pv == NULL)
12754 init.push_back(gogo->backend()->zero_expression(fbtype));
12755 ++pv;
12757 else
12759 Expression* val =
12760 Expression::convert_for_assignment(gogo, pf->type(),
12761 *pv, this->location());
12762 init.push_back(val->get_backend(context));
12763 ++pv;
12766 return gogo->backend()->constructor_expression(btype, init, this->location());
12769 // Export a struct construction.
12771 void
12772 Struct_construction_expression::do_export(Export* exp) const
12774 exp->write_c_string("convert(");
12775 exp->write_type(this->type_);
12776 for (Expression_list::const_iterator pv = this->vals()->begin();
12777 pv != this->vals()->end();
12778 ++pv)
12780 exp->write_c_string(", ");
12781 if (*pv != NULL)
12782 (*pv)->export_expression(exp);
12784 exp->write_c_string(")");
12787 // Dump ast representation of a struct construction expression.
12789 void
12790 Struct_construction_expression::do_dump_expression(
12791 Ast_dump_context* ast_dump_context) const
12793 ast_dump_context->dump_type(this->type_);
12794 ast_dump_context->ostream() << "{";
12795 ast_dump_context->dump_expression_list(this->vals());
12796 ast_dump_context->ostream() << "}";
12799 // Make a struct composite literal. This used by the thunk code.
12801 Expression*
12802 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12803 Location location)
12805 go_assert(type->struct_type() != NULL);
12806 return new Struct_construction_expression(type, vals, location);
12809 // Class Array_construction_expression.
12811 // Traversal.
12814 Array_construction_expression::do_traverse(Traverse* traverse)
12816 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12817 return TRAVERSE_EXIT;
12818 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12819 return TRAVERSE_EXIT;
12820 return TRAVERSE_CONTINUE;
12823 // Return whether this is a constant initializer.
12825 bool
12826 Array_construction_expression::is_constant_array() const
12828 if (this->vals() == NULL)
12829 return true;
12831 // There are no constant constructors for interfaces.
12832 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12833 return false;
12835 for (Expression_list::const_iterator pv = this->vals()->begin();
12836 pv != this->vals()->end();
12837 ++pv)
12839 if (*pv != NULL
12840 && !(*pv)->is_constant()
12841 && (!(*pv)->is_composite_literal()
12842 || (*pv)->is_nonconstant_composite_literal()))
12843 return false;
12845 return true;
12848 // Return whether this can be used a constant initializer.
12850 bool
12851 Array_construction_expression::do_is_static_initializer() const
12853 if (this->vals() == NULL)
12854 return true;
12856 // There are no constant constructors for interfaces.
12857 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12858 return false;
12860 for (Expression_list::const_iterator pv = this->vals()->begin();
12861 pv != this->vals()->end();
12862 ++pv)
12864 if (*pv != NULL && !(*pv)->is_static_initializer())
12865 return false;
12867 return true;
12870 // Final type determination.
12872 void
12873 Array_construction_expression::do_determine_type(const Type_context*)
12875 if (this->vals() == NULL)
12876 return;
12877 Type_context subcontext(this->type_->array_type()->element_type(), false);
12878 for (Expression_list::const_iterator pv = this->vals()->begin();
12879 pv != this->vals()->end();
12880 ++pv)
12882 if (*pv != NULL)
12883 (*pv)->determine_type(&subcontext);
12887 // Check types.
12889 void
12890 Array_construction_expression::do_check_types(Gogo*)
12892 if (this->vals() == NULL)
12893 return;
12895 Array_type* at = this->type_->array_type();
12896 int i = 0;
12897 Type* element_type = at->element_type();
12898 for (Expression_list::const_iterator pv = this->vals()->begin();
12899 pv != this->vals()->end();
12900 ++pv, ++i)
12902 if (*pv != NULL
12903 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12905 go_error_at((*pv)->location(),
12906 "incompatible type for element %d in composite literal",
12907 i + 1);
12908 this->set_is_error();
12913 // Flatten an array construction expression. Store the values into
12914 // temporaries in case they need interface conversion.
12916 Expression*
12917 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12918 Statement_inserter* inserter)
12920 if (this->vals() == NULL)
12921 return this;
12923 // If this is a constant array, we don't need temporaries.
12924 if (this->is_constant_array() || this->is_static_initializer())
12925 return this;
12927 Location loc = this->location();
12928 for (Expression_list::iterator pv = this->vals()->begin();
12929 pv != this->vals()->end();
12930 ++pv)
12932 if (*pv != NULL)
12934 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12936 go_assert(saw_errors());
12937 return Expression::make_error(loc);
12939 if (!(*pv)->is_variable())
12941 Temporary_statement* temp =
12942 Statement::make_temporary(NULL, *pv, loc);
12943 inserter->insert(temp);
12944 *pv = Expression::make_temporary_reference(temp, loc);
12948 return this;
12951 // Get a constructor expression for the array values.
12953 Bexpression*
12954 Array_construction_expression::get_constructor(Translate_context* context,
12955 Btype* array_btype)
12957 Type* element_type = this->type_->array_type()->element_type();
12959 std::vector<unsigned long> indexes;
12960 std::vector<Bexpression*> vals;
12961 Gogo* gogo = context->gogo();
12962 if (this->vals() != NULL)
12964 size_t i = 0;
12965 std::vector<unsigned long>::const_iterator pi;
12966 if (this->indexes_ != NULL)
12967 pi = this->indexes_->begin();
12968 for (Expression_list::const_iterator pv = this->vals()->begin();
12969 pv != this->vals()->end();
12970 ++pv, ++i)
12972 if (this->indexes_ != NULL)
12973 go_assert(pi != this->indexes_->end());
12975 if (this->indexes_ == NULL)
12976 indexes.push_back(i);
12977 else
12978 indexes.push_back(*pi);
12979 if (*pv == NULL)
12981 Btype* ebtype = element_type->get_backend(gogo);
12982 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12983 vals.push_back(zv);
12985 else
12987 Expression* val_expr =
12988 Expression::convert_for_assignment(gogo, element_type, *pv,
12989 this->location());
12990 vals.push_back(val_expr->get_backend(context));
12992 if (this->indexes_ != NULL)
12993 ++pi;
12995 if (this->indexes_ != NULL)
12996 go_assert(pi == this->indexes_->end());
12998 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12999 vals, this->location());
13002 // Export an array construction.
13004 void
13005 Array_construction_expression::do_export(Export* exp) const
13007 exp->write_c_string("convert(");
13008 exp->write_type(this->type_);
13009 if (this->vals() != NULL)
13011 std::vector<unsigned long>::const_iterator pi;
13012 if (this->indexes_ != NULL)
13013 pi = this->indexes_->begin();
13014 for (Expression_list::const_iterator pv = this->vals()->begin();
13015 pv != this->vals()->end();
13016 ++pv)
13018 exp->write_c_string(", ");
13020 if (this->indexes_ != NULL)
13022 char buf[100];
13023 snprintf(buf, sizeof buf, "%lu", *pi);
13024 exp->write_c_string(buf);
13025 exp->write_c_string(":");
13028 if (*pv != NULL)
13029 (*pv)->export_expression(exp);
13031 if (this->indexes_ != NULL)
13032 ++pi;
13035 exp->write_c_string(")");
13038 // Dump ast representation of an array construction expression.
13040 void
13041 Array_construction_expression::do_dump_expression(
13042 Ast_dump_context* ast_dump_context) const
13044 Expression* length = this->type_->array_type()->length();
13046 ast_dump_context->ostream() << "[" ;
13047 if (length != NULL)
13049 ast_dump_context->dump_expression(length);
13051 ast_dump_context->ostream() << "]" ;
13052 ast_dump_context->dump_type(this->type_);
13053 this->dump_slice_storage_expression(ast_dump_context);
13054 ast_dump_context->ostream() << "{" ;
13055 if (this->indexes_ == NULL)
13056 ast_dump_context->dump_expression_list(this->vals());
13057 else
13059 Expression_list::const_iterator pv = this->vals()->begin();
13060 for (std::vector<unsigned long>::const_iterator pi =
13061 this->indexes_->begin();
13062 pi != this->indexes_->end();
13063 ++pi, ++pv)
13065 if (pi != this->indexes_->begin())
13066 ast_dump_context->ostream() << ", ";
13067 ast_dump_context->ostream() << *pi << ':';
13068 ast_dump_context->dump_expression(*pv);
13071 ast_dump_context->ostream() << "}" ;
13075 // Class Fixed_array_construction_expression.
13077 Fixed_array_construction_expression::Fixed_array_construction_expression(
13078 Type* type, const std::vector<unsigned long>* indexes,
13079 Expression_list* vals, Location location)
13080 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13081 type, indexes, vals, location)
13082 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13085 // Copy.
13087 Expression*
13088 Fixed_array_construction_expression::do_copy()
13090 Type* t = this->type()->copy_expressions();
13091 return new Fixed_array_construction_expression(t, this->indexes(),
13092 (this->vals() == NULL
13093 ? NULL
13094 : this->vals()->copy()),
13095 this->location());
13098 // Return the backend representation for constructing a fixed array.
13100 Bexpression*
13101 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13103 Type* type = this->type();
13104 Btype* btype = type->get_backend(context->gogo());
13105 return this->get_constructor(context, btype);
13108 Expression*
13109 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13110 Location location)
13112 go_assert(type->array_type() != NULL && !type->is_slice_type());
13113 return new Fixed_array_construction_expression(type, NULL, vals, location);
13116 // Class Slice_construction_expression.
13118 Slice_construction_expression::Slice_construction_expression(
13119 Type* type, const std::vector<unsigned long>* indexes,
13120 Expression_list* vals, Location location)
13121 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13122 type, indexes, vals, location),
13123 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13124 storage_escapes_(true)
13126 go_assert(type->is_slice_type());
13128 unsigned long lenval;
13129 Expression* length;
13130 if (vals == NULL || vals->empty())
13131 lenval = 0;
13132 else
13134 if (this->indexes() == NULL)
13135 lenval = vals->size();
13136 else
13137 lenval = indexes->back() + 1;
13139 Type* int_type = Type::lookup_integer_type("int");
13140 length = Expression::make_integer_ul(lenval, int_type, location);
13141 Type* element_type = type->array_type()->element_type();
13142 Array_type* array_type = Type::make_array_type(element_type, length);
13143 array_type->set_is_array_incomparable();
13144 this->valtype_ = array_type;
13147 // Traversal.
13150 Slice_construction_expression::do_traverse(Traverse* traverse)
13152 if (this->Array_construction_expression::do_traverse(traverse)
13153 == TRAVERSE_EXIT)
13154 return TRAVERSE_EXIT;
13155 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13156 return TRAVERSE_EXIT;
13157 if (this->array_val_ != NULL
13158 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13159 return TRAVERSE_EXIT;
13160 if (this->slice_storage_ != NULL
13161 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13162 return TRAVERSE_EXIT;
13163 return TRAVERSE_CONTINUE;
13166 // Helper routine to create fixed array value underlying the slice literal.
13167 // May be called during flattening, or later during do_get_backend().
13169 Expression*
13170 Slice_construction_expression::create_array_val()
13172 Array_type* array_type = this->type()->array_type();
13173 if (array_type == NULL)
13175 go_assert(this->type()->is_error());
13176 return NULL;
13179 Location loc = this->location();
13180 go_assert(this->valtype_ != NULL);
13182 Expression_list* vals = this->vals();
13183 return new Fixed_array_construction_expression(
13184 this->valtype_, this->indexes(), vals, loc);
13187 // If we're previous established that the slice storage does not
13188 // escape, then create a separate array temp val here for it. We
13189 // need to do this as part of flattening so as to be able to insert
13190 // the new temp statement.
13192 Expression*
13193 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13194 Statement_inserter* inserter)
13196 if (this->type()->array_type() == NULL)
13197 return NULL;
13199 // Base class flattening first
13200 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13202 // Create a stack-allocated storage temp if storage won't escape
13203 if (!this->storage_escapes_
13204 && this->slice_storage_ == NULL
13205 && this->element_count() > 0)
13207 Location loc = this->location();
13208 this->array_val_ = this->create_array_val();
13209 go_assert(this->array_val_);
13210 Temporary_statement* temp =
13211 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13212 inserter->insert(temp);
13213 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13215 return this;
13218 // When dumping a slice construction expression that has an explicit
13219 // storeage temp, emit the temp here (if we don't do this the storage
13220 // temp appears unused in the AST dump).
13222 void
13223 Slice_construction_expression::
13224 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13226 if (this->slice_storage_ == NULL)
13227 return;
13228 ast_dump_context->ostream() << "storage=" ;
13229 ast_dump_context->dump_expression(this->slice_storage_);
13232 // Copy.
13234 Expression*
13235 Slice_construction_expression::do_copy()
13237 return new Slice_construction_expression(this->type()->copy_expressions(),
13238 this->indexes(),
13239 (this->vals() == NULL
13240 ? NULL
13241 : this->vals()->copy()),
13242 this->location());
13245 // Return the backend representation for constructing a slice.
13247 Bexpression*
13248 Slice_construction_expression::do_get_backend(Translate_context* context)
13250 if (this->array_val_ == NULL)
13251 this->array_val_ = this->create_array_val();
13252 if (this->array_val_ == NULL)
13254 go_assert(this->type()->is_error());
13255 return context->backend()->error_expression();
13258 Location loc = this->location();
13260 bool is_static_initializer = this->array_val_->is_static_initializer();
13262 // We have to copy the initial values into heap memory if we are in
13263 // a function or if the values are not constants.
13264 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13266 Expression* space;
13268 if (this->slice_storage_ != NULL)
13270 go_assert(!this->storage_escapes_);
13271 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13273 else if (!copy_to_heap)
13275 // The initializer will only run once.
13276 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13277 space->unary_expression()->set_is_slice_init();
13279 else
13281 go_assert(this->storage_escapes_ || this->element_count() == 0);
13282 space = Expression::make_heap_expression(this->array_val_, loc);
13285 // Build a constructor for the slice.
13286 Expression* len = this->valtype_->array_type()->length();
13287 Expression* slice_val =
13288 Expression::make_slice_value(this->type(), space, len, len, loc);
13289 return slice_val->get_backend(context);
13292 // Make a slice composite literal. This is used by the type
13293 // descriptor code.
13295 Slice_construction_expression*
13296 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13297 Location location)
13299 go_assert(type->is_slice_type());
13300 return new Slice_construction_expression(type, NULL, vals, location);
13303 // Class Map_construction_expression.
13305 // Traversal.
13308 Map_construction_expression::do_traverse(Traverse* traverse)
13310 if (this->vals_ != NULL
13311 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13312 return TRAVERSE_EXIT;
13313 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13314 return TRAVERSE_EXIT;
13315 return TRAVERSE_CONTINUE;
13318 // Flatten constructor initializer into a temporary variable since
13319 // we need to take its address for __go_construct_map.
13321 Expression*
13322 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13323 Statement_inserter* inserter)
13325 if (!this->is_error_expression()
13326 && this->vals_ != NULL
13327 && !this->vals_->empty()
13328 && this->constructor_temp_ == NULL)
13330 Map_type* mt = this->type_->map_type();
13331 Type* key_type = mt->key_type();
13332 Type* val_type = mt->val_type();
13333 this->element_type_ = Type::make_builtin_struct_type(2,
13334 "__key", key_type,
13335 "__val", val_type);
13337 Expression_list* value_pairs = new Expression_list();
13338 Location loc = this->location();
13340 size_t i = 0;
13341 for (Expression_list::const_iterator pv = this->vals_->begin();
13342 pv != this->vals_->end();
13343 ++pv, ++i)
13345 Expression_list* key_value_pair = new Expression_list();
13346 Expression* key = *pv;
13347 if (key->is_error_expression() || key->type()->is_error_type())
13349 go_assert(saw_errors());
13350 return Expression::make_error(loc);
13352 if (key->type()->interface_type() != NULL && !key->is_variable())
13354 Temporary_statement* temp =
13355 Statement::make_temporary(NULL, key, loc);
13356 inserter->insert(temp);
13357 key = Expression::make_temporary_reference(temp, loc);
13359 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13361 ++pv;
13362 Expression* val = *pv;
13363 if (val->is_error_expression() || val->type()->is_error_type())
13365 go_assert(saw_errors());
13366 return Expression::make_error(loc);
13368 if (val->type()->interface_type() != NULL && !val->is_variable())
13370 Temporary_statement* temp =
13371 Statement::make_temporary(NULL, val, loc);
13372 inserter->insert(temp);
13373 val = Expression::make_temporary_reference(temp, loc);
13375 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13377 key_value_pair->push_back(key);
13378 key_value_pair->push_back(val);
13379 value_pairs->push_back(
13380 Expression::make_struct_composite_literal(this->element_type_,
13381 key_value_pair, loc));
13384 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13385 Array_type* ctor_type =
13386 Type::make_array_type(this->element_type_, element_count);
13387 ctor_type->set_is_array_incomparable();
13388 Expression* constructor =
13389 new Fixed_array_construction_expression(ctor_type, NULL,
13390 value_pairs, loc);
13392 this->constructor_temp_ =
13393 Statement::make_temporary(NULL, constructor, loc);
13394 constructor->issue_nil_check();
13395 this->constructor_temp_->set_is_address_taken();
13396 inserter->insert(this->constructor_temp_);
13399 return this;
13402 // Final type determination.
13404 void
13405 Map_construction_expression::do_determine_type(const Type_context*)
13407 if (this->vals_ == NULL)
13408 return;
13410 Map_type* mt = this->type_->map_type();
13411 Type_context key_context(mt->key_type(), false);
13412 Type_context val_context(mt->val_type(), false);
13413 for (Expression_list::const_iterator pv = this->vals_->begin();
13414 pv != this->vals_->end();
13415 ++pv)
13417 (*pv)->determine_type(&key_context);
13418 ++pv;
13419 (*pv)->determine_type(&val_context);
13423 // Check types.
13425 void
13426 Map_construction_expression::do_check_types(Gogo*)
13428 if (this->vals_ == NULL)
13429 return;
13431 Map_type* mt = this->type_->map_type();
13432 int i = 0;
13433 Type* key_type = mt->key_type();
13434 Type* val_type = mt->val_type();
13435 for (Expression_list::const_iterator pv = this->vals_->begin();
13436 pv != this->vals_->end();
13437 ++pv, ++i)
13439 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13441 go_error_at((*pv)->location(),
13442 "incompatible type for element %d key in map construction",
13443 i + 1);
13444 this->set_is_error();
13446 ++pv;
13447 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13449 go_error_at((*pv)->location(),
13450 ("incompatible type for element %d value "
13451 "in map construction"),
13452 i + 1);
13453 this->set_is_error();
13458 // Copy.
13460 Expression*
13461 Map_construction_expression::do_copy()
13463 return new Map_construction_expression(this->type_->copy_expressions(),
13464 (this->vals_ == NULL
13465 ? NULL
13466 : this->vals_->copy()),
13467 this->location());
13470 // Return the backend representation for constructing a map.
13472 Bexpression*
13473 Map_construction_expression::do_get_backend(Translate_context* context)
13475 if (this->is_error_expression())
13476 return context->backend()->error_expression();
13477 Location loc = this->location();
13479 size_t i = 0;
13480 Expression* ventries;
13481 if (this->vals_ == NULL || this->vals_->empty())
13482 ventries = Expression::make_nil(loc);
13483 else
13485 go_assert(this->constructor_temp_ != NULL);
13486 i = this->vals_->size() / 2;
13488 Expression* ctor_ref =
13489 Expression::make_temporary_reference(this->constructor_temp_, loc);
13490 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13493 Map_type* mt = this->type_->map_type();
13494 if (this->element_type_ == NULL)
13495 this->element_type_ =
13496 Type::make_builtin_struct_type(2,
13497 "__key", mt->key_type(),
13498 "__val", mt->val_type());
13499 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13501 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13502 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13504 Expression* entry_size =
13505 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13507 unsigned int field_index;
13508 const Struct_field* valfield =
13509 this->element_type_->find_local_field("__val", &field_index);
13510 Expression* val_offset =
13511 Expression::make_struct_field_offset(this->element_type_, valfield);
13513 Expression* map_ctor =
13514 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13515 entry_size, val_offset, ventries);
13516 return map_ctor->get_backend(context);
13519 // Export an array construction.
13521 void
13522 Map_construction_expression::do_export(Export* exp) const
13524 exp->write_c_string("convert(");
13525 exp->write_type(this->type_);
13526 for (Expression_list::const_iterator pv = this->vals_->begin();
13527 pv != this->vals_->end();
13528 ++pv)
13530 exp->write_c_string(", ");
13531 (*pv)->export_expression(exp);
13533 exp->write_c_string(")");
13536 // Dump ast representation for a map construction expression.
13538 void
13539 Map_construction_expression::do_dump_expression(
13540 Ast_dump_context* ast_dump_context) const
13542 ast_dump_context->ostream() << "{" ;
13543 ast_dump_context->dump_expression_list(this->vals_, true);
13544 ast_dump_context->ostream() << "}";
13547 // Class Composite_literal_expression.
13549 // Traversal.
13552 Composite_literal_expression::do_traverse(Traverse* traverse)
13554 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13555 return TRAVERSE_EXIT;
13557 // If this is a struct composite literal with keys, then the keys
13558 // are field names, not expressions. We don't want to traverse them
13559 // in that case. If we do, we can give an erroneous error "variable
13560 // initializer refers to itself." See bug482.go in the testsuite.
13561 if (this->has_keys_ && this->vals_ != NULL)
13563 // The type may not be resolvable at this point.
13564 Type* type = this->type_;
13566 for (int depth = 0; depth < this->depth_; ++depth)
13568 if (type->array_type() != NULL)
13569 type = type->array_type()->element_type();
13570 else if (type->map_type() != NULL)
13572 if (this->key_path_[depth])
13573 type = type->map_type()->key_type();
13574 else
13575 type = type->map_type()->val_type();
13577 else
13579 // This error will be reported during lowering.
13580 return TRAVERSE_CONTINUE;
13584 while (true)
13586 if (type->classification() == Type::TYPE_NAMED)
13587 type = type->named_type()->real_type();
13588 else if (type->classification() == Type::TYPE_FORWARD)
13590 Type* t = type->forwarded();
13591 if (t == type)
13592 break;
13593 type = t;
13595 else
13596 break;
13599 if (type->classification() == Type::TYPE_STRUCT)
13601 Expression_list::iterator p = this->vals_->begin();
13602 while (p != this->vals_->end())
13604 // Skip key.
13605 ++p;
13606 go_assert(p != this->vals_->end());
13607 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13608 return TRAVERSE_EXIT;
13609 ++p;
13611 return TRAVERSE_CONTINUE;
13615 if (this->vals_ != NULL)
13616 return this->vals_->traverse(traverse);
13618 return TRAVERSE_CONTINUE;
13621 // Lower a generic composite literal into a specific version based on
13622 // the type.
13624 Expression*
13625 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13626 Statement_inserter* inserter, int)
13628 Type* type = this->type_;
13630 for (int depth = 0; depth < this->depth_; ++depth)
13632 if (type->array_type() != NULL)
13633 type = type->array_type()->element_type();
13634 else if (type->map_type() != NULL)
13636 if (this->key_path_[depth])
13637 type = type->map_type()->key_type();
13638 else
13639 type = type->map_type()->val_type();
13641 else
13643 if (!type->is_error())
13644 go_error_at(this->location(),
13645 ("may only omit types within composite literals "
13646 "of slice, array, or map type"));
13647 return Expression::make_error(this->location());
13651 Type *pt = type->points_to();
13652 bool is_pointer = false;
13653 if (pt != NULL)
13655 is_pointer = true;
13656 type = pt;
13659 Expression* ret;
13660 if (type->is_error())
13661 return Expression::make_error(this->location());
13662 else if (type->struct_type() != NULL)
13663 ret = this->lower_struct(gogo, type);
13664 else if (type->array_type() != NULL)
13665 ret = this->lower_array(type);
13666 else if (type->map_type() != NULL)
13667 ret = this->lower_map(gogo, function, inserter, type);
13668 else
13670 go_error_at(this->location(),
13671 ("expected struct, slice, array, or map type "
13672 "for composite literal"));
13673 return Expression::make_error(this->location());
13676 if (is_pointer)
13677 ret = Expression::make_heap_expression(ret, this->location());
13679 return ret;
13682 // Lower a struct composite literal.
13684 Expression*
13685 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13687 Location location = this->location();
13688 Struct_type* st = type->struct_type();
13689 if (this->vals_ == NULL || !this->has_keys_)
13691 if (this->vals_ != NULL
13692 && !this->vals_->empty()
13693 && type->named_type() != NULL
13694 && type->named_type()->named_object()->package() != NULL)
13696 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13697 pf != st->fields()->end();
13698 ++pf)
13700 if (Gogo::is_hidden_name(pf->field_name())
13701 || pf->is_embedded_builtin(gogo))
13702 go_error_at(this->location(),
13703 "assignment of unexported field %qs in %qs literal",
13704 Gogo::message_name(pf->field_name()).c_str(),
13705 type->named_type()->message_name().c_str());
13709 return new Struct_construction_expression(type, this->vals_, location);
13712 size_t field_count = st->field_count();
13713 std::vector<Expression*> vals(field_count);
13714 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13715 Expression_list::const_iterator p = this->vals_->begin();
13716 Expression* external_expr = NULL;
13717 const Named_object* external_no = NULL;
13718 while (p != this->vals_->end())
13720 Expression* name_expr = *p;
13722 ++p;
13723 go_assert(p != this->vals_->end());
13724 Expression* val = *p;
13726 ++p;
13728 if (name_expr == NULL)
13730 go_error_at(val->location(),
13731 "mixture of field and value initializers");
13732 return Expression::make_error(location);
13735 bool bad_key = false;
13736 std::string name;
13737 const Named_object* no = NULL;
13738 switch (name_expr->classification())
13740 case EXPRESSION_UNKNOWN_REFERENCE:
13741 name = name_expr->unknown_expression()->name();
13742 if (type->named_type() != NULL)
13744 // If the named object found for this field name comes from a
13745 // different package than the struct it is a part of, do not count
13746 // this incorrect lookup as a usage of the object's package.
13747 no = name_expr->unknown_expression()->named_object();
13748 if (no->package() != NULL
13749 && no->package() != type->named_type()->named_object()->package())
13750 no->package()->forget_usage(name_expr);
13752 break;
13754 case EXPRESSION_CONST_REFERENCE:
13755 no = static_cast<Const_expression*>(name_expr)->named_object();
13756 break;
13758 case EXPRESSION_TYPE:
13760 Type* t = name_expr->type();
13761 Named_type* nt = t->named_type();
13762 if (nt == NULL)
13763 bad_key = true;
13764 else
13765 no = nt->named_object();
13767 break;
13769 case EXPRESSION_VAR_REFERENCE:
13770 no = name_expr->var_expression()->named_object();
13771 break;
13773 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13774 no = name_expr->enclosed_var_expression()->variable();
13775 break;
13777 case EXPRESSION_FUNC_REFERENCE:
13778 no = name_expr->func_expression()->named_object();
13779 break;
13781 default:
13782 bad_key = true;
13783 break;
13785 if (bad_key)
13787 go_error_at(name_expr->location(), "expected struct field name");
13788 return Expression::make_error(location);
13791 if (no != NULL)
13793 if (no->package() != NULL && external_expr == NULL)
13795 external_expr = name_expr;
13796 external_no = no;
13799 name = no->name();
13801 // A predefined name won't be packed. If it starts with a
13802 // lower case letter we need to check for that case, because
13803 // the field name will be packed. FIXME.
13804 if (!Gogo::is_hidden_name(name)
13805 && name[0] >= 'a'
13806 && name[0] <= 'z')
13808 Named_object* gno = gogo->lookup_global(name.c_str());
13809 if (gno == no)
13810 name = gogo->pack_hidden_name(name, false);
13814 unsigned int index;
13815 const Struct_field* sf = st->find_local_field(name, &index);
13816 if (sf == NULL)
13818 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13819 Gogo::message_name(name).c_str(),
13820 (type->named_type() != NULL
13821 ? type->named_type()->message_name().c_str()
13822 : "unnamed struct"));
13823 return Expression::make_error(location);
13825 if (vals[index] != NULL)
13827 go_error_at(name_expr->location(),
13828 "duplicate value for field %qs in %qs",
13829 Gogo::message_name(name).c_str(),
13830 (type->named_type() != NULL
13831 ? type->named_type()->message_name().c_str()
13832 : "unnamed struct"));
13833 return Expression::make_error(location);
13836 if (type->named_type() != NULL
13837 && type->named_type()->named_object()->package() != NULL
13838 && (Gogo::is_hidden_name(sf->field_name())
13839 || sf->is_embedded_builtin(gogo)))
13840 go_error_at(name_expr->location(),
13841 "assignment of unexported field %qs in %qs literal",
13842 Gogo::message_name(sf->field_name()).c_str(),
13843 type->named_type()->message_name().c_str());
13845 vals[index] = val;
13846 traverse_order->push_back(static_cast<unsigned long>(index));
13849 if (!this->all_are_names_)
13851 // This is a weird case like bug462 in the testsuite.
13852 if (external_expr == NULL)
13853 go_error_at(this->location(), "unknown field in %qs literal",
13854 (type->named_type() != NULL
13855 ? type->named_type()->message_name().c_str()
13856 : "unnamed struct"));
13857 else
13858 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13859 external_no->message_name().c_str(),
13860 (type->named_type() != NULL
13861 ? type->named_type()->message_name().c_str()
13862 : "unnamed struct"));
13863 return Expression::make_error(location);
13866 Expression_list* list = new Expression_list;
13867 list->reserve(field_count);
13868 for (size_t i = 0; i < field_count; ++i)
13869 list->push_back(vals[i]);
13871 Struct_construction_expression* ret =
13872 new Struct_construction_expression(type, list, location);
13873 ret->set_traverse_order(traverse_order);
13874 return ret;
13877 // Index/value/traversal-order triple.
13879 struct IVT_triple {
13880 unsigned long index;
13881 unsigned long traversal_order;
13882 Expression* expr;
13883 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13884 : index(i), traversal_order(to), expr(e) { }
13885 bool operator<(const IVT_triple& other) const
13886 { return this->index < other.index; }
13889 // Lower an array composite literal.
13891 Expression*
13892 Composite_literal_expression::lower_array(Type* type)
13894 Location location = this->location();
13895 if (this->vals_ == NULL || !this->has_keys_)
13896 return this->make_array(type, NULL, this->vals_);
13898 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13899 indexes->reserve(this->vals_->size());
13900 bool indexes_out_of_order = false;
13901 Expression_list* vals = new Expression_list();
13902 vals->reserve(this->vals_->size());
13903 unsigned long index = 0;
13904 Expression_list::const_iterator p = this->vals_->begin();
13905 while (p != this->vals_->end())
13907 Expression* index_expr = *p;
13909 ++p;
13910 go_assert(p != this->vals_->end());
13911 Expression* val = *p;
13913 ++p;
13915 if (index_expr == NULL)
13917 if (!indexes->empty())
13918 indexes->push_back(index);
13920 else
13922 if (indexes->empty() && !vals->empty())
13924 for (size_t i = 0; i < vals->size(); ++i)
13925 indexes->push_back(i);
13928 Numeric_constant nc;
13929 if (!index_expr->numeric_constant_value(&nc))
13931 go_error_at(index_expr->location(),
13932 "index expression is not integer constant");
13933 return Expression::make_error(location);
13936 switch (nc.to_unsigned_long(&index))
13938 case Numeric_constant::NC_UL_VALID:
13939 break;
13940 case Numeric_constant::NC_UL_NOTINT:
13941 go_error_at(index_expr->location(),
13942 "index expression is not integer constant");
13943 return Expression::make_error(location);
13944 case Numeric_constant::NC_UL_NEGATIVE:
13945 go_error_at(index_expr->location(),
13946 "index expression is negative");
13947 return Expression::make_error(location);
13948 case Numeric_constant::NC_UL_BIG:
13949 go_error_at(index_expr->location(), "index value overflow");
13950 return Expression::make_error(location);
13951 default:
13952 go_unreachable();
13955 Named_type* ntype = Type::lookup_integer_type("int");
13956 Integer_type* inttype = ntype->integer_type();
13957 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13958 && index >> (inttype->bits() - 1) != 0)
13960 go_error_at(index_expr->location(), "index value overflow");
13961 return Expression::make_error(location);
13964 if (std::find(indexes->begin(), indexes->end(), index)
13965 != indexes->end())
13967 go_error_at(index_expr->location(),
13968 "duplicate value for index %lu",
13969 index);
13970 return Expression::make_error(location);
13973 if (!indexes->empty() && index < indexes->back())
13974 indexes_out_of_order = true;
13976 indexes->push_back(index);
13979 vals->push_back(val);
13981 ++index;
13984 if (indexes->empty())
13986 delete indexes;
13987 indexes = NULL;
13990 std::vector<unsigned long>* traverse_order = NULL;
13991 if (indexes_out_of_order)
13993 typedef std::vector<IVT_triple> V;
13995 V v;
13996 v.reserve(indexes->size());
13997 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13998 unsigned long torder = 0;
13999 for (Expression_list::const_iterator pe = vals->begin();
14000 pe != vals->end();
14001 ++pe, ++pi, ++torder)
14002 v.push_back(IVT_triple(*pi, torder, *pe));
14004 std::sort(v.begin(), v.end());
14006 delete indexes;
14007 delete vals;
14009 indexes = new std::vector<unsigned long>();
14010 indexes->reserve(v.size());
14011 vals = new Expression_list();
14012 vals->reserve(v.size());
14013 traverse_order = new std::vector<unsigned long>();
14014 traverse_order->reserve(v.size());
14016 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
14018 indexes->push_back(p->index);
14019 vals->push_back(p->expr);
14020 traverse_order->push_back(p->traversal_order);
14024 Expression* ret = this->make_array(type, indexes, vals);
14025 Array_construction_expression* ace = ret->array_literal();
14026 if (ace != NULL && traverse_order != NULL)
14027 ace->set_traverse_order(traverse_order);
14028 return ret;
14031 // Actually build the array composite literal. This handles
14032 // [...]{...}.
14034 Expression*
14035 Composite_literal_expression::make_array(
14036 Type* type,
14037 const std::vector<unsigned long>* indexes,
14038 Expression_list* vals)
14040 Location location = this->location();
14041 Array_type* at = type->array_type();
14043 if (at->length() != NULL && at->length()->is_nil_expression())
14045 size_t size;
14046 if (vals == NULL)
14047 size = 0;
14048 else if (indexes != NULL)
14049 size = indexes->back() + 1;
14050 else
14052 size = vals->size();
14053 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
14054 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
14055 && size >> (it->bits() - 1) != 0)
14057 go_error_at(location, "too many elements in composite literal");
14058 return Expression::make_error(location);
14062 Expression* elen = Expression::make_integer_ul(size, NULL, location);
14063 at = Type::make_array_type(at->element_type(), elen);
14064 type = at;
14066 else if (at->length() != NULL
14067 && !at->length()->is_error_expression()
14068 && this->vals_ != NULL)
14070 Numeric_constant nc;
14071 unsigned long val;
14072 if (at->length()->numeric_constant_value(&nc)
14073 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
14075 if (indexes == NULL)
14077 if (this->vals_->size() > val)
14079 go_error_at(location,
14080 "too many elements in composite literal");
14081 return Expression::make_error(location);
14084 else
14086 unsigned long max = indexes->back();
14087 if (max >= val)
14089 go_error_at(location,
14090 ("some element keys in composite literal "
14091 "are out of range"));
14092 return Expression::make_error(location);
14098 if (at->length() != NULL)
14099 return new Fixed_array_construction_expression(type, indexes, vals,
14100 location);
14101 else
14102 return new Slice_construction_expression(type, indexes, vals, location);
14105 // Lower a map composite literal.
14107 Expression*
14108 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
14109 Statement_inserter* inserter,
14110 Type* type)
14112 Location location = this->location();
14113 if (this->vals_ != NULL)
14115 if (!this->has_keys_)
14117 go_error_at(location, "map composite literal must have keys");
14118 return Expression::make_error(location);
14121 for (Expression_list::iterator p = this->vals_->begin();
14122 p != this->vals_->end();
14123 p += 2)
14125 if (*p == NULL)
14127 ++p;
14128 go_error_at((*p)->location(),
14129 ("map composite literal must "
14130 "have keys for every value"));
14131 return Expression::make_error(location);
14133 // Make sure we have lowered the key; it may not have been
14134 // lowered in order to handle keys for struct composite
14135 // literals. Lower it now to get the right error message.
14136 if ((*p)->unknown_expression() != NULL)
14138 (*p)->unknown_expression()->clear_is_composite_literal_key();
14139 gogo->lower_expression(function, inserter, &*p);
14140 go_assert((*p)->is_error_expression());
14141 return Expression::make_error(location);
14146 return new Map_construction_expression(type, this->vals_, location);
14149 // Copy.
14151 Expression*
14152 Composite_literal_expression::do_copy()
14154 Composite_literal_expression* ret =
14155 new Composite_literal_expression(this->type_->copy_expressions(),
14156 this->depth_, this->has_keys_,
14157 (this->vals_ == NULL
14158 ? NULL
14159 : this->vals_->copy()),
14160 this->all_are_names_,
14161 this->location());
14162 ret->key_path_ = this->key_path_;
14163 return ret;
14166 // Dump ast representation for a composite literal expression.
14168 void
14169 Composite_literal_expression::do_dump_expression(
14170 Ast_dump_context* ast_dump_context) const
14172 ast_dump_context->ostream() << "composite(";
14173 ast_dump_context->dump_type(this->type_);
14174 ast_dump_context->ostream() << ", {";
14175 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14176 ast_dump_context->ostream() << "})";
14179 // Make a composite literal expression.
14181 Expression*
14182 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14183 Expression_list* vals, bool all_are_names,
14184 Location location)
14186 return new Composite_literal_expression(type, depth, has_keys, vals,
14187 all_are_names, location);
14190 // Return whether this expression is a composite literal.
14192 bool
14193 Expression::is_composite_literal() const
14195 switch (this->classification_)
14197 case EXPRESSION_COMPOSITE_LITERAL:
14198 case EXPRESSION_STRUCT_CONSTRUCTION:
14199 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14200 case EXPRESSION_SLICE_CONSTRUCTION:
14201 case EXPRESSION_MAP_CONSTRUCTION:
14202 return true;
14203 default:
14204 return false;
14208 // Return whether this expression is a composite literal which is not
14209 // constant.
14211 bool
14212 Expression::is_nonconstant_composite_literal() const
14214 switch (this->classification_)
14216 case EXPRESSION_STRUCT_CONSTRUCTION:
14218 const Struct_construction_expression *psce =
14219 static_cast<const Struct_construction_expression*>(this);
14220 return !psce->is_constant_struct();
14222 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14224 const Fixed_array_construction_expression *pace =
14225 static_cast<const Fixed_array_construction_expression*>(this);
14226 return !pace->is_constant_array();
14228 case EXPRESSION_SLICE_CONSTRUCTION:
14230 const Slice_construction_expression *pace =
14231 static_cast<const Slice_construction_expression*>(this);
14232 return !pace->is_constant_array();
14234 case EXPRESSION_MAP_CONSTRUCTION:
14235 return true;
14236 default:
14237 return false;
14241 // Return true if this is a variable or temporary_variable.
14243 bool
14244 Expression::is_variable() const
14246 switch (this->classification_)
14248 case EXPRESSION_VAR_REFERENCE:
14249 case EXPRESSION_TEMPORARY_REFERENCE:
14250 case EXPRESSION_SET_AND_USE_TEMPORARY:
14251 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14252 return true;
14253 default:
14254 return false;
14258 // Return true if this is a reference to a local variable.
14260 bool
14261 Expression::is_local_variable() const
14263 const Var_expression* ve = this->var_expression();
14264 if (ve == NULL)
14265 return false;
14266 const Named_object* no = ve->named_object();
14267 return (no->is_result_variable()
14268 || (no->is_variable() && !no->var_value()->is_global()));
14271 // Class Type_guard_expression.
14273 // Traversal.
14276 Type_guard_expression::do_traverse(Traverse* traverse)
14278 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14279 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14280 return TRAVERSE_EXIT;
14281 return TRAVERSE_CONTINUE;
14284 Expression*
14285 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14286 Statement_inserter* inserter)
14288 if (this->expr_->is_error_expression()
14289 || this->expr_->type()->is_error_type())
14291 go_assert(saw_errors());
14292 return Expression::make_error(this->location());
14295 if (!this->expr_->is_variable())
14297 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14298 this->location());
14299 inserter->insert(temp);
14300 this->expr_ =
14301 Expression::make_temporary_reference(temp, this->location());
14303 return this;
14306 // Check types of a type guard expression. The expression must have
14307 // an interface type, but the actual type conversion is checked at run
14308 // time.
14310 void
14311 Type_guard_expression::do_check_types(Gogo*)
14313 Type* expr_type = this->expr_->type();
14314 if (expr_type->interface_type() == NULL)
14316 if (!expr_type->is_error() && !this->type_->is_error())
14317 this->report_error(_("type assertion only valid for interface types"));
14318 this->set_is_error();
14320 else if (this->type_->interface_type() == NULL)
14322 std::string reason;
14323 if (!expr_type->interface_type()->implements_interface(this->type_,
14324 &reason))
14326 if (!this->type_->is_error())
14328 if (reason.empty())
14329 this->report_error(_("impossible type assertion: "
14330 "type does not implement interface"));
14331 else
14332 go_error_at(this->location(),
14333 ("impossible type assertion: "
14334 "type does not implement interface (%s)"),
14335 reason.c_str());
14337 this->set_is_error();
14342 // Copy.
14344 Expression*
14345 Type_guard_expression::do_copy()
14347 return new Type_guard_expression(this->expr_->copy(),
14348 this->type_->copy_expressions(),
14349 this->location());
14352 // Return the backend representation for a type guard expression.
14354 Bexpression*
14355 Type_guard_expression::do_get_backend(Translate_context* context)
14357 Expression* conversion;
14358 if (this->type_->interface_type() != NULL)
14359 conversion =
14360 Expression::convert_interface_to_interface(this->type_, this->expr_,
14361 true, this->location());
14362 else
14363 conversion =
14364 Expression::convert_for_assignment(context->gogo(), this->type_,
14365 this->expr_, this->location());
14367 Gogo* gogo = context->gogo();
14368 Btype* bt = this->type_->get_backend(gogo);
14369 Bexpression* bexpr = conversion->get_backend(context);
14370 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14373 // Dump ast representation for a type guard expression.
14375 void
14376 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14377 const
14379 this->expr_->dump_expression(ast_dump_context);
14380 ast_dump_context->ostream() << ".";
14381 ast_dump_context->dump_type(this->type_);
14384 // Make a type guard expression.
14386 Expression*
14387 Expression::make_type_guard(Expression* expr, Type* type,
14388 Location location)
14390 return new Type_guard_expression(expr, type, location);
14393 // Class Heap_expression.
14395 // Return the type of the expression stored on the heap.
14397 Type*
14398 Heap_expression::do_type()
14399 { return Type::make_pointer_type(this->expr_->type()); }
14401 // Return the backend representation for allocating an expression on the heap.
14403 Bexpression*
14404 Heap_expression::do_get_backend(Translate_context* context)
14406 Type* etype = this->expr_->type();
14407 if (this->expr_->is_error_expression() || etype->is_error())
14408 return context->backend()->error_expression();
14410 Location loc = this->location();
14411 Gogo* gogo = context->gogo();
14412 Btype* btype = this->type()->get_backend(gogo);
14414 Expression* alloc = Expression::make_allocation(etype, loc);
14415 if (this->allocate_on_stack_)
14416 alloc->allocation_expression()->set_allocate_on_stack();
14417 Bexpression* space = alloc->get_backend(context);
14419 Bstatement* decl;
14420 Named_object* fn = context->function();
14421 go_assert(fn != NULL);
14422 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14423 Bvariable* space_temp =
14424 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14425 space, true, loc, &decl);
14426 Btype* expr_btype = etype->get_backend(gogo);
14428 Bexpression* bexpr = this->expr_->get_backend(context);
14430 // If this assignment needs a write barrier, call typedmemmove. We
14431 // don't do this in the write barrier pass because in some cases
14432 // backend conversion can introduce new Heap_expression values.
14433 Bstatement* assn;
14434 if (!etype->has_pointer() || this->allocate_on_stack_)
14436 space = gogo->backend()->var_expression(space_temp, loc);
14437 Bexpression* ref =
14438 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14439 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14441 else
14443 Bstatement* edecl;
14444 Bvariable* btemp =
14445 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14446 expr_btype, bexpr, true, loc,
14447 &edecl);
14448 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14449 loc);
14450 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14452 Expression* td = Expression::make_type_descriptor(etype, loc);
14453 Type* etype_ptr = Type::make_pointer_type(etype);
14454 space = gogo->backend()->var_expression(space_temp, loc);
14455 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14456 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14457 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14458 td, elhs, erhs);
14459 Bexpression* bcall = call->get_backend(context);
14460 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14461 assn = gogo->backend()->compound_statement(edecl, s);
14463 decl = gogo->backend()->compound_statement(decl, assn);
14464 space = gogo->backend()->var_expression(space_temp, loc);
14465 return gogo->backend()->compound_expression(decl, space, loc);
14468 // Dump ast representation for a heap expression.
14470 void
14471 Heap_expression::do_dump_expression(
14472 Ast_dump_context* ast_dump_context) const
14474 ast_dump_context->ostream() << "&(";
14475 ast_dump_context->dump_expression(this->expr_);
14476 ast_dump_context->ostream() << ")";
14479 // Allocate an expression on the heap.
14481 Expression*
14482 Expression::make_heap_expression(Expression* expr, Location location)
14484 return new Heap_expression(expr, location);
14487 // Class Receive_expression.
14489 // Return the type of a receive expression.
14491 Type*
14492 Receive_expression::do_type()
14494 if (this->is_error_expression())
14495 return Type::make_error_type();
14496 Channel_type* channel_type = this->channel_->type()->channel_type();
14497 if (channel_type == NULL)
14499 this->report_error(_("expected channel"));
14500 return Type::make_error_type();
14502 return channel_type->element_type();
14505 // Check types for a receive expression.
14507 void
14508 Receive_expression::do_check_types(Gogo*)
14510 Type* type = this->channel_->type();
14511 if (type->is_error())
14513 go_assert(saw_errors());
14514 this->set_is_error();
14515 return;
14517 if (type->channel_type() == NULL)
14519 this->report_error(_("expected channel"));
14520 return;
14522 if (!type->channel_type()->may_receive())
14524 this->report_error(_("invalid receive on send-only channel"));
14525 return;
14529 // Flattening for receive expressions creates a temporary variable to store
14530 // received data in for receives.
14532 Expression*
14533 Receive_expression::do_flatten(Gogo*, Named_object*,
14534 Statement_inserter* inserter)
14536 Channel_type* channel_type = this->channel_->type()->channel_type();
14537 if (channel_type == NULL)
14539 go_assert(saw_errors());
14540 return this;
14542 else if (this->channel_->is_error_expression())
14544 go_assert(saw_errors());
14545 return Expression::make_error(this->location());
14548 Type* element_type = channel_type->element_type();
14549 if (this->temp_receiver_ == NULL)
14551 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14552 this->location());
14553 this->temp_receiver_->set_is_address_taken();
14554 inserter->insert(this->temp_receiver_);
14557 return this;
14560 // Get the backend representation for a receive expression.
14562 Bexpression*
14563 Receive_expression::do_get_backend(Translate_context* context)
14565 Location loc = this->location();
14567 Channel_type* channel_type = this->channel_->type()->channel_type();
14568 if (channel_type == NULL)
14570 go_assert(this->channel_->type()->is_error());
14571 return context->backend()->error_expression();
14574 Expression* recv_ref =
14575 Expression::make_temporary_reference(this->temp_receiver_, loc);
14576 Expression* recv_addr =
14577 Expression::make_temporary_reference(this->temp_receiver_, loc);
14578 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14579 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14580 this->channel_, recv_addr);
14581 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14584 // Dump ast representation for a receive expression.
14586 void
14587 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14589 ast_dump_context->ostream() << " <- " ;
14590 ast_dump_context->dump_expression(channel_);
14593 // Make a receive expression.
14595 Receive_expression*
14596 Expression::make_receive(Expression* channel, Location location)
14598 return new Receive_expression(channel, location);
14601 // An expression which evaluates to a pointer to the type descriptor
14602 // of a type.
14604 class Type_descriptor_expression : public Expression
14606 public:
14607 Type_descriptor_expression(Type* type, Location location)
14608 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14609 type_(type)
14612 protected:
14614 do_traverse(Traverse*);
14616 Type*
14617 do_type()
14618 { return Type::make_type_descriptor_ptr_type(); }
14620 bool
14621 do_is_static_initializer() const
14622 { return true; }
14624 void
14625 do_determine_type(const Type_context*)
14628 Expression*
14629 do_copy()
14630 { return this; }
14632 Bexpression*
14633 do_get_backend(Translate_context* context)
14635 return this->type_->type_descriptor_pointer(context->gogo(),
14636 this->location());
14639 void
14640 do_dump_expression(Ast_dump_context*) const;
14642 private:
14643 // The type for which this is the descriptor.
14644 Type* type_;
14648 Type_descriptor_expression::do_traverse(Traverse* traverse)
14650 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14651 return TRAVERSE_EXIT;
14652 return TRAVERSE_CONTINUE;
14655 // Dump ast representation for a type descriptor expression.
14657 void
14658 Type_descriptor_expression::do_dump_expression(
14659 Ast_dump_context* ast_dump_context) const
14661 ast_dump_context->dump_type(this->type_);
14664 // Make a type descriptor expression.
14666 Expression*
14667 Expression::make_type_descriptor(Type* type, Location location)
14669 return new Type_descriptor_expression(type, location);
14672 // An expression which evaluates to a pointer to the Garbage Collection symbol
14673 // of a type.
14675 class GC_symbol_expression : public Expression
14677 public:
14678 GC_symbol_expression(Type* type)
14679 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14680 type_(type)
14683 protected:
14684 Type*
14685 do_type()
14686 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14688 bool
14689 do_is_static_initializer() const
14690 { return true; }
14692 void
14693 do_determine_type(const Type_context*)
14696 Expression*
14697 do_copy()
14698 { return this; }
14700 Bexpression*
14701 do_get_backend(Translate_context* context)
14702 { return this->type_->gc_symbol_pointer(context->gogo()); }
14704 void
14705 do_dump_expression(Ast_dump_context*) const;
14707 private:
14708 // The type which this gc symbol describes.
14709 Type* type_;
14712 // Dump ast representation for a gc symbol expression.
14714 void
14715 GC_symbol_expression::do_dump_expression(
14716 Ast_dump_context* ast_dump_context) const
14718 ast_dump_context->ostream() << "gcdata(";
14719 ast_dump_context->dump_type(this->type_);
14720 ast_dump_context->ostream() << ")";
14723 // Make a gc symbol expression.
14725 Expression*
14726 Expression::make_gc_symbol(Type* type)
14728 return new GC_symbol_expression(type);
14731 // An expression that evaluates to a pointer to a symbol holding the
14732 // ptrmask data of a type.
14734 class Ptrmask_symbol_expression : public Expression
14736 public:
14737 Ptrmask_symbol_expression(Type* type)
14738 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14739 type_(type)
14742 protected:
14743 Type*
14744 do_type()
14745 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14747 bool
14748 do_is_static_initializer() const
14749 { return true; }
14751 void
14752 do_determine_type(const Type_context*)
14755 Expression*
14756 do_copy()
14757 { return this; }
14759 Bexpression*
14760 do_get_backend(Translate_context*);
14762 void
14763 do_dump_expression(Ast_dump_context*) const;
14765 private:
14766 // The type that this ptrmask symbol describes.
14767 Type* type_;
14770 // Return the ptrmask variable.
14772 Bexpression*
14773 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14775 Gogo* gogo = context->gogo();
14777 // If this type does not need a gcprog, then we can use the standard
14778 // GC symbol.
14779 int64_t ptrsize, ptrdata;
14780 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14781 return this->type_->gc_symbol_pointer(gogo);
14783 // Otherwise we have to build a ptrmask variable, and return a
14784 // pointer to it.
14786 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14787 Location bloc = Linemap::predeclared_location();
14788 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
14789 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14791 Type* uint8_type = Type::lookup_integer_type("uint8");
14792 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14793 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14794 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14797 // Dump AST for a ptrmask symbol expression.
14799 void
14800 Ptrmask_symbol_expression::do_dump_expression(
14801 Ast_dump_context* ast_dump_context) const
14803 ast_dump_context->ostream() << "ptrmask(";
14804 ast_dump_context->dump_type(this->type_);
14805 ast_dump_context->ostream() << ")";
14808 // Make a ptrmask symbol expression.
14810 Expression*
14811 Expression::make_ptrmask_symbol(Type* type)
14813 return new Ptrmask_symbol_expression(type);
14816 // An expression which evaluates to some characteristic of a type.
14817 // This is only used to initialize fields of a type descriptor. Using
14818 // a new expression class is slightly inefficient but gives us a good
14819 // separation between the frontend and the middle-end with regard to
14820 // how types are laid out.
14822 class Type_info_expression : public Expression
14824 public:
14825 Type_info_expression(Type* type, Type_info type_info)
14826 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14827 type_(type), type_info_(type_info)
14830 protected:
14831 bool
14832 do_is_static_initializer() const
14833 { return true; }
14835 Type*
14836 do_type();
14838 void
14839 do_determine_type(const Type_context*)
14842 Expression*
14843 do_copy()
14844 { return this; }
14846 Bexpression*
14847 do_get_backend(Translate_context* context);
14849 void
14850 do_dump_expression(Ast_dump_context*) const;
14852 private:
14853 // The type for which we are getting information.
14854 Type* type_;
14855 // What information we want.
14856 Type_info type_info_;
14859 // The type is chosen to match what the type descriptor struct
14860 // expects.
14862 Type*
14863 Type_info_expression::do_type()
14865 switch (this->type_info_)
14867 case TYPE_INFO_SIZE:
14868 case TYPE_INFO_BACKEND_PTRDATA:
14869 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14870 return Type::lookup_integer_type("uintptr");
14871 case TYPE_INFO_ALIGNMENT:
14872 case TYPE_INFO_FIELD_ALIGNMENT:
14873 return Type::lookup_integer_type("uint8");
14874 default:
14875 go_unreachable();
14879 // Return the backend representation for type information.
14881 Bexpression*
14882 Type_info_expression::do_get_backend(Translate_context* context)
14884 Gogo* gogo = context->gogo();
14885 bool ok = true;
14886 int64_t val;
14887 switch (this->type_info_)
14889 case TYPE_INFO_SIZE:
14890 ok = this->type_->backend_type_size(gogo, &val);
14891 break;
14892 case TYPE_INFO_ALIGNMENT:
14893 ok = this->type_->backend_type_align(gogo, &val);
14894 break;
14895 case TYPE_INFO_FIELD_ALIGNMENT:
14896 ok = this->type_->backend_type_field_align(gogo, &val);
14897 break;
14898 case TYPE_INFO_BACKEND_PTRDATA:
14899 ok = this->type_->backend_type_ptrdata(gogo, &val);
14900 break;
14901 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14902 ok = this->type_->descriptor_ptrdata(gogo, &val);
14903 break;
14904 default:
14905 go_unreachable();
14907 if (!ok)
14909 go_assert(saw_errors());
14910 return gogo->backend()->error_expression();
14912 Expression* e = Expression::make_integer_int64(val, this->type(),
14913 this->location());
14914 return e->get_backend(context);
14917 // Dump ast representation for a type info expression.
14919 void
14920 Type_info_expression::do_dump_expression(
14921 Ast_dump_context* ast_dump_context) const
14923 ast_dump_context->ostream() << "typeinfo(";
14924 ast_dump_context->dump_type(this->type_);
14925 ast_dump_context->ostream() << ",";
14926 ast_dump_context->ostream() <<
14927 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14928 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14929 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14930 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14931 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14932 : "unknown");
14933 ast_dump_context->ostream() << ")";
14936 // Make a type info expression.
14938 Expression*
14939 Expression::make_type_info(Type* type, Type_info type_info)
14941 return new Type_info_expression(type, type_info);
14944 // An expression that evaluates to some characteristic of a slice.
14945 // This is used when indexing, bound-checking, or nil checking a slice.
14947 class Slice_info_expression : public Expression
14949 public:
14950 Slice_info_expression(Expression* slice, Slice_info slice_info,
14951 Location location)
14952 : Expression(EXPRESSION_SLICE_INFO, location),
14953 slice_(slice), slice_info_(slice_info)
14956 protected:
14957 Type*
14958 do_type();
14960 void
14961 do_determine_type(const Type_context*)
14964 Expression*
14965 do_copy()
14967 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14968 this->location());
14971 Bexpression*
14972 do_get_backend(Translate_context* context);
14974 void
14975 do_dump_expression(Ast_dump_context*) const;
14977 void
14978 do_issue_nil_check()
14979 { this->slice_->issue_nil_check(); }
14981 private:
14982 // The slice for which we are getting information.
14983 Expression* slice_;
14984 // What information we want.
14985 Slice_info slice_info_;
14988 // Return the type of the slice info.
14990 Type*
14991 Slice_info_expression::do_type()
14993 switch (this->slice_info_)
14995 case SLICE_INFO_VALUE_POINTER:
14996 return Type::make_pointer_type(
14997 this->slice_->type()->array_type()->element_type());
14998 case SLICE_INFO_LENGTH:
14999 case SLICE_INFO_CAPACITY:
15000 return Type::lookup_integer_type("int");
15001 default:
15002 go_unreachable();
15006 // Return the backend information for slice information.
15008 Bexpression*
15009 Slice_info_expression::do_get_backend(Translate_context* context)
15011 Gogo* gogo = context->gogo();
15012 Bexpression* bslice = this->slice_->get_backend(context);
15013 switch (this->slice_info_)
15015 case SLICE_INFO_VALUE_POINTER:
15016 case SLICE_INFO_LENGTH:
15017 case SLICE_INFO_CAPACITY:
15018 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
15019 this->location());
15020 break;
15021 default:
15022 go_unreachable();
15026 // Dump ast representation for a type info expression.
15028 void
15029 Slice_info_expression::do_dump_expression(
15030 Ast_dump_context* ast_dump_context) const
15032 ast_dump_context->ostream() << "sliceinfo(";
15033 this->slice_->dump_expression(ast_dump_context);
15034 ast_dump_context->ostream() << ",";
15035 ast_dump_context->ostream() <<
15036 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
15037 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
15038 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
15039 : "unknown");
15040 ast_dump_context->ostream() << ")";
15043 // Make a slice info expression.
15045 Expression*
15046 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
15047 Location location)
15049 return new Slice_info_expression(slice, slice_info, location);
15052 // An expression that represents a slice value: a struct with value pointer,
15053 // length, and capacity fields.
15055 class Slice_value_expression : public Expression
15057 public:
15058 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
15059 Expression* cap, Location location)
15060 : Expression(EXPRESSION_SLICE_VALUE, location),
15061 type_(type), valptr_(valptr), len_(len), cap_(cap)
15064 protected:
15066 do_traverse(Traverse*);
15068 Type*
15069 do_type()
15070 { return this->type_; }
15072 void
15073 do_determine_type(const Type_context*)
15074 { go_unreachable(); }
15076 Expression*
15077 do_copy()
15079 return new Slice_value_expression(this->type_->copy_expressions(),
15080 this->valptr_->copy(),
15081 this->len_->copy(), this->cap_->copy(),
15082 this->location());
15085 Bexpression*
15086 do_get_backend(Translate_context* context);
15088 void
15089 do_dump_expression(Ast_dump_context*) const;
15091 private:
15092 // The type of the slice value.
15093 Type* type_;
15094 // The pointer to the values in the slice.
15095 Expression* valptr_;
15096 // The length of the slice.
15097 Expression* len_;
15098 // The capacity of the slice.
15099 Expression* cap_;
15103 Slice_value_expression::do_traverse(Traverse* traverse)
15105 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
15106 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
15107 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
15108 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
15109 return TRAVERSE_EXIT;
15110 return TRAVERSE_CONTINUE;
15113 Bexpression*
15114 Slice_value_expression::do_get_backend(Translate_context* context)
15116 std::vector<Bexpression*> vals(3);
15117 vals[0] = this->valptr_->get_backend(context);
15118 vals[1] = this->len_->get_backend(context);
15119 vals[2] = this->cap_->get_backend(context);
15121 Gogo* gogo = context->gogo();
15122 Btype* btype = this->type_->get_backend(gogo);
15123 return gogo->backend()->constructor_expression(btype, vals, this->location());
15126 void
15127 Slice_value_expression::do_dump_expression(
15128 Ast_dump_context* ast_dump_context) const
15130 ast_dump_context->ostream() << "slicevalue(";
15131 ast_dump_context->ostream() << "values: ";
15132 this->valptr_->dump_expression(ast_dump_context);
15133 ast_dump_context->ostream() << ", length: ";
15134 this->len_->dump_expression(ast_dump_context);
15135 ast_dump_context->ostream() << ", capacity: ";
15136 this->cap_->dump_expression(ast_dump_context);
15137 ast_dump_context->ostream() << ")";
15140 Expression*
15141 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
15142 Expression* cap, Location location)
15144 go_assert(at->is_slice_type());
15145 return new Slice_value_expression(at, valptr, len, cap, location);
15148 // An expression that evaluates to some characteristic of a non-empty interface.
15149 // This is used to access the method table or underlying object of an interface.
15151 class Interface_info_expression : public Expression
15153 public:
15154 Interface_info_expression(Expression* iface, Interface_info iface_info,
15155 Location location)
15156 : Expression(EXPRESSION_INTERFACE_INFO, location),
15157 iface_(iface), iface_info_(iface_info)
15160 protected:
15161 Type*
15162 do_type();
15164 void
15165 do_determine_type(const Type_context*)
15168 Expression*
15169 do_copy()
15171 return new Interface_info_expression(this->iface_->copy(),
15172 this->iface_info_, this->location());
15175 Bexpression*
15176 do_get_backend(Translate_context* context);
15178 void
15179 do_dump_expression(Ast_dump_context*) const;
15181 void
15182 do_issue_nil_check()
15183 { this->iface_->issue_nil_check(); }
15185 private:
15186 // The interface for which we are getting information.
15187 Expression* iface_;
15188 // What information we want.
15189 Interface_info iface_info_;
15192 // Return the type of the interface info.
15194 Type*
15195 Interface_info_expression::do_type()
15197 switch (this->iface_info_)
15199 case INTERFACE_INFO_METHODS:
15201 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15202 static Hashtable result_types;
15204 Interface_type* itype = this->iface_->type()->interface_type();
15206 Hashtable::const_iterator p = result_types.find(itype);
15207 if (p != result_types.end())
15208 return p->second;
15210 Type* pdt = Type::make_type_descriptor_ptr_type();
15211 if (itype->is_empty())
15213 result_types[itype] = pdt;
15214 return pdt;
15217 Location loc = this->location();
15218 Struct_field_list* sfl = new Struct_field_list();
15219 sfl->push_back(
15220 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15222 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15223 p != itype->methods()->end();
15224 ++p)
15226 Function_type* ft = p->type()->function_type();
15227 go_assert(ft->receiver() == NULL);
15229 const Typed_identifier_list* params = ft->parameters();
15230 Typed_identifier_list* mparams = new Typed_identifier_list();
15231 if (params != NULL)
15232 mparams->reserve(params->size() + 1);
15233 Type* vt = Type::make_pointer_type(Type::make_void_type());
15234 mparams->push_back(Typed_identifier("", vt, ft->location()));
15235 if (params != NULL)
15237 for (Typed_identifier_list::const_iterator pp = params->begin();
15238 pp != params->end();
15239 ++pp)
15240 mparams->push_back(*pp);
15243 Typed_identifier_list* mresults = (ft->results() == NULL
15244 ? NULL
15245 : ft->results()->copy());
15246 Backend_function_type* mft =
15247 Type::make_backend_function_type(NULL, mparams, mresults,
15248 ft->location());
15250 std::string fname = Gogo::unpack_hidden_name(p->name());
15251 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15254 Struct_type* st = Type::make_struct_type(sfl, loc);
15255 st->set_is_struct_incomparable();
15256 Pointer_type *pt = Type::make_pointer_type(st);
15257 result_types[itype] = pt;
15258 return pt;
15260 case INTERFACE_INFO_OBJECT:
15261 return Type::make_pointer_type(Type::make_void_type());
15262 default:
15263 go_unreachable();
15267 // Return the backend representation for interface information.
15269 Bexpression*
15270 Interface_info_expression::do_get_backend(Translate_context* context)
15272 Gogo* gogo = context->gogo();
15273 Bexpression* biface = this->iface_->get_backend(context);
15274 switch (this->iface_info_)
15276 case INTERFACE_INFO_METHODS:
15277 case INTERFACE_INFO_OBJECT:
15278 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15279 this->location());
15280 break;
15281 default:
15282 go_unreachable();
15286 // Dump ast representation for an interface info expression.
15288 void
15289 Interface_info_expression::do_dump_expression(
15290 Ast_dump_context* ast_dump_context) const
15292 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15293 ast_dump_context->ostream() << "interfaceinfo(";
15294 this->iface_->dump_expression(ast_dump_context);
15295 ast_dump_context->ostream() << ",";
15296 ast_dump_context->ostream() <<
15297 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15298 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15299 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15300 : "unknown");
15301 ast_dump_context->ostream() << ")";
15304 // Make an interface info expression.
15306 Expression*
15307 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15308 Location location)
15310 return new Interface_info_expression(iface, iface_info, location);
15313 // An expression that represents an interface value. The first field is either
15314 // a type descriptor for an empty interface or a pointer to the interface method
15315 // table for a non-empty interface. The second field is always the object.
15317 class Interface_value_expression : public Expression
15319 public:
15320 Interface_value_expression(Type* type, Expression* first_field,
15321 Expression* obj, Location location)
15322 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15323 type_(type), first_field_(first_field), obj_(obj)
15326 protected:
15328 do_traverse(Traverse*);
15330 Type*
15331 do_type()
15332 { return this->type_; }
15334 void
15335 do_determine_type(const Type_context*)
15336 { go_unreachable(); }
15338 Expression*
15339 do_copy()
15341 return new Interface_value_expression(this->type_->copy_expressions(),
15342 this->first_field_->copy(),
15343 this->obj_->copy(), this->location());
15346 Bexpression*
15347 do_get_backend(Translate_context* context);
15349 void
15350 do_dump_expression(Ast_dump_context*) const;
15352 private:
15353 // The type of the interface value.
15354 Type* type_;
15355 // The first field of the interface (either a type descriptor or a pointer
15356 // to the method table.
15357 Expression* first_field_;
15358 // The underlying object of the interface.
15359 Expression* obj_;
15363 Interface_value_expression::do_traverse(Traverse* traverse)
15365 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15366 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15367 return TRAVERSE_EXIT;
15368 return TRAVERSE_CONTINUE;
15371 Bexpression*
15372 Interface_value_expression::do_get_backend(Translate_context* context)
15374 std::vector<Bexpression*> vals(2);
15375 vals[0] = this->first_field_->get_backend(context);
15376 vals[1] = this->obj_->get_backend(context);
15378 Gogo* gogo = context->gogo();
15379 Btype* btype = this->type_->get_backend(gogo);
15380 return gogo->backend()->constructor_expression(btype, vals, this->location());
15383 void
15384 Interface_value_expression::do_dump_expression(
15385 Ast_dump_context* ast_dump_context) const
15387 ast_dump_context->ostream() << "interfacevalue(";
15388 ast_dump_context->ostream() <<
15389 (this->type_->interface_type()->is_empty()
15390 ? "type_descriptor: "
15391 : "methods: ");
15392 this->first_field_->dump_expression(ast_dump_context);
15393 ast_dump_context->ostream() << ", object: ";
15394 this->obj_->dump_expression(ast_dump_context);
15395 ast_dump_context->ostream() << ")";
15398 Expression*
15399 Expression::make_interface_value(Type* type, Expression* first_value,
15400 Expression* object, Location location)
15402 return new Interface_value_expression(type, first_value, object, location);
15405 // An interface method table for a pair of types: an interface type and a type
15406 // that implements that interface.
15408 class Interface_mtable_expression : public Expression
15410 public:
15411 Interface_mtable_expression(Interface_type* itype, Type* type,
15412 bool is_pointer, Location location)
15413 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15414 itype_(itype), type_(type), is_pointer_(is_pointer),
15415 method_table_type_(NULL), bvar_(NULL)
15418 protected:
15420 do_traverse(Traverse*);
15422 Type*
15423 do_type();
15425 bool
15426 do_is_static_initializer() const
15427 { return true; }
15429 void
15430 do_determine_type(const Type_context*)
15431 { go_unreachable(); }
15433 Expression*
15434 do_copy()
15436 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
15437 return new Interface_mtable_expression(itype,
15438 this->type_->copy_expressions(),
15439 this->is_pointer_, this->location());
15442 bool
15443 do_is_addressable() const
15444 { return true; }
15446 Bexpression*
15447 do_get_backend(Translate_context* context);
15449 void
15450 do_dump_expression(Ast_dump_context*) const;
15452 private:
15453 // The interface type for which the methods are defined.
15454 Interface_type* itype_;
15455 // The type to construct the interface method table for.
15456 Type* type_;
15457 // Whether this table contains the method set for the receiver type or the
15458 // pointer receiver type.
15459 bool is_pointer_;
15460 // The type of the method table.
15461 Type* method_table_type_;
15462 // The backend variable that refers to the interface method table.
15463 Bvariable* bvar_;
15467 Interface_mtable_expression::do_traverse(Traverse* traverse)
15469 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15470 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15471 return TRAVERSE_EXIT;
15472 return TRAVERSE_CONTINUE;
15475 Type*
15476 Interface_mtable_expression::do_type()
15478 if (this->method_table_type_ != NULL)
15479 return this->method_table_type_;
15481 const Typed_identifier_list* interface_methods = this->itype_->methods();
15482 go_assert(!interface_methods->empty());
15484 Struct_field_list* sfl = new Struct_field_list;
15485 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15486 this->location());
15487 sfl->push_back(Struct_field(tid));
15488 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15489 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15490 p != interface_methods->end();
15491 ++p)
15493 // We want C function pointers here, not func descriptors; model
15494 // using void* pointers.
15495 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15496 sfl->push_back(Struct_field(method));
15498 Struct_type* st = Type::make_struct_type(sfl, this->location());
15499 st->set_is_struct_incomparable();
15500 this->method_table_type_ = st;
15501 return this->method_table_type_;
15504 Bexpression*
15505 Interface_mtable_expression::do_get_backend(Translate_context* context)
15507 Gogo* gogo = context->gogo();
15508 Location loc = Linemap::predeclared_location();
15509 if (this->bvar_ != NULL)
15510 return gogo->backend()->var_expression(this->bvar_, this->location());
15512 const Typed_identifier_list* interface_methods = this->itype_->methods();
15513 go_assert(!interface_methods->empty());
15515 std::string mangled_name =
15516 gogo->interface_method_table_name(this->itype_, this->type_,
15517 this->is_pointer_);
15519 // Set is_public if we are converting a named type to an interface
15520 // type that is defined in the same package as the named type, and
15521 // the interface has hidden methods. In that case the interface
15522 // method table will be defined by the package that defines the
15523 // types.
15524 bool is_public = false;
15525 if (this->type_->named_type() != NULL
15526 && (this->type_->named_type()->named_object()->package()
15527 == this->itype_->package()))
15529 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15530 p != interface_methods->end();
15531 ++p)
15533 if (Gogo::is_hidden_name(p->name()))
15535 is_public = true;
15536 break;
15541 if (is_public
15542 && this->type_->named_type()->named_object()->package() != NULL)
15544 // The interface conversion table is defined elsewhere.
15545 Btype* btype = this->type()->get_backend(gogo);
15546 std::string asm_name(go_selectively_encode_id(mangled_name));
15547 this->bvar_ =
15548 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15549 btype, loc);
15550 return gogo->backend()->var_expression(this->bvar_, this->location());
15553 // The first element is the type descriptor.
15554 Type* td_type;
15555 if (!this->is_pointer_)
15556 td_type = this->type_;
15557 else
15558 td_type = Type::make_pointer_type(this->type_);
15560 std::vector<Backend::Btyped_identifier> bstructfields;
15562 // Build an interface method table for a type: a type descriptor followed by a
15563 // list of function pointers, one for each interface method. This is used for
15564 // interfaces.
15565 Expression_list* svals = new Expression_list();
15566 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15567 svals->push_back(tdescriptor);
15569 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15570 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15571 bstructfields.push_back(btd);
15573 Named_type* nt = this->type_->named_type();
15574 Struct_type* st = this->type_->struct_type();
15575 go_assert(nt != NULL || st != NULL);
15577 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15578 p != interface_methods->end();
15579 ++p)
15581 bool is_ambiguous;
15582 Method* m;
15583 if (nt != NULL)
15584 m = nt->method_function(p->name(), &is_ambiguous);
15585 else
15586 m = st->method_function(p->name(), &is_ambiguous);
15587 go_assert(m != NULL);
15588 Named_object* no = m->named_object();
15590 go_assert(no->is_function() || no->is_function_declaration());
15592 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15593 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15594 bstructfields.push_back(bmtype);
15596 svals->push_back(Expression::make_func_code_reference(no, loc));
15599 Btype *btype = gogo->backend()->struct_type(bstructfields);
15600 std::vector<Bexpression*> ctor_bexprs;
15601 for (Expression_list::const_iterator pe = svals->begin();
15602 pe != svals->end();
15603 ++pe)
15605 ctor_bexprs.push_back((*pe)->get_backend(context));
15607 Bexpression* ctor =
15608 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15610 std::string asm_name(go_selectively_encode_id(mangled_name));
15611 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15612 !is_public, btype, loc);
15613 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15614 !is_public, btype, loc, ctor);
15615 return gogo->backend()->var_expression(this->bvar_, loc);
15618 void
15619 Interface_mtable_expression::do_dump_expression(
15620 Ast_dump_context* ast_dump_context) const
15622 ast_dump_context->ostream() << "__go_"
15623 << (this->is_pointer_ ? "pimt__" : "imt_");
15624 ast_dump_context->dump_type(this->itype_);
15625 ast_dump_context->ostream() << "__";
15626 ast_dump_context->dump_type(this->type_);
15629 Expression*
15630 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15631 bool is_pointer, Location location)
15633 return new Interface_mtable_expression(itype, type, is_pointer, location);
15636 // An expression which evaluates to the offset of a field within a
15637 // struct. This, like Type_info_expression, q.v., is only used to
15638 // initialize fields of a type descriptor.
15640 class Struct_field_offset_expression : public Expression
15642 public:
15643 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15644 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15645 Linemap::predeclared_location()),
15646 type_(type), field_(field)
15649 protected:
15650 bool
15651 do_is_static_initializer() const
15652 { return true; }
15654 Type*
15655 do_type()
15656 { return Type::lookup_integer_type("uintptr"); }
15658 void
15659 do_determine_type(const Type_context*)
15662 Expression*
15663 do_copy()
15664 { return this; }
15666 Bexpression*
15667 do_get_backend(Translate_context* context);
15669 void
15670 do_dump_expression(Ast_dump_context*) const;
15672 private:
15673 // The type of the struct.
15674 Struct_type* type_;
15675 // The field.
15676 const Struct_field* field_;
15679 // Return the backend representation for a struct field offset.
15681 Bexpression*
15682 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15684 const Struct_field_list* fields = this->type_->fields();
15685 Struct_field_list::const_iterator p;
15686 unsigned i = 0;
15687 for (p = fields->begin();
15688 p != fields->end();
15689 ++p, ++i)
15690 if (&*p == this->field_)
15691 break;
15692 go_assert(&*p == this->field_);
15694 Gogo* gogo = context->gogo();
15695 Btype* btype = this->type_->get_backend(gogo);
15697 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15698 Type* uptr_type = Type::lookup_integer_type("uintptr");
15699 Expression* ret =
15700 Expression::make_integer_int64(offset, uptr_type,
15701 Linemap::predeclared_location());
15702 return ret->get_backend(context);
15705 // Dump ast representation for a struct field offset expression.
15707 void
15708 Struct_field_offset_expression::do_dump_expression(
15709 Ast_dump_context* ast_dump_context) const
15711 ast_dump_context->ostream() << "unsafe.Offsetof(";
15712 ast_dump_context->dump_type(this->type_);
15713 ast_dump_context->ostream() << '.';
15714 ast_dump_context->ostream() <<
15715 Gogo::message_name(this->field_->field_name());
15716 ast_dump_context->ostream() << ")";
15719 // Make an expression for a struct field offset.
15721 Expression*
15722 Expression::make_struct_field_offset(Struct_type* type,
15723 const Struct_field* field)
15725 return new Struct_field_offset_expression(type, field);
15728 // An expression which evaluates to the address of an unnamed label.
15730 class Label_addr_expression : public Expression
15732 public:
15733 Label_addr_expression(Label* label, Location location)
15734 : Expression(EXPRESSION_LABEL_ADDR, location),
15735 label_(label)
15738 protected:
15739 Type*
15740 do_type()
15741 { return Type::make_pointer_type(Type::make_void_type()); }
15743 void
15744 do_determine_type(const Type_context*)
15747 Expression*
15748 do_copy()
15749 { return new Label_addr_expression(this->label_, this->location()); }
15751 Bexpression*
15752 do_get_backend(Translate_context* context)
15753 { return this->label_->get_addr(context, this->location()); }
15755 void
15756 do_dump_expression(Ast_dump_context* ast_dump_context) const
15757 { ast_dump_context->ostream() << this->label_->name(); }
15759 private:
15760 // The label whose address we are taking.
15761 Label* label_;
15764 // Make an expression for the address of an unnamed label.
15766 Expression*
15767 Expression::make_label_addr(Label* label, Location location)
15769 return new Label_addr_expression(label, location);
15772 // Class Conditional_expression.
15774 // Traversal.
15777 Conditional_expression::do_traverse(Traverse* traverse)
15779 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15780 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15781 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15782 return TRAVERSE_EXIT;
15783 return TRAVERSE_CONTINUE;
15786 // Return the type of the conditional expression.
15788 Type*
15789 Conditional_expression::do_type()
15791 Type* result_type = Type::make_void_type();
15792 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15793 NULL))
15794 result_type = this->then_->type();
15795 else if (this->then_->is_nil_expression()
15796 || this->else_->is_nil_expression())
15797 result_type = (!this->then_->is_nil_expression()
15798 ? this->then_->type()
15799 : this->else_->type());
15800 return result_type;
15803 // Determine type for a conditional expression.
15805 void
15806 Conditional_expression::do_determine_type(const Type_context* context)
15808 this->cond_->determine_type_no_context();
15809 this->then_->determine_type(context);
15810 this->else_->determine_type(context);
15813 // Get the backend representation of a conditional expression.
15815 Bexpression*
15816 Conditional_expression::do_get_backend(Translate_context* context)
15818 Gogo* gogo = context->gogo();
15819 Btype* result_btype = this->type()->get_backend(gogo);
15820 Bexpression* cond = this->cond_->get_backend(context);
15821 Bexpression* then = this->then_->get_backend(context);
15822 Bexpression* belse = this->else_->get_backend(context);
15823 Bfunction* bfn = context->function()->func_value()->get_decl();
15824 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15825 belse, this->location());
15828 // Dump ast representation of a conditional expression.
15830 void
15831 Conditional_expression::do_dump_expression(
15832 Ast_dump_context* ast_dump_context) const
15834 ast_dump_context->ostream() << "(";
15835 ast_dump_context->dump_expression(this->cond_);
15836 ast_dump_context->ostream() << " ? ";
15837 ast_dump_context->dump_expression(this->then_);
15838 ast_dump_context->ostream() << " : ";
15839 ast_dump_context->dump_expression(this->else_);
15840 ast_dump_context->ostream() << ") ";
15843 // Make a conditional expression.
15845 Expression*
15846 Expression::make_conditional(Expression* cond, Expression* then,
15847 Expression* else_expr, Location location)
15849 return new Conditional_expression(cond, then, else_expr, location);
15852 // Class Compound_expression.
15854 // Traversal.
15857 Compound_expression::do_traverse(Traverse* traverse)
15859 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15860 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15861 return TRAVERSE_EXIT;
15862 return TRAVERSE_CONTINUE;
15865 // Return the type of the compound expression.
15867 Type*
15868 Compound_expression::do_type()
15870 return this->expr_->type();
15873 // Determine type for a compound expression.
15875 void
15876 Compound_expression::do_determine_type(const Type_context* context)
15878 this->init_->determine_type_no_context();
15879 this->expr_->determine_type(context);
15882 // Get the backend representation of a compound expression.
15884 Bexpression*
15885 Compound_expression::do_get_backend(Translate_context* context)
15887 Gogo* gogo = context->gogo();
15888 Bexpression* binit = this->init_->get_backend(context);
15889 Bfunction* bfunction = context->function()->func_value()->get_decl();
15890 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15891 binit);
15892 Bexpression* bexpr = this->expr_->get_backend(context);
15893 return gogo->backend()->compound_expression(init_stmt, bexpr,
15894 this->location());
15897 // Dump ast representation of a conditional expression.
15899 void
15900 Compound_expression::do_dump_expression(
15901 Ast_dump_context* ast_dump_context) const
15903 ast_dump_context->ostream() << "(";
15904 ast_dump_context->dump_expression(this->init_);
15905 ast_dump_context->ostream() << ",";
15906 ast_dump_context->dump_expression(this->expr_);
15907 ast_dump_context->ostream() << ") ";
15910 // Make a compound expression.
15912 Expression*
15913 Expression::make_compound(Expression* init, Expression* expr, Location location)
15915 return new Compound_expression(init, expr, location);
15918 // Class Backend_expression.
15921 Backend_expression::do_traverse(Traverse*)
15923 return TRAVERSE_CONTINUE;
15926 Expression*
15927 Backend_expression::do_copy()
15929 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
15930 this->location());
15933 void
15934 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15936 ast_dump_context->ostream() << "backend_expression<";
15937 ast_dump_context->dump_type(this->type_);
15938 ast_dump_context->ostream() << ">";
15941 Expression*
15942 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15944 return new Backend_expression(bexpr, type, location);
15947 // Import an expression. This comes at the end in order to see the
15948 // various class definitions.
15950 Expression*
15951 Expression::import_expression(Import* imp)
15953 int c = imp->peek_char();
15954 if (imp->match_c_string("- ")
15955 || imp->match_c_string("! ")
15956 || imp->match_c_string("^ "))
15957 return Unary_expression::do_import(imp);
15958 else if (c == '(')
15959 return Binary_expression::do_import(imp);
15960 else if (imp->match_c_string("true")
15961 || imp->match_c_string("false"))
15962 return Boolean_expression::do_import(imp);
15963 else if (c == '"')
15964 return String_expression::do_import(imp);
15965 else if (c == '-' || (c >= '0' && c <= '9'))
15967 // This handles integers, floats and complex constants.
15968 return Integer_expression::do_import(imp);
15970 else if (imp->match_c_string("nil"))
15971 return Nil_expression::do_import(imp);
15972 else if (imp->match_c_string("convert"))
15973 return Type_conversion_expression::do_import(imp);
15974 else
15976 go_error_at(imp->location(), "import error: expected expression");
15977 return Expression::make_error(imp->location());
15981 // Class Expression_list.
15983 // Traverse the list.
15986 Expression_list::traverse(Traverse* traverse)
15988 for (Expression_list::iterator p = this->begin();
15989 p != this->end();
15990 ++p)
15992 if (*p != NULL)
15994 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15995 return TRAVERSE_EXIT;
15998 return TRAVERSE_CONTINUE;
16001 // Copy the list.
16003 Expression_list*
16004 Expression_list::copy()
16006 Expression_list* ret = new Expression_list();
16007 for (Expression_list::iterator p = this->begin();
16008 p != this->end();
16009 ++p)
16011 if (*p == NULL)
16012 ret->push_back(NULL);
16013 else
16014 ret->push_back((*p)->copy());
16016 return ret;
16019 // Return whether an expression list has an error expression.
16021 bool
16022 Expression_list::contains_error() const
16024 for (Expression_list::const_iterator p = this->begin();
16025 p != this->end();
16026 ++p)
16027 if (*p != NULL && (*p)->is_error_expression())
16028 return true;
16029 return false;
16032 // Class Numeric_constant.
16034 // Destructor.
16036 Numeric_constant::~Numeric_constant()
16038 this->clear();
16041 // Copy constructor.
16043 Numeric_constant::Numeric_constant(const Numeric_constant& a)
16044 : classification_(a.classification_), type_(a.type_)
16046 switch (a.classification_)
16048 case NC_INVALID:
16049 break;
16050 case NC_INT:
16051 case NC_RUNE:
16052 mpz_init_set(this->u_.int_val, a.u_.int_val);
16053 break;
16054 case NC_FLOAT:
16055 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16056 break;
16057 case NC_COMPLEX:
16058 mpc_init2(this->u_.complex_val, mpc_precision);
16059 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16060 break;
16061 default:
16062 go_unreachable();
16066 // Assignment operator.
16068 Numeric_constant&
16069 Numeric_constant::operator=(const Numeric_constant& a)
16071 this->clear();
16072 this->classification_ = a.classification_;
16073 this->type_ = a.type_;
16074 switch (a.classification_)
16076 case NC_INVALID:
16077 break;
16078 case NC_INT:
16079 case NC_RUNE:
16080 mpz_init_set(this->u_.int_val, a.u_.int_val);
16081 break;
16082 case NC_FLOAT:
16083 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16084 break;
16085 case NC_COMPLEX:
16086 mpc_init2(this->u_.complex_val, mpc_precision);
16087 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16088 break;
16089 default:
16090 go_unreachable();
16092 return *this;
16095 // Clear the contents.
16097 void
16098 Numeric_constant::clear()
16100 switch (this->classification_)
16102 case NC_INVALID:
16103 break;
16104 case NC_INT:
16105 case NC_RUNE:
16106 mpz_clear(this->u_.int_val);
16107 break;
16108 case NC_FLOAT:
16109 mpfr_clear(this->u_.float_val);
16110 break;
16111 case NC_COMPLEX:
16112 mpc_clear(this->u_.complex_val);
16113 break;
16114 default:
16115 go_unreachable();
16117 this->classification_ = NC_INVALID;
16120 // Set to an unsigned long value.
16122 void
16123 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
16125 this->clear();
16126 this->classification_ = NC_INT;
16127 this->type_ = type;
16128 mpz_init_set_ui(this->u_.int_val, val);
16131 // Set to an integer value.
16133 void
16134 Numeric_constant::set_int(Type* type, const mpz_t val)
16136 this->clear();
16137 this->classification_ = NC_INT;
16138 this->type_ = type;
16139 mpz_init_set(this->u_.int_val, val);
16142 // Set to a rune value.
16144 void
16145 Numeric_constant::set_rune(Type* type, const mpz_t val)
16147 this->clear();
16148 this->classification_ = NC_RUNE;
16149 this->type_ = type;
16150 mpz_init_set(this->u_.int_val, val);
16153 // Set to a floating point value.
16155 void
16156 Numeric_constant::set_float(Type* type, const mpfr_t val)
16158 this->clear();
16159 this->classification_ = NC_FLOAT;
16160 this->type_ = type;
16162 // Numeric constants do not have negative zero values, so remove
16163 // them here. They also don't have infinity or NaN values, but we
16164 // should never see them here.
16165 int bits = 0;
16166 if (type != NULL
16167 && type->float_type() != NULL
16168 && !type->float_type()->is_abstract())
16169 bits = type->float_type()->bits();
16170 if (Numeric_constant::is_float_zero(val, bits))
16171 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16172 else
16173 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16176 // Set to a complex value.
16178 void
16179 Numeric_constant::set_complex(Type* type, const mpc_t val)
16181 this->clear();
16182 this->classification_ = NC_COMPLEX;
16183 this->type_ = type;
16185 // Avoid negative zero as in set_float.
16186 int bits = 0;
16187 if (type != NULL
16188 && type->complex_type() != NULL
16189 && !type->complex_type()->is_abstract())
16190 bits = type->complex_type()->bits() / 2;
16192 mpfr_t real;
16193 mpfr_init_set(real, mpc_realref(val), GMP_RNDN);
16194 if (Numeric_constant::is_float_zero(real, bits))
16195 mpfr_set_ui(real, 0, GMP_RNDN);
16197 mpfr_t imag;
16198 mpfr_init_set(imag, mpc_imagref(val), GMP_RNDN);
16199 if (Numeric_constant::is_float_zero(imag, bits))
16200 mpfr_set_ui(imag, 0, GMP_RNDN);
16202 mpc_init2(this->u_.complex_val, mpc_precision);
16203 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
16205 mpfr_clear(real);
16206 mpfr_clear(imag);
16209 // Return whether VAL, at a precision of BITS, is zero. BITS may be
16210 // zero in which case it is ignored.
16212 bool
16213 Numeric_constant::is_float_zero(const mpfr_t val, int bits)
16215 if (mpfr_zero_p(val))
16216 return true;
16217 switch (bits)
16219 case 0:
16220 return false;
16221 case 32:
16222 return mpfr_get_flt(val, GMP_RNDN) == 0;
16223 case 64:
16224 return mpfr_get_d(val, GMP_RNDN) == 0;
16225 default:
16226 go_unreachable();
16230 // Get an int value.
16232 void
16233 Numeric_constant::get_int(mpz_t* val) const
16235 go_assert(this->is_int());
16236 mpz_init_set(*val, this->u_.int_val);
16239 // Get a rune value.
16241 void
16242 Numeric_constant::get_rune(mpz_t* val) const
16244 go_assert(this->is_rune());
16245 mpz_init_set(*val, this->u_.int_val);
16248 // Get a floating point value.
16250 void
16251 Numeric_constant::get_float(mpfr_t* val) const
16253 go_assert(this->is_float());
16254 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16257 // Get a complex value.
16259 void
16260 Numeric_constant::get_complex(mpc_t* val) const
16262 go_assert(this->is_complex());
16263 mpc_init2(*val, mpc_precision);
16264 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16267 // Express value as unsigned long if possible.
16269 Numeric_constant::To_unsigned_long
16270 Numeric_constant::to_unsigned_long(unsigned long* val) const
16272 switch (this->classification_)
16274 case NC_INT:
16275 case NC_RUNE:
16276 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16277 case NC_FLOAT:
16278 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16279 case NC_COMPLEX:
16280 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16281 return NC_UL_NOTINT;
16282 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16283 val);
16284 default:
16285 go_unreachable();
16289 // Express integer value as unsigned long if possible.
16291 Numeric_constant::To_unsigned_long
16292 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16293 unsigned long *val) const
16295 if (mpz_sgn(ival) < 0)
16296 return NC_UL_NEGATIVE;
16297 unsigned long ui = mpz_get_ui(ival);
16298 if (mpz_cmp_ui(ival, ui) != 0)
16299 return NC_UL_BIG;
16300 *val = ui;
16301 return NC_UL_VALID;
16304 // Express floating point value as unsigned long if possible.
16306 Numeric_constant::To_unsigned_long
16307 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16308 unsigned long *val) const
16310 if (!mpfr_integer_p(fval))
16311 return NC_UL_NOTINT;
16312 mpz_t ival;
16313 mpz_init(ival);
16314 mpfr_get_z(ival, fval, GMP_RNDN);
16315 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16316 mpz_clear(ival);
16317 return ret;
16320 // Express value as memory size if possible.
16322 bool
16323 Numeric_constant::to_memory_size(int64_t* val) const
16325 switch (this->classification_)
16327 case NC_INT:
16328 case NC_RUNE:
16329 return this->mpz_to_memory_size(this->u_.int_val, val);
16330 case NC_FLOAT:
16331 return this->mpfr_to_memory_size(this->u_.float_val, val);
16332 case NC_COMPLEX:
16333 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16334 return false;
16335 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16336 default:
16337 go_unreachable();
16341 // Express integer as memory size if possible.
16343 bool
16344 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16346 if (mpz_sgn(ival) < 0)
16347 return false;
16348 if (mpz_fits_slong_p(ival))
16350 *val = static_cast<int64_t>(mpz_get_si(ival));
16351 return true;
16354 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16355 // positive value.
16356 if (mpz_sizeinbase(ival, 2) >= 64)
16357 return false;
16359 mpz_t q, r;
16360 mpz_init(q);
16361 mpz_init(r);
16362 mpz_tdiv_q_2exp(q, ival, 32);
16363 mpz_tdiv_r_2exp(r, ival, 32);
16364 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16365 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16366 + static_cast<int64_t>(mpz_get_ui(r)));
16367 mpz_clear(r);
16368 mpz_clear(q);
16369 return true;
16372 // Express floating point value as memory size if possible.
16374 bool
16375 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16377 if (!mpfr_integer_p(fval))
16378 return false;
16379 mpz_t ival;
16380 mpz_init(ival);
16381 mpfr_get_z(ival, fval, GMP_RNDN);
16382 bool ret = this->mpz_to_memory_size(ival, val);
16383 mpz_clear(ival);
16384 return ret;
16387 // Convert value to integer if possible.
16389 bool
16390 Numeric_constant::to_int(mpz_t* val) const
16392 switch (this->classification_)
16394 case NC_INT:
16395 case NC_RUNE:
16396 mpz_init_set(*val, this->u_.int_val);
16397 return true;
16398 case NC_FLOAT:
16399 if (!mpfr_integer_p(this->u_.float_val))
16400 return false;
16401 mpz_init(*val);
16402 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16403 return true;
16404 case NC_COMPLEX:
16405 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16406 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16407 return false;
16408 mpz_init(*val);
16409 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16410 return true;
16411 default:
16412 go_unreachable();
16416 // Convert value to floating point if possible.
16418 bool
16419 Numeric_constant::to_float(mpfr_t* val) const
16421 switch (this->classification_)
16423 case NC_INT:
16424 case NC_RUNE:
16425 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16426 return true;
16427 case NC_FLOAT:
16428 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16429 return true;
16430 case NC_COMPLEX:
16431 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16432 return false;
16433 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16434 return true;
16435 default:
16436 go_unreachable();
16440 // Convert value to complex.
16442 bool
16443 Numeric_constant::to_complex(mpc_t* val) const
16445 mpc_init2(*val, mpc_precision);
16446 switch (this->classification_)
16448 case NC_INT:
16449 case NC_RUNE:
16450 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16451 return true;
16452 case NC_FLOAT:
16453 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16454 return true;
16455 case NC_COMPLEX:
16456 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16457 return true;
16458 default:
16459 go_unreachable();
16463 // Get the type.
16465 Type*
16466 Numeric_constant::type() const
16468 if (this->type_ != NULL)
16469 return this->type_;
16470 switch (this->classification_)
16472 case NC_INT:
16473 return Type::make_abstract_integer_type();
16474 case NC_RUNE:
16475 return Type::make_abstract_character_type();
16476 case NC_FLOAT:
16477 return Type::make_abstract_float_type();
16478 case NC_COMPLEX:
16479 return Type::make_abstract_complex_type();
16480 default:
16481 go_unreachable();
16485 // If the constant can be expressed in TYPE, then set the type of the
16486 // constant to TYPE and return true. Otherwise return false, and, if
16487 // ISSUE_ERROR is true, report an appropriate error message.
16489 bool
16490 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16492 bool ret;
16493 if (type == NULL || type->is_error())
16494 ret = true;
16495 else if (type->integer_type() != NULL)
16496 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16497 else if (type->float_type() != NULL)
16498 ret = this->check_float_type(type->float_type(), issue_error, loc);
16499 else if (type->complex_type() != NULL)
16500 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16501 else
16503 ret = false;
16504 if (issue_error)
16505 go_assert(saw_errors());
16507 if (ret)
16508 this->type_ = type;
16509 return ret;
16512 // Check whether the constant can be expressed in an integer type.
16514 bool
16515 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16516 Location location)
16518 mpz_t val;
16519 switch (this->classification_)
16521 case NC_INT:
16522 case NC_RUNE:
16523 mpz_init_set(val, this->u_.int_val);
16524 break;
16526 case NC_FLOAT:
16527 if (!mpfr_integer_p(this->u_.float_val))
16529 if (issue_error)
16531 go_error_at(location,
16532 "floating point constant truncated to integer");
16533 this->set_invalid();
16535 return false;
16537 mpz_init(val);
16538 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16539 break;
16541 case NC_COMPLEX:
16542 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16543 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16545 if (issue_error)
16547 go_error_at(location, "complex constant truncated to integer");
16548 this->set_invalid();
16550 return false;
16552 mpz_init(val);
16553 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16554 break;
16556 default:
16557 go_unreachable();
16560 bool ret;
16561 if (type->is_abstract())
16562 ret = true;
16563 else
16565 int bits = mpz_sizeinbase(val, 2);
16566 if (type->is_unsigned())
16568 // For an unsigned type we can only accept a nonnegative
16569 // number, and we must be able to represents at least BITS.
16570 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16572 else
16574 // For a signed type we need an extra bit to indicate the
16575 // sign. We have to handle the most negative integer
16576 // specially.
16577 ret = (bits + 1 <= type->bits()
16578 || (bits <= type->bits()
16579 && mpz_sgn(val) < 0
16580 && (mpz_scan1(val, 0)
16581 == static_cast<unsigned long>(type->bits() - 1))
16582 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16586 if (!ret && issue_error)
16588 go_error_at(location, "integer constant overflow");
16589 this->set_invalid();
16592 return ret;
16595 // Check whether the constant can be expressed in a floating point
16596 // type.
16598 bool
16599 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16600 Location location)
16602 mpfr_t val;
16603 switch (this->classification_)
16605 case NC_INT:
16606 case NC_RUNE:
16607 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16608 break;
16610 case NC_FLOAT:
16611 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16612 break;
16614 case NC_COMPLEX:
16615 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16617 if (issue_error)
16619 this->set_invalid();
16620 go_error_at(location, "complex constant truncated to float");
16622 return false;
16624 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16625 break;
16627 default:
16628 go_unreachable();
16631 bool ret;
16632 if (type->is_abstract())
16633 ret = true;
16634 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16636 // A NaN or Infinity always fits in the range of the type.
16637 ret = true;
16639 else
16641 mp_exp_t exp = mpfr_get_exp(val);
16642 mp_exp_t max_exp;
16643 switch (type->bits())
16645 case 32:
16646 max_exp = 128;
16647 break;
16648 case 64:
16649 max_exp = 1024;
16650 break;
16651 default:
16652 go_unreachable();
16655 ret = exp <= max_exp;
16657 if (ret)
16659 // Round the constant to the desired type.
16660 mpfr_t t;
16661 mpfr_init(t);
16662 switch (type->bits())
16664 case 32:
16665 mpfr_set_prec(t, 24);
16666 break;
16667 case 64:
16668 mpfr_set_prec(t, 53);
16669 break;
16670 default:
16671 go_unreachable();
16673 mpfr_set(t, val, GMP_RNDN);
16674 mpfr_set(val, t, GMP_RNDN);
16675 mpfr_clear(t);
16677 this->set_float(type, val);
16681 mpfr_clear(val);
16683 if (!ret && issue_error)
16685 go_error_at(location, "floating point constant overflow");
16686 this->set_invalid();
16689 return ret;
16692 // Check whether the constant can be expressed in a complex type.
16694 bool
16695 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16696 Location location)
16698 if (type->is_abstract())
16699 return true;
16701 mp_exp_t max_exp;
16702 switch (type->bits())
16704 case 64:
16705 max_exp = 128;
16706 break;
16707 case 128:
16708 max_exp = 1024;
16709 break;
16710 default:
16711 go_unreachable();
16714 mpc_t val;
16715 mpc_init2(val, mpc_precision);
16716 switch (this->classification_)
16718 case NC_INT:
16719 case NC_RUNE:
16720 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16721 break;
16723 case NC_FLOAT:
16724 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16725 break;
16727 case NC_COMPLEX:
16728 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16729 break;
16731 default:
16732 go_unreachable();
16735 bool ret = true;
16736 if (!mpfr_nan_p(mpc_realref(val))
16737 && !mpfr_inf_p(mpc_realref(val))
16738 && !mpfr_zero_p(mpc_realref(val))
16739 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16741 if (issue_error)
16743 go_error_at(location, "complex real part overflow");
16744 this->set_invalid();
16746 ret = false;
16749 if (!mpfr_nan_p(mpc_imagref(val))
16750 && !mpfr_inf_p(mpc_imagref(val))
16751 && !mpfr_zero_p(mpc_imagref(val))
16752 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16754 if (issue_error)
16756 go_error_at(location, "complex imaginary part overflow");
16757 this->set_invalid();
16759 ret = false;
16762 if (ret)
16764 // Round the constant to the desired type.
16765 mpc_t t;
16766 switch (type->bits())
16768 case 64:
16769 mpc_init2(t, 24);
16770 break;
16771 case 128:
16772 mpc_init2(t, 53);
16773 break;
16774 default:
16775 go_unreachable();
16777 mpc_set(t, val, MPC_RNDNN);
16778 mpc_set(val, t, MPC_RNDNN);
16779 mpc_clear(t);
16781 this->set_complex(type, val);
16784 mpc_clear(val);
16786 return ret;
16789 // Return an Expression for this value.
16791 Expression*
16792 Numeric_constant::expression(Location loc) const
16794 switch (this->classification_)
16796 case NC_INT:
16797 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16798 case NC_RUNE:
16799 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16800 case NC_FLOAT:
16801 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16802 case NC_COMPLEX:
16803 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16804 case NC_INVALID:
16805 go_assert(saw_errors());
16806 return Expression::make_error(loc);
16807 default:
16808 go_unreachable();