* auto-profile.c (afdo_annotate_cfg): Use update_max_bb_count.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blobdad22ebd2c97adaeab654beafa5b6b77deee3070
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_unary(OPERATOR_MULT, mtable, 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_unary(OPERATOR_MULT, obj, location);
398 return Expression::make_compound(check_iface, obj, location);
401 // Convert an expression to its backend representation. This is implemented by
402 // the child class. Not that it is not in general safe to call this multiple
403 // times for a single expression, but that we don't catch such errors.
405 Bexpression*
406 Expression::get_backend(Translate_context* context)
408 // The child may have marked this expression as having an error.
409 if (this->classification_ == EXPRESSION_ERROR)
410 return context->backend()->error_expression();
412 return this->do_get_backend(context);
415 // Return a backend expression for VAL.
416 Bexpression*
417 Expression::backend_numeric_constant_expression(Translate_context* context,
418 Numeric_constant* val)
420 Gogo* gogo = context->gogo();
421 Type* type = val->type();
422 if (type == NULL)
423 return gogo->backend()->error_expression();
425 Btype* btype = type->get_backend(gogo);
426 Bexpression* ret;
427 if (type->integer_type() != NULL)
429 mpz_t ival;
430 if (!val->to_int(&ival))
432 go_assert(saw_errors());
433 return gogo->backend()->error_expression();
435 ret = gogo->backend()->integer_constant_expression(btype, ival);
436 mpz_clear(ival);
438 else if (type->float_type() != NULL)
440 mpfr_t fval;
441 if (!val->to_float(&fval))
443 go_assert(saw_errors());
444 return gogo->backend()->error_expression();
446 ret = gogo->backend()->float_constant_expression(btype, fval);
447 mpfr_clear(fval);
449 else if (type->complex_type() != NULL)
451 mpc_t cval;
452 if (!val->to_complex(&cval))
454 go_assert(saw_errors());
455 return gogo->backend()->error_expression();
457 ret = gogo->backend()->complex_constant_expression(btype, cval);
458 mpc_clear(cval);
460 else
461 go_unreachable();
463 return ret;
466 // Return an expression which evaluates to true if VAL, of arbitrary integer
467 // type, is negative or is more than the maximum value of the Go type "int".
469 Expression*
470 Expression::check_bounds(Expression* val, Location loc)
472 Type* val_type = val->type();
473 Type* bound_type = Type::lookup_integer_type("int");
475 int val_type_size;
476 bool val_is_unsigned = false;
477 if (val_type->integer_type() != NULL)
479 val_type_size = val_type->integer_type()->bits();
480 val_is_unsigned = val_type->integer_type()->is_unsigned();
482 else
484 if (!val_type->is_numeric_type()
485 || !Type::are_convertible(bound_type, val_type, NULL))
487 go_assert(saw_errors());
488 return Expression::make_boolean(true, loc);
491 if (val_type->complex_type() != NULL)
492 val_type_size = val_type->complex_type()->bits();
493 else
494 val_type_size = val_type->float_type()->bits();
497 Expression* negative_index = Expression::make_boolean(false, loc);
498 Expression* index_overflows = Expression::make_boolean(false, loc);
499 if (!val_is_unsigned)
501 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
502 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
505 int bound_type_size = bound_type->integer_type()->bits();
506 if (val_type_size > bound_type_size
507 || (val_type_size == bound_type_size
508 && val_is_unsigned))
510 mpz_t one;
511 mpz_init_set_ui(one, 1UL);
513 // maxval = 2^(bound_type_size - 1) - 1
514 mpz_t maxval;
515 mpz_init(maxval);
516 mpz_mul_2exp(maxval, one, bound_type_size - 1);
517 mpz_sub_ui(maxval, maxval, 1);
518 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
519 mpz_clear(one);
520 mpz_clear(maxval);
522 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
525 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
526 loc);
529 void
530 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
532 this->do_dump_expression(ast_dump_context);
535 // Error expressions. This are used to avoid cascading errors.
537 class Error_expression : public Expression
539 public:
540 Error_expression(Location location)
541 : Expression(EXPRESSION_ERROR, location)
544 protected:
545 bool
546 do_is_constant() const
547 { return true; }
549 bool
550 do_numeric_constant_value(Numeric_constant* nc) const
552 nc->set_unsigned_long(NULL, 0);
553 return true;
556 bool
557 do_discarding_value()
558 { return true; }
560 Type*
561 do_type()
562 { return Type::make_error_type(); }
564 void
565 do_determine_type(const Type_context*)
568 Expression*
569 do_copy()
570 { return this; }
572 bool
573 do_is_addressable() const
574 { return true; }
576 Bexpression*
577 do_get_backend(Translate_context* context)
578 { return context->backend()->error_expression(); }
580 void
581 do_dump_expression(Ast_dump_context*) const;
584 // Dump the ast representation for an error expression to a dump context.
586 void
587 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
589 ast_dump_context->ostream() << "_Error_" ;
592 Expression*
593 Expression::make_error(Location location)
595 return new Error_expression(location);
598 // An expression which is really a type. This is used during parsing.
599 // It is an error if these survive after lowering.
601 class
602 Type_expression : public Expression
604 public:
605 Type_expression(Type* type, Location location)
606 : Expression(EXPRESSION_TYPE, location),
607 type_(type)
610 protected:
612 do_traverse(Traverse* traverse)
613 { return Type::traverse(this->type_, traverse); }
615 Type*
616 do_type()
617 { return this->type_; }
619 void
620 do_determine_type(const Type_context*)
623 void
624 do_check_types(Gogo*)
625 { this->report_error(_("invalid use of type")); }
627 Expression*
628 do_copy()
629 { return this; }
631 Bexpression*
632 do_get_backend(Translate_context*)
633 { go_unreachable(); }
635 void do_dump_expression(Ast_dump_context*) const;
637 private:
638 // The type which we are representing as an expression.
639 Type* type_;
642 void
643 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
645 ast_dump_context->dump_type(this->type_);
648 Expression*
649 Expression::make_type(Type* type, Location location)
651 return new Type_expression(type, location);
654 // Class Parser_expression.
656 Type*
657 Parser_expression::do_type()
659 // We should never really ask for the type of a Parser_expression.
660 // However, it can happen, at least when we have an invalid const
661 // whose initializer refers to the const itself. In that case we
662 // may ask for the type when lowering the const itself.
663 go_assert(saw_errors());
664 return Type::make_error_type();
667 // Class Var_expression.
669 // Lower a variable expression. Here we just make sure that the
670 // initialization expression of the variable has been lowered. This
671 // ensures that we will be able to determine the type of the variable
672 // if necessary.
674 Expression*
675 Var_expression::do_lower(Gogo* gogo, Named_object* function,
676 Statement_inserter* inserter, int)
678 if (this->variable_->is_variable())
680 Variable* var = this->variable_->var_value();
681 // This is either a local variable or a global variable. A
682 // reference to a variable which is local to an enclosing
683 // function will be a reference to a field in a closure.
684 if (var->is_global())
686 function = NULL;
687 inserter = NULL;
689 var->lower_init_expression(gogo, function, inserter);
691 return this;
694 // Return the type of a reference to a variable.
696 Type*
697 Var_expression::do_type()
699 if (this->variable_->is_variable())
700 return this->variable_->var_value()->type();
701 else if (this->variable_->is_result_variable())
702 return this->variable_->result_var_value()->type();
703 else
704 go_unreachable();
707 // Determine the type of a reference to a variable.
709 void
710 Var_expression::do_determine_type(const Type_context*)
712 if (this->variable_->is_variable())
713 this->variable_->var_value()->determine_type();
716 // Something takes the address of this variable. This means that we
717 // may want to move the variable onto the heap.
719 void
720 Var_expression::do_address_taken(bool escapes)
722 if (!escapes)
724 if (this->variable_->is_variable())
725 this->variable_->var_value()->set_non_escaping_address_taken();
726 else if (this->variable_->is_result_variable())
727 this->variable_->result_var_value()->set_non_escaping_address_taken();
728 else
729 go_unreachable();
731 else
733 if (this->variable_->is_variable())
734 this->variable_->var_value()->set_address_taken();
735 else if (this->variable_->is_result_variable())
736 this->variable_->result_var_value()->set_address_taken();
737 else
738 go_unreachable();
741 if (this->variable_->is_variable()
742 && this->variable_->var_value()->is_in_heap())
744 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
745 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
749 // Get the backend representation for a reference to a variable.
751 Bexpression*
752 Var_expression::do_get_backend(Translate_context* context)
754 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
755 context->function());
756 bool is_in_heap;
757 Location loc = this->location();
758 Btype* btype;
759 Gogo* gogo = context->gogo();
760 if (this->variable_->is_variable())
762 is_in_heap = this->variable_->var_value()->is_in_heap();
763 btype = this->variable_->var_value()->type()->get_backend(gogo);
765 else if (this->variable_->is_result_variable())
767 is_in_heap = this->variable_->result_var_value()->is_in_heap();
768 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
770 else
771 go_unreachable();
773 Bexpression* ret =
774 context->backend()->var_expression(bvar, this->in_lvalue_pos_, loc);
775 if (is_in_heap)
776 ret = context->backend()->indirect_expression(btype, ret, true, loc);
777 return ret;
780 // Ast dump for variable expression.
782 void
783 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
785 ast_dump_context->ostream() << this->variable_->name() ;
788 // Make a reference to a variable in an expression.
790 Expression*
791 Expression::make_var_reference(Named_object* var, Location location)
793 if (var->is_sink())
794 return Expression::make_sink(location);
796 // FIXME: Creating a new object for each reference to a variable is
797 // wasteful.
798 return new Var_expression(var, location);
801 // Class Enclosed_var_expression.
804 Enclosed_var_expression::do_traverse(Traverse*)
806 return TRAVERSE_CONTINUE;
809 // Lower the reference to the enclosed variable.
811 Expression*
812 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
813 Statement_inserter* inserter, int)
815 gogo->lower_expression(function, inserter, &this->reference_);
816 return this;
819 // Flatten the reference to the enclosed variable.
821 Expression*
822 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
823 Statement_inserter* inserter)
825 gogo->flatten_expression(function, inserter, &this->reference_);
826 return this;
829 void
830 Enclosed_var_expression::do_address_taken(bool escapes)
832 if (!escapes)
834 if (this->variable_->is_variable())
835 this->variable_->var_value()->set_non_escaping_address_taken();
836 else if (this->variable_->is_result_variable())
837 this->variable_->result_var_value()->set_non_escaping_address_taken();
838 else
839 go_unreachable();
841 else
843 if (this->variable_->is_variable())
844 this->variable_->var_value()->set_address_taken();
845 else if (this->variable_->is_result_variable())
846 this->variable_->result_var_value()->set_address_taken();
847 else
848 go_unreachable();
851 if (this->variable_->is_variable()
852 && this->variable_->var_value()->is_in_heap())
853 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
856 // Ast dump for enclosed variable expression.
858 void
859 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
861 adc->ostream() << this->variable_->name();
864 // Make a reference to a variable within an enclosing function.
866 Expression*
867 Expression::make_enclosing_var_reference(Expression* reference,
868 Named_object* var, Location location)
870 return new Enclosed_var_expression(reference, var, location);
873 // Class Temporary_reference_expression.
875 // The type.
877 Type*
878 Temporary_reference_expression::do_type()
880 return this->statement_->type();
883 // Called if something takes the address of this temporary variable.
884 // We never have to move temporary variables to the heap, but we do
885 // need to know that they must live in the stack rather than in a
886 // register.
888 void
889 Temporary_reference_expression::do_address_taken(bool)
891 this->statement_->set_is_address_taken();
894 // Get a backend expression referring to the variable.
896 Bexpression*
897 Temporary_reference_expression::do_get_backend(Translate_context* context)
899 Gogo* gogo = context->gogo();
900 Bvariable* bvar = this->statement_->get_backend_variable(context);
901 Varexpr_context ve_ctxt = (this->is_lvalue_ ? VE_lvalue : VE_rvalue);
903 Bexpression* ret = gogo->backend()->var_expression(bvar, ve_ctxt,
904 this->location());
906 // The backend can't always represent the same set of recursive types
907 // that the Go frontend can. In some cases this means that a
908 // temporary variable won't have the right backend type. Correct
909 // that here by adding a type cast. We need to use base() to push
910 // the circularity down one level.
911 Type* stype = this->statement_->type();
912 if (!this->is_lvalue_
913 && stype->points_to() != NULL
914 && stype->points_to()->is_void_type())
916 Btype* btype = this->type()->base()->get_backend(gogo);
917 ret = gogo->backend()->convert_expression(btype, ret, this->location());
919 return ret;
922 // Ast dump for temporary reference.
924 void
925 Temporary_reference_expression::do_dump_expression(
926 Ast_dump_context* ast_dump_context) const
928 ast_dump_context->dump_temp_variable_name(this->statement_);
931 // Make a reference to a temporary variable.
933 Temporary_reference_expression*
934 Expression::make_temporary_reference(Temporary_statement* statement,
935 Location location)
937 return new Temporary_reference_expression(statement, location);
940 // Class Set_and_use_temporary_expression.
942 // Return the type.
944 Type*
945 Set_and_use_temporary_expression::do_type()
947 return this->statement_->type();
950 // Determine the type of the expression.
952 void
953 Set_and_use_temporary_expression::do_determine_type(
954 const Type_context* context)
956 this->expr_->determine_type(context);
959 // Take the address.
961 void
962 Set_and_use_temporary_expression::do_address_taken(bool)
964 this->statement_->set_is_address_taken();
967 // Return the backend representation.
969 Bexpression*
970 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
972 Location loc = this->location();
973 Gogo* gogo = context->gogo();
974 Bvariable* bvar = this->statement_->get_backend_variable(context);
975 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, VE_lvalue, loc);
977 Named_object* fn = context->function();
978 go_assert(fn != NULL);
979 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
980 Bexpression* bexpr = this->expr_->get_backend(context);
981 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
982 bexpr, loc);
983 Bexpression* var_ref = gogo->backend()->var_expression(bvar, VE_rvalue, loc);
984 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
985 return ret;
988 // Dump.
990 void
991 Set_and_use_temporary_expression::do_dump_expression(
992 Ast_dump_context* ast_dump_context) const
994 ast_dump_context->ostream() << '(';
995 ast_dump_context->dump_temp_variable_name(this->statement_);
996 ast_dump_context->ostream() << " = ";
997 this->expr_->dump_expression(ast_dump_context);
998 ast_dump_context->ostream() << ')';
1001 // Make a set-and-use temporary.
1003 Set_and_use_temporary_expression*
1004 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1005 Expression* expr, Location location)
1007 return new Set_and_use_temporary_expression(statement, expr, location);
1010 // A sink expression--a use of the blank identifier _.
1012 class Sink_expression : public Expression
1014 public:
1015 Sink_expression(Location location)
1016 : Expression(EXPRESSION_SINK, location),
1017 type_(NULL), bvar_(NULL)
1020 protected:
1021 bool
1022 do_discarding_value()
1023 { return true; }
1025 Type*
1026 do_type();
1028 void
1029 do_determine_type(const Type_context*);
1031 Expression*
1032 do_copy()
1033 { return new Sink_expression(this->location()); }
1035 Bexpression*
1036 do_get_backend(Translate_context*);
1038 void
1039 do_dump_expression(Ast_dump_context*) const;
1041 private:
1042 // The type of this sink variable.
1043 Type* type_;
1044 // The temporary variable we generate.
1045 Bvariable* bvar_;
1048 // Return the type of a sink expression.
1050 Type*
1051 Sink_expression::do_type()
1053 if (this->type_ == NULL)
1054 return Type::make_sink_type();
1055 return this->type_;
1058 // Determine the type of a sink expression.
1060 void
1061 Sink_expression::do_determine_type(const Type_context* context)
1063 if (context->type != NULL)
1064 this->type_ = context->type;
1067 // Return a temporary variable for a sink expression. This will
1068 // presumably be a write-only variable which the middle-end will drop.
1070 Bexpression*
1071 Sink_expression::do_get_backend(Translate_context* context)
1073 Location loc = this->location();
1074 Gogo* gogo = context->gogo();
1075 if (this->bvar_ == NULL)
1077 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1078 Named_object* fn = context->function();
1079 go_assert(fn != NULL);
1080 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1081 Btype* bt = this->type_->get_backend(context->gogo());
1082 Bstatement* decl;
1083 this->bvar_ =
1084 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1085 false, loc, &decl);
1086 Bexpression* var_ref =
1087 gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
1088 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1089 return var_ref;
1091 return gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
1094 // Ast dump for sink expression.
1096 void
1097 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1099 ast_dump_context->ostream() << "_" ;
1102 // Make a sink expression.
1104 Expression*
1105 Expression::make_sink(Location location)
1107 return new Sink_expression(location);
1110 // Class Func_expression.
1112 // FIXME: Can a function expression appear in a constant expression?
1113 // The value is unchanging. Initializing a constant to the address of
1114 // a function seems like it could work, though there might be little
1115 // point to it.
1117 // Traversal.
1120 Func_expression::do_traverse(Traverse* traverse)
1122 return (this->closure_ == NULL
1123 ? TRAVERSE_CONTINUE
1124 : Expression::traverse(&this->closure_, traverse));
1127 // Return the type of a function expression.
1129 Type*
1130 Func_expression::do_type()
1132 if (this->function_->is_function())
1133 return this->function_->func_value()->type();
1134 else if (this->function_->is_function_declaration())
1135 return this->function_->func_declaration_value()->type();
1136 else
1137 go_unreachable();
1140 // Get the backend representation for the code of a function expression.
1142 Bexpression*
1143 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1145 Function_type* fntype;
1146 if (no->is_function())
1147 fntype = no->func_value()->type();
1148 else if (no->is_function_declaration())
1149 fntype = no->func_declaration_value()->type();
1150 else
1151 go_unreachable();
1153 // Builtin functions are handled specially by Call_expression. We
1154 // can't take their address.
1155 if (fntype->is_builtin())
1157 go_error_at(loc,
1158 "invalid use of special builtin function %qs; must be called",
1159 no->message_name().c_str());
1160 return gogo->backend()->error_expression();
1163 Bfunction* fndecl;
1164 if (no->is_function())
1165 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1166 else if (no->is_function_declaration())
1167 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1168 else
1169 go_unreachable();
1171 return gogo->backend()->function_code_expression(fndecl, loc);
1174 // Get the backend representation for a function expression. This is used when
1175 // we take the address of a function rather than simply calling it. A func
1176 // value is represented as a pointer to a block of memory. The first
1177 // word of that memory is a pointer to the function code. The
1178 // remaining parts of that memory are the addresses of variables that
1179 // the function closes over.
1181 Bexpression*
1182 Func_expression::do_get_backend(Translate_context* context)
1184 // If there is no closure, just use the function descriptor.
1185 if (this->closure_ == NULL)
1187 Gogo* gogo = context->gogo();
1188 Named_object* no = this->function_;
1189 Expression* descriptor;
1190 if (no->is_function())
1191 descriptor = no->func_value()->descriptor(gogo, no);
1192 else if (no->is_function_declaration())
1194 if (no->func_declaration_value()->type()->is_builtin())
1196 go_error_at(this->location(),
1197 ("invalid use of special builtin function %qs; "
1198 "must be called"),
1199 no->message_name().c_str());
1200 return gogo->backend()->error_expression();
1202 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1204 else
1205 go_unreachable();
1207 Bexpression* bdesc = descriptor->get_backend(context);
1208 return gogo->backend()->address_expression(bdesc, this->location());
1211 go_assert(this->function_->func_value()->enclosing() != NULL);
1213 // If there is a closure, then the closure is itself the function
1214 // expression. It is a pointer to a struct whose first field points
1215 // to the function code and whose remaining fields are the addresses
1216 // of the closed-over variables.
1217 Bexpression *bexpr = this->closure_->get_backend(context);
1219 // Introduce a backend type conversion, to account for any differences
1220 // between the argument type (function descriptor, struct with a
1221 // single field) and the closure (struct with multiple fields).
1222 Gogo* gogo = context->gogo();
1223 Btype *btype = this->type()->get_backend(gogo);
1224 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1227 // Ast dump for function.
1229 void
1230 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1232 ast_dump_context->ostream() << this->function_->name();
1233 if (this->closure_ != NULL)
1235 ast_dump_context->ostream() << " {closure = ";
1236 this->closure_->dump_expression(ast_dump_context);
1237 ast_dump_context->ostream() << "}";
1241 // Make a reference to a function in an expression.
1243 Expression*
1244 Expression::make_func_reference(Named_object* function, Expression* closure,
1245 Location location)
1247 Func_expression* fe = new Func_expression(function, closure, location);
1249 // Detect references to builtin functions and set the runtime code if
1250 // appropriate.
1251 if (function->is_function_declaration())
1252 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1253 return fe;
1256 // Class Func_descriptor_expression.
1258 // Constructor.
1260 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1261 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1262 fn_(fn), dvar_(NULL)
1264 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1267 // Traversal.
1270 Func_descriptor_expression::do_traverse(Traverse*)
1272 return TRAVERSE_CONTINUE;
1275 // All function descriptors have the same type.
1277 Type* Func_descriptor_expression::descriptor_type;
1279 void
1280 Func_descriptor_expression::make_func_descriptor_type()
1282 if (Func_descriptor_expression::descriptor_type != NULL)
1283 return;
1284 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1285 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1286 Func_descriptor_expression::descriptor_type =
1287 Type::make_builtin_named_type("functionDescriptor", struct_type);
1290 Type*
1291 Func_descriptor_expression::do_type()
1293 Func_descriptor_expression::make_func_descriptor_type();
1294 return Func_descriptor_expression::descriptor_type;
1297 // The backend representation for a function descriptor.
1299 Bexpression*
1300 Func_descriptor_expression::do_get_backend(Translate_context* context)
1302 Named_object* no = this->fn_;
1303 Location loc = no->location();
1304 if (this->dvar_ != NULL)
1305 return context->backend()->var_expression(this->dvar_, VE_rvalue, loc);
1307 Gogo* gogo = context->gogo();
1308 std::string var_name(gogo->function_descriptor_name(no));
1309 bool is_descriptor = false;
1310 if (no->is_function_declaration()
1311 && !no->func_declaration_value()->asm_name().empty()
1312 && Linemap::is_predeclared_location(no->location()))
1313 is_descriptor = true;
1315 Btype* btype = this->type()->get_backend(gogo);
1317 Bvariable* bvar;
1318 std::string asm_name(go_selectively_encode_id(var_name));
1319 if (no->package() != NULL || is_descriptor)
1320 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1321 btype, loc);
1322 else
1324 Location bloc = Linemap::predeclared_location();
1325 bool is_hidden = ((no->is_function()
1326 && no->func_value()->enclosing() != NULL)
1327 || Gogo::is_thunk(no));
1328 bvar = context->backend()->immutable_struct(var_name, asm_name,
1329 is_hidden, false,
1330 btype, bloc);
1331 Expression_list* vals = new Expression_list();
1332 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1333 Expression* init =
1334 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1335 Translate_context bcontext(gogo, NULL, NULL, NULL);
1336 bcontext.set_is_const();
1337 Bexpression* binit = init->get_backend(&bcontext);
1338 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1339 false, btype, bloc, binit);
1342 this->dvar_ = bvar;
1343 return gogo->backend()->var_expression(bvar, VE_rvalue, loc);
1346 // Print a function descriptor expression.
1348 void
1349 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1351 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1354 // Make a function descriptor expression.
1356 Func_descriptor_expression*
1357 Expression::make_func_descriptor(Named_object* fn)
1359 return new Func_descriptor_expression(fn);
1362 // Make the function descriptor type, so that it can be converted.
1364 void
1365 Expression::make_func_descriptor_type()
1367 Func_descriptor_expression::make_func_descriptor_type();
1370 // A reference to just the code of a function.
1372 class Func_code_reference_expression : public Expression
1374 public:
1375 Func_code_reference_expression(Named_object* function, Location location)
1376 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1377 function_(function)
1380 protected:
1382 do_traverse(Traverse*)
1383 { return TRAVERSE_CONTINUE; }
1385 bool
1386 do_is_static_initializer() const
1387 { return true; }
1389 Type*
1390 do_type()
1391 { return Type::make_pointer_type(Type::make_void_type()); }
1393 void
1394 do_determine_type(const Type_context*)
1397 Expression*
1398 do_copy()
1400 return Expression::make_func_code_reference(this->function_,
1401 this->location());
1404 Bexpression*
1405 do_get_backend(Translate_context*);
1407 void
1408 do_dump_expression(Ast_dump_context* context) const
1409 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1411 private:
1412 // The function.
1413 Named_object* function_;
1416 // Get the backend representation for a reference to function code.
1418 Bexpression*
1419 Func_code_reference_expression::do_get_backend(Translate_context* context)
1421 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1422 this->location());
1425 // Make a reference to the code of a function.
1427 Expression*
1428 Expression::make_func_code_reference(Named_object* function, Location location)
1430 return new Func_code_reference_expression(function, location);
1433 // Class Unknown_expression.
1435 // Return the name of an unknown expression.
1437 const std::string&
1438 Unknown_expression::name() const
1440 return this->named_object_->name();
1443 // Lower a reference to an unknown name.
1445 Expression*
1446 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1448 Location location = this->location();
1449 Named_object* no = this->named_object_;
1450 Named_object* real;
1451 if (!no->is_unknown())
1452 real = no;
1453 else
1455 real = no->unknown_value()->real_named_object();
1456 if (real == NULL)
1458 if (this->is_composite_literal_key_)
1459 return this;
1460 if (!this->no_error_message_)
1461 go_error_at(location, "reference to undefined name %qs",
1462 this->named_object_->message_name().c_str());
1463 return Expression::make_error(location);
1466 switch (real->classification())
1468 case Named_object::NAMED_OBJECT_CONST:
1469 return Expression::make_const_reference(real, location);
1470 case Named_object::NAMED_OBJECT_TYPE:
1471 return Expression::make_type(real->type_value(), location);
1472 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1473 if (this->is_composite_literal_key_)
1474 return this;
1475 if (!this->no_error_message_)
1476 go_error_at(location, "reference to undefined type %qs",
1477 real->message_name().c_str());
1478 return Expression::make_error(location);
1479 case Named_object::NAMED_OBJECT_VAR:
1480 real->var_value()->set_is_used();
1481 return Expression::make_var_reference(real, location);
1482 case Named_object::NAMED_OBJECT_FUNC:
1483 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1484 return Expression::make_func_reference(real, NULL, location);
1485 case Named_object::NAMED_OBJECT_PACKAGE:
1486 if (this->is_composite_literal_key_)
1487 return this;
1488 if (!this->no_error_message_)
1489 go_error_at(location, "unexpected reference to package");
1490 return Expression::make_error(location);
1491 default:
1492 go_unreachable();
1496 // Dump the ast representation for an unknown expression to a dump context.
1498 void
1499 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1501 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1502 << ")";
1505 // Make a reference to an unknown name.
1507 Unknown_expression*
1508 Expression::make_unknown_reference(Named_object* no, Location location)
1510 return new Unknown_expression(no, location);
1513 // A boolean expression.
1515 class Boolean_expression : public Expression
1517 public:
1518 Boolean_expression(bool val, Location location)
1519 : Expression(EXPRESSION_BOOLEAN, location),
1520 val_(val), type_(NULL)
1523 static Expression*
1524 do_import(Import*);
1526 protected:
1527 bool
1528 do_is_constant() const
1529 { return true; }
1531 bool
1532 do_is_static_initializer() const
1533 { return true; }
1535 Type*
1536 do_type();
1538 void
1539 do_determine_type(const Type_context*);
1541 Expression*
1542 do_copy()
1543 { return this; }
1545 Bexpression*
1546 do_get_backend(Translate_context* context)
1547 { return context->backend()->boolean_constant_expression(this->val_); }
1549 void
1550 do_export(Export* exp) const
1551 { exp->write_c_string(this->val_ ? "true" : "false"); }
1553 void
1554 do_dump_expression(Ast_dump_context* ast_dump_context) const
1555 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1557 private:
1558 // The constant.
1559 bool val_;
1560 // The type as determined by context.
1561 Type* type_;
1564 // Get the type.
1566 Type*
1567 Boolean_expression::do_type()
1569 if (this->type_ == NULL)
1570 this->type_ = Type::make_boolean_type();
1571 return this->type_;
1574 // Set the type from the context.
1576 void
1577 Boolean_expression::do_determine_type(const Type_context* context)
1579 if (this->type_ != NULL && !this->type_->is_abstract())
1581 else if (context->type != NULL && context->type->is_boolean_type())
1582 this->type_ = context->type;
1583 else if (!context->may_be_abstract)
1584 this->type_ = Type::lookup_bool_type();
1587 // Import a boolean constant.
1589 Expression*
1590 Boolean_expression::do_import(Import* imp)
1592 if (imp->peek_char() == 't')
1594 imp->require_c_string("true");
1595 return Expression::make_boolean(true, imp->location());
1597 else
1599 imp->require_c_string("false");
1600 return Expression::make_boolean(false, imp->location());
1604 // Make a boolean expression.
1606 Expression*
1607 Expression::make_boolean(bool val, Location location)
1609 return new Boolean_expression(val, location);
1612 // Class String_expression.
1614 // Get the type.
1616 Type*
1617 String_expression::do_type()
1619 if (this->type_ == NULL)
1620 this->type_ = Type::make_string_type();
1621 return this->type_;
1624 // Set the type from the context.
1626 void
1627 String_expression::do_determine_type(const Type_context* context)
1629 if (this->type_ != NULL && !this->type_->is_abstract())
1631 else if (context->type != NULL && context->type->is_string_type())
1632 this->type_ = context->type;
1633 else if (!context->may_be_abstract)
1634 this->type_ = Type::lookup_string_type();
1637 // Build a string constant.
1639 Bexpression*
1640 String_expression::do_get_backend(Translate_context* context)
1642 Gogo* gogo = context->gogo();
1643 Btype* btype = Type::make_string_type()->get_backend(gogo);
1645 Location loc = this->location();
1646 std::vector<Bexpression*> init(2);
1647 Bexpression* str_cst =
1648 gogo->backend()->string_constant_expression(this->val_);
1649 init[0] = gogo->backend()->address_expression(str_cst, loc);
1651 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1652 mpz_t lenval;
1653 mpz_init_set_ui(lenval, this->val_.length());
1654 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1655 mpz_clear(lenval);
1657 return gogo->backend()->constructor_expression(btype, init, loc);
1660 // Write string literal to string dump.
1662 void
1663 String_expression::export_string(String_dump* exp,
1664 const String_expression* str)
1666 std::string s;
1667 s.reserve(str->val_.length() * 4 + 2);
1668 s += '"';
1669 for (std::string::const_iterator p = str->val_.begin();
1670 p != str->val_.end();
1671 ++p)
1673 if (*p == '\\' || *p == '"')
1675 s += '\\';
1676 s += *p;
1678 else if (*p >= 0x20 && *p < 0x7f)
1679 s += *p;
1680 else if (*p == '\n')
1681 s += "\\n";
1682 else if (*p == '\t')
1683 s += "\\t";
1684 else
1686 s += "\\x";
1687 unsigned char c = *p;
1688 unsigned int dig = c >> 4;
1689 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1690 dig = c & 0xf;
1691 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1694 s += '"';
1695 exp->write_string(s);
1698 // Export a string expression.
1700 void
1701 String_expression::do_export(Export* exp) const
1703 String_expression::export_string(exp, this);
1706 // Import a string expression.
1708 Expression*
1709 String_expression::do_import(Import* imp)
1711 imp->require_c_string("\"");
1712 std::string val;
1713 while (true)
1715 int c = imp->get_char();
1716 if (c == '"' || c == -1)
1717 break;
1718 if (c != '\\')
1719 val += static_cast<char>(c);
1720 else
1722 c = imp->get_char();
1723 if (c == '\\' || c == '"')
1724 val += static_cast<char>(c);
1725 else if (c == 'n')
1726 val += '\n';
1727 else if (c == 't')
1728 val += '\t';
1729 else if (c == 'x')
1731 c = imp->get_char();
1732 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1733 c = imp->get_char();
1734 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1735 char v = (vh << 4) | vl;
1736 val += v;
1738 else
1740 go_error_at(imp->location(), "bad string constant");
1741 return Expression::make_error(imp->location());
1745 return Expression::make_string(val, imp->location());
1748 // Ast dump for string expression.
1750 void
1751 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1753 String_expression::export_string(ast_dump_context, this);
1756 // Make a string expression.
1758 Expression*
1759 Expression::make_string(const std::string& val, Location location)
1761 return new String_expression(val, location);
1764 // An expression that evaluates to some characteristic of a string.
1765 // This is used when indexing, bound-checking, or nil checking a string.
1767 class String_info_expression : public Expression
1769 public:
1770 String_info_expression(Expression* string, String_info string_info,
1771 Location location)
1772 : Expression(EXPRESSION_STRING_INFO, location),
1773 string_(string), string_info_(string_info)
1776 protected:
1777 Type*
1778 do_type();
1780 void
1781 do_determine_type(const Type_context*)
1782 { go_unreachable(); }
1784 Expression*
1785 do_copy()
1787 return new String_info_expression(this->string_->copy(), this->string_info_,
1788 this->location());
1791 Bexpression*
1792 do_get_backend(Translate_context* context);
1794 void
1795 do_dump_expression(Ast_dump_context*) const;
1797 void
1798 do_issue_nil_check()
1799 { this->string_->issue_nil_check(); }
1801 private:
1802 // The string for which we are getting information.
1803 Expression* string_;
1804 // What information we want.
1805 String_info string_info_;
1808 // Return the type of the string info.
1810 Type*
1811 String_info_expression::do_type()
1813 switch (this->string_info_)
1815 case STRING_INFO_DATA:
1817 Type* byte_type = Type::lookup_integer_type("uint8");
1818 return Type::make_pointer_type(byte_type);
1820 case STRING_INFO_LENGTH:
1821 return Type::lookup_integer_type("int");
1822 default:
1823 go_unreachable();
1827 // Return string information in GENERIC.
1829 Bexpression*
1830 String_info_expression::do_get_backend(Translate_context* context)
1832 Gogo* gogo = context->gogo();
1834 Bexpression* bstring = this->string_->get_backend(context);
1835 switch (this->string_info_)
1837 case STRING_INFO_DATA:
1838 case STRING_INFO_LENGTH:
1839 return gogo->backend()->struct_field_expression(bstring,
1840 this->string_info_,
1841 this->location());
1842 break;
1843 default:
1844 go_unreachable();
1848 // Dump ast representation for a type info expression.
1850 void
1851 String_info_expression::do_dump_expression(
1852 Ast_dump_context* ast_dump_context) const
1854 ast_dump_context->ostream() << "stringinfo(";
1855 this->string_->dump_expression(ast_dump_context);
1856 ast_dump_context->ostream() << ",";
1857 ast_dump_context->ostream() <<
1858 (this->string_info_ == STRING_INFO_DATA ? "data"
1859 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1860 : "unknown");
1861 ast_dump_context->ostream() << ")";
1864 // Make a string info expression.
1866 Expression*
1867 Expression::make_string_info(Expression* string, String_info string_info,
1868 Location location)
1870 return new String_info_expression(string, string_info, location);
1873 // Make an integer expression.
1875 class Integer_expression : public Expression
1877 public:
1878 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1879 Location location)
1880 : Expression(EXPRESSION_INTEGER, location),
1881 type_(type), is_character_constant_(is_character_constant)
1882 { mpz_init_set(this->val_, *val); }
1884 static Expression*
1885 do_import(Import*);
1887 // Write VAL to string dump.
1888 static void
1889 export_integer(String_dump* exp, const mpz_t val);
1891 // Write VAL to dump context.
1892 static void
1893 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1895 protected:
1896 bool
1897 do_is_constant() const
1898 { return true; }
1900 bool
1901 do_is_static_initializer() const
1902 { return true; }
1904 bool
1905 do_numeric_constant_value(Numeric_constant* nc) const;
1907 Type*
1908 do_type();
1910 void
1911 do_determine_type(const Type_context* context);
1913 void
1914 do_check_types(Gogo*);
1916 Bexpression*
1917 do_get_backend(Translate_context*);
1919 Expression*
1920 do_copy()
1922 if (this->is_character_constant_)
1923 return Expression::make_character(&this->val_, this->type_,
1924 this->location());
1925 else
1926 return Expression::make_integer_z(&this->val_, this->type_,
1927 this->location());
1930 void
1931 do_export(Export*) const;
1933 void
1934 do_dump_expression(Ast_dump_context*) const;
1936 private:
1937 // The integer value.
1938 mpz_t val_;
1939 // The type so far.
1940 Type* type_;
1941 // Whether this is a character constant.
1942 bool is_character_constant_;
1945 // Return a numeric constant for this expression. We have to mark
1946 // this as a character when appropriate.
1948 bool
1949 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1951 if (this->is_character_constant_)
1952 nc->set_rune(this->type_, this->val_);
1953 else
1954 nc->set_int(this->type_, this->val_);
1955 return true;
1958 // Return the current type. If we haven't set the type yet, we return
1959 // an abstract integer type.
1961 Type*
1962 Integer_expression::do_type()
1964 if (this->type_ == NULL)
1966 if (this->is_character_constant_)
1967 this->type_ = Type::make_abstract_character_type();
1968 else
1969 this->type_ = Type::make_abstract_integer_type();
1971 return this->type_;
1974 // Set the type of the integer value. Here we may switch from an
1975 // abstract type to a real type.
1977 void
1978 Integer_expression::do_determine_type(const Type_context* context)
1980 if (this->type_ != NULL && !this->type_->is_abstract())
1982 else if (context->type != NULL && context->type->is_numeric_type())
1983 this->type_ = context->type;
1984 else if (!context->may_be_abstract)
1986 if (this->is_character_constant_)
1987 this->type_ = Type::lookup_integer_type("int32");
1988 else
1989 this->type_ = Type::lookup_integer_type("int");
1993 // Check the type of an integer constant.
1995 void
1996 Integer_expression::do_check_types(Gogo*)
1998 Type* type = this->type_;
1999 if (type == NULL)
2000 return;
2001 Numeric_constant nc;
2002 if (this->is_character_constant_)
2003 nc.set_rune(NULL, this->val_);
2004 else
2005 nc.set_int(NULL, this->val_);
2006 if (!nc.set_type(type, true, this->location()))
2007 this->set_is_error();
2010 // Get the backend representation for an integer constant.
2012 Bexpression*
2013 Integer_expression::do_get_backend(Translate_context* context)
2015 if (this->is_error_expression()
2016 || (this->type_ != NULL && this->type_->is_error_type()))
2018 go_assert(saw_errors());
2019 return context->gogo()->backend()->error_expression();
2022 Type* resolved_type = NULL;
2023 if (this->type_ != NULL && !this->type_->is_abstract())
2024 resolved_type = this->type_;
2025 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2027 // We are converting to an abstract floating point type.
2028 resolved_type = Type::lookup_float_type("float64");
2030 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2032 // We are converting to an abstract complex type.
2033 resolved_type = Type::lookup_complex_type("complex128");
2035 else
2037 // If we still have an abstract type here, then this is being
2038 // used in a constant expression which didn't get reduced for
2039 // some reason. Use a type which will fit the value. We use <,
2040 // not <=, because we need an extra bit for the sign bit.
2041 int bits = mpz_sizeinbase(this->val_, 2);
2042 Type* int_type = Type::lookup_integer_type("int");
2043 if (bits < int_type->integer_type()->bits())
2044 resolved_type = int_type;
2045 else if (bits < 64)
2046 resolved_type = Type::lookup_integer_type("int64");
2047 else
2049 if (!saw_errors())
2050 go_error_at(this->location(),
2051 "unknown type for large integer constant");
2052 return context->gogo()->backend()->error_expression();
2055 Numeric_constant nc;
2056 nc.set_int(resolved_type, this->val_);
2057 return Expression::backend_numeric_constant_expression(context, &nc);
2060 // Write VAL to export data.
2062 void
2063 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2065 char* s = mpz_get_str(NULL, 10, val);
2066 exp->write_c_string(s);
2067 free(s);
2070 // Export an integer in a constant expression.
2072 void
2073 Integer_expression::do_export(Export* exp) const
2075 Integer_expression::export_integer(exp, this->val_);
2076 if (this->is_character_constant_)
2077 exp->write_c_string("'");
2078 // A trailing space lets us reliably identify the end of the number.
2079 exp->write_c_string(" ");
2082 // Import an integer, floating point, or complex value. This handles
2083 // all these types because they all start with digits.
2085 Expression*
2086 Integer_expression::do_import(Import* imp)
2088 std::string num = imp->read_identifier();
2089 imp->require_c_string(" ");
2090 if (!num.empty() && num[num.length() - 1] == 'i')
2092 mpfr_t real;
2093 size_t plus_pos = num.find('+', 1);
2094 size_t minus_pos = num.find('-', 1);
2095 size_t pos;
2096 if (plus_pos == std::string::npos)
2097 pos = minus_pos;
2098 else if (minus_pos == std::string::npos)
2099 pos = plus_pos;
2100 else
2102 go_error_at(imp->location(), "bad number in import data: %qs",
2103 num.c_str());
2104 return Expression::make_error(imp->location());
2106 if (pos == std::string::npos)
2107 mpfr_set_ui(real, 0, GMP_RNDN);
2108 else
2110 std::string real_str = num.substr(0, pos);
2111 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2113 go_error_at(imp->location(), "bad number in import data: %qs",
2114 real_str.c_str());
2115 return Expression::make_error(imp->location());
2119 std::string imag_str;
2120 if (pos == std::string::npos)
2121 imag_str = num;
2122 else
2123 imag_str = num.substr(pos);
2124 imag_str = imag_str.substr(0, imag_str.size() - 1);
2125 mpfr_t imag;
2126 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2128 go_error_at(imp->location(), "bad number in import data: %qs",
2129 imag_str.c_str());
2130 return Expression::make_error(imp->location());
2132 mpc_t cval;
2133 mpc_init2(cval, mpc_precision);
2134 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2135 mpfr_clear(real);
2136 mpfr_clear(imag);
2137 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2138 mpc_clear(cval);
2139 return ret;
2141 else if (num.find('.') == std::string::npos
2142 && num.find('E') == std::string::npos)
2144 bool is_character_constant = (!num.empty()
2145 && num[num.length() - 1] == '\'');
2146 if (is_character_constant)
2147 num = num.substr(0, num.length() - 1);
2148 mpz_t val;
2149 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2151 go_error_at(imp->location(), "bad number in import data: %qs",
2152 num.c_str());
2153 return Expression::make_error(imp->location());
2155 Expression* ret;
2156 if (is_character_constant)
2157 ret = Expression::make_character(&val, NULL, imp->location());
2158 else
2159 ret = Expression::make_integer_z(&val, NULL, imp->location());
2160 mpz_clear(val);
2161 return ret;
2163 else
2165 mpfr_t val;
2166 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2168 go_error_at(imp->location(), "bad number in import data: %qs",
2169 num.c_str());
2170 return Expression::make_error(imp->location());
2172 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2173 mpfr_clear(val);
2174 return ret;
2177 // Ast dump for integer expression.
2179 void
2180 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2182 if (this->is_character_constant_)
2183 ast_dump_context->ostream() << '\'';
2184 Integer_expression::export_integer(ast_dump_context, this->val_);
2185 if (this->is_character_constant_)
2186 ast_dump_context->ostream() << '\'';
2189 // Build a new integer value from a multi-precision integer.
2191 Expression*
2192 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2194 return new Integer_expression(val, type, false, location);
2197 // Build a new integer value from an unsigned long.
2199 Expression*
2200 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2202 mpz_t zval;
2203 mpz_init_set_ui(zval, val);
2204 Expression* ret = Expression::make_integer_z(&zval, type, location);
2205 mpz_clear(zval);
2206 return ret;
2209 // Build a new integer value from a signed long.
2211 Expression*
2212 Expression::make_integer_sl(long val, Type *type, Location location)
2214 mpz_t zval;
2215 mpz_init_set_si(zval, val);
2216 Expression* ret = Expression::make_integer_z(&zval, type, location);
2217 mpz_clear(zval);
2218 return ret;
2221 // Store an int64_t in an uninitialized mpz_t.
2223 static void
2224 set_mpz_from_int64(mpz_t* zval, int64_t val)
2226 if (val >= 0)
2228 unsigned long ul = static_cast<unsigned long>(val);
2229 if (static_cast<int64_t>(ul) == val)
2231 mpz_init_set_ui(*zval, ul);
2232 return;
2235 uint64_t uv;
2236 if (val >= 0)
2237 uv = static_cast<uint64_t>(val);
2238 else
2239 uv = static_cast<uint64_t>(- val);
2240 unsigned long ul = uv & 0xffffffffUL;
2241 mpz_init_set_ui(*zval, ul);
2242 mpz_t hval;
2243 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2244 mpz_mul_2exp(hval, hval, 32);
2245 mpz_add(*zval, *zval, hval);
2246 mpz_clear(hval);
2247 if (val < 0)
2248 mpz_neg(*zval, *zval);
2251 // Build a new integer value from an int64_t.
2253 Expression*
2254 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2256 mpz_t zval;
2257 set_mpz_from_int64(&zval, val);
2258 Expression* ret = Expression::make_integer_z(&zval, type, location);
2259 mpz_clear(zval);
2260 return ret;
2263 // Build a new character constant value.
2265 Expression*
2266 Expression::make_character(const mpz_t* val, Type* type, Location location)
2268 return new Integer_expression(val, type, true, location);
2271 // Floats.
2273 class Float_expression : public Expression
2275 public:
2276 Float_expression(const mpfr_t* val, Type* type, Location location)
2277 : Expression(EXPRESSION_FLOAT, location),
2278 type_(type)
2280 mpfr_init_set(this->val_, *val, GMP_RNDN);
2283 // Write VAL to export data.
2284 static void
2285 export_float(String_dump* exp, const mpfr_t val);
2287 // Write VAL to dump file.
2288 static void
2289 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2291 protected:
2292 bool
2293 do_is_constant() const
2294 { return true; }
2296 bool
2297 do_is_static_initializer() const
2298 { return true; }
2300 bool
2301 do_numeric_constant_value(Numeric_constant* nc) const
2303 nc->set_float(this->type_, this->val_);
2304 return true;
2307 Type*
2308 do_type();
2310 void
2311 do_determine_type(const Type_context*);
2313 void
2314 do_check_types(Gogo*);
2316 Expression*
2317 do_copy()
2318 { return Expression::make_float(&this->val_, this->type_,
2319 this->location()); }
2321 Bexpression*
2322 do_get_backend(Translate_context*);
2324 void
2325 do_export(Export*) const;
2327 void
2328 do_dump_expression(Ast_dump_context*) const;
2330 private:
2331 // The floating point value.
2332 mpfr_t val_;
2333 // The type so far.
2334 Type* type_;
2337 // Return the current type. If we haven't set the type yet, we return
2338 // an abstract float type.
2340 Type*
2341 Float_expression::do_type()
2343 if (this->type_ == NULL)
2344 this->type_ = Type::make_abstract_float_type();
2345 return this->type_;
2348 // Set the type of the float value. Here we may switch from an
2349 // abstract type to a real type.
2351 void
2352 Float_expression::do_determine_type(const Type_context* context)
2354 if (this->type_ != NULL && !this->type_->is_abstract())
2356 else if (context->type != NULL
2357 && (context->type->integer_type() != NULL
2358 || context->type->float_type() != NULL
2359 || context->type->complex_type() != NULL))
2360 this->type_ = context->type;
2361 else if (!context->may_be_abstract)
2362 this->type_ = Type::lookup_float_type("float64");
2365 // Check the type of a float value.
2367 void
2368 Float_expression::do_check_types(Gogo*)
2370 Type* type = this->type_;
2371 if (type == NULL)
2372 return;
2373 Numeric_constant nc;
2374 nc.set_float(NULL, this->val_);
2375 if (!nc.set_type(this->type_, true, this->location()))
2376 this->set_is_error();
2379 // Get the backend representation for a float constant.
2381 Bexpression*
2382 Float_expression::do_get_backend(Translate_context* context)
2384 if (this->is_error_expression()
2385 || (this->type_ != NULL && this->type_->is_error_type()))
2387 go_assert(saw_errors());
2388 return context->gogo()->backend()->error_expression();
2391 Type* resolved_type;
2392 if (this->type_ != NULL && !this->type_->is_abstract())
2393 resolved_type = this->type_;
2394 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2396 // We have an abstract integer type. We just hope for the best.
2397 resolved_type = Type::lookup_integer_type("int");
2399 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2401 // We are converting to an abstract complex type.
2402 resolved_type = Type::lookup_complex_type("complex128");
2404 else
2406 // If we still have an abstract type here, then this is being
2407 // used in a constant expression which didn't get reduced. We
2408 // just use float64 and hope for the best.
2409 resolved_type = Type::lookup_float_type("float64");
2412 Numeric_constant nc;
2413 nc.set_float(resolved_type, this->val_);
2414 return Expression::backend_numeric_constant_expression(context, &nc);
2417 // Write a floating point number to a string dump.
2419 void
2420 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2422 mp_exp_t exponent;
2423 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2424 if (*s == '-')
2425 exp->write_c_string("-");
2426 exp->write_c_string("0.");
2427 exp->write_c_string(*s == '-' ? s + 1 : s);
2428 mpfr_free_str(s);
2429 char buf[30];
2430 snprintf(buf, sizeof buf, "E%ld", exponent);
2431 exp->write_c_string(buf);
2434 // Export a floating point number in a constant expression.
2436 void
2437 Float_expression::do_export(Export* exp) const
2439 Float_expression::export_float(exp, this->val_);
2440 // A trailing space lets us reliably identify the end of the number.
2441 exp->write_c_string(" ");
2444 // Dump a floating point number to the dump file.
2446 void
2447 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2449 Float_expression::export_float(ast_dump_context, this->val_);
2452 // Make a float expression.
2454 Expression*
2455 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2457 return new Float_expression(val, type, location);
2460 // Complex numbers.
2462 class Complex_expression : public Expression
2464 public:
2465 Complex_expression(const mpc_t* val, Type* type, Location location)
2466 : Expression(EXPRESSION_COMPLEX, location),
2467 type_(type)
2469 mpc_init2(this->val_, mpc_precision);
2470 mpc_set(this->val_, *val, MPC_RNDNN);
2473 // Write VAL to string dump.
2474 static void
2475 export_complex(String_dump* exp, const mpc_t val);
2477 // Write REAL/IMAG to dump context.
2478 static void
2479 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2481 protected:
2482 bool
2483 do_is_constant() const
2484 { return true; }
2486 bool
2487 do_is_static_initializer() const
2488 { return true; }
2490 bool
2491 do_numeric_constant_value(Numeric_constant* nc) const
2493 nc->set_complex(this->type_, this->val_);
2494 return true;
2497 Type*
2498 do_type();
2500 void
2501 do_determine_type(const Type_context*);
2503 void
2504 do_check_types(Gogo*);
2506 Expression*
2507 do_copy()
2509 return Expression::make_complex(&this->val_, this->type_,
2510 this->location());
2513 Bexpression*
2514 do_get_backend(Translate_context*);
2516 void
2517 do_export(Export*) const;
2519 void
2520 do_dump_expression(Ast_dump_context*) const;
2522 private:
2523 // The complex value.
2524 mpc_t val_;
2525 // The type if known.
2526 Type* type_;
2529 // Return the current type. If we haven't set the type yet, we return
2530 // an abstract complex type.
2532 Type*
2533 Complex_expression::do_type()
2535 if (this->type_ == NULL)
2536 this->type_ = Type::make_abstract_complex_type();
2537 return this->type_;
2540 // Set the type of the complex value. Here we may switch from an
2541 // abstract type to a real type.
2543 void
2544 Complex_expression::do_determine_type(const Type_context* context)
2546 if (this->type_ != NULL && !this->type_->is_abstract())
2548 else if (context->type != NULL && context->type->is_numeric_type())
2549 this->type_ = context->type;
2550 else if (!context->may_be_abstract)
2551 this->type_ = Type::lookup_complex_type("complex128");
2554 // Check the type of a complex value.
2556 void
2557 Complex_expression::do_check_types(Gogo*)
2559 Type* type = this->type_;
2560 if (type == NULL)
2561 return;
2562 Numeric_constant nc;
2563 nc.set_complex(NULL, this->val_);
2564 if (!nc.set_type(this->type_, true, this->location()))
2565 this->set_is_error();
2568 // Get the backend representation for a complex constant.
2570 Bexpression*
2571 Complex_expression::do_get_backend(Translate_context* context)
2573 if (this->is_error_expression()
2574 || (this->type_ != NULL && this->type_->is_error_type()))
2576 go_assert(saw_errors());
2577 return context->gogo()->backend()->error_expression();
2580 Type* resolved_type;
2581 if (this->type_ != NULL && !this->type_->is_abstract())
2582 resolved_type = this->type_;
2583 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2585 // We are converting to an abstract integer type.
2586 resolved_type = Type::lookup_integer_type("int");
2588 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2590 // We are converting to an abstract float type.
2591 resolved_type = Type::lookup_float_type("float64");
2593 else
2595 // If we still have an abstract type here, this is being
2596 // used in a constant expression which didn't get reduced. We
2597 // just use complex128 and hope for the best.
2598 resolved_type = Type::lookup_complex_type("complex128");
2601 Numeric_constant nc;
2602 nc.set_complex(resolved_type, this->val_);
2603 return Expression::backend_numeric_constant_expression(context, &nc);
2606 // Write REAL/IMAG to export data.
2608 void
2609 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2611 if (!mpfr_zero_p(mpc_realref(val)))
2613 Float_expression::export_float(exp, mpc_realref(val));
2614 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2615 exp->write_c_string("+");
2617 Float_expression::export_float(exp, mpc_imagref(val));
2618 exp->write_c_string("i");
2621 // Export a complex number in a constant expression.
2623 void
2624 Complex_expression::do_export(Export* exp) const
2626 Complex_expression::export_complex(exp, this->val_);
2627 // A trailing space lets us reliably identify the end of the number.
2628 exp->write_c_string(" ");
2631 // Dump a complex expression to the dump file.
2633 void
2634 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2636 Complex_expression::export_complex(ast_dump_context, this->val_);
2639 // Make a complex expression.
2641 Expression*
2642 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2644 return new Complex_expression(val, type, location);
2647 // Find a named object in an expression.
2649 class Find_named_object : public Traverse
2651 public:
2652 Find_named_object(Named_object* no)
2653 : Traverse(traverse_expressions),
2654 no_(no), found_(false)
2657 // Whether we found the object.
2658 bool
2659 found() const
2660 { return this->found_; }
2662 protected:
2664 expression(Expression**);
2666 private:
2667 // The object we are looking for.
2668 Named_object* no_;
2669 // Whether we found it.
2670 bool found_;
2673 // A reference to a const in an expression.
2675 class Const_expression : public Expression
2677 public:
2678 Const_expression(Named_object* constant, Location location)
2679 : Expression(EXPRESSION_CONST_REFERENCE, location),
2680 constant_(constant), type_(NULL), seen_(false)
2683 Named_object*
2684 named_object()
2685 { return this->constant_; }
2687 // Check that the initializer does not refer to the constant itself.
2688 void
2689 check_for_init_loop();
2691 protected:
2693 do_traverse(Traverse*);
2695 Expression*
2696 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2698 bool
2699 do_is_constant() const
2700 { return true; }
2702 bool
2703 do_is_static_initializer() const
2704 { return true; }
2706 bool
2707 do_numeric_constant_value(Numeric_constant* nc) const;
2709 bool
2710 do_string_constant_value(std::string* val) const;
2712 Type*
2713 do_type();
2715 // The type of a const is set by the declaration, not the use.
2716 void
2717 do_determine_type(const Type_context*);
2719 void
2720 do_check_types(Gogo*);
2722 Expression*
2723 do_copy()
2724 { return this; }
2726 Bexpression*
2727 do_get_backend(Translate_context* context);
2729 // When exporting a reference to a const as part of a const
2730 // expression, we export the value. We ignore the fact that it has
2731 // a name.
2732 void
2733 do_export(Export* exp) const
2734 { this->constant_->const_value()->expr()->export_expression(exp); }
2736 void
2737 do_dump_expression(Ast_dump_context*) const;
2739 private:
2740 // The constant.
2741 Named_object* constant_;
2742 // The type of this reference. This is used if the constant has an
2743 // abstract type.
2744 Type* type_;
2745 // Used to prevent infinite recursion when a constant incorrectly
2746 // refers to itself.
2747 mutable bool seen_;
2750 // Traversal.
2753 Const_expression::do_traverse(Traverse* traverse)
2755 if (this->type_ != NULL)
2756 return Type::traverse(this->type_, traverse);
2757 return TRAVERSE_CONTINUE;
2760 // Lower a constant expression. This is where we convert the
2761 // predeclared constant iota into an integer value.
2763 Expression*
2764 Const_expression::do_lower(Gogo* gogo, Named_object*,
2765 Statement_inserter*, int iota_value)
2767 if (this->constant_->const_value()->expr()->classification()
2768 == EXPRESSION_IOTA)
2770 if (iota_value == -1)
2772 go_error_at(this->location(),
2773 "iota is only defined in const declarations");
2774 iota_value = 0;
2776 return Expression::make_integer_ul(iota_value, NULL, this->location());
2779 // Make sure that the constant itself has been lowered.
2780 gogo->lower_constant(this->constant_);
2782 return this;
2785 // Return a numeric constant value.
2787 bool
2788 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2790 if (this->seen_)
2791 return false;
2793 Expression* e = this->constant_->const_value()->expr();
2795 this->seen_ = true;
2797 bool r = e->numeric_constant_value(nc);
2799 this->seen_ = false;
2801 Type* ctype;
2802 if (this->type_ != NULL)
2803 ctype = this->type_;
2804 else
2805 ctype = this->constant_->const_value()->type();
2806 if (r && ctype != NULL)
2808 if (!nc->set_type(ctype, false, this->location()))
2809 return false;
2812 return r;
2815 bool
2816 Const_expression::do_string_constant_value(std::string* val) const
2818 if (this->seen_)
2819 return false;
2821 Expression* e = this->constant_->const_value()->expr();
2823 this->seen_ = true;
2824 bool ok = e->string_constant_value(val);
2825 this->seen_ = false;
2827 return ok;
2830 // Return the type of the const reference.
2832 Type*
2833 Const_expression::do_type()
2835 if (this->type_ != NULL)
2836 return this->type_;
2838 Named_constant* nc = this->constant_->const_value();
2840 if (this->seen_ || nc->lowering())
2842 this->report_error(_("constant refers to itself"));
2843 this->type_ = Type::make_error_type();
2844 return this->type_;
2847 this->seen_ = true;
2849 Type* ret = nc->type();
2851 if (ret != NULL)
2853 this->seen_ = false;
2854 return ret;
2857 // During parsing, a named constant may have a NULL type, but we
2858 // must not return a NULL type here.
2859 ret = nc->expr()->type();
2861 this->seen_ = false;
2863 return ret;
2866 // Set the type of the const reference.
2868 void
2869 Const_expression::do_determine_type(const Type_context* context)
2871 Type* ctype = this->constant_->const_value()->type();
2872 Type* cetype = (ctype != NULL
2873 ? ctype
2874 : this->constant_->const_value()->expr()->type());
2875 if (ctype != NULL && !ctype->is_abstract())
2877 else if (context->type != NULL
2878 && context->type->is_numeric_type()
2879 && cetype->is_numeric_type())
2880 this->type_ = context->type;
2881 else if (context->type != NULL
2882 && context->type->is_string_type()
2883 && cetype->is_string_type())
2884 this->type_ = context->type;
2885 else if (context->type != NULL
2886 && context->type->is_boolean_type()
2887 && cetype->is_boolean_type())
2888 this->type_ = context->type;
2889 else if (!context->may_be_abstract)
2891 if (cetype->is_abstract())
2892 cetype = cetype->make_non_abstract_type();
2893 this->type_ = cetype;
2897 // Check for a loop in which the initializer of a constant refers to
2898 // the constant itself.
2900 void
2901 Const_expression::check_for_init_loop()
2903 if (this->type_ != NULL && this->type_->is_error())
2904 return;
2906 if (this->seen_)
2908 this->report_error(_("constant refers to itself"));
2909 this->type_ = Type::make_error_type();
2910 return;
2913 Expression* init = this->constant_->const_value()->expr();
2914 Find_named_object find_named_object(this->constant_);
2916 this->seen_ = true;
2917 Expression::traverse(&init, &find_named_object);
2918 this->seen_ = false;
2920 if (find_named_object.found())
2922 if (this->type_ == NULL || !this->type_->is_error())
2924 this->report_error(_("constant refers to itself"));
2925 this->type_ = Type::make_error_type();
2927 return;
2931 // Check types of a const reference.
2933 void
2934 Const_expression::do_check_types(Gogo*)
2936 if (this->type_ != NULL && this->type_->is_error())
2937 return;
2939 this->check_for_init_loop();
2941 // Check that numeric constant fits in type.
2942 if (this->type_ != NULL && this->type_->is_numeric_type())
2944 Numeric_constant nc;
2945 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2947 if (!nc.set_type(this->type_, true, this->location()))
2948 this->set_is_error();
2953 // Return the backend representation for a const reference.
2955 Bexpression*
2956 Const_expression::do_get_backend(Translate_context* context)
2958 if (this->is_error_expression()
2959 || (this->type_ != NULL && this->type_->is_error()))
2961 go_assert(saw_errors());
2962 return context->backend()->error_expression();
2965 // If the type has been set for this expression, but the underlying
2966 // object is an abstract int or float, we try to get the abstract
2967 // value. Otherwise we may lose something in the conversion.
2968 Expression* expr = this->constant_->const_value()->expr();
2969 if (this->type_ != NULL
2970 && this->type_->is_numeric_type()
2971 && (this->constant_->const_value()->type() == NULL
2972 || this->constant_->const_value()->type()->is_abstract()))
2974 Numeric_constant nc;
2975 if (expr->numeric_constant_value(&nc)
2976 && nc.set_type(this->type_, false, this->location()))
2978 Expression* e = nc.expression(this->location());
2979 return e->get_backend(context);
2983 if (this->type_ != NULL)
2984 expr = Expression::make_cast(this->type_, expr, this->location());
2985 return expr->get_backend(context);
2988 // Dump ast representation for constant expression.
2990 void
2991 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2993 ast_dump_context->ostream() << this->constant_->name();
2996 // Make a reference to a constant in an expression.
2998 Expression*
2999 Expression::make_const_reference(Named_object* constant,
3000 Location location)
3002 return new Const_expression(constant, location);
3005 // Find a named object in an expression.
3008 Find_named_object::expression(Expression** pexpr)
3010 switch ((*pexpr)->classification())
3012 case Expression::EXPRESSION_CONST_REFERENCE:
3014 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3015 if (ce->named_object() == this->no_)
3016 break;
3018 // We need to check a constant initializer explicitly, as
3019 // loops here will not be caught by the loop checking for
3020 // variable initializers.
3021 ce->check_for_init_loop();
3023 return TRAVERSE_CONTINUE;
3026 case Expression::EXPRESSION_VAR_REFERENCE:
3027 if ((*pexpr)->var_expression()->named_object() == this->no_)
3028 break;
3029 return TRAVERSE_CONTINUE;
3030 case Expression::EXPRESSION_FUNC_REFERENCE:
3031 if ((*pexpr)->func_expression()->named_object() == this->no_)
3032 break;
3033 return TRAVERSE_CONTINUE;
3034 default:
3035 return TRAVERSE_CONTINUE;
3037 this->found_ = true;
3038 return TRAVERSE_EXIT;
3041 // The nil value.
3043 class Nil_expression : public Expression
3045 public:
3046 Nil_expression(Location location)
3047 : Expression(EXPRESSION_NIL, location)
3050 static Expression*
3051 do_import(Import*);
3053 protected:
3054 bool
3055 do_is_constant() const
3056 { return true; }
3058 bool
3059 do_is_static_initializer() const
3060 { return true; }
3062 Type*
3063 do_type()
3064 { return Type::make_nil_type(); }
3066 void
3067 do_determine_type(const Type_context*)
3070 Expression*
3071 do_copy()
3072 { return this; }
3074 Bexpression*
3075 do_get_backend(Translate_context* context)
3076 { return context->backend()->nil_pointer_expression(); }
3078 void
3079 do_export(Export* exp) const
3080 { exp->write_c_string("nil"); }
3082 void
3083 do_dump_expression(Ast_dump_context* ast_dump_context) const
3084 { ast_dump_context->ostream() << "nil"; }
3087 // Import a nil expression.
3089 Expression*
3090 Nil_expression::do_import(Import* imp)
3092 imp->require_c_string("nil");
3093 return Expression::make_nil(imp->location());
3096 // Make a nil expression.
3098 Expression*
3099 Expression::make_nil(Location location)
3101 return new Nil_expression(location);
3104 // The value of the predeclared constant iota. This is little more
3105 // than a marker. This will be lowered to an integer in
3106 // Const_expression::do_lower, which is where we know the value that
3107 // it should have.
3109 class Iota_expression : public Parser_expression
3111 public:
3112 Iota_expression(Location location)
3113 : Parser_expression(EXPRESSION_IOTA, location)
3116 protected:
3117 Expression*
3118 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3119 { go_unreachable(); }
3121 // There should only ever be one of these.
3122 Expression*
3123 do_copy()
3124 { go_unreachable(); }
3126 void
3127 do_dump_expression(Ast_dump_context* ast_dump_context) const
3128 { ast_dump_context->ostream() << "iota"; }
3131 // Make an iota expression. This is only called for one case: the
3132 // value of the predeclared constant iota.
3134 Expression*
3135 Expression::make_iota()
3137 static Iota_expression iota_expression(Linemap::unknown_location());
3138 return &iota_expression;
3141 // Class Type_conversion_expression.
3143 // Traversal.
3146 Type_conversion_expression::do_traverse(Traverse* traverse)
3148 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3149 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3150 return TRAVERSE_EXIT;
3151 return TRAVERSE_CONTINUE;
3154 // Convert to a constant at lowering time.
3156 Expression*
3157 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3158 Statement_inserter*, int)
3160 Type* type = this->type_;
3161 Expression* val = this->expr_;
3162 Location location = this->location();
3164 if (type->is_numeric_type())
3166 Numeric_constant nc;
3167 if (val->numeric_constant_value(&nc))
3169 if (!nc.set_type(type, true, location))
3170 return Expression::make_error(location);
3171 return nc.expression(location);
3175 // According to the language specification on string conversions
3176 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3177 // When converting an integer into a string, the string will be a UTF-8
3178 // representation of the integer and integers "outside the range of valid
3179 // Unicode code points are converted to '\uFFFD'."
3180 if (type->is_string_type())
3182 Numeric_constant nc;
3183 if (val->numeric_constant_value(&nc) && nc.is_int())
3185 // An integer value doesn't fit in the Unicode code point range if it
3186 // overflows the Go "int" type or is negative.
3187 unsigned long ul;
3188 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3189 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3190 return Expression::make_string("\ufffd", location);
3194 if (type->is_slice_type())
3196 Type* element_type = type->array_type()->element_type()->forwarded();
3197 bool is_byte = (element_type->integer_type() != NULL
3198 && element_type->integer_type()->is_byte());
3199 bool is_rune = (element_type->integer_type() != NULL
3200 && element_type->integer_type()->is_rune());
3201 if (is_byte || is_rune)
3203 std::string s;
3204 if (val->string_constant_value(&s))
3206 Expression_list* vals = new Expression_list();
3207 if (is_byte)
3209 for (std::string::const_iterator p = s.begin();
3210 p != s.end();
3211 p++)
3213 unsigned char c = static_cast<unsigned char>(*p);
3214 vals->push_back(Expression::make_integer_ul(c,
3215 element_type,
3216 location));
3219 else
3221 const char *p = s.data();
3222 const char *pend = s.data() + s.length();
3223 while (p < pend)
3225 unsigned int c;
3226 int adv = Lex::fetch_char(p, &c);
3227 if (adv == 0)
3229 go_warning_at(this->location(), 0,
3230 "invalid UTF-8 encoding");
3231 adv = 1;
3233 p += adv;
3234 vals->push_back(Expression::make_integer_ul(c,
3235 element_type,
3236 location));
3240 return Expression::make_slice_composite_literal(type, vals,
3241 location);
3246 return this;
3249 // Flatten a type conversion by using a temporary variable for the slice
3250 // in slice to string conversions.
3252 Expression*
3253 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3254 Statement_inserter* inserter)
3256 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3258 go_assert(saw_errors());
3259 return Expression::make_error(this->location());
3262 if (((this->type()->is_string_type()
3263 && this->expr_->type()->is_slice_type())
3264 || this->expr_->type()->interface_type() != NULL)
3265 && !this->expr_->is_variable())
3267 Temporary_statement* temp =
3268 Statement::make_temporary(NULL, this->expr_, this->location());
3269 inserter->insert(temp);
3270 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3272 return this;
3275 // Return whether a type conversion is a constant.
3277 bool
3278 Type_conversion_expression::do_is_constant() const
3280 if (!this->expr_->is_constant())
3281 return false;
3283 // A conversion to a type that may not be used as a constant is not
3284 // a constant. For example, []byte(nil).
3285 Type* type = this->type_;
3286 if (type->integer_type() == NULL
3287 && type->float_type() == NULL
3288 && type->complex_type() == NULL
3289 && !type->is_boolean_type()
3290 && !type->is_string_type())
3291 return false;
3293 return true;
3296 // Return whether a type conversion can be used in a constant
3297 // initializer.
3299 bool
3300 Type_conversion_expression::do_is_static_initializer() const
3302 Type* type = this->type_;
3303 Type* expr_type = this->expr_->type();
3305 if (type->interface_type() != NULL
3306 || expr_type->interface_type() != NULL)
3307 return false;
3309 if (!this->expr_->is_static_initializer())
3310 return false;
3312 if (Type::are_identical(type, expr_type, false, NULL))
3313 return true;
3315 if (type->is_string_type() && expr_type->is_string_type())
3316 return true;
3318 if ((type->is_numeric_type()
3319 || type->is_boolean_type()
3320 || type->points_to() != NULL)
3321 && (expr_type->is_numeric_type()
3322 || expr_type->is_boolean_type()
3323 || expr_type->points_to() != NULL))
3324 return true;
3326 return false;
3329 // Return the constant numeric value if there is one.
3331 bool
3332 Type_conversion_expression::do_numeric_constant_value(
3333 Numeric_constant* nc) const
3335 if (!this->type_->is_numeric_type())
3336 return false;
3337 if (!this->expr_->numeric_constant_value(nc))
3338 return false;
3339 return nc->set_type(this->type_, false, this->location());
3342 // Return the constant string value if there is one.
3344 bool
3345 Type_conversion_expression::do_string_constant_value(std::string* val) const
3347 if (this->type_->is_string_type()
3348 && this->expr_->type()->integer_type() != NULL)
3350 Numeric_constant nc;
3351 if (this->expr_->numeric_constant_value(&nc))
3353 unsigned long ival;
3354 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3356 val->clear();
3357 Lex::append_char(ival, true, val, this->location());
3358 return true;
3363 // FIXME: Could handle conversion from const []int here.
3365 return false;
3368 // Determine the resulting type of the conversion.
3370 void
3371 Type_conversion_expression::do_determine_type(const Type_context*)
3373 Type_context subcontext(this->type_, false);
3374 this->expr_->determine_type(&subcontext);
3377 // Check that types are convertible.
3379 void
3380 Type_conversion_expression::do_check_types(Gogo*)
3382 Type* type = this->type_;
3383 Type* expr_type = this->expr_->type();
3384 std::string reason;
3386 if (type->is_error() || expr_type->is_error())
3388 this->set_is_error();
3389 return;
3392 if (this->may_convert_function_types_
3393 && type->function_type() != NULL
3394 && expr_type->function_type() != NULL)
3395 return;
3397 if (Type::are_convertible(type, expr_type, &reason))
3398 return;
3400 go_error_at(this->location(), "%s", reason.c_str());
3401 this->set_is_error();
3404 // Get the backend representation for a type conversion.
3406 Bexpression*
3407 Type_conversion_expression::do_get_backend(Translate_context* context)
3409 Type* type = this->type_;
3410 Type* expr_type = this->expr_->type();
3412 Gogo* gogo = context->gogo();
3413 Btype* btype = type->get_backend(gogo);
3414 Location loc = this->location();
3416 if (Type::are_identical(type, expr_type, false, NULL))
3418 Bexpression* bexpr = this->expr_->get_backend(context);
3419 return gogo->backend()->convert_expression(btype, bexpr, loc);
3421 else if (type->interface_type() != NULL
3422 || expr_type->interface_type() != NULL)
3424 Expression* conversion =
3425 Expression::convert_for_assignment(gogo, type, this->expr_,
3426 this->location());
3427 return conversion->get_backend(context);
3429 else if (type->is_string_type()
3430 && expr_type->integer_type() != NULL)
3432 mpz_t intval;
3433 Numeric_constant nc;
3434 if (this->expr_->numeric_constant_value(&nc)
3435 && nc.to_int(&intval)
3436 && mpz_fits_ushort_p(intval))
3438 std::string s;
3439 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3440 mpz_clear(intval);
3441 Expression* se = Expression::make_string(s, loc);
3442 return se->get_backend(context);
3445 Expression* i2s_expr =
3446 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3447 Expression::make_nil(loc), this->expr_);
3448 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3450 else if (type->is_string_type() && expr_type->is_slice_type())
3452 Array_type* a = expr_type->array_type();
3453 Type* e = a->element_type()->forwarded();
3454 go_assert(e->integer_type() != NULL);
3455 go_assert(this->expr_->is_variable());
3457 Runtime::Function code;
3458 if (e->integer_type()->is_byte())
3459 code = Runtime::SLICEBYTETOSTRING;
3460 else
3462 go_assert(e->integer_type()->is_rune());
3463 code = Runtime::SLICERUNETOSTRING;
3465 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3466 this->expr_)->get_backend(context);
3468 else if (type->is_slice_type() && expr_type->is_string_type())
3470 Type* e = type->array_type()->element_type()->forwarded();
3471 go_assert(e->integer_type() != NULL);
3473 Runtime::Function code;
3474 if (e->integer_type()->is_byte())
3475 code = Runtime::STRINGTOSLICEBYTE;
3476 else
3478 go_assert(e->integer_type()->is_rune());
3479 code = Runtime::STRINGTOSLICERUNE;
3481 Expression* s2a = Runtime::make_call(code, loc, 2,
3482 Expression::make_nil(loc),
3483 this->expr_);
3484 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3486 else if (type->is_numeric_type())
3488 go_assert(Type::are_convertible(type, expr_type, NULL));
3489 Bexpression* bexpr = this->expr_->get_backend(context);
3490 return gogo->backend()->convert_expression(btype, bexpr, loc);
3492 else if ((type->is_unsafe_pointer_type()
3493 && (expr_type->points_to() != NULL
3494 || expr_type->integer_type()))
3495 || (expr_type->is_unsafe_pointer_type()
3496 && type->points_to() != NULL)
3497 || (this->may_convert_function_types_
3498 && type->function_type() != NULL
3499 && expr_type->function_type() != NULL))
3501 Bexpression* bexpr = this->expr_->get_backend(context);
3502 return gogo->backend()->convert_expression(btype, bexpr, loc);
3504 else
3506 Expression* conversion =
3507 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3508 return conversion->get_backend(context);
3512 // Output a type conversion in a constant expression.
3514 void
3515 Type_conversion_expression::do_export(Export* exp) const
3517 exp->write_c_string("convert(");
3518 exp->write_type(this->type_);
3519 exp->write_c_string(", ");
3520 this->expr_->export_expression(exp);
3521 exp->write_c_string(")");
3524 // Import a type conversion or a struct construction.
3526 Expression*
3527 Type_conversion_expression::do_import(Import* imp)
3529 imp->require_c_string("convert(");
3530 Type* type = imp->read_type();
3531 imp->require_c_string(", ");
3532 Expression* val = Expression::import_expression(imp);
3533 imp->require_c_string(")");
3534 return Expression::make_cast(type, val, imp->location());
3537 // Dump ast representation for a type conversion expression.
3539 void
3540 Type_conversion_expression::do_dump_expression(
3541 Ast_dump_context* ast_dump_context) const
3543 ast_dump_context->dump_type(this->type_);
3544 ast_dump_context->ostream() << "(";
3545 ast_dump_context->dump_expression(this->expr_);
3546 ast_dump_context->ostream() << ") ";
3549 // Make a type cast expression.
3551 Expression*
3552 Expression::make_cast(Type* type, Expression* val, Location location)
3554 if (type->is_error_type() || val->is_error_expression())
3555 return Expression::make_error(location);
3556 return new Type_conversion_expression(type, val, location);
3559 // Class Unsafe_type_conversion_expression.
3561 // Traversal.
3564 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3566 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3567 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3568 return TRAVERSE_EXIT;
3569 return TRAVERSE_CONTINUE;
3572 // Return whether an unsafe type conversion can be used as a constant
3573 // initializer.
3575 bool
3576 Unsafe_type_conversion_expression::do_is_static_initializer() const
3578 Type* type = this->type_;
3579 Type* expr_type = this->expr_->type();
3581 if (type->interface_type() != NULL
3582 || expr_type->interface_type() != NULL)
3583 return false;
3585 if (!this->expr_->is_static_initializer())
3586 return false;
3588 if (Type::are_convertible(type, expr_type, NULL))
3589 return true;
3591 if (type->is_string_type() && expr_type->is_string_type())
3592 return true;
3594 if ((type->is_numeric_type()
3595 || type->is_boolean_type()
3596 || type->points_to() != NULL)
3597 && (expr_type->is_numeric_type()
3598 || expr_type->is_boolean_type()
3599 || expr_type->points_to() != NULL))
3600 return true;
3602 return false;
3605 // Convert to backend representation.
3607 Bexpression*
3608 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3610 // We are only called for a limited number of cases.
3612 Type* t = this->type_;
3613 Type* et = this->expr_->type();
3615 if (t->is_error_type()
3616 || this->expr_->is_error_expression()
3617 || et->is_error_type())
3619 go_assert(saw_errors());
3620 return context->backend()->error_expression();
3623 if (t->array_type() != NULL)
3624 go_assert(et->array_type() != NULL
3625 && t->is_slice_type() == et->is_slice_type());
3626 else if (t->struct_type() != NULL)
3628 if (t->named_type() != NULL
3629 && et->named_type() != NULL
3630 && !Type::are_convertible(t, et, NULL))
3632 go_assert(saw_errors());
3633 return context->backend()->error_expression();
3636 go_assert(et->struct_type() != NULL
3637 && Type::are_convertible(t, et, NULL));
3639 else if (t->map_type() != NULL)
3640 go_assert(et->map_type() != NULL);
3641 else if (t->channel_type() != NULL)
3642 go_assert(et->channel_type() != NULL);
3643 else if (t->points_to() != NULL)
3644 go_assert(et->points_to() != NULL
3645 || et->channel_type() != NULL
3646 || et->map_type() != NULL
3647 || et->function_type() != NULL
3648 || et->integer_type() != NULL
3649 || et->is_nil_type());
3650 else if (et->is_unsafe_pointer_type())
3651 go_assert(t->points_to() != NULL);
3652 else if (t->interface_type() != NULL)
3654 bool empty_iface = t->interface_type()->is_empty();
3655 go_assert(et->interface_type() != NULL
3656 && et->interface_type()->is_empty() == empty_iface);
3658 else if (t->integer_type() != NULL)
3659 go_assert(et->is_boolean_type()
3660 || et->integer_type() != NULL
3661 || et->function_type() != NULL
3662 || et->points_to() != NULL
3663 || et->map_type() != NULL
3664 || et->channel_type() != NULL
3665 || et->is_nil_type());
3666 else if (t->function_type() != NULL)
3667 go_assert(et->points_to() != NULL);
3668 else
3669 go_unreachable();
3671 Gogo* gogo = context->gogo();
3672 Btype* btype = t->get_backend(gogo);
3673 Bexpression* bexpr = this->expr_->get_backend(context);
3674 Location loc = this->location();
3675 return gogo->backend()->convert_expression(btype, bexpr, loc);
3678 // Dump ast representation for an unsafe type conversion expression.
3680 void
3681 Unsafe_type_conversion_expression::do_dump_expression(
3682 Ast_dump_context* ast_dump_context) const
3684 ast_dump_context->dump_type(this->type_);
3685 ast_dump_context->ostream() << "(";
3686 ast_dump_context->dump_expression(this->expr_);
3687 ast_dump_context->ostream() << ") ";
3690 // Make an unsafe type conversion expression.
3692 Expression*
3693 Expression::make_unsafe_cast(Type* type, Expression* expr,
3694 Location location)
3696 return new Unsafe_type_conversion_expression(type, expr, location);
3699 // Class Unary_expression.
3701 // Call the address_taken method of the operand if needed. This is
3702 // called after escape analysis but before inserting write barriers.
3704 void
3705 Unary_expression::check_operand_address_taken(Gogo* gogo)
3707 if (this->op_ != OPERATOR_AND)
3708 return;
3710 // If this->escapes_ is false at this point, then it was set to
3711 // false by an explicit call to set_does_not_escape, and the value
3712 // does not escape. If this->escapes_ is true, we may be able to
3713 // set it to false if taking the address of a variable that does not
3714 // escape.
3715 Node* n = Node::make_node(this);
3716 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3717 this->escapes_ = false;
3719 // When compiling the runtime, the address operator does not cause
3720 // local variables to escape. When escape analysis becomes the
3721 // default, this should be changed to make it an error if we have an
3722 // address operator that escapes.
3723 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3724 this->escapes_ = false;
3726 Named_object* var = NULL;
3727 if (this->expr_->var_expression() != NULL)
3728 var = this->expr_->var_expression()->named_object();
3729 else if (this->expr_->enclosed_var_expression() != NULL)
3730 var = this->expr_->enclosed_var_expression()->variable();
3732 if (this->escapes_ && var != NULL)
3734 if (var->is_variable())
3735 this->escapes_ = var->var_value()->escapes();
3736 if (var->is_result_variable())
3737 this->escapes_ = var->result_var_value()->escapes();
3740 this->expr_->address_taken(this->escapes_);
3743 // If we are taking the address of a composite literal, and the
3744 // contents are not constant, then we want to make a heap expression
3745 // instead.
3747 Expression*
3748 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3750 Location loc = this->location();
3751 Operator op = this->op_;
3752 Expression* expr = this->expr_;
3754 if (op == OPERATOR_MULT && expr->is_type_expression())
3755 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3757 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3758 // moving x to the heap. FIXME: Is it worth doing a real escape
3759 // analysis here? This case is found in math/unsafe.go and is
3760 // therefore worth special casing.
3761 if (op == OPERATOR_MULT)
3763 Expression* e = expr;
3764 while (e->classification() == EXPRESSION_CONVERSION)
3766 Type_conversion_expression* te
3767 = static_cast<Type_conversion_expression*>(e);
3768 e = te->expr();
3771 if (e->classification() == EXPRESSION_UNARY)
3773 Unary_expression* ue = static_cast<Unary_expression*>(e);
3774 if (ue->op_ == OPERATOR_AND)
3776 if (e == expr)
3778 // *&x == x.
3779 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3781 go_error_at(ue->location(),
3782 "invalid operand for unary %<&%>");
3783 this->set_is_error();
3785 return ue->expr_;
3787 ue->set_does_not_escape();
3792 // Catching an invalid indirection of unsafe.Pointer here avoid
3793 // having to deal with TYPE_VOID in other places.
3794 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3796 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3797 return Expression::make_error(this->location());
3800 // Check for an invalid pointer dereference. We need to do this
3801 // here because Unary_expression::do_type will return an error type
3802 // in this case. That can cause code to appear erroneous, and
3803 // therefore disappear at lowering time, without any error message.
3804 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3806 this->report_error(_("expected pointer"));
3807 return Expression::make_error(this->location());
3810 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3812 Numeric_constant nc;
3813 if (expr->numeric_constant_value(&nc))
3815 Numeric_constant result;
3816 bool issued_error;
3817 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3818 &issued_error))
3819 return result.expression(loc);
3820 else if (issued_error)
3821 return Expression::make_error(this->location());
3825 return this;
3828 // Flatten expression if a nil check must be performed and create temporary
3829 // variables if necessary.
3831 Expression*
3832 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3833 Statement_inserter* inserter)
3835 if (this->is_error_expression()
3836 || this->expr_->is_error_expression()
3837 || this->expr_->type()->is_error_type())
3839 go_assert(saw_errors());
3840 return Expression::make_error(this->location());
3843 Location location = this->location();
3844 if (this->op_ == OPERATOR_MULT
3845 && !this->expr_->is_variable())
3847 go_assert(this->expr_->type()->points_to() != NULL);
3848 Type* ptype = this->expr_->type()->points_to();
3849 if (!ptype->is_void_type())
3851 int64_t s;
3852 bool ok = ptype->backend_type_size(gogo, &s);
3853 if (!ok)
3855 go_assert(saw_errors());
3856 return Expression::make_error(this->location());
3858 if (s >= 4096 || this->issue_nil_check_)
3860 Temporary_statement* temp =
3861 Statement::make_temporary(NULL, this->expr_, location);
3862 inserter->insert(temp);
3863 this->expr_ =
3864 Expression::make_temporary_reference(temp, location);
3869 if (this->create_temp_ && !this->expr_->is_variable())
3871 Temporary_statement* temp =
3872 Statement::make_temporary(NULL, this->expr_, location);
3873 inserter->insert(temp);
3874 this->expr_ = Expression::make_temporary_reference(temp, location);
3877 return this;
3880 // Return whether a unary expression is a constant.
3882 bool
3883 Unary_expression::do_is_constant() const
3885 if (this->op_ == OPERATOR_MULT)
3887 // Indirecting through a pointer is only constant if the object
3888 // to which the expression points is constant, but we currently
3889 // have no way to determine that.
3890 return false;
3892 else if (this->op_ == OPERATOR_AND)
3894 // Taking the address of a variable is constant if it is a
3895 // global variable, not constant otherwise. In other cases taking the
3896 // address is probably not a constant.
3897 Var_expression* ve = this->expr_->var_expression();
3898 if (ve != NULL)
3900 Named_object* no = ve->named_object();
3901 return no->is_variable() && no->var_value()->is_global();
3903 return false;
3905 else
3906 return this->expr_->is_constant();
3909 // Return whether a unary expression can be used as a constant
3910 // initializer.
3912 bool
3913 Unary_expression::do_is_static_initializer() const
3915 if (this->op_ == OPERATOR_MULT)
3916 return false;
3917 else if (this->op_ == OPERATOR_AND)
3918 return Unary_expression::base_is_static_initializer(this->expr_);
3919 else
3920 return this->expr_->is_static_initializer();
3923 // Return whether the address of EXPR can be used as a static
3924 // initializer.
3926 bool
3927 Unary_expression::base_is_static_initializer(Expression* expr)
3929 // The address of a field reference can be a static initializer if
3930 // the base can be a static initializer.
3931 Field_reference_expression* fre = expr->field_reference_expression();
3932 if (fre != NULL)
3933 return Unary_expression::base_is_static_initializer(fre->expr());
3935 // The address of an index expression can be a static initializer if
3936 // the base can be a static initializer and the index is constant.
3937 Array_index_expression* aind = expr->array_index_expression();
3938 if (aind != NULL)
3939 return (aind->end() == NULL
3940 && aind->start()->is_constant()
3941 && Unary_expression::base_is_static_initializer(aind->array()));
3943 // The address of a global variable can be a static initializer.
3944 Var_expression* ve = expr->var_expression();
3945 if (ve != NULL)
3947 Named_object* no = ve->named_object();
3948 return no->is_variable() && no->var_value()->is_global();
3951 // The address of a composite literal can be used as a static
3952 // initializer if the composite literal is itself usable as a
3953 // static initializer.
3954 if (expr->is_composite_literal() && expr->is_static_initializer())
3955 return true;
3957 // The address of a string constant can be used as a static
3958 // initializer. This can not be written in Go itself but this is
3959 // used when building a type descriptor.
3960 if (expr->string_expression() != NULL)
3961 return true;
3963 return false;
3966 // Apply unary opcode OP to UNC, setting NC. Return true if this
3967 // could be done, false if not. On overflow, issues an error and sets
3968 // *ISSUED_ERROR.
3970 bool
3971 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3972 Location location, Numeric_constant* nc,
3973 bool* issued_error)
3975 *issued_error = false;
3976 switch (op)
3978 case OPERATOR_PLUS:
3979 *nc = *unc;
3980 return true;
3982 case OPERATOR_MINUS:
3983 if (unc->is_int() || unc->is_rune())
3984 break;
3985 else if (unc->is_float())
3987 mpfr_t uval;
3988 unc->get_float(&uval);
3989 mpfr_t val;
3990 mpfr_init(val);
3991 mpfr_neg(val, uval, GMP_RNDN);
3992 nc->set_float(unc->type(), val);
3993 mpfr_clear(uval);
3994 mpfr_clear(val);
3995 return true;
3997 else if (unc->is_complex())
3999 mpc_t uval;
4000 unc->get_complex(&uval);
4001 mpc_t val;
4002 mpc_init2(val, mpc_precision);
4003 mpc_neg(val, uval, MPC_RNDNN);
4004 nc->set_complex(unc->type(), val);
4005 mpc_clear(uval);
4006 mpc_clear(val);
4007 return true;
4009 else
4010 go_unreachable();
4012 case OPERATOR_XOR:
4013 break;
4015 case OPERATOR_NOT:
4016 case OPERATOR_AND:
4017 case OPERATOR_MULT:
4018 return false;
4020 default:
4021 go_unreachable();
4024 if (!unc->is_int() && !unc->is_rune())
4025 return false;
4027 mpz_t uval;
4028 if (unc->is_rune())
4029 unc->get_rune(&uval);
4030 else
4031 unc->get_int(&uval);
4032 mpz_t val;
4033 mpz_init(val);
4035 switch (op)
4037 case OPERATOR_MINUS:
4038 mpz_neg(val, uval);
4039 break;
4041 case OPERATOR_NOT:
4042 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4043 break;
4045 case OPERATOR_XOR:
4047 Type* utype = unc->type();
4048 if (utype->integer_type() == NULL
4049 || utype->integer_type()->is_abstract())
4050 mpz_com(val, uval);
4051 else
4053 // The number of HOST_WIDE_INTs that it takes to represent
4054 // UVAL.
4055 size_t count = ((mpz_sizeinbase(uval, 2)
4056 + HOST_BITS_PER_WIDE_INT
4057 - 1)
4058 / HOST_BITS_PER_WIDE_INT);
4060 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4061 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4063 size_t obits = utype->integer_type()->bits();
4065 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4067 mpz_t adj;
4068 mpz_init_set_ui(adj, 1);
4069 mpz_mul_2exp(adj, adj, obits);
4070 mpz_add(uval, uval, adj);
4071 mpz_clear(adj);
4074 size_t ecount;
4075 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4076 go_assert(ecount <= count);
4078 // Trim down to the number of words required by the type.
4079 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4080 / HOST_BITS_PER_WIDE_INT);
4081 go_assert(ocount <= count);
4083 for (size_t i = 0; i < ocount; ++i)
4084 phwi[i] = ~phwi[i];
4086 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4087 if (clearbits != 0)
4088 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4089 >> clearbits);
4091 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4093 if (!utype->integer_type()->is_unsigned()
4094 && mpz_tstbit(val, obits - 1))
4096 mpz_t adj;
4097 mpz_init_set_ui(adj, 1);
4098 mpz_mul_2exp(adj, adj, obits);
4099 mpz_sub(val, val, adj);
4100 mpz_clear(adj);
4103 delete[] phwi;
4106 break;
4108 default:
4109 go_unreachable();
4112 if (unc->is_rune())
4113 nc->set_rune(NULL, val);
4114 else
4115 nc->set_int(NULL, val);
4117 mpz_clear(uval);
4118 mpz_clear(val);
4120 if (!nc->set_type(unc->type(), true, location))
4122 *issued_error = true;
4123 return false;
4125 return true;
4128 // Return the integral constant value of a unary expression, if it has one.
4130 bool
4131 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4133 Numeric_constant unc;
4134 if (!this->expr_->numeric_constant_value(&unc))
4135 return false;
4136 bool issued_error;
4137 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4138 nc, &issued_error);
4141 // Return the type of a unary expression.
4143 Type*
4144 Unary_expression::do_type()
4146 switch (this->op_)
4148 case OPERATOR_PLUS:
4149 case OPERATOR_MINUS:
4150 case OPERATOR_NOT:
4151 case OPERATOR_XOR:
4152 return this->expr_->type();
4154 case OPERATOR_AND:
4155 return Type::make_pointer_type(this->expr_->type());
4157 case OPERATOR_MULT:
4159 Type* subtype = this->expr_->type();
4160 Type* points_to = subtype->points_to();
4161 if (points_to == NULL)
4162 return Type::make_error_type();
4163 return points_to;
4166 default:
4167 go_unreachable();
4171 // Determine abstract types for a unary expression.
4173 void
4174 Unary_expression::do_determine_type(const Type_context* context)
4176 switch (this->op_)
4178 case OPERATOR_PLUS:
4179 case OPERATOR_MINUS:
4180 case OPERATOR_NOT:
4181 case OPERATOR_XOR:
4182 this->expr_->determine_type(context);
4183 break;
4185 case OPERATOR_AND:
4186 // Taking the address of something.
4188 Type* subtype = (context->type == NULL
4189 ? NULL
4190 : context->type->points_to());
4191 Type_context subcontext(subtype, false);
4192 this->expr_->determine_type(&subcontext);
4194 break;
4196 case OPERATOR_MULT:
4197 // Indirecting through a pointer.
4199 Type* subtype = (context->type == NULL
4200 ? NULL
4201 : Type::make_pointer_type(context->type));
4202 Type_context subcontext(subtype, false);
4203 this->expr_->determine_type(&subcontext);
4205 break;
4207 default:
4208 go_unreachable();
4212 // Check types for a unary expression.
4214 void
4215 Unary_expression::do_check_types(Gogo*)
4217 Type* type = this->expr_->type();
4218 if (type->is_error())
4220 this->set_is_error();
4221 return;
4224 switch (this->op_)
4226 case OPERATOR_PLUS:
4227 case OPERATOR_MINUS:
4228 if (type->integer_type() == NULL
4229 && type->float_type() == NULL
4230 && type->complex_type() == NULL)
4231 this->report_error(_("expected numeric type"));
4232 break;
4234 case OPERATOR_NOT:
4235 if (!type->is_boolean_type())
4236 this->report_error(_("expected boolean type"));
4237 break;
4239 case OPERATOR_XOR:
4240 if (type->integer_type() == NULL)
4241 this->report_error(_("expected integer"));
4242 break;
4244 case OPERATOR_AND:
4245 if (!this->expr_->is_addressable())
4247 if (!this->create_temp_)
4249 go_error_at(this->location(), "invalid operand for unary %<&%>");
4250 this->set_is_error();
4253 else
4254 this->expr_->issue_nil_check();
4255 break;
4257 case OPERATOR_MULT:
4258 // Indirecting through a pointer.
4259 if (type->points_to() == NULL)
4260 this->report_error(_("expected pointer"));
4261 if (type->points_to()->is_error())
4262 this->set_is_error();
4263 break;
4265 default:
4266 go_unreachable();
4270 // Get the backend representation for a unary expression.
4272 Bexpression*
4273 Unary_expression::do_get_backend(Translate_context* context)
4275 Gogo* gogo = context->gogo();
4276 Location loc = this->location();
4278 // Taking the address of a set-and-use-temporary expression requires
4279 // setting the temporary and then taking the address.
4280 if (this->op_ == OPERATOR_AND)
4282 Set_and_use_temporary_expression* sut =
4283 this->expr_->set_and_use_temporary_expression();
4284 if (sut != NULL)
4286 Temporary_statement* temp = sut->temporary();
4287 Bvariable* bvar = temp->get_backend_variable(context);
4288 Bexpression* bvar_expr =
4289 gogo->backend()->var_expression(bvar, VE_lvalue, loc);
4290 Bexpression* bval = sut->expression()->get_backend(context);
4292 Named_object* fn = context->function();
4293 go_assert(fn != NULL);
4294 Bfunction* bfn =
4295 fn->func_value()->get_or_make_decl(gogo, fn);
4296 Bstatement* bassign =
4297 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4298 Bexpression* bvar_addr =
4299 gogo->backend()->address_expression(bvar_expr, loc);
4300 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4304 Bexpression* ret;
4305 Bexpression* bexpr = this->expr_->get_backend(context);
4306 Btype* btype = this->expr_->type()->get_backend(gogo);
4307 switch (this->op_)
4309 case OPERATOR_PLUS:
4310 ret = bexpr;
4311 break;
4313 case OPERATOR_MINUS:
4314 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4315 ret = gogo->backend()->convert_expression(btype, ret, loc);
4316 break;
4318 case OPERATOR_NOT:
4319 case OPERATOR_XOR:
4320 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4321 break;
4323 case OPERATOR_AND:
4324 if (!this->create_temp_)
4326 // We should not see a non-constant constructor here; cases
4327 // where we would see one should have been moved onto the
4328 // heap at parse time. Taking the address of a nonconstant
4329 // constructor will not do what the programmer expects.
4331 go_assert(!this->expr_->is_composite_literal()
4332 || this->expr_->is_static_initializer());
4333 if (this->expr_->classification() == EXPRESSION_UNARY)
4335 Unary_expression* ue =
4336 static_cast<Unary_expression*>(this->expr_);
4337 go_assert(ue->op() != OPERATOR_AND);
4341 if (this->is_gc_root_ || this->is_slice_init_)
4343 std::string var_name;
4344 bool copy_to_heap = false;
4345 if (this->is_gc_root_)
4347 // Build a decl for a GC root variable. GC roots are mutable, so
4348 // they cannot be represented as an immutable_struct in the
4349 // backend.
4350 var_name = gogo->gc_root_name();
4352 else
4354 // Build a decl for a slice value initializer. An immutable slice
4355 // value initializer may have to be copied to the heap if it
4356 // contains pointers in a non-constant context.
4357 var_name = gogo->initializer_name();
4359 Array_type* at = this->expr_->type()->array_type();
4360 go_assert(at != NULL);
4362 // If we are not copying the value to the heap, we will only
4363 // initialize the value once, so we can use this directly
4364 // rather than copying it. In that case we can't make it
4365 // read-only, because the program is permitted to change it.
4366 copy_to_heap = context->function() != NULL;
4368 std::string asm_name(go_selectively_encode_id(var_name));
4369 Bvariable* implicit =
4370 gogo->backend()->implicit_variable(var_name, asm_name,
4371 btype, true, copy_to_heap,
4372 false, 0);
4373 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4374 true, copy_to_heap, false,
4375 bexpr);
4376 bexpr = gogo->backend()->var_expression(implicit, VE_rvalue, loc);
4378 // If we are not copying a slice initializer to the heap,
4379 // then it can be changed by the program, so if it can
4380 // contain pointers we must register it as a GC root.
4381 if (this->is_slice_init_
4382 && !copy_to_heap
4383 && this->expr_->type()->has_pointer())
4385 Bexpression* root =
4386 gogo->backend()->var_expression(implicit, VE_rvalue, loc);
4387 root = gogo->backend()->address_expression(root, loc);
4388 Type* type = Type::make_pointer_type(this->expr_->type());
4389 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4392 else if ((this->expr_->is_composite_literal()
4393 || this->expr_->string_expression() != NULL)
4394 && this->expr_->is_static_initializer())
4396 std::string var_name(gogo->initializer_name());
4397 std::string asm_name(go_selectively_encode_id(var_name));
4398 Bvariable* decl =
4399 gogo->backend()->immutable_struct(var_name, asm_name,
4400 true, false, btype, loc);
4401 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4402 false, btype, loc, bexpr);
4403 bexpr = gogo->backend()->var_expression(decl, VE_rvalue, loc);
4406 go_assert(!this->create_temp_ || this->expr_->is_variable());
4407 ret = gogo->backend()->address_expression(bexpr, loc);
4408 break;
4410 case OPERATOR_MULT:
4412 go_assert(this->expr_->type()->points_to() != NULL);
4414 // If we are dereferencing the pointer to a large struct, we
4415 // need to check for nil. We don't bother to check for small
4416 // structs because we expect the system to crash on a nil
4417 // pointer dereference. However, if we know the address of this
4418 // expression is being taken, we must always check for nil.
4420 Type* ptype = this->expr_->type()->points_to();
4421 Btype* pbtype = ptype->get_backend(gogo);
4422 if (!ptype->is_void_type())
4424 int64_t s;
4425 bool ok = ptype->backend_type_size(gogo, &s);
4426 if (!ok)
4428 go_assert(saw_errors());
4429 return gogo->backend()->error_expression();
4431 if (s >= 4096 || this->issue_nil_check_)
4433 go_assert(this->expr_->is_variable());
4434 Bexpression* nil =
4435 Expression::make_nil(loc)->get_backend(context);
4436 Bexpression* compare =
4437 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4438 nil, loc);
4439 Bexpression* crash =
4440 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4441 loc)->get_backend(context);
4442 Bfunction* bfn = context->function()->func_value()->get_decl();
4443 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4444 compare,
4445 crash, bexpr,
4446 loc);
4450 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4452 break;
4454 default:
4455 go_unreachable();
4458 return ret;
4461 // Export a unary expression.
4463 void
4464 Unary_expression::do_export(Export* exp) const
4466 switch (this->op_)
4468 case OPERATOR_PLUS:
4469 exp->write_c_string("+ ");
4470 break;
4471 case OPERATOR_MINUS:
4472 exp->write_c_string("- ");
4473 break;
4474 case OPERATOR_NOT:
4475 exp->write_c_string("! ");
4476 break;
4477 case OPERATOR_XOR:
4478 exp->write_c_string("^ ");
4479 break;
4480 case OPERATOR_AND:
4481 case OPERATOR_MULT:
4482 default:
4483 go_unreachable();
4485 this->expr_->export_expression(exp);
4488 // Import a unary expression.
4490 Expression*
4491 Unary_expression::do_import(Import* imp)
4493 Operator op;
4494 switch (imp->get_char())
4496 case '+':
4497 op = OPERATOR_PLUS;
4498 break;
4499 case '-':
4500 op = OPERATOR_MINUS;
4501 break;
4502 case '!':
4503 op = OPERATOR_NOT;
4504 break;
4505 case '^':
4506 op = OPERATOR_XOR;
4507 break;
4508 default:
4509 go_unreachable();
4511 imp->require_c_string(" ");
4512 Expression* expr = Expression::import_expression(imp);
4513 return Expression::make_unary(op, expr, imp->location());
4516 // Dump ast representation of an unary expression.
4518 void
4519 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4521 ast_dump_context->dump_operator(this->op_);
4522 ast_dump_context->ostream() << "(";
4523 ast_dump_context->dump_expression(this->expr_);
4524 ast_dump_context->ostream() << ") ";
4527 // Make a unary expression.
4529 Expression*
4530 Expression::make_unary(Operator op, Expression* expr, Location location)
4532 return new Unary_expression(op, expr, location);
4535 // If this is an indirection through a pointer, return the expression
4536 // being pointed through. Otherwise return this.
4538 Expression*
4539 Expression::deref()
4541 if (this->classification_ == EXPRESSION_UNARY)
4543 Unary_expression* ue = static_cast<Unary_expression*>(this);
4544 if (ue->op() == OPERATOR_MULT)
4545 return ue->operand();
4547 return this;
4550 // Class Binary_expression.
4552 // Traversal.
4555 Binary_expression::do_traverse(Traverse* traverse)
4557 int t = Expression::traverse(&this->left_, traverse);
4558 if (t == TRAVERSE_EXIT)
4559 return TRAVERSE_EXIT;
4560 return Expression::traverse(&this->right_, traverse);
4563 // Return whether this expression may be used as a static initializer.
4565 bool
4566 Binary_expression::do_is_static_initializer() const
4568 if (!this->left_->is_static_initializer()
4569 || !this->right_->is_static_initializer())
4570 return false;
4572 // Addresses can be static initializers, but we can't implement
4573 // arbitray binary expressions of them.
4574 Unary_expression* lu = this->left_->unary_expression();
4575 Unary_expression* ru = this->right_->unary_expression();
4576 if (lu != NULL && lu->op() == OPERATOR_AND)
4578 if (ru != NULL && ru->op() == OPERATOR_AND)
4579 return this->op_ == OPERATOR_MINUS;
4580 else
4581 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4583 else if (ru != NULL && ru->op() == OPERATOR_AND)
4584 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4586 // Other cases should resolve in the backend.
4587 return true;
4590 // Return the type to use for a binary operation on operands of
4591 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4592 // such may be NULL or abstract.
4594 bool
4595 Binary_expression::operation_type(Operator op, Type* left_type,
4596 Type* right_type, Type** result_type)
4598 if (left_type != right_type
4599 && !left_type->is_abstract()
4600 && !right_type->is_abstract()
4601 && left_type->base() != right_type->base()
4602 && op != OPERATOR_LSHIFT
4603 && op != OPERATOR_RSHIFT)
4605 // May be a type error--let it be diagnosed elsewhere.
4606 return false;
4609 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4611 if (left_type->integer_type() != NULL)
4612 *result_type = left_type;
4613 else
4614 *result_type = Type::make_abstract_integer_type();
4616 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4617 *result_type = left_type;
4618 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4619 *result_type = right_type;
4620 else if (!left_type->is_abstract())
4621 *result_type = left_type;
4622 else if (!right_type->is_abstract())
4623 *result_type = right_type;
4624 else if (left_type->complex_type() != NULL)
4625 *result_type = left_type;
4626 else if (right_type->complex_type() != NULL)
4627 *result_type = right_type;
4628 else if (left_type->float_type() != NULL)
4629 *result_type = left_type;
4630 else if (right_type->float_type() != NULL)
4631 *result_type = right_type;
4632 else if (left_type->integer_type() != NULL
4633 && left_type->integer_type()->is_rune())
4634 *result_type = left_type;
4635 else if (right_type->integer_type() != NULL
4636 && right_type->integer_type()->is_rune())
4637 *result_type = right_type;
4638 else
4639 *result_type = left_type;
4641 return true;
4644 // Convert an integer comparison code and an operator to a boolean
4645 // value.
4647 bool
4648 Binary_expression::cmp_to_bool(Operator op, int cmp)
4650 switch (op)
4652 case OPERATOR_EQEQ:
4653 return cmp == 0;
4654 break;
4655 case OPERATOR_NOTEQ:
4656 return cmp != 0;
4657 break;
4658 case OPERATOR_LT:
4659 return cmp < 0;
4660 break;
4661 case OPERATOR_LE:
4662 return cmp <= 0;
4663 case OPERATOR_GT:
4664 return cmp > 0;
4665 case OPERATOR_GE:
4666 return cmp >= 0;
4667 default:
4668 go_unreachable();
4672 // Compare constants according to OP.
4674 bool
4675 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4676 Numeric_constant* right_nc,
4677 Location location, bool* result)
4679 Type* left_type = left_nc->type();
4680 Type* right_type = right_nc->type();
4682 Type* type;
4683 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4684 return false;
4686 // When comparing an untyped operand to a typed operand, we are
4687 // effectively coercing the untyped operand to the other operand's
4688 // type, so make sure that is valid.
4689 if (!left_nc->set_type(type, true, location)
4690 || !right_nc->set_type(type, true, location))
4691 return false;
4693 bool ret;
4694 int cmp;
4695 if (type->complex_type() != NULL)
4697 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4698 return false;
4699 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4701 else if (type->float_type() != NULL)
4702 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4703 else
4704 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4706 if (ret)
4707 *result = Binary_expression::cmp_to_bool(op, cmp);
4709 return ret;
4712 // Compare integer constants.
4714 bool
4715 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4716 const Numeric_constant* right_nc,
4717 int* cmp)
4719 mpz_t left_val;
4720 if (!left_nc->to_int(&left_val))
4721 return false;
4722 mpz_t right_val;
4723 if (!right_nc->to_int(&right_val))
4725 mpz_clear(left_val);
4726 return false;
4729 *cmp = mpz_cmp(left_val, right_val);
4731 mpz_clear(left_val);
4732 mpz_clear(right_val);
4734 return true;
4737 // Compare floating point constants.
4739 bool
4740 Binary_expression::compare_float(const Numeric_constant* left_nc,
4741 const Numeric_constant* right_nc,
4742 int* cmp)
4744 mpfr_t left_val;
4745 if (!left_nc->to_float(&left_val))
4746 return false;
4747 mpfr_t right_val;
4748 if (!right_nc->to_float(&right_val))
4750 mpfr_clear(left_val);
4751 return false;
4754 // We already coerced both operands to the same type. If that type
4755 // is not an abstract type, we need to round the values accordingly.
4756 Type* type = left_nc->type();
4757 if (!type->is_abstract() && type->float_type() != NULL)
4759 int bits = type->float_type()->bits();
4760 mpfr_prec_round(left_val, bits, GMP_RNDN);
4761 mpfr_prec_round(right_val, bits, GMP_RNDN);
4764 *cmp = mpfr_cmp(left_val, right_val);
4766 mpfr_clear(left_val);
4767 mpfr_clear(right_val);
4769 return true;
4772 // Compare complex constants. Complex numbers may only be compared
4773 // for equality.
4775 bool
4776 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4777 const Numeric_constant* right_nc,
4778 int* cmp)
4780 mpc_t left_val;
4781 if (!left_nc->to_complex(&left_val))
4782 return false;
4783 mpc_t right_val;
4784 if (!right_nc->to_complex(&right_val))
4786 mpc_clear(left_val);
4787 return false;
4790 // We already coerced both operands to the same type. If that type
4791 // is not an abstract type, we need to round the values accordingly.
4792 Type* type = left_nc->type();
4793 if (!type->is_abstract() && type->complex_type() != NULL)
4795 int bits = type->complex_type()->bits();
4796 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4797 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4798 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4799 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4802 *cmp = mpc_cmp(left_val, right_val) != 0;
4804 mpc_clear(left_val);
4805 mpc_clear(right_val);
4807 return true;
4810 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4811 // true if this could be done, false if not. Issue errors at LOCATION
4812 // as appropriate, and sets *ISSUED_ERROR if it did.
4814 bool
4815 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4816 Numeric_constant* right_nc,
4817 Location location, Numeric_constant* nc,
4818 bool* issued_error)
4820 *issued_error = false;
4821 switch (op)
4823 case OPERATOR_OROR:
4824 case OPERATOR_ANDAND:
4825 case OPERATOR_EQEQ:
4826 case OPERATOR_NOTEQ:
4827 case OPERATOR_LT:
4828 case OPERATOR_LE:
4829 case OPERATOR_GT:
4830 case OPERATOR_GE:
4831 // These return boolean values, not numeric.
4832 return false;
4833 default:
4834 break;
4837 Type* left_type = left_nc->type();
4838 Type* right_type = right_nc->type();
4840 Type* type;
4841 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4842 return false;
4844 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4846 // When combining an untyped operand with a typed operand, we are
4847 // effectively coercing the untyped operand to the other operand's
4848 // type, so make sure that is valid.
4849 if (!left_nc->set_type(type, true, location))
4850 return false;
4851 if (!is_shift && !right_nc->set_type(type, true, location))
4852 return false;
4853 if (is_shift
4854 && ((left_type->integer_type() == NULL
4855 && !left_type->is_abstract())
4856 || (right_type->integer_type() == NULL
4857 && !right_type->is_abstract())))
4858 return false;
4860 bool r;
4861 if (type->complex_type() != NULL)
4862 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4863 else if (type->float_type() != NULL)
4864 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4865 else
4866 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4868 if (r)
4870 r = nc->set_type(type, true, location);
4871 if (!r)
4872 *issued_error = true;
4875 return r;
4878 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4879 // integer operations. Return true if this could be done, false if
4880 // not.
4882 bool
4883 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4884 const Numeric_constant* right_nc,
4885 Location location, Numeric_constant* nc)
4887 mpz_t left_val;
4888 if (!left_nc->to_int(&left_val))
4889 return false;
4890 mpz_t right_val;
4891 if (!right_nc->to_int(&right_val))
4893 mpz_clear(left_val);
4894 return false;
4897 mpz_t val;
4898 mpz_init(val);
4900 switch (op)
4902 case OPERATOR_PLUS:
4903 mpz_add(val, left_val, right_val);
4904 if (mpz_sizeinbase(val, 2) > 0x100000)
4906 go_error_at(location, "constant addition overflow");
4907 nc->set_invalid();
4908 mpz_set_ui(val, 1);
4910 break;
4911 case OPERATOR_MINUS:
4912 mpz_sub(val, left_val, right_val);
4913 if (mpz_sizeinbase(val, 2) > 0x100000)
4915 go_error_at(location, "constant subtraction overflow");
4916 nc->set_invalid();
4917 mpz_set_ui(val, 1);
4919 break;
4920 case OPERATOR_OR:
4921 mpz_ior(val, left_val, right_val);
4922 break;
4923 case OPERATOR_XOR:
4924 mpz_xor(val, left_val, right_val);
4925 break;
4926 case OPERATOR_MULT:
4927 mpz_mul(val, left_val, right_val);
4928 if (mpz_sizeinbase(val, 2) > 0x100000)
4930 go_error_at(location, "constant multiplication overflow");
4931 nc->set_invalid();
4932 mpz_set_ui(val, 1);
4934 break;
4935 case OPERATOR_DIV:
4936 if (mpz_sgn(right_val) != 0)
4937 mpz_tdiv_q(val, left_val, right_val);
4938 else
4940 go_error_at(location, "division by zero");
4941 nc->set_invalid();
4942 mpz_set_ui(val, 0);
4944 break;
4945 case OPERATOR_MOD:
4946 if (mpz_sgn(right_val) != 0)
4947 mpz_tdiv_r(val, left_val, right_val);
4948 else
4950 go_error_at(location, "division by zero");
4951 nc->set_invalid();
4952 mpz_set_ui(val, 0);
4954 break;
4955 case OPERATOR_LSHIFT:
4957 unsigned long shift = mpz_get_ui(right_val);
4958 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4959 mpz_mul_2exp(val, left_val, shift);
4960 else
4962 go_error_at(location, "shift count overflow");
4963 nc->set_invalid();
4964 mpz_set_ui(val, 1);
4966 break;
4968 break;
4969 case OPERATOR_RSHIFT:
4971 unsigned long shift = mpz_get_ui(right_val);
4972 if (mpz_cmp_ui(right_val, shift) != 0)
4974 go_error_at(location, "shift count overflow");
4975 nc->set_invalid();
4976 mpz_set_ui(val, 1);
4978 else
4980 if (mpz_cmp_ui(left_val, 0) >= 0)
4981 mpz_tdiv_q_2exp(val, left_val, shift);
4982 else
4983 mpz_fdiv_q_2exp(val, left_val, shift);
4985 break;
4987 break;
4988 case OPERATOR_AND:
4989 mpz_and(val, left_val, right_val);
4990 break;
4991 case OPERATOR_BITCLEAR:
4993 mpz_t tval;
4994 mpz_init(tval);
4995 mpz_com(tval, right_val);
4996 mpz_and(val, left_val, tval);
4997 mpz_clear(tval);
4999 break;
5000 default:
5001 go_unreachable();
5004 mpz_clear(left_val);
5005 mpz_clear(right_val);
5007 if (left_nc->is_rune()
5008 || (op != OPERATOR_LSHIFT
5009 && op != OPERATOR_RSHIFT
5010 && right_nc->is_rune()))
5011 nc->set_rune(NULL, val);
5012 else
5013 nc->set_int(NULL, val);
5015 mpz_clear(val);
5017 return true;
5020 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5021 // floating point operations. Return true if this could be done,
5022 // false if not.
5024 bool
5025 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5026 const Numeric_constant* right_nc,
5027 Location location, Numeric_constant* nc)
5029 mpfr_t left_val;
5030 if (!left_nc->to_float(&left_val))
5031 return false;
5032 mpfr_t right_val;
5033 if (!right_nc->to_float(&right_val))
5035 mpfr_clear(left_val);
5036 return false;
5039 mpfr_t val;
5040 mpfr_init(val);
5042 bool ret = true;
5043 switch (op)
5045 case OPERATOR_PLUS:
5046 mpfr_add(val, left_val, right_val, GMP_RNDN);
5047 break;
5048 case OPERATOR_MINUS:
5049 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5050 break;
5051 case OPERATOR_OR:
5052 case OPERATOR_XOR:
5053 case OPERATOR_AND:
5054 case OPERATOR_BITCLEAR:
5055 case OPERATOR_MOD:
5056 case OPERATOR_LSHIFT:
5057 case OPERATOR_RSHIFT:
5058 mpfr_set_ui(val, 0, GMP_RNDN);
5059 ret = false;
5060 break;
5061 case OPERATOR_MULT:
5062 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5063 break;
5064 case OPERATOR_DIV:
5065 if (!mpfr_zero_p(right_val))
5066 mpfr_div(val, left_val, right_val, GMP_RNDN);
5067 else
5069 go_error_at(location, "division by zero");
5070 nc->set_invalid();
5071 mpfr_set_ui(val, 0, GMP_RNDN);
5073 break;
5074 default:
5075 go_unreachable();
5078 mpfr_clear(left_val);
5079 mpfr_clear(right_val);
5081 nc->set_float(NULL, val);
5082 mpfr_clear(val);
5084 return ret;
5087 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5088 // complex operations. Return true if this could be done, false if
5089 // not.
5091 bool
5092 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5093 const Numeric_constant* right_nc,
5094 Location location, Numeric_constant* nc)
5096 mpc_t left_val;
5097 if (!left_nc->to_complex(&left_val))
5098 return false;
5099 mpc_t right_val;
5100 if (!right_nc->to_complex(&right_val))
5102 mpc_clear(left_val);
5103 return false;
5106 mpc_t val;
5107 mpc_init2(val, mpc_precision);
5109 bool ret = true;
5110 switch (op)
5112 case OPERATOR_PLUS:
5113 mpc_add(val, left_val, right_val, MPC_RNDNN);
5114 break;
5115 case OPERATOR_MINUS:
5116 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5117 break;
5118 case OPERATOR_OR:
5119 case OPERATOR_XOR:
5120 case OPERATOR_AND:
5121 case OPERATOR_BITCLEAR:
5122 case OPERATOR_MOD:
5123 case OPERATOR_LSHIFT:
5124 case OPERATOR_RSHIFT:
5125 mpc_set_ui(val, 0, MPC_RNDNN);
5126 ret = false;
5127 break;
5128 case OPERATOR_MULT:
5129 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5130 break;
5131 case OPERATOR_DIV:
5132 if (mpc_cmp_si(right_val, 0) == 0)
5134 go_error_at(location, "division by zero");
5135 nc->set_invalid();
5136 mpc_set_ui(val, 0, MPC_RNDNN);
5137 break;
5139 mpc_div(val, left_val, right_val, MPC_RNDNN);
5140 break;
5141 default:
5142 go_unreachable();
5145 mpc_clear(left_val);
5146 mpc_clear(right_val);
5148 nc->set_complex(NULL, val);
5149 mpc_clear(val);
5151 return ret;
5154 // Lower a binary expression. We have to evaluate constant
5155 // expressions now, in order to implement Go's unlimited precision
5156 // constants.
5158 Expression*
5159 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5160 Statement_inserter* inserter, int)
5162 Location location = this->location();
5163 Operator op = this->op_;
5164 Expression* left = this->left_;
5165 Expression* right = this->right_;
5167 const bool is_comparison = (op == OPERATOR_EQEQ
5168 || op == OPERATOR_NOTEQ
5169 || op == OPERATOR_LT
5170 || op == OPERATOR_LE
5171 || op == OPERATOR_GT
5172 || op == OPERATOR_GE);
5174 // Numeric constant expressions.
5176 Numeric_constant left_nc;
5177 Numeric_constant right_nc;
5178 if (left->numeric_constant_value(&left_nc)
5179 && right->numeric_constant_value(&right_nc))
5181 if (is_comparison)
5183 bool result;
5184 if (!Binary_expression::compare_constant(op, &left_nc,
5185 &right_nc, location,
5186 &result))
5187 return this;
5188 return Expression::make_cast(Type::make_boolean_type(),
5189 Expression::make_boolean(result,
5190 location),
5191 location);
5193 else
5195 Numeric_constant nc;
5196 bool issued_error;
5197 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5198 location, &nc,
5199 &issued_error))
5201 if (issued_error)
5202 return Expression::make_error(location);
5203 return this;
5205 return nc.expression(location);
5210 // String constant expressions.
5211 if (left->type()->is_string_type() && right->type()->is_string_type())
5213 std::string left_string;
5214 std::string right_string;
5215 if (left->string_constant_value(&left_string)
5216 && right->string_constant_value(&right_string))
5218 if (op == OPERATOR_PLUS)
5219 return Expression::make_string(left_string + right_string,
5220 location);
5221 else if (is_comparison)
5223 int cmp = left_string.compare(right_string);
5224 bool r = Binary_expression::cmp_to_bool(op, cmp);
5225 return Expression::make_boolean(r, location);
5230 // Lower struct, array, and some interface comparisons.
5231 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5233 if (left->type()->struct_type() != NULL
5234 && right->type()->struct_type() != NULL)
5235 return this->lower_struct_comparison(gogo, inserter);
5236 else if (left->type()->array_type() != NULL
5237 && !left->type()->is_slice_type()
5238 && right->type()->array_type() != NULL
5239 && !right->type()->is_slice_type())
5240 return this->lower_array_comparison(gogo, inserter);
5241 else if ((left->type()->interface_type() != NULL
5242 && right->type()->interface_type() == NULL)
5243 || (left->type()->interface_type() == NULL
5244 && right->type()->interface_type() != NULL))
5245 return this->lower_interface_value_comparison(gogo, inserter);
5248 // Lower string concatenation to String_concat_expression, so that
5249 // we can group sequences of string additions.
5250 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5252 Expression_list* exprs;
5253 String_concat_expression* left_sce =
5254 this->left_->string_concat_expression();
5255 if (left_sce != NULL)
5256 exprs = left_sce->exprs();
5257 else
5259 exprs = new Expression_list();
5260 exprs->push_back(this->left_);
5263 String_concat_expression* right_sce =
5264 this->right_->string_concat_expression();
5265 if (right_sce != NULL)
5266 exprs->append(right_sce->exprs());
5267 else
5268 exprs->push_back(this->right_);
5270 return Expression::make_string_concat(exprs);
5273 return this;
5276 // Lower a struct comparison.
5278 Expression*
5279 Binary_expression::lower_struct_comparison(Gogo* gogo,
5280 Statement_inserter* inserter)
5282 Struct_type* st = this->left_->type()->struct_type();
5283 Struct_type* st2 = this->right_->type()->struct_type();
5284 if (st2 == NULL)
5285 return this;
5286 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5287 return this;
5288 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5289 this->right_->type(), NULL))
5290 return this;
5292 // See if we can compare using memcmp. As a heuristic, we use
5293 // memcmp rather than field references and comparisons if there are
5294 // more than two fields.
5295 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5296 return this->lower_compare_to_memcmp(gogo, inserter);
5298 Location loc = this->location();
5300 Expression* left = this->left_;
5301 Temporary_statement* left_temp = NULL;
5302 if (left->var_expression() == NULL
5303 && left->temporary_reference_expression() == NULL)
5305 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5306 inserter->insert(left_temp);
5307 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5310 Expression* right = this->right_;
5311 Temporary_statement* right_temp = NULL;
5312 if (right->var_expression() == NULL
5313 && right->temporary_reference_expression() == NULL)
5315 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5316 inserter->insert(right_temp);
5317 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5320 Expression* ret = Expression::make_boolean(true, loc);
5321 const Struct_field_list* fields = st->fields();
5322 unsigned int field_index = 0;
5323 for (Struct_field_list::const_iterator pf = fields->begin();
5324 pf != fields->end();
5325 ++pf, ++field_index)
5327 if (Gogo::is_sink_name(pf->field_name()))
5328 continue;
5330 if (field_index > 0)
5332 if (left_temp == NULL)
5333 left = left->copy();
5334 else
5335 left = Expression::make_temporary_reference(left_temp, loc);
5336 if (right_temp == NULL)
5337 right = right->copy();
5338 else
5339 right = Expression::make_temporary_reference(right_temp, loc);
5341 Expression* f1 = Expression::make_field_reference(left, field_index,
5342 loc);
5343 Expression* f2 = Expression::make_field_reference(right, field_index,
5344 loc);
5345 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5346 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5349 if (this->op_ == OPERATOR_NOTEQ)
5350 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5352 return ret;
5355 // Lower an array comparison.
5357 Expression*
5358 Binary_expression::lower_array_comparison(Gogo* gogo,
5359 Statement_inserter* inserter)
5361 Array_type* at = this->left_->type()->array_type();
5362 Array_type* at2 = this->right_->type()->array_type();
5363 if (at2 == NULL)
5364 return this;
5365 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5366 return this;
5367 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5368 this->right_->type(), NULL))
5369 return this;
5371 // Call memcmp directly if possible. This may let the middle-end
5372 // optimize the call.
5373 if (at->compare_is_identity(gogo))
5374 return this->lower_compare_to_memcmp(gogo, inserter);
5376 // Call the array comparison function.
5377 Named_object* hash_fn;
5378 Named_object* equal_fn;
5379 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5380 &hash_fn, &equal_fn);
5382 Location loc = this->location();
5384 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5386 Expression_list* args = new Expression_list();
5387 args->push_back(this->operand_address(inserter, this->left_));
5388 args->push_back(this->operand_address(inserter, this->right_));
5390 Expression* ret = Expression::make_call(func, args, false, loc);
5392 if (this->op_ == OPERATOR_NOTEQ)
5393 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5395 return ret;
5398 // Lower an interface to value comparison.
5400 Expression*
5401 Binary_expression::lower_interface_value_comparison(Gogo*,
5402 Statement_inserter* inserter)
5404 Type* left_type = this->left_->type();
5405 Type* right_type = this->right_->type();
5406 Interface_type* ift;
5407 if (left_type->interface_type() != NULL)
5409 ift = left_type->interface_type();
5410 if (!ift->implements_interface(right_type, NULL))
5411 return this;
5413 else
5415 ift = right_type->interface_type();
5416 if (!ift->implements_interface(left_type, NULL))
5417 return this;
5419 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5420 return this;
5422 Location loc = this->location();
5424 if (left_type->interface_type() == NULL
5425 && left_type->points_to() == NULL
5426 && !this->left_->is_addressable())
5428 Temporary_statement* temp =
5429 Statement::make_temporary(left_type, NULL, loc);
5430 inserter->insert(temp);
5431 this->left_ =
5432 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5435 if (right_type->interface_type() == NULL
5436 && right_type->points_to() == NULL
5437 && !this->right_->is_addressable())
5439 Temporary_statement* temp =
5440 Statement::make_temporary(right_type, NULL, loc);
5441 inserter->insert(temp);
5442 this->right_ =
5443 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5446 return this;
5449 // Lower a struct or array comparison to a call to memcmp.
5451 Expression*
5452 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5454 Location loc = this->location();
5456 Expression* a1 = this->operand_address(inserter, this->left_);
5457 Expression* a2 = this->operand_address(inserter, this->right_);
5458 Expression* len = Expression::make_type_info(this->left_->type(),
5459 TYPE_INFO_SIZE);
5461 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5462 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5463 return Expression::make_binary(this->op_, call, zero, loc);
5466 Expression*
5467 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5468 Statement_inserter* inserter)
5470 Location loc = this->location();
5471 if (this->left_->type()->is_error_type()
5472 || this->right_->type()->is_error_type()
5473 || this->left_->is_error_expression()
5474 || this->right_->is_error_expression())
5476 go_assert(saw_errors());
5477 return Expression::make_error(loc);
5480 Temporary_statement* temp;
5482 Type* left_type = this->left_->type();
5483 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5484 || this->op_ == OPERATOR_RSHIFT);
5485 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5486 left_type->integer_type() != NULL)
5487 || this->op_ == OPERATOR_MOD);
5489 if (is_shift_op
5490 || (is_idiv_op
5491 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5493 if (!this->left_->is_variable() && !this->left_->is_constant())
5495 temp = Statement::make_temporary(NULL, this->left_, loc);
5496 inserter->insert(temp);
5497 this->left_ = Expression::make_temporary_reference(temp, loc);
5499 if (!this->right_->is_variable() && !this->right_->is_constant())
5501 temp =
5502 Statement::make_temporary(NULL, this->right_, loc);
5503 this->right_ = Expression::make_temporary_reference(temp, loc);
5504 inserter->insert(temp);
5507 return this;
5511 // Return the address of EXPR, cast to unsafe.Pointer.
5513 Expression*
5514 Binary_expression::operand_address(Statement_inserter* inserter,
5515 Expression* expr)
5517 Location loc = this->location();
5519 if (!expr->is_addressable())
5521 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5522 loc);
5523 inserter->insert(temp);
5524 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5526 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5527 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5528 Type* void_type = Type::make_void_type();
5529 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5530 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5533 // Return the numeric constant value, if it has one.
5535 bool
5536 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5538 Numeric_constant left_nc;
5539 if (!this->left_->numeric_constant_value(&left_nc))
5540 return false;
5541 Numeric_constant right_nc;
5542 if (!this->right_->numeric_constant_value(&right_nc))
5543 return false;
5544 bool issued_error;
5545 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5546 this->location(), nc, &issued_error);
5549 // Note that the value is being discarded.
5551 bool
5552 Binary_expression::do_discarding_value()
5554 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5555 return this->right_->discarding_value();
5556 else
5558 this->unused_value_error();
5559 return false;
5563 // Get type.
5565 Type*
5566 Binary_expression::do_type()
5568 if (this->classification() == EXPRESSION_ERROR)
5569 return Type::make_error_type();
5571 switch (this->op_)
5573 case OPERATOR_EQEQ:
5574 case OPERATOR_NOTEQ:
5575 case OPERATOR_LT:
5576 case OPERATOR_LE:
5577 case OPERATOR_GT:
5578 case OPERATOR_GE:
5579 if (this->type_ == NULL)
5580 this->type_ = Type::make_boolean_type();
5581 return this->type_;
5583 case OPERATOR_PLUS:
5584 case OPERATOR_MINUS:
5585 case OPERATOR_OR:
5586 case OPERATOR_XOR:
5587 case OPERATOR_MULT:
5588 case OPERATOR_DIV:
5589 case OPERATOR_MOD:
5590 case OPERATOR_AND:
5591 case OPERATOR_BITCLEAR:
5592 case OPERATOR_OROR:
5593 case OPERATOR_ANDAND:
5595 Type* type;
5596 if (!Binary_expression::operation_type(this->op_,
5597 this->left_->type(),
5598 this->right_->type(),
5599 &type))
5600 return Type::make_error_type();
5601 return type;
5604 case OPERATOR_LSHIFT:
5605 case OPERATOR_RSHIFT:
5606 return this->left_->type();
5608 default:
5609 go_unreachable();
5613 // Set type for a binary expression.
5615 void
5616 Binary_expression::do_determine_type(const Type_context* context)
5618 Type* tleft = this->left_->type();
5619 Type* tright = this->right_->type();
5621 // Both sides should have the same type, except for the shift
5622 // operations. For a comparison, we should ignore the incoming
5623 // type.
5625 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5626 || this->op_ == OPERATOR_RSHIFT);
5628 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5629 || this->op_ == OPERATOR_NOTEQ
5630 || this->op_ == OPERATOR_LT
5631 || this->op_ == OPERATOR_LE
5632 || this->op_ == OPERATOR_GT
5633 || this->op_ == OPERATOR_GE);
5635 // For constant expressions, the context of the result is not useful in
5636 // determining the types of the operands. It is only legal to use abstract
5637 // boolean, numeric, and string constants as operands where it is legal to
5638 // use non-abstract boolean, numeric, and string constants, respectively.
5639 // Any issues with the operation will be resolved in the check_types pass.
5640 bool is_constant_expr = (this->left_->is_constant()
5641 && this->right_->is_constant());
5643 Type_context subcontext(*context);
5645 if (is_constant_expr && !is_shift_op)
5647 subcontext.type = NULL;
5648 subcontext.may_be_abstract = true;
5650 else if (is_comparison)
5652 // In a comparison, the context does not determine the types of
5653 // the operands.
5654 subcontext.type = NULL;
5657 // Set the context for the left hand operand.
5658 if (is_shift_op)
5660 // The right hand operand of a shift plays no role in
5661 // determining the type of the left hand operand.
5663 else if (!tleft->is_abstract())
5664 subcontext.type = tleft;
5665 else if (!tright->is_abstract())
5666 subcontext.type = tright;
5667 else if (subcontext.type == NULL)
5669 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5670 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5671 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5673 // Both sides have an abstract integer, abstract float, or
5674 // abstract complex type. Just let CONTEXT determine
5675 // whether they may remain abstract or not.
5677 else if (tleft->complex_type() != NULL)
5678 subcontext.type = tleft;
5679 else if (tright->complex_type() != NULL)
5680 subcontext.type = tright;
5681 else if (tleft->float_type() != NULL)
5682 subcontext.type = tleft;
5683 else if (tright->float_type() != NULL)
5684 subcontext.type = tright;
5685 else
5686 subcontext.type = tleft;
5688 if (subcontext.type != NULL && !context->may_be_abstract)
5689 subcontext.type = subcontext.type->make_non_abstract_type();
5692 this->left_->determine_type(&subcontext);
5694 if (is_shift_op)
5696 // We may have inherited an unusable type for the shift operand.
5697 // Give a useful error if that happened.
5698 if (tleft->is_abstract()
5699 && subcontext.type != NULL
5700 && !subcontext.may_be_abstract
5701 && subcontext.type->interface_type() == NULL
5702 && subcontext.type->integer_type() == NULL)
5703 this->report_error(("invalid context-determined non-integer type "
5704 "for left operand of shift"));
5706 // The context for the right hand operand is the same as for the
5707 // left hand operand, except for a shift operator.
5708 subcontext.type = Type::lookup_integer_type("uint");
5709 subcontext.may_be_abstract = false;
5712 this->right_->determine_type(&subcontext);
5714 if (is_comparison)
5716 if (this->type_ != NULL && !this->type_->is_abstract())
5718 else if (context->type != NULL && context->type->is_boolean_type())
5719 this->type_ = context->type;
5720 else if (!context->may_be_abstract)
5721 this->type_ = Type::lookup_bool_type();
5725 // Report an error if the binary operator OP does not support TYPE.
5726 // OTYPE is the type of the other operand. Return whether the
5727 // operation is OK. This should not be used for shift.
5729 bool
5730 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5731 Location location)
5733 switch (op)
5735 case OPERATOR_OROR:
5736 case OPERATOR_ANDAND:
5737 if (!type->is_boolean_type()
5738 || !otype->is_boolean_type())
5740 go_error_at(location, "expected boolean type");
5741 return false;
5743 break;
5745 case OPERATOR_EQEQ:
5746 case OPERATOR_NOTEQ:
5748 std::string reason;
5749 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5751 go_error_at(location, "%s", reason.c_str());
5752 return false;
5755 break;
5757 case OPERATOR_LT:
5758 case OPERATOR_LE:
5759 case OPERATOR_GT:
5760 case OPERATOR_GE:
5762 std::string reason;
5763 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5765 go_error_at(location, "%s", reason.c_str());
5766 return false;
5769 break;
5771 case OPERATOR_PLUS:
5772 case OPERATOR_PLUSEQ:
5773 if ((!type->is_numeric_type() && !type->is_string_type())
5774 || (!otype->is_numeric_type() && !otype->is_string_type()))
5776 go_error_at(location,
5777 "expected integer, floating, complex, or string type");
5778 return false;
5780 break;
5782 case OPERATOR_MINUS:
5783 case OPERATOR_MINUSEQ:
5784 case OPERATOR_MULT:
5785 case OPERATOR_MULTEQ:
5786 case OPERATOR_DIV:
5787 case OPERATOR_DIVEQ:
5788 if (!type->is_numeric_type() || !otype->is_numeric_type())
5790 go_error_at(location, "expected integer, floating, or complex type");
5791 return false;
5793 break;
5795 case OPERATOR_MOD:
5796 case OPERATOR_MODEQ:
5797 case OPERATOR_OR:
5798 case OPERATOR_OREQ:
5799 case OPERATOR_AND:
5800 case OPERATOR_ANDEQ:
5801 case OPERATOR_XOR:
5802 case OPERATOR_XOREQ:
5803 case OPERATOR_BITCLEAR:
5804 case OPERATOR_BITCLEAREQ:
5805 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5807 go_error_at(location, "expected integer type");
5808 return false;
5810 break;
5812 default:
5813 go_unreachable();
5816 return true;
5819 // Check types.
5821 void
5822 Binary_expression::do_check_types(Gogo*)
5824 if (this->classification() == EXPRESSION_ERROR)
5825 return;
5827 Type* left_type = this->left_->type();
5828 Type* right_type = this->right_->type();
5829 if (left_type->is_error() || right_type->is_error())
5831 this->set_is_error();
5832 return;
5835 if (this->op_ == OPERATOR_EQEQ
5836 || this->op_ == OPERATOR_NOTEQ
5837 || this->op_ == OPERATOR_LT
5838 || this->op_ == OPERATOR_LE
5839 || this->op_ == OPERATOR_GT
5840 || this->op_ == OPERATOR_GE)
5842 if (left_type->is_nil_type() && right_type->is_nil_type())
5844 this->report_error(_("invalid comparison of nil with nil"));
5845 return;
5847 if (!Type::are_assignable(left_type, right_type, NULL)
5848 && !Type::are_assignable(right_type, left_type, NULL))
5850 this->report_error(_("incompatible types in binary expression"));
5851 return;
5853 if (!Binary_expression::check_operator_type(this->op_, left_type,
5854 right_type,
5855 this->location())
5856 || !Binary_expression::check_operator_type(this->op_, right_type,
5857 left_type,
5858 this->location()))
5860 this->set_is_error();
5861 return;
5864 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5866 if (!Type::are_compatible_for_binop(left_type, right_type))
5868 this->report_error(_("incompatible types in binary expression"));
5869 return;
5871 if (!Binary_expression::check_operator_type(this->op_, left_type,
5872 right_type,
5873 this->location()))
5875 this->set_is_error();
5876 return;
5878 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5880 // Division by a zero integer constant is an error.
5881 Numeric_constant rconst;
5882 unsigned long rval;
5883 if (left_type->integer_type() != NULL
5884 && this->right_->numeric_constant_value(&rconst)
5885 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5886 && rval == 0)
5888 this->report_error(_("integer division by zero"));
5889 return;
5893 else
5895 if (left_type->integer_type() == NULL)
5896 this->report_error(_("shift of non-integer operand"));
5898 if (right_type->is_string_type())
5899 this->report_error(_("shift count not unsigned integer"));
5900 else if (!right_type->is_abstract()
5901 && (right_type->integer_type() == NULL
5902 || !right_type->integer_type()->is_unsigned()))
5903 this->report_error(_("shift count not unsigned integer"));
5904 else
5906 Numeric_constant nc;
5907 if (this->right_->numeric_constant_value(&nc))
5909 mpz_t val;
5910 if (!nc.to_int(&val))
5911 this->report_error(_("shift count not unsigned integer"));
5912 else
5914 if (mpz_sgn(val) < 0)
5916 this->report_error(_("negative shift count"));
5917 Location rloc = this->right_->location();
5918 this->right_ = Expression::make_integer_ul(0, right_type,
5919 rloc);
5921 mpz_clear(val);
5928 // Get the backend representation for a binary expression.
5930 Bexpression*
5931 Binary_expression::do_get_backend(Translate_context* context)
5933 Gogo* gogo = context->gogo();
5934 Location loc = this->location();
5935 Type* left_type = this->left_->type();
5936 Type* right_type = this->right_->type();
5938 bool use_left_type = true;
5939 bool is_shift_op = false;
5940 bool is_idiv_op = false;
5941 switch (this->op_)
5943 case OPERATOR_EQEQ:
5944 case OPERATOR_NOTEQ:
5945 case OPERATOR_LT:
5946 case OPERATOR_LE:
5947 case OPERATOR_GT:
5948 case OPERATOR_GE:
5949 return Expression::comparison(context, this->type_, this->op_,
5950 this->left_, this->right_, loc);
5952 case OPERATOR_OROR:
5953 case OPERATOR_ANDAND:
5954 use_left_type = false;
5955 break;
5956 case OPERATOR_PLUS:
5957 case OPERATOR_MINUS:
5958 case OPERATOR_OR:
5959 case OPERATOR_XOR:
5960 case OPERATOR_MULT:
5961 break;
5962 case OPERATOR_DIV:
5963 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5964 break;
5965 // Fall through.
5966 case OPERATOR_MOD:
5967 is_idiv_op = true;
5968 break;
5969 case OPERATOR_LSHIFT:
5970 case OPERATOR_RSHIFT:
5971 is_shift_op = true;
5972 break;
5973 case OPERATOR_BITCLEAR:
5974 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5975 case OPERATOR_AND:
5976 break;
5977 default:
5978 go_unreachable();
5981 // The only binary operation for string is +, and that should have
5982 // been converted to a String_concat_expression in do_lower.
5983 go_assert(!left_type->is_string_type());
5985 // For complex division Go might want slightly different results than the
5986 // backend implementation provides, so we have our own runtime routine.
5987 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5989 Runtime::Function complex_code;
5990 switch (this->left_->type()->complex_type()->bits())
5992 case 64:
5993 complex_code = Runtime::COMPLEX64_DIV;
5994 break;
5995 case 128:
5996 complex_code = Runtime::COMPLEX128_DIV;
5997 break;
5998 default:
5999 go_unreachable();
6001 Expression* complex_div =
6002 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6003 return complex_div->get_backend(context);
6006 Bexpression* left = this->left_->get_backend(context);
6007 Bexpression* right = this->right_->get_backend(context);
6009 Type* type = use_left_type ? left_type : right_type;
6010 Btype* btype = type->get_backend(gogo);
6012 Bexpression* ret =
6013 gogo->backend()->binary_expression(this->op_, left, right, loc);
6014 ret = gogo->backend()->convert_expression(btype, ret, loc);
6016 // Initialize overflow constants.
6017 Bexpression* overflow;
6018 mpz_t zero;
6019 mpz_init_set_ui(zero, 0UL);
6020 mpz_t one;
6021 mpz_init_set_ui(one, 1UL);
6022 mpz_t neg_one;
6023 mpz_init_set_si(neg_one, -1);
6025 Btype* left_btype = left_type->get_backend(gogo);
6026 Btype* right_btype = right_type->get_backend(gogo);
6028 // In Go, a shift larger than the size of the type is well-defined.
6029 // This is not true in C, so we need to insert a conditional.
6030 if (is_shift_op)
6032 go_assert(left_type->integer_type() != NULL);
6034 int bits = left_type->integer_type()->bits();
6036 Numeric_constant nc;
6037 unsigned long ul;
6038 if (!this->right_->numeric_constant_value(&nc)
6039 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6040 || ul >= static_cast<unsigned long>(bits))
6042 mpz_t bitsval;
6043 mpz_init_set_ui(bitsval, bits);
6044 Bexpression* bits_expr =
6045 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6046 Bexpression* compare =
6047 gogo->backend()->binary_expression(OPERATOR_LT,
6048 right, bits_expr, loc);
6050 Bexpression* zero_expr =
6051 gogo->backend()->integer_constant_expression(left_btype, zero);
6052 overflow = zero_expr;
6053 Bfunction* bfn = context->function()->func_value()->get_decl();
6054 if (this->op_ == OPERATOR_RSHIFT
6055 && !left_type->integer_type()->is_unsigned())
6057 Bexpression* neg_expr =
6058 gogo->backend()->binary_expression(OPERATOR_LT, left,
6059 zero_expr, loc);
6060 Bexpression* neg_one_expr =
6061 gogo->backend()->integer_constant_expression(left_btype,
6062 neg_one);
6063 overflow = gogo->backend()->conditional_expression(bfn,
6064 btype,
6065 neg_expr,
6066 neg_one_expr,
6067 zero_expr,
6068 loc);
6070 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6071 ret, overflow, loc);
6072 mpz_clear(bitsval);
6076 // Add checks for division by zero and division overflow as needed.
6077 if (is_idiv_op)
6079 if (gogo->check_divide_by_zero())
6081 // right == 0
6082 Bexpression* zero_expr =
6083 gogo->backend()->integer_constant_expression(right_btype, zero);
6084 Bexpression* check =
6085 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6086 right, zero_expr, loc);
6088 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6089 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6090 Bexpression* crash = gogo->runtime_error(errcode,
6091 loc)->get_backend(context);
6093 // right == 0 ? (__go_runtime_error(...), 0) : ret
6094 Bfunction* bfn = context->function()->func_value()->get_decl();
6095 ret = gogo->backend()->conditional_expression(bfn, btype,
6096 check, crash,
6097 ret, loc);
6100 if (gogo->check_divide_overflow())
6102 // right == -1
6103 // FIXME: It would be nice to say that this test is expected
6104 // to return false.
6106 Bexpression* neg_one_expr =
6107 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6108 Bexpression* check =
6109 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6110 right, neg_one_expr, loc);
6112 Bexpression* zero_expr =
6113 gogo->backend()->integer_constant_expression(btype, zero);
6114 Bexpression* one_expr =
6115 gogo->backend()->integer_constant_expression(btype, one);
6116 Bfunction* bfn = context->function()->func_value()->get_decl();
6118 if (type->integer_type()->is_unsigned())
6120 // An unsigned -1 is the largest possible number, so
6121 // dividing is always 1 or 0.
6123 Bexpression* cmp =
6124 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6125 left, right, loc);
6126 if (this->op_ == OPERATOR_DIV)
6127 overflow =
6128 gogo->backend()->conditional_expression(bfn, btype, cmp,
6129 one_expr, zero_expr,
6130 loc);
6131 else
6132 overflow =
6133 gogo->backend()->conditional_expression(bfn, btype, cmp,
6134 zero_expr, left,
6135 loc);
6137 else
6139 // Computing left / -1 is the same as computing - left,
6140 // which does not overflow since Go sets -fwrapv.
6141 if (this->op_ == OPERATOR_DIV)
6143 Expression* negate_expr =
6144 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6145 overflow = negate_expr->get_backend(context);
6147 else
6148 overflow = zero_expr;
6150 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6152 // right == -1 ? - left : ret
6153 ret = gogo->backend()->conditional_expression(bfn, btype,
6154 check, overflow,
6155 ret, loc);
6159 mpz_clear(zero);
6160 mpz_clear(one);
6161 mpz_clear(neg_one);
6162 return ret;
6165 // Export a binary expression.
6167 void
6168 Binary_expression::do_export(Export* exp) const
6170 exp->write_c_string("(");
6171 this->left_->export_expression(exp);
6172 switch (this->op_)
6174 case OPERATOR_OROR:
6175 exp->write_c_string(" || ");
6176 break;
6177 case OPERATOR_ANDAND:
6178 exp->write_c_string(" && ");
6179 break;
6180 case OPERATOR_EQEQ:
6181 exp->write_c_string(" == ");
6182 break;
6183 case OPERATOR_NOTEQ:
6184 exp->write_c_string(" != ");
6185 break;
6186 case OPERATOR_LT:
6187 exp->write_c_string(" < ");
6188 break;
6189 case OPERATOR_LE:
6190 exp->write_c_string(" <= ");
6191 break;
6192 case OPERATOR_GT:
6193 exp->write_c_string(" > ");
6194 break;
6195 case OPERATOR_GE:
6196 exp->write_c_string(" >= ");
6197 break;
6198 case OPERATOR_PLUS:
6199 exp->write_c_string(" + ");
6200 break;
6201 case OPERATOR_MINUS:
6202 exp->write_c_string(" - ");
6203 break;
6204 case OPERATOR_OR:
6205 exp->write_c_string(" | ");
6206 break;
6207 case OPERATOR_XOR:
6208 exp->write_c_string(" ^ ");
6209 break;
6210 case OPERATOR_MULT:
6211 exp->write_c_string(" * ");
6212 break;
6213 case OPERATOR_DIV:
6214 exp->write_c_string(" / ");
6215 break;
6216 case OPERATOR_MOD:
6217 exp->write_c_string(" % ");
6218 break;
6219 case OPERATOR_LSHIFT:
6220 exp->write_c_string(" << ");
6221 break;
6222 case OPERATOR_RSHIFT:
6223 exp->write_c_string(" >> ");
6224 break;
6225 case OPERATOR_AND:
6226 exp->write_c_string(" & ");
6227 break;
6228 case OPERATOR_BITCLEAR:
6229 exp->write_c_string(" &^ ");
6230 break;
6231 default:
6232 go_unreachable();
6234 this->right_->export_expression(exp);
6235 exp->write_c_string(")");
6238 // Import a binary expression.
6240 Expression*
6241 Binary_expression::do_import(Import* imp)
6243 imp->require_c_string("(");
6245 Expression* left = Expression::import_expression(imp);
6247 Operator op;
6248 if (imp->match_c_string(" || "))
6250 op = OPERATOR_OROR;
6251 imp->advance(4);
6253 else if (imp->match_c_string(" && "))
6255 op = OPERATOR_ANDAND;
6256 imp->advance(4);
6258 else if (imp->match_c_string(" == "))
6260 op = OPERATOR_EQEQ;
6261 imp->advance(4);
6263 else if (imp->match_c_string(" != "))
6265 op = OPERATOR_NOTEQ;
6266 imp->advance(4);
6268 else if (imp->match_c_string(" < "))
6270 op = OPERATOR_LT;
6271 imp->advance(3);
6273 else if (imp->match_c_string(" <= "))
6275 op = OPERATOR_LE;
6276 imp->advance(4);
6278 else if (imp->match_c_string(" > "))
6280 op = OPERATOR_GT;
6281 imp->advance(3);
6283 else if (imp->match_c_string(" >= "))
6285 op = OPERATOR_GE;
6286 imp->advance(4);
6288 else if (imp->match_c_string(" + "))
6290 op = OPERATOR_PLUS;
6291 imp->advance(3);
6293 else if (imp->match_c_string(" - "))
6295 op = OPERATOR_MINUS;
6296 imp->advance(3);
6298 else if (imp->match_c_string(" | "))
6300 op = OPERATOR_OR;
6301 imp->advance(3);
6303 else if (imp->match_c_string(" ^ "))
6305 op = OPERATOR_XOR;
6306 imp->advance(3);
6308 else if (imp->match_c_string(" * "))
6310 op = OPERATOR_MULT;
6311 imp->advance(3);
6313 else if (imp->match_c_string(" / "))
6315 op = OPERATOR_DIV;
6316 imp->advance(3);
6318 else if (imp->match_c_string(" % "))
6320 op = OPERATOR_MOD;
6321 imp->advance(3);
6323 else if (imp->match_c_string(" << "))
6325 op = OPERATOR_LSHIFT;
6326 imp->advance(4);
6328 else if (imp->match_c_string(" >> "))
6330 op = OPERATOR_RSHIFT;
6331 imp->advance(4);
6333 else if (imp->match_c_string(" & "))
6335 op = OPERATOR_AND;
6336 imp->advance(3);
6338 else if (imp->match_c_string(" &^ "))
6340 op = OPERATOR_BITCLEAR;
6341 imp->advance(4);
6343 else
6345 go_error_at(imp->location(), "unrecognized binary operator");
6346 return Expression::make_error(imp->location());
6349 Expression* right = Expression::import_expression(imp);
6351 imp->require_c_string(")");
6353 return Expression::make_binary(op, left, right, imp->location());
6356 // Dump ast representation of a binary expression.
6358 void
6359 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6361 ast_dump_context->ostream() << "(";
6362 ast_dump_context->dump_expression(this->left_);
6363 ast_dump_context->ostream() << " ";
6364 ast_dump_context->dump_operator(this->op_);
6365 ast_dump_context->ostream() << " ";
6366 ast_dump_context->dump_expression(this->right_);
6367 ast_dump_context->ostream() << ") ";
6370 // Make a binary expression.
6372 Expression*
6373 Expression::make_binary(Operator op, Expression* left, Expression* right,
6374 Location location)
6376 return new Binary_expression(op, left, right, location);
6379 // Implement a comparison.
6381 Bexpression*
6382 Expression::comparison(Translate_context* context, Type* result_type,
6383 Operator op, Expression* left, Expression* right,
6384 Location location)
6386 Type* left_type = left->type();
6387 Type* right_type = right->type();
6389 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6391 if (left_type->is_string_type() && right_type->is_string_type())
6393 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6395 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6396 left, right);
6397 right = Expression::make_boolean(true, location);
6399 else
6401 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6402 left, right);
6403 right = zexpr;
6406 else if ((left_type->interface_type() != NULL
6407 && right_type->interface_type() == NULL
6408 && !right_type->is_nil_type())
6409 || (left_type->interface_type() == NULL
6410 && !left_type->is_nil_type()
6411 && right_type->interface_type() != NULL))
6413 // Comparing an interface value to a non-interface value.
6414 if (left_type->interface_type() == NULL)
6416 std::swap(left_type, right_type);
6417 std::swap(left, right);
6420 // The right operand is not an interface. We need to take its
6421 // address if it is not a pointer.
6422 Expression* pointer_arg = NULL;
6423 if (right_type->points_to() != NULL)
6424 pointer_arg = right;
6425 else
6427 go_assert(right->is_addressable());
6428 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6429 location);
6432 Expression* descriptor =
6433 Expression::make_type_descriptor(right_type, location);
6434 left =
6435 Runtime::make_call((left_type->interface_type()->is_empty()
6436 ? Runtime::EFACEVALEQ
6437 : Runtime::IFACEVALEQ),
6438 location, 3, left, descriptor,
6439 pointer_arg);
6440 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6441 right = Expression::make_boolean(true, location);
6443 else if (left_type->interface_type() != NULL
6444 && right_type->interface_type() != NULL)
6446 Runtime::Function compare_function;
6447 if (left_type->interface_type()->is_empty()
6448 && right_type->interface_type()->is_empty())
6449 compare_function = Runtime::EFACEEQ;
6450 else if (!left_type->interface_type()->is_empty()
6451 && !right_type->interface_type()->is_empty())
6452 compare_function = Runtime::IFACEEQ;
6453 else
6455 if (left_type->interface_type()->is_empty())
6457 std::swap(left_type, right_type);
6458 std::swap(left, right);
6460 go_assert(!left_type->interface_type()->is_empty());
6461 go_assert(right_type->interface_type()->is_empty());
6462 compare_function = Runtime::IFACEEFACEEQ;
6465 left = Runtime::make_call(compare_function, location, 2, left, right);
6466 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6467 right = Expression::make_boolean(true, location);
6470 if (left_type->is_nil_type()
6471 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6473 std::swap(left_type, right_type);
6474 std::swap(left, right);
6477 if (right_type->is_nil_type())
6479 right = Expression::make_nil(location);
6480 if (left_type->array_type() != NULL
6481 && left_type->array_type()->length() == NULL)
6483 Array_type* at = left_type->array_type();
6484 bool is_lvalue = false;
6485 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6487 else if (left_type->interface_type() != NULL)
6489 // An interface is nil if the first field is nil.
6490 left = Expression::make_field_reference(left, 0, location);
6494 Bexpression* left_bexpr = left->get_backend(context);
6495 Bexpression* right_bexpr = right->get_backend(context);
6497 Gogo* gogo = context->gogo();
6498 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6499 right_bexpr, location);
6500 if (result_type != NULL)
6501 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6502 ret, location);
6503 return ret;
6506 // Class String_concat_expression.
6508 bool
6509 String_concat_expression::do_is_constant() const
6511 for (Expression_list::const_iterator pe = this->exprs_->begin();
6512 pe != this->exprs_->end();
6513 ++pe)
6515 if (!(*pe)->is_constant())
6516 return false;
6518 return true;
6521 bool
6522 String_concat_expression::do_is_static_initializer() const
6524 for (Expression_list::const_iterator pe = this->exprs_->begin();
6525 pe != this->exprs_->end();
6526 ++pe)
6528 if (!(*pe)->is_static_initializer())
6529 return false;
6531 return true;
6534 Type*
6535 String_concat_expression::do_type()
6537 Type* t = this->exprs_->front()->type();
6538 Expression_list::iterator pe = this->exprs_->begin();
6539 ++pe;
6540 for (; pe != this->exprs_->end(); ++pe)
6542 Type* t1;
6543 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6544 (*pe)->type(),
6545 &t1))
6546 return Type::make_error_type();
6547 t = t1;
6549 return t;
6552 void
6553 String_concat_expression::do_determine_type(const Type_context* context)
6555 Type_context subcontext(*context);
6556 for (Expression_list::iterator pe = this->exprs_->begin();
6557 pe != this->exprs_->end();
6558 ++pe)
6560 Type* t = (*pe)->type();
6561 if (!t->is_abstract())
6563 subcontext.type = t;
6564 break;
6567 if (subcontext.type == NULL)
6568 subcontext.type = this->exprs_->front()->type();
6569 for (Expression_list::iterator pe = this->exprs_->begin();
6570 pe != this->exprs_->end();
6571 ++pe)
6572 (*pe)->determine_type(&subcontext);
6575 void
6576 String_concat_expression::do_check_types(Gogo*)
6578 if (this->is_error_expression())
6579 return;
6580 Type* t = this->exprs_->front()->type();
6581 if (t->is_error())
6583 this->set_is_error();
6584 return;
6586 Expression_list::iterator pe = this->exprs_->begin();
6587 ++pe;
6588 for (; pe != this->exprs_->end(); ++pe)
6590 Type* t1 = (*pe)->type();
6591 if (!Type::are_compatible_for_binop(t, t1))
6593 this->report_error("incompatible types in binary expression");
6594 return;
6596 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6597 this->location()))
6599 this->set_is_error();
6600 return;
6605 Expression*
6606 String_concat_expression::do_flatten(Gogo*, Named_object*,
6607 Statement_inserter*)
6609 if (this->is_error_expression())
6610 return this;
6611 Location loc = this->location();
6612 Type* type = this->type();
6613 Expression* nil_arg = Expression::make_nil(loc);
6614 Expression* call;
6615 switch (this->exprs_->size())
6617 case 0: case 1:
6618 go_unreachable();
6620 case 2: case 3: case 4: case 5:
6622 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6623 NULL, loc);
6624 Array_type* arg_type = Type::make_array_type(type, len);
6625 arg_type->set_is_array_incomparable();
6626 Expression* arg =
6627 Expression::make_array_composite_literal(arg_type, this->exprs_,
6628 loc);
6629 Runtime::Function code;
6630 switch (this->exprs_->size())
6632 default:
6633 go_unreachable();
6634 case 2:
6635 code = Runtime::CONCATSTRING2;
6636 break;
6637 case 3:
6638 code = Runtime::CONCATSTRING3;
6639 break;
6640 case 4:
6641 code = Runtime::CONCATSTRING4;
6642 break;
6643 case 5:
6644 code = Runtime::CONCATSTRING5;
6645 break;
6647 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6649 break;
6651 default:
6653 Type* arg_type = Type::make_array_type(type, NULL);
6654 Slice_construction_expression* sce =
6655 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6656 loc);
6657 sce->set_storage_does_not_escape();
6658 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6659 sce);
6661 break;
6664 return Expression::make_cast(type, call, loc);
6667 void
6668 String_concat_expression::do_dump_expression(
6669 Ast_dump_context* ast_dump_context) const
6671 ast_dump_context->ostream() << "concat(";
6672 ast_dump_context->dump_expression_list(this->exprs_, false);
6673 ast_dump_context->ostream() << ")";
6676 Expression*
6677 Expression::make_string_concat(Expression_list* exprs)
6679 return new String_concat_expression(exprs);
6682 // Class Bound_method_expression.
6684 // Traversal.
6687 Bound_method_expression::do_traverse(Traverse* traverse)
6689 return Expression::traverse(&this->expr_, traverse);
6692 // Return the type of a bound method expression. The type of this
6693 // object is simply the type of the method with no receiver.
6695 Type*
6696 Bound_method_expression::do_type()
6698 Named_object* fn = this->method_->named_object();
6699 Function_type* fntype;
6700 if (fn->is_function())
6701 fntype = fn->func_value()->type();
6702 else if (fn->is_function_declaration())
6703 fntype = fn->func_declaration_value()->type();
6704 else
6705 return Type::make_error_type();
6706 return fntype->copy_without_receiver();
6709 // Determine the types of a method expression.
6711 void
6712 Bound_method_expression::do_determine_type(const Type_context*)
6714 Named_object* fn = this->method_->named_object();
6715 Function_type* fntype;
6716 if (fn->is_function())
6717 fntype = fn->func_value()->type();
6718 else if (fn->is_function_declaration())
6719 fntype = fn->func_declaration_value()->type();
6720 else
6721 fntype = NULL;
6722 if (fntype == NULL || !fntype->is_method())
6723 this->expr_->determine_type_no_context();
6724 else
6726 Type_context subcontext(fntype->receiver()->type(), false);
6727 this->expr_->determine_type(&subcontext);
6731 // Check the types of a method expression.
6733 void
6734 Bound_method_expression::do_check_types(Gogo*)
6736 Named_object* fn = this->method_->named_object();
6737 if (!fn->is_function() && !fn->is_function_declaration())
6739 this->report_error(_("object is not a method"));
6740 return;
6743 Function_type* fntype;
6744 if (fn->is_function())
6745 fntype = fn->func_value()->type();
6746 else if (fn->is_function_declaration())
6747 fntype = fn->func_declaration_value()->type();
6748 else
6749 go_unreachable();
6750 Type* rtype = fntype->receiver()->type()->deref();
6751 Type* etype = (this->expr_type_ != NULL
6752 ? this->expr_type_
6753 : this->expr_->type());
6754 etype = etype->deref();
6755 if (!Type::are_identical(rtype, etype, true, NULL))
6756 this->report_error(_("method type does not match object type"));
6759 // If a bound method expression is not simply called, then it is
6760 // represented as a closure. The closure will hold a single variable,
6761 // the receiver to pass to the method. The function will be a simple
6762 // thunk that pulls that value from the closure and calls the method
6763 // with the remaining arguments.
6765 // Because method values are not common, we don't build all thunks for
6766 // every methods, but instead only build them as we need them. In
6767 // particular, we even build them on demand for methods defined in
6768 // other packages.
6770 Bound_method_expression::Method_value_thunks
6771 Bound_method_expression::method_value_thunks;
6773 // Find or create the thunk for METHOD.
6775 Named_object*
6776 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6777 Named_object* fn)
6779 std::pair<Named_object*, Named_object*> val(fn, NULL);
6780 std::pair<Method_value_thunks::iterator, bool> ins =
6781 Bound_method_expression::method_value_thunks.insert(val);
6782 if (!ins.second)
6784 // We have seen this method before.
6785 go_assert(ins.first->second != NULL);
6786 return ins.first->second;
6789 Location loc = fn->location();
6791 Function_type* orig_fntype;
6792 if (fn->is_function())
6793 orig_fntype = fn->func_value()->type();
6794 else if (fn->is_function_declaration())
6795 orig_fntype = fn->func_declaration_value()->type();
6796 else
6797 orig_fntype = NULL;
6799 if (orig_fntype == NULL || !orig_fntype->is_method())
6801 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6802 return ins.first->second;
6805 Struct_field_list* sfl = new Struct_field_list();
6806 // The type here is wrong--it should be the C function type. But it
6807 // doesn't really matter.
6808 Type* vt = Type::make_pointer_type(Type::make_void_type());
6809 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6810 sfl->push_back(Struct_field(Typed_identifier("val.1",
6811 orig_fntype->receiver()->type(),
6812 loc)));
6813 Struct_type* st = Type::make_struct_type(sfl, loc);
6814 st->set_is_struct_incomparable();
6815 Type* closure_type = Type::make_pointer_type(st);
6817 Function_type* new_fntype = orig_fntype->copy_with_names();
6819 std::string thunk_name = Gogo::thunk_name();
6820 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6821 false, loc);
6823 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6824 cvar->set_is_used();
6825 cvar->set_is_closure();
6826 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6827 NULL, cvar);
6828 new_no->func_value()->set_closure_var(cp);
6830 gogo->start_block(loc);
6832 // Field 0 of the closure is the function code pointer, field 1 is
6833 // the value on which to invoke the method.
6834 Expression* arg = Expression::make_var_reference(cp, loc);
6835 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6836 arg = Expression::make_field_reference(arg, 1, loc);
6838 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6840 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6841 Expression_list* args;
6842 if (orig_params == NULL || orig_params->empty())
6843 args = NULL;
6844 else
6846 const Typed_identifier_list* new_params = new_fntype->parameters();
6847 args = new Expression_list();
6848 for (Typed_identifier_list::const_iterator p = new_params->begin();
6849 p != new_params->end();
6850 ++p)
6852 Named_object* p_no = gogo->lookup(p->name(), NULL);
6853 go_assert(p_no != NULL
6854 && p_no->is_variable()
6855 && p_no->var_value()->is_parameter());
6856 args->push_back(Expression::make_var_reference(p_no, loc));
6860 Call_expression* call = Expression::make_call(bme, args,
6861 orig_fntype->is_varargs(),
6862 loc);
6863 call->set_varargs_are_lowered();
6865 Statement* s = Statement::make_return_from_call(call, loc);
6866 gogo->add_statement(s);
6867 Block* b = gogo->finish_block(loc);
6868 gogo->add_block(b, loc);
6869 gogo->lower_block(new_no, b);
6870 gogo->flatten_block(new_no, b);
6871 gogo->finish_function(loc);
6873 ins.first->second = new_no;
6874 return new_no;
6877 // Return an expression to check *REF for nil while dereferencing
6878 // according to FIELD_INDEXES. Update *REF to build up the field
6879 // reference. This is a static function so that we don't have to
6880 // worry about declaring Field_indexes in expressions.h.
6882 static Expression*
6883 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6884 Expression** ref)
6886 if (field_indexes == NULL)
6887 return Expression::make_boolean(false, loc);
6888 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6889 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6890 go_assert(stype != NULL
6891 && field_indexes->field_index < stype->field_count());
6892 if ((*ref)->type()->struct_type() == NULL)
6894 go_assert((*ref)->type()->points_to() != NULL);
6895 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6896 Expression::make_nil(loc),
6897 loc);
6898 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6899 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6900 go_assert((*ref)->type()->struct_type() == stype);
6902 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6903 loc);
6904 return cond;
6907 // Flatten a method value into a struct with nil checks. We can't do
6908 // this in the lowering phase, because if the method value is called
6909 // directly we don't need a thunk. That case will have been handled
6910 // by Call_expression::do_lower, so if we get here then we do need a
6911 // thunk.
6913 Expression*
6914 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6915 Statement_inserter* inserter)
6917 Location loc = this->location();
6919 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
6920 this->method_,
6921 this->function_);
6922 if (thunk->is_erroneous())
6924 go_assert(saw_errors());
6925 return Expression::make_error(loc);
6928 // Force the expression into a variable. This is only necessary if
6929 // we are going to do nil checks below, but it's easy enough to
6930 // always do it.
6931 Expression* expr = this->expr_;
6932 if (!expr->is_variable())
6934 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6935 inserter->insert(etemp);
6936 expr = Expression::make_temporary_reference(etemp, loc);
6939 // If the method expects a value, and we have a pointer, we need to
6940 // dereference the pointer.
6942 Named_object* fn = this->method_->named_object();
6943 Function_type *fntype;
6944 if (fn->is_function())
6945 fntype = fn->func_value()->type();
6946 else if (fn->is_function_declaration())
6947 fntype = fn->func_declaration_value()->type();
6948 else
6949 go_unreachable();
6951 Expression* val = expr;
6952 if (fntype->receiver()->type()->points_to() == NULL
6953 && val->type()->points_to() != NULL)
6954 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6956 // Note that we are ignoring this->expr_type_ here. The thunk will
6957 // expect a closure whose second field has type this->expr_type_ (if
6958 // that is not NULL). We are going to pass it a closure whose
6959 // second field has type this->expr_->type(). Since
6960 // this->expr_type_ is only not-NULL for pointer types, we can get
6961 // away with this.
6963 Struct_field_list* fields = new Struct_field_list();
6964 fields->push_back(Struct_field(Typed_identifier("fn.0",
6965 thunk->func_value()->type(),
6966 loc)));
6967 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6968 Struct_type* st = Type::make_struct_type(fields, loc);
6969 st->set_is_struct_incomparable();
6971 Expression_list* vals = new Expression_list();
6972 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6973 vals->push_back(val);
6975 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6977 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
6978 ret = Expression::make_heap_expression(ret, loc);
6979 else
6981 // When compiling the runtime, method closures do not escape.
6982 // When escape analysis becomes the default, and applies to
6983 // method closures, this should be changed to make it an error
6984 // if a method closure escapes.
6985 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
6986 inserter->insert(ctemp);
6987 ret = Expression::make_temporary_reference(ctemp, loc);
6988 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
6989 ret->unary_expression()->set_does_not_escape();
6992 // If necessary, check whether the expression or any embedded
6993 // pointers are nil.
6995 Expression* nil_check = NULL;
6996 if (this->method_->field_indexes() != NULL)
6998 Expression* ref = expr;
6999 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7000 expr = ref;
7003 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7005 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7006 Expression::make_nil(loc),
7007 loc);
7008 if (nil_check == NULL)
7009 nil_check = n;
7010 else
7011 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7014 if (nil_check != NULL)
7016 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7017 loc);
7018 // Fix the type of the conditional expression by pretending to
7019 // evaluate to RET either way through the conditional.
7020 crash = Expression::make_compound(crash, ret, loc);
7021 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7024 // RET is a pointer to a struct, but we want a function type.
7025 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7027 return ret;
7030 // Dump ast representation of a bound method expression.
7032 void
7033 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7034 const
7036 if (this->expr_type_ != NULL)
7037 ast_dump_context->ostream() << "(";
7038 ast_dump_context->dump_expression(this->expr_);
7039 if (this->expr_type_ != NULL)
7041 ast_dump_context->ostream() << ":";
7042 ast_dump_context->dump_type(this->expr_type_);
7043 ast_dump_context->ostream() << ")";
7046 ast_dump_context->ostream() << "." << this->function_->name();
7049 // Make a method expression.
7051 Bound_method_expression*
7052 Expression::make_bound_method(Expression* expr, const Method* method,
7053 Named_object* function, Location location)
7055 return new Bound_method_expression(expr, method, function, location);
7058 // Class Builtin_call_expression. This is used for a call to a
7059 // builtin function.
7061 class Builtin_call_expression : public Call_expression
7063 public:
7064 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
7065 bool is_varargs, Location location);
7067 protected:
7068 // This overrides Call_expression::do_lower.
7069 Expression*
7070 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7072 Expression*
7073 do_flatten(Gogo*, Named_object*, Statement_inserter*);
7075 bool
7076 do_is_constant() const;
7078 bool
7079 do_numeric_constant_value(Numeric_constant*) const;
7081 bool
7082 do_discarding_value();
7084 Type*
7085 do_type();
7087 void
7088 do_determine_type(const Type_context*);
7090 void
7091 do_check_types(Gogo*);
7093 Expression*
7094 do_copy();
7096 Bexpression*
7097 do_get_backend(Translate_context*);
7099 void
7100 do_export(Export*) const;
7102 virtual bool
7103 do_is_recover_call() const;
7105 virtual void
7106 do_set_recover_arg(Expression*);
7108 private:
7109 // The builtin functions.
7110 enum Builtin_function_code
7112 BUILTIN_INVALID,
7114 // Predeclared builtin functions.
7115 BUILTIN_APPEND,
7116 BUILTIN_CAP,
7117 BUILTIN_CLOSE,
7118 BUILTIN_COMPLEX,
7119 BUILTIN_COPY,
7120 BUILTIN_DELETE,
7121 BUILTIN_IMAG,
7122 BUILTIN_LEN,
7123 BUILTIN_MAKE,
7124 BUILTIN_NEW,
7125 BUILTIN_PANIC,
7126 BUILTIN_PRINT,
7127 BUILTIN_PRINTLN,
7128 BUILTIN_REAL,
7129 BUILTIN_RECOVER,
7131 // Builtin functions from the unsafe package.
7132 BUILTIN_ALIGNOF,
7133 BUILTIN_OFFSETOF,
7134 BUILTIN_SIZEOF
7137 Expression*
7138 one_arg() const;
7140 bool
7141 check_one_arg();
7143 static Type*
7144 real_imag_type(Type*);
7146 static Type*
7147 complex_type(Type*);
7149 Expression*
7150 lower_make(Statement_inserter*);
7152 Expression* flatten_append(Gogo*, Named_object*, Statement_inserter*);
7154 bool
7155 check_int_value(Expression*, bool is_length, bool* small);
7157 // A pointer back to the general IR structure. This avoids a global
7158 // variable, or passing it around everywhere.
7159 Gogo* gogo_;
7160 // The builtin function being called.
7161 Builtin_function_code code_;
7162 // Used to stop endless loops when the length of an array uses len
7163 // or cap of the array itself.
7164 mutable bool seen_;
7165 // Whether the argument is set for calls to BUILTIN_RECOVER.
7166 bool recover_arg_is_set_;
7169 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7170 Expression* fn,
7171 Expression_list* args,
7172 bool is_varargs,
7173 Location location)
7174 : Call_expression(fn, args, is_varargs, location),
7175 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7176 recover_arg_is_set_(false)
7178 Func_expression* fnexp = this->fn()->func_expression();
7179 if (fnexp == NULL)
7181 this->code_ = BUILTIN_INVALID;
7182 return;
7184 const std::string& name(fnexp->named_object()->name());
7185 if (name == "append")
7186 this->code_ = BUILTIN_APPEND;
7187 else if (name == "cap")
7188 this->code_ = BUILTIN_CAP;
7189 else if (name == "close")
7190 this->code_ = BUILTIN_CLOSE;
7191 else if (name == "complex")
7192 this->code_ = BUILTIN_COMPLEX;
7193 else if (name == "copy")
7194 this->code_ = BUILTIN_COPY;
7195 else if (name == "delete")
7196 this->code_ = BUILTIN_DELETE;
7197 else if (name == "imag")
7198 this->code_ = BUILTIN_IMAG;
7199 else if (name == "len")
7200 this->code_ = BUILTIN_LEN;
7201 else if (name == "make")
7202 this->code_ = BUILTIN_MAKE;
7203 else if (name == "new")
7204 this->code_ = BUILTIN_NEW;
7205 else if (name == "panic")
7206 this->code_ = BUILTIN_PANIC;
7207 else if (name == "print")
7208 this->code_ = BUILTIN_PRINT;
7209 else if (name == "println")
7210 this->code_ = BUILTIN_PRINTLN;
7211 else if (name == "real")
7212 this->code_ = BUILTIN_REAL;
7213 else if (name == "recover")
7214 this->code_ = BUILTIN_RECOVER;
7215 else if (name == "Alignof")
7216 this->code_ = BUILTIN_ALIGNOF;
7217 else if (name == "Offsetof")
7218 this->code_ = BUILTIN_OFFSETOF;
7219 else if (name == "Sizeof")
7220 this->code_ = BUILTIN_SIZEOF;
7221 else
7222 go_unreachable();
7225 // Return whether this is a call to recover. This is a virtual
7226 // function called from the parent class.
7228 bool
7229 Builtin_call_expression::do_is_recover_call() const
7231 if (this->classification() == EXPRESSION_ERROR)
7232 return false;
7233 return this->code_ == BUILTIN_RECOVER;
7236 // Set the argument for a call to recover.
7238 void
7239 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7241 const Expression_list* args = this->args();
7242 go_assert(args == NULL || args->empty());
7243 Expression_list* new_args = new Expression_list();
7244 new_args->push_back(arg);
7245 this->set_args(new_args);
7246 this->recover_arg_is_set_ = true;
7249 // Lower a builtin call expression. This turns new and make into
7250 // specific expressions. We also convert to a constant if we can.
7252 Expression*
7253 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7254 Statement_inserter* inserter, int)
7256 if (this->is_error_expression())
7257 return this;
7259 Location loc = this->location();
7261 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7263 this->report_error(_("invalid use of %<...%> with builtin function"));
7264 return Expression::make_error(loc);
7267 if (this->code_ == BUILTIN_OFFSETOF)
7269 Expression* arg = this->one_arg();
7271 if (arg->bound_method_expression() != NULL
7272 || arg->interface_field_reference_expression() != NULL)
7274 this->report_error(_("invalid use of method value as argument "
7275 "of Offsetof"));
7276 return this;
7279 Field_reference_expression* farg = arg->field_reference_expression();
7280 while (farg != NULL)
7282 if (!farg->implicit())
7283 break;
7284 // When the selector refers to an embedded field,
7285 // it must not be reached through pointer indirections.
7286 if (farg->expr()->deref() != farg->expr())
7288 this->report_error(_("argument of Offsetof implies "
7289 "indirection of an embedded field"));
7290 return this;
7292 // Go up until we reach the original base.
7293 farg = farg->expr()->field_reference_expression();
7297 if (this->is_constant())
7299 Numeric_constant nc;
7300 if (this->numeric_constant_value(&nc))
7301 return nc.expression(loc);
7304 switch (this->code_)
7306 default:
7307 break;
7309 case BUILTIN_NEW:
7311 const Expression_list* args = this->args();
7312 if (args == NULL || args->size() < 1)
7313 this->report_error(_("not enough arguments"));
7314 else if (args->size() > 1)
7315 this->report_error(_("too many arguments"));
7316 else
7318 Expression* arg = args->front();
7319 if (!arg->is_type_expression())
7321 go_error_at(arg->location(), "expected type");
7322 this->set_is_error();
7324 else
7325 return Expression::make_allocation(arg->type(), loc);
7328 break;
7330 case BUILTIN_MAKE:
7331 return this->lower_make(inserter);
7333 case BUILTIN_RECOVER:
7334 if (function != NULL)
7335 function->func_value()->set_calls_recover();
7336 else
7338 // Calling recover outside of a function always returns the
7339 // nil empty interface.
7340 Type* eface = Type::make_empty_interface_type(loc);
7341 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7343 break;
7345 case BUILTIN_DELETE:
7347 // Lower to a runtime function call.
7348 const Expression_list* args = this->args();
7349 if (args == NULL || args->size() < 2)
7350 this->report_error(_("not enough arguments"));
7351 else if (args->size() > 2)
7352 this->report_error(_("too many arguments"));
7353 else if (args->front()->type()->map_type() == NULL)
7354 this->report_error(_("argument 1 must be a map"));
7355 else
7357 // Since this function returns no value it must appear in
7358 // a statement by itself, so we don't have to worry about
7359 // order of evaluation of values around it. Evaluate the
7360 // map first to get order of evaluation right.
7361 Map_type* mt = args->front()->type()->map_type();
7362 Temporary_statement* map_temp =
7363 Statement::make_temporary(mt, args->front(), loc);
7364 inserter->insert(map_temp);
7366 Temporary_statement* key_temp =
7367 Statement::make_temporary(mt->key_type(), args->back(), loc);
7368 inserter->insert(key_temp);
7370 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7371 Expression* e2 = Expression::make_temporary_reference(map_temp,
7372 loc);
7373 Expression* e3 = Expression::make_temporary_reference(key_temp,
7374 loc);
7375 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7376 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7377 3, e1, e2, e3);
7380 break;
7382 case BUILTIN_PRINT:
7383 case BUILTIN_PRINTLN:
7384 // Force all the arguments into temporary variables, so that we
7385 // don't try to evaluate something while holding the print lock.
7386 if (this->args() == NULL)
7387 break;
7388 for (Expression_list::iterator pa = this->args()->begin();
7389 pa != this->args()->end();
7390 ++pa)
7392 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7394 Temporary_statement* temp =
7395 Statement::make_temporary(NULL, *pa, loc);
7396 inserter->insert(temp);
7397 *pa = Expression::make_temporary_reference(temp, loc);
7400 break;
7403 return this;
7406 // Flatten a builtin call expression. This turns the arguments of copy and
7407 // append into temporary expressions.
7409 Expression*
7410 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7411 Statement_inserter* inserter)
7413 Location loc = this->location();
7415 switch (this->code_)
7417 default:
7418 break;
7420 case BUILTIN_APPEND:
7421 return this->flatten_append(gogo, function, inserter);
7423 case BUILTIN_COPY:
7425 Type* at = this->args()->front()->type();
7426 for (Expression_list::iterator pa = this->args()->begin();
7427 pa != this->args()->end();
7428 ++pa)
7430 if ((*pa)->is_nil_expression())
7432 Expression* nil = Expression::make_nil(loc);
7433 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7434 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7436 if (!(*pa)->is_variable())
7438 Temporary_statement* temp =
7439 Statement::make_temporary(NULL, *pa, loc);
7440 inserter->insert(temp);
7441 *pa = Expression::make_temporary_reference(temp, loc);
7445 break;
7447 case BUILTIN_PANIC:
7448 for (Expression_list::iterator pa = this->args()->begin();
7449 pa != this->args()->end();
7450 ++pa)
7452 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7454 Temporary_statement* temp =
7455 Statement::make_temporary(NULL, *pa, loc);
7456 inserter->insert(temp);
7457 *pa = Expression::make_temporary_reference(temp, loc);
7460 break;
7462 case BUILTIN_LEN:
7463 case BUILTIN_CAP:
7465 Expression_list::iterator pa = this->args()->begin();
7466 if (!(*pa)->is_variable()
7467 && ((*pa)->type()->map_type() != NULL
7468 || (*pa)->type()->channel_type() != NULL))
7470 Temporary_statement* temp =
7471 Statement::make_temporary(NULL, *pa, loc);
7472 inserter->insert(temp);
7473 *pa = Expression::make_temporary_reference(temp, loc);
7476 break;
7479 return this;
7482 // Lower a make expression.
7484 Expression*
7485 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7487 Location loc = this->location();
7489 const Expression_list* args = this->args();
7490 if (args == NULL || args->size() < 1)
7492 this->report_error(_("not enough arguments"));
7493 return Expression::make_error(this->location());
7496 Expression_list::const_iterator parg = args->begin();
7498 Expression* first_arg = *parg;
7499 if (!first_arg->is_type_expression())
7501 go_error_at(first_arg->location(), "expected type");
7502 this->set_is_error();
7503 return Expression::make_error(this->location());
7505 Type* type = first_arg->type();
7507 if (!type->in_heap())
7508 go_error_at(first_arg->location(),
7509 "can't make slice of go:notinheap type");
7511 bool is_slice = false;
7512 bool is_map = false;
7513 bool is_chan = false;
7514 if (type->is_slice_type())
7515 is_slice = true;
7516 else if (type->map_type() != NULL)
7517 is_map = true;
7518 else if (type->channel_type() != NULL)
7519 is_chan = true;
7520 else
7522 this->report_error(_("invalid type for make function"));
7523 return Expression::make_error(this->location());
7526 Type_context int_context(Type::lookup_integer_type("int"), false);
7528 ++parg;
7529 Expression* len_arg;
7530 bool len_small = false;
7531 if (parg == args->end())
7533 if (is_slice)
7535 this->report_error(_("length required when allocating a slice"));
7536 return Expression::make_error(this->location());
7538 len_arg = Expression::make_integer_ul(0, NULL, loc);
7540 else
7542 len_arg = *parg;
7543 len_arg->determine_type(&int_context);
7544 if (!this->check_int_value(len_arg, true, &len_small))
7545 return Expression::make_error(this->location());
7546 ++parg;
7549 Expression* cap_arg = NULL;
7550 bool cap_small = false;
7551 if (is_slice && parg != args->end())
7553 cap_arg = *parg;
7554 cap_arg->determine_type(&int_context);
7555 if (!this->check_int_value(cap_arg, false, &cap_small))
7556 return Expression::make_error(this->location());
7558 Numeric_constant nclen;
7559 Numeric_constant nccap;
7560 unsigned long vlen;
7561 unsigned long vcap;
7562 if (len_arg->numeric_constant_value(&nclen)
7563 && cap_arg->numeric_constant_value(&nccap)
7564 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7565 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7566 && vlen > vcap)
7568 this->report_error(_("len larger than cap"));
7569 return Expression::make_error(this->location());
7572 ++parg;
7575 if (parg != args->end())
7577 this->report_error(_("too many arguments to make"));
7578 return Expression::make_error(this->location());
7581 Location type_loc = first_arg->location();
7583 Expression* call;
7584 if (is_slice)
7586 Type* et = type->array_type()->element_type();
7587 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7588 if (cap_arg == NULL)
7590 Temporary_statement* temp = Statement::make_temporary(NULL,
7591 len_arg,
7592 loc);
7593 inserter->insert(temp);
7594 len_arg = Expression::make_temporary_reference(temp, loc);
7595 cap_arg = Expression::make_temporary_reference(temp, loc);
7596 cap_small = len_small;
7599 Runtime::Function code = Runtime::MAKESLICE;
7600 if (!len_small || !cap_small)
7601 code = Runtime::MAKESLICE64;
7602 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7604 else if (is_map)
7606 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7607 call = Runtime::make_call(Runtime::MAKEMAP, loc, 4, type_arg, len_arg,
7608 Expression::make_nil(loc),
7609 Expression::make_nil(loc));
7611 else if (is_chan)
7613 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7614 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7616 else
7617 go_unreachable();
7619 return Expression::make_unsafe_cast(type, call, loc);
7622 // Flatten a call to the predeclared append function. We do this in
7623 // the flatten phase, not the lowering phase, so that we run after
7624 // type checking and after order_evaluations.
7626 Expression*
7627 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7628 Statement_inserter* inserter)
7630 if (this->is_error_expression())
7631 return this;
7633 Location loc = this->location();
7635 const Expression_list* args = this->args();
7636 go_assert(args != NULL && !args->empty());
7638 Type* slice_type = args->front()->type();
7639 go_assert(slice_type->is_slice_type());
7640 Type* element_type = slice_type->array_type()->element_type();
7642 if (args->size() == 1)
7644 // append(s) evaluates to s.
7645 return args->front();
7648 Type* int_type = Type::lookup_integer_type("int");
7649 Type* uint_type = Type::lookup_integer_type("uint");
7651 // Implementing
7652 // append(s1, s2...)
7653 // or
7654 // append(s1, a1, a2, a3, ...)
7656 // s1tmp := s1
7657 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7658 loc);
7659 inserter->insert(s1tmp);
7661 // l1tmp := len(s1tmp)
7662 Named_object* lenfn = gogo->lookup_global("len");
7663 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7664 Expression_list* call_args = new Expression_list();
7665 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7666 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7667 gogo->lower_expression(function, inserter, &len);
7668 gogo->flatten_expression(function, inserter, &len);
7669 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7670 inserter->insert(l1tmp);
7672 Temporary_statement* s2tmp = NULL;
7673 Temporary_statement* l2tmp = NULL;
7674 Expression_list* add = NULL;
7675 Expression* len2;
7676 if (this->is_varargs())
7678 go_assert(args->size() == 2);
7680 // s2tmp := s2
7681 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7682 inserter->insert(s2tmp);
7684 // l2tmp := len(s2tmp)
7685 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7686 call_args = new Expression_list();
7687 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7688 len = Expression::make_call(lenref, call_args, false, loc);
7689 gogo->lower_expression(function, inserter, &len);
7690 gogo->flatten_expression(function, inserter, &len);
7691 l2tmp = Statement::make_temporary(int_type, len, loc);
7692 inserter->insert(l2tmp);
7694 // len2 = l2tmp
7695 len2 = Expression::make_temporary_reference(l2tmp, loc);
7697 else
7699 // We have to ensure that all the arguments are in variables
7700 // now, because otherwise if one of them is an index expression
7701 // into the current slice we could overwrite it before we fetch
7702 // it.
7703 add = new Expression_list();
7704 Expression_list::const_iterator pa = args->begin();
7705 for (++pa; pa != args->end(); ++pa)
7707 if ((*pa)->is_variable())
7708 add->push_back(*pa);
7709 else
7711 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7712 loc);
7713 inserter->insert(tmp);
7714 add->push_back(Expression::make_temporary_reference(tmp, loc));
7718 // len2 = len(add)
7719 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7722 // ntmp := l1tmp + len2
7723 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7724 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7725 gogo->lower_expression(function, inserter, &sum);
7726 gogo->flatten_expression(function, inserter, &sum);
7727 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7728 inserter->insert(ntmp);
7730 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7731 // growslice(type, s1tmp, ntmp) :
7732 // s1tmp[:ntmp]
7733 // Using uint here means that if the computation of ntmp overflowed,
7734 // we will call growslice which will panic.
7736 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7737 left = Expression::make_cast(uint_type, left, loc);
7739 Named_object* capfn = gogo->lookup_global("cap");
7740 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7741 call_args = new Expression_list();
7742 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7743 Expression* right = Expression::make_call(capref, call_args, false, loc);
7744 right = Expression::make_cast(uint_type, right, loc);
7746 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7748 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7749 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7750 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7751 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7752 a1, a2, a3);
7753 call = Expression::make_unsafe_cast(slice_type, call, loc);
7755 ref = Expression::make_temporary_reference(s1tmp, loc);
7756 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7757 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7758 // FIXME: Mark this index as not requiring bounds checks.
7759 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7761 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7763 gogo->lower_expression(function, inserter, &rhs);
7764 gogo->flatten_expression(function, inserter, &rhs);
7766 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7767 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7768 inserter->insert(assign);
7770 if (this->is_varargs())
7772 // copy(s1tmp[l1tmp:], s2tmp)
7773 a1 = Expression::make_temporary_reference(s1tmp, loc);
7774 ref = Expression::make_temporary_reference(l1tmp, loc);
7775 Expression* nil = Expression::make_nil(loc);
7776 // FIXME: Mark this index as not requiring bounds checks.
7777 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7779 a2 = Expression::make_temporary_reference(s2tmp, loc);
7781 Named_object* copyfn = gogo->lookup_global("copy");
7782 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7783 call_args = new Expression_list();
7784 call_args->push_back(a1);
7785 call_args->push_back(a2);
7786 call = Expression::make_call(copyref, call_args, false, loc);
7787 gogo->lower_expression(function, inserter, &call);
7788 gogo->flatten_expression(function, inserter, &call);
7789 inserter->insert(Statement::make_statement(call, false));
7791 else
7793 // For each argument:
7794 // s1tmp[l1tmp+i] = a
7795 unsigned long i = 0;
7796 for (Expression_list::const_iterator pa = add->begin();
7797 pa != add->end();
7798 ++pa, ++i)
7800 ref = Expression::make_temporary_reference(s1tmp, loc);
7801 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7802 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7803 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7804 // FIXME: Mark this index as not requiring bounds checks.
7805 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7806 gogo->lower_expression(function, inserter, &lhs);
7807 gogo->flatten_expression(function, inserter, &lhs);
7808 // The flatten pass runs after the write barrier pass, so we
7809 // need to insert a write barrier here if necessary.
7810 if (!gogo->assign_needs_write_barrier(lhs))
7811 assign = Statement::make_assignment(lhs, *pa, loc);
7812 else
7814 Function* f = function == NULL ? NULL : function->func_value();
7815 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7816 lhs, *pa, loc);
7818 inserter->insert(assign);
7822 return Expression::make_temporary_reference(s1tmp, loc);
7825 // Return whether an expression has an integer value. Report an error
7826 // if not. This is used when handling calls to the predeclared make
7827 // function. Set *SMALL if the value is known to fit in type "int".
7829 bool
7830 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7831 bool *small)
7833 *small = false;
7835 Numeric_constant nc;
7836 if (e->numeric_constant_value(&nc))
7838 unsigned long v;
7839 switch (nc.to_unsigned_long(&v))
7841 case Numeric_constant::NC_UL_VALID:
7842 break;
7843 case Numeric_constant::NC_UL_NOTINT:
7844 go_error_at(e->location(), "non-integer %s argument to make",
7845 is_length ? "len" : "cap");
7846 return false;
7847 case Numeric_constant::NC_UL_NEGATIVE:
7848 go_error_at(e->location(), "negative %s argument to make",
7849 is_length ? "len" : "cap");
7850 return false;
7851 case Numeric_constant::NC_UL_BIG:
7852 // We don't want to give a compile-time error for a 64-bit
7853 // value on a 32-bit target.
7854 break;
7857 mpz_t val;
7858 if (!nc.to_int(&val))
7859 go_unreachable();
7860 int bits = mpz_sizeinbase(val, 2);
7861 mpz_clear(val);
7862 Type* int_type = Type::lookup_integer_type("int");
7863 if (bits >= int_type->integer_type()->bits())
7865 go_error_at(e->location(), "%s argument too large for make",
7866 is_length ? "len" : "cap");
7867 return false;
7870 *small = true;
7871 return true;
7874 if (e->type()->integer_type() != NULL)
7876 int ebits = e->type()->integer_type()->bits();
7877 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7879 // We can treat ebits == intbits as small even for an unsigned
7880 // integer type, because we will convert the value to int and
7881 // then reject it in the runtime if it is negative.
7882 *small = ebits <= intbits;
7884 return true;
7887 go_error_at(e->location(), "non-integer %s argument to make",
7888 is_length ? "len" : "cap");
7889 return false;
7892 // Return the type of the real or imag functions, given the type of
7893 // the argument. We need to map complex64 to float32 and complex128
7894 // to float64, so it has to be done by name. This returns NULL if it
7895 // can't figure out the type.
7897 Type*
7898 Builtin_call_expression::real_imag_type(Type* arg_type)
7900 if (arg_type == NULL || arg_type->is_abstract())
7901 return NULL;
7902 Named_type* nt = arg_type->named_type();
7903 if (nt == NULL)
7904 return NULL;
7905 while (nt->real_type()->named_type() != NULL)
7906 nt = nt->real_type()->named_type();
7907 if (nt->name() == "complex64")
7908 return Type::lookup_float_type("float32");
7909 else if (nt->name() == "complex128")
7910 return Type::lookup_float_type("float64");
7911 else
7912 return NULL;
7915 // Return the type of the complex function, given the type of one of the
7916 // argments. Like real_imag_type, we have to map by name.
7918 Type*
7919 Builtin_call_expression::complex_type(Type* arg_type)
7921 if (arg_type == NULL || arg_type->is_abstract())
7922 return NULL;
7923 Named_type* nt = arg_type->named_type();
7924 if (nt == NULL)
7925 return NULL;
7926 while (nt->real_type()->named_type() != NULL)
7927 nt = nt->real_type()->named_type();
7928 if (nt->name() == "float32")
7929 return Type::lookup_complex_type("complex64");
7930 else if (nt->name() == "float64")
7931 return Type::lookup_complex_type("complex128");
7932 else
7933 return NULL;
7936 // Return a single argument, or NULL if there isn't one.
7938 Expression*
7939 Builtin_call_expression::one_arg() const
7941 const Expression_list* args = this->args();
7942 if (args == NULL || args->size() != 1)
7943 return NULL;
7944 return args->front();
7947 // A traversal class which looks for a call or receive expression.
7949 class Find_call_expression : public Traverse
7951 public:
7952 Find_call_expression()
7953 : Traverse(traverse_expressions),
7954 found_(false)
7958 expression(Expression**);
7960 bool
7961 found()
7962 { return this->found_; }
7964 private:
7965 bool found_;
7969 Find_call_expression::expression(Expression** pexpr)
7971 if ((*pexpr)->call_expression() != NULL
7972 || (*pexpr)->receive_expression() != NULL)
7974 this->found_ = true;
7975 return TRAVERSE_EXIT;
7977 return TRAVERSE_CONTINUE;
7980 // Return whether this is constant: len of a string constant, or len
7981 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7982 // unsafe.Alignof.
7984 bool
7985 Builtin_call_expression::do_is_constant() const
7987 if (this->is_error_expression())
7988 return true;
7989 switch (this->code_)
7991 case BUILTIN_LEN:
7992 case BUILTIN_CAP:
7994 if (this->seen_)
7995 return false;
7997 Expression* arg = this->one_arg();
7998 if (arg == NULL)
7999 return false;
8000 Type* arg_type = arg->type();
8002 if (arg_type->points_to() != NULL
8003 && arg_type->points_to()->array_type() != NULL
8004 && !arg_type->points_to()->is_slice_type())
8005 arg_type = arg_type->points_to();
8007 // The len and cap functions are only constant if there are no
8008 // function calls or channel operations in the arguments.
8009 // Otherwise we have to make the call.
8010 if (!arg->is_constant())
8012 Find_call_expression find_call;
8013 Expression::traverse(&arg, &find_call);
8014 if (find_call.found())
8015 return false;
8018 if (arg_type->array_type() != NULL
8019 && arg_type->array_type()->length() != NULL)
8020 return true;
8022 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8024 this->seen_ = true;
8025 bool ret = arg->is_constant();
8026 this->seen_ = false;
8027 return ret;
8030 break;
8032 case BUILTIN_SIZEOF:
8033 case BUILTIN_ALIGNOF:
8034 return this->one_arg() != NULL;
8036 case BUILTIN_OFFSETOF:
8038 Expression* arg = this->one_arg();
8039 if (arg == NULL)
8040 return false;
8041 return arg->field_reference_expression() != NULL;
8044 case BUILTIN_COMPLEX:
8046 const Expression_list* args = this->args();
8047 if (args != NULL && args->size() == 2)
8048 return args->front()->is_constant() && args->back()->is_constant();
8050 break;
8052 case BUILTIN_REAL:
8053 case BUILTIN_IMAG:
8055 Expression* arg = this->one_arg();
8056 return arg != NULL && arg->is_constant();
8059 default:
8060 break;
8063 return false;
8066 // Return a numeric constant if possible.
8068 bool
8069 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8071 if (this->code_ == BUILTIN_LEN
8072 || this->code_ == BUILTIN_CAP)
8074 Expression* arg = this->one_arg();
8075 if (arg == NULL)
8076 return false;
8077 Type* arg_type = arg->type();
8079 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8081 std::string sval;
8082 if (arg->string_constant_value(&sval))
8084 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8085 sval.length());
8086 return true;
8090 if (arg_type->points_to() != NULL
8091 && arg_type->points_to()->array_type() != NULL
8092 && !arg_type->points_to()->is_slice_type())
8093 arg_type = arg_type->points_to();
8095 if (arg_type->array_type() != NULL
8096 && arg_type->array_type()->length() != NULL)
8098 if (this->seen_)
8099 return false;
8100 Expression* e = arg_type->array_type()->length();
8101 this->seen_ = true;
8102 bool r = e->numeric_constant_value(nc);
8103 this->seen_ = false;
8104 if (r)
8106 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8107 this->location()))
8108 r = false;
8110 return r;
8113 else if (this->code_ == BUILTIN_SIZEOF
8114 || this->code_ == BUILTIN_ALIGNOF)
8116 Expression* arg = this->one_arg();
8117 if (arg == NULL)
8118 return false;
8119 Type* arg_type = arg->type();
8120 if (arg_type->is_error())
8121 return false;
8122 if (arg_type->is_abstract())
8123 return false;
8124 if (this->seen_)
8125 return false;
8127 int64_t ret;
8128 if (this->code_ == BUILTIN_SIZEOF)
8130 this->seen_ = true;
8131 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8132 this->seen_ = false;
8133 if (!ok)
8134 return false;
8136 else if (this->code_ == BUILTIN_ALIGNOF)
8138 bool ok;
8139 this->seen_ = true;
8140 if (arg->field_reference_expression() == NULL)
8141 ok = arg_type->backend_type_align(this->gogo_, &ret);
8142 else
8144 // Calling unsafe.Alignof(s.f) returns the alignment of
8145 // the type of f when it is used as a field in a struct.
8146 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8148 this->seen_ = false;
8149 if (!ok)
8150 return false;
8152 else
8153 go_unreachable();
8155 mpz_t zval;
8156 set_mpz_from_int64(&zval, ret);
8157 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8158 mpz_clear(zval);
8159 return true;
8161 else if (this->code_ == BUILTIN_OFFSETOF)
8163 Expression* arg = this->one_arg();
8164 if (arg == NULL)
8165 return false;
8166 Field_reference_expression* farg = arg->field_reference_expression();
8167 if (farg == NULL)
8168 return false;
8169 if (this->seen_)
8170 return false;
8172 int64_t total_offset = 0;
8173 while (true)
8175 Expression* struct_expr = farg->expr();
8176 Type* st = struct_expr->type();
8177 if (st->struct_type() == NULL)
8178 return false;
8179 if (st->named_type() != NULL)
8180 st->named_type()->convert(this->gogo_);
8181 int64_t offset;
8182 this->seen_ = true;
8183 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8184 farg->field_index(),
8185 &offset);
8186 this->seen_ = false;
8187 if (!ok)
8188 return false;
8189 total_offset += offset;
8190 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8192 // Go up until we reach the original base.
8193 farg = struct_expr->field_reference_expression();
8194 continue;
8196 break;
8198 mpz_t zval;
8199 set_mpz_from_int64(&zval, total_offset);
8200 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8201 mpz_clear(zval);
8202 return true;
8204 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8206 Expression* arg = this->one_arg();
8207 if (arg == NULL)
8208 return false;
8210 Numeric_constant argnc;
8211 if (!arg->numeric_constant_value(&argnc))
8212 return false;
8214 mpc_t val;
8215 if (!argnc.to_complex(&val))
8216 return false;
8218 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8219 if (this->code_ == BUILTIN_REAL)
8220 nc->set_float(type, mpc_realref(val));
8221 else
8222 nc->set_float(type, mpc_imagref(val));
8223 mpc_clear(val);
8224 return true;
8226 else if (this->code_ == BUILTIN_COMPLEX)
8228 const Expression_list* args = this->args();
8229 if (args == NULL || args->size() != 2)
8230 return false;
8232 Numeric_constant rnc;
8233 if (!args->front()->numeric_constant_value(&rnc))
8234 return false;
8235 Numeric_constant inc;
8236 if (!args->back()->numeric_constant_value(&inc))
8237 return false;
8239 if (rnc.type() != NULL
8240 && !rnc.type()->is_abstract()
8241 && inc.type() != NULL
8242 && !inc.type()->is_abstract()
8243 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8244 return false;
8246 mpfr_t r;
8247 if (!rnc.to_float(&r))
8248 return false;
8249 mpfr_t i;
8250 if (!inc.to_float(&i))
8252 mpfr_clear(r);
8253 return false;
8256 Type* arg_type = rnc.type();
8257 if (arg_type == NULL || arg_type->is_abstract())
8258 arg_type = inc.type();
8260 mpc_t val;
8261 mpc_init2(val, mpc_precision);
8262 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8263 mpfr_clear(r);
8264 mpfr_clear(i);
8266 Type* type = Builtin_call_expression::complex_type(arg_type);
8267 nc->set_complex(type, val);
8269 mpc_clear(val);
8271 return true;
8274 return false;
8277 // Give an error if we are discarding the value of an expression which
8278 // should not normally be discarded. We don't give an error for
8279 // discarding the value of an ordinary function call, but we do for
8280 // builtin functions, purely for consistency with the gc compiler.
8282 bool
8283 Builtin_call_expression::do_discarding_value()
8285 switch (this->code_)
8287 case BUILTIN_INVALID:
8288 default:
8289 go_unreachable();
8291 case BUILTIN_APPEND:
8292 case BUILTIN_CAP:
8293 case BUILTIN_COMPLEX:
8294 case BUILTIN_IMAG:
8295 case BUILTIN_LEN:
8296 case BUILTIN_MAKE:
8297 case BUILTIN_NEW:
8298 case BUILTIN_REAL:
8299 case BUILTIN_ALIGNOF:
8300 case BUILTIN_OFFSETOF:
8301 case BUILTIN_SIZEOF:
8302 this->unused_value_error();
8303 return false;
8305 case BUILTIN_CLOSE:
8306 case BUILTIN_COPY:
8307 case BUILTIN_DELETE:
8308 case BUILTIN_PANIC:
8309 case BUILTIN_PRINT:
8310 case BUILTIN_PRINTLN:
8311 case BUILTIN_RECOVER:
8312 return true;
8316 // Return the type.
8318 Type*
8319 Builtin_call_expression::do_type()
8321 if (this->is_error_expression())
8322 return Type::make_error_type();
8323 switch (this->code_)
8325 case BUILTIN_INVALID:
8326 default:
8327 return Type::make_error_type();
8329 case BUILTIN_NEW:
8330 case BUILTIN_MAKE:
8332 const Expression_list* args = this->args();
8333 if (args == NULL || args->empty())
8334 return Type::make_error_type();
8335 return Type::make_pointer_type(args->front()->type());
8338 case BUILTIN_CAP:
8339 case BUILTIN_COPY:
8340 case BUILTIN_LEN:
8341 return Type::lookup_integer_type("int");
8343 case BUILTIN_ALIGNOF:
8344 case BUILTIN_OFFSETOF:
8345 case BUILTIN_SIZEOF:
8346 return Type::lookup_integer_type("uintptr");
8348 case BUILTIN_CLOSE:
8349 case BUILTIN_DELETE:
8350 case BUILTIN_PANIC:
8351 case BUILTIN_PRINT:
8352 case BUILTIN_PRINTLN:
8353 return Type::make_void_type();
8355 case BUILTIN_RECOVER:
8356 return Type::make_empty_interface_type(Linemap::predeclared_location());
8358 case BUILTIN_APPEND:
8360 const Expression_list* args = this->args();
8361 if (args == NULL || args->empty())
8362 return Type::make_error_type();
8363 Type *ret = args->front()->type();
8364 if (!ret->is_slice_type())
8365 return Type::make_error_type();
8366 return ret;
8369 case BUILTIN_REAL:
8370 case BUILTIN_IMAG:
8372 Expression* arg = this->one_arg();
8373 if (arg == NULL)
8374 return Type::make_error_type();
8375 Type* t = arg->type();
8376 if (t->is_abstract())
8377 t = t->make_non_abstract_type();
8378 t = Builtin_call_expression::real_imag_type(t);
8379 if (t == NULL)
8380 t = Type::make_error_type();
8381 return t;
8384 case BUILTIN_COMPLEX:
8386 const Expression_list* args = this->args();
8387 if (args == NULL || args->size() != 2)
8388 return Type::make_error_type();
8389 Type* t = args->front()->type();
8390 if (t->is_abstract())
8392 t = args->back()->type();
8393 if (t->is_abstract())
8394 t = t->make_non_abstract_type();
8396 t = Builtin_call_expression::complex_type(t);
8397 if (t == NULL)
8398 t = Type::make_error_type();
8399 return t;
8404 // Determine the type.
8406 void
8407 Builtin_call_expression::do_determine_type(const Type_context* context)
8409 if (!this->determining_types())
8410 return;
8412 this->fn()->determine_type_no_context();
8414 const Expression_list* args = this->args();
8416 bool is_print;
8417 Type* arg_type = NULL;
8418 Type* trailing_arg_types = NULL;
8419 switch (this->code_)
8421 case BUILTIN_PRINT:
8422 case BUILTIN_PRINTLN:
8423 // Do not force a large integer constant to "int".
8424 is_print = true;
8425 break;
8427 case BUILTIN_REAL:
8428 case BUILTIN_IMAG:
8429 arg_type = Builtin_call_expression::complex_type(context->type);
8430 if (arg_type == NULL)
8431 arg_type = Type::lookup_complex_type("complex128");
8432 is_print = false;
8433 break;
8435 case BUILTIN_COMPLEX:
8437 // For the complex function the type of one operand can
8438 // determine the type of the other, as in a binary expression.
8439 arg_type = Builtin_call_expression::real_imag_type(context->type);
8440 if (arg_type == NULL)
8441 arg_type = Type::lookup_float_type("float64");
8442 if (args != NULL && args->size() == 2)
8444 Type* t1 = args->front()->type();
8445 Type* t2 = args->back()->type();
8446 if (!t1->is_abstract())
8447 arg_type = t1;
8448 else if (!t2->is_abstract())
8449 arg_type = t2;
8451 is_print = false;
8453 break;
8455 case BUILTIN_APPEND:
8456 if (!this->is_varargs()
8457 && args != NULL
8458 && !args->empty()
8459 && args->front()->type()->is_slice_type())
8460 trailing_arg_types =
8461 args->front()->type()->array_type()->element_type();
8462 is_print = false;
8463 break;
8465 default:
8466 is_print = false;
8467 break;
8470 if (args != NULL)
8472 for (Expression_list::const_iterator pa = args->begin();
8473 pa != args->end();
8474 ++pa)
8476 Type_context subcontext;
8477 subcontext.type = arg_type;
8479 if (is_print)
8481 // We want to print large constants, we so can't just
8482 // use the appropriate nonabstract type. Use uint64 for
8483 // an integer if we know it is nonnegative, otherwise
8484 // use int64 for a integer, otherwise use float64 for a
8485 // float or complex128 for a complex.
8486 Type* want_type = NULL;
8487 Type* atype = (*pa)->type();
8488 if (atype->is_abstract())
8490 if (atype->integer_type() != NULL)
8492 Numeric_constant nc;
8493 if (this->numeric_constant_value(&nc))
8495 mpz_t val;
8496 if (nc.to_int(&val))
8498 if (mpz_sgn(val) >= 0)
8499 want_type = Type::lookup_integer_type("uint64");
8500 mpz_clear(val);
8503 if (want_type == NULL)
8504 want_type = Type::lookup_integer_type("int64");
8506 else if (atype->float_type() != NULL)
8507 want_type = Type::lookup_float_type("float64");
8508 else if (atype->complex_type() != NULL)
8509 want_type = Type::lookup_complex_type("complex128");
8510 else if (atype->is_abstract_string_type())
8511 want_type = Type::lookup_string_type();
8512 else if (atype->is_abstract_boolean_type())
8513 want_type = Type::lookup_bool_type();
8514 else
8515 go_unreachable();
8516 subcontext.type = want_type;
8520 (*pa)->determine_type(&subcontext);
8522 if (trailing_arg_types != NULL)
8524 arg_type = trailing_arg_types;
8525 trailing_arg_types = NULL;
8531 // If there is exactly one argument, return true. Otherwise give an
8532 // error message and return false.
8534 bool
8535 Builtin_call_expression::check_one_arg()
8537 const Expression_list* args = this->args();
8538 if (args == NULL || args->size() < 1)
8540 this->report_error(_("not enough arguments"));
8541 return false;
8543 else if (args->size() > 1)
8545 this->report_error(_("too many arguments"));
8546 return false;
8548 if (args->front()->is_error_expression()
8549 || args->front()->type()->is_error())
8551 this->set_is_error();
8552 return false;
8554 return true;
8557 // Check argument types for a builtin function.
8559 void
8560 Builtin_call_expression::do_check_types(Gogo*)
8562 if (this->is_error_expression())
8563 return;
8564 switch (this->code_)
8566 case BUILTIN_INVALID:
8567 case BUILTIN_NEW:
8568 case BUILTIN_MAKE:
8569 case BUILTIN_DELETE:
8570 return;
8572 case BUILTIN_LEN:
8573 case BUILTIN_CAP:
8575 // The single argument may be either a string or an array or a
8576 // map or a channel, or a pointer to a closed array.
8577 if (this->check_one_arg())
8579 Type* arg_type = this->one_arg()->type();
8580 if (arg_type->points_to() != NULL
8581 && arg_type->points_to()->array_type() != NULL
8582 && !arg_type->points_to()->is_slice_type())
8583 arg_type = arg_type->points_to();
8584 if (this->code_ == BUILTIN_CAP)
8586 if (!arg_type->is_error()
8587 && arg_type->array_type() == NULL
8588 && arg_type->channel_type() == NULL)
8589 this->report_error(_("argument must be array or slice "
8590 "or channel"));
8592 else
8594 if (!arg_type->is_error()
8595 && !arg_type->is_string_type()
8596 && arg_type->array_type() == NULL
8597 && arg_type->map_type() == NULL
8598 && arg_type->channel_type() == NULL)
8599 this->report_error(_("argument must be string or "
8600 "array or slice or map or channel"));
8604 break;
8606 case BUILTIN_PRINT:
8607 case BUILTIN_PRINTLN:
8609 const Expression_list* args = this->args();
8610 if (args == NULL)
8612 if (this->code_ == BUILTIN_PRINT)
8613 go_warning_at(this->location(), 0,
8614 "no arguments for builtin function %<%s%>",
8615 (this->code_ == BUILTIN_PRINT
8616 ? "print"
8617 : "println"));
8619 else
8621 for (Expression_list::const_iterator p = args->begin();
8622 p != args->end();
8623 ++p)
8625 Type* type = (*p)->type();
8626 if (type->is_error()
8627 || type->is_string_type()
8628 || type->integer_type() != NULL
8629 || type->float_type() != NULL
8630 || type->complex_type() != NULL
8631 || type->is_boolean_type()
8632 || type->points_to() != NULL
8633 || type->interface_type() != NULL
8634 || type->channel_type() != NULL
8635 || type->map_type() != NULL
8636 || type->function_type() != NULL
8637 || type->is_slice_type())
8639 else if ((*p)->is_type_expression())
8641 // If this is a type expression it's going to give
8642 // an error anyhow, so we don't need one here.
8644 else
8645 this->report_error(_("unsupported argument type to "
8646 "builtin function"));
8650 break;
8652 case BUILTIN_CLOSE:
8653 if (this->check_one_arg())
8655 if (this->one_arg()->type()->channel_type() == NULL)
8656 this->report_error(_("argument must be channel"));
8657 else if (!this->one_arg()->type()->channel_type()->may_send())
8658 this->report_error(_("cannot close receive-only channel"));
8660 break;
8662 case BUILTIN_PANIC:
8663 case BUILTIN_SIZEOF:
8664 case BUILTIN_ALIGNOF:
8665 this->check_one_arg();
8666 break;
8668 case BUILTIN_RECOVER:
8669 if (this->args() != NULL
8670 && !this->args()->empty()
8671 && !this->recover_arg_is_set_)
8672 this->report_error(_("too many arguments"));
8673 break;
8675 case BUILTIN_OFFSETOF:
8676 if (this->check_one_arg())
8678 Expression* arg = this->one_arg();
8679 if (arg->field_reference_expression() == NULL)
8680 this->report_error(_("argument must be a field reference"));
8682 break;
8684 case BUILTIN_COPY:
8686 const Expression_list* args = this->args();
8687 if (args == NULL || args->size() < 2)
8689 this->report_error(_("not enough arguments"));
8690 break;
8692 else if (args->size() > 2)
8694 this->report_error(_("too many arguments"));
8695 break;
8697 Type* arg1_type = args->front()->type();
8698 Type* arg2_type = args->back()->type();
8699 if (arg1_type->is_error() || arg2_type->is_error())
8701 this->set_is_error();
8702 break;
8705 Type* e1;
8706 if (arg1_type->is_slice_type())
8707 e1 = arg1_type->array_type()->element_type();
8708 else
8710 this->report_error(_("left argument must be a slice"));
8711 break;
8714 if (arg2_type->is_slice_type())
8716 Type* e2 = arg2_type->array_type()->element_type();
8717 if (!Type::are_identical(e1, e2, true, NULL))
8718 this->report_error(_("element types must be the same"));
8720 else if (arg2_type->is_string_type())
8722 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8723 this->report_error(_("first argument must be []byte"));
8725 else
8726 this->report_error(_("second argument must be slice or string"));
8728 break;
8730 case BUILTIN_APPEND:
8732 const Expression_list* args = this->args();
8733 if (args == NULL || args->empty())
8735 this->report_error(_("not enough arguments"));
8736 break;
8739 Type* slice_type = args->front()->type();
8740 if (!slice_type->is_slice_type())
8742 if (slice_type->is_error_type())
8743 break;
8744 if (slice_type->is_nil_type())
8745 go_error_at(args->front()->location(), "use of untyped nil");
8746 else
8747 go_error_at(args->front()->location(),
8748 "argument 1 must be a slice");
8749 this->set_is_error();
8750 break;
8753 Type* element_type = slice_type->array_type()->element_type();
8754 if (!element_type->in_heap())
8755 go_error_at(args->front()->location(),
8756 "can't append to slice of go:notinheap type");
8757 if (this->is_varargs())
8759 if (!args->back()->type()->is_slice_type()
8760 && !args->back()->type()->is_string_type())
8762 go_error_at(args->back()->location(),
8763 "invalid use of %<...%> with non-slice/non-string");
8764 this->set_is_error();
8765 break;
8768 if (args->size() < 2)
8770 this->report_error(_("not enough arguments"));
8771 break;
8773 if (args->size() > 2)
8775 this->report_error(_("too many arguments"));
8776 break;
8779 if (args->back()->type()->is_string_type()
8780 && element_type->integer_type() != NULL
8781 && element_type->integer_type()->is_byte())
8783 // Permit append(s1, s2...) when s1 is a slice of
8784 // bytes and s2 is a string type.
8786 else
8788 // We have to test for assignment compatibility to a
8789 // slice of the element type, which is not necessarily
8790 // the same as the type of the first argument: the
8791 // first argument might have a named type.
8792 Type* check_type = Type::make_array_type(element_type, NULL);
8793 std::string reason;
8794 if (!Type::are_assignable(check_type, args->back()->type(),
8795 &reason))
8797 if (reason.empty())
8798 go_error_at(args->back()->location(),
8799 "argument 2 has invalid type");
8800 else
8801 go_error_at(args->back()->location(),
8802 "argument 2 has invalid type (%s)",
8803 reason.c_str());
8804 this->set_is_error();
8805 break;
8809 else
8811 Expression_list::const_iterator pa = args->begin();
8812 int i = 2;
8813 for (++pa; pa != args->end(); ++pa, ++i)
8815 std::string reason;
8816 if (!Type::are_assignable(element_type, (*pa)->type(),
8817 &reason))
8819 if (reason.empty())
8820 go_error_at((*pa)->location(),
8821 "argument %d has incompatible type", i);
8822 else
8823 go_error_at((*pa)->location(),
8824 "argument %d has incompatible type (%s)",
8825 i, reason.c_str());
8826 this->set_is_error();
8831 break;
8833 case BUILTIN_REAL:
8834 case BUILTIN_IMAG:
8835 if (this->check_one_arg())
8837 if (this->one_arg()->type()->complex_type() == NULL)
8838 this->report_error(_("argument must have complex type"));
8840 break;
8842 case BUILTIN_COMPLEX:
8844 const Expression_list* args = this->args();
8845 if (args == NULL || args->size() < 2)
8846 this->report_error(_("not enough arguments"));
8847 else if (args->size() > 2)
8848 this->report_error(_("too many arguments"));
8849 else if (args->front()->is_error_expression()
8850 || args->front()->type()->is_error()
8851 || args->back()->is_error_expression()
8852 || args->back()->type()->is_error())
8853 this->set_is_error();
8854 else if (!Type::are_identical(args->front()->type(),
8855 args->back()->type(), true, NULL))
8856 this->report_error(_("complex arguments must have identical types"));
8857 else if (args->front()->type()->float_type() == NULL)
8858 this->report_error(_("complex arguments must have "
8859 "floating-point type"));
8861 break;
8863 default:
8864 go_unreachable();
8868 Expression*
8869 Builtin_call_expression::do_copy()
8871 Call_expression* bce =
8872 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8873 (this->args() == NULL
8874 ? NULL
8875 : this->args()->copy()),
8876 this->is_varargs(),
8877 this->location());
8879 if (this->varargs_are_lowered())
8880 bce->set_varargs_are_lowered();
8881 return bce;
8884 // Return the backend representation for a builtin function.
8886 Bexpression*
8887 Builtin_call_expression::do_get_backend(Translate_context* context)
8889 Gogo* gogo = context->gogo();
8890 Location location = this->location();
8892 if (this->is_erroneous_call())
8894 go_assert(saw_errors());
8895 return gogo->backend()->error_expression();
8898 switch (this->code_)
8900 case BUILTIN_INVALID:
8901 case BUILTIN_NEW:
8902 case BUILTIN_MAKE:
8903 go_unreachable();
8905 case BUILTIN_LEN:
8906 case BUILTIN_CAP:
8908 const Expression_list* args = this->args();
8909 go_assert(args != NULL && args->size() == 1);
8910 Expression* arg = args->front();
8911 Type* arg_type = arg->type();
8913 if (this->seen_)
8915 go_assert(saw_errors());
8916 return context->backend()->error_expression();
8918 this->seen_ = true;
8919 this->seen_ = false;
8920 if (arg_type->points_to() != NULL)
8922 arg_type = arg_type->points_to();
8923 go_assert(arg_type->array_type() != NULL
8924 && !arg_type->is_slice_type());
8925 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8928 Type* int_type = Type::lookup_integer_type("int");
8929 Expression* val;
8930 if (this->code_ == BUILTIN_LEN)
8932 if (arg_type->is_string_type())
8933 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8934 location);
8935 else if (arg_type->array_type() != NULL)
8937 if (this->seen_)
8939 go_assert(saw_errors());
8940 return context->backend()->error_expression();
8942 this->seen_ = true;
8943 val = arg_type->array_type()->get_length(gogo, arg);
8944 this->seen_ = false;
8946 else if (arg_type->map_type() != NULL
8947 || arg_type->channel_type() != NULL)
8949 // The first field is the length. If the pointer is
8950 // nil, the length is zero.
8951 Type* pint_type = Type::make_pointer_type(int_type);
8952 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8953 Expression* nil = Expression::make_nil(location);
8954 nil = Expression::make_cast(pint_type, nil, location);
8955 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8956 arg, nil, location);
8957 Expression* zero = Expression::make_integer_ul(0, int_type,
8958 location);
8959 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8960 arg, location);
8961 val = Expression::make_conditional(cmp, zero, indir, location);
8963 else
8964 go_unreachable();
8966 else
8968 if (arg_type->array_type() != NULL)
8970 if (this->seen_)
8972 go_assert(saw_errors());
8973 return context->backend()->error_expression();
8975 this->seen_ = true;
8976 val = arg_type->array_type()->get_capacity(gogo, arg);
8977 this->seen_ = false;
8979 else if (arg_type->channel_type() != NULL)
8981 // The second field is the capacity. If the pointer
8982 // is nil, the capacity is zero.
8983 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8984 Type* pint_type = Type::make_pointer_type(int_type);
8985 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8986 arg,
8987 location);
8988 int off = int_type->integer_type()->bits() / 8;
8989 Expression* eoff = Expression::make_integer_ul(off,
8990 uintptr_type,
8991 location);
8992 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8993 location);
8994 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8995 Expression* nil = Expression::make_nil(location);
8996 nil = Expression::make_cast(pint_type, nil, location);
8997 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8998 arg, nil, location);
8999 Expression* zero = Expression::make_integer_ul(0, int_type,
9000 location);
9001 Expression* indir = Expression::make_unary(OPERATOR_MULT,
9002 parg, location);
9003 val = Expression::make_conditional(cmp, zero, indir, location);
9005 else
9006 go_unreachable();
9009 return Expression::make_cast(int_type, val,
9010 location)->get_backend(context);
9013 case BUILTIN_PRINT:
9014 case BUILTIN_PRINTLN:
9016 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
9018 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9019 location, 0);
9021 const Expression_list* call_args = this->args();
9022 if (call_args != NULL)
9024 for (Expression_list::const_iterator p = call_args->begin();
9025 p != call_args->end();
9026 ++p)
9028 if (is_ln && p != call_args->begin())
9030 Expression* print_space =
9031 Runtime::make_call(Runtime::PRINTSP, location, 0);
9033 print_stmts =
9034 Expression::make_compound(print_stmts, print_space,
9035 location);
9038 Expression* arg = *p;
9039 Type* type = arg->type();
9040 Runtime::Function code;
9041 if (type->is_string_type())
9042 code = Runtime::PRINTSTRING;
9043 else if (type->integer_type() != NULL
9044 && type->integer_type()->is_unsigned())
9046 Type* itype = Type::lookup_integer_type("uint64");
9047 arg = Expression::make_cast(itype, arg, location);
9048 code = Runtime::PRINTUINT;
9050 else if (type->integer_type() != NULL)
9052 Type* itype = Type::lookup_integer_type("int64");
9053 arg = Expression::make_cast(itype, arg, location);
9054 code = Runtime::PRINTINT;
9056 else if (type->float_type() != NULL)
9058 Type* dtype = Type::lookup_float_type("float64");
9059 arg = Expression::make_cast(dtype, arg, location);
9060 code = Runtime::PRINTFLOAT;
9062 else if (type->complex_type() != NULL)
9064 Type* ctype = Type::lookup_complex_type("complex128");
9065 arg = Expression::make_cast(ctype, arg, location);
9066 code = Runtime::PRINTCOMPLEX;
9068 else if (type->is_boolean_type())
9069 code = Runtime::PRINTBOOL;
9070 else if (type->points_to() != NULL
9071 || type->channel_type() != NULL
9072 || type->map_type() != NULL
9073 || type->function_type() != NULL)
9075 arg = Expression::make_cast(type, arg, location);
9076 code = Runtime::PRINTPOINTER;
9078 else if (type->interface_type() != NULL)
9080 if (type->interface_type()->is_empty())
9081 code = Runtime::PRINTEFACE;
9082 else
9083 code = Runtime::PRINTIFACE;
9085 else if (type->is_slice_type())
9086 code = Runtime::PRINTSLICE;
9087 else
9089 go_assert(saw_errors());
9090 return context->backend()->error_expression();
9093 Expression* call = Runtime::make_call(code, location, 1, arg);
9094 print_stmts = Expression::make_compound(print_stmts, call,
9095 location);
9099 if (is_ln)
9101 Expression* print_nl =
9102 Runtime::make_call(Runtime::PRINTNL, location, 0);
9103 print_stmts = Expression::make_compound(print_stmts, print_nl,
9104 location);
9107 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9108 location, 0);
9109 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9111 return print_stmts->get_backend(context);
9114 case BUILTIN_PANIC:
9116 const Expression_list* args = this->args();
9117 go_assert(args != NULL && args->size() == 1);
9118 Expression* arg = args->front();
9119 Type *empty =
9120 Type::make_empty_interface_type(Linemap::predeclared_location());
9121 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9123 Expression* panic =
9124 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9125 return panic->get_backend(context);
9128 case BUILTIN_RECOVER:
9130 // The argument is set when building recover thunks. It's a
9131 // boolean value which is true if we can recover a value now.
9132 const Expression_list* args = this->args();
9133 go_assert(args != NULL && args->size() == 1);
9134 Expression* arg = args->front();
9135 Type *empty =
9136 Type::make_empty_interface_type(Linemap::predeclared_location());
9138 Expression* nil = Expression::make_nil(location);
9139 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9141 // We need to handle a deferred call to recover specially,
9142 // because it changes whether it can recover a panic or not.
9143 // See test7 in test/recover1.go.
9144 Expression* recover = Runtime::make_call((this->is_deferred()
9145 ? Runtime::DEFERREDRECOVER
9146 : Runtime::GORECOVER),
9147 location, 0);
9148 Expression* cond =
9149 Expression::make_conditional(arg, recover, nil, location);
9150 return cond->get_backend(context);
9153 case BUILTIN_CLOSE:
9155 const Expression_list* args = this->args();
9156 go_assert(args != NULL && args->size() == 1);
9157 Expression* arg = args->front();
9158 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9159 1, arg);
9160 return close->get_backend(context);
9163 case BUILTIN_SIZEOF:
9164 case BUILTIN_OFFSETOF:
9165 case BUILTIN_ALIGNOF:
9167 Numeric_constant nc;
9168 unsigned long val;
9169 if (!this->numeric_constant_value(&nc)
9170 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9172 go_assert(saw_errors());
9173 return context->backend()->error_expression();
9175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9176 mpz_t ival;
9177 nc.get_int(&ival);
9178 Expression* int_cst =
9179 Expression::make_integer_z(&ival, uintptr_type, location);
9180 mpz_clear(ival);
9181 return int_cst->get_backend(context);
9184 case BUILTIN_COPY:
9186 const Expression_list* args = this->args();
9187 go_assert(args != NULL && args->size() == 2);
9188 Expression* arg1 = args->front();
9189 Expression* arg2 = args->back();
9191 Type* arg1_type = arg1->type();
9192 Array_type* at = arg1_type->array_type();
9193 go_assert(arg1->is_variable());
9195 Expression* call;
9197 Type* arg2_type = arg2->type();
9198 go_assert(arg2->is_variable());
9199 if (arg2_type->is_string_type())
9200 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9201 2, arg1, arg2);
9202 else
9204 Type* et = at->element_type();
9205 if (et->has_pointer())
9207 Expression* td = Expression::make_type_descriptor(et,
9208 location);
9209 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9210 3, td, arg1, arg2);
9212 else
9214 Expression* sz = Expression::make_type_info(et,
9215 TYPE_INFO_SIZE);
9216 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9217 arg1, arg2, sz);
9221 return call->get_backend(context);
9224 case BUILTIN_APPEND:
9225 // Handled in Builtin_call_expression::flatten_append.
9226 go_unreachable();
9228 case BUILTIN_REAL:
9229 case BUILTIN_IMAG:
9231 const Expression_list* args = this->args();
9232 go_assert(args != NULL && args->size() == 1);
9234 Bexpression* ret;
9235 Bexpression* bcomplex = args->front()->get_backend(context);
9236 if (this->code_ == BUILTIN_REAL)
9237 ret = gogo->backend()->real_part_expression(bcomplex, location);
9238 else
9239 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9240 return ret;
9243 case BUILTIN_COMPLEX:
9245 const Expression_list* args = this->args();
9246 go_assert(args != NULL && args->size() == 2);
9247 Bexpression* breal = args->front()->get_backend(context);
9248 Bexpression* bimag = args->back()->get_backend(context);
9249 return gogo->backend()->complex_expression(breal, bimag, location);
9252 default:
9253 go_unreachable();
9257 // We have to support exporting a builtin call expression, because
9258 // code can set a constant to the result of a builtin expression.
9260 void
9261 Builtin_call_expression::do_export(Export* exp) const
9263 Numeric_constant nc;
9264 if (!this->numeric_constant_value(&nc))
9266 go_error_at(this->location(), "value is not constant");
9267 return;
9270 if (nc.is_int())
9272 mpz_t val;
9273 nc.get_int(&val);
9274 Integer_expression::export_integer(exp, val);
9275 mpz_clear(val);
9277 else if (nc.is_float())
9279 mpfr_t fval;
9280 nc.get_float(&fval);
9281 Float_expression::export_float(exp, fval);
9282 mpfr_clear(fval);
9284 else if (nc.is_complex())
9286 mpc_t cval;
9287 nc.get_complex(&cval);
9288 Complex_expression::export_complex(exp, cval);
9289 mpc_clear(cval);
9291 else
9292 go_unreachable();
9294 // A trailing space lets us reliably identify the end of the number.
9295 exp->write_c_string(" ");
9298 // Class Call_expression.
9300 // A Go function can be viewed in a couple of different ways. The
9301 // code of a Go function becomes a backend function with parameters
9302 // whose types are simply the backend representation of the Go types.
9303 // If there are multiple results, they are returned as a backend
9304 // struct.
9306 // However, when Go code refers to a function other than simply
9307 // calling it, the backend type of that function is actually a struct.
9308 // The first field of the struct points to the Go function code
9309 // (sometimes a wrapper as described below). The remaining fields
9310 // hold addresses of closed-over variables. This struct is called a
9311 // closure.
9313 // There are a few cases to consider.
9315 // A direct function call of a known function in package scope. In
9316 // this case there are no closed-over variables, and we know the name
9317 // of the function code. We can simply produce a backend call to the
9318 // function directly, and not worry about the closure.
9320 // A direct function call of a known function literal. In this case
9321 // we know the function code and we know the closure. We generate the
9322 // function code such that it expects an additional final argument of
9323 // the closure type. We pass the closure as the last argument, after
9324 // the other arguments.
9326 // An indirect function call. In this case we have a closure. We
9327 // load the pointer to the function code from the first field of the
9328 // closure. We pass the address of the closure as the last argument.
9330 // A call to a method of an interface. Type methods are always at
9331 // package scope, so we call the function directly, and don't worry
9332 // about the closure.
9334 // This means that for a function at package scope we have two cases.
9335 // One is the direct call, which has no closure. The other is the
9336 // indirect call, which does have a closure. We can't simply ignore
9337 // the closure, even though it is the last argument, because that will
9338 // fail on targets where the function pops its arguments. So when
9339 // generating a closure for a package-scope function we set the
9340 // function code pointer in the closure to point to a wrapper
9341 // function. This wrapper function accepts a final argument that
9342 // points to the closure, ignores it, and calls the real function as a
9343 // direct function call. This wrapper will normally be efficient, and
9344 // can often simply be a tail call to the real function.
9346 // We don't use GCC's static chain pointer because 1) we don't need
9347 // it; 2) GCC only permits using a static chain to call a known
9348 // function, so we can't use it for an indirect call anyhow. Since we
9349 // can't use it for an indirect call, we may as well not worry about
9350 // using it for a direct call either.
9352 // We pass the closure last rather than first because it means that
9353 // the function wrapper we put into a closure for a package-scope
9354 // function can normally just be a tail call to the real function.
9356 // For method expressions we generate a wrapper that loads the
9357 // receiver from the closure and then calls the method. This
9358 // unfortunately forces reshuffling the arguments, since there is a
9359 // new first argument, but we can't avoid reshuffling either for
9360 // method expressions or for indirect calls of package-scope
9361 // functions, and since the latter are more common we reshuffle for
9362 // method expressions.
9364 // Note that the Go code retains the Go types. The extra final
9365 // argument only appears when we convert to the backend
9366 // representation.
9368 // Traversal.
9371 Call_expression::do_traverse(Traverse* traverse)
9373 // If we are calling a function in a different package that returns
9374 // an unnamed type, this may be the only chance we get to traverse
9375 // that type. We don't traverse this->type_ because it may be a
9376 // Call_multiple_result_type that will just lead back here.
9377 if (this->type_ != NULL && !this->type_->is_error_type())
9379 Function_type *fntype = this->get_function_type();
9380 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9381 return TRAVERSE_EXIT;
9383 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9384 return TRAVERSE_EXIT;
9385 if (this->args_ != NULL)
9387 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9388 return TRAVERSE_EXIT;
9390 return TRAVERSE_CONTINUE;
9393 // Lower a call statement.
9395 Expression*
9396 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9397 Statement_inserter* inserter, int)
9399 Location loc = this->location();
9401 // A type cast can look like a function call.
9402 if (this->fn_->is_type_expression()
9403 && this->args_ != NULL
9404 && this->args_->size() == 1)
9405 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9406 loc);
9408 // Because do_type will return an error type and thus prevent future
9409 // errors, check for that case now to ensure that the error gets
9410 // reported.
9411 Function_type* fntype = this->get_function_type();
9412 if (fntype == NULL)
9414 if (!this->fn_->type()->is_error())
9415 this->report_error(_("expected function"));
9416 this->set_is_error();
9417 return this;
9420 // Handle an argument which is a call to a function which returns
9421 // multiple results.
9422 if (this->args_ != NULL
9423 && this->args_->size() == 1
9424 && this->args_->front()->call_expression() != NULL)
9426 size_t rc = this->args_->front()->call_expression()->result_count();
9427 if (rc > 1
9428 && ((fntype->parameters() != NULL
9429 && (fntype->parameters()->size() == rc
9430 || (fntype->is_varargs()
9431 && fntype->parameters()->size() - 1 <= rc)))
9432 || fntype->is_builtin()))
9434 Call_expression* call = this->args_->front()->call_expression();
9435 call->set_is_multi_value_arg();
9436 if (this->is_varargs_)
9438 // It is not clear which result of a multiple result call
9439 // the ellipsis operator should be applied to. If we unpack the
9440 // the call into its individual results here, the ellipsis will be
9441 // applied to the last result.
9442 go_error_at(call->location(),
9443 _("multiple-value argument in single-value context"));
9444 return Expression::make_error(call->location());
9447 Expression_list* args = new Expression_list;
9448 for (size_t i = 0; i < rc; ++i)
9449 args->push_back(Expression::make_call_result(call, i));
9450 // We can't return a new call expression here, because this
9451 // one may be referenced by Call_result expressions. We
9452 // also can't delete the old arguments, because we may still
9453 // traverse them somewhere up the call stack. FIXME.
9454 this->args_ = args;
9458 // Recognize a call to a builtin function.
9459 if (fntype->is_builtin())
9460 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9461 this->is_varargs_, loc);
9463 // If this call returns multiple results, create a temporary
9464 // variable to hold them.
9465 if (this->result_count() > 1 && this->call_temp_ == NULL)
9467 Struct_field_list* sfl = new Struct_field_list();
9468 Function_type* fntype = this->get_function_type();
9469 const Typed_identifier_list* results = fntype->results();
9470 Location loc = this->location();
9472 int i = 0;
9473 char buf[20];
9474 for (Typed_identifier_list::const_iterator p = results->begin();
9475 p != results->end();
9476 ++p, ++i)
9478 snprintf(buf, sizeof buf, "res%d", i);
9479 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9482 Struct_type* st = Type::make_struct_type(sfl, loc);
9483 st->set_is_struct_incomparable();
9484 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9485 inserter->insert(this->call_temp_);
9488 // Handle a call to a varargs function by packaging up the extra
9489 // parameters.
9490 if (fntype->is_varargs())
9492 const Typed_identifier_list* parameters = fntype->parameters();
9493 go_assert(parameters != NULL && !parameters->empty());
9494 Type* varargs_type = parameters->back().type();
9495 this->lower_varargs(gogo, function, inserter, varargs_type,
9496 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9499 // If this is call to a method, call the method directly passing the
9500 // object as the first parameter.
9501 Bound_method_expression* bme = this->fn_->bound_method_expression();
9502 if (bme != NULL)
9504 Named_object* methodfn = bme->function();
9505 Expression* first_arg = bme->first_argument();
9507 // We always pass a pointer when calling a method.
9508 if (first_arg->type()->points_to() == NULL
9509 && !first_arg->type()->is_error())
9511 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9512 // We may need to create a temporary variable so that we can
9513 // take the address. We can't do that here because it will
9514 // mess up the order of evaluation.
9515 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9516 ue->set_create_temp();
9519 // If we are calling a method which was inherited from an
9520 // embedded struct, and the method did not get a stub, then the
9521 // first type may be wrong.
9522 Type* fatype = bme->first_argument_type();
9523 if (fatype != NULL)
9525 if (fatype->points_to() == NULL)
9526 fatype = Type::make_pointer_type(fatype);
9527 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9530 Expression_list* new_args = new Expression_list();
9531 new_args->push_back(first_arg);
9532 if (this->args_ != NULL)
9534 for (Expression_list::const_iterator p = this->args_->begin();
9535 p != this->args_->end();
9536 ++p)
9537 new_args->push_back(*p);
9540 // We have to change in place because this structure may be
9541 // referenced by Call_result_expressions. We can't delete the
9542 // old arguments, because we may be traversing them up in some
9543 // caller. FIXME.
9544 this->args_ = new_args;
9545 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9546 bme->location());
9549 // Handle a couple of special runtime functions. In the runtime
9550 // package, getcallerpc returns the PC of the caller, and
9551 // getcallersp returns the frame pointer of the caller. Implement
9552 // these by turning them into calls to GCC builtin functions. We
9553 // could implement them in normal code, but then we would have to
9554 // explicitly unwind the stack. These functions are intended to be
9555 // efficient. Note that this technique obviously only works for
9556 // direct calls, but that is the only way they are used. The actual
9557 // argument to these functions is always the address of a parameter;
9558 // we don't need that for the GCC builtin functions, so we just
9559 // ignore it.
9560 if (gogo->compiling_runtime()
9561 && this->args_ != NULL
9562 && this->args_->size() == 1
9563 && gogo->package_name() == "runtime")
9565 Func_expression* fe = this->fn_->func_expression();
9566 if (fe != NULL
9567 && fe->named_object()->is_function_declaration()
9568 && fe->named_object()->package() == NULL)
9570 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9571 if (n == "getcallerpc")
9573 static Named_object* builtin_return_address;
9574 return this->lower_to_builtin(&builtin_return_address,
9575 "__builtin_return_address",
9578 else if (n == "getcallersp")
9580 static Named_object* builtin_frame_address;
9581 return this->lower_to_builtin(&builtin_frame_address,
9582 "__builtin_frame_address",
9588 return this;
9591 // Lower a call to a varargs function. FUNCTION is the function in
9592 // which the call occurs--it's not the function we are calling.
9593 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9594 // PARAM_COUNT is the number of parameters of the function we are
9595 // calling; the last of these parameters will be the varargs
9596 // parameter.
9598 void
9599 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9600 Statement_inserter* inserter,
9601 Type* varargs_type, size_t param_count,
9602 Slice_storage_escape_disp escape_disp)
9604 // When compiling the runtime, varargs slices do not escape. When
9605 // escape analysis becomes the default, this should be changed to
9606 // make it an error if we have a varargs slice that escapes.
9607 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9608 escape_disp = SLICE_STORAGE_DOES_NOT_ESCAPE;
9610 if (this->varargs_are_lowered_)
9611 return;
9613 Location loc = this->location();
9615 go_assert(param_count > 0);
9616 go_assert(varargs_type->is_slice_type());
9618 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9619 if (arg_count < param_count - 1)
9621 // Not enough arguments; will be caught in check_types.
9622 return;
9625 Expression_list* old_args = this->args_;
9626 Expression_list* new_args = new Expression_list();
9627 bool push_empty_arg = false;
9628 if (old_args == NULL || old_args->empty())
9630 go_assert(param_count == 1);
9631 push_empty_arg = true;
9633 else
9635 Expression_list::const_iterator pa;
9636 int i = 1;
9637 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9639 if (static_cast<size_t>(i) == param_count)
9640 break;
9641 new_args->push_back(*pa);
9644 // We have reached the varargs parameter.
9646 bool issued_error = false;
9647 if (pa == old_args->end())
9648 push_empty_arg = true;
9649 else if (pa + 1 == old_args->end() && this->is_varargs_)
9650 new_args->push_back(*pa);
9651 else if (this->is_varargs_)
9653 if ((*pa)->type()->is_slice_type())
9654 this->report_error(_("too many arguments"));
9655 else
9657 go_error_at(this->location(),
9658 _("invalid use of %<...%> with non-slice"));
9659 this->set_is_error();
9661 return;
9663 else
9665 Type* element_type = varargs_type->array_type()->element_type();
9666 Expression_list* vals = new Expression_list;
9667 for (; pa != old_args->end(); ++pa, ++i)
9669 // Check types here so that we get a better message.
9670 Type* patype = (*pa)->type();
9671 Location paloc = (*pa)->location();
9672 if (!this->check_argument_type(i, element_type, patype,
9673 paloc, issued_error))
9674 continue;
9675 vals->push_back(*pa);
9677 Slice_construction_expression* sce =
9678 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9679 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9680 sce->set_storage_does_not_escape();
9681 Expression* val = sce;
9682 gogo->lower_expression(function, inserter, &val);
9683 new_args->push_back(val);
9687 if (push_empty_arg)
9688 new_args->push_back(Expression::make_nil(loc));
9690 // We can't return a new call expression here, because this one may
9691 // be referenced by Call_result expressions. FIXME. We can't
9692 // delete OLD_ARGS because we may have both a Call_expression and a
9693 // Builtin_call_expression which refer to them. FIXME.
9694 this->args_ = new_args;
9695 this->varargs_are_lowered_ = true;
9698 // Return a call to __builtin_return_address or __builtin_frame_address.
9700 Expression*
9701 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9702 int arg)
9704 if (*pno == NULL)
9705 *pno = Gogo::declare_builtin_rf_address(name);
9707 Location loc = this->location();
9709 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9710 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9711 Expression_list *args = new Expression_list();
9712 args->push_back(a);
9713 Expression* call = Expression::make_call(fn, args, false, loc);
9715 // The builtin functions return void*, but the Go functions return uintptr.
9716 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9717 return Expression::make_cast(uintptr_type, call, loc);
9720 // Flatten a call with multiple results into a temporary.
9722 Expression*
9723 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9724 Statement_inserter* inserter)
9726 if (this->is_erroneous_call())
9728 go_assert(saw_errors());
9729 return Expression::make_error(this->location());
9732 if (this->is_flattened_)
9733 return this;
9734 this->is_flattened_ = true;
9736 // Add temporary variables for all arguments that require type
9737 // conversion.
9738 Function_type* fntype = this->get_function_type();
9739 if (fntype == NULL)
9741 go_assert(saw_errors());
9742 return this;
9744 if (this->args_ != NULL && !this->args_->empty()
9745 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9747 bool is_interface_method =
9748 this->fn_->interface_field_reference_expression() != NULL;
9750 Expression_list *args = new Expression_list();
9751 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9752 Expression_list::const_iterator pa = this->args_->begin();
9753 if (!is_interface_method && fntype->is_method())
9755 // The receiver argument.
9756 args->push_back(*pa);
9757 ++pa;
9759 for (; pa != this->args_->end(); ++pa, ++pp)
9761 go_assert(pp != fntype->parameters()->end());
9762 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9763 args->push_back(*pa);
9764 else
9766 Location loc = (*pa)->location();
9767 Expression* arg = *pa;
9768 if (!arg->is_variable())
9770 Temporary_statement *temp =
9771 Statement::make_temporary(NULL, arg, loc);
9772 inserter->insert(temp);
9773 arg = Expression::make_temporary_reference(temp, loc);
9775 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9776 loc);
9777 args->push_back(arg);
9780 delete this->args_;
9781 this->args_ = args;
9784 return this;
9787 // Get the function type. This can return NULL in error cases.
9789 Function_type*
9790 Call_expression::get_function_type() const
9792 return this->fn_->type()->function_type();
9795 // Return the number of values which this call will return.
9797 size_t
9798 Call_expression::result_count() const
9800 const Function_type* fntype = this->get_function_type();
9801 if (fntype == NULL)
9802 return 0;
9803 if (fntype->results() == NULL)
9804 return 0;
9805 return fntype->results()->size();
9808 // Return the temporary that holds the result for a call with multiple
9809 // results.
9811 Temporary_statement*
9812 Call_expression::results() const
9814 if (this->call_temp_ == NULL)
9816 go_assert(saw_errors());
9817 return NULL;
9819 return this->call_temp_;
9822 // Set the number of results expected from a call expression.
9824 void
9825 Call_expression::set_expected_result_count(size_t count)
9827 go_assert(this->expected_result_count_ == 0);
9828 this->expected_result_count_ = count;
9831 // Return whether this is a call to the predeclared function recover.
9833 bool
9834 Call_expression::is_recover_call() const
9836 return this->do_is_recover_call();
9839 // Set the argument to the recover function.
9841 void
9842 Call_expression::set_recover_arg(Expression* arg)
9844 this->do_set_recover_arg(arg);
9847 // Virtual functions also implemented by Builtin_call_expression.
9849 bool
9850 Call_expression::do_is_recover_call() const
9852 return false;
9855 void
9856 Call_expression::do_set_recover_arg(Expression*)
9858 go_unreachable();
9861 // We have found an error with this call expression; return true if
9862 // we should report it.
9864 bool
9865 Call_expression::issue_error()
9867 if (this->issued_error_)
9868 return false;
9869 else
9871 this->issued_error_ = true;
9872 return true;
9876 // Whether or not this call contains errors, either in the call or the
9877 // arguments to the call.
9879 bool
9880 Call_expression::is_erroneous_call()
9882 if (this->is_error_expression() || this->fn()->is_error_expression())
9883 return true;
9885 if (this->args() == NULL)
9886 return false;
9887 for (Expression_list::iterator pa = this->args()->begin();
9888 pa != this->args()->end();
9889 ++pa)
9891 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9892 return true;
9894 return false;
9897 // Get the type.
9899 Type*
9900 Call_expression::do_type()
9902 if (this->type_ != NULL)
9903 return this->type_;
9905 Type* ret;
9906 Function_type* fntype = this->get_function_type();
9907 if (fntype == NULL)
9908 return Type::make_error_type();
9910 const Typed_identifier_list* results = fntype->results();
9911 if (results == NULL)
9912 ret = Type::make_void_type();
9913 else if (results->size() == 1)
9914 ret = results->begin()->type();
9915 else
9916 ret = Type::make_call_multiple_result_type(this);
9918 this->type_ = ret;
9920 return this->type_;
9923 // Determine types for a call expression. We can use the function
9924 // parameter types to set the types of the arguments.
9926 void
9927 Call_expression::do_determine_type(const Type_context*)
9929 if (!this->determining_types())
9930 return;
9932 this->fn_->determine_type_no_context();
9933 Function_type* fntype = this->get_function_type();
9934 const Typed_identifier_list* parameters = NULL;
9935 if (fntype != NULL)
9936 parameters = fntype->parameters();
9937 if (this->args_ != NULL)
9939 Typed_identifier_list::const_iterator pt;
9940 if (parameters != NULL)
9941 pt = parameters->begin();
9942 bool first = true;
9943 for (Expression_list::const_iterator pa = this->args_->begin();
9944 pa != this->args_->end();
9945 ++pa)
9947 if (first)
9949 first = false;
9950 // If this is a method, the first argument is the
9951 // receiver.
9952 if (fntype != NULL && fntype->is_method())
9954 Type* rtype = fntype->receiver()->type();
9955 // The receiver is always passed as a pointer.
9956 if (rtype->points_to() == NULL)
9957 rtype = Type::make_pointer_type(rtype);
9958 Type_context subcontext(rtype, false);
9959 (*pa)->determine_type(&subcontext);
9960 continue;
9964 if (parameters != NULL && pt != parameters->end())
9966 Type_context subcontext(pt->type(), false);
9967 (*pa)->determine_type(&subcontext);
9968 ++pt;
9970 else
9971 (*pa)->determine_type_no_context();
9976 // Called when determining types for a Call_expression. Return true
9977 // if we should go ahead, false if they have already been determined.
9979 bool
9980 Call_expression::determining_types()
9982 if (this->types_are_determined_)
9983 return false;
9984 else
9986 this->types_are_determined_ = true;
9987 return true;
9991 // Check types for parameter I.
9993 bool
9994 Call_expression::check_argument_type(int i, const Type* parameter_type,
9995 const Type* argument_type,
9996 Location argument_location,
9997 bool issued_error)
9999 std::string reason;
10000 if (!Type::are_assignable(parameter_type, argument_type, &reason))
10002 if (!issued_error)
10004 if (reason.empty())
10005 go_error_at(argument_location, "argument %d has incompatible type", i);
10006 else
10007 go_error_at(argument_location,
10008 "argument %d has incompatible type (%s)",
10009 i, reason.c_str());
10011 this->set_is_error();
10012 return false;
10014 return true;
10017 // Check types.
10019 void
10020 Call_expression::do_check_types(Gogo*)
10022 if (this->classification() == EXPRESSION_ERROR)
10023 return;
10025 Function_type* fntype = this->get_function_type();
10026 if (fntype == NULL)
10028 if (!this->fn_->type()->is_error())
10029 this->report_error(_("expected function"));
10030 return;
10033 if (this->expected_result_count_ != 0
10034 && this->expected_result_count_ != this->result_count())
10036 if (this->issue_error())
10037 this->report_error(_("function result count mismatch"));
10038 this->set_is_error();
10039 return;
10042 bool is_method = fntype->is_method();
10043 if (is_method)
10045 go_assert(this->args_ != NULL && !this->args_->empty());
10046 Type* rtype = fntype->receiver()->type();
10047 Expression* first_arg = this->args_->front();
10048 // We dereference the values since receivers are always passed
10049 // as pointers.
10050 std::string reason;
10051 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10052 &reason))
10054 if (reason.empty())
10055 this->report_error(_("incompatible type for receiver"));
10056 else
10058 go_error_at(this->location(),
10059 "incompatible type for receiver (%s)",
10060 reason.c_str());
10061 this->set_is_error();
10066 // Note that varargs was handled by the lower_varargs() method, so
10067 // we don't have to worry about it here unless something is wrong.
10068 if (this->is_varargs_ && !this->varargs_are_lowered_)
10070 if (!fntype->is_varargs())
10072 go_error_at(this->location(),
10073 _("invalid use of %<...%> calling non-variadic function"));
10074 this->set_is_error();
10075 return;
10079 const Typed_identifier_list* parameters = fntype->parameters();
10080 if (this->args_ == NULL)
10082 if (parameters != NULL && !parameters->empty())
10083 this->report_error(_("not enough arguments"));
10085 else if (parameters == NULL)
10087 if (!is_method || this->args_->size() > 1)
10088 this->report_error(_("too many arguments"));
10090 else if (this->args_->size() == 1
10091 && this->args_->front()->call_expression() != NULL
10092 && this->args_->front()->call_expression()->result_count() > 1)
10094 // This is F(G()) when G returns more than one result. If the
10095 // results can be matched to parameters, it would have been
10096 // lowered in do_lower. If we get here we know there is a
10097 // mismatch.
10098 if (this->args_->front()->call_expression()->result_count()
10099 < parameters->size())
10100 this->report_error(_("not enough arguments"));
10101 else
10102 this->report_error(_("too many arguments"));
10104 else
10106 int i = 0;
10107 Expression_list::const_iterator pa = this->args_->begin();
10108 if (is_method)
10109 ++pa;
10110 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10111 pt != parameters->end();
10112 ++pt, ++pa, ++i)
10114 if (pa == this->args_->end())
10116 this->report_error(_("not enough arguments"));
10117 return;
10119 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10120 (*pa)->location(), false);
10122 if (pa != this->args_->end())
10123 this->report_error(_("too many arguments"));
10127 Expression*
10128 Call_expression::do_copy()
10130 Call_expression* call =
10131 Expression::make_call(this->fn_->copy(),
10132 (this->args_ == NULL
10133 ? NULL
10134 : this->args_->copy()),
10135 this->is_varargs_, this->location());
10137 if (this->varargs_are_lowered_)
10138 call->set_varargs_are_lowered();
10139 return call;
10142 // Return whether we have to use a temporary variable to ensure that
10143 // we evaluate this call expression in order. If the call returns no
10144 // results then it will inevitably be executed last.
10146 bool
10147 Call_expression::do_must_eval_in_order() const
10149 return this->result_count() > 0;
10152 // Get the function and the first argument to use when calling an
10153 // interface method.
10155 Expression*
10156 Call_expression::interface_method_function(
10157 Interface_field_reference_expression* interface_method,
10158 Expression** first_arg_ptr,
10159 Location location)
10161 Expression* object = interface_method->get_underlying_object();
10162 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10163 *first_arg_ptr =
10164 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10165 return interface_method->get_function();
10168 // Build the call expression.
10170 Bexpression*
10171 Call_expression::do_get_backend(Translate_context* context)
10173 Location location = this->location();
10175 if (this->call_ != NULL)
10177 // If the call returns multiple results, make a new reference to
10178 // the temporary.
10179 if (this->call_temp_ != NULL)
10181 Expression* ref =
10182 Expression::make_temporary_reference(this->call_temp_, location);
10183 return ref->get_backend(context);
10186 return this->call_;
10189 Function_type* fntype = this->get_function_type();
10190 if (fntype == NULL)
10191 return context->backend()->error_expression();
10193 if (this->fn_->is_error_expression())
10194 return context->backend()->error_expression();
10196 Gogo* gogo = context->gogo();
10198 Func_expression* func = this->fn_->func_expression();
10199 Interface_field_reference_expression* interface_method =
10200 this->fn_->interface_field_reference_expression();
10201 const bool has_closure = func != NULL && func->closure() != NULL;
10202 const bool is_interface_method = interface_method != NULL;
10204 bool has_closure_arg;
10205 if (has_closure)
10206 has_closure_arg = true;
10207 else if (func != NULL)
10208 has_closure_arg = false;
10209 else if (is_interface_method)
10210 has_closure_arg = false;
10211 else
10212 has_closure_arg = true;
10214 int nargs;
10215 std::vector<Bexpression*> fn_args;
10216 if (this->args_ == NULL || this->args_->empty())
10218 nargs = is_interface_method ? 1 : 0;
10219 if (nargs > 0)
10220 fn_args.resize(1);
10222 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10224 // Passing a receiver parameter.
10225 go_assert(!is_interface_method
10226 && fntype->is_method()
10227 && this->args_->size() == 1);
10228 nargs = 1;
10229 fn_args.resize(1);
10230 fn_args[0] = this->args_->front()->get_backend(context);
10232 else
10234 const Typed_identifier_list* params = fntype->parameters();
10236 nargs = this->args_->size();
10237 int i = is_interface_method ? 1 : 0;
10238 nargs += i;
10239 fn_args.resize(nargs);
10241 Typed_identifier_list::const_iterator pp = params->begin();
10242 Expression_list::const_iterator pe = this->args_->begin();
10243 if (!is_interface_method && fntype->is_method())
10245 fn_args[i] = (*pe)->get_backend(context);
10246 ++pe;
10247 ++i;
10249 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10251 go_assert(pp != params->end());
10252 Expression* arg =
10253 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10254 location);
10255 fn_args[i] = arg->get_backend(context);
10257 go_assert(pp == params->end());
10258 go_assert(i == nargs);
10261 Expression* fn;
10262 Expression* closure = NULL;
10263 if (func != NULL)
10265 Named_object* no = func->named_object();
10266 fn = Expression::make_func_code_reference(no, location);
10267 if (has_closure)
10268 closure = func->closure();
10270 else if (!is_interface_method)
10272 closure = this->fn_;
10274 // The backend representation of this function type is a pointer
10275 // to a struct whose first field is the actual function to call.
10276 Type* pfntype =
10277 Type::make_pointer_type(
10278 Type::make_pointer_type(Type::make_void_type()));
10279 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10280 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
10282 else
10284 Expression* first_arg;
10285 fn = this->interface_method_function(interface_method, &first_arg,
10286 location);
10287 fn_args[0] = first_arg->get_backend(context);
10290 Bexpression* bclosure = NULL;
10291 if (has_closure_arg)
10292 bclosure = closure->get_backend(context);
10293 else
10294 go_assert(closure == NULL);
10296 Bexpression* bfn = fn->get_backend(context);
10298 // When not calling a named function directly, use a type conversion
10299 // in case the type of the function is a recursive type which refers
10300 // to itself. We don't do this for an interface method because 1)
10301 // an interface method never refers to itself, so we always have a
10302 // function type here; 2) we pass an extra first argument to an
10303 // interface method, so fntype is not correct.
10304 if (func == NULL && !is_interface_method)
10306 Btype* bft = fntype->get_backend_fntype(gogo);
10307 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10310 Bfunction* bfunction = NULL;
10311 if (context->function())
10312 bfunction = context->function()->func_value()->get_decl();
10313 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10314 fn_args, bclosure,
10315 location);
10317 if (this->call_temp_ != NULL)
10319 // This case occurs when the call returns multiple results.
10321 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10322 location);
10323 Bexpression* bref = ref->get_backend(context);
10324 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10325 bref, call,
10326 location);
10328 ref = Expression::make_temporary_reference(this->call_temp_, location);
10329 this->call_ = ref->get_backend(context);
10331 return gogo->backend()->compound_expression(bassn, this->call_,
10332 location);
10335 this->call_ = call;
10336 return this->call_;
10339 // Dump ast representation for a call expressin.
10341 void
10342 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10344 this->fn_->dump_expression(ast_dump_context);
10345 ast_dump_context->ostream() << "(";
10346 if (args_ != NULL)
10347 ast_dump_context->dump_expression_list(this->args_);
10349 ast_dump_context->ostream() << ") ";
10352 // Make a call expression.
10354 Call_expression*
10355 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10356 Location location)
10358 return new Call_expression(fn, args, is_varargs, location);
10361 // Class Call_result_expression.
10363 // Traverse a call result.
10366 Call_result_expression::do_traverse(Traverse* traverse)
10368 if (traverse->remember_expression(this->call_))
10370 // We have already traversed the call expression.
10371 return TRAVERSE_CONTINUE;
10373 return Expression::traverse(&this->call_, traverse);
10376 // Get the type.
10378 Type*
10379 Call_result_expression::do_type()
10381 if (this->classification() == EXPRESSION_ERROR)
10382 return Type::make_error_type();
10384 // THIS->CALL_ can be replaced with a temporary reference due to
10385 // Call_expression::do_must_eval_in_order when there is an error.
10386 Call_expression* ce = this->call_->call_expression();
10387 if (ce == NULL)
10389 this->set_is_error();
10390 return Type::make_error_type();
10392 Function_type* fntype = ce->get_function_type();
10393 if (fntype == NULL)
10395 if (ce->issue_error())
10397 if (!ce->fn()->type()->is_error())
10398 this->report_error(_("expected function"));
10400 this->set_is_error();
10401 return Type::make_error_type();
10403 const Typed_identifier_list* results = fntype->results();
10404 if (results == NULL || results->size() < 2)
10406 if (ce->issue_error())
10407 this->report_error(_("number of results does not match "
10408 "number of values"));
10409 return Type::make_error_type();
10411 Typed_identifier_list::const_iterator pr = results->begin();
10412 for (unsigned int i = 0; i < this->index_; ++i)
10414 if (pr == results->end())
10415 break;
10416 ++pr;
10418 if (pr == results->end())
10420 if (ce->issue_error())
10421 this->report_error(_("number of results does not match "
10422 "number of values"));
10423 return Type::make_error_type();
10425 return pr->type();
10428 // Check the type. Just make sure that we trigger the warning in
10429 // do_type.
10431 void
10432 Call_result_expression::do_check_types(Gogo*)
10434 this->type();
10437 // Determine the type. We have nothing to do here, but the 0 result
10438 // needs to pass down to the caller.
10440 void
10441 Call_result_expression::do_determine_type(const Type_context*)
10443 this->call_->determine_type_no_context();
10446 // Return the backend representation. We just refer to the temporary set by the
10447 // call expression. We don't do this at lowering time because it makes it
10448 // hard to evaluate the call at the right time.
10450 Bexpression*
10451 Call_result_expression::do_get_backend(Translate_context* context)
10453 Call_expression* ce = this->call_->call_expression();
10454 if (ce == NULL)
10456 go_assert(this->call_->is_error_expression());
10457 return context->backend()->error_expression();
10459 Temporary_statement* ts = ce->results();
10460 if (ts == NULL)
10462 go_assert(saw_errors());
10463 return context->backend()->error_expression();
10465 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10466 ref = Expression::make_field_reference(ref, this->index_, this->location());
10467 return ref->get_backend(context);
10470 // Dump ast representation for a call result expression.
10472 void
10473 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10474 const
10476 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10477 // (struct) and the fields are referenced instead.
10478 ast_dump_context->ostream() << this->index_ << "@(";
10479 ast_dump_context->dump_expression(this->call_);
10480 ast_dump_context->ostream() << ")";
10483 // Make a reference to a single result of a call which returns
10484 // multiple results.
10486 Expression*
10487 Expression::make_call_result(Call_expression* call, unsigned int index)
10489 return new Call_result_expression(call, index);
10492 // Class Index_expression.
10494 // Traversal.
10497 Index_expression::do_traverse(Traverse* traverse)
10499 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10500 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10501 || (this->end_ != NULL
10502 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10503 || (this->cap_ != NULL
10504 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10505 return TRAVERSE_EXIT;
10506 return TRAVERSE_CONTINUE;
10509 // Lower an index expression. This converts the generic index
10510 // expression into an array index, a string index, or a map index.
10512 Expression*
10513 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10515 Location location = this->location();
10516 Expression* left = this->left_;
10517 Expression* start = this->start_;
10518 Expression* end = this->end_;
10519 Expression* cap = this->cap_;
10521 Type* type = left->type();
10522 if (type->is_error())
10524 go_assert(saw_errors());
10525 return Expression::make_error(location);
10527 else if (left->is_type_expression())
10529 go_error_at(location, "attempt to index type expression");
10530 return Expression::make_error(location);
10532 else if (type->array_type() != NULL)
10533 return Expression::make_array_index(left, start, end, cap, location);
10534 else if (type->points_to() != NULL
10535 && type->points_to()->array_type() != NULL
10536 && !type->points_to()->is_slice_type())
10538 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10539 location);
10541 // For an ordinary index into the array, the pointer will be
10542 // dereferenced. For a slice it will not--the resulting slice
10543 // will simply reuse the pointer, which is incorrect if that
10544 // pointer is nil.
10545 if (end != NULL || cap != NULL)
10546 deref->issue_nil_check();
10548 return Expression::make_array_index(deref, start, end, cap, location);
10550 else if (type->is_string_type())
10552 if (cap != NULL)
10554 go_error_at(location, "invalid 3-index slice of string");
10555 return Expression::make_error(location);
10557 return Expression::make_string_index(left, start, end, location);
10559 else if (type->map_type() != NULL)
10561 if (end != NULL || cap != NULL)
10563 go_error_at(location, "invalid slice of map");
10564 return Expression::make_error(location);
10566 return Expression::make_map_index(left, start, location);
10568 else if (cap != NULL)
10570 go_error_at(location,
10571 "invalid 3-index slice of object that is not a slice");
10572 return Expression::make_error(location);
10574 else if (end != NULL)
10576 go_error_at(location,
10577 ("attempt to slice object that is not "
10578 "array, slice, or string"));
10579 return Expression::make_error(location);
10581 else
10583 go_error_at(location,
10584 ("attempt to index object that is not "
10585 "array, slice, string, or map"));
10586 return Expression::make_error(location);
10590 // Write an indexed expression
10591 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10593 void
10594 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10595 const Expression* expr,
10596 const Expression* start,
10597 const Expression* end,
10598 const Expression* cap)
10600 expr->dump_expression(ast_dump_context);
10601 ast_dump_context->ostream() << "[";
10602 start->dump_expression(ast_dump_context);
10603 if (end != NULL)
10605 ast_dump_context->ostream() << ":";
10606 end->dump_expression(ast_dump_context);
10608 if (cap != NULL)
10610 ast_dump_context->ostream() << ":";
10611 cap->dump_expression(ast_dump_context);
10613 ast_dump_context->ostream() << "]";
10616 // Dump ast representation for an index expression.
10618 void
10619 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10620 const
10622 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10623 this->start_, this->end_, this->cap_);
10626 // Make an index expression.
10628 Expression*
10629 Expression::make_index(Expression* left, Expression* start, Expression* end,
10630 Expression* cap, Location location)
10632 return new Index_expression(left, start, end, cap, location);
10635 // Class Array_index_expression.
10637 // Array index traversal.
10640 Array_index_expression::do_traverse(Traverse* traverse)
10642 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10643 return TRAVERSE_EXIT;
10644 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10645 return TRAVERSE_EXIT;
10646 if (this->end_ != NULL)
10648 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10649 return TRAVERSE_EXIT;
10651 if (this->cap_ != NULL)
10653 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10654 return TRAVERSE_EXIT;
10656 return TRAVERSE_CONTINUE;
10659 // Return the type of an array index.
10661 Type*
10662 Array_index_expression::do_type()
10664 if (this->type_ == NULL)
10666 Array_type* type = this->array_->type()->array_type();
10667 if (type == NULL)
10668 this->type_ = Type::make_error_type();
10669 else if (this->end_ == NULL)
10670 this->type_ = type->element_type();
10671 else if (type->is_slice_type())
10673 // A slice of a slice has the same type as the original
10674 // slice.
10675 this->type_ = this->array_->type()->deref();
10677 else
10679 // A slice of an array is a slice.
10680 this->type_ = Type::make_array_type(type->element_type(), NULL);
10683 return this->type_;
10686 // Set the type of an array index.
10688 void
10689 Array_index_expression::do_determine_type(const Type_context*)
10691 this->array_->determine_type_no_context();
10693 Type_context index_context(Type::lookup_integer_type("int"), false);
10694 if (this->start_->is_constant())
10695 this->start_->determine_type(&index_context);
10696 else
10697 this->start_->determine_type_no_context();
10698 if (this->end_ != NULL)
10700 if (this->end_->is_constant())
10701 this->end_->determine_type(&index_context);
10702 else
10703 this->end_->determine_type_no_context();
10705 if (this->cap_ != NULL)
10707 if (this->cap_->is_constant())
10708 this->cap_->determine_type(&index_context);
10709 else
10710 this->cap_->determine_type_no_context();
10714 // Check types of an array index.
10716 void
10717 Array_index_expression::do_check_types(Gogo* gogo)
10719 Numeric_constant nc;
10720 unsigned long v;
10721 if (this->start_->type()->integer_type() == NULL
10722 && !this->start_->type()->is_error()
10723 && (!this->start_->numeric_constant_value(&nc)
10724 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10725 this->report_error(_("index must be integer"));
10726 if (this->end_ != NULL
10727 && this->end_->type()->integer_type() == NULL
10728 && !this->end_->type()->is_error()
10729 && !this->end_->is_nil_expression()
10730 && !this->end_->is_error_expression()
10731 && (!this->end_->numeric_constant_value(&nc)
10732 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10733 this->report_error(_("slice end must be integer"));
10734 if (this->cap_ != NULL
10735 && this->cap_->type()->integer_type() == NULL
10736 && !this->cap_->type()->is_error()
10737 && !this->cap_->is_nil_expression()
10738 && !this->cap_->is_error_expression()
10739 && (!this->cap_->numeric_constant_value(&nc)
10740 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10741 this->report_error(_("slice capacity must be integer"));
10743 Array_type* array_type = this->array_->type()->array_type();
10744 if (array_type == NULL)
10746 go_assert(this->array_->type()->is_error());
10747 return;
10750 unsigned int int_bits =
10751 Type::lookup_integer_type("int")->integer_type()->bits();
10753 Numeric_constant lvalnc;
10754 mpz_t lval;
10755 bool lval_valid = (array_type->length() != NULL
10756 && array_type->length()->numeric_constant_value(&lvalnc)
10757 && lvalnc.to_int(&lval));
10758 Numeric_constant inc;
10759 mpz_t ival;
10760 bool ival_valid = false;
10761 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10763 ival_valid = true;
10764 if (mpz_sgn(ival) < 0
10765 || mpz_sizeinbase(ival, 2) >= int_bits
10766 || (lval_valid
10767 && (this->end_ == NULL
10768 ? mpz_cmp(ival, lval) >= 0
10769 : mpz_cmp(ival, lval) > 0)))
10771 go_error_at(this->start_->location(), "array index out of bounds");
10772 this->set_is_error();
10775 if (this->end_ != NULL && !this->end_->is_nil_expression())
10777 Numeric_constant enc;
10778 mpz_t eval;
10779 bool eval_valid = false;
10780 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10782 eval_valid = true;
10783 if (mpz_sgn(eval) < 0
10784 || mpz_sizeinbase(eval, 2) >= int_bits
10785 || (lval_valid && mpz_cmp(eval, lval) > 0))
10787 go_error_at(this->end_->location(), "array index out of bounds");
10788 this->set_is_error();
10790 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10791 this->report_error(_("inverted slice range"));
10794 Numeric_constant cnc;
10795 mpz_t cval;
10796 if (this->cap_ != NULL
10797 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10799 if (mpz_sgn(cval) < 0
10800 || mpz_sizeinbase(cval, 2) >= int_bits
10801 || (lval_valid && mpz_cmp(cval, lval) > 0))
10803 go_error_at(this->cap_->location(), "array index out of bounds");
10804 this->set_is_error();
10806 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10808 go_error_at(this->cap_->location(),
10809 "invalid slice index: capacity less than start");
10810 this->set_is_error();
10812 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10814 go_error_at(this->cap_->location(),
10815 "invalid slice index: capacity less than length");
10816 this->set_is_error();
10818 mpz_clear(cval);
10821 if (eval_valid)
10822 mpz_clear(eval);
10824 if (ival_valid)
10825 mpz_clear(ival);
10826 if (lval_valid)
10827 mpz_clear(lval);
10829 // A slice of an array requires an addressable array. A slice of a
10830 // slice is always possible.
10831 if (this->end_ != NULL && !array_type->is_slice_type())
10833 if (!this->array_->is_addressable())
10834 this->report_error(_("slice of unaddressable value"));
10835 else
10837 bool escapes = true;
10839 // When compiling the runtime, a slice operation does not
10840 // cause local variables to escape. When escape analysis
10841 // becomes the default, this should be changed to make it an
10842 // error if we have a slice operation that escapes.
10843 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
10844 escapes = false;
10846 this->array_->address_taken(escapes);
10851 // Flatten array indexing by using temporary variables for slices and indexes.
10853 Expression*
10854 Array_index_expression::do_flatten(Gogo*, Named_object*,
10855 Statement_inserter* inserter)
10857 Location loc = this->location();
10858 Expression* array = this->array_;
10859 Expression* start = this->start_;
10860 Expression* end = this->end_;
10861 Expression* cap = this->cap_;
10862 if (array->is_error_expression()
10863 || array->type()->is_error_type()
10864 || start->is_error_expression()
10865 || start->type()->is_error_type()
10866 || (end != NULL
10867 && (end->is_error_expression() || end->type()->is_error_type()))
10868 || (cap != NULL
10869 && (cap->is_error_expression() || cap->type()->is_error_type())))
10871 go_assert(saw_errors());
10872 return Expression::make_error(loc);
10875 Temporary_statement* temp;
10876 if (array->type()->is_slice_type() && !array->is_variable())
10878 temp = Statement::make_temporary(NULL, array, loc);
10879 inserter->insert(temp);
10880 this->array_ = Expression::make_temporary_reference(temp, loc);
10882 if (!start->is_variable())
10884 temp = Statement::make_temporary(NULL, start, loc);
10885 inserter->insert(temp);
10886 this->start_ = Expression::make_temporary_reference(temp, loc);
10888 if (end != NULL
10889 && !end->is_nil_expression()
10890 && !end->is_variable())
10892 temp = Statement::make_temporary(NULL, end, loc);
10893 inserter->insert(temp);
10894 this->end_ = Expression::make_temporary_reference(temp, loc);
10896 if (cap != NULL && !cap->is_variable())
10898 temp = Statement::make_temporary(NULL, cap, loc);
10899 inserter->insert(temp);
10900 this->cap_ = Expression::make_temporary_reference(temp, loc);
10903 return this;
10906 // Return whether this expression is addressable.
10908 bool
10909 Array_index_expression::do_is_addressable() const
10911 // A slice expression is not addressable.
10912 if (this->end_ != NULL)
10913 return false;
10915 // An index into a slice is addressable.
10916 if (this->array_->type()->is_slice_type())
10917 return true;
10919 // An index into an array is addressable if the array is
10920 // addressable.
10921 return this->array_->is_addressable();
10924 // Get the backend representation for an array index.
10926 Bexpression*
10927 Array_index_expression::do_get_backend(Translate_context* context)
10929 Array_type* array_type = this->array_->type()->array_type();
10930 if (array_type == NULL)
10932 go_assert(this->array_->type()->is_error());
10933 return context->backend()->error_expression();
10935 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10937 Location loc = this->location();
10938 Gogo* gogo = context->gogo();
10940 Type* int_type = Type::lookup_integer_type("int");
10941 Btype* int_btype = int_type->get_backend(gogo);
10943 // We need to convert the length and capacity to the Go "int" type here
10944 // because the length of a fixed-length array could be of type "uintptr"
10945 // and gimple disallows binary operations between "uintptr" and other
10946 // integer types. FIXME.
10947 Bexpression* length = NULL;
10948 if (this->end_ == NULL || this->end_->is_nil_expression())
10950 Expression* len = array_type->get_length(gogo, this->array_);
10951 length = len->get_backend(context);
10952 length = gogo->backend()->convert_expression(int_btype, length, loc);
10955 Bexpression* capacity = NULL;
10956 if (this->end_ != NULL)
10958 Expression* cap = array_type->get_capacity(gogo, this->array_);
10959 capacity = cap->get_backend(context);
10960 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10963 Bexpression* cap_arg = capacity;
10964 if (this->cap_ != NULL)
10966 cap_arg = this->cap_->get_backend(context);
10967 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10970 if (length == NULL)
10971 length = cap_arg;
10973 int code = (array_type->length() != NULL
10974 ? (this->end_ == NULL
10975 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10976 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10977 : (this->end_ == NULL
10978 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10979 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10980 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10982 if (this->start_->type()->integer_type() == NULL
10983 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10985 go_assert(saw_errors());
10986 return context->backend()->error_expression();
10989 Bexpression* bad_index =
10990 Expression::check_bounds(this->start_, loc)->get_backend(context);
10992 Bexpression* start = this->start_->get_backend(context);
10993 start = gogo->backend()->convert_expression(int_btype, start, loc);
10994 Bexpression* start_too_large =
10995 gogo->backend()->binary_expression((this->end_ == NULL
10996 ? OPERATOR_GE
10997 : OPERATOR_GT),
10998 start,
10999 (this->end_ == NULL
11000 ? length
11001 : capacity),
11002 loc);
11003 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
11004 bad_index, loc);
11006 Bfunction* bfn = context->function()->func_value()->get_decl();
11007 if (this->end_ == NULL)
11009 // Simple array indexing. This has to return an l-value, so
11010 // wrap the index check into START.
11011 start =
11012 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
11013 crash, start, loc);
11015 Bexpression* ret;
11016 if (array_type->length() != NULL)
11018 Bexpression* array = this->array_->get_backend(context);
11019 ret = gogo->backend()->array_index_expression(array, start, loc);
11021 else
11023 // Slice.
11024 Expression* valptr =
11025 array_type->get_value_pointer(gogo, this->array_,
11026 this->is_lvalue_);
11027 Bexpression* ptr = valptr->get_backend(context);
11028 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11030 Type* ele_type = this->array_->type()->array_type()->element_type();
11031 Btype* ele_btype = ele_type->get_backend(gogo);
11032 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11034 return ret;
11037 // Array slice.
11039 if (this->cap_ != NULL)
11041 Bexpression* bounds_bcheck =
11042 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11043 bad_index =
11044 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11045 bad_index, loc);
11046 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11048 Bexpression* cap_too_small =
11049 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11050 Bexpression* cap_too_large =
11051 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11052 Bexpression* bad_cap =
11053 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11054 cap_too_large, loc);
11055 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11056 bad_index, loc);
11059 Bexpression* end;
11060 if (this->end_->is_nil_expression())
11061 end = length;
11062 else
11064 Bexpression* bounds_bcheck =
11065 Expression::check_bounds(this->end_, loc)->get_backend(context);
11067 bad_index =
11068 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11069 bad_index, loc);
11071 end = this->end_->get_backend(context);
11072 end = gogo->backend()->convert_expression(int_btype, end, loc);
11073 Bexpression* end_too_small =
11074 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11075 Bexpression* end_too_large =
11076 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11077 Bexpression* bad_end =
11078 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11079 end_too_large, loc);
11080 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11081 bad_index, loc);
11084 Bexpression* result_length =
11085 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11087 Bexpression* result_capacity =
11088 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11090 // If the new capacity is zero, don't change val. Otherwise we can
11091 // get a pointer to the next object in memory, keeping it live
11092 // unnecessarily. When the capacity is zero, the actual pointer
11093 // value doesn't matter.
11094 Bexpression* zero =
11095 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11096 Bexpression* cond =
11097 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11098 loc);
11099 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11100 cond, zero,
11101 start, loc);
11102 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11103 this->is_lvalue_);
11104 Bexpression* val = valptr->get_backend(context);
11105 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11107 Btype* struct_btype = this->type()->get_backend(gogo);
11108 std::vector<Bexpression*> init;
11109 init.push_back(val);
11110 init.push_back(result_length);
11111 init.push_back(result_capacity);
11113 Bexpression* ctor =
11114 gogo->backend()->constructor_expression(struct_btype, init, loc);
11115 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11116 crash, ctor, loc);
11119 // Dump ast representation for an array index expression.
11121 void
11122 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11123 const
11125 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11126 this->start_, this->end_, this->cap_);
11129 // Make an array index expression. END and CAP may be NULL.
11131 Expression*
11132 Expression::make_array_index(Expression* array, Expression* start,
11133 Expression* end, Expression* cap,
11134 Location location)
11136 return new Array_index_expression(array, start, end, cap, location);
11139 // Class String_index_expression.
11141 // String index traversal.
11144 String_index_expression::do_traverse(Traverse* traverse)
11146 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11147 return TRAVERSE_EXIT;
11148 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11149 return TRAVERSE_EXIT;
11150 if (this->end_ != NULL)
11152 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11153 return TRAVERSE_EXIT;
11155 return TRAVERSE_CONTINUE;
11158 Expression*
11159 String_index_expression::do_flatten(Gogo*, Named_object*,
11160 Statement_inserter* inserter)
11162 Location loc = this->location();
11163 Expression* string = this->string_;
11164 Expression* start = this->start_;
11165 Expression* end = this->end_;
11166 if (string->is_error_expression()
11167 || string->type()->is_error_type()
11168 || start->is_error_expression()
11169 || start->type()->is_error_type()
11170 || (end != NULL
11171 && (end->is_error_expression() || end->type()->is_error_type())))
11173 go_assert(saw_errors());
11174 return Expression::make_error(loc);
11177 Temporary_statement* temp;
11178 if (!this->string_->is_variable())
11180 temp = Statement::make_temporary(NULL, this->string_, loc);
11181 inserter->insert(temp);
11182 this->string_ = Expression::make_temporary_reference(temp, loc);
11184 if (!this->start_->is_variable())
11186 temp = Statement::make_temporary(NULL, this->start_, loc);
11187 inserter->insert(temp);
11188 this->start_ = Expression::make_temporary_reference(temp, loc);
11190 if (this->end_ != NULL
11191 && !this->end_->is_nil_expression()
11192 && !this->end_->is_variable())
11194 temp = Statement::make_temporary(NULL, this->end_, loc);
11195 inserter->insert(temp);
11196 this->end_ = Expression::make_temporary_reference(temp, loc);
11199 return this;
11202 // Return the type of a string index.
11204 Type*
11205 String_index_expression::do_type()
11207 if (this->end_ == NULL)
11208 return Type::lookup_integer_type("uint8");
11209 else
11210 return this->string_->type();
11213 // Determine the type of a string index.
11215 void
11216 String_index_expression::do_determine_type(const Type_context*)
11218 this->string_->determine_type_no_context();
11220 Type_context index_context(Type::lookup_integer_type("int"), false);
11221 if (this->start_->is_constant())
11222 this->start_->determine_type(&index_context);
11223 else
11224 this->start_->determine_type_no_context();
11225 if (this->end_ != NULL)
11227 if (this->end_->is_constant())
11228 this->end_->determine_type(&index_context);
11229 else
11230 this->end_->determine_type_no_context();
11234 // Check types of a string index.
11236 void
11237 String_index_expression::do_check_types(Gogo*)
11239 Numeric_constant nc;
11240 unsigned long v;
11241 if (this->start_->type()->integer_type() == NULL
11242 && !this->start_->type()->is_error()
11243 && (!this->start_->numeric_constant_value(&nc)
11244 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11245 this->report_error(_("index must be integer"));
11246 if (this->end_ != NULL
11247 && this->end_->type()->integer_type() == NULL
11248 && !this->end_->type()->is_error()
11249 && !this->end_->is_nil_expression()
11250 && !this->end_->is_error_expression()
11251 && (!this->end_->numeric_constant_value(&nc)
11252 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11253 this->report_error(_("slice end must be integer"));
11255 std::string sval;
11256 bool sval_valid = this->string_->string_constant_value(&sval);
11258 Numeric_constant inc;
11259 mpz_t ival;
11260 bool ival_valid = false;
11261 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11263 ival_valid = true;
11264 if (mpz_sgn(ival) < 0
11265 || (sval_valid
11266 && (this->end_ == NULL
11267 ? mpz_cmp_ui(ival, sval.length()) >= 0
11268 : mpz_cmp_ui(ival, sval.length()) > 0)))
11270 go_error_at(this->start_->location(), "string index out of bounds");
11271 this->set_is_error();
11274 if (this->end_ != NULL && !this->end_->is_nil_expression())
11276 Numeric_constant enc;
11277 mpz_t eval;
11278 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11280 if (mpz_sgn(eval) < 0
11281 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11283 go_error_at(this->end_->location(), "string index out of bounds");
11284 this->set_is_error();
11286 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11287 this->report_error(_("inverted slice range"));
11288 mpz_clear(eval);
11291 if (ival_valid)
11292 mpz_clear(ival);
11295 // Get the backend representation for a string index.
11297 Bexpression*
11298 String_index_expression::do_get_backend(Translate_context* context)
11300 Location loc = this->location();
11301 Expression* string_arg = this->string_;
11302 if (this->string_->type()->points_to() != NULL)
11303 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
11305 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11307 int code = (this->end_ == NULL
11308 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11309 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11311 Gogo* gogo = context->gogo();
11312 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11314 Type* int_type = Type::lookup_integer_type("int");
11316 // It is possible that an error occurred earlier because the start index
11317 // cannot be represented as an integer type. In this case, we shouldn't
11318 // try casting the starting index into an integer since
11319 // Type_conversion_expression will fail to get the backend representation.
11320 // FIXME.
11321 if (this->start_->type()->integer_type() == NULL
11322 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11324 go_assert(saw_errors());
11325 return context->backend()->error_expression();
11328 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11329 Bfunction* bfn = context->function()->func_value()->get_decl();
11331 if (this->end_ == NULL)
11333 Expression* length =
11334 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11336 Expression* start_too_large =
11337 Expression::make_binary(OPERATOR_GE, start, length, loc);
11338 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11339 bad_index, loc);
11340 Expression* bytes =
11341 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11343 Bexpression* bstart = start->get_backend(context);
11344 Bexpression* ptr = bytes->get_backend(context);
11345 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11346 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11347 Bexpression* index =
11348 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11350 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11351 Bexpression* index_error = bad_index->get_backend(context);
11352 return gogo->backend()->conditional_expression(bfn, byte_btype,
11353 index_error, crash,
11354 index, loc);
11357 Expression* end = NULL;
11358 if (this->end_->is_nil_expression())
11359 end = Expression::make_integer_sl(-1, int_type, loc);
11360 else
11362 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11363 bad_index =
11364 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11365 end = Expression::make_cast(int_type, this->end_, loc);
11368 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11369 string_arg, start, end);
11370 Bexpression* bstrslice = strslice->get_backend(context);
11372 Btype* str_btype = strslice->type()->get_backend(gogo);
11373 Bexpression* index_error = bad_index->get_backend(context);
11374 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11375 crash, bstrslice, loc);
11378 // Dump ast representation for a string index expression.
11380 void
11381 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11382 const
11384 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11385 this->start_, this->end_, NULL);
11388 // Make a string index expression. END may be NULL.
11390 Expression*
11391 Expression::make_string_index(Expression* string, Expression* start,
11392 Expression* end, Location location)
11394 return new String_index_expression(string, start, end, location);
11397 // Class Map_index.
11399 // Get the type of the map.
11401 Map_type*
11402 Map_index_expression::get_map_type() const
11404 Map_type* mt = this->map_->type()->map_type();
11405 if (mt == NULL)
11406 go_assert(saw_errors());
11407 return mt;
11410 // Map index traversal.
11413 Map_index_expression::do_traverse(Traverse* traverse)
11415 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11416 return TRAVERSE_EXIT;
11417 return Expression::traverse(&this->index_, traverse);
11420 // We need to pass in a pointer to the key, so flatten the index into a
11421 // temporary variable if it isn't already. The value pointer will be
11422 // dereferenced and checked for nil, so flatten into a temporary to avoid
11423 // recomputation.
11425 Expression*
11426 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11427 Statement_inserter* inserter)
11429 Location loc = this->location();
11430 Map_type* mt = this->get_map_type();
11431 if (this->index()->is_error_expression()
11432 || this->index()->type()->is_error_type()
11433 || mt->is_error_type())
11435 go_assert(saw_errors());
11436 return Expression::make_error(loc);
11439 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11441 if (this->index_->type()->interface_type() != NULL
11442 && !this->index_->is_variable())
11444 Temporary_statement* temp =
11445 Statement::make_temporary(NULL, this->index_, loc);
11446 inserter->insert(temp);
11447 this->index_ = Expression::make_temporary_reference(temp, loc);
11449 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11450 this->index_, loc);
11453 if (!this->index_->is_variable())
11455 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11456 loc);
11457 inserter->insert(temp);
11458 this->index_ = Expression::make_temporary_reference(temp, loc);
11461 if (this->value_pointer_ == NULL)
11462 this->get_value_pointer(gogo);
11463 if (this->value_pointer_->is_error_expression()
11464 || this->value_pointer_->type()->is_error_type())
11465 return Expression::make_error(loc);
11466 if (!this->value_pointer_->is_variable())
11468 Temporary_statement* temp =
11469 Statement::make_temporary(NULL, this->value_pointer_, loc);
11470 inserter->insert(temp);
11471 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11474 return this;
11477 // Return the type of a map index.
11479 Type*
11480 Map_index_expression::do_type()
11482 Map_type* mt = this->get_map_type();
11483 if (mt == NULL)
11484 return Type::make_error_type();
11485 return mt->val_type();
11488 // Fix the type of a map index.
11490 void
11491 Map_index_expression::do_determine_type(const Type_context*)
11493 this->map_->determine_type_no_context();
11494 Map_type* mt = this->get_map_type();
11495 Type* key_type = mt == NULL ? NULL : mt->key_type();
11496 Type_context subcontext(key_type, false);
11497 this->index_->determine_type(&subcontext);
11500 // Check types of a map index.
11502 void
11503 Map_index_expression::do_check_types(Gogo*)
11505 std::string reason;
11506 Map_type* mt = this->get_map_type();
11507 if (mt == NULL)
11508 return;
11509 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11511 if (reason.empty())
11512 this->report_error(_("incompatible type for map index"));
11513 else
11515 go_error_at(this->location(), "incompatible type for map index (%s)",
11516 reason.c_str());
11517 this->set_is_error();
11522 // Get the backend representation for a map index.
11524 Bexpression*
11525 Map_index_expression::do_get_backend(Translate_context* context)
11527 Map_type* type = this->get_map_type();
11528 if (type == NULL)
11530 go_assert(saw_errors());
11531 return context->backend()->error_expression();
11534 go_assert(this->value_pointer_ != NULL
11535 && this->value_pointer_->is_variable());
11537 Expression* val = Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
11538 this->location());
11539 return val->get_backend(context);
11542 // Get an expression for the map index. This returns an expression
11543 // that evaluates to a pointer to a value. If the key is not in the
11544 // map, the pointer will point to a zero value.
11546 Expression*
11547 Map_index_expression::get_value_pointer(Gogo* gogo)
11549 if (this->value_pointer_ == NULL)
11551 Map_type* type = this->get_map_type();
11552 if (type == NULL)
11554 go_assert(saw_errors());
11555 return Expression::make_error(this->location());
11558 Location loc = this->location();
11559 Expression* map_ref = this->map_;
11561 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11562 this->index_,
11563 loc);
11565 Expression* zero = type->fat_zero_value(gogo);
11567 Expression* map_index;
11569 if (zero == NULL)
11570 map_index =
11571 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11572 Expression::make_type_descriptor(type, loc),
11573 map_ref, index_ptr);
11574 else
11575 map_index =
11576 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11577 Expression::make_type_descriptor(type, loc),
11578 map_ref, index_ptr, zero);
11580 Type* val_type = type->val_type();
11581 this->value_pointer_ =
11582 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11583 map_index, this->location());
11586 return this->value_pointer_;
11589 // Dump ast representation for a map index expression
11591 void
11592 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11593 const
11595 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11596 this->index_, NULL, NULL);
11599 // Make a map index expression.
11601 Map_index_expression*
11602 Expression::make_map_index(Expression* map, Expression* index,
11603 Location location)
11605 return new Map_index_expression(map, index, location);
11608 // Class Field_reference_expression.
11610 // Lower a field reference expression. There is nothing to lower, but
11611 // this is where we generate the tracking information for fields with
11612 // the magic go:"track" tag.
11614 Expression*
11615 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11616 Statement_inserter* inserter, int)
11618 Struct_type* struct_type = this->expr_->type()->struct_type();
11619 if (struct_type == NULL)
11621 // Error will be reported elsewhere.
11622 return this;
11624 const Struct_field* field = struct_type->field(this->field_index_);
11625 if (field == NULL)
11626 return this;
11627 if (!field->has_tag())
11628 return this;
11629 if (field->tag().find("go:\"track\"") == std::string::npos)
11630 return this;
11632 // References from functions generated by the compiler don't count.
11633 if (function != NULL && function->func_value()->is_type_specific_function())
11634 return this;
11636 // We have found a reference to a tracked field. Build a call to
11637 // the runtime function __go_fieldtrack with a string that describes
11638 // the field. FIXME: We should only call this once per referenced
11639 // field per function, not once for each reference to the field.
11641 if (this->called_fieldtrack_)
11642 return this;
11643 this->called_fieldtrack_ = true;
11645 Location loc = this->location();
11647 std::string s = "fieldtrack \"";
11648 Named_type* nt = this->expr_->type()->named_type();
11649 if (nt == NULL || nt->named_object()->package() == NULL)
11650 s.append(gogo->pkgpath());
11651 else
11652 s.append(nt->named_object()->package()->pkgpath());
11653 s.push_back('.');
11654 if (nt != NULL)
11655 s.append(Gogo::unpack_hidden_name(nt->name()));
11656 s.push_back('.');
11657 s.append(field->field_name());
11658 s.push_back('"');
11660 // We can't use a string here, because internally a string holds a
11661 // pointer to the actual bytes; when the linker garbage collects the
11662 // string, it won't garbage collect the bytes. So we use a
11663 // [...]byte.
11665 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11667 Type* byte_type = gogo->lookup_global("byte")->type_value();
11668 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11669 array_type->set_is_array_incomparable();
11671 Expression_list* bytes = new Expression_list();
11672 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11674 unsigned char c = static_cast<unsigned char>(*p);
11675 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11678 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11679 bytes, false, loc);
11681 Variable* var = new Variable(array_type, e, true, false, false, loc);
11683 static int count;
11684 char buf[50];
11685 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11686 ++count;
11688 Named_object* no = gogo->add_variable(buf, var);
11689 e = Expression::make_var_reference(no, loc);
11690 e = Expression::make_unary(OPERATOR_AND, e, loc);
11692 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11693 gogo->lower_expression(function, inserter, &call);
11694 inserter->insert(Statement::make_statement(call, false));
11696 // Put this function, and the global variable we just created, into
11697 // unique sections. This will permit the linker to garbage collect
11698 // them if they are not referenced. The effect is that the only
11699 // strings, indicating field references, that will wind up in the
11700 // executable will be those for functions that are actually needed.
11701 if (function != NULL)
11702 function->func_value()->set_in_unique_section();
11703 var->set_in_unique_section();
11705 return this;
11708 // Return the type of a field reference.
11710 Type*
11711 Field_reference_expression::do_type()
11713 Type* type = this->expr_->type();
11714 if (type->is_error())
11715 return type;
11716 Struct_type* struct_type = type->struct_type();
11717 go_assert(struct_type != NULL);
11718 return struct_type->field(this->field_index_)->type();
11721 // Check the types for a field reference.
11723 void
11724 Field_reference_expression::do_check_types(Gogo*)
11726 Type* type = this->expr_->type();
11727 if (type->is_error())
11728 return;
11729 Struct_type* struct_type = type->struct_type();
11730 go_assert(struct_type != NULL);
11731 go_assert(struct_type->field(this->field_index_) != NULL);
11734 // Get the backend representation for a field reference.
11736 Bexpression*
11737 Field_reference_expression::do_get_backend(Translate_context* context)
11739 Bexpression* bstruct = this->expr_->get_backend(context);
11740 return context->gogo()->backend()->struct_field_expression(bstruct,
11741 this->field_index_,
11742 this->location());
11745 // Dump ast representation for a field reference expression.
11747 void
11748 Field_reference_expression::do_dump_expression(
11749 Ast_dump_context* ast_dump_context) const
11751 this->expr_->dump_expression(ast_dump_context);
11752 ast_dump_context->ostream() << "." << this->field_index_;
11755 // Make a reference to a qualified identifier in an expression.
11757 Field_reference_expression*
11758 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11759 Location location)
11761 return new Field_reference_expression(expr, field_index, location);
11764 // Class Interface_field_reference_expression.
11766 // Return an expression for the pointer to the function to call.
11768 Expression*
11769 Interface_field_reference_expression::get_function()
11771 Expression* ref = this->expr_;
11772 Location loc = this->location();
11773 if (ref->type()->points_to() != NULL)
11774 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11776 Expression* mtable =
11777 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11778 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11780 std::string name = Gogo::unpack_hidden_name(this->name_);
11781 unsigned int index;
11782 const Struct_field* field = mtable_type->find_local_field(name, &index);
11783 go_assert(field != NULL);
11784 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11785 return Expression::make_field_reference(mtable, index, loc);
11788 // Return an expression for the first argument to pass to the interface
11789 // function.
11791 Expression*
11792 Interface_field_reference_expression::get_underlying_object()
11794 Expression* expr = this->expr_;
11795 if (expr->type()->points_to() != NULL)
11796 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11797 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11798 this->location());
11801 // Traversal.
11804 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11806 return Expression::traverse(&this->expr_, traverse);
11809 // Lower the expression. If this expression is not called, we need to
11810 // evaluate the expression twice when converting to the backend
11811 // interface. So introduce a temporary variable if necessary.
11813 Expression*
11814 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11815 Statement_inserter* inserter)
11817 if (this->expr_->is_error_expression()
11818 || this->expr_->type()->is_error_type())
11820 go_assert(saw_errors());
11821 return Expression::make_error(this->location());
11824 if (!this->expr_->is_variable())
11826 Temporary_statement* temp =
11827 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11828 inserter->insert(temp);
11829 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11830 this->location());
11832 return this;
11835 // Return the type of an interface field reference.
11837 Type*
11838 Interface_field_reference_expression::do_type()
11840 Type* expr_type = this->expr_->type();
11842 Type* points_to = expr_type->points_to();
11843 if (points_to != NULL)
11844 expr_type = points_to;
11846 Interface_type* interface_type = expr_type->interface_type();
11847 if (interface_type == NULL)
11848 return Type::make_error_type();
11850 const Typed_identifier* method = interface_type->find_method(this->name_);
11851 if (method == NULL)
11852 return Type::make_error_type();
11854 return method->type();
11857 // Determine types.
11859 void
11860 Interface_field_reference_expression::do_determine_type(const Type_context*)
11862 this->expr_->determine_type_no_context();
11865 // Check the types for an interface field reference.
11867 void
11868 Interface_field_reference_expression::do_check_types(Gogo*)
11870 Type* type = this->expr_->type();
11872 Type* points_to = type->points_to();
11873 if (points_to != NULL)
11874 type = points_to;
11876 Interface_type* interface_type = type->interface_type();
11877 if (interface_type == NULL)
11879 if (!type->is_error_type())
11880 this->report_error(_("expected interface or pointer to interface"));
11882 else
11884 const Typed_identifier* method =
11885 interface_type->find_method(this->name_);
11886 if (method == NULL)
11888 go_error_at(this->location(), "method %qs not in interface",
11889 Gogo::message_name(this->name_).c_str());
11890 this->set_is_error();
11895 // If an interface field reference is not simply called, then it is
11896 // represented as a closure. The closure will hold a single variable,
11897 // the value of the interface on which the method should be called.
11898 // The function will be a simple thunk that pulls the value from the
11899 // closure and calls the method with the remaining arguments.
11901 // Because method values are not common, we don't build all thunks for
11902 // all possible interface methods, but instead only build them as we
11903 // need them. In particular, we even build them on demand for
11904 // interface methods defined in other packages.
11906 Interface_field_reference_expression::Interface_method_thunks
11907 Interface_field_reference_expression::interface_method_thunks;
11909 // Find or create the thunk to call method NAME on TYPE.
11911 Named_object*
11912 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11913 Interface_type* type,
11914 const std::string& name)
11916 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11917 std::pair<Interface_method_thunks::iterator, bool> ins =
11918 Interface_field_reference_expression::interface_method_thunks.insert(val);
11919 if (ins.second)
11921 // This is the first time we have seen this interface.
11922 ins.first->second = new Method_thunks();
11925 for (Method_thunks::const_iterator p = ins.first->second->begin();
11926 p != ins.first->second->end();
11927 p++)
11928 if (p->first == name)
11929 return p->second;
11931 Location loc = type->location();
11933 const Typed_identifier* method_id = type->find_method(name);
11934 if (method_id == NULL)
11935 return Named_object::make_erroneous_name(Gogo::thunk_name());
11937 Function_type* orig_fntype = method_id->type()->function_type();
11938 if (orig_fntype == NULL)
11939 return Named_object::make_erroneous_name(Gogo::thunk_name());
11941 Struct_field_list* sfl = new Struct_field_list();
11942 // The type here is wrong--it should be the C function type. But it
11943 // doesn't really matter.
11944 Type* vt = Type::make_pointer_type(Type::make_void_type());
11945 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11946 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11947 Struct_type* st = Type::make_struct_type(sfl, loc);
11948 st->set_is_struct_incomparable();
11949 Type* closure_type = Type::make_pointer_type(st);
11951 Function_type* new_fntype = orig_fntype->copy_with_names();
11953 std::string thunk_name = Gogo::thunk_name();
11954 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11955 false, loc);
11957 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11958 cvar->set_is_used();
11959 cvar->set_is_closure();
11960 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11961 NULL, cvar);
11962 new_no->func_value()->set_closure_var(cp);
11964 gogo->start_block(loc);
11966 // Field 0 of the closure is the function code pointer, field 1 is
11967 // the value on which to invoke the method.
11968 Expression* arg = Expression::make_var_reference(cp, loc);
11969 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11970 arg = Expression::make_field_reference(arg, 1, loc);
11972 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11973 loc);
11975 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11976 Expression_list* args;
11977 if (orig_params == NULL || orig_params->empty())
11978 args = NULL;
11979 else
11981 const Typed_identifier_list* new_params = new_fntype->parameters();
11982 args = new Expression_list();
11983 for (Typed_identifier_list::const_iterator p = new_params->begin();
11984 p != new_params->end();
11985 ++p)
11987 Named_object* p_no = gogo->lookup(p->name(), NULL);
11988 go_assert(p_no != NULL
11989 && p_no->is_variable()
11990 && p_no->var_value()->is_parameter());
11991 args->push_back(Expression::make_var_reference(p_no, loc));
11995 Call_expression* call = Expression::make_call(ifre, args,
11996 orig_fntype->is_varargs(),
11997 loc);
11998 call->set_varargs_are_lowered();
12000 Statement* s = Statement::make_return_from_call(call, loc);
12001 gogo->add_statement(s);
12002 Block* b = gogo->finish_block(loc);
12003 gogo->add_block(b, loc);
12004 gogo->lower_block(new_no, b);
12005 gogo->flatten_block(new_no, b);
12006 gogo->finish_function(loc);
12008 ins.first->second->push_back(std::make_pair(name, new_no));
12009 return new_no;
12012 // Get the backend representation for a method value.
12014 Bexpression*
12015 Interface_field_reference_expression::do_get_backend(Translate_context* context)
12017 Interface_type* type = this->expr_->type()->interface_type();
12018 if (type == NULL)
12020 go_assert(saw_errors());
12021 return context->backend()->error_expression();
12024 Named_object* thunk =
12025 Interface_field_reference_expression::create_thunk(context->gogo(),
12026 type, this->name_);
12027 if (thunk->is_erroneous())
12029 go_assert(saw_errors());
12030 return context->backend()->error_expression();
12033 // FIXME: We should lower this earlier, but we can't it lower it in
12034 // the lowering pass because at that point we don't know whether we
12035 // need to create the thunk or not. If the expression is called, we
12036 // don't need the thunk.
12038 Location loc = this->location();
12040 Struct_field_list* fields = new Struct_field_list();
12041 fields->push_back(Struct_field(Typed_identifier("fn.0",
12042 thunk->func_value()->type(),
12043 loc)));
12044 fields->push_back(Struct_field(Typed_identifier("val.1",
12045 this->expr_->type(),
12046 loc)));
12047 Struct_type* st = Type::make_struct_type(fields, loc);
12048 st->set_is_struct_incomparable();
12050 Expression_list* vals = new Expression_list();
12051 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12052 vals->push_back(this->expr_);
12054 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12055 Bexpression* bclosure =
12056 Expression::make_heap_expression(expr, loc)->get_backend(context);
12058 Gogo* gogo = context->gogo();
12059 Btype* btype = this->type()->get_backend(gogo);
12060 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12062 Expression* nil_check =
12063 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12064 Expression::make_nil(loc), loc);
12065 Bexpression* bnil_check = nil_check->get_backend(context);
12067 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12068 loc)->get_backend(context);
12070 Bfunction* bfn = context->function()->func_value()->get_decl();
12071 Bexpression* bcond =
12072 gogo->backend()->conditional_expression(bfn, NULL,
12073 bnil_check, bcrash, NULL, loc);
12074 Bfunction* bfunction = context->function()->func_value()->get_decl();
12075 Bstatement* cond_statement =
12076 gogo->backend()->expression_statement(bfunction, bcond);
12077 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12080 // Dump ast representation for an interface field reference.
12082 void
12083 Interface_field_reference_expression::do_dump_expression(
12084 Ast_dump_context* ast_dump_context) const
12086 this->expr_->dump_expression(ast_dump_context);
12087 ast_dump_context->ostream() << "." << this->name_;
12090 // Make a reference to a field in an interface.
12092 Expression*
12093 Expression::make_interface_field_reference(Expression* expr,
12094 const std::string& field,
12095 Location location)
12097 return new Interface_field_reference_expression(expr, field, location);
12100 // A general selector. This is a Parser_expression for LEFT.NAME. It
12101 // is lowered after we know the type of the left hand side.
12103 class Selector_expression : public Parser_expression
12105 public:
12106 Selector_expression(Expression* left, const std::string& name,
12107 Location location)
12108 : Parser_expression(EXPRESSION_SELECTOR, location),
12109 left_(left), name_(name)
12112 protected:
12114 do_traverse(Traverse* traverse)
12115 { return Expression::traverse(&this->left_, traverse); }
12117 Expression*
12118 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12120 Expression*
12121 do_copy()
12123 return new Selector_expression(this->left_->copy(), this->name_,
12124 this->location());
12127 void
12128 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12130 private:
12131 Expression*
12132 lower_method_expression(Gogo*);
12134 // The expression on the left hand side.
12135 Expression* left_;
12136 // The name on the right hand side.
12137 std::string name_;
12140 // Lower a selector expression once we know the real type of the left
12141 // hand side.
12143 Expression*
12144 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12145 int)
12147 Expression* left = this->left_;
12148 if (left->is_type_expression())
12149 return this->lower_method_expression(gogo);
12150 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12151 this->location());
12154 // Lower a method expression T.M or (*T).M. We turn this into a
12155 // function literal.
12157 Expression*
12158 Selector_expression::lower_method_expression(Gogo* gogo)
12160 Location location = this->location();
12161 Type* left_type = this->left_->type();
12162 Type* type = left_type;
12163 const std::string& name(this->name_);
12165 bool is_pointer;
12166 if (type->points_to() == NULL)
12167 is_pointer = false;
12168 else
12170 is_pointer = true;
12171 type = type->points_to();
12173 Named_type* nt = type->named_type();
12174 if (nt == NULL)
12176 go_error_at(location,
12177 ("method expression requires named type or "
12178 "pointer to named type"));
12179 return Expression::make_error(location);
12182 bool is_ambiguous;
12183 Method* method = nt->method_function(name, &is_ambiguous);
12184 const Typed_identifier* imethod = NULL;
12185 if (method == NULL && !is_pointer)
12187 Interface_type* it = nt->interface_type();
12188 if (it != NULL)
12189 imethod = it->find_method(name);
12192 if ((method == NULL && imethod == NULL)
12193 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12195 if (!is_ambiguous)
12196 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12197 is_pointer ? "*" : "",
12198 nt->message_name().c_str(),
12199 Gogo::message_name(name).c_str());
12200 else
12201 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12202 Gogo::message_name(name).c_str(),
12203 is_pointer ? "*" : "",
12204 nt->message_name().c_str());
12205 return Expression::make_error(location);
12208 if (method != NULL && !is_pointer && !method->is_value_method())
12210 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12211 nt->message_name().c_str(),
12212 Gogo::message_name(name).c_str());
12213 return Expression::make_error(location);
12216 // Build a new function type in which the receiver becomes the first
12217 // argument.
12218 Function_type* method_type;
12219 if (method != NULL)
12221 method_type = method->type();
12222 go_assert(method_type->is_method());
12224 else
12226 method_type = imethod->type()->function_type();
12227 go_assert(method_type != NULL && !method_type->is_method());
12230 const char* const receiver_name = "$this";
12231 Typed_identifier_list* parameters = new Typed_identifier_list();
12232 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12233 location));
12235 const Typed_identifier_list* method_parameters = method_type->parameters();
12236 if (method_parameters != NULL)
12238 int i = 0;
12239 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12240 p != method_parameters->end();
12241 ++p, ++i)
12243 if (!p->name().empty())
12244 parameters->push_back(*p);
12245 else
12247 char buf[20];
12248 snprintf(buf, sizeof buf, "$param%d", i);
12249 parameters->push_back(Typed_identifier(buf, p->type(),
12250 p->location()));
12255 const Typed_identifier_list* method_results = method_type->results();
12256 Typed_identifier_list* results;
12257 if (method_results == NULL)
12258 results = NULL;
12259 else
12261 results = new Typed_identifier_list();
12262 for (Typed_identifier_list::const_iterator p = method_results->begin();
12263 p != method_results->end();
12264 ++p)
12265 results->push_back(*p);
12268 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12269 location);
12270 if (method_type->is_varargs())
12271 fntype->set_is_varargs();
12273 // We generate methods which always takes a pointer to the receiver
12274 // as their first argument. If this is for a pointer type, we can
12275 // simply reuse the existing function. We use an internal hack to
12276 // get the right type.
12277 // FIXME: This optimization is disabled because it doesn't yet work
12278 // with function descriptors when the method expression is not
12279 // directly called.
12280 if (method != NULL && is_pointer && false)
12282 Named_object* mno = (method->needs_stub_method()
12283 ? method->stub_object()
12284 : method->named_object());
12285 Expression* f = Expression::make_func_reference(mno, NULL, location);
12286 f = Expression::make_cast(fntype, f, location);
12287 Type_conversion_expression* tce =
12288 static_cast<Type_conversion_expression*>(f);
12289 tce->set_may_convert_function_types();
12290 return f;
12293 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12294 location);
12296 Named_object* vno = gogo->lookup(receiver_name, NULL);
12297 go_assert(vno != NULL);
12298 Expression* ve = Expression::make_var_reference(vno, location);
12299 Expression* bm;
12300 if (method != NULL)
12301 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12302 else
12303 bm = Expression::make_interface_field_reference(ve, name, location);
12305 // Even though we found the method above, if it has an error type we
12306 // may see an error here.
12307 if (bm->is_error_expression())
12309 gogo->finish_function(location);
12310 return bm;
12313 Expression_list* args;
12314 if (parameters->size() <= 1)
12315 args = NULL;
12316 else
12318 args = new Expression_list();
12319 Typed_identifier_list::const_iterator p = parameters->begin();
12320 ++p;
12321 for (; p != parameters->end(); ++p)
12323 vno = gogo->lookup(p->name(), NULL);
12324 go_assert(vno != NULL);
12325 args->push_back(Expression::make_var_reference(vno, location));
12329 gogo->start_block(location);
12331 Call_expression* call = Expression::make_call(bm, args,
12332 method_type->is_varargs(),
12333 location);
12335 Statement* s = Statement::make_return_from_call(call, location);
12336 gogo->add_statement(s);
12338 Block* b = gogo->finish_block(location);
12340 gogo->add_block(b, location);
12342 // Lower the call in case there are multiple results.
12343 gogo->lower_block(no, b);
12344 gogo->flatten_block(no, b);
12346 gogo->finish_function(location);
12348 return Expression::make_func_reference(no, NULL, location);
12351 // Dump the ast for a selector expression.
12353 void
12354 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12355 const
12357 ast_dump_context->dump_expression(this->left_);
12358 ast_dump_context->ostream() << ".";
12359 ast_dump_context->ostream() << this->name_;
12362 // Make a selector expression.
12364 Expression*
12365 Expression::make_selector(Expression* left, const std::string& name,
12366 Location location)
12368 return new Selector_expression(left, name, location);
12371 // Class Allocation_expression.
12374 Allocation_expression::do_traverse(Traverse* traverse)
12376 return Type::traverse(this->type_, traverse);
12379 Type*
12380 Allocation_expression::do_type()
12382 return Type::make_pointer_type(this->type_);
12385 void
12386 Allocation_expression::do_check_types(Gogo*)
12388 if (!this->type_->in_heap())
12389 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12392 // Make a copy of an allocation expression.
12394 Expression*
12395 Allocation_expression::do_copy()
12397 Allocation_expression* alloc =
12398 new Allocation_expression(this->type_, this->location());
12399 if (this->allocate_on_stack_)
12400 alloc->set_allocate_on_stack();
12401 return alloc;
12404 // Return the backend representation for an allocation expression.
12406 Bexpression*
12407 Allocation_expression::do_get_backend(Translate_context* context)
12409 Gogo* gogo = context->gogo();
12410 Location loc = this->location();
12412 Node* n = Node::make_node(this);
12413 if (this->allocate_on_stack_
12414 || (n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
12416 int64_t size;
12417 bool ok = this->type_->backend_type_size(gogo, &size);
12418 if (!ok)
12420 go_assert(saw_errors());
12421 return gogo->backend()->error_expression();
12423 return gogo->backend()->stack_allocation_expression(size, loc);
12426 Btype* btype = this->type_->get_backend(gogo);
12427 Bexpression* space =
12428 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12429 Btype* pbtype = gogo->backend()->pointer_type(btype);
12430 return gogo->backend()->convert_expression(pbtype, space, loc);
12433 // Dump ast representation for an allocation expression.
12435 void
12436 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12437 const
12439 ast_dump_context->ostream() << "new(";
12440 ast_dump_context->dump_type(this->type_);
12441 ast_dump_context->ostream() << ")";
12444 // Make an allocation expression.
12446 Expression*
12447 Expression::make_allocation(Type* type, Location location)
12449 return new Allocation_expression(type, location);
12452 // Class Ordered_value_list.
12455 Ordered_value_list::traverse_vals(Traverse* traverse)
12457 if (this->vals_ != NULL)
12459 if (this->traverse_order_ == NULL)
12461 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12462 return TRAVERSE_EXIT;
12464 else
12466 for (std::vector<unsigned long>::const_iterator p =
12467 this->traverse_order_->begin();
12468 p != this->traverse_order_->end();
12469 ++p)
12471 if (Expression::traverse(&this->vals_->at(*p), traverse)
12472 == TRAVERSE_EXIT)
12473 return TRAVERSE_EXIT;
12477 return TRAVERSE_CONTINUE;
12480 // Class Struct_construction_expression.
12482 // Traversal.
12485 Struct_construction_expression::do_traverse(Traverse* traverse)
12487 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12488 return TRAVERSE_EXIT;
12489 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12490 return TRAVERSE_EXIT;
12491 return TRAVERSE_CONTINUE;
12494 // Return whether this is a constant initializer.
12496 bool
12497 Struct_construction_expression::is_constant_struct() const
12499 if (this->vals() == NULL)
12500 return true;
12501 for (Expression_list::const_iterator pv = this->vals()->begin();
12502 pv != this->vals()->end();
12503 ++pv)
12505 if (*pv != NULL
12506 && !(*pv)->is_constant()
12507 && (!(*pv)->is_composite_literal()
12508 || (*pv)->is_nonconstant_composite_literal()))
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 // Return whether this struct can be used as a constant initializer.
12527 bool
12528 Struct_construction_expression::do_is_static_initializer() const
12530 if (this->vals() == NULL)
12531 return true;
12532 for (Expression_list::const_iterator pv = this->vals()->begin();
12533 pv != this->vals()->end();
12534 ++pv)
12536 if (*pv != NULL && !(*pv)->is_static_initializer())
12537 return false;
12540 const Struct_field_list* fields = this->type_->struct_type()->fields();
12541 for (Struct_field_list::const_iterator pf = fields->begin();
12542 pf != fields->end();
12543 ++pf)
12545 // There are no constant constructors for interfaces.
12546 if (pf->type()->interface_type() != NULL)
12547 return false;
12550 return true;
12553 // Final type determination.
12555 void
12556 Struct_construction_expression::do_determine_type(const Type_context*)
12558 if (this->vals() == NULL)
12559 return;
12560 const Struct_field_list* fields = this->type_->struct_type()->fields();
12561 Expression_list::const_iterator pv = this->vals()->begin();
12562 for (Struct_field_list::const_iterator pf = fields->begin();
12563 pf != fields->end();
12564 ++pf, ++pv)
12566 if (pv == this->vals()->end())
12567 return;
12568 if (*pv != NULL)
12570 Type_context subcontext(pf->type(), false);
12571 (*pv)->determine_type(&subcontext);
12574 // Extra values are an error we will report elsewhere; we still want
12575 // to determine the type to avoid knockon errors.
12576 for (; pv != this->vals()->end(); ++pv)
12577 (*pv)->determine_type_no_context();
12580 // Check types.
12582 void
12583 Struct_construction_expression::do_check_types(Gogo*)
12585 if (this->vals() == NULL)
12586 return;
12588 Struct_type* st = this->type_->struct_type();
12589 if (this->vals()->size() > st->field_count())
12591 this->report_error(_("too many expressions for struct"));
12592 return;
12595 const Struct_field_list* fields = st->fields();
12596 Expression_list::const_iterator pv = this->vals()->begin();
12597 int i = 0;
12598 for (Struct_field_list::const_iterator pf = fields->begin();
12599 pf != fields->end();
12600 ++pf, ++pv, ++i)
12602 if (pv == this->vals()->end())
12604 this->report_error(_("too few expressions for struct"));
12605 break;
12608 if (*pv == NULL)
12609 continue;
12611 std::string reason;
12612 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12614 if (reason.empty())
12615 go_error_at((*pv)->location(),
12616 "incompatible type for field %d in struct construction",
12617 i + 1);
12618 else
12619 go_error_at((*pv)->location(),
12620 ("incompatible type for field %d in "
12621 "struct construction (%s)"),
12622 i + 1, reason.c_str());
12623 this->set_is_error();
12626 go_assert(pv == this->vals()->end());
12629 // Flatten a struct construction expression. Store the values into
12630 // temporaries in case they need interface conversion.
12632 Expression*
12633 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12634 Statement_inserter* inserter)
12636 if (this->vals() == NULL)
12637 return this;
12639 // If this is a constant struct, we don't need temporaries.
12640 if (this->is_constant_struct() || this->is_static_initializer())
12641 return this;
12643 Location loc = this->location();
12644 for (Expression_list::iterator pv = this->vals()->begin();
12645 pv != this->vals()->end();
12646 ++pv)
12648 if (*pv != NULL)
12650 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12652 go_assert(saw_errors());
12653 return Expression::make_error(loc);
12655 if (!(*pv)->is_variable())
12657 Temporary_statement* temp =
12658 Statement::make_temporary(NULL, *pv, loc);
12659 inserter->insert(temp);
12660 *pv = Expression::make_temporary_reference(temp, loc);
12664 return this;
12667 // Return the backend representation for constructing a struct.
12669 Bexpression*
12670 Struct_construction_expression::do_get_backend(Translate_context* context)
12672 Gogo* gogo = context->gogo();
12674 Btype* btype = this->type_->get_backend(gogo);
12675 if (this->vals() == NULL)
12676 return gogo->backend()->zero_expression(btype);
12678 const Struct_field_list* fields = this->type_->struct_type()->fields();
12679 Expression_list::const_iterator pv = this->vals()->begin();
12680 std::vector<Bexpression*> init;
12681 for (Struct_field_list::const_iterator pf = fields->begin();
12682 pf != fields->end();
12683 ++pf)
12685 Btype* fbtype = pf->type()->get_backend(gogo);
12686 if (pv == this->vals()->end())
12687 init.push_back(gogo->backend()->zero_expression(fbtype));
12688 else if (*pv == NULL)
12690 init.push_back(gogo->backend()->zero_expression(fbtype));
12691 ++pv;
12693 else
12695 Expression* val =
12696 Expression::convert_for_assignment(gogo, pf->type(),
12697 *pv, this->location());
12698 init.push_back(val->get_backend(context));
12699 ++pv;
12702 return gogo->backend()->constructor_expression(btype, init, this->location());
12705 // Export a struct construction.
12707 void
12708 Struct_construction_expression::do_export(Export* exp) const
12710 exp->write_c_string("convert(");
12711 exp->write_type(this->type_);
12712 for (Expression_list::const_iterator pv = this->vals()->begin();
12713 pv != this->vals()->end();
12714 ++pv)
12716 exp->write_c_string(", ");
12717 if (*pv != NULL)
12718 (*pv)->export_expression(exp);
12720 exp->write_c_string(")");
12723 // Dump ast representation of a struct construction expression.
12725 void
12726 Struct_construction_expression::do_dump_expression(
12727 Ast_dump_context* ast_dump_context) const
12729 ast_dump_context->dump_type(this->type_);
12730 ast_dump_context->ostream() << "{";
12731 ast_dump_context->dump_expression_list(this->vals());
12732 ast_dump_context->ostream() << "}";
12735 // Make a struct composite literal. This used by the thunk code.
12737 Expression*
12738 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12739 Location location)
12741 go_assert(type->struct_type() != NULL);
12742 return new Struct_construction_expression(type, vals, location);
12745 // Class Array_construction_expression.
12747 // Traversal.
12750 Array_construction_expression::do_traverse(Traverse* traverse)
12752 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12753 return TRAVERSE_EXIT;
12754 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12755 return TRAVERSE_EXIT;
12756 return TRAVERSE_CONTINUE;
12759 // Return whether this is a constant initializer.
12761 bool
12762 Array_construction_expression::is_constant_array() const
12764 if (this->vals() == NULL)
12765 return true;
12767 // There are no constant constructors for interfaces.
12768 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12769 return false;
12771 for (Expression_list::const_iterator pv = this->vals()->begin();
12772 pv != this->vals()->end();
12773 ++pv)
12775 if (*pv != NULL
12776 && !(*pv)->is_constant()
12777 && (!(*pv)->is_composite_literal()
12778 || (*pv)->is_nonconstant_composite_literal()))
12779 return false;
12781 return true;
12784 // Return whether this can be used a constant initializer.
12786 bool
12787 Array_construction_expression::do_is_static_initializer() const
12789 if (this->vals() == NULL)
12790 return true;
12792 // There are no constant constructors for interfaces.
12793 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12794 return false;
12796 for (Expression_list::const_iterator pv = this->vals()->begin();
12797 pv != this->vals()->end();
12798 ++pv)
12800 if (*pv != NULL && !(*pv)->is_static_initializer())
12801 return false;
12803 return true;
12806 // Final type determination.
12808 void
12809 Array_construction_expression::do_determine_type(const Type_context*)
12811 if (this->vals() == NULL)
12812 return;
12813 Type_context subcontext(this->type_->array_type()->element_type(), false);
12814 for (Expression_list::const_iterator pv = this->vals()->begin();
12815 pv != this->vals()->end();
12816 ++pv)
12818 if (*pv != NULL)
12819 (*pv)->determine_type(&subcontext);
12823 // Check types.
12825 void
12826 Array_construction_expression::do_check_types(Gogo*)
12828 if (this->vals() == NULL)
12829 return;
12831 Array_type* at = this->type_->array_type();
12832 int i = 0;
12833 Type* element_type = at->element_type();
12834 for (Expression_list::const_iterator pv = this->vals()->begin();
12835 pv != this->vals()->end();
12836 ++pv, ++i)
12838 if (*pv != NULL
12839 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12841 go_error_at((*pv)->location(),
12842 "incompatible type for element %d in composite literal",
12843 i + 1);
12844 this->set_is_error();
12849 // Flatten an array construction expression. Store the values into
12850 // temporaries in case they need interface conversion.
12852 Expression*
12853 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12854 Statement_inserter* inserter)
12856 if (this->vals() == NULL)
12857 return this;
12859 // If this is a constant array, we don't need temporaries.
12860 if (this->is_constant_array() || this->is_static_initializer())
12861 return this;
12863 Location loc = this->location();
12864 for (Expression_list::iterator pv = this->vals()->begin();
12865 pv != this->vals()->end();
12866 ++pv)
12868 if (*pv != NULL)
12870 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12872 go_assert(saw_errors());
12873 return Expression::make_error(loc);
12875 if (!(*pv)->is_variable())
12877 Temporary_statement* temp =
12878 Statement::make_temporary(NULL, *pv, loc);
12879 inserter->insert(temp);
12880 *pv = Expression::make_temporary_reference(temp, loc);
12884 return this;
12887 // Get a constructor expression for the array values.
12889 Bexpression*
12890 Array_construction_expression::get_constructor(Translate_context* context,
12891 Btype* array_btype)
12893 Type* element_type = this->type_->array_type()->element_type();
12895 std::vector<unsigned long> indexes;
12896 std::vector<Bexpression*> vals;
12897 Gogo* gogo = context->gogo();
12898 if (this->vals() != NULL)
12900 size_t i = 0;
12901 std::vector<unsigned long>::const_iterator pi;
12902 if (this->indexes_ != NULL)
12903 pi = this->indexes_->begin();
12904 for (Expression_list::const_iterator pv = this->vals()->begin();
12905 pv != this->vals()->end();
12906 ++pv, ++i)
12908 if (this->indexes_ != NULL)
12909 go_assert(pi != this->indexes_->end());
12911 if (this->indexes_ == NULL)
12912 indexes.push_back(i);
12913 else
12914 indexes.push_back(*pi);
12915 if (*pv == NULL)
12917 Btype* ebtype = element_type->get_backend(gogo);
12918 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12919 vals.push_back(zv);
12921 else
12923 Expression* val_expr =
12924 Expression::convert_for_assignment(gogo, element_type, *pv,
12925 this->location());
12926 vals.push_back(val_expr->get_backend(context));
12928 if (this->indexes_ != NULL)
12929 ++pi;
12931 if (this->indexes_ != NULL)
12932 go_assert(pi == this->indexes_->end());
12934 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12935 vals, this->location());
12938 // Export an array construction.
12940 void
12941 Array_construction_expression::do_export(Export* exp) const
12943 exp->write_c_string("convert(");
12944 exp->write_type(this->type_);
12945 if (this->vals() != NULL)
12947 std::vector<unsigned long>::const_iterator pi;
12948 if (this->indexes_ != NULL)
12949 pi = this->indexes_->begin();
12950 for (Expression_list::const_iterator pv = this->vals()->begin();
12951 pv != this->vals()->end();
12952 ++pv)
12954 exp->write_c_string(", ");
12956 if (this->indexes_ != NULL)
12958 char buf[100];
12959 snprintf(buf, sizeof buf, "%lu", *pi);
12960 exp->write_c_string(buf);
12961 exp->write_c_string(":");
12964 if (*pv != NULL)
12965 (*pv)->export_expression(exp);
12967 if (this->indexes_ != NULL)
12968 ++pi;
12971 exp->write_c_string(")");
12974 // Dump ast representation of an array construction expression.
12976 void
12977 Array_construction_expression::do_dump_expression(
12978 Ast_dump_context* ast_dump_context) const
12980 Expression* length = this->type_->array_type()->length();
12982 ast_dump_context->ostream() << "[" ;
12983 if (length != NULL)
12985 ast_dump_context->dump_expression(length);
12987 ast_dump_context->ostream() << "]" ;
12988 ast_dump_context->dump_type(this->type_);
12989 this->dump_slice_storage_expression(ast_dump_context);
12990 ast_dump_context->ostream() << "{" ;
12991 if (this->indexes_ == NULL)
12992 ast_dump_context->dump_expression_list(this->vals());
12993 else
12995 Expression_list::const_iterator pv = this->vals()->begin();
12996 for (std::vector<unsigned long>::const_iterator pi =
12997 this->indexes_->begin();
12998 pi != this->indexes_->end();
12999 ++pi, ++pv)
13001 if (pi != this->indexes_->begin())
13002 ast_dump_context->ostream() << ", ";
13003 ast_dump_context->ostream() << *pi << ':';
13004 ast_dump_context->dump_expression(*pv);
13007 ast_dump_context->ostream() << "}" ;
13011 // Class Fixed_array_construction_expression.
13013 Fixed_array_construction_expression::Fixed_array_construction_expression(
13014 Type* type, const std::vector<unsigned long>* indexes,
13015 Expression_list* vals, Location location)
13016 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13017 type, indexes, vals, location)
13018 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13020 // Return the backend representation for constructing a fixed array.
13022 Bexpression*
13023 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13025 Type* type = this->type();
13026 Btype* btype = type->get_backend(context->gogo());
13027 return this->get_constructor(context, btype);
13030 Expression*
13031 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13032 Location location)
13034 go_assert(type->array_type() != NULL && !type->is_slice_type());
13035 return new Fixed_array_construction_expression(type, NULL, vals, location);
13038 // Class Slice_construction_expression.
13040 Slice_construction_expression::Slice_construction_expression(
13041 Type* type, const std::vector<unsigned long>* indexes,
13042 Expression_list* vals, Location location)
13043 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13044 type, indexes, vals, location),
13045 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13046 storage_escapes_(true)
13048 go_assert(type->is_slice_type());
13050 unsigned long lenval;
13051 Expression* length;
13052 if (vals == NULL || vals->empty())
13053 lenval = 0;
13054 else
13056 if (this->indexes() == NULL)
13057 lenval = vals->size();
13058 else
13059 lenval = indexes->back() + 1;
13061 Type* int_type = Type::lookup_integer_type("int");
13062 length = Expression::make_integer_ul(lenval, int_type, location);
13063 Type* element_type = type->array_type()->element_type();
13064 Array_type* array_type = Type::make_array_type(element_type, length);
13065 array_type->set_is_array_incomparable();
13066 this->valtype_ = array_type;
13069 // Traversal.
13072 Slice_construction_expression::do_traverse(Traverse* traverse)
13074 if (this->Array_construction_expression::do_traverse(traverse)
13075 == TRAVERSE_EXIT)
13076 return TRAVERSE_EXIT;
13077 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13078 return TRAVERSE_EXIT;
13079 if (this->array_val_ != NULL
13080 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13081 return TRAVERSE_EXIT;
13082 if (this->slice_storage_ != NULL
13083 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13084 return TRAVERSE_EXIT;
13085 return TRAVERSE_CONTINUE;
13088 // Helper routine to create fixed array value underlying the slice literal.
13089 // May be called during flattening, or later during do_get_backend().
13091 Expression*
13092 Slice_construction_expression::create_array_val()
13094 Array_type* array_type = this->type()->array_type();
13095 if (array_type == NULL)
13097 go_assert(this->type()->is_error());
13098 return NULL;
13101 Location loc = this->location();
13102 go_assert(this->valtype_ != NULL);
13104 Expression_list* vals = this->vals();
13105 return new Fixed_array_construction_expression(
13106 this->valtype_, this->indexes(), vals, loc);
13109 // If we're previous established that the slice storage does not
13110 // escape, then create a separate array temp val here for it. We
13111 // need to do this as part of flattening so as to be able to insert
13112 // the new temp statement.
13114 Expression*
13115 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13116 Statement_inserter* inserter)
13118 if (this->type()->array_type() == NULL)
13119 return NULL;
13121 // Base class flattening first
13122 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13124 // Create a stack-allocated storage temp if storage won't escape
13125 if (!this->storage_escapes_
13126 && this->slice_storage_ == NULL
13127 && this->element_count() > 0)
13129 Location loc = this->location();
13130 this->array_val_ = this->create_array_val();
13131 go_assert(this->array_val_);
13132 Temporary_statement* temp =
13133 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13134 inserter->insert(temp);
13135 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13137 return this;
13140 // When dumping a slice construction expression that has an explicit
13141 // storeage temp, emit the temp here (if we don't do this the storage
13142 // temp appears unused in the AST dump).
13144 void
13145 Slice_construction_expression::
13146 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13148 if (this->slice_storage_ == NULL)
13149 return;
13150 ast_dump_context->ostream() << "storage=" ;
13151 ast_dump_context->dump_expression(this->slice_storage_);
13154 // Return the backend representation for constructing a slice.
13156 Bexpression*
13157 Slice_construction_expression::do_get_backend(Translate_context* context)
13159 if (this->array_val_ == NULL)
13160 this->array_val_ = this->create_array_val();
13161 if (this->array_val_ == NULL)
13163 go_assert(this->type()->is_error());
13164 return context->backend()->error_expression();
13167 Location loc = this->location();
13169 bool is_static_initializer = this->array_val_->is_static_initializer();
13171 // We have to copy the initial values into heap memory if we are in
13172 // a function or if the values are not constants.
13173 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13175 Expression* space;
13177 if (this->slice_storage_ != NULL)
13179 go_assert(!this->storage_escapes_);
13180 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13182 else if (!copy_to_heap)
13184 // The initializer will only run once.
13185 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13186 space->unary_expression()->set_is_slice_init();
13188 else
13190 space = Expression::make_heap_expression(this->array_val_, loc);
13191 Node* n = Node::make_node(this);
13192 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
13194 n = Node::make_node(space);
13195 n->set_encoding(Node::ESCAPE_NONE);
13199 // Build a constructor for the slice.
13200 Expression* len = this->valtype_->array_type()->length();
13201 Expression* slice_val =
13202 Expression::make_slice_value(this->type(), space, len, len, loc);
13203 return slice_val->get_backend(context);
13206 // Make a slice composite literal. This is used by the type
13207 // descriptor code.
13209 Slice_construction_expression*
13210 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13211 Location location)
13213 go_assert(type->is_slice_type());
13214 return new Slice_construction_expression(type, NULL, vals, location);
13217 // Class Map_construction_expression.
13219 // Traversal.
13222 Map_construction_expression::do_traverse(Traverse* traverse)
13224 if (this->vals_ != NULL
13225 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13226 return TRAVERSE_EXIT;
13227 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13228 return TRAVERSE_EXIT;
13229 return TRAVERSE_CONTINUE;
13232 // Flatten constructor initializer into a temporary variable since
13233 // we need to take its address for __go_construct_map.
13235 Expression*
13236 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13237 Statement_inserter* inserter)
13239 if (!this->is_error_expression()
13240 && this->vals_ != NULL
13241 && !this->vals_->empty()
13242 && this->constructor_temp_ == NULL)
13244 Map_type* mt = this->type_->map_type();
13245 Type* key_type = mt->key_type();
13246 Type* val_type = mt->val_type();
13247 this->element_type_ = Type::make_builtin_struct_type(2,
13248 "__key", key_type,
13249 "__val", val_type);
13251 Expression_list* value_pairs = new Expression_list();
13252 Location loc = this->location();
13254 size_t i = 0;
13255 for (Expression_list::const_iterator pv = this->vals_->begin();
13256 pv != this->vals_->end();
13257 ++pv, ++i)
13259 Expression_list* key_value_pair = new Expression_list();
13260 Expression* key = *pv;
13261 if (key->is_error_expression() || key->type()->is_error_type())
13263 go_assert(saw_errors());
13264 return Expression::make_error(loc);
13266 if (key->type()->interface_type() != NULL && !key->is_variable())
13268 Temporary_statement* temp =
13269 Statement::make_temporary(NULL, key, loc);
13270 inserter->insert(temp);
13271 key = Expression::make_temporary_reference(temp, loc);
13273 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13275 ++pv;
13276 Expression* val = *pv;
13277 if (val->is_error_expression() || val->type()->is_error_type())
13279 go_assert(saw_errors());
13280 return Expression::make_error(loc);
13282 if (val->type()->interface_type() != NULL && !val->is_variable())
13284 Temporary_statement* temp =
13285 Statement::make_temporary(NULL, val, loc);
13286 inserter->insert(temp);
13287 val = Expression::make_temporary_reference(temp, loc);
13289 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13291 key_value_pair->push_back(key);
13292 key_value_pair->push_back(val);
13293 value_pairs->push_back(
13294 Expression::make_struct_composite_literal(this->element_type_,
13295 key_value_pair, loc));
13298 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13299 Array_type* ctor_type =
13300 Type::make_array_type(this->element_type_, element_count);
13301 ctor_type->set_is_array_incomparable();
13302 Expression* constructor =
13303 new Fixed_array_construction_expression(ctor_type, NULL,
13304 value_pairs, loc);
13306 this->constructor_temp_ =
13307 Statement::make_temporary(NULL, constructor, loc);
13308 constructor->issue_nil_check();
13309 this->constructor_temp_->set_is_address_taken();
13310 inserter->insert(this->constructor_temp_);
13313 return this;
13316 // Final type determination.
13318 void
13319 Map_construction_expression::do_determine_type(const Type_context*)
13321 if (this->vals_ == NULL)
13322 return;
13324 Map_type* mt = this->type_->map_type();
13325 Type_context key_context(mt->key_type(), false);
13326 Type_context val_context(mt->val_type(), false);
13327 for (Expression_list::const_iterator pv = this->vals_->begin();
13328 pv != this->vals_->end();
13329 ++pv)
13331 (*pv)->determine_type(&key_context);
13332 ++pv;
13333 (*pv)->determine_type(&val_context);
13337 // Check types.
13339 void
13340 Map_construction_expression::do_check_types(Gogo*)
13342 if (this->vals_ == NULL)
13343 return;
13345 Map_type* mt = this->type_->map_type();
13346 int i = 0;
13347 Type* key_type = mt->key_type();
13348 Type* val_type = mt->val_type();
13349 for (Expression_list::const_iterator pv = this->vals_->begin();
13350 pv != this->vals_->end();
13351 ++pv, ++i)
13353 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13355 go_error_at((*pv)->location(),
13356 "incompatible type for element %d key in map construction",
13357 i + 1);
13358 this->set_is_error();
13360 ++pv;
13361 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13363 go_error_at((*pv)->location(),
13364 ("incompatible type for element %d value "
13365 "in map construction"),
13366 i + 1);
13367 this->set_is_error();
13372 // Return the backend representation for constructing a map.
13374 Bexpression*
13375 Map_construction_expression::do_get_backend(Translate_context* context)
13377 if (this->is_error_expression())
13378 return context->backend()->error_expression();
13379 Location loc = this->location();
13381 size_t i = 0;
13382 Expression* ventries;
13383 if (this->vals_ == NULL || this->vals_->empty())
13384 ventries = Expression::make_nil(loc);
13385 else
13387 go_assert(this->constructor_temp_ != NULL);
13388 i = this->vals_->size() / 2;
13390 Expression* ctor_ref =
13391 Expression::make_temporary_reference(this->constructor_temp_, loc);
13392 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13395 Map_type* mt = this->type_->map_type();
13396 if (this->element_type_ == NULL)
13397 this->element_type_ =
13398 Type::make_builtin_struct_type(2,
13399 "__key", mt->key_type(),
13400 "__val", mt->val_type());
13401 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13403 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13404 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13406 Expression* entry_size =
13407 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13409 unsigned int field_index;
13410 const Struct_field* valfield =
13411 this->element_type_->find_local_field("__val", &field_index);
13412 Expression* val_offset =
13413 Expression::make_struct_field_offset(this->element_type_, valfield);
13415 Expression* map_ctor =
13416 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13417 entry_size, val_offset, ventries);
13418 return map_ctor->get_backend(context);
13421 // Export an array construction.
13423 void
13424 Map_construction_expression::do_export(Export* exp) const
13426 exp->write_c_string("convert(");
13427 exp->write_type(this->type_);
13428 for (Expression_list::const_iterator pv = this->vals_->begin();
13429 pv != this->vals_->end();
13430 ++pv)
13432 exp->write_c_string(", ");
13433 (*pv)->export_expression(exp);
13435 exp->write_c_string(")");
13438 // Dump ast representation for a map construction expression.
13440 void
13441 Map_construction_expression::do_dump_expression(
13442 Ast_dump_context* ast_dump_context) const
13444 ast_dump_context->ostream() << "{" ;
13445 ast_dump_context->dump_expression_list(this->vals_, true);
13446 ast_dump_context->ostream() << "}";
13449 // Class Composite_literal_expression.
13451 // Traversal.
13454 Composite_literal_expression::do_traverse(Traverse* traverse)
13456 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13457 return TRAVERSE_EXIT;
13459 // If this is a struct composite literal with keys, then the keys
13460 // are field names, not expressions. We don't want to traverse them
13461 // in that case. If we do, we can give an erroneous error "variable
13462 // initializer refers to itself." See bug482.go in the testsuite.
13463 if (this->has_keys_ && this->vals_ != NULL)
13465 // The type may not be resolvable at this point.
13466 Type* type = this->type_;
13468 for (int depth = 0; depth < this->depth_; ++depth)
13470 if (type->array_type() != NULL)
13471 type = type->array_type()->element_type();
13472 else if (type->map_type() != NULL)
13474 if (this->key_path_[depth])
13475 type = type->map_type()->key_type();
13476 else
13477 type = type->map_type()->val_type();
13479 else
13481 // This error will be reported during lowering.
13482 return TRAVERSE_CONTINUE;
13486 while (true)
13488 if (type->classification() == Type::TYPE_NAMED)
13489 type = type->named_type()->real_type();
13490 else if (type->classification() == Type::TYPE_FORWARD)
13492 Type* t = type->forwarded();
13493 if (t == type)
13494 break;
13495 type = t;
13497 else
13498 break;
13501 if (type->classification() == Type::TYPE_STRUCT)
13503 Expression_list::iterator p = this->vals_->begin();
13504 while (p != this->vals_->end())
13506 // Skip key.
13507 ++p;
13508 go_assert(p != this->vals_->end());
13509 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13510 return TRAVERSE_EXIT;
13511 ++p;
13513 return TRAVERSE_CONTINUE;
13517 if (this->vals_ != NULL)
13518 return this->vals_->traverse(traverse);
13520 return TRAVERSE_CONTINUE;
13523 // Lower a generic composite literal into a specific version based on
13524 // the type.
13526 Expression*
13527 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13528 Statement_inserter* inserter, int)
13530 Type* type = this->type_;
13532 for (int depth = 0; depth < this->depth_; ++depth)
13534 if (type->array_type() != NULL)
13535 type = type->array_type()->element_type();
13536 else if (type->map_type() != NULL)
13538 if (this->key_path_[depth])
13539 type = type->map_type()->key_type();
13540 else
13541 type = type->map_type()->val_type();
13543 else
13545 if (!type->is_error())
13546 go_error_at(this->location(),
13547 ("may only omit types within composite literals "
13548 "of slice, array, or map type"));
13549 return Expression::make_error(this->location());
13553 Type *pt = type->points_to();
13554 bool is_pointer = false;
13555 if (pt != NULL)
13557 is_pointer = true;
13558 type = pt;
13561 Expression* ret;
13562 if (type->is_error())
13563 return Expression::make_error(this->location());
13564 else if (type->struct_type() != NULL)
13565 ret = this->lower_struct(gogo, type);
13566 else if (type->array_type() != NULL)
13567 ret = this->lower_array(type);
13568 else if (type->map_type() != NULL)
13569 ret = this->lower_map(gogo, function, inserter, type);
13570 else
13572 go_error_at(this->location(),
13573 ("expected struct, slice, array, or map type "
13574 "for composite literal"));
13575 return Expression::make_error(this->location());
13578 if (is_pointer)
13579 ret = Expression::make_heap_expression(ret, this->location());
13581 return ret;
13584 // Lower a struct composite literal.
13586 Expression*
13587 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13589 Location location = this->location();
13590 Struct_type* st = type->struct_type();
13591 if (this->vals_ == NULL || !this->has_keys_)
13593 if (this->vals_ != NULL
13594 && !this->vals_->empty()
13595 && type->named_type() != NULL
13596 && type->named_type()->named_object()->package() != NULL)
13598 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13599 pf != st->fields()->end();
13600 ++pf)
13602 if (Gogo::is_hidden_name(pf->field_name())
13603 || pf->is_embedded_builtin(gogo))
13604 go_error_at(this->location(),
13605 "assignment of unexported field %qs in %qs literal",
13606 Gogo::message_name(pf->field_name()).c_str(),
13607 type->named_type()->message_name().c_str());
13611 return new Struct_construction_expression(type, this->vals_, location);
13614 size_t field_count = st->field_count();
13615 std::vector<Expression*> vals(field_count);
13616 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13617 Expression_list::const_iterator p = this->vals_->begin();
13618 Expression* external_expr = NULL;
13619 const Named_object* external_no = NULL;
13620 while (p != this->vals_->end())
13622 Expression* name_expr = *p;
13624 ++p;
13625 go_assert(p != this->vals_->end());
13626 Expression* val = *p;
13628 ++p;
13630 if (name_expr == NULL)
13632 go_error_at(val->location(),
13633 "mixture of field and value initializers");
13634 return Expression::make_error(location);
13637 bool bad_key = false;
13638 std::string name;
13639 const Named_object* no = NULL;
13640 switch (name_expr->classification())
13642 case EXPRESSION_UNKNOWN_REFERENCE:
13643 name = name_expr->unknown_expression()->name();
13644 if (type->named_type() != NULL)
13646 // If the named object found for this field name comes from a
13647 // different package than the struct it is a part of, do not count
13648 // this incorrect lookup as a usage of the object's package.
13649 no = name_expr->unknown_expression()->named_object();
13650 if (no->package() != NULL
13651 && no->package() != type->named_type()->named_object()->package())
13652 no->package()->forget_usage(name_expr);
13654 break;
13656 case EXPRESSION_CONST_REFERENCE:
13657 no = static_cast<Const_expression*>(name_expr)->named_object();
13658 break;
13660 case EXPRESSION_TYPE:
13662 Type* t = name_expr->type();
13663 Named_type* nt = t->named_type();
13664 if (nt == NULL)
13665 bad_key = true;
13666 else
13667 no = nt->named_object();
13669 break;
13671 case EXPRESSION_VAR_REFERENCE:
13672 no = name_expr->var_expression()->named_object();
13673 break;
13675 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13676 no = name_expr->enclosed_var_expression()->variable();
13677 break;
13679 case EXPRESSION_FUNC_REFERENCE:
13680 no = name_expr->func_expression()->named_object();
13681 break;
13683 default:
13684 bad_key = true;
13685 break;
13687 if (bad_key)
13689 go_error_at(name_expr->location(), "expected struct field name");
13690 return Expression::make_error(location);
13693 if (no != NULL)
13695 if (no->package() != NULL && external_expr == NULL)
13697 external_expr = name_expr;
13698 external_no = no;
13701 name = no->name();
13703 // A predefined name won't be packed. If it starts with a
13704 // lower case letter we need to check for that case, because
13705 // the field name will be packed. FIXME.
13706 if (!Gogo::is_hidden_name(name)
13707 && name[0] >= 'a'
13708 && name[0] <= 'z')
13710 Named_object* gno = gogo->lookup_global(name.c_str());
13711 if (gno == no)
13712 name = gogo->pack_hidden_name(name, false);
13716 unsigned int index;
13717 const Struct_field* sf = st->find_local_field(name, &index);
13718 if (sf == NULL)
13720 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13721 Gogo::message_name(name).c_str(),
13722 (type->named_type() != NULL
13723 ? type->named_type()->message_name().c_str()
13724 : "unnamed struct"));
13725 return Expression::make_error(location);
13727 if (vals[index] != NULL)
13729 go_error_at(name_expr->location(),
13730 "duplicate value for field %qs in %qs",
13731 Gogo::message_name(name).c_str(),
13732 (type->named_type() != NULL
13733 ? type->named_type()->message_name().c_str()
13734 : "unnamed struct"));
13735 return Expression::make_error(location);
13738 if (type->named_type() != NULL
13739 && type->named_type()->named_object()->package() != NULL
13740 && (Gogo::is_hidden_name(sf->field_name())
13741 || sf->is_embedded_builtin(gogo)))
13742 go_error_at(name_expr->location(),
13743 "assignment of unexported field %qs in %qs literal",
13744 Gogo::message_name(sf->field_name()).c_str(),
13745 type->named_type()->message_name().c_str());
13747 vals[index] = val;
13748 traverse_order->push_back(static_cast<unsigned long>(index));
13751 if (!this->all_are_names_)
13753 // This is a weird case like bug462 in the testsuite.
13754 if (external_expr == NULL)
13755 go_error_at(this->location(), "unknown field in %qs literal",
13756 (type->named_type() != NULL
13757 ? type->named_type()->message_name().c_str()
13758 : "unnamed struct"));
13759 else
13760 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13761 external_no->message_name().c_str(),
13762 (type->named_type() != NULL
13763 ? type->named_type()->message_name().c_str()
13764 : "unnamed struct"));
13765 return Expression::make_error(location);
13768 Expression_list* list = new Expression_list;
13769 list->reserve(field_count);
13770 for (size_t i = 0; i < field_count; ++i)
13771 list->push_back(vals[i]);
13773 Struct_construction_expression* ret =
13774 new Struct_construction_expression(type, list, location);
13775 ret->set_traverse_order(traverse_order);
13776 return ret;
13779 // Index/value/traversal-order triple.
13781 struct IVT_triple {
13782 unsigned long index;
13783 unsigned long traversal_order;
13784 Expression* expr;
13785 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13786 : index(i), traversal_order(to), expr(e) { }
13787 bool operator<(const IVT_triple& other) const
13788 { return this->index < other.index; }
13791 // Lower an array composite literal.
13793 Expression*
13794 Composite_literal_expression::lower_array(Type* type)
13796 Location location = this->location();
13797 if (this->vals_ == NULL || !this->has_keys_)
13798 return this->make_array(type, NULL, this->vals_);
13800 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13801 indexes->reserve(this->vals_->size());
13802 bool indexes_out_of_order = false;
13803 Expression_list* vals = new Expression_list();
13804 vals->reserve(this->vals_->size());
13805 unsigned long index = 0;
13806 Expression_list::const_iterator p = this->vals_->begin();
13807 while (p != this->vals_->end())
13809 Expression* index_expr = *p;
13811 ++p;
13812 go_assert(p != this->vals_->end());
13813 Expression* val = *p;
13815 ++p;
13817 if (index_expr == NULL)
13819 if (!indexes->empty())
13820 indexes->push_back(index);
13822 else
13824 if (indexes->empty() && !vals->empty())
13826 for (size_t i = 0; i < vals->size(); ++i)
13827 indexes->push_back(i);
13830 Numeric_constant nc;
13831 if (!index_expr->numeric_constant_value(&nc))
13833 go_error_at(index_expr->location(),
13834 "index expression is not integer constant");
13835 return Expression::make_error(location);
13838 switch (nc.to_unsigned_long(&index))
13840 case Numeric_constant::NC_UL_VALID:
13841 break;
13842 case Numeric_constant::NC_UL_NOTINT:
13843 go_error_at(index_expr->location(),
13844 "index expression is not integer constant");
13845 return Expression::make_error(location);
13846 case Numeric_constant::NC_UL_NEGATIVE:
13847 go_error_at(index_expr->location(),
13848 "index expression is negative");
13849 return Expression::make_error(location);
13850 case Numeric_constant::NC_UL_BIG:
13851 go_error_at(index_expr->location(), "index value overflow");
13852 return Expression::make_error(location);
13853 default:
13854 go_unreachable();
13857 Named_type* ntype = Type::lookup_integer_type("int");
13858 Integer_type* inttype = ntype->integer_type();
13859 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13860 && index >> (inttype->bits() - 1) != 0)
13862 go_error_at(index_expr->location(), "index value overflow");
13863 return Expression::make_error(location);
13866 if (std::find(indexes->begin(), indexes->end(), index)
13867 != indexes->end())
13869 go_error_at(index_expr->location(),
13870 "duplicate value for index %lu",
13871 index);
13872 return Expression::make_error(location);
13875 if (!indexes->empty() && index < indexes->back())
13876 indexes_out_of_order = true;
13878 indexes->push_back(index);
13881 vals->push_back(val);
13883 ++index;
13886 if (indexes->empty())
13888 delete indexes;
13889 indexes = NULL;
13892 std::vector<unsigned long>* traverse_order = NULL;
13893 if (indexes_out_of_order)
13895 typedef std::vector<IVT_triple> V;
13897 V v;
13898 v.reserve(indexes->size());
13899 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13900 unsigned long torder = 0;
13901 for (Expression_list::const_iterator pe = vals->begin();
13902 pe != vals->end();
13903 ++pe, ++pi, ++torder)
13904 v.push_back(IVT_triple(*pi, torder, *pe));
13906 std::sort(v.begin(), v.end());
13908 delete indexes;
13909 delete vals;
13911 indexes = new std::vector<unsigned long>();
13912 indexes->reserve(v.size());
13913 vals = new Expression_list();
13914 vals->reserve(v.size());
13915 traverse_order = new std::vector<unsigned long>();
13916 traverse_order->reserve(v.size());
13918 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13920 indexes->push_back(p->index);
13921 vals->push_back(p->expr);
13922 traverse_order->push_back(p->traversal_order);
13926 Expression* ret = this->make_array(type, indexes, vals);
13927 Array_construction_expression* ace = ret->array_literal();
13928 if (ace != NULL && traverse_order != NULL)
13929 ace->set_traverse_order(traverse_order);
13930 return ret;
13933 // Actually build the array composite literal. This handles
13934 // [...]{...}.
13936 Expression*
13937 Composite_literal_expression::make_array(
13938 Type* type,
13939 const std::vector<unsigned long>* indexes,
13940 Expression_list* vals)
13942 Location location = this->location();
13943 Array_type* at = type->array_type();
13945 if (at->length() != NULL && at->length()->is_nil_expression())
13947 size_t size;
13948 if (vals == NULL)
13949 size = 0;
13950 else if (indexes != NULL)
13951 size = indexes->back() + 1;
13952 else
13954 size = vals->size();
13955 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13956 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13957 && size >> (it->bits() - 1) != 0)
13959 go_error_at(location, "too many elements in composite literal");
13960 return Expression::make_error(location);
13964 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13965 at = Type::make_array_type(at->element_type(), elen);
13966 type = at;
13968 else if (at->length() != NULL
13969 && !at->length()->is_error_expression()
13970 && this->vals_ != NULL)
13972 Numeric_constant nc;
13973 unsigned long val;
13974 if (at->length()->numeric_constant_value(&nc)
13975 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13977 if (indexes == NULL)
13979 if (this->vals_->size() > val)
13981 go_error_at(location,
13982 "too many elements in composite literal");
13983 return Expression::make_error(location);
13986 else
13988 unsigned long max = indexes->back();
13989 if (max >= val)
13991 go_error_at(location,
13992 ("some element keys in composite literal "
13993 "are out of range"));
13994 return Expression::make_error(location);
14000 if (at->length() != NULL)
14001 return new Fixed_array_construction_expression(type, indexes, vals,
14002 location);
14003 else
14004 return new Slice_construction_expression(type, indexes, vals, location);
14007 // Lower a map composite literal.
14009 Expression*
14010 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
14011 Statement_inserter* inserter,
14012 Type* type)
14014 Location location = this->location();
14015 if (this->vals_ != NULL)
14017 if (!this->has_keys_)
14019 go_error_at(location, "map composite literal must have keys");
14020 return Expression::make_error(location);
14023 for (Expression_list::iterator p = this->vals_->begin();
14024 p != this->vals_->end();
14025 p += 2)
14027 if (*p == NULL)
14029 ++p;
14030 go_error_at((*p)->location(),
14031 ("map composite literal must "
14032 "have keys for every value"));
14033 return Expression::make_error(location);
14035 // Make sure we have lowered the key; it may not have been
14036 // lowered in order to handle keys for struct composite
14037 // literals. Lower it now to get the right error message.
14038 if ((*p)->unknown_expression() != NULL)
14040 (*p)->unknown_expression()->clear_is_composite_literal_key();
14041 gogo->lower_expression(function, inserter, &*p);
14042 go_assert((*p)->is_error_expression());
14043 return Expression::make_error(location);
14048 return new Map_construction_expression(type, this->vals_, location);
14051 // Dump ast representation for a composite literal expression.
14053 void
14054 Composite_literal_expression::do_dump_expression(
14055 Ast_dump_context* ast_dump_context) const
14057 ast_dump_context->ostream() << "composite(";
14058 ast_dump_context->dump_type(this->type_);
14059 ast_dump_context->ostream() << ", {";
14060 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14061 ast_dump_context->ostream() << "})";
14064 // Make a composite literal expression.
14066 Expression*
14067 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14068 Expression_list* vals, bool all_are_names,
14069 Location location)
14071 return new Composite_literal_expression(type, depth, has_keys, vals,
14072 all_are_names, location);
14075 // Return whether this expression is a composite literal.
14077 bool
14078 Expression::is_composite_literal() const
14080 switch (this->classification_)
14082 case EXPRESSION_COMPOSITE_LITERAL:
14083 case EXPRESSION_STRUCT_CONSTRUCTION:
14084 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14085 case EXPRESSION_SLICE_CONSTRUCTION:
14086 case EXPRESSION_MAP_CONSTRUCTION:
14087 return true;
14088 default:
14089 return false;
14093 // Return whether this expression is a composite literal which is not
14094 // constant.
14096 bool
14097 Expression::is_nonconstant_composite_literal() const
14099 switch (this->classification_)
14101 case EXPRESSION_STRUCT_CONSTRUCTION:
14103 const Struct_construction_expression *psce =
14104 static_cast<const Struct_construction_expression*>(this);
14105 return !psce->is_constant_struct();
14107 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14109 const Fixed_array_construction_expression *pace =
14110 static_cast<const Fixed_array_construction_expression*>(this);
14111 return !pace->is_constant_array();
14113 case EXPRESSION_SLICE_CONSTRUCTION:
14115 const Slice_construction_expression *pace =
14116 static_cast<const Slice_construction_expression*>(this);
14117 return !pace->is_constant_array();
14119 case EXPRESSION_MAP_CONSTRUCTION:
14120 return true;
14121 default:
14122 return false;
14126 // Return true if this is a variable or temporary_variable.
14128 bool
14129 Expression::is_variable() const
14131 switch (this->classification_)
14133 case EXPRESSION_VAR_REFERENCE:
14134 case EXPRESSION_TEMPORARY_REFERENCE:
14135 case EXPRESSION_SET_AND_USE_TEMPORARY:
14136 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14137 return true;
14138 default:
14139 return false;
14143 // Return true if this is a reference to a local variable.
14145 bool
14146 Expression::is_local_variable() const
14148 const Var_expression* ve = this->var_expression();
14149 if (ve == NULL)
14150 return false;
14151 const Named_object* no = ve->named_object();
14152 return (no->is_result_variable()
14153 || (no->is_variable() && !no->var_value()->is_global()));
14156 // Class Type_guard_expression.
14158 // Traversal.
14161 Type_guard_expression::do_traverse(Traverse* traverse)
14163 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14164 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14165 return TRAVERSE_EXIT;
14166 return TRAVERSE_CONTINUE;
14169 Expression*
14170 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14171 Statement_inserter* inserter)
14173 if (this->expr_->is_error_expression()
14174 || this->expr_->type()->is_error_type())
14176 go_assert(saw_errors());
14177 return Expression::make_error(this->location());
14180 if (!this->expr_->is_variable())
14182 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14183 this->location());
14184 inserter->insert(temp);
14185 this->expr_ =
14186 Expression::make_temporary_reference(temp, this->location());
14188 return this;
14191 // Check types of a type guard expression. The expression must have
14192 // an interface type, but the actual type conversion is checked at run
14193 // time.
14195 void
14196 Type_guard_expression::do_check_types(Gogo*)
14198 Type* expr_type = this->expr_->type();
14199 if (expr_type->interface_type() == NULL)
14201 if (!expr_type->is_error() && !this->type_->is_error())
14202 this->report_error(_("type assertion only valid for interface types"));
14203 this->set_is_error();
14205 else if (this->type_->interface_type() == NULL)
14207 std::string reason;
14208 if (!expr_type->interface_type()->implements_interface(this->type_,
14209 &reason))
14211 if (!this->type_->is_error())
14213 if (reason.empty())
14214 this->report_error(_("impossible type assertion: "
14215 "type does not implement interface"));
14216 else
14217 go_error_at(this->location(),
14218 ("impossible type assertion: "
14219 "type does not implement interface (%s)"),
14220 reason.c_str());
14222 this->set_is_error();
14227 // Return the backend representation for a type guard expression.
14229 Bexpression*
14230 Type_guard_expression::do_get_backend(Translate_context* context)
14232 Expression* conversion;
14233 if (this->type_->interface_type() != NULL)
14234 conversion =
14235 Expression::convert_interface_to_interface(this->type_, this->expr_,
14236 true, this->location());
14237 else
14238 conversion =
14239 Expression::convert_for_assignment(context->gogo(), this->type_,
14240 this->expr_, this->location());
14242 Gogo* gogo = context->gogo();
14243 Btype* bt = this->type_->get_backend(gogo);
14244 Bexpression* bexpr = conversion->get_backend(context);
14245 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14248 // Dump ast representation for a type guard expression.
14250 void
14251 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14252 const
14254 this->expr_->dump_expression(ast_dump_context);
14255 ast_dump_context->ostream() << ".";
14256 ast_dump_context->dump_type(this->type_);
14259 // Make a type guard expression.
14261 Expression*
14262 Expression::make_type_guard(Expression* expr, Type* type,
14263 Location location)
14265 return new Type_guard_expression(expr, type, location);
14268 // Class Heap_expression.
14270 // Return the type of the expression stored on the heap.
14272 Type*
14273 Heap_expression::do_type()
14274 { return Type::make_pointer_type(this->expr_->type()); }
14276 // Return the backend representation for allocating an expression on the heap.
14278 Bexpression*
14279 Heap_expression::do_get_backend(Translate_context* context)
14281 Type* etype = this->expr_->type();
14282 if (this->expr_->is_error_expression() || etype->is_error())
14283 return context->backend()->error_expression();
14285 Location loc = this->location();
14286 Gogo* gogo = context->gogo();
14287 Btype* btype = this->type()->get_backend(gogo);
14289 Expression* alloc = Expression::make_allocation(etype, loc);
14290 Node* n = Node::make_node(this);
14291 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
14292 alloc->allocation_expression()->set_allocate_on_stack();
14293 Bexpression* space = alloc->get_backend(context);
14295 Bstatement* decl;
14296 Named_object* fn = context->function();
14297 go_assert(fn != NULL);
14298 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14299 Bvariable* space_temp =
14300 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14301 space, true, loc, &decl);
14302 Btype* expr_btype = etype->get_backend(gogo);
14304 Bexpression* bexpr = this->expr_->get_backend(context);
14306 // If this assignment needs a write barrier, call typedmemmove. We
14307 // don't do this in the write barrier pass because in some cases
14308 // backend conversion can introduce new Heap_expression values.
14309 Bstatement* assn;
14310 if (!etype->has_pointer())
14312 space = gogo->backend()->var_expression(space_temp, VE_lvalue, loc);
14313 Bexpression* ref =
14314 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14315 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14317 else
14319 Bstatement* edecl;
14320 Bvariable* btemp =
14321 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14322 expr_btype, bexpr, true, loc,
14323 &edecl);
14324 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14325 VE_lvalue, loc);
14326 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14328 Expression* td = Expression::make_type_descriptor(etype, loc);
14329 Type* etype_ptr = Type::make_pointer_type(etype);
14330 space = gogo->backend()->var_expression(space_temp, VE_rvalue, loc);
14331 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14332 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14333 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14334 td, elhs, erhs);
14335 Bexpression* bcall = call->get_backend(context);
14336 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14337 assn = gogo->backend()->compound_statement(edecl, s);
14339 decl = gogo->backend()->compound_statement(decl, assn);
14340 space = gogo->backend()->var_expression(space_temp, VE_rvalue, loc);
14341 return gogo->backend()->compound_expression(decl, space, loc);
14344 // Dump ast representation for a heap expression.
14346 void
14347 Heap_expression::do_dump_expression(
14348 Ast_dump_context* ast_dump_context) const
14350 ast_dump_context->ostream() << "&(";
14351 ast_dump_context->dump_expression(this->expr_);
14352 ast_dump_context->ostream() << ")";
14355 // Allocate an expression on the heap.
14357 Expression*
14358 Expression::make_heap_expression(Expression* expr, Location location)
14360 return new Heap_expression(expr, location);
14363 // Class Receive_expression.
14365 // Return the type of a receive expression.
14367 Type*
14368 Receive_expression::do_type()
14370 if (this->is_error_expression())
14371 return Type::make_error_type();
14372 Channel_type* channel_type = this->channel_->type()->channel_type();
14373 if (channel_type == NULL)
14375 this->report_error(_("expected channel"));
14376 return Type::make_error_type();
14378 return channel_type->element_type();
14381 // Check types for a receive expression.
14383 void
14384 Receive_expression::do_check_types(Gogo*)
14386 Type* type = this->channel_->type();
14387 if (type->is_error())
14389 go_assert(saw_errors());
14390 this->set_is_error();
14391 return;
14393 if (type->channel_type() == NULL)
14395 this->report_error(_("expected channel"));
14396 return;
14398 if (!type->channel_type()->may_receive())
14400 this->report_error(_("invalid receive on send-only channel"));
14401 return;
14405 // Flattening for receive expressions creates a temporary variable to store
14406 // received data in for receives.
14408 Expression*
14409 Receive_expression::do_flatten(Gogo*, Named_object*,
14410 Statement_inserter* inserter)
14412 Channel_type* channel_type = this->channel_->type()->channel_type();
14413 if (channel_type == NULL)
14415 go_assert(saw_errors());
14416 return this;
14418 else if (this->channel_->is_error_expression())
14420 go_assert(saw_errors());
14421 return Expression::make_error(this->location());
14424 Type* element_type = channel_type->element_type();
14425 if (this->temp_receiver_ == NULL)
14427 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14428 this->location());
14429 this->temp_receiver_->set_is_address_taken();
14430 inserter->insert(this->temp_receiver_);
14433 return this;
14436 // Get the backend representation for a receive expression.
14438 Bexpression*
14439 Receive_expression::do_get_backend(Translate_context* context)
14441 Location loc = this->location();
14443 Channel_type* channel_type = this->channel_->type()->channel_type();
14444 if (channel_type == NULL)
14446 go_assert(this->channel_->type()->is_error());
14447 return context->backend()->error_expression();
14450 Expression* recv_ref =
14451 Expression::make_temporary_reference(this->temp_receiver_, loc);
14452 Expression* recv_addr =
14453 Expression::make_temporary_reference(this->temp_receiver_, loc);
14454 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14455 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14456 this->channel_, recv_addr);
14457 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14460 // Dump ast representation for a receive expression.
14462 void
14463 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14465 ast_dump_context->ostream() << " <- " ;
14466 ast_dump_context->dump_expression(channel_);
14469 // Make a receive expression.
14471 Receive_expression*
14472 Expression::make_receive(Expression* channel, Location location)
14474 return new Receive_expression(channel, location);
14477 // An expression which evaluates to a pointer to the type descriptor
14478 // of a type.
14480 class Type_descriptor_expression : public Expression
14482 public:
14483 Type_descriptor_expression(Type* type, Location location)
14484 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14485 type_(type)
14488 protected:
14490 do_traverse(Traverse*);
14492 Type*
14493 do_type()
14494 { return Type::make_type_descriptor_ptr_type(); }
14496 bool
14497 do_is_static_initializer() const
14498 { return true; }
14500 void
14501 do_determine_type(const Type_context*)
14504 Expression*
14505 do_copy()
14506 { return this; }
14508 Bexpression*
14509 do_get_backend(Translate_context* context)
14511 return this->type_->type_descriptor_pointer(context->gogo(),
14512 this->location());
14515 void
14516 do_dump_expression(Ast_dump_context*) const;
14518 private:
14519 // The type for which this is the descriptor.
14520 Type* type_;
14524 Type_descriptor_expression::do_traverse(Traverse* traverse)
14526 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14527 return TRAVERSE_EXIT;
14528 return TRAVERSE_CONTINUE;
14531 // Dump ast representation for a type descriptor expression.
14533 void
14534 Type_descriptor_expression::do_dump_expression(
14535 Ast_dump_context* ast_dump_context) const
14537 ast_dump_context->dump_type(this->type_);
14540 // Make a type descriptor expression.
14542 Expression*
14543 Expression::make_type_descriptor(Type* type, Location location)
14545 return new Type_descriptor_expression(type, location);
14548 // An expression which evaluates to a pointer to the Garbage Collection symbol
14549 // of a type.
14551 class GC_symbol_expression : public Expression
14553 public:
14554 GC_symbol_expression(Type* type)
14555 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14556 type_(type)
14559 protected:
14560 Type*
14561 do_type()
14562 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14564 bool
14565 do_is_static_initializer() const
14566 { return true; }
14568 void
14569 do_determine_type(const Type_context*)
14572 Expression*
14573 do_copy()
14574 { return this; }
14576 Bexpression*
14577 do_get_backend(Translate_context* context)
14578 { return this->type_->gc_symbol_pointer(context->gogo()); }
14580 void
14581 do_dump_expression(Ast_dump_context*) const;
14583 private:
14584 // The type which this gc symbol describes.
14585 Type* type_;
14588 // Dump ast representation for a gc symbol expression.
14590 void
14591 GC_symbol_expression::do_dump_expression(
14592 Ast_dump_context* ast_dump_context) const
14594 ast_dump_context->ostream() << "gcdata(";
14595 ast_dump_context->dump_type(this->type_);
14596 ast_dump_context->ostream() << ")";
14599 // Make a gc symbol expression.
14601 Expression*
14602 Expression::make_gc_symbol(Type* type)
14604 return new GC_symbol_expression(type);
14607 // An expression that evaluates to a pointer to a symbol holding the
14608 // ptrmask data of a type.
14610 class Ptrmask_symbol_expression : public Expression
14612 public:
14613 Ptrmask_symbol_expression(Type* type)
14614 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14615 type_(type)
14618 protected:
14619 Type*
14620 do_type()
14621 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14623 bool
14624 do_is_static_initializer() const
14625 { return true; }
14627 void
14628 do_determine_type(const Type_context*)
14631 Expression*
14632 do_copy()
14633 { return this; }
14635 Bexpression*
14636 do_get_backend(Translate_context*);
14638 void
14639 do_dump_expression(Ast_dump_context*) const;
14641 private:
14642 // The type that this ptrmask symbol describes.
14643 Type* type_;
14646 // Return the ptrmask variable.
14648 Bexpression*
14649 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14651 Gogo* gogo = context->gogo();
14653 // If this type does not need a gcprog, then we can use the standard
14654 // GC symbol.
14655 int64_t ptrsize, ptrdata;
14656 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14657 return this->type_->gc_symbol_pointer(gogo);
14659 // Otherwise we have to build a ptrmask variable, and return a
14660 // pointer to it.
14662 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14663 Location bloc = Linemap::predeclared_location();
14664 Bexpression* bref = gogo->backend()->var_expression(bvar, VE_rvalue, bloc);
14665 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14667 Type* uint8_type = Type::lookup_integer_type("uint8");
14668 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14669 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14670 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14673 // Dump AST for a ptrmask symbol expression.
14675 void
14676 Ptrmask_symbol_expression::do_dump_expression(
14677 Ast_dump_context* ast_dump_context) const
14679 ast_dump_context->ostream() << "ptrmask(";
14680 ast_dump_context->dump_type(this->type_);
14681 ast_dump_context->ostream() << ")";
14684 // Make a ptrmask symbol expression.
14686 Expression*
14687 Expression::make_ptrmask_symbol(Type* type)
14689 return new Ptrmask_symbol_expression(type);
14692 // An expression which evaluates to some characteristic of a type.
14693 // This is only used to initialize fields of a type descriptor. Using
14694 // a new expression class is slightly inefficient but gives us a good
14695 // separation between the frontend and the middle-end with regard to
14696 // how types are laid out.
14698 class Type_info_expression : public Expression
14700 public:
14701 Type_info_expression(Type* type, Type_info type_info)
14702 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14703 type_(type), type_info_(type_info)
14706 protected:
14707 bool
14708 do_is_static_initializer() const
14709 { return true; }
14711 Type*
14712 do_type();
14714 void
14715 do_determine_type(const Type_context*)
14718 Expression*
14719 do_copy()
14720 { return this; }
14722 Bexpression*
14723 do_get_backend(Translate_context* context);
14725 void
14726 do_dump_expression(Ast_dump_context*) const;
14728 private:
14729 // The type for which we are getting information.
14730 Type* type_;
14731 // What information we want.
14732 Type_info type_info_;
14735 // The type is chosen to match what the type descriptor struct
14736 // expects.
14738 Type*
14739 Type_info_expression::do_type()
14741 switch (this->type_info_)
14743 case TYPE_INFO_SIZE:
14744 case TYPE_INFO_BACKEND_PTRDATA:
14745 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14746 return Type::lookup_integer_type("uintptr");
14747 case TYPE_INFO_ALIGNMENT:
14748 case TYPE_INFO_FIELD_ALIGNMENT:
14749 return Type::lookup_integer_type("uint8");
14750 default:
14751 go_unreachable();
14755 // Return the backend representation for type information.
14757 Bexpression*
14758 Type_info_expression::do_get_backend(Translate_context* context)
14760 Gogo* gogo = context->gogo();
14761 bool ok = true;
14762 int64_t val;
14763 switch (this->type_info_)
14765 case TYPE_INFO_SIZE:
14766 ok = this->type_->backend_type_size(gogo, &val);
14767 break;
14768 case TYPE_INFO_ALIGNMENT:
14769 ok = this->type_->backend_type_align(gogo, &val);
14770 break;
14771 case TYPE_INFO_FIELD_ALIGNMENT:
14772 ok = this->type_->backend_type_field_align(gogo, &val);
14773 break;
14774 case TYPE_INFO_BACKEND_PTRDATA:
14775 ok = this->type_->backend_type_ptrdata(gogo, &val);
14776 break;
14777 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14778 ok = this->type_->descriptor_ptrdata(gogo, &val);
14779 break;
14780 default:
14781 go_unreachable();
14783 if (!ok)
14785 go_assert(saw_errors());
14786 return gogo->backend()->error_expression();
14788 Expression* e = Expression::make_integer_int64(val, this->type(),
14789 this->location());
14790 return e->get_backend(context);
14793 // Dump ast representation for a type info expression.
14795 void
14796 Type_info_expression::do_dump_expression(
14797 Ast_dump_context* ast_dump_context) const
14799 ast_dump_context->ostream() << "typeinfo(";
14800 ast_dump_context->dump_type(this->type_);
14801 ast_dump_context->ostream() << ",";
14802 ast_dump_context->ostream() <<
14803 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14804 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14805 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14806 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14807 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14808 : "unknown");
14809 ast_dump_context->ostream() << ")";
14812 // Make a type info expression.
14814 Expression*
14815 Expression::make_type_info(Type* type, Type_info type_info)
14817 return new Type_info_expression(type, type_info);
14820 // An expression that evaluates to some characteristic of a slice.
14821 // This is used when indexing, bound-checking, or nil checking a slice.
14823 class Slice_info_expression : public Expression
14825 public:
14826 Slice_info_expression(Expression* slice, Slice_info slice_info,
14827 Location location)
14828 : Expression(EXPRESSION_SLICE_INFO, location),
14829 slice_(slice), slice_info_(slice_info)
14832 protected:
14833 Type*
14834 do_type();
14836 void
14837 do_determine_type(const Type_context*)
14840 Expression*
14841 do_copy()
14843 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14844 this->location());
14847 Bexpression*
14848 do_get_backend(Translate_context* context);
14850 void
14851 do_dump_expression(Ast_dump_context*) const;
14853 void
14854 do_issue_nil_check()
14855 { this->slice_->issue_nil_check(); }
14857 private:
14858 // The slice for which we are getting information.
14859 Expression* slice_;
14860 // What information we want.
14861 Slice_info slice_info_;
14864 // Return the type of the slice info.
14866 Type*
14867 Slice_info_expression::do_type()
14869 switch (this->slice_info_)
14871 case SLICE_INFO_VALUE_POINTER:
14872 return Type::make_pointer_type(
14873 this->slice_->type()->array_type()->element_type());
14874 case SLICE_INFO_LENGTH:
14875 case SLICE_INFO_CAPACITY:
14876 return Type::lookup_integer_type("int");
14877 default:
14878 go_unreachable();
14882 // Return the backend information for slice information.
14884 Bexpression*
14885 Slice_info_expression::do_get_backend(Translate_context* context)
14887 Gogo* gogo = context->gogo();
14888 Bexpression* bslice = this->slice_->get_backend(context);
14889 switch (this->slice_info_)
14891 case SLICE_INFO_VALUE_POINTER:
14892 case SLICE_INFO_LENGTH:
14893 case SLICE_INFO_CAPACITY:
14894 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14895 this->location());
14896 break;
14897 default:
14898 go_unreachable();
14902 // Dump ast representation for a type info expression.
14904 void
14905 Slice_info_expression::do_dump_expression(
14906 Ast_dump_context* ast_dump_context) const
14908 ast_dump_context->ostream() << "sliceinfo(";
14909 this->slice_->dump_expression(ast_dump_context);
14910 ast_dump_context->ostream() << ",";
14911 ast_dump_context->ostream() <<
14912 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14913 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14914 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14915 : "unknown");
14916 ast_dump_context->ostream() << ")";
14919 // Make a slice info expression.
14921 Expression*
14922 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14923 Location location)
14925 return new Slice_info_expression(slice, slice_info, location);
14928 // An expression that represents a slice value: a struct with value pointer,
14929 // length, and capacity fields.
14931 class Slice_value_expression : public Expression
14933 public:
14934 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14935 Expression* cap, Location location)
14936 : Expression(EXPRESSION_SLICE_VALUE, location),
14937 type_(type), valptr_(valptr), len_(len), cap_(cap)
14940 protected:
14942 do_traverse(Traverse*);
14944 Type*
14945 do_type()
14946 { return this->type_; }
14948 void
14949 do_determine_type(const Type_context*)
14950 { go_unreachable(); }
14952 Expression*
14953 do_copy()
14955 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14956 this->len_->copy(), this->cap_->copy(),
14957 this->location());
14960 Bexpression*
14961 do_get_backend(Translate_context* context);
14963 void
14964 do_dump_expression(Ast_dump_context*) const;
14966 private:
14967 // The type of the slice value.
14968 Type* type_;
14969 // The pointer to the values in the slice.
14970 Expression* valptr_;
14971 // The length of the slice.
14972 Expression* len_;
14973 // The capacity of the slice.
14974 Expression* cap_;
14978 Slice_value_expression::do_traverse(Traverse* traverse)
14980 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14981 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14982 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14983 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14984 return TRAVERSE_EXIT;
14985 return TRAVERSE_CONTINUE;
14988 Bexpression*
14989 Slice_value_expression::do_get_backend(Translate_context* context)
14991 std::vector<Bexpression*> vals(3);
14992 vals[0] = this->valptr_->get_backend(context);
14993 vals[1] = this->len_->get_backend(context);
14994 vals[2] = this->cap_->get_backend(context);
14996 Gogo* gogo = context->gogo();
14997 Btype* btype = this->type_->get_backend(gogo);
14998 return gogo->backend()->constructor_expression(btype, vals, this->location());
15001 void
15002 Slice_value_expression::do_dump_expression(
15003 Ast_dump_context* ast_dump_context) const
15005 ast_dump_context->ostream() << "slicevalue(";
15006 ast_dump_context->ostream() << "values: ";
15007 this->valptr_->dump_expression(ast_dump_context);
15008 ast_dump_context->ostream() << ", length: ";
15009 this->len_->dump_expression(ast_dump_context);
15010 ast_dump_context->ostream() << ", capacity: ";
15011 this->cap_->dump_expression(ast_dump_context);
15012 ast_dump_context->ostream() << ")";
15015 Expression*
15016 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
15017 Expression* cap, Location location)
15019 go_assert(at->is_slice_type());
15020 return new Slice_value_expression(at, valptr, len, cap, location);
15023 // An expression that evaluates to some characteristic of a non-empty interface.
15024 // This is used to access the method table or underlying object of an interface.
15026 class Interface_info_expression : public Expression
15028 public:
15029 Interface_info_expression(Expression* iface, Interface_info iface_info,
15030 Location location)
15031 : Expression(EXPRESSION_INTERFACE_INFO, location),
15032 iface_(iface), iface_info_(iface_info)
15035 protected:
15036 Type*
15037 do_type();
15039 void
15040 do_determine_type(const Type_context*)
15043 Expression*
15044 do_copy()
15046 return new Interface_info_expression(this->iface_->copy(),
15047 this->iface_info_, this->location());
15050 Bexpression*
15051 do_get_backend(Translate_context* context);
15053 void
15054 do_dump_expression(Ast_dump_context*) const;
15056 void
15057 do_issue_nil_check()
15058 { this->iface_->issue_nil_check(); }
15060 private:
15061 // The interface for which we are getting information.
15062 Expression* iface_;
15063 // What information we want.
15064 Interface_info iface_info_;
15067 // Return the type of the interface info.
15069 Type*
15070 Interface_info_expression::do_type()
15072 switch (this->iface_info_)
15074 case INTERFACE_INFO_METHODS:
15076 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15077 static Hashtable result_types;
15079 Interface_type* itype = this->iface_->type()->interface_type();
15081 Hashtable::const_iterator p = result_types.find(itype);
15082 if (p != result_types.end())
15083 return p->second;
15085 Type* pdt = Type::make_type_descriptor_ptr_type();
15086 if (itype->is_empty())
15088 result_types[itype] = pdt;
15089 return pdt;
15092 Location loc = this->location();
15093 Struct_field_list* sfl = new Struct_field_list();
15094 sfl->push_back(
15095 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15097 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15098 p != itype->methods()->end();
15099 ++p)
15101 Function_type* ft = p->type()->function_type();
15102 go_assert(ft->receiver() == NULL);
15104 const Typed_identifier_list* params = ft->parameters();
15105 Typed_identifier_list* mparams = new Typed_identifier_list();
15106 if (params != NULL)
15107 mparams->reserve(params->size() + 1);
15108 Type* vt = Type::make_pointer_type(Type::make_void_type());
15109 mparams->push_back(Typed_identifier("", vt, ft->location()));
15110 if (params != NULL)
15112 for (Typed_identifier_list::const_iterator pp = params->begin();
15113 pp != params->end();
15114 ++pp)
15115 mparams->push_back(*pp);
15118 Typed_identifier_list* mresults = (ft->results() == NULL
15119 ? NULL
15120 : ft->results()->copy());
15121 Backend_function_type* mft =
15122 Type::make_backend_function_type(NULL, mparams, mresults,
15123 ft->location());
15125 std::string fname = Gogo::unpack_hidden_name(p->name());
15126 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15129 Struct_type* st = Type::make_struct_type(sfl, loc);
15130 st->set_is_struct_incomparable();
15131 Pointer_type *pt = Type::make_pointer_type(st);
15132 result_types[itype] = pt;
15133 return pt;
15135 case INTERFACE_INFO_OBJECT:
15136 return Type::make_pointer_type(Type::make_void_type());
15137 default:
15138 go_unreachable();
15142 // Return the backend representation for interface information.
15144 Bexpression*
15145 Interface_info_expression::do_get_backend(Translate_context* context)
15147 Gogo* gogo = context->gogo();
15148 Bexpression* biface = this->iface_->get_backend(context);
15149 switch (this->iface_info_)
15151 case INTERFACE_INFO_METHODS:
15152 case INTERFACE_INFO_OBJECT:
15153 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15154 this->location());
15155 break;
15156 default:
15157 go_unreachable();
15161 // Dump ast representation for an interface info expression.
15163 void
15164 Interface_info_expression::do_dump_expression(
15165 Ast_dump_context* ast_dump_context) const
15167 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15168 ast_dump_context->ostream() << "interfaceinfo(";
15169 this->iface_->dump_expression(ast_dump_context);
15170 ast_dump_context->ostream() << ",";
15171 ast_dump_context->ostream() <<
15172 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15173 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15174 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15175 : "unknown");
15176 ast_dump_context->ostream() << ")";
15179 // Make an interface info expression.
15181 Expression*
15182 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15183 Location location)
15185 return new Interface_info_expression(iface, iface_info, location);
15188 // An expression that represents an interface value. The first field is either
15189 // a type descriptor for an empty interface or a pointer to the interface method
15190 // table for a non-empty interface. The second field is always the object.
15192 class Interface_value_expression : public Expression
15194 public:
15195 Interface_value_expression(Type* type, Expression* first_field,
15196 Expression* obj, Location location)
15197 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15198 type_(type), first_field_(first_field), obj_(obj)
15201 protected:
15203 do_traverse(Traverse*);
15205 Type*
15206 do_type()
15207 { return this->type_; }
15209 void
15210 do_determine_type(const Type_context*)
15211 { go_unreachable(); }
15213 Expression*
15214 do_copy()
15216 return new Interface_value_expression(this->type_,
15217 this->first_field_->copy(),
15218 this->obj_->copy(), this->location());
15221 Bexpression*
15222 do_get_backend(Translate_context* context);
15224 void
15225 do_dump_expression(Ast_dump_context*) const;
15227 private:
15228 // The type of the interface value.
15229 Type* type_;
15230 // The first field of the interface (either a type descriptor or a pointer
15231 // to the method table.
15232 Expression* first_field_;
15233 // The underlying object of the interface.
15234 Expression* obj_;
15238 Interface_value_expression::do_traverse(Traverse* traverse)
15240 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15241 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15242 return TRAVERSE_EXIT;
15243 return TRAVERSE_CONTINUE;
15246 Bexpression*
15247 Interface_value_expression::do_get_backend(Translate_context* context)
15249 std::vector<Bexpression*> vals(2);
15250 vals[0] = this->first_field_->get_backend(context);
15251 vals[1] = this->obj_->get_backend(context);
15253 Gogo* gogo = context->gogo();
15254 Btype* btype = this->type_->get_backend(gogo);
15255 return gogo->backend()->constructor_expression(btype, vals, this->location());
15258 void
15259 Interface_value_expression::do_dump_expression(
15260 Ast_dump_context* ast_dump_context) const
15262 ast_dump_context->ostream() << "interfacevalue(";
15263 ast_dump_context->ostream() <<
15264 (this->type_->interface_type()->is_empty()
15265 ? "type_descriptor: "
15266 : "methods: ");
15267 this->first_field_->dump_expression(ast_dump_context);
15268 ast_dump_context->ostream() << ", object: ";
15269 this->obj_->dump_expression(ast_dump_context);
15270 ast_dump_context->ostream() << ")";
15273 Expression*
15274 Expression::make_interface_value(Type* type, Expression* first_value,
15275 Expression* object, Location location)
15277 return new Interface_value_expression(type, first_value, object, location);
15280 // An interface method table for a pair of types: an interface type and a type
15281 // that implements that interface.
15283 class Interface_mtable_expression : public Expression
15285 public:
15286 Interface_mtable_expression(Interface_type* itype, Type* type,
15287 bool is_pointer, Location location)
15288 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15289 itype_(itype), type_(type), is_pointer_(is_pointer),
15290 method_table_type_(NULL), bvar_(NULL)
15293 protected:
15295 do_traverse(Traverse*);
15297 Type*
15298 do_type();
15300 bool
15301 do_is_static_initializer() const
15302 { return true; }
15304 void
15305 do_determine_type(const Type_context*)
15306 { go_unreachable(); }
15308 Expression*
15309 do_copy()
15311 return new Interface_mtable_expression(this->itype_, this->type_,
15312 this->is_pointer_, this->location());
15315 bool
15316 do_is_addressable() const
15317 { return true; }
15319 Bexpression*
15320 do_get_backend(Translate_context* context);
15322 void
15323 do_dump_expression(Ast_dump_context*) const;
15325 private:
15326 // The interface type for which the methods are defined.
15327 Interface_type* itype_;
15328 // The type to construct the interface method table for.
15329 Type* type_;
15330 // Whether this table contains the method set for the receiver type or the
15331 // pointer receiver type.
15332 bool is_pointer_;
15333 // The type of the method table.
15334 Type* method_table_type_;
15335 // The backend variable that refers to the interface method table.
15336 Bvariable* bvar_;
15340 Interface_mtable_expression::do_traverse(Traverse* traverse)
15342 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15343 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15344 return TRAVERSE_EXIT;
15345 return TRAVERSE_CONTINUE;
15348 Type*
15349 Interface_mtable_expression::do_type()
15351 if (this->method_table_type_ != NULL)
15352 return this->method_table_type_;
15354 const Typed_identifier_list* interface_methods = this->itype_->methods();
15355 go_assert(!interface_methods->empty());
15357 Struct_field_list* sfl = new Struct_field_list;
15358 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15359 this->location());
15360 sfl->push_back(Struct_field(tid));
15361 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15362 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15363 p != interface_methods->end();
15364 ++p)
15366 // We want C function pointers here, not func descriptors; model
15367 // using void* pointers.
15368 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15369 sfl->push_back(Struct_field(method));
15371 Struct_type* st = Type::make_struct_type(sfl, this->location());
15372 st->set_is_struct_incomparable();
15373 this->method_table_type_ = st;
15374 return this->method_table_type_;
15377 Bexpression*
15378 Interface_mtable_expression::do_get_backend(Translate_context* context)
15380 Gogo* gogo = context->gogo();
15381 Location loc = Linemap::predeclared_location();
15382 if (this->bvar_ != NULL)
15383 return gogo->backend()->var_expression(this->bvar_, VE_rvalue,
15384 this->location());
15386 const Typed_identifier_list* interface_methods = this->itype_->methods();
15387 go_assert(!interface_methods->empty());
15389 std::string mangled_name =
15390 gogo->interface_method_table_name(this->itype_, this->type_,
15391 this->is_pointer_);
15393 // Set is_public if we are converting a named type to an interface
15394 // type that is defined in the same package as the named type, and
15395 // the interface has hidden methods. In that case the interface
15396 // method table will be defined by the package that defines the
15397 // types.
15398 bool is_public = false;
15399 if (this->type_->named_type() != NULL
15400 && (this->type_->named_type()->named_object()->package()
15401 == this->itype_->package()))
15403 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15404 p != interface_methods->end();
15405 ++p)
15407 if (Gogo::is_hidden_name(p->name()))
15409 is_public = true;
15410 break;
15415 if (is_public
15416 && this->type_->named_type()->named_object()->package() != NULL)
15418 // The interface conversion table is defined elsewhere.
15419 Btype* btype = this->type()->get_backend(gogo);
15420 std::string asm_name(go_selectively_encode_id(mangled_name));
15421 this->bvar_ =
15422 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15423 btype, loc);
15424 return gogo->backend()->var_expression(this->bvar_, VE_rvalue,
15425 this->location());
15428 // The first element is the type descriptor.
15429 Type* td_type;
15430 if (!this->is_pointer_)
15431 td_type = this->type_;
15432 else
15433 td_type = Type::make_pointer_type(this->type_);
15435 std::vector<Backend::Btyped_identifier> bstructfields;
15437 // Build an interface method table for a type: a type descriptor followed by a
15438 // list of function pointers, one for each interface method. This is used for
15439 // interfaces.
15440 Expression_list* svals = new Expression_list();
15441 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15442 svals->push_back(tdescriptor);
15444 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15445 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15446 bstructfields.push_back(btd);
15448 Named_type* nt = this->type_->named_type();
15449 Struct_type* st = this->type_->struct_type();
15450 go_assert(nt != NULL || st != NULL);
15452 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15453 p != interface_methods->end();
15454 ++p)
15456 bool is_ambiguous;
15457 Method* m;
15458 if (nt != NULL)
15459 m = nt->method_function(p->name(), &is_ambiguous);
15460 else
15461 m = st->method_function(p->name(), &is_ambiguous);
15462 go_assert(m != NULL);
15463 Named_object* no = m->named_object();
15465 go_assert(no->is_function() || no->is_function_declaration());
15467 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15468 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15469 bstructfields.push_back(bmtype);
15471 svals->push_back(Expression::make_func_code_reference(no, loc));
15474 Btype *btype = gogo->backend()->struct_type(bstructfields);
15475 std::vector<Bexpression*> ctor_bexprs;
15476 for (Expression_list::const_iterator pe = svals->begin();
15477 pe != svals->end();
15478 ++pe)
15480 ctor_bexprs.push_back((*pe)->get_backend(context));
15482 Bexpression* ctor =
15483 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15485 std::string asm_name(go_selectively_encode_id(mangled_name));
15486 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15487 !is_public, btype, loc);
15488 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15489 !is_public, btype, loc, ctor);
15490 return gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
15493 void
15494 Interface_mtable_expression::do_dump_expression(
15495 Ast_dump_context* ast_dump_context) const
15497 ast_dump_context->ostream() << "__go_"
15498 << (this->is_pointer_ ? "pimt__" : "imt_");
15499 ast_dump_context->dump_type(this->itype_);
15500 ast_dump_context->ostream() << "__";
15501 ast_dump_context->dump_type(this->type_);
15504 Expression*
15505 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15506 bool is_pointer, Location location)
15508 return new Interface_mtable_expression(itype, type, is_pointer, location);
15511 // An expression which evaluates to the offset of a field within a
15512 // struct. This, like Type_info_expression, q.v., is only used to
15513 // initialize fields of a type descriptor.
15515 class Struct_field_offset_expression : public Expression
15517 public:
15518 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15519 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15520 Linemap::predeclared_location()),
15521 type_(type), field_(field)
15524 protected:
15525 bool
15526 do_is_static_initializer() const
15527 { return true; }
15529 Type*
15530 do_type()
15531 { return Type::lookup_integer_type("uintptr"); }
15533 void
15534 do_determine_type(const Type_context*)
15537 Expression*
15538 do_copy()
15539 { return this; }
15541 Bexpression*
15542 do_get_backend(Translate_context* context);
15544 void
15545 do_dump_expression(Ast_dump_context*) const;
15547 private:
15548 // The type of the struct.
15549 Struct_type* type_;
15550 // The field.
15551 const Struct_field* field_;
15554 // Return the backend representation for a struct field offset.
15556 Bexpression*
15557 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15559 const Struct_field_list* fields = this->type_->fields();
15560 Struct_field_list::const_iterator p;
15561 unsigned i = 0;
15562 for (p = fields->begin();
15563 p != fields->end();
15564 ++p, ++i)
15565 if (&*p == this->field_)
15566 break;
15567 go_assert(&*p == this->field_);
15569 Gogo* gogo = context->gogo();
15570 Btype* btype = this->type_->get_backend(gogo);
15572 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15573 Type* uptr_type = Type::lookup_integer_type("uintptr");
15574 Expression* ret =
15575 Expression::make_integer_int64(offset, uptr_type,
15576 Linemap::predeclared_location());
15577 return ret->get_backend(context);
15580 // Dump ast representation for a struct field offset expression.
15582 void
15583 Struct_field_offset_expression::do_dump_expression(
15584 Ast_dump_context* ast_dump_context) const
15586 ast_dump_context->ostream() << "unsafe.Offsetof(";
15587 ast_dump_context->dump_type(this->type_);
15588 ast_dump_context->ostream() << '.';
15589 ast_dump_context->ostream() <<
15590 Gogo::message_name(this->field_->field_name());
15591 ast_dump_context->ostream() << ")";
15594 // Make an expression for a struct field offset.
15596 Expression*
15597 Expression::make_struct_field_offset(Struct_type* type,
15598 const Struct_field* field)
15600 return new Struct_field_offset_expression(type, field);
15603 // An expression which evaluates to the address of an unnamed label.
15605 class Label_addr_expression : public Expression
15607 public:
15608 Label_addr_expression(Label* label, Location location)
15609 : Expression(EXPRESSION_LABEL_ADDR, location),
15610 label_(label)
15613 protected:
15614 Type*
15615 do_type()
15616 { return Type::make_pointer_type(Type::make_void_type()); }
15618 void
15619 do_determine_type(const Type_context*)
15622 Expression*
15623 do_copy()
15624 { return new Label_addr_expression(this->label_, this->location()); }
15626 Bexpression*
15627 do_get_backend(Translate_context* context)
15628 { return this->label_->get_addr(context, this->location()); }
15630 void
15631 do_dump_expression(Ast_dump_context* ast_dump_context) const
15632 { ast_dump_context->ostream() << this->label_->name(); }
15634 private:
15635 // The label whose address we are taking.
15636 Label* label_;
15639 // Make an expression for the address of an unnamed label.
15641 Expression*
15642 Expression::make_label_addr(Label* label, Location location)
15644 return new Label_addr_expression(label, location);
15647 // Class Conditional_expression.
15649 // Traversal.
15652 Conditional_expression::do_traverse(Traverse* traverse)
15654 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15655 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15656 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15657 return TRAVERSE_EXIT;
15658 return TRAVERSE_CONTINUE;
15661 // Return the type of the conditional expression.
15663 Type*
15664 Conditional_expression::do_type()
15666 Type* result_type = Type::make_void_type();
15667 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15668 NULL))
15669 result_type = this->then_->type();
15670 else if (this->then_->is_nil_expression()
15671 || this->else_->is_nil_expression())
15672 result_type = (!this->then_->is_nil_expression()
15673 ? this->then_->type()
15674 : this->else_->type());
15675 return result_type;
15678 // Determine type for a conditional expression.
15680 void
15681 Conditional_expression::do_determine_type(const Type_context* context)
15683 this->cond_->determine_type_no_context();
15684 this->then_->determine_type(context);
15685 this->else_->determine_type(context);
15688 // Get the backend representation of a conditional expression.
15690 Bexpression*
15691 Conditional_expression::do_get_backend(Translate_context* context)
15693 Gogo* gogo = context->gogo();
15694 Btype* result_btype = this->type()->get_backend(gogo);
15695 Bexpression* cond = this->cond_->get_backend(context);
15696 Bexpression* then = this->then_->get_backend(context);
15697 Bexpression* belse = this->else_->get_backend(context);
15698 Bfunction* bfn = context->function()->func_value()->get_decl();
15699 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15700 belse, this->location());
15703 // Dump ast representation of a conditional expression.
15705 void
15706 Conditional_expression::do_dump_expression(
15707 Ast_dump_context* ast_dump_context) const
15709 ast_dump_context->ostream() << "(";
15710 ast_dump_context->dump_expression(this->cond_);
15711 ast_dump_context->ostream() << " ? ";
15712 ast_dump_context->dump_expression(this->then_);
15713 ast_dump_context->ostream() << " : ";
15714 ast_dump_context->dump_expression(this->else_);
15715 ast_dump_context->ostream() << ") ";
15718 // Make a conditional expression.
15720 Expression*
15721 Expression::make_conditional(Expression* cond, Expression* then,
15722 Expression* else_expr, Location location)
15724 return new Conditional_expression(cond, then, else_expr, location);
15727 // Class Compound_expression.
15729 // Traversal.
15732 Compound_expression::do_traverse(Traverse* traverse)
15734 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15735 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15736 return TRAVERSE_EXIT;
15737 return TRAVERSE_CONTINUE;
15740 // Return the type of the compound expression.
15742 Type*
15743 Compound_expression::do_type()
15745 return this->expr_->type();
15748 // Determine type for a compound expression.
15750 void
15751 Compound_expression::do_determine_type(const Type_context* context)
15753 this->init_->determine_type_no_context();
15754 this->expr_->determine_type(context);
15757 // Get the backend representation of a compound expression.
15759 Bexpression*
15760 Compound_expression::do_get_backend(Translate_context* context)
15762 Gogo* gogo = context->gogo();
15763 Bexpression* binit = this->init_->get_backend(context);
15764 Bfunction* bfunction = context->function()->func_value()->get_decl();
15765 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15766 binit);
15767 Bexpression* bexpr = this->expr_->get_backend(context);
15768 return gogo->backend()->compound_expression(init_stmt, bexpr,
15769 this->location());
15772 // Dump ast representation of a conditional expression.
15774 void
15775 Compound_expression::do_dump_expression(
15776 Ast_dump_context* ast_dump_context) const
15778 ast_dump_context->ostream() << "(";
15779 ast_dump_context->dump_expression(this->init_);
15780 ast_dump_context->ostream() << ",";
15781 ast_dump_context->dump_expression(this->expr_);
15782 ast_dump_context->ostream() << ") ";
15785 // Make a compound expression.
15787 Expression*
15788 Expression::make_compound(Expression* init, Expression* expr, Location location)
15790 return new Compound_expression(init, expr, location);
15793 // Class Backend_expression.
15796 Backend_expression::do_traverse(Traverse*)
15798 return TRAVERSE_CONTINUE;
15801 void
15802 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15804 ast_dump_context->ostream() << "backend_expression<";
15805 ast_dump_context->dump_type(this->type_);
15806 ast_dump_context->ostream() << ">";
15809 Expression*
15810 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15812 return new Backend_expression(bexpr, type, location);
15815 // Import an expression. This comes at the end in order to see the
15816 // various class definitions.
15818 Expression*
15819 Expression::import_expression(Import* imp)
15821 int c = imp->peek_char();
15822 if (imp->match_c_string("- ")
15823 || imp->match_c_string("! ")
15824 || imp->match_c_string("^ "))
15825 return Unary_expression::do_import(imp);
15826 else if (c == '(')
15827 return Binary_expression::do_import(imp);
15828 else if (imp->match_c_string("true")
15829 || imp->match_c_string("false"))
15830 return Boolean_expression::do_import(imp);
15831 else if (c == '"')
15832 return String_expression::do_import(imp);
15833 else if (c == '-' || (c >= '0' && c <= '9'))
15835 // This handles integers, floats and complex constants.
15836 return Integer_expression::do_import(imp);
15838 else if (imp->match_c_string("nil"))
15839 return Nil_expression::do_import(imp);
15840 else if (imp->match_c_string("convert"))
15841 return Type_conversion_expression::do_import(imp);
15842 else
15844 go_error_at(imp->location(), "import error: expected expression");
15845 return Expression::make_error(imp->location());
15849 // Class Expression_list.
15851 // Traverse the list.
15854 Expression_list::traverse(Traverse* traverse)
15856 for (Expression_list::iterator p = this->begin();
15857 p != this->end();
15858 ++p)
15860 if (*p != NULL)
15862 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15863 return TRAVERSE_EXIT;
15866 return TRAVERSE_CONTINUE;
15869 // Copy the list.
15871 Expression_list*
15872 Expression_list::copy()
15874 Expression_list* ret = new Expression_list();
15875 for (Expression_list::iterator p = this->begin();
15876 p != this->end();
15877 ++p)
15879 if (*p == NULL)
15880 ret->push_back(NULL);
15881 else
15882 ret->push_back((*p)->copy());
15884 return ret;
15887 // Return whether an expression list has an error expression.
15889 bool
15890 Expression_list::contains_error() const
15892 for (Expression_list::const_iterator p = this->begin();
15893 p != this->end();
15894 ++p)
15895 if (*p != NULL && (*p)->is_error_expression())
15896 return true;
15897 return false;
15900 // Class Numeric_constant.
15902 // Destructor.
15904 Numeric_constant::~Numeric_constant()
15906 this->clear();
15909 // Copy constructor.
15911 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15912 : classification_(a.classification_), type_(a.type_)
15914 switch (a.classification_)
15916 case NC_INVALID:
15917 break;
15918 case NC_INT:
15919 case NC_RUNE:
15920 mpz_init_set(this->u_.int_val, a.u_.int_val);
15921 break;
15922 case NC_FLOAT:
15923 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15924 break;
15925 case NC_COMPLEX:
15926 mpc_init2(this->u_.complex_val, mpc_precision);
15927 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15928 break;
15929 default:
15930 go_unreachable();
15934 // Assignment operator.
15936 Numeric_constant&
15937 Numeric_constant::operator=(const Numeric_constant& a)
15939 this->clear();
15940 this->classification_ = a.classification_;
15941 this->type_ = a.type_;
15942 switch (a.classification_)
15944 case NC_INVALID:
15945 break;
15946 case NC_INT:
15947 case NC_RUNE:
15948 mpz_init_set(this->u_.int_val, a.u_.int_val);
15949 break;
15950 case NC_FLOAT:
15951 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15952 break;
15953 case NC_COMPLEX:
15954 mpc_init2(this->u_.complex_val, mpc_precision);
15955 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15956 break;
15957 default:
15958 go_unreachable();
15960 return *this;
15963 // Clear the contents.
15965 void
15966 Numeric_constant::clear()
15968 switch (this->classification_)
15970 case NC_INVALID:
15971 break;
15972 case NC_INT:
15973 case NC_RUNE:
15974 mpz_clear(this->u_.int_val);
15975 break;
15976 case NC_FLOAT:
15977 mpfr_clear(this->u_.float_val);
15978 break;
15979 case NC_COMPLEX:
15980 mpc_clear(this->u_.complex_val);
15981 break;
15982 default:
15983 go_unreachable();
15985 this->classification_ = NC_INVALID;
15988 // Set to an unsigned long value.
15990 void
15991 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15993 this->clear();
15994 this->classification_ = NC_INT;
15995 this->type_ = type;
15996 mpz_init_set_ui(this->u_.int_val, val);
15999 // Set to an integer value.
16001 void
16002 Numeric_constant::set_int(Type* type, const mpz_t val)
16004 this->clear();
16005 this->classification_ = NC_INT;
16006 this->type_ = type;
16007 mpz_init_set(this->u_.int_val, val);
16010 // Set to a rune value.
16012 void
16013 Numeric_constant::set_rune(Type* type, const mpz_t val)
16015 this->clear();
16016 this->classification_ = NC_RUNE;
16017 this->type_ = type;
16018 mpz_init_set(this->u_.int_val, val);
16021 // Set to a floating point value.
16023 void
16024 Numeric_constant::set_float(Type* type, const mpfr_t val)
16026 this->clear();
16027 this->classification_ = NC_FLOAT;
16028 this->type_ = type;
16029 // Numeric constants do not have negative zero values, so remove
16030 // them here. They also don't have infinity or NaN values, but we
16031 // should never see them here.
16032 if (mpfr_zero_p(val))
16033 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16034 else
16035 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16038 // Set to a complex value.
16040 void
16041 Numeric_constant::set_complex(Type* type, const mpc_t val)
16043 this->clear();
16044 this->classification_ = NC_COMPLEX;
16045 this->type_ = type;
16046 mpc_init2(this->u_.complex_val, mpc_precision);
16047 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
16050 // Get an int value.
16052 void
16053 Numeric_constant::get_int(mpz_t* val) const
16055 go_assert(this->is_int());
16056 mpz_init_set(*val, this->u_.int_val);
16059 // Get a rune value.
16061 void
16062 Numeric_constant::get_rune(mpz_t* val) const
16064 go_assert(this->is_rune());
16065 mpz_init_set(*val, this->u_.int_val);
16068 // Get a floating point value.
16070 void
16071 Numeric_constant::get_float(mpfr_t* val) const
16073 go_assert(this->is_float());
16074 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16077 // Get a complex value.
16079 void
16080 Numeric_constant::get_complex(mpc_t* val) const
16082 go_assert(this->is_complex());
16083 mpc_init2(*val, mpc_precision);
16084 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16087 // Express value as unsigned long if possible.
16089 Numeric_constant::To_unsigned_long
16090 Numeric_constant::to_unsigned_long(unsigned long* val) const
16092 switch (this->classification_)
16094 case NC_INT:
16095 case NC_RUNE:
16096 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16097 case NC_FLOAT:
16098 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16099 case NC_COMPLEX:
16100 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16101 return NC_UL_NOTINT;
16102 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16103 val);
16104 default:
16105 go_unreachable();
16109 // Express integer value as unsigned long if possible.
16111 Numeric_constant::To_unsigned_long
16112 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16113 unsigned long *val) const
16115 if (mpz_sgn(ival) < 0)
16116 return NC_UL_NEGATIVE;
16117 unsigned long ui = mpz_get_ui(ival);
16118 if (mpz_cmp_ui(ival, ui) != 0)
16119 return NC_UL_BIG;
16120 *val = ui;
16121 return NC_UL_VALID;
16124 // Express floating point value as unsigned long if possible.
16126 Numeric_constant::To_unsigned_long
16127 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16128 unsigned long *val) const
16130 if (!mpfr_integer_p(fval))
16131 return NC_UL_NOTINT;
16132 mpz_t ival;
16133 mpz_init(ival);
16134 mpfr_get_z(ival, fval, GMP_RNDN);
16135 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16136 mpz_clear(ival);
16137 return ret;
16140 // Express value as memory size if possible.
16142 bool
16143 Numeric_constant::to_memory_size(int64_t* val) const
16145 switch (this->classification_)
16147 case NC_INT:
16148 case NC_RUNE:
16149 return this->mpz_to_memory_size(this->u_.int_val, val);
16150 case NC_FLOAT:
16151 return this->mpfr_to_memory_size(this->u_.float_val, val);
16152 case NC_COMPLEX:
16153 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16154 return false;
16155 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16156 default:
16157 go_unreachable();
16161 // Express integer as memory size if possible.
16163 bool
16164 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16166 if (mpz_sgn(ival) < 0)
16167 return false;
16168 if (mpz_fits_slong_p(ival))
16170 *val = static_cast<int64_t>(mpz_get_si(ival));
16171 return true;
16174 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16175 // positive value.
16176 if (mpz_sizeinbase(ival, 2) >= 64)
16177 return false;
16179 mpz_t q, r;
16180 mpz_init(q);
16181 mpz_init(r);
16182 mpz_tdiv_q_2exp(q, ival, 32);
16183 mpz_tdiv_r_2exp(r, ival, 32);
16184 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16185 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16186 + static_cast<int64_t>(mpz_get_ui(r)));
16187 mpz_clear(r);
16188 mpz_clear(q);
16189 return true;
16192 // Express floating point value as memory size if possible.
16194 bool
16195 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16197 if (!mpfr_integer_p(fval))
16198 return false;
16199 mpz_t ival;
16200 mpz_init(ival);
16201 mpfr_get_z(ival, fval, GMP_RNDN);
16202 bool ret = this->mpz_to_memory_size(ival, val);
16203 mpz_clear(ival);
16204 return ret;
16207 // Convert value to integer if possible.
16209 bool
16210 Numeric_constant::to_int(mpz_t* val) const
16212 switch (this->classification_)
16214 case NC_INT:
16215 case NC_RUNE:
16216 mpz_init_set(*val, this->u_.int_val);
16217 return true;
16218 case NC_FLOAT:
16219 if (!mpfr_integer_p(this->u_.float_val))
16220 return false;
16221 mpz_init(*val);
16222 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16223 return true;
16224 case NC_COMPLEX:
16225 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16226 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16227 return false;
16228 mpz_init(*val);
16229 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16230 return true;
16231 default:
16232 go_unreachable();
16236 // Convert value to floating point if possible.
16238 bool
16239 Numeric_constant::to_float(mpfr_t* val) const
16241 switch (this->classification_)
16243 case NC_INT:
16244 case NC_RUNE:
16245 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16246 return true;
16247 case NC_FLOAT:
16248 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16249 return true;
16250 case NC_COMPLEX:
16251 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16252 return false;
16253 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16254 return true;
16255 default:
16256 go_unreachable();
16260 // Convert value to complex.
16262 bool
16263 Numeric_constant::to_complex(mpc_t* val) const
16265 mpc_init2(*val, mpc_precision);
16266 switch (this->classification_)
16268 case NC_INT:
16269 case NC_RUNE:
16270 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16271 return true;
16272 case NC_FLOAT:
16273 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16274 return true;
16275 case NC_COMPLEX:
16276 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16277 return true;
16278 default:
16279 go_unreachable();
16283 // Get the type.
16285 Type*
16286 Numeric_constant::type() const
16288 if (this->type_ != NULL)
16289 return this->type_;
16290 switch (this->classification_)
16292 case NC_INT:
16293 return Type::make_abstract_integer_type();
16294 case NC_RUNE:
16295 return Type::make_abstract_character_type();
16296 case NC_FLOAT:
16297 return Type::make_abstract_float_type();
16298 case NC_COMPLEX:
16299 return Type::make_abstract_complex_type();
16300 default:
16301 go_unreachable();
16305 // If the constant can be expressed in TYPE, then set the type of the
16306 // constant to TYPE and return true. Otherwise return false, and, if
16307 // ISSUE_ERROR is true, report an appropriate error message.
16309 bool
16310 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16312 bool ret;
16313 if (type == NULL || type->is_error())
16314 ret = true;
16315 else if (type->integer_type() != NULL)
16316 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16317 else if (type->float_type() != NULL)
16318 ret = this->check_float_type(type->float_type(), issue_error, loc);
16319 else if (type->complex_type() != NULL)
16320 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16321 else
16323 ret = false;
16324 if (issue_error)
16325 go_assert(saw_errors());
16327 if (ret)
16328 this->type_ = type;
16329 return ret;
16332 // Check whether the constant can be expressed in an integer type.
16334 bool
16335 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16336 Location location)
16338 mpz_t val;
16339 switch (this->classification_)
16341 case NC_INT:
16342 case NC_RUNE:
16343 mpz_init_set(val, this->u_.int_val);
16344 break;
16346 case NC_FLOAT:
16347 if (!mpfr_integer_p(this->u_.float_val))
16349 if (issue_error)
16351 go_error_at(location,
16352 "floating point constant truncated to integer");
16353 this->set_invalid();
16355 return false;
16357 mpz_init(val);
16358 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16359 break;
16361 case NC_COMPLEX:
16362 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16363 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16365 if (issue_error)
16367 go_error_at(location, "complex constant truncated to integer");
16368 this->set_invalid();
16370 return false;
16372 mpz_init(val);
16373 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16374 break;
16376 default:
16377 go_unreachable();
16380 bool ret;
16381 if (type->is_abstract())
16382 ret = true;
16383 else
16385 int bits = mpz_sizeinbase(val, 2);
16386 if (type->is_unsigned())
16388 // For an unsigned type we can only accept a nonnegative
16389 // number, and we must be able to represents at least BITS.
16390 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16392 else
16394 // For a signed type we need an extra bit to indicate the
16395 // sign. We have to handle the most negative integer
16396 // specially.
16397 ret = (bits + 1 <= type->bits()
16398 || (bits <= type->bits()
16399 && mpz_sgn(val) < 0
16400 && (mpz_scan1(val, 0)
16401 == static_cast<unsigned long>(type->bits() - 1))
16402 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16406 if (!ret && issue_error)
16408 go_error_at(location, "integer constant overflow");
16409 this->set_invalid();
16412 return ret;
16415 // Check whether the constant can be expressed in a floating point
16416 // type.
16418 bool
16419 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16420 Location location)
16422 mpfr_t val;
16423 switch (this->classification_)
16425 case NC_INT:
16426 case NC_RUNE:
16427 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16428 break;
16430 case NC_FLOAT:
16431 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16432 break;
16434 case NC_COMPLEX:
16435 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16437 if (issue_error)
16439 this->set_invalid();
16440 go_error_at(location, "complex constant truncated to float");
16442 return false;
16444 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16445 break;
16447 default:
16448 go_unreachable();
16451 bool ret;
16452 if (type->is_abstract())
16453 ret = true;
16454 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16456 // A NaN or Infinity always fits in the range of the type.
16457 ret = true;
16459 else
16461 mp_exp_t exp = mpfr_get_exp(val);
16462 mp_exp_t max_exp;
16463 switch (type->bits())
16465 case 32:
16466 max_exp = 128;
16467 break;
16468 case 64:
16469 max_exp = 1024;
16470 break;
16471 default:
16472 go_unreachable();
16475 ret = exp <= max_exp;
16477 if (ret)
16479 // Round the constant to the desired type.
16480 mpfr_t t;
16481 mpfr_init(t);
16482 switch (type->bits())
16484 case 32:
16485 mpfr_set_prec(t, 24);
16486 break;
16487 case 64:
16488 mpfr_set_prec(t, 53);
16489 break;
16490 default:
16491 go_unreachable();
16493 mpfr_set(t, val, GMP_RNDN);
16494 mpfr_set(val, t, GMP_RNDN);
16495 mpfr_clear(t);
16497 this->set_float(type, val);
16501 mpfr_clear(val);
16503 if (!ret && issue_error)
16505 go_error_at(location, "floating point constant overflow");
16506 this->set_invalid();
16509 return ret;
16512 // Check whether the constant can be expressed in a complex type.
16514 bool
16515 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16516 Location location)
16518 if (type->is_abstract())
16519 return true;
16521 mp_exp_t max_exp;
16522 switch (type->bits())
16524 case 64:
16525 max_exp = 128;
16526 break;
16527 case 128:
16528 max_exp = 1024;
16529 break;
16530 default:
16531 go_unreachable();
16534 mpc_t val;
16535 mpc_init2(val, mpc_precision);
16536 switch (this->classification_)
16538 case NC_INT:
16539 case NC_RUNE:
16540 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16541 break;
16543 case NC_FLOAT:
16544 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16545 break;
16547 case NC_COMPLEX:
16548 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16549 break;
16551 default:
16552 go_unreachable();
16555 bool ret = true;
16556 if (!mpfr_nan_p(mpc_realref(val))
16557 && !mpfr_inf_p(mpc_realref(val))
16558 && !mpfr_zero_p(mpc_realref(val))
16559 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16561 if (issue_error)
16563 go_error_at(location, "complex real part overflow");
16564 this->set_invalid();
16566 ret = false;
16569 if (!mpfr_nan_p(mpc_imagref(val))
16570 && !mpfr_inf_p(mpc_imagref(val))
16571 && !mpfr_zero_p(mpc_imagref(val))
16572 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16574 if (issue_error)
16576 go_error_at(location, "complex imaginary part overflow");
16577 this->set_invalid();
16579 ret = false;
16582 if (ret)
16584 // Round the constant to the desired type.
16585 mpc_t t;
16586 switch (type->bits())
16588 case 64:
16589 mpc_init2(t, 24);
16590 break;
16591 case 128:
16592 mpc_init2(t, 53);
16593 break;
16594 default:
16595 go_unreachable();
16597 mpc_set(t, val, MPC_RNDNN);
16598 mpc_set(val, t, MPC_RNDNN);
16599 mpc_clear(t);
16601 this->set_complex(type, val);
16604 mpc_clear(val);
16606 return ret;
16609 // Return an Expression for this value.
16611 Expression*
16612 Numeric_constant::expression(Location loc) const
16614 switch (this->classification_)
16616 case NC_INT:
16617 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16618 case NC_RUNE:
16619 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16620 case NC_FLOAT:
16621 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16622 case NC_COMPLEX:
16623 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16624 case NC_INVALID:
16625 go_assert(saw_errors());
16626 return Expression::make_error(loc);
16627 default:
16628 go_unreachable();