* gcc-interface/trans.c (node_has_volatile_full_access) <N_Identifier>:
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob109d6b469316e37feef221b7e625984ee205cc72
1 // expressions.cc -- Go frontend expression handling.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <algorithm>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
25 // Class Expression.
27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
33 Expression::~Expression()
37 // Traverse the expressions.
39 int
40 Expression::traverse(Expression** pexpr, Traverse* traverse)
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
51 return expr->do_traverse(traverse);
54 // Traverse subexpressions of this expression.
56 int
57 Expression::traverse_subexpressions(Traverse* traverse)
59 return this->do_traverse(traverse);
62 // Default implementation for do_traverse for child classes.
64 int
65 Expression::do_traverse(Traverse*)
67 return TRAVERSE_CONTINUE;
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded. By default, we give an error.
72 // Expressions with side effects override.
74 bool
75 Expression::do_discarding_value()
77 this->unused_value_error();
78 return false;
81 // This virtual function is called to export expressions. This will
82 // only be used by expressions which may be constant.
84 void
85 Expression::do_export(Export*) const
87 go_unreachable();
90 // Give an error saying that the value of the expression is not used.
92 void
93 Expression::unused_value_error()
95 this->report_error(_("value computed is not used"));
98 // Note that this expression is an error. This is called by children
99 // when they discover an error.
101 void
102 Expression::set_is_error()
104 this->classification_ = EXPRESSION_ERROR;
107 // For children to call to report an error conveniently.
109 void
110 Expression::report_error(const char* msg)
112 go_error_at(this->location_, "%s", msg);
113 this->set_is_error();
116 // Set types of variables and constants. This is implemented by the
117 // child class.
119 void
120 Expression::determine_type(const Type_context* context)
122 this->do_determine_type(context);
125 // Set types when there is no context.
127 void
128 Expression::determine_type_no_context()
130 Type_context context;
131 this->do_determine_type(&context);
134 // Return an expression handling any conversions which must be done during
135 // assignment.
137 Expression*
138 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
139 Expression* rhs, Location location)
141 Type* rhs_type = rhs->type();
142 if (lhs_type->is_error()
143 || rhs_type->is_error()
144 || rhs->is_error_expression())
145 return Expression::make_error(location);
147 bool are_identical = Type::are_identical(lhs_type, rhs_type, false, NULL);
148 if (!are_identical && lhs_type->interface_type() != NULL)
150 if (rhs_type->interface_type() == NULL)
151 return Expression::convert_type_to_interface(lhs_type, rhs, location);
152 else
153 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154 location);
156 else if (!are_identical && rhs_type->interface_type() != NULL)
157 return Expression::convert_interface_to_type(lhs_type, rhs, location);
158 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
160 // Assigning nil to a slice.
161 Expression* nil = Expression::make_nil(location);
162 Expression* zero = Expression::make_integer_ul(0, NULL, location);
163 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
165 else if (rhs_type->is_nil_type())
166 return Expression::make_nil(location);
167 else if (are_identical)
169 if (lhs_type->forwarded() != rhs_type->forwarded())
171 // Different but identical types require an explicit
172 // conversion. This happens with type aliases.
173 return Expression::make_cast(lhs_type, rhs, location);
176 // No conversion is needed.
177 return rhs;
179 else if (lhs_type->points_to() != NULL)
180 return Expression::make_unsafe_cast(lhs_type, rhs, location);
181 else if (lhs_type->is_numeric_type())
182 return Expression::make_cast(lhs_type, rhs, location);
183 else if ((lhs_type->struct_type() != NULL
184 && rhs_type->struct_type() != NULL)
185 || (lhs_type->array_type() != NULL
186 && rhs_type->array_type() != NULL))
188 // This conversion must be permitted by Go, or we wouldn't have
189 // gotten here.
190 return Expression::make_unsafe_cast(lhs_type, rhs, location);
192 else
193 return rhs;
196 // Return an expression for a conversion from a non-interface type to an
197 // interface type.
199 Expression*
200 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
201 Location location)
203 Interface_type* lhs_interface_type = lhs_type->interface_type();
204 bool lhs_is_empty = lhs_interface_type->is_empty();
206 // Since RHS_TYPE is a static type, we can create the interface
207 // method table at compile time.
209 // When setting an interface to nil, we just set both fields to
210 // NULL.
211 Type* rhs_type = rhs->type();
212 if (rhs_type->is_nil_type())
214 Expression* nil = Expression::make_nil(location);
215 return Expression::make_interface_value(lhs_type, nil, nil, location);
218 // This should have been checked already.
219 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
221 go_assert(saw_errors());
222 return Expression::make_error(location);
225 // An interface is a tuple. If LHS_TYPE is an empty interface type,
226 // then the first field is the type descriptor for RHS_TYPE.
227 // Otherwise it is the interface method table for RHS_TYPE.
228 Expression* first_field;
229 if (lhs_is_empty)
230 first_field = Expression::make_type_descriptor(rhs_type, location);
231 else
233 // Build the interface method table for this interface and this
234 // object type: a list of function pointers for each interface
235 // method.
236 Named_type* rhs_named_type = rhs_type->named_type();
237 Struct_type* rhs_struct_type = rhs_type->struct_type();
238 bool is_pointer = false;
239 if (rhs_named_type == NULL && rhs_struct_type == NULL)
241 rhs_named_type = rhs_type->deref()->named_type();
242 rhs_struct_type = rhs_type->deref()->struct_type();
243 is_pointer = true;
245 if (rhs_named_type != NULL)
246 first_field =
247 rhs_named_type->interface_method_table(lhs_interface_type,
248 is_pointer);
249 else if (rhs_struct_type != NULL)
250 first_field =
251 rhs_struct_type->interface_method_table(lhs_interface_type,
252 is_pointer);
253 else
254 first_field = Expression::make_nil(location);
257 Expression* obj;
258 if (rhs_type->points_to() != NULL)
260 // We are assigning a pointer to the interface; the interface
261 // holds the pointer itself.
262 obj = rhs;
264 else
266 // We are assigning a non-pointer value to the interface; the
267 // interface gets a copy of the value in the heap if it escapes.
268 // TODO(cmang): Associate escape state state of RHS with newly
269 // created OBJ.
270 obj = Expression::make_heap_expression(rhs, location);
273 return Expression::make_interface_value(lhs_type, first_field, obj, location);
276 // Return an expression for the type descriptor of RHS.
278 Expression*
279 Expression::get_interface_type_descriptor(Expression* rhs)
281 go_assert(rhs->type()->interface_type() != NULL);
282 Location location = rhs->location();
284 // The type descriptor is the first field of an empty interface.
285 if (rhs->type()->interface_type()->is_empty())
286 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
287 location);
289 Expression* mtable =
290 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
292 Expression* descriptor =
293 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
294 descriptor = Expression::make_field_reference(descriptor, 0, location);
295 Expression* nil = Expression::make_nil(location);
297 Expression* eq =
298 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
299 return Expression::make_conditional(eq, nil, descriptor, location);
302 // Return an expression for the conversion of an interface type to an
303 // interface type.
305 Expression*
306 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
307 bool for_type_guard,
308 Location location)
310 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
311 return rhs;
313 Interface_type* lhs_interface_type = lhs_type->interface_type();
314 bool lhs_is_empty = lhs_interface_type->is_empty();
316 // In the general case this requires runtime examination of the type
317 // method table to match it up with the interface methods.
319 // FIXME: If all of the methods in the right hand side interface
320 // also appear in the left hand side interface, then we don't need
321 // to do a runtime check, although we still need to build a new
322 // method table.
324 // We are going to evaluate RHS multiple times.
325 go_assert(rhs->is_variable());
327 // Get the type descriptor for the right hand side. This will be
328 // NULL for a nil interface.
329 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
330 Expression* lhs_type_expr =
331 Expression::make_type_descriptor(lhs_type, location);
333 Expression* first_field;
334 if (for_type_guard)
336 // A type assertion fails when converting a nil interface.
337 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
338 lhs_type_expr, rhs_type_expr);
340 else if (lhs_is_empty)
342 // A conversion to an empty interface always succeeds, and the
343 // first field is just the type descriptor of the object.
344 first_field = rhs_type_expr;
346 else
348 // A conversion to a non-empty interface may fail, but unlike a
349 // type assertion converting nil will always succeed.
350 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
351 lhs_type_expr, rhs_type_expr);
354 // The second field is simply the object pointer.
355 Expression* obj =
356 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
357 return Expression::make_interface_value(lhs_type, first_field, obj, location);
360 // Return an expression for the conversion of an interface type to a
361 // non-interface type.
363 Expression*
364 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
365 Location location)
367 // We are going to evaluate RHS multiple times.
368 go_assert(rhs->is_variable());
370 // Call a function to check that the type is valid. The function
371 // will panic with an appropriate runtime type error if the type is
372 // not valid.
373 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
374 location);
375 Expression* rhs_descriptor =
376 Expression::get_interface_type_descriptor(rhs);
378 Type* rhs_type = rhs->type();
379 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
380 location);
382 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
383 location, 3, lhs_type_expr,
384 rhs_descriptor, rhs_inter_expr);
386 // If the call succeeds, pull out the value.
387 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
388 location);
390 // If the value is a pointer, then it is the value we want.
391 // Otherwise it points to the value.
392 if (lhs_type->points_to() == NULL)
394 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
395 location);
396 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
397 location);
399 return Expression::make_compound(check_iface, obj, location);
402 // Convert an expression to its backend representation. This is implemented by
403 // the child class. Not that it is not in general safe to call this multiple
404 // times for a single expression, but that we don't catch such errors.
406 Bexpression*
407 Expression::get_backend(Translate_context* context)
409 // The child may have marked this expression as having an error.
410 if (this->classification_ == EXPRESSION_ERROR)
411 return context->backend()->error_expression();
413 return this->do_get_backend(context);
416 // Return a backend expression for VAL.
417 Bexpression*
418 Expression::backend_numeric_constant_expression(Translate_context* context,
419 Numeric_constant* val)
421 Gogo* gogo = context->gogo();
422 Type* type = val->type();
423 if (type == NULL)
424 return gogo->backend()->error_expression();
426 Btype* btype = type->get_backend(gogo);
427 Bexpression* ret;
428 if (type->integer_type() != NULL)
430 mpz_t ival;
431 if (!val->to_int(&ival))
433 go_assert(saw_errors());
434 return gogo->backend()->error_expression();
436 ret = gogo->backend()->integer_constant_expression(btype, ival);
437 mpz_clear(ival);
439 else if (type->float_type() != NULL)
441 mpfr_t fval;
442 if (!val->to_float(&fval))
444 go_assert(saw_errors());
445 return gogo->backend()->error_expression();
447 ret = gogo->backend()->float_constant_expression(btype, fval);
448 mpfr_clear(fval);
450 else if (type->complex_type() != NULL)
452 mpc_t cval;
453 if (!val->to_complex(&cval))
455 go_assert(saw_errors());
456 return gogo->backend()->error_expression();
458 ret = gogo->backend()->complex_constant_expression(btype, cval);
459 mpc_clear(cval);
461 else
462 go_unreachable();
464 return ret;
467 // Return an expression which evaluates to true if VAL, of arbitrary integer
468 // type, is negative or is more than the maximum value of the Go type "int".
470 Expression*
471 Expression::check_bounds(Expression* val, Location loc)
473 Type* val_type = val->type();
474 Type* bound_type = Type::lookup_integer_type("int");
476 int val_type_size;
477 bool val_is_unsigned = false;
478 if (val_type->integer_type() != NULL)
480 val_type_size = val_type->integer_type()->bits();
481 val_is_unsigned = val_type->integer_type()->is_unsigned();
483 else
485 if (!val_type->is_numeric_type()
486 || !Type::are_convertible(bound_type, val_type, NULL))
488 go_assert(saw_errors());
489 return Expression::make_boolean(true, loc);
492 if (val_type->complex_type() != NULL)
493 val_type_size = val_type->complex_type()->bits();
494 else
495 val_type_size = val_type->float_type()->bits();
498 Expression* negative_index = Expression::make_boolean(false, loc);
499 Expression* index_overflows = Expression::make_boolean(false, loc);
500 if (!val_is_unsigned)
502 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
503 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
506 int bound_type_size = bound_type->integer_type()->bits();
507 if (val_type_size > bound_type_size
508 || (val_type_size == bound_type_size
509 && val_is_unsigned))
511 mpz_t one;
512 mpz_init_set_ui(one, 1UL);
514 // maxval = 2^(bound_type_size - 1) - 1
515 mpz_t maxval;
516 mpz_init(maxval);
517 mpz_mul_2exp(maxval, one, bound_type_size - 1);
518 mpz_sub_ui(maxval, maxval, 1);
519 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
520 mpz_clear(one);
521 mpz_clear(maxval);
523 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
526 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
527 loc);
530 void
531 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
533 this->do_dump_expression(ast_dump_context);
536 // Error expressions. This are used to avoid cascading errors.
538 class Error_expression : public Expression
540 public:
541 Error_expression(Location location)
542 : Expression(EXPRESSION_ERROR, location)
545 protected:
546 bool
547 do_is_constant() const
548 { return true; }
550 bool
551 do_numeric_constant_value(Numeric_constant* nc) const
553 nc->set_unsigned_long(NULL, 0);
554 return true;
557 bool
558 do_discarding_value()
559 { return true; }
561 Type*
562 do_type()
563 { return Type::make_error_type(); }
565 void
566 do_determine_type(const Type_context*)
569 Expression*
570 do_copy()
571 { return this; }
573 bool
574 do_is_addressable() const
575 { return true; }
577 Bexpression*
578 do_get_backend(Translate_context* context)
579 { return context->backend()->error_expression(); }
581 void
582 do_dump_expression(Ast_dump_context*) const;
585 // Dump the ast representation for an error expression to a dump context.
587 void
588 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
590 ast_dump_context->ostream() << "_Error_" ;
593 Expression*
594 Expression::make_error(Location location)
596 return new Error_expression(location);
599 // An expression which is really a type. This is used during parsing.
600 // It is an error if these survive after lowering.
602 class
603 Type_expression : public Expression
605 public:
606 Type_expression(Type* type, Location location)
607 : Expression(EXPRESSION_TYPE, location),
608 type_(type)
611 protected:
613 do_traverse(Traverse* traverse)
614 { return Type::traverse(this->type_, traverse); }
616 Type*
617 do_type()
618 { return this->type_; }
620 void
621 do_determine_type(const Type_context*)
624 void
625 do_check_types(Gogo*)
626 { this->report_error(_("invalid use of type")); }
628 Expression*
629 do_copy()
630 { return this; }
632 Bexpression*
633 do_get_backend(Translate_context*)
634 { go_unreachable(); }
636 void do_dump_expression(Ast_dump_context*) const;
638 private:
639 // The type which we are representing as an expression.
640 Type* type_;
643 void
644 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
646 ast_dump_context->dump_type(this->type_);
649 Expression*
650 Expression::make_type(Type* type, Location location)
652 return new Type_expression(type, location);
655 // Class Parser_expression.
657 Type*
658 Parser_expression::do_type()
660 // We should never really ask for the type of a Parser_expression.
661 // However, it can happen, at least when we have an invalid const
662 // whose initializer refers to the const itself. In that case we
663 // may ask for the type when lowering the const itself.
664 go_assert(saw_errors());
665 return Type::make_error_type();
668 // Class Var_expression.
670 // Lower a variable expression. Here we just make sure that the
671 // initialization expression of the variable has been lowered. This
672 // ensures that we will be able to determine the type of the variable
673 // if necessary.
675 Expression*
676 Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 Statement_inserter* inserter, int)
679 if (this->variable_->is_variable())
681 Variable* var = this->variable_->var_value();
682 // This is either a local variable or a global variable. A
683 // reference to a variable which is local to an enclosing
684 // function will be a reference to a field in a closure.
685 if (var->is_global())
687 function = NULL;
688 inserter = NULL;
690 var->lower_init_expression(gogo, function, inserter);
692 return this;
695 // Return the type of a reference to a variable.
697 Type*
698 Var_expression::do_type()
700 if (this->variable_->is_variable())
701 return this->variable_->var_value()->type();
702 else if (this->variable_->is_result_variable())
703 return this->variable_->result_var_value()->type();
704 else
705 go_unreachable();
708 // Determine the type of a reference to a variable.
710 void
711 Var_expression::do_determine_type(const Type_context*)
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->determine_type();
717 // Something takes the address of this variable. This means that we
718 // may want to move the variable onto the heap.
720 void
721 Var_expression::do_address_taken(bool escapes)
723 if (!escapes)
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_non_escaping_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_non_escaping_address_taken();
729 else
730 go_unreachable();
732 else
734 if (this->variable_->is_variable())
735 this->variable_->var_value()->set_address_taken();
736 else if (this->variable_->is_result_variable())
737 this->variable_->result_var_value()->set_address_taken();
738 else
739 go_unreachable();
742 if (this->variable_->is_variable()
743 && this->variable_->var_value()->is_in_heap())
745 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
746 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
750 // Get the backend representation for a reference to a variable.
752 Bexpression*
753 Var_expression::do_get_backend(Translate_context* context)
755 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
756 context->function());
757 bool is_in_heap;
758 Location loc = this->location();
759 Btype* btype;
760 Gogo* gogo = context->gogo();
761 if (this->variable_->is_variable())
763 is_in_heap = this->variable_->var_value()->is_in_heap();
764 btype = this->variable_->var_value()->type()->get_backend(gogo);
766 else if (this->variable_->is_result_variable())
768 is_in_heap = this->variable_->result_var_value()->is_in_heap();
769 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
771 else
772 go_unreachable();
774 Bexpression* ret =
775 context->backend()->var_expression(bvar, loc);
776 if (is_in_heap)
777 ret = context->backend()->indirect_expression(btype, ret, true, loc);
778 return ret;
781 // Ast dump for variable expression.
783 void
784 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
786 ast_dump_context->ostream() << this->variable_->message_name() ;
789 // Make a reference to a variable in an expression.
791 Expression*
792 Expression::make_var_reference(Named_object* var, Location location)
794 if (var->is_sink())
795 return Expression::make_sink(location);
797 // FIXME: Creating a new object for each reference to a variable is
798 // wasteful.
799 return new Var_expression(var, location);
802 // Class Enclosed_var_expression.
805 Enclosed_var_expression::do_traverse(Traverse*)
807 return TRAVERSE_CONTINUE;
810 // Lower the reference to the enclosed variable.
812 Expression*
813 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
814 Statement_inserter* inserter, int)
816 gogo->lower_expression(function, inserter, &this->reference_);
817 return this;
820 // Flatten the reference to the enclosed variable.
822 Expression*
823 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
824 Statement_inserter* inserter)
826 gogo->flatten_expression(function, inserter, &this->reference_);
827 return this;
830 void
831 Enclosed_var_expression::do_address_taken(bool escapes)
833 if (!escapes)
835 if (this->variable_->is_variable())
836 this->variable_->var_value()->set_non_escaping_address_taken();
837 else if (this->variable_->is_result_variable())
838 this->variable_->result_var_value()->set_non_escaping_address_taken();
839 else
840 go_unreachable();
842 else
844 if (this->variable_->is_variable())
845 this->variable_->var_value()->set_address_taken();
846 else if (this->variable_->is_result_variable())
847 this->variable_->result_var_value()->set_address_taken();
848 else
849 go_unreachable();
852 if (this->variable_->is_variable()
853 && this->variable_->var_value()->is_in_heap())
854 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
857 // Ast dump for enclosed variable expression.
859 void
860 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
862 adc->ostream() << this->variable_->message_name();
865 // Make a reference to a variable within an enclosing function.
867 Expression*
868 Expression::make_enclosing_var_reference(Expression* reference,
869 Named_object* var, Location location)
871 return new Enclosed_var_expression(reference, var, location);
874 // Class Temporary_reference_expression.
876 // The type.
878 Type*
879 Temporary_reference_expression::do_type()
881 return this->statement_->type();
884 // Called if something takes the address of this temporary variable.
885 // We never have to move temporary variables to the heap, but we do
886 // need to know that they must live in the stack rather than in a
887 // register.
889 void
890 Temporary_reference_expression::do_address_taken(bool)
892 this->statement_->set_is_address_taken();
895 // Get a backend expression referring to the variable.
897 Bexpression*
898 Temporary_reference_expression::do_get_backend(Translate_context* context)
900 Gogo* gogo = context->gogo();
901 Bvariable* bvar = this->statement_->get_backend_variable(context);
902 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
904 // The backend can't always represent the same set of recursive types
905 // that the Go frontend can. In some cases this means that a
906 // temporary variable won't have the right backend type. Correct
907 // that here by adding a type cast. We need to use base() to push
908 // the circularity down one level.
909 Type* stype = this->statement_->type();
910 if (!this->is_lvalue_
911 && stype->points_to() != NULL
912 && stype->points_to()->is_void_type())
914 Btype* btype = this->type()->base()->get_backend(gogo);
915 ret = gogo->backend()->convert_expression(btype, ret, this->location());
917 return ret;
920 // Ast dump for temporary reference.
922 void
923 Temporary_reference_expression::do_dump_expression(
924 Ast_dump_context* ast_dump_context) const
926 ast_dump_context->dump_temp_variable_name(this->statement_);
929 // Make a reference to a temporary variable.
931 Temporary_reference_expression*
932 Expression::make_temporary_reference(Temporary_statement* statement,
933 Location location)
935 return new Temporary_reference_expression(statement, location);
938 // Class Set_and_use_temporary_expression.
940 // Return the type.
942 Type*
943 Set_and_use_temporary_expression::do_type()
945 return this->statement_->type();
948 // Determine the type of the expression.
950 void
951 Set_and_use_temporary_expression::do_determine_type(
952 const Type_context* context)
954 this->expr_->determine_type(context);
957 // Take the address.
959 void
960 Set_and_use_temporary_expression::do_address_taken(bool)
962 this->statement_->set_is_address_taken();
965 // Return the backend representation.
967 Bexpression*
968 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
970 Location loc = this->location();
971 Gogo* gogo = context->gogo();
972 Bvariable* bvar = this->statement_->get_backend_variable(context);
973 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
975 Named_object* fn = context->function();
976 go_assert(fn != NULL);
977 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
978 Bexpression* bexpr = this->expr_->get_backend(context);
979 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
980 bexpr, loc);
981 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
982 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
983 return ret;
986 // Dump.
988 void
989 Set_and_use_temporary_expression::do_dump_expression(
990 Ast_dump_context* ast_dump_context) const
992 ast_dump_context->ostream() << '(';
993 ast_dump_context->dump_temp_variable_name(this->statement_);
994 ast_dump_context->ostream() << " = ";
995 this->expr_->dump_expression(ast_dump_context);
996 ast_dump_context->ostream() << ')';
999 // Make a set-and-use temporary.
1001 Set_and_use_temporary_expression*
1002 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1003 Expression* expr, Location location)
1005 return new Set_and_use_temporary_expression(statement, expr, location);
1008 // A sink expression--a use of the blank identifier _.
1010 class Sink_expression : public Expression
1012 public:
1013 Sink_expression(Location location)
1014 : Expression(EXPRESSION_SINK, location),
1015 type_(NULL), bvar_(NULL)
1018 protected:
1019 bool
1020 do_discarding_value()
1021 { return true; }
1023 Type*
1024 do_type();
1026 void
1027 do_determine_type(const Type_context*);
1029 Expression*
1030 do_copy()
1031 { return new Sink_expression(this->location()); }
1033 Bexpression*
1034 do_get_backend(Translate_context*);
1036 void
1037 do_dump_expression(Ast_dump_context*) const;
1039 private:
1040 // The type of this sink variable.
1041 Type* type_;
1042 // The temporary variable we generate.
1043 Bvariable* bvar_;
1046 // Return the type of a sink expression.
1048 Type*
1049 Sink_expression::do_type()
1051 if (this->type_ == NULL)
1052 return Type::make_sink_type();
1053 return this->type_;
1056 // Determine the type of a sink expression.
1058 void
1059 Sink_expression::do_determine_type(const Type_context* context)
1061 if (context->type != NULL)
1062 this->type_ = context->type;
1065 // Return a temporary variable for a sink expression. This will
1066 // presumably be a write-only variable which the middle-end will drop.
1068 Bexpression*
1069 Sink_expression::do_get_backend(Translate_context* context)
1071 Location loc = this->location();
1072 Gogo* gogo = context->gogo();
1073 if (this->bvar_ == NULL)
1075 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1076 Named_object* fn = context->function();
1077 go_assert(fn != NULL);
1078 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1079 Btype* bt = this->type_->get_backend(context->gogo());
1080 Bstatement* decl;
1081 this->bvar_ =
1082 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1083 false, loc, &decl);
1084 Bexpression* var_ref =
1085 gogo->backend()->var_expression(this->bvar_, loc);
1086 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1087 return var_ref;
1089 return gogo->backend()->var_expression(this->bvar_, loc);
1092 // Ast dump for sink expression.
1094 void
1095 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1097 ast_dump_context->ostream() << "_" ;
1100 // Make a sink expression.
1102 Expression*
1103 Expression::make_sink(Location location)
1105 return new Sink_expression(location);
1108 // Class Func_expression.
1110 // FIXME: Can a function expression appear in a constant expression?
1111 // The value is unchanging. Initializing a constant to the address of
1112 // a function seems like it could work, though there might be little
1113 // point to it.
1115 // Traversal.
1118 Func_expression::do_traverse(Traverse* traverse)
1120 return (this->closure_ == NULL
1121 ? TRAVERSE_CONTINUE
1122 : Expression::traverse(&this->closure_, traverse));
1125 // Return the type of a function expression.
1127 Type*
1128 Func_expression::do_type()
1130 if (this->function_->is_function())
1131 return this->function_->func_value()->type();
1132 else if (this->function_->is_function_declaration())
1133 return this->function_->func_declaration_value()->type();
1134 else
1135 go_unreachable();
1138 // Get the backend representation for the code of a function expression.
1140 Bexpression*
1141 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1143 Function_type* fntype;
1144 if (no->is_function())
1145 fntype = no->func_value()->type();
1146 else if (no->is_function_declaration())
1147 fntype = no->func_declaration_value()->type();
1148 else
1149 go_unreachable();
1151 // Builtin functions are handled specially by Call_expression. We
1152 // can't take their address.
1153 if (fntype->is_builtin())
1155 go_error_at(loc,
1156 "invalid use of special builtin function %qs; must be called",
1157 no->message_name().c_str());
1158 return gogo->backend()->error_expression();
1161 Bfunction* fndecl;
1162 if (no->is_function())
1163 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1164 else if (no->is_function_declaration())
1165 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1166 else
1167 go_unreachable();
1169 return gogo->backend()->function_code_expression(fndecl, loc);
1172 // Get the backend representation for a function expression. This is used when
1173 // we take the address of a function rather than simply calling it. A func
1174 // value is represented as a pointer to a block of memory. The first
1175 // word of that memory is a pointer to the function code. The
1176 // remaining parts of that memory are the addresses of variables that
1177 // the function closes over.
1179 Bexpression*
1180 Func_expression::do_get_backend(Translate_context* context)
1182 // If there is no closure, just use the function descriptor.
1183 if (this->closure_ == NULL)
1185 Gogo* gogo = context->gogo();
1186 Named_object* no = this->function_;
1187 Expression* descriptor;
1188 if (no->is_function())
1189 descriptor = no->func_value()->descriptor(gogo, no);
1190 else if (no->is_function_declaration())
1192 if (no->func_declaration_value()->type()->is_builtin())
1194 go_error_at(this->location(),
1195 ("invalid use of special builtin function %qs; "
1196 "must be called"),
1197 no->message_name().c_str());
1198 return gogo->backend()->error_expression();
1200 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1202 else
1203 go_unreachable();
1205 Bexpression* bdesc = descriptor->get_backend(context);
1206 return gogo->backend()->address_expression(bdesc, this->location());
1209 go_assert(this->function_->func_value()->enclosing() != NULL);
1211 // If there is a closure, then the closure is itself the function
1212 // expression. It is a pointer to a struct whose first field points
1213 // to the function code and whose remaining fields are the addresses
1214 // of the closed-over variables.
1215 Bexpression *bexpr = this->closure_->get_backend(context);
1217 // Introduce a backend type conversion, to account for any differences
1218 // between the argument type (function descriptor, struct with a
1219 // single field) and the closure (struct with multiple fields).
1220 Gogo* gogo = context->gogo();
1221 Btype *btype = this->type()->get_backend(gogo);
1222 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1225 // Ast dump for function.
1227 void
1228 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1230 ast_dump_context->ostream() << this->function_->name();
1231 if (this->closure_ != NULL)
1233 ast_dump_context->ostream() << " {closure = ";
1234 this->closure_->dump_expression(ast_dump_context);
1235 ast_dump_context->ostream() << "}";
1239 // Make a reference to a function in an expression.
1241 Expression*
1242 Expression::make_func_reference(Named_object* function, Expression* closure,
1243 Location location)
1245 Func_expression* fe = new Func_expression(function, closure, location);
1247 // Detect references to builtin functions and set the runtime code if
1248 // appropriate.
1249 if (function->is_function_declaration())
1250 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1251 return fe;
1254 // Class Func_descriptor_expression.
1256 // Constructor.
1258 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1259 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1260 fn_(fn), dvar_(NULL)
1262 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1265 // Traversal.
1268 Func_descriptor_expression::do_traverse(Traverse*)
1270 return TRAVERSE_CONTINUE;
1273 // All function descriptors have the same type.
1275 Type* Func_descriptor_expression::descriptor_type;
1277 void
1278 Func_descriptor_expression::make_func_descriptor_type()
1280 if (Func_descriptor_expression::descriptor_type != NULL)
1281 return;
1282 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1283 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1284 Func_descriptor_expression::descriptor_type =
1285 Type::make_builtin_named_type("functionDescriptor", struct_type);
1288 Type*
1289 Func_descriptor_expression::do_type()
1291 Func_descriptor_expression::make_func_descriptor_type();
1292 return Func_descriptor_expression::descriptor_type;
1295 // The backend representation for a function descriptor.
1297 Bexpression*
1298 Func_descriptor_expression::do_get_backend(Translate_context* context)
1300 Named_object* no = this->fn_;
1301 Location loc = no->location();
1302 if (this->dvar_ != NULL)
1303 return context->backend()->var_expression(this->dvar_, loc);
1305 Gogo* gogo = context->gogo();
1306 std::string var_name(gogo->function_descriptor_name(no));
1307 bool is_descriptor = false;
1308 if (no->is_function_declaration()
1309 && !no->func_declaration_value()->asm_name().empty()
1310 && Linemap::is_predeclared_location(no->location()))
1311 is_descriptor = true;
1313 // The runtime package implements some functions defined in the
1314 // syscall package. Let the syscall package define the descriptor
1315 // in this case.
1316 if (gogo->compiling_runtime()
1317 && gogo->package_name() == "runtime"
1318 && no->is_function()
1319 && !no->func_value()->asm_name().empty()
1320 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1321 is_descriptor = true;
1323 Btype* btype = this->type()->get_backend(gogo);
1325 Bvariable* bvar;
1326 std::string asm_name(go_selectively_encode_id(var_name));
1327 if (no->package() != NULL || is_descriptor)
1328 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1329 btype, loc);
1330 else
1332 Location bloc = Linemap::predeclared_location();
1334 // The runtime package has hash/equality functions that are
1335 // referenced by type descriptors outside of the runtime, so the
1336 // function descriptors must be visible even though they are not
1337 // exported.
1338 bool is_exported_runtime = false;
1339 if (gogo->compiling_runtime()
1340 && gogo->package_name() == "runtime"
1341 && (no->name().find("hash") != std::string::npos
1342 || no->name().find("equal") != std::string::npos))
1343 is_exported_runtime = true;
1345 bool is_hidden = ((no->is_function()
1346 && no->func_value()->enclosing() != NULL)
1347 || (Gogo::is_hidden_name(no->name())
1348 && !is_exported_runtime)
1349 || Gogo::is_thunk(no));
1351 bvar = context->backend()->immutable_struct(var_name, asm_name,
1352 is_hidden, false,
1353 btype, bloc);
1354 Expression_list* vals = new Expression_list();
1355 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1356 Expression* init =
1357 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1358 Translate_context bcontext(gogo, NULL, NULL, NULL);
1359 bcontext.set_is_const();
1360 Bexpression* binit = init->get_backend(&bcontext);
1361 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1362 false, btype, bloc, binit);
1365 this->dvar_ = bvar;
1366 return gogo->backend()->var_expression(bvar, loc);
1369 // Print a function descriptor expression.
1371 void
1372 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1374 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1377 // Make a function descriptor expression.
1379 Func_descriptor_expression*
1380 Expression::make_func_descriptor(Named_object* fn)
1382 return new Func_descriptor_expression(fn);
1385 // Make the function descriptor type, so that it can be converted.
1387 void
1388 Expression::make_func_descriptor_type()
1390 Func_descriptor_expression::make_func_descriptor_type();
1393 // A reference to just the code of a function.
1395 class Func_code_reference_expression : public Expression
1397 public:
1398 Func_code_reference_expression(Named_object* function, Location location)
1399 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1400 function_(function)
1403 protected:
1405 do_traverse(Traverse*)
1406 { return TRAVERSE_CONTINUE; }
1408 bool
1409 do_is_static_initializer() const
1410 { return true; }
1412 Type*
1413 do_type()
1414 { return Type::make_pointer_type(Type::make_void_type()); }
1416 void
1417 do_determine_type(const Type_context*)
1420 Expression*
1421 do_copy()
1423 return Expression::make_func_code_reference(this->function_,
1424 this->location());
1427 Bexpression*
1428 do_get_backend(Translate_context*);
1430 void
1431 do_dump_expression(Ast_dump_context* context) const
1432 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1434 private:
1435 // The function.
1436 Named_object* function_;
1439 // Get the backend representation for a reference to function code.
1441 Bexpression*
1442 Func_code_reference_expression::do_get_backend(Translate_context* context)
1444 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1445 this->location());
1448 // Make a reference to the code of a function.
1450 Expression*
1451 Expression::make_func_code_reference(Named_object* function, Location location)
1453 return new Func_code_reference_expression(function, location);
1456 // Class Unknown_expression.
1458 // Return the name of an unknown expression.
1460 const std::string&
1461 Unknown_expression::name() const
1463 return this->named_object_->name();
1466 // Lower a reference to an unknown name.
1468 Expression*
1469 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1471 Location location = this->location();
1472 Named_object* no = this->named_object_;
1473 Named_object* real;
1474 if (!no->is_unknown())
1475 real = no;
1476 else
1478 real = no->unknown_value()->real_named_object();
1479 if (real == NULL)
1481 if (this->is_composite_literal_key_)
1482 return this;
1483 if (!this->no_error_message_)
1484 go_error_at(location, "reference to undefined name %qs",
1485 this->named_object_->message_name().c_str());
1486 return Expression::make_error(location);
1489 switch (real->classification())
1491 case Named_object::NAMED_OBJECT_CONST:
1492 return Expression::make_const_reference(real, location);
1493 case Named_object::NAMED_OBJECT_TYPE:
1494 return Expression::make_type(real->type_value(), location);
1495 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1496 if (this->is_composite_literal_key_)
1497 return this;
1498 if (!this->no_error_message_)
1499 go_error_at(location, "reference to undefined type %qs",
1500 real->message_name().c_str());
1501 return Expression::make_error(location);
1502 case Named_object::NAMED_OBJECT_VAR:
1503 real->var_value()->set_is_used();
1504 return Expression::make_var_reference(real, location);
1505 case Named_object::NAMED_OBJECT_FUNC:
1506 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1507 return Expression::make_func_reference(real, NULL, location);
1508 case Named_object::NAMED_OBJECT_PACKAGE:
1509 if (this->is_composite_literal_key_)
1510 return this;
1511 if (!this->no_error_message_)
1512 go_error_at(location, "unexpected reference to package");
1513 return Expression::make_error(location);
1514 default:
1515 go_unreachable();
1519 // Dump the ast representation for an unknown expression to a dump context.
1521 void
1522 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1524 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1525 << ")";
1528 // Make a reference to an unknown name.
1530 Unknown_expression*
1531 Expression::make_unknown_reference(Named_object* no, Location location)
1533 return new Unknown_expression(no, location);
1536 // A boolean expression.
1538 class Boolean_expression : public Expression
1540 public:
1541 Boolean_expression(bool val, Location location)
1542 : Expression(EXPRESSION_BOOLEAN, location),
1543 val_(val), type_(NULL)
1546 static Expression*
1547 do_import(Import*);
1549 protected:
1550 bool
1551 do_is_constant() const
1552 { return true; }
1554 bool
1555 do_is_static_initializer() const
1556 { return true; }
1558 Type*
1559 do_type();
1561 void
1562 do_determine_type(const Type_context*);
1564 Expression*
1565 do_copy()
1566 { return this; }
1568 Bexpression*
1569 do_get_backend(Translate_context* context)
1570 { return context->backend()->boolean_constant_expression(this->val_); }
1572 void
1573 do_export(Export* exp) const
1574 { exp->write_c_string(this->val_ ? "true" : "false"); }
1576 void
1577 do_dump_expression(Ast_dump_context* ast_dump_context) const
1578 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1580 private:
1581 // The constant.
1582 bool val_;
1583 // The type as determined by context.
1584 Type* type_;
1587 // Get the type.
1589 Type*
1590 Boolean_expression::do_type()
1592 if (this->type_ == NULL)
1593 this->type_ = Type::make_boolean_type();
1594 return this->type_;
1597 // Set the type from the context.
1599 void
1600 Boolean_expression::do_determine_type(const Type_context* context)
1602 if (this->type_ != NULL && !this->type_->is_abstract())
1604 else if (context->type != NULL && context->type->is_boolean_type())
1605 this->type_ = context->type;
1606 else if (!context->may_be_abstract)
1607 this->type_ = Type::lookup_bool_type();
1610 // Import a boolean constant.
1612 Expression*
1613 Boolean_expression::do_import(Import* imp)
1615 if (imp->peek_char() == 't')
1617 imp->require_c_string("true");
1618 return Expression::make_boolean(true, imp->location());
1620 else
1622 imp->require_c_string("false");
1623 return Expression::make_boolean(false, imp->location());
1627 // Make a boolean expression.
1629 Expression*
1630 Expression::make_boolean(bool val, Location location)
1632 return new Boolean_expression(val, location);
1635 // Class String_expression.
1637 // Get the type.
1639 Type*
1640 String_expression::do_type()
1642 if (this->type_ == NULL)
1643 this->type_ = Type::make_string_type();
1644 return this->type_;
1647 // Set the type from the context.
1649 void
1650 String_expression::do_determine_type(const Type_context* context)
1652 if (this->type_ != NULL && !this->type_->is_abstract())
1654 else if (context->type != NULL && context->type->is_string_type())
1655 this->type_ = context->type;
1656 else if (!context->may_be_abstract)
1657 this->type_ = Type::lookup_string_type();
1660 // Build a string constant.
1662 Bexpression*
1663 String_expression::do_get_backend(Translate_context* context)
1665 Gogo* gogo = context->gogo();
1666 Btype* btype = Type::make_string_type()->get_backend(gogo);
1668 Location loc = this->location();
1669 std::vector<Bexpression*> init(2);
1670 Bexpression* str_cst =
1671 gogo->backend()->string_constant_expression(this->val_);
1672 init[0] = gogo->backend()->address_expression(str_cst, loc);
1674 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1675 mpz_t lenval;
1676 mpz_init_set_ui(lenval, this->val_.length());
1677 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1678 mpz_clear(lenval);
1680 return gogo->backend()->constructor_expression(btype, init, loc);
1683 // Write string literal to string dump.
1685 void
1686 String_expression::export_string(String_dump* exp,
1687 const String_expression* str)
1689 std::string s;
1690 s.reserve(str->val_.length() * 4 + 2);
1691 s += '"';
1692 for (std::string::const_iterator p = str->val_.begin();
1693 p != str->val_.end();
1694 ++p)
1696 if (*p == '\\' || *p == '"')
1698 s += '\\';
1699 s += *p;
1701 else if (*p >= 0x20 && *p < 0x7f)
1702 s += *p;
1703 else if (*p == '\n')
1704 s += "\\n";
1705 else if (*p == '\t')
1706 s += "\\t";
1707 else
1709 s += "\\x";
1710 unsigned char c = *p;
1711 unsigned int dig = c >> 4;
1712 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1713 dig = c & 0xf;
1714 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1717 s += '"';
1718 exp->write_string(s);
1721 // Export a string expression.
1723 void
1724 String_expression::do_export(Export* exp) const
1726 String_expression::export_string(exp, this);
1729 // Import a string expression.
1731 Expression*
1732 String_expression::do_import(Import* imp)
1734 imp->require_c_string("\"");
1735 std::string val;
1736 while (true)
1738 int c = imp->get_char();
1739 if (c == '"' || c == -1)
1740 break;
1741 if (c != '\\')
1742 val += static_cast<char>(c);
1743 else
1745 c = imp->get_char();
1746 if (c == '\\' || c == '"')
1747 val += static_cast<char>(c);
1748 else if (c == 'n')
1749 val += '\n';
1750 else if (c == 't')
1751 val += '\t';
1752 else if (c == 'x')
1754 c = imp->get_char();
1755 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1756 c = imp->get_char();
1757 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1758 char v = (vh << 4) | vl;
1759 val += v;
1761 else
1763 go_error_at(imp->location(), "bad string constant");
1764 return Expression::make_error(imp->location());
1768 return Expression::make_string(val, imp->location());
1771 // Ast dump for string expression.
1773 void
1774 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1776 String_expression::export_string(ast_dump_context, this);
1779 // Make a string expression.
1781 Expression*
1782 Expression::make_string(const std::string& val, Location location)
1784 return new String_expression(val, location);
1787 // An expression that evaluates to some characteristic of a string.
1788 // This is used when indexing, bound-checking, or nil checking a string.
1790 class String_info_expression : public Expression
1792 public:
1793 String_info_expression(Expression* string, String_info string_info,
1794 Location location)
1795 : Expression(EXPRESSION_STRING_INFO, location),
1796 string_(string), string_info_(string_info)
1799 protected:
1800 Type*
1801 do_type();
1803 void
1804 do_determine_type(const Type_context*)
1805 { go_unreachable(); }
1807 Expression*
1808 do_copy()
1810 return new String_info_expression(this->string_->copy(), this->string_info_,
1811 this->location());
1814 Bexpression*
1815 do_get_backend(Translate_context* context);
1817 void
1818 do_dump_expression(Ast_dump_context*) const;
1820 void
1821 do_issue_nil_check()
1822 { this->string_->issue_nil_check(); }
1824 private:
1825 // The string for which we are getting information.
1826 Expression* string_;
1827 // What information we want.
1828 String_info string_info_;
1831 // Return the type of the string info.
1833 Type*
1834 String_info_expression::do_type()
1836 switch (this->string_info_)
1838 case STRING_INFO_DATA:
1840 Type* byte_type = Type::lookup_integer_type("uint8");
1841 return Type::make_pointer_type(byte_type);
1843 case STRING_INFO_LENGTH:
1844 return Type::lookup_integer_type("int");
1845 default:
1846 go_unreachable();
1850 // Return string information in GENERIC.
1852 Bexpression*
1853 String_info_expression::do_get_backend(Translate_context* context)
1855 Gogo* gogo = context->gogo();
1857 Bexpression* bstring = this->string_->get_backend(context);
1858 switch (this->string_info_)
1860 case STRING_INFO_DATA:
1861 case STRING_INFO_LENGTH:
1862 return gogo->backend()->struct_field_expression(bstring,
1863 this->string_info_,
1864 this->location());
1865 break;
1866 default:
1867 go_unreachable();
1871 // Dump ast representation for a type info expression.
1873 void
1874 String_info_expression::do_dump_expression(
1875 Ast_dump_context* ast_dump_context) const
1877 ast_dump_context->ostream() << "stringinfo(";
1878 this->string_->dump_expression(ast_dump_context);
1879 ast_dump_context->ostream() << ",";
1880 ast_dump_context->ostream() <<
1881 (this->string_info_ == STRING_INFO_DATA ? "data"
1882 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1883 : "unknown");
1884 ast_dump_context->ostream() << ")";
1887 // Make a string info expression.
1889 Expression*
1890 Expression::make_string_info(Expression* string, String_info string_info,
1891 Location location)
1893 return new String_info_expression(string, string_info, location);
1896 // Make an integer expression.
1898 class Integer_expression : public Expression
1900 public:
1901 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1902 Location location)
1903 : Expression(EXPRESSION_INTEGER, location),
1904 type_(type), is_character_constant_(is_character_constant)
1905 { mpz_init_set(this->val_, *val); }
1907 static Expression*
1908 do_import(Import*);
1910 // Write VAL to string dump.
1911 static void
1912 export_integer(String_dump* exp, const mpz_t val);
1914 // Write VAL to dump context.
1915 static void
1916 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1918 protected:
1919 bool
1920 do_is_constant() const
1921 { return true; }
1923 bool
1924 do_is_static_initializer() const
1925 { return true; }
1927 bool
1928 do_numeric_constant_value(Numeric_constant* nc) const;
1930 Type*
1931 do_type();
1933 void
1934 do_determine_type(const Type_context* context);
1936 void
1937 do_check_types(Gogo*);
1939 Bexpression*
1940 do_get_backend(Translate_context*);
1942 Expression*
1943 do_copy()
1945 if (this->is_character_constant_)
1946 return Expression::make_character(&this->val_,
1947 (this->type_ == NULL
1948 ? NULL
1949 : this->type_->copy_expressions()),
1950 this->location());
1951 else
1952 return Expression::make_integer_z(&this->val_,
1953 (this->type_ == NULL
1954 ? NULL
1955 : this->type_->copy_expressions()),
1956 this->location());
1959 void
1960 do_export(Export*) const;
1962 void
1963 do_dump_expression(Ast_dump_context*) const;
1965 private:
1966 // The integer value.
1967 mpz_t val_;
1968 // The type so far.
1969 Type* type_;
1970 // Whether this is a character constant.
1971 bool is_character_constant_;
1974 // Return a numeric constant for this expression. We have to mark
1975 // this as a character when appropriate.
1977 bool
1978 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1980 if (this->is_character_constant_)
1981 nc->set_rune(this->type_, this->val_);
1982 else
1983 nc->set_int(this->type_, this->val_);
1984 return true;
1987 // Return the current type. If we haven't set the type yet, we return
1988 // an abstract integer type.
1990 Type*
1991 Integer_expression::do_type()
1993 if (this->type_ == NULL)
1995 if (this->is_character_constant_)
1996 this->type_ = Type::make_abstract_character_type();
1997 else
1998 this->type_ = Type::make_abstract_integer_type();
2000 return this->type_;
2003 // Set the type of the integer value. Here we may switch from an
2004 // abstract type to a real type.
2006 void
2007 Integer_expression::do_determine_type(const Type_context* context)
2009 if (this->type_ != NULL && !this->type_->is_abstract())
2011 else if (context->type != NULL && context->type->is_numeric_type())
2012 this->type_ = context->type;
2013 else if (!context->may_be_abstract)
2015 if (this->is_character_constant_)
2016 this->type_ = Type::lookup_integer_type("int32");
2017 else
2018 this->type_ = Type::lookup_integer_type("int");
2022 // Check the type of an integer constant.
2024 void
2025 Integer_expression::do_check_types(Gogo*)
2027 Type* type = this->type_;
2028 if (type == NULL)
2029 return;
2030 Numeric_constant nc;
2031 if (this->is_character_constant_)
2032 nc.set_rune(NULL, this->val_);
2033 else
2034 nc.set_int(NULL, this->val_);
2035 if (!nc.set_type(type, true, this->location()))
2036 this->set_is_error();
2039 // Get the backend representation for an integer constant.
2041 Bexpression*
2042 Integer_expression::do_get_backend(Translate_context* context)
2044 if (this->is_error_expression()
2045 || (this->type_ != NULL && this->type_->is_error_type()))
2047 go_assert(saw_errors());
2048 return context->gogo()->backend()->error_expression();
2051 Type* resolved_type = NULL;
2052 if (this->type_ != NULL && !this->type_->is_abstract())
2053 resolved_type = this->type_;
2054 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2056 // We are converting to an abstract floating point type.
2057 resolved_type = Type::lookup_float_type("float64");
2059 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2061 // We are converting to an abstract complex type.
2062 resolved_type = Type::lookup_complex_type("complex128");
2064 else
2066 // If we still have an abstract type here, then this is being
2067 // used in a constant expression which didn't get reduced for
2068 // some reason. Use a type which will fit the value. We use <,
2069 // not <=, because we need an extra bit for the sign bit.
2070 int bits = mpz_sizeinbase(this->val_, 2);
2071 Type* int_type = Type::lookup_integer_type("int");
2072 if (bits < int_type->integer_type()->bits())
2073 resolved_type = int_type;
2074 else if (bits < 64)
2075 resolved_type = Type::lookup_integer_type("int64");
2076 else
2078 if (!saw_errors())
2079 go_error_at(this->location(),
2080 "unknown type for large integer constant");
2081 return context->gogo()->backend()->error_expression();
2084 Numeric_constant nc;
2085 nc.set_int(resolved_type, this->val_);
2086 return Expression::backend_numeric_constant_expression(context, &nc);
2089 // Write VAL to export data.
2091 void
2092 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2094 char* s = mpz_get_str(NULL, 10, val);
2095 exp->write_c_string(s);
2096 free(s);
2099 // Export an integer in a constant expression.
2101 void
2102 Integer_expression::do_export(Export* exp) const
2104 Integer_expression::export_integer(exp, this->val_);
2105 if (this->is_character_constant_)
2106 exp->write_c_string("'");
2107 // A trailing space lets us reliably identify the end of the number.
2108 exp->write_c_string(" ");
2111 // Import an integer, floating point, or complex value. This handles
2112 // all these types because they all start with digits.
2114 Expression*
2115 Integer_expression::do_import(Import* imp)
2117 std::string num = imp->read_identifier();
2118 imp->require_c_string(" ");
2119 if (!num.empty() && num[num.length() - 1] == 'i')
2121 mpfr_t real;
2122 size_t plus_pos = num.find('+', 1);
2123 size_t minus_pos = num.find('-', 1);
2124 size_t pos;
2125 if (plus_pos == std::string::npos)
2126 pos = minus_pos;
2127 else if (minus_pos == std::string::npos)
2128 pos = plus_pos;
2129 else
2131 go_error_at(imp->location(), "bad number in import data: %qs",
2132 num.c_str());
2133 return Expression::make_error(imp->location());
2135 if (pos == std::string::npos)
2136 mpfr_set_ui(real, 0, GMP_RNDN);
2137 else
2139 std::string real_str = num.substr(0, pos);
2140 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2142 go_error_at(imp->location(), "bad number in import data: %qs",
2143 real_str.c_str());
2144 return Expression::make_error(imp->location());
2148 std::string imag_str;
2149 if (pos == std::string::npos)
2150 imag_str = num;
2151 else
2152 imag_str = num.substr(pos);
2153 imag_str = imag_str.substr(0, imag_str.size() - 1);
2154 mpfr_t imag;
2155 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2157 go_error_at(imp->location(), "bad number in import data: %qs",
2158 imag_str.c_str());
2159 return Expression::make_error(imp->location());
2161 mpc_t cval;
2162 mpc_init2(cval, mpc_precision);
2163 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2164 mpfr_clear(real);
2165 mpfr_clear(imag);
2166 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2167 mpc_clear(cval);
2168 return ret;
2170 else if (num.find('.') == std::string::npos
2171 && num.find('E') == std::string::npos)
2173 bool is_character_constant = (!num.empty()
2174 && num[num.length() - 1] == '\'');
2175 if (is_character_constant)
2176 num = num.substr(0, num.length() - 1);
2177 mpz_t val;
2178 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2180 go_error_at(imp->location(), "bad number in import data: %qs",
2181 num.c_str());
2182 return Expression::make_error(imp->location());
2184 Expression* ret;
2185 if (is_character_constant)
2186 ret = Expression::make_character(&val, NULL, imp->location());
2187 else
2188 ret = Expression::make_integer_z(&val, NULL, imp->location());
2189 mpz_clear(val);
2190 return ret;
2192 else
2194 mpfr_t val;
2195 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2197 go_error_at(imp->location(), "bad number in import data: %qs",
2198 num.c_str());
2199 return Expression::make_error(imp->location());
2201 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2202 mpfr_clear(val);
2203 return ret;
2206 // Ast dump for integer expression.
2208 void
2209 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2211 if (this->is_character_constant_)
2212 ast_dump_context->ostream() << '\'';
2213 Integer_expression::export_integer(ast_dump_context, this->val_);
2214 if (this->is_character_constant_)
2215 ast_dump_context->ostream() << '\'';
2218 // Build a new integer value from a multi-precision integer.
2220 Expression*
2221 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2223 return new Integer_expression(val, type, false, location);
2226 // Build a new integer value from an unsigned long.
2228 Expression*
2229 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2231 mpz_t zval;
2232 mpz_init_set_ui(zval, val);
2233 Expression* ret = Expression::make_integer_z(&zval, type, location);
2234 mpz_clear(zval);
2235 return ret;
2238 // Build a new integer value from a signed long.
2240 Expression*
2241 Expression::make_integer_sl(long val, Type *type, Location location)
2243 mpz_t zval;
2244 mpz_init_set_si(zval, val);
2245 Expression* ret = Expression::make_integer_z(&zval, type, location);
2246 mpz_clear(zval);
2247 return ret;
2250 // Store an int64_t in an uninitialized mpz_t.
2252 static void
2253 set_mpz_from_int64(mpz_t* zval, int64_t val)
2255 if (val >= 0)
2257 unsigned long ul = static_cast<unsigned long>(val);
2258 if (static_cast<int64_t>(ul) == val)
2260 mpz_init_set_ui(*zval, ul);
2261 return;
2264 uint64_t uv;
2265 if (val >= 0)
2266 uv = static_cast<uint64_t>(val);
2267 else
2268 uv = static_cast<uint64_t>(- val);
2269 unsigned long ul = uv & 0xffffffffUL;
2270 mpz_init_set_ui(*zval, ul);
2271 mpz_t hval;
2272 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2273 mpz_mul_2exp(hval, hval, 32);
2274 mpz_add(*zval, *zval, hval);
2275 mpz_clear(hval);
2276 if (val < 0)
2277 mpz_neg(*zval, *zval);
2280 // Build a new integer value from an int64_t.
2282 Expression*
2283 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2285 mpz_t zval;
2286 set_mpz_from_int64(&zval, val);
2287 Expression* ret = Expression::make_integer_z(&zval, type, location);
2288 mpz_clear(zval);
2289 return ret;
2292 // Build a new character constant value.
2294 Expression*
2295 Expression::make_character(const mpz_t* val, Type* type, Location location)
2297 return new Integer_expression(val, type, true, location);
2300 // Floats.
2302 class Float_expression : public Expression
2304 public:
2305 Float_expression(const mpfr_t* val, Type* type, Location location)
2306 : Expression(EXPRESSION_FLOAT, location),
2307 type_(type)
2309 mpfr_init_set(this->val_, *val, GMP_RNDN);
2312 // Write VAL to export data.
2313 static void
2314 export_float(String_dump* exp, const mpfr_t val);
2316 // Write VAL to dump file.
2317 static void
2318 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2320 protected:
2321 bool
2322 do_is_constant() const
2323 { return true; }
2325 bool
2326 do_is_static_initializer() const
2327 { return true; }
2329 bool
2330 do_numeric_constant_value(Numeric_constant* nc) const
2332 nc->set_float(this->type_, this->val_);
2333 return true;
2336 Type*
2337 do_type();
2339 void
2340 do_determine_type(const Type_context*);
2342 void
2343 do_check_types(Gogo*);
2345 Expression*
2346 do_copy()
2347 { return Expression::make_float(&this->val_,
2348 (this->type_ == NULL
2349 ? NULL
2350 : this->type_->copy_expressions()),
2351 this->location()); }
2353 Bexpression*
2354 do_get_backend(Translate_context*);
2356 void
2357 do_export(Export*) const;
2359 void
2360 do_dump_expression(Ast_dump_context*) const;
2362 private:
2363 // The floating point value.
2364 mpfr_t val_;
2365 // The type so far.
2366 Type* type_;
2369 // Return the current type. If we haven't set the type yet, we return
2370 // an abstract float type.
2372 Type*
2373 Float_expression::do_type()
2375 if (this->type_ == NULL)
2376 this->type_ = Type::make_abstract_float_type();
2377 return this->type_;
2380 // Set the type of the float value. Here we may switch from an
2381 // abstract type to a real type.
2383 void
2384 Float_expression::do_determine_type(const Type_context* context)
2386 if (this->type_ != NULL && !this->type_->is_abstract())
2388 else if (context->type != NULL
2389 && (context->type->integer_type() != NULL
2390 || context->type->float_type() != NULL
2391 || context->type->complex_type() != NULL))
2392 this->type_ = context->type;
2393 else if (!context->may_be_abstract)
2394 this->type_ = Type::lookup_float_type("float64");
2397 // Check the type of a float value.
2399 void
2400 Float_expression::do_check_types(Gogo*)
2402 Type* type = this->type_;
2403 if (type == NULL)
2404 return;
2405 Numeric_constant nc;
2406 nc.set_float(NULL, this->val_);
2407 if (!nc.set_type(this->type_, true, this->location()))
2408 this->set_is_error();
2411 // Get the backend representation for a float constant.
2413 Bexpression*
2414 Float_expression::do_get_backend(Translate_context* context)
2416 if (this->is_error_expression()
2417 || (this->type_ != NULL && this->type_->is_error_type()))
2419 go_assert(saw_errors());
2420 return context->gogo()->backend()->error_expression();
2423 Type* resolved_type;
2424 if (this->type_ != NULL && !this->type_->is_abstract())
2425 resolved_type = this->type_;
2426 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2428 // We have an abstract integer type. We just hope for the best.
2429 resolved_type = Type::lookup_integer_type("int");
2431 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2433 // We are converting to an abstract complex type.
2434 resolved_type = Type::lookup_complex_type("complex128");
2436 else
2438 // If we still have an abstract type here, then this is being
2439 // used in a constant expression which didn't get reduced. We
2440 // just use float64 and hope for the best.
2441 resolved_type = Type::lookup_float_type("float64");
2444 Numeric_constant nc;
2445 nc.set_float(resolved_type, this->val_);
2446 return Expression::backend_numeric_constant_expression(context, &nc);
2449 // Write a floating point number to a string dump.
2451 void
2452 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2454 mp_exp_t exponent;
2455 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2456 if (*s == '-')
2457 exp->write_c_string("-");
2458 exp->write_c_string("0.");
2459 exp->write_c_string(*s == '-' ? s + 1 : s);
2460 mpfr_free_str(s);
2461 char buf[30];
2462 snprintf(buf, sizeof buf, "E%ld", exponent);
2463 exp->write_c_string(buf);
2466 // Export a floating point number in a constant expression.
2468 void
2469 Float_expression::do_export(Export* exp) const
2471 Float_expression::export_float(exp, this->val_);
2472 // A trailing space lets us reliably identify the end of the number.
2473 exp->write_c_string(" ");
2476 // Dump a floating point number to the dump file.
2478 void
2479 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2481 Float_expression::export_float(ast_dump_context, this->val_);
2484 // Make a float expression.
2486 Expression*
2487 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2489 return new Float_expression(val, type, location);
2492 // Complex numbers.
2494 class Complex_expression : public Expression
2496 public:
2497 Complex_expression(const mpc_t* val, Type* type, Location location)
2498 : Expression(EXPRESSION_COMPLEX, location),
2499 type_(type)
2501 mpc_init2(this->val_, mpc_precision);
2502 mpc_set(this->val_, *val, MPC_RNDNN);
2505 // Write VAL to string dump.
2506 static void
2507 export_complex(String_dump* exp, const mpc_t val);
2509 // Write REAL/IMAG to dump context.
2510 static void
2511 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2513 protected:
2514 bool
2515 do_is_constant() const
2516 { return true; }
2518 bool
2519 do_is_static_initializer() const
2520 { return true; }
2522 bool
2523 do_numeric_constant_value(Numeric_constant* nc) const
2525 nc->set_complex(this->type_, this->val_);
2526 return true;
2529 Type*
2530 do_type();
2532 void
2533 do_determine_type(const Type_context*);
2535 void
2536 do_check_types(Gogo*);
2538 Expression*
2539 do_copy()
2541 return Expression::make_complex(&this->val_,
2542 (this->type_ == NULL
2543 ? NULL
2544 : this->type_->copy_expressions()),
2545 this->location());
2548 Bexpression*
2549 do_get_backend(Translate_context*);
2551 void
2552 do_export(Export*) const;
2554 void
2555 do_dump_expression(Ast_dump_context*) const;
2557 private:
2558 // The complex value.
2559 mpc_t val_;
2560 // The type if known.
2561 Type* type_;
2564 // Return the current type. If we haven't set the type yet, we return
2565 // an abstract complex type.
2567 Type*
2568 Complex_expression::do_type()
2570 if (this->type_ == NULL)
2571 this->type_ = Type::make_abstract_complex_type();
2572 return this->type_;
2575 // Set the type of the complex value. Here we may switch from an
2576 // abstract type to a real type.
2578 void
2579 Complex_expression::do_determine_type(const Type_context* context)
2581 if (this->type_ != NULL && !this->type_->is_abstract())
2583 else if (context->type != NULL && context->type->is_numeric_type())
2584 this->type_ = context->type;
2585 else if (!context->may_be_abstract)
2586 this->type_ = Type::lookup_complex_type("complex128");
2589 // Check the type of a complex value.
2591 void
2592 Complex_expression::do_check_types(Gogo*)
2594 Type* type = this->type_;
2595 if (type == NULL)
2596 return;
2597 Numeric_constant nc;
2598 nc.set_complex(NULL, this->val_);
2599 if (!nc.set_type(this->type_, true, this->location()))
2600 this->set_is_error();
2603 // Get the backend representation for a complex constant.
2605 Bexpression*
2606 Complex_expression::do_get_backend(Translate_context* context)
2608 if (this->is_error_expression()
2609 || (this->type_ != NULL && this->type_->is_error_type()))
2611 go_assert(saw_errors());
2612 return context->gogo()->backend()->error_expression();
2615 Type* resolved_type;
2616 if (this->type_ != NULL && !this->type_->is_abstract())
2617 resolved_type = this->type_;
2618 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2620 // We are converting to an abstract integer type.
2621 resolved_type = Type::lookup_integer_type("int");
2623 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2625 // We are converting to an abstract float type.
2626 resolved_type = Type::lookup_float_type("float64");
2628 else
2630 // If we still have an abstract type here, this is being
2631 // used in a constant expression which didn't get reduced. We
2632 // just use complex128 and hope for the best.
2633 resolved_type = Type::lookup_complex_type("complex128");
2636 Numeric_constant nc;
2637 nc.set_complex(resolved_type, this->val_);
2638 return Expression::backend_numeric_constant_expression(context, &nc);
2641 // Write REAL/IMAG to export data.
2643 void
2644 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2646 if (!mpfr_zero_p(mpc_realref(val)))
2648 Float_expression::export_float(exp, mpc_realref(val));
2649 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2650 exp->write_c_string("+");
2652 Float_expression::export_float(exp, mpc_imagref(val));
2653 exp->write_c_string("i");
2656 // Export a complex number in a constant expression.
2658 void
2659 Complex_expression::do_export(Export* exp) const
2661 Complex_expression::export_complex(exp, this->val_);
2662 // A trailing space lets us reliably identify the end of the number.
2663 exp->write_c_string(" ");
2666 // Dump a complex expression to the dump file.
2668 void
2669 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2671 Complex_expression::export_complex(ast_dump_context, this->val_);
2674 // Make a complex expression.
2676 Expression*
2677 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2679 return new Complex_expression(val, type, location);
2682 // Find a named object in an expression.
2684 class Find_named_object : public Traverse
2686 public:
2687 Find_named_object(Named_object* no)
2688 : Traverse(traverse_expressions),
2689 no_(no), found_(false)
2692 // Whether we found the object.
2693 bool
2694 found() const
2695 { return this->found_; }
2697 protected:
2699 expression(Expression**);
2701 private:
2702 // The object we are looking for.
2703 Named_object* no_;
2704 // Whether we found it.
2705 bool found_;
2708 // A reference to a const in an expression.
2710 class Const_expression : public Expression
2712 public:
2713 Const_expression(Named_object* constant, Location location)
2714 : Expression(EXPRESSION_CONST_REFERENCE, location),
2715 constant_(constant), type_(NULL), seen_(false)
2718 Named_object*
2719 named_object()
2720 { return this->constant_; }
2722 // Check that the initializer does not refer to the constant itself.
2723 void
2724 check_for_init_loop();
2726 protected:
2728 do_traverse(Traverse*);
2730 Expression*
2731 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2733 bool
2734 do_is_constant() const
2735 { return true; }
2737 bool
2738 do_is_static_initializer() const
2739 { return true; }
2741 bool
2742 do_numeric_constant_value(Numeric_constant* nc) const;
2744 bool
2745 do_string_constant_value(std::string* val) const;
2747 Type*
2748 do_type();
2750 // The type of a const is set by the declaration, not the use.
2751 void
2752 do_determine_type(const Type_context*);
2754 void
2755 do_check_types(Gogo*);
2757 Expression*
2758 do_copy()
2759 { return this; }
2761 Bexpression*
2762 do_get_backend(Translate_context* context);
2764 // When exporting a reference to a const as part of a const
2765 // expression, we export the value. We ignore the fact that it has
2766 // a name.
2767 void
2768 do_export(Export* exp) const
2769 { this->constant_->const_value()->expr()->export_expression(exp); }
2771 void
2772 do_dump_expression(Ast_dump_context*) const;
2774 private:
2775 // The constant.
2776 Named_object* constant_;
2777 // The type of this reference. This is used if the constant has an
2778 // abstract type.
2779 Type* type_;
2780 // Used to prevent infinite recursion when a constant incorrectly
2781 // refers to itself.
2782 mutable bool seen_;
2785 // Traversal.
2788 Const_expression::do_traverse(Traverse* traverse)
2790 if (this->type_ != NULL)
2791 return Type::traverse(this->type_, traverse);
2792 return TRAVERSE_CONTINUE;
2795 // Lower a constant expression. This is where we convert the
2796 // predeclared constant iota into an integer value.
2798 Expression*
2799 Const_expression::do_lower(Gogo* gogo, Named_object*,
2800 Statement_inserter*, int iota_value)
2802 if (this->constant_->const_value()->expr()->classification()
2803 == EXPRESSION_IOTA)
2805 if (iota_value == -1)
2807 go_error_at(this->location(),
2808 "iota is only defined in const declarations");
2809 iota_value = 0;
2811 return Expression::make_integer_ul(iota_value, NULL, this->location());
2814 // Make sure that the constant itself has been lowered.
2815 gogo->lower_constant(this->constant_);
2817 return this;
2820 // Return a numeric constant value.
2822 bool
2823 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2825 if (this->seen_)
2826 return false;
2828 Expression* e = this->constant_->const_value()->expr();
2830 this->seen_ = true;
2832 bool r = e->numeric_constant_value(nc);
2834 this->seen_ = false;
2836 Type* ctype;
2837 if (this->type_ != NULL)
2838 ctype = this->type_;
2839 else
2840 ctype = this->constant_->const_value()->type();
2841 if (r && ctype != NULL)
2843 if (!nc->set_type(ctype, false, this->location()))
2844 return false;
2847 return r;
2850 bool
2851 Const_expression::do_string_constant_value(std::string* val) const
2853 if (this->seen_)
2854 return false;
2856 Expression* e = this->constant_->const_value()->expr();
2858 this->seen_ = true;
2859 bool ok = e->string_constant_value(val);
2860 this->seen_ = false;
2862 return ok;
2865 // Return the type of the const reference.
2867 Type*
2868 Const_expression::do_type()
2870 if (this->type_ != NULL)
2871 return this->type_;
2873 Named_constant* nc = this->constant_->const_value();
2875 if (this->seen_ || nc->lowering())
2877 if (nc->type() == NULL || !nc->type()->is_error_type())
2879 Location loc = this->location();
2880 if (!this->seen_)
2881 loc = nc->location();
2882 go_error_at(loc, "constant refers to itself");
2884 this->set_is_error();
2885 this->type_ = Type::make_error_type();
2886 nc->set_type(this->type_);
2887 return this->type_;
2890 this->seen_ = true;
2892 Type* ret = nc->type();
2894 if (ret != NULL)
2896 this->seen_ = false;
2897 return ret;
2900 // During parsing, a named constant may have a NULL type, but we
2901 // must not return a NULL type here.
2902 ret = nc->expr()->type();
2904 this->seen_ = false;
2906 if (ret->is_error_type())
2907 nc->set_type(ret);
2909 return ret;
2912 // Set the type of the const reference.
2914 void
2915 Const_expression::do_determine_type(const Type_context* context)
2917 Type* ctype = this->constant_->const_value()->type();
2918 Type* cetype = (ctype != NULL
2919 ? ctype
2920 : this->constant_->const_value()->expr()->type());
2921 if (ctype != NULL && !ctype->is_abstract())
2923 else if (context->type != NULL
2924 && context->type->is_numeric_type()
2925 && cetype->is_numeric_type())
2926 this->type_ = context->type;
2927 else if (context->type != NULL
2928 && context->type->is_string_type()
2929 && cetype->is_string_type())
2930 this->type_ = context->type;
2931 else if (context->type != NULL
2932 && context->type->is_boolean_type()
2933 && cetype->is_boolean_type())
2934 this->type_ = context->type;
2935 else if (!context->may_be_abstract)
2937 if (cetype->is_abstract())
2938 cetype = cetype->make_non_abstract_type();
2939 this->type_ = cetype;
2943 // Check for a loop in which the initializer of a constant refers to
2944 // the constant itself.
2946 void
2947 Const_expression::check_for_init_loop()
2949 if (this->type_ != NULL && this->type_->is_error())
2950 return;
2952 if (this->seen_)
2954 this->report_error(_("constant refers to itself"));
2955 this->type_ = Type::make_error_type();
2956 return;
2959 Expression* init = this->constant_->const_value()->expr();
2960 Find_named_object find_named_object(this->constant_);
2962 this->seen_ = true;
2963 Expression::traverse(&init, &find_named_object);
2964 this->seen_ = false;
2966 if (find_named_object.found())
2968 if (this->type_ == NULL || !this->type_->is_error())
2970 this->report_error(_("constant refers to itself"));
2971 this->type_ = Type::make_error_type();
2973 return;
2977 // Check types of a const reference.
2979 void
2980 Const_expression::do_check_types(Gogo*)
2982 if (this->type_ != NULL && this->type_->is_error())
2983 return;
2985 this->check_for_init_loop();
2987 // Check that numeric constant fits in type.
2988 if (this->type_ != NULL && this->type_->is_numeric_type())
2990 Numeric_constant nc;
2991 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2993 if (!nc.set_type(this->type_, true, this->location()))
2994 this->set_is_error();
2999 // Return the backend representation for a const reference.
3001 Bexpression*
3002 Const_expression::do_get_backend(Translate_context* context)
3004 if (this->is_error_expression()
3005 || (this->type_ != NULL && this->type_->is_error()))
3007 go_assert(saw_errors());
3008 return context->backend()->error_expression();
3011 // If the type has been set for this expression, but the underlying
3012 // object is an abstract int or float, we try to get the abstract
3013 // value. Otherwise we may lose something in the conversion.
3014 Expression* expr = this->constant_->const_value()->expr();
3015 if (this->type_ != NULL
3016 && this->type_->is_numeric_type()
3017 && (this->constant_->const_value()->type() == NULL
3018 || this->constant_->const_value()->type()->is_abstract()))
3020 Numeric_constant nc;
3021 if (expr->numeric_constant_value(&nc)
3022 && nc.set_type(this->type_, false, this->location()))
3024 Expression* e = nc.expression(this->location());
3025 return e->get_backend(context);
3029 if (this->type_ != NULL)
3030 expr = Expression::make_cast(this->type_, expr, this->location());
3031 return expr->get_backend(context);
3034 // Dump ast representation for constant expression.
3036 void
3037 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3039 ast_dump_context->ostream() << this->constant_->name();
3042 // Make a reference to a constant in an expression.
3044 Expression*
3045 Expression::make_const_reference(Named_object* constant,
3046 Location location)
3048 return new Const_expression(constant, location);
3051 // Find a named object in an expression.
3054 Find_named_object::expression(Expression** pexpr)
3056 switch ((*pexpr)->classification())
3058 case Expression::EXPRESSION_CONST_REFERENCE:
3060 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3061 if (ce->named_object() == this->no_)
3062 break;
3064 // We need to check a constant initializer explicitly, as
3065 // loops here will not be caught by the loop checking for
3066 // variable initializers.
3067 ce->check_for_init_loop();
3069 return TRAVERSE_CONTINUE;
3072 case Expression::EXPRESSION_VAR_REFERENCE:
3073 if ((*pexpr)->var_expression()->named_object() == this->no_)
3074 break;
3075 return TRAVERSE_CONTINUE;
3076 case Expression::EXPRESSION_FUNC_REFERENCE:
3077 if ((*pexpr)->func_expression()->named_object() == this->no_)
3078 break;
3079 return TRAVERSE_CONTINUE;
3080 default:
3081 return TRAVERSE_CONTINUE;
3083 this->found_ = true;
3084 return TRAVERSE_EXIT;
3087 // The nil value.
3089 class Nil_expression : public Expression
3091 public:
3092 Nil_expression(Location location)
3093 : Expression(EXPRESSION_NIL, location)
3096 static Expression*
3097 do_import(Import*);
3099 protected:
3100 bool
3101 do_is_constant() const
3102 { return true; }
3104 bool
3105 do_is_static_initializer() const
3106 { return true; }
3108 Type*
3109 do_type()
3110 { return Type::make_nil_type(); }
3112 void
3113 do_determine_type(const Type_context*)
3116 Expression*
3117 do_copy()
3118 { return this; }
3120 Bexpression*
3121 do_get_backend(Translate_context* context)
3122 { return context->backend()->nil_pointer_expression(); }
3124 void
3125 do_export(Export* exp) const
3126 { exp->write_c_string("nil"); }
3128 void
3129 do_dump_expression(Ast_dump_context* ast_dump_context) const
3130 { ast_dump_context->ostream() << "nil"; }
3133 // Import a nil expression.
3135 Expression*
3136 Nil_expression::do_import(Import* imp)
3138 imp->require_c_string("nil");
3139 return Expression::make_nil(imp->location());
3142 // Make a nil expression.
3144 Expression*
3145 Expression::make_nil(Location location)
3147 return new Nil_expression(location);
3150 // The value of the predeclared constant iota. This is little more
3151 // than a marker. This will be lowered to an integer in
3152 // Const_expression::do_lower, which is where we know the value that
3153 // it should have.
3155 class Iota_expression : public Parser_expression
3157 public:
3158 Iota_expression(Location location)
3159 : Parser_expression(EXPRESSION_IOTA, location)
3162 protected:
3163 Expression*
3164 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3165 { go_unreachable(); }
3167 // There should only ever be one of these.
3168 Expression*
3169 do_copy()
3170 { go_unreachable(); }
3172 void
3173 do_dump_expression(Ast_dump_context* ast_dump_context) const
3174 { ast_dump_context->ostream() << "iota"; }
3177 // Make an iota expression. This is only called for one case: the
3178 // value of the predeclared constant iota.
3180 Expression*
3181 Expression::make_iota()
3183 static Iota_expression iota_expression(Linemap::unknown_location());
3184 return &iota_expression;
3187 // Class Type_conversion_expression.
3189 // Traversal.
3192 Type_conversion_expression::do_traverse(Traverse* traverse)
3194 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3195 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3196 return TRAVERSE_EXIT;
3197 return TRAVERSE_CONTINUE;
3200 // Convert to a constant at lowering time.
3202 Expression*
3203 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3204 Statement_inserter*, int)
3206 Type* type = this->type_;
3207 Expression* val = this->expr_;
3208 Location location = this->location();
3210 if (type->is_numeric_type())
3212 Numeric_constant nc;
3213 if (val->numeric_constant_value(&nc))
3215 if (!nc.set_type(type, true, location))
3216 return Expression::make_error(location);
3217 return nc.expression(location);
3221 // According to the language specification on string conversions
3222 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3223 // When converting an integer into a string, the string will be a UTF-8
3224 // representation of the integer and integers "outside the range of valid
3225 // Unicode code points are converted to '\uFFFD'."
3226 if (type->is_string_type())
3228 Numeric_constant nc;
3229 if (val->numeric_constant_value(&nc) && nc.is_int())
3231 // An integer value doesn't fit in the Unicode code point range if it
3232 // overflows the Go "int" type or is negative.
3233 unsigned long ul;
3234 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3235 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3236 return Expression::make_string("\ufffd", location);
3240 if (type->is_slice_type())
3242 Type* element_type = type->array_type()->element_type()->forwarded();
3243 bool is_byte = (element_type->integer_type() != NULL
3244 && element_type->integer_type()->is_byte());
3245 bool is_rune = (element_type->integer_type() != NULL
3246 && element_type->integer_type()->is_rune());
3247 if (is_byte || is_rune)
3249 std::string s;
3250 if (val->string_constant_value(&s))
3252 Expression_list* vals = new Expression_list();
3253 if (is_byte)
3255 for (std::string::const_iterator p = s.begin();
3256 p != s.end();
3257 p++)
3259 unsigned char c = static_cast<unsigned char>(*p);
3260 vals->push_back(Expression::make_integer_ul(c,
3261 element_type,
3262 location));
3265 else
3267 const char *p = s.data();
3268 const char *pend = s.data() + s.length();
3269 while (p < pend)
3271 unsigned int c;
3272 int adv = Lex::fetch_char(p, &c);
3273 if (adv == 0)
3275 go_warning_at(this->location(), 0,
3276 "invalid UTF-8 encoding");
3277 adv = 1;
3279 p += adv;
3280 vals->push_back(Expression::make_integer_ul(c,
3281 element_type,
3282 location));
3286 return Expression::make_slice_composite_literal(type, vals,
3287 location);
3292 return this;
3295 // Flatten a type conversion by using a temporary variable for the slice
3296 // in slice to string conversions.
3298 Expression*
3299 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3300 Statement_inserter* inserter)
3302 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3304 go_assert(saw_errors());
3305 return Expression::make_error(this->location());
3308 if (((this->type()->is_string_type()
3309 && this->expr_->type()->is_slice_type())
3310 || this->expr_->type()->interface_type() != NULL)
3311 && !this->expr_->is_variable())
3313 Temporary_statement* temp =
3314 Statement::make_temporary(NULL, this->expr_, this->location());
3315 inserter->insert(temp);
3316 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3318 return this;
3321 // Return whether a type conversion is a constant.
3323 bool
3324 Type_conversion_expression::do_is_constant() const
3326 if (!this->expr_->is_constant())
3327 return false;
3329 // A conversion to a type that may not be used as a constant is not
3330 // a constant. For example, []byte(nil).
3331 Type* type = this->type_;
3332 if (type->integer_type() == NULL
3333 && type->float_type() == NULL
3334 && type->complex_type() == NULL
3335 && !type->is_boolean_type()
3336 && !type->is_string_type())
3337 return false;
3339 return true;
3342 // Return whether a type conversion can be used in a constant
3343 // initializer.
3345 bool
3346 Type_conversion_expression::do_is_static_initializer() const
3348 Type* type = this->type_;
3349 Type* expr_type = this->expr_->type();
3351 if (type->interface_type() != NULL
3352 || expr_type->interface_type() != NULL)
3353 return false;
3355 if (!this->expr_->is_static_initializer())
3356 return false;
3358 if (Type::are_identical(type, expr_type, false, NULL))
3359 return true;
3361 if (type->is_string_type() && expr_type->is_string_type())
3362 return true;
3364 if ((type->is_numeric_type()
3365 || type->is_boolean_type()
3366 || type->points_to() != NULL)
3367 && (expr_type->is_numeric_type()
3368 || expr_type->is_boolean_type()
3369 || expr_type->points_to() != NULL))
3370 return true;
3372 return false;
3375 // Return the constant numeric value if there is one.
3377 bool
3378 Type_conversion_expression::do_numeric_constant_value(
3379 Numeric_constant* nc) const
3381 if (!this->type_->is_numeric_type())
3382 return false;
3383 if (!this->expr_->numeric_constant_value(nc))
3384 return false;
3385 return nc->set_type(this->type_, false, this->location());
3388 // Return the constant string value if there is one.
3390 bool
3391 Type_conversion_expression::do_string_constant_value(std::string* val) const
3393 if (this->type_->is_string_type()
3394 && this->expr_->type()->integer_type() != NULL)
3396 Numeric_constant nc;
3397 if (this->expr_->numeric_constant_value(&nc))
3399 unsigned long ival;
3400 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3402 val->clear();
3403 Lex::append_char(ival, true, val, this->location());
3404 return true;
3409 // FIXME: Could handle conversion from const []int here.
3411 return false;
3414 // Determine the resulting type of the conversion.
3416 void
3417 Type_conversion_expression::do_determine_type(const Type_context*)
3419 Type_context subcontext(this->type_, false);
3420 this->expr_->determine_type(&subcontext);
3423 // Check that types are convertible.
3425 void
3426 Type_conversion_expression::do_check_types(Gogo*)
3428 Type* type = this->type_;
3429 Type* expr_type = this->expr_->type();
3430 std::string reason;
3432 if (type->is_error() || expr_type->is_error())
3434 this->set_is_error();
3435 return;
3438 if (this->may_convert_function_types_
3439 && type->function_type() != NULL
3440 && expr_type->function_type() != NULL)
3441 return;
3443 if (Type::are_convertible(type, expr_type, &reason))
3444 return;
3446 go_error_at(this->location(), "%s", reason.c_str());
3447 this->set_is_error();
3450 // Copy.
3452 Expression*
3453 Type_conversion_expression::do_copy()
3455 return new Type_conversion_expression(this->type_->copy_expressions(),
3456 this->expr_->copy(),
3457 this->location());
3460 // Get the backend representation for a type conversion.
3462 Bexpression*
3463 Type_conversion_expression::do_get_backend(Translate_context* context)
3465 Type* type = this->type_;
3466 Type* expr_type = this->expr_->type();
3468 Gogo* gogo = context->gogo();
3469 Btype* btype = type->get_backend(gogo);
3470 Location loc = this->location();
3472 if (Type::are_identical(type, expr_type, false, NULL))
3474 Bexpression* bexpr = this->expr_->get_backend(context);
3475 return gogo->backend()->convert_expression(btype, bexpr, loc);
3477 else if (type->interface_type() != NULL
3478 || expr_type->interface_type() != NULL)
3480 Expression* conversion =
3481 Expression::convert_for_assignment(gogo, type, this->expr_,
3482 this->location());
3483 return conversion->get_backend(context);
3485 else if (type->is_string_type()
3486 && expr_type->integer_type() != NULL)
3488 mpz_t intval;
3489 Numeric_constant nc;
3490 if (this->expr_->numeric_constant_value(&nc)
3491 && nc.to_int(&intval)
3492 && mpz_fits_ushort_p(intval))
3494 std::string s;
3495 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3496 mpz_clear(intval);
3497 Expression* se = Expression::make_string(s, loc);
3498 return se->get_backend(context);
3501 Expression* i2s_expr =
3502 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3503 Expression::make_nil(loc), this->expr_);
3504 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3506 else if (type->is_string_type() && expr_type->is_slice_type())
3508 Array_type* a = expr_type->array_type();
3509 Type* e = a->element_type()->forwarded();
3510 go_assert(e->integer_type() != NULL);
3511 go_assert(this->expr_->is_variable());
3513 Runtime::Function code;
3514 if (e->integer_type()->is_byte())
3515 code = Runtime::SLICEBYTETOSTRING;
3516 else
3518 go_assert(e->integer_type()->is_rune());
3519 code = Runtime::SLICERUNETOSTRING;
3521 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3522 this->expr_)->get_backend(context);
3524 else if (type->is_slice_type() && expr_type->is_string_type())
3526 Type* e = type->array_type()->element_type()->forwarded();
3527 go_assert(e->integer_type() != NULL);
3529 Runtime::Function code;
3530 if (e->integer_type()->is_byte())
3531 code = Runtime::STRINGTOSLICEBYTE;
3532 else
3534 go_assert(e->integer_type()->is_rune());
3535 code = Runtime::STRINGTOSLICERUNE;
3537 Expression* s2a = Runtime::make_call(code, loc, 2,
3538 Expression::make_nil(loc),
3539 this->expr_);
3540 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3542 else if (type->is_numeric_type())
3544 go_assert(Type::are_convertible(type, expr_type, NULL));
3545 Bexpression* bexpr = this->expr_->get_backend(context);
3546 return gogo->backend()->convert_expression(btype, bexpr, loc);
3548 else if ((type->is_unsafe_pointer_type()
3549 && (expr_type->points_to() != NULL
3550 || expr_type->integer_type()))
3551 || (expr_type->is_unsafe_pointer_type()
3552 && type->points_to() != NULL)
3553 || (this->may_convert_function_types_
3554 && type->function_type() != NULL
3555 && expr_type->function_type() != NULL))
3557 Bexpression* bexpr = this->expr_->get_backend(context);
3558 return gogo->backend()->convert_expression(btype, bexpr, loc);
3560 else
3562 Expression* conversion =
3563 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3564 return conversion->get_backend(context);
3568 // Output a type conversion in a constant expression.
3570 void
3571 Type_conversion_expression::do_export(Export* exp) const
3573 exp->write_c_string("convert(");
3574 exp->write_type(this->type_);
3575 exp->write_c_string(", ");
3576 this->expr_->export_expression(exp);
3577 exp->write_c_string(")");
3580 // Import a type conversion or a struct construction.
3582 Expression*
3583 Type_conversion_expression::do_import(Import* imp)
3585 imp->require_c_string("convert(");
3586 Type* type = imp->read_type();
3587 imp->require_c_string(", ");
3588 Expression* val = Expression::import_expression(imp);
3589 imp->require_c_string(")");
3590 return Expression::make_cast(type, val, imp->location());
3593 // Dump ast representation for a type conversion expression.
3595 void
3596 Type_conversion_expression::do_dump_expression(
3597 Ast_dump_context* ast_dump_context) const
3599 ast_dump_context->dump_type(this->type_);
3600 ast_dump_context->ostream() << "(";
3601 ast_dump_context->dump_expression(this->expr_);
3602 ast_dump_context->ostream() << ") ";
3605 // Make a type cast expression.
3607 Expression*
3608 Expression::make_cast(Type* type, Expression* val, Location location)
3610 if (type->is_error_type() || val->is_error_expression())
3611 return Expression::make_error(location);
3612 return new Type_conversion_expression(type, val, location);
3615 // Class Unsafe_type_conversion_expression.
3617 // Traversal.
3620 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3622 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3623 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3624 return TRAVERSE_EXIT;
3625 return TRAVERSE_CONTINUE;
3628 // Return whether an unsafe type conversion can be used as a constant
3629 // initializer.
3631 bool
3632 Unsafe_type_conversion_expression::do_is_static_initializer() const
3634 Type* type = this->type_;
3635 Type* expr_type = this->expr_->type();
3637 if (type->interface_type() != NULL
3638 || expr_type->interface_type() != NULL)
3639 return false;
3641 if (!this->expr_->is_static_initializer())
3642 return false;
3644 if (Type::are_convertible(type, expr_type, NULL))
3645 return true;
3647 if (type->is_string_type() && expr_type->is_string_type())
3648 return true;
3650 if ((type->is_numeric_type()
3651 || type->is_boolean_type()
3652 || type->points_to() != NULL)
3653 && (expr_type->is_numeric_type()
3654 || expr_type->is_boolean_type()
3655 || expr_type->points_to() != NULL))
3656 return true;
3658 return false;
3661 // Copy.
3663 Expression*
3664 Unsafe_type_conversion_expression::do_copy()
3666 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
3667 this->expr_->copy(),
3668 this->location());
3671 // Convert to backend representation.
3673 Bexpression*
3674 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3676 // We are only called for a limited number of cases.
3678 Type* t = this->type_;
3679 Type* et = this->expr_->type();
3681 if (t->is_error_type()
3682 || this->expr_->is_error_expression()
3683 || et->is_error_type())
3685 go_assert(saw_errors());
3686 return context->backend()->error_expression();
3689 if (t->array_type() != NULL)
3690 go_assert(et->array_type() != NULL
3691 && t->is_slice_type() == et->is_slice_type());
3692 else if (t->struct_type() != NULL)
3694 if (t->named_type() != NULL
3695 && et->named_type() != NULL
3696 && !Type::are_convertible(t, et, NULL))
3698 go_assert(saw_errors());
3699 return context->backend()->error_expression();
3702 go_assert(et->struct_type() != NULL
3703 && Type::are_convertible(t, et, NULL));
3705 else if (t->map_type() != NULL)
3706 go_assert(et->map_type() != NULL);
3707 else if (t->channel_type() != NULL)
3708 go_assert(et->channel_type() != NULL);
3709 else if (t->points_to() != NULL)
3710 go_assert(et->points_to() != NULL
3711 || et->channel_type() != NULL
3712 || et->map_type() != NULL
3713 || et->function_type() != NULL
3714 || et->integer_type() != NULL
3715 || et->is_nil_type());
3716 else if (et->is_unsafe_pointer_type())
3717 go_assert(t->points_to() != NULL);
3718 else if (t->interface_type() != NULL)
3720 bool empty_iface = t->interface_type()->is_empty();
3721 go_assert(et->interface_type() != NULL
3722 && et->interface_type()->is_empty() == empty_iface);
3724 else if (t->integer_type() != NULL)
3725 go_assert(et->is_boolean_type()
3726 || et->integer_type() != NULL
3727 || et->function_type() != NULL
3728 || et->points_to() != NULL
3729 || et->map_type() != NULL
3730 || et->channel_type() != NULL
3731 || et->is_nil_type());
3732 else if (t->function_type() != NULL)
3733 go_assert(et->points_to() != NULL);
3734 else
3735 go_unreachable();
3737 Gogo* gogo = context->gogo();
3738 Btype* btype = t->get_backend(gogo);
3739 Bexpression* bexpr = this->expr_->get_backend(context);
3740 Location loc = this->location();
3741 return gogo->backend()->convert_expression(btype, bexpr, loc);
3744 // Dump ast representation for an unsafe type conversion expression.
3746 void
3747 Unsafe_type_conversion_expression::do_dump_expression(
3748 Ast_dump_context* ast_dump_context) const
3750 ast_dump_context->dump_type(this->type_);
3751 ast_dump_context->ostream() << "(";
3752 ast_dump_context->dump_expression(this->expr_);
3753 ast_dump_context->ostream() << ") ";
3756 // Make an unsafe type conversion expression.
3758 Expression*
3759 Expression::make_unsafe_cast(Type* type, Expression* expr,
3760 Location location)
3762 return new Unsafe_type_conversion_expression(type, expr, location);
3765 // Class Unary_expression.
3767 // Call the address_taken method of the operand if needed. This is
3768 // called after escape analysis but before inserting write barriers.
3770 void
3771 Unary_expression::check_operand_address_taken(Gogo*)
3773 if (this->op_ != OPERATOR_AND)
3774 return;
3776 // If this->escapes_ is false at this point, then it was set to
3777 // false by an explicit call to set_does_not_escape, and the value
3778 // does not escape. If this->escapes_ is true, we may be able to
3779 // set it to false if taking the address of a variable that does not
3780 // escape.
3781 Node* n = Node::make_node(this);
3782 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3783 this->escapes_ = false;
3785 Named_object* var = NULL;
3786 if (this->expr_->var_expression() != NULL)
3787 var = this->expr_->var_expression()->named_object();
3788 else if (this->expr_->enclosed_var_expression() != NULL)
3789 var = this->expr_->enclosed_var_expression()->variable();
3791 if (this->escapes_ && var != NULL)
3793 if (var->is_variable())
3794 this->escapes_ = var->var_value()->escapes();
3795 if (var->is_result_variable())
3796 this->escapes_ = var->result_var_value()->escapes();
3799 this->expr_->address_taken(this->escapes_);
3802 // If we are taking the address of a composite literal, and the
3803 // contents are not constant, then we want to make a heap expression
3804 // instead.
3806 Expression*
3807 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3809 Location loc = this->location();
3810 Operator op = this->op_;
3811 Expression* expr = this->expr_;
3813 if (op == OPERATOR_MULT && expr->is_type_expression())
3814 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3816 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3817 // moving x to the heap. FIXME: Is it worth doing a real escape
3818 // analysis here? This case is found in math/unsafe.go and is
3819 // therefore worth special casing.
3820 if (op == OPERATOR_MULT)
3822 Expression* e = expr;
3823 while (e->classification() == EXPRESSION_CONVERSION)
3825 Type_conversion_expression* te
3826 = static_cast<Type_conversion_expression*>(e);
3827 e = te->expr();
3830 if (e->classification() == EXPRESSION_UNARY)
3832 Unary_expression* ue = static_cast<Unary_expression*>(e);
3833 if (ue->op_ == OPERATOR_AND)
3835 if (e == expr)
3837 // *&x == x.
3838 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3840 go_error_at(ue->location(),
3841 "invalid operand for unary %<&%>");
3842 this->set_is_error();
3844 return ue->expr_;
3846 ue->set_does_not_escape();
3851 // Catching an invalid indirection of unsafe.Pointer here avoid
3852 // having to deal with TYPE_VOID in other places.
3853 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3855 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3856 return Expression::make_error(this->location());
3859 // Check for an invalid pointer dereference. We need to do this
3860 // here because Unary_expression::do_type will return an error type
3861 // in this case. That can cause code to appear erroneous, and
3862 // therefore disappear at lowering time, without any error message.
3863 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3865 this->report_error(_("expected pointer"));
3866 return Expression::make_error(this->location());
3869 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3871 Numeric_constant nc;
3872 if (expr->numeric_constant_value(&nc))
3874 Numeric_constant result;
3875 bool issued_error;
3876 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3877 &issued_error))
3878 return result.expression(loc);
3879 else if (issued_error)
3880 return Expression::make_error(this->location());
3884 return this;
3887 // Flatten expression if a nil check must be performed and create temporary
3888 // variables if necessary.
3890 Expression*
3891 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3892 Statement_inserter* inserter)
3894 if (this->is_error_expression()
3895 || this->expr_->is_error_expression()
3896 || this->expr_->type()->is_error_type())
3898 go_assert(saw_errors());
3899 return Expression::make_error(this->location());
3902 Location location = this->location();
3903 if (this->op_ == OPERATOR_MULT
3904 && !this->expr_->is_variable())
3906 go_assert(this->expr_->type()->points_to() != NULL);
3907 switch (this->requires_nil_check(gogo))
3909 case NIL_CHECK_ERROR_ENCOUNTERED:
3911 go_assert(saw_errors());
3912 return Expression::make_error(this->location());
3914 case NIL_CHECK_NOT_NEEDED:
3915 break;
3916 case NIL_CHECK_NEEDED:
3917 this->create_temp_ = true;
3918 break;
3919 case NIL_CHECK_DEFAULT:
3920 go_unreachable();
3924 if (this->create_temp_ && !this->expr_->is_variable())
3926 Temporary_statement* temp =
3927 Statement::make_temporary(NULL, this->expr_, location);
3928 inserter->insert(temp);
3929 this->expr_ = Expression::make_temporary_reference(temp, location);
3932 return this;
3935 // Return whether a unary expression is a constant.
3937 bool
3938 Unary_expression::do_is_constant() const
3940 if (this->op_ == OPERATOR_MULT)
3942 // Indirecting through a pointer is only constant if the object
3943 // to which the expression points is constant, but we currently
3944 // have no way to determine that.
3945 return false;
3947 else if (this->op_ == OPERATOR_AND)
3949 // Taking the address of a variable is constant if it is a
3950 // global variable, not constant otherwise. In other cases taking the
3951 // address is probably not a constant.
3952 Var_expression* ve = this->expr_->var_expression();
3953 if (ve != NULL)
3955 Named_object* no = ve->named_object();
3956 return no->is_variable() && no->var_value()->is_global();
3958 return false;
3960 else
3961 return this->expr_->is_constant();
3964 // Return whether a unary expression can be used as a constant
3965 // initializer.
3967 bool
3968 Unary_expression::do_is_static_initializer() const
3970 if (this->op_ == OPERATOR_MULT)
3971 return false;
3972 else if (this->op_ == OPERATOR_AND)
3973 return Unary_expression::base_is_static_initializer(this->expr_);
3974 else
3975 return this->expr_->is_static_initializer();
3978 // Return whether the address of EXPR can be used as a static
3979 // initializer.
3981 bool
3982 Unary_expression::base_is_static_initializer(Expression* expr)
3984 // The address of a field reference can be a static initializer if
3985 // the base can be a static initializer.
3986 Field_reference_expression* fre = expr->field_reference_expression();
3987 if (fre != NULL)
3988 return Unary_expression::base_is_static_initializer(fre->expr());
3990 // The address of an index expression can be a static initializer if
3991 // the base can be a static initializer and the index is constant.
3992 Array_index_expression* aind = expr->array_index_expression();
3993 if (aind != NULL)
3994 return (aind->end() == NULL
3995 && aind->start()->is_constant()
3996 && Unary_expression::base_is_static_initializer(aind->array()));
3998 // The address of a global variable can be a static initializer.
3999 Var_expression* ve = expr->var_expression();
4000 if (ve != NULL)
4002 Named_object* no = ve->named_object();
4003 return no->is_variable() && no->var_value()->is_global();
4006 // The address of a composite literal can be used as a static
4007 // initializer if the composite literal is itself usable as a
4008 // static initializer.
4009 if (expr->is_composite_literal() && expr->is_static_initializer())
4010 return true;
4012 // The address of a string constant can be used as a static
4013 // initializer. This can not be written in Go itself but this is
4014 // used when building a type descriptor.
4015 if (expr->string_expression() != NULL)
4016 return true;
4018 return false;
4021 // Return whether this dereference expression requires an explicit nil
4022 // check. If we are dereferencing the pointer to a large struct
4023 // (greater than the specified size threshold), we need to check for
4024 // nil. We don't bother to check for small structs because we expect
4025 // the system to crash on a nil pointer dereference. However, if we
4026 // know the address of this expression is being taken, we must always
4027 // check for nil.
4028 Unary_expression::Nil_check_classification
4029 Unary_expression::requires_nil_check(Gogo* gogo)
4031 go_assert(this->op_ == OPERATOR_MULT);
4032 go_assert(this->expr_->type()->points_to() != NULL);
4034 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4035 return NIL_CHECK_NEEDED;
4036 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4037 return NIL_CHECK_NOT_NEEDED;
4039 Type* ptype = this->expr_->type()->points_to();
4040 int64_t type_size = -1;
4041 if (!ptype->is_void_type())
4043 bool ok = ptype->backend_type_size(gogo, &type_size);
4044 if (!ok)
4045 return NIL_CHECK_ERROR_ENCOUNTERED;
4048 int64_t size_cutoff = gogo->nil_check_size_threshold();
4049 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4050 this->issue_nil_check_ = NIL_CHECK_NEEDED;
4051 else
4052 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4053 return this->issue_nil_check_;
4056 // Apply unary opcode OP to UNC, setting NC. Return true if this
4057 // could be done, false if not. On overflow, issues an error and sets
4058 // *ISSUED_ERROR.
4060 bool
4061 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4062 Location location, Numeric_constant* nc,
4063 bool* issued_error)
4065 *issued_error = false;
4066 switch (op)
4068 case OPERATOR_PLUS:
4069 *nc = *unc;
4070 return true;
4072 case OPERATOR_MINUS:
4073 if (unc->is_int() || unc->is_rune())
4074 break;
4075 else if (unc->is_float())
4077 mpfr_t uval;
4078 unc->get_float(&uval);
4079 mpfr_t val;
4080 mpfr_init(val);
4081 mpfr_neg(val, uval, GMP_RNDN);
4082 nc->set_float(unc->type(), val);
4083 mpfr_clear(uval);
4084 mpfr_clear(val);
4085 return true;
4087 else if (unc->is_complex())
4089 mpc_t uval;
4090 unc->get_complex(&uval);
4091 mpc_t val;
4092 mpc_init2(val, mpc_precision);
4093 mpc_neg(val, uval, MPC_RNDNN);
4094 nc->set_complex(unc->type(), val);
4095 mpc_clear(uval);
4096 mpc_clear(val);
4097 return true;
4099 else
4100 go_unreachable();
4102 case OPERATOR_XOR:
4103 break;
4105 case OPERATOR_NOT:
4106 case OPERATOR_AND:
4107 case OPERATOR_MULT:
4108 return false;
4110 default:
4111 go_unreachable();
4114 if (!unc->is_int() && !unc->is_rune())
4115 return false;
4117 mpz_t uval;
4118 if (unc->is_rune())
4119 unc->get_rune(&uval);
4120 else
4121 unc->get_int(&uval);
4122 mpz_t val;
4123 mpz_init(val);
4125 switch (op)
4127 case OPERATOR_MINUS:
4128 mpz_neg(val, uval);
4129 break;
4131 case OPERATOR_NOT:
4132 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4133 break;
4135 case OPERATOR_XOR:
4137 Type* utype = unc->type();
4138 if (utype->integer_type() == NULL
4139 || utype->integer_type()->is_abstract())
4140 mpz_com(val, uval);
4141 else
4143 // The number of HOST_WIDE_INTs that it takes to represent
4144 // UVAL.
4145 size_t count = ((mpz_sizeinbase(uval, 2)
4146 + HOST_BITS_PER_WIDE_INT
4147 - 1)
4148 / HOST_BITS_PER_WIDE_INT);
4150 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4151 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4153 size_t obits = utype->integer_type()->bits();
4155 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4157 mpz_t adj;
4158 mpz_init_set_ui(adj, 1);
4159 mpz_mul_2exp(adj, adj, obits);
4160 mpz_add(uval, uval, adj);
4161 mpz_clear(adj);
4164 size_t ecount;
4165 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4166 go_assert(ecount <= count);
4168 // Trim down to the number of words required by the type.
4169 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4170 / HOST_BITS_PER_WIDE_INT);
4171 go_assert(ocount <= count);
4173 for (size_t i = 0; i < ocount; ++i)
4174 phwi[i] = ~phwi[i];
4176 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4177 if (clearbits != 0)
4178 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4179 >> clearbits);
4181 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4183 if (!utype->integer_type()->is_unsigned()
4184 && mpz_tstbit(val, obits - 1))
4186 mpz_t adj;
4187 mpz_init_set_ui(adj, 1);
4188 mpz_mul_2exp(adj, adj, obits);
4189 mpz_sub(val, val, adj);
4190 mpz_clear(adj);
4193 delete[] phwi;
4196 break;
4198 default:
4199 go_unreachable();
4202 if (unc->is_rune())
4203 nc->set_rune(NULL, val);
4204 else
4205 nc->set_int(NULL, val);
4207 mpz_clear(uval);
4208 mpz_clear(val);
4210 if (!nc->set_type(unc->type(), true, location))
4212 *issued_error = true;
4213 return false;
4215 return true;
4218 // Return the integral constant value of a unary expression, if it has one.
4220 bool
4221 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4223 Numeric_constant unc;
4224 if (!this->expr_->numeric_constant_value(&unc))
4225 return false;
4226 bool issued_error;
4227 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4228 nc, &issued_error);
4231 // Return the type of a unary expression.
4233 Type*
4234 Unary_expression::do_type()
4236 switch (this->op_)
4238 case OPERATOR_PLUS:
4239 case OPERATOR_MINUS:
4240 case OPERATOR_NOT:
4241 case OPERATOR_XOR:
4242 return this->expr_->type();
4244 case OPERATOR_AND:
4245 return Type::make_pointer_type(this->expr_->type());
4247 case OPERATOR_MULT:
4249 Type* subtype = this->expr_->type();
4250 Type* points_to = subtype->points_to();
4251 if (points_to == NULL)
4252 return Type::make_error_type();
4253 return points_to;
4256 default:
4257 go_unreachable();
4261 // Determine abstract types for a unary expression.
4263 void
4264 Unary_expression::do_determine_type(const Type_context* context)
4266 switch (this->op_)
4268 case OPERATOR_PLUS:
4269 case OPERATOR_MINUS:
4270 case OPERATOR_NOT:
4271 case OPERATOR_XOR:
4272 this->expr_->determine_type(context);
4273 break;
4275 case OPERATOR_AND:
4276 // Taking the address of something.
4278 Type* subtype = (context->type == NULL
4279 ? NULL
4280 : context->type->points_to());
4281 Type_context subcontext(subtype, false);
4282 this->expr_->determine_type(&subcontext);
4284 break;
4286 case OPERATOR_MULT:
4287 // Indirecting through a pointer.
4289 Type* subtype = (context->type == NULL
4290 ? NULL
4291 : Type::make_pointer_type(context->type));
4292 Type_context subcontext(subtype, false);
4293 this->expr_->determine_type(&subcontext);
4295 break;
4297 default:
4298 go_unreachable();
4302 // Check types for a unary expression.
4304 void
4305 Unary_expression::do_check_types(Gogo*)
4307 Type* type = this->expr_->type();
4308 if (type->is_error())
4310 this->set_is_error();
4311 return;
4314 switch (this->op_)
4316 case OPERATOR_PLUS:
4317 case OPERATOR_MINUS:
4318 if (type->integer_type() == NULL
4319 && type->float_type() == NULL
4320 && type->complex_type() == NULL)
4321 this->report_error(_("expected numeric type"));
4322 break;
4324 case OPERATOR_NOT:
4325 if (!type->is_boolean_type())
4326 this->report_error(_("expected boolean type"));
4327 break;
4329 case OPERATOR_XOR:
4330 if (type->integer_type() == NULL)
4331 this->report_error(_("expected integer"));
4332 break;
4334 case OPERATOR_AND:
4335 if (!this->expr_->is_addressable())
4337 if (!this->create_temp_)
4339 go_error_at(this->location(), "invalid operand for unary %<&%>");
4340 this->set_is_error();
4343 else
4344 this->expr_->issue_nil_check();
4345 break;
4347 case OPERATOR_MULT:
4348 // Indirecting through a pointer.
4349 if (type->points_to() == NULL)
4350 this->report_error(_("expected pointer"));
4351 if (type->points_to()->is_error())
4352 this->set_is_error();
4353 break;
4355 default:
4356 go_unreachable();
4360 // Get the backend representation for a unary expression.
4362 Bexpression*
4363 Unary_expression::do_get_backend(Translate_context* context)
4365 Gogo* gogo = context->gogo();
4366 Location loc = this->location();
4368 // Taking the address of a set-and-use-temporary expression requires
4369 // setting the temporary and then taking the address.
4370 if (this->op_ == OPERATOR_AND)
4372 Set_and_use_temporary_expression* sut =
4373 this->expr_->set_and_use_temporary_expression();
4374 if (sut != NULL)
4376 Temporary_statement* temp = sut->temporary();
4377 Bvariable* bvar = temp->get_backend_variable(context);
4378 Bexpression* bvar_expr =
4379 gogo->backend()->var_expression(bvar, loc);
4380 Bexpression* bval = sut->expression()->get_backend(context);
4382 Named_object* fn = context->function();
4383 go_assert(fn != NULL);
4384 Bfunction* bfn =
4385 fn->func_value()->get_or_make_decl(gogo, fn);
4386 Bstatement* bassign =
4387 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4388 Bexpression* bvar_addr =
4389 gogo->backend()->address_expression(bvar_expr, loc);
4390 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4394 Bexpression* ret;
4395 Bexpression* bexpr = this->expr_->get_backend(context);
4396 Btype* btype = this->expr_->type()->get_backend(gogo);
4397 switch (this->op_)
4399 case OPERATOR_PLUS:
4400 ret = bexpr;
4401 break;
4403 case OPERATOR_MINUS:
4404 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4405 ret = gogo->backend()->convert_expression(btype, ret, loc);
4406 break;
4408 case OPERATOR_NOT:
4409 case OPERATOR_XOR:
4410 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4411 break;
4413 case OPERATOR_AND:
4414 if (!this->create_temp_)
4416 // We should not see a non-constant constructor here; cases
4417 // where we would see one should have been moved onto the
4418 // heap at parse time. Taking the address of a nonconstant
4419 // constructor will not do what the programmer expects.
4421 go_assert(!this->expr_->is_composite_literal()
4422 || this->expr_->is_static_initializer());
4423 if (this->expr_->classification() == EXPRESSION_UNARY)
4425 Unary_expression* ue =
4426 static_cast<Unary_expression*>(this->expr_);
4427 go_assert(ue->op() != OPERATOR_AND);
4431 if (this->is_gc_root_ || this->is_slice_init_)
4433 std::string var_name;
4434 bool copy_to_heap = false;
4435 if (this->is_gc_root_)
4437 // Build a decl for a GC root variable. GC roots are mutable, so
4438 // they cannot be represented as an immutable_struct in the
4439 // backend.
4440 var_name = gogo->gc_root_name();
4442 else
4444 // Build a decl for a slice value initializer. An immutable slice
4445 // value initializer may have to be copied to the heap if it
4446 // contains pointers in a non-constant context.
4447 var_name = gogo->initializer_name();
4449 Array_type* at = this->expr_->type()->array_type();
4450 go_assert(at != NULL);
4452 // If we are not copying the value to the heap, we will only
4453 // initialize the value once, so we can use this directly
4454 // rather than copying it. In that case we can't make it
4455 // read-only, because the program is permitted to change it.
4456 copy_to_heap = context->function() != NULL;
4458 std::string asm_name(go_selectively_encode_id(var_name));
4459 Bvariable* implicit =
4460 gogo->backend()->implicit_variable(var_name, asm_name,
4461 btype, true, copy_to_heap,
4462 false, 0);
4463 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4464 true, copy_to_heap, false,
4465 bexpr);
4466 bexpr = gogo->backend()->var_expression(implicit, loc);
4468 // If we are not copying a slice initializer to the heap,
4469 // then it can be changed by the program, so if it can
4470 // contain pointers we must register it as a GC root.
4471 if (this->is_slice_init_
4472 && !copy_to_heap
4473 && this->expr_->type()->has_pointer())
4475 Bexpression* root =
4476 gogo->backend()->var_expression(implicit, loc);
4477 root = gogo->backend()->address_expression(root, loc);
4478 Type* type = Type::make_pointer_type(this->expr_->type());
4479 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4482 else if ((this->expr_->is_composite_literal()
4483 || this->expr_->string_expression() != NULL)
4484 && this->expr_->is_static_initializer())
4486 std::string var_name(gogo->initializer_name());
4487 std::string asm_name(go_selectively_encode_id(var_name));
4488 Bvariable* decl =
4489 gogo->backend()->immutable_struct(var_name, asm_name,
4490 true, false, btype, loc);
4491 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4492 false, btype, loc, bexpr);
4493 bexpr = gogo->backend()->var_expression(decl, loc);
4496 go_assert(!this->create_temp_ || this->expr_->is_variable());
4497 ret = gogo->backend()->address_expression(bexpr, loc);
4498 break;
4500 case OPERATOR_MULT:
4502 go_assert(this->expr_->type()->points_to() != NULL);
4504 bool known_valid = false;
4505 Type* ptype = this->expr_->type()->points_to();
4506 Btype* pbtype = ptype->get_backend(gogo);
4507 switch (this->requires_nil_check(gogo))
4509 case NIL_CHECK_NOT_NEEDED:
4510 break;
4511 case NIL_CHECK_ERROR_ENCOUNTERED:
4513 go_assert(saw_errors());
4514 return gogo->backend()->error_expression();
4516 case NIL_CHECK_NEEDED:
4518 go_assert(this->expr_->is_variable());
4520 // If we're nil-checking the result of a set-and-use-temporary
4521 // expression, then pick out the target temp and use that
4522 // for the final result of the conditional.
4523 Bexpression* tbexpr = bexpr;
4524 Bexpression* ubexpr = bexpr;
4525 Set_and_use_temporary_expression* sut =
4526 this->expr_->set_and_use_temporary_expression();
4527 if (sut != NULL) {
4528 Temporary_statement* temp = sut->temporary();
4529 Bvariable* bvar = temp->get_backend_variable(context);
4530 ubexpr = gogo->backend()->var_expression(bvar, loc);
4532 Bexpression* nil =
4533 Expression::make_nil(loc)->get_backend(context);
4534 Bexpression* compare =
4535 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4536 nil, loc);
4537 Bexpression* crash =
4538 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4539 loc)->get_backend(context);
4540 Bfunction* bfn = context->function()->func_value()->get_decl();
4541 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4542 compare,
4543 crash, ubexpr,
4544 loc);
4545 known_valid = true;
4546 break;
4548 case NIL_CHECK_DEFAULT:
4549 go_unreachable();
4551 ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4552 known_valid, loc);
4554 break;
4556 default:
4557 go_unreachable();
4560 return ret;
4563 // Export a unary expression.
4565 void
4566 Unary_expression::do_export(Export* exp) const
4568 switch (this->op_)
4570 case OPERATOR_PLUS:
4571 exp->write_c_string("+ ");
4572 break;
4573 case OPERATOR_MINUS:
4574 exp->write_c_string("- ");
4575 break;
4576 case OPERATOR_NOT:
4577 exp->write_c_string("! ");
4578 break;
4579 case OPERATOR_XOR:
4580 exp->write_c_string("^ ");
4581 break;
4582 case OPERATOR_AND:
4583 case OPERATOR_MULT:
4584 default:
4585 go_unreachable();
4587 this->expr_->export_expression(exp);
4590 // Import a unary expression.
4592 Expression*
4593 Unary_expression::do_import(Import* imp)
4595 Operator op;
4596 switch (imp->get_char())
4598 case '+':
4599 op = OPERATOR_PLUS;
4600 break;
4601 case '-':
4602 op = OPERATOR_MINUS;
4603 break;
4604 case '!':
4605 op = OPERATOR_NOT;
4606 break;
4607 case '^':
4608 op = OPERATOR_XOR;
4609 break;
4610 default:
4611 go_unreachable();
4613 imp->require_c_string(" ");
4614 Expression* expr = Expression::import_expression(imp);
4615 return Expression::make_unary(op, expr, imp->location());
4618 // Dump ast representation of an unary expression.
4620 void
4621 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4623 ast_dump_context->dump_operator(this->op_);
4624 ast_dump_context->ostream() << "(";
4625 ast_dump_context->dump_expression(this->expr_);
4626 ast_dump_context->ostream() << ") ";
4629 // Make a unary expression.
4631 Expression*
4632 Expression::make_unary(Operator op, Expression* expr, Location location)
4634 return new Unary_expression(op, expr, location);
4637 Expression*
4638 Expression::make_dereference(Expression* ptr,
4639 Nil_check_classification docheck,
4640 Location location)
4642 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4643 if (docheck == NIL_CHECK_NEEDED)
4644 deref->unary_expression()->set_requires_nil_check(true);
4645 else if (docheck == NIL_CHECK_NOT_NEEDED)
4646 deref->unary_expression()->set_requires_nil_check(false);
4647 return deref;
4650 // If this is an indirection through a pointer, return the expression
4651 // being pointed through. Otherwise return this.
4653 Expression*
4654 Expression::deref()
4656 if (this->classification_ == EXPRESSION_UNARY)
4658 Unary_expression* ue = static_cast<Unary_expression*>(this);
4659 if (ue->op() == OPERATOR_MULT)
4660 return ue->operand();
4662 return this;
4665 // Class Binary_expression.
4667 // Traversal.
4670 Binary_expression::do_traverse(Traverse* traverse)
4672 int t = Expression::traverse(&this->left_, traverse);
4673 if (t == TRAVERSE_EXIT)
4674 return TRAVERSE_EXIT;
4675 return Expression::traverse(&this->right_, traverse);
4678 // Return whether this expression may be used as a static initializer.
4680 bool
4681 Binary_expression::do_is_static_initializer() const
4683 if (!this->left_->is_static_initializer()
4684 || !this->right_->is_static_initializer())
4685 return false;
4687 // Addresses can be static initializers, but we can't implement
4688 // arbitray binary expressions of them.
4689 Unary_expression* lu = this->left_->unary_expression();
4690 Unary_expression* ru = this->right_->unary_expression();
4691 if (lu != NULL && lu->op() == OPERATOR_AND)
4693 if (ru != NULL && ru->op() == OPERATOR_AND)
4694 return this->op_ == OPERATOR_MINUS;
4695 else
4696 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4698 else if (ru != NULL && ru->op() == OPERATOR_AND)
4699 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4701 // Other cases should resolve in the backend.
4702 return true;
4705 // Return the type to use for a binary operation on operands of
4706 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4707 // such may be NULL or abstract.
4709 bool
4710 Binary_expression::operation_type(Operator op, Type* left_type,
4711 Type* right_type, Type** result_type)
4713 if (left_type != right_type
4714 && !left_type->is_abstract()
4715 && !right_type->is_abstract()
4716 && left_type->base() != right_type->base()
4717 && op != OPERATOR_LSHIFT
4718 && op != OPERATOR_RSHIFT)
4720 // May be a type error--let it be diagnosed elsewhere.
4721 return false;
4724 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4726 if (left_type->integer_type() != NULL)
4727 *result_type = left_type;
4728 else
4729 *result_type = Type::make_abstract_integer_type();
4731 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4732 *result_type = left_type;
4733 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4734 *result_type = right_type;
4735 else if (!left_type->is_abstract())
4736 *result_type = left_type;
4737 else if (!right_type->is_abstract())
4738 *result_type = right_type;
4739 else if (left_type->complex_type() != NULL)
4740 *result_type = left_type;
4741 else if (right_type->complex_type() != NULL)
4742 *result_type = right_type;
4743 else if (left_type->float_type() != NULL)
4744 *result_type = left_type;
4745 else if (right_type->float_type() != NULL)
4746 *result_type = right_type;
4747 else if (left_type->integer_type() != NULL
4748 && left_type->integer_type()->is_rune())
4749 *result_type = left_type;
4750 else if (right_type->integer_type() != NULL
4751 && right_type->integer_type()->is_rune())
4752 *result_type = right_type;
4753 else
4754 *result_type = left_type;
4756 return true;
4759 // Convert an integer comparison code and an operator to a boolean
4760 // value.
4762 bool
4763 Binary_expression::cmp_to_bool(Operator op, int cmp)
4765 switch (op)
4767 case OPERATOR_EQEQ:
4768 return cmp == 0;
4769 break;
4770 case OPERATOR_NOTEQ:
4771 return cmp != 0;
4772 break;
4773 case OPERATOR_LT:
4774 return cmp < 0;
4775 break;
4776 case OPERATOR_LE:
4777 return cmp <= 0;
4778 case OPERATOR_GT:
4779 return cmp > 0;
4780 case OPERATOR_GE:
4781 return cmp >= 0;
4782 default:
4783 go_unreachable();
4787 // Compare constants according to OP.
4789 bool
4790 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4791 Numeric_constant* right_nc,
4792 Location location, bool* result)
4794 Type* left_type = left_nc->type();
4795 Type* right_type = right_nc->type();
4797 Type* type;
4798 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4799 return false;
4801 // When comparing an untyped operand to a typed operand, we are
4802 // effectively coercing the untyped operand to the other operand's
4803 // type, so make sure that is valid.
4804 if (!left_nc->set_type(type, true, location)
4805 || !right_nc->set_type(type, true, location))
4806 return false;
4808 bool ret;
4809 int cmp;
4810 if (type->complex_type() != NULL)
4812 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4813 return false;
4814 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4816 else if (type->float_type() != NULL)
4817 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4818 else
4819 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4821 if (ret)
4822 *result = Binary_expression::cmp_to_bool(op, cmp);
4824 return ret;
4827 // Compare integer constants.
4829 bool
4830 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4831 const Numeric_constant* right_nc,
4832 int* cmp)
4834 mpz_t left_val;
4835 if (!left_nc->to_int(&left_val))
4836 return false;
4837 mpz_t right_val;
4838 if (!right_nc->to_int(&right_val))
4840 mpz_clear(left_val);
4841 return false;
4844 *cmp = mpz_cmp(left_val, right_val);
4846 mpz_clear(left_val);
4847 mpz_clear(right_val);
4849 return true;
4852 // Compare floating point constants.
4854 bool
4855 Binary_expression::compare_float(const Numeric_constant* left_nc,
4856 const Numeric_constant* right_nc,
4857 int* cmp)
4859 mpfr_t left_val;
4860 if (!left_nc->to_float(&left_val))
4861 return false;
4862 mpfr_t right_val;
4863 if (!right_nc->to_float(&right_val))
4865 mpfr_clear(left_val);
4866 return false;
4869 // We already coerced both operands to the same type. If that type
4870 // is not an abstract type, we need to round the values accordingly.
4871 Type* type = left_nc->type();
4872 if (!type->is_abstract() && type->float_type() != NULL)
4874 int bits = type->float_type()->bits();
4875 mpfr_prec_round(left_val, bits, GMP_RNDN);
4876 mpfr_prec_round(right_val, bits, GMP_RNDN);
4879 *cmp = mpfr_cmp(left_val, right_val);
4881 mpfr_clear(left_val);
4882 mpfr_clear(right_val);
4884 return true;
4887 // Compare complex constants. Complex numbers may only be compared
4888 // for equality.
4890 bool
4891 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4892 const Numeric_constant* right_nc,
4893 int* cmp)
4895 mpc_t left_val;
4896 if (!left_nc->to_complex(&left_val))
4897 return false;
4898 mpc_t right_val;
4899 if (!right_nc->to_complex(&right_val))
4901 mpc_clear(left_val);
4902 return false;
4905 // We already coerced both operands to the same type. If that type
4906 // is not an abstract type, we need to round the values accordingly.
4907 Type* type = left_nc->type();
4908 if (!type->is_abstract() && type->complex_type() != NULL)
4910 int bits = type->complex_type()->bits();
4911 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4912 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4913 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4914 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4917 *cmp = mpc_cmp(left_val, right_val) != 0;
4919 mpc_clear(left_val);
4920 mpc_clear(right_val);
4922 return true;
4925 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4926 // true if this could be done, false if not. Issue errors at LOCATION
4927 // as appropriate, and sets *ISSUED_ERROR if it did.
4929 bool
4930 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4931 Numeric_constant* right_nc,
4932 Location location, Numeric_constant* nc,
4933 bool* issued_error)
4935 *issued_error = false;
4936 switch (op)
4938 case OPERATOR_OROR:
4939 case OPERATOR_ANDAND:
4940 case OPERATOR_EQEQ:
4941 case OPERATOR_NOTEQ:
4942 case OPERATOR_LT:
4943 case OPERATOR_LE:
4944 case OPERATOR_GT:
4945 case OPERATOR_GE:
4946 // These return boolean values, not numeric.
4947 return false;
4948 default:
4949 break;
4952 Type* left_type = left_nc->type();
4953 Type* right_type = right_nc->type();
4955 Type* type;
4956 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4957 return false;
4959 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4961 // When combining an untyped operand with a typed operand, we are
4962 // effectively coercing the untyped operand to the other operand's
4963 // type, so make sure that is valid.
4964 if (!left_nc->set_type(type, true, location))
4965 return false;
4966 if (!is_shift && !right_nc->set_type(type, true, location))
4967 return false;
4968 if (is_shift
4969 && ((left_type->integer_type() == NULL
4970 && !left_type->is_abstract())
4971 || (right_type->integer_type() == NULL
4972 && !right_type->is_abstract())))
4973 return false;
4975 bool r;
4976 if (type->complex_type() != NULL)
4977 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4978 else if (type->float_type() != NULL)
4979 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4980 else
4981 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4983 if (r)
4985 r = nc->set_type(type, true, location);
4986 if (!r)
4987 *issued_error = true;
4990 return r;
4993 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4994 // integer operations. Return true if this could be done, false if
4995 // not.
4997 bool
4998 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4999 const Numeric_constant* right_nc,
5000 Location location, Numeric_constant* nc)
5002 mpz_t left_val;
5003 if (!left_nc->to_int(&left_val))
5004 return false;
5005 mpz_t right_val;
5006 if (!right_nc->to_int(&right_val))
5008 mpz_clear(left_val);
5009 return false;
5012 mpz_t val;
5013 mpz_init(val);
5015 switch (op)
5017 case OPERATOR_PLUS:
5018 mpz_add(val, left_val, right_val);
5019 if (mpz_sizeinbase(val, 2) > 0x100000)
5021 go_error_at(location, "constant addition overflow");
5022 nc->set_invalid();
5023 mpz_set_ui(val, 1);
5025 break;
5026 case OPERATOR_MINUS:
5027 mpz_sub(val, left_val, right_val);
5028 if (mpz_sizeinbase(val, 2) > 0x100000)
5030 go_error_at(location, "constant subtraction overflow");
5031 nc->set_invalid();
5032 mpz_set_ui(val, 1);
5034 break;
5035 case OPERATOR_OR:
5036 mpz_ior(val, left_val, right_val);
5037 break;
5038 case OPERATOR_XOR:
5039 mpz_xor(val, left_val, right_val);
5040 break;
5041 case OPERATOR_MULT:
5042 mpz_mul(val, left_val, right_val);
5043 if (mpz_sizeinbase(val, 2) > 0x100000)
5045 go_error_at(location, "constant multiplication overflow");
5046 nc->set_invalid();
5047 mpz_set_ui(val, 1);
5049 break;
5050 case OPERATOR_DIV:
5051 if (mpz_sgn(right_val) != 0)
5052 mpz_tdiv_q(val, left_val, right_val);
5053 else
5055 go_error_at(location, "division by zero");
5056 nc->set_invalid();
5057 mpz_set_ui(val, 0);
5059 break;
5060 case OPERATOR_MOD:
5061 if (mpz_sgn(right_val) != 0)
5062 mpz_tdiv_r(val, left_val, right_val);
5063 else
5065 go_error_at(location, "division by zero");
5066 nc->set_invalid();
5067 mpz_set_ui(val, 0);
5069 break;
5070 case OPERATOR_LSHIFT:
5072 unsigned long shift = mpz_get_ui(right_val);
5073 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5074 mpz_mul_2exp(val, left_val, shift);
5075 else
5077 go_error_at(location, "shift count overflow");
5078 nc->set_invalid();
5079 mpz_set_ui(val, 1);
5081 break;
5083 break;
5084 case OPERATOR_RSHIFT:
5086 unsigned long shift = mpz_get_ui(right_val);
5087 if (mpz_cmp_ui(right_val, shift) != 0)
5089 go_error_at(location, "shift count overflow");
5090 nc->set_invalid();
5091 mpz_set_ui(val, 1);
5093 else
5095 if (mpz_cmp_ui(left_val, 0) >= 0)
5096 mpz_tdiv_q_2exp(val, left_val, shift);
5097 else
5098 mpz_fdiv_q_2exp(val, left_val, shift);
5100 break;
5102 break;
5103 case OPERATOR_AND:
5104 mpz_and(val, left_val, right_val);
5105 break;
5106 case OPERATOR_BITCLEAR:
5108 mpz_t tval;
5109 mpz_init(tval);
5110 mpz_com(tval, right_val);
5111 mpz_and(val, left_val, tval);
5112 mpz_clear(tval);
5114 break;
5115 default:
5116 go_unreachable();
5119 mpz_clear(left_val);
5120 mpz_clear(right_val);
5122 if (left_nc->is_rune()
5123 || (op != OPERATOR_LSHIFT
5124 && op != OPERATOR_RSHIFT
5125 && right_nc->is_rune()))
5126 nc->set_rune(NULL, val);
5127 else
5128 nc->set_int(NULL, val);
5130 mpz_clear(val);
5132 return true;
5135 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5136 // floating point operations. Return true if this could be done,
5137 // false if not.
5139 bool
5140 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5141 const Numeric_constant* right_nc,
5142 Location location, Numeric_constant* nc)
5144 mpfr_t left_val;
5145 if (!left_nc->to_float(&left_val))
5146 return false;
5147 mpfr_t right_val;
5148 if (!right_nc->to_float(&right_val))
5150 mpfr_clear(left_val);
5151 return false;
5154 mpfr_t val;
5155 mpfr_init(val);
5157 bool ret = true;
5158 switch (op)
5160 case OPERATOR_PLUS:
5161 mpfr_add(val, left_val, right_val, GMP_RNDN);
5162 break;
5163 case OPERATOR_MINUS:
5164 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5165 break;
5166 case OPERATOR_OR:
5167 case OPERATOR_XOR:
5168 case OPERATOR_AND:
5169 case OPERATOR_BITCLEAR:
5170 case OPERATOR_MOD:
5171 case OPERATOR_LSHIFT:
5172 case OPERATOR_RSHIFT:
5173 mpfr_set_ui(val, 0, GMP_RNDN);
5174 ret = false;
5175 break;
5176 case OPERATOR_MULT:
5177 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5178 break;
5179 case OPERATOR_DIV:
5180 if (!mpfr_zero_p(right_val))
5181 mpfr_div(val, left_val, right_val, GMP_RNDN);
5182 else
5184 go_error_at(location, "division by zero");
5185 nc->set_invalid();
5186 mpfr_set_ui(val, 0, GMP_RNDN);
5188 break;
5189 default:
5190 go_unreachable();
5193 mpfr_clear(left_val);
5194 mpfr_clear(right_val);
5196 nc->set_float(NULL, val);
5197 mpfr_clear(val);
5199 return ret;
5202 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5203 // complex operations. Return true if this could be done, false if
5204 // not.
5206 bool
5207 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5208 const Numeric_constant* right_nc,
5209 Location location, Numeric_constant* nc)
5211 mpc_t left_val;
5212 if (!left_nc->to_complex(&left_val))
5213 return false;
5214 mpc_t right_val;
5215 if (!right_nc->to_complex(&right_val))
5217 mpc_clear(left_val);
5218 return false;
5221 mpc_t val;
5222 mpc_init2(val, mpc_precision);
5224 bool ret = true;
5225 switch (op)
5227 case OPERATOR_PLUS:
5228 mpc_add(val, left_val, right_val, MPC_RNDNN);
5229 break;
5230 case OPERATOR_MINUS:
5231 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5232 break;
5233 case OPERATOR_OR:
5234 case OPERATOR_XOR:
5235 case OPERATOR_AND:
5236 case OPERATOR_BITCLEAR:
5237 case OPERATOR_MOD:
5238 case OPERATOR_LSHIFT:
5239 case OPERATOR_RSHIFT:
5240 mpc_set_ui(val, 0, MPC_RNDNN);
5241 ret = false;
5242 break;
5243 case OPERATOR_MULT:
5244 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5245 break;
5246 case OPERATOR_DIV:
5247 if (mpc_cmp_si(right_val, 0) == 0)
5249 go_error_at(location, "division by zero");
5250 nc->set_invalid();
5251 mpc_set_ui(val, 0, MPC_RNDNN);
5252 break;
5254 mpc_div(val, left_val, right_val, MPC_RNDNN);
5255 break;
5256 default:
5257 go_unreachable();
5260 mpc_clear(left_val);
5261 mpc_clear(right_val);
5263 nc->set_complex(NULL, val);
5264 mpc_clear(val);
5266 return ret;
5269 // Lower a binary expression. We have to evaluate constant
5270 // expressions now, in order to implement Go's unlimited precision
5271 // constants.
5273 Expression*
5274 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5275 Statement_inserter* inserter, int)
5277 Location location = this->location();
5278 Operator op = this->op_;
5279 Expression* left = this->left_;
5280 Expression* right = this->right_;
5282 const bool is_comparison = (op == OPERATOR_EQEQ
5283 || op == OPERATOR_NOTEQ
5284 || op == OPERATOR_LT
5285 || op == OPERATOR_LE
5286 || op == OPERATOR_GT
5287 || op == OPERATOR_GE);
5289 // Numeric constant expressions.
5291 Numeric_constant left_nc;
5292 Numeric_constant right_nc;
5293 if (left->numeric_constant_value(&left_nc)
5294 && right->numeric_constant_value(&right_nc))
5296 if (is_comparison)
5298 bool result;
5299 if (!Binary_expression::compare_constant(op, &left_nc,
5300 &right_nc, location,
5301 &result))
5302 return this;
5303 return Expression::make_cast(Type::make_boolean_type(),
5304 Expression::make_boolean(result,
5305 location),
5306 location);
5308 else
5310 Numeric_constant nc;
5311 bool issued_error;
5312 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5313 location, &nc,
5314 &issued_error))
5316 if (issued_error)
5317 return Expression::make_error(location);
5318 return this;
5320 return nc.expression(location);
5325 // String constant expressions.
5326 if (left->type()->is_string_type() && right->type()->is_string_type())
5328 std::string left_string;
5329 std::string right_string;
5330 if (left->string_constant_value(&left_string)
5331 && right->string_constant_value(&right_string))
5333 if (op == OPERATOR_PLUS)
5334 return Expression::make_string(left_string + right_string,
5335 location);
5336 else if (is_comparison)
5338 int cmp = left_string.compare(right_string);
5339 bool r = Binary_expression::cmp_to_bool(op, cmp);
5340 return Expression::make_boolean(r, location);
5345 // Lower struct, array, and some interface comparisons.
5346 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5348 if (left->type()->struct_type() != NULL
5349 && right->type()->struct_type() != NULL)
5350 return this->lower_struct_comparison(gogo, inserter);
5351 else if (left->type()->array_type() != NULL
5352 && !left->type()->is_slice_type()
5353 && right->type()->array_type() != NULL
5354 && !right->type()->is_slice_type())
5355 return this->lower_array_comparison(gogo, inserter);
5356 else if ((left->type()->interface_type() != NULL
5357 && right->type()->interface_type() == NULL)
5358 || (left->type()->interface_type() == NULL
5359 && right->type()->interface_type() != NULL))
5360 return this->lower_interface_value_comparison(gogo, inserter);
5363 // Lower string concatenation to String_concat_expression, so that
5364 // we can group sequences of string additions.
5365 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5367 Expression_list* exprs;
5368 String_concat_expression* left_sce =
5369 this->left_->string_concat_expression();
5370 if (left_sce != NULL)
5371 exprs = left_sce->exprs();
5372 else
5374 exprs = new Expression_list();
5375 exprs->push_back(this->left_);
5378 String_concat_expression* right_sce =
5379 this->right_->string_concat_expression();
5380 if (right_sce != NULL)
5381 exprs->append(right_sce->exprs());
5382 else
5383 exprs->push_back(this->right_);
5385 return Expression::make_string_concat(exprs);
5388 return this;
5391 // Lower a struct comparison.
5393 Expression*
5394 Binary_expression::lower_struct_comparison(Gogo* gogo,
5395 Statement_inserter* inserter)
5397 Struct_type* st = this->left_->type()->struct_type();
5398 Struct_type* st2 = this->right_->type()->struct_type();
5399 if (st2 == NULL)
5400 return this;
5401 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5402 return this;
5403 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5404 this->right_->type(), NULL))
5405 return this;
5407 // See if we can compare using memcmp. As a heuristic, we use
5408 // memcmp rather than field references and comparisons if there are
5409 // more than two fields.
5410 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5411 return this->lower_compare_to_memcmp(gogo, inserter);
5413 Location loc = this->location();
5415 Expression* left = this->left_;
5416 Temporary_statement* left_temp = NULL;
5417 if (left->var_expression() == NULL
5418 && left->temporary_reference_expression() == NULL)
5420 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5421 inserter->insert(left_temp);
5422 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5425 Expression* right = this->right_;
5426 Temporary_statement* right_temp = NULL;
5427 if (right->var_expression() == NULL
5428 && right->temporary_reference_expression() == NULL)
5430 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5431 inserter->insert(right_temp);
5432 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5435 Expression* ret = Expression::make_boolean(true, loc);
5436 const Struct_field_list* fields = st->fields();
5437 unsigned int field_index = 0;
5438 for (Struct_field_list::const_iterator pf = fields->begin();
5439 pf != fields->end();
5440 ++pf, ++field_index)
5442 if (Gogo::is_sink_name(pf->field_name()))
5443 continue;
5445 if (field_index > 0)
5447 if (left_temp == NULL)
5448 left = left->copy();
5449 else
5450 left = Expression::make_temporary_reference(left_temp, loc);
5451 if (right_temp == NULL)
5452 right = right->copy();
5453 else
5454 right = Expression::make_temporary_reference(right_temp, loc);
5456 Expression* f1 = Expression::make_field_reference(left, field_index,
5457 loc);
5458 Expression* f2 = Expression::make_field_reference(right, field_index,
5459 loc);
5460 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5461 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5464 if (this->op_ == OPERATOR_NOTEQ)
5465 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5467 return ret;
5470 // Lower an array comparison.
5472 Expression*
5473 Binary_expression::lower_array_comparison(Gogo* gogo,
5474 Statement_inserter* inserter)
5476 Array_type* at = this->left_->type()->array_type();
5477 Array_type* at2 = this->right_->type()->array_type();
5478 if (at2 == NULL)
5479 return this;
5480 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5481 return this;
5482 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5483 this->right_->type(), NULL))
5484 return this;
5486 // Call memcmp directly if possible. This may let the middle-end
5487 // optimize the call.
5488 if (at->compare_is_identity(gogo))
5489 return this->lower_compare_to_memcmp(gogo, inserter);
5491 // Call the array comparison function.
5492 Named_object* hash_fn;
5493 Named_object* equal_fn;
5494 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5495 &hash_fn, &equal_fn);
5497 Location loc = this->location();
5499 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5501 Expression_list* args = new Expression_list();
5502 args->push_back(this->operand_address(inserter, this->left_));
5503 args->push_back(this->operand_address(inserter, this->right_));
5505 Expression* ret = Expression::make_call(func, args, false, loc);
5507 if (this->op_ == OPERATOR_NOTEQ)
5508 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5510 return ret;
5513 // Lower an interface to value comparison.
5515 Expression*
5516 Binary_expression::lower_interface_value_comparison(Gogo*,
5517 Statement_inserter* inserter)
5519 Type* left_type = this->left_->type();
5520 Type* right_type = this->right_->type();
5521 Interface_type* ift;
5522 if (left_type->interface_type() != NULL)
5524 ift = left_type->interface_type();
5525 if (!ift->implements_interface(right_type, NULL))
5526 return this;
5528 else
5530 ift = right_type->interface_type();
5531 if (!ift->implements_interface(left_type, NULL))
5532 return this;
5534 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5535 return this;
5537 Location loc = this->location();
5539 if (left_type->interface_type() == NULL
5540 && left_type->points_to() == NULL
5541 && !this->left_->is_addressable())
5543 Temporary_statement* temp =
5544 Statement::make_temporary(left_type, NULL, loc);
5545 inserter->insert(temp);
5546 this->left_ =
5547 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5550 if (right_type->interface_type() == NULL
5551 && right_type->points_to() == NULL
5552 && !this->right_->is_addressable())
5554 Temporary_statement* temp =
5555 Statement::make_temporary(right_type, NULL, loc);
5556 inserter->insert(temp);
5557 this->right_ =
5558 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5561 return this;
5564 // Lower a struct or array comparison to a call to memcmp.
5566 Expression*
5567 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5569 Location loc = this->location();
5571 Expression* a1 = this->operand_address(inserter, this->left_);
5572 Expression* a2 = this->operand_address(inserter, this->right_);
5573 Expression* len = Expression::make_type_info(this->left_->type(),
5574 TYPE_INFO_SIZE);
5576 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5577 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5578 return Expression::make_binary(this->op_, call, zero, loc);
5581 Expression*
5582 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5583 Statement_inserter* inserter)
5585 Location loc = this->location();
5586 if (this->left_->type()->is_error_type()
5587 || this->right_->type()->is_error_type()
5588 || this->left_->is_error_expression()
5589 || this->right_->is_error_expression())
5591 go_assert(saw_errors());
5592 return Expression::make_error(loc);
5595 Temporary_statement* temp;
5597 Type* left_type = this->left_->type();
5598 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5599 || this->op_ == OPERATOR_RSHIFT);
5600 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5601 left_type->integer_type() != NULL)
5602 || this->op_ == OPERATOR_MOD);
5604 if (is_shift_op
5605 || (is_idiv_op
5606 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5608 if (!this->left_->is_variable() && !this->left_->is_constant())
5610 temp = Statement::make_temporary(NULL, this->left_, loc);
5611 inserter->insert(temp);
5612 this->left_ = Expression::make_temporary_reference(temp, loc);
5614 if (!this->right_->is_variable() && !this->right_->is_constant())
5616 temp =
5617 Statement::make_temporary(NULL, this->right_, loc);
5618 this->right_ = Expression::make_temporary_reference(temp, loc);
5619 inserter->insert(temp);
5622 return this;
5626 // Return the address of EXPR, cast to unsafe.Pointer.
5628 Expression*
5629 Binary_expression::operand_address(Statement_inserter* inserter,
5630 Expression* expr)
5632 Location loc = this->location();
5634 if (!expr->is_addressable())
5636 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5637 loc);
5638 inserter->insert(temp);
5639 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5641 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5642 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5643 Type* void_type = Type::make_void_type();
5644 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5645 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5648 // Return the numeric constant value, if it has one.
5650 bool
5651 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5653 Numeric_constant left_nc;
5654 if (!this->left_->numeric_constant_value(&left_nc))
5655 return false;
5656 Numeric_constant right_nc;
5657 if (!this->right_->numeric_constant_value(&right_nc))
5658 return false;
5659 bool issued_error;
5660 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5661 this->location(), nc, &issued_error);
5664 // Note that the value is being discarded.
5666 bool
5667 Binary_expression::do_discarding_value()
5669 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5670 return this->right_->discarding_value();
5671 else
5673 this->unused_value_error();
5674 return false;
5678 // Get type.
5680 Type*
5681 Binary_expression::do_type()
5683 if (this->classification() == EXPRESSION_ERROR)
5684 return Type::make_error_type();
5686 switch (this->op_)
5688 case OPERATOR_EQEQ:
5689 case OPERATOR_NOTEQ:
5690 case OPERATOR_LT:
5691 case OPERATOR_LE:
5692 case OPERATOR_GT:
5693 case OPERATOR_GE:
5694 if (this->type_ == NULL)
5695 this->type_ = Type::make_boolean_type();
5696 return this->type_;
5698 case OPERATOR_PLUS:
5699 case OPERATOR_MINUS:
5700 case OPERATOR_OR:
5701 case OPERATOR_XOR:
5702 case OPERATOR_MULT:
5703 case OPERATOR_DIV:
5704 case OPERATOR_MOD:
5705 case OPERATOR_AND:
5706 case OPERATOR_BITCLEAR:
5707 case OPERATOR_OROR:
5708 case OPERATOR_ANDAND:
5710 Type* type;
5711 if (!Binary_expression::operation_type(this->op_,
5712 this->left_->type(),
5713 this->right_->type(),
5714 &type))
5715 return Type::make_error_type();
5716 return type;
5719 case OPERATOR_LSHIFT:
5720 case OPERATOR_RSHIFT:
5721 return this->left_->type();
5723 default:
5724 go_unreachable();
5728 // Set type for a binary expression.
5730 void
5731 Binary_expression::do_determine_type(const Type_context* context)
5733 Type* tleft = this->left_->type();
5734 Type* tright = this->right_->type();
5736 // Both sides should have the same type, except for the shift
5737 // operations. For a comparison, we should ignore the incoming
5738 // type.
5740 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5741 || this->op_ == OPERATOR_RSHIFT);
5743 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5744 || this->op_ == OPERATOR_NOTEQ
5745 || this->op_ == OPERATOR_LT
5746 || this->op_ == OPERATOR_LE
5747 || this->op_ == OPERATOR_GT
5748 || this->op_ == OPERATOR_GE);
5750 // For constant expressions, the context of the result is not useful in
5751 // determining the types of the operands. It is only legal to use abstract
5752 // boolean, numeric, and string constants as operands where it is legal to
5753 // use non-abstract boolean, numeric, and string constants, respectively.
5754 // Any issues with the operation will be resolved in the check_types pass.
5755 bool is_constant_expr = (this->left_->is_constant()
5756 && this->right_->is_constant());
5758 Type_context subcontext(*context);
5760 if (is_constant_expr && !is_shift_op)
5762 subcontext.type = NULL;
5763 subcontext.may_be_abstract = true;
5765 else if (is_comparison)
5767 // In a comparison, the context does not determine the types of
5768 // the operands.
5769 subcontext.type = NULL;
5772 // Set the context for the left hand operand.
5773 if (is_shift_op)
5775 // The right hand operand of a shift plays no role in
5776 // determining the type of the left hand operand.
5778 else if (!tleft->is_abstract())
5779 subcontext.type = tleft;
5780 else if (!tright->is_abstract())
5781 subcontext.type = tright;
5782 else if (subcontext.type == NULL)
5784 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5785 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5786 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5788 // Both sides have an abstract integer, abstract float, or
5789 // abstract complex type. Just let CONTEXT determine
5790 // whether they may remain abstract or not.
5792 else if (tleft->complex_type() != NULL)
5793 subcontext.type = tleft;
5794 else if (tright->complex_type() != NULL)
5795 subcontext.type = tright;
5796 else if (tleft->float_type() != NULL)
5797 subcontext.type = tleft;
5798 else if (tright->float_type() != NULL)
5799 subcontext.type = tright;
5800 else
5801 subcontext.type = tleft;
5803 if (subcontext.type != NULL && !context->may_be_abstract)
5804 subcontext.type = subcontext.type->make_non_abstract_type();
5807 this->left_->determine_type(&subcontext);
5809 if (is_shift_op)
5811 // We may have inherited an unusable type for the shift operand.
5812 // Give a useful error if that happened.
5813 if (tleft->is_abstract()
5814 && subcontext.type != NULL
5815 && !subcontext.may_be_abstract
5816 && subcontext.type->interface_type() == NULL
5817 && subcontext.type->integer_type() == NULL)
5818 this->report_error(("invalid context-determined non-integer type "
5819 "for left operand of shift"));
5821 // The context for the right hand operand is the same as for the
5822 // left hand operand, except for a shift operator.
5823 subcontext.type = Type::lookup_integer_type("uint");
5824 subcontext.may_be_abstract = false;
5827 this->right_->determine_type(&subcontext);
5829 if (is_comparison)
5831 if (this->type_ != NULL && !this->type_->is_abstract())
5833 else if (context->type != NULL && context->type->is_boolean_type())
5834 this->type_ = context->type;
5835 else if (!context->may_be_abstract)
5836 this->type_ = Type::lookup_bool_type();
5840 // Report an error if the binary operator OP does not support TYPE.
5841 // OTYPE is the type of the other operand. Return whether the
5842 // operation is OK. This should not be used for shift.
5844 bool
5845 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5846 Location location)
5848 switch (op)
5850 case OPERATOR_OROR:
5851 case OPERATOR_ANDAND:
5852 if (!type->is_boolean_type()
5853 || !otype->is_boolean_type())
5855 go_error_at(location, "expected boolean type");
5856 return false;
5858 break;
5860 case OPERATOR_EQEQ:
5861 case OPERATOR_NOTEQ:
5863 std::string reason;
5864 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5866 go_error_at(location, "%s", reason.c_str());
5867 return false;
5870 break;
5872 case OPERATOR_LT:
5873 case OPERATOR_LE:
5874 case OPERATOR_GT:
5875 case OPERATOR_GE:
5877 std::string reason;
5878 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5880 go_error_at(location, "%s", reason.c_str());
5881 return false;
5884 break;
5886 case OPERATOR_PLUS:
5887 case OPERATOR_PLUSEQ:
5888 if ((!type->is_numeric_type() && !type->is_string_type())
5889 || (!otype->is_numeric_type() && !otype->is_string_type()))
5891 go_error_at(location,
5892 "expected integer, floating, complex, or string type");
5893 return false;
5895 break;
5897 case OPERATOR_MINUS:
5898 case OPERATOR_MINUSEQ:
5899 case OPERATOR_MULT:
5900 case OPERATOR_MULTEQ:
5901 case OPERATOR_DIV:
5902 case OPERATOR_DIVEQ:
5903 if (!type->is_numeric_type() || !otype->is_numeric_type())
5905 go_error_at(location, "expected integer, floating, or complex type");
5906 return false;
5908 break;
5910 case OPERATOR_MOD:
5911 case OPERATOR_MODEQ:
5912 case OPERATOR_OR:
5913 case OPERATOR_OREQ:
5914 case OPERATOR_AND:
5915 case OPERATOR_ANDEQ:
5916 case OPERATOR_XOR:
5917 case OPERATOR_XOREQ:
5918 case OPERATOR_BITCLEAR:
5919 case OPERATOR_BITCLEAREQ:
5920 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5922 go_error_at(location, "expected integer type");
5923 return false;
5925 break;
5927 default:
5928 go_unreachable();
5931 return true;
5934 // Check types.
5936 void
5937 Binary_expression::do_check_types(Gogo*)
5939 if (this->classification() == EXPRESSION_ERROR)
5940 return;
5942 Type* left_type = this->left_->type();
5943 Type* right_type = this->right_->type();
5944 if (left_type->is_error() || right_type->is_error())
5946 this->set_is_error();
5947 return;
5950 if (this->op_ == OPERATOR_EQEQ
5951 || this->op_ == OPERATOR_NOTEQ
5952 || this->op_ == OPERATOR_LT
5953 || this->op_ == OPERATOR_LE
5954 || this->op_ == OPERATOR_GT
5955 || this->op_ == OPERATOR_GE)
5957 if (left_type->is_nil_type() && right_type->is_nil_type())
5959 this->report_error(_("invalid comparison of nil with nil"));
5960 return;
5962 if (!Type::are_assignable(left_type, right_type, NULL)
5963 && !Type::are_assignable(right_type, left_type, NULL))
5965 this->report_error(_("incompatible types in binary expression"));
5966 return;
5968 if (!Binary_expression::check_operator_type(this->op_, left_type,
5969 right_type,
5970 this->location())
5971 || !Binary_expression::check_operator_type(this->op_, right_type,
5972 left_type,
5973 this->location()))
5975 this->set_is_error();
5976 return;
5979 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5981 if (!Type::are_compatible_for_binop(left_type, right_type))
5983 this->report_error(_("incompatible types in binary expression"));
5984 return;
5986 if (!Binary_expression::check_operator_type(this->op_, left_type,
5987 right_type,
5988 this->location()))
5990 this->set_is_error();
5991 return;
5993 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5995 // Division by a zero integer constant is an error.
5996 Numeric_constant rconst;
5997 unsigned long rval;
5998 if (left_type->integer_type() != NULL
5999 && this->right_->numeric_constant_value(&rconst)
6000 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6001 && rval == 0)
6003 this->report_error(_("integer division by zero"));
6004 return;
6008 else
6010 if (left_type->integer_type() == NULL)
6011 this->report_error(_("shift of non-integer operand"));
6013 if (right_type->is_string_type())
6014 this->report_error(_("shift count not unsigned integer"));
6015 else if (!right_type->is_abstract()
6016 && (right_type->integer_type() == NULL
6017 || !right_type->integer_type()->is_unsigned()))
6018 this->report_error(_("shift count not unsigned integer"));
6019 else
6021 Numeric_constant nc;
6022 if (this->right_->numeric_constant_value(&nc))
6024 mpz_t val;
6025 if (!nc.to_int(&val))
6026 this->report_error(_("shift count not unsigned integer"));
6027 else
6029 if (mpz_sgn(val) < 0)
6031 this->report_error(_("negative shift count"));
6032 Location rloc = this->right_->location();
6033 this->right_ = Expression::make_integer_ul(0, right_type,
6034 rloc);
6036 mpz_clear(val);
6043 // Get the backend representation for a binary expression.
6045 Bexpression*
6046 Binary_expression::do_get_backend(Translate_context* context)
6048 Gogo* gogo = context->gogo();
6049 Location loc = this->location();
6050 Type* left_type = this->left_->type();
6051 Type* right_type = this->right_->type();
6053 bool use_left_type = true;
6054 bool is_shift_op = false;
6055 bool is_idiv_op = false;
6056 switch (this->op_)
6058 case OPERATOR_EQEQ:
6059 case OPERATOR_NOTEQ:
6060 case OPERATOR_LT:
6061 case OPERATOR_LE:
6062 case OPERATOR_GT:
6063 case OPERATOR_GE:
6064 return Expression::comparison(context, this->type_, this->op_,
6065 this->left_, this->right_, loc);
6067 case OPERATOR_OROR:
6068 case OPERATOR_ANDAND:
6069 use_left_type = false;
6070 break;
6071 case OPERATOR_PLUS:
6072 case OPERATOR_MINUS:
6073 case OPERATOR_OR:
6074 case OPERATOR_XOR:
6075 case OPERATOR_MULT:
6076 break;
6077 case OPERATOR_DIV:
6078 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6079 break;
6080 // Fall through.
6081 case OPERATOR_MOD:
6082 is_idiv_op = true;
6083 break;
6084 case OPERATOR_LSHIFT:
6085 case OPERATOR_RSHIFT:
6086 is_shift_op = true;
6087 break;
6088 case OPERATOR_BITCLEAR:
6089 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6090 case OPERATOR_AND:
6091 break;
6092 default:
6093 go_unreachable();
6096 // The only binary operation for string is +, and that should have
6097 // been converted to a String_concat_expression in do_lower.
6098 go_assert(!left_type->is_string_type());
6100 // For complex division Go might want slightly different results than the
6101 // backend implementation provides, so we have our own runtime routine.
6102 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6104 Runtime::Function complex_code;
6105 switch (this->left_->type()->complex_type()->bits())
6107 case 64:
6108 complex_code = Runtime::COMPLEX64_DIV;
6109 break;
6110 case 128:
6111 complex_code = Runtime::COMPLEX128_DIV;
6112 break;
6113 default:
6114 go_unreachable();
6116 Expression* complex_div =
6117 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6118 return complex_div->get_backend(context);
6121 Bexpression* left = this->left_->get_backend(context);
6122 Bexpression* right = this->right_->get_backend(context);
6124 Type* type = use_left_type ? left_type : right_type;
6125 Btype* btype = type->get_backend(gogo);
6127 Bexpression* ret =
6128 gogo->backend()->binary_expression(this->op_, left, right, loc);
6129 ret = gogo->backend()->convert_expression(btype, ret, loc);
6131 // Initialize overflow constants.
6132 Bexpression* overflow;
6133 mpz_t zero;
6134 mpz_init_set_ui(zero, 0UL);
6135 mpz_t one;
6136 mpz_init_set_ui(one, 1UL);
6137 mpz_t neg_one;
6138 mpz_init_set_si(neg_one, -1);
6140 Btype* left_btype = left_type->get_backend(gogo);
6141 Btype* right_btype = right_type->get_backend(gogo);
6143 // In Go, a shift larger than the size of the type is well-defined.
6144 // This is not true in C, so we need to insert a conditional.
6145 if (is_shift_op)
6147 go_assert(left_type->integer_type() != NULL);
6149 int bits = left_type->integer_type()->bits();
6151 Numeric_constant nc;
6152 unsigned long ul;
6153 if (!this->right_->numeric_constant_value(&nc)
6154 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6155 || ul >= static_cast<unsigned long>(bits))
6157 mpz_t bitsval;
6158 mpz_init_set_ui(bitsval, bits);
6159 Bexpression* bits_expr =
6160 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6161 Bexpression* compare =
6162 gogo->backend()->binary_expression(OPERATOR_LT,
6163 right, bits_expr, loc);
6165 Bexpression* zero_expr =
6166 gogo->backend()->integer_constant_expression(left_btype, zero);
6167 overflow = zero_expr;
6168 Bfunction* bfn = context->function()->func_value()->get_decl();
6169 if (this->op_ == OPERATOR_RSHIFT
6170 && !left_type->integer_type()->is_unsigned())
6172 Bexpression* neg_expr =
6173 gogo->backend()->binary_expression(OPERATOR_LT, left,
6174 zero_expr, loc);
6175 Bexpression* neg_one_expr =
6176 gogo->backend()->integer_constant_expression(left_btype,
6177 neg_one);
6178 overflow = gogo->backend()->conditional_expression(bfn,
6179 btype,
6180 neg_expr,
6181 neg_one_expr,
6182 zero_expr,
6183 loc);
6185 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6186 ret, overflow, loc);
6187 mpz_clear(bitsval);
6191 // Add checks for division by zero and division overflow as needed.
6192 if (is_idiv_op)
6194 if (gogo->check_divide_by_zero())
6196 // right == 0
6197 Bexpression* zero_expr =
6198 gogo->backend()->integer_constant_expression(right_btype, zero);
6199 Bexpression* check =
6200 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6201 right, zero_expr, loc);
6203 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6204 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6205 Bexpression* crash = gogo->runtime_error(errcode,
6206 loc)->get_backend(context);
6208 // right == 0 ? (__go_runtime_error(...), 0) : ret
6209 Bfunction* bfn = context->function()->func_value()->get_decl();
6210 ret = gogo->backend()->conditional_expression(bfn, btype,
6211 check, crash,
6212 ret, loc);
6215 if (gogo->check_divide_overflow())
6217 // right == -1
6218 // FIXME: It would be nice to say that this test is expected
6219 // to return false.
6221 Bexpression* neg_one_expr =
6222 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6223 Bexpression* check =
6224 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6225 right, neg_one_expr, loc);
6227 Bexpression* zero_expr =
6228 gogo->backend()->integer_constant_expression(btype, zero);
6229 Bexpression* one_expr =
6230 gogo->backend()->integer_constant_expression(btype, one);
6231 Bfunction* bfn = context->function()->func_value()->get_decl();
6233 if (type->integer_type()->is_unsigned())
6235 // An unsigned -1 is the largest possible number, so
6236 // dividing is always 1 or 0.
6238 Bexpression* cmp =
6239 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6240 left, right, loc);
6241 if (this->op_ == OPERATOR_DIV)
6242 overflow =
6243 gogo->backend()->conditional_expression(bfn, btype, cmp,
6244 one_expr, zero_expr,
6245 loc);
6246 else
6247 overflow =
6248 gogo->backend()->conditional_expression(bfn, btype, cmp,
6249 zero_expr, left,
6250 loc);
6252 else
6254 // Computing left / -1 is the same as computing - left,
6255 // which does not overflow since Go sets -fwrapv.
6256 if (this->op_ == OPERATOR_DIV)
6258 Expression* negate_expr =
6259 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6260 overflow = negate_expr->get_backend(context);
6262 else
6263 overflow = zero_expr;
6265 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6267 // right == -1 ? - left : ret
6268 ret = gogo->backend()->conditional_expression(bfn, btype,
6269 check, overflow,
6270 ret, loc);
6274 mpz_clear(zero);
6275 mpz_clear(one);
6276 mpz_clear(neg_one);
6277 return ret;
6280 // Export a binary expression.
6282 void
6283 Binary_expression::do_export(Export* exp) const
6285 exp->write_c_string("(");
6286 this->left_->export_expression(exp);
6287 switch (this->op_)
6289 case OPERATOR_OROR:
6290 exp->write_c_string(" || ");
6291 break;
6292 case OPERATOR_ANDAND:
6293 exp->write_c_string(" && ");
6294 break;
6295 case OPERATOR_EQEQ:
6296 exp->write_c_string(" == ");
6297 break;
6298 case OPERATOR_NOTEQ:
6299 exp->write_c_string(" != ");
6300 break;
6301 case OPERATOR_LT:
6302 exp->write_c_string(" < ");
6303 break;
6304 case OPERATOR_LE:
6305 exp->write_c_string(" <= ");
6306 break;
6307 case OPERATOR_GT:
6308 exp->write_c_string(" > ");
6309 break;
6310 case OPERATOR_GE:
6311 exp->write_c_string(" >= ");
6312 break;
6313 case OPERATOR_PLUS:
6314 exp->write_c_string(" + ");
6315 break;
6316 case OPERATOR_MINUS:
6317 exp->write_c_string(" - ");
6318 break;
6319 case OPERATOR_OR:
6320 exp->write_c_string(" | ");
6321 break;
6322 case OPERATOR_XOR:
6323 exp->write_c_string(" ^ ");
6324 break;
6325 case OPERATOR_MULT:
6326 exp->write_c_string(" * ");
6327 break;
6328 case OPERATOR_DIV:
6329 exp->write_c_string(" / ");
6330 break;
6331 case OPERATOR_MOD:
6332 exp->write_c_string(" % ");
6333 break;
6334 case OPERATOR_LSHIFT:
6335 exp->write_c_string(" << ");
6336 break;
6337 case OPERATOR_RSHIFT:
6338 exp->write_c_string(" >> ");
6339 break;
6340 case OPERATOR_AND:
6341 exp->write_c_string(" & ");
6342 break;
6343 case OPERATOR_BITCLEAR:
6344 exp->write_c_string(" &^ ");
6345 break;
6346 default:
6347 go_unreachable();
6349 this->right_->export_expression(exp);
6350 exp->write_c_string(")");
6353 // Import a binary expression.
6355 Expression*
6356 Binary_expression::do_import(Import* imp)
6358 imp->require_c_string("(");
6360 Expression* left = Expression::import_expression(imp);
6362 Operator op;
6363 if (imp->match_c_string(" || "))
6365 op = OPERATOR_OROR;
6366 imp->advance(4);
6368 else if (imp->match_c_string(" && "))
6370 op = OPERATOR_ANDAND;
6371 imp->advance(4);
6373 else if (imp->match_c_string(" == "))
6375 op = OPERATOR_EQEQ;
6376 imp->advance(4);
6378 else if (imp->match_c_string(" != "))
6380 op = OPERATOR_NOTEQ;
6381 imp->advance(4);
6383 else if (imp->match_c_string(" < "))
6385 op = OPERATOR_LT;
6386 imp->advance(3);
6388 else if (imp->match_c_string(" <= "))
6390 op = OPERATOR_LE;
6391 imp->advance(4);
6393 else if (imp->match_c_string(" > "))
6395 op = OPERATOR_GT;
6396 imp->advance(3);
6398 else if (imp->match_c_string(" >= "))
6400 op = OPERATOR_GE;
6401 imp->advance(4);
6403 else if (imp->match_c_string(" + "))
6405 op = OPERATOR_PLUS;
6406 imp->advance(3);
6408 else if (imp->match_c_string(" - "))
6410 op = OPERATOR_MINUS;
6411 imp->advance(3);
6413 else if (imp->match_c_string(" | "))
6415 op = OPERATOR_OR;
6416 imp->advance(3);
6418 else if (imp->match_c_string(" ^ "))
6420 op = OPERATOR_XOR;
6421 imp->advance(3);
6423 else if (imp->match_c_string(" * "))
6425 op = OPERATOR_MULT;
6426 imp->advance(3);
6428 else if (imp->match_c_string(" / "))
6430 op = OPERATOR_DIV;
6431 imp->advance(3);
6433 else if (imp->match_c_string(" % "))
6435 op = OPERATOR_MOD;
6436 imp->advance(3);
6438 else if (imp->match_c_string(" << "))
6440 op = OPERATOR_LSHIFT;
6441 imp->advance(4);
6443 else if (imp->match_c_string(" >> "))
6445 op = OPERATOR_RSHIFT;
6446 imp->advance(4);
6448 else if (imp->match_c_string(" & "))
6450 op = OPERATOR_AND;
6451 imp->advance(3);
6453 else if (imp->match_c_string(" &^ "))
6455 op = OPERATOR_BITCLEAR;
6456 imp->advance(4);
6458 else
6460 go_error_at(imp->location(), "unrecognized binary operator");
6461 return Expression::make_error(imp->location());
6464 Expression* right = Expression::import_expression(imp);
6466 imp->require_c_string(")");
6468 return Expression::make_binary(op, left, right, imp->location());
6471 // Dump ast representation of a binary expression.
6473 void
6474 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6476 ast_dump_context->ostream() << "(";
6477 ast_dump_context->dump_expression(this->left_);
6478 ast_dump_context->ostream() << " ";
6479 ast_dump_context->dump_operator(this->op_);
6480 ast_dump_context->ostream() << " ";
6481 ast_dump_context->dump_expression(this->right_);
6482 ast_dump_context->ostream() << ") ";
6485 // Make a binary expression.
6487 Expression*
6488 Expression::make_binary(Operator op, Expression* left, Expression* right,
6489 Location location)
6491 return new Binary_expression(op, left, right, location);
6494 // Implement a comparison.
6496 Bexpression*
6497 Expression::comparison(Translate_context* context, Type* result_type,
6498 Operator op, Expression* left, Expression* right,
6499 Location location)
6501 Type* left_type = left->type();
6502 Type* right_type = right->type();
6504 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6506 if (left_type->is_string_type() && right_type->is_string_type())
6508 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6510 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6511 left, right);
6512 right = Expression::make_boolean(true, location);
6514 else
6516 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6517 left, right);
6518 right = zexpr;
6521 else if ((left_type->interface_type() != NULL
6522 && right_type->interface_type() == NULL
6523 && !right_type->is_nil_type())
6524 || (left_type->interface_type() == NULL
6525 && !left_type->is_nil_type()
6526 && right_type->interface_type() != NULL))
6528 // Comparing an interface value to a non-interface value.
6529 if (left_type->interface_type() == NULL)
6531 std::swap(left_type, right_type);
6532 std::swap(left, right);
6535 // The right operand is not an interface. We need to take its
6536 // address if it is not a pointer.
6537 Expression* pointer_arg = NULL;
6538 if (right_type->points_to() != NULL)
6539 pointer_arg = right;
6540 else
6542 go_assert(right->is_addressable());
6543 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6544 location);
6547 Expression* descriptor =
6548 Expression::make_type_descriptor(right_type, location);
6549 left =
6550 Runtime::make_call((left_type->interface_type()->is_empty()
6551 ? Runtime::EFACEVALEQ
6552 : Runtime::IFACEVALEQ),
6553 location, 3, left, descriptor,
6554 pointer_arg);
6555 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6556 right = Expression::make_boolean(true, location);
6558 else if (left_type->interface_type() != NULL
6559 && right_type->interface_type() != NULL)
6561 Runtime::Function compare_function;
6562 if (left_type->interface_type()->is_empty()
6563 && right_type->interface_type()->is_empty())
6564 compare_function = Runtime::EFACEEQ;
6565 else if (!left_type->interface_type()->is_empty()
6566 && !right_type->interface_type()->is_empty())
6567 compare_function = Runtime::IFACEEQ;
6568 else
6570 if (left_type->interface_type()->is_empty())
6572 std::swap(left_type, right_type);
6573 std::swap(left, right);
6575 go_assert(!left_type->interface_type()->is_empty());
6576 go_assert(right_type->interface_type()->is_empty());
6577 compare_function = Runtime::IFACEEFACEEQ;
6580 left = Runtime::make_call(compare_function, location, 2, left, right);
6581 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6582 right = Expression::make_boolean(true, location);
6585 if (left_type->is_nil_type()
6586 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6588 std::swap(left_type, right_type);
6589 std::swap(left, right);
6592 if (right_type->is_nil_type())
6594 right = Expression::make_nil(location);
6595 if (left_type->array_type() != NULL
6596 && left_type->array_type()->length() == NULL)
6598 Array_type* at = left_type->array_type();
6599 bool is_lvalue = false;
6600 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6602 else if (left_type->interface_type() != NULL)
6604 // An interface is nil if the first field is nil.
6605 left = Expression::make_field_reference(left, 0, location);
6609 Bexpression* left_bexpr = left->get_backend(context);
6610 Bexpression* right_bexpr = right->get_backend(context);
6612 Gogo* gogo = context->gogo();
6613 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6614 right_bexpr, location);
6615 if (result_type != NULL)
6616 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6617 ret, location);
6618 return ret;
6621 // Class String_concat_expression.
6623 bool
6624 String_concat_expression::do_is_constant() const
6626 for (Expression_list::const_iterator pe = this->exprs_->begin();
6627 pe != this->exprs_->end();
6628 ++pe)
6630 if (!(*pe)->is_constant())
6631 return false;
6633 return true;
6636 bool
6637 String_concat_expression::do_is_static_initializer() const
6639 for (Expression_list::const_iterator pe = this->exprs_->begin();
6640 pe != this->exprs_->end();
6641 ++pe)
6643 if (!(*pe)->is_static_initializer())
6644 return false;
6646 return true;
6649 Type*
6650 String_concat_expression::do_type()
6652 Type* t = this->exprs_->front()->type();
6653 Expression_list::iterator pe = this->exprs_->begin();
6654 ++pe;
6655 for (; pe != this->exprs_->end(); ++pe)
6657 Type* t1;
6658 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6659 (*pe)->type(),
6660 &t1))
6661 return Type::make_error_type();
6662 t = t1;
6664 return t;
6667 void
6668 String_concat_expression::do_determine_type(const Type_context* context)
6670 Type_context subcontext(*context);
6671 for (Expression_list::iterator pe = this->exprs_->begin();
6672 pe != this->exprs_->end();
6673 ++pe)
6675 Type* t = (*pe)->type();
6676 if (!t->is_abstract())
6678 subcontext.type = t;
6679 break;
6682 if (subcontext.type == NULL)
6683 subcontext.type = this->exprs_->front()->type();
6684 for (Expression_list::iterator pe = this->exprs_->begin();
6685 pe != this->exprs_->end();
6686 ++pe)
6687 (*pe)->determine_type(&subcontext);
6690 void
6691 String_concat_expression::do_check_types(Gogo*)
6693 if (this->is_error_expression())
6694 return;
6695 Type* t = this->exprs_->front()->type();
6696 if (t->is_error())
6698 this->set_is_error();
6699 return;
6701 Expression_list::iterator pe = this->exprs_->begin();
6702 ++pe;
6703 for (; pe != this->exprs_->end(); ++pe)
6705 Type* t1 = (*pe)->type();
6706 if (!Type::are_compatible_for_binop(t, t1))
6708 this->report_error("incompatible types in binary expression");
6709 return;
6711 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6712 this->location()))
6714 this->set_is_error();
6715 return;
6720 Expression*
6721 String_concat_expression::do_flatten(Gogo*, Named_object*,
6722 Statement_inserter*)
6724 if (this->is_error_expression())
6725 return this;
6726 Location loc = this->location();
6727 Type* type = this->type();
6728 Expression* nil_arg = Expression::make_nil(loc);
6729 Expression* call;
6730 switch (this->exprs_->size())
6732 case 0: case 1:
6733 go_unreachable();
6735 case 2: case 3: case 4: case 5:
6737 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6738 NULL, loc);
6739 Array_type* arg_type = Type::make_array_type(type, len);
6740 arg_type->set_is_array_incomparable();
6741 Expression* arg =
6742 Expression::make_array_composite_literal(arg_type, this->exprs_,
6743 loc);
6744 Runtime::Function code;
6745 switch (this->exprs_->size())
6747 default:
6748 go_unreachable();
6749 case 2:
6750 code = Runtime::CONCATSTRING2;
6751 break;
6752 case 3:
6753 code = Runtime::CONCATSTRING3;
6754 break;
6755 case 4:
6756 code = Runtime::CONCATSTRING4;
6757 break;
6758 case 5:
6759 code = Runtime::CONCATSTRING5;
6760 break;
6762 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6764 break;
6766 default:
6768 Type* arg_type = Type::make_array_type(type, NULL);
6769 Slice_construction_expression* sce =
6770 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6771 loc);
6772 sce->set_storage_does_not_escape();
6773 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6774 sce);
6776 break;
6779 return Expression::make_cast(type, call, loc);
6782 void
6783 String_concat_expression::do_dump_expression(
6784 Ast_dump_context* ast_dump_context) const
6786 ast_dump_context->ostream() << "concat(";
6787 ast_dump_context->dump_expression_list(this->exprs_, false);
6788 ast_dump_context->ostream() << ")";
6791 Expression*
6792 Expression::make_string_concat(Expression_list* exprs)
6794 return new String_concat_expression(exprs);
6797 // Class Bound_method_expression.
6799 // Traversal.
6802 Bound_method_expression::do_traverse(Traverse* traverse)
6804 return Expression::traverse(&this->expr_, traverse);
6807 // Return the type of a bound method expression. The type of this
6808 // object is simply the type of the method with no receiver.
6810 Type*
6811 Bound_method_expression::do_type()
6813 Named_object* fn = this->method_->named_object();
6814 Function_type* fntype;
6815 if (fn->is_function())
6816 fntype = fn->func_value()->type();
6817 else if (fn->is_function_declaration())
6818 fntype = fn->func_declaration_value()->type();
6819 else
6820 return Type::make_error_type();
6821 return fntype->copy_without_receiver();
6824 // Determine the types of a method expression.
6826 void
6827 Bound_method_expression::do_determine_type(const Type_context*)
6829 Named_object* fn = this->method_->named_object();
6830 Function_type* fntype;
6831 if (fn->is_function())
6832 fntype = fn->func_value()->type();
6833 else if (fn->is_function_declaration())
6834 fntype = fn->func_declaration_value()->type();
6835 else
6836 fntype = NULL;
6837 if (fntype == NULL || !fntype->is_method())
6838 this->expr_->determine_type_no_context();
6839 else
6841 Type_context subcontext(fntype->receiver()->type(), false);
6842 this->expr_->determine_type(&subcontext);
6846 // Check the types of a method expression.
6848 void
6849 Bound_method_expression::do_check_types(Gogo*)
6851 Named_object* fn = this->method_->named_object();
6852 if (!fn->is_function() && !fn->is_function_declaration())
6854 this->report_error(_("object is not a method"));
6855 return;
6858 Function_type* fntype;
6859 if (fn->is_function())
6860 fntype = fn->func_value()->type();
6861 else if (fn->is_function_declaration())
6862 fntype = fn->func_declaration_value()->type();
6863 else
6864 go_unreachable();
6865 Type* rtype = fntype->receiver()->type()->deref();
6866 Type* etype = (this->expr_type_ != NULL
6867 ? this->expr_type_
6868 : this->expr_->type());
6869 etype = etype->deref();
6870 if (!Type::are_identical(rtype, etype, true, NULL))
6871 this->report_error(_("method type does not match object type"));
6874 // If a bound method expression is not simply called, then it is
6875 // represented as a closure. The closure will hold a single variable,
6876 // the receiver to pass to the method. The function will be a simple
6877 // thunk that pulls that value from the closure and calls the method
6878 // with the remaining arguments.
6880 // Because method values are not common, we don't build all thunks for
6881 // every methods, but instead only build them as we need them. In
6882 // particular, we even build them on demand for methods defined in
6883 // other packages.
6885 Bound_method_expression::Method_value_thunks
6886 Bound_method_expression::method_value_thunks;
6888 // Find or create the thunk for METHOD.
6890 Named_object*
6891 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6892 Named_object* fn)
6894 std::pair<Named_object*, Named_object*> val(fn, NULL);
6895 std::pair<Method_value_thunks::iterator, bool> ins =
6896 Bound_method_expression::method_value_thunks.insert(val);
6897 if (!ins.second)
6899 // We have seen this method before.
6900 go_assert(ins.first->second != NULL);
6901 return ins.first->second;
6904 Location loc = fn->location();
6906 Function_type* orig_fntype;
6907 if (fn->is_function())
6908 orig_fntype = fn->func_value()->type();
6909 else if (fn->is_function_declaration())
6910 orig_fntype = fn->func_declaration_value()->type();
6911 else
6912 orig_fntype = NULL;
6914 if (orig_fntype == NULL || !orig_fntype->is_method())
6916 ins.first->second =
6917 Named_object::make_erroneous_name(gogo->thunk_name());
6918 return ins.first->second;
6921 Struct_field_list* sfl = new Struct_field_list();
6922 // The type here is wrong--it should be the C function type. But it
6923 // doesn't really matter.
6924 Type* vt = Type::make_pointer_type(Type::make_void_type());
6925 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
6926 sfl->push_back(Struct_field(Typed_identifier("val",
6927 orig_fntype->receiver()->type(),
6928 loc)));
6929 Struct_type* st = Type::make_struct_type(sfl, loc);
6930 st->set_is_struct_incomparable();
6931 Type* closure_type = Type::make_pointer_type(st);
6933 Function_type* new_fntype = orig_fntype->copy_with_names();
6935 std::string thunk_name = gogo->thunk_name();
6936 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6937 false, loc);
6939 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6940 cvar->set_is_used();
6941 cvar->set_is_closure();
6942 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6943 NULL, cvar);
6944 new_no->func_value()->set_closure_var(cp);
6946 gogo->start_block(loc);
6948 // Field 0 of the closure is the function code pointer, field 1 is
6949 // the value on which to invoke the method.
6950 Expression* arg = Expression::make_var_reference(cp, loc);
6951 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
6952 arg = Expression::make_field_reference(arg, 1, loc);
6954 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6956 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6957 Expression_list* args;
6958 if (orig_params == NULL || orig_params->empty())
6959 args = NULL;
6960 else
6962 const Typed_identifier_list* new_params = new_fntype->parameters();
6963 args = new Expression_list();
6964 for (Typed_identifier_list::const_iterator p = new_params->begin();
6965 p != new_params->end();
6966 ++p)
6968 Named_object* p_no = gogo->lookup(p->name(), NULL);
6969 go_assert(p_no != NULL
6970 && p_no->is_variable()
6971 && p_no->var_value()->is_parameter());
6972 args->push_back(Expression::make_var_reference(p_no, loc));
6976 Call_expression* call = Expression::make_call(bme, args,
6977 orig_fntype->is_varargs(),
6978 loc);
6979 call->set_varargs_are_lowered();
6981 Statement* s = Statement::make_return_from_call(call, loc);
6982 gogo->add_statement(s);
6983 Block* b = gogo->finish_block(loc);
6984 gogo->add_block(b, loc);
6985 gogo->lower_block(new_no, b);
6986 gogo->flatten_block(new_no, b);
6987 gogo->finish_function(loc);
6989 ins.first->second = new_no;
6990 return new_no;
6993 // Return an expression to check *REF for nil while dereferencing
6994 // according to FIELD_INDEXES. Update *REF to build up the field
6995 // reference. This is a static function so that we don't have to
6996 // worry about declaring Field_indexes in expressions.h.
6998 static Expression*
6999 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
7000 Expression** ref)
7002 if (field_indexes == NULL)
7003 return Expression::make_boolean(false, loc);
7004 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
7005 Struct_type* stype = (*ref)->type()->deref()->struct_type();
7006 go_assert(stype != NULL
7007 && field_indexes->field_index < stype->field_count());
7008 if ((*ref)->type()->struct_type() == NULL)
7010 go_assert((*ref)->type()->points_to() != NULL);
7011 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
7012 Expression::make_nil(loc),
7013 loc);
7014 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7015 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7016 loc);
7017 go_assert((*ref)->type()->struct_type() == stype);
7019 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7020 loc);
7021 return cond;
7024 // Flatten a method value into a struct with nil checks. We can't do
7025 // this in the lowering phase, because if the method value is called
7026 // directly we don't need a thunk. That case will have been handled
7027 // by Call_expression::do_lower, so if we get here then we do need a
7028 // thunk.
7030 Expression*
7031 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7032 Statement_inserter* inserter)
7034 Location loc = this->location();
7036 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7037 this->method_,
7038 this->function_);
7039 if (thunk->is_erroneous())
7041 go_assert(saw_errors());
7042 return Expression::make_error(loc);
7045 // Force the expression into a variable. This is only necessary if
7046 // we are going to do nil checks below, but it's easy enough to
7047 // always do it.
7048 Expression* expr = this->expr_;
7049 if (!expr->is_variable())
7051 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7052 inserter->insert(etemp);
7053 expr = Expression::make_temporary_reference(etemp, loc);
7056 // If the method expects a value, and we have a pointer, we need to
7057 // dereference the pointer.
7059 Named_object* fn = this->method_->named_object();
7060 Function_type *fntype;
7061 if (fn->is_function())
7062 fntype = fn->func_value()->type();
7063 else if (fn->is_function_declaration())
7064 fntype = fn->func_declaration_value()->type();
7065 else
7066 go_unreachable();
7068 Expression* val = expr;
7069 if (fntype->receiver()->type()->points_to() == NULL
7070 && val->type()->points_to() != NULL)
7071 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7073 // Note that we are ignoring this->expr_type_ here. The thunk will
7074 // expect a closure whose second field has type this->expr_type_ (if
7075 // that is not NULL). We are going to pass it a closure whose
7076 // second field has type this->expr_->type(). Since
7077 // this->expr_type_ is only not-NULL for pointer types, we can get
7078 // away with this.
7080 Struct_field_list* fields = new Struct_field_list();
7081 fields->push_back(Struct_field(Typed_identifier("fn",
7082 thunk->func_value()->type(),
7083 loc)));
7084 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
7085 Struct_type* st = Type::make_struct_type(fields, loc);
7086 st->set_is_struct_incomparable();
7088 Expression_list* vals = new Expression_list();
7089 vals->push_back(Expression::make_func_code_reference(thunk, loc));
7090 vals->push_back(val);
7092 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7093 ret = Expression::make_heap_expression(ret, loc);
7095 Node* n = Node::make_node(this);
7096 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7097 ret->heap_expression()->set_allocate_on_stack();
7098 else if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
7099 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
7100 n->ast_format(gogo).c_str());
7102 // If necessary, check whether the expression or any embedded
7103 // pointers are nil.
7105 Expression* nil_check = NULL;
7106 if (this->method_->field_indexes() != NULL)
7108 Expression* ref = expr;
7109 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7110 expr = ref;
7113 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7115 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7116 Expression::make_nil(loc),
7117 loc);
7118 if (nil_check == NULL)
7119 nil_check = n;
7120 else
7121 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7124 if (nil_check != NULL)
7126 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7127 loc);
7128 // Fix the type of the conditional expression by pretending to
7129 // evaluate to RET either way through the conditional.
7130 crash = Expression::make_compound(crash, ret, loc);
7131 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7134 // RET is a pointer to a struct, but we want a function type.
7135 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7137 return ret;
7140 // Dump ast representation of a bound method expression.
7142 void
7143 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7144 const
7146 if (this->expr_type_ != NULL)
7147 ast_dump_context->ostream() << "(";
7148 ast_dump_context->dump_expression(this->expr_);
7149 if (this->expr_type_ != NULL)
7151 ast_dump_context->ostream() << ":";
7152 ast_dump_context->dump_type(this->expr_type_);
7153 ast_dump_context->ostream() << ")";
7156 ast_dump_context->ostream() << "." << this->function_->name();
7159 // Make a method expression.
7161 Bound_method_expression*
7162 Expression::make_bound_method(Expression* expr, const Method* method,
7163 Named_object* function, Location location)
7165 return new Bound_method_expression(expr, method, function, location);
7168 // Class Builtin_call_expression. This is used for a call to a
7169 // builtin function.
7171 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7172 Expression* fn,
7173 Expression_list* args,
7174 bool is_varargs,
7175 Location location)
7176 : Call_expression(fn, args, is_varargs, location),
7177 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7178 recover_arg_is_set_(false)
7180 Func_expression* fnexp = this->fn()->func_expression();
7181 if (fnexp == NULL)
7183 this->code_ = BUILTIN_INVALID;
7184 return;
7186 const std::string& name(fnexp->named_object()->name());
7187 if (name == "append")
7188 this->code_ = BUILTIN_APPEND;
7189 else if (name == "cap")
7190 this->code_ = BUILTIN_CAP;
7191 else if (name == "close")
7192 this->code_ = BUILTIN_CLOSE;
7193 else if (name == "complex")
7194 this->code_ = BUILTIN_COMPLEX;
7195 else if (name == "copy")
7196 this->code_ = BUILTIN_COPY;
7197 else if (name == "delete")
7198 this->code_ = BUILTIN_DELETE;
7199 else if (name == "imag")
7200 this->code_ = BUILTIN_IMAG;
7201 else if (name == "len")
7202 this->code_ = BUILTIN_LEN;
7203 else if (name == "make")
7204 this->code_ = BUILTIN_MAKE;
7205 else if (name == "new")
7206 this->code_ = BUILTIN_NEW;
7207 else if (name == "panic")
7208 this->code_ = BUILTIN_PANIC;
7209 else if (name == "print")
7210 this->code_ = BUILTIN_PRINT;
7211 else if (name == "println")
7212 this->code_ = BUILTIN_PRINTLN;
7213 else if (name == "real")
7214 this->code_ = BUILTIN_REAL;
7215 else if (name == "recover")
7216 this->code_ = BUILTIN_RECOVER;
7217 else if (name == "Alignof")
7218 this->code_ = BUILTIN_ALIGNOF;
7219 else if (name == "Offsetof")
7220 this->code_ = BUILTIN_OFFSETOF;
7221 else if (name == "Sizeof")
7222 this->code_ = BUILTIN_SIZEOF;
7223 else
7224 go_unreachable();
7227 // Return whether this is a call to recover. This is a virtual
7228 // function called from the parent class.
7230 bool
7231 Builtin_call_expression::do_is_recover_call() const
7233 if (this->classification() == EXPRESSION_ERROR)
7234 return false;
7235 return this->code_ == BUILTIN_RECOVER;
7238 // Set the argument for a call to recover.
7240 void
7241 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7243 const Expression_list* args = this->args();
7244 go_assert(args == NULL || args->empty());
7245 Expression_list* new_args = new Expression_list();
7246 new_args->push_back(arg);
7247 this->set_args(new_args);
7248 this->recover_arg_is_set_ = true;
7251 // Lower a builtin call expression. This turns new and make into
7252 // specific expressions. We also convert to a constant if we can.
7254 Expression*
7255 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7256 Statement_inserter* inserter, int)
7258 if (this->is_error_expression())
7259 return this;
7261 Location loc = this->location();
7263 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7265 this->report_error(_("invalid use of %<...%> with builtin function"));
7266 return Expression::make_error(loc);
7269 if (this->code_ == BUILTIN_OFFSETOF)
7271 Expression* arg = this->one_arg();
7273 if (arg->bound_method_expression() != NULL
7274 || arg->interface_field_reference_expression() != NULL)
7276 this->report_error(_("invalid use of method value as argument "
7277 "of Offsetof"));
7278 return this;
7281 Field_reference_expression* farg = arg->field_reference_expression();
7282 while (farg != NULL)
7284 if (!farg->implicit())
7285 break;
7286 // When the selector refers to an embedded field,
7287 // it must not be reached through pointer indirections.
7288 if (farg->expr()->deref() != farg->expr())
7290 this->report_error(_("argument of Offsetof implies "
7291 "indirection of an embedded field"));
7292 return this;
7294 // Go up until we reach the original base.
7295 farg = farg->expr()->field_reference_expression();
7299 if (this->is_constant())
7301 Numeric_constant nc;
7302 if (this->numeric_constant_value(&nc))
7303 return nc.expression(loc);
7306 switch (this->code_)
7308 default:
7309 break;
7311 case BUILTIN_NEW:
7313 const Expression_list* args = this->args();
7314 if (args == NULL || args->size() < 1)
7315 this->report_error(_("not enough arguments"));
7316 else if (args->size() > 1)
7317 this->report_error(_("too many arguments"));
7318 else
7320 Expression* arg = args->front();
7321 if (!arg->is_type_expression())
7323 go_error_at(arg->location(), "expected type");
7324 this->set_is_error();
7326 else
7327 return Expression::make_allocation(arg->type(), loc);
7330 break;
7332 case BUILTIN_MAKE:
7333 return this->lower_make(inserter);
7335 case BUILTIN_RECOVER:
7336 if (function != NULL)
7337 function->func_value()->set_calls_recover();
7338 else
7340 // Calling recover outside of a function always returns the
7341 // nil empty interface.
7342 Type* eface = Type::make_empty_interface_type(loc);
7343 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7345 break;
7347 case BUILTIN_DELETE:
7349 // Lower to a runtime function call.
7350 const Expression_list* args = this->args();
7351 if (args == NULL || args->size() < 2)
7352 this->report_error(_("not enough arguments"));
7353 else if (args->size() > 2)
7354 this->report_error(_("too many arguments"));
7355 else if (args->front()->type()->map_type() == NULL)
7356 this->report_error(_("argument 1 must be a map"));
7357 else
7359 // Since this function returns no value it must appear in
7360 // a statement by itself, so we don't have to worry about
7361 // order of evaluation of values around it. Evaluate the
7362 // map first to get order of evaluation right.
7363 Map_type* mt = args->front()->type()->map_type();
7364 Temporary_statement* map_temp =
7365 Statement::make_temporary(mt, args->front(), loc);
7366 inserter->insert(map_temp);
7368 Temporary_statement* key_temp =
7369 Statement::make_temporary(mt->key_type(), args->back(), loc);
7370 inserter->insert(key_temp);
7372 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7373 Expression* e2 = Expression::make_temporary_reference(map_temp,
7374 loc);
7375 Expression* e3 = Expression::make_temporary_reference(key_temp,
7376 loc);
7377 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7378 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7379 3, e1, e2, e3);
7382 break;
7384 case BUILTIN_PRINT:
7385 case BUILTIN_PRINTLN:
7386 // Force all the arguments into temporary variables, so that we
7387 // don't try to evaluate something while holding the print lock.
7388 if (this->args() == NULL)
7389 break;
7390 for (Expression_list::iterator pa = this->args()->begin();
7391 pa != this->args()->end();
7392 ++pa)
7394 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7396 Temporary_statement* temp =
7397 Statement::make_temporary(NULL, *pa, loc);
7398 inserter->insert(temp);
7399 *pa = Expression::make_temporary_reference(temp, loc);
7402 break;
7405 return this;
7408 // Flatten a builtin call expression. This turns the arguments of copy and
7409 // append into temporary expressions.
7411 Expression*
7412 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7413 Statement_inserter* inserter)
7415 Location loc = this->location();
7417 switch (this->code_)
7419 default:
7420 break;
7422 case BUILTIN_APPEND:
7423 return this->flatten_append(gogo, function, inserter);
7425 case BUILTIN_COPY:
7427 Type* at = this->args()->front()->type();
7428 for (Expression_list::iterator pa = this->args()->begin();
7429 pa != this->args()->end();
7430 ++pa)
7432 if ((*pa)->is_nil_expression())
7434 Expression* nil = Expression::make_nil(loc);
7435 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7436 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7438 if (!(*pa)->is_variable())
7440 Temporary_statement* temp =
7441 Statement::make_temporary(NULL, *pa, loc);
7442 inserter->insert(temp);
7443 *pa = Expression::make_temporary_reference(temp, loc);
7447 break;
7449 case BUILTIN_PANIC:
7450 for (Expression_list::iterator pa = this->args()->begin();
7451 pa != this->args()->end();
7452 ++pa)
7454 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7456 Temporary_statement* temp =
7457 Statement::make_temporary(NULL, *pa, loc);
7458 inserter->insert(temp);
7459 *pa = Expression::make_temporary_reference(temp, loc);
7462 break;
7464 case BUILTIN_LEN:
7465 case BUILTIN_CAP:
7467 Expression_list::iterator pa = this->args()->begin();
7468 if (!(*pa)->is_variable()
7469 && ((*pa)->type()->map_type() != NULL
7470 || (*pa)->type()->channel_type() != NULL))
7472 Temporary_statement* temp =
7473 Statement::make_temporary(NULL, *pa, loc);
7474 inserter->insert(temp);
7475 *pa = Expression::make_temporary_reference(temp, loc);
7478 break;
7481 return this;
7484 // Lower a make expression.
7486 Expression*
7487 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7489 Location loc = this->location();
7491 const Expression_list* args = this->args();
7492 if (args == NULL || args->size() < 1)
7494 this->report_error(_("not enough arguments"));
7495 return Expression::make_error(this->location());
7498 Expression_list::const_iterator parg = args->begin();
7500 Expression* first_arg = *parg;
7501 if (!first_arg->is_type_expression())
7503 go_error_at(first_arg->location(), "expected type");
7504 this->set_is_error();
7505 return Expression::make_error(this->location());
7507 Type* type = first_arg->type();
7509 if (!type->in_heap())
7510 go_error_at(first_arg->location(),
7511 "can't make slice of go:notinheap type");
7513 bool is_slice = false;
7514 bool is_map = false;
7515 bool is_chan = false;
7516 if (type->is_slice_type())
7517 is_slice = true;
7518 else if (type->map_type() != NULL)
7519 is_map = true;
7520 else if (type->channel_type() != NULL)
7521 is_chan = true;
7522 else
7524 this->report_error(_("invalid type for make function"));
7525 return Expression::make_error(this->location());
7528 Type_context int_context(Type::lookup_integer_type("int"), false);
7530 ++parg;
7531 Expression* len_arg;
7532 bool len_small = false;
7533 if (parg == args->end())
7535 if (is_slice)
7537 this->report_error(_("length required when allocating a slice"));
7538 return Expression::make_error(this->location());
7540 len_arg = Expression::make_integer_ul(0, NULL, loc);
7541 len_small = true;
7543 else
7545 len_arg = *parg;
7546 len_arg->determine_type(&int_context);
7547 if (len_arg->type()->integer_type() == NULL)
7549 go_error_at(len_arg->location(), "non-integer len argument in make");
7550 return Expression::make_error(this->location());
7552 if (!this->check_int_value(len_arg, true, &len_small))
7553 return Expression::make_error(this->location());
7554 ++parg;
7557 Expression* cap_arg = NULL;
7558 bool cap_small = false;
7559 Numeric_constant nclen;
7560 Numeric_constant nccap;
7561 unsigned long vlen;
7562 unsigned long vcap;
7563 if (is_slice && parg != args->end())
7565 cap_arg = *parg;
7566 cap_arg->determine_type(&int_context);
7567 if (cap_arg->type()->integer_type() == NULL)
7569 go_error_at(cap_arg->location(), "non-integer cap argument in make");
7570 return Expression::make_error(this->location());
7572 if (!this->check_int_value(cap_arg, false, &cap_small))
7573 return Expression::make_error(this->location());
7575 if (len_arg->numeric_constant_value(&nclen)
7576 && cap_arg->numeric_constant_value(&nccap)
7577 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7578 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7579 && vlen > vcap)
7581 this->report_error(_("len larger than cap"));
7582 return Expression::make_error(this->location());
7585 ++parg;
7588 if (parg != args->end())
7590 this->report_error(_("too many arguments to make"));
7591 return Expression::make_error(this->location());
7594 Location type_loc = first_arg->location();
7596 Expression* call;
7597 if (is_slice)
7599 if (cap_arg == NULL)
7601 cap_small = len_small;
7602 if (len_arg->numeric_constant_value(&nclen)
7603 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID)
7604 cap_arg = Expression::make_integer_ul(vlen, len_arg->type(), loc);
7605 else
7607 Temporary_statement* temp = Statement::make_temporary(NULL,
7608 len_arg,
7609 loc);
7610 inserter->insert(temp);
7611 len_arg = Expression::make_temporary_reference(temp, loc);
7612 cap_arg = Expression::make_temporary_reference(temp, loc);
7616 Type* et = type->array_type()->element_type();
7617 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7618 Runtime::Function code = Runtime::MAKESLICE;
7619 if (!len_small || !cap_small)
7620 code = Runtime::MAKESLICE64;
7621 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7623 else if (is_map)
7625 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7626 if (!len_small)
7627 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7628 len_arg,
7629 Expression::make_nil(loc));
7630 else
7632 Numeric_constant nclen;
7633 unsigned long vlen;
7634 if (len_arg->numeric_constant_value(&nclen)
7635 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7636 && vlen <= Map_type::bucket_size)
7637 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7638 else
7639 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7640 len_arg,
7641 Expression::make_nil(loc));
7644 else if (is_chan)
7646 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7647 Runtime::Function code = Runtime::MAKECHAN;
7648 if (!len_small)
7649 code = Runtime::MAKECHAN64;
7650 call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
7652 else
7653 go_unreachable();
7655 return Expression::make_unsafe_cast(type, call, loc);
7658 // Flatten a call to the predeclared append function. We do this in
7659 // the flatten phase, not the lowering phase, so that we run after
7660 // type checking and after order_evaluations.
7662 Expression*
7663 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7664 Statement_inserter* inserter)
7666 if (this->is_error_expression())
7667 return this;
7669 Location loc = this->location();
7671 const Expression_list* args = this->args();
7672 go_assert(args != NULL && !args->empty());
7674 Type* slice_type = args->front()->type();
7675 go_assert(slice_type->is_slice_type());
7676 Type* element_type = slice_type->array_type()->element_type();
7678 if (args->size() == 1)
7680 // append(s) evaluates to s.
7681 return args->front();
7684 Type* int_type = Type::lookup_integer_type("int");
7685 Type* uint_type = Type::lookup_integer_type("uint");
7687 // Implementing
7688 // append(s1, s2...)
7689 // or
7690 // append(s1, a1, a2, a3, ...)
7692 // s1tmp := s1
7693 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7694 loc);
7695 inserter->insert(s1tmp);
7697 // l1tmp := len(s1tmp)
7698 Named_object* lenfn = gogo->lookup_global("len");
7699 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7700 Expression_list* call_args = new Expression_list();
7701 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7702 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7703 gogo->lower_expression(function, inserter, &len);
7704 gogo->flatten_expression(function, inserter, &len);
7705 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7706 inserter->insert(l1tmp);
7708 Temporary_statement* s2tmp = NULL;
7709 Temporary_statement* l2tmp = NULL;
7710 Expression_list* add = NULL;
7711 Expression* len2;
7712 if (this->is_varargs())
7714 go_assert(args->size() == 2);
7716 // s2tmp := s2
7717 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7718 inserter->insert(s2tmp);
7720 // l2tmp := len(s2tmp)
7721 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7722 call_args = new Expression_list();
7723 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7724 len = Expression::make_call(lenref, call_args, false, loc);
7725 gogo->lower_expression(function, inserter, &len);
7726 gogo->flatten_expression(function, inserter, &len);
7727 l2tmp = Statement::make_temporary(int_type, len, loc);
7728 inserter->insert(l2tmp);
7730 // len2 = l2tmp
7731 len2 = Expression::make_temporary_reference(l2tmp, loc);
7733 else
7735 // We have to ensure that all the arguments are in variables
7736 // now, because otherwise if one of them is an index expression
7737 // into the current slice we could overwrite it before we fetch
7738 // it.
7739 add = new Expression_list();
7740 Expression_list::const_iterator pa = args->begin();
7741 for (++pa; pa != args->end(); ++pa)
7743 if ((*pa)->is_variable())
7744 add->push_back(*pa);
7745 else
7747 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7748 loc);
7749 inserter->insert(tmp);
7750 add->push_back(Expression::make_temporary_reference(tmp, loc));
7754 // len2 = len(add)
7755 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7758 // ntmp := l1tmp + len2
7759 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7760 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7761 gogo->lower_expression(function, inserter, &sum);
7762 gogo->flatten_expression(function, inserter, &sum);
7763 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7764 inserter->insert(ntmp);
7766 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7767 // growslice(type, s1tmp, ntmp) :
7768 // s1tmp[:ntmp]
7769 // Using uint here means that if the computation of ntmp overflowed,
7770 // we will call growslice which will panic.
7772 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7773 left = Expression::make_cast(uint_type, left, loc);
7775 Named_object* capfn = gogo->lookup_global("cap");
7776 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7777 call_args = new Expression_list();
7778 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7779 Expression* right = Expression::make_call(capref, call_args, false, loc);
7780 right = Expression::make_cast(uint_type, right, loc);
7782 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7784 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7785 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7786 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7787 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7788 a1, a2, a3);
7789 call = Expression::make_unsafe_cast(slice_type, call, loc);
7791 ref = Expression::make_temporary_reference(s1tmp, loc);
7792 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7793 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7794 // FIXME: Mark this index as not requiring bounds checks.
7795 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7797 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7799 gogo->lower_expression(function, inserter, &rhs);
7800 gogo->flatten_expression(function, inserter, &rhs);
7802 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7803 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7804 inserter->insert(assign);
7806 if (this->is_varargs())
7808 // copy(s1tmp[l1tmp:], s2tmp)
7809 a1 = Expression::make_temporary_reference(s1tmp, loc);
7810 ref = Expression::make_temporary_reference(l1tmp, loc);
7811 Expression* nil = Expression::make_nil(loc);
7812 // FIXME: Mark this index as not requiring bounds checks.
7813 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7815 a2 = Expression::make_temporary_reference(s2tmp, loc);
7817 Named_object* copyfn = gogo->lookup_global("copy");
7818 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7819 call_args = new Expression_list();
7820 call_args->push_back(a1);
7821 call_args->push_back(a2);
7822 call = Expression::make_call(copyref, call_args, false, loc);
7823 gogo->lower_expression(function, inserter, &call);
7824 gogo->flatten_expression(function, inserter, &call);
7825 inserter->insert(Statement::make_statement(call, false));
7827 else
7829 // For each argument:
7830 // s1tmp[l1tmp+i] = a
7831 unsigned long i = 0;
7832 for (Expression_list::const_iterator pa = add->begin();
7833 pa != add->end();
7834 ++pa, ++i)
7836 ref = Expression::make_temporary_reference(s1tmp, loc);
7837 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7838 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7839 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7840 // FIXME: Mark this index as not requiring bounds checks.
7841 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7842 gogo->lower_expression(function, inserter, &lhs);
7843 gogo->flatten_expression(function, inserter, &lhs);
7844 // The flatten pass runs after the write barrier pass, so we
7845 // need to insert a write barrier here if necessary.
7846 if (!gogo->assign_needs_write_barrier(lhs))
7847 assign = Statement::make_assignment(lhs, *pa, loc);
7848 else
7850 Function* f = function == NULL ? NULL : function->func_value();
7851 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7852 lhs, *pa, loc);
7854 inserter->insert(assign);
7858 return Expression::make_temporary_reference(s1tmp, loc);
7861 // Return whether an expression has an integer value. Report an error
7862 // if not. This is used when handling calls to the predeclared make
7863 // function. Set *SMALL if the value is known to fit in type "int".
7865 bool
7866 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7867 bool *small)
7869 *small = false;
7871 Numeric_constant nc;
7872 if (e->numeric_constant_value(&nc))
7874 unsigned long v;
7875 switch (nc.to_unsigned_long(&v))
7877 case Numeric_constant::NC_UL_VALID:
7878 break;
7879 case Numeric_constant::NC_UL_NOTINT:
7880 go_error_at(e->location(), "non-integer %s argument to make",
7881 is_length ? "len" : "cap");
7882 return false;
7883 case Numeric_constant::NC_UL_NEGATIVE:
7884 go_error_at(e->location(), "negative %s argument to make",
7885 is_length ? "len" : "cap");
7886 return false;
7887 case Numeric_constant::NC_UL_BIG:
7888 // We don't want to give a compile-time error for a 64-bit
7889 // value on a 32-bit target.
7890 break;
7893 mpz_t val;
7894 if (!nc.to_int(&val))
7895 go_unreachable();
7896 int bits = mpz_sizeinbase(val, 2);
7897 mpz_clear(val);
7898 Type* int_type = Type::lookup_integer_type("int");
7899 if (bits >= int_type->integer_type()->bits())
7901 go_error_at(e->location(), "%s argument too large for make",
7902 is_length ? "len" : "cap");
7903 return false;
7906 *small = true;
7907 return true;
7910 if (e->type()->integer_type() != NULL)
7912 int ebits = e->type()->integer_type()->bits();
7913 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7915 // We can treat ebits == intbits as small even for an unsigned
7916 // integer type, because we will convert the value to int and
7917 // then reject it in the runtime if it is negative.
7918 *small = ebits <= intbits;
7920 return true;
7923 go_error_at(e->location(), "non-integer %s argument to make",
7924 is_length ? "len" : "cap");
7925 return false;
7928 // Return the type of the real or imag functions, given the type of
7929 // the argument. We need to map complex64 to float32 and complex128
7930 // to float64, so it has to be done by name. This returns NULL if it
7931 // can't figure out the type.
7933 Type*
7934 Builtin_call_expression::real_imag_type(Type* arg_type)
7936 if (arg_type == NULL || arg_type->is_abstract())
7937 return NULL;
7938 Named_type* nt = arg_type->named_type();
7939 if (nt == NULL)
7940 return NULL;
7941 while (nt->real_type()->named_type() != NULL)
7942 nt = nt->real_type()->named_type();
7943 if (nt->name() == "complex64")
7944 return Type::lookup_float_type("float32");
7945 else if (nt->name() == "complex128")
7946 return Type::lookup_float_type("float64");
7947 else
7948 return NULL;
7951 // Return the type of the complex function, given the type of one of the
7952 // argments. Like real_imag_type, we have to map by name.
7954 Type*
7955 Builtin_call_expression::complex_type(Type* arg_type)
7957 if (arg_type == NULL || arg_type->is_abstract())
7958 return NULL;
7959 Named_type* nt = arg_type->named_type();
7960 if (nt == NULL)
7961 return NULL;
7962 while (nt->real_type()->named_type() != NULL)
7963 nt = nt->real_type()->named_type();
7964 if (nt->name() == "float32")
7965 return Type::lookup_complex_type("complex64");
7966 else if (nt->name() == "float64")
7967 return Type::lookup_complex_type("complex128");
7968 else
7969 return NULL;
7972 // Return a single argument, or NULL if there isn't one.
7974 Expression*
7975 Builtin_call_expression::one_arg() const
7977 const Expression_list* args = this->args();
7978 if (args == NULL || args->size() != 1)
7979 return NULL;
7980 return args->front();
7983 // A traversal class which looks for a call or receive expression.
7985 class Find_call_expression : public Traverse
7987 public:
7988 Find_call_expression()
7989 : Traverse(traverse_expressions),
7990 found_(false)
7994 expression(Expression**);
7996 bool
7997 found()
7998 { return this->found_; }
8000 private:
8001 bool found_;
8005 Find_call_expression::expression(Expression** pexpr)
8007 Expression* expr = *pexpr;
8008 if (!expr->is_constant()
8009 && (expr->call_expression() != NULL
8010 || expr->receive_expression() != NULL))
8012 this->found_ = true;
8013 return TRAVERSE_EXIT;
8015 return TRAVERSE_CONTINUE;
8018 // Return whether calling len or cap on EXPR, of array type, is a
8019 // constant. The language spec says "the expressions len(s) and
8020 // cap(s) are constants if the type of s is an array or pointer to an
8021 // array and the expression s does not contain channel receives or
8022 // (non-constant) function calls."
8024 bool
8025 Builtin_call_expression::array_len_is_constant(Expression* expr)
8027 go_assert(expr->type()->deref()->array_type() != NULL
8028 && !expr->type()->deref()->is_slice_type());
8029 if (expr->is_constant())
8030 return true;
8031 Find_call_expression find_call;
8032 Expression::traverse(&expr, &find_call);
8033 return !find_call.found();
8036 // Return whether this is constant: len of a string constant, or len
8037 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
8038 // unsafe.Alignof.
8040 bool
8041 Builtin_call_expression::do_is_constant() const
8043 if (this->is_error_expression())
8044 return true;
8045 switch (this->code_)
8047 case BUILTIN_LEN:
8048 case BUILTIN_CAP:
8050 if (this->seen_)
8051 return false;
8053 Expression* arg = this->one_arg();
8054 if (arg == NULL)
8055 return false;
8056 Type* arg_type = arg->type();
8058 if (arg_type->points_to() != NULL
8059 && arg_type->points_to()->array_type() != NULL
8060 && !arg_type->points_to()->is_slice_type())
8061 arg_type = arg_type->points_to();
8063 if (arg_type->array_type() != NULL
8064 && arg_type->array_type()->length() != NULL
8065 && Builtin_call_expression::array_len_is_constant(arg))
8066 return true;
8068 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8070 this->seen_ = true;
8071 bool ret = arg->is_constant();
8072 this->seen_ = false;
8073 return ret;
8076 break;
8078 case BUILTIN_SIZEOF:
8079 case BUILTIN_ALIGNOF:
8080 return this->one_arg() != NULL;
8082 case BUILTIN_OFFSETOF:
8084 Expression* arg = this->one_arg();
8085 if (arg == NULL)
8086 return false;
8087 return arg->field_reference_expression() != NULL;
8090 case BUILTIN_COMPLEX:
8092 const Expression_list* args = this->args();
8093 if (args != NULL && args->size() == 2)
8094 return args->front()->is_constant() && args->back()->is_constant();
8096 break;
8098 case BUILTIN_REAL:
8099 case BUILTIN_IMAG:
8101 Expression* arg = this->one_arg();
8102 return arg != NULL && arg->is_constant();
8105 default:
8106 break;
8109 return false;
8112 // Return a numeric constant if possible.
8114 bool
8115 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8117 if (this->code_ == BUILTIN_LEN
8118 || this->code_ == BUILTIN_CAP)
8120 Expression* arg = this->one_arg();
8121 if (arg == NULL)
8122 return false;
8123 Type* arg_type = arg->type();
8125 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8127 std::string sval;
8128 if (arg->string_constant_value(&sval))
8130 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8131 sval.length());
8132 return true;
8136 if (arg_type->points_to() != NULL
8137 && arg_type->points_to()->array_type() != NULL
8138 && !arg_type->points_to()->is_slice_type())
8139 arg_type = arg_type->points_to();
8141 if (arg_type->array_type() != NULL
8142 && arg_type->array_type()->length() != NULL)
8144 if (this->seen_)
8145 return false;
8146 Expression* e = arg_type->array_type()->length();
8147 this->seen_ = true;
8148 bool r = e->numeric_constant_value(nc);
8149 this->seen_ = false;
8150 if (r)
8152 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8153 this->location()))
8154 r = false;
8156 return r;
8159 else if (this->code_ == BUILTIN_SIZEOF
8160 || this->code_ == BUILTIN_ALIGNOF)
8162 Expression* arg = this->one_arg();
8163 if (arg == NULL)
8164 return false;
8165 Type* arg_type = arg->type();
8166 if (arg_type->is_error())
8167 return false;
8168 if (arg_type->is_abstract())
8169 return false;
8170 if (this->seen_)
8171 return false;
8173 int64_t ret;
8174 if (this->code_ == BUILTIN_SIZEOF)
8176 this->seen_ = true;
8177 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8178 this->seen_ = false;
8179 if (!ok)
8180 return false;
8182 else if (this->code_ == BUILTIN_ALIGNOF)
8184 bool ok;
8185 this->seen_ = true;
8186 if (arg->field_reference_expression() == NULL)
8187 ok = arg_type->backend_type_align(this->gogo_, &ret);
8188 else
8190 // Calling unsafe.Alignof(s.f) returns the alignment of
8191 // the type of f when it is used as a field in a struct.
8192 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8194 this->seen_ = false;
8195 if (!ok)
8196 return false;
8198 else
8199 go_unreachable();
8201 mpz_t zval;
8202 set_mpz_from_int64(&zval, ret);
8203 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8204 mpz_clear(zval);
8205 return true;
8207 else if (this->code_ == BUILTIN_OFFSETOF)
8209 Expression* arg = this->one_arg();
8210 if (arg == NULL)
8211 return false;
8212 Field_reference_expression* farg = arg->field_reference_expression();
8213 if (farg == NULL)
8214 return false;
8215 if (this->seen_)
8216 return false;
8218 int64_t total_offset = 0;
8219 while (true)
8221 Expression* struct_expr = farg->expr();
8222 Type* st = struct_expr->type();
8223 if (st->struct_type() == NULL)
8224 return false;
8225 if (st->named_type() != NULL)
8226 st->named_type()->convert(this->gogo_);
8227 if (st->is_error_type())
8229 go_assert(saw_errors());
8230 return false;
8232 int64_t offset;
8233 this->seen_ = true;
8234 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8235 farg->field_index(),
8236 &offset);
8237 this->seen_ = false;
8238 if (!ok)
8239 return false;
8240 total_offset += offset;
8241 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8243 // Go up until we reach the original base.
8244 farg = struct_expr->field_reference_expression();
8245 continue;
8247 break;
8249 mpz_t zval;
8250 set_mpz_from_int64(&zval, total_offset);
8251 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8252 mpz_clear(zval);
8253 return true;
8255 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8257 Expression* arg = this->one_arg();
8258 if (arg == NULL)
8259 return false;
8261 Numeric_constant argnc;
8262 if (!arg->numeric_constant_value(&argnc))
8263 return false;
8265 mpc_t val;
8266 if (!argnc.to_complex(&val))
8267 return false;
8269 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8270 if (this->code_ == BUILTIN_REAL)
8271 nc->set_float(type, mpc_realref(val));
8272 else
8273 nc->set_float(type, mpc_imagref(val));
8274 mpc_clear(val);
8275 return true;
8277 else if (this->code_ == BUILTIN_COMPLEX)
8279 const Expression_list* args = this->args();
8280 if (args == NULL || args->size() != 2)
8281 return false;
8283 Numeric_constant rnc;
8284 if (!args->front()->numeric_constant_value(&rnc))
8285 return false;
8286 Numeric_constant inc;
8287 if (!args->back()->numeric_constant_value(&inc))
8288 return false;
8290 if (rnc.type() != NULL
8291 && !rnc.type()->is_abstract()
8292 && inc.type() != NULL
8293 && !inc.type()->is_abstract()
8294 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8295 return false;
8297 mpfr_t r;
8298 if (!rnc.to_float(&r))
8299 return false;
8300 mpfr_t i;
8301 if (!inc.to_float(&i))
8303 mpfr_clear(r);
8304 return false;
8307 Type* arg_type = rnc.type();
8308 if (arg_type == NULL || arg_type->is_abstract())
8309 arg_type = inc.type();
8311 mpc_t val;
8312 mpc_init2(val, mpc_precision);
8313 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8314 mpfr_clear(r);
8315 mpfr_clear(i);
8317 Type* type = Builtin_call_expression::complex_type(arg_type);
8318 nc->set_complex(type, val);
8320 mpc_clear(val);
8322 return true;
8325 return false;
8328 // Give an error if we are discarding the value of an expression which
8329 // should not normally be discarded. We don't give an error for
8330 // discarding the value of an ordinary function call, but we do for
8331 // builtin functions, purely for consistency with the gc compiler.
8333 bool
8334 Builtin_call_expression::do_discarding_value()
8336 switch (this->code_)
8338 case BUILTIN_INVALID:
8339 default:
8340 go_unreachable();
8342 case BUILTIN_APPEND:
8343 case BUILTIN_CAP:
8344 case BUILTIN_COMPLEX:
8345 case BUILTIN_IMAG:
8346 case BUILTIN_LEN:
8347 case BUILTIN_MAKE:
8348 case BUILTIN_NEW:
8349 case BUILTIN_REAL:
8350 case BUILTIN_ALIGNOF:
8351 case BUILTIN_OFFSETOF:
8352 case BUILTIN_SIZEOF:
8353 this->unused_value_error();
8354 return false;
8356 case BUILTIN_CLOSE:
8357 case BUILTIN_COPY:
8358 case BUILTIN_DELETE:
8359 case BUILTIN_PANIC:
8360 case BUILTIN_PRINT:
8361 case BUILTIN_PRINTLN:
8362 case BUILTIN_RECOVER:
8363 return true;
8367 // Return the type.
8369 Type*
8370 Builtin_call_expression::do_type()
8372 if (this->is_error_expression())
8373 return Type::make_error_type();
8374 switch (this->code_)
8376 case BUILTIN_INVALID:
8377 default:
8378 return Type::make_error_type();
8380 case BUILTIN_NEW:
8382 const Expression_list* args = this->args();
8383 if (args == NULL || args->empty())
8384 return Type::make_error_type();
8385 return Type::make_pointer_type(args->front()->type());
8388 case BUILTIN_MAKE:
8390 const Expression_list* args = this->args();
8391 if (args == NULL || args->empty())
8392 return Type::make_error_type();
8393 return args->front()->type();
8396 case BUILTIN_CAP:
8397 case BUILTIN_COPY:
8398 case BUILTIN_LEN:
8399 return Type::lookup_integer_type("int");
8401 case BUILTIN_ALIGNOF:
8402 case BUILTIN_OFFSETOF:
8403 case BUILTIN_SIZEOF:
8404 return Type::lookup_integer_type("uintptr");
8406 case BUILTIN_CLOSE:
8407 case BUILTIN_DELETE:
8408 case BUILTIN_PANIC:
8409 case BUILTIN_PRINT:
8410 case BUILTIN_PRINTLN:
8411 return Type::make_void_type();
8413 case BUILTIN_RECOVER:
8414 return Type::make_empty_interface_type(Linemap::predeclared_location());
8416 case BUILTIN_APPEND:
8418 const Expression_list* args = this->args();
8419 if (args == NULL || args->empty())
8420 return Type::make_error_type();
8421 Type *ret = args->front()->type();
8422 if (!ret->is_slice_type())
8423 return Type::make_error_type();
8424 return ret;
8427 case BUILTIN_REAL:
8428 case BUILTIN_IMAG:
8430 Expression* arg = this->one_arg();
8431 if (arg == NULL)
8432 return Type::make_error_type();
8433 Type* t = arg->type();
8434 if (t->is_abstract())
8435 t = t->make_non_abstract_type();
8436 t = Builtin_call_expression::real_imag_type(t);
8437 if (t == NULL)
8438 t = Type::make_error_type();
8439 return t;
8442 case BUILTIN_COMPLEX:
8444 const Expression_list* args = this->args();
8445 if (args == NULL || args->size() != 2)
8446 return Type::make_error_type();
8447 Type* t = args->front()->type();
8448 if (t->is_abstract())
8450 t = args->back()->type();
8451 if (t->is_abstract())
8452 t = t->make_non_abstract_type();
8454 t = Builtin_call_expression::complex_type(t);
8455 if (t == NULL)
8456 t = Type::make_error_type();
8457 return t;
8462 // Determine the type.
8464 void
8465 Builtin_call_expression::do_determine_type(const Type_context* context)
8467 if (!this->determining_types())
8468 return;
8470 this->fn()->determine_type_no_context();
8472 const Expression_list* args = this->args();
8474 bool is_print;
8475 Type* arg_type = NULL;
8476 Type* trailing_arg_types = NULL;
8477 switch (this->code_)
8479 case BUILTIN_PRINT:
8480 case BUILTIN_PRINTLN:
8481 // Do not force a large integer constant to "int".
8482 is_print = true;
8483 break;
8485 case BUILTIN_REAL:
8486 case BUILTIN_IMAG:
8487 arg_type = Builtin_call_expression::complex_type(context->type);
8488 if (arg_type == NULL)
8489 arg_type = Type::lookup_complex_type("complex128");
8490 is_print = false;
8491 break;
8493 case BUILTIN_COMPLEX:
8495 // For the complex function the type of one operand can
8496 // determine the type of the other, as in a binary expression.
8497 arg_type = Builtin_call_expression::real_imag_type(context->type);
8498 if (arg_type == NULL)
8499 arg_type = Type::lookup_float_type("float64");
8500 if (args != NULL && args->size() == 2)
8502 Type* t1 = args->front()->type();
8503 Type* t2 = args->back()->type();
8504 if (!t1->is_abstract())
8505 arg_type = t1;
8506 else if (!t2->is_abstract())
8507 arg_type = t2;
8509 is_print = false;
8511 break;
8513 case BUILTIN_APPEND:
8514 if (!this->is_varargs()
8515 && args != NULL
8516 && !args->empty()
8517 && args->front()->type()->is_slice_type())
8518 trailing_arg_types =
8519 args->front()->type()->array_type()->element_type();
8520 is_print = false;
8521 break;
8523 default:
8524 is_print = false;
8525 break;
8528 if (args != NULL)
8530 for (Expression_list::const_iterator pa = args->begin();
8531 pa != args->end();
8532 ++pa)
8534 Type_context subcontext;
8535 subcontext.type = arg_type;
8537 if (is_print)
8539 // We want to print large constants, we so can't just
8540 // use the appropriate nonabstract type. Use uint64 for
8541 // an integer if we know it is nonnegative, otherwise
8542 // use int64 for a integer, otherwise use float64 for a
8543 // float or complex128 for a complex.
8544 Type* want_type = NULL;
8545 Type* atype = (*pa)->type();
8546 if (atype->is_abstract())
8548 if (atype->integer_type() != NULL)
8550 Numeric_constant nc;
8551 if (this->numeric_constant_value(&nc))
8553 mpz_t val;
8554 if (nc.to_int(&val))
8556 if (mpz_sgn(val) >= 0)
8557 want_type = Type::lookup_integer_type("uint64");
8558 mpz_clear(val);
8561 if (want_type == NULL)
8562 want_type = Type::lookup_integer_type("int64");
8564 else if (atype->float_type() != NULL)
8565 want_type = Type::lookup_float_type("float64");
8566 else if (atype->complex_type() != NULL)
8567 want_type = Type::lookup_complex_type("complex128");
8568 else if (atype->is_abstract_string_type())
8569 want_type = Type::lookup_string_type();
8570 else if (atype->is_abstract_boolean_type())
8571 want_type = Type::lookup_bool_type();
8572 else
8573 go_unreachable();
8574 subcontext.type = want_type;
8578 (*pa)->determine_type(&subcontext);
8580 if (trailing_arg_types != NULL)
8582 arg_type = trailing_arg_types;
8583 trailing_arg_types = NULL;
8589 // If there is exactly one argument, return true. Otherwise give an
8590 // error message and return false.
8592 bool
8593 Builtin_call_expression::check_one_arg()
8595 const Expression_list* args = this->args();
8596 if (args == NULL || args->size() < 1)
8598 this->report_error(_("not enough arguments"));
8599 return false;
8601 else if (args->size() > 1)
8603 this->report_error(_("too many arguments"));
8604 return false;
8606 if (args->front()->is_error_expression()
8607 || args->front()->type()->is_error())
8609 this->set_is_error();
8610 return false;
8612 return true;
8615 // Check argument types for a builtin function.
8617 void
8618 Builtin_call_expression::do_check_types(Gogo*)
8620 if (this->is_error_expression())
8621 return;
8622 switch (this->code_)
8624 case BUILTIN_INVALID:
8625 case BUILTIN_NEW:
8626 case BUILTIN_MAKE:
8627 case BUILTIN_DELETE:
8628 return;
8630 case BUILTIN_LEN:
8631 case BUILTIN_CAP:
8633 // The single argument may be either a string or an array or a
8634 // map or a channel, or a pointer to a closed array.
8635 if (this->check_one_arg())
8637 Type* arg_type = this->one_arg()->type();
8638 if (arg_type->points_to() != NULL
8639 && arg_type->points_to()->array_type() != NULL
8640 && !arg_type->points_to()->is_slice_type())
8641 arg_type = arg_type->points_to();
8642 if (this->code_ == BUILTIN_CAP)
8644 if (!arg_type->is_error()
8645 && arg_type->array_type() == NULL
8646 && arg_type->channel_type() == NULL)
8647 this->report_error(_("argument must be array or slice "
8648 "or channel"));
8650 else
8652 if (!arg_type->is_error()
8653 && !arg_type->is_string_type()
8654 && arg_type->array_type() == NULL
8655 && arg_type->map_type() == NULL
8656 && arg_type->channel_type() == NULL)
8657 this->report_error(_("argument must be string or "
8658 "array or slice or map or channel"));
8662 break;
8664 case BUILTIN_PRINT:
8665 case BUILTIN_PRINTLN:
8667 const Expression_list* args = this->args();
8668 if (args == NULL)
8670 if (this->code_ == BUILTIN_PRINT)
8671 go_warning_at(this->location(), 0,
8672 "no arguments for builtin function %<%s%>",
8673 (this->code_ == BUILTIN_PRINT
8674 ? "print"
8675 : "println"));
8677 else
8679 for (Expression_list::const_iterator p = args->begin();
8680 p != args->end();
8681 ++p)
8683 Type* type = (*p)->type();
8684 if (type->is_error()
8685 || type->is_string_type()
8686 || type->integer_type() != NULL
8687 || type->float_type() != NULL
8688 || type->complex_type() != NULL
8689 || type->is_boolean_type()
8690 || type->points_to() != NULL
8691 || type->interface_type() != NULL
8692 || type->channel_type() != NULL
8693 || type->map_type() != NULL
8694 || type->function_type() != NULL
8695 || type->is_slice_type())
8697 else if ((*p)->is_type_expression())
8699 // If this is a type expression it's going to give
8700 // an error anyhow, so we don't need one here.
8702 else
8703 this->report_error(_("unsupported argument type to "
8704 "builtin function"));
8708 break;
8710 case BUILTIN_CLOSE:
8711 if (this->check_one_arg())
8713 if (this->one_arg()->type()->channel_type() == NULL)
8714 this->report_error(_("argument must be channel"));
8715 else if (!this->one_arg()->type()->channel_type()->may_send())
8716 this->report_error(_("cannot close receive-only channel"));
8718 break;
8720 case BUILTIN_PANIC:
8721 case BUILTIN_SIZEOF:
8722 case BUILTIN_ALIGNOF:
8723 this->check_one_arg();
8724 break;
8726 case BUILTIN_RECOVER:
8727 if (this->args() != NULL
8728 && !this->args()->empty()
8729 && !this->recover_arg_is_set_)
8730 this->report_error(_("too many arguments"));
8731 break;
8733 case BUILTIN_OFFSETOF:
8734 if (this->check_one_arg())
8736 Expression* arg = this->one_arg();
8737 if (arg->field_reference_expression() == NULL)
8738 this->report_error(_("argument must be a field reference"));
8740 break;
8742 case BUILTIN_COPY:
8744 const Expression_list* args = this->args();
8745 if (args == NULL || args->size() < 2)
8747 this->report_error(_("not enough arguments"));
8748 break;
8750 else if (args->size() > 2)
8752 this->report_error(_("too many arguments"));
8753 break;
8755 Type* arg1_type = args->front()->type();
8756 Type* arg2_type = args->back()->type();
8757 if (arg1_type->is_error() || arg2_type->is_error())
8759 this->set_is_error();
8760 break;
8763 Type* e1;
8764 if (arg1_type->is_slice_type())
8765 e1 = arg1_type->array_type()->element_type();
8766 else
8768 this->report_error(_("left argument must be a slice"));
8769 break;
8772 if (arg2_type->is_slice_type())
8774 Type* e2 = arg2_type->array_type()->element_type();
8775 if (!Type::are_identical(e1, e2, true, NULL))
8776 this->report_error(_("element types must be the same"));
8778 else if (arg2_type->is_string_type())
8780 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8781 this->report_error(_("first argument must be []byte"));
8783 else
8784 this->report_error(_("second argument must be slice or string"));
8786 break;
8788 case BUILTIN_APPEND:
8790 const Expression_list* args = this->args();
8791 if (args == NULL || args->empty())
8793 this->report_error(_("not enough arguments"));
8794 break;
8797 Type* slice_type = args->front()->type();
8798 if (!slice_type->is_slice_type())
8800 if (slice_type->is_error_type())
8801 break;
8802 if (slice_type->is_nil_type())
8803 go_error_at(args->front()->location(), "use of untyped nil");
8804 else
8805 go_error_at(args->front()->location(),
8806 "argument 1 must be a slice");
8807 this->set_is_error();
8808 break;
8811 Type* element_type = slice_type->array_type()->element_type();
8812 if (!element_type->in_heap())
8813 go_error_at(args->front()->location(),
8814 "can't append to slice of go:notinheap type");
8815 if (this->is_varargs())
8817 if (!args->back()->type()->is_slice_type()
8818 && !args->back()->type()->is_string_type())
8820 go_error_at(args->back()->location(),
8821 "invalid use of %<...%> with non-slice/non-string");
8822 this->set_is_error();
8823 break;
8826 if (args->size() < 2)
8828 this->report_error(_("not enough arguments"));
8829 break;
8831 if (args->size() > 2)
8833 this->report_error(_("too many arguments"));
8834 break;
8837 if (args->back()->type()->is_string_type()
8838 && element_type->integer_type() != NULL
8839 && element_type->integer_type()->is_byte())
8841 // Permit append(s1, s2...) when s1 is a slice of
8842 // bytes and s2 is a string type.
8844 else
8846 // We have to test for assignment compatibility to a
8847 // slice of the element type, which is not necessarily
8848 // the same as the type of the first argument: the
8849 // first argument might have a named type.
8850 Type* check_type = Type::make_array_type(element_type, NULL);
8851 std::string reason;
8852 if (!Type::are_assignable(check_type, args->back()->type(),
8853 &reason))
8855 if (reason.empty())
8856 go_error_at(args->back()->location(),
8857 "argument 2 has invalid type");
8858 else
8859 go_error_at(args->back()->location(),
8860 "argument 2 has invalid type (%s)",
8861 reason.c_str());
8862 this->set_is_error();
8863 break;
8867 else
8869 Expression_list::const_iterator pa = args->begin();
8870 int i = 2;
8871 for (++pa; pa != args->end(); ++pa, ++i)
8873 std::string reason;
8874 if (!Type::are_assignable(element_type, (*pa)->type(),
8875 &reason))
8877 if (reason.empty())
8878 go_error_at((*pa)->location(),
8879 "argument %d has incompatible type", i);
8880 else
8881 go_error_at((*pa)->location(),
8882 "argument %d has incompatible type (%s)",
8883 i, reason.c_str());
8884 this->set_is_error();
8889 break;
8891 case BUILTIN_REAL:
8892 case BUILTIN_IMAG:
8893 if (this->check_one_arg())
8895 if (this->one_arg()->type()->complex_type() == NULL)
8896 this->report_error(_("argument must have complex type"));
8898 break;
8900 case BUILTIN_COMPLEX:
8902 const Expression_list* args = this->args();
8903 if (args == NULL || args->size() < 2)
8904 this->report_error(_("not enough arguments"));
8905 else if (args->size() > 2)
8906 this->report_error(_("too many arguments"));
8907 else if (args->front()->is_error_expression()
8908 || args->front()->type()->is_error()
8909 || args->back()->is_error_expression()
8910 || args->back()->type()->is_error())
8911 this->set_is_error();
8912 else if (!Type::are_identical(args->front()->type(),
8913 args->back()->type(), true, NULL))
8914 this->report_error(_("complex arguments must have identical types"));
8915 else if (args->front()->type()->float_type() == NULL)
8916 this->report_error(_("complex arguments must have "
8917 "floating-point type"));
8919 break;
8921 default:
8922 go_unreachable();
8926 Expression*
8927 Builtin_call_expression::do_copy()
8929 Call_expression* bce =
8930 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8931 (this->args() == NULL
8932 ? NULL
8933 : this->args()->copy()),
8934 this->is_varargs(),
8935 this->location());
8937 if (this->varargs_are_lowered())
8938 bce->set_varargs_are_lowered();
8939 return bce;
8942 // Return the backend representation for a builtin function.
8944 Bexpression*
8945 Builtin_call_expression::do_get_backend(Translate_context* context)
8947 Gogo* gogo = context->gogo();
8948 Location location = this->location();
8950 if (this->is_erroneous_call())
8952 go_assert(saw_errors());
8953 return gogo->backend()->error_expression();
8956 switch (this->code_)
8958 case BUILTIN_INVALID:
8959 case BUILTIN_NEW:
8960 case BUILTIN_MAKE:
8961 go_unreachable();
8963 case BUILTIN_LEN:
8964 case BUILTIN_CAP:
8966 const Expression_list* args = this->args();
8967 go_assert(args != NULL && args->size() == 1);
8968 Expression* arg = args->front();
8969 Type* arg_type = arg->type();
8971 if (this->seen_)
8973 go_assert(saw_errors());
8974 return context->backend()->error_expression();
8976 this->seen_ = true;
8977 this->seen_ = false;
8978 if (arg_type->points_to() != NULL)
8980 arg_type = arg_type->points_to();
8981 go_assert(arg_type->array_type() != NULL
8982 && !arg_type->is_slice_type());
8983 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
8984 location);
8987 Type* int_type = Type::lookup_integer_type("int");
8988 Expression* val;
8989 if (this->code_ == BUILTIN_LEN)
8991 if (arg_type->is_string_type())
8992 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8993 location);
8994 else if (arg_type->array_type() != NULL)
8996 if (this->seen_)
8998 go_assert(saw_errors());
8999 return context->backend()->error_expression();
9001 this->seen_ = true;
9002 val = arg_type->array_type()->get_length(gogo, arg);
9003 this->seen_ = false;
9005 else if (arg_type->map_type() != NULL
9006 || arg_type->channel_type() != NULL)
9008 // The first field is the length. If the pointer is
9009 // nil, the length is zero.
9010 Type* pint_type = Type::make_pointer_type(int_type);
9011 arg = Expression::make_unsafe_cast(pint_type, arg, location);
9012 Expression* nil = Expression::make_nil(location);
9013 nil = Expression::make_cast(pint_type, nil, location);
9014 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9015 arg, nil, location);
9016 Expression* zero = Expression::make_integer_ul(0, int_type,
9017 location);
9018 Expression* indir =
9019 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
9020 location);
9021 val = Expression::make_conditional(cmp, zero, indir, location);
9023 else
9024 go_unreachable();
9026 else
9028 if (arg_type->array_type() != NULL)
9030 if (this->seen_)
9032 go_assert(saw_errors());
9033 return context->backend()->error_expression();
9035 this->seen_ = true;
9036 val = arg_type->array_type()->get_capacity(gogo, arg);
9037 this->seen_ = false;
9039 else if (arg_type->channel_type() != NULL)
9041 // The second field is the capacity. If the pointer
9042 // is nil, the capacity is zero.
9043 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9044 Type* pint_type = Type::make_pointer_type(int_type);
9045 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
9046 arg,
9047 location);
9048 int off = int_type->integer_type()->bits() / 8;
9049 Expression* eoff = Expression::make_integer_ul(off,
9050 uintptr_type,
9051 location);
9052 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
9053 location);
9054 parg = Expression::make_unsafe_cast(pint_type, parg, location);
9055 Expression* nil = Expression::make_nil(location);
9056 nil = Expression::make_cast(pint_type, nil, location);
9057 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9058 arg, nil, location);
9059 Expression* zero = Expression::make_integer_ul(0, int_type,
9060 location);
9061 Expression* indir =
9062 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
9063 location);
9064 val = Expression::make_conditional(cmp, zero, indir, location);
9066 else
9067 go_unreachable();
9070 return Expression::make_cast(int_type, val,
9071 location)->get_backend(context);
9074 case BUILTIN_PRINT:
9075 case BUILTIN_PRINTLN:
9077 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
9079 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9080 location, 0);
9082 const Expression_list* call_args = this->args();
9083 if (call_args != NULL)
9085 for (Expression_list::const_iterator p = call_args->begin();
9086 p != call_args->end();
9087 ++p)
9089 if (is_ln && p != call_args->begin())
9091 Expression* print_space =
9092 Runtime::make_call(Runtime::PRINTSP, location, 0);
9094 print_stmts =
9095 Expression::make_compound(print_stmts, print_space,
9096 location);
9099 Expression* arg = *p;
9100 Type* type = arg->type();
9101 Runtime::Function code;
9102 if (type->is_string_type())
9103 code = Runtime::PRINTSTRING;
9104 else if (type->integer_type() != NULL
9105 && type->integer_type()->is_unsigned())
9107 Type* itype = Type::lookup_integer_type("uint64");
9108 arg = Expression::make_cast(itype, arg, location);
9109 code = Runtime::PRINTUINT;
9111 else if (type->integer_type() != NULL)
9113 Type* itype = Type::lookup_integer_type("int64");
9114 arg = Expression::make_cast(itype, arg, location);
9115 code = Runtime::PRINTINT;
9117 else if (type->float_type() != NULL)
9119 Type* dtype = Type::lookup_float_type("float64");
9120 arg = Expression::make_cast(dtype, arg, location);
9121 code = Runtime::PRINTFLOAT;
9123 else if (type->complex_type() != NULL)
9125 Type* ctype = Type::lookup_complex_type("complex128");
9126 arg = Expression::make_cast(ctype, arg, location);
9127 code = Runtime::PRINTCOMPLEX;
9129 else if (type->is_boolean_type())
9130 code = Runtime::PRINTBOOL;
9131 else if (type->points_to() != NULL
9132 || type->channel_type() != NULL
9133 || type->map_type() != NULL
9134 || type->function_type() != NULL)
9136 arg = Expression::make_cast(type, arg, location);
9137 code = Runtime::PRINTPOINTER;
9139 else if (type->interface_type() != NULL)
9141 if (type->interface_type()->is_empty())
9142 code = Runtime::PRINTEFACE;
9143 else
9144 code = Runtime::PRINTIFACE;
9146 else if (type->is_slice_type())
9147 code = Runtime::PRINTSLICE;
9148 else
9150 go_assert(saw_errors());
9151 return context->backend()->error_expression();
9154 Expression* call = Runtime::make_call(code, location, 1, arg);
9155 print_stmts = Expression::make_compound(print_stmts, call,
9156 location);
9160 if (is_ln)
9162 Expression* print_nl =
9163 Runtime::make_call(Runtime::PRINTNL, location, 0);
9164 print_stmts = Expression::make_compound(print_stmts, print_nl,
9165 location);
9168 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9169 location, 0);
9170 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9172 return print_stmts->get_backend(context);
9175 case BUILTIN_PANIC:
9177 const Expression_list* args = this->args();
9178 go_assert(args != NULL && args->size() == 1);
9179 Expression* arg = args->front();
9180 Type *empty =
9181 Type::make_empty_interface_type(Linemap::predeclared_location());
9182 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9184 Expression* panic =
9185 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9186 return panic->get_backend(context);
9189 case BUILTIN_RECOVER:
9191 // The argument is set when building recover thunks. It's a
9192 // boolean value which is true if we can recover a value now.
9193 const Expression_list* args = this->args();
9194 go_assert(args != NULL && args->size() == 1);
9195 Expression* arg = args->front();
9196 Type *empty =
9197 Type::make_empty_interface_type(Linemap::predeclared_location());
9199 Expression* nil = Expression::make_nil(location);
9200 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9202 // We need to handle a deferred call to recover specially,
9203 // because it changes whether it can recover a panic or not.
9204 // See test7 in test/recover1.go.
9205 Expression* recover = Runtime::make_call((this->is_deferred()
9206 ? Runtime::DEFERREDRECOVER
9207 : Runtime::GORECOVER),
9208 location, 0);
9209 Expression* cond =
9210 Expression::make_conditional(arg, recover, nil, location);
9211 return cond->get_backend(context);
9214 case BUILTIN_CLOSE:
9216 const Expression_list* args = this->args();
9217 go_assert(args != NULL && args->size() == 1);
9218 Expression* arg = args->front();
9219 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9220 1, arg);
9221 return close->get_backend(context);
9224 case BUILTIN_SIZEOF:
9225 case BUILTIN_OFFSETOF:
9226 case BUILTIN_ALIGNOF:
9228 Numeric_constant nc;
9229 unsigned long val;
9230 if (!this->numeric_constant_value(&nc)
9231 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9233 go_assert(saw_errors());
9234 return context->backend()->error_expression();
9236 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9237 mpz_t ival;
9238 nc.get_int(&ival);
9239 Expression* int_cst =
9240 Expression::make_integer_z(&ival, uintptr_type, location);
9241 mpz_clear(ival);
9242 return int_cst->get_backend(context);
9245 case BUILTIN_COPY:
9247 const Expression_list* args = this->args();
9248 go_assert(args != NULL && args->size() == 2);
9249 Expression* arg1 = args->front();
9250 Expression* arg2 = args->back();
9252 Type* arg1_type = arg1->type();
9253 Array_type* at = arg1_type->array_type();
9254 go_assert(arg1->is_variable());
9256 Expression* call;
9258 Type* arg2_type = arg2->type();
9259 go_assert(arg2->is_variable());
9260 if (arg2_type->is_string_type())
9261 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9262 2, arg1, arg2);
9263 else
9265 Type* et = at->element_type();
9266 if (et->has_pointer())
9268 Expression* td = Expression::make_type_descriptor(et,
9269 location);
9270 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9271 3, td, arg1, arg2);
9273 else
9275 Expression* sz = Expression::make_type_info(et,
9276 TYPE_INFO_SIZE);
9277 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9278 arg1, arg2, sz);
9282 return call->get_backend(context);
9285 case BUILTIN_APPEND:
9286 // Handled in Builtin_call_expression::flatten_append.
9287 go_unreachable();
9289 case BUILTIN_REAL:
9290 case BUILTIN_IMAG:
9292 const Expression_list* args = this->args();
9293 go_assert(args != NULL && args->size() == 1);
9295 Bexpression* ret;
9296 Bexpression* bcomplex = args->front()->get_backend(context);
9297 if (this->code_ == BUILTIN_REAL)
9298 ret = gogo->backend()->real_part_expression(bcomplex, location);
9299 else
9300 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9301 return ret;
9304 case BUILTIN_COMPLEX:
9306 const Expression_list* args = this->args();
9307 go_assert(args != NULL && args->size() == 2);
9308 Bexpression* breal = args->front()->get_backend(context);
9309 Bexpression* bimag = args->back()->get_backend(context);
9310 return gogo->backend()->complex_expression(breal, bimag, location);
9313 default:
9314 go_unreachable();
9318 // We have to support exporting a builtin call expression, because
9319 // code can set a constant to the result of a builtin expression.
9321 void
9322 Builtin_call_expression::do_export(Export* exp) const
9324 Numeric_constant nc;
9325 if (!this->numeric_constant_value(&nc))
9327 go_error_at(this->location(), "value is not constant");
9328 return;
9331 if (nc.is_int())
9333 mpz_t val;
9334 nc.get_int(&val);
9335 Integer_expression::export_integer(exp, val);
9336 mpz_clear(val);
9338 else if (nc.is_float())
9340 mpfr_t fval;
9341 nc.get_float(&fval);
9342 Float_expression::export_float(exp, fval);
9343 mpfr_clear(fval);
9345 else if (nc.is_complex())
9347 mpc_t cval;
9348 nc.get_complex(&cval);
9349 Complex_expression::export_complex(exp, cval);
9350 mpc_clear(cval);
9352 else
9353 go_unreachable();
9355 // A trailing space lets us reliably identify the end of the number.
9356 exp->write_c_string(" ");
9359 // Class Call_expression.
9361 // A Go function can be viewed in a couple of different ways. The
9362 // code of a Go function becomes a backend function with parameters
9363 // whose types are simply the backend representation of the Go types.
9364 // If there are multiple results, they are returned as a backend
9365 // struct.
9367 // However, when Go code refers to a function other than simply
9368 // calling it, the backend type of that function is actually a struct.
9369 // The first field of the struct points to the Go function code
9370 // (sometimes a wrapper as described below). The remaining fields
9371 // hold addresses of closed-over variables. This struct is called a
9372 // closure.
9374 // There are a few cases to consider.
9376 // A direct function call of a known function in package scope. In
9377 // this case there are no closed-over variables, and we know the name
9378 // of the function code. We can simply produce a backend call to the
9379 // function directly, and not worry about the closure.
9381 // A direct function call of a known function literal. In this case
9382 // we know the function code and we know the closure. We generate the
9383 // function code such that it expects an additional final argument of
9384 // the closure type. We pass the closure as the last argument, after
9385 // the other arguments.
9387 // An indirect function call. In this case we have a closure. We
9388 // load the pointer to the function code from the first field of the
9389 // closure. We pass the address of the closure as the last argument.
9391 // A call to a method of an interface. Type methods are always at
9392 // package scope, so we call the function directly, and don't worry
9393 // about the closure.
9395 // This means that for a function at package scope we have two cases.
9396 // One is the direct call, which has no closure. The other is the
9397 // indirect call, which does have a closure. We can't simply ignore
9398 // the closure, even though it is the last argument, because that will
9399 // fail on targets where the function pops its arguments. So when
9400 // generating a closure for a package-scope function we set the
9401 // function code pointer in the closure to point to a wrapper
9402 // function. This wrapper function accepts a final argument that
9403 // points to the closure, ignores it, and calls the real function as a
9404 // direct function call. This wrapper will normally be efficient, and
9405 // can often simply be a tail call to the real function.
9407 // We don't use GCC's static chain pointer because 1) we don't need
9408 // it; 2) GCC only permits using a static chain to call a known
9409 // function, so we can't use it for an indirect call anyhow. Since we
9410 // can't use it for an indirect call, we may as well not worry about
9411 // using it for a direct call either.
9413 // We pass the closure last rather than first because it means that
9414 // the function wrapper we put into a closure for a package-scope
9415 // function can normally just be a tail call to the real function.
9417 // For method expressions we generate a wrapper that loads the
9418 // receiver from the closure and then calls the method. This
9419 // unfortunately forces reshuffling the arguments, since there is a
9420 // new first argument, but we can't avoid reshuffling either for
9421 // method expressions or for indirect calls of package-scope
9422 // functions, and since the latter are more common we reshuffle for
9423 // method expressions.
9425 // Note that the Go code retains the Go types. The extra final
9426 // argument only appears when we convert to the backend
9427 // representation.
9429 // Traversal.
9432 Call_expression::do_traverse(Traverse* traverse)
9434 // If we are calling a function in a different package that returns
9435 // an unnamed type, this may be the only chance we get to traverse
9436 // that type. We don't traverse this->type_ because it may be a
9437 // Call_multiple_result_type that will just lead back here.
9438 if (this->type_ != NULL && !this->type_->is_error_type())
9440 Function_type *fntype = this->get_function_type();
9441 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9442 return TRAVERSE_EXIT;
9444 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9445 return TRAVERSE_EXIT;
9446 if (this->args_ != NULL)
9448 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9449 return TRAVERSE_EXIT;
9451 return TRAVERSE_CONTINUE;
9454 // Lower a call statement.
9456 Expression*
9457 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9458 Statement_inserter* inserter, int)
9460 Location loc = this->location();
9462 // A type cast can look like a function call.
9463 if (this->fn_->is_type_expression()
9464 && this->args_ != NULL
9465 && this->args_->size() == 1)
9466 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9467 loc);
9469 // Because do_type will return an error type and thus prevent future
9470 // errors, check for that case now to ensure that the error gets
9471 // reported.
9472 Function_type* fntype = this->get_function_type();
9473 if (fntype == NULL)
9475 if (!this->fn_->type()->is_error())
9476 this->report_error(_("expected function"));
9477 this->set_is_error();
9478 return this;
9481 // Handle an argument which is a call to a function which returns
9482 // multiple results.
9483 if (this->args_ != NULL
9484 && this->args_->size() == 1
9485 && this->args_->front()->call_expression() != NULL)
9487 size_t rc = this->args_->front()->call_expression()->result_count();
9488 if (rc > 1
9489 && ((fntype->parameters() != NULL
9490 && (fntype->parameters()->size() == rc
9491 || (fntype->is_varargs()
9492 && fntype->parameters()->size() - 1 <= rc)))
9493 || fntype->is_builtin()))
9495 Call_expression* call = this->args_->front()->call_expression();
9496 call->set_is_multi_value_arg();
9497 if (this->is_varargs_)
9499 // It is not clear which result of a multiple result call
9500 // the ellipsis operator should be applied to. If we unpack the
9501 // the call into its individual results here, the ellipsis will be
9502 // applied to the last result.
9503 go_error_at(call->location(),
9504 _("multiple-value argument in single-value context"));
9505 return Expression::make_error(call->location());
9508 Expression_list* args = new Expression_list;
9509 for (size_t i = 0; i < rc; ++i)
9510 args->push_back(Expression::make_call_result(call, i));
9511 // We can't return a new call expression here, because this
9512 // one may be referenced by Call_result expressions. We
9513 // also can't delete the old arguments, because we may still
9514 // traverse them somewhere up the call stack. FIXME.
9515 this->args_ = args;
9519 // Recognize a call to a builtin function.
9520 if (fntype->is_builtin())
9521 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9522 this->is_varargs_, loc);
9524 // If this call returns multiple results, create a temporary
9525 // variable to hold them.
9526 if (this->result_count() > 1 && this->call_temp_ == NULL)
9528 Struct_field_list* sfl = new Struct_field_list();
9529 Function_type* fntype = this->get_function_type();
9530 const Typed_identifier_list* results = fntype->results();
9531 Location loc = this->location();
9533 int i = 0;
9534 char buf[20];
9535 for (Typed_identifier_list::const_iterator p = results->begin();
9536 p != results->end();
9537 ++p, ++i)
9539 snprintf(buf, sizeof buf, "res%d", i);
9540 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9543 Struct_type* st = Type::make_struct_type(sfl, loc);
9544 st->set_is_struct_incomparable();
9545 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9546 inserter->insert(this->call_temp_);
9549 // Handle a call to a varargs function by packaging up the extra
9550 // parameters.
9551 if (fntype->is_varargs())
9553 const Typed_identifier_list* parameters = fntype->parameters();
9554 go_assert(parameters != NULL && !parameters->empty());
9555 Type* varargs_type = parameters->back().type();
9556 this->lower_varargs(gogo, function, inserter, varargs_type,
9557 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9560 // If this is call to a method, call the method directly passing the
9561 // object as the first parameter.
9562 Bound_method_expression* bme = this->fn_->bound_method_expression();
9563 if (bme != NULL)
9565 Named_object* methodfn = bme->function();
9566 Expression* first_arg = bme->first_argument();
9568 // We always pass a pointer when calling a method.
9569 if (first_arg->type()->points_to() == NULL
9570 && !first_arg->type()->is_error())
9572 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9573 // We may need to create a temporary variable so that we can
9574 // take the address. We can't do that here because it will
9575 // mess up the order of evaluation.
9576 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9577 ue->set_create_temp();
9580 // If we are calling a method which was inherited from an
9581 // embedded struct, and the method did not get a stub, then the
9582 // first type may be wrong.
9583 Type* fatype = bme->first_argument_type();
9584 if (fatype != NULL)
9586 if (fatype->points_to() == NULL)
9587 fatype = Type::make_pointer_type(fatype);
9588 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9591 Expression_list* new_args = new Expression_list();
9592 new_args->push_back(first_arg);
9593 if (this->args_ != NULL)
9595 for (Expression_list::const_iterator p = this->args_->begin();
9596 p != this->args_->end();
9597 ++p)
9598 new_args->push_back(*p);
9601 // We have to change in place because this structure may be
9602 // referenced by Call_result_expressions. We can't delete the
9603 // old arguments, because we may be traversing them up in some
9604 // caller. FIXME.
9605 this->args_ = new_args;
9606 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9607 bme->location());
9610 // Handle a couple of special runtime functions. In the runtime
9611 // package, getcallerpc returns the PC of the caller, and
9612 // getcallersp returns the frame pointer of the caller. Implement
9613 // these by turning them into calls to GCC builtin functions. We
9614 // could implement them in normal code, but then we would have to
9615 // explicitly unwind the stack. These functions are intended to be
9616 // efficient. Note that this technique obviously only works for
9617 // direct calls, but that is the only way they are used.
9618 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9620 Func_expression* fe = this->fn_->func_expression();
9621 if (fe != NULL
9622 && fe->named_object()->is_function_declaration()
9623 && fe->named_object()->package() == NULL)
9625 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9626 if ((this->args_ == NULL || this->args_->size() == 0)
9627 && n == "getcallerpc")
9629 static Named_object* builtin_return_address;
9630 return this->lower_to_builtin(&builtin_return_address,
9631 "__builtin_return_address",
9634 else if (this->args_ != NULL
9635 && this->args_->size() == 1
9636 && n == "getcallersp")
9638 // The actual argument to getcallersp is always the
9639 // address of a parameter; we don't need that for the
9640 // GCC builtin function, so we just ignore it.
9641 static Named_object* builtin_frame_address;
9642 return this->lower_to_builtin(&builtin_frame_address,
9643 "__builtin_frame_address",
9649 return this;
9652 // Lower a call to a varargs function. FUNCTION is the function in
9653 // which the call occurs--it's not the function we are calling.
9654 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9655 // PARAM_COUNT is the number of parameters of the function we are
9656 // calling; the last of these parameters will be the varargs
9657 // parameter.
9659 void
9660 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9661 Statement_inserter* inserter,
9662 Type* varargs_type, size_t param_count,
9663 Slice_storage_escape_disp escape_disp)
9665 if (this->varargs_are_lowered_)
9666 return;
9668 Location loc = this->location();
9670 go_assert(param_count > 0);
9671 go_assert(varargs_type->is_slice_type());
9673 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9674 if (arg_count < param_count - 1)
9676 // Not enough arguments; will be caught in check_types.
9677 return;
9680 Expression_list* old_args = this->args_;
9681 Expression_list* new_args = new Expression_list();
9682 bool push_empty_arg = false;
9683 if (old_args == NULL || old_args->empty())
9685 go_assert(param_count == 1);
9686 push_empty_arg = true;
9688 else
9690 Expression_list::const_iterator pa;
9691 int i = 1;
9692 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9694 if (static_cast<size_t>(i) == param_count)
9695 break;
9696 new_args->push_back(*pa);
9699 // We have reached the varargs parameter.
9701 bool issued_error = false;
9702 if (pa == old_args->end())
9703 push_empty_arg = true;
9704 else if (pa + 1 == old_args->end() && this->is_varargs_)
9705 new_args->push_back(*pa);
9706 else if (this->is_varargs_)
9708 if ((*pa)->type()->is_slice_type())
9709 this->report_error(_("too many arguments"));
9710 else
9712 go_error_at(this->location(),
9713 _("invalid use of %<...%> with non-slice"));
9714 this->set_is_error();
9716 return;
9718 else
9720 Type* element_type = varargs_type->array_type()->element_type();
9721 Expression_list* vals = new Expression_list;
9722 for (; pa != old_args->end(); ++pa, ++i)
9724 // Check types here so that we get a better message.
9725 Type* patype = (*pa)->type();
9726 Location paloc = (*pa)->location();
9727 if (!this->check_argument_type(i, element_type, patype,
9728 paloc, issued_error))
9729 continue;
9730 vals->push_back(*pa);
9732 Slice_construction_expression* sce =
9733 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9734 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9735 sce->set_storage_does_not_escape();
9736 Expression* val = sce;
9737 gogo->lower_expression(function, inserter, &val);
9738 new_args->push_back(val);
9742 if (push_empty_arg)
9743 new_args->push_back(Expression::make_nil(loc));
9745 // We can't return a new call expression here, because this one may
9746 // be referenced by Call_result expressions. FIXME. We can't
9747 // delete OLD_ARGS because we may have both a Call_expression and a
9748 // Builtin_call_expression which refer to them. FIXME.
9749 this->args_ = new_args;
9750 this->varargs_are_lowered_ = true;
9753 // Return a call to __builtin_return_address or __builtin_frame_address.
9755 Expression*
9756 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9757 int arg)
9759 if (*pno == NULL)
9760 *pno = Gogo::declare_builtin_rf_address(name);
9762 Location loc = this->location();
9764 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9765 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9766 Expression_list *args = new Expression_list();
9767 args->push_back(a);
9768 Expression* call = Expression::make_call(fn, args, false, loc);
9770 // The builtin functions return void*, but the Go functions return uintptr.
9771 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9772 return Expression::make_cast(uintptr_type, call, loc);
9775 // Flatten a call with multiple results into a temporary.
9777 Expression*
9778 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9779 Statement_inserter* inserter)
9781 if (this->is_erroneous_call())
9783 go_assert(saw_errors());
9784 return Expression::make_error(this->location());
9787 if (this->is_flattened_)
9788 return this;
9789 this->is_flattened_ = true;
9791 // Add temporary variables for all arguments that require type
9792 // conversion.
9793 Function_type* fntype = this->get_function_type();
9794 if (fntype == NULL)
9796 go_assert(saw_errors());
9797 return this;
9799 if (this->args_ != NULL && !this->args_->empty()
9800 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9802 bool is_interface_method =
9803 this->fn_->interface_field_reference_expression() != NULL;
9805 Expression_list *args = new Expression_list();
9806 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9807 Expression_list::const_iterator pa = this->args_->begin();
9808 if (!is_interface_method && fntype->is_method())
9810 // The receiver argument.
9811 args->push_back(*pa);
9812 ++pa;
9814 for (; pa != this->args_->end(); ++pa, ++pp)
9816 go_assert(pp != fntype->parameters()->end());
9817 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9818 args->push_back(*pa);
9819 else
9821 Location loc = (*pa)->location();
9822 Expression* arg = *pa;
9823 if (!arg->is_variable())
9825 Temporary_statement *temp =
9826 Statement::make_temporary(NULL, arg, loc);
9827 inserter->insert(temp);
9828 arg = Expression::make_temporary_reference(temp, loc);
9830 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9831 loc);
9832 args->push_back(arg);
9835 delete this->args_;
9836 this->args_ = args;
9839 return this;
9842 // Get the function type. This can return NULL in error cases.
9844 Function_type*
9845 Call_expression::get_function_type() const
9847 return this->fn_->type()->function_type();
9850 // Return the number of values which this call will return.
9852 size_t
9853 Call_expression::result_count() const
9855 const Function_type* fntype = this->get_function_type();
9856 if (fntype == NULL)
9857 return 0;
9858 if (fntype->results() == NULL)
9859 return 0;
9860 return fntype->results()->size();
9863 // Return the temporary that holds the result for a call with multiple
9864 // results.
9866 Temporary_statement*
9867 Call_expression::results() const
9869 if (this->call_temp_ == NULL)
9871 go_assert(saw_errors());
9872 return NULL;
9874 return this->call_temp_;
9877 // Set the number of results expected from a call expression.
9879 void
9880 Call_expression::set_expected_result_count(size_t count)
9882 go_assert(this->expected_result_count_ == 0);
9883 this->expected_result_count_ = count;
9886 // Return whether this is a call to the predeclared function recover.
9888 bool
9889 Call_expression::is_recover_call() const
9891 return this->do_is_recover_call();
9894 // Set the argument to the recover function.
9896 void
9897 Call_expression::set_recover_arg(Expression* arg)
9899 this->do_set_recover_arg(arg);
9902 // Virtual functions also implemented by Builtin_call_expression.
9904 bool
9905 Call_expression::do_is_recover_call() const
9907 return false;
9910 void
9911 Call_expression::do_set_recover_arg(Expression*)
9913 go_unreachable();
9916 // We have found an error with this call expression; return true if
9917 // we should report it.
9919 bool
9920 Call_expression::issue_error()
9922 if (this->issued_error_)
9923 return false;
9924 else
9926 this->issued_error_ = true;
9927 return true;
9931 // Whether or not this call contains errors, either in the call or the
9932 // arguments to the call.
9934 bool
9935 Call_expression::is_erroneous_call()
9937 if (this->is_error_expression() || this->fn()->is_error_expression())
9938 return true;
9940 if (this->args() == NULL)
9941 return false;
9942 for (Expression_list::iterator pa = this->args()->begin();
9943 pa != this->args()->end();
9944 ++pa)
9946 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9947 return true;
9949 return false;
9952 // Get the type.
9954 Type*
9955 Call_expression::do_type()
9957 if (this->type_ != NULL)
9958 return this->type_;
9960 Type* ret;
9961 Function_type* fntype = this->get_function_type();
9962 if (fntype == NULL)
9963 return Type::make_error_type();
9965 const Typed_identifier_list* results = fntype->results();
9966 if (results == NULL)
9967 ret = Type::make_void_type();
9968 else if (results->size() == 1)
9969 ret = results->begin()->type();
9970 else
9971 ret = Type::make_call_multiple_result_type(this);
9973 this->type_ = ret;
9975 return this->type_;
9978 // Determine types for a call expression. We can use the function
9979 // parameter types to set the types of the arguments.
9981 void
9982 Call_expression::do_determine_type(const Type_context*)
9984 if (!this->determining_types())
9985 return;
9987 this->fn_->determine_type_no_context();
9988 Function_type* fntype = this->get_function_type();
9989 const Typed_identifier_list* parameters = NULL;
9990 if (fntype != NULL)
9991 parameters = fntype->parameters();
9992 if (this->args_ != NULL)
9994 Typed_identifier_list::const_iterator pt;
9995 if (parameters != NULL)
9996 pt = parameters->begin();
9997 bool first = true;
9998 for (Expression_list::const_iterator pa = this->args_->begin();
9999 pa != this->args_->end();
10000 ++pa)
10002 if (first)
10004 first = false;
10005 // If this is a method, the first argument is the
10006 // receiver.
10007 if (fntype != NULL && fntype->is_method())
10009 Type* rtype = fntype->receiver()->type();
10010 // The receiver is always passed as a pointer.
10011 if (rtype->points_to() == NULL)
10012 rtype = Type::make_pointer_type(rtype);
10013 Type_context subcontext(rtype, false);
10014 (*pa)->determine_type(&subcontext);
10015 continue;
10019 if (parameters != NULL && pt != parameters->end())
10021 Type_context subcontext(pt->type(), false);
10022 (*pa)->determine_type(&subcontext);
10023 ++pt;
10025 else
10026 (*pa)->determine_type_no_context();
10031 // Called when determining types for a Call_expression. Return true
10032 // if we should go ahead, false if they have already been determined.
10034 bool
10035 Call_expression::determining_types()
10037 if (this->types_are_determined_)
10038 return false;
10039 else
10041 this->types_are_determined_ = true;
10042 return true;
10046 // Check types for parameter I.
10048 bool
10049 Call_expression::check_argument_type(int i, const Type* parameter_type,
10050 const Type* argument_type,
10051 Location argument_location,
10052 bool issued_error)
10054 std::string reason;
10055 if (!Type::are_assignable(parameter_type, argument_type, &reason))
10057 if (!issued_error)
10059 if (reason.empty())
10060 go_error_at(argument_location, "argument %d has incompatible type", i);
10061 else
10062 go_error_at(argument_location,
10063 "argument %d has incompatible type (%s)",
10064 i, reason.c_str());
10066 this->set_is_error();
10067 return false;
10069 return true;
10072 // Check types.
10074 void
10075 Call_expression::do_check_types(Gogo*)
10077 if (this->classification() == EXPRESSION_ERROR)
10078 return;
10080 Function_type* fntype = this->get_function_type();
10081 if (fntype == NULL)
10083 if (!this->fn_->type()->is_error())
10084 this->report_error(_("expected function"));
10085 return;
10088 if (this->expected_result_count_ != 0
10089 && this->expected_result_count_ != this->result_count())
10091 if (this->issue_error())
10092 this->report_error(_("function result count mismatch"));
10093 this->set_is_error();
10094 return;
10097 bool is_method = fntype->is_method();
10098 if (is_method)
10100 go_assert(this->args_ != NULL && !this->args_->empty());
10101 Type* rtype = fntype->receiver()->type();
10102 Expression* first_arg = this->args_->front();
10103 // We dereference the values since receivers are always passed
10104 // as pointers.
10105 std::string reason;
10106 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10107 &reason))
10109 if (reason.empty())
10110 this->report_error(_("incompatible type for receiver"));
10111 else
10113 go_error_at(this->location(),
10114 "incompatible type for receiver (%s)",
10115 reason.c_str());
10116 this->set_is_error();
10121 // Note that varargs was handled by the lower_varargs() method, so
10122 // we don't have to worry about it here unless something is wrong.
10123 if (this->is_varargs_ && !this->varargs_are_lowered_)
10125 if (!fntype->is_varargs())
10127 go_error_at(this->location(),
10128 _("invalid use of %<...%> calling non-variadic function"));
10129 this->set_is_error();
10130 return;
10134 const Typed_identifier_list* parameters = fntype->parameters();
10135 if (this->args_ == NULL || this->args_->size() == 0)
10137 if (parameters != NULL && !parameters->empty())
10138 this->report_error(_("not enough arguments"));
10140 else if (parameters == NULL)
10142 if (!is_method || this->args_->size() > 1)
10143 this->report_error(_("too many arguments"));
10145 else if (this->args_->size() == 1
10146 && this->args_->front()->call_expression() != NULL
10147 && this->args_->front()->call_expression()->result_count() > 1)
10149 // This is F(G()) when G returns more than one result. If the
10150 // results can be matched to parameters, it would have been
10151 // lowered in do_lower. If we get here we know there is a
10152 // mismatch.
10153 if (this->args_->front()->call_expression()->result_count()
10154 < parameters->size())
10155 this->report_error(_("not enough arguments"));
10156 else
10157 this->report_error(_("too many arguments"));
10159 else
10161 int i = 0;
10162 Expression_list::const_iterator pa = this->args_->begin();
10163 if (is_method)
10164 ++pa;
10165 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10166 pt != parameters->end();
10167 ++pt, ++pa, ++i)
10169 if (pa == this->args_->end())
10171 this->report_error(_("not enough arguments"));
10172 return;
10174 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10175 (*pa)->location(), false);
10177 if (pa != this->args_->end())
10178 this->report_error(_("too many arguments"));
10182 Expression*
10183 Call_expression::do_copy()
10185 Call_expression* call =
10186 Expression::make_call(this->fn_->copy(),
10187 (this->args_ == NULL
10188 ? NULL
10189 : this->args_->copy()),
10190 this->is_varargs_, this->location());
10192 if (this->varargs_are_lowered_)
10193 call->set_varargs_are_lowered();
10194 return call;
10197 // Return whether we have to use a temporary variable to ensure that
10198 // we evaluate this call expression in order. If the call returns no
10199 // results then it will inevitably be executed last.
10201 bool
10202 Call_expression::do_must_eval_in_order() const
10204 return this->result_count() > 0;
10207 // Get the function and the first argument to use when calling an
10208 // interface method.
10210 Expression*
10211 Call_expression::interface_method_function(
10212 Interface_field_reference_expression* interface_method,
10213 Expression** first_arg_ptr,
10214 Location location)
10216 Expression* object = interface_method->get_underlying_object();
10217 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10218 *first_arg_ptr =
10219 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10220 return interface_method->get_function();
10223 // Build the call expression.
10225 Bexpression*
10226 Call_expression::do_get_backend(Translate_context* context)
10228 Location location = this->location();
10230 if (this->call_ != NULL)
10232 // If the call returns multiple results, make a new reference to
10233 // the temporary.
10234 if (this->call_temp_ != NULL)
10236 Expression* ref =
10237 Expression::make_temporary_reference(this->call_temp_, location);
10238 return ref->get_backend(context);
10241 return this->call_;
10244 Function_type* fntype = this->get_function_type();
10245 if (fntype == NULL)
10246 return context->backend()->error_expression();
10248 if (this->fn_->is_error_expression())
10249 return context->backend()->error_expression();
10251 Gogo* gogo = context->gogo();
10253 Func_expression* func = this->fn_->func_expression();
10254 Interface_field_reference_expression* interface_method =
10255 this->fn_->interface_field_reference_expression();
10256 const bool has_closure = func != NULL && func->closure() != NULL;
10257 const bool is_interface_method = interface_method != NULL;
10259 bool has_closure_arg;
10260 if (has_closure)
10261 has_closure_arg = true;
10262 else if (func != NULL)
10263 has_closure_arg = false;
10264 else if (is_interface_method)
10265 has_closure_arg = false;
10266 else
10267 has_closure_arg = true;
10269 int nargs;
10270 std::vector<Bexpression*> fn_args;
10271 if (this->args_ == NULL || this->args_->empty())
10273 nargs = is_interface_method ? 1 : 0;
10274 if (nargs > 0)
10275 fn_args.resize(1);
10277 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10279 // Passing a receiver parameter.
10280 go_assert(!is_interface_method
10281 && fntype->is_method()
10282 && this->args_->size() == 1);
10283 nargs = 1;
10284 fn_args.resize(1);
10285 fn_args[0] = this->args_->front()->get_backend(context);
10287 else
10289 const Typed_identifier_list* params = fntype->parameters();
10291 nargs = this->args_->size();
10292 int i = is_interface_method ? 1 : 0;
10293 nargs += i;
10294 fn_args.resize(nargs);
10296 Typed_identifier_list::const_iterator pp = params->begin();
10297 Expression_list::const_iterator pe = this->args_->begin();
10298 if (!is_interface_method && fntype->is_method())
10300 fn_args[i] = (*pe)->get_backend(context);
10301 ++pe;
10302 ++i;
10304 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10306 go_assert(pp != params->end());
10307 Expression* arg =
10308 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10309 location);
10310 fn_args[i] = arg->get_backend(context);
10312 go_assert(pp == params->end());
10313 go_assert(i == nargs);
10316 Expression* fn;
10317 Expression* closure = NULL;
10318 if (func != NULL)
10320 Named_object* no = func->named_object();
10321 fn = Expression::make_func_code_reference(no, location);
10322 if (has_closure)
10323 closure = func->closure();
10325 else if (!is_interface_method)
10327 closure = this->fn_;
10329 // The backend representation of this function type is a pointer
10330 // to a struct whose first field is the actual function to call.
10331 Type* pfntype =
10332 Type::make_pointer_type(
10333 Type::make_pointer_type(Type::make_void_type()));
10334 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10335 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10337 else
10339 Expression* first_arg;
10340 fn = this->interface_method_function(interface_method, &first_arg,
10341 location);
10342 fn_args[0] = first_arg->get_backend(context);
10345 Bexpression* bclosure = NULL;
10346 if (has_closure_arg)
10347 bclosure = closure->get_backend(context);
10348 else
10349 go_assert(closure == NULL);
10351 Bexpression* bfn = fn->get_backend(context);
10353 // When not calling a named function directly, use a type conversion
10354 // in case the type of the function is a recursive type which refers
10355 // to itself. We don't do this for an interface method because 1)
10356 // an interface method never refers to itself, so we always have a
10357 // function type here; 2) we pass an extra first argument to an
10358 // interface method, so fntype is not correct.
10359 if (func == NULL && !is_interface_method)
10361 Btype* bft = fntype->get_backend_fntype(gogo);
10362 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10365 Bfunction* bfunction = NULL;
10366 if (context->function())
10367 bfunction = context->function()->func_value()->get_decl();
10368 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10369 fn_args, bclosure,
10370 location);
10372 if (this->call_temp_ != NULL)
10374 // This case occurs when the call returns multiple results.
10376 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10377 location);
10378 Bexpression* bref = ref->get_backend(context);
10379 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10380 bref, call,
10381 location);
10383 ref = Expression::make_temporary_reference(this->call_temp_, location);
10384 this->call_ = ref->get_backend(context);
10386 return gogo->backend()->compound_expression(bassn, this->call_,
10387 location);
10390 this->call_ = call;
10391 return this->call_;
10394 // Dump ast representation for a call expressin.
10396 void
10397 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10399 this->fn_->dump_expression(ast_dump_context);
10400 ast_dump_context->ostream() << "(";
10401 if (args_ != NULL)
10402 ast_dump_context->dump_expression_list(this->args_);
10404 ast_dump_context->ostream() << ") ";
10407 // Make a call expression.
10409 Call_expression*
10410 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10411 Location location)
10413 return new Call_expression(fn, args, is_varargs, location);
10416 // Class Call_result_expression.
10418 // Traverse a call result.
10421 Call_result_expression::do_traverse(Traverse* traverse)
10423 if (traverse->remember_expression(this->call_))
10425 // We have already traversed the call expression.
10426 return TRAVERSE_CONTINUE;
10428 return Expression::traverse(&this->call_, traverse);
10431 // Get the type.
10433 Type*
10434 Call_result_expression::do_type()
10436 if (this->classification() == EXPRESSION_ERROR)
10437 return Type::make_error_type();
10439 // THIS->CALL_ can be replaced with a temporary reference due to
10440 // Call_expression::do_must_eval_in_order when there is an error.
10441 Call_expression* ce = this->call_->call_expression();
10442 if (ce == NULL)
10444 this->set_is_error();
10445 return Type::make_error_type();
10447 Function_type* fntype = ce->get_function_type();
10448 if (fntype == NULL)
10450 if (ce->issue_error())
10452 if (!ce->fn()->type()->is_error())
10453 this->report_error(_("expected function"));
10455 this->set_is_error();
10456 return Type::make_error_type();
10458 const Typed_identifier_list* results = fntype->results();
10459 if (results == NULL || results->size() < 2)
10461 if (ce->issue_error())
10462 this->report_error(_("number of results does not match "
10463 "number of values"));
10464 return Type::make_error_type();
10466 Typed_identifier_list::const_iterator pr = results->begin();
10467 for (unsigned int i = 0; i < this->index_; ++i)
10469 if (pr == results->end())
10470 break;
10471 ++pr;
10473 if (pr == results->end())
10475 if (ce->issue_error())
10476 this->report_error(_("number of results does not match "
10477 "number of values"));
10478 return Type::make_error_type();
10480 return pr->type();
10483 // Check the type. Just make sure that we trigger the warning in
10484 // do_type.
10486 void
10487 Call_result_expression::do_check_types(Gogo*)
10489 this->type();
10492 // Determine the type. We have nothing to do here, but the 0 result
10493 // needs to pass down to the caller.
10495 void
10496 Call_result_expression::do_determine_type(const Type_context*)
10498 this->call_->determine_type_no_context();
10501 // Return the backend representation. We just refer to the temporary set by the
10502 // call expression. We don't do this at lowering time because it makes it
10503 // hard to evaluate the call at the right time.
10505 Bexpression*
10506 Call_result_expression::do_get_backend(Translate_context* context)
10508 Call_expression* ce = this->call_->call_expression();
10509 if (ce == NULL)
10511 go_assert(this->call_->is_error_expression());
10512 return context->backend()->error_expression();
10514 Temporary_statement* ts = ce->results();
10515 if (ts == NULL)
10517 go_assert(saw_errors());
10518 return context->backend()->error_expression();
10520 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10521 ref = Expression::make_field_reference(ref, this->index_, this->location());
10522 return ref->get_backend(context);
10525 // Dump ast representation for a call result expression.
10527 void
10528 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10529 const
10531 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10532 // (struct) and the fields are referenced instead.
10533 ast_dump_context->ostream() << this->index_ << "@(";
10534 ast_dump_context->dump_expression(this->call_);
10535 ast_dump_context->ostream() << ")";
10538 // Make a reference to a single result of a call which returns
10539 // multiple results.
10541 Expression*
10542 Expression::make_call_result(Call_expression* call, unsigned int index)
10544 return new Call_result_expression(call, index);
10547 // Class Index_expression.
10549 // Traversal.
10552 Index_expression::do_traverse(Traverse* traverse)
10554 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10555 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10556 || (this->end_ != NULL
10557 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10558 || (this->cap_ != NULL
10559 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10560 return TRAVERSE_EXIT;
10561 return TRAVERSE_CONTINUE;
10564 // Lower an index expression. This converts the generic index
10565 // expression into an array index, a string index, or a map index.
10567 Expression*
10568 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10570 Location location = this->location();
10571 Expression* left = this->left_;
10572 Expression* start = this->start_;
10573 Expression* end = this->end_;
10574 Expression* cap = this->cap_;
10576 Type* type = left->type();
10577 if (type->is_error())
10579 go_assert(saw_errors());
10580 return Expression::make_error(location);
10582 else if (left->is_type_expression())
10584 go_error_at(location, "attempt to index type expression");
10585 return Expression::make_error(location);
10587 else if (type->array_type() != NULL)
10588 return Expression::make_array_index(left, start, end, cap, location);
10589 else if (type->points_to() != NULL
10590 && type->points_to()->array_type() != NULL
10591 && !type->points_to()->is_slice_type())
10593 Expression* deref =
10594 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10596 // For an ordinary index into the array, the pointer will be
10597 // dereferenced. For a slice it will not--the resulting slice
10598 // will simply reuse the pointer, which is incorrect if that
10599 // pointer is nil.
10600 if (end != NULL || cap != NULL)
10601 deref->issue_nil_check();
10603 return Expression::make_array_index(deref, start, end, cap, location);
10605 else if (type->is_string_type())
10607 if (cap != NULL)
10609 go_error_at(location, "invalid 3-index slice of string");
10610 return Expression::make_error(location);
10612 return Expression::make_string_index(left, start, end, location);
10614 else if (type->map_type() != NULL)
10616 if (end != NULL || cap != NULL)
10618 go_error_at(location, "invalid slice of map");
10619 return Expression::make_error(location);
10621 return Expression::make_map_index(left, start, location);
10623 else if (cap != NULL)
10625 go_error_at(location,
10626 "invalid 3-index slice of object that is not a slice");
10627 return Expression::make_error(location);
10629 else if (end != NULL)
10631 go_error_at(location,
10632 ("attempt to slice object that is not "
10633 "array, slice, or string"));
10634 return Expression::make_error(location);
10636 else
10638 go_error_at(location,
10639 ("attempt to index object that is not "
10640 "array, slice, string, or map"));
10641 return Expression::make_error(location);
10645 // Write an indexed expression
10646 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10648 void
10649 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10650 const Expression* expr,
10651 const Expression* start,
10652 const Expression* end,
10653 const Expression* cap)
10655 expr->dump_expression(ast_dump_context);
10656 ast_dump_context->ostream() << "[";
10657 start->dump_expression(ast_dump_context);
10658 if (end != NULL)
10660 ast_dump_context->ostream() << ":";
10661 end->dump_expression(ast_dump_context);
10663 if (cap != NULL)
10665 ast_dump_context->ostream() << ":";
10666 cap->dump_expression(ast_dump_context);
10668 ast_dump_context->ostream() << "]";
10671 // Dump ast representation for an index expression.
10673 void
10674 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10675 const
10677 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10678 this->start_, this->end_, this->cap_);
10681 // Make an index expression.
10683 Expression*
10684 Expression::make_index(Expression* left, Expression* start, Expression* end,
10685 Expression* cap, Location location)
10687 return new Index_expression(left, start, end, cap, location);
10690 // Class Array_index_expression.
10692 // Array index traversal.
10695 Array_index_expression::do_traverse(Traverse* traverse)
10697 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10698 return TRAVERSE_EXIT;
10699 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10700 return TRAVERSE_EXIT;
10701 if (this->end_ != NULL)
10703 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10704 return TRAVERSE_EXIT;
10706 if (this->cap_ != NULL)
10708 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10709 return TRAVERSE_EXIT;
10711 return TRAVERSE_CONTINUE;
10714 // Return the type of an array index.
10716 Type*
10717 Array_index_expression::do_type()
10719 if (this->type_ == NULL)
10721 Array_type* type = this->array_->type()->array_type();
10722 if (type == NULL)
10723 this->type_ = Type::make_error_type();
10724 else if (this->end_ == NULL)
10725 this->type_ = type->element_type();
10726 else if (type->is_slice_type())
10728 // A slice of a slice has the same type as the original
10729 // slice.
10730 this->type_ = this->array_->type()->deref();
10732 else
10734 // A slice of an array is a slice.
10735 this->type_ = Type::make_array_type(type->element_type(), NULL);
10738 return this->type_;
10741 // Set the type of an array index.
10743 void
10744 Array_index_expression::do_determine_type(const Type_context*)
10746 this->array_->determine_type_no_context();
10748 Type_context index_context(Type::lookup_integer_type("int"), false);
10749 if (this->start_->is_constant())
10750 this->start_->determine_type(&index_context);
10751 else
10752 this->start_->determine_type_no_context();
10753 if (this->end_ != NULL)
10755 if (this->end_->is_constant())
10756 this->end_->determine_type(&index_context);
10757 else
10758 this->end_->determine_type_no_context();
10760 if (this->cap_ != NULL)
10762 if (this->cap_->is_constant())
10763 this->cap_->determine_type(&index_context);
10764 else
10765 this->cap_->determine_type_no_context();
10769 // Check types of an array index.
10771 void
10772 Array_index_expression::do_check_types(Gogo*)
10774 Numeric_constant nc;
10775 unsigned long v;
10776 if (this->start_->type()->integer_type() == NULL
10777 && !this->start_->type()->is_error()
10778 && (!this->start_->numeric_constant_value(&nc)
10779 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10780 this->report_error(_("index must be integer"));
10781 if (this->end_ != NULL
10782 && this->end_->type()->integer_type() == NULL
10783 && !this->end_->type()->is_error()
10784 && !this->end_->is_nil_expression()
10785 && !this->end_->is_error_expression()
10786 && (!this->end_->numeric_constant_value(&nc)
10787 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10788 this->report_error(_("slice end must be integer"));
10789 if (this->cap_ != NULL
10790 && this->cap_->type()->integer_type() == NULL
10791 && !this->cap_->type()->is_error()
10792 && !this->cap_->is_nil_expression()
10793 && !this->cap_->is_error_expression()
10794 && (!this->cap_->numeric_constant_value(&nc)
10795 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10796 this->report_error(_("slice capacity must be integer"));
10798 Array_type* array_type = this->array_->type()->array_type();
10799 if (array_type == NULL)
10801 go_assert(this->array_->type()->is_error());
10802 return;
10805 unsigned int int_bits =
10806 Type::lookup_integer_type("int")->integer_type()->bits();
10808 Numeric_constant lvalnc;
10809 mpz_t lval;
10810 bool lval_valid = (array_type->length() != NULL
10811 && array_type->length()->numeric_constant_value(&lvalnc)
10812 && lvalnc.to_int(&lval));
10813 Numeric_constant inc;
10814 mpz_t ival;
10815 bool ival_valid = false;
10816 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10818 ival_valid = true;
10819 if (mpz_sgn(ival) < 0
10820 || mpz_sizeinbase(ival, 2) >= int_bits
10821 || (lval_valid
10822 && (this->end_ == NULL
10823 ? mpz_cmp(ival, lval) >= 0
10824 : mpz_cmp(ival, lval) > 0)))
10826 go_error_at(this->start_->location(), "array index out of bounds");
10827 this->set_is_error();
10830 if (this->end_ != NULL && !this->end_->is_nil_expression())
10832 Numeric_constant enc;
10833 mpz_t eval;
10834 bool eval_valid = false;
10835 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10837 eval_valid = true;
10838 if (mpz_sgn(eval) < 0
10839 || mpz_sizeinbase(eval, 2) >= int_bits
10840 || (lval_valid && mpz_cmp(eval, lval) > 0))
10842 go_error_at(this->end_->location(), "array index out of bounds");
10843 this->set_is_error();
10845 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10846 this->report_error(_("inverted slice range"));
10849 Numeric_constant cnc;
10850 mpz_t cval;
10851 if (this->cap_ != NULL
10852 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10854 if (mpz_sgn(cval) < 0
10855 || mpz_sizeinbase(cval, 2) >= int_bits
10856 || (lval_valid && mpz_cmp(cval, lval) > 0))
10858 go_error_at(this->cap_->location(), "array index out of bounds");
10859 this->set_is_error();
10861 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10863 go_error_at(this->cap_->location(),
10864 "invalid slice index: capacity less than start");
10865 this->set_is_error();
10867 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10869 go_error_at(this->cap_->location(),
10870 "invalid slice index: capacity less than length");
10871 this->set_is_error();
10873 mpz_clear(cval);
10876 if (eval_valid)
10877 mpz_clear(eval);
10879 if (ival_valid)
10880 mpz_clear(ival);
10881 if (lval_valid)
10882 mpz_clear(lval);
10884 // A slice of an array requires an addressable array. A slice of a
10885 // slice is always possible.
10886 if (this->end_ != NULL && !array_type->is_slice_type())
10888 if (!this->array_->is_addressable())
10889 this->report_error(_("slice of unaddressable value"));
10890 else
10891 // Set the array address taken but not escape. The escape
10892 // analysis will make it escape to heap when needed.
10893 this->array_->address_taken(false);
10897 // Flatten array indexing by using temporary variables for slices and indexes.
10899 Expression*
10900 Array_index_expression::do_flatten(Gogo*, Named_object*,
10901 Statement_inserter* inserter)
10903 Location loc = this->location();
10904 Expression* array = this->array_;
10905 Expression* start = this->start_;
10906 Expression* end = this->end_;
10907 Expression* cap = this->cap_;
10908 if (array->is_error_expression()
10909 || array->type()->is_error_type()
10910 || start->is_error_expression()
10911 || start->type()->is_error_type()
10912 || (end != NULL
10913 && (end->is_error_expression() || end->type()->is_error_type()))
10914 || (cap != NULL
10915 && (cap->is_error_expression() || cap->type()->is_error_type())))
10917 go_assert(saw_errors());
10918 return Expression::make_error(loc);
10921 Temporary_statement* temp;
10922 if (array->type()->is_slice_type() && !array->is_variable())
10924 temp = Statement::make_temporary(NULL, array, loc);
10925 inserter->insert(temp);
10926 this->array_ = Expression::make_temporary_reference(temp, loc);
10928 if (!start->is_variable())
10930 temp = Statement::make_temporary(NULL, start, loc);
10931 inserter->insert(temp);
10932 this->start_ = Expression::make_temporary_reference(temp, loc);
10934 if (end != NULL
10935 && !end->is_nil_expression()
10936 && !end->is_variable())
10938 temp = Statement::make_temporary(NULL, end, loc);
10939 inserter->insert(temp);
10940 this->end_ = Expression::make_temporary_reference(temp, loc);
10942 if (cap != NULL && !cap->is_variable())
10944 temp = Statement::make_temporary(NULL, cap, loc);
10945 inserter->insert(temp);
10946 this->cap_ = Expression::make_temporary_reference(temp, loc);
10949 return this;
10952 // Return whether this expression is addressable.
10954 bool
10955 Array_index_expression::do_is_addressable() const
10957 // A slice expression is not addressable.
10958 if (this->end_ != NULL)
10959 return false;
10961 // An index into a slice is addressable.
10962 if (this->array_->type()->is_slice_type())
10963 return true;
10965 // An index into an array is addressable if the array is
10966 // addressable.
10967 return this->array_->is_addressable();
10970 void
10971 Array_index_expression::do_address_taken(bool escapes)
10973 // In &x[0], if x is a slice, then x's address is not taken.
10974 if (!this->array_->type()->is_slice_type())
10975 this->array_->address_taken(escapes);
10978 // Get the backend representation for an array index.
10980 Bexpression*
10981 Array_index_expression::do_get_backend(Translate_context* context)
10983 Array_type* array_type = this->array_->type()->array_type();
10984 if (array_type == NULL)
10986 go_assert(this->array_->type()->is_error());
10987 return context->backend()->error_expression();
10989 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10991 Location loc = this->location();
10992 Gogo* gogo = context->gogo();
10994 Type* int_type = Type::lookup_integer_type("int");
10995 Btype* int_btype = int_type->get_backend(gogo);
10997 // We need to convert the length and capacity to the Go "int" type here
10998 // because the length of a fixed-length array could be of type "uintptr"
10999 // and gimple disallows binary operations between "uintptr" and other
11000 // integer types. FIXME.
11001 Bexpression* length = NULL;
11002 if (this->end_ == NULL || this->end_->is_nil_expression())
11004 Expression* len = array_type->get_length(gogo, this->array_);
11005 length = len->get_backend(context);
11006 length = gogo->backend()->convert_expression(int_btype, length, loc);
11009 Bexpression* capacity = NULL;
11010 if (this->end_ != NULL)
11012 Expression* cap = array_type->get_capacity(gogo, this->array_);
11013 capacity = cap->get_backend(context);
11014 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
11017 Bexpression* cap_arg = capacity;
11018 if (this->cap_ != NULL)
11020 cap_arg = this->cap_->get_backend(context);
11021 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11024 if (length == NULL)
11025 length = cap_arg;
11027 int code = (array_type->length() != NULL
11028 ? (this->end_ == NULL
11029 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
11030 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
11031 : (this->end_ == NULL
11032 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
11033 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
11034 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11036 if (this->start_->type()->integer_type() == NULL
11037 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11039 go_assert(saw_errors());
11040 return context->backend()->error_expression();
11043 Bexpression* bad_index =
11044 Expression::check_bounds(this->start_, loc)->get_backend(context);
11046 Bexpression* start = this->start_->get_backend(context);
11047 start = gogo->backend()->convert_expression(int_btype, start, loc);
11048 Bexpression* start_too_large =
11049 gogo->backend()->binary_expression((this->end_ == NULL
11050 ? OPERATOR_GE
11051 : OPERATOR_GT),
11052 start,
11053 (this->end_ == NULL
11054 ? length
11055 : capacity),
11056 loc);
11057 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
11058 bad_index, loc);
11060 Bfunction* bfn = context->function()->func_value()->get_decl();
11061 if (this->end_ == NULL)
11063 // Simple array indexing. This has to return an l-value, so
11064 // wrap the index check into START.
11065 start =
11066 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
11067 crash, start, loc);
11069 Bexpression* ret;
11070 if (array_type->length() != NULL)
11072 Bexpression* array = this->array_->get_backend(context);
11073 ret = gogo->backend()->array_index_expression(array, start, loc);
11075 else
11077 // Slice.
11078 Expression* valptr =
11079 array_type->get_value_pointer(gogo, this->array_,
11080 this->is_lvalue_);
11081 Bexpression* ptr = valptr->get_backend(context);
11082 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11084 Type* ele_type = this->array_->type()->array_type()->element_type();
11085 Btype* ele_btype = ele_type->get_backend(gogo);
11086 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11088 return ret;
11091 // Array slice.
11093 if (this->cap_ != NULL)
11095 Bexpression* bounds_bcheck =
11096 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11097 bad_index =
11098 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11099 bad_index, loc);
11100 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11102 Bexpression* cap_too_small =
11103 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11104 Bexpression* cap_too_large =
11105 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11106 Bexpression* bad_cap =
11107 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11108 cap_too_large, loc);
11109 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11110 bad_index, loc);
11113 Bexpression* end;
11114 if (this->end_->is_nil_expression())
11115 end = length;
11116 else
11118 Bexpression* bounds_bcheck =
11119 Expression::check_bounds(this->end_, loc)->get_backend(context);
11121 bad_index =
11122 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11123 bad_index, loc);
11125 end = this->end_->get_backend(context);
11126 end = gogo->backend()->convert_expression(int_btype, end, loc);
11127 Bexpression* end_too_small =
11128 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11129 Bexpression* end_too_large =
11130 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11131 Bexpression* bad_end =
11132 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11133 end_too_large, loc);
11134 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11135 bad_index, loc);
11138 Bexpression* result_length =
11139 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11141 Bexpression* result_capacity =
11142 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11144 // If the new capacity is zero, don't change val. Otherwise we can
11145 // get a pointer to the next object in memory, keeping it live
11146 // unnecessarily. When the capacity is zero, the actual pointer
11147 // value doesn't matter.
11148 Bexpression* zero =
11149 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11150 Bexpression* cond =
11151 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11152 loc);
11153 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11154 cond, zero,
11155 start, loc);
11156 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11157 this->is_lvalue_);
11158 Bexpression* val = valptr->get_backend(context);
11159 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11161 Btype* struct_btype = this->type()->get_backend(gogo);
11162 std::vector<Bexpression*> init;
11163 init.push_back(val);
11164 init.push_back(result_length);
11165 init.push_back(result_capacity);
11167 Bexpression* ctor =
11168 gogo->backend()->constructor_expression(struct_btype, init, loc);
11169 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11170 crash, ctor, loc);
11173 // Dump ast representation for an array index expression.
11175 void
11176 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11177 const
11179 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11180 this->start_, this->end_, this->cap_);
11183 // Make an array index expression. END and CAP may be NULL.
11185 Expression*
11186 Expression::make_array_index(Expression* array, Expression* start,
11187 Expression* end, Expression* cap,
11188 Location location)
11190 return new Array_index_expression(array, start, end, cap, location);
11193 // Class String_index_expression.
11195 // String index traversal.
11198 String_index_expression::do_traverse(Traverse* traverse)
11200 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11201 return TRAVERSE_EXIT;
11202 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11203 return TRAVERSE_EXIT;
11204 if (this->end_ != NULL)
11206 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11207 return TRAVERSE_EXIT;
11209 return TRAVERSE_CONTINUE;
11212 Expression*
11213 String_index_expression::do_flatten(Gogo*, Named_object*,
11214 Statement_inserter* inserter)
11216 Location loc = this->location();
11217 Expression* string = this->string_;
11218 Expression* start = this->start_;
11219 Expression* end = this->end_;
11220 if (string->is_error_expression()
11221 || string->type()->is_error_type()
11222 || start->is_error_expression()
11223 || start->type()->is_error_type()
11224 || (end != NULL
11225 && (end->is_error_expression() || end->type()->is_error_type())))
11227 go_assert(saw_errors());
11228 return Expression::make_error(loc);
11231 Temporary_statement* temp;
11232 if (!this->string_->is_variable())
11234 temp = Statement::make_temporary(NULL, this->string_, loc);
11235 inserter->insert(temp);
11236 this->string_ = Expression::make_temporary_reference(temp, loc);
11238 if (!this->start_->is_variable())
11240 temp = Statement::make_temporary(NULL, this->start_, loc);
11241 inserter->insert(temp);
11242 this->start_ = Expression::make_temporary_reference(temp, loc);
11244 if (this->end_ != NULL
11245 && !this->end_->is_nil_expression()
11246 && !this->end_->is_variable())
11248 temp = Statement::make_temporary(NULL, this->end_, loc);
11249 inserter->insert(temp);
11250 this->end_ = Expression::make_temporary_reference(temp, loc);
11253 return this;
11256 // Return the type of a string index.
11258 Type*
11259 String_index_expression::do_type()
11261 if (this->end_ == NULL)
11262 return Type::lookup_integer_type("uint8");
11263 else
11264 return this->string_->type();
11267 // Determine the type of a string index.
11269 void
11270 String_index_expression::do_determine_type(const Type_context*)
11272 this->string_->determine_type_no_context();
11274 Type_context index_context(Type::lookup_integer_type("int"), false);
11275 if (this->start_->is_constant())
11276 this->start_->determine_type(&index_context);
11277 else
11278 this->start_->determine_type_no_context();
11279 if (this->end_ != NULL)
11281 if (this->end_->is_constant())
11282 this->end_->determine_type(&index_context);
11283 else
11284 this->end_->determine_type_no_context();
11288 // Check types of a string index.
11290 void
11291 String_index_expression::do_check_types(Gogo*)
11293 Numeric_constant nc;
11294 unsigned long v;
11295 if (this->start_->type()->integer_type() == NULL
11296 && !this->start_->type()->is_error()
11297 && (!this->start_->numeric_constant_value(&nc)
11298 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11299 this->report_error(_("index must be integer"));
11300 if (this->end_ != NULL
11301 && this->end_->type()->integer_type() == NULL
11302 && !this->end_->type()->is_error()
11303 && !this->end_->is_nil_expression()
11304 && !this->end_->is_error_expression()
11305 && (!this->end_->numeric_constant_value(&nc)
11306 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11307 this->report_error(_("slice end must be integer"));
11309 std::string sval;
11310 bool sval_valid = this->string_->string_constant_value(&sval);
11312 Numeric_constant inc;
11313 mpz_t ival;
11314 bool ival_valid = false;
11315 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11317 ival_valid = true;
11318 if (mpz_sgn(ival) < 0
11319 || (sval_valid
11320 && (this->end_ == NULL
11321 ? mpz_cmp_ui(ival, sval.length()) >= 0
11322 : mpz_cmp_ui(ival, sval.length()) > 0)))
11324 go_error_at(this->start_->location(), "string index out of bounds");
11325 this->set_is_error();
11328 if (this->end_ != NULL && !this->end_->is_nil_expression())
11330 Numeric_constant enc;
11331 mpz_t eval;
11332 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11334 if (mpz_sgn(eval) < 0
11335 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11337 go_error_at(this->end_->location(), "string index out of bounds");
11338 this->set_is_error();
11340 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11341 this->report_error(_("inverted slice range"));
11342 mpz_clear(eval);
11345 if (ival_valid)
11346 mpz_clear(ival);
11349 // Get the backend representation for a string index.
11351 Bexpression*
11352 String_index_expression::do_get_backend(Translate_context* context)
11354 Location loc = this->location();
11355 Expression* string_arg = this->string_;
11356 if (this->string_->type()->points_to() != NULL)
11357 string_arg = Expression::make_dereference(this->string_,
11358 NIL_CHECK_NOT_NEEDED, loc);
11360 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11362 int code = (this->end_ == NULL
11363 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11364 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11366 Gogo* gogo = context->gogo();
11367 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11369 Type* int_type = Type::lookup_integer_type("int");
11371 // It is possible that an error occurred earlier because the start index
11372 // cannot be represented as an integer type. In this case, we shouldn't
11373 // try casting the starting index into an integer since
11374 // Type_conversion_expression will fail to get the backend representation.
11375 // FIXME.
11376 if (this->start_->type()->integer_type() == NULL
11377 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11379 go_assert(saw_errors());
11380 return context->backend()->error_expression();
11383 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11384 Bfunction* bfn = context->function()->func_value()->get_decl();
11386 if (this->end_ == NULL)
11388 Expression* length =
11389 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11391 Expression* start_too_large =
11392 Expression::make_binary(OPERATOR_GE, start, length, loc);
11393 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11394 bad_index, loc);
11395 Expression* bytes =
11396 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11398 Bexpression* bstart = start->get_backend(context);
11399 Bexpression* ptr = bytes->get_backend(context);
11400 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11401 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11402 Bexpression* index =
11403 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11405 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11406 Bexpression* index_error = bad_index->get_backend(context);
11407 return gogo->backend()->conditional_expression(bfn, byte_btype,
11408 index_error, crash,
11409 index, loc);
11412 Expression* end = NULL;
11413 if (this->end_->is_nil_expression())
11414 end = Expression::make_integer_sl(-1, int_type, loc);
11415 else
11417 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11418 bad_index =
11419 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11420 end = Expression::make_cast(int_type, this->end_, loc);
11423 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11424 string_arg, start, end);
11425 Bexpression* bstrslice = strslice->get_backend(context);
11427 Btype* str_btype = strslice->type()->get_backend(gogo);
11428 Bexpression* index_error = bad_index->get_backend(context);
11429 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11430 crash, bstrslice, loc);
11433 // Dump ast representation for a string index expression.
11435 void
11436 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11437 const
11439 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11440 this->start_, this->end_, NULL);
11443 // Make a string index expression. END may be NULL.
11445 Expression*
11446 Expression::make_string_index(Expression* string, Expression* start,
11447 Expression* end, Location location)
11449 return new String_index_expression(string, start, end, location);
11452 // Class Map_index.
11454 // Get the type of the map.
11456 Map_type*
11457 Map_index_expression::get_map_type() const
11459 Map_type* mt = this->map_->type()->map_type();
11460 if (mt == NULL)
11461 go_assert(saw_errors());
11462 return mt;
11465 // Map index traversal.
11468 Map_index_expression::do_traverse(Traverse* traverse)
11470 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11471 return TRAVERSE_EXIT;
11472 return Expression::traverse(&this->index_, traverse);
11475 // We need to pass in a pointer to the key, so flatten the index into a
11476 // temporary variable if it isn't already. The value pointer will be
11477 // dereferenced and checked for nil, so flatten into a temporary to avoid
11478 // recomputation.
11480 Expression*
11481 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11482 Statement_inserter* inserter)
11484 Location loc = this->location();
11485 Map_type* mt = this->get_map_type();
11486 if (this->index()->is_error_expression()
11487 || this->index()->type()->is_error_type()
11488 || mt->is_error_type())
11490 go_assert(saw_errors());
11491 return Expression::make_error(loc);
11494 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11496 if (this->index_->type()->interface_type() != NULL
11497 && !this->index_->is_variable())
11499 Temporary_statement* temp =
11500 Statement::make_temporary(NULL, this->index_, loc);
11501 inserter->insert(temp);
11502 this->index_ = Expression::make_temporary_reference(temp, loc);
11504 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11505 this->index_, loc);
11508 if (!this->index_->is_variable())
11510 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11511 loc);
11512 inserter->insert(temp);
11513 this->index_ = Expression::make_temporary_reference(temp, loc);
11516 if (this->value_pointer_ == NULL)
11517 this->get_value_pointer(gogo);
11518 if (this->value_pointer_->is_error_expression()
11519 || this->value_pointer_->type()->is_error_type())
11520 return Expression::make_error(loc);
11521 if (!this->value_pointer_->is_variable())
11523 Temporary_statement* temp =
11524 Statement::make_temporary(NULL, this->value_pointer_, loc);
11525 inserter->insert(temp);
11526 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11529 return this;
11532 // Return the type of a map index.
11534 Type*
11535 Map_index_expression::do_type()
11537 Map_type* mt = this->get_map_type();
11538 if (mt == NULL)
11539 return Type::make_error_type();
11540 return mt->val_type();
11543 // Fix the type of a map index.
11545 void
11546 Map_index_expression::do_determine_type(const Type_context*)
11548 this->map_->determine_type_no_context();
11549 Map_type* mt = this->get_map_type();
11550 Type* key_type = mt == NULL ? NULL : mt->key_type();
11551 Type_context subcontext(key_type, false);
11552 this->index_->determine_type(&subcontext);
11555 // Check types of a map index.
11557 void
11558 Map_index_expression::do_check_types(Gogo*)
11560 std::string reason;
11561 Map_type* mt = this->get_map_type();
11562 if (mt == NULL)
11563 return;
11564 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11566 if (reason.empty())
11567 this->report_error(_("incompatible type for map index"));
11568 else
11570 go_error_at(this->location(), "incompatible type for map index (%s)",
11571 reason.c_str());
11572 this->set_is_error();
11577 // Get the backend representation for a map index.
11579 Bexpression*
11580 Map_index_expression::do_get_backend(Translate_context* context)
11582 Map_type* type = this->get_map_type();
11583 if (type == NULL)
11585 go_assert(saw_errors());
11586 return context->backend()->error_expression();
11589 go_assert(this->value_pointer_ != NULL
11590 && this->value_pointer_->is_variable());
11592 Expression* val = Expression::make_dereference(this->value_pointer_,
11593 NIL_CHECK_NOT_NEEDED,
11594 this->location());
11595 return val->get_backend(context);
11598 // Get an expression for the map index. This returns an expression
11599 // that evaluates to a pointer to a value. If the key is not in the
11600 // map, the pointer will point to a zero value.
11602 Expression*
11603 Map_index_expression::get_value_pointer(Gogo* gogo)
11605 if (this->value_pointer_ == NULL)
11607 Map_type* type = this->get_map_type();
11608 if (type == NULL)
11610 go_assert(saw_errors());
11611 return Expression::make_error(this->location());
11614 Location loc = this->location();
11615 Expression* map_ref = this->map_;
11617 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11618 this->index_,
11619 loc);
11621 Expression* zero = type->fat_zero_value(gogo);
11623 Expression* map_index;
11625 if (zero == NULL)
11626 map_index =
11627 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11628 Expression::make_type_descriptor(type, loc),
11629 map_ref, index_ptr);
11630 else
11631 map_index =
11632 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11633 Expression::make_type_descriptor(type, loc),
11634 map_ref, index_ptr, zero);
11636 Type* val_type = type->val_type();
11637 this->value_pointer_ =
11638 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11639 map_index, this->location());
11642 return this->value_pointer_;
11645 // Dump ast representation for a map index expression
11647 void
11648 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11649 const
11651 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11652 this->index_, NULL, NULL);
11655 // Make a map index expression.
11657 Map_index_expression*
11658 Expression::make_map_index(Expression* map, Expression* index,
11659 Location location)
11661 return new Map_index_expression(map, index, location);
11664 // Class Field_reference_expression.
11666 // Lower a field reference expression. There is nothing to lower, but
11667 // this is where we generate the tracking information for fields with
11668 // the magic go:"track" tag.
11670 Expression*
11671 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11672 Statement_inserter* inserter, int)
11674 Struct_type* struct_type = this->expr_->type()->struct_type();
11675 if (struct_type == NULL)
11677 // Error will be reported elsewhere.
11678 return this;
11680 const Struct_field* field = struct_type->field(this->field_index_);
11681 if (field == NULL)
11682 return this;
11683 if (!field->has_tag())
11684 return this;
11685 if (field->tag().find("go:\"track\"") == std::string::npos)
11686 return this;
11688 // References from functions generated by the compiler don't count.
11689 if (function != NULL && function->func_value()->is_type_specific_function())
11690 return this;
11692 // We have found a reference to a tracked field. Build a call to
11693 // the runtime function __go_fieldtrack with a string that describes
11694 // the field. FIXME: We should only call this once per referenced
11695 // field per function, not once for each reference to the field.
11697 if (this->called_fieldtrack_)
11698 return this;
11699 this->called_fieldtrack_ = true;
11701 Location loc = this->location();
11703 std::string s = "fieldtrack \"";
11704 Named_type* nt = this->expr_->type()->unalias()->named_type();
11705 if (nt == NULL || nt->named_object()->package() == NULL)
11706 s.append(gogo->pkgpath());
11707 else
11708 s.append(nt->named_object()->package()->pkgpath());
11709 s.push_back('.');
11710 if (nt != NULL)
11711 s.append(Gogo::unpack_hidden_name(nt->name()));
11712 s.push_back('.');
11713 s.append(field->field_name());
11714 s.push_back('"');
11716 // We can't use a string here, because internally a string holds a
11717 // pointer to the actual bytes; when the linker garbage collects the
11718 // string, it won't garbage collect the bytes. So we use a
11719 // [...]byte.
11721 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11723 Type* byte_type = gogo->lookup_global("byte")->type_value();
11724 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11725 array_type->set_is_array_incomparable();
11727 Expression_list* bytes = new Expression_list();
11728 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11730 unsigned char c = static_cast<unsigned char>(*p);
11731 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11734 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11735 bytes, false, loc);
11737 Variable* var = new Variable(array_type, e, true, false, false, loc);
11739 static int count;
11740 char buf[50];
11741 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11742 ++count;
11744 Named_object* no = gogo->add_variable(buf, var);
11745 e = Expression::make_var_reference(no, loc);
11746 e = Expression::make_unary(OPERATOR_AND, e, loc);
11748 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11749 gogo->lower_expression(function, inserter, &call);
11750 inserter->insert(Statement::make_statement(call, false));
11752 // Put this function, and the global variable we just created, into
11753 // unique sections. This will permit the linker to garbage collect
11754 // them if they are not referenced. The effect is that the only
11755 // strings, indicating field references, that will wind up in the
11756 // executable will be those for functions that are actually needed.
11757 if (function != NULL)
11758 function->func_value()->set_in_unique_section();
11759 var->set_in_unique_section();
11761 return this;
11764 // Return the type of a field reference.
11766 Type*
11767 Field_reference_expression::do_type()
11769 Type* type = this->expr_->type();
11770 if (type->is_error())
11771 return type;
11772 Struct_type* struct_type = type->struct_type();
11773 go_assert(struct_type != NULL);
11774 return struct_type->field(this->field_index_)->type();
11777 // Check the types for a field reference.
11779 void
11780 Field_reference_expression::do_check_types(Gogo*)
11782 Type* type = this->expr_->type();
11783 if (type->is_error())
11784 return;
11785 Struct_type* struct_type = type->struct_type();
11786 go_assert(struct_type != NULL);
11787 go_assert(struct_type->field(this->field_index_) != NULL);
11790 // Get the backend representation for a field reference.
11792 Bexpression*
11793 Field_reference_expression::do_get_backend(Translate_context* context)
11795 Bexpression* bstruct = this->expr_->get_backend(context);
11796 return context->gogo()->backend()->struct_field_expression(bstruct,
11797 this->field_index_,
11798 this->location());
11801 // Dump ast representation for a field reference expression.
11803 void
11804 Field_reference_expression::do_dump_expression(
11805 Ast_dump_context* ast_dump_context) const
11807 this->expr_->dump_expression(ast_dump_context);
11808 ast_dump_context->ostream() << "." << this->field_index_;
11811 // Make a reference to a qualified identifier in an expression.
11813 Field_reference_expression*
11814 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11815 Location location)
11817 return new Field_reference_expression(expr, field_index, location);
11820 // Class Interface_field_reference_expression.
11822 // Return an expression for the pointer to the function to call.
11824 Expression*
11825 Interface_field_reference_expression::get_function()
11827 Expression* ref = this->expr_;
11828 Location loc = this->location();
11829 if (ref->type()->points_to() != NULL)
11830 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
11832 Expression* mtable =
11833 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11834 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11836 std::string name = Gogo::unpack_hidden_name(this->name_);
11837 unsigned int index;
11838 const Struct_field* field = mtable_type->find_local_field(name, &index);
11839 go_assert(field != NULL);
11841 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
11842 return Expression::make_field_reference(mtable, index, loc);
11845 // Return an expression for the first argument to pass to the interface
11846 // function.
11848 Expression*
11849 Interface_field_reference_expression::get_underlying_object()
11851 Expression* expr = this->expr_;
11852 if (expr->type()->points_to() != NULL)
11853 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
11854 this->location());
11855 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11856 this->location());
11859 // Traversal.
11862 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11864 return Expression::traverse(&this->expr_, traverse);
11867 // Lower the expression. If this expression is not called, we need to
11868 // evaluate the expression twice when converting to the backend
11869 // interface. So introduce a temporary variable if necessary.
11871 Expression*
11872 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11873 Statement_inserter* inserter)
11875 if (this->expr_->is_error_expression()
11876 || this->expr_->type()->is_error_type())
11878 go_assert(saw_errors());
11879 return Expression::make_error(this->location());
11882 if (!this->expr_->is_variable())
11884 Temporary_statement* temp =
11885 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11886 inserter->insert(temp);
11887 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11888 this->location());
11890 return this;
11893 // Return the type of an interface field reference.
11895 Type*
11896 Interface_field_reference_expression::do_type()
11898 Type* expr_type = this->expr_->type();
11900 Type* points_to = expr_type->points_to();
11901 if (points_to != NULL)
11902 expr_type = points_to;
11904 Interface_type* interface_type = expr_type->interface_type();
11905 if (interface_type == NULL)
11906 return Type::make_error_type();
11908 const Typed_identifier* method = interface_type->find_method(this->name_);
11909 if (method == NULL)
11910 return Type::make_error_type();
11912 return method->type();
11915 // Determine types.
11917 void
11918 Interface_field_reference_expression::do_determine_type(const Type_context*)
11920 this->expr_->determine_type_no_context();
11923 // Check the types for an interface field reference.
11925 void
11926 Interface_field_reference_expression::do_check_types(Gogo*)
11928 Type* type = this->expr_->type();
11930 Type* points_to = type->points_to();
11931 if (points_to != NULL)
11932 type = points_to;
11934 Interface_type* interface_type = type->interface_type();
11935 if (interface_type == NULL)
11937 if (!type->is_error_type())
11938 this->report_error(_("expected interface or pointer to interface"));
11940 else
11942 const Typed_identifier* method =
11943 interface_type->find_method(this->name_);
11944 if (method == NULL)
11946 go_error_at(this->location(), "method %qs not in interface",
11947 Gogo::message_name(this->name_).c_str());
11948 this->set_is_error();
11953 // If an interface field reference is not simply called, then it is
11954 // represented as a closure. The closure will hold a single variable,
11955 // the value of the interface on which the method should be called.
11956 // The function will be a simple thunk that pulls the value from the
11957 // closure and calls the method with the remaining arguments.
11959 // Because method values are not common, we don't build all thunks for
11960 // all possible interface methods, but instead only build them as we
11961 // need them. In particular, we even build them on demand for
11962 // interface methods defined in other packages.
11964 Interface_field_reference_expression::Interface_method_thunks
11965 Interface_field_reference_expression::interface_method_thunks;
11967 // Find or create the thunk to call method NAME on TYPE.
11969 Named_object*
11970 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11971 Interface_type* type,
11972 const std::string& name)
11974 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11975 std::pair<Interface_method_thunks::iterator, bool> ins =
11976 Interface_field_reference_expression::interface_method_thunks.insert(val);
11977 if (ins.second)
11979 // This is the first time we have seen this interface.
11980 ins.first->second = new Method_thunks();
11983 for (Method_thunks::const_iterator p = ins.first->second->begin();
11984 p != ins.first->second->end();
11985 p++)
11986 if (p->first == name)
11987 return p->second;
11989 Location loc = type->location();
11991 const Typed_identifier* method_id = type->find_method(name);
11992 if (method_id == NULL)
11993 return Named_object::make_erroneous_name(gogo->thunk_name());
11995 Function_type* orig_fntype = method_id->type()->function_type();
11996 if (orig_fntype == NULL)
11997 return Named_object::make_erroneous_name(gogo->thunk_name());
11999 Struct_field_list* sfl = new Struct_field_list();
12000 // The type here is wrong--it should be the C function type. But it
12001 // doesn't really matter.
12002 Type* vt = Type::make_pointer_type(Type::make_void_type());
12003 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
12004 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
12005 Struct_type* st = Type::make_struct_type(sfl, loc);
12006 st->set_is_struct_incomparable();
12007 Type* closure_type = Type::make_pointer_type(st);
12009 Function_type* new_fntype = orig_fntype->copy_with_names();
12011 std::string thunk_name = gogo->thunk_name();
12012 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
12013 false, loc);
12015 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
12016 cvar->set_is_used();
12017 cvar->set_is_closure();
12018 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
12019 NULL, cvar);
12020 new_no->func_value()->set_closure_var(cp);
12022 gogo->start_block(loc);
12024 // Field 0 of the closure is the function code pointer, field 1 is
12025 // the value on which to invoke the method.
12026 Expression* arg = Expression::make_var_reference(cp, loc);
12027 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
12028 arg = Expression::make_field_reference(arg, 1, loc);
12030 Expression *ifre = Expression::make_interface_field_reference(arg, name,
12031 loc);
12033 const Typed_identifier_list* orig_params = orig_fntype->parameters();
12034 Expression_list* args;
12035 if (orig_params == NULL || orig_params->empty())
12036 args = NULL;
12037 else
12039 const Typed_identifier_list* new_params = new_fntype->parameters();
12040 args = new Expression_list();
12041 for (Typed_identifier_list::const_iterator p = new_params->begin();
12042 p != new_params->end();
12043 ++p)
12045 Named_object* p_no = gogo->lookup(p->name(), NULL);
12046 go_assert(p_no != NULL
12047 && p_no->is_variable()
12048 && p_no->var_value()->is_parameter());
12049 args->push_back(Expression::make_var_reference(p_no, loc));
12053 Call_expression* call = Expression::make_call(ifre, args,
12054 orig_fntype->is_varargs(),
12055 loc);
12056 call->set_varargs_are_lowered();
12058 Statement* s = Statement::make_return_from_call(call, loc);
12059 gogo->add_statement(s);
12060 Block* b = gogo->finish_block(loc);
12061 gogo->add_block(b, loc);
12062 gogo->lower_block(new_no, b);
12063 gogo->flatten_block(new_no, b);
12064 gogo->finish_function(loc);
12066 ins.first->second->push_back(std::make_pair(name, new_no));
12067 return new_no;
12070 // Get the backend representation for a method value.
12072 Bexpression*
12073 Interface_field_reference_expression::do_get_backend(Translate_context* context)
12075 Interface_type* type = this->expr_->type()->interface_type();
12076 if (type == NULL)
12078 go_assert(saw_errors());
12079 return context->backend()->error_expression();
12082 Named_object* thunk =
12083 Interface_field_reference_expression::create_thunk(context->gogo(),
12084 type, this->name_);
12085 if (thunk->is_erroneous())
12087 go_assert(saw_errors());
12088 return context->backend()->error_expression();
12091 // FIXME: We should lower this earlier, but we can't it lower it in
12092 // the lowering pass because at that point we don't know whether we
12093 // need to create the thunk or not. If the expression is called, we
12094 // don't need the thunk.
12096 Location loc = this->location();
12098 Struct_field_list* fields = new Struct_field_list();
12099 fields->push_back(Struct_field(Typed_identifier("fn",
12100 thunk->func_value()->type(),
12101 loc)));
12102 fields->push_back(Struct_field(Typed_identifier("val",
12103 this->expr_->type(),
12104 loc)));
12105 Struct_type* st = Type::make_struct_type(fields, loc);
12106 st->set_is_struct_incomparable();
12108 Expression_list* vals = new Expression_list();
12109 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12110 vals->push_back(this->expr_);
12112 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12113 Bexpression* bclosure =
12114 Expression::make_heap_expression(expr, loc)->get_backend(context);
12116 Gogo* gogo = context->gogo();
12117 Btype* btype = this->type()->get_backend(gogo);
12118 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12120 Expression* nil_check =
12121 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12122 Expression::make_nil(loc), loc);
12123 Bexpression* bnil_check = nil_check->get_backend(context);
12125 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12126 loc)->get_backend(context);
12128 Bfunction* bfn = context->function()->func_value()->get_decl();
12129 Bexpression* bcond =
12130 gogo->backend()->conditional_expression(bfn, NULL,
12131 bnil_check, bcrash, NULL, loc);
12132 Bfunction* bfunction = context->function()->func_value()->get_decl();
12133 Bstatement* cond_statement =
12134 gogo->backend()->expression_statement(bfunction, bcond);
12135 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12138 // Dump ast representation for an interface field reference.
12140 void
12141 Interface_field_reference_expression::do_dump_expression(
12142 Ast_dump_context* ast_dump_context) const
12144 this->expr_->dump_expression(ast_dump_context);
12145 ast_dump_context->ostream() << "." << this->name_;
12148 // Make a reference to a field in an interface.
12150 Expression*
12151 Expression::make_interface_field_reference(Expression* expr,
12152 const std::string& field,
12153 Location location)
12155 return new Interface_field_reference_expression(expr, field, location);
12158 // A general selector. This is a Parser_expression for LEFT.NAME. It
12159 // is lowered after we know the type of the left hand side.
12161 class Selector_expression : public Parser_expression
12163 public:
12164 Selector_expression(Expression* left, const std::string& name,
12165 Location location)
12166 : Parser_expression(EXPRESSION_SELECTOR, location),
12167 left_(left), name_(name)
12170 protected:
12172 do_traverse(Traverse* traverse)
12173 { return Expression::traverse(&this->left_, traverse); }
12175 Expression*
12176 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12178 Expression*
12179 do_copy()
12181 return new Selector_expression(this->left_->copy(), this->name_,
12182 this->location());
12185 void
12186 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12188 private:
12189 Expression*
12190 lower_method_expression(Gogo*);
12192 // The expression on the left hand side.
12193 Expression* left_;
12194 // The name on the right hand side.
12195 std::string name_;
12198 // Lower a selector expression once we know the real type of the left
12199 // hand side.
12201 Expression*
12202 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12203 int)
12205 Expression* left = this->left_;
12206 if (left->is_type_expression())
12207 return this->lower_method_expression(gogo);
12208 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12209 this->location());
12212 // Lower a method expression T.M or (*T).M. We turn this into a
12213 // function literal.
12215 Expression*
12216 Selector_expression::lower_method_expression(Gogo* gogo)
12218 Location location = this->location();
12219 Type* left_type = this->left_->type();
12220 Type* type = left_type;
12221 const std::string& name(this->name_);
12223 bool is_pointer;
12224 if (type->points_to() == NULL)
12225 is_pointer = false;
12226 else
12228 is_pointer = true;
12229 type = type->points_to();
12231 Named_type* nt = type->named_type();
12232 if (nt == NULL)
12234 go_error_at(location,
12235 ("method expression requires named type or "
12236 "pointer to named type"));
12237 return Expression::make_error(location);
12240 bool is_ambiguous;
12241 Method* method = nt->method_function(name, &is_ambiguous);
12242 const Typed_identifier* imethod = NULL;
12243 if (method == NULL && !is_pointer)
12245 Interface_type* it = nt->interface_type();
12246 if (it != NULL)
12247 imethod = it->find_method(name);
12250 if ((method == NULL && imethod == NULL)
12251 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12253 if (!is_ambiguous)
12254 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12255 is_pointer ? "*" : "",
12256 nt->message_name().c_str(),
12257 Gogo::message_name(name).c_str());
12258 else
12259 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12260 Gogo::message_name(name).c_str(),
12261 is_pointer ? "*" : "",
12262 nt->message_name().c_str());
12263 return Expression::make_error(location);
12266 if (method != NULL && !is_pointer && !method->is_value_method())
12268 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12269 nt->message_name().c_str(),
12270 Gogo::message_name(name).c_str());
12271 return Expression::make_error(location);
12274 // Build a new function type in which the receiver becomes the first
12275 // argument.
12276 Function_type* method_type;
12277 if (method != NULL)
12279 method_type = method->type();
12280 go_assert(method_type->is_method());
12282 else
12284 method_type = imethod->type()->function_type();
12285 go_assert(method_type != NULL && !method_type->is_method());
12288 const char* const receiver_name = "$this";
12289 Typed_identifier_list* parameters = new Typed_identifier_list();
12290 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12291 location));
12293 const Typed_identifier_list* method_parameters = method_type->parameters();
12294 if (method_parameters != NULL)
12296 int i = 0;
12297 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12298 p != method_parameters->end();
12299 ++p, ++i)
12301 if (!p->name().empty())
12302 parameters->push_back(*p);
12303 else
12305 char buf[20];
12306 snprintf(buf, sizeof buf, "$param%d", i);
12307 parameters->push_back(Typed_identifier(buf, p->type(),
12308 p->location()));
12313 const Typed_identifier_list* method_results = method_type->results();
12314 Typed_identifier_list* results;
12315 if (method_results == NULL)
12316 results = NULL;
12317 else
12319 results = new Typed_identifier_list();
12320 for (Typed_identifier_list::const_iterator p = method_results->begin();
12321 p != method_results->end();
12322 ++p)
12323 results->push_back(*p);
12326 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12327 location);
12328 if (method_type->is_varargs())
12329 fntype->set_is_varargs();
12331 // We generate methods which always takes a pointer to the receiver
12332 // as their first argument. If this is for a pointer type, we can
12333 // simply reuse the existing function. We use an internal hack to
12334 // get the right type.
12335 // FIXME: This optimization is disabled because it doesn't yet work
12336 // with function descriptors when the method expression is not
12337 // directly called.
12338 if (method != NULL && is_pointer && false)
12340 Named_object* mno = (method->needs_stub_method()
12341 ? method->stub_object()
12342 : method->named_object());
12343 Expression* f = Expression::make_func_reference(mno, NULL, location);
12344 f = Expression::make_cast(fntype, f, location);
12345 Type_conversion_expression* tce =
12346 static_cast<Type_conversion_expression*>(f);
12347 tce->set_may_convert_function_types();
12348 return f;
12351 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
12352 location);
12354 Named_object* vno = gogo->lookup(receiver_name, NULL);
12355 go_assert(vno != NULL);
12356 Expression* ve = Expression::make_var_reference(vno, location);
12357 Expression* bm;
12358 if (method != NULL)
12359 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12360 else
12361 bm = Expression::make_interface_field_reference(ve, name, location);
12363 // Even though we found the method above, if it has an error type we
12364 // may see an error here.
12365 if (bm->is_error_expression())
12367 gogo->finish_function(location);
12368 return bm;
12371 Expression_list* args;
12372 if (parameters->size() <= 1)
12373 args = NULL;
12374 else
12376 args = new Expression_list();
12377 Typed_identifier_list::const_iterator p = parameters->begin();
12378 ++p;
12379 for (; p != parameters->end(); ++p)
12381 vno = gogo->lookup(p->name(), NULL);
12382 go_assert(vno != NULL);
12383 args->push_back(Expression::make_var_reference(vno, location));
12387 gogo->start_block(location);
12389 Call_expression* call = Expression::make_call(bm, args,
12390 method_type->is_varargs(),
12391 location);
12393 Statement* s = Statement::make_return_from_call(call, location);
12394 gogo->add_statement(s);
12396 Block* b = gogo->finish_block(location);
12398 gogo->add_block(b, location);
12400 // Lower the call in case there are multiple results.
12401 gogo->lower_block(no, b);
12402 gogo->flatten_block(no, b);
12404 gogo->finish_function(location);
12406 return Expression::make_func_reference(no, NULL, location);
12409 // Dump the ast for a selector expression.
12411 void
12412 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12413 const
12415 ast_dump_context->dump_expression(this->left_);
12416 ast_dump_context->ostream() << ".";
12417 ast_dump_context->ostream() << this->name_;
12420 // Make a selector expression.
12422 Expression*
12423 Expression::make_selector(Expression* left, const std::string& name,
12424 Location location)
12426 return new Selector_expression(left, name, location);
12429 // Class Allocation_expression.
12432 Allocation_expression::do_traverse(Traverse* traverse)
12434 return Type::traverse(this->type_, traverse);
12437 Type*
12438 Allocation_expression::do_type()
12440 return Type::make_pointer_type(this->type_);
12443 void
12444 Allocation_expression::do_check_types(Gogo*)
12446 if (!this->type_->in_heap())
12447 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12450 // Make a copy of an allocation expression.
12452 Expression*
12453 Allocation_expression::do_copy()
12455 Allocation_expression* alloc =
12456 new Allocation_expression(this->type_->copy_expressions(),
12457 this->location());
12458 if (this->allocate_on_stack_)
12459 alloc->set_allocate_on_stack();
12460 return alloc;
12463 // Return the backend representation for an allocation expression.
12465 Bexpression*
12466 Allocation_expression::do_get_backend(Translate_context* context)
12468 Gogo* gogo = context->gogo();
12469 Location loc = this->location();
12470 Btype* btype = this->type_->get_backend(gogo);
12472 if (this->allocate_on_stack_)
12474 int64_t size;
12475 bool ok = this->type_->backend_type_size(gogo, &size);
12476 if (!ok)
12478 go_assert(saw_errors());
12479 return gogo->backend()->error_expression();
12481 Bstatement* decl;
12482 Named_object* fn = context->function();
12483 go_assert(fn != NULL);
12484 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
12485 Bexpression* zero = gogo->backend()->zero_expression(btype);
12486 Bvariable* temp =
12487 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
12488 zero, true, loc, &decl);
12489 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
12490 ret = gogo->backend()->address_expression(ret, loc);
12491 ret = gogo->backend()->compound_expression(decl, ret, loc);
12492 return ret;
12495 Bexpression* space =
12496 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12497 Btype* pbtype = gogo->backend()->pointer_type(btype);
12498 return gogo->backend()->convert_expression(pbtype, space, loc);
12501 // Dump ast representation for an allocation expression.
12503 void
12504 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12505 const
12507 ast_dump_context->ostream() << "new(";
12508 ast_dump_context->dump_type(this->type_);
12509 ast_dump_context->ostream() << ")";
12512 // Make an allocation expression.
12514 Expression*
12515 Expression::make_allocation(Type* type, Location location)
12517 return new Allocation_expression(type, location);
12520 // Class Ordered_value_list.
12523 Ordered_value_list::traverse_vals(Traverse* traverse)
12525 if (this->vals_ != NULL)
12527 if (this->traverse_order_ == NULL)
12529 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12530 return TRAVERSE_EXIT;
12532 else
12534 for (std::vector<unsigned long>::const_iterator p =
12535 this->traverse_order_->begin();
12536 p != this->traverse_order_->end();
12537 ++p)
12539 if (Expression::traverse(&this->vals_->at(*p), traverse)
12540 == TRAVERSE_EXIT)
12541 return TRAVERSE_EXIT;
12545 return TRAVERSE_CONTINUE;
12548 // Class Struct_construction_expression.
12550 // Traversal.
12553 Struct_construction_expression::do_traverse(Traverse* traverse)
12555 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12556 return TRAVERSE_EXIT;
12557 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12558 return TRAVERSE_EXIT;
12559 return TRAVERSE_CONTINUE;
12562 // Return whether this is a constant initializer.
12564 bool
12565 Struct_construction_expression::is_constant_struct() const
12567 if (this->vals() == NULL)
12568 return true;
12569 for (Expression_list::const_iterator pv = this->vals()->begin();
12570 pv != this->vals()->end();
12571 ++pv)
12573 if (*pv != NULL
12574 && !(*pv)->is_constant()
12575 && (!(*pv)->is_composite_literal()
12576 || (*pv)->is_nonconstant_composite_literal()))
12577 return false;
12580 const Struct_field_list* fields = this->type_->struct_type()->fields();
12581 for (Struct_field_list::const_iterator pf = fields->begin();
12582 pf != fields->end();
12583 ++pf)
12585 // There are no constant constructors for interfaces.
12586 if (pf->type()->interface_type() != NULL)
12587 return false;
12590 return true;
12593 // Return whether this struct can be used as a constant initializer.
12595 bool
12596 Struct_construction_expression::do_is_static_initializer() const
12598 if (this->vals() == NULL)
12599 return true;
12600 for (Expression_list::const_iterator pv = this->vals()->begin();
12601 pv != this->vals()->end();
12602 ++pv)
12604 if (*pv != NULL && !(*pv)->is_static_initializer())
12605 return false;
12608 const Struct_field_list* fields = this->type_->struct_type()->fields();
12609 for (Struct_field_list::const_iterator pf = fields->begin();
12610 pf != fields->end();
12611 ++pf)
12613 // There are no constant constructors for interfaces.
12614 if (pf->type()->interface_type() != NULL)
12615 return false;
12618 return true;
12621 // Final type determination.
12623 void
12624 Struct_construction_expression::do_determine_type(const Type_context*)
12626 if (this->vals() == NULL)
12627 return;
12628 const Struct_field_list* fields = this->type_->struct_type()->fields();
12629 Expression_list::const_iterator pv = this->vals()->begin();
12630 for (Struct_field_list::const_iterator pf = fields->begin();
12631 pf != fields->end();
12632 ++pf, ++pv)
12634 if (pv == this->vals()->end())
12635 return;
12636 if (*pv != NULL)
12638 Type_context subcontext(pf->type(), false);
12639 (*pv)->determine_type(&subcontext);
12642 // Extra values are an error we will report elsewhere; we still want
12643 // to determine the type to avoid knockon errors.
12644 for (; pv != this->vals()->end(); ++pv)
12645 (*pv)->determine_type_no_context();
12648 // Check types.
12650 void
12651 Struct_construction_expression::do_check_types(Gogo*)
12653 if (this->vals() == NULL)
12654 return;
12656 Struct_type* st = this->type_->struct_type();
12657 if (this->vals()->size() > st->field_count())
12659 this->report_error(_("too many expressions for struct"));
12660 return;
12663 const Struct_field_list* fields = st->fields();
12664 Expression_list::const_iterator pv = this->vals()->begin();
12665 int i = 0;
12666 for (Struct_field_list::const_iterator pf = fields->begin();
12667 pf != fields->end();
12668 ++pf, ++pv, ++i)
12670 if (pv == this->vals()->end())
12672 this->report_error(_("too few expressions for struct"));
12673 break;
12676 if (*pv == NULL)
12677 continue;
12679 std::string reason;
12680 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12682 if (reason.empty())
12683 go_error_at((*pv)->location(),
12684 "incompatible type for field %d in struct construction",
12685 i + 1);
12686 else
12687 go_error_at((*pv)->location(),
12688 ("incompatible type for field %d in "
12689 "struct construction (%s)"),
12690 i + 1, reason.c_str());
12691 this->set_is_error();
12694 go_assert(pv == this->vals()->end());
12697 // Copy.
12699 Expression*
12700 Struct_construction_expression::do_copy()
12702 Struct_construction_expression* ret =
12703 new Struct_construction_expression(this->type_->copy_expressions(),
12704 (this->vals() == NULL
12705 ? NULL
12706 : this->vals()->copy()),
12707 this->location());
12708 if (this->traverse_order() != NULL)
12709 ret->set_traverse_order(this->traverse_order());
12710 return ret;
12713 // Flatten a struct construction expression. Store the values into
12714 // temporaries in case they need interface conversion.
12716 Expression*
12717 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12718 Statement_inserter* inserter)
12720 if (this->vals() == NULL)
12721 return this;
12723 // If this is a constant struct, we don't need temporaries.
12724 if (this->is_constant_struct() || this->is_static_initializer())
12725 return this;
12727 Location loc = this->location();
12728 for (Expression_list::iterator pv = this->vals()->begin();
12729 pv != this->vals()->end();
12730 ++pv)
12732 if (*pv != NULL)
12734 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12736 go_assert(saw_errors());
12737 return Expression::make_error(loc);
12739 if (!(*pv)->is_variable())
12741 Temporary_statement* temp =
12742 Statement::make_temporary(NULL, *pv, loc);
12743 inserter->insert(temp);
12744 *pv = Expression::make_temporary_reference(temp, loc);
12748 return this;
12751 // Return the backend representation for constructing a struct.
12753 Bexpression*
12754 Struct_construction_expression::do_get_backend(Translate_context* context)
12756 Gogo* gogo = context->gogo();
12758 Btype* btype = this->type_->get_backend(gogo);
12759 if (this->vals() == NULL)
12760 return gogo->backend()->zero_expression(btype);
12762 const Struct_field_list* fields = this->type_->struct_type()->fields();
12763 Expression_list::const_iterator pv = this->vals()->begin();
12764 std::vector<Bexpression*> init;
12765 for (Struct_field_list::const_iterator pf = fields->begin();
12766 pf != fields->end();
12767 ++pf)
12769 Btype* fbtype = pf->type()->get_backend(gogo);
12770 if (pv == this->vals()->end())
12771 init.push_back(gogo->backend()->zero_expression(fbtype));
12772 else if (*pv == NULL)
12774 init.push_back(gogo->backend()->zero_expression(fbtype));
12775 ++pv;
12777 else
12779 Expression* val =
12780 Expression::convert_for_assignment(gogo, pf->type(),
12781 *pv, this->location());
12782 init.push_back(val->get_backend(context));
12783 ++pv;
12786 return gogo->backend()->constructor_expression(btype, init, this->location());
12789 // Export a struct construction.
12791 void
12792 Struct_construction_expression::do_export(Export* exp) const
12794 exp->write_c_string("convert(");
12795 exp->write_type(this->type_);
12796 for (Expression_list::const_iterator pv = this->vals()->begin();
12797 pv != this->vals()->end();
12798 ++pv)
12800 exp->write_c_string(", ");
12801 if (*pv != NULL)
12802 (*pv)->export_expression(exp);
12804 exp->write_c_string(")");
12807 // Dump ast representation of a struct construction expression.
12809 void
12810 Struct_construction_expression::do_dump_expression(
12811 Ast_dump_context* ast_dump_context) const
12813 ast_dump_context->dump_type(this->type_);
12814 ast_dump_context->ostream() << "{";
12815 ast_dump_context->dump_expression_list(this->vals());
12816 ast_dump_context->ostream() << "}";
12819 // Make a struct composite literal. This used by the thunk code.
12821 Expression*
12822 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12823 Location location)
12825 go_assert(type->struct_type() != NULL);
12826 return new Struct_construction_expression(type, vals, location);
12829 // Class Array_construction_expression.
12831 // Traversal.
12834 Array_construction_expression::do_traverse(Traverse* traverse)
12836 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12837 return TRAVERSE_EXIT;
12838 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12839 return TRAVERSE_EXIT;
12840 return TRAVERSE_CONTINUE;
12843 // Return whether this is a constant initializer.
12845 bool
12846 Array_construction_expression::is_constant_array() const
12848 if (this->vals() == NULL)
12849 return true;
12851 // There are no constant constructors for interfaces.
12852 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12853 return false;
12855 for (Expression_list::const_iterator pv = this->vals()->begin();
12856 pv != this->vals()->end();
12857 ++pv)
12859 if (*pv != NULL
12860 && !(*pv)->is_constant()
12861 && (!(*pv)->is_composite_literal()
12862 || (*pv)->is_nonconstant_composite_literal()))
12863 return false;
12865 return true;
12868 // Return whether this can be used a constant initializer.
12870 bool
12871 Array_construction_expression::do_is_static_initializer() const
12873 if (this->vals() == NULL)
12874 return true;
12876 // There are no constant constructors for interfaces.
12877 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12878 return false;
12880 for (Expression_list::const_iterator pv = this->vals()->begin();
12881 pv != this->vals()->end();
12882 ++pv)
12884 if (*pv != NULL && !(*pv)->is_static_initializer())
12885 return false;
12887 return true;
12890 // Final type determination.
12892 void
12893 Array_construction_expression::do_determine_type(const Type_context*)
12895 if (this->vals() == NULL)
12896 return;
12897 Type_context subcontext(this->type_->array_type()->element_type(), false);
12898 for (Expression_list::const_iterator pv = this->vals()->begin();
12899 pv != this->vals()->end();
12900 ++pv)
12902 if (*pv != NULL)
12903 (*pv)->determine_type(&subcontext);
12907 // Check types.
12909 void
12910 Array_construction_expression::do_check_types(Gogo*)
12912 if (this->vals() == NULL)
12913 return;
12915 Array_type* at = this->type_->array_type();
12916 int i = 0;
12917 Type* element_type = at->element_type();
12918 for (Expression_list::const_iterator pv = this->vals()->begin();
12919 pv != this->vals()->end();
12920 ++pv, ++i)
12922 if (*pv != NULL
12923 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12925 go_error_at((*pv)->location(),
12926 "incompatible type for element %d in composite literal",
12927 i + 1);
12928 this->set_is_error();
12933 // Flatten an array construction expression. Store the values into
12934 // temporaries in case they need interface conversion.
12936 Expression*
12937 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12938 Statement_inserter* inserter)
12940 if (this->vals() == NULL)
12941 return this;
12943 // If this is a constant array, we don't need temporaries.
12944 if (this->is_constant_array() || this->is_static_initializer())
12945 return this;
12947 Location loc = this->location();
12948 for (Expression_list::iterator pv = this->vals()->begin();
12949 pv != this->vals()->end();
12950 ++pv)
12952 if (*pv != NULL)
12954 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12956 go_assert(saw_errors());
12957 return Expression::make_error(loc);
12959 if (!(*pv)->is_variable())
12961 Temporary_statement* temp =
12962 Statement::make_temporary(NULL, *pv, loc);
12963 inserter->insert(temp);
12964 *pv = Expression::make_temporary_reference(temp, loc);
12968 return this;
12971 // Get a constructor expression for the array values.
12973 Bexpression*
12974 Array_construction_expression::get_constructor(Translate_context* context,
12975 Btype* array_btype)
12977 Type* element_type = this->type_->array_type()->element_type();
12979 std::vector<unsigned long> indexes;
12980 std::vector<Bexpression*> vals;
12981 Gogo* gogo = context->gogo();
12982 if (this->vals() != NULL)
12984 size_t i = 0;
12985 std::vector<unsigned long>::const_iterator pi;
12986 if (this->indexes_ != NULL)
12987 pi = this->indexes_->begin();
12988 for (Expression_list::const_iterator pv = this->vals()->begin();
12989 pv != this->vals()->end();
12990 ++pv, ++i)
12992 if (this->indexes_ != NULL)
12993 go_assert(pi != this->indexes_->end());
12995 if (this->indexes_ == NULL)
12996 indexes.push_back(i);
12997 else
12998 indexes.push_back(*pi);
12999 if (*pv == NULL)
13001 Btype* ebtype = element_type->get_backend(gogo);
13002 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
13003 vals.push_back(zv);
13005 else
13007 Expression* val_expr =
13008 Expression::convert_for_assignment(gogo, element_type, *pv,
13009 this->location());
13010 vals.push_back(val_expr->get_backend(context));
13012 if (this->indexes_ != NULL)
13013 ++pi;
13015 if (this->indexes_ != NULL)
13016 go_assert(pi == this->indexes_->end());
13018 return gogo->backend()->array_constructor_expression(array_btype, indexes,
13019 vals, this->location());
13022 // Export an array construction.
13024 void
13025 Array_construction_expression::do_export(Export* exp) const
13027 exp->write_c_string("convert(");
13028 exp->write_type(this->type_);
13029 if (this->vals() != NULL)
13031 std::vector<unsigned long>::const_iterator pi;
13032 if (this->indexes_ != NULL)
13033 pi = this->indexes_->begin();
13034 for (Expression_list::const_iterator pv = this->vals()->begin();
13035 pv != this->vals()->end();
13036 ++pv)
13038 exp->write_c_string(", ");
13040 if (this->indexes_ != NULL)
13042 char buf[100];
13043 snprintf(buf, sizeof buf, "%lu", *pi);
13044 exp->write_c_string(buf);
13045 exp->write_c_string(":");
13048 if (*pv != NULL)
13049 (*pv)->export_expression(exp);
13051 if (this->indexes_ != NULL)
13052 ++pi;
13055 exp->write_c_string(")");
13058 // Dump ast representation of an array construction expression.
13060 void
13061 Array_construction_expression::do_dump_expression(
13062 Ast_dump_context* ast_dump_context) const
13064 Expression* length = this->type_->array_type()->length();
13066 ast_dump_context->ostream() << "[" ;
13067 if (length != NULL)
13069 ast_dump_context->dump_expression(length);
13071 ast_dump_context->ostream() << "]" ;
13072 ast_dump_context->dump_type(this->type_);
13073 this->dump_slice_storage_expression(ast_dump_context);
13074 ast_dump_context->ostream() << "{" ;
13075 if (this->indexes_ == NULL)
13076 ast_dump_context->dump_expression_list(this->vals());
13077 else
13079 Expression_list::const_iterator pv = this->vals()->begin();
13080 for (std::vector<unsigned long>::const_iterator pi =
13081 this->indexes_->begin();
13082 pi != this->indexes_->end();
13083 ++pi, ++pv)
13085 if (pi != this->indexes_->begin())
13086 ast_dump_context->ostream() << ", ";
13087 ast_dump_context->ostream() << *pi << ':';
13088 ast_dump_context->dump_expression(*pv);
13091 ast_dump_context->ostream() << "}" ;
13095 // Class Fixed_array_construction_expression.
13097 Fixed_array_construction_expression::Fixed_array_construction_expression(
13098 Type* type, const std::vector<unsigned long>* indexes,
13099 Expression_list* vals, Location location)
13100 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13101 type, indexes, vals, location)
13102 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13105 // Copy.
13107 Expression*
13108 Fixed_array_construction_expression::do_copy()
13110 Type* t = this->type()->copy_expressions();
13111 return new Fixed_array_construction_expression(t, this->indexes(),
13112 (this->vals() == NULL
13113 ? NULL
13114 : this->vals()->copy()),
13115 this->location());
13118 // Return the backend representation for constructing a fixed array.
13120 Bexpression*
13121 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13123 Type* type = this->type();
13124 Btype* btype = type->get_backend(context->gogo());
13125 return this->get_constructor(context, btype);
13128 Expression*
13129 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13130 Location location)
13132 go_assert(type->array_type() != NULL && !type->is_slice_type());
13133 return new Fixed_array_construction_expression(type, NULL, vals, location);
13136 // Class Slice_construction_expression.
13138 Slice_construction_expression::Slice_construction_expression(
13139 Type* type, const std::vector<unsigned long>* indexes,
13140 Expression_list* vals, Location location)
13141 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13142 type, indexes, vals, location),
13143 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13144 storage_escapes_(true)
13146 go_assert(type->is_slice_type());
13148 unsigned long lenval;
13149 Expression* length;
13150 if (vals == NULL || vals->empty())
13151 lenval = 0;
13152 else
13154 if (this->indexes() == NULL)
13155 lenval = vals->size();
13156 else
13157 lenval = indexes->back() + 1;
13159 Type* int_type = Type::lookup_integer_type("int");
13160 length = Expression::make_integer_ul(lenval, int_type, location);
13161 Type* element_type = type->array_type()->element_type();
13162 Array_type* array_type = Type::make_array_type(element_type, length);
13163 array_type->set_is_array_incomparable();
13164 this->valtype_ = array_type;
13167 // Traversal.
13170 Slice_construction_expression::do_traverse(Traverse* traverse)
13172 if (this->Array_construction_expression::do_traverse(traverse)
13173 == TRAVERSE_EXIT)
13174 return TRAVERSE_EXIT;
13175 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13176 return TRAVERSE_EXIT;
13177 if (this->array_val_ != NULL
13178 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13179 return TRAVERSE_EXIT;
13180 if (this->slice_storage_ != NULL
13181 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13182 return TRAVERSE_EXIT;
13183 return TRAVERSE_CONTINUE;
13186 // Helper routine to create fixed array value underlying the slice literal.
13187 // May be called during flattening, or later during do_get_backend().
13189 Expression*
13190 Slice_construction_expression::create_array_val()
13192 Array_type* array_type = this->type()->array_type();
13193 if (array_type == NULL)
13195 go_assert(this->type()->is_error());
13196 return NULL;
13199 Location loc = this->location();
13200 go_assert(this->valtype_ != NULL);
13202 Expression_list* vals = this->vals();
13203 return new Fixed_array_construction_expression(
13204 this->valtype_, this->indexes(), vals, loc);
13207 // If we're previous established that the slice storage does not
13208 // escape, then create a separate array temp val here for it. We
13209 // need to do this as part of flattening so as to be able to insert
13210 // the new temp statement.
13212 Expression*
13213 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13214 Statement_inserter* inserter)
13216 if (this->type()->array_type() == NULL)
13217 return NULL;
13219 // Base class flattening first
13220 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13222 // Create a stack-allocated storage temp if storage won't escape
13223 if (!this->storage_escapes_
13224 && this->slice_storage_ == NULL
13225 && this->element_count() > 0)
13227 Location loc = this->location();
13228 this->array_val_ = this->create_array_val();
13229 go_assert(this->array_val_);
13230 Temporary_statement* temp =
13231 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13232 inserter->insert(temp);
13233 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13235 return this;
13238 // When dumping a slice construction expression that has an explicit
13239 // storeage temp, emit the temp here (if we don't do this the storage
13240 // temp appears unused in the AST dump).
13242 void
13243 Slice_construction_expression::
13244 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13246 if (this->slice_storage_ == NULL)
13247 return;
13248 ast_dump_context->ostream() << "storage=" ;
13249 ast_dump_context->dump_expression(this->slice_storage_);
13252 // Copy.
13254 Expression*
13255 Slice_construction_expression::do_copy()
13257 return new Slice_construction_expression(this->type()->copy_expressions(),
13258 this->indexes(),
13259 (this->vals() == NULL
13260 ? NULL
13261 : this->vals()->copy()),
13262 this->location());
13265 // Return the backend representation for constructing a slice.
13267 Bexpression*
13268 Slice_construction_expression::do_get_backend(Translate_context* context)
13270 if (this->array_val_ == NULL)
13271 this->array_val_ = this->create_array_val();
13272 if (this->array_val_ == NULL)
13274 go_assert(this->type()->is_error());
13275 return context->backend()->error_expression();
13278 Location loc = this->location();
13280 bool is_static_initializer = this->array_val_->is_static_initializer();
13282 // We have to copy the initial values into heap memory if we are in
13283 // a function or if the values are not constants.
13284 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13286 Expression* space;
13288 if (this->slice_storage_ != NULL)
13290 go_assert(!this->storage_escapes_);
13291 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13293 else if (!copy_to_heap)
13295 // The initializer will only run once.
13296 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13297 space->unary_expression()->set_is_slice_init();
13299 else
13301 go_assert(this->storage_escapes_ || this->element_count() == 0);
13302 space = Expression::make_heap_expression(this->array_val_, loc);
13305 // Build a constructor for the slice.
13306 Expression* len = this->valtype_->array_type()->length();
13307 Expression* slice_val =
13308 Expression::make_slice_value(this->type(), space, len, len, loc);
13309 return slice_val->get_backend(context);
13312 // Make a slice composite literal. This is used by the type
13313 // descriptor code.
13315 Slice_construction_expression*
13316 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13317 Location location)
13319 go_assert(type->is_slice_type());
13320 return new Slice_construction_expression(type, NULL, vals, location);
13323 // Class Map_construction_expression.
13325 // Traversal.
13328 Map_construction_expression::do_traverse(Traverse* traverse)
13330 if (this->vals_ != NULL
13331 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13332 return TRAVERSE_EXIT;
13333 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13334 return TRAVERSE_EXIT;
13335 return TRAVERSE_CONTINUE;
13338 // Flatten constructor initializer into a temporary variable since
13339 // we need to take its address for __go_construct_map.
13341 Expression*
13342 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13343 Statement_inserter* inserter)
13345 if (!this->is_error_expression()
13346 && this->vals_ != NULL
13347 && !this->vals_->empty()
13348 && this->constructor_temp_ == NULL)
13350 Map_type* mt = this->type_->map_type();
13351 Type* key_type = mt->key_type();
13352 Type* val_type = mt->val_type();
13353 this->element_type_ = Type::make_builtin_struct_type(2,
13354 "__key", key_type,
13355 "__val", val_type);
13357 Expression_list* value_pairs = new Expression_list();
13358 Location loc = this->location();
13360 size_t i = 0;
13361 for (Expression_list::const_iterator pv = this->vals_->begin();
13362 pv != this->vals_->end();
13363 ++pv, ++i)
13365 Expression_list* key_value_pair = new Expression_list();
13366 Expression* key = *pv;
13367 if (key->is_error_expression() || key->type()->is_error_type())
13369 go_assert(saw_errors());
13370 return Expression::make_error(loc);
13372 if (key->type()->interface_type() != NULL && !key->is_variable())
13374 Temporary_statement* temp =
13375 Statement::make_temporary(NULL, key, loc);
13376 inserter->insert(temp);
13377 key = Expression::make_temporary_reference(temp, loc);
13379 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13381 ++pv;
13382 Expression* val = *pv;
13383 if (val->is_error_expression() || val->type()->is_error_type())
13385 go_assert(saw_errors());
13386 return Expression::make_error(loc);
13388 if (val->type()->interface_type() != NULL && !val->is_variable())
13390 Temporary_statement* temp =
13391 Statement::make_temporary(NULL, val, loc);
13392 inserter->insert(temp);
13393 val = Expression::make_temporary_reference(temp, loc);
13395 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13397 key_value_pair->push_back(key);
13398 key_value_pair->push_back(val);
13399 value_pairs->push_back(
13400 Expression::make_struct_composite_literal(this->element_type_,
13401 key_value_pair, loc));
13404 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13405 Array_type* ctor_type =
13406 Type::make_array_type(this->element_type_, element_count);
13407 ctor_type->set_is_array_incomparable();
13408 Expression* constructor =
13409 new Fixed_array_construction_expression(ctor_type, NULL,
13410 value_pairs, loc);
13412 this->constructor_temp_ =
13413 Statement::make_temporary(NULL, constructor, loc);
13414 constructor->issue_nil_check();
13415 this->constructor_temp_->set_is_address_taken();
13416 inserter->insert(this->constructor_temp_);
13419 return this;
13422 // Final type determination.
13424 void
13425 Map_construction_expression::do_determine_type(const Type_context*)
13427 if (this->vals_ == NULL)
13428 return;
13430 Map_type* mt = this->type_->map_type();
13431 Type_context key_context(mt->key_type(), false);
13432 Type_context val_context(mt->val_type(), false);
13433 for (Expression_list::const_iterator pv = this->vals_->begin();
13434 pv != this->vals_->end();
13435 ++pv)
13437 (*pv)->determine_type(&key_context);
13438 ++pv;
13439 (*pv)->determine_type(&val_context);
13443 // Check types.
13445 void
13446 Map_construction_expression::do_check_types(Gogo*)
13448 if (this->vals_ == NULL)
13449 return;
13451 Map_type* mt = this->type_->map_type();
13452 int i = 0;
13453 Type* key_type = mt->key_type();
13454 Type* val_type = mt->val_type();
13455 for (Expression_list::const_iterator pv = this->vals_->begin();
13456 pv != this->vals_->end();
13457 ++pv, ++i)
13459 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13461 go_error_at((*pv)->location(),
13462 "incompatible type for element %d key in map construction",
13463 i + 1);
13464 this->set_is_error();
13466 ++pv;
13467 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13469 go_error_at((*pv)->location(),
13470 ("incompatible type for element %d value "
13471 "in map construction"),
13472 i + 1);
13473 this->set_is_error();
13478 // Copy.
13480 Expression*
13481 Map_construction_expression::do_copy()
13483 return new Map_construction_expression(this->type_->copy_expressions(),
13484 (this->vals_ == NULL
13485 ? NULL
13486 : this->vals_->copy()),
13487 this->location());
13490 // Return the backend representation for constructing a map.
13492 Bexpression*
13493 Map_construction_expression::do_get_backend(Translate_context* context)
13495 if (this->is_error_expression())
13496 return context->backend()->error_expression();
13497 Location loc = this->location();
13499 size_t i = 0;
13500 Expression* ventries;
13501 if (this->vals_ == NULL || this->vals_->empty())
13502 ventries = Expression::make_nil(loc);
13503 else
13505 go_assert(this->constructor_temp_ != NULL);
13506 i = this->vals_->size() / 2;
13508 Expression* ctor_ref =
13509 Expression::make_temporary_reference(this->constructor_temp_, loc);
13510 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13513 Map_type* mt = this->type_->map_type();
13514 if (this->element_type_ == NULL)
13515 this->element_type_ =
13516 Type::make_builtin_struct_type(2,
13517 "__key", mt->key_type(),
13518 "__val", mt->val_type());
13519 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13521 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13522 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13524 Expression* entry_size =
13525 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13527 unsigned int field_index;
13528 const Struct_field* valfield =
13529 this->element_type_->find_local_field("__val", &field_index);
13530 Expression* val_offset =
13531 Expression::make_struct_field_offset(this->element_type_, valfield);
13533 Expression* map_ctor =
13534 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13535 entry_size, val_offset, ventries);
13536 return map_ctor->get_backend(context);
13539 // Export an array construction.
13541 void
13542 Map_construction_expression::do_export(Export* exp) const
13544 exp->write_c_string("convert(");
13545 exp->write_type(this->type_);
13546 for (Expression_list::const_iterator pv = this->vals_->begin();
13547 pv != this->vals_->end();
13548 ++pv)
13550 exp->write_c_string(", ");
13551 (*pv)->export_expression(exp);
13553 exp->write_c_string(")");
13556 // Dump ast representation for a map construction expression.
13558 void
13559 Map_construction_expression::do_dump_expression(
13560 Ast_dump_context* ast_dump_context) const
13562 ast_dump_context->ostream() << "{" ;
13563 ast_dump_context->dump_expression_list(this->vals_, true);
13564 ast_dump_context->ostream() << "}";
13567 // Class Composite_literal_expression.
13569 // Traversal.
13572 Composite_literal_expression::do_traverse(Traverse* traverse)
13574 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13575 return TRAVERSE_EXIT;
13577 // If this is a struct composite literal with keys, then the keys
13578 // are field names, not expressions. We don't want to traverse them
13579 // in that case. If we do, we can give an erroneous error "variable
13580 // initializer refers to itself." See bug482.go in the testsuite.
13581 if (this->has_keys_ && this->vals_ != NULL)
13583 // The type may not be resolvable at this point.
13584 Type* type = this->type_;
13586 for (int depth = 0; depth < this->depth_; ++depth)
13588 if (type->array_type() != NULL)
13589 type = type->array_type()->element_type();
13590 else if (type->map_type() != NULL)
13592 if (this->key_path_[depth])
13593 type = type->map_type()->key_type();
13594 else
13595 type = type->map_type()->val_type();
13597 else
13599 // This error will be reported during lowering.
13600 return TRAVERSE_CONTINUE;
13604 while (true)
13606 if (type->classification() == Type::TYPE_NAMED)
13607 type = type->named_type()->real_type();
13608 else if (type->classification() == Type::TYPE_FORWARD)
13610 Type* t = type->forwarded();
13611 if (t == type)
13612 break;
13613 type = t;
13615 else
13616 break;
13619 if (type->classification() == Type::TYPE_STRUCT)
13621 Expression_list::iterator p = this->vals_->begin();
13622 while (p != this->vals_->end())
13624 // Skip key.
13625 ++p;
13626 go_assert(p != this->vals_->end());
13627 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13628 return TRAVERSE_EXIT;
13629 ++p;
13631 return TRAVERSE_CONTINUE;
13635 if (this->vals_ != NULL)
13636 return this->vals_->traverse(traverse);
13638 return TRAVERSE_CONTINUE;
13641 // Lower a generic composite literal into a specific version based on
13642 // the type.
13644 Expression*
13645 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13646 Statement_inserter* inserter, int)
13648 Type* type = this->type_;
13650 for (int depth = 0; depth < this->depth_; ++depth)
13652 if (type->array_type() != NULL)
13653 type = type->array_type()->element_type();
13654 else if (type->map_type() != NULL)
13656 if (this->key_path_[depth])
13657 type = type->map_type()->key_type();
13658 else
13659 type = type->map_type()->val_type();
13661 else
13663 if (!type->is_error())
13664 go_error_at(this->location(),
13665 ("may only omit types within composite literals "
13666 "of slice, array, or map type"));
13667 return Expression::make_error(this->location());
13671 Type *pt = type->points_to();
13672 bool is_pointer = false;
13673 if (pt != NULL)
13675 is_pointer = true;
13676 type = pt;
13679 Expression* ret;
13680 if (type->is_error())
13681 return Expression::make_error(this->location());
13682 else if (type->struct_type() != NULL)
13683 ret = this->lower_struct(gogo, type);
13684 else if (type->array_type() != NULL)
13685 ret = this->lower_array(type);
13686 else if (type->map_type() != NULL)
13687 ret = this->lower_map(gogo, function, inserter, type);
13688 else
13690 go_error_at(this->location(),
13691 ("expected struct, slice, array, or map type "
13692 "for composite literal"));
13693 return Expression::make_error(this->location());
13696 if (is_pointer)
13697 ret = Expression::make_heap_expression(ret, this->location());
13699 return ret;
13702 // Lower a struct composite literal.
13704 Expression*
13705 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13707 Location location = this->location();
13708 Struct_type* st = type->struct_type();
13709 if (this->vals_ == NULL || !this->has_keys_)
13711 if (this->vals_ != NULL
13712 && !this->vals_->empty()
13713 && type->named_type() != NULL
13714 && type->named_type()->named_object()->package() != NULL)
13716 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13717 pf != st->fields()->end();
13718 ++pf)
13720 if (Gogo::is_hidden_name(pf->field_name())
13721 || pf->is_embedded_builtin(gogo))
13722 go_error_at(this->location(),
13723 "assignment of unexported field %qs in %qs literal",
13724 Gogo::message_name(pf->field_name()).c_str(),
13725 type->named_type()->message_name().c_str());
13729 return new Struct_construction_expression(type, this->vals_, location);
13732 size_t field_count = st->field_count();
13733 std::vector<Expression*> vals(field_count);
13734 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13735 Expression_list::const_iterator p = this->vals_->begin();
13736 Expression* external_expr = NULL;
13737 const Named_object* external_no = NULL;
13738 while (p != this->vals_->end())
13740 Expression* name_expr = *p;
13742 ++p;
13743 go_assert(p != this->vals_->end());
13744 Expression* val = *p;
13746 ++p;
13748 if (name_expr == NULL)
13750 go_error_at(val->location(),
13751 "mixture of field and value initializers");
13752 return Expression::make_error(location);
13755 bool bad_key = false;
13756 std::string name;
13757 const Named_object* no = NULL;
13758 switch (name_expr->classification())
13760 case EXPRESSION_UNKNOWN_REFERENCE:
13761 name = name_expr->unknown_expression()->name();
13762 if (type->named_type() != NULL)
13764 // If the named object found for this field name comes from a
13765 // different package than the struct it is a part of, do not count
13766 // this incorrect lookup as a usage of the object's package.
13767 no = name_expr->unknown_expression()->named_object();
13768 if (no->package() != NULL
13769 && no->package() != type->named_type()->named_object()->package())
13770 no->package()->forget_usage(name_expr);
13772 break;
13774 case EXPRESSION_CONST_REFERENCE:
13775 no = static_cast<Const_expression*>(name_expr)->named_object();
13776 break;
13778 case EXPRESSION_TYPE:
13780 Type* t = name_expr->type();
13781 Named_type* nt = t->named_type();
13782 if (nt == NULL)
13783 bad_key = true;
13784 else
13785 no = nt->named_object();
13787 break;
13789 case EXPRESSION_VAR_REFERENCE:
13790 no = name_expr->var_expression()->named_object();
13791 break;
13793 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13794 no = name_expr->enclosed_var_expression()->variable();
13795 break;
13797 case EXPRESSION_FUNC_REFERENCE:
13798 no = name_expr->func_expression()->named_object();
13799 break;
13801 default:
13802 bad_key = true;
13803 break;
13805 if (bad_key)
13807 go_error_at(name_expr->location(), "expected struct field name");
13808 return Expression::make_error(location);
13811 if (no != NULL)
13813 if (no->package() != NULL && external_expr == NULL)
13815 external_expr = name_expr;
13816 external_no = no;
13819 name = no->name();
13821 // A predefined name won't be packed. If it starts with a
13822 // lower case letter we need to check for that case, because
13823 // the field name will be packed. FIXME.
13824 if (!Gogo::is_hidden_name(name)
13825 && name[0] >= 'a'
13826 && name[0] <= 'z')
13828 Named_object* gno = gogo->lookup_global(name.c_str());
13829 if (gno == no)
13830 name = gogo->pack_hidden_name(name, false);
13834 unsigned int index;
13835 const Struct_field* sf = st->find_local_field(name, &index);
13836 if (sf == NULL)
13838 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13839 Gogo::message_name(name).c_str(),
13840 (type->named_type() != NULL
13841 ? type->named_type()->message_name().c_str()
13842 : "unnamed struct"));
13843 return Expression::make_error(location);
13845 if (vals[index] != NULL)
13847 go_error_at(name_expr->location(),
13848 "duplicate value for field %qs in %qs",
13849 Gogo::message_name(name).c_str(),
13850 (type->named_type() != NULL
13851 ? type->named_type()->message_name().c_str()
13852 : "unnamed struct"));
13853 return Expression::make_error(location);
13856 if (type->named_type() != NULL
13857 && type->named_type()->named_object()->package() != NULL
13858 && (Gogo::is_hidden_name(sf->field_name())
13859 || sf->is_embedded_builtin(gogo)))
13860 go_error_at(name_expr->location(),
13861 "assignment of unexported field %qs in %qs literal",
13862 Gogo::message_name(sf->field_name()).c_str(),
13863 type->named_type()->message_name().c_str());
13865 vals[index] = val;
13866 traverse_order->push_back(static_cast<unsigned long>(index));
13869 if (!this->all_are_names_)
13871 // This is a weird case like bug462 in the testsuite.
13872 if (external_expr == NULL)
13873 go_error_at(this->location(), "unknown field in %qs literal",
13874 (type->named_type() != NULL
13875 ? type->named_type()->message_name().c_str()
13876 : "unnamed struct"));
13877 else
13878 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13879 external_no->message_name().c_str(),
13880 (type->named_type() != NULL
13881 ? type->named_type()->message_name().c_str()
13882 : "unnamed struct"));
13883 return Expression::make_error(location);
13886 Expression_list* list = new Expression_list;
13887 list->reserve(field_count);
13888 for (size_t i = 0; i < field_count; ++i)
13889 list->push_back(vals[i]);
13891 Struct_construction_expression* ret =
13892 new Struct_construction_expression(type, list, location);
13893 ret->set_traverse_order(traverse_order);
13894 return ret;
13897 // Index/value/traversal-order triple.
13899 struct IVT_triple {
13900 unsigned long index;
13901 unsigned long traversal_order;
13902 Expression* expr;
13903 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13904 : index(i), traversal_order(to), expr(e) { }
13905 bool operator<(const IVT_triple& other) const
13906 { return this->index < other.index; }
13909 // Lower an array composite literal.
13911 Expression*
13912 Composite_literal_expression::lower_array(Type* type)
13914 Location location = this->location();
13915 if (this->vals_ == NULL || !this->has_keys_)
13916 return this->make_array(type, NULL, this->vals_);
13918 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13919 indexes->reserve(this->vals_->size());
13920 bool indexes_out_of_order = false;
13921 Expression_list* vals = new Expression_list();
13922 vals->reserve(this->vals_->size());
13923 unsigned long index = 0;
13924 Expression_list::const_iterator p = this->vals_->begin();
13925 while (p != this->vals_->end())
13927 Expression* index_expr = *p;
13929 ++p;
13930 go_assert(p != this->vals_->end());
13931 Expression* val = *p;
13933 ++p;
13935 if (index_expr == NULL)
13937 if (!indexes->empty())
13938 indexes->push_back(index);
13940 else
13942 if (indexes->empty() && !vals->empty())
13944 for (size_t i = 0; i < vals->size(); ++i)
13945 indexes->push_back(i);
13948 Numeric_constant nc;
13949 if (!index_expr->numeric_constant_value(&nc))
13951 go_error_at(index_expr->location(),
13952 "index expression is not integer constant");
13953 return Expression::make_error(location);
13956 switch (nc.to_unsigned_long(&index))
13958 case Numeric_constant::NC_UL_VALID:
13959 break;
13960 case Numeric_constant::NC_UL_NOTINT:
13961 go_error_at(index_expr->location(),
13962 "index expression is not integer constant");
13963 return Expression::make_error(location);
13964 case Numeric_constant::NC_UL_NEGATIVE:
13965 go_error_at(index_expr->location(),
13966 "index expression is negative");
13967 return Expression::make_error(location);
13968 case Numeric_constant::NC_UL_BIG:
13969 go_error_at(index_expr->location(), "index value overflow");
13970 return Expression::make_error(location);
13971 default:
13972 go_unreachable();
13975 Named_type* ntype = Type::lookup_integer_type("int");
13976 Integer_type* inttype = ntype->integer_type();
13977 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13978 && index >> (inttype->bits() - 1) != 0)
13980 go_error_at(index_expr->location(), "index value overflow");
13981 return Expression::make_error(location);
13984 if (std::find(indexes->begin(), indexes->end(), index)
13985 != indexes->end())
13987 go_error_at(index_expr->location(),
13988 "duplicate value for index %lu",
13989 index);
13990 return Expression::make_error(location);
13993 if (!indexes->empty() && index < indexes->back())
13994 indexes_out_of_order = true;
13996 indexes->push_back(index);
13999 vals->push_back(val);
14001 ++index;
14004 if (indexes->empty())
14006 delete indexes;
14007 indexes = NULL;
14010 std::vector<unsigned long>* traverse_order = NULL;
14011 if (indexes_out_of_order)
14013 typedef std::vector<IVT_triple> V;
14015 V v;
14016 v.reserve(indexes->size());
14017 std::vector<unsigned long>::const_iterator pi = indexes->begin();
14018 unsigned long torder = 0;
14019 for (Expression_list::const_iterator pe = vals->begin();
14020 pe != vals->end();
14021 ++pe, ++pi, ++torder)
14022 v.push_back(IVT_triple(*pi, torder, *pe));
14024 std::sort(v.begin(), v.end());
14026 delete indexes;
14027 delete vals;
14029 indexes = new std::vector<unsigned long>();
14030 indexes->reserve(v.size());
14031 vals = new Expression_list();
14032 vals->reserve(v.size());
14033 traverse_order = new std::vector<unsigned long>();
14034 traverse_order->reserve(v.size());
14036 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
14038 indexes->push_back(p->index);
14039 vals->push_back(p->expr);
14040 traverse_order->push_back(p->traversal_order);
14044 Expression* ret = this->make_array(type, indexes, vals);
14045 Array_construction_expression* ace = ret->array_literal();
14046 if (ace != NULL && traverse_order != NULL)
14047 ace->set_traverse_order(traverse_order);
14048 return ret;
14051 // Actually build the array composite literal. This handles
14052 // [...]{...}.
14054 Expression*
14055 Composite_literal_expression::make_array(
14056 Type* type,
14057 const std::vector<unsigned long>* indexes,
14058 Expression_list* vals)
14060 Location location = this->location();
14061 Array_type* at = type->array_type();
14063 if (at->length() != NULL && at->length()->is_nil_expression())
14065 size_t size;
14066 if (vals == NULL)
14067 size = 0;
14068 else if (indexes != NULL)
14069 size = indexes->back() + 1;
14070 else
14072 size = vals->size();
14073 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
14074 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
14075 && size >> (it->bits() - 1) != 0)
14077 go_error_at(location, "too many elements in composite literal");
14078 return Expression::make_error(location);
14082 Expression* elen = Expression::make_integer_ul(size, NULL, location);
14083 at = Type::make_array_type(at->element_type(), elen);
14084 type = at;
14086 else if (at->length() != NULL
14087 && !at->length()->is_error_expression()
14088 && this->vals_ != NULL)
14090 Numeric_constant nc;
14091 unsigned long val;
14092 if (at->length()->numeric_constant_value(&nc)
14093 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
14095 if (indexes == NULL)
14097 if (this->vals_->size() > val)
14099 go_error_at(location,
14100 "too many elements in composite literal");
14101 return Expression::make_error(location);
14104 else
14106 unsigned long max = indexes->back();
14107 if (max >= val)
14109 go_error_at(location,
14110 ("some element keys in composite literal "
14111 "are out of range"));
14112 return Expression::make_error(location);
14118 if (at->length() != NULL)
14119 return new Fixed_array_construction_expression(type, indexes, vals,
14120 location);
14121 else
14122 return new Slice_construction_expression(type, indexes, vals, location);
14125 // Lower a map composite literal.
14127 Expression*
14128 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
14129 Statement_inserter* inserter,
14130 Type* type)
14132 Location location = this->location();
14133 if (this->vals_ != NULL)
14135 if (!this->has_keys_)
14137 go_error_at(location, "map composite literal must have keys");
14138 return Expression::make_error(location);
14141 for (Expression_list::iterator p = this->vals_->begin();
14142 p != this->vals_->end();
14143 p += 2)
14145 if (*p == NULL)
14147 ++p;
14148 go_error_at((*p)->location(),
14149 ("map composite literal must "
14150 "have keys for every value"));
14151 return Expression::make_error(location);
14153 // Make sure we have lowered the key; it may not have been
14154 // lowered in order to handle keys for struct composite
14155 // literals. Lower it now to get the right error message.
14156 if ((*p)->unknown_expression() != NULL)
14158 (*p)->unknown_expression()->clear_is_composite_literal_key();
14159 gogo->lower_expression(function, inserter, &*p);
14160 go_assert((*p)->is_error_expression());
14161 return Expression::make_error(location);
14166 return new Map_construction_expression(type, this->vals_, location);
14169 // Copy.
14171 Expression*
14172 Composite_literal_expression::do_copy()
14174 Composite_literal_expression* ret =
14175 new Composite_literal_expression(this->type_->copy_expressions(),
14176 this->depth_, this->has_keys_,
14177 (this->vals_ == NULL
14178 ? NULL
14179 : this->vals_->copy()),
14180 this->all_are_names_,
14181 this->location());
14182 ret->key_path_ = this->key_path_;
14183 return ret;
14186 // Dump ast representation for a composite literal expression.
14188 void
14189 Composite_literal_expression::do_dump_expression(
14190 Ast_dump_context* ast_dump_context) const
14192 ast_dump_context->ostream() << "composite(";
14193 ast_dump_context->dump_type(this->type_);
14194 ast_dump_context->ostream() << ", {";
14195 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14196 ast_dump_context->ostream() << "})";
14199 // Make a composite literal expression.
14201 Expression*
14202 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14203 Expression_list* vals, bool all_are_names,
14204 Location location)
14206 return new Composite_literal_expression(type, depth, has_keys, vals,
14207 all_are_names, location);
14210 // Return whether this expression is a composite literal.
14212 bool
14213 Expression::is_composite_literal() const
14215 switch (this->classification_)
14217 case EXPRESSION_COMPOSITE_LITERAL:
14218 case EXPRESSION_STRUCT_CONSTRUCTION:
14219 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14220 case EXPRESSION_SLICE_CONSTRUCTION:
14221 case EXPRESSION_MAP_CONSTRUCTION:
14222 return true;
14223 default:
14224 return false;
14228 // Return whether this expression is a composite literal which is not
14229 // constant.
14231 bool
14232 Expression::is_nonconstant_composite_literal() const
14234 switch (this->classification_)
14236 case EXPRESSION_STRUCT_CONSTRUCTION:
14238 const Struct_construction_expression *psce =
14239 static_cast<const Struct_construction_expression*>(this);
14240 return !psce->is_constant_struct();
14242 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14244 const Fixed_array_construction_expression *pace =
14245 static_cast<const Fixed_array_construction_expression*>(this);
14246 return !pace->is_constant_array();
14248 case EXPRESSION_SLICE_CONSTRUCTION:
14250 const Slice_construction_expression *pace =
14251 static_cast<const Slice_construction_expression*>(this);
14252 return !pace->is_constant_array();
14254 case EXPRESSION_MAP_CONSTRUCTION:
14255 return true;
14256 default:
14257 return false;
14261 // Return true if this is a variable or temporary_variable.
14263 bool
14264 Expression::is_variable() const
14266 switch (this->classification_)
14268 case EXPRESSION_VAR_REFERENCE:
14269 case EXPRESSION_TEMPORARY_REFERENCE:
14270 case EXPRESSION_SET_AND_USE_TEMPORARY:
14271 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14272 return true;
14273 default:
14274 return false;
14278 // Return true if this is a reference to a local variable.
14280 bool
14281 Expression::is_local_variable() const
14283 const Var_expression* ve = this->var_expression();
14284 if (ve == NULL)
14285 return false;
14286 const Named_object* no = ve->named_object();
14287 return (no->is_result_variable()
14288 || (no->is_variable() && !no->var_value()->is_global()));
14291 // Class Type_guard_expression.
14293 // Traversal.
14296 Type_guard_expression::do_traverse(Traverse* traverse)
14298 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14299 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14300 return TRAVERSE_EXIT;
14301 return TRAVERSE_CONTINUE;
14304 Expression*
14305 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14306 Statement_inserter* inserter)
14308 if (this->expr_->is_error_expression()
14309 || this->expr_->type()->is_error_type())
14311 go_assert(saw_errors());
14312 return Expression::make_error(this->location());
14315 if (!this->expr_->is_variable())
14317 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14318 this->location());
14319 inserter->insert(temp);
14320 this->expr_ =
14321 Expression::make_temporary_reference(temp, this->location());
14323 return this;
14326 // Check types of a type guard expression. The expression must have
14327 // an interface type, but the actual type conversion is checked at run
14328 // time.
14330 void
14331 Type_guard_expression::do_check_types(Gogo*)
14333 Type* expr_type = this->expr_->type();
14334 if (expr_type->interface_type() == NULL)
14336 if (!expr_type->is_error() && !this->type_->is_error())
14337 this->report_error(_("type assertion only valid for interface types"));
14338 this->set_is_error();
14340 else if (this->type_->interface_type() == NULL)
14342 std::string reason;
14343 if (!expr_type->interface_type()->implements_interface(this->type_,
14344 &reason))
14346 if (!this->type_->is_error())
14348 if (reason.empty())
14349 this->report_error(_("impossible type assertion: "
14350 "type does not implement interface"));
14351 else
14352 go_error_at(this->location(),
14353 ("impossible type assertion: "
14354 "type does not implement interface (%s)"),
14355 reason.c_str());
14357 this->set_is_error();
14362 // Copy.
14364 Expression*
14365 Type_guard_expression::do_copy()
14367 return new Type_guard_expression(this->expr_->copy(),
14368 this->type_->copy_expressions(),
14369 this->location());
14372 // Return the backend representation for a type guard expression.
14374 Bexpression*
14375 Type_guard_expression::do_get_backend(Translate_context* context)
14377 Expression* conversion;
14378 if (this->type_->interface_type() != NULL)
14379 conversion =
14380 Expression::convert_interface_to_interface(this->type_, this->expr_,
14381 true, this->location());
14382 else
14383 conversion =
14384 Expression::convert_for_assignment(context->gogo(), this->type_,
14385 this->expr_, this->location());
14387 Gogo* gogo = context->gogo();
14388 Btype* bt = this->type_->get_backend(gogo);
14389 Bexpression* bexpr = conversion->get_backend(context);
14390 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14393 // Dump ast representation for a type guard expression.
14395 void
14396 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14397 const
14399 this->expr_->dump_expression(ast_dump_context);
14400 ast_dump_context->ostream() << ".";
14401 ast_dump_context->dump_type(this->type_);
14404 // Make a type guard expression.
14406 Expression*
14407 Expression::make_type_guard(Expression* expr, Type* type,
14408 Location location)
14410 return new Type_guard_expression(expr, type, location);
14413 // Class Heap_expression.
14415 // Return the type of the expression stored on the heap.
14417 Type*
14418 Heap_expression::do_type()
14419 { return Type::make_pointer_type(this->expr_->type()); }
14421 // Return the backend representation for allocating an expression on the heap.
14423 Bexpression*
14424 Heap_expression::do_get_backend(Translate_context* context)
14426 Type* etype = this->expr_->type();
14427 if (this->expr_->is_error_expression() || etype->is_error())
14428 return context->backend()->error_expression();
14430 Location loc = this->location();
14431 Gogo* gogo = context->gogo();
14432 Btype* btype = this->type()->get_backend(gogo);
14434 Expression* alloc = Expression::make_allocation(etype, loc);
14435 if (this->allocate_on_stack_)
14436 alloc->allocation_expression()->set_allocate_on_stack();
14437 Bexpression* space = alloc->get_backend(context);
14439 Bstatement* decl;
14440 Named_object* fn = context->function();
14441 go_assert(fn != NULL);
14442 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14443 Bvariable* space_temp =
14444 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14445 space, true, loc, &decl);
14446 Btype* expr_btype = etype->get_backend(gogo);
14448 Bexpression* bexpr = this->expr_->get_backend(context);
14450 // If this assignment needs a write barrier, call typedmemmove. We
14451 // don't do this in the write barrier pass because in some cases
14452 // backend conversion can introduce new Heap_expression values.
14453 Bstatement* assn;
14454 if (!etype->has_pointer() || this->allocate_on_stack_)
14456 space = gogo->backend()->var_expression(space_temp, loc);
14457 Bexpression* ref =
14458 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14459 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14461 else
14463 Bstatement* edecl;
14464 Bvariable* btemp =
14465 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14466 expr_btype, bexpr, true, loc,
14467 &edecl);
14468 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14469 loc);
14470 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14472 Expression* td = Expression::make_type_descriptor(etype, loc);
14473 Type* etype_ptr = Type::make_pointer_type(etype);
14474 space = gogo->backend()->var_expression(space_temp, loc);
14475 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14476 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14477 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14478 td, elhs, erhs);
14479 Bexpression* bcall = call->get_backend(context);
14480 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14481 assn = gogo->backend()->compound_statement(edecl, s);
14483 decl = gogo->backend()->compound_statement(decl, assn);
14484 space = gogo->backend()->var_expression(space_temp, loc);
14485 return gogo->backend()->compound_expression(decl, space, loc);
14488 // Dump ast representation for a heap expression.
14490 void
14491 Heap_expression::do_dump_expression(
14492 Ast_dump_context* ast_dump_context) const
14494 ast_dump_context->ostream() << "&(";
14495 ast_dump_context->dump_expression(this->expr_);
14496 ast_dump_context->ostream() << ")";
14499 // Allocate an expression on the heap.
14501 Expression*
14502 Expression::make_heap_expression(Expression* expr, Location location)
14504 return new Heap_expression(expr, location);
14507 // Class Receive_expression.
14509 // Return the type of a receive expression.
14511 Type*
14512 Receive_expression::do_type()
14514 if (this->is_error_expression())
14515 return Type::make_error_type();
14516 Channel_type* channel_type = this->channel_->type()->channel_type();
14517 if (channel_type == NULL)
14519 this->report_error(_("expected channel"));
14520 return Type::make_error_type();
14522 return channel_type->element_type();
14525 // Check types for a receive expression.
14527 void
14528 Receive_expression::do_check_types(Gogo*)
14530 Type* type = this->channel_->type();
14531 if (type->is_error())
14533 go_assert(saw_errors());
14534 this->set_is_error();
14535 return;
14537 if (type->channel_type() == NULL)
14539 this->report_error(_("expected channel"));
14540 return;
14542 if (!type->channel_type()->may_receive())
14544 this->report_error(_("invalid receive on send-only channel"));
14545 return;
14549 // Flattening for receive expressions creates a temporary variable to store
14550 // received data in for receives.
14552 Expression*
14553 Receive_expression::do_flatten(Gogo*, Named_object*,
14554 Statement_inserter* inserter)
14556 Channel_type* channel_type = this->channel_->type()->channel_type();
14557 if (channel_type == NULL)
14559 go_assert(saw_errors());
14560 return this;
14562 else if (this->channel_->is_error_expression())
14564 go_assert(saw_errors());
14565 return Expression::make_error(this->location());
14568 Type* element_type = channel_type->element_type();
14569 if (this->temp_receiver_ == NULL)
14571 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14572 this->location());
14573 this->temp_receiver_->set_is_address_taken();
14574 inserter->insert(this->temp_receiver_);
14577 return this;
14580 // Get the backend representation for a receive expression.
14582 Bexpression*
14583 Receive_expression::do_get_backend(Translate_context* context)
14585 Location loc = this->location();
14587 Channel_type* channel_type = this->channel_->type()->channel_type();
14588 if (channel_type == NULL)
14590 go_assert(this->channel_->type()->is_error());
14591 return context->backend()->error_expression();
14594 Expression* recv_ref =
14595 Expression::make_temporary_reference(this->temp_receiver_, loc);
14596 Expression* recv_addr =
14597 Expression::make_temporary_reference(this->temp_receiver_, loc);
14598 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14599 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14600 this->channel_, recv_addr);
14601 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14604 // Dump ast representation for a receive expression.
14606 void
14607 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14609 ast_dump_context->ostream() << " <- " ;
14610 ast_dump_context->dump_expression(channel_);
14613 // Make a receive expression.
14615 Receive_expression*
14616 Expression::make_receive(Expression* channel, Location location)
14618 return new Receive_expression(channel, location);
14621 // An expression which evaluates to a pointer to the type descriptor
14622 // of a type.
14624 class Type_descriptor_expression : public Expression
14626 public:
14627 Type_descriptor_expression(Type* type, Location location)
14628 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14629 type_(type)
14632 protected:
14634 do_traverse(Traverse*);
14636 Type*
14637 do_type()
14638 { return Type::make_type_descriptor_ptr_type(); }
14640 bool
14641 do_is_static_initializer() const
14642 { return true; }
14644 void
14645 do_determine_type(const Type_context*)
14648 Expression*
14649 do_copy()
14650 { return this; }
14652 Bexpression*
14653 do_get_backend(Translate_context* context)
14655 return this->type_->type_descriptor_pointer(context->gogo(),
14656 this->location());
14659 void
14660 do_dump_expression(Ast_dump_context*) const;
14662 private:
14663 // The type for which this is the descriptor.
14664 Type* type_;
14668 Type_descriptor_expression::do_traverse(Traverse* traverse)
14670 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14671 return TRAVERSE_EXIT;
14672 return TRAVERSE_CONTINUE;
14675 // Dump ast representation for a type descriptor expression.
14677 void
14678 Type_descriptor_expression::do_dump_expression(
14679 Ast_dump_context* ast_dump_context) const
14681 ast_dump_context->dump_type(this->type_);
14684 // Make a type descriptor expression.
14686 Expression*
14687 Expression::make_type_descriptor(Type* type, Location location)
14689 return new Type_descriptor_expression(type, location);
14692 // An expression which evaluates to a pointer to the Garbage Collection symbol
14693 // of a type.
14695 class GC_symbol_expression : public Expression
14697 public:
14698 GC_symbol_expression(Type* type)
14699 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14700 type_(type)
14703 protected:
14704 Type*
14705 do_type()
14706 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14708 bool
14709 do_is_static_initializer() const
14710 { return true; }
14712 void
14713 do_determine_type(const Type_context*)
14716 Expression*
14717 do_copy()
14718 { return this; }
14720 Bexpression*
14721 do_get_backend(Translate_context* context)
14722 { return this->type_->gc_symbol_pointer(context->gogo()); }
14724 void
14725 do_dump_expression(Ast_dump_context*) const;
14727 private:
14728 // The type which this gc symbol describes.
14729 Type* type_;
14732 // Dump ast representation for a gc symbol expression.
14734 void
14735 GC_symbol_expression::do_dump_expression(
14736 Ast_dump_context* ast_dump_context) const
14738 ast_dump_context->ostream() << "gcdata(";
14739 ast_dump_context->dump_type(this->type_);
14740 ast_dump_context->ostream() << ")";
14743 // Make a gc symbol expression.
14745 Expression*
14746 Expression::make_gc_symbol(Type* type)
14748 return new GC_symbol_expression(type);
14751 // An expression that evaluates to a pointer to a symbol holding the
14752 // ptrmask data of a type.
14754 class Ptrmask_symbol_expression : public Expression
14756 public:
14757 Ptrmask_symbol_expression(Type* type)
14758 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14759 type_(type)
14762 protected:
14763 Type*
14764 do_type()
14765 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14767 bool
14768 do_is_static_initializer() const
14769 { return true; }
14771 void
14772 do_determine_type(const Type_context*)
14775 Expression*
14776 do_copy()
14777 { return this; }
14779 Bexpression*
14780 do_get_backend(Translate_context*);
14782 void
14783 do_dump_expression(Ast_dump_context*) const;
14785 private:
14786 // The type that this ptrmask symbol describes.
14787 Type* type_;
14790 // Return the ptrmask variable.
14792 Bexpression*
14793 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14795 Gogo* gogo = context->gogo();
14797 // If this type does not need a gcprog, then we can use the standard
14798 // GC symbol.
14799 int64_t ptrsize, ptrdata;
14800 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14801 return this->type_->gc_symbol_pointer(gogo);
14803 // Otherwise we have to build a ptrmask variable, and return a
14804 // pointer to it.
14806 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14807 Location bloc = Linemap::predeclared_location();
14808 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
14809 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14811 Type* uint8_type = Type::lookup_integer_type("uint8");
14812 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14813 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14814 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14817 // Dump AST for a ptrmask symbol expression.
14819 void
14820 Ptrmask_symbol_expression::do_dump_expression(
14821 Ast_dump_context* ast_dump_context) const
14823 ast_dump_context->ostream() << "ptrmask(";
14824 ast_dump_context->dump_type(this->type_);
14825 ast_dump_context->ostream() << ")";
14828 // Make a ptrmask symbol expression.
14830 Expression*
14831 Expression::make_ptrmask_symbol(Type* type)
14833 return new Ptrmask_symbol_expression(type);
14836 // An expression which evaluates to some characteristic of a type.
14837 // This is only used to initialize fields of a type descriptor. Using
14838 // a new expression class is slightly inefficient but gives us a good
14839 // separation between the frontend and the middle-end with regard to
14840 // how types are laid out.
14842 class Type_info_expression : public Expression
14844 public:
14845 Type_info_expression(Type* type, Type_info type_info)
14846 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14847 type_(type), type_info_(type_info)
14850 protected:
14851 bool
14852 do_is_static_initializer() const
14853 { return true; }
14855 Type*
14856 do_type();
14858 void
14859 do_determine_type(const Type_context*)
14862 Expression*
14863 do_copy()
14864 { return this; }
14866 Bexpression*
14867 do_get_backend(Translate_context* context);
14869 void
14870 do_dump_expression(Ast_dump_context*) const;
14872 private:
14873 // The type for which we are getting information.
14874 Type* type_;
14875 // What information we want.
14876 Type_info type_info_;
14879 // The type is chosen to match what the type descriptor struct
14880 // expects.
14882 Type*
14883 Type_info_expression::do_type()
14885 switch (this->type_info_)
14887 case TYPE_INFO_SIZE:
14888 case TYPE_INFO_BACKEND_PTRDATA:
14889 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14890 return Type::lookup_integer_type("uintptr");
14891 case TYPE_INFO_ALIGNMENT:
14892 case TYPE_INFO_FIELD_ALIGNMENT:
14893 return Type::lookup_integer_type("uint8");
14894 default:
14895 go_unreachable();
14899 // Return the backend representation for type information.
14901 Bexpression*
14902 Type_info_expression::do_get_backend(Translate_context* context)
14904 Gogo* gogo = context->gogo();
14905 bool ok = true;
14906 int64_t val;
14907 switch (this->type_info_)
14909 case TYPE_INFO_SIZE:
14910 ok = this->type_->backend_type_size(gogo, &val);
14911 break;
14912 case TYPE_INFO_ALIGNMENT:
14913 ok = this->type_->backend_type_align(gogo, &val);
14914 break;
14915 case TYPE_INFO_FIELD_ALIGNMENT:
14916 ok = this->type_->backend_type_field_align(gogo, &val);
14917 break;
14918 case TYPE_INFO_BACKEND_PTRDATA:
14919 ok = this->type_->backend_type_ptrdata(gogo, &val);
14920 break;
14921 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14922 ok = this->type_->descriptor_ptrdata(gogo, &val);
14923 break;
14924 default:
14925 go_unreachable();
14927 if (!ok)
14929 go_assert(saw_errors());
14930 return gogo->backend()->error_expression();
14932 Expression* e = Expression::make_integer_int64(val, this->type(),
14933 this->location());
14934 return e->get_backend(context);
14937 // Dump ast representation for a type info expression.
14939 void
14940 Type_info_expression::do_dump_expression(
14941 Ast_dump_context* ast_dump_context) const
14943 ast_dump_context->ostream() << "typeinfo(";
14944 ast_dump_context->dump_type(this->type_);
14945 ast_dump_context->ostream() << ",";
14946 ast_dump_context->ostream() <<
14947 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14948 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14949 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14950 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14951 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14952 : "unknown");
14953 ast_dump_context->ostream() << ")";
14956 // Make a type info expression.
14958 Expression*
14959 Expression::make_type_info(Type* type, Type_info type_info)
14961 return new Type_info_expression(type, type_info);
14964 // An expression that evaluates to some characteristic of a slice.
14965 // This is used when indexing, bound-checking, or nil checking a slice.
14967 class Slice_info_expression : public Expression
14969 public:
14970 Slice_info_expression(Expression* slice, Slice_info slice_info,
14971 Location location)
14972 : Expression(EXPRESSION_SLICE_INFO, location),
14973 slice_(slice), slice_info_(slice_info)
14976 protected:
14977 Type*
14978 do_type();
14980 void
14981 do_determine_type(const Type_context*)
14984 Expression*
14985 do_copy()
14987 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14988 this->location());
14991 Bexpression*
14992 do_get_backend(Translate_context* context);
14994 void
14995 do_dump_expression(Ast_dump_context*) const;
14997 void
14998 do_issue_nil_check()
14999 { this->slice_->issue_nil_check(); }
15001 private:
15002 // The slice for which we are getting information.
15003 Expression* slice_;
15004 // What information we want.
15005 Slice_info slice_info_;
15008 // Return the type of the slice info.
15010 Type*
15011 Slice_info_expression::do_type()
15013 switch (this->slice_info_)
15015 case SLICE_INFO_VALUE_POINTER:
15016 return Type::make_pointer_type(
15017 this->slice_->type()->array_type()->element_type());
15018 case SLICE_INFO_LENGTH:
15019 case SLICE_INFO_CAPACITY:
15020 return Type::lookup_integer_type("int");
15021 default:
15022 go_unreachable();
15026 // Return the backend information for slice information.
15028 Bexpression*
15029 Slice_info_expression::do_get_backend(Translate_context* context)
15031 Gogo* gogo = context->gogo();
15032 Bexpression* bslice = this->slice_->get_backend(context);
15033 switch (this->slice_info_)
15035 case SLICE_INFO_VALUE_POINTER:
15036 case SLICE_INFO_LENGTH:
15037 case SLICE_INFO_CAPACITY:
15038 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
15039 this->location());
15040 break;
15041 default:
15042 go_unreachable();
15046 // Dump ast representation for a type info expression.
15048 void
15049 Slice_info_expression::do_dump_expression(
15050 Ast_dump_context* ast_dump_context) const
15052 ast_dump_context->ostream() << "sliceinfo(";
15053 this->slice_->dump_expression(ast_dump_context);
15054 ast_dump_context->ostream() << ",";
15055 ast_dump_context->ostream() <<
15056 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
15057 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
15058 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
15059 : "unknown");
15060 ast_dump_context->ostream() << ")";
15063 // Make a slice info expression.
15065 Expression*
15066 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
15067 Location location)
15069 return new Slice_info_expression(slice, slice_info, location);
15072 // An expression that represents a slice value: a struct with value pointer,
15073 // length, and capacity fields.
15075 class Slice_value_expression : public Expression
15077 public:
15078 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
15079 Expression* cap, Location location)
15080 : Expression(EXPRESSION_SLICE_VALUE, location),
15081 type_(type), valptr_(valptr), len_(len), cap_(cap)
15084 protected:
15086 do_traverse(Traverse*);
15088 Type*
15089 do_type()
15090 { return this->type_; }
15092 void
15093 do_determine_type(const Type_context*)
15094 { go_unreachable(); }
15096 Expression*
15097 do_copy()
15099 return new Slice_value_expression(this->type_->copy_expressions(),
15100 this->valptr_->copy(),
15101 this->len_->copy(), this->cap_->copy(),
15102 this->location());
15105 Bexpression*
15106 do_get_backend(Translate_context* context);
15108 void
15109 do_dump_expression(Ast_dump_context*) const;
15111 private:
15112 // The type of the slice value.
15113 Type* type_;
15114 // The pointer to the values in the slice.
15115 Expression* valptr_;
15116 // The length of the slice.
15117 Expression* len_;
15118 // The capacity of the slice.
15119 Expression* cap_;
15123 Slice_value_expression::do_traverse(Traverse* traverse)
15125 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
15126 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
15127 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
15128 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
15129 return TRAVERSE_EXIT;
15130 return TRAVERSE_CONTINUE;
15133 Bexpression*
15134 Slice_value_expression::do_get_backend(Translate_context* context)
15136 std::vector<Bexpression*> vals(3);
15137 vals[0] = this->valptr_->get_backend(context);
15138 vals[1] = this->len_->get_backend(context);
15139 vals[2] = this->cap_->get_backend(context);
15141 Gogo* gogo = context->gogo();
15142 Btype* btype = this->type_->get_backend(gogo);
15143 return gogo->backend()->constructor_expression(btype, vals, this->location());
15146 void
15147 Slice_value_expression::do_dump_expression(
15148 Ast_dump_context* ast_dump_context) const
15150 ast_dump_context->ostream() << "slicevalue(";
15151 ast_dump_context->ostream() << "values: ";
15152 this->valptr_->dump_expression(ast_dump_context);
15153 ast_dump_context->ostream() << ", length: ";
15154 this->len_->dump_expression(ast_dump_context);
15155 ast_dump_context->ostream() << ", capacity: ";
15156 this->cap_->dump_expression(ast_dump_context);
15157 ast_dump_context->ostream() << ")";
15160 Expression*
15161 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
15162 Expression* cap, Location location)
15164 go_assert(at->is_slice_type());
15165 return new Slice_value_expression(at, valptr, len, cap, location);
15168 // An expression that evaluates to some characteristic of a non-empty interface.
15169 // This is used to access the method table or underlying object of an interface.
15171 class Interface_info_expression : public Expression
15173 public:
15174 Interface_info_expression(Expression* iface, Interface_info iface_info,
15175 Location location)
15176 : Expression(EXPRESSION_INTERFACE_INFO, location),
15177 iface_(iface), iface_info_(iface_info)
15180 protected:
15181 Type*
15182 do_type();
15184 void
15185 do_determine_type(const Type_context*)
15188 Expression*
15189 do_copy()
15191 return new Interface_info_expression(this->iface_->copy(),
15192 this->iface_info_, this->location());
15195 Bexpression*
15196 do_get_backend(Translate_context* context);
15198 void
15199 do_dump_expression(Ast_dump_context*) const;
15201 void
15202 do_issue_nil_check()
15203 { this->iface_->issue_nil_check(); }
15205 private:
15206 // The interface for which we are getting information.
15207 Expression* iface_;
15208 // What information we want.
15209 Interface_info iface_info_;
15212 // Return the type of the interface info.
15214 Type*
15215 Interface_info_expression::do_type()
15217 switch (this->iface_info_)
15219 case INTERFACE_INFO_METHODS:
15221 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15222 static Hashtable result_types;
15224 Interface_type* itype = this->iface_->type()->interface_type();
15226 Hashtable::const_iterator p = result_types.find(itype);
15227 if (p != result_types.end())
15228 return p->second;
15230 Type* pdt = Type::make_type_descriptor_ptr_type();
15231 if (itype->is_empty())
15233 result_types[itype] = pdt;
15234 return pdt;
15237 Location loc = this->location();
15238 Struct_field_list* sfl = new Struct_field_list();
15239 sfl->push_back(
15240 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15242 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15243 p != itype->methods()->end();
15244 ++p)
15246 Function_type* ft = p->type()->function_type();
15247 go_assert(ft->receiver() == NULL);
15249 const Typed_identifier_list* params = ft->parameters();
15250 Typed_identifier_list* mparams = new Typed_identifier_list();
15251 if (params != NULL)
15252 mparams->reserve(params->size() + 1);
15253 Type* vt = Type::make_pointer_type(Type::make_void_type());
15254 mparams->push_back(Typed_identifier("", vt, ft->location()));
15255 if (params != NULL)
15257 for (Typed_identifier_list::const_iterator pp = params->begin();
15258 pp != params->end();
15259 ++pp)
15260 mparams->push_back(*pp);
15263 Typed_identifier_list* mresults = (ft->results() == NULL
15264 ? NULL
15265 : ft->results()->copy());
15266 Backend_function_type* mft =
15267 Type::make_backend_function_type(NULL, mparams, mresults,
15268 ft->location());
15270 std::string fname = Gogo::unpack_hidden_name(p->name());
15271 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15274 Struct_type* st = Type::make_struct_type(sfl, loc);
15275 st->set_is_struct_incomparable();
15276 Pointer_type *pt = Type::make_pointer_type(st);
15277 result_types[itype] = pt;
15278 return pt;
15280 case INTERFACE_INFO_OBJECT:
15281 return Type::make_pointer_type(Type::make_void_type());
15282 default:
15283 go_unreachable();
15287 // Return the backend representation for interface information.
15289 Bexpression*
15290 Interface_info_expression::do_get_backend(Translate_context* context)
15292 Gogo* gogo = context->gogo();
15293 Bexpression* biface = this->iface_->get_backend(context);
15294 switch (this->iface_info_)
15296 case INTERFACE_INFO_METHODS:
15297 case INTERFACE_INFO_OBJECT:
15298 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15299 this->location());
15300 break;
15301 default:
15302 go_unreachable();
15306 // Dump ast representation for an interface info expression.
15308 void
15309 Interface_info_expression::do_dump_expression(
15310 Ast_dump_context* ast_dump_context) const
15312 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15313 ast_dump_context->ostream() << "interfaceinfo(";
15314 this->iface_->dump_expression(ast_dump_context);
15315 ast_dump_context->ostream() << ",";
15316 ast_dump_context->ostream() <<
15317 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15318 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15319 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15320 : "unknown");
15321 ast_dump_context->ostream() << ")";
15324 // Make an interface info expression.
15326 Expression*
15327 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15328 Location location)
15330 return new Interface_info_expression(iface, iface_info, location);
15333 // An expression that represents an interface value. The first field is either
15334 // a type descriptor for an empty interface or a pointer to the interface method
15335 // table for a non-empty interface. The second field is always the object.
15337 class Interface_value_expression : public Expression
15339 public:
15340 Interface_value_expression(Type* type, Expression* first_field,
15341 Expression* obj, Location location)
15342 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15343 type_(type), first_field_(first_field), obj_(obj)
15346 protected:
15348 do_traverse(Traverse*);
15350 Type*
15351 do_type()
15352 { return this->type_; }
15354 void
15355 do_determine_type(const Type_context*)
15356 { go_unreachable(); }
15358 Expression*
15359 do_copy()
15361 return new Interface_value_expression(this->type_->copy_expressions(),
15362 this->first_field_->copy(),
15363 this->obj_->copy(), this->location());
15366 Bexpression*
15367 do_get_backend(Translate_context* context);
15369 void
15370 do_dump_expression(Ast_dump_context*) const;
15372 private:
15373 // The type of the interface value.
15374 Type* type_;
15375 // The first field of the interface (either a type descriptor or a pointer
15376 // to the method table.
15377 Expression* first_field_;
15378 // The underlying object of the interface.
15379 Expression* obj_;
15383 Interface_value_expression::do_traverse(Traverse* traverse)
15385 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15386 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15387 return TRAVERSE_EXIT;
15388 return TRAVERSE_CONTINUE;
15391 Bexpression*
15392 Interface_value_expression::do_get_backend(Translate_context* context)
15394 std::vector<Bexpression*> vals(2);
15395 vals[0] = this->first_field_->get_backend(context);
15396 vals[1] = this->obj_->get_backend(context);
15398 Gogo* gogo = context->gogo();
15399 Btype* btype = this->type_->get_backend(gogo);
15400 return gogo->backend()->constructor_expression(btype, vals, this->location());
15403 void
15404 Interface_value_expression::do_dump_expression(
15405 Ast_dump_context* ast_dump_context) const
15407 ast_dump_context->ostream() << "interfacevalue(";
15408 ast_dump_context->ostream() <<
15409 (this->type_->interface_type()->is_empty()
15410 ? "type_descriptor: "
15411 : "methods: ");
15412 this->first_field_->dump_expression(ast_dump_context);
15413 ast_dump_context->ostream() << ", object: ";
15414 this->obj_->dump_expression(ast_dump_context);
15415 ast_dump_context->ostream() << ")";
15418 Expression*
15419 Expression::make_interface_value(Type* type, Expression* first_value,
15420 Expression* object, Location location)
15422 return new Interface_value_expression(type, first_value, object, location);
15425 // An interface method table for a pair of types: an interface type and a type
15426 // that implements that interface.
15428 class Interface_mtable_expression : public Expression
15430 public:
15431 Interface_mtable_expression(Interface_type* itype, Type* type,
15432 bool is_pointer, Location location)
15433 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15434 itype_(itype), type_(type), is_pointer_(is_pointer),
15435 method_table_type_(NULL), bvar_(NULL)
15438 protected:
15440 do_traverse(Traverse*);
15442 Type*
15443 do_type();
15445 bool
15446 do_is_static_initializer() const
15447 { return true; }
15449 void
15450 do_determine_type(const Type_context*)
15451 { go_unreachable(); }
15453 Expression*
15454 do_copy()
15456 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
15457 return new Interface_mtable_expression(itype,
15458 this->type_->copy_expressions(),
15459 this->is_pointer_, this->location());
15462 bool
15463 do_is_addressable() const
15464 { return true; }
15466 Bexpression*
15467 do_get_backend(Translate_context* context);
15469 void
15470 do_dump_expression(Ast_dump_context*) const;
15472 private:
15473 // The interface type for which the methods are defined.
15474 Interface_type* itype_;
15475 // The type to construct the interface method table for.
15476 Type* type_;
15477 // Whether this table contains the method set for the receiver type or the
15478 // pointer receiver type.
15479 bool is_pointer_;
15480 // The type of the method table.
15481 Type* method_table_type_;
15482 // The backend variable that refers to the interface method table.
15483 Bvariable* bvar_;
15487 Interface_mtable_expression::do_traverse(Traverse* traverse)
15489 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15490 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15491 return TRAVERSE_EXIT;
15492 return TRAVERSE_CONTINUE;
15495 Type*
15496 Interface_mtable_expression::do_type()
15498 if (this->method_table_type_ != NULL)
15499 return this->method_table_type_;
15501 const Typed_identifier_list* interface_methods = this->itype_->methods();
15502 go_assert(!interface_methods->empty());
15504 Struct_field_list* sfl = new Struct_field_list;
15505 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15506 this->location());
15507 sfl->push_back(Struct_field(tid));
15508 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15509 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15510 p != interface_methods->end();
15511 ++p)
15513 // We want C function pointers here, not func descriptors; model
15514 // using void* pointers.
15515 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15516 sfl->push_back(Struct_field(method));
15518 Struct_type* st = Type::make_struct_type(sfl, this->location());
15519 st->set_is_struct_incomparable();
15520 this->method_table_type_ = st;
15521 return this->method_table_type_;
15524 Bexpression*
15525 Interface_mtable_expression::do_get_backend(Translate_context* context)
15527 Gogo* gogo = context->gogo();
15528 Location loc = Linemap::predeclared_location();
15529 if (this->bvar_ != NULL)
15530 return gogo->backend()->var_expression(this->bvar_, this->location());
15532 const Typed_identifier_list* interface_methods = this->itype_->methods();
15533 go_assert(!interface_methods->empty());
15535 std::string mangled_name =
15536 gogo->interface_method_table_name(this->itype_, this->type_,
15537 this->is_pointer_);
15539 // Set is_public if we are converting a named type to an interface
15540 // type that is defined in the same package as the named type, and
15541 // the interface has hidden methods. In that case the interface
15542 // method table will be defined by the package that defines the
15543 // types.
15544 bool is_public = false;
15545 if (this->type_->named_type() != NULL
15546 && (this->type_->named_type()->named_object()->package()
15547 == this->itype_->package()))
15549 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15550 p != interface_methods->end();
15551 ++p)
15553 if (Gogo::is_hidden_name(p->name()))
15555 is_public = true;
15556 break;
15561 if (is_public
15562 && this->type_->named_type()->named_object()->package() != NULL)
15564 // The interface conversion table is defined elsewhere.
15565 Btype* btype = this->type()->get_backend(gogo);
15566 std::string asm_name(go_selectively_encode_id(mangled_name));
15567 this->bvar_ =
15568 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15569 btype, loc);
15570 return gogo->backend()->var_expression(this->bvar_, this->location());
15573 // The first element is the type descriptor.
15574 Type* td_type;
15575 if (!this->is_pointer_)
15576 td_type = this->type_;
15577 else
15578 td_type = Type::make_pointer_type(this->type_);
15580 std::vector<Backend::Btyped_identifier> bstructfields;
15582 // Build an interface method table for a type: a type descriptor followed by a
15583 // list of function pointers, one for each interface method. This is used for
15584 // interfaces.
15585 Expression_list* svals = new Expression_list();
15586 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15587 svals->push_back(tdescriptor);
15589 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15590 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15591 bstructfields.push_back(btd);
15593 Named_type* nt = this->type_->named_type();
15594 Struct_type* st = this->type_->struct_type();
15595 go_assert(nt != NULL || st != NULL);
15597 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15598 p != interface_methods->end();
15599 ++p)
15601 bool is_ambiguous;
15602 Method* m;
15603 if (nt != NULL)
15604 m = nt->method_function(p->name(), &is_ambiguous);
15605 else
15606 m = st->method_function(p->name(), &is_ambiguous);
15607 go_assert(m != NULL);
15608 Named_object* no = m->named_object();
15610 go_assert(no->is_function() || no->is_function_declaration());
15612 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15613 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15614 bstructfields.push_back(bmtype);
15616 svals->push_back(Expression::make_func_code_reference(no, loc));
15619 Btype *btype = gogo->backend()->struct_type(bstructfields);
15620 std::vector<Bexpression*> ctor_bexprs;
15621 for (Expression_list::const_iterator pe = svals->begin();
15622 pe != svals->end();
15623 ++pe)
15625 ctor_bexprs.push_back((*pe)->get_backend(context));
15627 Bexpression* ctor =
15628 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15630 std::string asm_name(go_selectively_encode_id(mangled_name));
15631 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15632 !is_public, btype, loc);
15633 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15634 !is_public, btype, loc, ctor);
15635 return gogo->backend()->var_expression(this->bvar_, loc);
15638 void
15639 Interface_mtable_expression::do_dump_expression(
15640 Ast_dump_context* ast_dump_context) const
15642 ast_dump_context->ostream() << "__go_"
15643 << (this->is_pointer_ ? "pimt__" : "imt_");
15644 ast_dump_context->dump_type(this->itype_);
15645 ast_dump_context->ostream() << "__";
15646 ast_dump_context->dump_type(this->type_);
15649 Expression*
15650 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15651 bool is_pointer, Location location)
15653 return new Interface_mtable_expression(itype, type, is_pointer, location);
15656 // An expression which evaluates to the offset of a field within a
15657 // struct. This, like Type_info_expression, q.v., is only used to
15658 // initialize fields of a type descriptor.
15660 class Struct_field_offset_expression : public Expression
15662 public:
15663 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15664 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15665 Linemap::predeclared_location()),
15666 type_(type), field_(field)
15669 protected:
15670 bool
15671 do_is_static_initializer() const
15672 { return true; }
15674 Type*
15675 do_type()
15676 { return Type::lookup_integer_type("uintptr"); }
15678 void
15679 do_determine_type(const Type_context*)
15682 Expression*
15683 do_copy()
15684 { return this; }
15686 Bexpression*
15687 do_get_backend(Translate_context* context);
15689 void
15690 do_dump_expression(Ast_dump_context*) const;
15692 private:
15693 // The type of the struct.
15694 Struct_type* type_;
15695 // The field.
15696 const Struct_field* field_;
15699 // Return the backend representation for a struct field offset.
15701 Bexpression*
15702 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15704 const Struct_field_list* fields = this->type_->fields();
15705 Struct_field_list::const_iterator p;
15706 unsigned i = 0;
15707 for (p = fields->begin();
15708 p != fields->end();
15709 ++p, ++i)
15710 if (&*p == this->field_)
15711 break;
15712 go_assert(&*p == this->field_);
15714 Gogo* gogo = context->gogo();
15715 Btype* btype = this->type_->get_backend(gogo);
15717 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15718 Type* uptr_type = Type::lookup_integer_type("uintptr");
15719 Expression* ret =
15720 Expression::make_integer_int64(offset, uptr_type,
15721 Linemap::predeclared_location());
15722 return ret->get_backend(context);
15725 // Dump ast representation for a struct field offset expression.
15727 void
15728 Struct_field_offset_expression::do_dump_expression(
15729 Ast_dump_context* ast_dump_context) const
15731 ast_dump_context->ostream() << "unsafe.Offsetof(";
15732 ast_dump_context->dump_type(this->type_);
15733 ast_dump_context->ostream() << '.';
15734 ast_dump_context->ostream() <<
15735 Gogo::message_name(this->field_->field_name());
15736 ast_dump_context->ostream() << ")";
15739 // Make an expression for a struct field offset.
15741 Expression*
15742 Expression::make_struct_field_offset(Struct_type* type,
15743 const Struct_field* field)
15745 return new Struct_field_offset_expression(type, field);
15748 // An expression which evaluates to the address of an unnamed label.
15750 class Label_addr_expression : public Expression
15752 public:
15753 Label_addr_expression(Label* label, Location location)
15754 : Expression(EXPRESSION_LABEL_ADDR, location),
15755 label_(label)
15758 protected:
15759 Type*
15760 do_type()
15761 { return Type::make_pointer_type(Type::make_void_type()); }
15763 void
15764 do_determine_type(const Type_context*)
15767 Expression*
15768 do_copy()
15769 { return new Label_addr_expression(this->label_, this->location()); }
15771 Bexpression*
15772 do_get_backend(Translate_context* context)
15773 { return this->label_->get_addr(context, this->location()); }
15775 void
15776 do_dump_expression(Ast_dump_context* ast_dump_context) const
15777 { ast_dump_context->ostream() << this->label_->name(); }
15779 private:
15780 // The label whose address we are taking.
15781 Label* label_;
15784 // Make an expression for the address of an unnamed label.
15786 Expression*
15787 Expression::make_label_addr(Label* label, Location location)
15789 return new Label_addr_expression(label, location);
15792 // Class Conditional_expression.
15794 // Traversal.
15797 Conditional_expression::do_traverse(Traverse* traverse)
15799 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15800 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15801 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15802 return TRAVERSE_EXIT;
15803 return TRAVERSE_CONTINUE;
15806 // Return the type of the conditional expression.
15808 Type*
15809 Conditional_expression::do_type()
15811 Type* result_type = Type::make_void_type();
15812 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15813 NULL))
15814 result_type = this->then_->type();
15815 else if (this->then_->is_nil_expression()
15816 || this->else_->is_nil_expression())
15817 result_type = (!this->then_->is_nil_expression()
15818 ? this->then_->type()
15819 : this->else_->type());
15820 return result_type;
15823 // Determine type for a conditional expression.
15825 void
15826 Conditional_expression::do_determine_type(const Type_context* context)
15828 this->cond_->determine_type_no_context();
15829 this->then_->determine_type(context);
15830 this->else_->determine_type(context);
15833 // Get the backend representation of a conditional expression.
15835 Bexpression*
15836 Conditional_expression::do_get_backend(Translate_context* context)
15838 Gogo* gogo = context->gogo();
15839 Btype* result_btype = this->type()->get_backend(gogo);
15840 Bexpression* cond = this->cond_->get_backend(context);
15841 Bexpression* then = this->then_->get_backend(context);
15842 Bexpression* belse = this->else_->get_backend(context);
15843 Bfunction* bfn = context->function()->func_value()->get_decl();
15844 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15845 belse, this->location());
15848 // Dump ast representation of a conditional expression.
15850 void
15851 Conditional_expression::do_dump_expression(
15852 Ast_dump_context* ast_dump_context) const
15854 ast_dump_context->ostream() << "(";
15855 ast_dump_context->dump_expression(this->cond_);
15856 ast_dump_context->ostream() << " ? ";
15857 ast_dump_context->dump_expression(this->then_);
15858 ast_dump_context->ostream() << " : ";
15859 ast_dump_context->dump_expression(this->else_);
15860 ast_dump_context->ostream() << ") ";
15863 // Make a conditional expression.
15865 Expression*
15866 Expression::make_conditional(Expression* cond, Expression* then,
15867 Expression* else_expr, Location location)
15869 return new Conditional_expression(cond, then, else_expr, location);
15872 // Class Compound_expression.
15874 // Traversal.
15877 Compound_expression::do_traverse(Traverse* traverse)
15879 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15880 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15881 return TRAVERSE_EXIT;
15882 return TRAVERSE_CONTINUE;
15885 // Return the type of the compound expression.
15887 Type*
15888 Compound_expression::do_type()
15890 return this->expr_->type();
15893 // Determine type for a compound expression.
15895 void
15896 Compound_expression::do_determine_type(const Type_context* context)
15898 this->init_->determine_type_no_context();
15899 this->expr_->determine_type(context);
15902 // Get the backend representation of a compound expression.
15904 Bexpression*
15905 Compound_expression::do_get_backend(Translate_context* context)
15907 Gogo* gogo = context->gogo();
15908 Bexpression* binit = this->init_->get_backend(context);
15909 Bfunction* bfunction = context->function()->func_value()->get_decl();
15910 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15911 binit);
15912 Bexpression* bexpr = this->expr_->get_backend(context);
15913 return gogo->backend()->compound_expression(init_stmt, bexpr,
15914 this->location());
15917 // Dump ast representation of a conditional expression.
15919 void
15920 Compound_expression::do_dump_expression(
15921 Ast_dump_context* ast_dump_context) const
15923 ast_dump_context->ostream() << "(";
15924 ast_dump_context->dump_expression(this->init_);
15925 ast_dump_context->ostream() << ",";
15926 ast_dump_context->dump_expression(this->expr_);
15927 ast_dump_context->ostream() << ") ";
15930 // Make a compound expression.
15932 Expression*
15933 Expression::make_compound(Expression* init, Expression* expr, Location location)
15935 return new Compound_expression(init, expr, location);
15938 // Class Backend_expression.
15941 Backend_expression::do_traverse(Traverse*)
15943 return TRAVERSE_CONTINUE;
15946 Expression*
15947 Backend_expression::do_copy()
15949 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
15950 this->location());
15953 void
15954 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15956 ast_dump_context->ostream() << "backend_expression<";
15957 ast_dump_context->dump_type(this->type_);
15958 ast_dump_context->ostream() << ">";
15961 Expression*
15962 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15964 return new Backend_expression(bexpr, type, location);
15967 // Import an expression. This comes at the end in order to see the
15968 // various class definitions.
15970 Expression*
15971 Expression::import_expression(Import* imp)
15973 int c = imp->peek_char();
15974 if (imp->match_c_string("- ")
15975 || imp->match_c_string("! ")
15976 || imp->match_c_string("^ "))
15977 return Unary_expression::do_import(imp);
15978 else if (c == '(')
15979 return Binary_expression::do_import(imp);
15980 else if (imp->match_c_string("true")
15981 || imp->match_c_string("false"))
15982 return Boolean_expression::do_import(imp);
15983 else if (c == '"')
15984 return String_expression::do_import(imp);
15985 else if (c == '-' || (c >= '0' && c <= '9'))
15987 // This handles integers, floats and complex constants.
15988 return Integer_expression::do_import(imp);
15990 else if (imp->match_c_string("nil"))
15991 return Nil_expression::do_import(imp);
15992 else if (imp->match_c_string("convert"))
15993 return Type_conversion_expression::do_import(imp);
15994 else
15996 go_error_at(imp->location(), "import error: expected expression");
15997 return Expression::make_error(imp->location());
16001 // Class Expression_list.
16003 // Traverse the list.
16006 Expression_list::traverse(Traverse* traverse)
16008 for (Expression_list::iterator p = this->begin();
16009 p != this->end();
16010 ++p)
16012 if (*p != NULL)
16014 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16015 return TRAVERSE_EXIT;
16018 return TRAVERSE_CONTINUE;
16021 // Copy the list.
16023 Expression_list*
16024 Expression_list::copy()
16026 Expression_list* ret = new Expression_list();
16027 for (Expression_list::iterator p = this->begin();
16028 p != this->end();
16029 ++p)
16031 if (*p == NULL)
16032 ret->push_back(NULL);
16033 else
16034 ret->push_back((*p)->copy());
16036 return ret;
16039 // Return whether an expression list has an error expression.
16041 bool
16042 Expression_list::contains_error() const
16044 for (Expression_list::const_iterator p = this->begin();
16045 p != this->end();
16046 ++p)
16047 if (*p != NULL && (*p)->is_error_expression())
16048 return true;
16049 return false;
16052 // Class Numeric_constant.
16054 // Destructor.
16056 Numeric_constant::~Numeric_constant()
16058 this->clear();
16061 // Copy constructor.
16063 Numeric_constant::Numeric_constant(const Numeric_constant& a)
16064 : classification_(a.classification_), type_(a.type_)
16066 switch (a.classification_)
16068 case NC_INVALID:
16069 break;
16070 case NC_INT:
16071 case NC_RUNE:
16072 mpz_init_set(this->u_.int_val, a.u_.int_val);
16073 break;
16074 case NC_FLOAT:
16075 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16076 break;
16077 case NC_COMPLEX:
16078 mpc_init2(this->u_.complex_val, mpc_precision);
16079 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16080 break;
16081 default:
16082 go_unreachable();
16086 // Assignment operator.
16088 Numeric_constant&
16089 Numeric_constant::operator=(const Numeric_constant& a)
16091 this->clear();
16092 this->classification_ = a.classification_;
16093 this->type_ = a.type_;
16094 switch (a.classification_)
16096 case NC_INVALID:
16097 break;
16098 case NC_INT:
16099 case NC_RUNE:
16100 mpz_init_set(this->u_.int_val, a.u_.int_val);
16101 break;
16102 case NC_FLOAT:
16103 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16104 break;
16105 case NC_COMPLEX:
16106 mpc_init2(this->u_.complex_val, mpc_precision);
16107 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16108 break;
16109 default:
16110 go_unreachable();
16112 return *this;
16115 // Clear the contents.
16117 void
16118 Numeric_constant::clear()
16120 switch (this->classification_)
16122 case NC_INVALID:
16123 break;
16124 case NC_INT:
16125 case NC_RUNE:
16126 mpz_clear(this->u_.int_val);
16127 break;
16128 case NC_FLOAT:
16129 mpfr_clear(this->u_.float_val);
16130 break;
16131 case NC_COMPLEX:
16132 mpc_clear(this->u_.complex_val);
16133 break;
16134 default:
16135 go_unreachable();
16137 this->classification_ = NC_INVALID;
16140 // Set to an unsigned long value.
16142 void
16143 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
16145 this->clear();
16146 this->classification_ = NC_INT;
16147 this->type_ = type;
16148 mpz_init_set_ui(this->u_.int_val, val);
16151 // Set to an integer value.
16153 void
16154 Numeric_constant::set_int(Type* type, const mpz_t val)
16156 this->clear();
16157 this->classification_ = NC_INT;
16158 this->type_ = type;
16159 mpz_init_set(this->u_.int_val, val);
16162 // Set to a rune value.
16164 void
16165 Numeric_constant::set_rune(Type* type, const mpz_t val)
16167 this->clear();
16168 this->classification_ = NC_RUNE;
16169 this->type_ = type;
16170 mpz_init_set(this->u_.int_val, val);
16173 // Set to a floating point value.
16175 void
16176 Numeric_constant::set_float(Type* type, const mpfr_t val)
16178 this->clear();
16179 this->classification_ = NC_FLOAT;
16180 this->type_ = type;
16182 // Numeric constants do not have negative zero values, so remove
16183 // them here. They also don't have infinity or NaN values, but we
16184 // should never see them here.
16185 int bits = 0;
16186 if (type != NULL
16187 && type->float_type() != NULL
16188 && !type->float_type()->is_abstract())
16189 bits = type->float_type()->bits();
16190 if (Numeric_constant::is_float_neg_zero(val, bits))
16191 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16192 else
16193 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16196 // Set to a complex value.
16198 void
16199 Numeric_constant::set_complex(Type* type, const mpc_t val)
16201 this->clear();
16202 this->classification_ = NC_COMPLEX;
16203 this->type_ = type;
16205 // Avoid negative zero as in set_float.
16206 int bits = 0;
16207 if (type != NULL
16208 && type->complex_type() != NULL
16209 && !type->complex_type()->is_abstract())
16210 bits = type->complex_type()->bits() / 2;
16212 mpfr_t real;
16213 mpfr_init_set(real, mpc_realref(val), GMP_RNDN);
16214 if (Numeric_constant::is_float_neg_zero(real, bits))
16215 mpfr_set_ui(real, 0, GMP_RNDN);
16217 mpfr_t imag;
16218 mpfr_init_set(imag, mpc_imagref(val), GMP_RNDN);
16219 if (Numeric_constant::is_float_neg_zero(imag, bits))
16220 mpfr_set_ui(imag, 0, GMP_RNDN);
16222 mpc_init2(this->u_.complex_val, mpc_precision);
16223 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
16225 mpfr_clear(real);
16226 mpfr_clear(imag);
16229 // Return whether VAL, at a precision of BITS, is a negative zero.
16230 // BITS may be zero in which case it is ignored.
16232 bool
16233 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
16235 if (!mpfr_signbit(val))
16236 return false;
16237 if (mpfr_zero_p(val))
16238 return true;
16239 mp_exp_t min_exp;
16240 switch (bits)
16242 case 0:
16243 return false;
16244 case 32:
16245 // In a denormalized float32 the exponent is -126, and there are
16246 // 24 bits of which at least the last must be 1, so the smallest
16247 // representable non-zero exponent is -126 - (24 - 1) == -149.
16248 min_exp = -149;
16249 break;
16250 case 64:
16251 // Minimum exponent is -1022, there are 53 bits.
16252 min_exp = -1074;
16253 break;
16254 default:
16255 go_unreachable();
16257 return mpfr_get_exp(val) < min_exp;
16260 // Get an int value.
16262 void
16263 Numeric_constant::get_int(mpz_t* val) const
16265 go_assert(this->is_int());
16266 mpz_init_set(*val, this->u_.int_val);
16269 // Get a rune value.
16271 void
16272 Numeric_constant::get_rune(mpz_t* val) const
16274 go_assert(this->is_rune());
16275 mpz_init_set(*val, this->u_.int_val);
16278 // Get a floating point value.
16280 void
16281 Numeric_constant::get_float(mpfr_t* val) const
16283 go_assert(this->is_float());
16284 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16287 // Get a complex value.
16289 void
16290 Numeric_constant::get_complex(mpc_t* val) const
16292 go_assert(this->is_complex());
16293 mpc_init2(*val, mpc_precision);
16294 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16297 // Express value as unsigned long if possible.
16299 Numeric_constant::To_unsigned_long
16300 Numeric_constant::to_unsigned_long(unsigned long* val) const
16302 switch (this->classification_)
16304 case NC_INT:
16305 case NC_RUNE:
16306 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16307 case NC_FLOAT:
16308 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16309 case NC_COMPLEX:
16310 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16311 return NC_UL_NOTINT;
16312 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16313 val);
16314 default:
16315 go_unreachable();
16319 // Express integer value as unsigned long if possible.
16321 Numeric_constant::To_unsigned_long
16322 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16323 unsigned long *val) const
16325 if (mpz_sgn(ival) < 0)
16326 return NC_UL_NEGATIVE;
16327 unsigned long ui = mpz_get_ui(ival);
16328 if (mpz_cmp_ui(ival, ui) != 0)
16329 return NC_UL_BIG;
16330 *val = ui;
16331 return NC_UL_VALID;
16334 // Express floating point value as unsigned long if possible.
16336 Numeric_constant::To_unsigned_long
16337 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16338 unsigned long *val) const
16340 if (!mpfr_integer_p(fval))
16341 return NC_UL_NOTINT;
16342 mpz_t ival;
16343 mpz_init(ival);
16344 mpfr_get_z(ival, fval, GMP_RNDN);
16345 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16346 mpz_clear(ival);
16347 return ret;
16350 // Express value as memory size if possible.
16352 bool
16353 Numeric_constant::to_memory_size(int64_t* val) const
16355 switch (this->classification_)
16357 case NC_INT:
16358 case NC_RUNE:
16359 return this->mpz_to_memory_size(this->u_.int_val, val);
16360 case NC_FLOAT:
16361 return this->mpfr_to_memory_size(this->u_.float_val, val);
16362 case NC_COMPLEX:
16363 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16364 return false;
16365 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16366 default:
16367 go_unreachable();
16371 // Express integer as memory size if possible.
16373 bool
16374 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16376 if (mpz_sgn(ival) < 0)
16377 return false;
16378 if (mpz_fits_slong_p(ival))
16380 *val = static_cast<int64_t>(mpz_get_si(ival));
16381 return true;
16384 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16385 // positive value.
16386 if (mpz_sizeinbase(ival, 2) >= 64)
16387 return false;
16389 mpz_t q, r;
16390 mpz_init(q);
16391 mpz_init(r);
16392 mpz_tdiv_q_2exp(q, ival, 32);
16393 mpz_tdiv_r_2exp(r, ival, 32);
16394 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16395 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16396 + static_cast<int64_t>(mpz_get_ui(r)));
16397 mpz_clear(r);
16398 mpz_clear(q);
16399 return true;
16402 // Express floating point value as memory size if possible.
16404 bool
16405 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16407 if (!mpfr_integer_p(fval))
16408 return false;
16409 mpz_t ival;
16410 mpz_init(ival);
16411 mpfr_get_z(ival, fval, GMP_RNDN);
16412 bool ret = this->mpz_to_memory_size(ival, val);
16413 mpz_clear(ival);
16414 return ret;
16417 // Convert value to integer if possible.
16419 bool
16420 Numeric_constant::to_int(mpz_t* val) const
16422 switch (this->classification_)
16424 case NC_INT:
16425 case NC_RUNE:
16426 mpz_init_set(*val, this->u_.int_val);
16427 return true;
16428 case NC_FLOAT:
16429 if (!mpfr_integer_p(this->u_.float_val))
16430 return false;
16431 mpz_init(*val);
16432 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16433 return true;
16434 case NC_COMPLEX:
16435 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16436 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16437 return false;
16438 mpz_init(*val);
16439 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16440 return true;
16441 default:
16442 go_unreachable();
16446 // Convert value to floating point if possible.
16448 bool
16449 Numeric_constant::to_float(mpfr_t* val) const
16451 switch (this->classification_)
16453 case NC_INT:
16454 case NC_RUNE:
16455 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16456 return true;
16457 case NC_FLOAT:
16458 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16459 return true;
16460 case NC_COMPLEX:
16461 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16462 return false;
16463 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16464 return true;
16465 default:
16466 go_unreachable();
16470 // Convert value to complex.
16472 bool
16473 Numeric_constant::to_complex(mpc_t* val) const
16475 mpc_init2(*val, mpc_precision);
16476 switch (this->classification_)
16478 case NC_INT:
16479 case NC_RUNE:
16480 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16481 return true;
16482 case NC_FLOAT:
16483 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16484 return true;
16485 case NC_COMPLEX:
16486 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16487 return true;
16488 default:
16489 go_unreachable();
16493 // Get the type.
16495 Type*
16496 Numeric_constant::type() const
16498 if (this->type_ != NULL)
16499 return this->type_;
16500 switch (this->classification_)
16502 case NC_INT:
16503 return Type::make_abstract_integer_type();
16504 case NC_RUNE:
16505 return Type::make_abstract_character_type();
16506 case NC_FLOAT:
16507 return Type::make_abstract_float_type();
16508 case NC_COMPLEX:
16509 return Type::make_abstract_complex_type();
16510 default:
16511 go_unreachable();
16515 // If the constant can be expressed in TYPE, then set the type of the
16516 // constant to TYPE and return true. Otherwise return false, and, if
16517 // ISSUE_ERROR is true, report an appropriate error message.
16519 bool
16520 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16522 bool ret;
16523 if (type == NULL || type->is_error())
16524 ret = true;
16525 else if (type->integer_type() != NULL)
16526 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16527 else if (type->float_type() != NULL)
16528 ret = this->check_float_type(type->float_type(), issue_error, loc);
16529 else if (type->complex_type() != NULL)
16530 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16531 else
16533 ret = false;
16534 if (issue_error)
16535 go_assert(saw_errors());
16537 if (ret)
16538 this->type_ = type;
16539 return ret;
16542 // Check whether the constant can be expressed in an integer type.
16544 bool
16545 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16546 Location location)
16548 mpz_t val;
16549 switch (this->classification_)
16551 case NC_INT:
16552 case NC_RUNE:
16553 mpz_init_set(val, this->u_.int_val);
16554 break;
16556 case NC_FLOAT:
16557 if (!mpfr_integer_p(this->u_.float_val))
16559 if (issue_error)
16561 go_error_at(location,
16562 "floating point constant truncated to integer");
16563 this->set_invalid();
16565 return false;
16567 mpz_init(val);
16568 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16569 break;
16571 case NC_COMPLEX:
16572 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16573 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16575 if (issue_error)
16577 go_error_at(location, "complex constant truncated to integer");
16578 this->set_invalid();
16580 return false;
16582 mpz_init(val);
16583 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16584 break;
16586 default:
16587 go_unreachable();
16590 bool ret;
16591 if (type->is_abstract())
16592 ret = true;
16593 else
16595 int bits = mpz_sizeinbase(val, 2);
16596 if (type->is_unsigned())
16598 // For an unsigned type we can only accept a nonnegative
16599 // number, and we must be able to represents at least BITS.
16600 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16602 else
16604 // For a signed type we need an extra bit to indicate the
16605 // sign. We have to handle the most negative integer
16606 // specially.
16607 ret = (bits + 1 <= type->bits()
16608 || (bits <= type->bits()
16609 && mpz_sgn(val) < 0
16610 && (mpz_scan1(val, 0)
16611 == static_cast<unsigned long>(type->bits() - 1))
16612 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16616 if (!ret && issue_error)
16618 go_error_at(location, "integer constant overflow");
16619 this->set_invalid();
16622 return ret;
16625 // Check whether the constant can be expressed in a floating point
16626 // type.
16628 bool
16629 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16630 Location location)
16632 mpfr_t val;
16633 switch (this->classification_)
16635 case NC_INT:
16636 case NC_RUNE:
16637 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16638 break;
16640 case NC_FLOAT:
16641 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16642 break;
16644 case NC_COMPLEX:
16645 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16647 if (issue_error)
16649 this->set_invalid();
16650 go_error_at(location, "complex constant truncated to float");
16652 return false;
16654 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16655 break;
16657 default:
16658 go_unreachable();
16661 bool ret;
16662 if (type->is_abstract())
16663 ret = true;
16664 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16666 // A NaN or Infinity always fits in the range of the type.
16667 ret = true;
16669 else
16671 mp_exp_t exp = mpfr_get_exp(val);
16672 mp_exp_t max_exp;
16673 switch (type->bits())
16675 case 32:
16676 max_exp = 128;
16677 break;
16678 case 64:
16679 max_exp = 1024;
16680 break;
16681 default:
16682 go_unreachable();
16685 ret = exp <= max_exp;
16687 if (ret)
16689 // Round the constant to the desired type.
16690 mpfr_t t;
16691 mpfr_init(t);
16692 switch (type->bits())
16694 case 32:
16695 mpfr_set_prec(t, 24);
16696 break;
16697 case 64:
16698 mpfr_set_prec(t, 53);
16699 break;
16700 default:
16701 go_unreachable();
16703 mpfr_set(t, val, GMP_RNDN);
16704 mpfr_set(val, t, GMP_RNDN);
16705 mpfr_clear(t);
16707 this->set_float(type, val);
16711 mpfr_clear(val);
16713 if (!ret && issue_error)
16715 go_error_at(location, "floating point constant overflow");
16716 this->set_invalid();
16719 return ret;
16722 // Check whether the constant can be expressed in a complex type.
16724 bool
16725 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16726 Location location)
16728 if (type->is_abstract())
16729 return true;
16731 mp_exp_t max_exp;
16732 switch (type->bits())
16734 case 64:
16735 max_exp = 128;
16736 break;
16737 case 128:
16738 max_exp = 1024;
16739 break;
16740 default:
16741 go_unreachable();
16744 mpc_t val;
16745 mpc_init2(val, mpc_precision);
16746 switch (this->classification_)
16748 case NC_INT:
16749 case NC_RUNE:
16750 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16751 break;
16753 case NC_FLOAT:
16754 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16755 break;
16757 case NC_COMPLEX:
16758 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16759 break;
16761 default:
16762 go_unreachable();
16765 bool ret = true;
16766 if (!mpfr_nan_p(mpc_realref(val))
16767 && !mpfr_inf_p(mpc_realref(val))
16768 && !mpfr_zero_p(mpc_realref(val))
16769 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16771 if (issue_error)
16773 go_error_at(location, "complex real part overflow");
16774 this->set_invalid();
16776 ret = false;
16779 if (!mpfr_nan_p(mpc_imagref(val))
16780 && !mpfr_inf_p(mpc_imagref(val))
16781 && !mpfr_zero_p(mpc_imagref(val))
16782 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16784 if (issue_error)
16786 go_error_at(location, "complex imaginary part overflow");
16787 this->set_invalid();
16789 ret = false;
16792 if (ret)
16794 // Round the constant to the desired type.
16795 mpc_t t;
16796 switch (type->bits())
16798 case 64:
16799 mpc_init2(t, 24);
16800 break;
16801 case 128:
16802 mpc_init2(t, 53);
16803 break;
16804 default:
16805 go_unreachable();
16807 mpc_set(t, val, MPC_RNDNN);
16808 mpc_set(val, t, MPC_RNDNN);
16809 mpc_clear(t);
16811 this->set_complex(type, val);
16814 mpc_clear(val);
16816 return ret;
16819 // Return an Expression for this value.
16821 Expression*
16822 Numeric_constant::expression(Location loc) const
16824 switch (this->classification_)
16826 case NC_INT:
16827 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16828 case NC_RUNE:
16829 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16830 case NC_FLOAT:
16831 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16832 case NC_COMPLEX:
16833 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16834 case NC_INVALID:
16835 go_assert(saw_errors());
16836 return Expression::make_error(loc);
16837 default:
16838 go_unreachable();