compiler: move some escape check to Mark_address_taken
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob319fc9e693474c812e4e051538280bb59cec4430
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_->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_->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 Btype* btype = this->type()->get_backend(gogo);
1315 Bvariable* bvar;
1316 std::string asm_name(go_selectively_encode_id(var_name));
1317 if (no->package() != NULL || is_descriptor)
1318 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1319 btype, loc);
1320 else
1322 Location bloc = Linemap::predeclared_location();
1323 bool is_hidden = ((no->is_function()
1324 && no->func_value()->enclosing() != NULL)
1325 || Gogo::is_thunk(no));
1326 bvar = context->backend()->immutable_struct(var_name, asm_name,
1327 is_hidden, false,
1328 btype, bloc);
1329 Expression_list* vals = new Expression_list();
1330 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1331 Expression* init =
1332 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1333 Translate_context bcontext(gogo, NULL, NULL, NULL);
1334 bcontext.set_is_const();
1335 Bexpression* binit = init->get_backend(&bcontext);
1336 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1337 false, btype, bloc, binit);
1340 this->dvar_ = bvar;
1341 return gogo->backend()->var_expression(bvar, loc);
1344 // Print a function descriptor expression.
1346 void
1347 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1349 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1352 // Make a function descriptor expression.
1354 Func_descriptor_expression*
1355 Expression::make_func_descriptor(Named_object* fn)
1357 return new Func_descriptor_expression(fn);
1360 // Make the function descriptor type, so that it can be converted.
1362 void
1363 Expression::make_func_descriptor_type()
1365 Func_descriptor_expression::make_func_descriptor_type();
1368 // A reference to just the code of a function.
1370 class Func_code_reference_expression : public Expression
1372 public:
1373 Func_code_reference_expression(Named_object* function, Location location)
1374 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1375 function_(function)
1378 protected:
1380 do_traverse(Traverse*)
1381 { return TRAVERSE_CONTINUE; }
1383 bool
1384 do_is_static_initializer() const
1385 { return true; }
1387 Type*
1388 do_type()
1389 { return Type::make_pointer_type(Type::make_void_type()); }
1391 void
1392 do_determine_type(const Type_context*)
1395 Expression*
1396 do_copy()
1398 return Expression::make_func_code_reference(this->function_,
1399 this->location());
1402 Bexpression*
1403 do_get_backend(Translate_context*);
1405 void
1406 do_dump_expression(Ast_dump_context* context) const
1407 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1409 private:
1410 // The function.
1411 Named_object* function_;
1414 // Get the backend representation for a reference to function code.
1416 Bexpression*
1417 Func_code_reference_expression::do_get_backend(Translate_context* context)
1419 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1420 this->location());
1423 // Make a reference to the code of a function.
1425 Expression*
1426 Expression::make_func_code_reference(Named_object* function, Location location)
1428 return new Func_code_reference_expression(function, location);
1431 // Class Unknown_expression.
1433 // Return the name of an unknown expression.
1435 const std::string&
1436 Unknown_expression::name() const
1438 return this->named_object_->name();
1441 // Lower a reference to an unknown name.
1443 Expression*
1444 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1446 Location location = this->location();
1447 Named_object* no = this->named_object_;
1448 Named_object* real;
1449 if (!no->is_unknown())
1450 real = no;
1451 else
1453 real = no->unknown_value()->real_named_object();
1454 if (real == NULL)
1456 if (this->is_composite_literal_key_)
1457 return this;
1458 if (!this->no_error_message_)
1459 go_error_at(location, "reference to undefined name %qs",
1460 this->named_object_->message_name().c_str());
1461 return Expression::make_error(location);
1464 switch (real->classification())
1466 case Named_object::NAMED_OBJECT_CONST:
1467 return Expression::make_const_reference(real, location);
1468 case Named_object::NAMED_OBJECT_TYPE:
1469 return Expression::make_type(real->type_value(), location);
1470 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1471 if (this->is_composite_literal_key_)
1472 return this;
1473 if (!this->no_error_message_)
1474 go_error_at(location, "reference to undefined type %qs",
1475 real->message_name().c_str());
1476 return Expression::make_error(location);
1477 case Named_object::NAMED_OBJECT_VAR:
1478 real->var_value()->set_is_used();
1479 return Expression::make_var_reference(real, location);
1480 case Named_object::NAMED_OBJECT_FUNC:
1481 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1482 return Expression::make_func_reference(real, NULL, location);
1483 case Named_object::NAMED_OBJECT_PACKAGE:
1484 if (this->is_composite_literal_key_)
1485 return this;
1486 if (!this->no_error_message_)
1487 go_error_at(location, "unexpected reference to package");
1488 return Expression::make_error(location);
1489 default:
1490 go_unreachable();
1494 // Dump the ast representation for an unknown expression to a dump context.
1496 void
1497 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1499 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1500 << ")";
1503 // Make a reference to an unknown name.
1505 Unknown_expression*
1506 Expression::make_unknown_reference(Named_object* no, Location location)
1508 return new Unknown_expression(no, location);
1511 // A boolean expression.
1513 class Boolean_expression : public Expression
1515 public:
1516 Boolean_expression(bool val, Location location)
1517 : Expression(EXPRESSION_BOOLEAN, location),
1518 val_(val), type_(NULL)
1521 static Expression*
1522 do_import(Import*);
1524 protected:
1525 bool
1526 do_is_constant() const
1527 { return true; }
1529 bool
1530 do_is_static_initializer() const
1531 { return true; }
1533 Type*
1534 do_type();
1536 void
1537 do_determine_type(const Type_context*);
1539 Expression*
1540 do_copy()
1541 { return this; }
1543 Bexpression*
1544 do_get_backend(Translate_context* context)
1545 { return context->backend()->boolean_constant_expression(this->val_); }
1547 void
1548 do_export(Export* exp) const
1549 { exp->write_c_string(this->val_ ? "true" : "false"); }
1551 void
1552 do_dump_expression(Ast_dump_context* ast_dump_context) const
1553 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1555 private:
1556 // The constant.
1557 bool val_;
1558 // The type as determined by context.
1559 Type* type_;
1562 // Get the type.
1564 Type*
1565 Boolean_expression::do_type()
1567 if (this->type_ == NULL)
1568 this->type_ = Type::make_boolean_type();
1569 return this->type_;
1572 // Set the type from the context.
1574 void
1575 Boolean_expression::do_determine_type(const Type_context* context)
1577 if (this->type_ != NULL && !this->type_->is_abstract())
1579 else if (context->type != NULL && context->type->is_boolean_type())
1580 this->type_ = context->type;
1581 else if (!context->may_be_abstract)
1582 this->type_ = Type::lookup_bool_type();
1585 // Import a boolean constant.
1587 Expression*
1588 Boolean_expression::do_import(Import* imp)
1590 if (imp->peek_char() == 't')
1592 imp->require_c_string("true");
1593 return Expression::make_boolean(true, imp->location());
1595 else
1597 imp->require_c_string("false");
1598 return Expression::make_boolean(false, imp->location());
1602 // Make a boolean expression.
1604 Expression*
1605 Expression::make_boolean(bool val, Location location)
1607 return new Boolean_expression(val, location);
1610 // Class String_expression.
1612 // Get the type.
1614 Type*
1615 String_expression::do_type()
1617 if (this->type_ == NULL)
1618 this->type_ = Type::make_string_type();
1619 return this->type_;
1622 // Set the type from the context.
1624 void
1625 String_expression::do_determine_type(const Type_context* context)
1627 if (this->type_ != NULL && !this->type_->is_abstract())
1629 else if (context->type != NULL && context->type->is_string_type())
1630 this->type_ = context->type;
1631 else if (!context->may_be_abstract)
1632 this->type_ = Type::lookup_string_type();
1635 // Build a string constant.
1637 Bexpression*
1638 String_expression::do_get_backend(Translate_context* context)
1640 Gogo* gogo = context->gogo();
1641 Btype* btype = Type::make_string_type()->get_backend(gogo);
1643 Location loc = this->location();
1644 std::vector<Bexpression*> init(2);
1645 Bexpression* str_cst =
1646 gogo->backend()->string_constant_expression(this->val_);
1647 init[0] = gogo->backend()->address_expression(str_cst, loc);
1649 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1650 mpz_t lenval;
1651 mpz_init_set_ui(lenval, this->val_.length());
1652 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1653 mpz_clear(lenval);
1655 return gogo->backend()->constructor_expression(btype, init, loc);
1658 // Write string literal to string dump.
1660 void
1661 String_expression::export_string(String_dump* exp,
1662 const String_expression* str)
1664 std::string s;
1665 s.reserve(str->val_.length() * 4 + 2);
1666 s += '"';
1667 for (std::string::const_iterator p = str->val_.begin();
1668 p != str->val_.end();
1669 ++p)
1671 if (*p == '\\' || *p == '"')
1673 s += '\\';
1674 s += *p;
1676 else if (*p >= 0x20 && *p < 0x7f)
1677 s += *p;
1678 else if (*p == '\n')
1679 s += "\\n";
1680 else if (*p == '\t')
1681 s += "\\t";
1682 else
1684 s += "\\x";
1685 unsigned char c = *p;
1686 unsigned int dig = c >> 4;
1687 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1688 dig = c & 0xf;
1689 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1692 s += '"';
1693 exp->write_string(s);
1696 // Export a string expression.
1698 void
1699 String_expression::do_export(Export* exp) const
1701 String_expression::export_string(exp, this);
1704 // Import a string expression.
1706 Expression*
1707 String_expression::do_import(Import* imp)
1709 imp->require_c_string("\"");
1710 std::string val;
1711 while (true)
1713 int c = imp->get_char();
1714 if (c == '"' || c == -1)
1715 break;
1716 if (c != '\\')
1717 val += static_cast<char>(c);
1718 else
1720 c = imp->get_char();
1721 if (c == '\\' || c == '"')
1722 val += static_cast<char>(c);
1723 else if (c == 'n')
1724 val += '\n';
1725 else if (c == 't')
1726 val += '\t';
1727 else if (c == 'x')
1729 c = imp->get_char();
1730 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1731 c = imp->get_char();
1732 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1733 char v = (vh << 4) | vl;
1734 val += v;
1736 else
1738 go_error_at(imp->location(), "bad string constant");
1739 return Expression::make_error(imp->location());
1743 return Expression::make_string(val, imp->location());
1746 // Ast dump for string expression.
1748 void
1749 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1751 String_expression::export_string(ast_dump_context, this);
1754 // Make a string expression.
1756 Expression*
1757 Expression::make_string(const std::string& val, Location location)
1759 return new String_expression(val, location);
1762 // An expression that evaluates to some characteristic of a string.
1763 // This is used when indexing, bound-checking, or nil checking a string.
1765 class String_info_expression : public Expression
1767 public:
1768 String_info_expression(Expression* string, String_info string_info,
1769 Location location)
1770 : Expression(EXPRESSION_STRING_INFO, location),
1771 string_(string), string_info_(string_info)
1774 protected:
1775 Type*
1776 do_type();
1778 void
1779 do_determine_type(const Type_context*)
1780 { go_unreachable(); }
1782 Expression*
1783 do_copy()
1785 return new String_info_expression(this->string_->copy(), this->string_info_,
1786 this->location());
1789 Bexpression*
1790 do_get_backend(Translate_context* context);
1792 void
1793 do_dump_expression(Ast_dump_context*) const;
1795 void
1796 do_issue_nil_check()
1797 { this->string_->issue_nil_check(); }
1799 private:
1800 // The string for which we are getting information.
1801 Expression* string_;
1802 // What information we want.
1803 String_info string_info_;
1806 // Return the type of the string info.
1808 Type*
1809 String_info_expression::do_type()
1811 switch (this->string_info_)
1813 case STRING_INFO_DATA:
1815 Type* byte_type = Type::lookup_integer_type("uint8");
1816 return Type::make_pointer_type(byte_type);
1818 case STRING_INFO_LENGTH:
1819 return Type::lookup_integer_type("int");
1820 default:
1821 go_unreachable();
1825 // Return string information in GENERIC.
1827 Bexpression*
1828 String_info_expression::do_get_backend(Translate_context* context)
1830 Gogo* gogo = context->gogo();
1832 Bexpression* bstring = this->string_->get_backend(context);
1833 switch (this->string_info_)
1835 case STRING_INFO_DATA:
1836 case STRING_INFO_LENGTH:
1837 return gogo->backend()->struct_field_expression(bstring,
1838 this->string_info_,
1839 this->location());
1840 break;
1841 default:
1842 go_unreachable();
1846 // Dump ast representation for a type info expression.
1848 void
1849 String_info_expression::do_dump_expression(
1850 Ast_dump_context* ast_dump_context) const
1852 ast_dump_context->ostream() << "stringinfo(";
1853 this->string_->dump_expression(ast_dump_context);
1854 ast_dump_context->ostream() << ",";
1855 ast_dump_context->ostream() <<
1856 (this->string_info_ == STRING_INFO_DATA ? "data"
1857 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1858 : "unknown");
1859 ast_dump_context->ostream() << ")";
1862 // Make a string info expression.
1864 Expression*
1865 Expression::make_string_info(Expression* string, String_info string_info,
1866 Location location)
1868 return new String_info_expression(string, string_info, location);
1871 // Make an integer expression.
1873 class Integer_expression : public Expression
1875 public:
1876 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1877 Location location)
1878 : Expression(EXPRESSION_INTEGER, location),
1879 type_(type), is_character_constant_(is_character_constant)
1880 { mpz_init_set(this->val_, *val); }
1882 static Expression*
1883 do_import(Import*);
1885 // Write VAL to string dump.
1886 static void
1887 export_integer(String_dump* exp, const mpz_t val);
1889 // Write VAL to dump context.
1890 static void
1891 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1893 protected:
1894 bool
1895 do_is_constant() const
1896 { return true; }
1898 bool
1899 do_is_static_initializer() const
1900 { return true; }
1902 bool
1903 do_numeric_constant_value(Numeric_constant* nc) const;
1905 Type*
1906 do_type();
1908 void
1909 do_determine_type(const Type_context* context);
1911 void
1912 do_check_types(Gogo*);
1914 Bexpression*
1915 do_get_backend(Translate_context*);
1917 Expression*
1918 do_copy()
1920 if (this->is_character_constant_)
1921 return Expression::make_character(&this->val_, this->type_,
1922 this->location());
1923 else
1924 return Expression::make_integer_z(&this->val_, this->type_,
1925 this->location());
1928 void
1929 do_export(Export*) const;
1931 void
1932 do_dump_expression(Ast_dump_context*) const;
1934 private:
1935 // The integer value.
1936 mpz_t val_;
1937 // The type so far.
1938 Type* type_;
1939 // Whether this is a character constant.
1940 bool is_character_constant_;
1943 // Return a numeric constant for this expression. We have to mark
1944 // this as a character when appropriate.
1946 bool
1947 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1949 if (this->is_character_constant_)
1950 nc->set_rune(this->type_, this->val_);
1951 else
1952 nc->set_int(this->type_, this->val_);
1953 return true;
1956 // Return the current type. If we haven't set the type yet, we return
1957 // an abstract integer type.
1959 Type*
1960 Integer_expression::do_type()
1962 if (this->type_ == NULL)
1964 if (this->is_character_constant_)
1965 this->type_ = Type::make_abstract_character_type();
1966 else
1967 this->type_ = Type::make_abstract_integer_type();
1969 return this->type_;
1972 // Set the type of the integer value. Here we may switch from an
1973 // abstract type to a real type.
1975 void
1976 Integer_expression::do_determine_type(const Type_context* context)
1978 if (this->type_ != NULL && !this->type_->is_abstract())
1980 else if (context->type != NULL && context->type->is_numeric_type())
1981 this->type_ = context->type;
1982 else if (!context->may_be_abstract)
1984 if (this->is_character_constant_)
1985 this->type_ = Type::lookup_integer_type("int32");
1986 else
1987 this->type_ = Type::lookup_integer_type("int");
1991 // Check the type of an integer constant.
1993 void
1994 Integer_expression::do_check_types(Gogo*)
1996 Type* type = this->type_;
1997 if (type == NULL)
1998 return;
1999 Numeric_constant nc;
2000 if (this->is_character_constant_)
2001 nc.set_rune(NULL, this->val_);
2002 else
2003 nc.set_int(NULL, this->val_);
2004 if (!nc.set_type(type, true, this->location()))
2005 this->set_is_error();
2008 // Get the backend representation for an integer constant.
2010 Bexpression*
2011 Integer_expression::do_get_backend(Translate_context* context)
2013 if (this->is_error_expression()
2014 || (this->type_ != NULL && this->type_->is_error_type()))
2016 go_assert(saw_errors());
2017 return context->gogo()->backend()->error_expression();
2020 Type* resolved_type = NULL;
2021 if (this->type_ != NULL && !this->type_->is_abstract())
2022 resolved_type = this->type_;
2023 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2025 // We are converting to an abstract floating point type.
2026 resolved_type = Type::lookup_float_type("float64");
2028 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2030 // We are converting to an abstract complex type.
2031 resolved_type = Type::lookup_complex_type("complex128");
2033 else
2035 // If we still have an abstract type here, then this is being
2036 // used in a constant expression which didn't get reduced for
2037 // some reason. Use a type which will fit the value. We use <,
2038 // not <=, because we need an extra bit for the sign bit.
2039 int bits = mpz_sizeinbase(this->val_, 2);
2040 Type* int_type = Type::lookup_integer_type("int");
2041 if (bits < int_type->integer_type()->bits())
2042 resolved_type = int_type;
2043 else if (bits < 64)
2044 resolved_type = Type::lookup_integer_type("int64");
2045 else
2047 if (!saw_errors())
2048 go_error_at(this->location(),
2049 "unknown type for large integer constant");
2050 return context->gogo()->backend()->error_expression();
2053 Numeric_constant nc;
2054 nc.set_int(resolved_type, this->val_);
2055 return Expression::backend_numeric_constant_expression(context, &nc);
2058 // Write VAL to export data.
2060 void
2061 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2063 char* s = mpz_get_str(NULL, 10, val);
2064 exp->write_c_string(s);
2065 free(s);
2068 // Export an integer in a constant expression.
2070 void
2071 Integer_expression::do_export(Export* exp) const
2073 Integer_expression::export_integer(exp, this->val_);
2074 if (this->is_character_constant_)
2075 exp->write_c_string("'");
2076 // A trailing space lets us reliably identify the end of the number.
2077 exp->write_c_string(" ");
2080 // Import an integer, floating point, or complex value. This handles
2081 // all these types because they all start with digits.
2083 Expression*
2084 Integer_expression::do_import(Import* imp)
2086 std::string num = imp->read_identifier();
2087 imp->require_c_string(" ");
2088 if (!num.empty() && num[num.length() - 1] == 'i')
2090 mpfr_t real;
2091 size_t plus_pos = num.find('+', 1);
2092 size_t minus_pos = num.find('-', 1);
2093 size_t pos;
2094 if (plus_pos == std::string::npos)
2095 pos = minus_pos;
2096 else if (minus_pos == std::string::npos)
2097 pos = plus_pos;
2098 else
2100 go_error_at(imp->location(), "bad number in import data: %qs",
2101 num.c_str());
2102 return Expression::make_error(imp->location());
2104 if (pos == std::string::npos)
2105 mpfr_set_ui(real, 0, GMP_RNDN);
2106 else
2108 std::string real_str = num.substr(0, pos);
2109 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2111 go_error_at(imp->location(), "bad number in import data: %qs",
2112 real_str.c_str());
2113 return Expression::make_error(imp->location());
2117 std::string imag_str;
2118 if (pos == std::string::npos)
2119 imag_str = num;
2120 else
2121 imag_str = num.substr(pos);
2122 imag_str = imag_str.substr(0, imag_str.size() - 1);
2123 mpfr_t imag;
2124 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2126 go_error_at(imp->location(), "bad number in import data: %qs",
2127 imag_str.c_str());
2128 return Expression::make_error(imp->location());
2130 mpc_t cval;
2131 mpc_init2(cval, mpc_precision);
2132 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2133 mpfr_clear(real);
2134 mpfr_clear(imag);
2135 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2136 mpc_clear(cval);
2137 return ret;
2139 else if (num.find('.') == std::string::npos
2140 && num.find('E') == std::string::npos)
2142 bool is_character_constant = (!num.empty()
2143 && num[num.length() - 1] == '\'');
2144 if (is_character_constant)
2145 num = num.substr(0, num.length() - 1);
2146 mpz_t val;
2147 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2149 go_error_at(imp->location(), "bad number in import data: %qs",
2150 num.c_str());
2151 return Expression::make_error(imp->location());
2153 Expression* ret;
2154 if (is_character_constant)
2155 ret = Expression::make_character(&val, NULL, imp->location());
2156 else
2157 ret = Expression::make_integer_z(&val, NULL, imp->location());
2158 mpz_clear(val);
2159 return ret;
2161 else
2163 mpfr_t val;
2164 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2166 go_error_at(imp->location(), "bad number in import data: %qs",
2167 num.c_str());
2168 return Expression::make_error(imp->location());
2170 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2171 mpfr_clear(val);
2172 return ret;
2175 // Ast dump for integer expression.
2177 void
2178 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2180 if (this->is_character_constant_)
2181 ast_dump_context->ostream() << '\'';
2182 Integer_expression::export_integer(ast_dump_context, this->val_);
2183 if (this->is_character_constant_)
2184 ast_dump_context->ostream() << '\'';
2187 // Build a new integer value from a multi-precision integer.
2189 Expression*
2190 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2192 return new Integer_expression(val, type, false, location);
2195 // Build a new integer value from an unsigned long.
2197 Expression*
2198 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2200 mpz_t zval;
2201 mpz_init_set_ui(zval, val);
2202 Expression* ret = Expression::make_integer_z(&zval, type, location);
2203 mpz_clear(zval);
2204 return ret;
2207 // Build a new integer value from a signed long.
2209 Expression*
2210 Expression::make_integer_sl(long val, Type *type, Location location)
2212 mpz_t zval;
2213 mpz_init_set_si(zval, val);
2214 Expression* ret = Expression::make_integer_z(&zval, type, location);
2215 mpz_clear(zval);
2216 return ret;
2219 // Store an int64_t in an uninitialized mpz_t.
2221 static void
2222 set_mpz_from_int64(mpz_t* zval, int64_t val)
2224 if (val >= 0)
2226 unsigned long ul = static_cast<unsigned long>(val);
2227 if (static_cast<int64_t>(ul) == val)
2229 mpz_init_set_ui(*zval, ul);
2230 return;
2233 uint64_t uv;
2234 if (val >= 0)
2235 uv = static_cast<uint64_t>(val);
2236 else
2237 uv = static_cast<uint64_t>(- val);
2238 unsigned long ul = uv & 0xffffffffUL;
2239 mpz_init_set_ui(*zval, ul);
2240 mpz_t hval;
2241 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2242 mpz_mul_2exp(hval, hval, 32);
2243 mpz_add(*zval, *zval, hval);
2244 mpz_clear(hval);
2245 if (val < 0)
2246 mpz_neg(*zval, *zval);
2249 // Build a new integer value from an int64_t.
2251 Expression*
2252 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2254 mpz_t zval;
2255 set_mpz_from_int64(&zval, val);
2256 Expression* ret = Expression::make_integer_z(&zval, type, location);
2257 mpz_clear(zval);
2258 return ret;
2261 // Build a new character constant value.
2263 Expression*
2264 Expression::make_character(const mpz_t* val, Type* type, Location location)
2266 return new Integer_expression(val, type, true, location);
2269 // Floats.
2271 class Float_expression : public Expression
2273 public:
2274 Float_expression(const mpfr_t* val, Type* type, Location location)
2275 : Expression(EXPRESSION_FLOAT, location),
2276 type_(type)
2278 mpfr_init_set(this->val_, *val, GMP_RNDN);
2281 // Write VAL to export data.
2282 static void
2283 export_float(String_dump* exp, const mpfr_t val);
2285 // Write VAL to dump file.
2286 static void
2287 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2289 protected:
2290 bool
2291 do_is_constant() const
2292 { return true; }
2294 bool
2295 do_is_static_initializer() const
2296 { return true; }
2298 bool
2299 do_numeric_constant_value(Numeric_constant* nc) const
2301 nc->set_float(this->type_, this->val_);
2302 return true;
2305 Type*
2306 do_type();
2308 void
2309 do_determine_type(const Type_context*);
2311 void
2312 do_check_types(Gogo*);
2314 Expression*
2315 do_copy()
2316 { return Expression::make_float(&this->val_, this->type_,
2317 this->location()); }
2319 Bexpression*
2320 do_get_backend(Translate_context*);
2322 void
2323 do_export(Export*) const;
2325 void
2326 do_dump_expression(Ast_dump_context*) const;
2328 private:
2329 // The floating point value.
2330 mpfr_t val_;
2331 // The type so far.
2332 Type* type_;
2335 // Return the current type. If we haven't set the type yet, we return
2336 // an abstract float type.
2338 Type*
2339 Float_expression::do_type()
2341 if (this->type_ == NULL)
2342 this->type_ = Type::make_abstract_float_type();
2343 return this->type_;
2346 // Set the type of the float value. Here we may switch from an
2347 // abstract type to a real type.
2349 void
2350 Float_expression::do_determine_type(const Type_context* context)
2352 if (this->type_ != NULL && !this->type_->is_abstract())
2354 else if (context->type != NULL
2355 && (context->type->integer_type() != NULL
2356 || context->type->float_type() != NULL
2357 || context->type->complex_type() != NULL))
2358 this->type_ = context->type;
2359 else if (!context->may_be_abstract)
2360 this->type_ = Type::lookup_float_type("float64");
2363 // Check the type of a float value.
2365 void
2366 Float_expression::do_check_types(Gogo*)
2368 Type* type = this->type_;
2369 if (type == NULL)
2370 return;
2371 Numeric_constant nc;
2372 nc.set_float(NULL, this->val_);
2373 if (!nc.set_type(this->type_, true, this->location()))
2374 this->set_is_error();
2377 // Get the backend representation for a float constant.
2379 Bexpression*
2380 Float_expression::do_get_backend(Translate_context* context)
2382 if (this->is_error_expression()
2383 || (this->type_ != NULL && this->type_->is_error_type()))
2385 go_assert(saw_errors());
2386 return context->gogo()->backend()->error_expression();
2389 Type* resolved_type;
2390 if (this->type_ != NULL && !this->type_->is_abstract())
2391 resolved_type = this->type_;
2392 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2394 // We have an abstract integer type. We just hope for the best.
2395 resolved_type = Type::lookup_integer_type("int");
2397 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2399 // We are converting to an abstract complex type.
2400 resolved_type = Type::lookup_complex_type("complex128");
2402 else
2404 // If we still have an abstract type here, then this is being
2405 // used in a constant expression which didn't get reduced. We
2406 // just use float64 and hope for the best.
2407 resolved_type = Type::lookup_float_type("float64");
2410 Numeric_constant nc;
2411 nc.set_float(resolved_type, this->val_);
2412 return Expression::backend_numeric_constant_expression(context, &nc);
2415 // Write a floating point number to a string dump.
2417 void
2418 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2420 mp_exp_t exponent;
2421 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2422 if (*s == '-')
2423 exp->write_c_string("-");
2424 exp->write_c_string("0.");
2425 exp->write_c_string(*s == '-' ? s + 1 : s);
2426 mpfr_free_str(s);
2427 char buf[30];
2428 snprintf(buf, sizeof buf, "E%ld", exponent);
2429 exp->write_c_string(buf);
2432 // Export a floating point number in a constant expression.
2434 void
2435 Float_expression::do_export(Export* exp) const
2437 Float_expression::export_float(exp, this->val_);
2438 // A trailing space lets us reliably identify the end of the number.
2439 exp->write_c_string(" ");
2442 // Dump a floating point number to the dump file.
2444 void
2445 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2447 Float_expression::export_float(ast_dump_context, this->val_);
2450 // Make a float expression.
2452 Expression*
2453 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2455 return new Float_expression(val, type, location);
2458 // Complex numbers.
2460 class Complex_expression : public Expression
2462 public:
2463 Complex_expression(const mpc_t* val, Type* type, Location location)
2464 : Expression(EXPRESSION_COMPLEX, location),
2465 type_(type)
2467 mpc_init2(this->val_, mpc_precision);
2468 mpc_set(this->val_, *val, MPC_RNDNN);
2471 // Write VAL to string dump.
2472 static void
2473 export_complex(String_dump* exp, const mpc_t val);
2475 // Write REAL/IMAG to dump context.
2476 static void
2477 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2479 protected:
2480 bool
2481 do_is_constant() const
2482 { return true; }
2484 bool
2485 do_is_static_initializer() const
2486 { return true; }
2488 bool
2489 do_numeric_constant_value(Numeric_constant* nc) const
2491 nc->set_complex(this->type_, this->val_);
2492 return true;
2495 Type*
2496 do_type();
2498 void
2499 do_determine_type(const Type_context*);
2501 void
2502 do_check_types(Gogo*);
2504 Expression*
2505 do_copy()
2507 return Expression::make_complex(&this->val_, this->type_,
2508 this->location());
2511 Bexpression*
2512 do_get_backend(Translate_context*);
2514 void
2515 do_export(Export*) const;
2517 void
2518 do_dump_expression(Ast_dump_context*) const;
2520 private:
2521 // The complex value.
2522 mpc_t val_;
2523 // The type if known.
2524 Type* type_;
2527 // Return the current type. If we haven't set the type yet, we return
2528 // an abstract complex type.
2530 Type*
2531 Complex_expression::do_type()
2533 if (this->type_ == NULL)
2534 this->type_ = Type::make_abstract_complex_type();
2535 return this->type_;
2538 // Set the type of the complex value. Here we may switch from an
2539 // abstract type to a real type.
2541 void
2542 Complex_expression::do_determine_type(const Type_context* context)
2544 if (this->type_ != NULL && !this->type_->is_abstract())
2546 else if (context->type != NULL && context->type->is_numeric_type())
2547 this->type_ = context->type;
2548 else if (!context->may_be_abstract)
2549 this->type_ = Type::lookup_complex_type("complex128");
2552 // Check the type of a complex value.
2554 void
2555 Complex_expression::do_check_types(Gogo*)
2557 Type* type = this->type_;
2558 if (type == NULL)
2559 return;
2560 Numeric_constant nc;
2561 nc.set_complex(NULL, this->val_);
2562 if (!nc.set_type(this->type_, true, this->location()))
2563 this->set_is_error();
2566 // Get the backend representation for a complex constant.
2568 Bexpression*
2569 Complex_expression::do_get_backend(Translate_context* context)
2571 if (this->is_error_expression()
2572 || (this->type_ != NULL && this->type_->is_error_type()))
2574 go_assert(saw_errors());
2575 return context->gogo()->backend()->error_expression();
2578 Type* resolved_type;
2579 if (this->type_ != NULL && !this->type_->is_abstract())
2580 resolved_type = this->type_;
2581 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2583 // We are converting to an abstract integer type.
2584 resolved_type = Type::lookup_integer_type("int");
2586 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2588 // We are converting to an abstract float type.
2589 resolved_type = Type::lookup_float_type("float64");
2591 else
2593 // If we still have an abstract type here, this is being
2594 // used in a constant expression which didn't get reduced. We
2595 // just use complex128 and hope for the best.
2596 resolved_type = Type::lookup_complex_type("complex128");
2599 Numeric_constant nc;
2600 nc.set_complex(resolved_type, this->val_);
2601 return Expression::backend_numeric_constant_expression(context, &nc);
2604 // Write REAL/IMAG to export data.
2606 void
2607 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2609 if (!mpfr_zero_p(mpc_realref(val)))
2611 Float_expression::export_float(exp, mpc_realref(val));
2612 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2613 exp->write_c_string("+");
2615 Float_expression::export_float(exp, mpc_imagref(val));
2616 exp->write_c_string("i");
2619 // Export a complex number in a constant expression.
2621 void
2622 Complex_expression::do_export(Export* exp) const
2624 Complex_expression::export_complex(exp, this->val_);
2625 // A trailing space lets us reliably identify the end of the number.
2626 exp->write_c_string(" ");
2629 // Dump a complex expression to the dump file.
2631 void
2632 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2634 Complex_expression::export_complex(ast_dump_context, this->val_);
2637 // Make a complex expression.
2639 Expression*
2640 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2642 return new Complex_expression(val, type, location);
2645 // Find a named object in an expression.
2647 class Find_named_object : public Traverse
2649 public:
2650 Find_named_object(Named_object* no)
2651 : Traverse(traverse_expressions),
2652 no_(no), found_(false)
2655 // Whether we found the object.
2656 bool
2657 found() const
2658 { return this->found_; }
2660 protected:
2662 expression(Expression**);
2664 private:
2665 // The object we are looking for.
2666 Named_object* no_;
2667 // Whether we found it.
2668 bool found_;
2671 // A reference to a const in an expression.
2673 class Const_expression : public Expression
2675 public:
2676 Const_expression(Named_object* constant, Location location)
2677 : Expression(EXPRESSION_CONST_REFERENCE, location),
2678 constant_(constant), type_(NULL), seen_(false)
2681 Named_object*
2682 named_object()
2683 { return this->constant_; }
2685 // Check that the initializer does not refer to the constant itself.
2686 void
2687 check_for_init_loop();
2689 protected:
2691 do_traverse(Traverse*);
2693 Expression*
2694 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2696 bool
2697 do_is_constant() const
2698 { return true; }
2700 bool
2701 do_is_static_initializer() const
2702 { return true; }
2704 bool
2705 do_numeric_constant_value(Numeric_constant* nc) const;
2707 bool
2708 do_string_constant_value(std::string* val) const;
2710 Type*
2711 do_type();
2713 // The type of a const is set by the declaration, not the use.
2714 void
2715 do_determine_type(const Type_context*);
2717 void
2718 do_check_types(Gogo*);
2720 Expression*
2721 do_copy()
2722 { return this; }
2724 Bexpression*
2725 do_get_backend(Translate_context* context);
2727 // When exporting a reference to a const as part of a const
2728 // expression, we export the value. We ignore the fact that it has
2729 // a name.
2730 void
2731 do_export(Export* exp) const
2732 { this->constant_->const_value()->expr()->export_expression(exp); }
2734 void
2735 do_dump_expression(Ast_dump_context*) const;
2737 private:
2738 // The constant.
2739 Named_object* constant_;
2740 // The type of this reference. This is used if the constant has an
2741 // abstract type.
2742 Type* type_;
2743 // Used to prevent infinite recursion when a constant incorrectly
2744 // refers to itself.
2745 mutable bool seen_;
2748 // Traversal.
2751 Const_expression::do_traverse(Traverse* traverse)
2753 if (this->type_ != NULL)
2754 return Type::traverse(this->type_, traverse);
2755 return TRAVERSE_CONTINUE;
2758 // Lower a constant expression. This is where we convert the
2759 // predeclared constant iota into an integer value.
2761 Expression*
2762 Const_expression::do_lower(Gogo* gogo, Named_object*,
2763 Statement_inserter*, int iota_value)
2765 if (this->constant_->const_value()->expr()->classification()
2766 == EXPRESSION_IOTA)
2768 if (iota_value == -1)
2770 go_error_at(this->location(),
2771 "iota is only defined in const declarations");
2772 iota_value = 0;
2774 return Expression::make_integer_ul(iota_value, NULL, this->location());
2777 // Make sure that the constant itself has been lowered.
2778 gogo->lower_constant(this->constant_);
2780 return this;
2783 // Return a numeric constant value.
2785 bool
2786 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2788 if (this->seen_)
2789 return false;
2791 Expression* e = this->constant_->const_value()->expr();
2793 this->seen_ = true;
2795 bool r = e->numeric_constant_value(nc);
2797 this->seen_ = false;
2799 Type* ctype;
2800 if (this->type_ != NULL)
2801 ctype = this->type_;
2802 else
2803 ctype = this->constant_->const_value()->type();
2804 if (r && ctype != NULL)
2806 if (!nc->set_type(ctype, false, this->location()))
2807 return false;
2810 return r;
2813 bool
2814 Const_expression::do_string_constant_value(std::string* val) const
2816 if (this->seen_)
2817 return false;
2819 Expression* e = this->constant_->const_value()->expr();
2821 this->seen_ = true;
2822 bool ok = e->string_constant_value(val);
2823 this->seen_ = false;
2825 return ok;
2828 // Return the type of the const reference.
2830 Type*
2831 Const_expression::do_type()
2833 if (this->type_ != NULL)
2834 return this->type_;
2836 Named_constant* nc = this->constant_->const_value();
2838 if (this->seen_ || nc->lowering())
2840 this->report_error(_("constant refers to itself"));
2841 this->type_ = Type::make_error_type();
2842 return this->type_;
2845 this->seen_ = true;
2847 Type* ret = nc->type();
2849 if (ret != NULL)
2851 this->seen_ = false;
2852 return ret;
2855 // During parsing, a named constant may have a NULL type, but we
2856 // must not return a NULL type here.
2857 ret = nc->expr()->type();
2859 this->seen_ = false;
2861 return ret;
2864 // Set the type of the const reference.
2866 void
2867 Const_expression::do_determine_type(const Type_context* context)
2869 Type* ctype = this->constant_->const_value()->type();
2870 Type* cetype = (ctype != NULL
2871 ? ctype
2872 : this->constant_->const_value()->expr()->type());
2873 if (ctype != NULL && !ctype->is_abstract())
2875 else if (context->type != NULL
2876 && context->type->is_numeric_type()
2877 && cetype->is_numeric_type())
2878 this->type_ = context->type;
2879 else if (context->type != NULL
2880 && context->type->is_string_type()
2881 && cetype->is_string_type())
2882 this->type_ = context->type;
2883 else if (context->type != NULL
2884 && context->type->is_boolean_type()
2885 && cetype->is_boolean_type())
2886 this->type_ = context->type;
2887 else if (!context->may_be_abstract)
2889 if (cetype->is_abstract())
2890 cetype = cetype->make_non_abstract_type();
2891 this->type_ = cetype;
2895 // Check for a loop in which the initializer of a constant refers to
2896 // the constant itself.
2898 void
2899 Const_expression::check_for_init_loop()
2901 if (this->type_ != NULL && this->type_->is_error())
2902 return;
2904 if (this->seen_)
2906 this->report_error(_("constant refers to itself"));
2907 this->type_ = Type::make_error_type();
2908 return;
2911 Expression* init = this->constant_->const_value()->expr();
2912 Find_named_object find_named_object(this->constant_);
2914 this->seen_ = true;
2915 Expression::traverse(&init, &find_named_object);
2916 this->seen_ = false;
2918 if (find_named_object.found())
2920 if (this->type_ == NULL || !this->type_->is_error())
2922 this->report_error(_("constant refers to itself"));
2923 this->type_ = Type::make_error_type();
2925 return;
2929 // Check types of a const reference.
2931 void
2932 Const_expression::do_check_types(Gogo*)
2934 if (this->type_ != NULL && this->type_->is_error())
2935 return;
2937 this->check_for_init_loop();
2939 // Check that numeric constant fits in type.
2940 if (this->type_ != NULL && this->type_->is_numeric_type())
2942 Numeric_constant nc;
2943 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2945 if (!nc.set_type(this->type_, true, this->location()))
2946 this->set_is_error();
2951 // Return the backend representation for a const reference.
2953 Bexpression*
2954 Const_expression::do_get_backend(Translate_context* context)
2956 if (this->is_error_expression()
2957 || (this->type_ != NULL && this->type_->is_error()))
2959 go_assert(saw_errors());
2960 return context->backend()->error_expression();
2963 // If the type has been set for this expression, but the underlying
2964 // object is an abstract int or float, we try to get the abstract
2965 // value. Otherwise we may lose something in the conversion.
2966 Expression* expr = this->constant_->const_value()->expr();
2967 if (this->type_ != NULL
2968 && this->type_->is_numeric_type()
2969 && (this->constant_->const_value()->type() == NULL
2970 || this->constant_->const_value()->type()->is_abstract()))
2972 Numeric_constant nc;
2973 if (expr->numeric_constant_value(&nc)
2974 && nc.set_type(this->type_, false, this->location()))
2976 Expression* e = nc.expression(this->location());
2977 return e->get_backend(context);
2981 if (this->type_ != NULL)
2982 expr = Expression::make_cast(this->type_, expr, this->location());
2983 return expr->get_backend(context);
2986 // Dump ast representation for constant expression.
2988 void
2989 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2991 ast_dump_context->ostream() << this->constant_->name();
2994 // Make a reference to a constant in an expression.
2996 Expression*
2997 Expression::make_const_reference(Named_object* constant,
2998 Location location)
3000 return new Const_expression(constant, location);
3003 // Find a named object in an expression.
3006 Find_named_object::expression(Expression** pexpr)
3008 switch ((*pexpr)->classification())
3010 case Expression::EXPRESSION_CONST_REFERENCE:
3012 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3013 if (ce->named_object() == this->no_)
3014 break;
3016 // We need to check a constant initializer explicitly, as
3017 // loops here will not be caught by the loop checking for
3018 // variable initializers.
3019 ce->check_for_init_loop();
3021 return TRAVERSE_CONTINUE;
3024 case Expression::EXPRESSION_VAR_REFERENCE:
3025 if ((*pexpr)->var_expression()->named_object() == this->no_)
3026 break;
3027 return TRAVERSE_CONTINUE;
3028 case Expression::EXPRESSION_FUNC_REFERENCE:
3029 if ((*pexpr)->func_expression()->named_object() == this->no_)
3030 break;
3031 return TRAVERSE_CONTINUE;
3032 default:
3033 return TRAVERSE_CONTINUE;
3035 this->found_ = true;
3036 return TRAVERSE_EXIT;
3039 // The nil value.
3041 class Nil_expression : public Expression
3043 public:
3044 Nil_expression(Location location)
3045 : Expression(EXPRESSION_NIL, location)
3048 static Expression*
3049 do_import(Import*);
3051 protected:
3052 bool
3053 do_is_constant() const
3054 { return true; }
3056 bool
3057 do_is_static_initializer() const
3058 { return true; }
3060 Type*
3061 do_type()
3062 { return Type::make_nil_type(); }
3064 void
3065 do_determine_type(const Type_context*)
3068 Expression*
3069 do_copy()
3070 { return this; }
3072 Bexpression*
3073 do_get_backend(Translate_context* context)
3074 { return context->backend()->nil_pointer_expression(); }
3076 void
3077 do_export(Export* exp) const
3078 { exp->write_c_string("nil"); }
3080 void
3081 do_dump_expression(Ast_dump_context* ast_dump_context) const
3082 { ast_dump_context->ostream() << "nil"; }
3085 // Import a nil expression.
3087 Expression*
3088 Nil_expression::do_import(Import* imp)
3090 imp->require_c_string("nil");
3091 return Expression::make_nil(imp->location());
3094 // Make a nil expression.
3096 Expression*
3097 Expression::make_nil(Location location)
3099 return new Nil_expression(location);
3102 // The value of the predeclared constant iota. This is little more
3103 // than a marker. This will be lowered to an integer in
3104 // Const_expression::do_lower, which is where we know the value that
3105 // it should have.
3107 class Iota_expression : public Parser_expression
3109 public:
3110 Iota_expression(Location location)
3111 : Parser_expression(EXPRESSION_IOTA, location)
3114 protected:
3115 Expression*
3116 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3117 { go_unreachable(); }
3119 // There should only ever be one of these.
3120 Expression*
3121 do_copy()
3122 { go_unreachable(); }
3124 void
3125 do_dump_expression(Ast_dump_context* ast_dump_context) const
3126 { ast_dump_context->ostream() << "iota"; }
3129 // Make an iota expression. This is only called for one case: the
3130 // value of the predeclared constant iota.
3132 Expression*
3133 Expression::make_iota()
3135 static Iota_expression iota_expression(Linemap::unknown_location());
3136 return &iota_expression;
3139 // Class Type_conversion_expression.
3141 // Traversal.
3144 Type_conversion_expression::do_traverse(Traverse* traverse)
3146 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3147 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3148 return TRAVERSE_EXIT;
3149 return TRAVERSE_CONTINUE;
3152 // Convert to a constant at lowering time.
3154 Expression*
3155 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3156 Statement_inserter*, int)
3158 Type* type = this->type_;
3159 Expression* val = this->expr_;
3160 Location location = this->location();
3162 if (type->is_numeric_type())
3164 Numeric_constant nc;
3165 if (val->numeric_constant_value(&nc))
3167 if (!nc.set_type(type, true, location))
3168 return Expression::make_error(location);
3169 return nc.expression(location);
3173 // According to the language specification on string conversions
3174 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3175 // When converting an integer into a string, the string will be a UTF-8
3176 // representation of the integer and integers "outside the range of valid
3177 // Unicode code points are converted to '\uFFFD'."
3178 if (type->is_string_type())
3180 Numeric_constant nc;
3181 if (val->numeric_constant_value(&nc) && nc.is_int())
3183 // An integer value doesn't fit in the Unicode code point range if it
3184 // overflows the Go "int" type or is negative.
3185 unsigned long ul;
3186 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3187 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3188 return Expression::make_string("\ufffd", location);
3192 if (type->is_slice_type())
3194 Type* element_type = type->array_type()->element_type()->forwarded();
3195 bool is_byte = (element_type->integer_type() != NULL
3196 && element_type->integer_type()->is_byte());
3197 bool is_rune = (element_type->integer_type() != NULL
3198 && element_type->integer_type()->is_rune());
3199 if (is_byte || is_rune)
3201 std::string s;
3202 if (val->string_constant_value(&s))
3204 Expression_list* vals = new Expression_list();
3205 if (is_byte)
3207 for (std::string::const_iterator p = s.begin();
3208 p != s.end();
3209 p++)
3211 unsigned char c = static_cast<unsigned char>(*p);
3212 vals->push_back(Expression::make_integer_ul(c,
3213 element_type,
3214 location));
3217 else
3219 const char *p = s.data();
3220 const char *pend = s.data() + s.length();
3221 while (p < pend)
3223 unsigned int c;
3224 int adv = Lex::fetch_char(p, &c);
3225 if (adv == 0)
3227 go_warning_at(this->location(), 0,
3228 "invalid UTF-8 encoding");
3229 adv = 1;
3231 p += adv;
3232 vals->push_back(Expression::make_integer_ul(c,
3233 element_type,
3234 location));
3238 return Expression::make_slice_composite_literal(type, vals,
3239 location);
3244 return this;
3247 // Flatten a type conversion by using a temporary variable for the slice
3248 // in slice to string conversions.
3250 Expression*
3251 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3252 Statement_inserter* inserter)
3254 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3256 go_assert(saw_errors());
3257 return Expression::make_error(this->location());
3260 if (((this->type()->is_string_type()
3261 && this->expr_->type()->is_slice_type())
3262 || this->expr_->type()->interface_type() != NULL)
3263 && !this->expr_->is_variable())
3265 Temporary_statement* temp =
3266 Statement::make_temporary(NULL, this->expr_, this->location());
3267 inserter->insert(temp);
3268 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3270 return this;
3273 // Return whether a type conversion is a constant.
3275 bool
3276 Type_conversion_expression::do_is_constant() const
3278 if (!this->expr_->is_constant())
3279 return false;
3281 // A conversion to a type that may not be used as a constant is not
3282 // a constant. For example, []byte(nil).
3283 Type* type = this->type_;
3284 if (type->integer_type() == NULL
3285 && type->float_type() == NULL
3286 && type->complex_type() == NULL
3287 && !type->is_boolean_type()
3288 && !type->is_string_type())
3289 return false;
3291 return true;
3294 // Return whether a type conversion can be used in a constant
3295 // initializer.
3297 bool
3298 Type_conversion_expression::do_is_static_initializer() const
3300 Type* type = this->type_;
3301 Type* expr_type = this->expr_->type();
3303 if (type->interface_type() != NULL
3304 || expr_type->interface_type() != NULL)
3305 return false;
3307 if (!this->expr_->is_static_initializer())
3308 return false;
3310 if (Type::are_identical(type, expr_type, false, NULL))
3311 return true;
3313 if (type->is_string_type() && expr_type->is_string_type())
3314 return true;
3316 if ((type->is_numeric_type()
3317 || type->is_boolean_type()
3318 || type->points_to() != NULL)
3319 && (expr_type->is_numeric_type()
3320 || expr_type->is_boolean_type()
3321 || expr_type->points_to() != NULL))
3322 return true;
3324 return false;
3327 // Return the constant numeric value if there is one.
3329 bool
3330 Type_conversion_expression::do_numeric_constant_value(
3331 Numeric_constant* nc) const
3333 if (!this->type_->is_numeric_type())
3334 return false;
3335 if (!this->expr_->numeric_constant_value(nc))
3336 return false;
3337 return nc->set_type(this->type_, false, this->location());
3340 // Return the constant string value if there is one.
3342 bool
3343 Type_conversion_expression::do_string_constant_value(std::string* val) const
3345 if (this->type_->is_string_type()
3346 && this->expr_->type()->integer_type() != NULL)
3348 Numeric_constant nc;
3349 if (this->expr_->numeric_constant_value(&nc))
3351 unsigned long ival;
3352 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3354 val->clear();
3355 Lex::append_char(ival, true, val, this->location());
3356 return true;
3361 // FIXME: Could handle conversion from const []int here.
3363 return false;
3366 // Determine the resulting type of the conversion.
3368 void
3369 Type_conversion_expression::do_determine_type(const Type_context*)
3371 Type_context subcontext(this->type_, false);
3372 this->expr_->determine_type(&subcontext);
3375 // Check that types are convertible.
3377 void
3378 Type_conversion_expression::do_check_types(Gogo*)
3380 Type* type = this->type_;
3381 Type* expr_type = this->expr_->type();
3382 std::string reason;
3384 if (type->is_error() || expr_type->is_error())
3386 this->set_is_error();
3387 return;
3390 if (this->may_convert_function_types_
3391 && type->function_type() != NULL
3392 && expr_type->function_type() != NULL)
3393 return;
3395 if (Type::are_convertible(type, expr_type, &reason))
3396 return;
3398 go_error_at(this->location(), "%s", reason.c_str());
3399 this->set_is_error();
3402 // Get the backend representation for a type conversion.
3404 Bexpression*
3405 Type_conversion_expression::do_get_backend(Translate_context* context)
3407 Type* type = this->type_;
3408 Type* expr_type = this->expr_->type();
3410 Gogo* gogo = context->gogo();
3411 Btype* btype = type->get_backend(gogo);
3412 Location loc = this->location();
3414 if (Type::are_identical(type, expr_type, false, NULL))
3416 Bexpression* bexpr = this->expr_->get_backend(context);
3417 return gogo->backend()->convert_expression(btype, bexpr, loc);
3419 else if (type->interface_type() != NULL
3420 || expr_type->interface_type() != NULL)
3422 Expression* conversion =
3423 Expression::convert_for_assignment(gogo, type, this->expr_,
3424 this->location());
3425 return conversion->get_backend(context);
3427 else if (type->is_string_type()
3428 && expr_type->integer_type() != NULL)
3430 mpz_t intval;
3431 Numeric_constant nc;
3432 if (this->expr_->numeric_constant_value(&nc)
3433 && nc.to_int(&intval)
3434 && mpz_fits_ushort_p(intval))
3436 std::string s;
3437 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3438 mpz_clear(intval);
3439 Expression* se = Expression::make_string(s, loc);
3440 return se->get_backend(context);
3443 Expression* i2s_expr =
3444 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3445 Expression::make_nil(loc), this->expr_);
3446 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3448 else if (type->is_string_type() && expr_type->is_slice_type())
3450 Array_type* a = expr_type->array_type();
3451 Type* e = a->element_type()->forwarded();
3452 go_assert(e->integer_type() != NULL);
3453 go_assert(this->expr_->is_variable());
3455 Runtime::Function code;
3456 if (e->integer_type()->is_byte())
3457 code = Runtime::SLICEBYTETOSTRING;
3458 else
3460 go_assert(e->integer_type()->is_rune());
3461 code = Runtime::SLICERUNETOSTRING;
3463 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3464 this->expr_)->get_backend(context);
3466 else if (type->is_slice_type() && expr_type->is_string_type())
3468 Type* e = type->array_type()->element_type()->forwarded();
3469 go_assert(e->integer_type() != NULL);
3471 Runtime::Function code;
3472 if (e->integer_type()->is_byte())
3473 code = Runtime::STRINGTOSLICEBYTE;
3474 else
3476 go_assert(e->integer_type()->is_rune());
3477 code = Runtime::STRINGTOSLICERUNE;
3479 Expression* s2a = Runtime::make_call(code, loc, 2,
3480 Expression::make_nil(loc),
3481 this->expr_);
3482 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3484 else if (type->is_numeric_type())
3486 go_assert(Type::are_convertible(type, expr_type, NULL));
3487 Bexpression* bexpr = this->expr_->get_backend(context);
3488 return gogo->backend()->convert_expression(btype, bexpr, loc);
3490 else if ((type->is_unsafe_pointer_type()
3491 && (expr_type->points_to() != NULL
3492 || expr_type->integer_type()))
3493 || (expr_type->is_unsafe_pointer_type()
3494 && type->points_to() != NULL)
3495 || (this->may_convert_function_types_
3496 && type->function_type() != NULL
3497 && expr_type->function_type() != NULL))
3499 Bexpression* bexpr = this->expr_->get_backend(context);
3500 return gogo->backend()->convert_expression(btype, bexpr, loc);
3502 else
3504 Expression* conversion =
3505 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3506 return conversion->get_backend(context);
3510 // Output a type conversion in a constant expression.
3512 void
3513 Type_conversion_expression::do_export(Export* exp) const
3515 exp->write_c_string("convert(");
3516 exp->write_type(this->type_);
3517 exp->write_c_string(", ");
3518 this->expr_->export_expression(exp);
3519 exp->write_c_string(")");
3522 // Import a type conversion or a struct construction.
3524 Expression*
3525 Type_conversion_expression::do_import(Import* imp)
3527 imp->require_c_string("convert(");
3528 Type* type = imp->read_type();
3529 imp->require_c_string(", ");
3530 Expression* val = Expression::import_expression(imp);
3531 imp->require_c_string(")");
3532 return Expression::make_cast(type, val, imp->location());
3535 // Dump ast representation for a type conversion expression.
3537 void
3538 Type_conversion_expression::do_dump_expression(
3539 Ast_dump_context* ast_dump_context) const
3541 ast_dump_context->dump_type(this->type_);
3542 ast_dump_context->ostream() << "(";
3543 ast_dump_context->dump_expression(this->expr_);
3544 ast_dump_context->ostream() << ") ";
3547 // Make a type cast expression.
3549 Expression*
3550 Expression::make_cast(Type* type, Expression* val, Location location)
3552 if (type->is_error_type() || val->is_error_expression())
3553 return Expression::make_error(location);
3554 return new Type_conversion_expression(type, val, location);
3557 // Class Unsafe_type_conversion_expression.
3559 // Traversal.
3562 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3564 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3565 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3566 return TRAVERSE_EXIT;
3567 return TRAVERSE_CONTINUE;
3570 // Return whether an unsafe type conversion can be used as a constant
3571 // initializer.
3573 bool
3574 Unsafe_type_conversion_expression::do_is_static_initializer() const
3576 Type* type = this->type_;
3577 Type* expr_type = this->expr_->type();
3579 if (type->interface_type() != NULL
3580 || expr_type->interface_type() != NULL)
3581 return false;
3583 if (!this->expr_->is_static_initializer())
3584 return false;
3586 if (Type::are_convertible(type, expr_type, NULL))
3587 return true;
3589 if (type->is_string_type() && expr_type->is_string_type())
3590 return true;
3592 if ((type->is_numeric_type()
3593 || type->is_boolean_type()
3594 || type->points_to() != NULL)
3595 && (expr_type->is_numeric_type()
3596 || expr_type->is_boolean_type()
3597 || expr_type->points_to() != NULL))
3598 return true;
3600 return false;
3603 // Convert to backend representation.
3605 Bexpression*
3606 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3608 // We are only called for a limited number of cases.
3610 Type* t = this->type_;
3611 Type* et = this->expr_->type();
3613 if (t->is_error_type()
3614 || this->expr_->is_error_expression()
3615 || et->is_error_type())
3617 go_assert(saw_errors());
3618 return context->backend()->error_expression();
3621 if (t->array_type() != NULL)
3622 go_assert(et->array_type() != NULL
3623 && t->is_slice_type() == et->is_slice_type());
3624 else if (t->struct_type() != NULL)
3626 if (t->named_type() != NULL
3627 && et->named_type() != NULL
3628 && !Type::are_convertible(t, et, NULL))
3630 go_assert(saw_errors());
3631 return context->backend()->error_expression();
3634 go_assert(et->struct_type() != NULL
3635 && Type::are_convertible(t, et, NULL));
3637 else if (t->map_type() != NULL)
3638 go_assert(et->map_type() != NULL);
3639 else if (t->channel_type() != NULL)
3640 go_assert(et->channel_type() != NULL);
3641 else if (t->points_to() != NULL)
3642 go_assert(et->points_to() != NULL
3643 || et->channel_type() != NULL
3644 || et->map_type() != NULL
3645 || et->function_type() != NULL
3646 || et->integer_type() != NULL
3647 || et->is_nil_type());
3648 else if (et->is_unsafe_pointer_type())
3649 go_assert(t->points_to() != NULL);
3650 else if (t->interface_type() != NULL)
3652 bool empty_iface = t->interface_type()->is_empty();
3653 go_assert(et->interface_type() != NULL
3654 && et->interface_type()->is_empty() == empty_iface);
3656 else if (t->integer_type() != NULL)
3657 go_assert(et->is_boolean_type()
3658 || et->integer_type() != NULL
3659 || et->function_type() != NULL
3660 || et->points_to() != NULL
3661 || et->map_type() != NULL
3662 || et->channel_type() != NULL
3663 || et->is_nil_type());
3664 else if (t->function_type() != NULL)
3665 go_assert(et->points_to() != NULL);
3666 else
3667 go_unreachable();
3669 Gogo* gogo = context->gogo();
3670 Btype* btype = t->get_backend(gogo);
3671 Bexpression* bexpr = this->expr_->get_backend(context);
3672 Location loc = this->location();
3673 return gogo->backend()->convert_expression(btype, bexpr, loc);
3676 // Dump ast representation for an unsafe type conversion expression.
3678 void
3679 Unsafe_type_conversion_expression::do_dump_expression(
3680 Ast_dump_context* ast_dump_context) const
3682 ast_dump_context->dump_type(this->type_);
3683 ast_dump_context->ostream() << "(";
3684 ast_dump_context->dump_expression(this->expr_);
3685 ast_dump_context->ostream() << ") ";
3688 // Make an unsafe type conversion expression.
3690 Expression*
3691 Expression::make_unsafe_cast(Type* type, Expression* expr,
3692 Location location)
3694 return new Unsafe_type_conversion_expression(type, expr, location);
3697 // Class Unary_expression.
3699 // Call the address_taken method of the operand if needed. This is
3700 // called after escape analysis but before inserting write barriers.
3702 void
3703 Unary_expression::check_operand_address_taken(Gogo* gogo)
3705 if (this->op_ != OPERATOR_AND)
3706 return;
3708 // If this->escapes_ is false at this point, then it was set to
3709 // false by an explicit call to set_does_not_escape, and the value
3710 // does not escape. If this->escapes_ is true, we may be able to
3711 // set it to false if taking the address of a variable that does not
3712 // escape.
3713 Node* n = Node::make_node(this);
3714 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3715 this->escapes_ = false;
3717 // When compiling the runtime, the address operator does not cause
3718 // local variables to escape. When escape analysis becomes the
3719 // default, this should be changed to make it an error if we have an
3720 // address operator that escapes.
3721 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3722 this->escapes_ = false;
3724 Named_object* var = NULL;
3725 if (this->expr_->var_expression() != NULL)
3726 var = this->expr_->var_expression()->named_object();
3727 else if (this->expr_->enclosed_var_expression() != NULL)
3728 var = this->expr_->enclosed_var_expression()->variable();
3730 if (this->escapes_ && var != NULL)
3732 if (var->is_variable())
3733 this->escapes_ = var->var_value()->escapes();
3734 if (var->is_result_variable())
3735 this->escapes_ = var->result_var_value()->escapes();
3738 this->expr_->address_taken(this->escapes_);
3741 // If we are taking the address of a composite literal, and the
3742 // contents are not constant, then we want to make a heap expression
3743 // instead.
3745 Expression*
3746 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3748 Location loc = this->location();
3749 Operator op = this->op_;
3750 Expression* expr = this->expr_;
3752 if (op == OPERATOR_MULT && expr->is_type_expression())
3753 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3755 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3756 // moving x to the heap. FIXME: Is it worth doing a real escape
3757 // analysis here? This case is found in math/unsafe.go and is
3758 // therefore worth special casing.
3759 if (op == OPERATOR_MULT)
3761 Expression* e = expr;
3762 while (e->classification() == EXPRESSION_CONVERSION)
3764 Type_conversion_expression* te
3765 = static_cast<Type_conversion_expression*>(e);
3766 e = te->expr();
3769 if (e->classification() == EXPRESSION_UNARY)
3771 Unary_expression* ue = static_cast<Unary_expression*>(e);
3772 if (ue->op_ == OPERATOR_AND)
3774 if (e == expr)
3776 // *&x == x.
3777 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3779 go_error_at(ue->location(),
3780 "invalid operand for unary %<&%>");
3781 this->set_is_error();
3783 return ue->expr_;
3785 ue->set_does_not_escape();
3790 // Catching an invalid indirection of unsafe.Pointer here avoid
3791 // having to deal with TYPE_VOID in other places.
3792 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3794 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3795 return Expression::make_error(this->location());
3798 // Check for an invalid pointer dereference. We need to do this
3799 // here because Unary_expression::do_type will return an error type
3800 // in this case. That can cause code to appear erroneous, and
3801 // therefore disappear at lowering time, without any error message.
3802 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3804 this->report_error(_("expected pointer"));
3805 return Expression::make_error(this->location());
3808 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3810 Numeric_constant nc;
3811 if (expr->numeric_constant_value(&nc))
3813 Numeric_constant result;
3814 bool issued_error;
3815 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3816 &issued_error))
3817 return result.expression(loc);
3818 else if (issued_error)
3819 return Expression::make_error(this->location());
3823 return this;
3826 // Flatten expression if a nil check must be performed and create temporary
3827 // variables if necessary.
3829 Expression*
3830 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3831 Statement_inserter* inserter)
3833 if (this->is_error_expression()
3834 || this->expr_->is_error_expression()
3835 || this->expr_->type()->is_error_type())
3837 go_assert(saw_errors());
3838 return Expression::make_error(this->location());
3841 Location location = this->location();
3842 if (this->op_ == OPERATOR_MULT
3843 && !this->expr_->is_variable())
3845 go_assert(this->expr_->type()->points_to() != NULL);
3846 switch (this->requires_nil_check(gogo))
3848 case NIL_CHECK_ERROR_ENCOUNTERED:
3850 go_assert(saw_errors());
3851 return Expression::make_error(this->location());
3853 case NIL_CHECK_NOT_NEEDED:
3854 break;
3855 case NIL_CHECK_NEEDED:
3856 this->create_temp_ = true;
3857 break;
3858 case NIL_CHECK_DEFAULT:
3859 go_unreachable();
3863 if (this->create_temp_ && !this->expr_->is_variable())
3865 Temporary_statement* temp =
3866 Statement::make_temporary(NULL, this->expr_, location);
3867 inserter->insert(temp);
3868 this->expr_ = Expression::make_temporary_reference(temp, location);
3871 return this;
3874 // Return whether a unary expression is a constant.
3876 bool
3877 Unary_expression::do_is_constant() const
3879 if (this->op_ == OPERATOR_MULT)
3881 // Indirecting through a pointer is only constant if the object
3882 // to which the expression points is constant, but we currently
3883 // have no way to determine that.
3884 return false;
3886 else if (this->op_ == OPERATOR_AND)
3888 // Taking the address of a variable is constant if it is a
3889 // global variable, not constant otherwise. In other cases taking the
3890 // address is probably not a constant.
3891 Var_expression* ve = this->expr_->var_expression();
3892 if (ve != NULL)
3894 Named_object* no = ve->named_object();
3895 return no->is_variable() && no->var_value()->is_global();
3897 return false;
3899 else
3900 return this->expr_->is_constant();
3903 // Return whether a unary expression can be used as a constant
3904 // initializer.
3906 bool
3907 Unary_expression::do_is_static_initializer() const
3909 if (this->op_ == OPERATOR_MULT)
3910 return false;
3911 else if (this->op_ == OPERATOR_AND)
3912 return Unary_expression::base_is_static_initializer(this->expr_);
3913 else
3914 return this->expr_->is_static_initializer();
3917 // Return whether the address of EXPR can be used as a static
3918 // initializer.
3920 bool
3921 Unary_expression::base_is_static_initializer(Expression* expr)
3923 // The address of a field reference can be a static initializer if
3924 // the base can be a static initializer.
3925 Field_reference_expression* fre = expr->field_reference_expression();
3926 if (fre != NULL)
3927 return Unary_expression::base_is_static_initializer(fre->expr());
3929 // The address of an index expression can be a static initializer if
3930 // the base can be a static initializer and the index is constant.
3931 Array_index_expression* aind = expr->array_index_expression();
3932 if (aind != NULL)
3933 return (aind->end() == NULL
3934 && aind->start()->is_constant()
3935 && Unary_expression::base_is_static_initializer(aind->array()));
3937 // The address of a global variable can be a static initializer.
3938 Var_expression* ve = expr->var_expression();
3939 if (ve != NULL)
3941 Named_object* no = ve->named_object();
3942 return no->is_variable() && no->var_value()->is_global();
3945 // The address of a composite literal can be used as a static
3946 // initializer if the composite literal is itself usable as a
3947 // static initializer.
3948 if (expr->is_composite_literal() && expr->is_static_initializer())
3949 return true;
3951 // The address of a string constant can be used as a static
3952 // initializer. This can not be written in Go itself but this is
3953 // used when building a type descriptor.
3954 if (expr->string_expression() != NULL)
3955 return true;
3957 return false;
3960 // Return whether this dereference expression requires an explicit nil
3961 // check. If we are dereferencing the pointer to a large struct
3962 // (greater than the specified size threshold), we need to check for
3963 // nil. We don't bother to check for small structs because we expect
3964 // the system to crash on a nil pointer dereference. However, if we
3965 // know the address of this expression is being taken, we must always
3966 // check for nil.
3967 Unary_expression::Nil_check_classification
3968 Unary_expression::requires_nil_check(Gogo* gogo)
3970 go_assert(this->op_ == OPERATOR_MULT);
3971 go_assert(this->expr_->type()->points_to() != NULL);
3973 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
3974 return NIL_CHECK_NEEDED;
3975 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
3976 return NIL_CHECK_NOT_NEEDED;
3978 Type* ptype = this->expr_->type()->points_to();
3979 int64_t type_size = -1;
3980 if (!ptype->is_void_type())
3982 bool ok = ptype->backend_type_size(gogo, &type_size);
3983 if (!ok)
3984 return NIL_CHECK_ERROR_ENCOUNTERED;
3987 int64_t size_cutoff = gogo->nil_check_size_threshold();
3988 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
3989 this->issue_nil_check_ = NIL_CHECK_NEEDED;
3990 else
3991 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
3992 return this->issue_nil_check_;
3995 // Apply unary opcode OP to UNC, setting NC. Return true if this
3996 // could be done, false if not. On overflow, issues an error and sets
3997 // *ISSUED_ERROR.
3999 bool
4000 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4001 Location location, Numeric_constant* nc,
4002 bool* issued_error)
4004 *issued_error = false;
4005 switch (op)
4007 case OPERATOR_PLUS:
4008 *nc = *unc;
4009 return true;
4011 case OPERATOR_MINUS:
4012 if (unc->is_int() || unc->is_rune())
4013 break;
4014 else if (unc->is_float())
4016 mpfr_t uval;
4017 unc->get_float(&uval);
4018 mpfr_t val;
4019 mpfr_init(val);
4020 mpfr_neg(val, uval, GMP_RNDN);
4021 nc->set_float(unc->type(), val);
4022 mpfr_clear(uval);
4023 mpfr_clear(val);
4024 return true;
4026 else if (unc->is_complex())
4028 mpc_t uval;
4029 unc->get_complex(&uval);
4030 mpc_t val;
4031 mpc_init2(val, mpc_precision);
4032 mpc_neg(val, uval, MPC_RNDNN);
4033 nc->set_complex(unc->type(), val);
4034 mpc_clear(uval);
4035 mpc_clear(val);
4036 return true;
4038 else
4039 go_unreachable();
4041 case OPERATOR_XOR:
4042 break;
4044 case OPERATOR_NOT:
4045 case OPERATOR_AND:
4046 case OPERATOR_MULT:
4047 return false;
4049 default:
4050 go_unreachable();
4053 if (!unc->is_int() && !unc->is_rune())
4054 return false;
4056 mpz_t uval;
4057 if (unc->is_rune())
4058 unc->get_rune(&uval);
4059 else
4060 unc->get_int(&uval);
4061 mpz_t val;
4062 mpz_init(val);
4064 switch (op)
4066 case OPERATOR_MINUS:
4067 mpz_neg(val, uval);
4068 break;
4070 case OPERATOR_NOT:
4071 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4072 break;
4074 case OPERATOR_XOR:
4076 Type* utype = unc->type();
4077 if (utype->integer_type() == NULL
4078 || utype->integer_type()->is_abstract())
4079 mpz_com(val, uval);
4080 else
4082 // The number of HOST_WIDE_INTs that it takes to represent
4083 // UVAL.
4084 size_t count = ((mpz_sizeinbase(uval, 2)
4085 + HOST_BITS_PER_WIDE_INT
4086 - 1)
4087 / HOST_BITS_PER_WIDE_INT);
4089 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4090 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4092 size_t obits = utype->integer_type()->bits();
4094 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4096 mpz_t adj;
4097 mpz_init_set_ui(adj, 1);
4098 mpz_mul_2exp(adj, adj, obits);
4099 mpz_add(uval, uval, adj);
4100 mpz_clear(adj);
4103 size_t ecount;
4104 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4105 go_assert(ecount <= count);
4107 // Trim down to the number of words required by the type.
4108 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4109 / HOST_BITS_PER_WIDE_INT);
4110 go_assert(ocount <= count);
4112 for (size_t i = 0; i < ocount; ++i)
4113 phwi[i] = ~phwi[i];
4115 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4116 if (clearbits != 0)
4117 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4118 >> clearbits);
4120 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4122 if (!utype->integer_type()->is_unsigned()
4123 && mpz_tstbit(val, obits - 1))
4125 mpz_t adj;
4126 mpz_init_set_ui(adj, 1);
4127 mpz_mul_2exp(adj, adj, obits);
4128 mpz_sub(val, val, adj);
4129 mpz_clear(adj);
4132 delete[] phwi;
4135 break;
4137 default:
4138 go_unreachable();
4141 if (unc->is_rune())
4142 nc->set_rune(NULL, val);
4143 else
4144 nc->set_int(NULL, val);
4146 mpz_clear(uval);
4147 mpz_clear(val);
4149 if (!nc->set_type(unc->type(), true, location))
4151 *issued_error = true;
4152 return false;
4154 return true;
4157 // Return the integral constant value of a unary expression, if it has one.
4159 bool
4160 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4162 Numeric_constant unc;
4163 if (!this->expr_->numeric_constant_value(&unc))
4164 return false;
4165 bool issued_error;
4166 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4167 nc, &issued_error);
4170 // Return the type of a unary expression.
4172 Type*
4173 Unary_expression::do_type()
4175 switch (this->op_)
4177 case OPERATOR_PLUS:
4178 case OPERATOR_MINUS:
4179 case OPERATOR_NOT:
4180 case OPERATOR_XOR:
4181 return this->expr_->type();
4183 case OPERATOR_AND:
4184 return Type::make_pointer_type(this->expr_->type());
4186 case OPERATOR_MULT:
4188 Type* subtype = this->expr_->type();
4189 Type* points_to = subtype->points_to();
4190 if (points_to == NULL)
4191 return Type::make_error_type();
4192 return points_to;
4195 default:
4196 go_unreachable();
4200 // Determine abstract types for a unary expression.
4202 void
4203 Unary_expression::do_determine_type(const Type_context* context)
4205 switch (this->op_)
4207 case OPERATOR_PLUS:
4208 case OPERATOR_MINUS:
4209 case OPERATOR_NOT:
4210 case OPERATOR_XOR:
4211 this->expr_->determine_type(context);
4212 break;
4214 case OPERATOR_AND:
4215 // Taking the address of something.
4217 Type* subtype = (context->type == NULL
4218 ? NULL
4219 : context->type->points_to());
4220 Type_context subcontext(subtype, false);
4221 this->expr_->determine_type(&subcontext);
4223 break;
4225 case OPERATOR_MULT:
4226 // Indirecting through a pointer.
4228 Type* subtype = (context->type == NULL
4229 ? NULL
4230 : Type::make_pointer_type(context->type));
4231 Type_context subcontext(subtype, false);
4232 this->expr_->determine_type(&subcontext);
4234 break;
4236 default:
4237 go_unreachable();
4241 // Check types for a unary expression.
4243 void
4244 Unary_expression::do_check_types(Gogo*)
4246 Type* type = this->expr_->type();
4247 if (type->is_error())
4249 this->set_is_error();
4250 return;
4253 switch (this->op_)
4255 case OPERATOR_PLUS:
4256 case OPERATOR_MINUS:
4257 if (type->integer_type() == NULL
4258 && type->float_type() == NULL
4259 && type->complex_type() == NULL)
4260 this->report_error(_("expected numeric type"));
4261 break;
4263 case OPERATOR_NOT:
4264 if (!type->is_boolean_type())
4265 this->report_error(_("expected boolean type"));
4266 break;
4268 case OPERATOR_XOR:
4269 if (type->integer_type() == NULL)
4270 this->report_error(_("expected integer"));
4271 break;
4273 case OPERATOR_AND:
4274 if (!this->expr_->is_addressable())
4276 if (!this->create_temp_)
4278 go_error_at(this->location(), "invalid operand for unary %<&%>");
4279 this->set_is_error();
4282 else
4283 this->expr_->issue_nil_check();
4284 break;
4286 case OPERATOR_MULT:
4287 // Indirecting through a pointer.
4288 if (type->points_to() == NULL)
4289 this->report_error(_("expected pointer"));
4290 if (type->points_to()->is_error())
4291 this->set_is_error();
4292 break;
4294 default:
4295 go_unreachable();
4299 // Get the backend representation for a unary expression.
4301 Bexpression*
4302 Unary_expression::do_get_backend(Translate_context* context)
4304 Gogo* gogo = context->gogo();
4305 Location loc = this->location();
4307 // Taking the address of a set-and-use-temporary expression requires
4308 // setting the temporary and then taking the address.
4309 if (this->op_ == OPERATOR_AND)
4311 Set_and_use_temporary_expression* sut =
4312 this->expr_->set_and_use_temporary_expression();
4313 if (sut != NULL)
4315 Temporary_statement* temp = sut->temporary();
4316 Bvariable* bvar = temp->get_backend_variable(context);
4317 Bexpression* bvar_expr =
4318 gogo->backend()->var_expression(bvar, loc);
4319 Bexpression* bval = sut->expression()->get_backend(context);
4321 Named_object* fn = context->function();
4322 go_assert(fn != NULL);
4323 Bfunction* bfn =
4324 fn->func_value()->get_or_make_decl(gogo, fn);
4325 Bstatement* bassign =
4326 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4327 Bexpression* bvar_addr =
4328 gogo->backend()->address_expression(bvar_expr, loc);
4329 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4333 Bexpression* ret;
4334 Bexpression* bexpr = this->expr_->get_backend(context);
4335 Btype* btype = this->expr_->type()->get_backend(gogo);
4336 switch (this->op_)
4338 case OPERATOR_PLUS:
4339 ret = bexpr;
4340 break;
4342 case OPERATOR_MINUS:
4343 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4344 ret = gogo->backend()->convert_expression(btype, ret, loc);
4345 break;
4347 case OPERATOR_NOT:
4348 case OPERATOR_XOR:
4349 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4350 break;
4352 case OPERATOR_AND:
4353 if (!this->create_temp_)
4355 // We should not see a non-constant constructor here; cases
4356 // where we would see one should have been moved onto the
4357 // heap at parse time. Taking the address of a nonconstant
4358 // constructor will not do what the programmer expects.
4360 go_assert(!this->expr_->is_composite_literal()
4361 || this->expr_->is_static_initializer());
4362 if (this->expr_->classification() == EXPRESSION_UNARY)
4364 Unary_expression* ue =
4365 static_cast<Unary_expression*>(this->expr_);
4366 go_assert(ue->op() != OPERATOR_AND);
4370 if (this->is_gc_root_ || this->is_slice_init_)
4372 std::string var_name;
4373 bool copy_to_heap = false;
4374 if (this->is_gc_root_)
4376 // Build a decl for a GC root variable. GC roots are mutable, so
4377 // they cannot be represented as an immutable_struct in the
4378 // backend.
4379 var_name = gogo->gc_root_name();
4381 else
4383 // Build a decl for a slice value initializer. An immutable slice
4384 // value initializer may have to be copied to the heap if it
4385 // contains pointers in a non-constant context.
4386 var_name = gogo->initializer_name();
4388 Array_type* at = this->expr_->type()->array_type();
4389 go_assert(at != NULL);
4391 // If we are not copying the value to the heap, we will only
4392 // initialize the value once, so we can use this directly
4393 // rather than copying it. In that case we can't make it
4394 // read-only, because the program is permitted to change it.
4395 copy_to_heap = context->function() != NULL;
4397 std::string asm_name(go_selectively_encode_id(var_name));
4398 Bvariable* implicit =
4399 gogo->backend()->implicit_variable(var_name, asm_name,
4400 btype, true, copy_to_heap,
4401 false, 0);
4402 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4403 true, copy_to_heap, false,
4404 bexpr);
4405 bexpr = gogo->backend()->var_expression(implicit, loc);
4407 // If we are not copying a slice initializer to the heap,
4408 // then it can be changed by the program, so if it can
4409 // contain pointers we must register it as a GC root.
4410 if (this->is_slice_init_
4411 && !copy_to_heap
4412 && this->expr_->type()->has_pointer())
4414 Bexpression* root =
4415 gogo->backend()->var_expression(implicit, loc);
4416 root = gogo->backend()->address_expression(root, loc);
4417 Type* type = Type::make_pointer_type(this->expr_->type());
4418 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4421 else if ((this->expr_->is_composite_literal()
4422 || this->expr_->string_expression() != NULL)
4423 && this->expr_->is_static_initializer())
4425 std::string var_name(gogo->initializer_name());
4426 std::string asm_name(go_selectively_encode_id(var_name));
4427 Bvariable* decl =
4428 gogo->backend()->immutable_struct(var_name, asm_name,
4429 true, false, btype, loc);
4430 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4431 false, btype, loc, bexpr);
4432 bexpr = gogo->backend()->var_expression(decl, loc);
4435 go_assert(!this->create_temp_ || this->expr_->is_variable());
4436 ret = gogo->backend()->address_expression(bexpr, loc);
4437 break;
4439 case OPERATOR_MULT:
4441 go_assert(this->expr_->type()->points_to() != NULL);
4443 bool known_valid = false;
4444 Type* ptype = this->expr_->type()->points_to();
4445 Btype* pbtype = ptype->get_backend(gogo);
4446 switch (this->requires_nil_check(gogo))
4448 case NIL_CHECK_NOT_NEEDED:
4449 break;
4450 case NIL_CHECK_ERROR_ENCOUNTERED:
4452 go_assert(saw_errors());
4453 return gogo->backend()->error_expression();
4455 case NIL_CHECK_NEEDED:
4457 go_assert(this->expr_->is_variable());
4459 // If we're nil-checking the result of a set-and-use-temporary
4460 // expression, then pick out the target temp and use that
4461 // for the final result of the conditional.
4462 Bexpression* tbexpr = bexpr;
4463 Bexpression* ubexpr = bexpr;
4464 Set_and_use_temporary_expression* sut =
4465 this->expr_->set_and_use_temporary_expression();
4466 if (sut != NULL) {
4467 Temporary_statement* temp = sut->temporary();
4468 Bvariable* bvar = temp->get_backend_variable(context);
4469 ubexpr = gogo->backend()->var_expression(bvar, loc);
4471 Bexpression* nil =
4472 Expression::make_nil(loc)->get_backend(context);
4473 Bexpression* compare =
4474 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4475 nil, loc);
4476 Bexpression* crash =
4477 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4478 loc)->get_backend(context);
4479 Bfunction* bfn = context->function()->func_value()->get_decl();
4480 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4481 compare,
4482 crash, ubexpr,
4483 loc);
4484 known_valid = true;
4485 break;
4487 case NIL_CHECK_DEFAULT:
4488 go_unreachable();
4490 ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4491 known_valid, loc);
4493 break;
4495 default:
4496 go_unreachable();
4499 return ret;
4502 // Export a unary expression.
4504 void
4505 Unary_expression::do_export(Export* exp) const
4507 switch (this->op_)
4509 case OPERATOR_PLUS:
4510 exp->write_c_string("+ ");
4511 break;
4512 case OPERATOR_MINUS:
4513 exp->write_c_string("- ");
4514 break;
4515 case OPERATOR_NOT:
4516 exp->write_c_string("! ");
4517 break;
4518 case OPERATOR_XOR:
4519 exp->write_c_string("^ ");
4520 break;
4521 case OPERATOR_AND:
4522 case OPERATOR_MULT:
4523 default:
4524 go_unreachable();
4526 this->expr_->export_expression(exp);
4529 // Import a unary expression.
4531 Expression*
4532 Unary_expression::do_import(Import* imp)
4534 Operator op;
4535 switch (imp->get_char())
4537 case '+':
4538 op = OPERATOR_PLUS;
4539 break;
4540 case '-':
4541 op = OPERATOR_MINUS;
4542 break;
4543 case '!':
4544 op = OPERATOR_NOT;
4545 break;
4546 case '^':
4547 op = OPERATOR_XOR;
4548 break;
4549 default:
4550 go_unreachable();
4552 imp->require_c_string(" ");
4553 Expression* expr = Expression::import_expression(imp);
4554 return Expression::make_unary(op, expr, imp->location());
4557 // Dump ast representation of an unary expression.
4559 void
4560 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4562 ast_dump_context->dump_operator(this->op_);
4563 ast_dump_context->ostream() << "(";
4564 ast_dump_context->dump_expression(this->expr_);
4565 ast_dump_context->ostream() << ") ";
4568 // Make a unary expression.
4570 Expression*
4571 Expression::make_unary(Operator op, Expression* expr, Location location)
4573 return new Unary_expression(op, expr, location);
4576 Expression*
4577 Expression::make_dereference(Expression* ptr,
4578 Nil_check_classification docheck,
4579 Location location)
4581 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4582 if (docheck == NIL_CHECK_NEEDED)
4583 deref->unary_expression()->set_requires_nil_check(true);
4584 else if (docheck == NIL_CHECK_NOT_NEEDED)
4585 deref->unary_expression()->set_requires_nil_check(false);
4586 return deref;
4589 // If this is an indirection through a pointer, return the expression
4590 // being pointed through. Otherwise return this.
4592 Expression*
4593 Expression::deref()
4595 if (this->classification_ == EXPRESSION_UNARY)
4597 Unary_expression* ue = static_cast<Unary_expression*>(this);
4598 if (ue->op() == OPERATOR_MULT)
4599 return ue->operand();
4601 return this;
4604 // Class Binary_expression.
4606 // Traversal.
4609 Binary_expression::do_traverse(Traverse* traverse)
4611 int t = Expression::traverse(&this->left_, traverse);
4612 if (t == TRAVERSE_EXIT)
4613 return TRAVERSE_EXIT;
4614 return Expression::traverse(&this->right_, traverse);
4617 // Return whether this expression may be used as a static initializer.
4619 bool
4620 Binary_expression::do_is_static_initializer() const
4622 if (!this->left_->is_static_initializer()
4623 || !this->right_->is_static_initializer())
4624 return false;
4626 // Addresses can be static initializers, but we can't implement
4627 // arbitray binary expressions of them.
4628 Unary_expression* lu = this->left_->unary_expression();
4629 Unary_expression* ru = this->right_->unary_expression();
4630 if (lu != NULL && lu->op() == OPERATOR_AND)
4632 if (ru != NULL && ru->op() == OPERATOR_AND)
4633 return this->op_ == OPERATOR_MINUS;
4634 else
4635 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4637 else if (ru != NULL && ru->op() == OPERATOR_AND)
4638 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4640 // Other cases should resolve in the backend.
4641 return true;
4644 // Return the type to use for a binary operation on operands of
4645 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4646 // such may be NULL or abstract.
4648 bool
4649 Binary_expression::operation_type(Operator op, Type* left_type,
4650 Type* right_type, Type** result_type)
4652 if (left_type != right_type
4653 && !left_type->is_abstract()
4654 && !right_type->is_abstract()
4655 && left_type->base() != right_type->base()
4656 && op != OPERATOR_LSHIFT
4657 && op != OPERATOR_RSHIFT)
4659 // May be a type error--let it be diagnosed elsewhere.
4660 return false;
4663 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4665 if (left_type->integer_type() != NULL)
4666 *result_type = left_type;
4667 else
4668 *result_type = Type::make_abstract_integer_type();
4670 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4671 *result_type = left_type;
4672 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4673 *result_type = right_type;
4674 else if (!left_type->is_abstract())
4675 *result_type = left_type;
4676 else if (!right_type->is_abstract())
4677 *result_type = right_type;
4678 else if (left_type->complex_type() != NULL)
4679 *result_type = left_type;
4680 else if (right_type->complex_type() != NULL)
4681 *result_type = right_type;
4682 else if (left_type->float_type() != NULL)
4683 *result_type = left_type;
4684 else if (right_type->float_type() != NULL)
4685 *result_type = right_type;
4686 else if (left_type->integer_type() != NULL
4687 && left_type->integer_type()->is_rune())
4688 *result_type = left_type;
4689 else if (right_type->integer_type() != NULL
4690 && right_type->integer_type()->is_rune())
4691 *result_type = right_type;
4692 else
4693 *result_type = left_type;
4695 return true;
4698 // Convert an integer comparison code and an operator to a boolean
4699 // value.
4701 bool
4702 Binary_expression::cmp_to_bool(Operator op, int cmp)
4704 switch (op)
4706 case OPERATOR_EQEQ:
4707 return cmp == 0;
4708 break;
4709 case OPERATOR_NOTEQ:
4710 return cmp != 0;
4711 break;
4712 case OPERATOR_LT:
4713 return cmp < 0;
4714 break;
4715 case OPERATOR_LE:
4716 return cmp <= 0;
4717 case OPERATOR_GT:
4718 return cmp > 0;
4719 case OPERATOR_GE:
4720 return cmp >= 0;
4721 default:
4722 go_unreachable();
4726 // Compare constants according to OP.
4728 bool
4729 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4730 Numeric_constant* right_nc,
4731 Location location, bool* result)
4733 Type* left_type = left_nc->type();
4734 Type* right_type = right_nc->type();
4736 Type* type;
4737 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4738 return false;
4740 // When comparing an untyped operand to a typed operand, we are
4741 // effectively coercing the untyped operand to the other operand's
4742 // type, so make sure that is valid.
4743 if (!left_nc->set_type(type, true, location)
4744 || !right_nc->set_type(type, true, location))
4745 return false;
4747 bool ret;
4748 int cmp;
4749 if (type->complex_type() != NULL)
4751 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4752 return false;
4753 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4755 else if (type->float_type() != NULL)
4756 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4757 else
4758 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4760 if (ret)
4761 *result = Binary_expression::cmp_to_bool(op, cmp);
4763 return ret;
4766 // Compare integer constants.
4768 bool
4769 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4770 const Numeric_constant* right_nc,
4771 int* cmp)
4773 mpz_t left_val;
4774 if (!left_nc->to_int(&left_val))
4775 return false;
4776 mpz_t right_val;
4777 if (!right_nc->to_int(&right_val))
4779 mpz_clear(left_val);
4780 return false;
4783 *cmp = mpz_cmp(left_val, right_val);
4785 mpz_clear(left_val);
4786 mpz_clear(right_val);
4788 return true;
4791 // Compare floating point constants.
4793 bool
4794 Binary_expression::compare_float(const Numeric_constant* left_nc,
4795 const Numeric_constant* right_nc,
4796 int* cmp)
4798 mpfr_t left_val;
4799 if (!left_nc->to_float(&left_val))
4800 return false;
4801 mpfr_t right_val;
4802 if (!right_nc->to_float(&right_val))
4804 mpfr_clear(left_val);
4805 return false;
4808 // We already coerced both operands to the same type. If that type
4809 // is not an abstract type, we need to round the values accordingly.
4810 Type* type = left_nc->type();
4811 if (!type->is_abstract() && type->float_type() != NULL)
4813 int bits = type->float_type()->bits();
4814 mpfr_prec_round(left_val, bits, GMP_RNDN);
4815 mpfr_prec_round(right_val, bits, GMP_RNDN);
4818 *cmp = mpfr_cmp(left_val, right_val);
4820 mpfr_clear(left_val);
4821 mpfr_clear(right_val);
4823 return true;
4826 // Compare complex constants. Complex numbers may only be compared
4827 // for equality.
4829 bool
4830 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4831 const Numeric_constant* right_nc,
4832 int* cmp)
4834 mpc_t left_val;
4835 if (!left_nc->to_complex(&left_val))
4836 return false;
4837 mpc_t right_val;
4838 if (!right_nc->to_complex(&right_val))
4840 mpc_clear(left_val);
4841 return false;
4844 // We already coerced both operands to the same type. If that type
4845 // is not an abstract type, we need to round the values accordingly.
4846 Type* type = left_nc->type();
4847 if (!type->is_abstract() && type->complex_type() != NULL)
4849 int bits = type->complex_type()->bits();
4850 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4851 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4852 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4853 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4856 *cmp = mpc_cmp(left_val, right_val) != 0;
4858 mpc_clear(left_val);
4859 mpc_clear(right_val);
4861 return true;
4864 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4865 // true if this could be done, false if not. Issue errors at LOCATION
4866 // as appropriate, and sets *ISSUED_ERROR if it did.
4868 bool
4869 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4870 Numeric_constant* right_nc,
4871 Location location, Numeric_constant* nc,
4872 bool* issued_error)
4874 *issued_error = false;
4875 switch (op)
4877 case OPERATOR_OROR:
4878 case OPERATOR_ANDAND:
4879 case OPERATOR_EQEQ:
4880 case OPERATOR_NOTEQ:
4881 case OPERATOR_LT:
4882 case OPERATOR_LE:
4883 case OPERATOR_GT:
4884 case OPERATOR_GE:
4885 // These return boolean values, not numeric.
4886 return false;
4887 default:
4888 break;
4891 Type* left_type = left_nc->type();
4892 Type* right_type = right_nc->type();
4894 Type* type;
4895 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4896 return false;
4898 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4900 // When combining an untyped operand with a typed operand, we are
4901 // effectively coercing the untyped operand to the other operand's
4902 // type, so make sure that is valid.
4903 if (!left_nc->set_type(type, true, location))
4904 return false;
4905 if (!is_shift && !right_nc->set_type(type, true, location))
4906 return false;
4907 if (is_shift
4908 && ((left_type->integer_type() == NULL
4909 && !left_type->is_abstract())
4910 || (right_type->integer_type() == NULL
4911 && !right_type->is_abstract())))
4912 return false;
4914 bool r;
4915 if (type->complex_type() != NULL)
4916 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4917 else if (type->float_type() != NULL)
4918 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4919 else
4920 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4922 if (r)
4924 r = nc->set_type(type, true, location);
4925 if (!r)
4926 *issued_error = true;
4929 return r;
4932 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4933 // integer operations. Return true if this could be done, false if
4934 // not.
4936 bool
4937 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4938 const Numeric_constant* right_nc,
4939 Location location, Numeric_constant* nc)
4941 mpz_t left_val;
4942 if (!left_nc->to_int(&left_val))
4943 return false;
4944 mpz_t right_val;
4945 if (!right_nc->to_int(&right_val))
4947 mpz_clear(left_val);
4948 return false;
4951 mpz_t val;
4952 mpz_init(val);
4954 switch (op)
4956 case OPERATOR_PLUS:
4957 mpz_add(val, left_val, right_val);
4958 if (mpz_sizeinbase(val, 2) > 0x100000)
4960 go_error_at(location, "constant addition overflow");
4961 nc->set_invalid();
4962 mpz_set_ui(val, 1);
4964 break;
4965 case OPERATOR_MINUS:
4966 mpz_sub(val, left_val, right_val);
4967 if (mpz_sizeinbase(val, 2) > 0x100000)
4969 go_error_at(location, "constant subtraction overflow");
4970 nc->set_invalid();
4971 mpz_set_ui(val, 1);
4973 break;
4974 case OPERATOR_OR:
4975 mpz_ior(val, left_val, right_val);
4976 break;
4977 case OPERATOR_XOR:
4978 mpz_xor(val, left_val, right_val);
4979 break;
4980 case OPERATOR_MULT:
4981 mpz_mul(val, left_val, right_val);
4982 if (mpz_sizeinbase(val, 2) > 0x100000)
4984 go_error_at(location, "constant multiplication overflow");
4985 nc->set_invalid();
4986 mpz_set_ui(val, 1);
4988 break;
4989 case OPERATOR_DIV:
4990 if (mpz_sgn(right_val) != 0)
4991 mpz_tdiv_q(val, left_val, right_val);
4992 else
4994 go_error_at(location, "division by zero");
4995 nc->set_invalid();
4996 mpz_set_ui(val, 0);
4998 break;
4999 case OPERATOR_MOD:
5000 if (mpz_sgn(right_val) != 0)
5001 mpz_tdiv_r(val, left_val, right_val);
5002 else
5004 go_error_at(location, "division by zero");
5005 nc->set_invalid();
5006 mpz_set_ui(val, 0);
5008 break;
5009 case OPERATOR_LSHIFT:
5011 unsigned long shift = mpz_get_ui(right_val);
5012 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5013 mpz_mul_2exp(val, left_val, shift);
5014 else
5016 go_error_at(location, "shift count overflow");
5017 nc->set_invalid();
5018 mpz_set_ui(val, 1);
5020 break;
5022 break;
5023 case OPERATOR_RSHIFT:
5025 unsigned long shift = mpz_get_ui(right_val);
5026 if (mpz_cmp_ui(right_val, shift) != 0)
5028 go_error_at(location, "shift count overflow");
5029 nc->set_invalid();
5030 mpz_set_ui(val, 1);
5032 else
5034 if (mpz_cmp_ui(left_val, 0) >= 0)
5035 mpz_tdiv_q_2exp(val, left_val, shift);
5036 else
5037 mpz_fdiv_q_2exp(val, left_val, shift);
5039 break;
5041 break;
5042 case OPERATOR_AND:
5043 mpz_and(val, left_val, right_val);
5044 break;
5045 case OPERATOR_BITCLEAR:
5047 mpz_t tval;
5048 mpz_init(tval);
5049 mpz_com(tval, right_val);
5050 mpz_and(val, left_val, tval);
5051 mpz_clear(tval);
5053 break;
5054 default:
5055 go_unreachable();
5058 mpz_clear(left_val);
5059 mpz_clear(right_val);
5061 if (left_nc->is_rune()
5062 || (op != OPERATOR_LSHIFT
5063 && op != OPERATOR_RSHIFT
5064 && right_nc->is_rune()))
5065 nc->set_rune(NULL, val);
5066 else
5067 nc->set_int(NULL, val);
5069 mpz_clear(val);
5071 return true;
5074 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5075 // floating point operations. Return true if this could be done,
5076 // false if not.
5078 bool
5079 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5080 const Numeric_constant* right_nc,
5081 Location location, Numeric_constant* nc)
5083 mpfr_t left_val;
5084 if (!left_nc->to_float(&left_val))
5085 return false;
5086 mpfr_t right_val;
5087 if (!right_nc->to_float(&right_val))
5089 mpfr_clear(left_val);
5090 return false;
5093 mpfr_t val;
5094 mpfr_init(val);
5096 bool ret = true;
5097 switch (op)
5099 case OPERATOR_PLUS:
5100 mpfr_add(val, left_val, right_val, GMP_RNDN);
5101 break;
5102 case OPERATOR_MINUS:
5103 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5104 break;
5105 case OPERATOR_OR:
5106 case OPERATOR_XOR:
5107 case OPERATOR_AND:
5108 case OPERATOR_BITCLEAR:
5109 case OPERATOR_MOD:
5110 case OPERATOR_LSHIFT:
5111 case OPERATOR_RSHIFT:
5112 mpfr_set_ui(val, 0, GMP_RNDN);
5113 ret = false;
5114 break;
5115 case OPERATOR_MULT:
5116 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5117 break;
5118 case OPERATOR_DIV:
5119 if (!mpfr_zero_p(right_val))
5120 mpfr_div(val, left_val, right_val, GMP_RNDN);
5121 else
5123 go_error_at(location, "division by zero");
5124 nc->set_invalid();
5125 mpfr_set_ui(val, 0, GMP_RNDN);
5127 break;
5128 default:
5129 go_unreachable();
5132 mpfr_clear(left_val);
5133 mpfr_clear(right_val);
5135 nc->set_float(NULL, val);
5136 mpfr_clear(val);
5138 return ret;
5141 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5142 // complex operations. Return true if this could be done, false if
5143 // not.
5145 bool
5146 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5147 const Numeric_constant* right_nc,
5148 Location location, Numeric_constant* nc)
5150 mpc_t left_val;
5151 if (!left_nc->to_complex(&left_val))
5152 return false;
5153 mpc_t right_val;
5154 if (!right_nc->to_complex(&right_val))
5156 mpc_clear(left_val);
5157 return false;
5160 mpc_t val;
5161 mpc_init2(val, mpc_precision);
5163 bool ret = true;
5164 switch (op)
5166 case OPERATOR_PLUS:
5167 mpc_add(val, left_val, right_val, MPC_RNDNN);
5168 break;
5169 case OPERATOR_MINUS:
5170 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5171 break;
5172 case OPERATOR_OR:
5173 case OPERATOR_XOR:
5174 case OPERATOR_AND:
5175 case OPERATOR_BITCLEAR:
5176 case OPERATOR_MOD:
5177 case OPERATOR_LSHIFT:
5178 case OPERATOR_RSHIFT:
5179 mpc_set_ui(val, 0, MPC_RNDNN);
5180 ret = false;
5181 break;
5182 case OPERATOR_MULT:
5183 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5184 break;
5185 case OPERATOR_DIV:
5186 if (mpc_cmp_si(right_val, 0) == 0)
5188 go_error_at(location, "division by zero");
5189 nc->set_invalid();
5190 mpc_set_ui(val, 0, MPC_RNDNN);
5191 break;
5193 mpc_div(val, left_val, right_val, MPC_RNDNN);
5194 break;
5195 default:
5196 go_unreachable();
5199 mpc_clear(left_val);
5200 mpc_clear(right_val);
5202 nc->set_complex(NULL, val);
5203 mpc_clear(val);
5205 return ret;
5208 // Lower a binary expression. We have to evaluate constant
5209 // expressions now, in order to implement Go's unlimited precision
5210 // constants.
5212 Expression*
5213 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5214 Statement_inserter* inserter, int)
5216 Location location = this->location();
5217 Operator op = this->op_;
5218 Expression* left = this->left_;
5219 Expression* right = this->right_;
5221 const bool is_comparison = (op == OPERATOR_EQEQ
5222 || op == OPERATOR_NOTEQ
5223 || op == OPERATOR_LT
5224 || op == OPERATOR_LE
5225 || op == OPERATOR_GT
5226 || op == OPERATOR_GE);
5228 // Numeric constant expressions.
5230 Numeric_constant left_nc;
5231 Numeric_constant right_nc;
5232 if (left->numeric_constant_value(&left_nc)
5233 && right->numeric_constant_value(&right_nc))
5235 if (is_comparison)
5237 bool result;
5238 if (!Binary_expression::compare_constant(op, &left_nc,
5239 &right_nc, location,
5240 &result))
5241 return this;
5242 return Expression::make_cast(Type::make_boolean_type(),
5243 Expression::make_boolean(result,
5244 location),
5245 location);
5247 else
5249 Numeric_constant nc;
5250 bool issued_error;
5251 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5252 location, &nc,
5253 &issued_error))
5255 if (issued_error)
5256 return Expression::make_error(location);
5257 return this;
5259 return nc.expression(location);
5264 // String constant expressions.
5265 if (left->type()->is_string_type() && right->type()->is_string_type())
5267 std::string left_string;
5268 std::string right_string;
5269 if (left->string_constant_value(&left_string)
5270 && right->string_constant_value(&right_string))
5272 if (op == OPERATOR_PLUS)
5273 return Expression::make_string(left_string + right_string,
5274 location);
5275 else if (is_comparison)
5277 int cmp = left_string.compare(right_string);
5278 bool r = Binary_expression::cmp_to_bool(op, cmp);
5279 return Expression::make_boolean(r, location);
5284 // Lower struct, array, and some interface comparisons.
5285 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5287 if (left->type()->struct_type() != NULL
5288 && right->type()->struct_type() != NULL)
5289 return this->lower_struct_comparison(gogo, inserter);
5290 else if (left->type()->array_type() != NULL
5291 && !left->type()->is_slice_type()
5292 && right->type()->array_type() != NULL
5293 && !right->type()->is_slice_type())
5294 return this->lower_array_comparison(gogo, inserter);
5295 else if ((left->type()->interface_type() != NULL
5296 && right->type()->interface_type() == NULL)
5297 || (left->type()->interface_type() == NULL
5298 && right->type()->interface_type() != NULL))
5299 return this->lower_interface_value_comparison(gogo, inserter);
5302 // Lower string concatenation to String_concat_expression, so that
5303 // we can group sequences of string additions.
5304 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5306 Expression_list* exprs;
5307 String_concat_expression* left_sce =
5308 this->left_->string_concat_expression();
5309 if (left_sce != NULL)
5310 exprs = left_sce->exprs();
5311 else
5313 exprs = new Expression_list();
5314 exprs->push_back(this->left_);
5317 String_concat_expression* right_sce =
5318 this->right_->string_concat_expression();
5319 if (right_sce != NULL)
5320 exprs->append(right_sce->exprs());
5321 else
5322 exprs->push_back(this->right_);
5324 return Expression::make_string_concat(exprs);
5327 return this;
5330 // Lower a struct comparison.
5332 Expression*
5333 Binary_expression::lower_struct_comparison(Gogo* gogo,
5334 Statement_inserter* inserter)
5336 Struct_type* st = this->left_->type()->struct_type();
5337 Struct_type* st2 = this->right_->type()->struct_type();
5338 if (st2 == NULL)
5339 return this;
5340 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5341 return this;
5342 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5343 this->right_->type(), NULL))
5344 return this;
5346 // See if we can compare using memcmp. As a heuristic, we use
5347 // memcmp rather than field references and comparisons if there are
5348 // more than two fields.
5349 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5350 return this->lower_compare_to_memcmp(gogo, inserter);
5352 Location loc = this->location();
5354 Expression* left = this->left_;
5355 Temporary_statement* left_temp = NULL;
5356 if (left->var_expression() == NULL
5357 && left->temporary_reference_expression() == NULL)
5359 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5360 inserter->insert(left_temp);
5361 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5364 Expression* right = this->right_;
5365 Temporary_statement* right_temp = NULL;
5366 if (right->var_expression() == NULL
5367 && right->temporary_reference_expression() == NULL)
5369 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5370 inserter->insert(right_temp);
5371 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5374 Expression* ret = Expression::make_boolean(true, loc);
5375 const Struct_field_list* fields = st->fields();
5376 unsigned int field_index = 0;
5377 for (Struct_field_list::const_iterator pf = fields->begin();
5378 pf != fields->end();
5379 ++pf, ++field_index)
5381 if (Gogo::is_sink_name(pf->field_name()))
5382 continue;
5384 if (field_index > 0)
5386 if (left_temp == NULL)
5387 left = left->copy();
5388 else
5389 left = Expression::make_temporary_reference(left_temp, loc);
5390 if (right_temp == NULL)
5391 right = right->copy();
5392 else
5393 right = Expression::make_temporary_reference(right_temp, loc);
5395 Expression* f1 = Expression::make_field_reference(left, field_index,
5396 loc);
5397 Expression* f2 = Expression::make_field_reference(right, field_index,
5398 loc);
5399 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5400 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5403 if (this->op_ == OPERATOR_NOTEQ)
5404 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5406 return ret;
5409 // Lower an array comparison.
5411 Expression*
5412 Binary_expression::lower_array_comparison(Gogo* gogo,
5413 Statement_inserter* inserter)
5415 Array_type* at = this->left_->type()->array_type();
5416 Array_type* at2 = this->right_->type()->array_type();
5417 if (at2 == NULL)
5418 return this;
5419 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5420 return this;
5421 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5422 this->right_->type(), NULL))
5423 return this;
5425 // Call memcmp directly if possible. This may let the middle-end
5426 // optimize the call.
5427 if (at->compare_is_identity(gogo))
5428 return this->lower_compare_to_memcmp(gogo, inserter);
5430 // Call the array comparison function.
5431 Named_object* hash_fn;
5432 Named_object* equal_fn;
5433 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5434 &hash_fn, &equal_fn);
5436 Location loc = this->location();
5438 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5440 Expression_list* args = new Expression_list();
5441 args->push_back(this->operand_address(inserter, this->left_));
5442 args->push_back(this->operand_address(inserter, this->right_));
5444 Expression* ret = Expression::make_call(func, args, false, loc);
5446 if (this->op_ == OPERATOR_NOTEQ)
5447 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5449 return ret;
5452 // Lower an interface to value comparison.
5454 Expression*
5455 Binary_expression::lower_interface_value_comparison(Gogo*,
5456 Statement_inserter* inserter)
5458 Type* left_type = this->left_->type();
5459 Type* right_type = this->right_->type();
5460 Interface_type* ift;
5461 if (left_type->interface_type() != NULL)
5463 ift = left_type->interface_type();
5464 if (!ift->implements_interface(right_type, NULL))
5465 return this;
5467 else
5469 ift = right_type->interface_type();
5470 if (!ift->implements_interface(left_type, NULL))
5471 return this;
5473 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5474 return this;
5476 Location loc = this->location();
5478 if (left_type->interface_type() == NULL
5479 && left_type->points_to() == NULL
5480 && !this->left_->is_addressable())
5482 Temporary_statement* temp =
5483 Statement::make_temporary(left_type, NULL, loc);
5484 inserter->insert(temp);
5485 this->left_ =
5486 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5489 if (right_type->interface_type() == NULL
5490 && right_type->points_to() == NULL
5491 && !this->right_->is_addressable())
5493 Temporary_statement* temp =
5494 Statement::make_temporary(right_type, NULL, loc);
5495 inserter->insert(temp);
5496 this->right_ =
5497 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5500 return this;
5503 // Lower a struct or array comparison to a call to memcmp.
5505 Expression*
5506 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5508 Location loc = this->location();
5510 Expression* a1 = this->operand_address(inserter, this->left_);
5511 Expression* a2 = this->operand_address(inserter, this->right_);
5512 Expression* len = Expression::make_type_info(this->left_->type(),
5513 TYPE_INFO_SIZE);
5515 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5516 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5517 return Expression::make_binary(this->op_, call, zero, loc);
5520 Expression*
5521 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5522 Statement_inserter* inserter)
5524 Location loc = this->location();
5525 if (this->left_->type()->is_error_type()
5526 || this->right_->type()->is_error_type()
5527 || this->left_->is_error_expression()
5528 || this->right_->is_error_expression())
5530 go_assert(saw_errors());
5531 return Expression::make_error(loc);
5534 Temporary_statement* temp;
5536 Type* left_type = this->left_->type();
5537 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5538 || this->op_ == OPERATOR_RSHIFT);
5539 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5540 left_type->integer_type() != NULL)
5541 || this->op_ == OPERATOR_MOD);
5543 if (is_shift_op
5544 || (is_idiv_op
5545 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5547 if (!this->left_->is_variable() && !this->left_->is_constant())
5549 temp = Statement::make_temporary(NULL, this->left_, loc);
5550 inserter->insert(temp);
5551 this->left_ = Expression::make_temporary_reference(temp, loc);
5553 if (!this->right_->is_variable() && !this->right_->is_constant())
5555 temp =
5556 Statement::make_temporary(NULL, this->right_, loc);
5557 this->right_ = Expression::make_temporary_reference(temp, loc);
5558 inserter->insert(temp);
5561 return this;
5565 // Return the address of EXPR, cast to unsafe.Pointer.
5567 Expression*
5568 Binary_expression::operand_address(Statement_inserter* inserter,
5569 Expression* expr)
5571 Location loc = this->location();
5573 if (!expr->is_addressable())
5575 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5576 loc);
5577 inserter->insert(temp);
5578 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5580 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5581 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5582 Type* void_type = Type::make_void_type();
5583 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5584 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5587 // Return the numeric constant value, if it has one.
5589 bool
5590 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5592 Numeric_constant left_nc;
5593 if (!this->left_->numeric_constant_value(&left_nc))
5594 return false;
5595 Numeric_constant right_nc;
5596 if (!this->right_->numeric_constant_value(&right_nc))
5597 return false;
5598 bool issued_error;
5599 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5600 this->location(), nc, &issued_error);
5603 // Note that the value is being discarded.
5605 bool
5606 Binary_expression::do_discarding_value()
5608 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5609 return this->right_->discarding_value();
5610 else
5612 this->unused_value_error();
5613 return false;
5617 // Get type.
5619 Type*
5620 Binary_expression::do_type()
5622 if (this->classification() == EXPRESSION_ERROR)
5623 return Type::make_error_type();
5625 switch (this->op_)
5627 case OPERATOR_EQEQ:
5628 case OPERATOR_NOTEQ:
5629 case OPERATOR_LT:
5630 case OPERATOR_LE:
5631 case OPERATOR_GT:
5632 case OPERATOR_GE:
5633 if (this->type_ == NULL)
5634 this->type_ = Type::make_boolean_type();
5635 return this->type_;
5637 case OPERATOR_PLUS:
5638 case OPERATOR_MINUS:
5639 case OPERATOR_OR:
5640 case OPERATOR_XOR:
5641 case OPERATOR_MULT:
5642 case OPERATOR_DIV:
5643 case OPERATOR_MOD:
5644 case OPERATOR_AND:
5645 case OPERATOR_BITCLEAR:
5646 case OPERATOR_OROR:
5647 case OPERATOR_ANDAND:
5649 Type* type;
5650 if (!Binary_expression::operation_type(this->op_,
5651 this->left_->type(),
5652 this->right_->type(),
5653 &type))
5654 return Type::make_error_type();
5655 return type;
5658 case OPERATOR_LSHIFT:
5659 case OPERATOR_RSHIFT:
5660 return this->left_->type();
5662 default:
5663 go_unreachable();
5667 // Set type for a binary expression.
5669 void
5670 Binary_expression::do_determine_type(const Type_context* context)
5672 Type* tleft = this->left_->type();
5673 Type* tright = this->right_->type();
5675 // Both sides should have the same type, except for the shift
5676 // operations. For a comparison, we should ignore the incoming
5677 // type.
5679 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5680 || this->op_ == OPERATOR_RSHIFT);
5682 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5683 || this->op_ == OPERATOR_NOTEQ
5684 || this->op_ == OPERATOR_LT
5685 || this->op_ == OPERATOR_LE
5686 || this->op_ == OPERATOR_GT
5687 || this->op_ == OPERATOR_GE);
5689 // For constant expressions, the context of the result is not useful in
5690 // determining the types of the operands. It is only legal to use abstract
5691 // boolean, numeric, and string constants as operands where it is legal to
5692 // use non-abstract boolean, numeric, and string constants, respectively.
5693 // Any issues with the operation will be resolved in the check_types pass.
5694 bool is_constant_expr = (this->left_->is_constant()
5695 && this->right_->is_constant());
5697 Type_context subcontext(*context);
5699 if (is_constant_expr && !is_shift_op)
5701 subcontext.type = NULL;
5702 subcontext.may_be_abstract = true;
5704 else if (is_comparison)
5706 // In a comparison, the context does not determine the types of
5707 // the operands.
5708 subcontext.type = NULL;
5711 // Set the context for the left hand operand.
5712 if (is_shift_op)
5714 // The right hand operand of a shift plays no role in
5715 // determining the type of the left hand operand.
5717 else if (!tleft->is_abstract())
5718 subcontext.type = tleft;
5719 else if (!tright->is_abstract())
5720 subcontext.type = tright;
5721 else if (subcontext.type == NULL)
5723 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5724 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5725 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5727 // Both sides have an abstract integer, abstract float, or
5728 // abstract complex type. Just let CONTEXT determine
5729 // whether they may remain abstract or not.
5731 else if (tleft->complex_type() != NULL)
5732 subcontext.type = tleft;
5733 else if (tright->complex_type() != NULL)
5734 subcontext.type = tright;
5735 else if (tleft->float_type() != NULL)
5736 subcontext.type = tleft;
5737 else if (tright->float_type() != NULL)
5738 subcontext.type = tright;
5739 else
5740 subcontext.type = tleft;
5742 if (subcontext.type != NULL && !context->may_be_abstract)
5743 subcontext.type = subcontext.type->make_non_abstract_type();
5746 this->left_->determine_type(&subcontext);
5748 if (is_shift_op)
5750 // We may have inherited an unusable type for the shift operand.
5751 // Give a useful error if that happened.
5752 if (tleft->is_abstract()
5753 && subcontext.type != NULL
5754 && !subcontext.may_be_abstract
5755 && subcontext.type->interface_type() == NULL
5756 && subcontext.type->integer_type() == NULL)
5757 this->report_error(("invalid context-determined non-integer type "
5758 "for left operand of shift"));
5760 // The context for the right hand operand is the same as for the
5761 // left hand operand, except for a shift operator.
5762 subcontext.type = Type::lookup_integer_type("uint");
5763 subcontext.may_be_abstract = false;
5766 this->right_->determine_type(&subcontext);
5768 if (is_comparison)
5770 if (this->type_ != NULL && !this->type_->is_abstract())
5772 else if (context->type != NULL && context->type->is_boolean_type())
5773 this->type_ = context->type;
5774 else if (!context->may_be_abstract)
5775 this->type_ = Type::lookup_bool_type();
5779 // Report an error if the binary operator OP does not support TYPE.
5780 // OTYPE is the type of the other operand. Return whether the
5781 // operation is OK. This should not be used for shift.
5783 bool
5784 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5785 Location location)
5787 switch (op)
5789 case OPERATOR_OROR:
5790 case OPERATOR_ANDAND:
5791 if (!type->is_boolean_type()
5792 || !otype->is_boolean_type())
5794 go_error_at(location, "expected boolean type");
5795 return false;
5797 break;
5799 case OPERATOR_EQEQ:
5800 case OPERATOR_NOTEQ:
5802 std::string reason;
5803 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5805 go_error_at(location, "%s", reason.c_str());
5806 return false;
5809 break;
5811 case OPERATOR_LT:
5812 case OPERATOR_LE:
5813 case OPERATOR_GT:
5814 case OPERATOR_GE:
5816 std::string reason;
5817 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5819 go_error_at(location, "%s", reason.c_str());
5820 return false;
5823 break;
5825 case OPERATOR_PLUS:
5826 case OPERATOR_PLUSEQ:
5827 if ((!type->is_numeric_type() && !type->is_string_type())
5828 || (!otype->is_numeric_type() && !otype->is_string_type()))
5830 go_error_at(location,
5831 "expected integer, floating, complex, or string type");
5832 return false;
5834 break;
5836 case OPERATOR_MINUS:
5837 case OPERATOR_MINUSEQ:
5838 case OPERATOR_MULT:
5839 case OPERATOR_MULTEQ:
5840 case OPERATOR_DIV:
5841 case OPERATOR_DIVEQ:
5842 if (!type->is_numeric_type() || !otype->is_numeric_type())
5844 go_error_at(location, "expected integer, floating, or complex type");
5845 return false;
5847 break;
5849 case OPERATOR_MOD:
5850 case OPERATOR_MODEQ:
5851 case OPERATOR_OR:
5852 case OPERATOR_OREQ:
5853 case OPERATOR_AND:
5854 case OPERATOR_ANDEQ:
5855 case OPERATOR_XOR:
5856 case OPERATOR_XOREQ:
5857 case OPERATOR_BITCLEAR:
5858 case OPERATOR_BITCLEAREQ:
5859 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5861 go_error_at(location, "expected integer type");
5862 return false;
5864 break;
5866 default:
5867 go_unreachable();
5870 return true;
5873 // Check types.
5875 void
5876 Binary_expression::do_check_types(Gogo*)
5878 if (this->classification() == EXPRESSION_ERROR)
5879 return;
5881 Type* left_type = this->left_->type();
5882 Type* right_type = this->right_->type();
5883 if (left_type->is_error() || right_type->is_error())
5885 this->set_is_error();
5886 return;
5889 if (this->op_ == OPERATOR_EQEQ
5890 || this->op_ == OPERATOR_NOTEQ
5891 || this->op_ == OPERATOR_LT
5892 || this->op_ == OPERATOR_LE
5893 || this->op_ == OPERATOR_GT
5894 || this->op_ == OPERATOR_GE)
5896 if (left_type->is_nil_type() && right_type->is_nil_type())
5898 this->report_error(_("invalid comparison of nil with nil"));
5899 return;
5901 if (!Type::are_assignable(left_type, right_type, NULL)
5902 && !Type::are_assignable(right_type, left_type, NULL))
5904 this->report_error(_("incompatible types in binary expression"));
5905 return;
5907 if (!Binary_expression::check_operator_type(this->op_, left_type,
5908 right_type,
5909 this->location())
5910 || !Binary_expression::check_operator_type(this->op_, right_type,
5911 left_type,
5912 this->location()))
5914 this->set_is_error();
5915 return;
5918 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5920 if (!Type::are_compatible_for_binop(left_type, right_type))
5922 this->report_error(_("incompatible types in binary expression"));
5923 return;
5925 if (!Binary_expression::check_operator_type(this->op_, left_type,
5926 right_type,
5927 this->location()))
5929 this->set_is_error();
5930 return;
5932 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5934 // Division by a zero integer constant is an error.
5935 Numeric_constant rconst;
5936 unsigned long rval;
5937 if (left_type->integer_type() != NULL
5938 && this->right_->numeric_constant_value(&rconst)
5939 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5940 && rval == 0)
5942 this->report_error(_("integer division by zero"));
5943 return;
5947 else
5949 if (left_type->integer_type() == NULL)
5950 this->report_error(_("shift of non-integer operand"));
5952 if (right_type->is_string_type())
5953 this->report_error(_("shift count not unsigned integer"));
5954 else if (!right_type->is_abstract()
5955 && (right_type->integer_type() == NULL
5956 || !right_type->integer_type()->is_unsigned()))
5957 this->report_error(_("shift count not unsigned integer"));
5958 else
5960 Numeric_constant nc;
5961 if (this->right_->numeric_constant_value(&nc))
5963 mpz_t val;
5964 if (!nc.to_int(&val))
5965 this->report_error(_("shift count not unsigned integer"));
5966 else
5968 if (mpz_sgn(val) < 0)
5970 this->report_error(_("negative shift count"));
5971 Location rloc = this->right_->location();
5972 this->right_ = Expression::make_integer_ul(0, right_type,
5973 rloc);
5975 mpz_clear(val);
5982 // Get the backend representation for a binary expression.
5984 Bexpression*
5985 Binary_expression::do_get_backend(Translate_context* context)
5987 Gogo* gogo = context->gogo();
5988 Location loc = this->location();
5989 Type* left_type = this->left_->type();
5990 Type* right_type = this->right_->type();
5992 bool use_left_type = true;
5993 bool is_shift_op = false;
5994 bool is_idiv_op = false;
5995 switch (this->op_)
5997 case OPERATOR_EQEQ:
5998 case OPERATOR_NOTEQ:
5999 case OPERATOR_LT:
6000 case OPERATOR_LE:
6001 case OPERATOR_GT:
6002 case OPERATOR_GE:
6003 return Expression::comparison(context, this->type_, this->op_,
6004 this->left_, this->right_, loc);
6006 case OPERATOR_OROR:
6007 case OPERATOR_ANDAND:
6008 use_left_type = false;
6009 break;
6010 case OPERATOR_PLUS:
6011 case OPERATOR_MINUS:
6012 case OPERATOR_OR:
6013 case OPERATOR_XOR:
6014 case OPERATOR_MULT:
6015 break;
6016 case OPERATOR_DIV:
6017 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6018 break;
6019 // Fall through.
6020 case OPERATOR_MOD:
6021 is_idiv_op = true;
6022 break;
6023 case OPERATOR_LSHIFT:
6024 case OPERATOR_RSHIFT:
6025 is_shift_op = true;
6026 break;
6027 case OPERATOR_BITCLEAR:
6028 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6029 case OPERATOR_AND:
6030 break;
6031 default:
6032 go_unreachable();
6035 // The only binary operation for string is +, and that should have
6036 // been converted to a String_concat_expression in do_lower.
6037 go_assert(!left_type->is_string_type());
6039 // For complex division Go might want slightly different results than the
6040 // backend implementation provides, so we have our own runtime routine.
6041 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6043 Runtime::Function complex_code;
6044 switch (this->left_->type()->complex_type()->bits())
6046 case 64:
6047 complex_code = Runtime::COMPLEX64_DIV;
6048 break;
6049 case 128:
6050 complex_code = Runtime::COMPLEX128_DIV;
6051 break;
6052 default:
6053 go_unreachable();
6055 Expression* complex_div =
6056 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6057 return complex_div->get_backend(context);
6060 Bexpression* left = this->left_->get_backend(context);
6061 Bexpression* right = this->right_->get_backend(context);
6063 Type* type = use_left_type ? left_type : right_type;
6064 Btype* btype = type->get_backend(gogo);
6066 Bexpression* ret =
6067 gogo->backend()->binary_expression(this->op_, left, right, loc);
6068 ret = gogo->backend()->convert_expression(btype, ret, loc);
6070 // Initialize overflow constants.
6071 Bexpression* overflow;
6072 mpz_t zero;
6073 mpz_init_set_ui(zero, 0UL);
6074 mpz_t one;
6075 mpz_init_set_ui(one, 1UL);
6076 mpz_t neg_one;
6077 mpz_init_set_si(neg_one, -1);
6079 Btype* left_btype = left_type->get_backend(gogo);
6080 Btype* right_btype = right_type->get_backend(gogo);
6082 // In Go, a shift larger than the size of the type is well-defined.
6083 // This is not true in C, so we need to insert a conditional.
6084 if (is_shift_op)
6086 go_assert(left_type->integer_type() != NULL);
6088 int bits = left_type->integer_type()->bits();
6090 Numeric_constant nc;
6091 unsigned long ul;
6092 if (!this->right_->numeric_constant_value(&nc)
6093 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6094 || ul >= static_cast<unsigned long>(bits))
6096 mpz_t bitsval;
6097 mpz_init_set_ui(bitsval, bits);
6098 Bexpression* bits_expr =
6099 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6100 Bexpression* compare =
6101 gogo->backend()->binary_expression(OPERATOR_LT,
6102 right, bits_expr, loc);
6104 Bexpression* zero_expr =
6105 gogo->backend()->integer_constant_expression(left_btype, zero);
6106 overflow = zero_expr;
6107 Bfunction* bfn = context->function()->func_value()->get_decl();
6108 if (this->op_ == OPERATOR_RSHIFT
6109 && !left_type->integer_type()->is_unsigned())
6111 Bexpression* neg_expr =
6112 gogo->backend()->binary_expression(OPERATOR_LT, left,
6113 zero_expr, loc);
6114 Bexpression* neg_one_expr =
6115 gogo->backend()->integer_constant_expression(left_btype,
6116 neg_one);
6117 overflow = gogo->backend()->conditional_expression(bfn,
6118 btype,
6119 neg_expr,
6120 neg_one_expr,
6121 zero_expr,
6122 loc);
6124 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6125 ret, overflow, loc);
6126 mpz_clear(bitsval);
6130 // Add checks for division by zero and division overflow as needed.
6131 if (is_idiv_op)
6133 if (gogo->check_divide_by_zero())
6135 // right == 0
6136 Bexpression* zero_expr =
6137 gogo->backend()->integer_constant_expression(right_btype, zero);
6138 Bexpression* check =
6139 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6140 right, zero_expr, loc);
6142 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6143 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6144 Bexpression* crash = gogo->runtime_error(errcode,
6145 loc)->get_backend(context);
6147 // right == 0 ? (__go_runtime_error(...), 0) : ret
6148 Bfunction* bfn = context->function()->func_value()->get_decl();
6149 ret = gogo->backend()->conditional_expression(bfn, btype,
6150 check, crash,
6151 ret, loc);
6154 if (gogo->check_divide_overflow())
6156 // right == -1
6157 // FIXME: It would be nice to say that this test is expected
6158 // to return false.
6160 Bexpression* neg_one_expr =
6161 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6162 Bexpression* check =
6163 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6164 right, neg_one_expr, loc);
6166 Bexpression* zero_expr =
6167 gogo->backend()->integer_constant_expression(btype, zero);
6168 Bexpression* one_expr =
6169 gogo->backend()->integer_constant_expression(btype, one);
6170 Bfunction* bfn = context->function()->func_value()->get_decl();
6172 if (type->integer_type()->is_unsigned())
6174 // An unsigned -1 is the largest possible number, so
6175 // dividing is always 1 or 0.
6177 Bexpression* cmp =
6178 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6179 left, right, loc);
6180 if (this->op_ == OPERATOR_DIV)
6181 overflow =
6182 gogo->backend()->conditional_expression(bfn, btype, cmp,
6183 one_expr, zero_expr,
6184 loc);
6185 else
6186 overflow =
6187 gogo->backend()->conditional_expression(bfn, btype, cmp,
6188 zero_expr, left,
6189 loc);
6191 else
6193 // Computing left / -1 is the same as computing - left,
6194 // which does not overflow since Go sets -fwrapv.
6195 if (this->op_ == OPERATOR_DIV)
6197 Expression* negate_expr =
6198 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6199 overflow = negate_expr->get_backend(context);
6201 else
6202 overflow = zero_expr;
6204 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6206 // right == -1 ? - left : ret
6207 ret = gogo->backend()->conditional_expression(bfn, btype,
6208 check, overflow,
6209 ret, loc);
6213 mpz_clear(zero);
6214 mpz_clear(one);
6215 mpz_clear(neg_one);
6216 return ret;
6219 // Export a binary expression.
6221 void
6222 Binary_expression::do_export(Export* exp) const
6224 exp->write_c_string("(");
6225 this->left_->export_expression(exp);
6226 switch (this->op_)
6228 case OPERATOR_OROR:
6229 exp->write_c_string(" || ");
6230 break;
6231 case OPERATOR_ANDAND:
6232 exp->write_c_string(" && ");
6233 break;
6234 case OPERATOR_EQEQ:
6235 exp->write_c_string(" == ");
6236 break;
6237 case OPERATOR_NOTEQ:
6238 exp->write_c_string(" != ");
6239 break;
6240 case OPERATOR_LT:
6241 exp->write_c_string(" < ");
6242 break;
6243 case OPERATOR_LE:
6244 exp->write_c_string(" <= ");
6245 break;
6246 case OPERATOR_GT:
6247 exp->write_c_string(" > ");
6248 break;
6249 case OPERATOR_GE:
6250 exp->write_c_string(" >= ");
6251 break;
6252 case OPERATOR_PLUS:
6253 exp->write_c_string(" + ");
6254 break;
6255 case OPERATOR_MINUS:
6256 exp->write_c_string(" - ");
6257 break;
6258 case OPERATOR_OR:
6259 exp->write_c_string(" | ");
6260 break;
6261 case OPERATOR_XOR:
6262 exp->write_c_string(" ^ ");
6263 break;
6264 case OPERATOR_MULT:
6265 exp->write_c_string(" * ");
6266 break;
6267 case OPERATOR_DIV:
6268 exp->write_c_string(" / ");
6269 break;
6270 case OPERATOR_MOD:
6271 exp->write_c_string(" % ");
6272 break;
6273 case OPERATOR_LSHIFT:
6274 exp->write_c_string(" << ");
6275 break;
6276 case OPERATOR_RSHIFT:
6277 exp->write_c_string(" >> ");
6278 break;
6279 case OPERATOR_AND:
6280 exp->write_c_string(" & ");
6281 break;
6282 case OPERATOR_BITCLEAR:
6283 exp->write_c_string(" &^ ");
6284 break;
6285 default:
6286 go_unreachable();
6288 this->right_->export_expression(exp);
6289 exp->write_c_string(")");
6292 // Import a binary expression.
6294 Expression*
6295 Binary_expression::do_import(Import* imp)
6297 imp->require_c_string("(");
6299 Expression* left = Expression::import_expression(imp);
6301 Operator op;
6302 if (imp->match_c_string(" || "))
6304 op = OPERATOR_OROR;
6305 imp->advance(4);
6307 else if (imp->match_c_string(" && "))
6309 op = OPERATOR_ANDAND;
6310 imp->advance(4);
6312 else if (imp->match_c_string(" == "))
6314 op = OPERATOR_EQEQ;
6315 imp->advance(4);
6317 else if (imp->match_c_string(" != "))
6319 op = OPERATOR_NOTEQ;
6320 imp->advance(4);
6322 else if (imp->match_c_string(" < "))
6324 op = OPERATOR_LT;
6325 imp->advance(3);
6327 else if (imp->match_c_string(" <= "))
6329 op = OPERATOR_LE;
6330 imp->advance(4);
6332 else if (imp->match_c_string(" > "))
6334 op = OPERATOR_GT;
6335 imp->advance(3);
6337 else if (imp->match_c_string(" >= "))
6339 op = OPERATOR_GE;
6340 imp->advance(4);
6342 else if (imp->match_c_string(" + "))
6344 op = OPERATOR_PLUS;
6345 imp->advance(3);
6347 else if (imp->match_c_string(" - "))
6349 op = OPERATOR_MINUS;
6350 imp->advance(3);
6352 else if (imp->match_c_string(" | "))
6354 op = OPERATOR_OR;
6355 imp->advance(3);
6357 else if (imp->match_c_string(" ^ "))
6359 op = OPERATOR_XOR;
6360 imp->advance(3);
6362 else if (imp->match_c_string(" * "))
6364 op = OPERATOR_MULT;
6365 imp->advance(3);
6367 else if (imp->match_c_string(" / "))
6369 op = OPERATOR_DIV;
6370 imp->advance(3);
6372 else if (imp->match_c_string(" % "))
6374 op = OPERATOR_MOD;
6375 imp->advance(3);
6377 else if (imp->match_c_string(" << "))
6379 op = OPERATOR_LSHIFT;
6380 imp->advance(4);
6382 else if (imp->match_c_string(" >> "))
6384 op = OPERATOR_RSHIFT;
6385 imp->advance(4);
6387 else if (imp->match_c_string(" & "))
6389 op = OPERATOR_AND;
6390 imp->advance(3);
6392 else if (imp->match_c_string(" &^ "))
6394 op = OPERATOR_BITCLEAR;
6395 imp->advance(4);
6397 else
6399 go_error_at(imp->location(), "unrecognized binary operator");
6400 return Expression::make_error(imp->location());
6403 Expression* right = Expression::import_expression(imp);
6405 imp->require_c_string(")");
6407 return Expression::make_binary(op, left, right, imp->location());
6410 // Dump ast representation of a binary expression.
6412 void
6413 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6415 ast_dump_context->ostream() << "(";
6416 ast_dump_context->dump_expression(this->left_);
6417 ast_dump_context->ostream() << " ";
6418 ast_dump_context->dump_operator(this->op_);
6419 ast_dump_context->ostream() << " ";
6420 ast_dump_context->dump_expression(this->right_);
6421 ast_dump_context->ostream() << ") ";
6424 // Make a binary expression.
6426 Expression*
6427 Expression::make_binary(Operator op, Expression* left, Expression* right,
6428 Location location)
6430 return new Binary_expression(op, left, right, location);
6433 // Implement a comparison.
6435 Bexpression*
6436 Expression::comparison(Translate_context* context, Type* result_type,
6437 Operator op, Expression* left, Expression* right,
6438 Location location)
6440 Type* left_type = left->type();
6441 Type* right_type = right->type();
6443 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6445 if (left_type->is_string_type() && right_type->is_string_type())
6447 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6449 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6450 left, right);
6451 right = Expression::make_boolean(true, location);
6453 else
6455 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6456 left, right);
6457 right = zexpr;
6460 else if ((left_type->interface_type() != NULL
6461 && right_type->interface_type() == NULL
6462 && !right_type->is_nil_type())
6463 || (left_type->interface_type() == NULL
6464 && !left_type->is_nil_type()
6465 && right_type->interface_type() != NULL))
6467 // Comparing an interface value to a non-interface value.
6468 if (left_type->interface_type() == NULL)
6470 std::swap(left_type, right_type);
6471 std::swap(left, right);
6474 // The right operand is not an interface. We need to take its
6475 // address if it is not a pointer.
6476 Expression* pointer_arg = NULL;
6477 if (right_type->points_to() != NULL)
6478 pointer_arg = right;
6479 else
6481 go_assert(right->is_addressable());
6482 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6483 location);
6486 Expression* descriptor =
6487 Expression::make_type_descriptor(right_type, location);
6488 left =
6489 Runtime::make_call((left_type->interface_type()->is_empty()
6490 ? Runtime::EFACEVALEQ
6491 : Runtime::IFACEVALEQ),
6492 location, 3, left, descriptor,
6493 pointer_arg);
6494 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6495 right = Expression::make_boolean(true, location);
6497 else if (left_type->interface_type() != NULL
6498 && right_type->interface_type() != NULL)
6500 Runtime::Function compare_function;
6501 if (left_type->interface_type()->is_empty()
6502 && right_type->interface_type()->is_empty())
6503 compare_function = Runtime::EFACEEQ;
6504 else if (!left_type->interface_type()->is_empty()
6505 && !right_type->interface_type()->is_empty())
6506 compare_function = Runtime::IFACEEQ;
6507 else
6509 if (left_type->interface_type()->is_empty())
6511 std::swap(left_type, right_type);
6512 std::swap(left, right);
6514 go_assert(!left_type->interface_type()->is_empty());
6515 go_assert(right_type->interface_type()->is_empty());
6516 compare_function = Runtime::IFACEEFACEEQ;
6519 left = Runtime::make_call(compare_function, location, 2, left, right);
6520 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6521 right = Expression::make_boolean(true, location);
6524 if (left_type->is_nil_type()
6525 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6527 std::swap(left_type, right_type);
6528 std::swap(left, right);
6531 if (right_type->is_nil_type())
6533 right = Expression::make_nil(location);
6534 if (left_type->array_type() != NULL
6535 && left_type->array_type()->length() == NULL)
6537 Array_type* at = left_type->array_type();
6538 bool is_lvalue = false;
6539 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6541 else if (left_type->interface_type() != NULL)
6543 // An interface is nil if the first field is nil.
6544 left = Expression::make_field_reference(left, 0, location);
6548 Bexpression* left_bexpr = left->get_backend(context);
6549 Bexpression* right_bexpr = right->get_backend(context);
6551 Gogo* gogo = context->gogo();
6552 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6553 right_bexpr, location);
6554 if (result_type != NULL)
6555 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6556 ret, location);
6557 return ret;
6560 // Class String_concat_expression.
6562 bool
6563 String_concat_expression::do_is_constant() const
6565 for (Expression_list::const_iterator pe = this->exprs_->begin();
6566 pe != this->exprs_->end();
6567 ++pe)
6569 if (!(*pe)->is_constant())
6570 return false;
6572 return true;
6575 bool
6576 String_concat_expression::do_is_static_initializer() const
6578 for (Expression_list::const_iterator pe = this->exprs_->begin();
6579 pe != this->exprs_->end();
6580 ++pe)
6582 if (!(*pe)->is_static_initializer())
6583 return false;
6585 return true;
6588 Type*
6589 String_concat_expression::do_type()
6591 Type* t = this->exprs_->front()->type();
6592 Expression_list::iterator pe = this->exprs_->begin();
6593 ++pe;
6594 for (; pe != this->exprs_->end(); ++pe)
6596 Type* t1;
6597 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6598 (*pe)->type(),
6599 &t1))
6600 return Type::make_error_type();
6601 t = t1;
6603 return t;
6606 void
6607 String_concat_expression::do_determine_type(const Type_context* context)
6609 Type_context subcontext(*context);
6610 for (Expression_list::iterator pe = this->exprs_->begin();
6611 pe != this->exprs_->end();
6612 ++pe)
6614 Type* t = (*pe)->type();
6615 if (!t->is_abstract())
6617 subcontext.type = t;
6618 break;
6621 if (subcontext.type == NULL)
6622 subcontext.type = this->exprs_->front()->type();
6623 for (Expression_list::iterator pe = this->exprs_->begin();
6624 pe != this->exprs_->end();
6625 ++pe)
6626 (*pe)->determine_type(&subcontext);
6629 void
6630 String_concat_expression::do_check_types(Gogo*)
6632 if (this->is_error_expression())
6633 return;
6634 Type* t = this->exprs_->front()->type();
6635 if (t->is_error())
6637 this->set_is_error();
6638 return;
6640 Expression_list::iterator pe = this->exprs_->begin();
6641 ++pe;
6642 for (; pe != this->exprs_->end(); ++pe)
6644 Type* t1 = (*pe)->type();
6645 if (!Type::are_compatible_for_binop(t, t1))
6647 this->report_error("incompatible types in binary expression");
6648 return;
6650 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6651 this->location()))
6653 this->set_is_error();
6654 return;
6659 Expression*
6660 String_concat_expression::do_flatten(Gogo*, Named_object*,
6661 Statement_inserter*)
6663 if (this->is_error_expression())
6664 return this;
6665 Location loc = this->location();
6666 Type* type = this->type();
6667 Expression* nil_arg = Expression::make_nil(loc);
6668 Expression* call;
6669 switch (this->exprs_->size())
6671 case 0: case 1:
6672 go_unreachable();
6674 case 2: case 3: case 4: case 5:
6676 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6677 NULL, loc);
6678 Array_type* arg_type = Type::make_array_type(type, len);
6679 arg_type->set_is_array_incomparable();
6680 Expression* arg =
6681 Expression::make_array_composite_literal(arg_type, this->exprs_,
6682 loc);
6683 Runtime::Function code;
6684 switch (this->exprs_->size())
6686 default:
6687 go_unreachable();
6688 case 2:
6689 code = Runtime::CONCATSTRING2;
6690 break;
6691 case 3:
6692 code = Runtime::CONCATSTRING3;
6693 break;
6694 case 4:
6695 code = Runtime::CONCATSTRING4;
6696 break;
6697 case 5:
6698 code = Runtime::CONCATSTRING5;
6699 break;
6701 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6703 break;
6705 default:
6707 Type* arg_type = Type::make_array_type(type, NULL);
6708 Slice_construction_expression* sce =
6709 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6710 loc);
6711 sce->set_storage_does_not_escape();
6712 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6713 sce);
6715 break;
6718 return Expression::make_cast(type, call, loc);
6721 void
6722 String_concat_expression::do_dump_expression(
6723 Ast_dump_context* ast_dump_context) const
6725 ast_dump_context->ostream() << "concat(";
6726 ast_dump_context->dump_expression_list(this->exprs_, false);
6727 ast_dump_context->ostream() << ")";
6730 Expression*
6731 Expression::make_string_concat(Expression_list* exprs)
6733 return new String_concat_expression(exprs);
6736 // Class Bound_method_expression.
6738 // Traversal.
6741 Bound_method_expression::do_traverse(Traverse* traverse)
6743 return Expression::traverse(&this->expr_, traverse);
6746 // Return the type of a bound method expression. The type of this
6747 // object is simply the type of the method with no receiver.
6749 Type*
6750 Bound_method_expression::do_type()
6752 Named_object* fn = this->method_->named_object();
6753 Function_type* fntype;
6754 if (fn->is_function())
6755 fntype = fn->func_value()->type();
6756 else if (fn->is_function_declaration())
6757 fntype = fn->func_declaration_value()->type();
6758 else
6759 return Type::make_error_type();
6760 return fntype->copy_without_receiver();
6763 // Determine the types of a method expression.
6765 void
6766 Bound_method_expression::do_determine_type(const Type_context*)
6768 Named_object* fn = this->method_->named_object();
6769 Function_type* fntype;
6770 if (fn->is_function())
6771 fntype = fn->func_value()->type();
6772 else if (fn->is_function_declaration())
6773 fntype = fn->func_declaration_value()->type();
6774 else
6775 fntype = NULL;
6776 if (fntype == NULL || !fntype->is_method())
6777 this->expr_->determine_type_no_context();
6778 else
6780 Type_context subcontext(fntype->receiver()->type(), false);
6781 this->expr_->determine_type(&subcontext);
6785 // Check the types of a method expression.
6787 void
6788 Bound_method_expression::do_check_types(Gogo*)
6790 Named_object* fn = this->method_->named_object();
6791 if (!fn->is_function() && !fn->is_function_declaration())
6793 this->report_error(_("object is not a method"));
6794 return;
6797 Function_type* fntype;
6798 if (fn->is_function())
6799 fntype = fn->func_value()->type();
6800 else if (fn->is_function_declaration())
6801 fntype = fn->func_declaration_value()->type();
6802 else
6803 go_unreachable();
6804 Type* rtype = fntype->receiver()->type()->deref();
6805 Type* etype = (this->expr_type_ != NULL
6806 ? this->expr_type_
6807 : this->expr_->type());
6808 etype = etype->deref();
6809 if (!Type::are_identical(rtype, etype, true, NULL))
6810 this->report_error(_("method type does not match object type"));
6813 // If a bound method expression is not simply called, then it is
6814 // represented as a closure. The closure will hold a single variable,
6815 // the receiver to pass to the method. The function will be a simple
6816 // thunk that pulls that value from the closure and calls the method
6817 // with the remaining arguments.
6819 // Because method values are not common, we don't build all thunks for
6820 // every methods, but instead only build them as we need them. In
6821 // particular, we even build them on demand for methods defined in
6822 // other packages.
6824 Bound_method_expression::Method_value_thunks
6825 Bound_method_expression::method_value_thunks;
6827 // Find or create the thunk for METHOD.
6829 Named_object*
6830 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6831 Named_object* fn)
6833 std::pair<Named_object*, Named_object*> val(fn, NULL);
6834 std::pair<Method_value_thunks::iterator, bool> ins =
6835 Bound_method_expression::method_value_thunks.insert(val);
6836 if (!ins.second)
6838 // We have seen this method before.
6839 go_assert(ins.first->second != NULL);
6840 return ins.first->second;
6843 Location loc = fn->location();
6845 Function_type* orig_fntype;
6846 if (fn->is_function())
6847 orig_fntype = fn->func_value()->type();
6848 else if (fn->is_function_declaration())
6849 orig_fntype = fn->func_declaration_value()->type();
6850 else
6851 orig_fntype = NULL;
6853 if (orig_fntype == NULL || !orig_fntype->is_method())
6855 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6856 return ins.first->second;
6859 Struct_field_list* sfl = new Struct_field_list();
6860 // The type here is wrong--it should be the C function type. But it
6861 // doesn't really matter.
6862 Type* vt = Type::make_pointer_type(Type::make_void_type());
6863 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6864 sfl->push_back(Struct_field(Typed_identifier("val.1",
6865 orig_fntype->receiver()->type(),
6866 loc)));
6867 Struct_type* st = Type::make_struct_type(sfl, loc);
6868 st->set_is_struct_incomparable();
6869 Type* closure_type = Type::make_pointer_type(st);
6871 Function_type* new_fntype = orig_fntype->copy_with_names();
6873 std::string thunk_name = Gogo::thunk_name();
6874 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6875 false, loc);
6877 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6878 cvar->set_is_used();
6879 cvar->set_is_closure();
6880 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6881 NULL, cvar);
6882 new_no->func_value()->set_closure_var(cp);
6884 gogo->start_block(loc);
6886 // Field 0 of the closure is the function code pointer, field 1 is
6887 // the value on which to invoke the method.
6888 Expression* arg = Expression::make_var_reference(cp, loc);
6889 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
6890 arg = Expression::make_field_reference(arg, 1, loc);
6892 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6894 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6895 Expression_list* args;
6896 if (orig_params == NULL || orig_params->empty())
6897 args = NULL;
6898 else
6900 const Typed_identifier_list* new_params = new_fntype->parameters();
6901 args = new Expression_list();
6902 for (Typed_identifier_list::const_iterator p = new_params->begin();
6903 p != new_params->end();
6904 ++p)
6906 Named_object* p_no = gogo->lookup(p->name(), NULL);
6907 go_assert(p_no != NULL
6908 && p_no->is_variable()
6909 && p_no->var_value()->is_parameter());
6910 args->push_back(Expression::make_var_reference(p_no, loc));
6914 Call_expression* call = Expression::make_call(bme, args,
6915 orig_fntype->is_varargs(),
6916 loc);
6917 call->set_varargs_are_lowered();
6919 Statement* s = Statement::make_return_from_call(call, loc);
6920 gogo->add_statement(s);
6921 Block* b = gogo->finish_block(loc);
6922 gogo->add_block(b, loc);
6923 gogo->lower_block(new_no, b);
6924 gogo->flatten_block(new_no, b);
6925 gogo->finish_function(loc);
6927 ins.first->second = new_no;
6928 return new_no;
6931 // Return an expression to check *REF for nil while dereferencing
6932 // according to FIELD_INDEXES. Update *REF to build up the field
6933 // reference. This is a static function so that we don't have to
6934 // worry about declaring Field_indexes in expressions.h.
6936 static Expression*
6937 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6938 Expression** ref)
6940 if (field_indexes == NULL)
6941 return Expression::make_boolean(false, loc);
6942 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6943 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6944 go_assert(stype != NULL
6945 && field_indexes->field_index < stype->field_count());
6946 if ((*ref)->type()->struct_type() == NULL)
6948 go_assert((*ref)->type()->points_to() != NULL);
6949 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6950 Expression::make_nil(loc),
6951 loc);
6952 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6953 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
6954 loc);
6955 go_assert((*ref)->type()->struct_type() == stype);
6957 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6958 loc);
6959 return cond;
6962 // Flatten a method value into a struct with nil checks. We can't do
6963 // this in the lowering phase, because if the method value is called
6964 // directly we don't need a thunk. That case will have been handled
6965 // by Call_expression::do_lower, so if we get here then we do need a
6966 // thunk.
6968 Expression*
6969 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6970 Statement_inserter* inserter)
6972 Location loc = this->location();
6974 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
6975 this->method_,
6976 this->function_);
6977 if (thunk->is_erroneous())
6979 go_assert(saw_errors());
6980 return Expression::make_error(loc);
6983 // Force the expression into a variable. This is only necessary if
6984 // we are going to do nil checks below, but it's easy enough to
6985 // always do it.
6986 Expression* expr = this->expr_;
6987 if (!expr->is_variable())
6989 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6990 inserter->insert(etemp);
6991 expr = Expression::make_temporary_reference(etemp, loc);
6994 // If the method expects a value, and we have a pointer, we need to
6995 // dereference the pointer.
6997 Named_object* fn = this->method_->named_object();
6998 Function_type *fntype;
6999 if (fn->is_function())
7000 fntype = fn->func_value()->type();
7001 else if (fn->is_function_declaration())
7002 fntype = fn->func_declaration_value()->type();
7003 else
7004 go_unreachable();
7006 Expression* val = expr;
7007 if (fntype->receiver()->type()->points_to() == NULL
7008 && val->type()->points_to() != NULL)
7009 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7011 // Note that we are ignoring this->expr_type_ here. The thunk will
7012 // expect a closure whose second field has type this->expr_type_ (if
7013 // that is not NULL). We are going to pass it a closure whose
7014 // second field has type this->expr_->type(). Since
7015 // this->expr_type_ is only not-NULL for pointer types, we can get
7016 // away with this.
7018 Struct_field_list* fields = new Struct_field_list();
7019 fields->push_back(Struct_field(Typed_identifier("fn.0",
7020 thunk->func_value()->type(),
7021 loc)));
7022 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
7023 Struct_type* st = Type::make_struct_type(fields, loc);
7024 st->set_is_struct_incomparable();
7026 Expression_list* vals = new Expression_list();
7027 vals->push_back(Expression::make_func_code_reference(thunk, loc));
7028 vals->push_back(val);
7030 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7032 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
7033 ret = Expression::make_heap_expression(ret, loc);
7034 else
7036 // When compiling the runtime, method closures do not escape.
7037 // When escape analysis becomes the default, and applies to
7038 // method closures, this should be changed to make it an error
7039 // if a method closure escapes.
7040 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
7041 inserter->insert(ctemp);
7042 ret = Expression::make_temporary_reference(ctemp, loc);
7043 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
7044 ret->unary_expression()->set_does_not_escape();
7047 // If necessary, check whether the expression or any embedded
7048 // pointers are nil.
7050 Expression* nil_check = NULL;
7051 if (this->method_->field_indexes() != NULL)
7053 Expression* ref = expr;
7054 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7055 expr = ref;
7058 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7060 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7061 Expression::make_nil(loc),
7062 loc);
7063 if (nil_check == NULL)
7064 nil_check = n;
7065 else
7066 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7069 if (nil_check != NULL)
7071 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7072 loc);
7073 // Fix the type of the conditional expression by pretending to
7074 // evaluate to RET either way through the conditional.
7075 crash = Expression::make_compound(crash, ret, loc);
7076 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7079 // RET is a pointer to a struct, but we want a function type.
7080 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7082 return ret;
7085 // Dump ast representation of a bound method expression.
7087 void
7088 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7089 const
7091 if (this->expr_type_ != NULL)
7092 ast_dump_context->ostream() << "(";
7093 ast_dump_context->dump_expression(this->expr_);
7094 if (this->expr_type_ != NULL)
7096 ast_dump_context->ostream() << ":";
7097 ast_dump_context->dump_type(this->expr_type_);
7098 ast_dump_context->ostream() << ")";
7101 ast_dump_context->ostream() << "." << this->function_->name();
7104 // Make a method expression.
7106 Bound_method_expression*
7107 Expression::make_bound_method(Expression* expr, const Method* method,
7108 Named_object* function, Location location)
7110 return new Bound_method_expression(expr, method, function, location);
7113 // Class Builtin_call_expression. This is used for a call to a
7114 // builtin function.
7116 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7117 Expression* fn,
7118 Expression_list* args,
7119 bool is_varargs,
7120 Location location)
7121 : Call_expression(fn, args, is_varargs, location),
7122 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7123 recover_arg_is_set_(false)
7125 Func_expression* fnexp = this->fn()->func_expression();
7126 if (fnexp == NULL)
7128 this->code_ = BUILTIN_INVALID;
7129 return;
7131 const std::string& name(fnexp->named_object()->name());
7132 if (name == "append")
7133 this->code_ = BUILTIN_APPEND;
7134 else if (name == "cap")
7135 this->code_ = BUILTIN_CAP;
7136 else if (name == "close")
7137 this->code_ = BUILTIN_CLOSE;
7138 else if (name == "complex")
7139 this->code_ = BUILTIN_COMPLEX;
7140 else if (name == "copy")
7141 this->code_ = BUILTIN_COPY;
7142 else if (name == "delete")
7143 this->code_ = BUILTIN_DELETE;
7144 else if (name == "imag")
7145 this->code_ = BUILTIN_IMAG;
7146 else if (name == "len")
7147 this->code_ = BUILTIN_LEN;
7148 else if (name == "make")
7149 this->code_ = BUILTIN_MAKE;
7150 else if (name == "new")
7151 this->code_ = BUILTIN_NEW;
7152 else if (name == "panic")
7153 this->code_ = BUILTIN_PANIC;
7154 else if (name == "print")
7155 this->code_ = BUILTIN_PRINT;
7156 else if (name == "println")
7157 this->code_ = BUILTIN_PRINTLN;
7158 else if (name == "real")
7159 this->code_ = BUILTIN_REAL;
7160 else if (name == "recover")
7161 this->code_ = BUILTIN_RECOVER;
7162 else if (name == "Alignof")
7163 this->code_ = BUILTIN_ALIGNOF;
7164 else if (name == "Offsetof")
7165 this->code_ = BUILTIN_OFFSETOF;
7166 else if (name == "Sizeof")
7167 this->code_ = BUILTIN_SIZEOF;
7168 else
7169 go_unreachable();
7172 // Return whether this is a call to recover. This is a virtual
7173 // function called from the parent class.
7175 bool
7176 Builtin_call_expression::do_is_recover_call() const
7178 if (this->classification() == EXPRESSION_ERROR)
7179 return false;
7180 return this->code_ == BUILTIN_RECOVER;
7183 // Set the argument for a call to recover.
7185 void
7186 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7188 const Expression_list* args = this->args();
7189 go_assert(args == NULL || args->empty());
7190 Expression_list* new_args = new Expression_list();
7191 new_args->push_back(arg);
7192 this->set_args(new_args);
7193 this->recover_arg_is_set_ = true;
7196 // Lower a builtin call expression. This turns new and make into
7197 // specific expressions. We also convert to a constant if we can.
7199 Expression*
7200 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7201 Statement_inserter* inserter, int)
7203 if (this->is_error_expression())
7204 return this;
7206 Location loc = this->location();
7208 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7210 this->report_error(_("invalid use of %<...%> with builtin function"));
7211 return Expression::make_error(loc);
7214 if (this->code_ == BUILTIN_OFFSETOF)
7216 Expression* arg = this->one_arg();
7218 if (arg->bound_method_expression() != NULL
7219 || arg->interface_field_reference_expression() != NULL)
7221 this->report_error(_("invalid use of method value as argument "
7222 "of Offsetof"));
7223 return this;
7226 Field_reference_expression* farg = arg->field_reference_expression();
7227 while (farg != NULL)
7229 if (!farg->implicit())
7230 break;
7231 // When the selector refers to an embedded field,
7232 // it must not be reached through pointer indirections.
7233 if (farg->expr()->deref() != farg->expr())
7235 this->report_error(_("argument of Offsetof implies "
7236 "indirection of an embedded field"));
7237 return this;
7239 // Go up until we reach the original base.
7240 farg = farg->expr()->field_reference_expression();
7244 if (this->is_constant())
7246 Numeric_constant nc;
7247 if (this->numeric_constant_value(&nc))
7248 return nc.expression(loc);
7251 switch (this->code_)
7253 default:
7254 break;
7256 case BUILTIN_NEW:
7258 const Expression_list* args = this->args();
7259 if (args == NULL || args->size() < 1)
7260 this->report_error(_("not enough arguments"));
7261 else if (args->size() > 1)
7262 this->report_error(_("too many arguments"));
7263 else
7265 Expression* arg = args->front();
7266 if (!arg->is_type_expression())
7268 go_error_at(arg->location(), "expected type");
7269 this->set_is_error();
7271 else
7272 return Expression::make_allocation(arg->type(), loc);
7275 break;
7277 case BUILTIN_MAKE:
7278 return this->lower_make(inserter);
7280 case BUILTIN_RECOVER:
7281 if (function != NULL)
7282 function->func_value()->set_calls_recover();
7283 else
7285 // Calling recover outside of a function always returns the
7286 // nil empty interface.
7287 Type* eface = Type::make_empty_interface_type(loc);
7288 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7290 break;
7292 case BUILTIN_DELETE:
7294 // Lower to a runtime function call.
7295 const Expression_list* args = this->args();
7296 if (args == NULL || args->size() < 2)
7297 this->report_error(_("not enough arguments"));
7298 else if (args->size() > 2)
7299 this->report_error(_("too many arguments"));
7300 else if (args->front()->type()->map_type() == NULL)
7301 this->report_error(_("argument 1 must be a map"));
7302 else
7304 // Since this function returns no value it must appear in
7305 // a statement by itself, so we don't have to worry about
7306 // order of evaluation of values around it. Evaluate the
7307 // map first to get order of evaluation right.
7308 Map_type* mt = args->front()->type()->map_type();
7309 Temporary_statement* map_temp =
7310 Statement::make_temporary(mt, args->front(), loc);
7311 inserter->insert(map_temp);
7313 Temporary_statement* key_temp =
7314 Statement::make_temporary(mt->key_type(), args->back(), loc);
7315 inserter->insert(key_temp);
7317 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7318 Expression* e2 = Expression::make_temporary_reference(map_temp,
7319 loc);
7320 Expression* e3 = Expression::make_temporary_reference(key_temp,
7321 loc);
7322 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7323 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7324 3, e1, e2, e3);
7327 break;
7329 case BUILTIN_PRINT:
7330 case BUILTIN_PRINTLN:
7331 // Force all the arguments into temporary variables, so that we
7332 // don't try to evaluate something while holding the print lock.
7333 if (this->args() == NULL)
7334 break;
7335 for (Expression_list::iterator pa = this->args()->begin();
7336 pa != this->args()->end();
7337 ++pa)
7339 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7341 Temporary_statement* temp =
7342 Statement::make_temporary(NULL, *pa, loc);
7343 inserter->insert(temp);
7344 *pa = Expression::make_temporary_reference(temp, loc);
7347 break;
7350 return this;
7353 // Flatten a builtin call expression. This turns the arguments of copy and
7354 // append into temporary expressions.
7356 Expression*
7357 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7358 Statement_inserter* inserter)
7360 Location loc = this->location();
7362 switch (this->code_)
7364 default:
7365 break;
7367 case BUILTIN_APPEND:
7368 return this->flatten_append(gogo, function, inserter);
7370 case BUILTIN_COPY:
7372 Type* at = this->args()->front()->type();
7373 for (Expression_list::iterator pa = this->args()->begin();
7374 pa != this->args()->end();
7375 ++pa)
7377 if ((*pa)->is_nil_expression())
7379 Expression* nil = Expression::make_nil(loc);
7380 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7381 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7383 if (!(*pa)->is_variable())
7385 Temporary_statement* temp =
7386 Statement::make_temporary(NULL, *pa, loc);
7387 inserter->insert(temp);
7388 *pa = Expression::make_temporary_reference(temp, loc);
7392 break;
7394 case BUILTIN_PANIC:
7395 for (Expression_list::iterator pa = this->args()->begin();
7396 pa != this->args()->end();
7397 ++pa)
7399 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7401 Temporary_statement* temp =
7402 Statement::make_temporary(NULL, *pa, loc);
7403 inserter->insert(temp);
7404 *pa = Expression::make_temporary_reference(temp, loc);
7407 break;
7409 case BUILTIN_LEN:
7410 case BUILTIN_CAP:
7412 Expression_list::iterator pa = this->args()->begin();
7413 if (!(*pa)->is_variable()
7414 && ((*pa)->type()->map_type() != NULL
7415 || (*pa)->type()->channel_type() != NULL))
7417 Temporary_statement* temp =
7418 Statement::make_temporary(NULL, *pa, loc);
7419 inserter->insert(temp);
7420 *pa = Expression::make_temporary_reference(temp, loc);
7423 break;
7426 return this;
7429 // Lower a make expression.
7431 Expression*
7432 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7434 Location loc = this->location();
7436 const Expression_list* args = this->args();
7437 if (args == NULL || args->size() < 1)
7439 this->report_error(_("not enough arguments"));
7440 return Expression::make_error(this->location());
7443 Expression_list::const_iterator parg = args->begin();
7445 Expression* first_arg = *parg;
7446 if (!first_arg->is_type_expression())
7448 go_error_at(first_arg->location(), "expected type");
7449 this->set_is_error();
7450 return Expression::make_error(this->location());
7452 Type* type = first_arg->type();
7454 if (!type->in_heap())
7455 go_error_at(first_arg->location(),
7456 "can't make slice of go:notinheap type");
7458 bool is_slice = false;
7459 bool is_map = false;
7460 bool is_chan = false;
7461 if (type->is_slice_type())
7462 is_slice = true;
7463 else if (type->map_type() != NULL)
7464 is_map = true;
7465 else if (type->channel_type() != NULL)
7466 is_chan = true;
7467 else
7469 this->report_error(_("invalid type for make function"));
7470 return Expression::make_error(this->location());
7473 Type_context int_context(Type::lookup_integer_type("int"), false);
7475 ++parg;
7476 Expression* len_arg;
7477 bool len_small = false;
7478 if (parg == args->end())
7480 if (is_slice)
7482 this->report_error(_("length required when allocating a slice"));
7483 return Expression::make_error(this->location());
7485 len_arg = Expression::make_integer_ul(0, NULL, loc);
7486 len_small = true;
7488 else
7490 len_arg = *parg;
7491 len_arg->determine_type(&int_context);
7492 if (!this->check_int_value(len_arg, true, &len_small))
7493 return Expression::make_error(this->location());
7494 ++parg;
7497 Expression* cap_arg = NULL;
7498 bool cap_small = false;
7499 Numeric_constant nclen;
7500 Numeric_constant nccap;
7501 unsigned long vlen;
7502 unsigned long vcap;
7503 if (is_slice && parg != args->end())
7505 cap_arg = *parg;
7506 cap_arg->determine_type(&int_context);
7507 if (!this->check_int_value(cap_arg, false, &cap_small))
7508 return Expression::make_error(this->location());
7510 if (len_arg->numeric_constant_value(&nclen)
7511 && cap_arg->numeric_constant_value(&nccap)
7512 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7513 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7514 && vlen > vcap)
7516 this->report_error(_("len larger than cap"));
7517 return Expression::make_error(this->location());
7520 ++parg;
7523 if (parg != args->end())
7525 this->report_error(_("too many arguments to make"));
7526 return Expression::make_error(this->location());
7529 Location type_loc = first_arg->location();
7531 Expression* call;
7532 if (is_slice)
7534 if (cap_arg == NULL)
7536 cap_small = len_small;
7537 if (len_arg->numeric_constant_value(&nclen)
7538 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID)
7539 cap_arg = Expression::make_integer_ul(vlen, len_arg->type(), loc);
7540 else
7542 Temporary_statement* temp = Statement::make_temporary(NULL,
7543 len_arg,
7544 loc);
7545 inserter->insert(temp);
7546 len_arg = Expression::make_temporary_reference(temp, loc);
7547 cap_arg = Expression::make_temporary_reference(temp, loc);
7551 Type* et = type->array_type()->element_type();
7552 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7553 Runtime::Function code = Runtime::MAKESLICE;
7554 if (!len_small || !cap_small)
7555 code = Runtime::MAKESLICE64;
7556 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7558 else if (is_map)
7560 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7561 if (!len_small)
7562 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7563 len_arg,
7564 Expression::make_nil(loc));
7565 else
7567 Numeric_constant nclen;
7568 unsigned long vlen;
7569 if (len_arg->numeric_constant_value(&nclen)
7570 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7571 && vlen <= Map_type::bucket_size)
7572 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7573 else
7574 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7575 len_arg,
7576 Expression::make_nil(loc));
7579 else if (is_chan)
7581 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7582 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7584 else
7585 go_unreachable();
7587 return Expression::make_unsafe_cast(type, call, loc);
7590 // Flatten a call to the predeclared append function. We do this in
7591 // the flatten phase, not the lowering phase, so that we run after
7592 // type checking and after order_evaluations.
7594 Expression*
7595 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7596 Statement_inserter* inserter)
7598 if (this->is_error_expression())
7599 return this;
7601 Location loc = this->location();
7603 const Expression_list* args = this->args();
7604 go_assert(args != NULL && !args->empty());
7606 Type* slice_type = args->front()->type();
7607 go_assert(slice_type->is_slice_type());
7608 Type* element_type = slice_type->array_type()->element_type();
7610 if (args->size() == 1)
7612 // append(s) evaluates to s.
7613 return args->front();
7616 Type* int_type = Type::lookup_integer_type("int");
7617 Type* uint_type = Type::lookup_integer_type("uint");
7619 // Implementing
7620 // append(s1, s2...)
7621 // or
7622 // append(s1, a1, a2, a3, ...)
7624 // s1tmp := s1
7625 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7626 loc);
7627 inserter->insert(s1tmp);
7629 // l1tmp := len(s1tmp)
7630 Named_object* lenfn = gogo->lookup_global("len");
7631 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7632 Expression_list* call_args = new Expression_list();
7633 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7634 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7635 gogo->lower_expression(function, inserter, &len);
7636 gogo->flatten_expression(function, inserter, &len);
7637 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7638 inserter->insert(l1tmp);
7640 Temporary_statement* s2tmp = NULL;
7641 Temporary_statement* l2tmp = NULL;
7642 Expression_list* add = NULL;
7643 Expression* len2;
7644 if (this->is_varargs())
7646 go_assert(args->size() == 2);
7648 // s2tmp := s2
7649 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7650 inserter->insert(s2tmp);
7652 // l2tmp := len(s2tmp)
7653 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7654 call_args = new Expression_list();
7655 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7656 len = Expression::make_call(lenref, call_args, false, loc);
7657 gogo->lower_expression(function, inserter, &len);
7658 gogo->flatten_expression(function, inserter, &len);
7659 l2tmp = Statement::make_temporary(int_type, len, loc);
7660 inserter->insert(l2tmp);
7662 // len2 = l2tmp
7663 len2 = Expression::make_temporary_reference(l2tmp, loc);
7665 else
7667 // We have to ensure that all the arguments are in variables
7668 // now, because otherwise if one of them is an index expression
7669 // into the current slice we could overwrite it before we fetch
7670 // it.
7671 add = new Expression_list();
7672 Expression_list::const_iterator pa = args->begin();
7673 for (++pa; pa != args->end(); ++pa)
7675 if ((*pa)->is_variable())
7676 add->push_back(*pa);
7677 else
7679 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7680 loc);
7681 inserter->insert(tmp);
7682 add->push_back(Expression::make_temporary_reference(tmp, loc));
7686 // len2 = len(add)
7687 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7690 // ntmp := l1tmp + len2
7691 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7692 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7693 gogo->lower_expression(function, inserter, &sum);
7694 gogo->flatten_expression(function, inserter, &sum);
7695 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7696 inserter->insert(ntmp);
7698 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7699 // growslice(type, s1tmp, ntmp) :
7700 // s1tmp[:ntmp]
7701 // Using uint here means that if the computation of ntmp overflowed,
7702 // we will call growslice which will panic.
7704 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7705 left = Expression::make_cast(uint_type, left, loc);
7707 Named_object* capfn = gogo->lookup_global("cap");
7708 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7709 call_args = new Expression_list();
7710 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7711 Expression* right = Expression::make_call(capref, call_args, false, loc);
7712 right = Expression::make_cast(uint_type, right, loc);
7714 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7716 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7717 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7718 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7719 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7720 a1, a2, a3);
7721 call = Expression::make_unsafe_cast(slice_type, call, loc);
7723 ref = Expression::make_temporary_reference(s1tmp, loc);
7724 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7725 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7726 // FIXME: Mark this index as not requiring bounds checks.
7727 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7729 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7731 gogo->lower_expression(function, inserter, &rhs);
7732 gogo->flatten_expression(function, inserter, &rhs);
7734 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7735 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7736 inserter->insert(assign);
7738 if (this->is_varargs())
7740 // copy(s1tmp[l1tmp:], s2tmp)
7741 a1 = Expression::make_temporary_reference(s1tmp, loc);
7742 ref = Expression::make_temporary_reference(l1tmp, loc);
7743 Expression* nil = Expression::make_nil(loc);
7744 // FIXME: Mark this index as not requiring bounds checks.
7745 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7747 a2 = Expression::make_temporary_reference(s2tmp, loc);
7749 Named_object* copyfn = gogo->lookup_global("copy");
7750 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7751 call_args = new Expression_list();
7752 call_args->push_back(a1);
7753 call_args->push_back(a2);
7754 call = Expression::make_call(copyref, call_args, false, loc);
7755 gogo->lower_expression(function, inserter, &call);
7756 gogo->flatten_expression(function, inserter, &call);
7757 inserter->insert(Statement::make_statement(call, false));
7759 else
7761 // For each argument:
7762 // s1tmp[l1tmp+i] = a
7763 unsigned long i = 0;
7764 for (Expression_list::const_iterator pa = add->begin();
7765 pa != add->end();
7766 ++pa, ++i)
7768 ref = Expression::make_temporary_reference(s1tmp, loc);
7769 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7770 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7771 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7772 // FIXME: Mark this index as not requiring bounds checks.
7773 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7774 gogo->lower_expression(function, inserter, &lhs);
7775 gogo->flatten_expression(function, inserter, &lhs);
7776 // The flatten pass runs after the write barrier pass, so we
7777 // need to insert a write barrier here if necessary.
7778 if (!gogo->assign_needs_write_barrier(lhs))
7779 assign = Statement::make_assignment(lhs, *pa, loc);
7780 else
7782 Function* f = function == NULL ? NULL : function->func_value();
7783 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7784 lhs, *pa, loc);
7786 inserter->insert(assign);
7790 return Expression::make_temporary_reference(s1tmp, loc);
7793 // Return whether an expression has an integer value. Report an error
7794 // if not. This is used when handling calls to the predeclared make
7795 // function. Set *SMALL if the value is known to fit in type "int".
7797 bool
7798 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7799 bool *small)
7801 *small = false;
7803 Numeric_constant nc;
7804 if (e->numeric_constant_value(&nc))
7806 unsigned long v;
7807 switch (nc.to_unsigned_long(&v))
7809 case Numeric_constant::NC_UL_VALID:
7810 break;
7811 case Numeric_constant::NC_UL_NOTINT:
7812 go_error_at(e->location(), "non-integer %s argument to make",
7813 is_length ? "len" : "cap");
7814 return false;
7815 case Numeric_constant::NC_UL_NEGATIVE:
7816 go_error_at(e->location(), "negative %s argument to make",
7817 is_length ? "len" : "cap");
7818 return false;
7819 case Numeric_constant::NC_UL_BIG:
7820 // We don't want to give a compile-time error for a 64-bit
7821 // value on a 32-bit target.
7822 break;
7825 mpz_t val;
7826 if (!nc.to_int(&val))
7827 go_unreachable();
7828 int bits = mpz_sizeinbase(val, 2);
7829 mpz_clear(val);
7830 Type* int_type = Type::lookup_integer_type("int");
7831 if (bits >= int_type->integer_type()->bits())
7833 go_error_at(e->location(), "%s argument too large for make",
7834 is_length ? "len" : "cap");
7835 return false;
7838 *small = true;
7839 return true;
7842 if (e->type()->integer_type() != NULL)
7844 int ebits = e->type()->integer_type()->bits();
7845 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7847 // We can treat ebits == intbits as small even for an unsigned
7848 // integer type, because we will convert the value to int and
7849 // then reject it in the runtime if it is negative.
7850 *small = ebits <= intbits;
7852 return true;
7855 go_error_at(e->location(), "non-integer %s argument to make",
7856 is_length ? "len" : "cap");
7857 return false;
7860 // Return the type of the real or imag functions, given the type of
7861 // the argument. We need to map complex64 to float32 and complex128
7862 // to float64, so it has to be done by name. This returns NULL if it
7863 // can't figure out the type.
7865 Type*
7866 Builtin_call_expression::real_imag_type(Type* arg_type)
7868 if (arg_type == NULL || arg_type->is_abstract())
7869 return NULL;
7870 Named_type* nt = arg_type->named_type();
7871 if (nt == NULL)
7872 return NULL;
7873 while (nt->real_type()->named_type() != NULL)
7874 nt = nt->real_type()->named_type();
7875 if (nt->name() == "complex64")
7876 return Type::lookup_float_type("float32");
7877 else if (nt->name() == "complex128")
7878 return Type::lookup_float_type("float64");
7879 else
7880 return NULL;
7883 // Return the type of the complex function, given the type of one of the
7884 // argments. Like real_imag_type, we have to map by name.
7886 Type*
7887 Builtin_call_expression::complex_type(Type* arg_type)
7889 if (arg_type == NULL || arg_type->is_abstract())
7890 return NULL;
7891 Named_type* nt = arg_type->named_type();
7892 if (nt == NULL)
7893 return NULL;
7894 while (nt->real_type()->named_type() != NULL)
7895 nt = nt->real_type()->named_type();
7896 if (nt->name() == "float32")
7897 return Type::lookup_complex_type("complex64");
7898 else if (nt->name() == "float64")
7899 return Type::lookup_complex_type("complex128");
7900 else
7901 return NULL;
7904 // Return a single argument, or NULL if there isn't one.
7906 Expression*
7907 Builtin_call_expression::one_arg() const
7909 const Expression_list* args = this->args();
7910 if (args == NULL || args->size() != 1)
7911 return NULL;
7912 return args->front();
7915 // A traversal class which looks for a call or receive expression.
7917 class Find_call_expression : public Traverse
7919 public:
7920 Find_call_expression()
7921 : Traverse(traverse_expressions),
7922 found_(false)
7926 expression(Expression**);
7928 bool
7929 found()
7930 { return this->found_; }
7932 private:
7933 bool found_;
7937 Find_call_expression::expression(Expression** pexpr)
7939 if ((*pexpr)->call_expression() != NULL
7940 || (*pexpr)->receive_expression() != NULL)
7942 this->found_ = true;
7943 return TRAVERSE_EXIT;
7945 return TRAVERSE_CONTINUE;
7948 // Return whether this is constant: len of a string constant, or len
7949 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7950 // unsafe.Alignof.
7952 bool
7953 Builtin_call_expression::do_is_constant() const
7955 if (this->is_error_expression())
7956 return true;
7957 switch (this->code_)
7959 case BUILTIN_LEN:
7960 case BUILTIN_CAP:
7962 if (this->seen_)
7963 return false;
7965 Expression* arg = this->one_arg();
7966 if (arg == NULL)
7967 return false;
7968 Type* arg_type = arg->type();
7970 if (arg_type->points_to() != NULL
7971 && arg_type->points_to()->array_type() != NULL
7972 && !arg_type->points_to()->is_slice_type())
7973 arg_type = arg_type->points_to();
7975 // The len and cap functions are only constant if there are no
7976 // function calls or channel operations in the arguments.
7977 // Otherwise we have to make the call.
7978 if (!arg->is_constant())
7980 Find_call_expression find_call;
7981 Expression::traverse(&arg, &find_call);
7982 if (find_call.found())
7983 return false;
7986 if (arg_type->array_type() != NULL
7987 && arg_type->array_type()->length() != NULL)
7988 return true;
7990 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7992 this->seen_ = true;
7993 bool ret = arg->is_constant();
7994 this->seen_ = false;
7995 return ret;
7998 break;
8000 case BUILTIN_SIZEOF:
8001 case BUILTIN_ALIGNOF:
8002 return this->one_arg() != NULL;
8004 case BUILTIN_OFFSETOF:
8006 Expression* arg = this->one_arg();
8007 if (arg == NULL)
8008 return false;
8009 return arg->field_reference_expression() != NULL;
8012 case BUILTIN_COMPLEX:
8014 const Expression_list* args = this->args();
8015 if (args != NULL && args->size() == 2)
8016 return args->front()->is_constant() && args->back()->is_constant();
8018 break;
8020 case BUILTIN_REAL:
8021 case BUILTIN_IMAG:
8023 Expression* arg = this->one_arg();
8024 return arg != NULL && arg->is_constant();
8027 default:
8028 break;
8031 return false;
8034 // Return a numeric constant if possible.
8036 bool
8037 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8039 if (this->code_ == BUILTIN_LEN
8040 || this->code_ == BUILTIN_CAP)
8042 Expression* arg = this->one_arg();
8043 if (arg == NULL)
8044 return false;
8045 Type* arg_type = arg->type();
8047 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8049 std::string sval;
8050 if (arg->string_constant_value(&sval))
8052 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8053 sval.length());
8054 return true;
8058 if (arg_type->points_to() != NULL
8059 && arg_type->points_to()->array_type() != NULL
8060 && !arg_type->points_to()->is_slice_type())
8061 arg_type = arg_type->points_to();
8063 if (arg_type->array_type() != NULL
8064 && arg_type->array_type()->length() != NULL)
8066 if (this->seen_)
8067 return false;
8068 Expression* e = arg_type->array_type()->length();
8069 this->seen_ = true;
8070 bool r = e->numeric_constant_value(nc);
8071 this->seen_ = false;
8072 if (r)
8074 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8075 this->location()))
8076 r = false;
8078 return r;
8081 else if (this->code_ == BUILTIN_SIZEOF
8082 || this->code_ == BUILTIN_ALIGNOF)
8084 Expression* arg = this->one_arg();
8085 if (arg == NULL)
8086 return false;
8087 Type* arg_type = arg->type();
8088 if (arg_type->is_error())
8089 return false;
8090 if (arg_type->is_abstract())
8091 return false;
8092 if (this->seen_)
8093 return false;
8095 int64_t ret;
8096 if (this->code_ == BUILTIN_SIZEOF)
8098 this->seen_ = true;
8099 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8100 this->seen_ = false;
8101 if (!ok)
8102 return false;
8104 else if (this->code_ == BUILTIN_ALIGNOF)
8106 bool ok;
8107 this->seen_ = true;
8108 if (arg->field_reference_expression() == NULL)
8109 ok = arg_type->backend_type_align(this->gogo_, &ret);
8110 else
8112 // Calling unsafe.Alignof(s.f) returns the alignment of
8113 // the type of f when it is used as a field in a struct.
8114 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8116 this->seen_ = false;
8117 if (!ok)
8118 return false;
8120 else
8121 go_unreachable();
8123 mpz_t zval;
8124 set_mpz_from_int64(&zval, ret);
8125 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8126 mpz_clear(zval);
8127 return true;
8129 else if (this->code_ == BUILTIN_OFFSETOF)
8131 Expression* arg = this->one_arg();
8132 if (arg == NULL)
8133 return false;
8134 Field_reference_expression* farg = arg->field_reference_expression();
8135 if (farg == NULL)
8136 return false;
8137 if (this->seen_)
8138 return false;
8140 int64_t total_offset = 0;
8141 while (true)
8143 Expression* struct_expr = farg->expr();
8144 Type* st = struct_expr->type();
8145 if (st->struct_type() == NULL)
8146 return false;
8147 if (st->named_type() != NULL)
8148 st->named_type()->convert(this->gogo_);
8149 int64_t offset;
8150 this->seen_ = true;
8151 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8152 farg->field_index(),
8153 &offset);
8154 this->seen_ = false;
8155 if (!ok)
8156 return false;
8157 total_offset += offset;
8158 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8160 // Go up until we reach the original base.
8161 farg = struct_expr->field_reference_expression();
8162 continue;
8164 break;
8166 mpz_t zval;
8167 set_mpz_from_int64(&zval, total_offset);
8168 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8169 mpz_clear(zval);
8170 return true;
8172 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8174 Expression* arg = this->one_arg();
8175 if (arg == NULL)
8176 return false;
8178 Numeric_constant argnc;
8179 if (!arg->numeric_constant_value(&argnc))
8180 return false;
8182 mpc_t val;
8183 if (!argnc.to_complex(&val))
8184 return false;
8186 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8187 if (this->code_ == BUILTIN_REAL)
8188 nc->set_float(type, mpc_realref(val));
8189 else
8190 nc->set_float(type, mpc_imagref(val));
8191 mpc_clear(val);
8192 return true;
8194 else if (this->code_ == BUILTIN_COMPLEX)
8196 const Expression_list* args = this->args();
8197 if (args == NULL || args->size() != 2)
8198 return false;
8200 Numeric_constant rnc;
8201 if (!args->front()->numeric_constant_value(&rnc))
8202 return false;
8203 Numeric_constant inc;
8204 if (!args->back()->numeric_constant_value(&inc))
8205 return false;
8207 if (rnc.type() != NULL
8208 && !rnc.type()->is_abstract()
8209 && inc.type() != NULL
8210 && !inc.type()->is_abstract()
8211 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8212 return false;
8214 mpfr_t r;
8215 if (!rnc.to_float(&r))
8216 return false;
8217 mpfr_t i;
8218 if (!inc.to_float(&i))
8220 mpfr_clear(r);
8221 return false;
8224 Type* arg_type = rnc.type();
8225 if (arg_type == NULL || arg_type->is_abstract())
8226 arg_type = inc.type();
8228 mpc_t val;
8229 mpc_init2(val, mpc_precision);
8230 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8231 mpfr_clear(r);
8232 mpfr_clear(i);
8234 Type* type = Builtin_call_expression::complex_type(arg_type);
8235 nc->set_complex(type, val);
8237 mpc_clear(val);
8239 return true;
8242 return false;
8245 // Give an error if we are discarding the value of an expression which
8246 // should not normally be discarded. We don't give an error for
8247 // discarding the value of an ordinary function call, but we do for
8248 // builtin functions, purely for consistency with the gc compiler.
8250 bool
8251 Builtin_call_expression::do_discarding_value()
8253 switch (this->code_)
8255 case BUILTIN_INVALID:
8256 default:
8257 go_unreachable();
8259 case BUILTIN_APPEND:
8260 case BUILTIN_CAP:
8261 case BUILTIN_COMPLEX:
8262 case BUILTIN_IMAG:
8263 case BUILTIN_LEN:
8264 case BUILTIN_MAKE:
8265 case BUILTIN_NEW:
8266 case BUILTIN_REAL:
8267 case BUILTIN_ALIGNOF:
8268 case BUILTIN_OFFSETOF:
8269 case BUILTIN_SIZEOF:
8270 this->unused_value_error();
8271 return false;
8273 case BUILTIN_CLOSE:
8274 case BUILTIN_COPY:
8275 case BUILTIN_DELETE:
8276 case BUILTIN_PANIC:
8277 case BUILTIN_PRINT:
8278 case BUILTIN_PRINTLN:
8279 case BUILTIN_RECOVER:
8280 return true;
8284 // Return the type.
8286 Type*
8287 Builtin_call_expression::do_type()
8289 if (this->is_error_expression())
8290 return Type::make_error_type();
8291 switch (this->code_)
8293 case BUILTIN_INVALID:
8294 default:
8295 return Type::make_error_type();
8297 case BUILTIN_NEW:
8298 case BUILTIN_MAKE:
8300 const Expression_list* args = this->args();
8301 if (args == NULL || args->empty())
8302 return Type::make_error_type();
8303 return Type::make_pointer_type(args->front()->type());
8306 case BUILTIN_CAP:
8307 case BUILTIN_COPY:
8308 case BUILTIN_LEN:
8309 return Type::lookup_integer_type("int");
8311 case BUILTIN_ALIGNOF:
8312 case BUILTIN_OFFSETOF:
8313 case BUILTIN_SIZEOF:
8314 return Type::lookup_integer_type("uintptr");
8316 case BUILTIN_CLOSE:
8317 case BUILTIN_DELETE:
8318 case BUILTIN_PANIC:
8319 case BUILTIN_PRINT:
8320 case BUILTIN_PRINTLN:
8321 return Type::make_void_type();
8323 case BUILTIN_RECOVER:
8324 return Type::make_empty_interface_type(Linemap::predeclared_location());
8326 case BUILTIN_APPEND:
8328 const Expression_list* args = this->args();
8329 if (args == NULL || args->empty())
8330 return Type::make_error_type();
8331 Type *ret = args->front()->type();
8332 if (!ret->is_slice_type())
8333 return Type::make_error_type();
8334 return ret;
8337 case BUILTIN_REAL:
8338 case BUILTIN_IMAG:
8340 Expression* arg = this->one_arg();
8341 if (arg == NULL)
8342 return Type::make_error_type();
8343 Type* t = arg->type();
8344 if (t->is_abstract())
8345 t = t->make_non_abstract_type();
8346 t = Builtin_call_expression::real_imag_type(t);
8347 if (t == NULL)
8348 t = Type::make_error_type();
8349 return t;
8352 case BUILTIN_COMPLEX:
8354 const Expression_list* args = this->args();
8355 if (args == NULL || args->size() != 2)
8356 return Type::make_error_type();
8357 Type* t = args->front()->type();
8358 if (t->is_abstract())
8360 t = args->back()->type();
8361 if (t->is_abstract())
8362 t = t->make_non_abstract_type();
8364 t = Builtin_call_expression::complex_type(t);
8365 if (t == NULL)
8366 t = Type::make_error_type();
8367 return t;
8372 // Determine the type.
8374 void
8375 Builtin_call_expression::do_determine_type(const Type_context* context)
8377 if (!this->determining_types())
8378 return;
8380 this->fn()->determine_type_no_context();
8382 const Expression_list* args = this->args();
8384 bool is_print;
8385 Type* arg_type = NULL;
8386 Type* trailing_arg_types = NULL;
8387 switch (this->code_)
8389 case BUILTIN_PRINT:
8390 case BUILTIN_PRINTLN:
8391 // Do not force a large integer constant to "int".
8392 is_print = true;
8393 break;
8395 case BUILTIN_REAL:
8396 case BUILTIN_IMAG:
8397 arg_type = Builtin_call_expression::complex_type(context->type);
8398 if (arg_type == NULL)
8399 arg_type = Type::lookup_complex_type("complex128");
8400 is_print = false;
8401 break;
8403 case BUILTIN_COMPLEX:
8405 // For the complex function the type of one operand can
8406 // determine the type of the other, as in a binary expression.
8407 arg_type = Builtin_call_expression::real_imag_type(context->type);
8408 if (arg_type == NULL)
8409 arg_type = Type::lookup_float_type("float64");
8410 if (args != NULL && args->size() == 2)
8412 Type* t1 = args->front()->type();
8413 Type* t2 = args->back()->type();
8414 if (!t1->is_abstract())
8415 arg_type = t1;
8416 else if (!t2->is_abstract())
8417 arg_type = t2;
8419 is_print = false;
8421 break;
8423 case BUILTIN_APPEND:
8424 if (!this->is_varargs()
8425 && args != NULL
8426 && !args->empty()
8427 && args->front()->type()->is_slice_type())
8428 trailing_arg_types =
8429 args->front()->type()->array_type()->element_type();
8430 is_print = false;
8431 break;
8433 default:
8434 is_print = false;
8435 break;
8438 if (args != NULL)
8440 for (Expression_list::const_iterator pa = args->begin();
8441 pa != args->end();
8442 ++pa)
8444 Type_context subcontext;
8445 subcontext.type = arg_type;
8447 if (is_print)
8449 // We want to print large constants, we so can't just
8450 // use the appropriate nonabstract type. Use uint64 for
8451 // an integer if we know it is nonnegative, otherwise
8452 // use int64 for a integer, otherwise use float64 for a
8453 // float or complex128 for a complex.
8454 Type* want_type = NULL;
8455 Type* atype = (*pa)->type();
8456 if (atype->is_abstract())
8458 if (atype->integer_type() != NULL)
8460 Numeric_constant nc;
8461 if (this->numeric_constant_value(&nc))
8463 mpz_t val;
8464 if (nc.to_int(&val))
8466 if (mpz_sgn(val) >= 0)
8467 want_type = Type::lookup_integer_type("uint64");
8468 mpz_clear(val);
8471 if (want_type == NULL)
8472 want_type = Type::lookup_integer_type("int64");
8474 else if (atype->float_type() != NULL)
8475 want_type = Type::lookup_float_type("float64");
8476 else if (atype->complex_type() != NULL)
8477 want_type = Type::lookup_complex_type("complex128");
8478 else if (atype->is_abstract_string_type())
8479 want_type = Type::lookup_string_type();
8480 else if (atype->is_abstract_boolean_type())
8481 want_type = Type::lookup_bool_type();
8482 else
8483 go_unreachable();
8484 subcontext.type = want_type;
8488 (*pa)->determine_type(&subcontext);
8490 if (trailing_arg_types != NULL)
8492 arg_type = trailing_arg_types;
8493 trailing_arg_types = NULL;
8499 // If there is exactly one argument, return true. Otherwise give an
8500 // error message and return false.
8502 bool
8503 Builtin_call_expression::check_one_arg()
8505 const Expression_list* args = this->args();
8506 if (args == NULL || args->size() < 1)
8508 this->report_error(_("not enough arguments"));
8509 return false;
8511 else if (args->size() > 1)
8513 this->report_error(_("too many arguments"));
8514 return false;
8516 if (args->front()->is_error_expression()
8517 || args->front()->type()->is_error())
8519 this->set_is_error();
8520 return false;
8522 return true;
8525 // Check argument types for a builtin function.
8527 void
8528 Builtin_call_expression::do_check_types(Gogo*)
8530 if (this->is_error_expression())
8531 return;
8532 switch (this->code_)
8534 case BUILTIN_INVALID:
8535 case BUILTIN_NEW:
8536 case BUILTIN_MAKE:
8537 case BUILTIN_DELETE:
8538 return;
8540 case BUILTIN_LEN:
8541 case BUILTIN_CAP:
8543 // The single argument may be either a string or an array or a
8544 // map or a channel, or a pointer to a closed array.
8545 if (this->check_one_arg())
8547 Type* arg_type = this->one_arg()->type();
8548 if (arg_type->points_to() != NULL
8549 && arg_type->points_to()->array_type() != NULL
8550 && !arg_type->points_to()->is_slice_type())
8551 arg_type = arg_type->points_to();
8552 if (this->code_ == BUILTIN_CAP)
8554 if (!arg_type->is_error()
8555 && arg_type->array_type() == NULL
8556 && arg_type->channel_type() == NULL)
8557 this->report_error(_("argument must be array or slice "
8558 "or channel"));
8560 else
8562 if (!arg_type->is_error()
8563 && !arg_type->is_string_type()
8564 && arg_type->array_type() == NULL
8565 && arg_type->map_type() == NULL
8566 && arg_type->channel_type() == NULL)
8567 this->report_error(_("argument must be string or "
8568 "array or slice or map or channel"));
8572 break;
8574 case BUILTIN_PRINT:
8575 case BUILTIN_PRINTLN:
8577 const Expression_list* args = this->args();
8578 if (args == NULL)
8580 if (this->code_ == BUILTIN_PRINT)
8581 go_warning_at(this->location(), 0,
8582 "no arguments for builtin function %<%s%>",
8583 (this->code_ == BUILTIN_PRINT
8584 ? "print"
8585 : "println"));
8587 else
8589 for (Expression_list::const_iterator p = args->begin();
8590 p != args->end();
8591 ++p)
8593 Type* type = (*p)->type();
8594 if (type->is_error()
8595 || type->is_string_type()
8596 || type->integer_type() != NULL
8597 || type->float_type() != NULL
8598 || type->complex_type() != NULL
8599 || type->is_boolean_type()
8600 || type->points_to() != NULL
8601 || type->interface_type() != NULL
8602 || type->channel_type() != NULL
8603 || type->map_type() != NULL
8604 || type->function_type() != NULL
8605 || type->is_slice_type())
8607 else if ((*p)->is_type_expression())
8609 // If this is a type expression it's going to give
8610 // an error anyhow, so we don't need one here.
8612 else
8613 this->report_error(_("unsupported argument type to "
8614 "builtin function"));
8618 break;
8620 case BUILTIN_CLOSE:
8621 if (this->check_one_arg())
8623 if (this->one_arg()->type()->channel_type() == NULL)
8624 this->report_error(_("argument must be channel"));
8625 else if (!this->one_arg()->type()->channel_type()->may_send())
8626 this->report_error(_("cannot close receive-only channel"));
8628 break;
8630 case BUILTIN_PANIC:
8631 case BUILTIN_SIZEOF:
8632 case BUILTIN_ALIGNOF:
8633 this->check_one_arg();
8634 break;
8636 case BUILTIN_RECOVER:
8637 if (this->args() != NULL
8638 && !this->args()->empty()
8639 && !this->recover_arg_is_set_)
8640 this->report_error(_("too many arguments"));
8641 break;
8643 case BUILTIN_OFFSETOF:
8644 if (this->check_one_arg())
8646 Expression* arg = this->one_arg();
8647 if (arg->field_reference_expression() == NULL)
8648 this->report_error(_("argument must be a field reference"));
8650 break;
8652 case BUILTIN_COPY:
8654 const Expression_list* args = this->args();
8655 if (args == NULL || args->size() < 2)
8657 this->report_error(_("not enough arguments"));
8658 break;
8660 else if (args->size() > 2)
8662 this->report_error(_("too many arguments"));
8663 break;
8665 Type* arg1_type = args->front()->type();
8666 Type* arg2_type = args->back()->type();
8667 if (arg1_type->is_error() || arg2_type->is_error())
8669 this->set_is_error();
8670 break;
8673 Type* e1;
8674 if (arg1_type->is_slice_type())
8675 e1 = arg1_type->array_type()->element_type();
8676 else
8678 this->report_error(_("left argument must be a slice"));
8679 break;
8682 if (arg2_type->is_slice_type())
8684 Type* e2 = arg2_type->array_type()->element_type();
8685 if (!Type::are_identical(e1, e2, true, NULL))
8686 this->report_error(_("element types must be the same"));
8688 else if (arg2_type->is_string_type())
8690 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8691 this->report_error(_("first argument must be []byte"));
8693 else
8694 this->report_error(_("second argument must be slice or string"));
8696 break;
8698 case BUILTIN_APPEND:
8700 const Expression_list* args = this->args();
8701 if (args == NULL || args->empty())
8703 this->report_error(_("not enough arguments"));
8704 break;
8707 Type* slice_type = args->front()->type();
8708 if (!slice_type->is_slice_type())
8710 if (slice_type->is_error_type())
8711 break;
8712 if (slice_type->is_nil_type())
8713 go_error_at(args->front()->location(), "use of untyped nil");
8714 else
8715 go_error_at(args->front()->location(),
8716 "argument 1 must be a slice");
8717 this->set_is_error();
8718 break;
8721 Type* element_type = slice_type->array_type()->element_type();
8722 if (!element_type->in_heap())
8723 go_error_at(args->front()->location(),
8724 "can't append to slice of go:notinheap type");
8725 if (this->is_varargs())
8727 if (!args->back()->type()->is_slice_type()
8728 && !args->back()->type()->is_string_type())
8730 go_error_at(args->back()->location(),
8731 "invalid use of %<...%> with non-slice/non-string");
8732 this->set_is_error();
8733 break;
8736 if (args->size() < 2)
8738 this->report_error(_("not enough arguments"));
8739 break;
8741 if (args->size() > 2)
8743 this->report_error(_("too many arguments"));
8744 break;
8747 if (args->back()->type()->is_string_type()
8748 && element_type->integer_type() != NULL
8749 && element_type->integer_type()->is_byte())
8751 // Permit append(s1, s2...) when s1 is a slice of
8752 // bytes and s2 is a string type.
8754 else
8756 // We have to test for assignment compatibility to a
8757 // slice of the element type, which is not necessarily
8758 // the same as the type of the first argument: the
8759 // first argument might have a named type.
8760 Type* check_type = Type::make_array_type(element_type, NULL);
8761 std::string reason;
8762 if (!Type::are_assignable(check_type, args->back()->type(),
8763 &reason))
8765 if (reason.empty())
8766 go_error_at(args->back()->location(),
8767 "argument 2 has invalid type");
8768 else
8769 go_error_at(args->back()->location(),
8770 "argument 2 has invalid type (%s)",
8771 reason.c_str());
8772 this->set_is_error();
8773 break;
8777 else
8779 Expression_list::const_iterator pa = args->begin();
8780 int i = 2;
8781 for (++pa; pa != args->end(); ++pa, ++i)
8783 std::string reason;
8784 if (!Type::are_assignable(element_type, (*pa)->type(),
8785 &reason))
8787 if (reason.empty())
8788 go_error_at((*pa)->location(),
8789 "argument %d has incompatible type", i);
8790 else
8791 go_error_at((*pa)->location(),
8792 "argument %d has incompatible type (%s)",
8793 i, reason.c_str());
8794 this->set_is_error();
8799 break;
8801 case BUILTIN_REAL:
8802 case BUILTIN_IMAG:
8803 if (this->check_one_arg())
8805 if (this->one_arg()->type()->complex_type() == NULL)
8806 this->report_error(_("argument must have complex type"));
8808 break;
8810 case BUILTIN_COMPLEX:
8812 const Expression_list* args = this->args();
8813 if (args == NULL || args->size() < 2)
8814 this->report_error(_("not enough arguments"));
8815 else if (args->size() > 2)
8816 this->report_error(_("too many arguments"));
8817 else if (args->front()->is_error_expression()
8818 || args->front()->type()->is_error()
8819 || args->back()->is_error_expression()
8820 || args->back()->type()->is_error())
8821 this->set_is_error();
8822 else if (!Type::are_identical(args->front()->type(),
8823 args->back()->type(), true, NULL))
8824 this->report_error(_("complex arguments must have identical types"));
8825 else if (args->front()->type()->float_type() == NULL)
8826 this->report_error(_("complex arguments must have "
8827 "floating-point type"));
8829 break;
8831 default:
8832 go_unreachable();
8836 Expression*
8837 Builtin_call_expression::do_copy()
8839 Call_expression* bce =
8840 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8841 (this->args() == NULL
8842 ? NULL
8843 : this->args()->copy()),
8844 this->is_varargs(),
8845 this->location());
8847 if (this->varargs_are_lowered())
8848 bce->set_varargs_are_lowered();
8849 return bce;
8852 // Return the backend representation for a builtin function.
8854 Bexpression*
8855 Builtin_call_expression::do_get_backend(Translate_context* context)
8857 Gogo* gogo = context->gogo();
8858 Location location = this->location();
8860 if (this->is_erroneous_call())
8862 go_assert(saw_errors());
8863 return gogo->backend()->error_expression();
8866 switch (this->code_)
8868 case BUILTIN_INVALID:
8869 case BUILTIN_NEW:
8870 case BUILTIN_MAKE:
8871 go_unreachable();
8873 case BUILTIN_LEN:
8874 case BUILTIN_CAP:
8876 const Expression_list* args = this->args();
8877 go_assert(args != NULL && args->size() == 1);
8878 Expression* arg = args->front();
8879 Type* arg_type = arg->type();
8881 if (this->seen_)
8883 go_assert(saw_errors());
8884 return context->backend()->error_expression();
8886 this->seen_ = true;
8887 this->seen_ = false;
8888 if (arg_type->points_to() != NULL)
8890 arg_type = arg_type->points_to();
8891 go_assert(arg_type->array_type() != NULL
8892 && !arg_type->is_slice_type());
8893 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
8894 location);
8897 Type* int_type = Type::lookup_integer_type("int");
8898 Expression* val;
8899 if (this->code_ == BUILTIN_LEN)
8901 if (arg_type->is_string_type())
8902 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8903 location);
8904 else if (arg_type->array_type() != NULL)
8906 if (this->seen_)
8908 go_assert(saw_errors());
8909 return context->backend()->error_expression();
8911 this->seen_ = true;
8912 val = arg_type->array_type()->get_length(gogo, arg);
8913 this->seen_ = false;
8915 else if (arg_type->map_type() != NULL
8916 || arg_type->channel_type() != NULL)
8918 // The first field is the length. If the pointer is
8919 // nil, the length is zero.
8920 Type* pint_type = Type::make_pointer_type(int_type);
8921 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8922 Expression* nil = Expression::make_nil(location);
8923 nil = Expression::make_cast(pint_type, nil, location);
8924 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8925 arg, nil, location);
8926 Expression* zero = Expression::make_integer_ul(0, int_type,
8927 location);
8928 Expression* indir =
8929 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
8930 location);
8931 val = Expression::make_conditional(cmp, zero, indir, location);
8933 else
8934 go_unreachable();
8936 else
8938 if (arg_type->array_type() != NULL)
8940 if (this->seen_)
8942 go_assert(saw_errors());
8943 return context->backend()->error_expression();
8945 this->seen_ = true;
8946 val = arg_type->array_type()->get_capacity(gogo, arg);
8947 this->seen_ = false;
8949 else if (arg_type->channel_type() != NULL)
8951 // The second field is the capacity. If the pointer
8952 // is nil, the capacity is zero.
8953 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8954 Type* pint_type = Type::make_pointer_type(int_type);
8955 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8956 arg,
8957 location);
8958 int off = int_type->integer_type()->bits() / 8;
8959 Expression* eoff = Expression::make_integer_ul(off,
8960 uintptr_type,
8961 location);
8962 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8963 location);
8964 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8965 Expression* nil = Expression::make_nil(location);
8966 nil = Expression::make_cast(pint_type, nil, location);
8967 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8968 arg, nil, location);
8969 Expression* zero = Expression::make_integer_ul(0, int_type,
8970 location);
8971 Expression* indir =
8972 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
8973 location);
8974 val = Expression::make_conditional(cmp, zero, indir, location);
8976 else
8977 go_unreachable();
8980 return Expression::make_cast(int_type, val,
8981 location)->get_backend(context);
8984 case BUILTIN_PRINT:
8985 case BUILTIN_PRINTLN:
8987 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8989 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
8990 location, 0);
8992 const Expression_list* call_args = this->args();
8993 if (call_args != NULL)
8995 for (Expression_list::const_iterator p = call_args->begin();
8996 p != call_args->end();
8997 ++p)
8999 if (is_ln && p != call_args->begin())
9001 Expression* print_space =
9002 Runtime::make_call(Runtime::PRINTSP, location, 0);
9004 print_stmts =
9005 Expression::make_compound(print_stmts, print_space,
9006 location);
9009 Expression* arg = *p;
9010 Type* type = arg->type();
9011 Runtime::Function code;
9012 if (type->is_string_type())
9013 code = Runtime::PRINTSTRING;
9014 else if (type->integer_type() != NULL
9015 && type->integer_type()->is_unsigned())
9017 Type* itype = Type::lookup_integer_type("uint64");
9018 arg = Expression::make_cast(itype, arg, location);
9019 code = Runtime::PRINTUINT;
9021 else if (type->integer_type() != NULL)
9023 Type* itype = Type::lookup_integer_type("int64");
9024 arg = Expression::make_cast(itype, arg, location);
9025 code = Runtime::PRINTINT;
9027 else if (type->float_type() != NULL)
9029 Type* dtype = Type::lookup_float_type("float64");
9030 arg = Expression::make_cast(dtype, arg, location);
9031 code = Runtime::PRINTFLOAT;
9033 else if (type->complex_type() != NULL)
9035 Type* ctype = Type::lookup_complex_type("complex128");
9036 arg = Expression::make_cast(ctype, arg, location);
9037 code = Runtime::PRINTCOMPLEX;
9039 else if (type->is_boolean_type())
9040 code = Runtime::PRINTBOOL;
9041 else if (type->points_to() != NULL
9042 || type->channel_type() != NULL
9043 || type->map_type() != NULL
9044 || type->function_type() != NULL)
9046 arg = Expression::make_cast(type, arg, location);
9047 code = Runtime::PRINTPOINTER;
9049 else if (type->interface_type() != NULL)
9051 if (type->interface_type()->is_empty())
9052 code = Runtime::PRINTEFACE;
9053 else
9054 code = Runtime::PRINTIFACE;
9056 else if (type->is_slice_type())
9057 code = Runtime::PRINTSLICE;
9058 else
9060 go_assert(saw_errors());
9061 return context->backend()->error_expression();
9064 Expression* call = Runtime::make_call(code, location, 1, arg);
9065 print_stmts = Expression::make_compound(print_stmts, call,
9066 location);
9070 if (is_ln)
9072 Expression* print_nl =
9073 Runtime::make_call(Runtime::PRINTNL, location, 0);
9074 print_stmts = Expression::make_compound(print_stmts, print_nl,
9075 location);
9078 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9079 location, 0);
9080 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9082 return print_stmts->get_backend(context);
9085 case BUILTIN_PANIC:
9087 const Expression_list* args = this->args();
9088 go_assert(args != NULL && args->size() == 1);
9089 Expression* arg = args->front();
9090 Type *empty =
9091 Type::make_empty_interface_type(Linemap::predeclared_location());
9092 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9094 Expression* panic =
9095 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9096 return panic->get_backend(context);
9099 case BUILTIN_RECOVER:
9101 // The argument is set when building recover thunks. It's a
9102 // boolean value which is true if we can recover a value now.
9103 const Expression_list* args = this->args();
9104 go_assert(args != NULL && args->size() == 1);
9105 Expression* arg = args->front();
9106 Type *empty =
9107 Type::make_empty_interface_type(Linemap::predeclared_location());
9109 Expression* nil = Expression::make_nil(location);
9110 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9112 // We need to handle a deferred call to recover specially,
9113 // because it changes whether it can recover a panic or not.
9114 // See test7 in test/recover1.go.
9115 Expression* recover = Runtime::make_call((this->is_deferred()
9116 ? Runtime::DEFERREDRECOVER
9117 : Runtime::GORECOVER),
9118 location, 0);
9119 Expression* cond =
9120 Expression::make_conditional(arg, recover, nil, location);
9121 return cond->get_backend(context);
9124 case BUILTIN_CLOSE:
9126 const Expression_list* args = this->args();
9127 go_assert(args != NULL && args->size() == 1);
9128 Expression* arg = args->front();
9129 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9130 1, arg);
9131 return close->get_backend(context);
9134 case BUILTIN_SIZEOF:
9135 case BUILTIN_OFFSETOF:
9136 case BUILTIN_ALIGNOF:
9138 Numeric_constant nc;
9139 unsigned long val;
9140 if (!this->numeric_constant_value(&nc)
9141 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9143 go_assert(saw_errors());
9144 return context->backend()->error_expression();
9146 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9147 mpz_t ival;
9148 nc.get_int(&ival);
9149 Expression* int_cst =
9150 Expression::make_integer_z(&ival, uintptr_type, location);
9151 mpz_clear(ival);
9152 return int_cst->get_backend(context);
9155 case BUILTIN_COPY:
9157 const Expression_list* args = this->args();
9158 go_assert(args != NULL && args->size() == 2);
9159 Expression* arg1 = args->front();
9160 Expression* arg2 = args->back();
9162 Type* arg1_type = arg1->type();
9163 Array_type* at = arg1_type->array_type();
9164 go_assert(arg1->is_variable());
9166 Expression* call;
9168 Type* arg2_type = arg2->type();
9169 go_assert(arg2->is_variable());
9170 if (arg2_type->is_string_type())
9171 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9172 2, arg1, arg2);
9173 else
9175 Type* et = at->element_type();
9176 if (et->has_pointer())
9178 Expression* td = Expression::make_type_descriptor(et,
9179 location);
9180 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9181 3, td, arg1, arg2);
9183 else
9185 Expression* sz = Expression::make_type_info(et,
9186 TYPE_INFO_SIZE);
9187 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9188 arg1, arg2, sz);
9192 return call->get_backend(context);
9195 case BUILTIN_APPEND:
9196 // Handled in Builtin_call_expression::flatten_append.
9197 go_unreachable();
9199 case BUILTIN_REAL:
9200 case BUILTIN_IMAG:
9202 const Expression_list* args = this->args();
9203 go_assert(args != NULL && args->size() == 1);
9205 Bexpression* ret;
9206 Bexpression* bcomplex = args->front()->get_backend(context);
9207 if (this->code_ == BUILTIN_REAL)
9208 ret = gogo->backend()->real_part_expression(bcomplex, location);
9209 else
9210 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9211 return ret;
9214 case BUILTIN_COMPLEX:
9216 const Expression_list* args = this->args();
9217 go_assert(args != NULL && args->size() == 2);
9218 Bexpression* breal = args->front()->get_backend(context);
9219 Bexpression* bimag = args->back()->get_backend(context);
9220 return gogo->backend()->complex_expression(breal, bimag, location);
9223 default:
9224 go_unreachable();
9228 // We have to support exporting a builtin call expression, because
9229 // code can set a constant to the result of a builtin expression.
9231 void
9232 Builtin_call_expression::do_export(Export* exp) const
9234 Numeric_constant nc;
9235 if (!this->numeric_constant_value(&nc))
9237 go_error_at(this->location(), "value is not constant");
9238 return;
9241 if (nc.is_int())
9243 mpz_t val;
9244 nc.get_int(&val);
9245 Integer_expression::export_integer(exp, val);
9246 mpz_clear(val);
9248 else if (nc.is_float())
9250 mpfr_t fval;
9251 nc.get_float(&fval);
9252 Float_expression::export_float(exp, fval);
9253 mpfr_clear(fval);
9255 else if (nc.is_complex())
9257 mpc_t cval;
9258 nc.get_complex(&cval);
9259 Complex_expression::export_complex(exp, cval);
9260 mpc_clear(cval);
9262 else
9263 go_unreachable();
9265 // A trailing space lets us reliably identify the end of the number.
9266 exp->write_c_string(" ");
9269 // Class Call_expression.
9271 // A Go function can be viewed in a couple of different ways. The
9272 // code of a Go function becomes a backend function with parameters
9273 // whose types are simply the backend representation of the Go types.
9274 // If there are multiple results, they are returned as a backend
9275 // struct.
9277 // However, when Go code refers to a function other than simply
9278 // calling it, the backend type of that function is actually a struct.
9279 // The first field of the struct points to the Go function code
9280 // (sometimes a wrapper as described below). The remaining fields
9281 // hold addresses of closed-over variables. This struct is called a
9282 // closure.
9284 // There are a few cases to consider.
9286 // A direct function call of a known function in package scope. In
9287 // this case there are no closed-over variables, and we know the name
9288 // of the function code. We can simply produce a backend call to the
9289 // function directly, and not worry about the closure.
9291 // A direct function call of a known function literal. In this case
9292 // we know the function code and we know the closure. We generate the
9293 // function code such that it expects an additional final argument of
9294 // the closure type. We pass the closure as the last argument, after
9295 // the other arguments.
9297 // An indirect function call. In this case we have a closure. We
9298 // load the pointer to the function code from the first field of the
9299 // closure. We pass the address of the closure as the last argument.
9301 // A call to a method of an interface. Type methods are always at
9302 // package scope, so we call the function directly, and don't worry
9303 // about the closure.
9305 // This means that for a function at package scope we have two cases.
9306 // One is the direct call, which has no closure. The other is the
9307 // indirect call, which does have a closure. We can't simply ignore
9308 // the closure, even though it is the last argument, because that will
9309 // fail on targets where the function pops its arguments. So when
9310 // generating a closure for a package-scope function we set the
9311 // function code pointer in the closure to point to a wrapper
9312 // function. This wrapper function accepts a final argument that
9313 // points to the closure, ignores it, and calls the real function as a
9314 // direct function call. This wrapper will normally be efficient, and
9315 // can often simply be a tail call to the real function.
9317 // We don't use GCC's static chain pointer because 1) we don't need
9318 // it; 2) GCC only permits using a static chain to call a known
9319 // function, so we can't use it for an indirect call anyhow. Since we
9320 // can't use it for an indirect call, we may as well not worry about
9321 // using it for a direct call either.
9323 // We pass the closure last rather than first because it means that
9324 // the function wrapper we put into a closure for a package-scope
9325 // function can normally just be a tail call to the real function.
9327 // For method expressions we generate a wrapper that loads the
9328 // receiver from the closure and then calls the method. This
9329 // unfortunately forces reshuffling the arguments, since there is a
9330 // new first argument, but we can't avoid reshuffling either for
9331 // method expressions or for indirect calls of package-scope
9332 // functions, and since the latter are more common we reshuffle for
9333 // method expressions.
9335 // Note that the Go code retains the Go types. The extra final
9336 // argument only appears when we convert to the backend
9337 // representation.
9339 // Traversal.
9342 Call_expression::do_traverse(Traverse* traverse)
9344 // If we are calling a function in a different package that returns
9345 // an unnamed type, this may be the only chance we get to traverse
9346 // that type. We don't traverse this->type_ because it may be a
9347 // Call_multiple_result_type that will just lead back here.
9348 if (this->type_ != NULL && !this->type_->is_error_type())
9350 Function_type *fntype = this->get_function_type();
9351 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9352 return TRAVERSE_EXIT;
9354 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9355 return TRAVERSE_EXIT;
9356 if (this->args_ != NULL)
9358 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9359 return TRAVERSE_EXIT;
9361 return TRAVERSE_CONTINUE;
9364 // Lower a call statement.
9366 Expression*
9367 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9368 Statement_inserter* inserter, int)
9370 Location loc = this->location();
9372 // A type cast can look like a function call.
9373 if (this->fn_->is_type_expression()
9374 && this->args_ != NULL
9375 && this->args_->size() == 1)
9376 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9377 loc);
9379 // Because do_type will return an error type and thus prevent future
9380 // errors, check for that case now to ensure that the error gets
9381 // reported.
9382 Function_type* fntype = this->get_function_type();
9383 if (fntype == NULL)
9385 if (!this->fn_->type()->is_error())
9386 this->report_error(_("expected function"));
9387 this->set_is_error();
9388 return this;
9391 // Handle an argument which is a call to a function which returns
9392 // multiple results.
9393 if (this->args_ != NULL
9394 && this->args_->size() == 1
9395 && this->args_->front()->call_expression() != NULL)
9397 size_t rc = this->args_->front()->call_expression()->result_count();
9398 if (rc > 1
9399 && ((fntype->parameters() != NULL
9400 && (fntype->parameters()->size() == rc
9401 || (fntype->is_varargs()
9402 && fntype->parameters()->size() - 1 <= rc)))
9403 || fntype->is_builtin()))
9405 Call_expression* call = this->args_->front()->call_expression();
9406 call->set_is_multi_value_arg();
9407 if (this->is_varargs_)
9409 // It is not clear which result of a multiple result call
9410 // the ellipsis operator should be applied to. If we unpack the
9411 // the call into its individual results here, the ellipsis will be
9412 // applied to the last result.
9413 go_error_at(call->location(),
9414 _("multiple-value argument in single-value context"));
9415 return Expression::make_error(call->location());
9418 Expression_list* args = new Expression_list;
9419 for (size_t i = 0; i < rc; ++i)
9420 args->push_back(Expression::make_call_result(call, i));
9421 // We can't return a new call expression here, because this
9422 // one may be referenced by Call_result expressions. We
9423 // also can't delete the old arguments, because we may still
9424 // traverse them somewhere up the call stack. FIXME.
9425 this->args_ = args;
9429 // Recognize a call to a builtin function.
9430 if (fntype->is_builtin())
9431 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9432 this->is_varargs_, loc);
9434 // If this call returns multiple results, create a temporary
9435 // variable to hold them.
9436 if (this->result_count() > 1 && this->call_temp_ == NULL)
9438 Struct_field_list* sfl = new Struct_field_list();
9439 Function_type* fntype = this->get_function_type();
9440 const Typed_identifier_list* results = fntype->results();
9441 Location loc = this->location();
9443 int i = 0;
9444 char buf[20];
9445 for (Typed_identifier_list::const_iterator p = results->begin();
9446 p != results->end();
9447 ++p, ++i)
9449 snprintf(buf, sizeof buf, "res%d", i);
9450 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9453 Struct_type* st = Type::make_struct_type(sfl, loc);
9454 st->set_is_struct_incomparable();
9455 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9456 inserter->insert(this->call_temp_);
9459 // Handle a call to a varargs function by packaging up the extra
9460 // parameters.
9461 if (fntype->is_varargs())
9463 const Typed_identifier_list* parameters = fntype->parameters();
9464 go_assert(parameters != NULL && !parameters->empty());
9465 Type* varargs_type = parameters->back().type();
9466 this->lower_varargs(gogo, function, inserter, varargs_type,
9467 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9470 // If this is call to a method, call the method directly passing the
9471 // object as the first parameter.
9472 Bound_method_expression* bme = this->fn_->bound_method_expression();
9473 if (bme != NULL)
9475 Named_object* methodfn = bme->function();
9476 Expression* first_arg = bme->first_argument();
9478 // We always pass a pointer when calling a method.
9479 if (first_arg->type()->points_to() == NULL
9480 && !first_arg->type()->is_error())
9482 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9483 // We may need to create a temporary variable so that we can
9484 // take the address. We can't do that here because it will
9485 // mess up the order of evaluation.
9486 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9487 ue->set_create_temp();
9490 // If we are calling a method which was inherited from an
9491 // embedded struct, and the method did not get a stub, then the
9492 // first type may be wrong.
9493 Type* fatype = bme->first_argument_type();
9494 if (fatype != NULL)
9496 if (fatype->points_to() == NULL)
9497 fatype = Type::make_pointer_type(fatype);
9498 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9501 Expression_list* new_args = new Expression_list();
9502 new_args->push_back(first_arg);
9503 if (this->args_ != NULL)
9505 for (Expression_list::const_iterator p = this->args_->begin();
9506 p != this->args_->end();
9507 ++p)
9508 new_args->push_back(*p);
9511 // We have to change in place because this structure may be
9512 // referenced by Call_result_expressions. We can't delete the
9513 // old arguments, because we may be traversing them up in some
9514 // caller. FIXME.
9515 this->args_ = new_args;
9516 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9517 bme->location());
9520 // Handle a couple of special runtime functions. In the runtime
9521 // package, getcallerpc returns the PC of the caller, and
9522 // getcallersp returns the frame pointer of the caller. Implement
9523 // these by turning them into calls to GCC builtin functions. We
9524 // could implement them in normal code, but then we would have to
9525 // explicitly unwind the stack. These functions are intended to be
9526 // efficient. Note that this technique obviously only works for
9527 // direct calls, but that is the only way they are used.
9528 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9530 Func_expression* fe = this->fn_->func_expression();
9531 if (fe != NULL
9532 && fe->named_object()->is_function_declaration()
9533 && fe->named_object()->package() == NULL)
9535 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9536 if ((this->args_ == NULL || this->args_->size() == 0)
9537 && n == "getcallerpc")
9539 static Named_object* builtin_return_address;
9540 return this->lower_to_builtin(&builtin_return_address,
9541 "__builtin_return_address",
9544 else if (this->args_ != NULL
9545 && this->args_->size() == 1
9546 && n == "getcallersp")
9548 // The actual argument to getcallersp is always the
9549 // address of a parameter; we don't need that for the
9550 // GCC builtin function, so we just ignore it.
9551 static Named_object* builtin_frame_address;
9552 return this->lower_to_builtin(&builtin_frame_address,
9553 "__builtin_frame_address",
9559 return this;
9562 // Lower a call to a varargs function. FUNCTION is the function in
9563 // which the call occurs--it's not the function we are calling.
9564 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9565 // PARAM_COUNT is the number of parameters of the function we are
9566 // calling; the last of these parameters will be the varargs
9567 // parameter.
9569 void
9570 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9571 Statement_inserter* inserter,
9572 Type* varargs_type, size_t param_count,
9573 Slice_storage_escape_disp escape_disp)
9575 // When compiling the runtime, varargs slices do not escape. When
9576 // escape analysis becomes the default, this should be changed to
9577 // make it an error if we have a varargs slice that escapes.
9578 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9579 escape_disp = SLICE_STORAGE_DOES_NOT_ESCAPE;
9581 if (this->varargs_are_lowered_)
9582 return;
9584 Location loc = this->location();
9586 go_assert(param_count > 0);
9587 go_assert(varargs_type->is_slice_type());
9589 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9590 if (arg_count < param_count - 1)
9592 // Not enough arguments; will be caught in check_types.
9593 return;
9596 Expression_list* old_args = this->args_;
9597 Expression_list* new_args = new Expression_list();
9598 bool push_empty_arg = false;
9599 if (old_args == NULL || old_args->empty())
9601 go_assert(param_count == 1);
9602 push_empty_arg = true;
9604 else
9606 Expression_list::const_iterator pa;
9607 int i = 1;
9608 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9610 if (static_cast<size_t>(i) == param_count)
9611 break;
9612 new_args->push_back(*pa);
9615 // We have reached the varargs parameter.
9617 bool issued_error = false;
9618 if (pa == old_args->end())
9619 push_empty_arg = true;
9620 else if (pa + 1 == old_args->end() && this->is_varargs_)
9621 new_args->push_back(*pa);
9622 else if (this->is_varargs_)
9624 if ((*pa)->type()->is_slice_type())
9625 this->report_error(_("too many arguments"));
9626 else
9628 go_error_at(this->location(),
9629 _("invalid use of %<...%> with non-slice"));
9630 this->set_is_error();
9632 return;
9634 else
9636 Type* element_type = varargs_type->array_type()->element_type();
9637 Expression_list* vals = new Expression_list;
9638 for (; pa != old_args->end(); ++pa, ++i)
9640 // Check types here so that we get a better message.
9641 Type* patype = (*pa)->type();
9642 Location paloc = (*pa)->location();
9643 if (!this->check_argument_type(i, element_type, patype,
9644 paloc, issued_error))
9645 continue;
9646 vals->push_back(*pa);
9648 Slice_construction_expression* sce =
9649 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9650 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9651 sce->set_storage_does_not_escape();
9652 Expression* val = sce;
9653 gogo->lower_expression(function, inserter, &val);
9654 new_args->push_back(val);
9658 if (push_empty_arg)
9659 new_args->push_back(Expression::make_nil(loc));
9661 // We can't return a new call expression here, because this one may
9662 // be referenced by Call_result expressions. FIXME. We can't
9663 // delete OLD_ARGS because we may have both a Call_expression and a
9664 // Builtin_call_expression which refer to them. FIXME.
9665 this->args_ = new_args;
9666 this->varargs_are_lowered_ = true;
9669 // Return a call to __builtin_return_address or __builtin_frame_address.
9671 Expression*
9672 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9673 int arg)
9675 if (*pno == NULL)
9676 *pno = Gogo::declare_builtin_rf_address(name);
9678 Location loc = this->location();
9680 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9681 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9682 Expression_list *args = new Expression_list();
9683 args->push_back(a);
9684 Expression* call = Expression::make_call(fn, args, false, loc);
9686 // The builtin functions return void*, but the Go functions return uintptr.
9687 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9688 return Expression::make_cast(uintptr_type, call, loc);
9691 // Flatten a call with multiple results into a temporary.
9693 Expression*
9694 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9695 Statement_inserter* inserter)
9697 if (this->is_erroneous_call())
9699 go_assert(saw_errors());
9700 return Expression::make_error(this->location());
9703 if (this->is_flattened_)
9704 return this;
9705 this->is_flattened_ = true;
9707 // Add temporary variables for all arguments that require type
9708 // conversion.
9709 Function_type* fntype = this->get_function_type();
9710 if (fntype == NULL)
9712 go_assert(saw_errors());
9713 return this;
9715 if (this->args_ != NULL && !this->args_->empty()
9716 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9718 bool is_interface_method =
9719 this->fn_->interface_field_reference_expression() != NULL;
9721 Expression_list *args = new Expression_list();
9722 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9723 Expression_list::const_iterator pa = this->args_->begin();
9724 if (!is_interface_method && fntype->is_method())
9726 // The receiver argument.
9727 args->push_back(*pa);
9728 ++pa;
9730 for (; pa != this->args_->end(); ++pa, ++pp)
9732 go_assert(pp != fntype->parameters()->end());
9733 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9734 args->push_back(*pa);
9735 else
9737 Location loc = (*pa)->location();
9738 Expression* arg = *pa;
9739 if (!arg->is_variable())
9741 Temporary_statement *temp =
9742 Statement::make_temporary(NULL, arg, loc);
9743 inserter->insert(temp);
9744 arg = Expression::make_temporary_reference(temp, loc);
9746 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9747 loc);
9748 args->push_back(arg);
9751 delete this->args_;
9752 this->args_ = args;
9755 return this;
9758 // Get the function type. This can return NULL in error cases.
9760 Function_type*
9761 Call_expression::get_function_type() const
9763 return this->fn_->type()->function_type();
9766 // Return the number of values which this call will return.
9768 size_t
9769 Call_expression::result_count() const
9771 const Function_type* fntype = this->get_function_type();
9772 if (fntype == NULL)
9773 return 0;
9774 if (fntype->results() == NULL)
9775 return 0;
9776 return fntype->results()->size();
9779 // Return the temporary that holds the result for a call with multiple
9780 // results.
9782 Temporary_statement*
9783 Call_expression::results() const
9785 if (this->call_temp_ == NULL)
9787 go_assert(saw_errors());
9788 return NULL;
9790 return this->call_temp_;
9793 // Set the number of results expected from a call expression.
9795 void
9796 Call_expression::set_expected_result_count(size_t count)
9798 go_assert(this->expected_result_count_ == 0);
9799 this->expected_result_count_ = count;
9802 // Return whether this is a call to the predeclared function recover.
9804 bool
9805 Call_expression::is_recover_call() const
9807 return this->do_is_recover_call();
9810 // Set the argument to the recover function.
9812 void
9813 Call_expression::set_recover_arg(Expression* arg)
9815 this->do_set_recover_arg(arg);
9818 // Virtual functions also implemented by Builtin_call_expression.
9820 bool
9821 Call_expression::do_is_recover_call() const
9823 return false;
9826 void
9827 Call_expression::do_set_recover_arg(Expression*)
9829 go_unreachable();
9832 // We have found an error with this call expression; return true if
9833 // we should report it.
9835 bool
9836 Call_expression::issue_error()
9838 if (this->issued_error_)
9839 return false;
9840 else
9842 this->issued_error_ = true;
9843 return true;
9847 // Whether or not this call contains errors, either in the call or the
9848 // arguments to the call.
9850 bool
9851 Call_expression::is_erroneous_call()
9853 if (this->is_error_expression() || this->fn()->is_error_expression())
9854 return true;
9856 if (this->args() == NULL)
9857 return false;
9858 for (Expression_list::iterator pa = this->args()->begin();
9859 pa != this->args()->end();
9860 ++pa)
9862 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9863 return true;
9865 return false;
9868 // Get the type.
9870 Type*
9871 Call_expression::do_type()
9873 if (this->type_ != NULL)
9874 return this->type_;
9876 Type* ret;
9877 Function_type* fntype = this->get_function_type();
9878 if (fntype == NULL)
9879 return Type::make_error_type();
9881 const Typed_identifier_list* results = fntype->results();
9882 if (results == NULL)
9883 ret = Type::make_void_type();
9884 else if (results->size() == 1)
9885 ret = results->begin()->type();
9886 else
9887 ret = Type::make_call_multiple_result_type(this);
9889 this->type_ = ret;
9891 return this->type_;
9894 // Determine types for a call expression. We can use the function
9895 // parameter types to set the types of the arguments.
9897 void
9898 Call_expression::do_determine_type(const Type_context*)
9900 if (!this->determining_types())
9901 return;
9903 this->fn_->determine_type_no_context();
9904 Function_type* fntype = this->get_function_type();
9905 const Typed_identifier_list* parameters = NULL;
9906 if (fntype != NULL)
9907 parameters = fntype->parameters();
9908 if (this->args_ != NULL)
9910 Typed_identifier_list::const_iterator pt;
9911 if (parameters != NULL)
9912 pt = parameters->begin();
9913 bool first = true;
9914 for (Expression_list::const_iterator pa = this->args_->begin();
9915 pa != this->args_->end();
9916 ++pa)
9918 if (first)
9920 first = false;
9921 // If this is a method, the first argument is the
9922 // receiver.
9923 if (fntype != NULL && fntype->is_method())
9925 Type* rtype = fntype->receiver()->type();
9926 // The receiver is always passed as a pointer.
9927 if (rtype->points_to() == NULL)
9928 rtype = Type::make_pointer_type(rtype);
9929 Type_context subcontext(rtype, false);
9930 (*pa)->determine_type(&subcontext);
9931 continue;
9935 if (parameters != NULL && pt != parameters->end())
9937 Type_context subcontext(pt->type(), false);
9938 (*pa)->determine_type(&subcontext);
9939 ++pt;
9941 else
9942 (*pa)->determine_type_no_context();
9947 // Called when determining types for a Call_expression. Return true
9948 // if we should go ahead, false if they have already been determined.
9950 bool
9951 Call_expression::determining_types()
9953 if (this->types_are_determined_)
9954 return false;
9955 else
9957 this->types_are_determined_ = true;
9958 return true;
9962 // Check types for parameter I.
9964 bool
9965 Call_expression::check_argument_type(int i, const Type* parameter_type,
9966 const Type* argument_type,
9967 Location argument_location,
9968 bool issued_error)
9970 std::string reason;
9971 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9973 if (!issued_error)
9975 if (reason.empty())
9976 go_error_at(argument_location, "argument %d has incompatible type", i);
9977 else
9978 go_error_at(argument_location,
9979 "argument %d has incompatible type (%s)",
9980 i, reason.c_str());
9982 this->set_is_error();
9983 return false;
9985 return true;
9988 // Check types.
9990 void
9991 Call_expression::do_check_types(Gogo*)
9993 if (this->classification() == EXPRESSION_ERROR)
9994 return;
9996 Function_type* fntype = this->get_function_type();
9997 if (fntype == NULL)
9999 if (!this->fn_->type()->is_error())
10000 this->report_error(_("expected function"));
10001 return;
10004 if (this->expected_result_count_ != 0
10005 && this->expected_result_count_ != this->result_count())
10007 if (this->issue_error())
10008 this->report_error(_("function result count mismatch"));
10009 this->set_is_error();
10010 return;
10013 bool is_method = fntype->is_method();
10014 if (is_method)
10016 go_assert(this->args_ != NULL && !this->args_->empty());
10017 Type* rtype = fntype->receiver()->type();
10018 Expression* first_arg = this->args_->front();
10019 // We dereference the values since receivers are always passed
10020 // as pointers.
10021 std::string reason;
10022 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10023 &reason))
10025 if (reason.empty())
10026 this->report_error(_("incompatible type for receiver"));
10027 else
10029 go_error_at(this->location(),
10030 "incompatible type for receiver (%s)",
10031 reason.c_str());
10032 this->set_is_error();
10037 // Note that varargs was handled by the lower_varargs() method, so
10038 // we don't have to worry about it here unless something is wrong.
10039 if (this->is_varargs_ && !this->varargs_are_lowered_)
10041 if (!fntype->is_varargs())
10043 go_error_at(this->location(),
10044 _("invalid use of %<...%> calling non-variadic function"));
10045 this->set_is_error();
10046 return;
10050 const Typed_identifier_list* parameters = fntype->parameters();
10051 if (this->args_ == NULL || this->args_->size() == 0)
10053 if (parameters != NULL && !parameters->empty())
10054 this->report_error(_("not enough arguments"));
10056 else if (parameters == NULL)
10058 if (!is_method || this->args_->size() > 1)
10059 this->report_error(_("too many arguments"));
10061 else if (this->args_->size() == 1
10062 && this->args_->front()->call_expression() != NULL
10063 && this->args_->front()->call_expression()->result_count() > 1)
10065 // This is F(G()) when G returns more than one result. If the
10066 // results can be matched to parameters, it would have been
10067 // lowered in do_lower. If we get here we know there is a
10068 // mismatch.
10069 if (this->args_->front()->call_expression()->result_count()
10070 < parameters->size())
10071 this->report_error(_("not enough arguments"));
10072 else
10073 this->report_error(_("too many arguments"));
10075 else
10077 int i = 0;
10078 Expression_list::const_iterator pa = this->args_->begin();
10079 if (is_method)
10080 ++pa;
10081 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10082 pt != parameters->end();
10083 ++pt, ++pa, ++i)
10085 if (pa == this->args_->end())
10087 this->report_error(_("not enough arguments"));
10088 return;
10090 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10091 (*pa)->location(), false);
10093 if (pa != this->args_->end())
10094 this->report_error(_("too many arguments"));
10098 Expression*
10099 Call_expression::do_copy()
10101 Call_expression* call =
10102 Expression::make_call(this->fn_->copy(),
10103 (this->args_ == NULL
10104 ? NULL
10105 : this->args_->copy()),
10106 this->is_varargs_, this->location());
10108 if (this->varargs_are_lowered_)
10109 call->set_varargs_are_lowered();
10110 return call;
10113 // Return whether we have to use a temporary variable to ensure that
10114 // we evaluate this call expression in order. If the call returns no
10115 // results then it will inevitably be executed last.
10117 bool
10118 Call_expression::do_must_eval_in_order() const
10120 return this->result_count() > 0;
10123 // Get the function and the first argument to use when calling an
10124 // interface method.
10126 Expression*
10127 Call_expression::interface_method_function(
10128 Interface_field_reference_expression* interface_method,
10129 Expression** first_arg_ptr,
10130 Location location)
10132 Expression* object = interface_method->get_underlying_object();
10133 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10134 *first_arg_ptr =
10135 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10136 return interface_method->get_function();
10139 // Build the call expression.
10141 Bexpression*
10142 Call_expression::do_get_backend(Translate_context* context)
10144 Location location = this->location();
10146 if (this->call_ != NULL)
10148 // If the call returns multiple results, make a new reference to
10149 // the temporary.
10150 if (this->call_temp_ != NULL)
10152 Expression* ref =
10153 Expression::make_temporary_reference(this->call_temp_, location);
10154 return ref->get_backend(context);
10157 return this->call_;
10160 Function_type* fntype = this->get_function_type();
10161 if (fntype == NULL)
10162 return context->backend()->error_expression();
10164 if (this->fn_->is_error_expression())
10165 return context->backend()->error_expression();
10167 Gogo* gogo = context->gogo();
10169 Func_expression* func = this->fn_->func_expression();
10170 Interface_field_reference_expression* interface_method =
10171 this->fn_->interface_field_reference_expression();
10172 const bool has_closure = func != NULL && func->closure() != NULL;
10173 const bool is_interface_method = interface_method != NULL;
10175 bool has_closure_arg;
10176 if (has_closure)
10177 has_closure_arg = true;
10178 else if (func != NULL)
10179 has_closure_arg = false;
10180 else if (is_interface_method)
10181 has_closure_arg = false;
10182 else
10183 has_closure_arg = true;
10185 int nargs;
10186 std::vector<Bexpression*> fn_args;
10187 if (this->args_ == NULL || this->args_->empty())
10189 nargs = is_interface_method ? 1 : 0;
10190 if (nargs > 0)
10191 fn_args.resize(1);
10193 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10195 // Passing a receiver parameter.
10196 go_assert(!is_interface_method
10197 && fntype->is_method()
10198 && this->args_->size() == 1);
10199 nargs = 1;
10200 fn_args.resize(1);
10201 fn_args[0] = this->args_->front()->get_backend(context);
10203 else
10205 const Typed_identifier_list* params = fntype->parameters();
10207 nargs = this->args_->size();
10208 int i = is_interface_method ? 1 : 0;
10209 nargs += i;
10210 fn_args.resize(nargs);
10212 Typed_identifier_list::const_iterator pp = params->begin();
10213 Expression_list::const_iterator pe = this->args_->begin();
10214 if (!is_interface_method && fntype->is_method())
10216 fn_args[i] = (*pe)->get_backend(context);
10217 ++pe;
10218 ++i;
10220 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10222 go_assert(pp != params->end());
10223 Expression* arg =
10224 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10225 location);
10226 fn_args[i] = arg->get_backend(context);
10228 go_assert(pp == params->end());
10229 go_assert(i == nargs);
10232 Expression* fn;
10233 Expression* closure = NULL;
10234 if (func != NULL)
10236 Named_object* no = func->named_object();
10237 fn = Expression::make_func_code_reference(no, location);
10238 if (has_closure)
10239 closure = func->closure();
10241 else if (!is_interface_method)
10243 closure = this->fn_;
10245 // The backend representation of this function type is a pointer
10246 // to a struct whose first field is the actual function to call.
10247 Type* pfntype =
10248 Type::make_pointer_type(
10249 Type::make_pointer_type(Type::make_void_type()));
10250 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10251 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10253 else
10255 Expression* first_arg;
10256 fn = this->interface_method_function(interface_method, &first_arg,
10257 location);
10258 fn_args[0] = first_arg->get_backend(context);
10261 Bexpression* bclosure = NULL;
10262 if (has_closure_arg)
10263 bclosure = closure->get_backend(context);
10264 else
10265 go_assert(closure == NULL);
10267 Bexpression* bfn = fn->get_backend(context);
10269 // When not calling a named function directly, use a type conversion
10270 // in case the type of the function is a recursive type which refers
10271 // to itself. We don't do this for an interface method because 1)
10272 // an interface method never refers to itself, so we always have a
10273 // function type here; 2) we pass an extra first argument to an
10274 // interface method, so fntype is not correct.
10275 if (func == NULL && !is_interface_method)
10277 Btype* bft = fntype->get_backend_fntype(gogo);
10278 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10281 Bfunction* bfunction = NULL;
10282 if (context->function())
10283 bfunction = context->function()->func_value()->get_decl();
10284 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10285 fn_args, bclosure,
10286 location);
10288 if (this->call_temp_ != NULL)
10290 // This case occurs when the call returns multiple results.
10292 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10293 location);
10294 Bexpression* bref = ref->get_backend(context);
10295 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10296 bref, call,
10297 location);
10299 ref = Expression::make_temporary_reference(this->call_temp_, location);
10300 this->call_ = ref->get_backend(context);
10302 return gogo->backend()->compound_expression(bassn, this->call_,
10303 location);
10306 this->call_ = call;
10307 return this->call_;
10310 // Dump ast representation for a call expressin.
10312 void
10313 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10315 this->fn_->dump_expression(ast_dump_context);
10316 ast_dump_context->ostream() << "(";
10317 if (args_ != NULL)
10318 ast_dump_context->dump_expression_list(this->args_);
10320 ast_dump_context->ostream() << ") ";
10323 // Make a call expression.
10325 Call_expression*
10326 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10327 Location location)
10329 return new Call_expression(fn, args, is_varargs, location);
10332 // Class Call_result_expression.
10334 // Traverse a call result.
10337 Call_result_expression::do_traverse(Traverse* traverse)
10339 if (traverse->remember_expression(this->call_))
10341 // We have already traversed the call expression.
10342 return TRAVERSE_CONTINUE;
10344 return Expression::traverse(&this->call_, traverse);
10347 // Get the type.
10349 Type*
10350 Call_result_expression::do_type()
10352 if (this->classification() == EXPRESSION_ERROR)
10353 return Type::make_error_type();
10355 // THIS->CALL_ can be replaced with a temporary reference due to
10356 // Call_expression::do_must_eval_in_order when there is an error.
10357 Call_expression* ce = this->call_->call_expression();
10358 if (ce == NULL)
10360 this->set_is_error();
10361 return Type::make_error_type();
10363 Function_type* fntype = ce->get_function_type();
10364 if (fntype == NULL)
10366 if (ce->issue_error())
10368 if (!ce->fn()->type()->is_error())
10369 this->report_error(_("expected function"));
10371 this->set_is_error();
10372 return Type::make_error_type();
10374 const Typed_identifier_list* results = fntype->results();
10375 if (results == NULL || results->size() < 2)
10377 if (ce->issue_error())
10378 this->report_error(_("number of results does not match "
10379 "number of values"));
10380 return Type::make_error_type();
10382 Typed_identifier_list::const_iterator pr = results->begin();
10383 for (unsigned int i = 0; i < this->index_; ++i)
10385 if (pr == results->end())
10386 break;
10387 ++pr;
10389 if (pr == results->end())
10391 if (ce->issue_error())
10392 this->report_error(_("number of results does not match "
10393 "number of values"));
10394 return Type::make_error_type();
10396 return pr->type();
10399 // Check the type. Just make sure that we trigger the warning in
10400 // do_type.
10402 void
10403 Call_result_expression::do_check_types(Gogo*)
10405 this->type();
10408 // Determine the type. We have nothing to do here, but the 0 result
10409 // needs to pass down to the caller.
10411 void
10412 Call_result_expression::do_determine_type(const Type_context*)
10414 this->call_->determine_type_no_context();
10417 // Return the backend representation. We just refer to the temporary set by the
10418 // call expression. We don't do this at lowering time because it makes it
10419 // hard to evaluate the call at the right time.
10421 Bexpression*
10422 Call_result_expression::do_get_backend(Translate_context* context)
10424 Call_expression* ce = this->call_->call_expression();
10425 if (ce == NULL)
10427 go_assert(this->call_->is_error_expression());
10428 return context->backend()->error_expression();
10430 Temporary_statement* ts = ce->results();
10431 if (ts == NULL)
10433 go_assert(saw_errors());
10434 return context->backend()->error_expression();
10436 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10437 ref = Expression::make_field_reference(ref, this->index_, this->location());
10438 return ref->get_backend(context);
10441 // Dump ast representation for a call result expression.
10443 void
10444 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10445 const
10447 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10448 // (struct) and the fields are referenced instead.
10449 ast_dump_context->ostream() << this->index_ << "@(";
10450 ast_dump_context->dump_expression(this->call_);
10451 ast_dump_context->ostream() << ")";
10454 // Make a reference to a single result of a call which returns
10455 // multiple results.
10457 Expression*
10458 Expression::make_call_result(Call_expression* call, unsigned int index)
10460 return new Call_result_expression(call, index);
10463 // Class Index_expression.
10465 // Traversal.
10468 Index_expression::do_traverse(Traverse* traverse)
10470 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10471 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10472 || (this->end_ != NULL
10473 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10474 || (this->cap_ != NULL
10475 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10476 return TRAVERSE_EXIT;
10477 return TRAVERSE_CONTINUE;
10480 // Lower an index expression. This converts the generic index
10481 // expression into an array index, a string index, or a map index.
10483 Expression*
10484 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10486 Location location = this->location();
10487 Expression* left = this->left_;
10488 Expression* start = this->start_;
10489 Expression* end = this->end_;
10490 Expression* cap = this->cap_;
10492 Type* type = left->type();
10493 if (type->is_error())
10495 go_assert(saw_errors());
10496 return Expression::make_error(location);
10498 else if (left->is_type_expression())
10500 go_error_at(location, "attempt to index type expression");
10501 return Expression::make_error(location);
10503 else if (type->array_type() != NULL)
10504 return Expression::make_array_index(left, start, end, cap, location);
10505 else if (type->points_to() != NULL
10506 && type->points_to()->array_type() != NULL
10507 && !type->points_to()->is_slice_type())
10509 Expression* deref =
10510 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10512 // For an ordinary index into the array, the pointer will be
10513 // dereferenced. For a slice it will not--the resulting slice
10514 // will simply reuse the pointer, which is incorrect if that
10515 // pointer is nil.
10516 if (end != NULL || cap != NULL)
10517 deref->issue_nil_check();
10519 return Expression::make_array_index(deref, start, end, cap, location);
10521 else if (type->is_string_type())
10523 if (cap != NULL)
10525 go_error_at(location, "invalid 3-index slice of string");
10526 return Expression::make_error(location);
10528 return Expression::make_string_index(left, start, end, location);
10530 else if (type->map_type() != NULL)
10532 if (end != NULL || cap != NULL)
10534 go_error_at(location, "invalid slice of map");
10535 return Expression::make_error(location);
10537 return Expression::make_map_index(left, start, location);
10539 else if (cap != NULL)
10541 go_error_at(location,
10542 "invalid 3-index slice of object that is not a slice");
10543 return Expression::make_error(location);
10545 else if (end != NULL)
10547 go_error_at(location,
10548 ("attempt to slice object that is not "
10549 "array, slice, or string"));
10550 return Expression::make_error(location);
10552 else
10554 go_error_at(location,
10555 ("attempt to index object that is not "
10556 "array, slice, string, or map"));
10557 return Expression::make_error(location);
10561 // Write an indexed expression
10562 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10564 void
10565 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10566 const Expression* expr,
10567 const Expression* start,
10568 const Expression* end,
10569 const Expression* cap)
10571 expr->dump_expression(ast_dump_context);
10572 ast_dump_context->ostream() << "[";
10573 start->dump_expression(ast_dump_context);
10574 if (end != NULL)
10576 ast_dump_context->ostream() << ":";
10577 end->dump_expression(ast_dump_context);
10579 if (cap != NULL)
10581 ast_dump_context->ostream() << ":";
10582 cap->dump_expression(ast_dump_context);
10584 ast_dump_context->ostream() << "]";
10587 // Dump ast representation for an index expression.
10589 void
10590 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10591 const
10593 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10594 this->start_, this->end_, this->cap_);
10597 // Make an index expression.
10599 Expression*
10600 Expression::make_index(Expression* left, Expression* start, Expression* end,
10601 Expression* cap, Location location)
10603 return new Index_expression(left, start, end, cap, location);
10606 // Class Array_index_expression.
10608 // Array index traversal.
10611 Array_index_expression::do_traverse(Traverse* traverse)
10613 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10614 return TRAVERSE_EXIT;
10615 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10616 return TRAVERSE_EXIT;
10617 if (this->end_ != NULL)
10619 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10620 return TRAVERSE_EXIT;
10622 if (this->cap_ != NULL)
10624 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10625 return TRAVERSE_EXIT;
10627 return TRAVERSE_CONTINUE;
10630 // Return the type of an array index.
10632 Type*
10633 Array_index_expression::do_type()
10635 if (this->type_ == NULL)
10637 Array_type* type = this->array_->type()->array_type();
10638 if (type == NULL)
10639 this->type_ = Type::make_error_type();
10640 else if (this->end_ == NULL)
10641 this->type_ = type->element_type();
10642 else if (type->is_slice_type())
10644 // A slice of a slice has the same type as the original
10645 // slice.
10646 this->type_ = this->array_->type()->deref();
10648 else
10650 // A slice of an array is a slice.
10651 this->type_ = Type::make_array_type(type->element_type(), NULL);
10654 return this->type_;
10657 // Set the type of an array index.
10659 void
10660 Array_index_expression::do_determine_type(const Type_context*)
10662 this->array_->determine_type_no_context();
10664 Type_context index_context(Type::lookup_integer_type("int"), false);
10665 if (this->start_->is_constant())
10666 this->start_->determine_type(&index_context);
10667 else
10668 this->start_->determine_type_no_context();
10669 if (this->end_ != NULL)
10671 if (this->end_->is_constant())
10672 this->end_->determine_type(&index_context);
10673 else
10674 this->end_->determine_type_no_context();
10676 if (this->cap_ != NULL)
10678 if (this->cap_->is_constant())
10679 this->cap_->determine_type(&index_context);
10680 else
10681 this->cap_->determine_type_no_context();
10685 // Check types of an array index.
10687 void
10688 Array_index_expression::do_check_types(Gogo*)
10690 Numeric_constant nc;
10691 unsigned long v;
10692 if (this->start_->type()->integer_type() == NULL
10693 && !this->start_->type()->is_error()
10694 && (!this->start_->numeric_constant_value(&nc)
10695 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10696 this->report_error(_("index must be integer"));
10697 if (this->end_ != NULL
10698 && this->end_->type()->integer_type() == NULL
10699 && !this->end_->type()->is_error()
10700 && !this->end_->is_nil_expression()
10701 && !this->end_->is_error_expression()
10702 && (!this->end_->numeric_constant_value(&nc)
10703 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10704 this->report_error(_("slice end must be integer"));
10705 if (this->cap_ != NULL
10706 && this->cap_->type()->integer_type() == NULL
10707 && !this->cap_->type()->is_error()
10708 && !this->cap_->is_nil_expression()
10709 && !this->cap_->is_error_expression()
10710 && (!this->cap_->numeric_constant_value(&nc)
10711 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10712 this->report_error(_("slice capacity must be integer"));
10714 Array_type* array_type = this->array_->type()->array_type();
10715 if (array_type == NULL)
10717 go_assert(this->array_->type()->is_error());
10718 return;
10721 unsigned int int_bits =
10722 Type::lookup_integer_type("int")->integer_type()->bits();
10724 Numeric_constant lvalnc;
10725 mpz_t lval;
10726 bool lval_valid = (array_type->length() != NULL
10727 && array_type->length()->numeric_constant_value(&lvalnc)
10728 && lvalnc.to_int(&lval));
10729 Numeric_constant inc;
10730 mpz_t ival;
10731 bool ival_valid = false;
10732 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10734 ival_valid = true;
10735 if (mpz_sgn(ival) < 0
10736 || mpz_sizeinbase(ival, 2) >= int_bits
10737 || (lval_valid
10738 && (this->end_ == NULL
10739 ? mpz_cmp(ival, lval) >= 0
10740 : mpz_cmp(ival, lval) > 0)))
10742 go_error_at(this->start_->location(), "array index out of bounds");
10743 this->set_is_error();
10746 if (this->end_ != NULL && !this->end_->is_nil_expression())
10748 Numeric_constant enc;
10749 mpz_t eval;
10750 bool eval_valid = false;
10751 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10753 eval_valid = true;
10754 if (mpz_sgn(eval) < 0
10755 || mpz_sizeinbase(eval, 2) >= int_bits
10756 || (lval_valid && mpz_cmp(eval, lval) > 0))
10758 go_error_at(this->end_->location(), "array index out of bounds");
10759 this->set_is_error();
10761 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10762 this->report_error(_("inverted slice range"));
10765 Numeric_constant cnc;
10766 mpz_t cval;
10767 if (this->cap_ != NULL
10768 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10770 if (mpz_sgn(cval) < 0
10771 || mpz_sizeinbase(cval, 2) >= int_bits
10772 || (lval_valid && mpz_cmp(cval, lval) > 0))
10774 go_error_at(this->cap_->location(), "array index out of bounds");
10775 this->set_is_error();
10777 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10779 go_error_at(this->cap_->location(),
10780 "invalid slice index: capacity less than start");
10781 this->set_is_error();
10783 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10785 go_error_at(this->cap_->location(),
10786 "invalid slice index: capacity less than length");
10787 this->set_is_error();
10789 mpz_clear(cval);
10792 if (eval_valid)
10793 mpz_clear(eval);
10795 if (ival_valid)
10796 mpz_clear(ival);
10797 if (lval_valid)
10798 mpz_clear(lval);
10800 // A slice of an array requires an addressable array. A slice of a
10801 // slice is always possible.
10802 if (this->end_ != NULL && !array_type->is_slice_type())
10804 if (!this->array_->is_addressable())
10805 this->report_error(_("slice of unaddressable value"));
10806 else
10807 // Set the array address taken but not escape. The escape
10808 // analysis will make it escape to heap when needed.
10809 this->array_->address_taken(false);
10813 // Flatten array indexing by using temporary variables for slices and indexes.
10815 Expression*
10816 Array_index_expression::do_flatten(Gogo*, Named_object*,
10817 Statement_inserter* inserter)
10819 Location loc = this->location();
10820 Expression* array = this->array_;
10821 Expression* start = this->start_;
10822 Expression* end = this->end_;
10823 Expression* cap = this->cap_;
10824 if (array->is_error_expression()
10825 || array->type()->is_error_type()
10826 || start->is_error_expression()
10827 || start->type()->is_error_type()
10828 || (end != NULL
10829 && (end->is_error_expression() || end->type()->is_error_type()))
10830 || (cap != NULL
10831 && (cap->is_error_expression() || cap->type()->is_error_type())))
10833 go_assert(saw_errors());
10834 return Expression::make_error(loc);
10837 Temporary_statement* temp;
10838 if (array->type()->is_slice_type() && !array->is_variable())
10840 temp = Statement::make_temporary(NULL, array, loc);
10841 inserter->insert(temp);
10842 this->array_ = Expression::make_temporary_reference(temp, loc);
10844 if (!start->is_variable())
10846 temp = Statement::make_temporary(NULL, start, loc);
10847 inserter->insert(temp);
10848 this->start_ = Expression::make_temporary_reference(temp, loc);
10850 if (end != NULL
10851 && !end->is_nil_expression()
10852 && !end->is_variable())
10854 temp = Statement::make_temporary(NULL, end, loc);
10855 inserter->insert(temp);
10856 this->end_ = Expression::make_temporary_reference(temp, loc);
10858 if (cap != NULL && !cap->is_variable())
10860 temp = Statement::make_temporary(NULL, cap, loc);
10861 inserter->insert(temp);
10862 this->cap_ = Expression::make_temporary_reference(temp, loc);
10865 return this;
10868 // Return whether this expression is addressable.
10870 bool
10871 Array_index_expression::do_is_addressable() const
10873 // A slice expression is not addressable.
10874 if (this->end_ != NULL)
10875 return false;
10877 // An index into a slice is addressable.
10878 if (this->array_->type()->is_slice_type())
10879 return true;
10881 // An index into an array is addressable if the array is
10882 // addressable.
10883 return this->array_->is_addressable();
10886 void
10887 Array_index_expression::do_address_taken(bool escapes)
10889 // In &x[0], if x is a slice, then x's address is not taken.
10890 if (!this->array_->type()->is_slice_type())
10891 this->array_->address_taken(escapes);
10894 // Get the backend representation for an array index.
10896 Bexpression*
10897 Array_index_expression::do_get_backend(Translate_context* context)
10899 Array_type* array_type = this->array_->type()->array_type();
10900 if (array_type == NULL)
10902 go_assert(this->array_->type()->is_error());
10903 return context->backend()->error_expression();
10905 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10907 Location loc = this->location();
10908 Gogo* gogo = context->gogo();
10910 Type* int_type = Type::lookup_integer_type("int");
10911 Btype* int_btype = int_type->get_backend(gogo);
10913 // We need to convert the length and capacity to the Go "int" type here
10914 // because the length of a fixed-length array could be of type "uintptr"
10915 // and gimple disallows binary operations between "uintptr" and other
10916 // integer types. FIXME.
10917 Bexpression* length = NULL;
10918 if (this->end_ == NULL || this->end_->is_nil_expression())
10920 Expression* len = array_type->get_length(gogo, this->array_);
10921 length = len->get_backend(context);
10922 length = gogo->backend()->convert_expression(int_btype, length, loc);
10925 Bexpression* capacity = NULL;
10926 if (this->end_ != NULL)
10928 Expression* cap = array_type->get_capacity(gogo, this->array_);
10929 capacity = cap->get_backend(context);
10930 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10933 Bexpression* cap_arg = capacity;
10934 if (this->cap_ != NULL)
10936 cap_arg = this->cap_->get_backend(context);
10937 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10940 if (length == NULL)
10941 length = cap_arg;
10943 int code = (array_type->length() != NULL
10944 ? (this->end_ == NULL
10945 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10946 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10947 : (this->end_ == NULL
10948 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10949 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10950 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10952 if (this->start_->type()->integer_type() == NULL
10953 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10955 go_assert(saw_errors());
10956 return context->backend()->error_expression();
10959 Bexpression* bad_index =
10960 Expression::check_bounds(this->start_, loc)->get_backend(context);
10962 Bexpression* start = this->start_->get_backend(context);
10963 start = gogo->backend()->convert_expression(int_btype, start, loc);
10964 Bexpression* start_too_large =
10965 gogo->backend()->binary_expression((this->end_ == NULL
10966 ? OPERATOR_GE
10967 : OPERATOR_GT),
10968 start,
10969 (this->end_ == NULL
10970 ? length
10971 : capacity),
10972 loc);
10973 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10974 bad_index, loc);
10976 Bfunction* bfn = context->function()->func_value()->get_decl();
10977 if (this->end_ == NULL)
10979 // Simple array indexing. This has to return an l-value, so
10980 // wrap the index check into START.
10981 start =
10982 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
10983 crash, start, loc);
10985 Bexpression* ret;
10986 if (array_type->length() != NULL)
10988 Bexpression* array = this->array_->get_backend(context);
10989 ret = gogo->backend()->array_index_expression(array, start, loc);
10991 else
10993 // Slice.
10994 Expression* valptr =
10995 array_type->get_value_pointer(gogo, this->array_,
10996 this->is_lvalue_);
10997 Bexpression* ptr = valptr->get_backend(context);
10998 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11000 Type* ele_type = this->array_->type()->array_type()->element_type();
11001 Btype* ele_btype = ele_type->get_backend(gogo);
11002 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11004 return ret;
11007 // Array slice.
11009 if (this->cap_ != NULL)
11011 Bexpression* bounds_bcheck =
11012 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11013 bad_index =
11014 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11015 bad_index, loc);
11016 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11018 Bexpression* cap_too_small =
11019 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11020 Bexpression* cap_too_large =
11021 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11022 Bexpression* bad_cap =
11023 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11024 cap_too_large, loc);
11025 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11026 bad_index, loc);
11029 Bexpression* end;
11030 if (this->end_->is_nil_expression())
11031 end = length;
11032 else
11034 Bexpression* bounds_bcheck =
11035 Expression::check_bounds(this->end_, loc)->get_backend(context);
11037 bad_index =
11038 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11039 bad_index, loc);
11041 end = this->end_->get_backend(context);
11042 end = gogo->backend()->convert_expression(int_btype, end, loc);
11043 Bexpression* end_too_small =
11044 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11045 Bexpression* end_too_large =
11046 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11047 Bexpression* bad_end =
11048 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11049 end_too_large, loc);
11050 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11051 bad_index, loc);
11054 Bexpression* result_length =
11055 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11057 Bexpression* result_capacity =
11058 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11060 // If the new capacity is zero, don't change val. Otherwise we can
11061 // get a pointer to the next object in memory, keeping it live
11062 // unnecessarily. When the capacity is zero, the actual pointer
11063 // value doesn't matter.
11064 Bexpression* zero =
11065 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11066 Bexpression* cond =
11067 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11068 loc);
11069 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11070 cond, zero,
11071 start, loc);
11072 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11073 this->is_lvalue_);
11074 Bexpression* val = valptr->get_backend(context);
11075 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11077 Btype* struct_btype = this->type()->get_backend(gogo);
11078 std::vector<Bexpression*> init;
11079 init.push_back(val);
11080 init.push_back(result_length);
11081 init.push_back(result_capacity);
11083 Bexpression* ctor =
11084 gogo->backend()->constructor_expression(struct_btype, init, loc);
11085 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11086 crash, ctor, loc);
11089 // Dump ast representation for an array index expression.
11091 void
11092 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11093 const
11095 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11096 this->start_, this->end_, this->cap_);
11099 // Make an array index expression. END and CAP may be NULL.
11101 Expression*
11102 Expression::make_array_index(Expression* array, Expression* start,
11103 Expression* end, Expression* cap,
11104 Location location)
11106 return new Array_index_expression(array, start, end, cap, location);
11109 // Class String_index_expression.
11111 // String index traversal.
11114 String_index_expression::do_traverse(Traverse* traverse)
11116 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11117 return TRAVERSE_EXIT;
11118 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11119 return TRAVERSE_EXIT;
11120 if (this->end_ != NULL)
11122 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11123 return TRAVERSE_EXIT;
11125 return TRAVERSE_CONTINUE;
11128 Expression*
11129 String_index_expression::do_flatten(Gogo*, Named_object*,
11130 Statement_inserter* inserter)
11132 Location loc = this->location();
11133 Expression* string = this->string_;
11134 Expression* start = this->start_;
11135 Expression* end = this->end_;
11136 if (string->is_error_expression()
11137 || string->type()->is_error_type()
11138 || start->is_error_expression()
11139 || start->type()->is_error_type()
11140 || (end != NULL
11141 && (end->is_error_expression() || end->type()->is_error_type())))
11143 go_assert(saw_errors());
11144 return Expression::make_error(loc);
11147 Temporary_statement* temp;
11148 if (!this->string_->is_variable())
11150 temp = Statement::make_temporary(NULL, this->string_, loc);
11151 inserter->insert(temp);
11152 this->string_ = Expression::make_temporary_reference(temp, loc);
11154 if (!this->start_->is_variable())
11156 temp = Statement::make_temporary(NULL, this->start_, loc);
11157 inserter->insert(temp);
11158 this->start_ = Expression::make_temporary_reference(temp, loc);
11160 if (this->end_ != NULL
11161 && !this->end_->is_nil_expression()
11162 && !this->end_->is_variable())
11164 temp = Statement::make_temporary(NULL, this->end_, loc);
11165 inserter->insert(temp);
11166 this->end_ = Expression::make_temporary_reference(temp, loc);
11169 return this;
11172 // Return the type of a string index.
11174 Type*
11175 String_index_expression::do_type()
11177 if (this->end_ == NULL)
11178 return Type::lookup_integer_type("uint8");
11179 else
11180 return this->string_->type();
11183 // Determine the type of a string index.
11185 void
11186 String_index_expression::do_determine_type(const Type_context*)
11188 this->string_->determine_type_no_context();
11190 Type_context index_context(Type::lookup_integer_type("int"), false);
11191 if (this->start_->is_constant())
11192 this->start_->determine_type(&index_context);
11193 else
11194 this->start_->determine_type_no_context();
11195 if (this->end_ != NULL)
11197 if (this->end_->is_constant())
11198 this->end_->determine_type(&index_context);
11199 else
11200 this->end_->determine_type_no_context();
11204 // Check types of a string index.
11206 void
11207 String_index_expression::do_check_types(Gogo*)
11209 Numeric_constant nc;
11210 unsigned long v;
11211 if (this->start_->type()->integer_type() == NULL
11212 && !this->start_->type()->is_error()
11213 && (!this->start_->numeric_constant_value(&nc)
11214 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11215 this->report_error(_("index must be integer"));
11216 if (this->end_ != NULL
11217 && this->end_->type()->integer_type() == NULL
11218 && !this->end_->type()->is_error()
11219 && !this->end_->is_nil_expression()
11220 && !this->end_->is_error_expression()
11221 && (!this->end_->numeric_constant_value(&nc)
11222 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11223 this->report_error(_("slice end must be integer"));
11225 std::string sval;
11226 bool sval_valid = this->string_->string_constant_value(&sval);
11228 Numeric_constant inc;
11229 mpz_t ival;
11230 bool ival_valid = false;
11231 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11233 ival_valid = true;
11234 if (mpz_sgn(ival) < 0
11235 || (sval_valid
11236 && (this->end_ == NULL
11237 ? mpz_cmp_ui(ival, sval.length()) >= 0
11238 : mpz_cmp_ui(ival, sval.length()) > 0)))
11240 go_error_at(this->start_->location(), "string index out of bounds");
11241 this->set_is_error();
11244 if (this->end_ != NULL && !this->end_->is_nil_expression())
11246 Numeric_constant enc;
11247 mpz_t eval;
11248 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11250 if (mpz_sgn(eval) < 0
11251 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11253 go_error_at(this->end_->location(), "string index out of bounds");
11254 this->set_is_error();
11256 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11257 this->report_error(_("inverted slice range"));
11258 mpz_clear(eval);
11261 if (ival_valid)
11262 mpz_clear(ival);
11265 // Get the backend representation for a string index.
11267 Bexpression*
11268 String_index_expression::do_get_backend(Translate_context* context)
11270 Location loc = this->location();
11271 Expression* string_arg = this->string_;
11272 if (this->string_->type()->points_to() != NULL)
11273 string_arg = Expression::make_dereference(this->string_,
11274 NIL_CHECK_NOT_NEEDED, loc);
11276 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11278 int code = (this->end_ == NULL
11279 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11280 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11282 Gogo* gogo = context->gogo();
11283 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11285 Type* int_type = Type::lookup_integer_type("int");
11287 // It is possible that an error occurred earlier because the start index
11288 // cannot be represented as an integer type. In this case, we shouldn't
11289 // try casting the starting index into an integer since
11290 // Type_conversion_expression will fail to get the backend representation.
11291 // FIXME.
11292 if (this->start_->type()->integer_type() == NULL
11293 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11295 go_assert(saw_errors());
11296 return context->backend()->error_expression();
11299 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11300 Bfunction* bfn = context->function()->func_value()->get_decl();
11302 if (this->end_ == NULL)
11304 Expression* length =
11305 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11307 Expression* start_too_large =
11308 Expression::make_binary(OPERATOR_GE, start, length, loc);
11309 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11310 bad_index, loc);
11311 Expression* bytes =
11312 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11314 Bexpression* bstart = start->get_backend(context);
11315 Bexpression* ptr = bytes->get_backend(context);
11316 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11317 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11318 Bexpression* index =
11319 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11321 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11322 Bexpression* index_error = bad_index->get_backend(context);
11323 return gogo->backend()->conditional_expression(bfn, byte_btype,
11324 index_error, crash,
11325 index, loc);
11328 Expression* end = NULL;
11329 if (this->end_->is_nil_expression())
11330 end = Expression::make_integer_sl(-1, int_type, loc);
11331 else
11333 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11334 bad_index =
11335 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11336 end = Expression::make_cast(int_type, this->end_, loc);
11339 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11340 string_arg, start, end);
11341 Bexpression* bstrslice = strslice->get_backend(context);
11343 Btype* str_btype = strslice->type()->get_backend(gogo);
11344 Bexpression* index_error = bad_index->get_backend(context);
11345 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11346 crash, bstrslice, loc);
11349 // Dump ast representation for a string index expression.
11351 void
11352 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11353 const
11355 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11356 this->start_, this->end_, NULL);
11359 // Make a string index expression. END may be NULL.
11361 Expression*
11362 Expression::make_string_index(Expression* string, Expression* start,
11363 Expression* end, Location location)
11365 return new String_index_expression(string, start, end, location);
11368 // Class Map_index.
11370 // Get the type of the map.
11372 Map_type*
11373 Map_index_expression::get_map_type() const
11375 Map_type* mt = this->map_->type()->map_type();
11376 if (mt == NULL)
11377 go_assert(saw_errors());
11378 return mt;
11381 // Map index traversal.
11384 Map_index_expression::do_traverse(Traverse* traverse)
11386 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11387 return TRAVERSE_EXIT;
11388 return Expression::traverse(&this->index_, traverse);
11391 // We need to pass in a pointer to the key, so flatten the index into a
11392 // temporary variable if it isn't already. The value pointer will be
11393 // dereferenced and checked for nil, so flatten into a temporary to avoid
11394 // recomputation.
11396 Expression*
11397 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11398 Statement_inserter* inserter)
11400 Location loc = this->location();
11401 Map_type* mt = this->get_map_type();
11402 if (this->index()->is_error_expression()
11403 || this->index()->type()->is_error_type()
11404 || mt->is_error_type())
11406 go_assert(saw_errors());
11407 return Expression::make_error(loc);
11410 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11412 if (this->index_->type()->interface_type() != NULL
11413 && !this->index_->is_variable())
11415 Temporary_statement* temp =
11416 Statement::make_temporary(NULL, this->index_, loc);
11417 inserter->insert(temp);
11418 this->index_ = Expression::make_temporary_reference(temp, loc);
11420 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11421 this->index_, loc);
11424 if (!this->index_->is_variable())
11426 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11427 loc);
11428 inserter->insert(temp);
11429 this->index_ = Expression::make_temporary_reference(temp, loc);
11432 if (this->value_pointer_ == NULL)
11433 this->get_value_pointer(gogo);
11434 if (this->value_pointer_->is_error_expression()
11435 || this->value_pointer_->type()->is_error_type())
11436 return Expression::make_error(loc);
11437 if (!this->value_pointer_->is_variable())
11439 Temporary_statement* temp =
11440 Statement::make_temporary(NULL, this->value_pointer_, loc);
11441 inserter->insert(temp);
11442 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11445 return this;
11448 // Return the type of a map index.
11450 Type*
11451 Map_index_expression::do_type()
11453 Map_type* mt = this->get_map_type();
11454 if (mt == NULL)
11455 return Type::make_error_type();
11456 return mt->val_type();
11459 // Fix the type of a map index.
11461 void
11462 Map_index_expression::do_determine_type(const Type_context*)
11464 this->map_->determine_type_no_context();
11465 Map_type* mt = this->get_map_type();
11466 Type* key_type = mt == NULL ? NULL : mt->key_type();
11467 Type_context subcontext(key_type, false);
11468 this->index_->determine_type(&subcontext);
11471 // Check types of a map index.
11473 void
11474 Map_index_expression::do_check_types(Gogo*)
11476 std::string reason;
11477 Map_type* mt = this->get_map_type();
11478 if (mt == NULL)
11479 return;
11480 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11482 if (reason.empty())
11483 this->report_error(_("incompatible type for map index"));
11484 else
11486 go_error_at(this->location(), "incompatible type for map index (%s)",
11487 reason.c_str());
11488 this->set_is_error();
11493 // Get the backend representation for a map index.
11495 Bexpression*
11496 Map_index_expression::do_get_backend(Translate_context* context)
11498 Map_type* type = this->get_map_type();
11499 if (type == NULL)
11501 go_assert(saw_errors());
11502 return context->backend()->error_expression();
11505 go_assert(this->value_pointer_ != NULL
11506 && this->value_pointer_->is_variable());
11508 Expression* val = Expression::make_dereference(this->value_pointer_,
11509 NIL_CHECK_NOT_NEEDED,
11510 this->location());
11511 return val->get_backend(context);
11514 // Get an expression for the map index. This returns an expression
11515 // that evaluates to a pointer to a value. If the key is not in the
11516 // map, the pointer will point to a zero value.
11518 Expression*
11519 Map_index_expression::get_value_pointer(Gogo* gogo)
11521 if (this->value_pointer_ == NULL)
11523 Map_type* type = this->get_map_type();
11524 if (type == NULL)
11526 go_assert(saw_errors());
11527 return Expression::make_error(this->location());
11530 Location loc = this->location();
11531 Expression* map_ref = this->map_;
11533 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11534 this->index_,
11535 loc);
11537 Expression* zero = type->fat_zero_value(gogo);
11539 Expression* map_index;
11541 if (zero == NULL)
11542 map_index =
11543 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11544 Expression::make_type_descriptor(type, loc),
11545 map_ref, index_ptr);
11546 else
11547 map_index =
11548 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11549 Expression::make_type_descriptor(type, loc),
11550 map_ref, index_ptr, zero);
11552 Type* val_type = type->val_type();
11553 this->value_pointer_ =
11554 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11555 map_index, this->location());
11558 return this->value_pointer_;
11561 // Dump ast representation for a map index expression
11563 void
11564 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11565 const
11567 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11568 this->index_, NULL, NULL);
11571 // Make a map index expression.
11573 Map_index_expression*
11574 Expression::make_map_index(Expression* map, Expression* index,
11575 Location location)
11577 return new Map_index_expression(map, index, location);
11580 // Class Field_reference_expression.
11582 // Lower a field reference expression. There is nothing to lower, but
11583 // this is where we generate the tracking information for fields with
11584 // the magic go:"track" tag.
11586 Expression*
11587 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11588 Statement_inserter* inserter, int)
11590 Struct_type* struct_type = this->expr_->type()->struct_type();
11591 if (struct_type == NULL)
11593 // Error will be reported elsewhere.
11594 return this;
11596 const Struct_field* field = struct_type->field(this->field_index_);
11597 if (field == NULL)
11598 return this;
11599 if (!field->has_tag())
11600 return this;
11601 if (field->tag().find("go:\"track\"") == std::string::npos)
11602 return this;
11604 // References from functions generated by the compiler don't count.
11605 if (function != NULL && function->func_value()->is_type_specific_function())
11606 return this;
11608 // We have found a reference to a tracked field. Build a call to
11609 // the runtime function __go_fieldtrack with a string that describes
11610 // the field. FIXME: We should only call this once per referenced
11611 // field per function, not once for each reference to the field.
11613 if (this->called_fieldtrack_)
11614 return this;
11615 this->called_fieldtrack_ = true;
11617 Location loc = this->location();
11619 std::string s = "fieldtrack \"";
11620 Named_type* nt = this->expr_->type()->named_type();
11621 if (nt == NULL || nt->named_object()->package() == NULL)
11622 s.append(gogo->pkgpath());
11623 else
11624 s.append(nt->named_object()->package()->pkgpath());
11625 s.push_back('.');
11626 if (nt != NULL)
11627 s.append(Gogo::unpack_hidden_name(nt->name()));
11628 s.push_back('.');
11629 s.append(field->field_name());
11630 s.push_back('"');
11632 // We can't use a string here, because internally a string holds a
11633 // pointer to the actual bytes; when the linker garbage collects the
11634 // string, it won't garbage collect the bytes. So we use a
11635 // [...]byte.
11637 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11639 Type* byte_type = gogo->lookup_global("byte")->type_value();
11640 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11641 array_type->set_is_array_incomparable();
11643 Expression_list* bytes = new Expression_list();
11644 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11646 unsigned char c = static_cast<unsigned char>(*p);
11647 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11650 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11651 bytes, false, loc);
11653 Variable* var = new Variable(array_type, e, true, false, false, loc);
11655 static int count;
11656 char buf[50];
11657 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11658 ++count;
11660 Named_object* no = gogo->add_variable(buf, var);
11661 e = Expression::make_var_reference(no, loc);
11662 e = Expression::make_unary(OPERATOR_AND, e, loc);
11664 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11665 gogo->lower_expression(function, inserter, &call);
11666 inserter->insert(Statement::make_statement(call, false));
11668 // Put this function, and the global variable we just created, into
11669 // unique sections. This will permit the linker to garbage collect
11670 // them if they are not referenced. The effect is that the only
11671 // strings, indicating field references, that will wind up in the
11672 // executable will be those for functions that are actually needed.
11673 if (function != NULL)
11674 function->func_value()->set_in_unique_section();
11675 var->set_in_unique_section();
11677 return this;
11680 // Return the type of a field reference.
11682 Type*
11683 Field_reference_expression::do_type()
11685 Type* type = this->expr_->type();
11686 if (type->is_error())
11687 return type;
11688 Struct_type* struct_type = type->struct_type();
11689 go_assert(struct_type != NULL);
11690 return struct_type->field(this->field_index_)->type();
11693 // Check the types for a field reference.
11695 void
11696 Field_reference_expression::do_check_types(Gogo*)
11698 Type* type = this->expr_->type();
11699 if (type->is_error())
11700 return;
11701 Struct_type* struct_type = type->struct_type();
11702 go_assert(struct_type != NULL);
11703 go_assert(struct_type->field(this->field_index_) != NULL);
11706 // Get the backend representation for a field reference.
11708 Bexpression*
11709 Field_reference_expression::do_get_backend(Translate_context* context)
11711 Bexpression* bstruct = this->expr_->get_backend(context);
11712 return context->gogo()->backend()->struct_field_expression(bstruct,
11713 this->field_index_,
11714 this->location());
11717 // Dump ast representation for a field reference expression.
11719 void
11720 Field_reference_expression::do_dump_expression(
11721 Ast_dump_context* ast_dump_context) const
11723 this->expr_->dump_expression(ast_dump_context);
11724 ast_dump_context->ostream() << "." << this->field_index_;
11727 // Make a reference to a qualified identifier in an expression.
11729 Field_reference_expression*
11730 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11731 Location location)
11733 return new Field_reference_expression(expr, field_index, location);
11736 // Class Interface_field_reference_expression.
11738 // Return an expression for the pointer to the function to call.
11740 Expression*
11741 Interface_field_reference_expression::get_function()
11743 Expression* ref = this->expr_;
11744 Location loc = this->location();
11745 if (ref->type()->points_to() != NULL)
11746 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
11748 Expression* mtable =
11749 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11750 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11752 std::string name = Gogo::unpack_hidden_name(this->name_);
11753 unsigned int index;
11754 const Struct_field* field = mtable_type->find_local_field(name, &index);
11755 go_assert(field != NULL);
11757 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
11758 return Expression::make_field_reference(mtable, index, loc);
11761 // Return an expression for the first argument to pass to the interface
11762 // function.
11764 Expression*
11765 Interface_field_reference_expression::get_underlying_object()
11767 Expression* expr = this->expr_;
11768 if (expr->type()->points_to() != NULL)
11769 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
11770 this->location());
11771 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11772 this->location());
11775 // Traversal.
11778 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11780 return Expression::traverse(&this->expr_, traverse);
11783 // Lower the expression. If this expression is not called, we need to
11784 // evaluate the expression twice when converting to the backend
11785 // interface. So introduce a temporary variable if necessary.
11787 Expression*
11788 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11789 Statement_inserter* inserter)
11791 if (this->expr_->is_error_expression()
11792 || this->expr_->type()->is_error_type())
11794 go_assert(saw_errors());
11795 return Expression::make_error(this->location());
11798 if (!this->expr_->is_variable())
11800 Temporary_statement* temp =
11801 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11802 inserter->insert(temp);
11803 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11804 this->location());
11806 return this;
11809 // Return the type of an interface field reference.
11811 Type*
11812 Interface_field_reference_expression::do_type()
11814 Type* expr_type = this->expr_->type();
11816 Type* points_to = expr_type->points_to();
11817 if (points_to != NULL)
11818 expr_type = points_to;
11820 Interface_type* interface_type = expr_type->interface_type();
11821 if (interface_type == NULL)
11822 return Type::make_error_type();
11824 const Typed_identifier* method = interface_type->find_method(this->name_);
11825 if (method == NULL)
11826 return Type::make_error_type();
11828 return method->type();
11831 // Determine types.
11833 void
11834 Interface_field_reference_expression::do_determine_type(const Type_context*)
11836 this->expr_->determine_type_no_context();
11839 // Check the types for an interface field reference.
11841 void
11842 Interface_field_reference_expression::do_check_types(Gogo*)
11844 Type* type = this->expr_->type();
11846 Type* points_to = type->points_to();
11847 if (points_to != NULL)
11848 type = points_to;
11850 Interface_type* interface_type = type->interface_type();
11851 if (interface_type == NULL)
11853 if (!type->is_error_type())
11854 this->report_error(_("expected interface or pointer to interface"));
11856 else
11858 const Typed_identifier* method =
11859 interface_type->find_method(this->name_);
11860 if (method == NULL)
11862 go_error_at(this->location(), "method %qs not in interface",
11863 Gogo::message_name(this->name_).c_str());
11864 this->set_is_error();
11869 // If an interface field reference is not simply called, then it is
11870 // represented as a closure. The closure will hold a single variable,
11871 // the value of the interface on which the method should be called.
11872 // The function will be a simple thunk that pulls the value from the
11873 // closure and calls the method with the remaining arguments.
11875 // Because method values are not common, we don't build all thunks for
11876 // all possible interface methods, but instead only build them as we
11877 // need them. In particular, we even build them on demand for
11878 // interface methods defined in other packages.
11880 Interface_field_reference_expression::Interface_method_thunks
11881 Interface_field_reference_expression::interface_method_thunks;
11883 // Find or create the thunk to call method NAME on TYPE.
11885 Named_object*
11886 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11887 Interface_type* type,
11888 const std::string& name)
11890 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11891 std::pair<Interface_method_thunks::iterator, bool> ins =
11892 Interface_field_reference_expression::interface_method_thunks.insert(val);
11893 if (ins.second)
11895 // This is the first time we have seen this interface.
11896 ins.first->second = new Method_thunks();
11899 for (Method_thunks::const_iterator p = ins.first->second->begin();
11900 p != ins.first->second->end();
11901 p++)
11902 if (p->first == name)
11903 return p->second;
11905 Location loc = type->location();
11907 const Typed_identifier* method_id = type->find_method(name);
11908 if (method_id == NULL)
11909 return Named_object::make_erroneous_name(Gogo::thunk_name());
11911 Function_type* orig_fntype = method_id->type()->function_type();
11912 if (orig_fntype == NULL)
11913 return Named_object::make_erroneous_name(Gogo::thunk_name());
11915 Struct_field_list* sfl = new Struct_field_list();
11916 // The type here is wrong--it should be the C function type. But it
11917 // doesn't really matter.
11918 Type* vt = Type::make_pointer_type(Type::make_void_type());
11919 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11920 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11921 Struct_type* st = Type::make_struct_type(sfl, loc);
11922 st->set_is_struct_incomparable();
11923 Type* closure_type = Type::make_pointer_type(st);
11925 Function_type* new_fntype = orig_fntype->copy_with_names();
11927 std::string thunk_name = Gogo::thunk_name();
11928 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11929 false, loc);
11931 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11932 cvar->set_is_used();
11933 cvar->set_is_closure();
11934 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11935 NULL, cvar);
11936 new_no->func_value()->set_closure_var(cp);
11938 gogo->start_block(loc);
11940 // Field 0 of the closure is the function code pointer, field 1 is
11941 // the value on which to invoke the method.
11942 Expression* arg = Expression::make_var_reference(cp, loc);
11943 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
11944 arg = Expression::make_field_reference(arg, 1, loc);
11946 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11947 loc);
11949 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11950 Expression_list* args;
11951 if (orig_params == NULL || orig_params->empty())
11952 args = NULL;
11953 else
11955 const Typed_identifier_list* new_params = new_fntype->parameters();
11956 args = new Expression_list();
11957 for (Typed_identifier_list::const_iterator p = new_params->begin();
11958 p != new_params->end();
11959 ++p)
11961 Named_object* p_no = gogo->lookup(p->name(), NULL);
11962 go_assert(p_no != NULL
11963 && p_no->is_variable()
11964 && p_no->var_value()->is_parameter());
11965 args->push_back(Expression::make_var_reference(p_no, loc));
11969 Call_expression* call = Expression::make_call(ifre, args,
11970 orig_fntype->is_varargs(),
11971 loc);
11972 call->set_varargs_are_lowered();
11974 Statement* s = Statement::make_return_from_call(call, loc);
11975 gogo->add_statement(s);
11976 Block* b = gogo->finish_block(loc);
11977 gogo->add_block(b, loc);
11978 gogo->lower_block(new_no, b);
11979 gogo->flatten_block(new_no, b);
11980 gogo->finish_function(loc);
11982 ins.first->second->push_back(std::make_pair(name, new_no));
11983 return new_no;
11986 // Get the backend representation for a method value.
11988 Bexpression*
11989 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11991 Interface_type* type = this->expr_->type()->interface_type();
11992 if (type == NULL)
11994 go_assert(saw_errors());
11995 return context->backend()->error_expression();
11998 Named_object* thunk =
11999 Interface_field_reference_expression::create_thunk(context->gogo(),
12000 type, this->name_);
12001 if (thunk->is_erroneous())
12003 go_assert(saw_errors());
12004 return context->backend()->error_expression();
12007 // FIXME: We should lower this earlier, but we can't it lower it in
12008 // the lowering pass because at that point we don't know whether we
12009 // need to create the thunk or not. If the expression is called, we
12010 // don't need the thunk.
12012 Location loc = this->location();
12014 Struct_field_list* fields = new Struct_field_list();
12015 fields->push_back(Struct_field(Typed_identifier("fn.0",
12016 thunk->func_value()->type(),
12017 loc)));
12018 fields->push_back(Struct_field(Typed_identifier("val.1",
12019 this->expr_->type(),
12020 loc)));
12021 Struct_type* st = Type::make_struct_type(fields, loc);
12022 st->set_is_struct_incomparable();
12024 Expression_list* vals = new Expression_list();
12025 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12026 vals->push_back(this->expr_);
12028 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12029 Bexpression* bclosure =
12030 Expression::make_heap_expression(expr, loc)->get_backend(context);
12032 Gogo* gogo = context->gogo();
12033 Btype* btype = this->type()->get_backend(gogo);
12034 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12036 Expression* nil_check =
12037 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12038 Expression::make_nil(loc), loc);
12039 Bexpression* bnil_check = nil_check->get_backend(context);
12041 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12042 loc)->get_backend(context);
12044 Bfunction* bfn = context->function()->func_value()->get_decl();
12045 Bexpression* bcond =
12046 gogo->backend()->conditional_expression(bfn, NULL,
12047 bnil_check, bcrash, NULL, loc);
12048 Bfunction* bfunction = context->function()->func_value()->get_decl();
12049 Bstatement* cond_statement =
12050 gogo->backend()->expression_statement(bfunction, bcond);
12051 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12054 // Dump ast representation for an interface field reference.
12056 void
12057 Interface_field_reference_expression::do_dump_expression(
12058 Ast_dump_context* ast_dump_context) const
12060 this->expr_->dump_expression(ast_dump_context);
12061 ast_dump_context->ostream() << "." << this->name_;
12064 // Make a reference to a field in an interface.
12066 Expression*
12067 Expression::make_interface_field_reference(Expression* expr,
12068 const std::string& field,
12069 Location location)
12071 return new Interface_field_reference_expression(expr, field, location);
12074 // A general selector. This is a Parser_expression for LEFT.NAME. It
12075 // is lowered after we know the type of the left hand side.
12077 class Selector_expression : public Parser_expression
12079 public:
12080 Selector_expression(Expression* left, const std::string& name,
12081 Location location)
12082 : Parser_expression(EXPRESSION_SELECTOR, location),
12083 left_(left), name_(name)
12086 protected:
12088 do_traverse(Traverse* traverse)
12089 { return Expression::traverse(&this->left_, traverse); }
12091 Expression*
12092 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12094 Expression*
12095 do_copy()
12097 return new Selector_expression(this->left_->copy(), this->name_,
12098 this->location());
12101 void
12102 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12104 private:
12105 Expression*
12106 lower_method_expression(Gogo*);
12108 // The expression on the left hand side.
12109 Expression* left_;
12110 // The name on the right hand side.
12111 std::string name_;
12114 // Lower a selector expression once we know the real type of the left
12115 // hand side.
12117 Expression*
12118 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12119 int)
12121 Expression* left = this->left_;
12122 if (left->is_type_expression())
12123 return this->lower_method_expression(gogo);
12124 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12125 this->location());
12128 // Lower a method expression T.M or (*T).M. We turn this into a
12129 // function literal.
12131 Expression*
12132 Selector_expression::lower_method_expression(Gogo* gogo)
12134 Location location = this->location();
12135 Type* left_type = this->left_->type();
12136 Type* type = left_type;
12137 const std::string& name(this->name_);
12139 bool is_pointer;
12140 if (type->points_to() == NULL)
12141 is_pointer = false;
12142 else
12144 is_pointer = true;
12145 type = type->points_to();
12147 Named_type* nt = type->named_type();
12148 if (nt == NULL)
12150 go_error_at(location,
12151 ("method expression requires named type or "
12152 "pointer to named type"));
12153 return Expression::make_error(location);
12156 bool is_ambiguous;
12157 Method* method = nt->method_function(name, &is_ambiguous);
12158 const Typed_identifier* imethod = NULL;
12159 if (method == NULL && !is_pointer)
12161 Interface_type* it = nt->interface_type();
12162 if (it != NULL)
12163 imethod = it->find_method(name);
12166 if ((method == NULL && imethod == NULL)
12167 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12169 if (!is_ambiguous)
12170 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12171 is_pointer ? "*" : "",
12172 nt->message_name().c_str(),
12173 Gogo::message_name(name).c_str());
12174 else
12175 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12176 Gogo::message_name(name).c_str(),
12177 is_pointer ? "*" : "",
12178 nt->message_name().c_str());
12179 return Expression::make_error(location);
12182 if (method != NULL && !is_pointer && !method->is_value_method())
12184 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12185 nt->message_name().c_str(),
12186 Gogo::message_name(name).c_str());
12187 return Expression::make_error(location);
12190 // Build a new function type in which the receiver becomes the first
12191 // argument.
12192 Function_type* method_type;
12193 if (method != NULL)
12195 method_type = method->type();
12196 go_assert(method_type->is_method());
12198 else
12200 method_type = imethod->type()->function_type();
12201 go_assert(method_type != NULL && !method_type->is_method());
12204 const char* const receiver_name = "$this";
12205 Typed_identifier_list* parameters = new Typed_identifier_list();
12206 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12207 location));
12209 const Typed_identifier_list* method_parameters = method_type->parameters();
12210 if (method_parameters != NULL)
12212 int i = 0;
12213 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12214 p != method_parameters->end();
12215 ++p, ++i)
12217 if (!p->name().empty())
12218 parameters->push_back(*p);
12219 else
12221 char buf[20];
12222 snprintf(buf, sizeof buf, "$param%d", i);
12223 parameters->push_back(Typed_identifier(buf, p->type(),
12224 p->location()));
12229 const Typed_identifier_list* method_results = method_type->results();
12230 Typed_identifier_list* results;
12231 if (method_results == NULL)
12232 results = NULL;
12233 else
12235 results = new Typed_identifier_list();
12236 for (Typed_identifier_list::const_iterator p = method_results->begin();
12237 p != method_results->end();
12238 ++p)
12239 results->push_back(*p);
12242 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12243 location);
12244 if (method_type->is_varargs())
12245 fntype->set_is_varargs();
12247 // We generate methods which always takes a pointer to the receiver
12248 // as their first argument. If this is for a pointer type, we can
12249 // simply reuse the existing function. We use an internal hack to
12250 // get the right type.
12251 // FIXME: This optimization is disabled because it doesn't yet work
12252 // with function descriptors when the method expression is not
12253 // directly called.
12254 if (method != NULL && is_pointer && false)
12256 Named_object* mno = (method->needs_stub_method()
12257 ? method->stub_object()
12258 : method->named_object());
12259 Expression* f = Expression::make_func_reference(mno, NULL, location);
12260 f = Expression::make_cast(fntype, f, location);
12261 Type_conversion_expression* tce =
12262 static_cast<Type_conversion_expression*>(f);
12263 tce->set_may_convert_function_types();
12264 return f;
12267 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12268 location);
12270 Named_object* vno = gogo->lookup(receiver_name, NULL);
12271 go_assert(vno != NULL);
12272 Expression* ve = Expression::make_var_reference(vno, location);
12273 Expression* bm;
12274 if (method != NULL)
12275 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12276 else
12277 bm = Expression::make_interface_field_reference(ve, name, location);
12279 // Even though we found the method above, if it has an error type we
12280 // may see an error here.
12281 if (bm->is_error_expression())
12283 gogo->finish_function(location);
12284 return bm;
12287 Expression_list* args;
12288 if (parameters->size() <= 1)
12289 args = NULL;
12290 else
12292 args = new Expression_list();
12293 Typed_identifier_list::const_iterator p = parameters->begin();
12294 ++p;
12295 for (; p != parameters->end(); ++p)
12297 vno = gogo->lookup(p->name(), NULL);
12298 go_assert(vno != NULL);
12299 args->push_back(Expression::make_var_reference(vno, location));
12303 gogo->start_block(location);
12305 Call_expression* call = Expression::make_call(bm, args,
12306 method_type->is_varargs(),
12307 location);
12309 Statement* s = Statement::make_return_from_call(call, location);
12310 gogo->add_statement(s);
12312 Block* b = gogo->finish_block(location);
12314 gogo->add_block(b, location);
12316 // Lower the call in case there are multiple results.
12317 gogo->lower_block(no, b);
12318 gogo->flatten_block(no, b);
12320 gogo->finish_function(location);
12322 return Expression::make_func_reference(no, NULL, location);
12325 // Dump the ast for a selector expression.
12327 void
12328 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12329 const
12331 ast_dump_context->dump_expression(this->left_);
12332 ast_dump_context->ostream() << ".";
12333 ast_dump_context->ostream() << this->name_;
12336 // Make a selector expression.
12338 Expression*
12339 Expression::make_selector(Expression* left, const std::string& name,
12340 Location location)
12342 return new Selector_expression(left, name, location);
12345 // Class Allocation_expression.
12348 Allocation_expression::do_traverse(Traverse* traverse)
12350 return Type::traverse(this->type_, traverse);
12353 Type*
12354 Allocation_expression::do_type()
12356 return Type::make_pointer_type(this->type_);
12359 void
12360 Allocation_expression::do_check_types(Gogo*)
12362 if (!this->type_->in_heap())
12363 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12366 // Make a copy of an allocation expression.
12368 Expression*
12369 Allocation_expression::do_copy()
12371 Allocation_expression* alloc =
12372 new Allocation_expression(this->type_, this->location());
12373 if (this->allocate_on_stack_)
12374 alloc->set_allocate_on_stack();
12375 return alloc;
12378 // Return the backend representation for an allocation expression.
12380 Bexpression*
12381 Allocation_expression::do_get_backend(Translate_context* context)
12383 Gogo* gogo = context->gogo();
12384 Location loc = this->location();
12386 if (this->allocate_on_stack_)
12388 int64_t size;
12389 bool ok = this->type_->backend_type_size(gogo, &size);
12390 if (!ok)
12392 go_assert(saw_errors());
12393 return gogo->backend()->error_expression();
12395 return gogo->backend()->stack_allocation_expression(size, loc);
12398 Btype* btype = this->type_->get_backend(gogo);
12399 Bexpression* space =
12400 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12401 Btype* pbtype = gogo->backend()->pointer_type(btype);
12402 return gogo->backend()->convert_expression(pbtype, space, loc);
12405 // Dump ast representation for an allocation expression.
12407 void
12408 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12409 const
12411 ast_dump_context->ostream() << "new(";
12412 ast_dump_context->dump_type(this->type_);
12413 ast_dump_context->ostream() << ")";
12416 // Make an allocation expression.
12418 Expression*
12419 Expression::make_allocation(Type* type, Location location)
12421 return new Allocation_expression(type, location);
12424 // Class Ordered_value_list.
12427 Ordered_value_list::traverse_vals(Traverse* traverse)
12429 if (this->vals_ != NULL)
12431 if (this->traverse_order_ == NULL)
12433 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12434 return TRAVERSE_EXIT;
12436 else
12438 for (std::vector<unsigned long>::const_iterator p =
12439 this->traverse_order_->begin();
12440 p != this->traverse_order_->end();
12441 ++p)
12443 if (Expression::traverse(&this->vals_->at(*p), traverse)
12444 == TRAVERSE_EXIT)
12445 return TRAVERSE_EXIT;
12449 return TRAVERSE_CONTINUE;
12452 // Class Struct_construction_expression.
12454 // Traversal.
12457 Struct_construction_expression::do_traverse(Traverse* traverse)
12459 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12460 return TRAVERSE_EXIT;
12461 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12462 return TRAVERSE_EXIT;
12463 return TRAVERSE_CONTINUE;
12466 // Return whether this is a constant initializer.
12468 bool
12469 Struct_construction_expression::is_constant_struct() const
12471 if (this->vals() == NULL)
12472 return true;
12473 for (Expression_list::const_iterator pv = this->vals()->begin();
12474 pv != this->vals()->end();
12475 ++pv)
12477 if (*pv != NULL
12478 && !(*pv)->is_constant()
12479 && (!(*pv)->is_composite_literal()
12480 || (*pv)->is_nonconstant_composite_literal()))
12481 return false;
12484 const Struct_field_list* fields = this->type_->struct_type()->fields();
12485 for (Struct_field_list::const_iterator pf = fields->begin();
12486 pf != fields->end();
12487 ++pf)
12489 // There are no constant constructors for interfaces.
12490 if (pf->type()->interface_type() != NULL)
12491 return false;
12494 return true;
12497 // Return whether this struct can be used as a constant initializer.
12499 bool
12500 Struct_construction_expression::do_is_static_initializer() const
12502 if (this->vals() == NULL)
12503 return true;
12504 for (Expression_list::const_iterator pv = this->vals()->begin();
12505 pv != this->vals()->end();
12506 ++pv)
12508 if (*pv != NULL && !(*pv)->is_static_initializer())
12509 return false;
12512 const Struct_field_list* fields = this->type_->struct_type()->fields();
12513 for (Struct_field_list::const_iterator pf = fields->begin();
12514 pf != fields->end();
12515 ++pf)
12517 // There are no constant constructors for interfaces.
12518 if (pf->type()->interface_type() != NULL)
12519 return false;
12522 return true;
12525 // Final type determination.
12527 void
12528 Struct_construction_expression::do_determine_type(const Type_context*)
12530 if (this->vals() == NULL)
12531 return;
12532 const Struct_field_list* fields = this->type_->struct_type()->fields();
12533 Expression_list::const_iterator pv = this->vals()->begin();
12534 for (Struct_field_list::const_iterator pf = fields->begin();
12535 pf != fields->end();
12536 ++pf, ++pv)
12538 if (pv == this->vals()->end())
12539 return;
12540 if (*pv != NULL)
12542 Type_context subcontext(pf->type(), false);
12543 (*pv)->determine_type(&subcontext);
12546 // Extra values are an error we will report elsewhere; we still want
12547 // to determine the type to avoid knockon errors.
12548 for (; pv != this->vals()->end(); ++pv)
12549 (*pv)->determine_type_no_context();
12552 // Check types.
12554 void
12555 Struct_construction_expression::do_check_types(Gogo*)
12557 if (this->vals() == NULL)
12558 return;
12560 Struct_type* st = this->type_->struct_type();
12561 if (this->vals()->size() > st->field_count())
12563 this->report_error(_("too many expressions for struct"));
12564 return;
12567 const Struct_field_list* fields = st->fields();
12568 Expression_list::const_iterator pv = this->vals()->begin();
12569 int i = 0;
12570 for (Struct_field_list::const_iterator pf = fields->begin();
12571 pf != fields->end();
12572 ++pf, ++pv, ++i)
12574 if (pv == this->vals()->end())
12576 this->report_error(_("too few expressions for struct"));
12577 break;
12580 if (*pv == NULL)
12581 continue;
12583 std::string reason;
12584 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12586 if (reason.empty())
12587 go_error_at((*pv)->location(),
12588 "incompatible type for field %d in struct construction",
12589 i + 1);
12590 else
12591 go_error_at((*pv)->location(),
12592 ("incompatible type for field %d in "
12593 "struct construction (%s)"),
12594 i + 1, reason.c_str());
12595 this->set_is_error();
12598 go_assert(pv == this->vals()->end());
12601 // Flatten a struct construction expression. Store the values into
12602 // temporaries in case they need interface conversion.
12604 Expression*
12605 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12606 Statement_inserter* inserter)
12608 if (this->vals() == NULL)
12609 return this;
12611 // If this is a constant struct, we don't need temporaries.
12612 if (this->is_constant_struct() || this->is_static_initializer())
12613 return this;
12615 Location loc = this->location();
12616 for (Expression_list::iterator pv = this->vals()->begin();
12617 pv != this->vals()->end();
12618 ++pv)
12620 if (*pv != NULL)
12622 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12624 go_assert(saw_errors());
12625 return Expression::make_error(loc);
12627 if (!(*pv)->is_variable())
12629 Temporary_statement* temp =
12630 Statement::make_temporary(NULL, *pv, loc);
12631 inserter->insert(temp);
12632 *pv = Expression::make_temporary_reference(temp, loc);
12636 return this;
12639 // Return the backend representation for constructing a struct.
12641 Bexpression*
12642 Struct_construction_expression::do_get_backend(Translate_context* context)
12644 Gogo* gogo = context->gogo();
12646 Btype* btype = this->type_->get_backend(gogo);
12647 if (this->vals() == NULL)
12648 return gogo->backend()->zero_expression(btype);
12650 const Struct_field_list* fields = this->type_->struct_type()->fields();
12651 Expression_list::const_iterator pv = this->vals()->begin();
12652 std::vector<Bexpression*> init;
12653 for (Struct_field_list::const_iterator pf = fields->begin();
12654 pf != fields->end();
12655 ++pf)
12657 Btype* fbtype = pf->type()->get_backend(gogo);
12658 if (pv == this->vals()->end())
12659 init.push_back(gogo->backend()->zero_expression(fbtype));
12660 else if (*pv == NULL)
12662 init.push_back(gogo->backend()->zero_expression(fbtype));
12663 ++pv;
12665 else
12667 Expression* val =
12668 Expression::convert_for_assignment(gogo, pf->type(),
12669 *pv, this->location());
12670 init.push_back(val->get_backend(context));
12671 ++pv;
12674 return gogo->backend()->constructor_expression(btype, init, this->location());
12677 // Export a struct construction.
12679 void
12680 Struct_construction_expression::do_export(Export* exp) const
12682 exp->write_c_string("convert(");
12683 exp->write_type(this->type_);
12684 for (Expression_list::const_iterator pv = this->vals()->begin();
12685 pv != this->vals()->end();
12686 ++pv)
12688 exp->write_c_string(", ");
12689 if (*pv != NULL)
12690 (*pv)->export_expression(exp);
12692 exp->write_c_string(")");
12695 // Dump ast representation of a struct construction expression.
12697 void
12698 Struct_construction_expression::do_dump_expression(
12699 Ast_dump_context* ast_dump_context) const
12701 ast_dump_context->dump_type(this->type_);
12702 ast_dump_context->ostream() << "{";
12703 ast_dump_context->dump_expression_list(this->vals());
12704 ast_dump_context->ostream() << "}";
12707 // Make a struct composite literal. This used by the thunk code.
12709 Expression*
12710 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12711 Location location)
12713 go_assert(type->struct_type() != NULL);
12714 return new Struct_construction_expression(type, vals, location);
12717 // Class Array_construction_expression.
12719 // Traversal.
12722 Array_construction_expression::do_traverse(Traverse* traverse)
12724 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12725 return TRAVERSE_EXIT;
12726 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12727 return TRAVERSE_EXIT;
12728 return TRAVERSE_CONTINUE;
12731 // Return whether this is a constant initializer.
12733 bool
12734 Array_construction_expression::is_constant_array() const
12736 if (this->vals() == NULL)
12737 return true;
12739 // There are no constant constructors for interfaces.
12740 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12741 return false;
12743 for (Expression_list::const_iterator pv = this->vals()->begin();
12744 pv != this->vals()->end();
12745 ++pv)
12747 if (*pv != NULL
12748 && !(*pv)->is_constant()
12749 && (!(*pv)->is_composite_literal()
12750 || (*pv)->is_nonconstant_composite_literal()))
12751 return false;
12753 return true;
12756 // Return whether this can be used a constant initializer.
12758 bool
12759 Array_construction_expression::do_is_static_initializer() const
12761 if (this->vals() == NULL)
12762 return true;
12764 // There are no constant constructors for interfaces.
12765 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12766 return false;
12768 for (Expression_list::const_iterator pv = this->vals()->begin();
12769 pv != this->vals()->end();
12770 ++pv)
12772 if (*pv != NULL && !(*pv)->is_static_initializer())
12773 return false;
12775 return true;
12778 // Final type determination.
12780 void
12781 Array_construction_expression::do_determine_type(const Type_context*)
12783 if (this->vals() == NULL)
12784 return;
12785 Type_context subcontext(this->type_->array_type()->element_type(), false);
12786 for (Expression_list::const_iterator pv = this->vals()->begin();
12787 pv != this->vals()->end();
12788 ++pv)
12790 if (*pv != NULL)
12791 (*pv)->determine_type(&subcontext);
12795 // Check types.
12797 void
12798 Array_construction_expression::do_check_types(Gogo*)
12800 if (this->vals() == NULL)
12801 return;
12803 Array_type* at = this->type_->array_type();
12804 int i = 0;
12805 Type* element_type = at->element_type();
12806 for (Expression_list::const_iterator pv = this->vals()->begin();
12807 pv != this->vals()->end();
12808 ++pv, ++i)
12810 if (*pv != NULL
12811 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12813 go_error_at((*pv)->location(),
12814 "incompatible type for element %d in composite literal",
12815 i + 1);
12816 this->set_is_error();
12821 // Flatten an array construction expression. Store the values into
12822 // temporaries in case they need interface conversion.
12824 Expression*
12825 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12826 Statement_inserter* inserter)
12828 if (this->vals() == NULL)
12829 return this;
12831 // If this is a constant array, we don't need temporaries.
12832 if (this->is_constant_array() || this->is_static_initializer())
12833 return this;
12835 Location loc = this->location();
12836 for (Expression_list::iterator pv = this->vals()->begin();
12837 pv != this->vals()->end();
12838 ++pv)
12840 if (*pv != NULL)
12842 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12844 go_assert(saw_errors());
12845 return Expression::make_error(loc);
12847 if (!(*pv)->is_variable())
12849 Temporary_statement* temp =
12850 Statement::make_temporary(NULL, *pv, loc);
12851 inserter->insert(temp);
12852 *pv = Expression::make_temporary_reference(temp, loc);
12856 return this;
12859 // Get a constructor expression for the array values.
12861 Bexpression*
12862 Array_construction_expression::get_constructor(Translate_context* context,
12863 Btype* array_btype)
12865 Type* element_type = this->type_->array_type()->element_type();
12867 std::vector<unsigned long> indexes;
12868 std::vector<Bexpression*> vals;
12869 Gogo* gogo = context->gogo();
12870 if (this->vals() != NULL)
12872 size_t i = 0;
12873 std::vector<unsigned long>::const_iterator pi;
12874 if (this->indexes_ != NULL)
12875 pi = this->indexes_->begin();
12876 for (Expression_list::const_iterator pv = this->vals()->begin();
12877 pv != this->vals()->end();
12878 ++pv, ++i)
12880 if (this->indexes_ != NULL)
12881 go_assert(pi != this->indexes_->end());
12883 if (this->indexes_ == NULL)
12884 indexes.push_back(i);
12885 else
12886 indexes.push_back(*pi);
12887 if (*pv == NULL)
12889 Btype* ebtype = element_type->get_backend(gogo);
12890 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12891 vals.push_back(zv);
12893 else
12895 Expression* val_expr =
12896 Expression::convert_for_assignment(gogo, element_type, *pv,
12897 this->location());
12898 vals.push_back(val_expr->get_backend(context));
12900 if (this->indexes_ != NULL)
12901 ++pi;
12903 if (this->indexes_ != NULL)
12904 go_assert(pi == this->indexes_->end());
12906 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12907 vals, this->location());
12910 // Export an array construction.
12912 void
12913 Array_construction_expression::do_export(Export* exp) const
12915 exp->write_c_string("convert(");
12916 exp->write_type(this->type_);
12917 if (this->vals() != NULL)
12919 std::vector<unsigned long>::const_iterator pi;
12920 if (this->indexes_ != NULL)
12921 pi = this->indexes_->begin();
12922 for (Expression_list::const_iterator pv = this->vals()->begin();
12923 pv != this->vals()->end();
12924 ++pv)
12926 exp->write_c_string(", ");
12928 if (this->indexes_ != NULL)
12930 char buf[100];
12931 snprintf(buf, sizeof buf, "%lu", *pi);
12932 exp->write_c_string(buf);
12933 exp->write_c_string(":");
12936 if (*pv != NULL)
12937 (*pv)->export_expression(exp);
12939 if (this->indexes_ != NULL)
12940 ++pi;
12943 exp->write_c_string(")");
12946 // Dump ast representation of an array construction expression.
12948 void
12949 Array_construction_expression::do_dump_expression(
12950 Ast_dump_context* ast_dump_context) const
12952 Expression* length = this->type_->array_type()->length();
12954 ast_dump_context->ostream() << "[" ;
12955 if (length != NULL)
12957 ast_dump_context->dump_expression(length);
12959 ast_dump_context->ostream() << "]" ;
12960 ast_dump_context->dump_type(this->type_);
12961 this->dump_slice_storage_expression(ast_dump_context);
12962 ast_dump_context->ostream() << "{" ;
12963 if (this->indexes_ == NULL)
12964 ast_dump_context->dump_expression_list(this->vals());
12965 else
12967 Expression_list::const_iterator pv = this->vals()->begin();
12968 for (std::vector<unsigned long>::const_iterator pi =
12969 this->indexes_->begin();
12970 pi != this->indexes_->end();
12971 ++pi, ++pv)
12973 if (pi != this->indexes_->begin())
12974 ast_dump_context->ostream() << ", ";
12975 ast_dump_context->ostream() << *pi << ':';
12976 ast_dump_context->dump_expression(*pv);
12979 ast_dump_context->ostream() << "}" ;
12983 // Class Fixed_array_construction_expression.
12985 Fixed_array_construction_expression::Fixed_array_construction_expression(
12986 Type* type, const std::vector<unsigned long>* indexes,
12987 Expression_list* vals, Location location)
12988 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12989 type, indexes, vals, location)
12990 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12992 // Return the backend representation for constructing a fixed array.
12994 Bexpression*
12995 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12997 Type* type = this->type();
12998 Btype* btype = type->get_backend(context->gogo());
12999 return this->get_constructor(context, btype);
13002 Expression*
13003 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13004 Location location)
13006 go_assert(type->array_type() != NULL && !type->is_slice_type());
13007 return new Fixed_array_construction_expression(type, NULL, vals, location);
13010 // Class Slice_construction_expression.
13012 Slice_construction_expression::Slice_construction_expression(
13013 Type* type, const std::vector<unsigned long>* indexes,
13014 Expression_list* vals, Location location)
13015 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13016 type, indexes, vals, location),
13017 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13018 storage_escapes_(true)
13020 go_assert(type->is_slice_type());
13022 unsigned long lenval;
13023 Expression* length;
13024 if (vals == NULL || vals->empty())
13025 lenval = 0;
13026 else
13028 if (this->indexes() == NULL)
13029 lenval = vals->size();
13030 else
13031 lenval = indexes->back() + 1;
13033 Type* int_type = Type::lookup_integer_type("int");
13034 length = Expression::make_integer_ul(lenval, int_type, location);
13035 Type* element_type = type->array_type()->element_type();
13036 Array_type* array_type = Type::make_array_type(element_type, length);
13037 array_type->set_is_array_incomparable();
13038 this->valtype_ = array_type;
13041 // Traversal.
13044 Slice_construction_expression::do_traverse(Traverse* traverse)
13046 if (this->Array_construction_expression::do_traverse(traverse)
13047 == TRAVERSE_EXIT)
13048 return TRAVERSE_EXIT;
13049 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13050 return TRAVERSE_EXIT;
13051 if (this->array_val_ != NULL
13052 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13053 return TRAVERSE_EXIT;
13054 if (this->slice_storage_ != NULL
13055 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13056 return TRAVERSE_EXIT;
13057 return TRAVERSE_CONTINUE;
13060 // Helper routine to create fixed array value underlying the slice literal.
13061 // May be called during flattening, or later during do_get_backend().
13063 Expression*
13064 Slice_construction_expression::create_array_val()
13066 Array_type* array_type = this->type()->array_type();
13067 if (array_type == NULL)
13069 go_assert(this->type()->is_error());
13070 return NULL;
13073 Location loc = this->location();
13074 go_assert(this->valtype_ != NULL);
13076 Expression_list* vals = this->vals();
13077 return new Fixed_array_construction_expression(
13078 this->valtype_, this->indexes(), vals, loc);
13081 // If we're previous established that the slice storage does not
13082 // escape, then create a separate array temp val here for it. We
13083 // need to do this as part of flattening so as to be able to insert
13084 // the new temp statement.
13086 Expression*
13087 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13088 Statement_inserter* inserter)
13090 if (this->type()->array_type() == NULL)
13091 return NULL;
13093 // Base class flattening first
13094 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13096 // Create a stack-allocated storage temp if storage won't escape
13097 if (!this->storage_escapes_
13098 && this->slice_storage_ == NULL
13099 && this->element_count() > 0)
13101 Location loc = this->location();
13102 this->array_val_ = this->create_array_val();
13103 go_assert(this->array_val_);
13104 Temporary_statement* temp =
13105 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13106 inserter->insert(temp);
13107 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13109 return this;
13112 // When dumping a slice construction expression that has an explicit
13113 // storeage temp, emit the temp here (if we don't do this the storage
13114 // temp appears unused in the AST dump).
13116 void
13117 Slice_construction_expression::
13118 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13120 if (this->slice_storage_ == NULL)
13121 return;
13122 ast_dump_context->ostream() << "storage=" ;
13123 ast_dump_context->dump_expression(this->slice_storage_);
13126 // Return the backend representation for constructing a slice.
13128 Bexpression*
13129 Slice_construction_expression::do_get_backend(Translate_context* context)
13131 if (this->array_val_ == NULL)
13132 this->array_val_ = this->create_array_val();
13133 if (this->array_val_ == NULL)
13135 go_assert(this->type()->is_error());
13136 return context->backend()->error_expression();
13139 Location loc = this->location();
13141 bool is_static_initializer = this->array_val_->is_static_initializer();
13143 // We have to copy the initial values into heap memory if we are in
13144 // a function or if the values are not constants.
13145 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13147 Expression* space;
13149 if (this->slice_storage_ != NULL)
13151 go_assert(!this->storage_escapes_);
13152 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13154 else if (!copy_to_heap)
13156 // The initializer will only run once.
13157 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13158 space->unary_expression()->set_is_slice_init();
13160 else
13162 go_assert(this->storage_escapes_ || this->element_count() == 0);
13163 space = Expression::make_heap_expression(this->array_val_, loc);
13166 // Build a constructor for the slice.
13167 Expression* len = this->valtype_->array_type()->length();
13168 Expression* slice_val =
13169 Expression::make_slice_value(this->type(), space, len, len, loc);
13170 return slice_val->get_backend(context);
13173 // Make a slice composite literal. This is used by the type
13174 // descriptor code.
13176 Slice_construction_expression*
13177 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13178 Location location)
13180 go_assert(type->is_slice_type());
13181 return new Slice_construction_expression(type, NULL, vals, location);
13184 // Class Map_construction_expression.
13186 // Traversal.
13189 Map_construction_expression::do_traverse(Traverse* traverse)
13191 if (this->vals_ != NULL
13192 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13193 return TRAVERSE_EXIT;
13194 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13195 return TRAVERSE_EXIT;
13196 return TRAVERSE_CONTINUE;
13199 // Flatten constructor initializer into a temporary variable since
13200 // we need to take its address for __go_construct_map.
13202 Expression*
13203 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13204 Statement_inserter* inserter)
13206 if (!this->is_error_expression()
13207 && this->vals_ != NULL
13208 && !this->vals_->empty()
13209 && this->constructor_temp_ == NULL)
13211 Map_type* mt = this->type_->map_type();
13212 Type* key_type = mt->key_type();
13213 Type* val_type = mt->val_type();
13214 this->element_type_ = Type::make_builtin_struct_type(2,
13215 "__key", key_type,
13216 "__val", val_type);
13218 Expression_list* value_pairs = new Expression_list();
13219 Location loc = this->location();
13221 size_t i = 0;
13222 for (Expression_list::const_iterator pv = this->vals_->begin();
13223 pv != this->vals_->end();
13224 ++pv, ++i)
13226 Expression_list* key_value_pair = new Expression_list();
13227 Expression* key = *pv;
13228 if (key->is_error_expression() || key->type()->is_error_type())
13230 go_assert(saw_errors());
13231 return Expression::make_error(loc);
13233 if (key->type()->interface_type() != NULL && !key->is_variable())
13235 Temporary_statement* temp =
13236 Statement::make_temporary(NULL, key, loc);
13237 inserter->insert(temp);
13238 key = Expression::make_temporary_reference(temp, loc);
13240 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13242 ++pv;
13243 Expression* val = *pv;
13244 if (val->is_error_expression() || val->type()->is_error_type())
13246 go_assert(saw_errors());
13247 return Expression::make_error(loc);
13249 if (val->type()->interface_type() != NULL && !val->is_variable())
13251 Temporary_statement* temp =
13252 Statement::make_temporary(NULL, val, loc);
13253 inserter->insert(temp);
13254 val = Expression::make_temporary_reference(temp, loc);
13256 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13258 key_value_pair->push_back(key);
13259 key_value_pair->push_back(val);
13260 value_pairs->push_back(
13261 Expression::make_struct_composite_literal(this->element_type_,
13262 key_value_pair, loc));
13265 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13266 Array_type* ctor_type =
13267 Type::make_array_type(this->element_type_, element_count);
13268 ctor_type->set_is_array_incomparable();
13269 Expression* constructor =
13270 new Fixed_array_construction_expression(ctor_type, NULL,
13271 value_pairs, loc);
13273 this->constructor_temp_ =
13274 Statement::make_temporary(NULL, constructor, loc);
13275 constructor->issue_nil_check();
13276 this->constructor_temp_->set_is_address_taken();
13277 inserter->insert(this->constructor_temp_);
13280 return this;
13283 // Final type determination.
13285 void
13286 Map_construction_expression::do_determine_type(const Type_context*)
13288 if (this->vals_ == NULL)
13289 return;
13291 Map_type* mt = this->type_->map_type();
13292 Type_context key_context(mt->key_type(), false);
13293 Type_context val_context(mt->val_type(), false);
13294 for (Expression_list::const_iterator pv = this->vals_->begin();
13295 pv != this->vals_->end();
13296 ++pv)
13298 (*pv)->determine_type(&key_context);
13299 ++pv;
13300 (*pv)->determine_type(&val_context);
13304 // Check types.
13306 void
13307 Map_construction_expression::do_check_types(Gogo*)
13309 if (this->vals_ == NULL)
13310 return;
13312 Map_type* mt = this->type_->map_type();
13313 int i = 0;
13314 Type* key_type = mt->key_type();
13315 Type* val_type = mt->val_type();
13316 for (Expression_list::const_iterator pv = this->vals_->begin();
13317 pv != this->vals_->end();
13318 ++pv, ++i)
13320 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13322 go_error_at((*pv)->location(),
13323 "incompatible type for element %d key in map construction",
13324 i + 1);
13325 this->set_is_error();
13327 ++pv;
13328 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13330 go_error_at((*pv)->location(),
13331 ("incompatible type for element %d value "
13332 "in map construction"),
13333 i + 1);
13334 this->set_is_error();
13339 // Return the backend representation for constructing a map.
13341 Bexpression*
13342 Map_construction_expression::do_get_backend(Translate_context* context)
13344 if (this->is_error_expression())
13345 return context->backend()->error_expression();
13346 Location loc = this->location();
13348 size_t i = 0;
13349 Expression* ventries;
13350 if (this->vals_ == NULL || this->vals_->empty())
13351 ventries = Expression::make_nil(loc);
13352 else
13354 go_assert(this->constructor_temp_ != NULL);
13355 i = this->vals_->size() / 2;
13357 Expression* ctor_ref =
13358 Expression::make_temporary_reference(this->constructor_temp_, loc);
13359 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13362 Map_type* mt = this->type_->map_type();
13363 if (this->element_type_ == NULL)
13364 this->element_type_ =
13365 Type::make_builtin_struct_type(2,
13366 "__key", mt->key_type(),
13367 "__val", mt->val_type());
13368 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13370 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13371 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13373 Expression* entry_size =
13374 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13376 unsigned int field_index;
13377 const Struct_field* valfield =
13378 this->element_type_->find_local_field("__val", &field_index);
13379 Expression* val_offset =
13380 Expression::make_struct_field_offset(this->element_type_, valfield);
13382 Expression* map_ctor =
13383 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13384 entry_size, val_offset, ventries);
13385 return map_ctor->get_backend(context);
13388 // Export an array construction.
13390 void
13391 Map_construction_expression::do_export(Export* exp) const
13393 exp->write_c_string("convert(");
13394 exp->write_type(this->type_);
13395 for (Expression_list::const_iterator pv = this->vals_->begin();
13396 pv != this->vals_->end();
13397 ++pv)
13399 exp->write_c_string(", ");
13400 (*pv)->export_expression(exp);
13402 exp->write_c_string(")");
13405 // Dump ast representation for a map construction expression.
13407 void
13408 Map_construction_expression::do_dump_expression(
13409 Ast_dump_context* ast_dump_context) const
13411 ast_dump_context->ostream() << "{" ;
13412 ast_dump_context->dump_expression_list(this->vals_, true);
13413 ast_dump_context->ostream() << "}";
13416 // Class Composite_literal_expression.
13418 // Traversal.
13421 Composite_literal_expression::do_traverse(Traverse* traverse)
13423 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13424 return TRAVERSE_EXIT;
13426 // If this is a struct composite literal with keys, then the keys
13427 // are field names, not expressions. We don't want to traverse them
13428 // in that case. If we do, we can give an erroneous error "variable
13429 // initializer refers to itself." See bug482.go in the testsuite.
13430 if (this->has_keys_ && this->vals_ != NULL)
13432 // The type may not be resolvable at this point.
13433 Type* type = this->type_;
13435 for (int depth = 0; depth < this->depth_; ++depth)
13437 if (type->array_type() != NULL)
13438 type = type->array_type()->element_type();
13439 else if (type->map_type() != NULL)
13441 if (this->key_path_[depth])
13442 type = type->map_type()->key_type();
13443 else
13444 type = type->map_type()->val_type();
13446 else
13448 // This error will be reported during lowering.
13449 return TRAVERSE_CONTINUE;
13453 while (true)
13455 if (type->classification() == Type::TYPE_NAMED)
13456 type = type->named_type()->real_type();
13457 else if (type->classification() == Type::TYPE_FORWARD)
13459 Type* t = type->forwarded();
13460 if (t == type)
13461 break;
13462 type = t;
13464 else
13465 break;
13468 if (type->classification() == Type::TYPE_STRUCT)
13470 Expression_list::iterator p = this->vals_->begin();
13471 while (p != this->vals_->end())
13473 // Skip key.
13474 ++p;
13475 go_assert(p != this->vals_->end());
13476 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13477 return TRAVERSE_EXIT;
13478 ++p;
13480 return TRAVERSE_CONTINUE;
13484 if (this->vals_ != NULL)
13485 return this->vals_->traverse(traverse);
13487 return TRAVERSE_CONTINUE;
13490 // Lower a generic composite literal into a specific version based on
13491 // the type.
13493 Expression*
13494 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13495 Statement_inserter* inserter, int)
13497 Type* type = this->type_;
13499 for (int depth = 0; depth < this->depth_; ++depth)
13501 if (type->array_type() != NULL)
13502 type = type->array_type()->element_type();
13503 else if (type->map_type() != NULL)
13505 if (this->key_path_[depth])
13506 type = type->map_type()->key_type();
13507 else
13508 type = type->map_type()->val_type();
13510 else
13512 if (!type->is_error())
13513 go_error_at(this->location(),
13514 ("may only omit types within composite literals "
13515 "of slice, array, or map type"));
13516 return Expression::make_error(this->location());
13520 Type *pt = type->points_to();
13521 bool is_pointer = false;
13522 if (pt != NULL)
13524 is_pointer = true;
13525 type = pt;
13528 Expression* ret;
13529 if (type->is_error())
13530 return Expression::make_error(this->location());
13531 else if (type->struct_type() != NULL)
13532 ret = this->lower_struct(gogo, type);
13533 else if (type->array_type() != NULL)
13534 ret = this->lower_array(type);
13535 else if (type->map_type() != NULL)
13536 ret = this->lower_map(gogo, function, inserter, type);
13537 else
13539 go_error_at(this->location(),
13540 ("expected struct, slice, array, or map type "
13541 "for composite literal"));
13542 return Expression::make_error(this->location());
13545 if (is_pointer)
13546 ret = Expression::make_heap_expression(ret, this->location());
13548 return ret;
13551 // Lower a struct composite literal.
13553 Expression*
13554 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13556 Location location = this->location();
13557 Struct_type* st = type->struct_type();
13558 if (this->vals_ == NULL || !this->has_keys_)
13560 if (this->vals_ != NULL
13561 && !this->vals_->empty()
13562 && type->named_type() != NULL
13563 && type->named_type()->named_object()->package() != NULL)
13565 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13566 pf != st->fields()->end();
13567 ++pf)
13569 if (Gogo::is_hidden_name(pf->field_name())
13570 || pf->is_embedded_builtin(gogo))
13571 go_error_at(this->location(),
13572 "assignment of unexported field %qs in %qs literal",
13573 Gogo::message_name(pf->field_name()).c_str(),
13574 type->named_type()->message_name().c_str());
13578 return new Struct_construction_expression(type, this->vals_, location);
13581 size_t field_count = st->field_count();
13582 std::vector<Expression*> vals(field_count);
13583 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13584 Expression_list::const_iterator p = this->vals_->begin();
13585 Expression* external_expr = NULL;
13586 const Named_object* external_no = NULL;
13587 while (p != this->vals_->end())
13589 Expression* name_expr = *p;
13591 ++p;
13592 go_assert(p != this->vals_->end());
13593 Expression* val = *p;
13595 ++p;
13597 if (name_expr == NULL)
13599 go_error_at(val->location(),
13600 "mixture of field and value initializers");
13601 return Expression::make_error(location);
13604 bool bad_key = false;
13605 std::string name;
13606 const Named_object* no = NULL;
13607 switch (name_expr->classification())
13609 case EXPRESSION_UNKNOWN_REFERENCE:
13610 name = name_expr->unknown_expression()->name();
13611 if (type->named_type() != NULL)
13613 // If the named object found for this field name comes from a
13614 // different package than the struct it is a part of, do not count
13615 // this incorrect lookup as a usage of the object's package.
13616 no = name_expr->unknown_expression()->named_object();
13617 if (no->package() != NULL
13618 && no->package() != type->named_type()->named_object()->package())
13619 no->package()->forget_usage(name_expr);
13621 break;
13623 case EXPRESSION_CONST_REFERENCE:
13624 no = static_cast<Const_expression*>(name_expr)->named_object();
13625 break;
13627 case EXPRESSION_TYPE:
13629 Type* t = name_expr->type();
13630 Named_type* nt = t->named_type();
13631 if (nt == NULL)
13632 bad_key = true;
13633 else
13634 no = nt->named_object();
13636 break;
13638 case EXPRESSION_VAR_REFERENCE:
13639 no = name_expr->var_expression()->named_object();
13640 break;
13642 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13643 no = name_expr->enclosed_var_expression()->variable();
13644 break;
13646 case EXPRESSION_FUNC_REFERENCE:
13647 no = name_expr->func_expression()->named_object();
13648 break;
13650 default:
13651 bad_key = true;
13652 break;
13654 if (bad_key)
13656 go_error_at(name_expr->location(), "expected struct field name");
13657 return Expression::make_error(location);
13660 if (no != NULL)
13662 if (no->package() != NULL && external_expr == NULL)
13664 external_expr = name_expr;
13665 external_no = no;
13668 name = no->name();
13670 // A predefined name won't be packed. If it starts with a
13671 // lower case letter we need to check for that case, because
13672 // the field name will be packed. FIXME.
13673 if (!Gogo::is_hidden_name(name)
13674 && name[0] >= 'a'
13675 && name[0] <= 'z')
13677 Named_object* gno = gogo->lookup_global(name.c_str());
13678 if (gno == no)
13679 name = gogo->pack_hidden_name(name, false);
13683 unsigned int index;
13684 const Struct_field* sf = st->find_local_field(name, &index);
13685 if (sf == NULL)
13687 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13688 Gogo::message_name(name).c_str(),
13689 (type->named_type() != NULL
13690 ? type->named_type()->message_name().c_str()
13691 : "unnamed struct"));
13692 return Expression::make_error(location);
13694 if (vals[index] != NULL)
13696 go_error_at(name_expr->location(),
13697 "duplicate value for field %qs in %qs",
13698 Gogo::message_name(name).c_str(),
13699 (type->named_type() != NULL
13700 ? type->named_type()->message_name().c_str()
13701 : "unnamed struct"));
13702 return Expression::make_error(location);
13705 if (type->named_type() != NULL
13706 && type->named_type()->named_object()->package() != NULL
13707 && (Gogo::is_hidden_name(sf->field_name())
13708 || sf->is_embedded_builtin(gogo)))
13709 go_error_at(name_expr->location(),
13710 "assignment of unexported field %qs in %qs literal",
13711 Gogo::message_name(sf->field_name()).c_str(),
13712 type->named_type()->message_name().c_str());
13714 vals[index] = val;
13715 traverse_order->push_back(static_cast<unsigned long>(index));
13718 if (!this->all_are_names_)
13720 // This is a weird case like bug462 in the testsuite.
13721 if (external_expr == NULL)
13722 go_error_at(this->location(), "unknown field in %qs literal",
13723 (type->named_type() != NULL
13724 ? type->named_type()->message_name().c_str()
13725 : "unnamed struct"));
13726 else
13727 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13728 external_no->message_name().c_str(),
13729 (type->named_type() != NULL
13730 ? type->named_type()->message_name().c_str()
13731 : "unnamed struct"));
13732 return Expression::make_error(location);
13735 Expression_list* list = new Expression_list;
13736 list->reserve(field_count);
13737 for (size_t i = 0; i < field_count; ++i)
13738 list->push_back(vals[i]);
13740 Struct_construction_expression* ret =
13741 new Struct_construction_expression(type, list, location);
13742 ret->set_traverse_order(traverse_order);
13743 return ret;
13746 // Index/value/traversal-order triple.
13748 struct IVT_triple {
13749 unsigned long index;
13750 unsigned long traversal_order;
13751 Expression* expr;
13752 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13753 : index(i), traversal_order(to), expr(e) { }
13754 bool operator<(const IVT_triple& other) const
13755 { return this->index < other.index; }
13758 // Lower an array composite literal.
13760 Expression*
13761 Composite_literal_expression::lower_array(Type* type)
13763 Location location = this->location();
13764 if (this->vals_ == NULL || !this->has_keys_)
13765 return this->make_array(type, NULL, this->vals_);
13767 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13768 indexes->reserve(this->vals_->size());
13769 bool indexes_out_of_order = false;
13770 Expression_list* vals = new Expression_list();
13771 vals->reserve(this->vals_->size());
13772 unsigned long index = 0;
13773 Expression_list::const_iterator p = this->vals_->begin();
13774 while (p != this->vals_->end())
13776 Expression* index_expr = *p;
13778 ++p;
13779 go_assert(p != this->vals_->end());
13780 Expression* val = *p;
13782 ++p;
13784 if (index_expr == NULL)
13786 if (!indexes->empty())
13787 indexes->push_back(index);
13789 else
13791 if (indexes->empty() && !vals->empty())
13793 for (size_t i = 0; i < vals->size(); ++i)
13794 indexes->push_back(i);
13797 Numeric_constant nc;
13798 if (!index_expr->numeric_constant_value(&nc))
13800 go_error_at(index_expr->location(),
13801 "index expression is not integer constant");
13802 return Expression::make_error(location);
13805 switch (nc.to_unsigned_long(&index))
13807 case Numeric_constant::NC_UL_VALID:
13808 break;
13809 case Numeric_constant::NC_UL_NOTINT:
13810 go_error_at(index_expr->location(),
13811 "index expression is not integer constant");
13812 return Expression::make_error(location);
13813 case Numeric_constant::NC_UL_NEGATIVE:
13814 go_error_at(index_expr->location(),
13815 "index expression is negative");
13816 return Expression::make_error(location);
13817 case Numeric_constant::NC_UL_BIG:
13818 go_error_at(index_expr->location(), "index value overflow");
13819 return Expression::make_error(location);
13820 default:
13821 go_unreachable();
13824 Named_type* ntype = Type::lookup_integer_type("int");
13825 Integer_type* inttype = ntype->integer_type();
13826 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13827 && index >> (inttype->bits() - 1) != 0)
13829 go_error_at(index_expr->location(), "index value overflow");
13830 return Expression::make_error(location);
13833 if (std::find(indexes->begin(), indexes->end(), index)
13834 != indexes->end())
13836 go_error_at(index_expr->location(),
13837 "duplicate value for index %lu",
13838 index);
13839 return Expression::make_error(location);
13842 if (!indexes->empty() && index < indexes->back())
13843 indexes_out_of_order = true;
13845 indexes->push_back(index);
13848 vals->push_back(val);
13850 ++index;
13853 if (indexes->empty())
13855 delete indexes;
13856 indexes = NULL;
13859 std::vector<unsigned long>* traverse_order = NULL;
13860 if (indexes_out_of_order)
13862 typedef std::vector<IVT_triple> V;
13864 V v;
13865 v.reserve(indexes->size());
13866 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13867 unsigned long torder = 0;
13868 for (Expression_list::const_iterator pe = vals->begin();
13869 pe != vals->end();
13870 ++pe, ++pi, ++torder)
13871 v.push_back(IVT_triple(*pi, torder, *pe));
13873 std::sort(v.begin(), v.end());
13875 delete indexes;
13876 delete vals;
13878 indexes = new std::vector<unsigned long>();
13879 indexes->reserve(v.size());
13880 vals = new Expression_list();
13881 vals->reserve(v.size());
13882 traverse_order = new std::vector<unsigned long>();
13883 traverse_order->reserve(v.size());
13885 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13887 indexes->push_back(p->index);
13888 vals->push_back(p->expr);
13889 traverse_order->push_back(p->traversal_order);
13893 Expression* ret = this->make_array(type, indexes, vals);
13894 Array_construction_expression* ace = ret->array_literal();
13895 if (ace != NULL && traverse_order != NULL)
13896 ace->set_traverse_order(traverse_order);
13897 return ret;
13900 // Actually build the array composite literal. This handles
13901 // [...]{...}.
13903 Expression*
13904 Composite_literal_expression::make_array(
13905 Type* type,
13906 const std::vector<unsigned long>* indexes,
13907 Expression_list* vals)
13909 Location location = this->location();
13910 Array_type* at = type->array_type();
13912 if (at->length() != NULL && at->length()->is_nil_expression())
13914 size_t size;
13915 if (vals == NULL)
13916 size = 0;
13917 else if (indexes != NULL)
13918 size = indexes->back() + 1;
13919 else
13921 size = vals->size();
13922 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13923 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13924 && size >> (it->bits() - 1) != 0)
13926 go_error_at(location, "too many elements in composite literal");
13927 return Expression::make_error(location);
13931 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13932 at = Type::make_array_type(at->element_type(), elen);
13933 type = at;
13935 else if (at->length() != NULL
13936 && !at->length()->is_error_expression()
13937 && this->vals_ != NULL)
13939 Numeric_constant nc;
13940 unsigned long val;
13941 if (at->length()->numeric_constant_value(&nc)
13942 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13944 if (indexes == NULL)
13946 if (this->vals_->size() > val)
13948 go_error_at(location,
13949 "too many elements in composite literal");
13950 return Expression::make_error(location);
13953 else
13955 unsigned long max = indexes->back();
13956 if (max >= val)
13958 go_error_at(location,
13959 ("some element keys in composite literal "
13960 "are out of range"));
13961 return Expression::make_error(location);
13967 if (at->length() != NULL)
13968 return new Fixed_array_construction_expression(type, indexes, vals,
13969 location);
13970 else
13971 return new Slice_construction_expression(type, indexes, vals, location);
13974 // Lower a map composite literal.
13976 Expression*
13977 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13978 Statement_inserter* inserter,
13979 Type* type)
13981 Location location = this->location();
13982 if (this->vals_ != NULL)
13984 if (!this->has_keys_)
13986 go_error_at(location, "map composite literal must have keys");
13987 return Expression::make_error(location);
13990 for (Expression_list::iterator p = this->vals_->begin();
13991 p != this->vals_->end();
13992 p += 2)
13994 if (*p == NULL)
13996 ++p;
13997 go_error_at((*p)->location(),
13998 ("map composite literal must "
13999 "have keys for every value"));
14000 return Expression::make_error(location);
14002 // Make sure we have lowered the key; it may not have been
14003 // lowered in order to handle keys for struct composite
14004 // literals. Lower it now to get the right error message.
14005 if ((*p)->unknown_expression() != NULL)
14007 (*p)->unknown_expression()->clear_is_composite_literal_key();
14008 gogo->lower_expression(function, inserter, &*p);
14009 go_assert((*p)->is_error_expression());
14010 return Expression::make_error(location);
14015 return new Map_construction_expression(type, this->vals_, location);
14018 // Dump ast representation for a composite literal expression.
14020 void
14021 Composite_literal_expression::do_dump_expression(
14022 Ast_dump_context* ast_dump_context) const
14024 ast_dump_context->ostream() << "composite(";
14025 ast_dump_context->dump_type(this->type_);
14026 ast_dump_context->ostream() << ", {";
14027 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14028 ast_dump_context->ostream() << "})";
14031 // Make a composite literal expression.
14033 Expression*
14034 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14035 Expression_list* vals, bool all_are_names,
14036 Location location)
14038 return new Composite_literal_expression(type, depth, has_keys, vals,
14039 all_are_names, location);
14042 // Return whether this expression is a composite literal.
14044 bool
14045 Expression::is_composite_literal() const
14047 switch (this->classification_)
14049 case EXPRESSION_COMPOSITE_LITERAL:
14050 case EXPRESSION_STRUCT_CONSTRUCTION:
14051 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14052 case EXPRESSION_SLICE_CONSTRUCTION:
14053 case EXPRESSION_MAP_CONSTRUCTION:
14054 return true;
14055 default:
14056 return false;
14060 // Return whether this expression is a composite literal which is not
14061 // constant.
14063 bool
14064 Expression::is_nonconstant_composite_literal() const
14066 switch (this->classification_)
14068 case EXPRESSION_STRUCT_CONSTRUCTION:
14070 const Struct_construction_expression *psce =
14071 static_cast<const Struct_construction_expression*>(this);
14072 return !psce->is_constant_struct();
14074 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14076 const Fixed_array_construction_expression *pace =
14077 static_cast<const Fixed_array_construction_expression*>(this);
14078 return !pace->is_constant_array();
14080 case EXPRESSION_SLICE_CONSTRUCTION:
14082 const Slice_construction_expression *pace =
14083 static_cast<const Slice_construction_expression*>(this);
14084 return !pace->is_constant_array();
14086 case EXPRESSION_MAP_CONSTRUCTION:
14087 return true;
14088 default:
14089 return false;
14093 // Return true if this is a variable or temporary_variable.
14095 bool
14096 Expression::is_variable() const
14098 switch (this->classification_)
14100 case EXPRESSION_VAR_REFERENCE:
14101 case EXPRESSION_TEMPORARY_REFERENCE:
14102 case EXPRESSION_SET_AND_USE_TEMPORARY:
14103 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14104 return true;
14105 default:
14106 return false;
14110 // Return true if this is a reference to a local variable.
14112 bool
14113 Expression::is_local_variable() const
14115 const Var_expression* ve = this->var_expression();
14116 if (ve == NULL)
14117 return false;
14118 const Named_object* no = ve->named_object();
14119 return (no->is_result_variable()
14120 || (no->is_variable() && !no->var_value()->is_global()));
14123 // Class Type_guard_expression.
14125 // Traversal.
14128 Type_guard_expression::do_traverse(Traverse* traverse)
14130 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14131 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14132 return TRAVERSE_EXIT;
14133 return TRAVERSE_CONTINUE;
14136 Expression*
14137 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14138 Statement_inserter* inserter)
14140 if (this->expr_->is_error_expression()
14141 || this->expr_->type()->is_error_type())
14143 go_assert(saw_errors());
14144 return Expression::make_error(this->location());
14147 if (!this->expr_->is_variable())
14149 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14150 this->location());
14151 inserter->insert(temp);
14152 this->expr_ =
14153 Expression::make_temporary_reference(temp, this->location());
14155 return this;
14158 // Check types of a type guard expression. The expression must have
14159 // an interface type, but the actual type conversion is checked at run
14160 // time.
14162 void
14163 Type_guard_expression::do_check_types(Gogo*)
14165 Type* expr_type = this->expr_->type();
14166 if (expr_type->interface_type() == NULL)
14168 if (!expr_type->is_error() && !this->type_->is_error())
14169 this->report_error(_("type assertion only valid for interface types"));
14170 this->set_is_error();
14172 else if (this->type_->interface_type() == NULL)
14174 std::string reason;
14175 if (!expr_type->interface_type()->implements_interface(this->type_,
14176 &reason))
14178 if (!this->type_->is_error())
14180 if (reason.empty())
14181 this->report_error(_("impossible type assertion: "
14182 "type does not implement interface"));
14183 else
14184 go_error_at(this->location(),
14185 ("impossible type assertion: "
14186 "type does not implement interface (%s)"),
14187 reason.c_str());
14189 this->set_is_error();
14194 // Return the backend representation for a type guard expression.
14196 Bexpression*
14197 Type_guard_expression::do_get_backend(Translate_context* context)
14199 Expression* conversion;
14200 if (this->type_->interface_type() != NULL)
14201 conversion =
14202 Expression::convert_interface_to_interface(this->type_, this->expr_,
14203 true, this->location());
14204 else
14205 conversion =
14206 Expression::convert_for_assignment(context->gogo(), this->type_,
14207 this->expr_, this->location());
14209 Gogo* gogo = context->gogo();
14210 Btype* bt = this->type_->get_backend(gogo);
14211 Bexpression* bexpr = conversion->get_backend(context);
14212 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14215 // Dump ast representation for a type guard expression.
14217 void
14218 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14219 const
14221 this->expr_->dump_expression(ast_dump_context);
14222 ast_dump_context->ostream() << ".";
14223 ast_dump_context->dump_type(this->type_);
14226 // Make a type guard expression.
14228 Expression*
14229 Expression::make_type_guard(Expression* expr, Type* type,
14230 Location location)
14232 return new Type_guard_expression(expr, type, location);
14235 // Class Heap_expression.
14237 // Return the type of the expression stored on the heap.
14239 Type*
14240 Heap_expression::do_type()
14241 { return Type::make_pointer_type(this->expr_->type()); }
14243 // Return the backend representation for allocating an expression on the heap.
14245 Bexpression*
14246 Heap_expression::do_get_backend(Translate_context* context)
14248 Type* etype = this->expr_->type();
14249 if (this->expr_->is_error_expression() || etype->is_error())
14250 return context->backend()->error_expression();
14252 Location loc = this->location();
14253 Gogo* gogo = context->gogo();
14254 Btype* btype = this->type()->get_backend(gogo);
14256 Expression* alloc = Expression::make_allocation(etype, loc);
14257 if (this->allocate_on_stack_)
14258 alloc->allocation_expression()->set_allocate_on_stack();
14259 Bexpression* space = alloc->get_backend(context);
14261 Bstatement* decl;
14262 Named_object* fn = context->function();
14263 go_assert(fn != NULL);
14264 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14265 Bvariable* space_temp =
14266 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14267 space, true, loc, &decl);
14268 Btype* expr_btype = etype->get_backend(gogo);
14270 Bexpression* bexpr = this->expr_->get_backend(context);
14272 // If this assignment needs a write barrier, call typedmemmove. We
14273 // don't do this in the write barrier pass because in some cases
14274 // backend conversion can introduce new Heap_expression values.
14275 Bstatement* assn;
14276 if (!etype->has_pointer())
14278 space = gogo->backend()->var_expression(space_temp, loc);
14279 Bexpression* ref =
14280 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14281 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14283 else
14285 Bstatement* edecl;
14286 Bvariable* btemp =
14287 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14288 expr_btype, bexpr, true, loc,
14289 &edecl);
14290 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14291 loc);
14292 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14294 Expression* td = Expression::make_type_descriptor(etype, loc);
14295 Type* etype_ptr = Type::make_pointer_type(etype);
14296 space = gogo->backend()->var_expression(space_temp, loc);
14297 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14298 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14299 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14300 td, elhs, erhs);
14301 Bexpression* bcall = call->get_backend(context);
14302 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14303 assn = gogo->backend()->compound_statement(edecl, s);
14305 decl = gogo->backend()->compound_statement(decl, assn);
14306 space = gogo->backend()->var_expression(space_temp, loc);
14307 return gogo->backend()->compound_expression(decl, space, loc);
14310 // Dump ast representation for a heap expression.
14312 void
14313 Heap_expression::do_dump_expression(
14314 Ast_dump_context* ast_dump_context) const
14316 ast_dump_context->ostream() << "&(";
14317 ast_dump_context->dump_expression(this->expr_);
14318 ast_dump_context->ostream() << ")";
14321 // Allocate an expression on the heap.
14323 Expression*
14324 Expression::make_heap_expression(Expression* expr, Location location)
14326 return new Heap_expression(expr, location);
14329 // Class Receive_expression.
14331 // Return the type of a receive expression.
14333 Type*
14334 Receive_expression::do_type()
14336 if (this->is_error_expression())
14337 return Type::make_error_type();
14338 Channel_type* channel_type = this->channel_->type()->channel_type();
14339 if (channel_type == NULL)
14341 this->report_error(_("expected channel"));
14342 return Type::make_error_type();
14344 return channel_type->element_type();
14347 // Check types for a receive expression.
14349 void
14350 Receive_expression::do_check_types(Gogo*)
14352 Type* type = this->channel_->type();
14353 if (type->is_error())
14355 go_assert(saw_errors());
14356 this->set_is_error();
14357 return;
14359 if (type->channel_type() == NULL)
14361 this->report_error(_("expected channel"));
14362 return;
14364 if (!type->channel_type()->may_receive())
14366 this->report_error(_("invalid receive on send-only channel"));
14367 return;
14371 // Flattening for receive expressions creates a temporary variable to store
14372 // received data in for receives.
14374 Expression*
14375 Receive_expression::do_flatten(Gogo*, Named_object*,
14376 Statement_inserter* inserter)
14378 Channel_type* channel_type = this->channel_->type()->channel_type();
14379 if (channel_type == NULL)
14381 go_assert(saw_errors());
14382 return this;
14384 else if (this->channel_->is_error_expression())
14386 go_assert(saw_errors());
14387 return Expression::make_error(this->location());
14390 Type* element_type = channel_type->element_type();
14391 if (this->temp_receiver_ == NULL)
14393 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14394 this->location());
14395 this->temp_receiver_->set_is_address_taken();
14396 inserter->insert(this->temp_receiver_);
14399 return this;
14402 // Get the backend representation for a receive expression.
14404 Bexpression*
14405 Receive_expression::do_get_backend(Translate_context* context)
14407 Location loc = this->location();
14409 Channel_type* channel_type = this->channel_->type()->channel_type();
14410 if (channel_type == NULL)
14412 go_assert(this->channel_->type()->is_error());
14413 return context->backend()->error_expression();
14416 Expression* recv_ref =
14417 Expression::make_temporary_reference(this->temp_receiver_, loc);
14418 Expression* recv_addr =
14419 Expression::make_temporary_reference(this->temp_receiver_, loc);
14420 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14421 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14422 this->channel_, recv_addr);
14423 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14426 // Dump ast representation for a receive expression.
14428 void
14429 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14431 ast_dump_context->ostream() << " <- " ;
14432 ast_dump_context->dump_expression(channel_);
14435 // Make a receive expression.
14437 Receive_expression*
14438 Expression::make_receive(Expression* channel, Location location)
14440 return new Receive_expression(channel, location);
14443 // An expression which evaluates to a pointer to the type descriptor
14444 // of a type.
14446 class Type_descriptor_expression : public Expression
14448 public:
14449 Type_descriptor_expression(Type* type, Location location)
14450 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14451 type_(type)
14454 protected:
14456 do_traverse(Traverse*);
14458 Type*
14459 do_type()
14460 { return Type::make_type_descriptor_ptr_type(); }
14462 bool
14463 do_is_static_initializer() const
14464 { return true; }
14466 void
14467 do_determine_type(const Type_context*)
14470 Expression*
14471 do_copy()
14472 { return this; }
14474 Bexpression*
14475 do_get_backend(Translate_context* context)
14477 return this->type_->type_descriptor_pointer(context->gogo(),
14478 this->location());
14481 void
14482 do_dump_expression(Ast_dump_context*) const;
14484 private:
14485 // The type for which this is the descriptor.
14486 Type* type_;
14490 Type_descriptor_expression::do_traverse(Traverse* traverse)
14492 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14493 return TRAVERSE_EXIT;
14494 return TRAVERSE_CONTINUE;
14497 // Dump ast representation for a type descriptor expression.
14499 void
14500 Type_descriptor_expression::do_dump_expression(
14501 Ast_dump_context* ast_dump_context) const
14503 ast_dump_context->dump_type(this->type_);
14506 // Make a type descriptor expression.
14508 Expression*
14509 Expression::make_type_descriptor(Type* type, Location location)
14511 return new Type_descriptor_expression(type, location);
14514 // An expression which evaluates to a pointer to the Garbage Collection symbol
14515 // of a type.
14517 class GC_symbol_expression : public Expression
14519 public:
14520 GC_symbol_expression(Type* type)
14521 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14522 type_(type)
14525 protected:
14526 Type*
14527 do_type()
14528 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14530 bool
14531 do_is_static_initializer() const
14532 { return true; }
14534 void
14535 do_determine_type(const Type_context*)
14538 Expression*
14539 do_copy()
14540 { return this; }
14542 Bexpression*
14543 do_get_backend(Translate_context* context)
14544 { return this->type_->gc_symbol_pointer(context->gogo()); }
14546 void
14547 do_dump_expression(Ast_dump_context*) const;
14549 private:
14550 // The type which this gc symbol describes.
14551 Type* type_;
14554 // Dump ast representation for a gc symbol expression.
14556 void
14557 GC_symbol_expression::do_dump_expression(
14558 Ast_dump_context* ast_dump_context) const
14560 ast_dump_context->ostream() << "gcdata(";
14561 ast_dump_context->dump_type(this->type_);
14562 ast_dump_context->ostream() << ")";
14565 // Make a gc symbol expression.
14567 Expression*
14568 Expression::make_gc_symbol(Type* type)
14570 return new GC_symbol_expression(type);
14573 // An expression that evaluates to a pointer to a symbol holding the
14574 // ptrmask data of a type.
14576 class Ptrmask_symbol_expression : public Expression
14578 public:
14579 Ptrmask_symbol_expression(Type* type)
14580 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14581 type_(type)
14584 protected:
14585 Type*
14586 do_type()
14587 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14589 bool
14590 do_is_static_initializer() const
14591 { return true; }
14593 void
14594 do_determine_type(const Type_context*)
14597 Expression*
14598 do_copy()
14599 { return this; }
14601 Bexpression*
14602 do_get_backend(Translate_context*);
14604 void
14605 do_dump_expression(Ast_dump_context*) const;
14607 private:
14608 // The type that this ptrmask symbol describes.
14609 Type* type_;
14612 // Return the ptrmask variable.
14614 Bexpression*
14615 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14617 Gogo* gogo = context->gogo();
14619 // If this type does not need a gcprog, then we can use the standard
14620 // GC symbol.
14621 int64_t ptrsize, ptrdata;
14622 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14623 return this->type_->gc_symbol_pointer(gogo);
14625 // Otherwise we have to build a ptrmask variable, and return a
14626 // pointer to it.
14628 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14629 Location bloc = Linemap::predeclared_location();
14630 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
14631 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14633 Type* uint8_type = Type::lookup_integer_type("uint8");
14634 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14635 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14636 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14639 // Dump AST for a ptrmask symbol expression.
14641 void
14642 Ptrmask_symbol_expression::do_dump_expression(
14643 Ast_dump_context* ast_dump_context) const
14645 ast_dump_context->ostream() << "ptrmask(";
14646 ast_dump_context->dump_type(this->type_);
14647 ast_dump_context->ostream() << ")";
14650 // Make a ptrmask symbol expression.
14652 Expression*
14653 Expression::make_ptrmask_symbol(Type* type)
14655 return new Ptrmask_symbol_expression(type);
14658 // An expression which evaluates to some characteristic of a type.
14659 // This is only used to initialize fields of a type descriptor. Using
14660 // a new expression class is slightly inefficient but gives us a good
14661 // separation between the frontend and the middle-end with regard to
14662 // how types are laid out.
14664 class Type_info_expression : public Expression
14666 public:
14667 Type_info_expression(Type* type, Type_info type_info)
14668 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14669 type_(type), type_info_(type_info)
14672 protected:
14673 bool
14674 do_is_static_initializer() const
14675 { return true; }
14677 Type*
14678 do_type();
14680 void
14681 do_determine_type(const Type_context*)
14684 Expression*
14685 do_copy()
14686 { return this; }
14688 Bexpression*
14689 do_get_backend(Translate_context* context);
14691 void
14692 do_dump_expression(Ast_dump_context*) const;
14694 private:
14695 // The type for which we are getting information.
14696 Type* type_;
14697 // What information we want.
14698 Type_info type_info_;
14701 // The type is chosen to match what the type descriptor struct
14702 // expects.
14704 Type*
14705 Type_info_expression::do_type()
14707 switch (this->type_info_)
14709 case TYPE_INFO_SIZE:
14710 case TYPE_INFO_BACKEND_PTRDATA:
14711 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14712 return Type::lookup_integer_type("uintptr");
14713 case TYPE_INFO_ALIGNMENT:
14714 case TYPE_INFO_FIELD_ALIGNMENT:
14715 return Type::lookup_integer_type("uint8");
14716 default:
14717 go_unreachable();
14721 // Return the backend representation for type information.
14723 Bexpression*
14724 Type_info_expression::do_get_backend(Translate_context* context)
14726 Gogo* gogo = context->gogo();
14727 bool ok = true;
14728 int64_t val;
14729 switch (this->type_info_)
14731 case TYPE_INFO_SIZE:
14732 ok = this->type_->backend_type_size(gogo, &val);
14733 break;
14734 case TYPE_INFO_ALIGNMENT:
14735 ok = this->type_->backend_type_align(gogo, &val);
14736 break;
14737 case TYPE_INFO_FIELD_ALIGNMENT:
14738 ok = this->type_->backend_type_field_align(gogo, &val);
14739 break;
14740 case TYPE_INFO_BACKEND_PTRDATA:
14741 ok = this->type_->backend_type_ptrdata(gogo, &val);
14742 break;
14743 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14744 ok = this->type_->descriptor_ptrdata(gogo, &val);
14745 break;
14746 default:
14747 go_unreachable();
14749 if (!ok)
14751 go_assert(saw_errors());
14752 return gogo->backend()->error_expression();
14754 Expression* e = Expression::make_integer_int64(val, this->type(),
14755 this->location());
14756 return e->get_backend(context);
14759 // Dump ast representation for a type info expression.
14761 void
14762 Type_info_expression::do_dump_expression(
14763 Ast_dump_context* ast_dump_context) const
14765 ast_dump_context->ostream() << "typeinfo(";
14766 ast_dump_context->dump_type(this->type_);
14767 ast_dump_context->ostream() << ",";
14768 ast_dump_context->ostream() <<
14769 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14770 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14771 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14772 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14773 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14774 : "unknown");
14775 ast_dump_context->ostream() << ")";
14778 // Make a type info expression.
14780 Expression*
14781 Expression::make_type_info(Type* type, Type_info type_info)
14783 return new Type_info_expression(type, type_info);
14786 // An expression that evaluates to some characteristic of a slice.
14787 // This is used when indexing, bound-checking, or nil checking a slice.
14789 class Slice_info_expression : public Expression
14791 public:
14792 Slice_info_expression(Expression* slice, Slice_info slice_info,
14793 Location location)
14794 : Expression(EXPRESSION_SLICE_INFO, location),
14795 slice_(slice), slice_info_(slice_info)
14798 protected:
14799 Type*
14800 do_type();
14802 void
14803 do_determine_type(const Type_context*)
14806 Expression*
14807 do_copy()
14809 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14810 this->location());
14813 Bexpression*
14814 do_get_backend(Translate_context* context);
14816 void
14817 do_dump_expression(Ast_dump_context*) const;
14819 void
14820 do_issue_nil_check()
14821 { this->slice_->issue_nil_check(); }
14823 private:
14824 // The slice for which we are getting information.
14825 Expression* slice_;
14826 // What information we want.
14827 Slice_info slice_info_;
14830 // Return the type of the slice info.
14832 Type*
14833 Slice_info_expression::do_type()
14835 switch (this->slice_info_)
14837 case SLICE_INFO_VALUE_POINTER:
14838 return Type::make_pointer_type(
14839 this->slice_->type()->array_type()->element_type());
14840 case SLICE_INFO_LENGTH:
14841 case SLICE_INFO_CAPACITY:
14842 return Type::lookup_integer_type("int");
14843 default:
14844 go_unreachable();
14848 // Return the backend information for slice information.
14850 Bexpression*
14851 Slice_info_expression::do_get_backend(Translate_context* context)
14853 Gogo* gogo = context->gogo();
14854 Bexpression* bslice = this->slice_->get_backend(context);
14855 switch (this->slice_info_)
14857 case SLICE_INFO_VALUE_POINTER:
14858 case SLICE_INFO_LENGTH:
14859 case SLICE_INFO_CAPACITY:
14860 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14861 this->location());
14862 break;
14863 default:
14864 go_unreachable();
14868 // Dump ast representation for a type info expression.
14870 void
14871 Slice_info_expression::do_dump_expression(
14872 Ast_dump_context* ast_dump_context) const
14874 ast_dump_context->ostream() << "sliceinfo(";
14875 this->slice_->dump_expression(ast_dump_context);
14876 ast_dump_context->ostream() << ",";
14877 ast_dump_context->ostream() <<
14878 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14879 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14880 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14881 : "unknown");
14882 ast_dump_context->ostream() << ")";
14885 // Make a slice info expression.
14887 Expression*
14888 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14889 Location location)
14891 return new Slice_info_expression(slice, slice_info, location);
14894 // An expression that represents a slice value: a struct with value pointer,
14895 // length, and capacity fields.
14897 class Slice_value_expression : public Expression
14899 public:
14900 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14901 Expression* cap, Location location)
14902 : Expression(EXPRESSION_SLICE_VALUE, location),
14903 type_(type), valptr_(valptr), len_(len), cap_(cap)
14906 protected:
14908 do_traverse(Traverse*);
14910 Type*
14911 do_type()
14912 { return this->type_; }
14914 void
14915 do_determine_type(const Type_context*)
14916 { go_unreachable(); }
14918 Expression*
14919 do_copy()
14921 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14922 this->len_->copy(), this->cap_->copy(),
14923 this->location());
14926 Bexpression*
14927 do_get_backend(Translate_context* context);
14929 void
14930 do_dump_expression(Ast_dump_context*) const;
14932 private:
14933 // The type of the slice value.
14934 Type* type_;
14935 // The pointer to the values in the slice.
14936 Expression* valptr_;
14937 // The length of the slice.
14938 Expression* len_;
14939 // The capacity of the slice.
14940 Expression* cap_;
14944 Slice_value_expression::do_traverse(Traverse* traverse)
14946 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14947 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14948 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14949 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14950 return TRAVERSE_EXIT;
14951 return TRAVERSE_CONTINUE;
14954 Bexpression*
14955 Slice_value_expression::do_get_backend(Translate_context* context)
14957 std::vector<Bexpression*> vals(3);
14958 vals[0] = this->valptr_->get_backend(context);
14959 vals[1] = this->len_->get_backend(context);
14960 vals[2] = this->cap_->get_backend(context);
14962 Gogo* gogo = context->gogo();
14963 Btype* btype = this->type_->get_backend(gogo);
14964 return gogo->backend()->constructor_expression(btype, vals, this->location());
14967 void
14968 Slice_value_expression::do_dump_expression(
14969 Ast_dump_context* ast_dump_context) const
14971 ast_dump_context->ostream() << "slicevalue(";
14972 ast_dump_context->ostream() << "values: ";
14973 this->valptr_->dump_expression(ast_dump_context);
14974 ast_dump_context->ostream() << ", length: ";
14975 this->len_->dump_expression(ast_dump_context);
14976 ast_dump_context->ostream() << ", capacity: ";
14977 this->cap_->dump_expression(ast_dump_context);
14978 ast_dump_context->ostream() << ")";
14981 Expression*
14982 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14983 Expression* cap, Location location)
14985 go_assert(at->is_slice_type());
14986 return new Slice_value_expression(at, valptr, len, cap, location);
14989 // An expression that evaluates to some characteristic of a non-empty interface.
14990 // This is used to access the method table or underlying object of an interface.
14992 class Interface_info_expression : public Expression
14994 public:
14995 Interface_info_expression(Expression* iface, Interface_info iface_info,
14996 Location location)
14997 : Expression(EXPRESSION_INTERFACE_INFO, location),
14998 iface_(iface), iface_info_(iface_info)
15001 protected:
15002 Type*
15003 do_type();
15005 void
15006 do_determine_type(const Type_context*)
15009 Expression*
15010 do_copy()
15012 return new Interface_info_expression(this->iface_->copy(),
15013 this->iface_info_, this->location());
15016 Bexpression*
15017 do_get_backend(Translate_context* context);
15019 void
15020 do_dump_expression(Ast_dump_context*) const;
15022 void
15023 do_issue_nil_check()
15024 { this->iface_->issue_nil_check(); }
15026 private:
15027 // The interface for which we are getting information.
15028 Expression* iface_;
15029 // What information we want.
15030 Interface_info iface_info_;
15033 // Return the type of the interface info.
15035 Type*
15036 Interface_info_expression::do_type()
15038 switch (this->iface_info_)
15040 case INTERFACE_INFO_METHODS:
15042 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15043 static Hashtable result_types;
15045 Interface_type* itype = this->iface_->type()->interface_type();
15047 Hashtable::const_iterator p = result_types.find(itype);
15048 if (p != result_types.end())
15049 return p->second;
15051 Type* pdt = Type::make_type_descriptor_ptr_type();
15052 if (itype->is_empty())
15054 result_types[itype] = pdt;
15055 return pdt;
15058 Location loc = this->location();
15059 Struct_field_list* sfl = new Struct_field_list();
15060 sfl->push_back(
15061 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15063 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15064 p != itype->methods()->end();
15065 ++p)
15067 Function_type* ft = p->type()->function_type();
15068 go_assert(ft->receiver() == NULL);
15070 const Typed_identifier_list* params = ft->parameters();
15071 Typed_identifier_list* mparams = new Typed_identifier_list();
15072 if (params != NULL)
15073 mparams->reserve(params->size() + 1);
15074 Type* vt = Type::make_pointer_type(Type::make_void_type());
15075 mparams->push_back(Typed_identifier("", vt, ft->location()));
15076 if (params != NULL)
15078 for (Typed_identifier_list::const_iterator pp = params->begin();
15079 pp != params->end();
15080 ++pp)
15081 mparams->push_back(*pp);
15084 Typed_identifier_list* mresults = (ft->results() == NULL
15085 ? NULL
15086 : ft->results()->copy());
15087 Backend_function_type* mft =
15088 Type::make_backend_function_type(NULL, mparams, mresults,
15089 ft->location());
15091 std::string fname = Gogo::unpack_hidden_name(p->name());
15092 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15095 Struct_type* st = Type::make_struct_type(sfl, loc);
15096 st->set_is_struct_incomparable();
15097 Pointer_type *pt = Type::make_pointer_type(st);
15098 result_types[itype] = pt;
15099 return pt;
15101 case INTERFACE_INFO_OBJECT:
15102 return Type::make_pointer_type(Type::make_void_type());
15103 default:
15104 go_unreachable();
15108 // Return the backend representation for interface information.
15110 Bexpression*
15111 Interface_info_expression::do_get_backend(Translate_context* context)
15113 Gogo* gogo = context->gogo();
15114 Bexpression* biface = this->iface_->get_backend(context);
15115 switch (this->iface_info_)
15117 case INTERFACE_INFO_METHODS:
15118 case INTERFACE_INFO_OBJECT:
15119 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15120 this->location());
15121 break;
15122 default:
15123 go_unreachable();
15127 // Dump ast representation for an interface info expression.
15129 void
15130 Interface_info_expression::do_dump_expression(
15131 Ast_dump_context* ast_dump_context) const
15133 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15134 ast_dump_context->ostream() << "interfaceinfo(";
15135 this->iface_->dump_expression(ast_dump_context);
15136 ast_dump_context->ostream() << ",";
15137 ast_dump_context->ostream() <<
15138 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15139 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15140 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15141 : "unknown");
15142 ast_dump_context->ostream() << ")";
15145 // Make an interface info expression.
15147 Expression*
15148 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15149 Location location)
15151 return new Interface_info_expression(iface, iface_info, location);
15154 // An expression that represents an interface value. The first field is either
15155 // a type descriptor for an empty interface or a pointer to the interface method
15156 // table for a non-empty interface. The second field is always the object.
15158 class Interface_value_expression : public Expression
15160 public:
15161 Interface_value_expression(Type* type, Expression* first_field,
15162 Expression* obj, Location location)
15163 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15164 type_(type), first_field_(first_field), obj_(obj)
15167 protected:
15169 do_traverse(Traverse*);
15171 Type*
15172 do_type()
15173 { return this->type_; }
15175 void
15176 do_determine_type(const Type_context*)
15177 { go_unreachable(); }
15179 Expression*
15180 do_copy()
15182 return new Interface_value_expression(this->type_,
15183 this->first_field_->copy(),
15184 this->obj_->copy(), this->location());
15187 Bexpression*
15188 do_get_backend(Translate_context* context);
15190 void
15191 do_dump_expression(Ast_dump_context*) const;
15193 private:
15194 // The type of the interface value.
15195 Type* type_;
15196 // The first field of the interface (either a type descriptor or a pointer
15197 // to the method table.
15198 Expression* first_field_;
15199 // The underlying object of the interface.
15200 Expression* obj_;
15204 Interface_value_expression::do_traverse(Traverse* traverse)
15206 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15207 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15208 return TRAVERSE_EXIT;
15209 return TRAVERSE_CONTINUE;
15212 Bexpression*
15213 Interface_value_expression::do_get_backend(Translate_context* context)
15215 std::vector<Bexpression*> vals(2);
15216 vals[0] = this->first_field_->get_backend(context);
15217 vals[1] = this->obj_->get_backend(context);
15219 Gogo* gogo = context->gogo();
15220 Btype* btype = this->type_->get_backend(gogo);
15221 return gogo->backend()->constructor_expression(btype, vals, this->location());
15224 void
15225 Interface_value_expression::do_dump_expression(
15226 Ast_dump_context* ast_dump_context) const
15228 ast_dump_context->ostream() << "interfacevalue(";
15229 ast_dump_context->ostream() <<
15230 (this->type_->interface_type()->is_empty()
15231 ? "type_descriptor: "
15232 : "methods: ");
15233 this->first_field_->dump_expression(ast_dump_context);
15234 ast_dump_context->ostream() << ", object: ";
15235 this->obj_->dump_expression(ast_dump_context);
15236 ast_dump_context->ostream() << ")";
15239 Expression*
15240 Expression::make_interface_value(Type* type, Expression* first_value,
15241 Expression* object, Location location)
15243 return new Interface_value_expression(type, first_value, object, location);
15246 // An interface method table for a pair of types: an interface type and a type
15247 // that implements that interface.
15249 class Interface_mtable_expression : public Expression
15251 public:
15252 Interface_mtable_expression(Interface_type* itype, Type* type,
15253 bool is_pointer, Location location)
15254 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15255 itype_(itype), type_(type), is_pointer_(is_pointer),
15256 method_table_type_(NULL), bvar_(NULL)
15259 protected:
15261 do_traverse(Traverse*);
15263 Type*
15264 do_type();
15266 bool
15267 do_is_static_initializer() const
15268 { return true; }
15270 void
15271 do_determine_type(const Type_context*)
15272 { go_unreachable(); }
15274 Expression*
15275 do_copy()
15277 return new Interface_mtable_expression(this->itype_, this->type_,
15278 this->is_pointer_, this->location());
15281 bool
15282 do_is_addressable() const
15283 { return true; }
15285 Bexpression*
15286 do_get_backend(Translate_context* context);
15288 void
15289 do_dump_expression(Ast_dump_context*) const;
15291 private:
15292 // The interface type for which the methods are defined.
15293 Interface_type* itype_;
15294 // The type to construct the interface method table for.
15295 Type* type_;
15296 // Whether this table contains the method set for the receiver type or the
15297 // pointer receiver type.
15298 bool is_pointer_;
15299 // The type of the method table.
15300 Type* method_table_type_;
15301 // The backend variable that refers to the interface method table.
15302 Bvariable* bvar_;
15306 Interface_mtable_expression::do_traverse(Traverse* traverse)
15308 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15309 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15310 return TRAVERSE_EXIT;
15311 return TRAVERSE_CONTINUE;
15314 Type*
15315 Interface_mtable_expression::do_type()
15317 if (this->method_table_type_ != NULL)
15318 return this->method_table_type_;
15320 const Typed_identifier_list* interface_methods = this->itype_->methods();
15321 go_assert(!interface_methods->empty());
15323 Struct_field_list* sfl = new Struct_field_list;
15324 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15325 this->location());
15326 sfl->push_back(Struct_field(tid));
15327 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15328 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15329 p != interface_methods->end();
15330 ++p)
15332 // We want C function pointers here, not func descriptors; model
15333 // using void* pointers.
15334 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15335 sfl->push_back(Struct_field(method));
15337 Struct_type* st = Type::make_struct_type(sfl, this->location());
15338 st->set_is_struct_incomparable();
15339 this->method_table_type_ = st;
15340 return this->method_table_type_;
15343 Bexpression*
15344 Interface_mtable_expression::do_get_backend(Translate_context* context)
15346 Gogo* gogo = context->gogo();
15347 Location loc = Linemap::predeclared_location();
15348 if (this->bvar_ != NULL)
15349 return gogo->backend()->var_expression(this->bvar_, this->location());
15351 const Typed_identifier_list* interface_methods = this->itype_->methods();
15352 go_assert(!interface_methods->empty());
15354 std::string mangled_name =
15355 gogo->interface_method_table_name(this->itype_, this->type_,
15356 this->is_pointer_);
15358 // Set is_public if we are converting a named type to an interface
15359 // type that is defined in the same package as the named type, and
15360 // the interface has hidden methods. In that case the interface
15361 // method table will be defined by the package that defines the
15362 // types.
15363 bool is_public = false;
15364 if (this->type_->named_type() != NULL
15365 && (this->type_->named_type()->named_object()->package()
15366 == this->itype_->package()))
15368 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15369 p != interface_methods->end();
15370 ++p)
15372 if (Gogo::is_hidden_name(p->name()))
15374 is_public = true;
15375 break;
15380 if (is_public
15381 && this->type_->named_type()->named_object()->package() != NULL)
15383 // The interface conversion table is defined elsewhere.
15384 Btype* btype = this->type()->get_backend(gogo);
15385 std::string asm_name(go_selectively_encode_id(mangled_name));
15386 this->bvar_ =
15387 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15388 btype, loc);
15389 return gogo->backend()->var_expression(this->bvar_, this->location());
15392 // The first element is the type descriptor.
15393 Type* td_type;
15394 if (!this->is_pointer_)
15395 td_type = this->type_;
15396 else
15397 td_type = Type::make_pointer_type(this->type_);
15399 std::vector<Backend::Btyped_identifier> bstructfields;
15401 // Build an interface method table for a type: a type descriptor followed by a
15402 // list of function pointers, one for each interface method. This is used for
15403 // interfaces.
15404 Expression_list* svals = new Expression_list();
15405 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15406 svals->push_back(tdescriptor);
15408 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15409 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15410 bstructfields.push_back(btd);
15412 Named_type* nt = this->type_->named_type();
15413 Struct_type* st = this->type_->struct_type();
15414 go_assert(nt != NULL || st != NULL);
15416 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15417 p != interface_methods->end();
15418 ++p)
15420 bool is_ambiguous;
15421 Method* m;
15422 if (nt != NULL)
15423 m = nt->method_function(p->name(), &is_ambiguous);
15424 else
15425 m = st->method_function(p->name(), &is_ambiguous);
15426 go_assert(m != NULL);
15427 Named_object* no = m->named_object();
15429 go_assert(no->is_function() || no->is_function_declaration());
15431 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15432 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15433 bstructfields.push_back(bmtype);
15435 svals->push_back(Expression::make_func_code_reference(no, loc));
15438 Btype *btype = gogo->backend()->struct_type(bstructfields);
15439 std::vector<Bexpression*> ctor_bexprs;
15440 for (Expression_list::const_iterator pe = svals->begin();
15441 pe != svals->end();
15442 ++pe)
15444 ctor_bexprs.push_back((*pe)->get_backend(context));
15446 Bexpression* ctor =
15447 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15449 std::string asm_name(go_selectively_encode_id(mangled_name));
15450 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15451 !is_public, btype, loc);
15452 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15453 !is_public, btype, loc, ctor);
15454 return gogo->backend()->var_expression(this->bvar_, loc);
15457 void
15458 Interface_mtable_expression::do_dump_expression(
15459 Ast_dump_context* ast_dump_context) const
15461 ast_dump_context->ostream() << "__go_"
15462 << (this->is_pointer_ ? "pimt__" : "imt_");
15463 ast_dump_context->dump_type(this->itype_);
15464 ast_dump_context->ostream() << "__";
15465 ast_dump_context->dump_type(this->type_);
15468 Expression*
15469 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15470 bool is_pointer, Location location)
15472 return new Interface_mtable_expression(itype, type, is_pointer, location);
15475 // An expression which evaluates to the offset of a field within a
15476 // struct. This, like Type_info_expression, q.v., is only used to
15477 // initialize fields of a type descriptor.
15479 class Struct_field_offset_expression : public Expression
15481 public:
15482 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15483 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15484 Linemap::predeclared_location()),
15485 type_(type), field_(field)
15488 protected:
15489 bool
15490 do_is_static_initializer() const
15491 { return true; }
15493 Type*
15494 do_type()
15495 { return Type::lookup_integer_type("uintptr"); }
15497 void
15498 do_determine_type(const Type_context*)
15501 Expression*
15502 do_copy()
15503 { return this; }
15505 Bexpression*
15506 do_get_backend(Translate_context* context);
15508 void
15509 do_dump_expression(Ast_dump_context*) const;
15511 private:
15512 // The type of the struct.
15513 Struct_type* type_;
15514 // The field.
15515 const Struct_field* field_;
15518 // Return the backend representation for a struct field offset.
15520 Bexpression*
15521 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15523 const Struct_field_list* fields = this->type_->fields();
15524 Struct_field_list::const_iterator p;
15525 unsigned i = 0;
15526 for (p = fields->begin();
15527 p != fields->end();
15528 ++p, ++i)
15529 if (&*p == this->field_)
15530 break;
15531 go_assert(&*p == this->field_);
15533 Gogo* gogo = context->gogo();
15534 Btype* btype = this->type_->get_backend(gogo);
15536 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15537 Type* uptr_type = Type::lookup_integer_type("uintptr");
15538 Expression* ret =
15539 Expression::make_integer_int64(offset, uptr_type,
15540 Linemap::predeclared_location());
15541 return ret->get_backend(context);
15544 // Dump ast representation for a struct field offset expression.
15546 void
15547 Struct_field_offset_expression::do_dump_expression(
15548 Ast_dump_context* ast_dump_context) const
15550 ast_dump_context->ostream() << "unsafe.Offsetof(";
15551 ast_dump_context->dump_type(this->type_);
15552 ast_dump_context->ostream() << '.';
15553 ast_dump_context->ostream() <<
15554 Gogo::message_name(this->field_->field_name());
15555 ast_dump_context->ostream() << ")";
15558 // Make an expression for a struct field offset.
15560 Expression*
15561 Expression::make_struct_field_offset(Struct_type* type,
15562 const Struct_field* field)
15564 return new Struct_field_offset_expression(type, field);
15567 // An expression which evaluates to the address of an unnamed label.
15569 class Label_addr_expression : public Expression
15571 public:
15572 Label_addr_expression(Label* label, Location location)
15573 : Expression(EXPRESSION_LABEL_ADDR, location),
15574 label_(label)
15577 protected:
15578 Type*
15579 do_type()
15580 { return Type::make_pointer_type(Type::make_void_type()); }
15582 void
15583 do_determine_type(const Type_context*)
15586 Expression*
15587 do_copy()
15588 { return new Label_addr_expression(this->label_, this->location()); }
15590 Bexpression*
15591 do_get_backend(Translate_context* context)
15592 { return this->label_->get_addr(context, this->location()); }
15594 void
15595 do_dump_expression(Ast_dump_context* ast_dump_context) const
15596 { ast_dump_context->ostream() << this->label_->name(); }
15598 private:
15599 // The label whose address we are taking.
15600 Label* label_;
15603 // Make an expression for the address of an unnamed label.
15605 Expression*
15606 Expression::make_label_addr(Label* label, Location location)
15608 return new Label_addr_expression(label, location);
15611 // Class Conditional_expression.
15613 // Traversal.
15616 Conditional_expression::do_traverse(Traverse* traverse)
15618 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15619 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15620 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15621 return TRAVERSE_EXIT;
15622 return TRAVERSE_CONTINUE;
15625 // Return the type of the conditional expression.
15627 Type*
15628 Conditional_expression::do_type()
15630 Type* result_type = Type::make_void_type();
15631 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15632 NULL))
15633 result_type = this->then_->type();
15634 else if (this->then_->is_nil_expression()
15635 || this->else_->is_nil_expression())
15636 result_type = (!this->then_->is_nil_expression()
15637 ? this->then_->type()
15638 : this->else_->type());
15639 return result_type;
15642 // Determine type for a conditional expression.
15644 void
15645 Conditional_expression::do_determine_type(const Type_context* context)
15647 this->cond_->determine_type_no_context();
15648 this->then_->determine_type(context);
15649 this->else_->determine_type(context);
15652 // Get the backend representation of a conditional expression.
15654 Bexpression*
15655 Conditional_expression::do_get_backend(Translate_context* context)
15657 Gogo* gogo = context->gogo();
15658 Btype* result_btype = this->type()->get_backend(gogo);
15659 Bexpression* cond = this->cond_->get_backend(context);
15660 Bexpression* then = this->then_->get_backend(context);
15661 Bexpression* belse = this->else_->get_backend(context);
15662 Bfunction* bfn = context->function()->func_value()->get_decl();
15663 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15664 belse, this->location());
15667 // Dump ast representation of a conditional expression.
15669 void
15670 Conditional_expression::do_dump_expression(
15671 Ast_dump_context* ast_dump_context) const
15673 ast_dump_context->ostream() << "(";
15674 ast_dump_context->dump_expression(this->cond_);
15675 ast_dump_context->ostream() << " ? ";
15676 ast_dump_context->dump_expression(this->then_);
15677 ast_dump_context->ostream() << " : ";
15678 ast_dump_context->dump_expression(this->else_);
15679 ast_dump_context->ostream() << ") ";
15682 // Make a conditional expression.
15684 Expression*
15685 Expression::make_conditional(Expression* cond, Expression* then,
15686 Expression* else_expr, Location location)
15688 return new Conditional_expression(cond, then, else_expr, location);
15691 // Class Compound_expression.
15693 // Traversal.
15696 Compound_expression::do_traverse(Traverse* traverse)
15698 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15699 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15700 return TRAVERSE_EXIT;
15701 return TRAVERSE_CONTINUE;
15704 // Return the type of the compound expression.
15706 Type*
15707 Compound_expression::do_type()
15709 return this->expr_->type();
15712 // Determine type for a compound expression.
15714 void
15715 Compound_expression::do_determine_type(const Type_context* context)
15717 this->init_->determine_type_no_context();
15718 this->expr_->determine_type(context);
15721 // Get the backend representation of a compound expression.
15723 Bexpression*
15724 Compound_expression::do_get_backend(Translate_context* context)
15726 Gogo* gogo = context->gogo();
15727 Bexpression* binit = this->init_->get_backend(context);
15728 Bfunction* bfunction = context->function()->func_value()->get_decl();
15729 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15730 binit);
15731 Bexpression* bexpr = this->expr_->get_backend(context);
15732 return gogo->backend()->compound_expression(init_stmt, bexpr,
15733 this->location());
15736 // Dump ast representation of a conditional expression.
15738 void
15739 Compound_expression::do_dump_expression(
15740 Ast_dump_context* ast_dump_context) const
15742 ast_dump_context->ostream() << "(";
15743 ast_dump_context->dump_expression(this->init_);
15744 ast_dump_context->ostream() << ",";
15745 ast_dump_context->dump_expression(this->expr_);
15746 ast_dump_context->ostream() << ") ";
15749 // Make a compound expression.
15751 Expression*
15752 Expression::make_compound(Expression* init, Expression* expr, Location location)
15754 return new Compound_expression(init, expr, location);
15757 // Class Backend_expression.
15760 Backend_expression::do_traverse(Traverse*)
15762 return TRAVERSE_CONTINUE;
15765 void
15766 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15768 ast_dump_context->ostream() << "backend_expression<";
15769 ast_dump_context->dump_type(this->type_);
15770 ast_dump_context->ostream() << ">";
15773 Expression*
15774 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15776 return new Backend_expression(bexpr, type, location);
15779 // Import an expression. This comes at the end in order to see the
15780 // various class definitions.
15782 Expression*
15783 Expression::import_expression(Import* imp)
15785 int c = imp->peek_char();
15786 if (imp->match_c_string("- ")
15787 || imp->match_c_string("! ")
15788 || imp->match_c_string("^ "))
15789 return Unary_expression::do_import(imp);
15790 else if (c == '(')
15791 return Binary_expression::do_import(imp);
15792 else if (imp->match_c_string("true")
15793 || imp->match_c_string("false"))
15794 return Boolean_expression::do_import(imp);
15795 else if (c == '"')
15796 return String_expression::do_import(imp);
15797 else if (c == '-' || (c >= '0' && c <= '9'))
15799 // This handles integers, floats and complex constants.
15800 return Integer_expression::do_import(imp);
15802 else if (imp->match_c_string("nil"))
15803 return Nil_expression::do_import(imp);
15804 else if (imp->match_c_string("convert"))
15805 return Type_conversion_expression::do_import(imp);
15806 else
15808 go_error_at(imp->location(), "import error: expected expression");
15809 return Expression::make_error(imp->location());
15813 // Class Expression_list.
15815 // Traverse the list.
15818 Expression_list::traverse(Traverse* traverse)
15820 for (Expression_list::iterator p = this->begin();
15821 p != this->end();
15822 ++p)
15824 if (*p != NULL)
15826 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15827 return TRAVERSE_EXIT;
15830 return TRAVERSE_CONTINUE;
15833 // Copy the list.
15835 Expression_list*
15836 Expression_list::copy()
15838 Expression_list* ret = new Expression_list();
15839 for (Expression_list::iterator p = this->begin();
15840 p != this->end();
15841 ++p)
15843 if (*p == NULL)
15844 ret->push_back(NULL);
15845 else
15846 ret->push_back((*p)->copy());
15848 return ret;
15851 // Return whether an expression list has an error expression.
15853 bool
15854 Expression_list::contains_error() const
15856 for (Expression_list::const_iterator p = this->begin();
15857 p != this->end();
15858 ++p)
15859 if (*p != NULL && (*p)->is_error_expression())
15860 return true;
15861 return false;
15864 // Class Numeric_constant.
15866 // Destructor.
15868 Numeric_constant::~Numeric_constant()
15870 this->clear();
15873 // Copy constructor.
15875 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15876 : classification_(a.classification_), type_(a.type_)
15878 switch (a.classification_)
15880 case NC_INVALID:
15881 break;
15882 case NC_INT:
15883 case NC_RUNE:
15884 mpz_init_set(this->u_.int_val, a.u_.int_val);
15885 break;
15886 case NC_FLOAT:
15887 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15888 break;
15889 case NC_COMPLEX:
15890 mpc_init2(this->u_.complex_val, mpc_precision);
15891 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15892 break;
15893 default:
15894 go_unreachable();
15898 // Assignment operator.
15900 Numeric_constant&
15901 Numeric_constant::operator=(const Numeric_constant& a)
15903 this->clear();
15904 this->classification_ = a.classification_;
15905 this->type_ = a.type_;
15906 switch (a.classification_)
15908 case NC_INVALID:
15909 break;
15910 case NC_INT:
15911 case NC_RUNE:
15912 mpz_init_set(this->u_.int_val, a.u_.int_val);
15913 break;
15914 case NC_FLOAT:
15915 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15916 break;
15917 case NC_COMPLEX:
15918 mpc_init2(this->u_.complex_val, mpc_precision);
15919 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15920 break;
15921 default:
15922 go_unreachable();
15924 return *this;
15927 // Clear the contents.
15929 void
15930 Numeric_constant::clear()
15932 switch (this->classification_)
15934 case NC_INVALID:
15935 break;
15936 case NC_INT:
15937 case NC_RUNE:
15938 mpz_clear(this->u_.int_val);
15939 break;
15940 case NC_FLOAT:
15941 mpfr_clear(this->u_.float_val);
15942 break;
15943 case NC_COMPLEX:
15944 mpc_clear(this->u_.complex_val);
15945 break;
15946 default:
15947 go_unreachable();
15949 this->classification_ = NC_INVALID;
15952 // Set to an unsigned long value.
15954 void
15955 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15957 this->clear();
15958 this->classification_ = NC_INT;
15959 this->type_ = type;
15960 mpz_init_set_ui(this->u_.int_val, val);
15963 // Set to an integer value.
15965 void
15966 Numeric_constant::set_int(Type* type, const mpz_t val)
15968 this->clear();
15969 this->classification_ = NC_INT;
15970 this->type_ = type;
15971 mpz_init_set(this->u_.int_val, val);
15974 // Set to a rune value.
15976 void
15977 Numeric_constant::set_rune(Type* type, const mpz_t val)
15979 this->clear();
15980 this->classification_ = NC_RUNE;
15981 this->type_ = type;
15982 mpz_init_set(this->u_.int_val, val);
15985 // Set to a floating point value.
15987 void
15988 Numeric_constant::set_float(Type* type, const mpfr_t val)
15990 this->clear();
15991 this->classification_ = NC_FLOAT;
15992 this->type_ = type;
15993 // Numeric constants do not have negative zero values, so remove
15994 // them here. They also don't have infinity or NaN values, but we
15995 // should never see them here.
15996 if (mpfr_zero_p(val))
15997 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15998 else
15999 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16002 // Set to a complex value.
16004 void
16005 Numeric_constant::set_complex(Type* type, const mpc_t val)
16007 this->clear();
16008 this->classification_ = NC_COMPLEX;
16009 this->type_ = type;
16010 mpc_init2(this->u_.complex_val, mpc_precision);
16011 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
16014 // Get an int value.
16016 void
16017 Numeric_constant::get_int(mpz_t* val) const
16019 go_assert(this->is_int());
16020 mpz_init_set(*val, this->u_.int_val);
16023 // Get a rune value.
16025 void
16026 Numeric_constant::get_rune(mpz_t* val) const
16028 go_assert(this->is_rune());
16029 mpz_init_set(*val, this->u_.int_val);
16032 // Get a floating point value.
16034 void
16035 Numeric_constant::get_float(mpfr_t* val) const
16037 go_assert(this->is_float());
16038 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16041 // Get a complex value.
16043 void
16044 Numeric_constant::get_complex(mpc_t* val) const
16046 go_assert(this->is_complex());
16047 mpc_init2(*val, mpc_precision);
16048 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16051 // Express value as unsigned long if possible.
16053 Numeric_constant::To_unsigned_long
16054 Numeric_constant::to_unsigned_long(unsigned long* val) const
16056 switch (this->classification_)
16058 case NC_INT:
16059 case NC_RUNE:
16060 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16061 case NC_FLOAT:
16062 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16063 case NC_COMPLEX:
16064 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16065 return NC_UL_NOTINT;
16066 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16067 val);
16068 default:
16069 go_unreachable();
16073 // Express integer value as unsigned long if possible.
16075 Numeric_constant::To_unsigned_long
16076 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16077 unsigned long *val) const
16079 if (mpz_sgn(ival) < 0)
16080 return NC_UL_NEGATIVE;
16081 unsigned long ui = mpz_get_ui(ival);
16082 if (mpz_cmp_ui(ival, ui) != 0)
16083 return NC_UL_BIG;
16084 *val = ui;
16085 return NC_UL_VALID;
16088 // Express floating point value as unsigned long if possible.
16090 Numeric_constant::To_unsigned_long
16091 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16092 unsigned long *val) const
16094 if (!mpfr_integer_p(fval))
16095 return NC_UL_NOTINT;
16096 mpz_t ival;
16097 mpz_init(ival);
16098 mpfr_get_z(ival, fval, GMP_RNDN);
16099 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16100 mpz_clear(ival);
16101 return ret;
16104 // Express value as memory size if possible.
16106 bool
16107 Numeric_constant::to_memory_size(int64_t* val) const
16109 switch (this->classification_)
16111 case NC_INT:
16112 case NC_RUNE:
16113 return this->mpz_to_memory_size(this->u_.int_val, val);
16114 case NC_FLOAT:
16115 return this->mpfr_to_memory_size(this->u_.float_val, val);
16116 case NC_COMPLEX:
16117 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16118 return false;
16119 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16120 default:
16121 go_unreachable();
16125 // Express integer as memory size if possible.
16127 bool
16128 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16130 if (mpz_sgn(ival) < 0)
16131 return false;
16132 if (mpz_fits_slong_p(ival))
16134 *val = static_cast<int64_t>(mpz_get_si(ival));
16135 return true;
16138 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16139 // positive value.
16140 if (mpz_sizeinbase(ival, 2) >= 64)
16141 return false;
16143 mpz_t q, r;
16144 mpz_init(q);
16145 mpz_init(r);
16146 mpz_tdiv_q_2exp(q, ival, 32);
16147 mpz_tdiv_r_2exp(r, ival, 32);
16148 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16149 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16150 + static_cast<int64_t>(mpz_get_ui(r)));
16151 mpz_clear(r);
16152 mpz_clear(q);
16153 return true;
16156 // Express floating point value as memory size if possible.
16158 bool
16159 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16161 if (!mpfr_integer_p(fval))
16162 return false;
16163 mpz_t ival;
16164 mpz_init(ival);
16165 mpfr_get_z(ival, fval, GMP_RNDN);
16166 bool ret = this->mpz_to_memory_size(ival, val);
16167 mpz_clear(ival);
16168 return ret;
16171 // Convert value to integer if possible.
16173 bool
16174 Numeric_constant::to_int(mpz_t* val) const
16176 switch (this->classification_)
16178 case NC_INT:
16179 case NC_RUNE:
16180 mpz_init_set(*val, this->u_.int_val);
16181 return true;
16182 case NC_FLOAT:
16183 if (!mpfr_integer_p(this->u_.float_val))
16184 return false;
16185 mpz_init(*val);
16186 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16187 return true;
16188 case NC_COMPLEX:
16189 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16190 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16191 return false;
16192 mpz_init(*val);
16193 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16194 return true;
16195 default:
16196 go_unreachable();
16200 // Convert value to floating point if possible.
16202 bool
16203 Numeric_constant::to_float(mpfr_t* val) const
16205 switch (this->classification_)
16207 case NC_INT:
16208 case NC_RUNE:
16209 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16210 return true;
16211 case NC_FLOAT:
16212 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16213 return true;
16214 case NC_COMPLEX:
16215 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16216 return false;
16217 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16218 return true;
16219 default:
16220 go_unreachable();
16224 // Convert value to complex.
16226 bool
16227 Numeric_constant::to_complex(mpc_t* val) const
16229 mpc_init2(*val, mpc_precision);
16230 switch (this->classification_)
16232 case NC_INT:
16233 case NC_RUNE:
16234 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16235 return true;
16236 case NC_FLOAT:
16237 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16238 return true;
16239 case NC_COMPLEX:
16240 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16241 return true;
16242 default:
16243 go_unreachable();
16247 // Get the type.
16249 Type*
16250 Numeric_constant::type() const
16252 if (this->type_ != NULL)
16253 return this->type_;
16254 switch (this->classification_)
16256 case NC_INT:
16257 return Type::make_abstract_integer_type();
16258 case NC_RUNE:
16259 return Type::make_abstract_character_type();
16260 case NC_FLOAT:
16261 return Type::make_abstract_float_type();
16262 case NC_COMPLEX:
16263 return Type::make_abstract_complex_type();
16264 default:
16265 go_unreachable();
16269 // If the constant can be expressed in TYPE, then set the type of the
16270 // constant to TYPE and return true. Otherwise return false, and, if
16271 // ISSUE_ERROR is true, report an appropriate error message.
16273 bool
16274 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16276 bool ret;
16277 if (type == NULL || type->is_error())
16278 ret = true;
16279 else if (type->integer_type() != NULL)
16280 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16281 else if (type->float_type() != NULL)
16282 ret = this->check_float_type(type->float_type(), issue_error, loc);
16283 else if (type->complex_type() != NULL)
16284 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16285 else
16287 ret = false;
16288 if (issue_error)
16289 go_assert(saw_errors());
16291 if (ret)
16292 this->type_ = type;
16293 return ret;
16296 // Check whether the constant can be expressed in an integer type.
16298 bool
16299 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16300 Location location)
16302 mpz_t val;
16303 switch (this->classification_)
16305 case NC_INT:
16306 case NC_RUNE:
16307 mpz_init_set(val, this->u_.int_val);
16308 break;
16310 case NC_FLOAT:
16311 if (!mpfr_integer_p(this->u_.float_val))
16313 if (issue_error)
16315 go_error_at(location,
16316 "floating point constant truncated to integer");
16317 this->set_invalid();
16319 return false;
16321 mpz_init(val);
16322 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16323 break;
16325 case NC_COMPLEX:
16326 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16327 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16329 if (issue_error)
16331 go_error_at(location, "complex constant truncated to integer");
16332 this->set_invalid();
16334 return false;
16336 mpz_init(val);
16337 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16338 break;
16340 default:
16341 go_unreachable();
16344 bool ret;
16345 if (type->is_abstract())
16346 ret = true;
16347 else
16349 int bits = mpz_sizeinbase(val, 2);
16350 if (type->is_unsigned())
16352 // For an unsigned type we can only accept a nonnegative
16353 // number, and we must be able to represents at least BITS.
16354 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16356 else
16358 // For a signed type we need an extra bit to indicate the
16359 // sign. We have to handle the most negative integer
16360 // specially.
16361 ret = (bits + 1 <= type->bits()
16362 || (bits <= type->bits()
16363 && mpz_sgn(val) < 0
16364 && (mpz_scan1(val, 0)
16365 == static_cast<unsigned long>(type->bits() - 1))
16366 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16370 if (!ret && issue_error)
16372 go_error_at(location, "integer constant overflow");
16373 this->set_invalid();
16376 return ret;
16379 // Check whether the constant can be expressed in a floating point
16380 // type.
16382 bool
16383 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16384 Location location)
16386 mpfr_t val;
16387 switch (this->classification_)
16389 case NC_INT:
16390 case NC_RUNE:
16391 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16392 break;
16394 case NC_FLOAT:
16395 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16396 break;
16398 case NC_COMPLEX:
16399 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16401 if (issue_error)
16403 this->set_invalid();
16404 go_error_at(location, "complex constant truncated to float");
16406 return false;
16408 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16409 break;
16411 default:
16412 go_unreachable();
16415 bool ret;
16416 if (type->is_abstract())
16417 ret = true;
16418 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16420 // A NaN or Infinity always fits in the range of the type.
16421 ret = true;
16423 else
16425 mp_exp_t exp = mpfr_get_exp(val);
16426 mp_exp_t max_exp;
16427 switch (type->bits())
16429 case 32:
16430 max_exp = 128;
16431 break;
16432 case 64:
16433 max_exp = 1024;
16434 break;
16435 default:
16436 go_unreachable();
16439 ret = exp <= max_exp;
16441 if (ret)
16443 // Round the constant to the desired type.
16444 mpfr_t t;
16445 mpfr_init(t);
16446 switch (type->bits())
16448 case 32:
16449 mpfr_set_prec(t, 24);
16450 break;
16451 case 64:
16452 mpfr_set_prec(t, 53);
16453 break;
16454 default:
16455 go_unreachable();
16457 mpfr_set(t, val, GMP_RNDN);
16458 mpfr_set(val, t, GMP_RNDN);
16459 mpfr_clear(t);
16461 this->set_float(type, val);
16465 mpfr_clear(val);
16467 if (!ret && issue_error)
16469 go_error_at(location, "floating point constant overflow");
16470 this->set_invalid();
16473 return ret;
16476 // Check whether the constant can be expressed in a complex type.
16478 bool
16479 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16480 Location location)
16482 if (type->is_abstract())
16483 return true;
16485 mp_exp_t max_exp;
16486 switch (type->bits())
16488 case 64:
16489 max_exp = 128;
16490 break;
16491 case 128:
16492 max_exp = 1024;
16493 break;
16494 default:
16495 go_unreachable();
16498 mpc_t val;
16499 mpc_init2(val, mpc_precision);
16500 switch (this->classification_)
16502 case NC_INT:
16503 case NC_RUNE:
16504 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16505 break;
16507 case NC_FLOAT:
16508 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16509 break;
16511 case NC_COMPLEX:
16512 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16513 break;
16515 default:
16516 go_unreachable();
16519 bool ret = true;
16520 if (!mpfr_nan_p(mpc_realref(val))
16521 && !mpfr_inf_p(mpc_realref(val))
16522 && !mpfr_zero_p(mpc_realref(val))
16523 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16525 if (issue_error)
16527 go_error_at(location, "complex real part overflow");
16528 this->set_invalid();
16530 ret = false;
16533 if (!mpfr_nan_p(mpc_imagref(val))
16534 && !mpfr_inf_p(mpc_imagref(val))
16535 && !mpfr_zero_p(mpc_imagref(val))
16536 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16538 if (issue_error)
16540 go_error_at(location, "complex imaginary part overflow");
16541 this->set_invalid();
16543 ret = false;
16546 if (ret)
16548 // Round the constant to the desired type.
16549 mpc_t t;
16550 switch (type->bits())
16552 case 64:
16553 mpc_init2(t, 24);
16554 break;
16555 case 128:
16556 mpc_init2(t, 53);
16557 break;
16558 default:
16559 go_unreachable();
16561 mpc_set(t, val, MPC_RNDNN);
16562 mpc_set(val, t, MPC_RNDNN);
16563 mpc_clear(t);
16565 this->set_complex(type, val);
16568 mpc_clear(val);
16570 return ret;
16573 // Return an Expression for this value.
16575 Expression*
16576 Numeric_constant::expression(Location loc) const
16578 switch (this->classification_)
16580 case NC_INT:
16581 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16582 case NC_RUNE:
16583 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16584 case NC_FLOAT:
16585 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16586 case NC_COMPLEX:
16587 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16588 case NC_INVALID:
16589 go_assert(saw_errors());
16590 return Expression::make_error(loc);
16591 default:
16592 go_unreachable();