compiler: use temporary variable for stack allocation
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blobd4a207174db62a441ac62a43e754e8ae222c12e2
1 // expressions.cc -- Go frontend expression handling.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <algorithm>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
25 // Class Expression.
27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
33 Expression::~Expression()
37 // Traverse the expressions.
39 int
40 Expression::traverse(Expression** pexpr, Traverse* traverse)
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
51 return expr->do_traverse(traverse);
54 // Traverse subexpressions of this expression.
56 int
57 Expression::traverse_subexpressions(Traverse* traverse)
59 return this->do_traverse(traverse);
62 // Default implementation for do_traverse for child classes.
64 int
65 Expression::do_traverse(Traverse*)
67 return TRAVERSE_CONTINUE;
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded. By default, we give an error.
72 // Expressions with side effects override.
74 bool
75 Expression::do_discarding_value()
77 this->unused_value_error();
78 return false;
81 // This virtual function is called to export expressions. This will
82 // only be used by expressions which may be constant.
84 void
85 Expression::do_export(Export*) const
87 go_unreachable();
90 // Give an error saying that the value of the expression is not used.
92 void
93 Expression::unused_value_error()
95 this->report_error(_("value computed is not used"));
98 // Note that this expression is an error. This is called by children
99 // when they discover an error.
101 void
102 Expression::set_is_error()
104 this->classification_ = EXPRESSION_ERROR;
107 // For children to call to report an error conveniently.
109 void
110 Expression::report_error(const char* msg)
112 go_error_at(this->location_, "%s", msg);
113 this->set_is_error();
116 // Set types of variables and constants. This is implemented by the
117 // child class.
119 void
120 Expression::determine_type(const Type_context* context)
122 this->do_determine_type(context);
125 // Set types when there is no context.
127 void
128 Expression::determine_type_no_context()
130 Type_context context;
131 this->do_determine_type(&context);
134 // Return an expression handling any conversions which must be done during
135 // assignment.
137 Expression*
138 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
139 Expression* rhs, Location location)
141 Type* rhs_type = rhs->type();
142 if (lhs_type->is_error()
143 || rhs_type->is_error()
144 || rhs->is_error_expression())
145 return Expression::make_error(location);
147 bool are_identical = Type::are_identical(lhs_type, rhs_type, false, NULL);
148 if (!are_identical && lhs_type->interface_type() != NULL)
150 if (rhs_type->interface_type() == NULL)
151 return Expression::convert_type_to_interface(lhs_type, rhs, location);
152 else
153 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154 location);
156 else if (!are_identical && rhs_type->interface_type() != NULL)
157 return Expression::convert_interface_to_type(lhs_type, rhs, location);
158 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
160 // Assigning nil to a slice.
161 Expression* nil = Expression::make_nil(location);
162 Expression* zero = Expression::make_integer_ul(0, NULL, location);
163 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
165 else if (rhs_type->is_nil_type())
166 return Expression::make_nil(location);
167 else if (are_identical)
169 if (lhs_type->forwarded() != rhs_type->forwarded())
171 // Different but identical types require an explicit
172 // conversion. This happens with type aliases.
173 return Expression::make_cast(lhs_type, rhs, location);
176 // No conversion is needed.
177 return rhs;
179 else if (lhs_type->points_to() != NULL)
180 return Expression::make_unsafe_cast(lhs_type, rhs, location);
181 else if (lhs_type->is_numeric_type())
182 return Expression::make_cast(lhs_type, rhs, location);
183 else if ((lhs_type->struct_type() != NULL
184 && rhs_type->struct_type() != NULL)
185 || (lhs_type->array_type() != NULL
186 && rhs_type->array_type() != NULL))
188 // This conversion must be permitted by Go, or we wouldn't have
189 // gotten here.
190 return Expression::make_unsafe_cast(lhs_type, rhs, location);
192 else
193 return rhs;
196 // Return an expression for a conversion from a non-interface type to an
197 // interface type.
199 Expression*
200 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
201 Location location)
203 Interface_type* lhs_interface_type = lhs_type->interface_type();
204 bool lhs_is_empty = lhs_interface_type->is_empty();
206 // Since RHS_TYPE is a static type, we can create the interface
207 // method table at compile time.
209 // When setting an interface to nil, we just set both fields to
210 // NULL.
211 Type* rhs_type = rhs->type();
212 if (rhs_type->is_nil_type())
214 Expression* nil = Expression::make_nil(location);
215 return Expression::make_interface_value(lhs_type, nil, nil, location);
218 // This should have been checked already.
219 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
221 go_assert(saw_errors());
222 return Expression::make_error(location);
225 // An interface is a tuple. If LHS_TYPE is an empty interface type,
226 // then the first field is the type descriptor for RHS_TYPE.
227 // Otherwise it is the interface method table for RHS_TYPE.
228 Expression* first_field;
229 if (lhs_is_empty)
230 first_field = Expression::make_type_descriptor(rhs_type, location);
231 else
233 // Build the interface method table for this interface and this
234 // object type: a list of function pointers for each interface
235 // method.
236 Named_type* rhs_named_type = rhs_type->named_type();
237 Struct_type* rhs_struct_type = rhs_type->struct_type();
238 bool is_pointer = false;
239 if (rhs_named_type == NULL && rhs_struct_type == NULL)
241 rhs_named_type = rhs_type->deref()->named_type();
242 rhs_struct_type = rhs_type->deref()->struct_type();
243 is_pointer = true;
245 if (rhs_named_type != NULL)
246 first_field =
247 rhs_named_type->interface_method_table(lhs_interface_type,
248 is_pointer);
249 else if (rhs_struct_type != NULL)
250 first_field =
251 rhs_struct_type->interface_method_table(lhs_interface_type,
252 is_pointer);
253 else
254 first_field = Expression::make_nil(location);
257 Expression* obj;
258 if (rhs_type->points_to() != NULL)
260 // We are assigning a pointer to the interface; the interface
261 // holds the pointer itself.
262 obj = rhs;
264 else
266 // We are assigning a non-pointer value to the interface; the
267 // interface gets a copy of the value in the heap if it escapes.
268 // TODO(cmang): Associate escape state state of RHS with newly
269 // created OBJ.
270 obj = Expression::make_heap_expression(rhs, location);
273 return Expression::make_interface_value(lhs_type, first_field, obj, location);
276 // Return an expression for the type descriptor of RHS.
278 Expression*
279 Expression::get_interface_type_descriptor(Expression* rhs)
281 go_assert(rhs->type()->interface_type() != NULL);
282 Location location = rhs->location();
284 // The type descriptor is the first field of an empty interface.
285 if (rhs->type()->interface_type()->is_empty())
286 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
287 location);
289 Expression* mtable =
290 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
292 Expression* descriptor =
293 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
294 descriptor = Expression::make_field_reference(descriptor, 0, location);
295 Expression* nil = Expression::make_nil(location);
297 Expression* eq =
298 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
299 return Expression::make_conditional(eq, nil, descriptor, location);
302 // Return an expression for the conversion of an interface type to an
303 // interface type.
305 Expression*
306 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
307 bool for_type_guard,
308 Location location)
310 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
311 return rhs;
313 Interface_type* lhs_interface_type = lhs_type->interface_type();
314 bool lhs_is_empty = lhs_interface_type->is_empty();
316 // In the general case this requires runtime examination of the type
317 // method table to match it up with the interface methods.
319 // FIXME: If all of the methods in the right hand side interface
320 // also appear in the left hand side interface, then we don't need
321 // to do a runtime check, although we still need to build a new
322 // method table.
324 // We are going to evaluate RHS multiple times.
325 go_assert(rhs->is_variable());
327 // Get the type descriptor for the right hand side. This will be
328 // NULL for a nil interface.
329 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
330 Expression* lhs_type_expr =
331 Expression::make_type_descriptor(lhs_type, location);
333 Expression* first_field;
334 if (for_type_guard)
336 // A type assertion fails when converting a nil interface.
337 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
338 lhs_type_expr, rhs_type_expr);
340 else if (lhs_is_empty)
342 // A conversion to an empty interface always succeeds, and the
343 // first field is just the type descriptor of the object.
344 first_field = rhs_type_expr;
346 else
348 // A conversion to a non-empty interface may fail, but unlike a
349 // type assertion converting nil will always succeed.
350 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
351 lhs_type_expr, rhs_type_expr);
354 // The second field is simply the object pointer.
355 Expression* obj =
356 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
357 return Expression::make_interface_value(lhs_type, first_field, obj, location);
360 // Return an expression for the conversion of an interface type to a
361 // non-interface type.
363 Expression*
364 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
365 Location location)
367 // We are going to evaluate RHS multiple times.
368 go_assert(rhs->is_variable());
370 // Call a function to check that the type is valid. The function
371 // will panic with an appropriate runtime type error if the type is
372 // not valid.
373 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
374 location);
375 Expression* rhs_descriptor =
376 Expression::get_interface_type_descriptor(rhs);
378 Type* rhs_type = rhs->type();
379 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
380 location);
382 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
383 location, 3, lhs_type_expr,
384 rhs_descriptor, rhs_inter_expr);
386 // If the call succeeds, pull out the value.
387 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
388 location);
390 // If the value is a pointer, then it is the value we want.
391 // Otherwise it points to the value.
392 if (lhs_type->points_to() == NULL)
394 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
395 location);
396 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
397 location);
399 return Expression::make_compound(check_iface, obj, location);
402 // Convert an expression to its backend representation. This is implemented by
403 // the child class. Not that it is not in general safe to call this multiple
404 // times for a single expression, but that we don't catch such errors.
406 Bexpression*
407 Expression::get_backend(Translate_context* context)
409 // The child may have marked this expression as having an error.
410 if (this->classification_ == EXPRESSION_ERROR)
411 return context->backend()->error_expression();
413 return this->do_get_backend(context);
416 // Return a backend expression for VAL.
417 Bexpression*
418 Expression::backend_numeric_constant_expression(Translate_context* context,
419 Numeric_constant* val)
421 Gogo* gogo = context->gogo();
422 Type* type = val->type();
423 if (type == NULL)
424 return gogo->backend()->error_expression();
426 Btype* btype = type->get_backend(gogo);
427 Bexpression* ret;
428 if (type->integer_type() != NULL)
430 mpz_t ival;
431 if (!val->to_int(&ival))
433 go_assert(saw_errors());
434 return gogo->backend()->error_expression();
436 ret = gogo->backend()->integer_constant_expression(btype, ival);
437 mpz_clear(ival);
439 else if (type->float_type() != NULL)
441 mpfr_t fval;
442 if (!val->to_float(&fval))
444 go_assert(saw_errors());
445 return gogo->backend()->error_expression();
447 ret = gogo->backend()->float_constant_expression(btype, fval);
448 mpfr_clear(fval);
450 else if (type->complex_type() != NULL)
452 mpc_t cval;
453 if (!val->to_complex(&cval))
455 go_assert(saw_errors());
456 return gogo->backend()->error_expression();
458 ret = gogo->backend()->complex_constant_expression(btype, cval);
459 mpc_clear(cval);
461 else
462 go_unreachable();
464 return ret;
467 // Return an expression which evaluates to true if VAL, of arbitrary integer
468 // type, is negative or is more than the maximum value of the Go type "int".
470 Expression*
471 Expression::check_bounds(Expression* val, Location loc)
473 Type* val_type = val->type();
474 Type* bound_type = Type::lookup_integer_type("int");
476 int val_type_size;
477 bool val_is_unsigned = false;
478 if (val_type->integer_type() != NULL)
480 val_type_size = val_type->integer_type()->bits();
481 val_is_unsigned = val_type->integer_type()->is_unsigned();
483 else
485 if (!val_type->is_numeric_type()
486 || !Type::are_convertible(bound_type, val_type, NULL))
488 go_assert(saw_errors());
489 return Expression::make_boolean(true, loc);
492 if (val_type->complex_type() != NULL)
493 val_type_size = val_type->complex_type()->bits();
494 else
495 val_type_size = val_type->float_type()->bits();
498 Expression* negative_index = Expression::make_boolean(false, loc);
499 Expression* index_overflows = Expression::make_boolean(false, loc);
500 if (!val_is_unsigned)
502 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
503 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
506 int bound_type_size = bound_type->integer_type()->bits();
507 if (val_type_size > bound_type_size
508 || (val_type_size == bound_type_size
509 && val_is_unsigned))
511 mpz_t one;
512 mpz_init_set_ui(one, 1UL);
514 // maxval = 2^(bound_type_size - 1) - 1
515 mpz_t maxval;
516 mpz_init(maxval);
517 mpz_mul_2exp(maxval, one, bound_type_size - 1);
518 mpz_sub_ui(maxval, maxval, 1);
519 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
520 mpz_clear(one);
521 mpz_clear(maxval);
523 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
526 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
527 loc);
530 void
531 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
533 this->do_dump_expression(ast_dump_context);
536 // Error expressions. This are used to avoid cascading errors.
538 class Error_expression : public Expression
540 public:
541 Error_expression(Location location)
542 : Expression(EXPRESSION_ERROR, location)
545 protected:
546 bool
547 do_is_constant() const
548 { return true; }
550 bool
551 do_numeric_constant_value(Numeric_constant* nc) const
553 nc->set_unsigned_long(NULL, 0);
554 return true;
557 bool
558 do_discarding_value()
559 { return true; }
561 Type*
562 do_type()
563 { return Type::make_error_type(); }
565 void
566 do_determine_type(const Type_context*)
569 Expression*
570 do_copy()
571 { return this; }
573 bool
574 do_is_addressable() const
575 { return true; }
577 Bexpression*
578 do_get_backend(Translate_context* context)
579 { return context->backend()->error_expression(); }
581 void
582 do_dump_expression(Ast_dump_context*) const;
585 // Dump the ast representation for an error expression to a dump context.
587 void
588 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
590 ast_dump_context->ostream() << "_Error_" ;
593 Expression*
594 Expression::make_error(Location location)
596 return new Error_expression(location);
599 // An expression which is really a type. This is used during parsing.
600 // It is an error if these survive after lowering.
602 class
603 Type_expression : public Expression
605 public:
606 Type_expression(Type* type, Location location)
607 : Expression(EXPRESSION_TYPE, location),
608 type_(type)
611 protected:
613 do_traverse(Traverse* traverse)
614 { return Type::traverse(this->type_, traverse); }
616 Type*
617 do_type()
618 { return this->type_; }
620 void
621 do_determine_type(const Type_context*)
624 void
625 do_check_types(Gogo*)
626 { this->report_error(_("invalid use of type")); }
628 Expression*
629 do_copy()
630 { return this; }
632 Bexpression*
633 do_get_backend(Translate_context*)
634 { go_unreachable(); }
636 void do_dump_expression(Ast_dump_context*) const;
638 private:
639 // The type which we are representing as an expression.
640 Type* type_;
643 void
644 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
646 ast_dump_context->dump_type(this->type_);
649 Expression*
650 Expression::make_type(Type* type, Location location)
652 return new Type_expression(type, location);
655 // Class Parser_expression.
657 Type*
658 Parser_expression::do_type()
660 // We should never really ask for the type of a Parser_expression.
661 // However, it can happen, at least when we have an invalid const
662 // whose initializer refers to the const itself. In that case we
663 // may ask for the type when lowering the const itself.
664 go_assert(saw_errors());
665 return Type::make_error_type();
668 // Class Var_expression.
670 // Lower a variable expression. Here we just make sure that the
671 // initialization expression of the variable has been lowered. This
672 // ensures that we will be able to determine the type of the variable
673 // if necessary.
675 Expression*
676 Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 Statement_inserter* inserter, int)
679 if (this->variable_->is_variable())
681 Variable* var = this->variable_->var_value();
682 // This is either a local variable or a global variable. A
683 // reference to a variable which is local to an enclosing
684 // function will be a reference to a field in a closure.
685 if (var->is_global())
687 function = NULL;
688 inserter = NULL;
690 var->lower_init_expression(gogo, function, inserter);
692 return this;
695 // Return the type of a reference to a variable.
697 Type*
698 Var_expression::do_type()
700 if (this->variable_->is_variable())
701 return this->variable_->var_value()->type();
702 else if (this->variable_->is_result_variable())
703 return this->variable_->result_var_value()->type();
704 else
705 go_unreachable();
708 // Determine the type of a reference to a variable.
710 void
711 Var_expression::do_determine_type(const Type_context*)
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->determine_type();
717 // Something takes the address of this variable. This means that we
718 // may want to move the variable onto the heap.
720 void
721 Var_expression::do_address_taken(bool escapes)
723 if (!escapes)
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_non_escaping_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_non_escaping_address_taken();
729 else
730 go_unreachable();
732 else
734 if (this->variable_->is_variable())
735 this->variable_->var_value()->set_address_taken();
736 else if (this->variable_->is_result_variable())
737 this->variable_->result_var_value()->set_address_taken();
738 else
739 go_unreachable();
742 if (this->variable_->is_variable()
743 && this->variable_->var_value()->is_in_heap())
745 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
746 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
750 // Get the backend representation for a reference to a variable.
752 Bexpression*
753 Var_expression::do_get_backend(Translate_context* context)
755 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
756 context->function());
757 bool is_in_heap;
758 Location loc = this->location();
759 Btype* btype;
760 Gogo* gogo = context->gogo();
761 if (this->variable_->is_variable())
763 is_in_heap = this->variable_->var_value()->is_in_heap();
764 btype = this->variable_->var_value()->type()->get_backend(gogo);
766 else if (this->variable_->is_result_variable())
768 is_in_heap = this->variable_->result_var_value()->is_in_heap();
769 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
771 else
772 go_unreachable();
774 Bexpression* ret =
775 context->backend()->var_expression(bvar, loc);
776 if (is_in_heap)
777 ret = context->backend()->indirect_expression(btype, ret, true, loc);
778 return ret;
781 // Ast dump for variable expression.
783 void
784 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
786 ast_dump_context->ostream() << this->variable_->name() ;
789 // Make a reference to a variable in an expression.
791 Expression*
792 Expression::make_var_reference(Named_object* var, Location location)
794 if (var->is_sink())
795 return Expression::make_sink(location);
797 // FIXME: Creating a new object for each reference to a variable is
798 // wasteful.
799 return new Var_expression(var, location);
802 // Class Enclosed_var_expression.
805 Enclosed_var_expression::do_traverse(Traverse*)
807 return TRAVERSE_CONTINUE;
810 // Lower the reference to the enclosed variable.
812 Expression*
813 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
814 Statement_inserter* inserter, int)
816 gogo->lower_expression(function, inserter, &this->reference_);
817 return this;
820 // Flatten the reference to the enclosed variable.
822 Expression*
823 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
824 Statement_inserter* inserter)
826 gogo->flatten_expression(function, inserter, &this->reference_);
827 return this;
830 void
831 Enclosed_var_expression::do_address_taken(bool escapes)
833 if (!escapes)
835 if (this->variable_->is_variable())
836 this->variable_->var_value()->set_non_escaping_address_taken();
837 else if (this->variable_->is_result_variable())
838 this->variable_->result_var_value()->set_non_escaping_address_taken();
839 else
840 go_unreachable();
842 else
844 if (this->variable_->is_variable())
845 this->variable_->var_value()->set_address_taken();
846 else if (this->variable_->is_result_variable())
847 this->variable_->result_var_value()->set_address_taken();
848 else
849 go_unreachable();
852 if (this->variable_->is_variable()
853 && this->variable_->var_value()->is_in_heap())
854 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
857 // Ast dump for enclosed variable expression.
859 void
860 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
862 adc->ostream() << this->variable_->name();
865 // Make a reference to a variable within an enclosing function.
867 Expression*
868 Expression::make_enclosing_var_reference(Expression* reference,
869 Named_object* var, Location location)
871 return new Enclosed_var_expression(reference, var, location);
874 // Class Temporary_reference_expression.
876 // The type.
878 Type*
879 Temporary_reference_expression::do_type()
881 return this->statement_->type();
884 // Called if something takes the address of this temporary variable.
885 // We never have to move temporary variables to the heap, but we do
886 // need to know that they must live in the stack rather than in a
887 // register.
889 void
890 Temporary_reference_expression::do_address_taken(bool)
892 this->statement_->set_is_address_taken();
895 // Get a backend expression referring to the variable.
897 Bexpression*
898 Temporary_reference_expression::do_get_backend(Translate_context* context)
900 Gogo* gogo = context->gogo();
901 Bvariable* bvar = this->statement_->get_backend_variable(context);
902 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
904 // The backend can't always represent the same set of recursive types
905 // that the Go frontend can. In some cases this means that a
906 // temporary variable won't have the right backend type. Correct
907 // that here by adding a type cast. We need to use base() to push
908 // the circularity down one level.
909 Type* stype = this->statement_->type();
910 if (!this->is_lvalue_
911 && stype->points_to() != NULL
912 && stype->points_to()->is_void_type())
914 Btype* btype = this->type()->base()->get_backend(gogo);
915 ret = gogo->backend()->convert_expression(btype, ret, this->location());
917 return ret;
920 // Ast dump for temporary reference.
922 void
923 Temporary_reference_expression::do_dump_expression(
924 Ast_dump_context* ast_dump_context) const
926 ast_dump_context->dump_temp_variable_name(this->statement_);
929 // Make a reference to a temporary variable.
931 Temporary_reference_expression*
932 Expression::make_temporary_reference(Temporary_statement* statement,
933 Location location)
935 return new Temporary_reference_expression(statement, location);
938 // Class Set_and_use_temporary_expression.
940 // Return the type.
942 Type*
943 Set_and_use_temporary_expression::do_type()
945 return this->statement_->type();
948 // Determine the type of the expression.
950 void
951 Set_and_use_temporary_expression::do_determine_type(
952 const Type_context* context)
954 this->expr_->determine_type(context);
957 // Take the address.
959 void
960 Set_and_use_temporary_expression::do_address_taken(bool)
962 this->statement_->set_is_address_taken();
965 // Return the backend representation.
967 Bexpression*
968 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
970 Location loc = this->location();
971 Gogo* gogo = context->gogo();
972 Bvariable* bvar = this->statement_->get_backend_variable(context);
973 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
975 Named_object* fn = context->function();
976 go_assert(fn != NULL);
977 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
978 Bexpression* bexpr = this->expr_->get_backend(context);
979 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
980 bexpr, loc);
981 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
982 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
983 return ret;
986 // Dump.
988 void
989 Set_and_use_temporary_expression::do_dump_expression(
990 Ast_dump_context* ast_dump_context) const
992 ast_dump_context->ostream() << '(';
993 ast_dump_context->dump_temp_variable_name(this->statement_);
994 ast_dump_context->ostream() << " = ";
995 this->expr_->dump_expression(ast_dump_context);
996 ast_dump_context->ostream() << ')';
999 // Make a set-and-use temporary.
1001 Set_and_use_temporary_expression*
1002 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1003 Expression* expr, Location location)
1005 return new Set_and_use_temporary_expression(statement, expr, location);
1008 // A sink expression--a use of the blank identifier _.
1010 class Sink_expression : public Expression
1012 public:
1013 Sink_expression(Location location)
1014 : Expression(EXPRESSION_SINK, location),
1015 type_(NULL), bvar_(NULL)
1018 protected:
1019 bool
1020 do_discarding_value()
1021 { return true; }
1023 Type*
1024 do_type();
1026 void
1027 do_determine_type(const Type_context*);
1029 Expression*
1030 do_copy()
1031 { return new Sink_expression(this->location()); }
1033 Bexpression*
1034 do_get_backend(Translate_context*);
1036 void
1037 do_dump_expression(Ast_dump_context*) const;
1039 private:
1040 // The type of this sink variable.
1041 Type* type_;
1042 // The temporary variable we generate.
1043 Bvariable* bvar_;
1046 // Return the type of a sink expression.
1048 Type*
1049 Sink_expression::do_type()
1051 if (this->type_ == NULL)
1052 return Type::make_sink_type();
1053 return this->type_;
1056 // Determine the type of a sink expression.
1058 void
1059 Sink_expression::do_determine_type(const Type_context* context)
1061 if (context->type != NULL)
1062 this->type_ = context->type;
1065 // Return a temporary variable for a sink expression. This will
1066 // presumably be a write-only variable which the middle-end will drop.
1068 Bexpression*
1069 Sink_expression::do_get_backend(Translate_context* context)
1071 Location loc = this->location();
1072 Gogo* gogo = context->gogo();
1073 if (this->bvar_ == NULL)
1075 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1076 Named_object* fn = context->function();
1077 go_assert(fn != NULL);
1078 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1079 Btype* bt = this->type_->get_backend(context->gogo());
1080 Bstatement* decl;
1081 this->bvar_ =
1082 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1083 false, loc, &decl);
1084 Bexpression* var_ref =
1085 gogo->backend()->var_expression(this->bvar_, loc);
1086 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1087 return var_ref;
1089 return gogo->backend()->var_expression(this->bvar_, loc);
1092 // Ast dump for sink expression.
1094 void
1095 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1097 ast_dump_context->ostream() << "_" ;
1100 // Make a sink expression.
1102 Expression*
1103 Expression::make_sink(Location location)
1105 return new Sink_expression(location);
1108 // Class Func_expression.
1110 // FIXME: Can a function expression appear in a constant expression?
1111 // The value is unchanging. Initializing a constant to the address of
1112 // a function seems like it could work, though there might be little
1113 // point to it.
1115 // Traversal.
1118 Func_expression::do_traverse(Traverse* traverse)
1120 return (this->closure_ == NULL
1121 ? TRAVERSE_CONTINUE
1122 : Expression::traverse(&this->closure_, traverse));
1125 // Return the type of a function expression.
1127 Type*
1128 Func_expression::do_type()
1130 if (this->function_->is_function())
1131 return this->function_->func_value()->type();
1132 else if (this->function_->is_function_declaration())
1133 return this->function_->func_declaration_value()->type();
1134 else
1135 go_unreachable();
1138 // Get the backend representation for the code of a function expression.
1140 Bexpression*
1141 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1143 Function_type* fntype;
1144 if (no->is_function())
1145 fntype = no->func_value()->type();
1146 else if (no->is_function_declaration())
1147 fntype = no->func_declaration_value()->type();
1148 else
1149 go_unreachable();
1151 // Builtin functions are handled specially by Call_expression. We
1152 // can't take their address.
1153 if (fntype->is_builtin())
1155 go_error_at(loc,
1156 "invalid use of special builtin function %qs; must be called",
1157 no->message_name().c_str());
1158 return gogo->backend()->error_expression();
1161 Bfunction* fndecl;
1162 if (no->is_function())
1163 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1164 else if (no->is_function_declaration())
1165 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1166 else
1167 go_unreachable();
1169 return gogo->backend()->function_code_expression(fndecl, loc);
1172 // Get the backend representation for a function expression. This is used when
1173 // we take the address of a function rather than simply calling it. A func
1174 // value is represented as a pointer to a block of memory. The first
1175 // word of that memory is a pointer to the function code. The
1176 // remaining parts of that memory are the addresses of variables that
1177 // the function closes over.
1179 Bexpression*
1180 Func_expression::do_get_backend(Translate_context* context)
1182 // If there is no closure, just use the function descriptor.
1183 if (this->closure_ == NULL)
1185 Gogo* gogo = context->gogo();
1186 Named_object* no = this->function_;
1187 Expression* descriptor;
1188 if (no->is_function())
1189 descriptor = no->func_value()->descriptor(gogo, no);
1190 else if (no->is_function_declaration())
1192 if (no->func_declaration_value()->type()->is_builtin())
1194 go_error_at(this->location(),
1195 ("invalid use of special builtin function %qs; "
1196 "must be called"),
1197 no->message_name().c_str());
1198 return gogo->backend()->error_expression();
1200 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1202 else
1203 go_unreachable();
1205 Bexpression* bdesc = descriptor->get_backend(context);
1206 return gogo->backend()->address_expression(bdesc, this->location());
1209 go_assert(this->function_->func_value()->enclosing() != NULL);
1211 // If there is a closure, then the closure is itself the function
1212 // expression. It is a pointer to a struct whose first field points
1213 // to the function code and whose remaining fields are the addresses
1214 // of the closed-over variables.
1215 Bexpression *bexpr = this->closure_->get_backend(context);
1217 // Introduce a backend type conversion, to account for any differences
1218 // between the argument type (function descriptor, struct with a
1219 // single field) and the closure (struct with multiple fields).
1220 Gogo* gogo = context->gogo();
1221 Btype *btype = this->type()->get_backend(gogo);
1222 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1225 // Ast dump for function.
1227 void
1228 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1230 ast_dump_context->ostream() << this->function_->name();
1231 if (this->closure_ != NULL)
1233 ast_dump_context->ostream() << " {closure = ";
1234 this->closure_->dump_expression(ast_dump_context);
1235 ast_dump_context->ostream() << "}";
1239 // Make a reference to a function in an expression.
1241 Expression*
1242 Expression::make_func_reference(Named_object* function, Expression* closure,
1243 Location location)
1245 Func_expression* fe = new Func_expression(function, closure, location);
1247 // Detect references to builtin functions and set the runtime code if
1248 // appropriate.
1249 if (function->is_function_declaration())
1250 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1251 return fe;
1254 // Class Func_descriptor_expression.
1256 // Constructor.
1258 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1259 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1260 fn_(fn), dvar_(NULL)
1262 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1265 // Traversal.
1268 Func_descriptor_expression::do_traverse(Traverse*)
1270 return TRAVERSE_CONTINUE;
1273 // All function descriptors have the same type.
1275 Type* Func_descriptor_expression::descriptor_type;
1277 void
1278 Func_descriptor_expression::make_func_descriptor_type()
1280 if (Func_descriptor_expression::descriptor_type != NULL)
1281 return;
1282 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1283 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1284 Func_descriptor_expression::descriptor_type =
1285 Type::make_builtin_named_type("functionDescriptor", struct_type);
1288 Type*
1289 Func_descriptor_expression::do_type()
1291 Func_descriptor_expression::make_func_descriptor_type();
1292 return Func_descriptor_expression::descriptor_type;
1295 // The backend representation for a function descriptor.
1297 Bexpression*
1298 Func_descriptor_expression::do_get_backend(Translate_context* context)
1300 Named_object* no = this->fn_;
1301 Location loc = no->location();
1302 if (this->dvar_ != NULL)
1303 return context->backend()->var_expression(this->dvar_, loc);
1305 Gogo* gogo = context->gogo();
1306 std::string var_name(gogo->function_descriptor_name(no));
1307 bool is_descriptor = false;
1308 if (no->is_function_declaration()
1309 && !no->func_declaration_value()->asm_name().empty()
1310 && Linemap::is_predeclared_location(no->location()))
1311 is_descriptor = true;
1313 Btype* btype = this->type()->get_backend(gogo);
1315 Bvariable* bvar;
1316 std::string asm_name(go_selectively_encode_id(var_name));
1317 if (no->package() != NULL || is_descriptor)
1318 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1319 btype, loc);
1320 else
1322 Location bloc = Linemap::predeclared_location();
1323 bool is_hidden = ((no->is_function()
1324 && no->func_value()->enclosing() != NULL)
1325 || Gogo::is_thunk(no));
1326 bvar = context->backend()->immutable_struct(var_name, asm_name,
1327 is_hidden, false,
1328 btype, bloc);
1329 Expression_list* vals = new Expression_list();
1330 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1331 Expression* init =
1332 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1333 Translate_context bcontext(gogo, NULL, NULL, NULL);
1334 bcontext.set_is_const();
1335 Bexpression* binit = init->get_backend(&bcontext);
1336 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1337 false, btype, bloc, binit);
1340 this->dvar_ = bvar;
1341 return gogo->backend()->var_expression(bvar, loc);
1344 // Print a function descriptor expression.
1346 void
1347 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1349 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1352 // Make a function descriptor expression.
1354 Func_descriptor_expression*
1355 Expression::make_func_descriptor(Named_object* fn)
1357 return new Func_descriptor_expression(fn);
1360 // Make the function descriptor type, so that it can be converted.
1362 void
1363 Expression::make_func_descriptor_type()
1365 Func_descriptor_expression::make_func_descriptor_type();
1368 // A reference to just the code of a function.
1370 class Func_code_reference_expression : public Expression
1372 public:
1373 Func_code_reference_expression(Named_object* function, Location location)
1374 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1375 function_(function)
1378 protected:
1380 do_traverse(Traverse*)
1381 { return TRAVERSE_CONTINUE; }
1383 bool
1384 do_is_static_initializer() const
1385 { return true; }
1387 Type*
1388 do_type()
1389 { return Type::make_pointer_type(Type::make_void_type()); }
1391 void
1392 do_determine_type(const Type_context*)
1395 Expression*
1396 do_copy()
1398 return Expression::make_func_code_reference(this->function_,
1399 this->location());
1402 Bexpression*
1403 do_get_backend(Translate_context*);
1405 void
1406 do_dump_expression(Ast_dump_context* context) const
1407 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1409 private:
1410 // The function.
1411 Named_object* function_;
1414 // Get the backend representation for a reference to function code.
1416 Bexpression*
1417 Func_code_reference_expression::do_get_backend(Translate_context* context)
1419 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1420 this->location());
1423 // Make a reference to the code of a function.
1425 Expression*
1426 Expression::make_func_code_reference(Named_object* function, Location location)
1428 return new Func_code_reference_expression(function, location);
1431 // Class Unknown_expression.
1433 // Return the name of an unknown expression.
1435 const std::string&
1436 Unknown_expression::name() const
1438 return this->named_object_->name();
1441 // Lower a reference to an unknown name.
1443 Expression*
1444 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1446 Location location = this->location();
1447 Named_object* no = this->named_object_;
1448 Named_object* real;
1449 if (!no->is_unknown())
1450 real = no;
1451 else
1453 real = no->unknown_value()->real_named_object();
1454 if (real == NULL)
1456 if (this->is_composite_literal_key_)
1457 return this;
1458 if (!this->no_error_message_)
1459 go_error_at(location, "reference to undefined name %qs",
1460 this->named_object_->message_name().c_str());
1461 return Expression::make_error(location);
1464 switch (real->classification())
1466 case Named_object::NAMED_OBJECT_CONST:
1467 return Expression::make_const_reference(real, location);
1468 case Named_object::NAMED_OBJECT_TYPE:
1469 return Expression::make_type(real->type_value(), location);
1470 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1471 if (this->is_composite_literal_key_)
1472 return this;
1473 if (!this->no_error_message_)
1474 go_error_at(location, "reference to undefined type %qs",
1475 real->message_name().c_str());
1476 return Expression::make_error(location);
1477 case Named_object::NAMED_OBJECT_VAR:
1478 real->var_value()->set_is_used();
1479 return Expression::make_var_reference(real, location);
1480 case Named_object::NAMED_OBJECT_FUNC:
1481 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1482 return Expression::make_func_reference(real, NULL, location);
1483 case Named_object::NAMED_OBJECT_PACKAGE:
1484 if (this->is_composite_literal_key_)
1485 return this;
1486 if (!this->no_error_message_)
1487 go_error_at(location, "unexpected reference to package");
1488 return Expression::make_error(location);
1489 default:
1490 go_unreachable();
1494 // Dump the ast representation for an unknown expression to a dump context.
1496 void
1497 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1499 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1500 << ")";
1503 // Make a reference to an unknown name.
1505 Unknown_expression*
1506 Expression::make_unknown_reference(Named_object* no, Location location)
1508 return new Unknown_expression(no, location);
1511 // A boolean expression.
1513 class Boolean_expression : public Expression
1515 public:
1516 Boolean_expression(bool val, Location location)
1517 : Expression(EXPRESSION_BOOLEAN, location),
1518 val_(val), type_(NULL)
1521 static Expression*
1522 do_import(Import*);
1524 protected:
1525 bool
1526 do_is_constant() const
1527 { return true; }
1529 bool
1530 do_is_static_initializer() const
1531 { return true; }
1533 Type*
1534 do_type();
1536 void
1537 do_determine_type(const Type_context*);
1539 Expression*
1540 do_copy()
1541 { return this; }
1543 Bexpression*
1544 do_get_backend(Translate_context* context)
1545 { return context->backend()->boolean_constant_expression(this->val_); }
1547 void
1548 do_export(Export* exp) const
1549 { exp->write_c_string(this->val_ ? "true" : "false"); }
1551 void
1552 do_dump_expression(Ast_dump_context* ast_dump_context) const
1553 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1555 private:
1556 // The constant.
1557 bool val_;
1558 // The type as determined by context.
1559 Type* type_;
1562 // Get the type.
1564 Type*
1565 Boolean_expression::do_type()
1567 if (this->type_ == NULL)
1568 this->type_ = Type::make_boolean_type();
1569 return this->type_;
1572 // Set the type from the context.
1574 void
1575 Boolean_expression::do_determine_type(const Type_context* context)
1577 if (this->type_ != NULL && !this->type_->is_abstract())
1579 else if (context->type != NULL && context->type->is_boolean_type())
1580 this->type_ = context->type;
1581 else if (!context->may_be_abstract)
1582 this->type_ = Type::lookup_bool_type();
1585 // Import a boolean constant.
1587 Expression*
1588 Boolean_expression::do_import(Import* imp)
1590 if (imp->peek_char() == 't')
1592 imp->require_c_string("true");
1593 return Expression::make_boolean(true, imp->location());
1595 else
1597 imp->require_c_string("false");
1598 return Expression::make_boolean(false, imp->location());
1602 // Make a boolean expression.
1604 Expression*
1605 Expression::make_boolean(bool val, Location location)
1607 return new Boolean_expression(val, location);
1610 // Class String_expression.
1612 // Get the type.
1614 Type*
1615 String_expression::do_type()
1617 if (this->type_ == NULL)
1618 this->type_ = Type::make_string_type();
1619 return this->type_;
1622 // Set the type from the context.
1624 void
1625 String_expression::do_determine_type(const Type_context* context)
1627 if (this->type_ != NULL && !this->type_->is_abstract())
1629 else if (context->type != NULL && context->type->is_string_type())
1630 this->type_ = context->type;
1631 else if (!context->may_be_abstract)
1632 this->type_ = Type::lookup_string_type();
1635 // Build a string constant.
1637 Bexpression*
1638 String_expression::do_get_backend(Translate_context* context)
1640 Gogo* gogo = context->gogo();
1641 Btype* btype = Type::make_string_type()->get_backend(gogo);
1643 Location loc = this->location();
1644 std::vector<Bexpression*> init(2);
1645 Bexpression* str_cst =
1646 gogo->backend()->string_constant_expression(this->val_);
1647 init[0] = gogo->backend()->address_expression(str_cst, loc);
1649 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1650 mpz_t lenval;
1651 mpz_init_set_ui(lenval, this->val_.length());
1652 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1653 mpz_clear(lenval);
1655 return gogo->backend()->constructor_expression(btype, init, loc);
1658 // Write string literal to string dump.
1660 void
1661 String_expression::export_string(String_dump* exp,
1662 const String_expression* str)
1664 std::string s;
1665 s.reserve(str->val_.length() * 4 + 2);
1666 s += '"';
1667 for (std::string::const_iterator p = str->val_.begin();
1668 p != str->val_.end();
1669 ++p)
1671 if (*p == '\\' || *p == '"')
1673 s += '\\';
1674 s += *p;
1676 else if (*p >= 0x20 && *p < 0x7f)
1677 s += *p;
1678 else if (*p == '\n')
1679 s += "\\n";
1680 else if (*p == '\t')
1681 s += "\\t";
1682 else
1684 s += "\\x";
1685 unsigned char c = *p;
1686 unsigned int dig = c >> 4;
1687 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1688 dig = c & 0xf;
1689 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1692 s += '"';
1693 exp->write_string(s);
1696 // Export a string expression.
1698 void
1699 String_expression::do_export(Export* exp) const
1701 String_expression::export_string(exp, this);
1704 // Import a string expression.
1706 Expression*
1707 String_expression::do_import(Import* imp)
1709 imp->require_c_string("\"");
1710 std::string val;
1711 while (true)
1713 int c = imp->get_char();
1714 if (c == '"' || c == -1)
1715 break;
1716 if (c != '\\')
1717 val += static_cast<char>(c);
1718 else
1720 c = imp->get_char();
1721 if (c == '\\' || c == '"')
1722 val += static_cast<char>(c);
1723 else if (c == 'n')
1724 val += '\n';
1725 else if (c == 't')
1726 val += '\t';
1727 else if (c == 'x')
1729 c = imp->get_char();
1730 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1731 c = imp->get_char();
1732 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1733 char v = (vh << 4) | vl;
1734 val += v;
1736 else
1738 go_error_at(imp->location(), "bad string constant");
1739 return Expression::make_error(imp->location());
1743 return Expression::make_string(val, imp->location());
1746 // Ast dump for string expression.
1748 void
1749 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1751 String_expression::export_string(ast_dump_context, this);
1754 // Make a string expression.
1756 Expression*
1757 Expression::make_string(const std::string& val, Location location)
1759 return new String_expression(val, location);
1762 // An expression that evaluates to some characteristic of a string.
1763 // This is used when indexing, bound-checking, or nil checking a string.
1765 class String_info_expression : public Expression
1767 public:
1768 String_info_expression(Expression* string, String_info string_info,
1769 Location location)
1770 : Expression(EXPRESSION_STRING_INFO, location),
1771 string_(string), string_info_(string_info)
1774 protected:
1775 Type*
1776 do_type();
1778 void
1779 do_determine_type(const Type_context*)
1780 { go_unreachable(); }
1782 Expression*
1783 do_copy()
1785 return new String_info_expression(this->string_->copy(), this->string_info_,
1786 this->location());
1789 Bexpression*
1790 do_get_backend(Translate_context* context);
1792 void
1793 do_dump_expression(Ast_dump_context*) const;
1795 void
1796 do_issue_nil_check()
1797 { this->string_->issue_nil_check(); }
1799 private:
1800 // The string for which we are getting information.
1801 Expression* string_;
1802 // What information we want.
1803 String_info string_info_;
1806 // Return the type of the string info.
1808 Type*
1809 String_info_expression::do_type()
1811 switch (this->string_info_)
1813 case STRING_INFO_DATA:
1815 Type* byte_type = Type::lookup_integer_type("uint8");
1816 return Type::make_pointer_type(byte_type);
1818 case STRING_INFO_LENGTH:
1819 return Type::lookup_integer_type("int");
1820 default:
1821 go_unreachable();
1825 // Return string information in GENERIC.
1827 Bexpression*
1828 String_info_expression::do_get_backend(Translate_context* context)
1830 Gogo* gogo = context->gogo();
1832 Bexpression* bstring = this->string_->get_backend(context);
1833 switch (this->string_info_)
1835 case STRING_INFO_DATA:
1836 case STRING_INFO_LENGTH:
1837 return gogo->backend()->struct_field_expression(bstring,
1838 this->string_info_,
1839 this->location());
1840 break;
1841 default:
1842 go_unreachable();
1846 // Dump ast representation for a type info expression.
1848 void
1849 String_info_expression::do_dump_expression(
1850 Ast_dump_context* ast_dump_context) const
1852 ast_dump_context->ostream() << "stringinfo(";
1853 this->string_->dump_expression(ast_dump_context);
1854 ast_dump_context->ostream() << ",";
1855 ast_dump_context->ostream() <<
1856 (this->string_info_ == STRING_INFO_DATA ? "data"
1857 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1858 : "unknown");
1859 ast_dump_context->ostream() << ")";
1862 // Make a string info expression.
1864 Expression*
1865 Expression::make_string_info(Expression* string, String_info string_info,
1866 Location location)
1868 return new String_info_expression(string, string_info, location);
1871 // Make an integer expression.
1873 class Integer_expression : public Expression
1875 public:
1876 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1877 Location location)
1878 : Expression(EXPRESSION_INTEGER, location),
1879 type_(type), is_character_constant_(is_character_constant)
1880 { mpz_init_set(this->val_, *val); }
1882 static Expression*
1883 do_import(Import*);
1885 // Write VAL to string dump.
1886 static void
1887 export_integer(String_dump* exp, const mpz_t val);
1889 // Write VAL to dump context.
1890 static void
1891 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1893 protected:
1894 bool
1895 do_is_constant() const
1896 { return true; }
1898 bool
1899 do_is_static_initializer() const
1900 { return true; }
1902 bool
1903 do_numeric_constant_value(Numeric_constant* nc) const;
1905 Type*
1906 do_type();
1908 void
1909 do_determine_type(const Type_context* context);
1911 void
1912 do_check_types(Gogo*);
1914 Bexpression*
1915 do_get_backend(Translate_context*);
1917 Expression*
1918 do_copy()
1920 if (this->is_character_constant_)
1921 return Expression::make_character(&this->val_, this->type_,
1922 this->location());
1923 else
1924 return Expression::make_integer_z(&this->val_, this->type_,
1925 this->location());
1928 void
1929 do_export(Export*) const;
1931 void
1932 do_dump_expression(Ast_dump_context*) const;
1934 private:
1935 // The integer value.
1936 mpz_t val_;
1937 // The type so far.
1938 Type* type_;
1939 // Whether this is a character constant.
1940 bool is_character_constant_;
1943 // Return a numeric constant for this expression. We have to mark
1944 // this as a character when appropriate.
1946 bool
1947 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1949 if (this->is_character_constant_)
1950 nc->set_rune(this->type_, this->val_);
1951 else
1952 nc->set_int(this->type_, this->val_);
1953 return true;
1956 // Return the current type. If we haven't set the type yet, we return
1957 // an abstract integer type.
1959 Type*
1960 Integer_expression::do_type()
1962 if (this->type_ == NULL)
1964 if (this->is_character_constant_)
1965 this->type_ = Type::make_abstract_character_type();
1966 else
1967 this->type_ = Type::make_abstract_integer_type();
1969 return this->type_;
1972 // Set the type of the integer value. Here we may switch from an
1973 // abstract type to a real type.
1975 void
1976 Integer_expression::do_determine_type(const Type_context* context)
1978 if (this->type_ != NULL && !this->type_->is_abstract())
1980 else if (context->type != NULL && context->type->is_numeric_type())
1981 this->type_ = context->type;
1982 else if (!context->may_be_abstract)
1984 if (this->is_character_constant_)
1985 this->type_ = Type::lookup_integer_type("int32");
1986 else
1987 this->type_ = Type::lookup_integer_type("int");
1991 // Check the type of an integer constant.
1993 void
1994 Integer_expression::do_check_types(Gogo*)
1996 Type* type = this->type_;
1997 if (type == NULL)
1998 return;
1999 Numeric_constant nc;
2000 if (this->is_character_constant_)
2001 nc.set_rune(NULL, this->val_);
2002 else
2003 nc.set_int(NULL, this->val_);
2004 if (!nc.set_type(type, true, this->location()))
2005 this->set_is_error();
2008 // Get the backend representation for an integer constant.
2010 Bexpression*
2011 Integer_expression::do_get_backend(Translate_context* context)
2013 if (this->is_error_expression()
2014 || (this->type_ != NULL && this->type_->is_error_type()))
2016 go_assert(saw_errors());
2017 return context->gogo()->backend()->error_expression();
2020 Type* resolved_type = NULL;
2021 if (this->type_ != NULL && !this->type_->is_abstract())
2022 resolved_type = this->type_;
2023 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2025 // We are converting to an abstract floating point type.
2026 resolved_type = Type::lookup_float_type("float64");
2028 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2030 // We are converting to an abstract complex type.
2031 resolved_type = Type::lookup_complex_type("complex128");
2033 else
2035 // If we still have an abstract type here, then this is being
2036 // used in a constant expression which didn't get reduced for
2037 // some reason. Use a type which will fit the value. We use <,
2038 // not <=, because we need an extra bit for the sign bit.
2039 int bits = mpz_sizeinbase(this->val_, 2);
2040 Type* int_type = Type::lookup_integer_type("int");
2041 if (bits < int_type->integer_type()->bits())
2042 resolved_type = int_type;
2043 else if (bits < 64)
2044 resolved_type = Type::lookup_integer_type("int64");
2045 else
2047 if (!saw_errors())
2048 go_error_at(this->location(),
2049 "unknown type for large integer constant");
2050 return context->gogo()->backend()->error_expression();
2053 Numeric_constant nc;
2054 nc.set_int(resolved_type, this->val_);
2055 return Expression::backend_numeric_constant_expression(context, &nc);
2058 // Write VAL to export data.
2060 void
2061 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2063 char* s = mpz_get_str(NULL, 10, val);
2064 exp->write_c_string(s);
2065 free(s);
2068 // Export an integer in a constant expression.
2070 void
2071 Integer_expression::do_export(Export* exp) const
2073 Integer_expression::export_integer(exp, this->val_);
2074 if (this->is_character_constant_)
2075 exp->write_c_string("'");
2076 // A trailing space lets us reliably identify the end of the number.
2077 exp->write_c_string(" ");
2080 // Import an integer, floating point, or complex value. This handles
2081 // all these types because they all start with digits.
2083 Expression*
2084 Integer_expression::do_import(Import* imp)
2086 std::string num = imp->read_identifier();
2087 imp->require_c_string(" ");
2088 if (!num.empty() && num[num.length() - 1] == 'i')
2090 mpfr_t real;
2091 size_t plus_pos = num.find('+', 1);
2092 size_t minus_pos = num.find('-', 1);
2093 size_t pos;
2094 if (plus_pos == std::string::npos)
2095 pos = minus_pos;
2096 else if (minus_pos == std::string::npos)
2097 pos = plus_pos;
2098 else
2100 go_error_at(imp->location(), "bad number in import data: %qs",
2101 num.c_str());
2102 return Expression::make_error(imp->location());
2104 if (pos == std::string::npos)
2105 mpfr_set_ui(real, 0, GMP_RNDN);
2106 else
2108 std::string real_str = num.substr(0, pos);
2109 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2111 go_error_at(imp->location(), "bad number in import data: %qs",
2112 real_str.c_str());
2113 return Expression::make_error(imp->location());
2117 std::string imag_str;
2118 if (pos == std::string::npos)
2119 imag_str = num;
2120 else
2121 imag_str = num.substr(pos);
2122 imag_str = imag_str.substr(0, imag_str.size() - 1);
2123 mpfr_t imag;
2124 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2126 go_error_at(imp->location(), "bad number in import data: %qs",
2127 imag_str.c_str());
2128 return Expression::make_error(imp->location());
2130 mpc_t cval;
2131 mpc_init2(cval, mpc_precision);
2132 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2133 mpfr_clear(real);
2134 mpfr_clear(imag);
2135 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2136 mpc_clear(cval);
2137 return ret;
2139 else if (num.find('.') == std::string::npos
2140 && num.find('E') == std::string::npos)
2142 bool is_character_constant = (!num.empty()
2143 && num[num.length() - 1] == '\'');
2144 if (is_character_constant)
2145 num = num.substr(0, num.length() - 1);
2146 mpz_t val;
2147 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2149 go_error_at(imp->location(), "bad number in import data: %qs",
2150 num.c_str());
2151 return Expression::make_error(imp->location());
2153 Expression* ret;
2154 if (is_character_constant)
2155 ret = Expression::make_character(&val, NULL, imp->location());
2156 else
2157 ret = Expression::make_integer_z(&val, NULL, imp->location());
2158 mpz_clear(val);
2159 return ret;
2161 else
2163 mpfr_t val;
2164 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2166 go_error_at(imp->location(), "bad number in import data: %qs",
2167 num.c_str());
2168 return Expression::make_error(imp->location());
2170 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2171 mpfr_clear(val);
2172 return ret;
2175 // Ast dump for integer expression.
2177 void
2178 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2180 if (this->is_character_constant_)
2181 ast_dump_context->ostream() << '\'';
2182 Integer_expression::export_integer(ast_dump_context, this->val_);
2183 if (this->is_character_constant_)
2184 ast_dump_context->ostream() << '\'';
2187 // Build a new integer value from a multi-precision integer.
2189 Expression*
2190 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2192 return new Integer_expression(val, type, false, location);
2195 // Build a new integer value from an unsigned long.
2197 Expression*
2198 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2200 mpz_t zval;
2201 mpz_init_set_ui(zval, val);
2202 Expression* ret = Expression::make_integer_z(&zval, type, location);
2203 mpz_clear(zval);
2204 return ret;
2207 // Build a new integer value from a signed long.
2209 Expression*
2210 Expression::make_integer_sl(long val, Type *type, Location location)
2212 mpz_t zval;
2213 mpz_init_set_si(zval, val);
2214 Expression* ret = Expression::make_integer_z(&zval, type, location);
2215 mpz_clear(zval);
2216 return ret;
2219 // Store an int64_t in an uninitialized mpz_t.
2221 static void
2222 set_mpz_from_int64(mpz_t* zval, int64_t val)
2224 if (val >= 0)
2226 unsigned long ul = static_cast<unsigned long>(val);
2227 if (static_cast<int64_t>(ul) == val)
2229 mpz_init_set_ui(*zval, ul);
2230 return;
2233 uint64_t uv;
2234 if (val >= 0)
2235 uv = static_cast<uint64_t>(val);
2236 else
2237 uv = static_cast<uint64_t>(- val);
2238 unsigned long ul = uv & 0xffffffffUL;
2239 mpz_init_set_ui(*zval, ul);
2240 mpz_t hval;
2241 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2242 mpz_mul_2exp(hval, hval, 32);
2243 mpz_add(*zval, *zval, hval);
2244 mpz_clear(hval);
2245 if (val < 0)
2246 mpz_neg(*zval, *zval);
2249 // Build a new integer value from an int64_t.
2251 Expression*
2252 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2254 mpz_t zval;
2255 set_mpz_from_int64(&zval, val);
2256 Expression* ret = Expression::make_integer_z(&zval, type, location);
2257 mpz_clear(zval);
2258 return ret;
2261 // Build a new character constant value.
2263 Expression*
2264 Expression::make_character(const mpz_t* val, Type* type, Location location)
2266 return new Integer_expression(val, type, true, location);
2269 // Floats.
2271 class Float_expression : public Expression
2273 public:
2274 Float_expression(const mpfr_t* val, Type* type, Location location)
2275 : Expression(EXPRESSION_FLOAT, location),
2276 type_(type)
2278 mpfr_init_set(this->val_, *val, GMP_RNDN);
2281 // Write VAL to export data.
2282 static void
2283 export_float(String_dump* exp, const mpfr_t val);
2285 // Write VAL to dump file.
2286 static void
2287 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2289 protected:
2290 bool
2291 do_is_constant() const
2292 { return true; }
2294 bool
2295 do_is_static_initializer() const
2296 { return true; }
2298 bool
2299 do_numeric_constant_value(Numeric_constant* nc) const
2301 nc->set_float(this->type_, this->val_);
2302 return true;
2305 Type*
2306 do_type();
2308 void
2309 do_determine_type(const Type_context*);
2311 void
2312 do_check_types(Gogo*);
2314 Expression*
2315 do_copy()
2316 { return Expression::make_float(&this->val_, this->type_,
2317 this->location()); }
2319 Bexpression*
2320 do_get_backend(Translate_context*);
2322 void
2323 do_export(Export*) const;
2325 void
2326 do_dump_expression(Ast_dump_context*) const;
2328 private:
2329 // The floating point value.
2330 mpfr_t val_;
2331 // The type so far.
2332 Type* type_;
2335 // Return the current type. If we haven't set the type yet, we return
2336 // an abstract float type.
2338 Type*
2339 Float_expression::do_type()
2341 if (this->type_ == NULL)
2342 this->type_ = Type::make_abstract_float_type();
2343 return this->type_;
2346 // Set the type of the float value. Here we may switch from an
2347 // abstract type to a real type.
2349 void
2350 Float_expression::do_determine_type(const Type_context* context)
2352 if (this->type_ != NULL && !this->type_->is_abstract())
2354 else if (context->type != NULL
2355 && (context->type->integer_type() != NULL
2356 || context->type->float_type() != NULL
2357 || context->type->complex_type() != NULL))
2358 this->type_ = context->type;
2359 else if (!context->may_be_abstract)
2360 this->type_ = Type::lookup_float_type("float64");
2363 // Check the type of a float value.
2365 void
2366 Float_expression::do_check_types(Gogo*)
2368 Type* type = this->type_;
2369 if (type == NULL)
2370 return;
2371 Numeric_constant nc;
2372 nc.set_float(NULL, this->val_);
2373 if (!nc.set_type(this->type_, true, this->location()))
2374 this->set_is_error();
2377 // Get the backend representation for a float constant.
2379 Bexpression*
2380 Float_expression::do_get_backend(Translate_context* context)
2382 if (this->is_error_expression()
2383 || (this->type_ != NULL && this->type_->is_error_type()))
2385 go_assert(saw_errors());
2386 return context->gogo()->backend()->error_expression();
2389 Type* resolved_type;
2390 if (this->type_ != NULL && !this->type_->is_abstract())
2391 resolved_type = this->type_;
2392 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2394 // We have an abstract integer type. We just hope for the best.
2395 resolved_type = Type::lookup_integer_type("int");
2397 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2399 // We are converting to an abstract complex type.
2400 resolved_type = Type::lookup_complex_type("complex128");
2402 else
2404 // If we still have an abstract type here, then this is being
2405 // used in a constant expression which didn't get reduced. We
2406 // just use float64 and hope for the best.
2407 resolved_type = Type::lookup_float_type("float64");
2410 Numeric_constant nc;
2411 nc.set_float(resolved_type, this->val_);
2412 return Expression::backend_numeric_constant_expression(context, &nc);
2415 // Write a floating point number to a string dump.
2417 void
2418 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2420 mp_exp_t exponent;
2421 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2422 if (*s == '-')
2423 exp->write_c_string("-");
2424 exp->write_c_string("0.");
2425 exp->write_c_string(*s == '-' ? s + 1 : s);
2426 mpfr_free_str(s);
2427 char buf[30];
2428 snprintf(buf, sizeof buf, "E%ld", exponent);
2429 exp->write_c_string(buf);
2432 // Export a floating point number in a constant expression.
2434 void
2435 Float_expression::do_export(Export* exp) const
2437 Float_expression::export_float(exp, this->val_);
2438 // A trailing space lets us reliably identify the end of the number.
2439 exp->write_c_string(" ");
2442 // Dump a floating point number to the dump file.
2444 void
2445 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2447 Float_expression::export_float(ast_dump_context, this->val_);
2450 // Make a float expression.
2452 Expression*
2453 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2455 return new Float_expression(val, type, location);
2458 // Complex numbers.
2460 class Complex_expression : public Expression
2462 public:
2463 Complex_expression(const mpc_t* val, Type* type, Location location)
2464 : Expression(EXPRESSION_COMPLEX, location),
2465 type_(type)
2467 mpc_init2(this->val_, mpc_precision);
2468 mpc_set(this->val_, *val, MPC_RNDNN);
2471 // Write VAL to string dump.
2472 static void
2473 export_complex(String_dump* exp, const mpc_t val);
2475 // Write REAL/IMAG to dump context.
2476 static void
2477 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2479 protected:
2480 bool
2481 do_is_constant() const
2482 { return true; }
2484 bool
2485 do_is_static_initializer() const
2486 { return true; }
2488 bool
2489 do_numeric_constant_value(Numeric_constant* nc) const
2491 nc->set_complex(this->type_, this->val_);
2492 return true;
2495 Type*
2496 do_type();
2498 void
2499 do_determine_type(const Type_context*);
2501 void
2502 do_check_types(Gogo*);
2504 Expression*
2505 do_copy()
2507 return Expression::make_complex(&this->val_, this->type_,
2508 this->location());
2511 Bexpression*
2512 do_get_backend(Translate_context*);
2514 void
2515 do_export(Export*) const;
2517 void
2518 do_dump_expression(Ast_dump_context*) const;
2520 private:
2521 // The complex value.
2522 mpc_t val_;
2523 // The type if known.
2524 Type* type_;
2527 // Return the current type. If we haven't set the type yet, we return
2528 // an abstract complex type.
2530 Type*
2531 Complex_expression::do_type()
2533 if (this->type_ == NULL)
2534 this->type_ = Type::make_abstract_complex_type();
2535 return this->type_;
2538 // Set the type of the complex value. Here we may switch from an
2539 // abstract type to a real type.
2541 void
2542 Complex_expression::do_determine_type(const Type_context* context)
2544 if (this->type_ != NULL && !this->type_->is_abstract())
2546 else if (context->type != NULL && context->type->is_numeric_type())
2547 this->type_ = context->type;
2548 else if (!context->may_be_abstract)
2549 this->type_ = Type::lookup_complex_type("complex128");
2552 // Check the type of a complex value.
2554 void
2555 Complex_expression::do_check_types(Gogo*)
2557 Type* type = this->type_;
2558 if (type == NULL)
2559 return;
2560 Numeric_constant nc;
2561 nc.set_complex(NULL, this->val_);
2562 if (!nc.set_type(this->type_, true, this->location()))
2563 this->set_is_error();
2566 // Get the backend representation for a complex constant.
2568 Bexpression*
2569 Complex_expression::do_get_backend(Translate_context* context)
2571 if (this->is_error_expression()
2572 || (this->type_ != NULL && this->type_->is_error_type()))
2574 go_assert(saw_errors());
2575 return context->gogo()->backend()->error_expression();
2578 Type* resolved_type;
2579 if (this->type_ != NULL && !this->type_->is_abstract())
2580 resolved_type = this->type_;
2581 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2583 // We are converting to an abstract integer type.
2584 resolved_type = Type::lookup_integer_type("int");
2586 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2588 // We are converting to an abstract float type.
2589 resolved_type = Type::lookup_float_type("float64");
2591 else
2593 // If we still have an abstract type here, this is being
2594 // used in a constant expression which didn't get reduced. We
2595 // just use complex128 and hope for the best.
2596 resolved_type = Type::lookup_complex_type("complex128");
2599 Numeric_constant nc;
2600 nc.set_complex(resolved_type, this->val_);
2601 return Expression::backend_numeric_constant_expression(context, &nc);
2604 // Write REAL/IMAG to export data.
2606 void
2607 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2609 if (!mpfr_zero_p(mpc_realref(val)))
2611 Float_expression::export_float(exp, mpc_realref(val));
2612 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2613 exp->write_c_string("+");
2615 Float_expression::export_float(exp, mpc_imagref(val));
2616 exp->write_c_string("i");
2619 // Export a complex number in a constant expression.
2621 void
2622 Complex_expression::do_export(Export* exp) const
2624 Complex_expression::export_complex(exp, this->val_);
2625 // A trailing space lets us reliably identify the end of the number.
2626 exp->write_c_string(" ");
2629 // Dump a complex expression to the dump file.
2631 void
2632 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2634 Complex_expression::export_complex(ast_dump_context, this->val_);
2637 // Make a complex expression.
2639 Expression*
2640 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2642 return new Complex_expression(val, type, location);
2645 // Find a named object in an expression.
2647 class Find_named_object : public Traverse
2649 public:
2650 Find_named_object(Named_object* no)
2651 : Traverse(traverse_expressions),
2652 no_(no), found_(false)
2655 // Whether we found the object.
2656 bool
2657 found() const
2658 { return this->found_; }
2660 protected:
2662 expression(Expression**);
2664 private:
2665 // The object we are looking for.
2666 Named_object* no_;
2667 // Whether we found it.
2668 bool found_;
2671 // A reference to a const in an expression.
2673 class Const_expression : public Expression
2675 public:
2676 Const_expression(Named_object* constant, Location location)
2677 : Expression(EXPRESSION_CONST_REFERENCE, location),
2678 constant_(constant), type_(NULL), seen_(false)
2681 Named_object*
2682 named_object()
2683 { return this->constant_; }
2685 // Check that the initializer does not refer to the constant itself.
2686 void
2687 check_for_init_loop();
2689 protected:
2691 do_traverse(Traverse*);
2693 Expression*
2694 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2696 bool
2697 do_is_constant() const
2698 { return true; }
2700 bool
2701 do_is_static_initializer() const
2702 { return true; }
2704 bool
2705 do_numeric_constant_value(Numeric_constant* nc) const;
2707 bool
2708 do_string_constant_value(std::string* val) const;
2710 Type*
2711 do_type();
2713 // The type of a const is set by the declaration, not the use.
2714 void
2715 do_determine_type(const Type_context*);
2717 void
2718 do_check_types(Gogo*);
2720 Expression*
2721 do_copy()
2722 { return this; }
2724 Bexpression*
2725 do_get_backend(Translate_context* context);
2727 // When exporting a reference to a const as part of a const
2728 // expression, we export the value. We ignore the fact that it has
2729 // a name.
2730 void
2731 do_export(Export* exp) const
2732 { this->constant_->const_value()->expr()->export_expression(exp); }
2734 void
2735 do_dump_expression(Ast_dump_context*) const;
2737 private:
2738 // The constant.
2739 Named_object* constant_;
2740 // The type of this reference. This is used if the constant has an
2741 // abstract type.
2742 Type* type_;
2743 // Used to prevent infinite recursion when a constant incorrectly
2744 // refers to itself.
2745 mutable bool seen_;
2748 // Traversal.
2751 Const_expression::do_traverse(Traverse* traverse)
2753 if (this->type_ != NULL)
2754 return Type::traverse(this->type_, traverse);
2755 return TRAVERSE_CONTINUE;
2758 // Lower a constant expression. This is where we convert the
2759 // predeclared constant iota into an integer value.
2761 Expression*
2762 Const_expression::do_lower(Gogo* gogo, Named_object*,
2763 Statement_inserter*, int iota_value)
2765 if (this->constant_->const_value()->expr()->classification()
2766 == EXPRESSION_IOTA)
2768 if (iota_value == -1)
2770 go_error_at(this->location(),
2771 "iota is only defined in const declarations");
2772 iota_value = 0;
2774 return Expression::make_integer_ul(iota_value, NULL, this->location());
2777 // Make sure that the constant itself has been lowered.
2778 gogo->lower_constant(this->constant_);
2780 return this;
2783 // Return a numeric constant value.
2785 bool
2786 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2788 if (this->seen_)
2789 return false;
2791 Expression* e = this->constant_->const_value()->expr();
2793 this->seen_ = true;
2795 bool r = e->numeric_constant_value(nc);
2797 this->seen_ = false;
2799 Type* ctype;
2800 if (this->type_ != NULL)
2801 ctype = this->type_;
2802 else
2803 ctype = this->constant_->const_value()->type();
2804 if (r && ctype != NULL)
2806 if (!nc->set_type(ctype, false, this->location()))
2807 return false;
2810 return r;
2813 bool
2814 Const_expression::do_string_constant_value(std::string* val) const
2816 if (this->seen_)
2817 return false;
2819 Expression* e = this->constant_->const_value()->expr();
2821 this->seen_ = true;
2822 bool ok = e->string_constant_value(val);
2823 this->seen_ = false;
2825 return ok;
2828 // Return the type of the const reference.
2830 Type*
2831 Const_expression::do_type()
2833 if (this->type_ != NULL)
2834 return this->type_;
2836 Named_constant* nc = this->constant_->const_value();
2838 if (this->seen_ || nc->lowering())
2840 this->report_error(_("constant refers to itself"));
2841 this->type_ = Type::make_error_type();
2842 return this->type_;
2845 this->seen_ = true;
2847 Type* ret = nc->type();
2849 if (ret != NULL)
2851 this->seen_ = false;
2852 return ret;
2855 // During parsing, a named constant may have a NULL type, but we
2856 // must not return a NULL type here.
2857 ret = nc->expr()->type();
2859 this->seen_ = false;
2861 return ret;
2864 // Set the type of the const reference.
2866 void
2867 Const_expression::do_determine_type(const Type_context* context)
2869 Type* ctype = this->constant_->const_value()->type();
2870 Type* cetype = (ctype != NULL
2871 ? ctype
2872 : this->constant_->const_value()->expr()->type());
2873 if (ctype != NULL && !ctype->is_abstract())
2875 else if (context->type != NULL
2876 && context->type->is_numeric_type()
2877 && cetype->is_numeric_type())
2878 this->type_ = context->type;
2879 else if (context->type != NULL
2880 && context->type->is_string_type()
2881 && cetype->is_string_type())
2882 this->type_ = context->type;
2883 else if (context->type != NULL
2884 && context->type->is_boolean_type()
2885 && cetype->is_boolean_type())
2886 this->type_ = context->type;
2887 else if (!context->may_be_abstract)
2889 if (cetype->is_abstract())
2890 cetype = cetype->make_non_abstract_type();
2891 this->type_ = cetype;
2895 // Check for a loop in which the initializer of a constant refers to
2896 // the constant itself.
2898 void
2899 Const_expression::check_for_init_loop()
2901 if (this->type_ != NULL && this->type_->is_error())
2902 return;
2904 if (this->seen_)
2906 this->report_error(_("constant refers to itself"));
2907 this->type_ = Type::make_error_type();
2908 return;
2911 Expression* init = this->constant_->const_value()->expr();
2912 Find_named_object find_named_object(this->constant_);
2914 this->seen_ = true;
2915 Expression::traverse(&init, &find_named_object);
2916 this->seen_ = false;
2918 if (find_named_object.found())
2920 if (this->type_ == NULL || !this->type_->is_error())
2922 this->report_error(_("constant refers to itself"));
2923 this->type_ = Type::make_error_type();
2925 return;
2929 // Check types of a const reference.
2931 void
2932 Const_expression::do_check_types(Gogo*)
2934 if (this->type_ != NULL && this->type_->is_error())
2935 return;
2937 this->check_for_init_loop();
2939 // Check that numeric constant fits in type.
2940 if (this->type_ != NULL && this->type_->is_numeric_type())
2942 Numeric_constant nc;
2943 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2945 if (!nc.set_type(this->type_, true, this->location()))
2946 this->set_is_error();
2951 // Return the backend representation for a const reference.
2953 Bexpression*
2954 Const_expression::do_get_backend(Translate_context* context)
2956 if (this->is_error_expression()
2957 || (this->type_ != NULL && this->type_->is_error()))
2959 go_assert(saw_errors());
2960 return context->backend()->error_expression();
2963 // If the type has been set for this expression, but the underlying
2964 // object is an abstract int or float, we try to get the abstract
2965 // value. Otherwise we may lose something in the conversion.
2966 Expression* expr = this->constant_->const_value()->expr();
2967 if (this->type_ != NULL
2968 && this->type_->is_numeric_type()
2969 && (this->constant_->const_value()->type() == NULL
2970 || this->constant_->const_value()->type()->is_abstract()))
2972 Numeric_constant nc;
2973 if (expr->numeric_constant_value(&nc)
2974 && nc.set_type(this->type_, false, this->location()))
2976 Expression* e = nc.expression(this->location());
2977 return e->get_backend(context);
2981 if (this->type_ != NULL)
2982 expr = Expression::make_cast(this->type_, expr, this->location());
2983 return expr->get_backend(context);
2986 // Dump ast representation for constant expression.
2988 void
2989 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2991 ast_dump_context->ostream() << this->constant_->name();
2994 // Make a reference to a constant in an expression.
2996 Expression*
2997 Expression::make_const_reference(Named_object* constant,
2998 Location location)
3000 return new Const_expression(constant, location);
3003 // Find a named object in an expression.
3006 Find_named_object::expression(Expression** pexpr)
3008 switch ((*pexpr)->classification())
3010 case Expression::EXPRESSION_CONST_REFERENCE:
3012 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3013 if (ce->named_object() == this->no_)
3014 break;
3016 // We need to check a constant initializer explicitly, as
3017 // loops here will not be caught by the loop checking for
3018 // variable initializers.
3019 ce->check_for_init_loop();
3021 return TRAVERSE_CONTINUE;
3024 case Expression::EXPRESSION_VAR_REFERENCE:
3025 if ((*pexpr)->var_expression()->named_object() == this->no_)
3026 break;
3027 return TRAVERSE_CONTINUE;
3028 case Expression::EXPRESSION_FUNC_REFERENCE:
3029 if ((*pexpr)->func_expression()->named_object() == this->no_)
3030 break;
3031 return TRAVERSE_CONTINUE;
3032 default:
3033 return TRAVERSE_CONTINUE;
3035 this->found_ = true;
3036 return TRAVERSE_EXIT;
3039 // The nil value.
3041 class Nil_expression : public Expression
3043 public:
3044 Nil_expression(Location location)
3045 : Expression(EXPRESSION_NIL, location)
3048 static Expression*
3049 do_import(Import*);
3051 protected:
3052 bool
3053 do_is_constant() const
3054 { return true; }
3056 bool
3057 do_is_static_initializer() const
3058 { return true; }
3060 Type*
3061 do_type()
3062 { return Type::make_nil_type(); }
3064 void
3065 do_determine_type(const Type_context*)
3068 Expression*
3069 do_copy()
3070 { return this; }
3072 Bexpression*
3073 do_get_backend(Translate_context* context)
3074 { return context->backend()->nil_pointer_expression(); }
3076 void
3077 do_export(Export* exp) const
3078 { exp->write_c_string("nil"); }
3080 void
3081 do_dump_expression(Ast_dump_context* ast_dump_context) const
3082 { ast_dump_context->ostream() << "nil"; }
3085 // Import a nil expression.
3087 Expression*
3088 Nil_expression::do_import(Import* imp)
3090 imp->require_c_string("nil");
3091 return Expression::make_nil(imp->location());
3094 // Make a nil expression.
3096 Expression*
3097 Expression::make_nil(Location location)
3099 return new Nil_expression(location);
3102 // The value of the predeclared constant iota. This is little more
3103 // than a marker. This will be lowered to an integer in
3104 // Const_expression::do_lower, which is where we know the value that
3105 // it should have.
3107 class Iota_expression : public Parser_expression
3109 public:
3110 Iota_expression(Location location)
3111 : Parser_expression(EXPRESSION_IOTA, location)
3114 protected:
3115 Expression*
3116 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3117 { go_unreachable(); }
3119 // There should only ever be one of these.
3120 Expression*
3121 do_copy()
3122 { go_unreachable(); }
3124 void
3125 do_dump_expression(Ast_dump_context* ast_dump_context) const
3126 { ast_dump_context->ostream() << "iota"; }
3129 // Make an iota expression. This is only called for one case: the
3130 // value of the predeclared constant iota.
3132 Expression*
3133 Expression::make_iota()
3135 static Iota_expression iota_expression(Linemap::unknown_location());
3136 return &iota_expression;
3139 // Class Type_conversion_expression.
3141 // Traversal.
3144 Type_conversion_expression::do_traverse(Traverse* traverse)
3146 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3147 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3148 return TRAVERSE_EXIT;
3149 return TRAVERSE_CONTINUE;
3152 // Convert to a constant at lowering time.
3154 Expression*
3155 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3156 Statement_inserter*, int)
3158 Type* type = this->type_;
3159 Expression* val = this->expr_;
3160 Location location = this->location();
3162 if (type->is_numeric_type())
3164 Numeric_constant nc;
3165 if (val->numeric_constant_value(&nc))
3167 if (!nc.set_type(type, true, location))
3168 return Expression::make_error(location);
3169 return nc.expression(location);
3173 // According to the language specification on string conversions
3174 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3175 // When converting an integer into a string, the string will be a UTF-8
3176 // representation of the integer and integers "outside the range of valid
3177 // Unicode code points are converted to '\uFFFD'."
3178 if (type->is_string_type())
3180 Numeric_constant nc;
3181 if (val->numeric_constant_value(&nc) && nc.is_int())
3183 // An integer value doesn't fit in the Unicode code point range if it
3184 // overflows the Go "int" type or is negative.
3185 unsigned long ul;
3186 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3187 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3188 return Expression::make_string("\ufffd", location);
3192 if (type->is_slice_type())
3194 Type* element_type = type->array_type()->element_type()->forwarded();
3195 bool is_byte = (element_type->integer_type() != NULL
3196 && element_type->integer_type()->is_byte());
3197 bool is_rune = (element_type->integer_type() != NULL
3198 && element_type->integer_type()->is_rune());
3199 if (is_byte || is_rune)
3201 std::string s;
3202 if (val->string_constant_value(&s))
3204 Expression_list* vals = new Expression_list();
3205 if (is_byte)
3207 for (std::string::const_iterator p = s.begin();
3208 p != s.end();
3209 p++)
3211 unsigned char c = static_cast<unsigned char>(*p);
3212 vals->push_back(Expression::make_integer_ul(c,
3213 element_type,
3214 location));
3217 else
3219 const char *p = s.data();
3220 const char *pend = s.data() + s.length();
3221 while (p < pend)
3223 unsigned int c;
3224 int adv = Lex::fetch_char(p, &c);
3225 if (adv == 0)
3227 go_warning_at(this->location(), 0,
3228 "invalid UTF-8 encoding");
3229 adv = 1;
3231 p += adv;
3232 vals->push_back(Expression::make_integer_ul(c,
3233 element_type,
3234 location));
3238 return Expression::make_slice_composite_literal(type, vals,
3239 location);
3244 return this;
3247 // Flatten a type conversion by using a temporary variable for the slice
3248 // in slice to string conversions.
3250 Expression*
3251 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3252 Statement_inserter* inserter)
3254 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3256 go_assert(saw_errors());
3257 return Expression::make_error(this->location());
3260 if (((this->type()->is_string_type()
3261 && this->expr_->type()->is_slice_type())
3262 || this->expr_->type()->interface_type() != NULL)
3263 && !this->expr_->is_variable())
3265 Temporary_statement* temp =
3266 Statement::make_temporary(NULL, this->expr_, this->location());
3267 inserter->insert(temp);
3268 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3270 return this;
3273 // Return whether a type conversion is a constant.
3275 bool
3276 Type_conversion_expression::do_is_constant() const
3278 if (!this->expr_->is_constant())
3279 return false;
3281 // A conversion to a type that may not be used as a constant is not
3282 // a constant. For example, []byte(nil).
3283 Type* type = this->type_;
3284 if (type->integer_type() == NULL
3285 && type->float_type() == NULL
3286 && type->complex_type() == NULL
3287 && !type->is_boolean_type()
3288 && !type->is_string_type())
3289 return false;
3291 return true;
3294 // Return whether a type conversion can be used in a constant
3295 // initializer.
3297 bool
3298 Type_conversion_expression::do_is_static_initializer() const
3300 Type* type = this->type_;
3301 Type* expr_type = this->expr_->type();
3303 if (type->interface_type() != NULL
3304 || expr_type->interface_type() != NULL)
3305 return false;
3307 if (!this->expr_->is_static_initializer())
3308 return false;
3310 if (Type::are_identical(type, expr_type, false, NULL))
3311 return true;
3313 if (type->is_string_type() && expr_type->is_string_type())
3314 return true;
3316 if ((type->is_numeric_type()
3317 || type->is_boolean_type()
3318 || type->points_to() != NULL)
3319 && (expr_type->is_numeric_type()
3320 || expr_type->is_boolean_type()
3321 || expr_type->points_to() != NULL))
3322 return true;
3324 return false;
3327 // Return the constant numeric value if there is one.
3329 bool
3330 Type_conversion_expression::do_numeric_constant_value(
3331 Numeric_constant* nc) const
3333 if (!this->type_->is_numeric_type())
3334 return false;
3335 if (!this->expr_->numeric_constant_value(nc))
3336 return false;
3337 return nc->set_type(this->type_, false, this->location());
3340 // Return the constant string value if there is one.
3342 bool
3343 Type_conversion_expression::do_string_constant_value(std::string* val) const
3345 if (this->type_->is_string_type()
3346 && this->expr_->type()->integer_type() != NULL)
3348 Numeric_constant nc;
3349 if (this->expr_->numeric_constant_value(&nc))
3351 unsigned long ival;
3352 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3354 val->clear();
3355 Lex::append_char(ival, true, val, this->location());
3356 return true;
3361 // FIXME: Could handle conversion from const []int here.
3363 return false;
3366 // Determine the resulting type of the conversion.
3368 void
3369 Type_conversion_expression::do_determine_type(const Type_context*)
3371 Type_context subcontext(this->type_, false);
3372 this->expr_->determine_type(&subcontext);
3375 // Check that types are convertible.
3377 void
3378 Type_conversion_expression::do_check_types(Gogo*)
3380 Type* type = this->type_;
3381 Type* expr_type = this->expr_->type();
3382 std::string reason;
3384 if (type->is_error() || expr_type->is_error())
3386 this->set_is_error();
3387 return;
3390 if (this->may_convert_function_types_
3391 && type->function_type() != NULL
3392 && expr_type->function_type() != NULL)
3393 return;
3395 if (Type::are_convertible(type, expr_type, &reason))
3396 return;
3398 go_error_at(this->location(), "%s", reason.c_str());
3399 this->set_is_error();
3402 // Get the backend representation for a type conversion.
3404 Bexpression*
3405 Type_conversion_expression::do_get_backend(Translate_context* context)
3407 Type* type = this->type_;
3408 Type* expr_type = this->expr_->type();
3410 Gogo* gogo = context->gogo();
3411 Btype* btype = type->get_backend(gogo);
3412 Location loc = this->location();
3414 if (Type::are_identical(type, expr_type, false, NULL))
3416 Bexpression* bexpr = this->expr_->get_backend(context);
3417 return gogo->backend()->convert_expression(btype, bexpr, loc);
3419 else if (type->interface_type() != NULL
3420 || expr_type->interface_type() != NULL)
3422 Expression* conversion =
3423 Expression::convert_for_assignment(gogo, type, this->expr_,
3424 this->location());
3425 return conversion->get_backend(context);
3427 else if (type->is_string_type()
3428 && expr_type->integer_type() != NULL)
3430 mpz_t intval;
3431 Numeric_constant nc;
3432 if (this->expr_->numeric_constant_value(&nc)
3433 && nc.to_int(&intval)
3434 && mpz_fits_ushort_p(intval))
3436 std::string s;
3437 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3438 mpz_clear(intval);
3439 Expression* se = Expression::make_string(s, loc);
3440 return se->get_backend(context);
3443 Expression* i2s_expr =
3444 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3445 Expression::make_nil(loc), this->expr_);
3446 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3448 else if (type->is_string_type() && expr_type->is_slice_type())
3450 Array_type* a = expr_type->array_type();
3451 Type* e = a->element_type()->forwarded();
3452 go_assert(e->integer_type() != NULL);
3453 go_assert(this->expr_->is_variable());
3455 Runtime::Function code;
3456 if (e->integer_type()->is_byte())
3457 code = Runtime::SLICEBYTETOSTRING;
3458 else
3460 go_assert(e->integer_type()->is_rune());
3461 code = Runtime::SLICERUNETOSTRING;
3463 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3464 this->expr_)->get_backend(context);
3466 else if (type->is_slice_type() && expr_type->is_string_type())
3468 Type* e = type->array_type()->element_type()->forwarded();
3469 go_assert(e->integer_type() != NULL);
3471 Runtime::Function code;
3472 if (e->integer_type()->is_byte())
3473 code = Runtime::STRINGTOSLICEBYTE;
3474 else
3476 go_assert(e->integer_type()->is_rune());
3477 code = Runtime::STRINGTOSLICERUNE;
3479 Expression* s2a = Runtime::make_call(code, loc, 2,
3480 Expression::make_nil(loc),
3481 this->expr_);
3482 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3484 else if (type->is_numeric_type())
3486 go_assert(Type::are_convertible(type, expr_type, NULL));
3487 Bexpression* bexpr = this->expr_->get_backend(context);
3488 return gogo->backend()->convert_expression(btype, bexpr, loc);
3490 else if ((type->is_unsafe_pointer_type()
3491 && (expr_type->points_to() != NULL
3492 || expr_type->integer_type()))
3493 || (expr_type->is_unsafe_pointer_type()
3494 && type->points_to() != NULL)
3495 || (this->may_convert_function_types_
3496 && type->function_type() != NULL
3497 && expr_type->function_type() != NULL))
3499 Bexpression* bexpr = this->expr_->get_backend(context);
3500 return gogo->backend()->convert_expression(btype, bexpr, loc);
3502 else
3504 Expression* conversion =
3505 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3506 return conversion->get_backend(context);
3510 // Output a type conversion in a constant expression.
3512 void
3513 Type_conversion_expression::do_export(Export* exp) const
3515 exp->write_c_string("convert(");
3516 exp->write_type(this->type_);
3517 exp->write_c_string(", ");
3518 this->expr_->export_expression(exp);
3519 exp->write_c_string(")");
3522 // Import a type conversion or a struct construction.
3524 Expression*
3525 Type_conversion_expression::do_import(Import* imp)
3527 imp->require_c_string("convert(");
3528 Type* type = imp->read_type();
3529 imp->require_c_string(", ");
3530 Expression* val = Expression::import_expression(imp);
3531 imp->require_c_string(")");
3532 return Expression::make_cast(type, val, imp->location());
3535 // Dump ast representation for a type conversion expression.
3537 void
3538 Type_conversion_expression::do_dump_expression(
3539 Ast_dump_context* ast_dump_context) const
3541 ast_dump_context->dump_type(this->type_);
3542 ast_dump_context->ostream() << "(";
3543 ast_dump_context->dump_expression(this->expr_);
3544 ast_dump_context->ostream() << ") ";
3547 // Make a type cast expression.
3549 Expression*
3550 Expression::make_cast(Type* type, Expression* val, Location location)
3552 if (type->is_error_type() || val->is_error_expression())
3553 return Expression::make_error(location);
3554 return new Type_conversion_expression(type, val, location);
3557 // Class Unsafe_type_conversion_expression.
3559 // Traversal.
3562 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3564 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3565 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3566 return TRAVERSE_EXIT;
3567 return TRAVERSE_CONTINUE;
3570 // Return whether an unsafe type conversion can be used as a constant
3571 // initializer.
3573 bool
3574 Unsafe_type_conversion_expression::do_is_static_initializer() const
3576 Type* type = this->type_;
3577 Type* expr_type = this->expr_->type();
3579 if (type->interface_type() != NULL
3580 || expr_type->interface_type() != NULL)
3581 return false;
3583 if (!this->expr_->is_static_initializer())
3584 return false;
3586 if (Type::are_convertible(type, expr_type, NULL))
3587 return true;
3589 if (type->is_string_type() && expr_type->is_string_type())
3590 return true;
3592 if ((type->is_numeric_type()
3593 || type->is_boolean_type()
3594 || type->points_to() != NULL)
3595 && (expr_type->is_numeric_type()
3596 || expr_type->is_boolean_type()
3597 || expr_type->points_to() != NULL))
3598 return true;
3600 return false;
3603 // Convert to backend representation.
3605 Bexpression*
3606 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3608 // We are only called for a limited number of cases.
3610 Type* t = this->type_;
3611 Type* et = this->expr_->type();
3613 if (t->is_error_type()
3614 || this->expr_->is_error_expression()
3615 || et->is_error_type())
3617 go_assert(saw_errors());
3618 return context->backend()->error_expression();
3621 if (t->array_type() != NULL)
3622 go_assert(et->array_type() != NULL
3623 && t->is_slice_type() == et->is_slice_type());
3624 else if (t->struct_type() != NULL)
3626 if (t->named_type() != NULL
3627 && et->named_type() != NULL
3628 && !Type::are_convertible(t, et, NULL))
3630 go_assert(saw_errors());
3631 return context->backend()->error_expression();
3634 go_assert(et->struct_type() != NULL
3635 && Type::are_convertible(t, et, NULL));
3637 else if (t->map_type() != NULL)
3638 go_assert(et->map_type() != NULL);
3639 else if (t->channel_type() != NULL)
3640 go_assert(et->channel_type() != NULL);
3641 else if (t->points_to() != NULL)
3642 go_assert(et->points_to() != NULL
3643 || et->channel_type() != NULL
3644 || et->map_type() != NULL
3645 || et->function_type() != NULL
3646 || et->integer_type() != NULL
3647 || et->is_nil_type());
3648 else if (et->is_unsafe_pointer_type())
3649 go_assert(t->points_to() != NULL);
3650 else if (t->interface_type() != NULL)
3652 bool empty_iface = t->interface_type()->is_empty();
3653 go_assert(et->interface_type() != NULL
3654 && et->interface_type()->is_empty() == empty_iface);
3656 else if (t->integer_type() != NULL)
3657 go_assert(et->is_boolean_type()
3658 || et->integer_type() != NULL
3659 || et->function_type() != NULL
3660 || et->points_to() != NULL
3661 || et->map_type() != NULL
3662 || et->channel_type() != NULL
3663 || et->is_nil_type());
3664 else if (t->function_type() != NULL)
3665 go_assert(et->points_to() != NULL);
3666 else
3667 go_unreachable();
3669 Gogo* gogo = context->gogo();
3670 Btype* btype = t->get_backend(gogo);
3671 Bexpression* bexpr = this->expr_->get_backend(context);
3672 Location loc = this->location();
3673 return gogo->backend()->convert_expression(btype, bexpr, loc);
3676 // Dump ast representation for an unsafe type conversion expression.
3678 void
3679 Unsafe_type_conversion_expression::do_dump_expression(
3680 Ast_dump_context* ast_dump_context) const
3682 ast_dump_context->dump_type(this->type_);
3683 ast_dump_context->ostream() << "(";
3684 ast_dump_context->dump_expression(this->expr_);
3685 ast_dump_context->ostream() << ") ";
3688 // Make an unsafe type conversion expression.
3690 Expression*
3691 Expression::make_unsafe_cast(Type* type, Expression* expr,
3692 Location location)
3694 return new Unsafe_type_conversion_expression(type, expr, location);
3697 // Class Unary_expression.
3699 // Call the address_taken method of the operand if needed. This is
3700 // called after escape analysis but before inserting write barriers.
3702 void
3703 Unary_expression::check_operand_address_taken(Gogo* gogo)
3705 if (this->op_ != OPERATOR_AND)
3706 return;
3708 // If this->escapes_ is false at this point, then it was set to
3709 // false by an explicit call to set_does_not_escape, and the value
3710 // does not escape. If this->escapes_ is true, we may be able to
3711 // set it to false if taking the address of a variable that does not
3712 // escape.
3713 Node* n = Node::make_node(this);
3714 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3715 this->escapes_ = false;
3717 // When compiling the runtime, the address operator does not cause
3718 // local variables to escape. When escape analysis becomes the
3719 // default, this should be changed to make it an error if we have an
3720 // address operator that escapes.
3721 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3722 this->escapes_ = false;
3724 Named_object* var = NULL;
3725 if (this->expr_->var_expression() != NULL)
3726 var = this->expr_->var_expression()->named_object();
3727 else if (this->expr_->enclosed_var_expression() != NULL)
3728 var = this->expr_->enclosed_var_expression()->variable();
3730 if (this->escapes_ && var != NULL)
3732 if (var->is_variable())
3733 this->escapes_ = var->var_value()->escapes();
3734 if (var->is_result_variable())
3735 this->escapes_ = var->result_var_value()->escapes();
3738 this->expr_->address_taken(this->escapes_);
3741 // If we are taking the address of a composite literal, and the
3742 // contents are not constant, then we want to make a heap expression
3743 // instead.
3745 Expression*
3746 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3748 Location loc = this->location();
3749 Operator op = this->op_;
3750 Expression* expr = this->expr_;
3752 if (op == OPERATOR_MULT && expr->is_type_expression())
3753 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3755 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3756 // moving x to the heap. FIXME: Is it worth doing a real escape
3757 // analysis here? This case is found in math/unsafe.go and is
3758 // therefore worth special casing.
3759 if (op == OPERATOR_MULT)
3761 Expression* e = expr;
3762 while (e->classification() == EXPRESSION_CONVERSION)
3764 Type_conversion_expression* te
3765 = static_cast<Type_conversion_expression*>(e);
3766 e = te->expr();
3769 if (e->classification() == EXPRESSION_UNARY)
3771 Unary_expression* ue = static_cast<Unary_expression*>(e);
3772 if (ue->op_ == OPERATOR_AND)
3774 if (e == expr)
3776 // *&x == x.
3777 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3779 go_error_at(ue->location(),
3780 "invalid operand for unary %<&%>");
3781 this->set_is_error();
3783 return ue->expr_;
3785 ue->set_does_not_escape();
3790 // Catching an invalid indirection of unsafe.Pointer here avoid
3791 // having to deal with TYPE_VOID in other places.
3792 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3794 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3795 return Expression::make_error(this->location());
3798 // Check for an invalid pointer dereference. We need to do this
3799 // here because Unary_expression::do_type will return an error type
3800 // in this case. That can cause code to appear erroneous, and
3801 // therefore disappear at lowering time, without any error message.
3802 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3804 this->report_error(_("expected pointer"));
3805 return Expression::make_error(this->location());
3808 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3810 Numeric_constant nc;
3811 if (expr->numeric_constant_value(&nc))
3813 Numeric_constant result;
3814 bool issued_error;
3815 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3816 &issued_error))
3817 return result.expression(loc);
3818 else if (issued_error)
3819 return Expression::make_error(this->location());
3823 return this;
3826 // Flatten expression if a nil check must be performed and create temporary
3827 // variables if necessary.
3829 Expression*
3830 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3831 Statement_inserter* inserter)
3833 if (this->is_error_expression()
3834 || this->expr_->is_error_expression()
3835 || this->expr_->type()->is_error_type())
3837 go_assert(saw_errors());
3838 return Expression::make_error(this->location());
3841 Location location = this->location();
3842 if (this->op_ == OPERATOR_MULT
3843 && !this->expr_->is_variable())
3845 go_assert(this->expr_->type()->points_to() != NULL);
3846 switch (this->requires_nil_check(gogo))
3848 case NIL_CHECK_ERROR_ENCOUNTERED:
3850 go_assert(saw_errors());
3851 return Expression::make_error(this->location());
3853 case NIL_CHECK_NOT_NEEDED:
3854 break;
3855 case NIL_CHECK_NEEDED:
3856 this->create_temp_ = true;
3857 break;
3858 case NIL_CHECK_DEFAULT:
3859 go_unreachable();
3863 if (this->create_temp_ && !this->expr_->is_variable())
3865 Temporary_statement* temp =
3866 Statement::make_temporary(NULL, this->expr_, location);
3867 inserter->insert(temp);
3868 this->expr_ = Expression::make_temporary_reference(temp, location);
3871 return this;
3874 // Return whether a unary expression is a constant.
3876 bool
3877 Unary_expression::do_is_constant() const
3879 if (this->op_ == OPERATOR_MULT)
3881 // Indirecting through a pointer is only constant if the object
3882 // to which the expression points is constant, but we currently
3883 // have no way to determine that.
3884 return false;
3886 else if (this->op_ == OPERATOR_AND)
3888 // Taking the address of a variable is constant if it is a
3889 // global variable, not constant otherwise. In other cases taking the
3890 // address is probably not a constant.
3891 Var_expression* ve = this->expr_->var_expression();
3892 if (ve != NULL)
3894 Named_object* no = ve->named_object();
3895 return no->is_variable() && no->var_value()->is_global();
3897 return false;
3899 else
3900 return this->expr_->is_constant();
3903 // Return whether a unary expression can be used as a constant
3904 // initializer.
3906 bool
3907 Unary_expression::do_is_static_initializer() const
3909 if (this->op_ == OPERATOR_MULT)
3910 return false;
3911 else if (this->op_ == OPERATOR_AND)
3912 return Unary_expression::base_is_static_initializer(this->expr_);
3913 else
3914 return this->expr_->is_static_initializer();
3917 // Return whether the address of EXPR can be used as a static
3918 // initializer.
3920 bool
3921 Unary_expression::base_is_static_initializer(Expression* expr)
3923 // The address of a field reference can be a static initializer if
3924 // the base can be a static initializer.
3925 Field_reference_expression* fre = expr->field_reference_expression();
3926 if (fre != NULL)
3927 return Unary_expression::base_is_static_initializer(fre->expr());
3929 // The address of an index expression can be a static initializer if
3930 // the base can be a static initializer and the index is constant.
3931 Array_index_expression* aind = expr->array_index_expression();
3932 if (aind != NULL)
3933 return (aind->end() == NULL
3934 && aind->start()->is_constant()
3935 && Unary_expression::base_is_static_initializer(aind->array()));
3937 // The address of a global variable can be a static initializer.
3938 Var_expression* ve = expr->var_expression();
3939 if (ve != NULL)
3941 Named_object* no = ve->named_object();
3942 return no->is_variable() && no->var_value()->is_global();
3945 // The address of a composite literal can be used as a static
3946 // initializer if the composite literal is itself usable as a
3947 // static initializer.
3948 if (expr->is_composite_literal() && expr->is_static_initializer())
3949 return true;
3951 // The address of a string constant can be used as a static
3952 // initializer. This can not be written in Go itself but this is
3953 // used when building a type descriptor.
3954 if (expr->string_expression() != NULL)
3955 return true;
3957 return false;
3960 // Return whether this dereference expression requires an explicit nil
3961 // check. If we are dereferencing the pointer to a large struct
3962 // (greater than the specified size threshold), we need to check for
3963 // nil. We don't bother to check for small structs because we expect
3964 // the system to crash on a nil pointer dereference. However, if we
3965 // know the address of this expression is being taken, we must always
3966 // check for nil.
3967 Unary_expression::Nil_check_classification
3968 Unary_expression::requires_nil_check(Gogo* gogo)
3970 go_assert(this->op_ == OPERATOR_MULT);
3971 go_assert(this->expr_->type()->points_to() != NULL);
3973 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
3974 return NIL_CHECK_NEEDED;
3975 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
3976 return NIL_CHECK_NOT_NEEDED;
3978 Type* ptype = this->expr_->type()->points_to();
3979 int64_t type_size = -1;
3980 if (!ptype->is_void_type())
3982 bool ok = ptype->backend_type_size(gogo, &type_size);
3983 if (!ok)
3984 return NIL_CHECK_ERROR_ENCOUNTERED;
3987 int64_t size_cutoff = gogo->nil_check_size_threshold();
3988 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
3989 this->issue_nil_check_ = NIL_CHECK_NEEDED;
3990 else
3991 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
3992 return this->issue_nil_check_;
3995 // Apply unary opcode OP to UNC, setting NC. Return true if this
3996 // could be done, false if not. On overflow, issues an error and sets
3997 // *ISSUED_ERROR.
3999 bool
4000 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4001 Location location, Numeric_constant* nc,
4002 bool* issued_error)
4004 *issued_error = false;
4005 switch (op)
4007 case OPERATOR_PLUS:
4008 *nc = *unc;
4009 return true;
4011 case OPERATOR_MINUS:
4012 if (unc->is_int() || unc->is_rune())
4013 break;
4014 else if (unc->is_float())
4016 mpfr_t uval;
4017 unc->get_float(&uval);
4018 mpfr_t val;
4019 mpfr_init(val);
4020 mpfr_neg(val, uval, GMP_RNDN);
4021 nc->set_float(unc->type(), val);
4022 mpfr_clear(uval);
4023 mpfr_clear(val);
4024 return true;
4026 else if (unc->is_complex())
4028 mpc_t uval;
4029 unc->get_complex(&uval);
4030 mpc_t val;
4031 mpc_init2(val, mpc_precision);
4032 mpc_neg(val, uval, MPC_RNDNN);
4033 nc->set_complex(unc->type(), val);
4034 mpc_clear(uval);
4035 mpc_clear(val);
4036 return true;
4038 else
4039 go_unreachable();
4041 case OPERATOR_XOR:
4042 break;
4044 case OPERATOR_NOT:
4045 case OPERATOR_AND:
4046 case OPERATOR_MULT:
4047 return false;
4049 default:
4050 go_unreachable();
4053 if (!unc->is_int() && !unc->is_rune())
4054 return false;
4056 mpz_t uval;
4057 if (unc->is_rune())
4058 unc->get_rune(&uval);
4059 else
4060 unc->get_int(&uval);
4061 mpz_t val;
4062 mpz_init(val);
4064 switch (op)
4066 case OPERATOR_MINUS:
4067 mpz_neg(val, uval);
4068 break;
4070 case OPERATOR_NOT:
4071 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4072 break;
4074 case OPERATOR_XOR:
4076 Type* utype = unc->type();
4077 if (utype->integer_type() == NULL
4078 || utype->integer_type()->is_abstract())
4079 mpz_com(val, uval);
4080 else
4082 // The number of HOST_WIDE_INTs that it takes to represent
4083 // UVAL.
4084 size_t count = ((mpz_sizeinbase(uval, 2)
4085 + HOST_BITS_PER_WIDE_INT
4086 - 1)
4087 / HOST_BITS_PER_WIDE_INT);
4089 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4090 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4092 size_t obits = utype->integer_type()->bits();
4094 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4096 mpz_t adj;
4097 mpz_init_set_ui(adj, 1);
4098 mpz_mul_2exp(adj, adj, obits);
4099 mpz_add(uval, uval, adj);
4100 mpz_clear(adj);
4103 size_t ecount;
4104 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4105 go_assert(ecount <= count);
4107 // Trim down to the number of words required by the type.
4108 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4109 / HOST_BITS_PER_WIDE_INT);
4110 go_assert(ocount <= count);
4112 for (size_t i = 0; i < ocount; ++i)
4113 phwi[i] = ~phwi[i];
4115 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4116 if (clearbits != 0)
4117 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4118 >> clearbits);
4120 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4122 if (!utype->integer_type()->is_unsigned()
4123 && mpz_tstbit(val, obits - 1))
4125 mpz_t adj;
4126 mpz_init_set_ui(adj, 1);
4127 mpz_mul_2exp(adj, adj, obits);
4128 mpz_sub(val, val, adj);
4129 mpz_clear(adj);
4132 delete[] phwi;
4135 break;
4137 default:
4138 go_unreachable();
4141 if (unc->is_rune())
4142 nc->set_rune(NULL, val);
4143 else
4144 nc->set_int(NULL, val);
4146 mpz_clear(uval);
4147 mpz_clear(val);
4149 if (!nc->set_type(unc->type(), true, location))
4151 *issued_error = true;
4152 return false;
4154 return true;
4157 // Return the integral constant value of a unary expression, if it has one.
4159 bool
4160 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4162 Numeric_constant unc;
4163 if (!this->expr_->numeric_constant_value(&unc))
4164 return false;
4165 bool issued_error;
4166 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4167 nc, &issued_error);
4170 // Return the type of a unary expression.
4172 Type*
4173 Unary_expression::do_type()
4175 switch (this->op_)
4177 case OPERATOR_PLUS:
4178 case OPERATOR_MINUS:
4179 case OPERATOR_NOT:
4180 case OPERATOR_XOR:
4181 return this->expr_->type();
4183 case OPERATOR_AND:
4184 return Type::make_pointer_type(this->expr_->type());
4186 case OPERATOR_MULT:
4188 Type* subtype = this->expr_->type();
4189 Type* points_to = subtype->points_to();
4190 if (points_to == NULL)
4191 return Type::make_error_type();
4192 return points_to;
4195 default:
4196 go_unreachable();
4200 // Determine abstract types for a unary expression.
4202 void
4203 Unary_expression::do_determine_type(const Type_context* context)
4205 switch (this->op_)
4207 case OPERATOR_PLUS:
4208 case OPERATOR_MINUS:
4209 case OPERATOR_NOT:
4210 case OPERATOR_XOR:
4211 this->expr_->determine_type(context);
4212 break;
4214 case OPERATOR_AND:
4215 // Taking the address of something.
4217 Type* subtype = (context->type == NULL
4218 ? NULL
4219 : context->type->points_to());
4220 Type_context subcontext(subtype, false);
4221 this->expr_->determine_type(&subcontext);
4223 break;
4225 case OPERATOR_MULT:
4226 // Indirecting through a pointer.
4228 Type* subtype = (context->type == NULL
4229 ? NULL
4230 : Type::make_pointer_type(context->type));
4231 Type_context subcontext(subtype, false);
4232 this->expr_->determine_type(&subcontext);
4234 break;
4236 default:
4237 go_unreachable();
4241 // Check types for a unary expression.
4243 void
4244 Unary_expression::do_check_types(Gogo*)
4246 Type* type = this->expr_->type();
4247 if (type->is_error())
4249 this->set_is_error();
4250 return;
4253 switch (this->op_)
4255 case OPERATOR_PLUS:
4256 case OPERATOR_MINUS:
4257 if (type->integer_type() == NULL
4258 && type->float_type() == NULL
4259 && type->complex_type() == NULL)
4260 this->report_error(_("expected numeric type"));
4261 break;
4263 case OPERATOR_NOT:
4264 if (!type->is_boolean_type())
4265 this->report_error(_("expected boolean type"));
4266 break;
4268 case OPERATOR_XOR:
4269 if (type->integer_type() == NULL)
4270 this->report_error(_("expected integer"));
4271 break;
4273 case OPERATOR_AND:
4274 if (!this->expr_->is_addressable())
4276 if (!this->create_temp_)
4278 go_error_at(this->location(), "invalid operand for unary %<&%>");
4279 this->set_is_error();
4282 else
4283 this->expr_->issue_nil_check();
4284 break;
4286 case OPERATOR_MULT:
4287 // Indirecting through a pointer.
4288 if (type->points_to() == NULL)
4289 this->report_error(_("expected pointer"));
4290 if (type->points_to()->is_error())
4291 this->set_is_error();
4292 break;
4294 default:
4295 go_unreachable();
4299 // Get the backend representation for a unary expression.
4301 Bexpression*
4302 Unary_expression::do_get_backend(Translate_context* context)
4304 Gogo* gogo = context->gogo();
4305 Location loc = this->location();
4307 // Taking the address of a set-and-use-temporary expression requires
4308 // setting the temporary and then taking the address.
4309 if (this->op_ == OPERATOR_AND)
4311 Set_and_use_temporary_expression* sut =
4312 this->expr_->set_and_use_temporary_expression();
4313 if (sut != NULL)
4315 Temporary_statement* temp = sut->temporary();
4316 Bvariable* bvar = temp->get_backend_variable(context);
4317 Bexpression* bvar_expr =
4318 gogo->backend()->var_expression(bvar, loc);
4319 Bexpression* bval = sut->expression()->get_backend(context);
4321 Named_object* fn = context->function();
4322 go_assert(fn != NULL);
4323 Bfunction* bfn =
4324 fn->func_value()->get_or_make_decl(gogo, fn);
4325 Bstatement* bassign =
4326 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4327 Bexpression* bvar_addr =
4328 gogo->backend()->address_expression(bvar_expr, loc);
4329 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4333 Bexpression* ret;
4334 Bexpression* bexpr = this->expr_->get_backend(context);
4335 Btype* btype = this->expr_->type()->get_backend(gogo);
4336 switch (this->op_)
4338 case OPERATOR_PLUS:
4339 ret = bexpr;
4340 break;
4342 case OPERATOR_MINUS:
4343 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4344 ret = gogo->backend()->convert_expression(btype, ret, loc);
4345 break;
4347 case OPERATOR_NOT:
4348 case OPERATOR_XOR:
4349 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4350 break;
4352 case OPERATOR_AND:
4353 if (!this->create_temp_)
4355 // We should not see a non-constant constructor here; cases
4356 // where we would see one should have been moved onto the
4357 // heap at parse time. Taking the address of a nonconstant
4358 // constructor will not do what the programmer expects.
4360 go_assert(!this->expr_->is_composite_literal()
4361 || this->expr_->is_static_initializer());
4362 if (this->expr_->classification() == EXPRESSION_UNARY)
4364 Unary_expression* ue =
4365 static_cast<Unary_expression*>(this->expr_);
4366 go_assert(ue->op() != OPERATOR_AND);
4370 if (this->is_gc_root_ || this->is_slice_init_)
4372 std::string var_name;
4373 bool copy_to_heap = false;
4374 if (this->is_gc_root_)
4376 // Build a decl for a GC root variable. GC roots are mutable, so
4377 // they cannot be represented as an immutable_struct in the
4378 // backend.
4379 var_name = gogo->gc_root_name();
4381 else
4383 // Build a decl for a slice value initializer. An immutable slice
4384 // value initializer may have to be copied to the heap if it
4385 // contains pointers in a non-constant context.
4386 var_name = gogo->initializer_name();
4388 Array_type* at = this->expr_->type()->array_type();
4389 go_assert(at != NULL);
4391 // If we are not copying the value to the heap, we will only
4392 // initialize the value once, so we can use this directly
4393 // rather than copying it. In that case we can't make it
4394 // read-only, because the program is permitted to change it.
4395 copy_to_heap = context->function() != NULL;
4397 std::string asm_name(go_selectively_encode_id(var_name));
4398 Bvariable* implicit =
4399 gogo->backend()->implicit_variable(var_name, asm_name,
4400 btype, true, copy_to_heap,
4401 false, 0);
4402 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4403 true, copy_to_heap, false,
4404 bexpr);
4405 bexpr = gogo->backend()->var_expression(implicit, loc);
4407 // If we are not copying a slice initializer to the heap,
4408 // then it can be changed by the program, so if it can
4409 // contain pointers we must register it as a GC root.
4410 if (this->is_slice_init_
4411 && !copy_to_heap
4412 && this->expr_->type()->has_pointer())
4414 Bexpression* root =
4415 gogo->backend()->var_expression(implicit, loc);
4416 root = gogo->backend()->address_expression(root, loc);
4417 Type* type = Type::make_pointer_type(this->expr_->type());
4418 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4421 else if ((this->expr_->is_composite_literal()
4422 || this->expr_->string_expression() != NULL)
4423 && this->expr_->is_static_initializer())
4425 std::string var_name(gogo->initializer_name());
4426 std::string asm_name(go_selectively_encode_id(var_name));
4427 Bvariable* decl =
4428 gogo->backend()->immutable_struct(var_name, asm_name,
4429 true, false, btype, loc);
4430 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4431 false, btype, loc, bexpr);
4432 bexpr = gogo->backend()->var_expression(decl, loc);
4435 go_assert(!this->create_temp_ || this->expr_->is_variable());
4436 ret = gogo->backend()->address_expression(bexpr, loc);
4437 break;
4439 case OPERATOR_MULT:
4441 go_assert(this->expr_->type()->points_to() != NULL);
4443 bool known_valid = false;
4444 Type* ptype = this->expr_->type()->points_to();
4445 Btype* pbtype = ptype->get_backend(gogo);
4446 switch (this->requires_nil_check(gogo))
4448 case NIL_CHECK_NOT_NEEDED:
4449 break;
4450 case NIL_CHECK_ERROR_ENCOUNTERED:
4452 go_assert(saw_errors());
4453 return gogo->backend()->error_expression();
4455 case NIL_CHECK_NEEDED:
4457 go_assert(this->expr_->is_variable());
4459 // If we're nil-checking the result of a set-and-use-temporary
4460 // expression, then pick out the target temp and use that
4461 // for the final result of the conditional.
4462 Bexpression* tbexpr = bexpr;
4463 Bexpression* ubexpr = bexpr;
4464 Set_and_use_temporary_expression* sut =
4465 this->expr_->set_and_use_temporary_expression();
4466 if (sut != NULL) {
4467 Temporary_statement* temp = sut->temporary();
4468 Bvariable* bvar = temp->get_backend_variable(context);
4469 ubexpr = gogo->backend()->var_expression(bvar, loc);
4471 Bexpression* nil =
4472 Expression::make_nil(loc)->get_backend(context);
4473 Bexpression* compare =
4474 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4475 nil, loc);
4476 Bexpression* crash =
4477 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4478 loc)->get_backend(context);
4479 Bfunction* bfn = context->function()->func_value()->get_decl();
4480 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4481 compare,
4482 crash, ubexpr,
4483 loc);
4484 known_valid = true;
4485 break;
4487 case NIL_CHECK_DEFAULT:
4488 go_unreachable();
4490 ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4491 known_valid, loc);
4493 break;
4495 default:
4496 go_unreachable();
4499 return ret;
4502 // Export a unary expression.
4504 void
4505 Unary_expression::do_export(Export* exp) const
4507 switch (this->op_)
4509 case OPERATOR_PLUS:
4510 exp->write_c_string("+ ");
4511 break;
4512 case OPERATOR_MINUS:
4513 exp->write_c_string("- ");
4514 break;
4515 case OPERATOR_NOT:
4516 exp->write_c_string("! ");
4517 break;
4518 case OPERATOR_XOR:
4519 exp->write_c_string("^ ");
4520 break;
4521 case OPERATOR_AND:
4522 case OPERATOR_MULT:
4523 default:
4524 go_unreachable();
4526 this->expr_->export_expression(exp);
4529 // Import a unary expression.
4531 Expression*
4532 Unary_expression::do_import(Import* imp)
4534 Operator op;
4535 switch (imp->get_char())
4537 case '+':
4538 op = OPERATOR_PLUS;
4539 break;
4540 case '-':
4541 op = OPERATOR_MINUS;
4542 break;
4543 case '!':
4544 op = OPERATOR_NOT;
4545 break;
4546 case '^':
4547 op = OPERATOR_XOR;
4548 break;
4549 default:
4550 go_unreachable();
4552 imp->require_c_string(" ");
4553 Expression* expr = Expression::import_expression(imp);
4554 return Expression::make_unary(op, expr, imp->location());
4557 // Dump ast representation of an unary expression.
4559 void
4560 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4562 ast_dump_context->dump_operator(this->op_);
4563 ast_dump_context->ostream() << "(";
4564 ast_dump_context->dump_expression(this->expr_);
4565 ast_dump_context->ostream() << ") ";
4568 // Make a unary expression.
4570 Expression*
4571 Expression::make_unary(Operator op, Expression* expr, Location location)
4573 return new Unary_expression(op, expr, location);
4576 Expression*
4577 Expression::make_dereference(Expression* ptr,
4578 Nil_check_classification docheck,
4579 Location location)
4581 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4582 if (docheck == NIL_CHECK_NEEDED)
4583 deref->unary_expression()->set_requires_nil_check(true);
4584 else if (docheck == NIL_CHECK_NOT_NEEDED)
4585 deref->unary_expression()->set_requires_nil_check(false);
4586 return deref;
4589 // If this is an indirection through a pointer, return the expression
4590 // being pointed through. Otherwise return this.
4592 Expression*
4593 Expression::deref()
4595 if (this->classification_ == EXPRESSION_UNARY)
4597 Unary_expression* ue = static_cast<Unary_expression*>(this);
4598 if (ue->op() == OPERATOR_MULT)
4599 return ue->operand();
4601 return this;
4604 // Class Binary_expression.
4606 // Traversal.
4609 Binary_expression::do_traverse(Traverse* traverse)
4611 int t = Expression::traverse(&this->left_, traverse);
4612 if (t == TRAVERSE_EXIT)
4613 return TRAVERSE_EXIT;
4614 return Expression::traverse(&this->right_, traverse);
4617 // Return whether this expression may be used as a static initializer.
4619 bool
4620 Binary_expression::do_is_static_initializer() const
4622 if (!this->left_->is_static_initializer()
4623 || !this->right_->is_static_initializer())
4624 return false;
4626 // Addresses can be static initializers, but we can't implement
4627 // arbitray binary expressions of them.
4628 Unary_expression* lu = this->left_->unary_expression();
4629 Unary_expression* ru = this->right_->unary_expression();
4630 if (lu != NULL && lu->op() == OPERATOR_AND)
4632 if (ru != NULL && ru->op() == OPERATOR_AND)
4633 return this->op_ == OPERATOR_MINUS;
4634 else
4635 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4637 else if (ru != NULL && ru->op() == OPERATOR_AND)
4638 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4640 // Other cases should resolve in the backend.
4641 return true;
4644 // Return the type to use for a binary operation on operands of
4645 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4646 // such may be NULL or abstract.
4648 bool
4649 Binary_expression::operation_type(Operator op, Type* left_type,
4650 Type* right_type, Type** result_type)
4652 if (left_type != right_type
4653 && !left_type->is_abstract()
4654 && !right_type->is_abstract()
4655 && left_type->base() != right_type->base()
4656 && op != OPERATOR_LSHIFT
4657 && op != OPERATOR_RSHIFT)
4659 // May be a type error--let it be diagnosed elsewhere.
4660 return false;
4663 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4665 if (left_type->integer_type() != NULL)
4666 *result_type = left_type;
4667 else
4668 *result_type = Type::make_abstract_integer_type();
4670 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4671 *result_type = left_type;
4672 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4673 *result_type = right_type;
4674 else if (!left_type->is_abstract())
4675 *result_type = left_type;
4676 else if (!right_type->is_abstract())
4677 *result_type = right_type;
4678 else if (left_type->complex_type() != NULL)
4679 *result_type = left_type;
4680 else if (right_type->complex_type() != NULL)
4681 *result_type = right_type;
4682 else if (left_type->float_type() != NULL)
4683 *result_type = left_type;
4684 else if (right_type->float_type() != NULL)
4685 *result_type = right_type;
4686 else if (left_type->integer_type() != NULL
4687 && left_type->integer_type()->is_rune())
4688 *result_type = left_type;
4689 else if (right_type->integer_type() != NULL
4690 && right_type->integer_type()->is_rune())
4691 *result_type = right_type;
4692 else
4693 *result_type = left_type;
4695 return true;
4698 // Convert an integer comparison code and an operator to a boolean
4699 // value.
4701 bool
4702 Binary_expression::cmp_to_bool(Operator op, int cmp)
4704 switch (op)
4706 case OPERATOR_EQEQ:
4707 return cmp == 0;
4708 break;
4709 case OPERATOR_NOTEQ:
4710 return cmp != 0;
4711 break;
4712 case OPERATOR_LT:
4713 return cmp < 0;
4714 break;
4715 case OPERATOR_LE:
4716 return cmp <= 0;
4717 case OPERATOR_GT:
4718 return cmp > 0;
4719 case OPERATOR_GE:
4720 return cmp >= 0;
4721 default:
4722 go_unreachable();
4726 // Compare constants according to OP.
4728 bool
4729 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4730 Numeric_constant* right_nc,
4731 Location location, bool* result)
4733 Type* left_type = left_nc->type();
4734 Type* right_type = right_nc->type();
4736 Type* type;
4737 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4738 return false;
4740 // When comparing an untyped operand to a typed operand, we are
4741 // effectively coercing the untyped operand to the other operand's
4742 // type, so make sure that is valid.
4743 if (!left_nc->set_type(type, true, location)
4744 || !right_nc->set_type(type, true, location))
4745 return false;
4747 bool ret;
4748 int cmp;
4749 if (type->complex_type() != NULL)
4751 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4752 return false;
4753 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4755 else if (type->float_type() != NULL)
4756 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4757 else
4758 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4760 if (ret)
4761 *result = Binary_expression::cmp_to_bool(op, cmp);
4763 return ret;
4766 // Compare integer constants.
4768 bool
4769 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4770 const Numeric_constant* right_nc,
4771 int* cmp)
4773 mpz_t left_val;
4774 if (!left_nc->to_int(&left_val))
4775 return false;
4776 mpz_t right_val;
4777 if (!right_nc->to_int(&right_val))
4779 mpz_clear(left_val);
4780 return false;
4783 *cmp = mpz_cmp(left_val, right_val);
4785 mpz_clear(left_val);
4786 mpz_clear(right_val);
4788 return true;
4791 // Compare floating point constants.
4793 bool
4794 Binary_expression::compare_float(const Numeric_constant* left_nc,
4795 const Numeric_constant* right_nc,
4796 int* cmp)
4798 mpfr_t left_val;
4799 if (!left_nc->to_float(&left_val))
4800 return false;
4801 mpfr_t right_val;
4802 if (!right_nc->to_float(&right_val))
4804 mpfr_clear(left_val);
4805 return false;
4808 // We already coerced both operands to the same type. If that type
4809 // is not an abstract type, we need to round the values accordingly.
4810 Type* type = left_nc->type();
4811 if (!type->is_abstract() && type->float_type() != NULL)
4813 int bits = type->float_type()->bits();
4814 mpfr_prec_round(left_val, bits, GMP_RNDN);
4815 mpfr_prec_round(right_val, bits, GMP_RNDN);
4818 *cmp = mpfr_cmp(left_val, right_val);
4820 mpfr_clear(left_val);
4821 mpfr_clear(right_val);
4823 return true;
4826 // Compare complex constants. Complex numbers may only be compared
4827 // for equality.
4829 bool
4830 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4831 const Numeric_constant* right_nc,
4832 int* cmp)
4834 mpc_t left_val;
4835 if (!left_nc->to_complex(&left_val))
4836 return false;
4837 mpc_t right_val;
4838 if (!right_nc->to_complex(&right_val))
4840 mpc_clear(left_val);
4841 return false;
4844 // We already coerced both operands to the same type. If that type
4845 // is not an abstract type, we need to round the values accordingly.
4846 Type* type = left_nc->type();
4847 if (!type->is_abstract() && type->complex_type() != NULL)
4849 int bits = type->complex_type()->bits();
4850 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4851 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4852 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4853 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4856 *cmp = mpc_cmp(left_val, right_val) != 0;
4858 mpc_clear(left_val);
4859 mpc_clear(right_val);
4861 return true;
4864 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4865 // true if this could be done, false if not. Issue errors at LOCATION
4866 // as appropriate, and sets *ISSUED_ERROR if it did.
4868 bool
4869 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4870 Numeric_constant* right_nc,
4871 Location location, Numeric_constant* nc,
4872 bool* issued_error)
4874 *issued_error = false;
4875 switch (op)
4877 case OPERATOR_OROR:
4878 case OPERATOR_ANDAND:
4879 case OPERATOR_EQEQ:
4880 case OPERATOR_NOTEQ:
4881 case OPERATOR_LT:
4882 case OPERATOR_LE:
4883 case OPERATOR_GT:
4884 case OPERATOR_GE:
4885 // These return boolean values, not numeric.
4886 return false;
4887 default:
4888 break;
4891 Type* left_type = left_nc->type();
4892 Type* right_type = right_nc->type();
4894 Type* type;
4895 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4896 return false;
4898 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4900 // When combining an untyped operand with a typed operand, we are
4901 // effectively coercing the untyped operand to the other operand's
4902 // type, so make sure that is valid.
4903 if (!left_nc->set_type(type, true, location))
4904 return false;
4905 if (!is_shift && !right_nc->set_type(type, true, location))
4906 return false;
4907 if (is_shift
4908 && ((left_type->integer_type() == NULL
4909 && !left_type->is_abstract())
4910 || (right_type->integer_type() == NULL
4911 && !right_type->is_abstract())))
4912 return false;
4914 bool r;
4915 if (type->complex_type() != NULL)
4916 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4917 else if (type->float_type() != NULL)
4918 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4919 else
4920 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4922 if (r)
4924 r = nc->set_type(type, true, location);
4925 if (!r)
4926 *issued_error = true;
4929 return r;
4932 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4933 // integer operations. Return true if this could be done, false if
4934 // not.
4936 bool
4937 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4938 const Numeric_constant* right_nc,
4939 Location location, Numeric_constant* nc)
4941 mpz_t left_val;
4942 if (!left_nc->to_int(&left_val))
4943 return false;
4944 mpz_t right_val;
4945 if (!right_nc->to_int(&right_val))
4947 mpz_clear(left_val);
4948 return false;
4951 mpz_t val;
4952 mpz_init(val);
4954 switch (op)
4956 case OPERATOR_PLUS:
4957 mpz_add(val, left_val, right_val);
4958 if (mpz_sizeinbase(val, 2) > 0x100000)
4960 go_error_at(location, "constant addition overflow");
4961 nc->set_invalid();
4962 mpz_set_ui(val, 1);
4964 break;
4965 case OPERATOR_MINUS:
4966 mpz_sub(val, left_val, right_val);
4967 if (mpz_sizeinbase(val, 2) > 0x100000)
4969 go_error_at(location, "constant subtraction overflow");
4970 nc->set_invalid();
4971 mpz_set_ui(val, 1);
4973 break;
4974 case OPERATOR_OR:
4975 mpz_ior(val, left_val, right_val);
4976 break;
4977 case OPERATOR_XOR:
4978 mpz_xor(val, left_val, right_val);
4979 break;
4980 case OPERATOR_MULT:
4981 mpz_mul(val, left_val, right_val);
4982 if (mpz_sizeinbase(val, 2) > 0x100000)
4984 go_error_at(location, "constant multiplication overflow");
4985 nc->set_invalid();
4986 mpz_set_ui(val, 1);
4988 break;
4989 case OPERATOR_DIV:
4990 if (mpz_sgn(right_val) != 0)
4991 mpz_tdiv_q(val, left_val, right_val);
4992 else
4994 go_error_at(location, "division by zero");
4995 nc->set_invalid();
4996 mpz_set_ui(val, 0);
4998 break;
4999 case OPERATOR_MOD:
5000 if (mpz_sgn(right_val) != 0)
5001 mpz_tdiv_r(val, left_val, right_val);
5002 else
5004 go_error_at(location, "division by zero");
5005 nc->set_invalid();
5006 mpz_set_ui(val, 0);
5008 break;
5009 case OPERATOR_LSHIFT:
5011 unsigned long shift = mpz_get_ui(right_val);
5012 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5013 mpz_mul_2exp(val, left_val, shift);
5014 else
5016 go_error_at(location, "shift count overflow");
5017 nc->set_invalid();
5018 mpz_set_ui(val, 1);
5020 break;
5022 break;
5023 case OPERATOR_RSHIFT:
5025 unsigned long shift = mpz_get_ui(right_val);
5026 if (mpz_cmp_ui(right_val, shift) != 0)
5028 go_error_at(location, "shift count overflow");
5029 nc->set_invalid();
5030 mpz_set_ui(val, 1);
5032 else
5034 if (mpz_cmp_ui(left_val, 0) >= 0)
5035 mpz_tdiv_q_2exp(val, left_val, shift);
5036 else
5037 mpz_fdiv_q_2exp(val, left_val, shift);
5039 break;
5041 break;
5042 case OPERATOR_AND:
5043 mpz_and(val, left_val, right_val);
5044 break;
5045 case OPERATOR_BITCLEAR:
5047 mpz_t tval;
5048 mpz_init(tval);
5049 mpz_com(tval, right_val);
5050 mpz_and(val, left_val, tval);
5051 mpz_clear(tval);
5053 break;
5054 default:
5055 go_unreachable();
5058 mpz_clear(left_val);
5059 mpz_clear(right_val);
5061 if (left_nc->is_rune()
5062 || (op != OPERATOR_LSHIFT
5063 && op != OPERATOR_RSHIFT
5064 && right_nc->is_rune()))
5065 nc->set_rune(NULL, val);
5066 else
5067 nc->set_int(NULL, val);
5069 mpz_clear(val);
5071 return true;
5074 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5075 // floating point operations. Return true if this could be done,
5076 // false if not.
5078 bool
5079 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5080 const Numeric_constant* right_nc,
5081 Location location, Numeric_constant* nc)
5083 mpfr_t left_val;
5084 if (!left_nc->to_float(&left_val))
5085 return false;
5086 mpfr_t right_val;
5087 if (!right_nc->to_float(&right_val))
5089 mpfr_clear(left_val);
5090 return false;
5093 mpfr_t val;
5094 mpfr_init(val);
5096 bool ret = true;
5097 switch (op)
5099 case OPERATOR_PLUS:
5100 mpfr_add(val, left_val, right_val, GMP_RNDN);
5101 break;
5102 case OPERATOR_MINUS:
5103 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5104 break;
5105 case OPERATOR_OR:
5106 case OPERATOR_XOR:
5107 case OPERATOR_AND:
5108 case OPERATOR_BITCLEAR:
5109 case OPERATOR_MOD:
5110 case OPERATOR_LSHIFT:
5111 case OPERATOR_RSHIFT:
5112 mpfr_set_ui(val, 0, GMP_RNDN);
5113 ret = false;
5114 break;
5115 case OPERATOR_MULT:
5116 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5117 break;
5118 case OPERATOR_DIV:
5119 if (!mpfr_zero_p(right_val))
5120 mpfr_div(val, left_val, right_val, GMP_RNDN);
5121 else
5123 go_error_at(location, "division by zero");
5124 nc->set_invalid();
5125 mpfr_set_ui(val, 0, GMP_RNDN);
5127 break;
5128 default:
5129 go_unreachable();
5132 mpfr_clear(left_val);
5133 mpfr_clear(right_val);
5135 nc->set_float(NULL, val);
5136 mpfr_clear(val);
5138 return ret;
5141 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5142 // complex operations. Return true if this could be done, false if
5143 // not.
5145 bool
5146 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5147 const Numeric_constant* right_nc,
5148 Location location, Numeric_constant* nc)
5150 mpc_t left_val;
5151 if (!left_nc->to_complex(&left_val))
5152 return false;
5153 mpc_t right_val;
5154 if (!right_nc->to_complex(&right_val))
5156 mpc_clear(left_val);
5157 return false;
5160 mpc_t val;
5161 mpc_init2(val, mpc_precision);
5163 bool ret = true;
5164 switch (op)
5166 case OPERATOR_PLUS:
5167 mpc_add(val, left_val, right_val, MPC_RNDNN);
5168 break;
5169 case OPERATOR_MINUS:
5170 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5171 break;
5172 case OPERATOR_OR:
5173 case OPERATOR_XOR:
5174 case OPERATOR_AND:
5175 case OPERATOR_BITCLEAR:
5176 case OPERATOR_MOD:
5177 case OPERATOR_LSHIFT:
5178 case OPERATOR_RSHIFT:
5179 mpc_set_ui(val, 0, MPC_RNDNN);
5180 ret = false;
5181 break;
5182 case OPERATOR_MULT:
5183 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5184 break;
5185 case OPERATOR_DIV:
5186 if (mpc_cmp_si(right_val, 0) == 0)
5188 go_error_at(location, "division by zero");
5189 nc->set_invalid();
5190 mpc_set_ui(val, 0, MPC_RNDNN);
5191 break;
5193 mpc_div(val, left_val, right_val, MPC_RNDNN);
5194 break;
5195 default:
5196 go_unreachable();
5199 mpc_clear(left_val);
5200 mpc_clear(right_val);
5202 nc->set_complex(NULL, val);
5203 mpc_clear(val);
5205 return ret;
5208 // Lower a binary expression. We have to evaluate constant
5209 // expressions now, in order to implement Go's unlimited precision
5210 // constants.
5212 Expression*
5213 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5214 Statement_inserter* inserter, int)
5216 Location location = this->location();
5217 Operator op = this->op_;
5218 Expression* left = this->left_;
5219 Expression* right = this->right_;
5221 const bool is_comparison = (op == OPERATOR_EQEQ
5222 || op == OPERATOR_NOTEQ
5223 || op == OPERATOR_LT
5224 || op == OPERATOR_LE
5225 || op == OPERATOR_GT
5226 || op == OPERATOR_GE);
5228 // Numeric constant expressions.
5230 Numeric_constant left_nc;
5231 Numeric_constant right_nc;
5232 if (left->numeric_constant_value(&left_nc)
5233 && right->numeric_constant_value(&right_nc))
5235 if (is_comparison)
5237 bool result;
5238 if (!Binary_expression::compare_constant(op, &left_nc,
5239 &right_nc, location,
5240 &result))
5241 return this;
5242 return Expression::make_cast(Type::make_boolean_type(),
5243 Expression::make_boolean(result,
5244 location),
5245 location);
5247 else
5249 Numeric_constant nc;
5250 bool issued_error;
5251 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5252 location, &nc,
5253 &issued_error))
5255 if (issued_error)
5256 return Expression::make_error(location);
5257 return this;
5259 return nc.expression(location);
5264 // String constant expressions.
5265 if (left->type()->is_string_type() && right->type()->is_string_type())
5267 std::string left_string;
5268 std::string right_string;
5269 if (left->string_constant_value(&left_string)
5270 && right->string_constant_value(&right_string))
5272 if (op == OPERATOR_PLUS)
5273 return Expression::make_string(left_string + right_string,
5274 location);
5275 else if (is_comparison)
5277 int cmp = left_string.compare(right_string);
5278 bool r = Binary_expression::cmp_to_bool(op, cmp);
5279 return Expression::make_boolean(r, location);
5284 // Lower struct, array, and some interface comparisons.
5285 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5287 if (left->type()->struct_type() != NULL
5288 && right->type()->struct_type() != NULL)
5289 return this->lower_struct_comparison(gogo, inserter);
5290 else if (left->type()->array_type() != NULL
5291 && !left->type()->is_slice_type()
5292 && right->type()->array_type() != NULL
5293 && !right->type()->is_slice_type())
5294 return this->lower_array_comparison(gogo, inserter);
5295 else if ((left->type()->interface_type() != NULL
5296 && right->type()->interface_type() == NULL)
5297 || (left->type()->interface_type() == NULL
5298 && right->type()->interface_type() != NULL))
5299 return this->lower_interface_value_comparison(gogo, inserter);
5302 // Lower string concatenation to String_concat_expression, so that
5303 // we can group sequences of string additions.
5304 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5306 Expression_list* exprs;
5307 String_concat_expression* left_sce =
5308 this->left_->string_concat_expression();
5309 if (left_sce != NULL)
5310 exprs = left_sce->exprs();
5311 else
5313 exprs = new Expression_list();
5314 exprs->push_back(this->left_);
5317 String_concat_expression* right_sce =
5318 this->right_->string_concat_expression();
5319 if (right_sce != NULL)
5320 exprs->append(right_sce->exprs());
5321 else
5322 exprs->push_back(this->right_);
5324 return Expression::make_string_concat(exprs);
5327 return this;
5330 // Lower a struct comparison.
5332 Expression*
5333 Binary_expression::lower_struct_comparison(Gogo* gogo,
5334 Statement_inserter* inserter)
5336 Struct_type* st = this->left_->type()->struct_type();
5337 Struct_type* st2 = this->right_->type()->struct_type();
5338 if (st2 == NULL)
5339 return this;
5340 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5341 return this;
5342 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5343 this->right_->type(), NULL))
5344 return this;
5346 // See if we can compare using memcmp. As a heuristic, we use
5347 // memcmp rather than field references and comparisons if there are
5348 // more than two fields.
5349 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5350 return this->lower_compare_to_memcmp(gogo, inserter);
5352 Location loc = this->location();
5354 Expression* left = this->left_;
5355 Temporary_statement* left_temp = NULL;
5356 if (left->var_expression() == NULL
5357 && left->temporary_reference_expression() == NULL)
5359 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5360 inserter->insert(left_temp);
5361 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5364 Expression* right = this->right_;
5365 Temporary_statement* right_temp = NULL;
5366 if (right->var_expression() == NULL
5367 && right->temporary_reference_expression() == NULL)
5369 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5370 inserter->insert(right_temp);
5371 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5374 Expression* ret = Expression::make_boolean(true, loc);
5375 const Struct_field_list* fields = st->fields();
5376 unsigned int field_index = 0;
5377 for (Struct_field_list::const_iterator pf = fields->begin();
5378 pf != fields->end();
5379 ++pf, ++field_index)
5381 if (Gogo::is_sink_name(pf->field_name()))
5382 continue;
5384 if (field_index > 0)
5386 if (left_temp == NULL)
5387 left = left->copy();
5388 else
5389 left = Expression::make_temporary_reference(left_temp, loc);
5390 if (right_temp == NULL)
5391 right = right->copy();
5392 else
5393 right = Expression::make_temporary_reference(right_temp, loc);
5395 Expression* f1 = Expression::make_field_reference(left, field_index,
5396 loc);
5397 Expression* f2 = Expression::make_field_reference(right, field_index,
5398 loc);
5399 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5400 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5403 if (this->op_ == OPERATOR_NOTEQ)
5404 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5406 return ret;
5409 // Lower an array comparison.
5411 Expression*
5412 Binary_expression::lower_array_comparison(Gogo* gogo,
5413 Statement_inserter* inserter)
5415 Array_type* at = this->left_->type()->array_type();
5416 Array_type* at2 = this->right_->type()->array_type();
5417 if (at2 == NULL)
5418 return this;
5419 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5420 return this;
5421 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5422 this->right_->type(), NULL))
5423 return this;
5425 // Call memcmp directly if possible. This may let the middle-end
5426 // optimize the call.
5427 if (at->compare_is_identity(gogo))
5428 return this->lower_compare_to_memcmp(gogo, inserter);
5430 // Call the array comparison function.
5431 Named_object* hash_fn;
5432 Named_object* equal_fn;
5433 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5434 &hash_fn, &equal_fn);
5436 Location loc = this->location();
5438 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5440 Expression_list* args = new Expression_list();
5441 args->push_back(this->operand_address(inserter, this->left_));
5442 args->push_back(this->operand_address(inserter, this->right_));
5444 Expression* ret = Expression::make_call(func, args, false, loc);
5446 if (this->op_ == OPERATOR_NOTEQ)
5447 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5449 return ret;
5452 // Lower an interface to value comparison.
5454 Expression*
5455 Binary_expression::lower_interface_value_comparison(Gogo*,
5456 Statement_inserter* inserter)
5458 Type* left_type = this->left_->type();
5459 Type* right_type = this->right_->type();
5460 Interface_type* ift;
5461 if (left_type->interface_type() != NULL)
5463 ift = left_type->interface_type();
5464 if (!ift->implements_interface(right_type, NULL))
5465 return this;
5467 else
5469 ift = right_type->interface_type();
5470 if (!ift->implements_interface(left_type, NULL))
5471 return this;
5473 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5474 return this;
5476 Location loc = this->location();
5478 if (left_type->interface_type() == NULL
5479 && left_type->points_to() == NULL
5480 && !this->left_->is_addressable())
5482 Temporary_statement* temp =
5483 Statement::make_temporary(left_type, NULL, loc);
5484 inserter->insert(temp);
5485 this->left_ =
5486 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5489 if (right_type->interface_type() == NULL
5490 && right_type->points_to() == NULL
5491 && !this->right_->is_addressable())
5493 Temporary_statement* temp =
5494 Statement::make_temporary(right_type, NULL, loc);
5495 inserter->insert(temp);
5496 this->right_ =
5497 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5500 return this;
5503 // Lower a struct or array comparison to a call to memcmp.
5505 Expression*
5506 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5508 Location loc = this->location();
5510 Expression* a1 = this->operand_address(inserter, this->left_);
5511 Expression* a2 = this->operand_address(inserter, this->right_);
5512 Expression* len = Expression::make_type_info(this->left_->type(),
5513 TYPE_INFO_SIZE);
5515 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5516 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5517 return Expression::make_binary(this->op_, call, zero, loc);
5520 Expression*
5521 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5522 Statement_inserter* inserter)
5524 Location loc = this->location();
5525 if (this->left_->type()->is_error_type()
5526 || this->right_->type()->is_error_type()
5527 || this->left_->is_error_expression()
5528 || this->right_->is_error_expression())
5530 go_assert(saw_errors());
5531 return Expression::make_error(loc);
5534 Temporary_statement* temp;
5536 Type* left_type = this->left_->type();
5537 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5538 || this->op_ == OPERATOR_RSHIFT);
5539 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5540 left_type->integer_type() != NULL)
5541 || this->op_ == OPERATOR_MOD);
5543 if (is_shift_op
5544 || (is_idiv_op
5545 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5547 if (!this->left_->is_variable() && !this->left_->is_constant())
5549 temp = Statement::make_temporary(NULL, this->left_, loc);
5550 inserter->insert(temp);
5551 this->left_ = Expression::make_temporary_reference(temp, loc);
5553 if (!this->right_->is_variable() && !this->right_->is_constant())
5555 temp =
5556 Statement::make_temporary(NULL, this->right_, loc);
5557 this->right_ = Expression::make_temporary_reference(temp, loc);
5558 inserter->insert(temp);
5561 return this;
5565 // Return the address of EXPR, cast to unsafe.Pointer.
5567 Expression*
5568 Binary_expression::operand_address(Statement_inserter* inserter,
5569 Expression* expr)
5571 Location loc = this->location();
5573 if (!expr->is_addressable())
5575 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5576 loc);
5577 inserter->insert(temp);
5578 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5580 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5581 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5582 Type* void_type = Type::make_void_type();
5583 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5584 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5587 // Return the numeric constant value, if it has one.
5589 bool
5590 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5592 Numeric_constant left_nc;
5593 if (!this->left_->numeric_constant_value(&left_nc))
5594 return false;
5595 Numeric_constant right_nc;
5596 if (!this->right_->numeric_constant_value(&right_nc))
5597 return false;
5598 bool issued_error;
5599 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5600 this->location(), nc, &issued_error);
5603 // Note that the value is being discarded.
5605 bool
5606 Binary_expression::do_discarding_value()
5608 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5609 return this->right_->discarding_value();
5610 else
5612 this->unused_value_error();
5613 return false;
5617 // Get type.
5619 Type*
5620 Binary_expression::do_type()
5622 if (this->classification() == EXPRESSION_ERROR)
5623 return Type::make_error_type();
5625 switch (this->op_)
5627 case OPERATOR_EQEQ:
5628 case OPERATOR_NOTEQ:
5629 case OPERATOR_LT:
5630 case OPERATOR_LE:
5631 case OPERATOR_GT:
5632 case OPERATOR_GE:
5633 if (this->type_ == NULL)
5634 this->type_ = Type::make_boolean_type();
5635 return this->type_;
5637 case OPERATOR_PLUS:
5638 case OPERATOR_MINUS:
5639 case OPERATOR_OR:
5640 case OPERATOR_XOR:
5641 case OPERATOR_MULT:
5642 case OPERATOR_DIV:
5643 case OPERATOR_MOD:
5644 case OPERATOR_AND:
5645 case OPERATOR_BITCLEAR:
5646 case OPERATOR_OROR:
5647 case OPERATOR_ANDAND:
5649 Type* type;
5650 if (!Binary_expression::operation_type(this->op_,
5651 this->left_->type(),
5652 this->right_->type(),
5653 &type))
5654 return Type::make_error_type();
5655 return type;
5658 case OPERATOR_LSHIFT:
5659 case OPERATOR_RSHIFT:
5660 return this->left_->type();
5662 default:
5663 go_unreachable();
5667 // Set type for a binary expression.
5669 void
5670 Binary_expression::do_determine_type(const Type_context* context)
5672 Type* tleft = this->left_->type();
5673 Type* tright = this->right_->type();
5675 // Both sides should have the same type, except for the shift
5676 // operations. For a comparison, we should ignore the incoming
5677 // type.
5679 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5680 || this->op_ == OPERATOR_RSHIFT);
5682 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5683 || this->op_ == OPERATOR_NOTEQ
5684 || this->op_ == OPERATOR_LT
5685 || this->op_ == OPERATOR_LE
5686 || this->op_ == OPERATOR_GT
5687 || this->op_ == OPERATOR_GE);
5689 // For constant expressions, the context of the result is not useful in
5690 // determining the types of the operands. It is only legal to use abstract
5691 // boolean, numeric, and string constants as operands where it is legal to
5692 // use non-abstract boolean, numeric, and string constants, respectively.
5693 // Any issues with the operation will be resolved in the check_types pass.
5694 bool is_constant_expr = (this->left_->is_constant()
5695 && this->right_->is_constant());
5697 Type_context subcontext(*context);
5699 if (is_constant_expr && !is_shift_op)
5701 subcontext.type = NULL;
5702 subcontext.may_be_abstract = true;
5704 else if (is_comparison)
5706 // In a comparison, the context does not determine the types of
5707 // the operands.
5708 subcontext.type = NULL;
5711 // Set the context for the left hand operand.
5712 if (is_shift_op)
5714 // The right hand operand of a shift plays no role in
5715 // determining the type of the left hand operand.
5717 else if (!tleft->is_abstract())
5718 subcontext.type = tleft;
5719 else if (!tright->is_abstract())
5720 subcontext.type = tright;
5721 else if (subcontext.type == NULL)
5723 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5724 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5725 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5727 // Both sides have an abstract integer, abstract float, or
5728 // abstract complex type. Just let CONTEXT determine
5729 // whether they may remain abstract or not.
5731 else if (tleft->complex_type() != NULL)
5732 subcontext.type = tleft;
5733 else if (tright->complex_type() != NULL)
5734 subcontext.type = tright;
5735 else if (tleft->float_type() != NULL)
5736 subcontext.type = tleft;
5737 else if (tright->float_type() != NULL)
5738 subcontext.type = tright;
5739 else
5740 subcontext.type = tleft;
5742 if (subcontext.type != NULL && !context->may_be_abstract)
5743 subcontext.type = subcontext.type->make_non_abstract_type();
5746 this->left_->determine_type(&subcontext);
5748 if (is_shift_op)
5750 // We may have inherited an unusable type for the shift operand.
5751 // Give a useful error if that happened.
5752 if (tleft->is_abstract()
5753 && subcontext.type != NULL
5754 && !subcontext.may_be_abstract
5755 && subcontext.type->interface_type() == NULL
5756 && subcontext.type->integer_type() == NULL)
5757 this->report_error(("invalid context-determined non-integer type "
5758 "for left operand of shift"));
5760 // The context for the right hand operand is the same as for the
5761 // left hand operand, except for a shift operator.
5762 subcontext.type = Type::lookup_integer_type("uint");
5763 subcontext.may_be_abstract = false;
5766 this->right_->determine_type(&subcontext);
5768 if (is_comparison)
5770 if (this->type_ != NULL && !this->type_->is_abstract())
5772 else if (context->type != NULL && context->type->is_boolean_type())
5773 this->type_ = context->type;
5774 else if (!context->may_be_abstract)
5775 this->type_ = Type::lookup_bool_type();
5779 // Report an error if the binary operator OP does not support TYPE.
5780 // OTYPE is the type of the other operand. Return whether the
5781 // operation is OK. This should not be used for shift.
5783 bool
5784 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5785 Location location)
5787 switch (op)
5789 case OPERATOR_OROR:
5790 case OPERATOR_ANDAND:
5791 if (!type->is_boolean_type()
5792 || !otype->is_boolean_type())
5794 go_error_at(location, "expected boolean type");
5795 return false;
5797 break;
5799 case OPERATOR_EQEQ:
5800 case OPERATOR_NOTEQ:
5802 std::string reason;
5803 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5805 go_error_at(location, "%s", reason.c_str());
5806 return false;
5809 break;
5811 case OPERATOR_LT:
5812 case OPERATOR_LE:
5813 case OPERATOR_GT:
5814 case OPERATOR_GE:
5816 std::string reason;
5817 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5819 go_error_at(location, "%s", reason.c_str());
5820 return false;
5823 break;
5825 case OPERATOR_PLUS:
5826 case OPERATOR_PLUSEQ:
5827 if ((!type->is_numeric_type() && !type->is_string_type())
5828 || (!otype->is_numeric_type() && !otype->is_string_type()))
5830 go_error_at(location,
5831 "expected integer, floating, complex, or string type");
5832 return false;
5834 break;
5836 case OPERATOR_MINUS:
5837 case OPERATOR_MINUSEQ:
5838 case OPERATOR_MULT:
5839 case OPERATOR_MULTEQ:
5840 case OPERATOR_DIV:
5841 case OPERATOR_DIVEQ:
5842 if (!type->is_numeric_type() || !otype->is_numeric_type())
5844 go_error_at(location, "expected integer, floating, or complex type");
5845 return false;
5847 break;
5849 case OPERATOR_MOD:
5850 case OPERATOR_MODEQ:
5851 case OPERATOR_OR:
5852 case OPERATOR_OREQ:
5853 case OPERATOR_AND:
5854 case OPERATOR_ANDEQ:
5855 case OPERATOR_XOR:
5856 case OPERATOR_XOREQ:
5857 case OPERATOR_BITCLEAR:
5858 case OPERATOR_BITCLEAREQ:
5859 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5861 go_error_at(location, "expected integer type");
5862 return false;
5864 break;
5866 default:
5867 go_unreachable();
5870 return true;
5873 // Check types.
5875 void
5876 Binary_expression::do_check_types(Gogo*)
5878 if (this->classification() == EXPRESSION_ERROR)
5879 return;
5881 Type* left_type = this->left_->type();
5882 Type* right_type = this->right_->type();
5883 if (left_type->is_error() || right_type->is_error())
5885 this->set_is_error();
5886 return;
5889 if (this->op_ == OPERATOR_EQEQ
5890 || this->op_ == OPERATOR_NOTEQ
5891 || this->op_ == OPERATOR_LT
5892 || this->op_ == OPERATOR_LE
5893 || this->op_ == OPERATOR_GT
5894 || this->op_ == OPERATOR_GE)
5896 if (left_type->is_nil_type() && right_type->is_nil_type())
5898 this->report_error(_("invalid comparison of nil with nil"));
5899 return;
5901 if (!Type::are_assignable(left_type, right_type, NULL)
5902 && !Type::are_assignable(right_type, left_type, NULL))
5904 this->report_error(_("incompatible types in binary expression"));
5905 return;
5907 if (!Binary_expression::check_operator_type(this->op_, left_type,
5908 right_type,
5909 this->location())
5910 || !Binary_expression::check_operator_type(this->op_, right_type,
5911 left_type,
5912 this->location()))
5914 this->set_is_error();
5915 return;
5918 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5920 if (!Type::are_compatible_for_binop(left_type, right_type))
5922 this->report_error(_("incompatible types in binary expression"));
5923 return;
5925 if (!Binary_expression::check_operator_type(this->op_, left_type,
5926 right_type,
5927 this->location()))
5929 this->set_is_error();
5930 return;
5932 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5934 // Division by a zero integer constant is an error.
5935 Numeric_constant rconst;
5936 unsigned long rval;
5937 if (left_type->integer_type() != NULL
5938 && this->right_->numeric_constant_value(&rconst)
5939 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5940 && rval == 0)
5942 this->report_error(_("integer division by zero"));
5943 return;
5947 else
5949 if (left_type->integer_type() == NULL)
5950 this->report_error(_("shift of non-integer operand"));
5952 if (right_type->is_string_type())
5953 this->report_error(_("shift count not unsigned integer"));
5954 else if (!right_type->is_abstract()
5955 && (right_type->integer_type() == NULL
5956 || !right_type->integer_type()->is_unsigned()))
5957 this->report_error(_("shift count not unsigned integer"));
5958 else
5960 Numeric_constant nc;
5961 if (this->right_->numeric_constant_value(&nc))
5963 mpz_t val;
5964 if (!nc.to_int(&val))
5965 this->report_error(_("shift count not unsigned integer"));
5966 else
5968 if (mpz_sgn(val) < 0)
5970 this->report_error(_("negative shift count"));
5971 Location rloc = this->right_->location();
5972 this->right_ = Expression::make_integer_ul(0, right_type,
5973 rloc);
5975 mpz_clear(val);
5982 // Get the backend representation for a binary expression.
5984 Bexpression*
5985 Binary_expression::do_get_backend(Translate_context* context)
5987 Gogo* gogo = context->gogo();
5988 Location loc = this->location();
5989 Type* left_type = this->left_->type();
5990 Type* right_type = this->right_->type();
5992 bool use_left_type = true;
5993 bool is_shift_op = false;
5994 bool is_idiv_op = false;
5995 switch (this->op_)
5997 case OPERATOR_EQEQ:
5998 case OPERATOR_NOTEQ:
5999 case OPERATOR_LT:
6000 case OPERATOR_LE:
6001 case OPERATOR_GT:
6002 case OPERATOR_GE:
6003 return Expression::comparison(context, this->type_, this->op_,
6004 this->left_, this->right_, loc);
6006 case OPERATOR_OROR:
6007 case OPERATOR_ANDAND:
6008 use_left_type = false;
6009 break;
6010 case OPERATOR_PLUS:
6011 case OPERATOR_MINUS:
6012 case OPERATOR_OR:
6013 case OPERATOR_XOR:
6014 case OPERATOR_MULT:
6015 break;
6016 case OPERATOR_DIV:
6017 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6018 break;
6019 // Fall through.
6020 case OPERATOR_MOD:
6021 is_idiv_op = true;
6022 break;
6023 case OPERATOR_LSHIFT:
6024 case OPERATOR_RSHIFT:
6025 is_shift_op = true;
6026 break;
6027 case OPERATOR_BITCLEAR:
6028 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6029 case OPERATOR_AND:
6030 break;
6031 default:
6032 go_unreachable();
6035 // The only binary operation for string is +, and that should have
6036 // been converted to a String_concat_expression in do_lower.
6037 go_assert(!left_type->is_string_type());
6039 // For complex division Go might want slightly different results than the
6040 // backend implementation provides, so we have our own runtime routine.
6041 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6043 Runtime::Function complex_code;
6044 switch (this->left_->type()->complex_type()->bits())
6046 case 64:
6047 complex_code = Runtime::COMPLEX64_DIV;
6048 break;
6049 case 128:
6050 complex_code = Runtime::COMPLEX128_DIV;
6051 break;
6052 default:
6053 go_unreachable();
6055 Expression* complex_div =
6056 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6057 return complex_div->get_backend(context);
6060 Bexpression* left = this->left_->get_backend(context);
6061 Bexpression* right = this->right_->get_backend(context);
6063 Type* type = use_left_type ? left_type : right_type;
6064 Btype* btype = type->get_backend(gogo);
6066 Bexpression* ret =
6067 gogo->backend()->binary_expression(this->op_, left, right, loc);
6068 ret = gogo->backend()->convert_expression(btype, ret, loc);
6070 // Initialize overflow constants.
6071 Bexpression* overflow;
6072 mpz_t zero;
6073 mpz_init_set_ui(zero, 0UL);
6074 mpz_t one;
6075 mpz_init_set_ui(one, 1UL);
6076 mpz_t neg_one;
6077 mpz_init_set_si(neg_one, -1);
6079 Btype* left_btype = left_type->get_backend(gogo);
6080 Btype* right_btype = right_type->get_backend(gogo);
6082 // In Go, a shift larger than the size of the type is well-defined.
6083 // This is not true in C, so we need to insert a conditional.
6084 if (is_shift_op)
6086 go_assert(left_type->integer_type() != NULL);
6088 int bits = left_type->integer_type()->bits();
6090 Numeric_constant nc;
6091 unsigned long ul;
6092 if (!this->right_->numeric_constant_value(&nc)
6093 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6094 || ul >= static_cast<unsigned long>(bits))
6096 mpz_t bitsval;
6097 mpz_init_set_ui(bitsval, bits);
6098 Bexpression* bits_expr =
6099 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6100 Bexpression* compare =
6101 gogo->backend()->binary_expression(OPERATOR_LT,
6102 right, bits_expr, loc);
6104 Bexpression* zero_expr =
6105 gogo->backend()->integer_constant_expression(left_btype, zero);
6106 overflow = zero_expr;
6107 Bfunction* bfn = context->function()->func_value()->get_decl();
6108 if (this->op_ == OPERATOR_RSHIFT
6109 && !left_type->integer_type()->is_unsigned())
6111 Bexpression* neg_expr =
6112 gogo->backend()->binary_expression(OPERATOR_LT, left,
6113 zero_expr, loc);
6114 Bexpression* neg_one_expr =
6115 gogo->backend()->integer_constant_expression(left_btype,
6116 neg_one);
6117 overflow = gogo->backend()->conditional_expression(bfn,
6118 btype,
6119 neg_expr,
6120 neg_one_expr,
6121 zero_expr,
6122 loc);
6124 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6125 ret, overflow, loc);
6126 mpz_clear(bitsval);
6130 // Add checks for division by zero and division overflow as needed.
6131 if (is_idiv_op)
6133 if (gogo->check_divide_by_zero())
6135 // right == 0
6136 Bexpression* zero_expr =
6137 gogo->backend()->integer_constant_expression(right_btype, zero);
6138 Bexpression* check =
6139 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6140 right, zero_expr, loc);
6142 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6143 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6144 Bexpression* crash = gogo->runtime_error(errcode,
6145 loc)->get_backend(context);
6147 // right == 0 ? (__go_runtime_error(...), 0) : ret
6148 Bfunction* bfn = context->function()->func_value()->get_decl();
6149 ret = gogo->backend()->conditional_expression(bfn, btype,
6150 check, crash,
6151 ret, loc);
6154 if (gogo->check_divide_overflow())
6156 // right == -1
6157 // FIXME: It would be nice to say that this test is expected
6158 // to return false.
6160 Bexpression* neg_one_expr =
6161 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6162 Bexpression* check =
6163 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6164 right, neg_one_expr, loc);
6166 Bexpression* zero_expr =
6167 gogo->backend()->integer_constant_expression(btype, zero);
6168 Bexpression* one_expr =
6169 gogo->backend()->integer_constant_expression(btype, one);
6170 Bfunction* bfn = context->function()->func_value()->get_decl();
6172 if (type->integer_type()->is_unsigned())
6174 // An unsigned -1 is the largest possible number, so
6175 // dividing is always 1 or 0.
6177 Bexpression* cmp =
6178 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6179 left, right, loc);
6180 if (this->op_ == OPERATOR_DIV)
6181 overflow =
6182 gogo->backend()->conditional_expression(bfn, btype, cmp,
6183 one_expr, zero_expr,
6184 loc);
6185 else
6186 overflow =
6187 gogo->backend()->conditional_expression(bfn, btype, cmp,
6188 zero_expr, left,
6189 loc);
6191 else
6193 // Computing left / -1 is the same as computing - left,
6194 // which does not overflow since Go sets -fwrapv.
6195 if (this->op_ == OPERATOR_DIV)
6197 Expression* negate_expr =
6198 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6199 overflow = negate_expr->get_backend(context);
6201 else
6202 overflow = zero_expr;
6204 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6206 // right == -1 ? - left : ret
6207 ret = gogo->backend()->conditional_expression(bfn, btype,
6208 check, overflow,
6209 ret, loc);
6213 mpz_clear(zero);
6214 mpz_clear(one);
6215 mpz_clear(neg_one);
6216 return ret;
6219 // Export a binary expression.
6221 void
6222 Binary_expression::do_export(Export* exp) const
6224 exp->write_c_string("(");
6225 this->left_->export_expression(exp);
6226 switch (this->op_)
6228 case OPERATOR_OROR:
6229 exp->write_c_string(" || ");
6230 break;
6231 case OPERATOR_ANDAND:
6232 exp->write_c_string(" && ");
6233 break;
6234 case OPERATOR_EQEQ:
6235 exp->write_c_string(" == ");
6236 break;
6237 case OPERATOR_NOTEQ:
6238 exp->write_c_string(" != ");
6239 break;
6240 case OPERATOR_LT:
6241 exp->write_c_string(" < ");
6242 break;
6243 case OPERATOR_LE:
6244 exp->write_c_string(" <= ");
6245 break;
6246 case OPERATOR_GT:
6247 exp->write_c_string(" > ");
6248 break;
6249 case OPERATOR_GE:
6250 exp->write_c_string(" >= ");
6251 break;
6252 case OPERATOR_PLUS:
6253 exp->write_c_string(" + ");
6254 break;
6255 case OPERATOR_MINUS:
6256 exp->write_c_string(" - ");
6257 break;
6258 case OPERATOR_OR:
6259 exp->write_c_string(" | ");
6260 break;
6261 case OPERATOR_XOR:
6262 exp->write_c_string(" ^ ");
6263 break;
6264 case OPERATOR_MULT:
6265 exp->write_c_string(" * ");
6266 break;
6267 case OPERATOR_DIV:
6268 exp->write_c_string(" / ");
6269 break;
6270 case OPERATOR_MOD:
6271 exp->write_c_string(" % ");
6272 break;
6273 case OPERATOR_LSHIFT:
6274 exp->write_c_string(" << ");
6275 break;
6276 case OPERATOR_RSHIFT:
6277 exp->write_c_string(" >> ");
6278 break;
6279 case OPERATOR_AND:
6280 exp->write_c_string(" & ");
6281 break;
6282 case OPERATOR_BITCLEAR:
6283 exp->write_c_string(" &^ ");
6284 break;
6285 default:
6286 go_unreachable();
6288 this->right_->export_expression(exp);
6289 exp->write_c_string(")");
6292 // Import a binary expression.
6294 Expression*
6295 Binary_expression::do_import(Import* imp)
6297 imp->require_c_string("(");
6299 Expression* left = Expression::import_expression(imp);
6301 Operator op;
6302 if (imp->match_c_string(" || "))
6304 op = OPERATOR_OROR;
6305 imp->advance(4);
6307 else if (imp->match_c_string(" && "))
6309 op = OPERATOR_ANDAND;
6310 imp->advance(4);
6312 else if (imp->match_c_string(" == "))
6314 op = OPERATOR_EQEQ;
6315 imp->advance(4);
6317 else if (imp->match_c_string(" != "))
6319 op = OPERATOR_NOTEQ;
6320 imp->advance(4);
6322 else if (imp->match_c_string(" < "))
6324 op = OPERATOR_LT;
6325 imp->advance(3);
6327 else if (imp->match_c_string(" <= "))
6329 op = OPERATOR_LE;
6330 imp->advance(4);
6332 else if (imp->match_c_string(" > "))
6334 op = OPERATOR_GT;
6335 imp->advance(3);
6337 else if (imp->match_c_string(" >= "))
6339 op = OPERATOR_GE;
6340 imp->advance(4);
6342 else if (imp->match_c_string(" + "))
6344 op = OPERATOR_PLUS;
6345 imp->advance(3);
6347 else if (imp->match_c_string(" - "))
6349 op = OPERATOR_MINUS;
6350 imp->advance(3);
6352 else if (imp->match_c_string(" | "))
6354 op = OPERATOR_OR;
6355 imp->advance(3);
6357 else if (imp->match_c_string(" ^ "))
6359 op = OPERATOR_XOR;
6360 imp->advance(3);
6362 else if (imp->match_c_string(" * "))
6364 op = OPERATOR_MULT;
6365 imp->advance(3);
6367 else if (imp->match_c_string(" / "))
6369 op = OPERATOR_DIV;
6370 imp->advance(3);
6372 else if (imp->match_c_string(" % "))
6374 op = OPERATOR_MOD;
6375 imp->advance(3);
6377 else if (imp->match_c_string(" << "))
6379 op = OPERATOR_LSHIFT;
6380 imp->advance(4);
6382 else if (imp->match_c_string(" >> "))
6384 op = OPERATOR_RSHIFT;
6385 imp->advance(4);
6387 else if (imp->match_c_string(" & "))
6389 op = OPERATOR_AND;
6390 imp->advance(3);
6392 else if (imp->match_c_string(" &^ "))
6394 op = OPERATOR_BITCLEAR;
6395 imp->advance(4);
6397 else
6399 go_error_at(imp->location(), "unrecognized binary operator");
6400 return Expression::make_error(imp->location());
6403 Expression* right = Expression::import_expression(imp);
6405 imp->require_c_string(")");
6407 return Expression::make_binary(op, left, right, imp->location());
6410 // Dump ast representation of a binary expression.
6412 void
6413 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6415 ast_dump_context->ostream() << "(";
6416 ast_dump_context->dump_expression(this->left_);
6417 ast_dump_context->ostream() << " ";
6418 ast_dump_context->dump_operator(this->op_);
6419 ast_dump_context->ostream() << " ";
6420 ast_dump_context->dump_expression(this->right_);
6421 ast_dump_context->ostream() << ") ";
6424 // Make a binary expression.
6426 Expression*
6427 Expression::make_binary(Operator op, Expression* left, Expression* right,
6428 Location location)
6430 return new Binary_expression(op, left, right, location);
6433 // Implement a comparison.
6435 Bexpression*
6436 Expression::comparison(Translate_context* context, Type* result_type,
6437 Operator op, Expression* left, Expression* right,
6438 Location location)
6440 Type* left_type = left->type();
6441 Type* right_type = right->type();
6443 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6445 if (left_type->is_string_type() && right_type->is_string_type())
6447 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6449 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6450 left, right);
6451 right = Expression::make_boolean(true, location);
6453 else
6455 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6456 left, right);
6457 right = zexpr;
6460 else if ((left_type->interface_type() != NULL
6461 && right_type->interface_type() == NULL
6462 && !right_type->is_nil_type())
6463 || (left_type->interface_type() == NULL
6464 && !left_type->is_nil_type()
6465 && right_type->interface_type() != NULL))
6467 // Comparing an interface value to a non-interface value.
6468 if (left_type->interface_type() == NULL)
6470 std::swap(left_type, right_type);
6471 std::swap(left, right);
6474 // The right operand is not an interface. We need to take its
6475 // address if it is not a pointer.
6476 Expression* pointer_arg = NULL;
6477 if (right_type->points_to() != NULL)
6478 pointer_arg = right;
6479 else
6481 go_assert(right->is_addressable());
6482 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6483 location);
6486 Expression* descriptor =
6487 Expression::make_type_descriptor(right_type, location);
6488 left =
6489 Runtime::make_call((left_type->interface_type()->is_empty()
6490 ? Runtime::EFACEVALEQ
6491 : Runtime::IFACEVALEQ),
6492 location, 3, left, descriptor,
6493 pointer_arg);
6494 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6495 right = Expression::make_boolean(true, location);
6497 else if (left_type->interface_type() != NULL
6498 && right_type->interface_type() != NULL)
6500 Runtime::Function compare_function;
6501 if (left_type->interface_type()->is_empty()
6502 && right_type->interface_type()->is_empty())
6503 compare_function = Runtime::EFACEEQ;
6504 else if (!left_type->interface_type()->is_empty()
6505 && !right_type->interface_type()->is_empty())
6506 compare_function = Runtime::IFACEEQ;
6507 else
6509 if (left_type->interface_type()->is_empty())
6511 std::swap(left_type, right_type);
6512 std::swap(left, right);
6514 go_assert(!left_type->interface_type()->is_empty());
6515 go_assert(right_type->interface_type()->is_empty());
6516 compare_function = Runtime::IFACEEFACEEQ;
6519 left = Runtime::make_call(compare_function, location, 2, left, right);
6520 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6521 right = Expression::make_boolean(true, location);
6524 if (left_type->is_nil_type()
6525 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6527 std::swap(left_type, right_type);
6528 std::swap(left, right);
6531 if (right_type->is_nil_type())
6533 right = Expression::make_nil(location);
6534 if (left_type->array_type() != NULL
6535 && left_type->array_type()->length() == NULL)
6537 Array_type* at = left_type->array_type();
6538 bool is_lvalue = false;
6539 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6541 else if (left_type->interface_type() != NULL)
6543 // An interface is nil if the first field is nil.
6544 left = Expression::make_field_reference(left, 0, location);
6548 Bexpression* left_bexpr = left->get_backend(context);
6549 Bexpression* right_bexpr = right->get_backend(context);
6551 Gogo* gogo = context->gogo();
6552 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6553 right_bexpr, location);
6554 if (result_type != NULL)
6555 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6556 ret, location);
6557 return ret;
6560 // Class String_concat_expression.
6562 bool
6563 String_concat_expression::do_is_constant() const
6565 for (Expression_list::const_iterator pe = this->exprs_->begin();
6566 pe != this->exprs_->end();
6567 ++pe)
6569 if (!(*pe)->is_constant())
6570 return false;
6572 return true;
6575 bool
6576 String_concat_expression::do_is_static_initializer() const
6578 for (Expression_list::const_iterator pe = this->exprs_->begin();
6579 pe != this->exprs_->end();
6580 ++pe)
6582 if (!(*pe)->is_static_initializer())
6583 return false;
6585 return true;
6588 Type*
6589 String_concat_expression::do_type()
6591 Type* t = this->exprs_->front()->type();
6592 Expression_list::iterator pe = this->exprs_->begin();
6593 ++pe;
6594 for (; pe != this->exprs_->end(); ++pe)
6596 Type* t1;
6597 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6598 (*pe)->type(),
6599 &t1))
6600 return Type::make_error_type();
6601 t = t1;
6603 return t;
6606 void
6607 String_concat_expression::do_determine_type(const Type_context* context)
6609 Type_context subcontext(*context);
6610 for (Expression_list::iterator pe = this->exprs_->begin();
6611 pe != this->exprs_->end();
6612 ++pe)
6614 Type* t = (*pe)->type();
6615 if (!t->is_abstract())
6617 subcontext.type = t;
6618 break;
6621 if (subcontext.type == NULL)
6622 subcontext.type = this->exprs_->front()->type();
6623 for (Expression_list::iterator pe = this->exprs_->begin();
6624 pe != this->exprs_->end();
6625 ++pe)
6626 (*pe)->determine_type(&subcontext);
6629 void
6630 String_concat_expression::do_check_types(Gogo*)
6632 if (this->is_error_expression())
6633 return;
6634 Type* t = this->exprs_->front()->type();
6635 if (t->is_error())
6637 this->set_is_error();
6638 return;
6640 Expression_list::iterator pe = this->exprs_->begin();
6641 ++pe;
6642 for (; pe != this->exprs_->end(); ++pe)
6644 Type* t1 = (*pe)->type();
6645 if (!Type::are_compatible_for_binop(t, t1))
6647 this->report_error("incompatible types in binary expression");
6648 return;
6650 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6651 this->location()))
6653 this->set_is_error();
6654 return;
6659 Expression*
6660 String_concat_expression::do_flatten(Gogo*, Named_object*,
6661 Statement_inserter*)
6663 if (this->is_error_expression())
6664 return this;
6665 Location loc = this->location();
6666 Type* type = this->type();
6667 Expression* nil_arg = Expression::make_nil(loc);
6668 Expression* call;
6669 switch (this->exprs_->size())
6671 case 0: case 1:
6672 go_unreachable();
6674 case 2: case 3: case 4: case 5:
6676 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6677 NULL, loc);
6678 Array_type* arg_type = Type::make_array_type(type, len);
6679 arg_type->set_is_array_incomparable();
6680 Expression* arg =
6681 Expression::make_array_composite_literal(arg_type, this->exprs_,
6682 loc);
6683 Runtime::Function code;
6684 switch (this->exprs_->size())
6686 default:
6687 go_unreachable();
6688 case 2:
6689 code = Runtime::CONCATSTRING2;
6690 break;
6691 case 3:
6692 code = Runtime::CONCATSTRING3;
6693 break;
6694 case 4:
6695 code = Runtime::CONCATSTRING4;
6696 break;
6697 case 5:
6698 code = Runtime::CONCATSTRING5;
6699 break;
6701 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6703 break;
6705 default:
6707 Type* arg_type = Type::make_array_type(type, NULL);
6708 Slice_construction_expression* sce =
6709 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6710 loc);
6711 sce->set_storage_does_not_escape();
6712 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6713 sce);
6715 break;
6718 return Expression::make_cast(type, call, loc);
6721 void
6722 String_concat_expression::do_dump_expression(
6723 Ast_dump_context* ast_dump_context) const
6725 ast_dump_context->ostream() << "concat(";
6726 ast_dump_context->dump_expression_list(this->exprs_, false);
6727 ast_dump_context->ostream() << ")";
6730 Expression*
6731 Expression::make_string_concat(Expression_list* exprs)
6733 return new String_concat_expression(exprs);
6736 // Class Bound_method_expression.
6738 // Traversal.
6741 Bound_method_expression::do_traverse(Traverse* traverse)
6743 return Expression::traverse(&this->expr_, traverse);
6746 // Return the type of a bound method expression. The type of this
6747 // object is simply the type of the method with no receiver.
6749 Type*
6750 Bound_method_expression::do_type()
6752 Named_object* fn = this->method_->named_object();
6753 Function_type* fntype;
6754 if (fn->is_function())
6755 fntype = fn->func_value()->type();
6756 else if (fn->is_function_declaration())
6757 fntype = fn->func_declaration_value()->type();
6758 else
6759 return Type::make_error_type();
6760 return fntype->copy_without_receiver();
6763 // Determine the types of a method expression.
6765 void
6766 Bound_method_expression::do_determine_type(const Type_context*)
6768 Named_object* fn = this->method_->named_object();
6769 Function_type* fntype;
6770 if (fn->is_function())
6771 fntype = fn->func_value()->type();
6772 else if (fn->is_function_declaration())
6773 fntype = fn->func_declaration_value()->type();
6774 else
6775 fntype = NULL;
6776 if (fntype == NULL || !fntype->is_method())
6777 this->expr_->determine_type_no_context();
6778 else
6780 Type_context subcontext(fntype->receiver()->type(), false);
6781 this->expr_->determine_type(&subcontext);
6785 // Check the types of a method expression.
6787 void
6788 Bound_method_expression::do_check_types(Gogo*)
6790 Named_object* fn = this->method_->named_object();
6791 if (!fn->is_function() && !fn->is_function_declaration())
6793 this->report_error(_("object is not a method"));
6794 return;
6797 Function_type* fntype;
6798 if (fn->is_function())
6799 fntype = fn->func_value()->type();
6800 else if (fn->is_function_declaration())
6801 fntype = fn->func_declaration_value()->type();
6802 else
6803 go_unreachable();
6804 Type* rtype = fntype->receiver()->type()->deref();
6805 Type* etype = (this->expr_type_ != NULL
6806 ? this->expr_type_
6807 : this->expr_->type());
6808 etype = etype->deref();
6809 if (!Type::are_identical(rtype, etype, true, NULL))
6810 this->report_error(_("method type does not match object type"));
6813 // If a bound method expression is not simply called, then it is
6814 // represented as a closure. The closure will hold a single variable,
6815 // the receiver to pass to the method. The function will be a simple
6816 // thunk that pulls that value from the closure and calls the method
6817 // with the remaining arguments.
6819 // Because method values are not common, we don't build all thunks for
6820 // every methods, but instead only build them as we need them. In
6821 // particular, we even build them on demand for methods defined in
6822 // other packages.
6824 Bound_method_expression::Method_value_thunks
6825 Bound_method_expression::method_value_thunks;
6827 // Find or create the thunk for METHOD.
6829 Named_object*
6830 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6831 Named_object* fn)
6833 std::pair<Named_object*, Named_object*> val(fn, NULL);
6834 std::pair<Method_value_thunks::iterator, bool> ins =
6835 Bound_method_expression::method_value_thunks.insert(val);
6836 if (!ins.second)
6838 // We have seen this method before.
6839 go_assert(ins.first->second != NULL);
6840 return ins.first->second;
6843 Location loc = fn->location();
6845 Function_type* orig_fntype;
6846 if (fn->is_function())
6847 orig_fntype = fn->func_value()->type();
6848 else if (fn->is_function_declaration())
6849 orig_fntype = fn->func_declaration_value()->type();
6850 else
6851 orig_fntype = NULL;
6853 if (orig_fntype == NULL || !orig_fntype->is_method())
6855 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6856 return ins.first->second;
6859 Struct_field_list* sfl = new Struct_field_list();
6860 // The type here is wrong--it should be the C function type. But it
6861 // doesn't really matter.
6862 Type* vt = Type::make_pointer_type(Type::make_void_type());
6863 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6864 sfl->push_back(Struct_field(Typed_identifier("val.1",
6865 orig_fntype->receiver()->type(),
6866 loc)));
6867 Struct_type* st = Type::make_struct_type(sfl, loc);
6868 st->set_is_struct_incomparable();
6869 Type* closure_type = Type::make_pointer_type(st);
6871 Function_type* new_fntype = orig_fntype->copy_with_names();
6873 std::string thunk_name = Gogo::thunk_name();
6874 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6875 false, loc);
6877 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6878 cvar->set_is_used();
6879 cvar->set_is_closure();
6880 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6881 NULL, cvar);
6882 new_no->func_value()->set_closure_var(cp);
6884 gogo->start_block(loc);
6886 // Field 0 of the closure is the function code pointer, field 1 is
6887 // the value on which to invoke the method.
6888 Expression* arg = Expression::make_var_reference(cp, loc);
6889 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
6890 arg = Expression::make_field_reference(arg, 1, loc);
6892 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6894 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6895 Expression_list* args;
6896 if (orig_params == NULL || orig_params->empty())
6897 args = NULL;
6898 else
6900 const Typed_identifier_list* new_params = new_fntype->parameters();
6901 args = new Expression_list();
6902 for (Typed_identifier_list::const_iterator p = new_params->begin();
6903 p != new_params->end();
6904 ++p)
6906 Named_object* p_no = gogo->lookup(p->name(), NULL);
6907 go_assert(p_no != NULL
6908 && p_no->is_variable()
6909 && p_no->var_value()->is_parameter());
6910 args->push_back(Expression::make_var_reference(p_no, loc));
6914 Call_expression* call = Expression::make_call(bme, args,
6915 orig_fntype->is_varargs(),
6916 loc);
6917 call->set_varargs_are_lowered();
6919 Statement* s = Statement::make_return_from_call(call, loc);
6920 gogo->add_statement(s);
6921 Block* b = gogo->finish_block(loc);
6922 gogo->add_block(b, loc);
6923 gogo->lower_block(new_no, b);
6924 gogo->flatten_block(new_no, b);
6925 gogo->finish_function(loc);
6927 ins.first->second = new_no;
6928 return new_no;
6931 // Return an expression to check *REF for nil while dereferencing
6932 // according to FIELD_INDEXES. Update *REF to build up the field
6933 // reference. This is a static function so that we don't have to
6934 // worry about declaring Field_indexes in expressions.h.
6936 static Expression*
6937 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6938 Expression** ref)
6940 if (field_indexes == NULL)
6941 return Expression::make_boolean(false, loc);
6942 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6943 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6944 go_assert(stype != NULL
6945 && field_indexes->field_index < stype->field_count());
6946 if ((*ref)->type()->struct_type() == NULL)
6948 go_assert((*ref)->type()->points_to() != NULL);
6949 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6950 Expression::make_nil(loc),
6951 loc);
6952 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6953 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
6954 loc);
6955 go_assert((*ref)->type()->struct_type() == stype);
6957 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6958 loc);
6959 return cond;
6962 // Flatten a method value into a struct with nil checks. We can't do
6963 // this in the lowering phase, because if the method value is called
6964 // directly we don't need a thunk. That case will have been handled
6965 // by Call_expression::do_lower, so if we get here then we do need a
6966 // thunk.
6968 Expression*
6969 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6970 Statement_inserter* inserter)
6972 Location loc = this->location();
6974 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
6975 this->method_,
6976 this->function_);
6977 if (thunk->is_erroneous())
6979 go_assert(saw_errors());
6980 return Expression::make_error(loc);
6983 // Force the expression into a variable. This is only necessary if
6984 // we are going to do nil checks below, but it's easy enough to
6985 // always do it.
6986 Expression* expr = this->expr_;
6987 if (!expr->is_variable())
6989 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6990 inserter->insert(etemp);
6991 expr = Expression::make_temporary_reference(etemp, loc);
6994 // If the method expects a value, and we have a pointer, we need to
6995 // dereference the pointer.
6997 Named_object* fn = this->method_->named_object();
6998 Function_type *fntype;
6999 if (fn->is_function())
7000 fntype = fn->func_value()->type();
7001 else if (fn->is_function_declaration())
7002 fntype = fn->func_declaration_value()->type();
7003 else
7004 go_unreachable();
7006 Expression* val = expr;
7007 if (fntype->receiver()->type()->points_to() == NULL
7008 && val->type()->points_to() != NULL)
7009 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7011 // Note that we are ignoring this->expr_type_ here. The thunk will
7012 // expect a closure whose second field has type this->expr_type_ (if
7013 // that is not NULL). We are going to pass it a closure whose
7014 // second field has type this->expr_->type(). Since
7015 // this->expr_type_ is only not-NULL for pointer types, we can get
7016 // away with this.
7018 Struct_field_list* fields = new Struct_field_list();
7019 fields->push_back(Struct_field(Typed_identifier("fn.0",
7020 thunk->func_value()->type(),
7021 loc)));
7022 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
7023 Struct_type* st = Type::make_struct_type(fields, loc);
7024 st->set_is_struct_incomparable();
7026 Expression_list* vals = new Expression_list();
7027 vals->push_back(Expression::make_func_code_reference(thunk, loc));
7028 vals->push_back(val);
7030 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7032 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
7034 ret = Expression::make_heap_expression(ret, loc);
7035 Node* n = Node::make_node(this);
7036 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7037 ret->heap_expression()->set_allocate_on_stack();
7039 else
7041 // When compiling the runtime, method closures do not escape.
7042 // When escape analysis becomes the default, and applies to
7043 // method closures, this should be changed to make it an error
7044 // if a method closure escapes.
7045 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
7046 inserter->insert(ctemp);
7047 ret = Expression::make_temporary_reference(ctemp, loc);
7048 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
7049 ret->unary_expression()->set_does_not_escape();
7052 // If necessary, check whether the expression or any embedded
7053 // pointers are nil.
7055 Expression* nil_check = NULL;
7056 if (this->method_->field_indexes() != NULL)
7058 Expression* ref = expr;
7059 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7060 expr = ref;
7063 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7065 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7066 Expression::make_nil(loc),
7067 loc);
7068 if (nil_check == NULL)
7069 nil_check = n;
7070 else
7071 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7074 if (nil_check != NULL)
7076 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7077 loc);
7078 // Fix the type of the conditional expression by pretending to
7079 // evaluate to RET either way through the conditional.
7080 crash = Expression::make_compound(crash, ret, loc);
7081 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7084 // RET is a pointer to a struct, but we want a function type.
7085 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7087 return ret;
7090 // Dump ast representation of a bound method expression.
7092 void
7093 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7094 const
7096 if (this->expr_type_ != NULL)
7097 ast_dump_context->ostream() << "(";
7098 ast_dump_context->dump_expression(this->expr_);
7099 if (this->expr_type_ != NULL)
7101 ast_dump_context->ostream() << ":";
7102 ast_dump_context->dump_type(this->expr_type_);
7103 ast_dump_context->ostream() << ")";
7106 ast_dump_context->ostream() << "." << this->function_->name();
7109 // Make a method expression.
7111 Bound_method_expression*
7112 Expression::make_bound_method(Expression* expr, const Method* method,
7113 Named_object* function, Location location)
7115 return new Bound_method_expression(expr, method, function, location);
7118 // Class Builtin_call_expression. This is used for a call to a
7119 // builtin function.
7121 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7122 Expression* fn,
7123 Expression_list* args,
7124 bool is_varargs,
7125 Location location)
7126 : Call_expression(fn, args, is_varargs, location),
7127 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7128 recover_arg_is_set_(false)
7130 Func_expression* fnexp = this->fn()->func_expression();
7131 if (fnexp == NULL)
7133 this->code_ = BUILTIN_INVALID;
7134 return;
7136 const std::string& name(fnexp->named_object()->name());
7137 if (name == "append")
7138 this->code_ = BUILTIN_APPEND;
7139 else if (name == "cap")
7140 this->code_ = BUILTIN_CAP;
7141 else if (name == "close")
7142 this->code_ = BUILTIN_CLOSE;
7143 else if (name == "complex")
7144 this->code_ = BUILTIN_COMPLEX;
7145 else if (name == "copy")
7146 this->code_ = BUILTIN_COPY;
7147 else if (name == "delete")
7148 this->code_ = BUILTIN_DELETE;
7149 else if (name == "imag")
7150 this->code_ = BUILTIN_IMAG;
7151 else if (name == "len")
7152 this->code_ = BUILTIN_LEN;
7153 else if (name == "make")
7154 this->code_ = BUILTIN_MAKE;
7155 else if (name == "new")
7156 this->code_ = BUILTIN_NEW;
7157 else if (name == "panic")
7158 this->code_ = BUILTIN_PANIC;
7159 else if (name == "print")
7160 this->code_ = BUILTIN_PRINT;
7161 else if (name == "println")
7162 this->code_ = BUILTIN_PRINTLN;
7163 else if (name == "real")
7164 this->code_ = BUILTIN_REAL;
7165 else if (name == "recover")
7166 this->code_ = BUILTIN_RECOVER;
7167 else if (name == "Alignof")
7168 this->code_ = BUILTIN_ALIGNOF;
7169 else if (name == "Offsetof")
7170 this->code_ = BUILTIN_OFFSETOF;
7171 else if (name == "Sizeof")
7172 this->code_ = BUILTIN_SIZEOF;
7173 else
7174 go_unreachable();
7177 // Return whether this is a call to recover. This is a virtual
7178 // function called from the parent class.
7180 bool
7181 Builtin_call_expression::do_is_recover_call() const
7183 if (this->classification() == EXPRESSION_ERROR)
7184 return false;
7185 return this->code_ == BUILTIN_RECOVER;
7188 // Set the argument for a call to recover.
7190 void
7191 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7193 const Expression_list* args = this->args();
7194 go_assert(args == NULL || args->empty());
7195 Expression_list* new_args = new Expression_list();
7196 new_args->push_back(arg);
7197 this->set_args(new_args);
7198 this->recover_arg_is_set_ = true;
7201 // Lower a builtin call expression. This turns new and make into
7202 // specific expressions. We also convert to a constant if we can.
7204 Expression*
7205 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7206 Statement_inserter* inserter, int)
7208 if (this->is_error_expression())
7209 return this;
7211 Location loc = this->location();
7213 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7215 this->report_error(_("invalid use of %<...%> with builtin function"));
7216 return Expression::make_error(loc);
7219 if (this->code_ == BUILTIN_OFFSETOF)
7221 Expression* arg = this->one_arg();
7223 if (arg->bound_method_expression() != NULL
7224 || arg->interface_field_reference_expression() != NULL)
7226 this->report_error(_("invalid use of method value as argument "
7227 "of Offsetof"));
7228 return this;
7231 Field_reference_expression* farg = arg->field_reference_expression();
7232 while (farg != NULL)
7234 if (!farg->implicit())
7235 break;
7236 // When the selector refers to an embedded field,
7237 // it must not be reached through pointer indirections.
7238 if (farg->expr()->deref() != farg->expr())
7240 this->report_error(_("argument of Offsetof implies "
7241 "indirection of an embedded field"));
7242 return this;
7244 // Go up until we reach the original base.
7245 farg = farg->expr()->field_reference_expression();
7249 if (this->is_constant())
7251 Numeric_constant nc;
7252 if (this->numeric_constant_value(&nc))
7253 return nc.expression(loc);
7256 switch (this->code_)
7258 default:
7259 break;
7261 case BUILTIN_NEW:
7263 const Expression_list* args = this->args();
7264 if (args == NULL || args->size() < 1)
7265 this->report_error(_("not enough arguments"));
7266 else if (args->size() > 1)
7267 this->report_error(_("too many arguments"));
7268 else
7270 Expression* arg = args->front();
7271 if (!arg->is_type_expression())
7273 go_error_at(arg->location(), "expected type");
7274 this->set_is_error();
7276 else
7277 return Expression::make_allocation(arg->type(), loc);
7280 break;
7282 case BUILTIN_MAKE:
7283 return this->lower_make(inserter);
7285 case BUILTIN_RECOVER:
7286 if (function != NULL)
7287 function->func_value()->set_calls_recover();
7288 else
7290 // Calling recover outside of a function always returns the
7291 // nil empty interface.
7292 Type* eface = Type::make_empty_interface_type(loc);
7293 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7295 break;
7297 case BUILTIN_DELETE:
7299 // Lower to a runtime function call.
7300 const Expression_list* args = this->args();
7301 if (args == NULL || args->size() < 2)
7302 this->report_error(_("not enough arguments"));
7303 else if (args->size() > 2)
7304 this->report_error(_("too many arguments"));
7305 else if (args->front()->type()->map_type() == NULL)
7306 this->report_error(_("argument 1 must be a map"));
7307 else
7309 // Since this function returns no value it must appear in
7310 // a statement by itself, so we don't have to worry about
7311 // order of evaluation of values around it. Evaluate the
7312 // map first to get order of evaluation right.
7313 Map_type* mt = args->front()->type()->map_type();
7314 Temporary_statement* map_temp =
7315 Statement::make_temporary(mt, args->front(), loc);
7316 inserter->insert(map_temp);
7318 Temporary_statement* key_temp =
7319 Statement::make_temporary(mt->key_type(), args->back(), loc);
7320 inserter->insert(key_temp);
7322 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7323 Expression* e2 = Expression::make_temporary_reference(map_temp,
7324 loc);
7325 Expression* e3 = Expression::make_temporary_reference(key_temp,
7326 loc);
7327 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7328 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7329 3, e1, e2, e3);
7332 break;
7334 case BUILTIN_PRINT:
7335 case BUILTIN_PRINTLN:
7336 // Force all the arguments into temporary variables, so that we
7337 // don't try to evaluate something while holding the print lock.
7338 if (this->args() == NULL)
7339 break;
7340 for (Expression_list::iterator pa = this->args()->begin();
7341 pa != this->args()->end();
7342 ++pa)
7344 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7346 Temporary_statement* temp =
7347 Statement::make_temporary(NULL, *pa, loc);
7348 inserter->insert(temp);
7349 *pa = Expression::make_temporary_reference(temp, loc);
7352 break;
7355 return this;
7358 // Flatten a builtin call expression. This turns the arguments of copy and
7359 // append into temporary expressions.
7361 Expression*
7362 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7363 Statement_inserter* inserter)
7365 Location loc = this->location();
7367 switch (this->code_)
7369 default:
7370 break;
7372 case BUILTIN_APPEND:
7373 return this->flatten_append(gogo, function, inserter);
7375 case BUILTIN_COPY:
7377 Type* at = this->args()->front()->type();
7378 for (Expression_list::iterator pa = this->args()->begin();
7379 pa != this->args()->end();
7380 ++pa)
7382 if ((*pa)->is_nil_expression())
7384 Expression* nil = Expression::make_nil(loc);
7385 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7386 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7388 if (!(*pa)->is_variable())
7390 Temporary_statement* temp =
7391 Statement::make_temporary(NULL, *pa, loc);
7392 inserter->insert(temp);
7393 *pa = Expression::make_temporary_reference(temp, loc);
7397 break;
7399 case BUILTIN_PANIC:
7400 for (Expression_list::iterator pa = this->args()->begin();
7401 pa != this->args()->end();
7402 ++pa)
7404 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7406 Temporary_statement* temp =
7407 Statement::make_temporary(NULL, *pa, loc);
7408 inserter->insert(temp);
7409 *pa = Expression::make_temporary_reference(temp, loc);
7412 break;
7414 case BUILTIN_LEN:
7415 case BUILTIN_CAP:
7417 Expression_list::iterator pa = this->args()->begin();
7418 if (!(*pa)->is_variable()
7419 && ((*pa)->type()->map_type() != NULL
7420 || (*pa)->type()->channel_type() != NULL))
7422 Temporary_statement* temp =
7423 Statement::make_temporary(NULL, *pa, loc);
7424 inserter->insert(temp);
7425 *pa = Expression::make_temporary_reference(temp, loc);
7428 break;
7431 return this;
7434 // Lower a make expression.
7436 Expression*
7437 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7439 Location loc = this->location();
7441 const Expression_list* args = this->args();
7442 if (args == NULL || args->size() < 1)
7444 this->report_error(_("not enough arguments"));
7445 return Expression::make_error(this->location());
7448 Expression_list::const_iterator parg = args->begin();
7450 Expression* first_arg = *parg;
7451 if (!first_arg->is_type_expression())
7453 go_error_at(first_arg->location(), "expected type");
7454 this->set_is_error();
7455 return Expression::make_error(this->location());
7457 Type* type = first_arg->type();
7459 if (!type->in_heap())
7460 go_error_at(first_arg->location(),
7461 "can't make slice of go:notinheap type");
7463 bool is_slice = false;
7464 bool is_map = false;
7465 bool is_chan = false;
7466 if (type->is_slice_type())
7467 is_slice = true;
7468 else if (type->map_type() != NULL)
7469 is_map = true;
7470 else if (type->channel_type() != NULL)
7471 is_chan = true;
7472 else
7474 this->report_error(_("invalid type for make function"));
7475 return Expression::make_error(this->location());
7478 Type_context int_context(Type::lookup_integer_type("int"), false);
7480 ++parg;
7481 Expression* len_arg;
7482 bool len_small = false;
7483 if (parg == args->end())
7485 if (is_slice)
7487 this->report_error(_("length required when allocating a slice"));
7488 return Expression::make_error(this->location());
7490 len_arg = Expression::make_integer_ul(0, NULL, loc);
7491 len_small = true;
7493 else
7495 len_arg = *parg;
7496 len_arg->determine_type(&int_context);
7497 if (!this->check_int_value(len_arg, true, &len_small))
7498 return Expression::make_error(this->location());
7499 ++parg;
7502 Expression* cap_arg = NULL;
7503 bool cap_small = false;
7504 Numeric_constant nclen;
7505 Numeric_constant nccap;
7506 unsigned long vlen;
7507 unsigned long vcap;
7508 if (is_slice && parg != args->end())
7510 cap_arg = *parg;
7511 cap_arg->determine_type(&int_context);
7512 if (!this->check_int_value(cap_arg, false, &cap_small))
7513 return Expression::make_error(this->location());
7515 if (len_arg->numeric_constant_value(&nclen)
7516 && cap_arg->numeric_constant_value(&nccap)
7517 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7518 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7519 && vlen > vcap)
7521 this->report_error(_("len larger than cap"));
7522 return Expression::make_error(this->location());
7525 ++parg;
7528 if (parg != args->end())
7530 this->report_error(_("too many arguments to make"));
7531 return Expression::make_error(this->location());
7534 Location type_loc = first_arg->location();
7536 Expression* call;
7537 if (is_slice)
7539 if (cap_arg == NULL)
7541 cap_small = len_small;
7542 if (len_arg->numeric_constant_value(&nclen)
7543 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID)
7544 cap_arg = Expression::make_integer_ul(vlen, len_arg->type(), loc);
7545 else
7547 Temporary_statement* temp = Statement::make_temporary(NULL,
7548 len_arg,
7549 loc);
7550 inserter->insert(temp);
7551 len_arg = Expression::make_temporary_reference(temp, loc);
7552 cap_arg = Expression::make_temporary_reference(temp, loc);
7556 Type* et = type->array_type()->element_type();
7557 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7558 Runtime::Function code = Runtime::MAKESLICE;
7559 if (!len_small || !cap_small)
7560 code = Runtime::MAKESLICE64;
7561 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
7563 else if (is_map)
7565 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7566 if (!len_small)
7567 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7568 len_arg,
7569 Expression::make_nil(loc));
7570 else
7572 Numeric_constant nclen;
7573 unsigned long vlen;
7574 if (len_arg->numeric_constant_value(&nclen)
7575 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7576 && vlen <= Map_type::bucket_size)
7577 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7578 else
7579 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7580 len_arg,
7581 Expression::make_nil(loc));
7584 else if (is_chan)
7586 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7587 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7589 else
7590 go_unreachable();
7592 return Expression::make_unsafe_cast(type, call, loc);
7595 // Flatten a call to the predeclared append function. We do this in
7596 // the flatten phase, not the lowering phase, so that we run after
7597 // type checking and after order_evaluations.
7599 Expression*
7600 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7601 Statement_inserter* inserter)
7603 if (this->is_error_expression())
7604 return this;
7606 Location loc = this->location();
7608 const Expression_list* args = this->args();
7609 go_assert(args != NULL && !args->empty());
7611 Type* slice_type = args->front()->type();
7612 go_assert(slice_type->is_slice_type());
7613 Type* element_type = slice_type->array_type()->element_type();
7615 if (args->size() == 1)
7617 // append(s) evaluates to s.
7618 return args->front();
7621 Type* int_type = Type::lookup_integer_type("int");
7622 Type* uint_type = Type::lookup_integer_type("uint");
7624 // Implementing
7625 // append(s1, s2...)
7626 // or
7627 // append(s1, a1, a2, a3, ...)
7629 // s1tmp := s1
7630 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7631 loc);
7632 inserter->insert(s1tmp);
7634 // l1tmp := len(s1tmp)
7635 Named_object* lenfn = gogo->lookup_global("len");
7636 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7637 Expression_list* call_args = new Expression_list();
7638 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7639 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7640 gogo->lower_expression(function, inserter, &len);
7641 gogo->flatten_expression(function, inserter, &len);
7642 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7643 inserter->insert(l1tmp);
7645 Temporary_statement* s2tmp = NULL;
7646 Temporary_statement* l2tmp = NULL;
7647 Expression_list* add = NULL;
7648 Expression* len2;
7649 if (this->is_varargs())
7651 go_assert(args->size() == 2);
7653 // s2tmp := s2
7654 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7655 inserter->insert(s2tmp);
7657 // l2tmp := len(s2tmp)
7658 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7659 call_args = new Expression_list();
7660 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7661 len = Expression::make_call(lenref, call_args, false, loc);
7662 gogo->lower_expression(function, inserter, &len);
7663 gogo->flatten_expression(function, inserter, &len);
7664 l2tmp = Statement::make_temporary(int_type, len, loc);
7665 inserter->insert(l2tmp);
7667 // len2 = l2tmp
7668 len2 = Expression::make_temporary_reference(l2tmp, loc);
7670 else
7672 // We have to ensure that all the arguments are in variables
7673 // now, because otherwise if one of them is an index expression
7674 // into the current slice we could overwrite it before we fetch
7675 // it.
7676 add = new Expression_list();
7677 Expression_list::const_iterator pa = args->begin();
7678 for (++pa; pa != args->end(); ++pa)
7680 if ((*pa)->is_variable())
7681 add->push_back(*pa);
7682 else
7684 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7685 loc);
7686 inserter->insert(tmp);
7687 add->push_back(Expression::make_temporary_reference(tmp, loc));
7691 // len2 = len(add)
7692 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7695 // ntmp := l1tmp + len2
7696 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7697 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7698 gogo->lower_expression(function, inserter, &sum);
7699 gogo->flatten_expression(function, inserter, &sum);
7700 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7701 inserter->insert(ntmp);
7703 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7704 // growslice(type, s1tmp, ntmp) :
7705 // s1tmp[:ntmp]
7706 // Using uint here means that if the computation of ntmp overflowed,
7707 // we will call growslice which will panic.
7709 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7710 left = Expression::make_cast(uint_type, left, loc);
7712 Named_object* capfn = gogo->lookup_global("cap");
7713 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7714 call_args = new Expression_list();
7715 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7716 Expression* right = Expression::make_call(capref, call_args, false, loc);
7717 right = Expression::make_cast(uint_type, right, loc);
7719 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7721 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7722 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7723 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7724 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7725 a1, a2, a3);
7726 call = Expression::make_unsafe_cast(slice_type, call, loc);
7728 ref = Expression::make_temporary_reference(s1tmp, loc);
7729 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7730 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7731 // FIXME: Mark this index as not requiring bounds checks.
7732 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7734 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7736 gogo->lower_expression(function, inserter, &rhs);
7737 gogo->flatten_expression(function, inserter, &rhs);
7739 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7740 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7741 inserter->insert(assign);
7743 if (this->is_varargs())
7745 // copy(s1tmp[l1tmp:], s2tmp)
7746 a1 = Expression::make_temporary_reference(s1tmp, loc);
7747 ref = Expression::make_temporary_reference(l1tmp, loc);
7748 Expression* nil = Expression::make_nil(loc);
7749 // FIXME: Mark this index as not requiring bounds checks.
7750 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7752 a2 = Expression::make_temporary_reference(s2tmp, loc);
7754 Named_object* copyfn = gogo->lookup_global("copy");
7755 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7756 call_args = new Expression_list();
7757 call_args->push_back(a1);
7758 call_args->push_back(a2);
7759 call = Expression::make_call(copyref, call_args, false, loc);
7760 gogo->lower_expression(function, inserter, &call);
7761 gogo->flatten_expression(function, inserter, &call);
7762 inserter->insert(Statement::make_statement(call, false));
7764 else
7766 // For each argument:
7767 // s1tmp[l1tmp+i] = a
7768 unsigned long i = 0;
7769 for (Expression_list::const_iterator pa = add->begin();
7770 pa != add->end();
7771 ++pa, ++i)
7773 ref = Expression::make_temporary_reference(s1tmp, loc);
7774 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7775 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7776 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7777 // FIXME: Mark this index as not requiring bounds checks.
7778 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7779 gogo->lower_expression(function, inserter, &lhs);
7780 gogo->flatten_expression(function, inserter, &lhs);
7781 // The flatten pass runs after the write barrier pass, so we
7782 // need to insert a write barrier here if necessary.
7783 if (!gogo->assign_needs_write_barrier(lhs))
7784 assign = Statement::make_assignment(lhs, *pa, loc);
7785 else
7787 Function* f = function == NULL ? NULL : function->func_value();
7788 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7789 lhs, *pa, loc);
7791 inserter->insert(assign);
7795 return Expression::make_temporary_reference(s1tmp, loc);
7798 // Return whether an expression has an integer value. Report an error
7799 // if not. This is used when handling calls to the predeclared make
7800 // function. Set *SMALL if the value is known to fit in type "int".
7802 bool
7803 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7804 bool *small)
7806 *small = false;
7808 Numeric_constant nc;
7809 if (e->numeric_constant_value(&nc))
7811 unsigned long v;
7812 switch (nc.to_unsigned_long(&v))
7814 case Numeric_constant::NC_UL_VALID:
7815 break;
7816 case Numeric_constant::NC_UL_NOTINT:
7817 go_error_at(e->location(), "non-integer %s argument to make",
7818 is_length ? "len" : "cap");
7819 return false;
7820 case Numeric_constant::NC_UL_NEGATIVE:
7821 go_error_at(e->location(), "negative %s argument to make",
7822 is_length ? "len" : "cap");
7823 return false;
7824 case Numeric_constant::NC_UL_BIG:
7825 // We don't want to give a compile-time error for a 64-bit
7826 // value on a 32-bit target.
7827 break;
7830 mpz_t val;
7831 if (!nc.to_int(&val))
7832 go_unreachable();
7833 int bits = mpz_sizeinbase(val, 2);
7834 mpz_clear(val);
7835 Type* int_type = Type::lookup_integer_type("int");
7836 if (bits >= int_type->integer_type()->bits())
7838 go_error_at(e->location(), "%s argument too large for make",
7839 is_length ? "len" : "cap");
7840 return false;
7843 *small = true;
7844 return true;
7847 if (e->type()->integer_type() != NULL)
7849 int ebits = e->type()->integer_type()->bits();
7850 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7852 // We can treat ebits == intbits as small even for an unsigned
7853 // integer type, because we will convert the value to int and
7854 // then reject it in the runtime if it is negative.
7855 *small = ebits <= intbits;
7857 return true;
7860 go_error_at(e->location(), "non-integer %s argument to make",
7861 is_length ? "len" : "cap");
7862 return false;
7865 // Return the type of the real or imag functions, given the type of
7866 // the argument. We need to map complex64 to float32 and complex128
7867 // to float64, so it has to be done by name. This returns NULL if it
7868 // can't figure out the type.
7870 Type*
7871 Builtin_call_expression::real_imag_type(Type* arg_type)
7873 if (arg_type == NULL || arg_type->is_abstract())
7874 return NULL;
7875 Named_type* nt = arg_type->named_type();
7876 if (nt == NULL)
7877 return NULL;
7878 while (nt->real_type()->named_type() != NULL)
7879 nt = nt->real_type()->named_type();
7880 if (nt->name() == "complex64")
7881 return Type::lookup_float_type("float32");
7882 else if (nt->name() == "complex128")
7883 return Type::lookup_float_type("float64");
7884 else
7885 return NULL;
7888 // Return the type of the complex function, given the type of one of the
7889 // argments. Like real_imag_type, we have to map by name.
7891 Type*
7892 Builtin_call_expression::complex_type(Type* arg_type)
7894 if (arg_type == NULL || arg_type->is_abstract())
7895 return NULL;
7896 Named_type* nt = arg_type->named_type();
7897 if (nt == NULL)
7898 return NULL;
7899 while (nt->real_type()->named_type() != NULL)
7900 nt = nt->real_type()->named_type();
7901 if (nt->name() == "float32")
7902 return Type::lookup_complex_type("complex64");
7903 else if (nt->name() == "float64")
7904 return Type::lookup_complex_type("complex128");
7905 else
7906 return NULL;
7909 // Return a single argument, or NULL if there isn't one.
7911 Expression*
7912 Builtin_call_expression::one_arg() const
7914 const Expression_list* args = this->args();
7915 if (args == NULL || args->size() != 1)
7916 return NULL;
7917 return args->front();
7920 // A traversal class which looks for a call or receive expression.
7922 class Find_call_expression : public Traverse
7924 public:
7925 Find_call_expression()
7926 : Traverse(traverse_expressions),
7927 found_(false)
7931 expression(Expression**);
7933 bool
7934 found()
7935 { return this->found_; }
7937 private:
7938 bool found_;
7942 Find_call_expression::expression(Expression** pexpr)
7944 if ((*pexpr)->call_expression() != NULL
7945 || (*pexpr)->receive_expression() != NULL)
7947 this->found_ = true;
7948 return TRAVERSE_EXIT;
7950 return TRAVERSE_CONTINUE;
7953 // Return whether this is constant: len of a string constant, or len
7954 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7955 // unsafe.Alignof.
7957 bool
7958 Builtin_call_expression::do_is_constant() const
7960 if (this->is_error_expression())
7961 return true;
7962 switch (this->code_)
7964 case BUILTIN_LEN:
7965 case BUILTIN_CAP:
7967 if (this->seen_)
7968 return false;
7970 Expression* arg = this->one_arg();
7971 if (arg == NULL)
7972 return false;
7973 Type* arg_type = arg->type();
7975 if (arg_type->points_to() != NULL
7976 && arg_type->points_to()->array_type() != NULL
7977 && !arg_type->points_to()->is_slice_type())
7978 arg_type = arg_type->points_to();
7980 // The len and cap functions are only constant if there are no
7981 // function calls or channel operations in the arguments.
7982 // Otherwise we have to make the call.
7983 if (!arg->is_constant())
7985 Find_call_expression find_call;
7986 Expression::traverse(&arg, &find_call);
7987 if (find_call.found())
7988 return false;
7991 if (arg_type->array_type() != NULL
7992 && arg_type->array_type()->length() != NULL)
7993 return true;
7995 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7997 this->seen_ = true;
7998 bool ret = arg->is_constant();
7999 this->seen_ = false;
8000 return ret;
8003 break;
8005 case BUILTIN_SIZEOF:
8006 case BUILTIN_ALIGNOF:
8007 return this->one_arg() != NULL;
8009 case BUILTIN_OFFSETOF:
8011 Expression* arg = this->one_arg();
8012 if (arg == NULL)
8013 return false;
8014 return arg->field_reference_expression() != NULL;
8017 case BUILTIN_COMPLEX:
8019 const Expression_list* args = this->args();
8020 if (args != NULL && args->size() == 2)
8021 return args->front()->is_constant() && args->back()->is_constant();
8023 break;
8025 case BUILTIN_REAL:
8026 case BUILTIN_IMAG:
8028 Expression* arg = this->one_arg();
8029 return arg != NULL && arg->is_constant();
8032 default:
8033 break;
8036 return false;
8039 // Return a numeric constant if possible.
8041 bool
8042 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8044 if (this->code_ == BUILTIN_LEN
8045 || this->code_ == BUILTIN_CAP)
8047 Expression* arg = this->one_arg();
8048 if (arg == NULL)
8049 return false;
8050 Type* arg_type = arg->type();
8052 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8054 std::string sval;
8055 if (arg->string_constant_value(&sval))
8057 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8058 sval.length());
8059 return true;
8063 if (arg_type->points_to() != NULL
8064 && arg_type->points_to()->array_type() != NULL
8065 && !arg_type->points_to()->is_slice_type())
8066 arg_type = arg_type->points_to();
8068 if (arg_type->array_type() != NULL
8069 && arg_type->array_type()->length() != NULL)
8071 if (this->seen_)
8072 return false;
8073 Expression* e = arg_type->array_type()->length();
8074 this->seen_ = true;
8075 bool r = e->numeric_constant_value(nc);
8076 this->seen_ = false;
8077 if (r)
8079 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8080 this->location()))
8081 r = false;
8083 return r;
8086 else if (this->code_ == BUILTIN_SIZEOF
8087 || this->code_ == BUILTIN_ALIGNOF)
8089 Expression* arg = this->one_arg();
8090 if (arg == NULL)
8091 return false;
8092 Type* arg_type = arg->type();
8093 if (arg_type->is_error())
8094 return false;
8095 if (arg_type->is_abstract())
8096 return false;
8097 if (this->seen_)
8098 return false;
8100 int64_t ret;
8101 if (this->code_ == BUILTIN_SIZEOF)
8103 this->seen_ = true;
8104 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8105 this->seen_ = false;
8106 if (!ok)
8107 return false;
8109 else if (this->code_ == BUILTIN_ALIGNOF)
8111 bool ok;
8112 this->seen_ = true;
8113 if (arg->field_reference_expression() == NULL)
8114 ok = arg_type->backend_type_align(this->gogo_, &ret);
8115 else
8117 // Calling unsafe.Alignof(s.f) returns the alignment of
8118 // the type of f when it is used as a field in a struct.
8119 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8121 this->seen_ = false;
8122 if (!ok)
8123 return false;
8125 else
8126 go_unreachable();
8128 mpz_t zval;
8129 set_mpz_from_int64(&zval, ret);
8130 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8131 mpz_clear(zval);
8132 return true;
8134 else if (this->code_ == BUILTIN_OFFSETOF)
8136 Expression* arg = this->one_arg();
8137 if (arg == NULL)
8138 return false;
8139 Field_reference_expression* farg = arg->field_reference_expression();
8140 if (farg == NULL)
8141 return false;
8142 if (this->seen_)
8143 return false;
8145 int64_t total_offset = 0;
8146 while (true)
8148 Expression* struct_expr = farg->expr();
8149 Type* st = struct_expr->type();
8150 if (st->struct_type() == NULL)
8151 return false;
8152 if (st->named_type() != NULL)
8153 st->named_type()->convert(this->gogo_);
8154 int64_t offset;
8155 this->seen_ = true;
8156 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8157 farg->field_index(),
8158 &offset);
8159 this->seen_ = false;
8160 if (!ok)
8161 return false;
8162 total_offset += offset;
8163 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8165 // Go up until we reach the original base.
8166 farg = struct_expr->field_reference_expression();
8167 continue;
8169 break;
8171 mpz_t zval;
8172 set_mpz_from_int64(&zval, total_offset);
8173 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8174 mpz_clear(zval);
8175 return true;
8177 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8179 Expression* arg = this->one_arg();
8180 if (arg == NULL)
8181 return false;
8183 Numeric_constant argnc;
8184 if (!arg->numeric_constant_value(&argnc))
8185 return false;
8187 mpc_t val;
8188 if (!argnc.to_complex(&val))
8189 return false;
8191 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8192 if (this->code_ == BUILTIN_REAL)
8193 nc->set_float(type, mpc_realref(val));
8194 else
8195 nc->set_float(type, mpc_imagref(val));
8196 mpc_clear(val);
8197 return true;
8199 else if (this->code_ == BUILTIN_COMPLEX)
8201 const Expression_list* args = this->args();
8202 if (args == NULL || args->size() != 2)
8203 return false;
8205 Numeric_constant rnc;
8206 if (!args->front()->numeric_constant_value(&rnc))
8207 return false;
8208 Numeric_constant inc;
8209 if (!args->back()->numeric_constant_value(&inc))
8210 return false;
8212 if (rnc.type() != NULL
8213 && !rnc.type()->is_abstract()
8214 && inc.type() != NULL
8215 && !inc.type()->is_abstract()
8216 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8217 return false;
8219 mpfr_t r;
8220 if (!rnc.to_float(&r))
8221 return false;
8222 mpfr_t i;
8223 if (!inc.to_float(&i))
8225 mpfr_clear(r);
8226 return false;
8229 Type* arg_type = rnc.type();
8230 if (arg_type == NULL || arg_type->is_abstract())
8231 arg_type = inc.type();
8233 mpc_t val;
8234 mpc_init2(val, mpc_precision);
8235 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8236 mpfr_clear(r);
8237 mpfr_clear(i);
8239 Type* type = Builtin_call_expression::complex_type(arg_type);
8240 nc->set_complex(type, val);
8242 mpc_clear(val);
8244 return true;
8247 return false;
8250 // Give an error if we are discarding the value of an expression which
8251 // should not normally be discarded. We don't give an error for
8252 // discarding the value of an ordinary function call, but we do for
8253 // builtin functions, purely for consistency with the gc compiler.
8255 bool
8256 Builtin_call_expression::do_discarding_value()
8258 switch (this->code_)
8260 case BUILTIN_INVALID:
8261 default:
8262 go_unreachable();
8264 case BUILTIN_APPEND:
8265 case BUILTIN_CAP:
8266 case BUILTIN_COMPLEX:
8267 case BUILTIN_IMAG:
8268 case BUILTIN_LEN:
8269 case BUILTIN_MAKE:
8270 case BUILTIN_NEW:
8271 case BUILTIN_REAL:
8272 case BUILTIN_ALIGNOF:
8273 case BUILTIN_OFFSETOF:
8274 case BUILTIN_SIZEOF:
8275 this->unused_value_error();
8276 return false;
8278 case BUILTIN_CLOSE:
8279 case BUILTIN_COPY:
8280 case BUILTIN_DELETE:
8281 case BUILTIN_PANIC:
8282 case BUILTIN_PRINT:
8283 case BUILTIN_PRINTLN:
8284 case BUILTIN_RECOVER:
8285 return true;
8289 // Return the type.
8291 Type*
8292 Builtin_call_expression::do_type()
8294 if (this->is_error_expression())
8295 return Type::make_error_type();
8296 switch (this->code_)
8298 case BUILTIN_INVALID:
8299 default:
8300 return Type::make_error_type();
8302 case BUILTIN_NEW:
8303 case BUILTIN_MAKE:
8305 const Expression_list* args = this->args();
8306 if (args == NULL || args->empty())
8307 return Type::make_error_type();
8308 return Type::make_pointer_type(args->front()->type());
8311 case BUILTIN_CAP:
8312 case BUILTIN_COPY:
8313 case BUILTIN_LEN:
8314 return Type::lookup_integer_type("int");
8316 case BUILTIN_ALIGNOF:
8317 case BUILTIN_OFFSETOF:
8318 case BUILTIN_SIZEOF:
8319 return Type::lookup_integer_type("uintptr");
8321 case BUILTIN_CLOSE:
8322 case BUILTIN_DELETE:
8323 case BUILTIN_PANIC:
8324 case BUILTIN_PRINT:
8325 case BUILTIN_PRINTLN:
8326 return Type::make_void_type();
8328 case BUILTIN_RECOVER:
8329 return Type::make_empty_interface_type(Linemap::predeclared_location());
8331 case BUILTIN_APPEND:
8333 const Expression_list* args = this->args();
8334 if (args == NULL || args->empty())
8335 return Type::make_error_type();
8336 Type *ret = args->front()->type();
8337 if (!ret->is_slice_type())
8338 return Type::make_error_type();
8339 return ret;
8342 case BUILTIN_REAL:
8343 case BUILTIN_IMAG:
8345 Expression* arg = this->one_arg();
8346 if (arg == NULL)
8347 return Type::make_error_type();
8348 Type* t = arg->type();
8349 if (t->is_abstract())
8350 t = t->make_non_abstract_type();
8351 t = Builtin_call_expression::real_imag_type(t);
8352 if (t == NULL)
8353 t = Type::make_error_type();
8354 return t;
8357 case BUILTIN_COMPLEX:
8359 const Expression_list* args = this->args();
8360 if (args == NULL || args->size() != 2)
8361 return Type::make_error_type();
8362 Type* t = args->front()->type();
8363 if (t->is_abstract())
8365 t = args->back()->type();
8366 if (t->is_abstract())
8367 t = t->make_non_abstract_type();
8369 t = Builtin_call_expression::complex_type(t);
8370 if (t == NULL)
8371 t = Type::make_error_type();
8372 return t;
8377 // Determine the type.
8379 void
8380 Builtin_call_expression::do_determine_type(const Type_context* context)
8382 if (!this->determining_types())
8383 return;
8385 this->fn()->determine_type_no_context();
8387 const Expression_list* args = this->args();
8389 bool is_print;
8390 Type* arg_type = NULL;
8391 Type* trailing_arg_types = NULL;
8392 switch (this->code_)
8394 case BUILTIN_PRINT:
8395 case BUILTIN_PRINTLN:
8396 // Do not force a large integer constant to "int".
8397 is_print = true;
8398 break;
8400 case BUILTIN_REAL:
8401 case BUILTIN_IMAG:
8402 arg_type = Builtin_call_expression::complex_type(context->type);
8403 if (arg_type == NULL)
8404 arg_type = Type::lookup_complex_type("complex128");
8405 is_print = false;
8406 break;
8408 case BUILTIN_COMPLEX:
8410 // For the complex function the type of one operand can
8411 // determine the type of the other, as in a binary expression.
8412 arg_type = Builtin_call_expression::real_imag_type(context->type);
8413 if (arg_type == NULL)
8414 arg_type = Type::lookup_float_type("float64");
8415 if (args != NULL && args->size() == 2)
8417 Type* t1 = args->front()->type();
8418 Type* t2 = args->back()->type();
8419 if (!t1->is_abstract())
8420 arg_type = t1;
8421 else if (!t2->is_abstract())
8422 arg_type = t2;
8424 is_print = false;
8426 break;
8428 case BUILTIN_APPEND:
8429 if (!this->is_varargs()
8430 && args != NULL
8431 && !args->empty()
8432 && args->front()->type()->is_slice_type())
8433 trailing_arg_types =
8434 args->front()->type()->array_type()->element_type();
8435 is_print = false;
8436 break;
8438 default:
8439 is_print = false;
8440 break;
8443 if (args != NULL)
8445 for (Expression_list::const_iterator pa = args->begin();
8446 pa != args->end();
8447 ++pa)
8449 Type_context subcontext;
8450 subcontext.type = arg_type;
8452 if (is_print)
8454 // We want to print large constants, we so can't just
8455 // use the appropriate nonabstract type. Use uint64 for
8456 // an integer if we know it is nonnegative, otherwise
8457 // use int64 for a integer, otherwise use float64 for a
8458 // float or complex128 for a complex.
8459 Type* want_type = NULL;
8460 Type* atype = (*pa)->type();
8461 if (atype->is_abstract())
8463 if (atype->integer_type() != NULL)
8465 Numeric_constant nc;
8466 if (this->numeric_constant_value(&nc))
8468 mpz_t val;
8469 if (nc.to_int(&val))
8471 if (mpz_sgn(val) >= 0)
8472 want_type = Type::lookup_integer_type("uint64");
8473 mpz_clear(val);
8476 if (want_type == NULL)
8477 want_type = Type::lookup_integer_type("int64");
8479 else if (atype->float_type() != NULL)
8480 want_type = Type::lookup_float_type("float64");
8481 else if (atype->complex_type() != NULL)
8482 want_type = Type::lookup_complex_type("complex128");
8483 else if (atype->is_abstract_string_type())
8484 want_type = Type::lookup_string_type();
8485 else if (atype->is_abstract_boolean_type())
8486 want_type = Type::lookup_bool_type();
8487 else
8488 go_unreachable();
8489 subcontext.type = want_type;
8493 (*pa)->determine_type(&subcontext);
8495 if (trailing_arg_types != NULL)
8497 arg_type = trailing_arg_types;
8498 trailing_arg_types = NULL;
8504 // If there is exactly one argument, return true. Otherwise give an
8505 // error message and return false.
8507 bool
8508 Builtin_call_expression::check_one_arg()
8510 const Expression_list* args = this->args();
8511 if (args == NULL || args->size() < 1)
8513 this->report_error(_("not enough arguments"));
8514 return false;
8516 else if (args->size() > 1)
8518 this->report_error(_("too many arguments"));
8519 return false;
8521 if (args->front()->is_error_expression()
8522 || args->front()->type()->is_error())
8524 this->set_is_error();
8525 return false;
8527 return true;
8530 // Check argument types for a builtin function.
8532 void
8533 Builtin_call_expression::do_check_types(Gogo*)
8535 if (this->is_error_expression())
8536 return;
8537 switch (this->code_)
8539 case BUILTIN_INVALID:
8540 case BUILTIN_NEW:
8541 case BUILTIN_MAKE:
8542 case BUILTIN_DELETE:
8543 return;
8545 case BUILTIN_LEN:
8546 case BUILTIN_CAP:
8548 // The single argument may be either a string or an array or a
8549 // map or a channel, or a pointer to a closed array.
8550 if (this->check_one_arg())
8552 Type* arg_type = this->one_arg()->type();
8553 if (arg_type->points_to() != NULL
8554 && arg_type->points_to()->array_type() != NULL
8555 && !arg_type->points_to()->is_slice_type())
8556 arg_type = arg_type->points_to();
8557 if (this->code_ == BUILTIN_CAP)
8559 if (!arg_type->is_error()
8560 && arg_type->array_type() == NULL
8561 && arg_type->channel_type() == NULL)
8562 this->report_error(_("argument must be array or slice "
8563 "or channel"));
8565 else
8567 if (!arg_type->is_error()
8568 && !arg_type->is_string_type()
8569 && arg_type->array_type() == NULL
8570 && arg_type->map_type() == NULL
8571 && arg_type->channel_type() == NULL)
8572 this->report_error(_("argument must be string or "
8573 "array or slice or map or channel"));
8577 break;
8579 case BUILTIN_PRINT:
8580 case BUILTIN_PRINTLN:
8582 const Expression_list* args = this->args();
8583 if (args == NULL)
8585 if (this->code_ == BUILTIN_PRINT)
8586 go_warning_at(this->location(), 0,
8587 "no arguments for builtin function %<%s%>",
8588 (this->code_ == BUILTIN_PRINT
8589 ? "print"
8590 : "println"));
8592 else
8594 for (Expression_list::const_iterator p = args->begin();
8595 p != args->end();
8596 ++p)
8598 Type* type = (*p)->type();
8599 if (type->is_error()
8600 || type->is_string_type()
8601 || type->integer_type() != NULL
8602 || type->float_type() != NULL
8603 || type->complex_type() != NULL
8604 || type->is_boolean_type()
8605 || type->points_to() != NULL
8606 || type->interface_type() != NULL
8607 || type->channel_type() != NULL
8608 || type->map_type() != NULL
8609 || type->function_type() != NULL
8610 || type->is_slice_type())
8612 else if ((*p)->is_type_expression())
8614 // If this is a type expression it's going to give
8615 // an error anyhow, so we don't need one here.
8617 else
8618 this->report_error(_("unsupported argument type to "
8619 "builtin function"));
8623 break;
8625 case BUILTIN_CLOSE:
8626 if (this->check_one_arg())
8628 if (this->one_arg()->type()->channel_type() == NULL)
8629 this->report_error(_("argument must be channel"));
8630 else if (!this->one_arg()->type()->channel_type()->may_send())
8631 this->report_error(_("cannot close receive-only channel"));
8633 break;
8635 case BUILTIN_PANIC:
8636 case BUILTIN_SIZEOF:
8637 case BUILTIN_ALIGNOF:
8638 this->check_one_arg();
8639 break;
8641 case BUILTIN_RECOVER:
8642 if (this->args() != NULL
8643 && !this->args()->empty()
8644 && !this->recover_arg_is_set_)
8645 this->report_error(_("too many arguments"));
8646 break;
8648 case BUILTIN_OFFSETOF:
8649 if (this->check_one_arg())
8651 Expression* arg = this->one_arg();
8652 if (arg->field_reference_expression() == NULL)
8653 this->report_error(_("argument must be a field reference"));
8655 break;
8657 case BUILTIN_COPY:
8659 const Expression_list* args = this->args();
8660 if (args == NULL || args->size() < 2)
8662 this->report_error(_("not enough arguments"));
8663 break;
8665 else if (args->size() > 2)
8667 this->report_error(_("too many arguments"));
8668 break;
8670 Type* arg1_type = args->front()->type();
8671 Type* arg2_type = args->back()->type();
8672 if (arg1_type->is_error() || arg2_type->is_error())
8674 this->set_is_error();
8675 break;
8678 Type* e1;
8679 if (arg1_type->is_slice_type())
8680 e1 = arg1_type->array_type()->element_type();
8681 else
8683 this->report_error(_("left argument must be a slice"));
8684 break;
8687 if (arg2_type->is_slice_type())
8689 Type* e2 = arg2_type->array_type()->element_type();
8690 if (!Type::are_identical(e1, e2, true, NULL))
8691 this->report_error(_("element types must be the same"));
8693 else if (arg2_type->is_string_type())
8695 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8696 this->report_error(_("first argument must be []byte"));
8698 else
8699 this->report_error(_("second argument must be slice or string"));
8701 break;
8703 case BUILTIN_APPEND:
8705 const Expression_list* args = this->args();
8706 if (args == NULL || args->empty())
8708 this->report_error(_("not enough arguments"));
8709 break;
8712 Type* slice_type = args->front()->type();
8713 if (!slice_type->is_slice_type())
8715 if (slice_type->is_error_type())
8716 break;
8717 if (slice_type->is_nil_type())
8718 go_error_at(args->front()->location(), "use of untyped nil");
8719 else
8720 go_error_at(args->front()->location(),
8721 "argument 1 must be a slice");
8722 this->set_is_error();
8723 break;
8726 Type* element_type = slice_type->array_type()->element_type();
8727 if (!element_type->in_heap())
8728 go_error_at(args->front()->location(),
8729 "can't append to slice of go:notinheap type");
8730 if (this->is_varargs())
8732 if (!args->back()->type()->is_slice_type()
8733 && !args->back()->type()->is_string_type())
8735 go_error_at(args->back()->location(),
8736 "invalid use of %<...%> with non-slice/non-string");
8737 this->set_is_error();
8738 break;
8741 if (args->size() < 2)
8743 this->report_error(_("not enough arguments"));
8744 break;
8746 if (args->size() > 2)
8748 this->report_error(_("too many arguments"));
8749 break;
8752 if (args->back()->type()->is_string_type()
8753 && element_type->integer_type() != NULL
8754 && element_type->integer_type()->is_byte())
8756 // Permit append(s1, s2...) when s1 is a slice of
8757 // bytes and s2 is a string type.
8759 else
8761 // We have to test for assignment compatibility to a
8762 // slice of the element type, which is not necessarily
8763 // the same as the type of the first argument: the
8764 // first argument might have a named type.
8765 Type* check_type = Type::make_array_type(element_type, NULL);
8766 std::string reason;
8767 if (!Type::are_assignable(check_type, args->back()->type(),
8768 &reason))
8770 if (reason.empty())
8771 go_error_at(args->back()->location(),
8772 "argument 2 has invalid type");
8773 else
8774 go_error_at(args->back()->location(),
8775 "argument 2 has invalid type (%s)",
8776 reason.c_str());
8777 this->set_is_error();
8778 break;
8782 else
8784 Expression_list::const_iterator pa = args->begin();
8785 int i = 2;
8786 for (++pa; pa != args->end(); ++pa, ++i)
8788 std::string reason;
8789 if (!Type::are_assignable(element_type, (*pa)->type(),
8790 &reason))
8792 if (reason.empty())
8793 go_error_at((*pa)->location(),
8794 "argument %d has incompatible type", i);
8795 else
8796 go_error_at((*pa)->location(),
8797 "argument %d has incompatible type (%s)",
8798 i, reason.c_str());
8799 this->set_is_error();
8804 break;
8806 case BUILTIN_REAL:
8807 case BUILTIN_IMAG:
8808 if (this->check_one_arg())
8810 if (this->one_arg()->type()->complex_type() == NULL)
8811 this->report_error(_("argument must have complex type"));
8813 break;
8815 case BUILTIN_COMPLEX:
8817 const Expression_list* args = this->args();
8818 if (args == NULL || args->size() < 2)
8819 this->report_error(_("not enough arguments"));
8820 else if (args->size() > 2)
8821 this->report_error(_("too many arguments"));
8822 else if (args->front()->is_error_expression()
8823 || args->front()->type()->is_error()
8824 || args->back()->is_error_expression()
8825 || args->back()->type()->is_error())
8826 this->set_is_error();
8827 else if (!Type::are_identical(args->front()->type(),
8828 args->back()->type(), true, NULL))
8829 this->report_error(_("complex arguments must have identical types"));
8830 else if (args->front()->type()->float_type() == NULL)
8831 this->report_error(_("complex arguments must have "
8832 "floating-point type"));
8834 break;
8836 default:
8837 go_unreachable();
8841 Expression*
8842 Builtin_call_expression::do_copy()
8844 Call_expression* bce =
8845 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8846 (this->args() == NULL
8847 ? NULL
8848 : this->args()->copy()),
8849 this->is_varargs(),
8850 this->location());
8852 if (this->varargs_are_lowered())
8853 bce->set_varargs_are_lowered();
8854 return bce;
8857 // Return the backend representation for a builtin function.
8859 Bexpression*
8860 Builtin_call_expression::do_get_backend(Translate_context* context)
8862 Gogo* gogo = context->gogo();
8863 Location location = this->location();
8865 if (this->is_erroneous_call())
8867 go_assert(saw_errors());
8868 return gogo->backend()->error_expression();
8871 switch (this->code_)
8873 case BUILTIN_INVALID:
8874 case BUILTIN_NEW:
8875 case BUILTIN_MAKE:
8876 go_unreachable();
8878 case BUILTIN_LEN:
8879 case BUILTIN_CAP:
8881 const Expression_list* args = this->args();
8882 go_assert(args != NULL && args->size() == 1);
8883 Expression* arg = args->front();
8884 Type* arg_type = arg->type();
8886 if (this->seen_)
8888 go_assert(saw_errors());
8889 return context->backend()->error_expression();
8891 this->seen_ = true;
8892 this->seen_ = false;
8893 if (arg_type->points_to() != NULL)
8895 arg_type = arg_type->points_to();
8896 go_assert(arg_type->array_type() != NULL
8897 && !arg_type->is_slice_type());
8898 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
8899 location);
8902 Type* int_type = Type::lookup_integer_type("int");
8903 Expression* val;
8904 if (this->code_ == BUILTIN_LEN)
8906 if (arg_type->is_string_type())
8907 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8908 location);
8909 else if (arg_type->array_type() != NULL)
8911 if (this->seen_)
8913 go_assert(saw_errors());
8914 return context->backend()->error_expression();
8916 this->seen_ = true;
8917 val = arg_type->array_type()->get_length(gogo, arg);
8918 this->seen_ = false;
8920 else if (arg_type->map_type() != NULL
8921 || arg_type->channel_type() != NULL)
8923 // The first field is the length. If the pointer is
8924 // nil, the length is zero.
8925 Type* pint_type = Type::make_pointer_type(int_type);
8926 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8927 Expression* nil = Expression::make_nil(location);
8928 nil = Expression::make_cast(pint_type, nil, location);
8929 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8930 arg, nil, location);
8931 Expression* zero = Expression::make_integer_ul(0, int_type,
8932 location);
8933 Expression* indir =
8934 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
8935 location);
8936 val = Expression::make_conditional(cmp, zero, indir, location);
8938 else
8939 go_unreachable();
8941 else
8943 if (arg_type->array_type() != NULL)
8945 if (this->seen_)
8947 go_assert(saw_errors());
8948 return context->backend()->error_expression();
8950 this->seen_ = true;
8951 val = arg_type->array_type()->get_capacity(gogo, arg);
8952 this->seen_ = false;
8954 else if (arg_type->channel_type() != NULL)
8956 // The second field is the capacity. If the pointer
8957 // is nil, the capacity is zero.
8958 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8959 Type* pint_type = Type::make_pointer_type(int_type);
8960 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8961 arg,
8962 location);
8963 int off = int_type->integer_type()->bits() / 8;
8964 Expression* eoff = Expression::make_integer_ul(off,
8965 uintptr_type,
8966 location);
8967 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8968 location);
8969 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8970 Expression* nil = Expression::make_nil(location);
8971 nil = Expression::make_cast(pint_type, nil, location);
8972 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8973 arg, nil, location);
8974 Expression* zero = Expression::make_integer_ul(0, int_type,
8975 location);
8976 Expression* indir =
8977 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
8978 location);
8979 val = Expression::make_conditional(cmp, zero, indir, location);
8981 else
8982 go_unreachable();
8985 return Expression::make_cast(int_type, val,
8986 location)->get_backend(context);
8989 case BUILTIN_PRINT:
8990 case BUILTIN_PRINTLN:
8992 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8994 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
8995 location, 0);
8997 const Expression_list* call_args = this->args();
8998 if (call_args != NULL)
9000 for (Expression_list::const_iterator p = call_args->begin();
9001 p != call_args->end();
9002 ++p)
9004 if (is_ln && p != call_args->begin())
9006 Expression* print_space =
9007 Runtime::make_call(Runtime::PRINTSP, location, 0);
9009 print_stmts =
9010 Expression::make_compound(print_stmts, print_space,
9011 location);
9014 Expression* arg = *p;
9015 Type* type = arg->type();
9016 Runtime::Function code;
9017 if (type->is_string_type())
9018 code = Runtime::PRINTSTRING;
9019 else if (type->integer_type() != NULL
9020 && type->integer_type()->is_unsigned())
9022 Type* itype = Type::lookup_integer_type("uint64");
9023 arg = Expression::make_cast(itype, arg, location);
9024 code = Runtime::PRINTUINT;
9026 else if (type->integer_type() != NULL)
9028 Type* itype = Type::lookup_integer_type("int64");
9029 arg = Expression::make_cast(itype, arg, location);
9030 code = Runtime::PRINTINT;
9032 else if (type->float_type() != NULL)
9034 Type* dtype = Type::lookup_float_type("float64");
9035 arg = Expression::make_cast(dtype, arg, location);
9036 code = Runtime::PRINTFLOAT;
9038 else if (type->complex_type() != NULL)
9040 Type* ctype = Type::lookup_complex_type("complex128");
9041 arg = Expression::make_cast(ctype, arg, location);
9042 code = Runtime::PRINTCOMPLEX;
9044 else if (type->is_boolean_type())
9045 code = Runtime::PRINTBOOL;
9046 else if (type->points_to() != NULL
9047 || type->channel_type() != NULL
9048 || type->map_type() != NULL
9049 || type->function_type() != NULL)
9051 arg = Expression::make_cast(type, arg, location);
9052 code = Runtime::PRINTPOINTER;
9054 else if (type->interface_type() != NULL)
9056 if (type->interface_type()->is_empty())
9057 code = Runtime::PRINTEFACE;
9058 else
9059 code = Runtime::PRINTIFACE;
9061 else if (type->is_slice_type())
9062 code = Runtime::PRINTSLICE;
9063 else
9065 go_assert(saw_errors());
9066 return context->backend()->error_expression();
9069 Expression* call = Runtime::make_call(code, location, 1, arg);
9070 print_stmts = Expression::make_compound(print_stmts, call,
9071 location);
9075 if (is_ln)
9077 Expression* print_nl =
9078 Runtime::make_call(Runtime::PRINTNL, location, 0);
9079 print_stmts = Expression::make_compound(print_stmts, print_nl,
9080 location);
9083 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9084 location, 0);
9085 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9087 return print_stmts->get_backend(context);
9090 case BUILTIN_PANIC:
9092 const Expression_list* args = this->args();
9093 go_assert(args != NULL && args->size() == 1);
9094 Expression* arg = args->front();
9095 Type *empty =
9096 Type::make_empty_interface_type(Linemap::predeclared_location());
9097 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9099 Expression* panic =
9100 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9101 return panic->get_backend(context);
9104 case BUILTIN_RECOVER:
9106 // The argument is set when building recover thunks. It's a
9107 // boolean value which is true if we can recover a value now.
9108 const Expression_list* args = this->args();
9109 go_assert(args != NULL && args->size() == 1);
9110 Expression* arg = args->front();
9111 Type *empty =
9112 Type::make_empty_interface_type(Linemap::predeclared_location());
9114 Expression* nil = Expression::make_nil(location);
9115 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9117 // We need to handle a deferred call to recover specially,
9118 // because it changes whether it can recover a panic or not.
9119 // See test7 in test/recover1.go.
9120 Expression* recover = Runtime::make_call((this->is_deferred()
9121 ? Runtime::DEFERREDRECOVER
9122 : Runtime::GORECOVER),
9123 location, 0);
9124 Expression* cond =
9125 Expression::make_conditional(arg, recover, nil, location);
9126 return cond->get_backend(context);
9129 case BUILTIN_CLOSE:
9131 const Expression_list* args = this->args();
9132 go_assert(args != NULL && args->size() == 1);
9133 Expression* arg = args->front();
9134 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9135 1, arg);
9136 return close->get_backend(context);
9139 case BUILTIN_SIZEOF:
9140 case BUILTIN_OFFSETOF:
9141 case BUILTIN_ALIGNOF:
9143 Numeric_constant nc;
9144 unsigned long val;
9145 if (!this->numeric_constant_value(&nc)
9146 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9148 go_assert(saw_errors());
9149 return context->backend()->error_expression();
9151 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9152 mpz_t ival;
9153 nc.get_int(&ival);
9154 Expression* int_cst =
9155 Expression::make_integer_z(&ival, uintptr_type, location);
9156 mpz_clear(ival);
9157 return int_cst->get_backend(context);
9160 case BUILTIN_COPY:
9162 const Expression_list* args = this->args();
9163 go_assert(args != NULL && args->size() == 2);
9164 Expression* arg1 = args->front();
9165 Expression* arg2 = args->back();
9167 Type* arg1_type = arg1->type();
9168 Array_type* at = arg1_type->array_type();
9169 go_assert(arg1->is_variable());
9171 Expression* call;
9173 Type* arg2_type = arg2->type();
9174 go_assert(arg2->is_variable());
9175 if (arg2_type->is_string_type())
9176 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9177 2, arg1, arg2);
9178 else
9180 Type* et = at->element_type();
9181 if (et->has_pointer())
9183 Expression* td = Expression::make_type_descriptor(et,
9184 location);
9185 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9186 3, td, arg1, arg2);
9188 else
9190 Expression* sz = Expression::make_type_info(et,
9191 TYPE_INFO_SIZE);
9192 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9193 arg1, arg2, sz);
9197 return call->get_backend(context);
9200 case BUILTIN_APPEND:
9201 // Handled in Builtin_call_expression::flatten_append.
9202 go_unreachable();
9204 case BUILTIN_REAL:
9205 case BUILTIN_IMAG:
9207 const Expression_list* args = this->args();
9208 go_assert(args != NULL && args->size() == 1);
9210 Bexpression* ret;
9211 Bexpression* bcomplex = args->front()->get_backend(context);
9212 if (this->code_ == BUILTIN_REAL)
9213 ret = gogo->backend()->real_part_expression(bcomplex, location);
9214 else
9215 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9216 return ret;
9219 case BUILTIN_COMPLEX:
9221 const Expression_list* args = this->args();
9222 go_assert(args != NULL && args->size() == 2);
9223 Bexpression* breal = args->front()->get_backend(context);
9224 Bexpression* bimag = args->back()->get_backend(context);
9225 return gogo->backend()->complex_expression(breal, bimag, location);
9228 default:
9229 go_unreachable();
9233 // We have to support exporting a builtin call expression, because
9234 // code can set a constant to the result of a builtin expression.
9236 void
9237 Builtin_call_expression::do_export(Export* exp) const
9239 Numeric_constant nc;
9240 if (!this->numeric_constant_value(&nc))
9242 go_error_at(this->location(), "value is not constant");
9243 return;
9246 if (nc.is_int())
9248 mpz_t val;
9249 nc.get_int(&val);
9250 Integer_expression::export_integer(exp, val);
9251 mpz_clear(val);
9253 else if (nc.is_float())
9255 mpfr_t fval;
9256 nc.get_float(&fval);
9257 Float_expression::export_float(exp, fval);
9258 mpfr_clear(fval);
9260 else if (nc.is_complex())
9262 mpc_t cval;
9263 nc.get_complex(&cval);
9264 Complex_expression::export_complex(exp, cval);
9265 mpc_clear(cval);
9267 else
9268 go_unreachable();
9270 // A trailing space lets us reliably identify the end of the number.
9271 exp->write_c_string(" ");
9274 // Class Call_expression.
9276 // A Go function can be viewed in a couple of different ways. The
9277 // code of a Go function becomes a backend function with parameters
9278 // whose types are simply the backend representation of the Go types.
9279 // If there are multiple results, they are returned as a backend
9280 // struct.
9282 // However, when Go code refers to a function other than simply
9283 // calling it, the backend type of that function is actually a struct.
9284 // The first field of the struct points to the Go function code
9285 // (sometimes a wrapper as described below). The remaining fields
9286 // hold addresses of closed-over variables. This struct is called a
9287 // closure.
9289 // There are a few cases to consider.
9291 // A direct function call of a known function in package scope. In
9292 // this case there are no closed-over variables, and we know the name
9293 // of the function code. We can simply produce a backend call to the
9294 // function directly, and not worry about the closure.
9296 // A direct function call of a known function literal. In this case
9297 // we know the function code and we know the closure. We generate the
9298 // function code such that it expects an additional final argument of
9299 // the closure type. We pass the closure as the last argument, after
9300 // the other arguments.
9302 // An indirect function call. In this case we have a closure. We
9303 // load the pointer to the function code from the first field of the
9304 // closure. We pass the address of the closure as the last argument.
9306 // A call to a method of an interface. Type methods are always at
9307 // package scope, so we call the function directly, and don't worry
9308 // about the closure.
9310 // This means that for a function at package scope we have two cases.
9311 // One is the direct call, which has no closure. The other is the
9312 // indirect call, which does have a closure. We can't simply ignore
9313 // the closure, even though it is the last argument, because that will
9314 // fail on targets where the function pops its arguments. So when
9315 // generating a closure for a package-scope function we set the
9316 // function code pointer in the closure to point to a wrapper
9317 // function. This wrapper function accepts a final argument that
9318 // points to the closure, ignores it, and calls the real function as a
9319 // direct function call. This wrapper will normally be efficient, and
9320 // can often simply be a tail call to the real function.
9322 // We don't use GCC's static chain pointer because 1) we don't need
9323 // it; 2) GCC only permits using a static chain to call a known
9324 // function, so we can't use it for an indirect call anyhow. Since we
9325 // can't use it for an indirect call, we may as well not worry about
9326 // using it for a direct call either.
9328 // We pass the closure last rather than first because it means that
9329 // the function wrapper we put into a closure for a package-scope
9330 // function can normally just be a tail call to the real function.
9332 // For method expressions we generate a wrapper that loads the
9333 // receiver from the closure and then calls the method. This
9334 // unfortunately forces reshuffling the arguments, since there is a
9335 // new first argument, but we can't avoid reshuffling either for
9336 // method expressions or for indirect calls of package-scope
9337 // functions, and since the latter are more common we reshuffle for
9338 // method expressions.
9340 // Note that the Go code retains the Go types. The extra final
9341 // argument only appears when we convert to the backend
9342 // representation.
9344 // Traversal.
9347 Call_expression::do_traverse(Traverse* traverse)
9349 // If we are calling a function in a different package that returns
9350 // an unnamed type, this may be the only chance we get to traverse
9351 // that type. We don't traverse this->type_ because it may be a
9352 // Call_multiple_result_type that will just lead back here.
9353 if (this->type_ != NULL && !this->type_->is_error_type())
9355 Function_type *fntype = this->get_function_type();
9356 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9357 return TRAVERSE_EXIT;
9359 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9360 return TRAVERSE_EXIT;
9361 if (this->args_ != NULL)
9363 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9364 return TRAVERSE_EXIT;
9366 return TRAVERSE_CONTINUE;
9369 // Lower a call statement.
9371 Expression*
9372 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9373 Statement_inserter* inserter, int)
9375 Location loc = this->location();
9377 // A type cast can look like a function call.
9378 if (this->fn_->is_type_expression()
9379 && this->args_ != NULL
9380 && this->args_->size() == 1)
9381 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9382 loc);
9384 // Because do_type will return an error type and thus prevent future
9385 // errors, check for that case now to ensure that the error gets
9386 // reported.
9387 Function_type* fntype = this->get_function_type();
9388 if (fntype == NULL)
9390 if (!this->fn_->type()->is_error())
9391 this->report_error(_("expected function"));
9392 this->set_is_error();
9393 return this;
9396 // Handle an argument which is a call to a function which returns
9397 // multiple results.
9398 if (this->args_ != NULL
9399 && this->args_->size() == 1
9400 && this->args_->front()->call_expression() != NULL)
9402 size_t rc = this->args_->front()->call_expression()->result_count();
9403 if (rc > 1
9404 && ((fntype->parameters() != NULL
9405 && (fntype->parameters()->size() == rc
9406 || (fntype->is_varargs()
9407 && fntype->parameters()->size() - 1 <= rc)))
9408 || fntype->is_builtin()))
9410 Call_expression* call = this->args_->front()->call_expression();
9411 call->set_is_multi_value_arg();
9412 if (this->is_varargs_)
9414 // It is not clear which result of a multiple result call
9415 // the ellipsis operator should be applied to. If we unpack the
9416 // the call into its individual results here, the ellipsis will be
9417 // applied to the last result.
9418 go_error_at(call->location(),
9419 _("multiple-value argument in single-value context"));
9420 return Expression::make_error(call->location());
9423 Expression_list* args = new Expression_list;
9424 for (size_t i = 0; i < rc; ++i)
9425 args->push_back(Expression::make_call_result(call, i));
9426 // We can't return a new call expression here, because this
9427 // one may be referenced by Call_result expressions. We
9428 // also can't delete the old arguments, because we may still
9429 // traverse them somewhere up the call stack. FIXME.
9430 this->args_ = args;
9434 // Recognize a call to a builtin function.
9435 if (fntype->is_builtin())
9436 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9437 this->is_varargs_, loc);
9439 // If this call returns multiple results, create a temporary
9440 // variable to hold them.
9441 if (this->result_count() > 1 && this->call_temp_ == NULL)
9443 Struct_field_list* sfl = new Struct_field_list();
9444 Function_type* fntype = this->get_function_type();
9445 const Typed_identifier_list* results = fntype->results();
9446 Location loc = this->location();
9448 int i = 0;
9449 char buf[20];
9450 for (Typed_identifier_list::const_iterator p = results->begin();
9451 p != results->end();
9452 ++p, ++i)
9454 snprintf(buf, sizeof buf, "res%d", i);
9455 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9458 Struct_type* st = Type::make_struct_type(sfl, loc);
9459 st->set_is_struct_incomparable();
9460 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9461 inserter->insert(this->call_temp_);
9464 // Handle a call to a varargs function by packaging up the extra
9465 // parameters.
9466 if (fntype->is_varargs())
9468 const Typed_identifier_list* parameters = fntype->parameters();
9469 go_assert(parameters != NULL && !parameters->empty());
9470 Type* varargs_type = parameters->back().type();
9471 this->lower_varargs(gogo, function, inserter, varargs_type,
9472 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9475 // If this is call to a method, call the method directly passing the
9476 // object as the first parameter.
9477 Bound_method_expression* bme = this->fn_->bound_method_expression();
9478 if (bme != NULL)
9480 Named_object* methodfn = bme->function();
9481 Expression* first_arg = bme->first_argument();
9483 // We always pass a pointer when calling a method.
9484 if (first_arg->type()->points_to() == NULL
9485 && !first_arg->type()->is_error())
9487 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9488 // We may need to create a temporary variable so that we can
9489 // take the address. We can't do that here because it will
9490 // mess up the order of evaluation.
9491 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9492 ue->set_create_temp();
9495 // If we are calling a method which was inherited from an
9496 // embedded struct, and the method did not get a stub, then the
9497 // first type may be wrong.
9498 Type* fatype = bme->first_argument_type();
9499 if (fatype != NULL)
9501 if (fatype->points_to() == NULL)
9502 fatype = Type::make_pointer_type(fatype);
9503 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9506 Expression_list* new_args = new Expression_list();
9507 new_args->push_back(first_arg);
9508 if (this->args_ != NULL)
9510 for (Expression_list::const_iterator p = this->args_->begin();
9511 p != this->args_->end();
9512 ++p)
9513 new_args->push_back(*p);
9516 // We have to change in place because this structure may be
9517 // referenced by Call_result_expressions. We can't delete the
9518 // old arguments, because we may be traversing them up in some
9519 // caller. FIXME.
9520 this->args_ = new_args;
9521 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9522 bme->location());
9525 // Handle a couple of special runtime functions. In the runtime
9526 // package, getcallerpc returns the PC of the caller, and
9527 // getcallersp returns the frame pointer of the caller. Implement
9528 // these by turning them into calls to GCC builtin functions. We
9529 // could implement them in normal code, but then we would have to
9530 // explicitly unwind the stack. These functions are intended to be
9531 // efficient. Note that this technique obviously only works for
9532 // direct calls, but that is the only way they are used.
9533 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9535 Func_expression* fe = this->fn_->func_expression();
9536 if (fe != NULL
9537 && fe->named_object()->is_function_declaration()
9538 && fe->named_object()->package() == NULL)
9540 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9541 if ((this->args_ == NULL || this->args_->size() == 0)
9542 && n == "getcallerpc")
9544 static Named_object* builtin_return_address;
9545 return this->lower_to_builtin(&builtin_return_address,
9546 "__builtin_return_address",
9549 else if (this->args_ != NULL
9550 && this->args_->size() == 1
9551 && n == "getcallersp")
9553 // The actual argument to getcallersp is always the
9554 // address of a parameter; we don't need that for the
9555 // GCC builtin function, so we just ignore it.
9556 static Named_object* builtin_frame_address;
9557 return this->lower_to_builtin(&builtin_frame_address,
9558 "__builtin_frame_address",
9564 return this;
9567 // Lower a call to a varargs function. FUNCTION is the function in
9568 // which the call occurs--it's not the function we are calling.
9569 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9570 // PARAM_COUNT is the number of parameters of the function we are
9571 // calling; the last of these parameters will be the varargs
9572 // parameter.
9574 void
9575 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9576 Statement_inserter* inserter,
9577 Type* varargs_type, size_t param_count,
9578 Slice_storage_escape_disp escape_disp)
9580 // When compiling the runtime, varargs slices do not escape. When
9581 // escape analysis becomes the default, this should be changed to
9582 // make it an error if we have a varargs slice that escapes.
9583 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9584 escape_disp = SLICE_STORAGE_DOES_NOT_ESCAPE;
9586 if (this->varargs_are_lowered_)
9587 return;
9589 Location loc = this->location();
9591 go_assert(param_count > 0);
9592 go_assert(varargs_type->is_slice_type());
9594 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9595 if (arg_count < param_count - 1)
9597 // Not enough arguments; will be caught in check_types.
9598 return;
9601 Expression_list* old_args = this->args_;
9602 Expression_list* new_args = new Expression_list();
9603 bool push_empty_arg = false;
9604 if (old_args == NULL || old_args->empty())
9606 go_assert(param_count == 1);
9607 push_empty_arg = true;
9609 else
9611 Expression_list::const_iterator pa;
9612 int i = 1;
9613 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9615 if (static_cast<size_t>(i) == param_count)
9616 break;
9617 new_args->push_back(*pa);
9620 // We have reached the varargs parameter.
9622 bool issued_error = false;
9623 if (pa == old_args->end())
9624 push_empty_arg = true;
9625 else if (pa + 1 == old_args->end() && this->is_varargs_)
9626 new_args->push_back(*pa);
9627 else if (this->is_varargs_)
9629 if ((*pa)->type()->is_slice_type())
9630 this->report_error(_("too many arguments"));
9631 else
9633 go_error_at(this->location(),
9634 _("invalid use of %<...%> with non-slice"));
9635 this->set_is_error();
9637 return;
9639 else
9641 Type* element_type = varargs_type->array_type()->element_type();
9642 Expression_list* vals = new Expression_list;
9643 for (; pa != old_args->end(); ++pa, ++i)
9645 // Check types here so that we get a better message.
9646 Type* patype = (*pa)->type();
9647 Location paloc = (*pa)->location();
9648 if (!this->check_argument_type(i, element_type, patype,
9649 paloc, issued_error))
9650 continue;
9651 vals->push_back(*pa);
9653 Slice_construction_expression* sce =
9654 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9655 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9656 sce->set_storage_does_not_escape();
9657 Expression* val = sce;
9658 gogo->lower_expression(function, inserter, &val);
9659 new_args->push_back(val);
9663 if (push_empty_arg)
9664 new_args->push_back(Expression::make_nil(loc));
9666 // We can't return a new call expression here, because this one may
9667 // be referenced by Call_result expressions. FIXME. We can't
9668 // delete OLD_ARGS because we may have both a Call_expression and a
9669 // Builtin_call_expression which refer to them. FIXME.
9670 this->args_ = new_args;
9671 this->varargs_are_lowered_ = true;
9674 // Return a call to __builtin_return_address or __builtin_frame_address.
9676 Expression*
9677 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9678 int arg)
9680 if (*pno == NULL)
9681 *pno = Gogo::declare_builtin_rf_address(name);
9683 Location loc = this->location();
9685 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9686 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9687 Expression_list *args = new Expression_list();
9688 args->push_back(a);
9689 Expression* call = Expression::make_call(fn, args, false, loc);
9691 // The builtin functions return void*, but the Go functions return uintptr.
9692 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9693 return Expression::make_cast(uintptr_type, call, loc);
9696 // Flatten a call with multiple results into a temporary.
9698 Expression*
9699 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9700 Statement_inserter* inserter)
9702 if (this->is_erroneous_call())
9704 go_assert(saw_errors());
9705 return Expression::make_error(this->location());
9708 if (this->is_flattened_)
9709 return this;
9710 this->is_flattened_ = true;
9712 // Add temporary variables for all arguments that require type
9713 // conversion.
9714 Function_type* fntype = this->get_function_type();
9715 if (fntype == NULL)
9717 go_assert(saw_errors());
9718 return this;
9720 if (this->args_ != NULL && !this->args_->empty()
9721 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9723 bool is_interface_method =
9724 this->fn_->interface_field_reference_expression() != NULL;
9726 Expression_list *args = new Expression_list();
9727 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9728 Expression_list::const_iterator pa = this->args_->begin();
9729 if (!is_interface_method && fntype->is_method())
9731 // The receiver argument.
9732 args->push_back(*pa);
9733 ++pa;
9735 for (; pa != this->args_->end(); ++pa, ++pp)
9737 go_assert(pp != fntype->parameters()->end());
9738 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9739 args->push_back(*pa);
9740 else
9742 Location loc = (*pa)->location();
9743 Expression* arg = *pa;
9744 if (!arg->is_variable())
9746 Temporary_statement *temp =
9747 Statement::make_temporary(NULL, arg, loc);
9748 inserter->insert(temp);
9749 arg = Expression::make_temporary_reference(temp, loc);
9751 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9752 loc);
9753 args->push_back(arg);
9756 delete this->args_;
9757 this->args_ = args;
9760 return this;
9763 // Get the function type. This can return NULL in error cases.
9765 Function_type*
9766 Call_expression::get_function_type() const
9768 return this->fn_->type()->function_type();
9771 // Return the number of values which this call will return.
9773 size_t
9774 Call_expression::result_count() const
9776 const Function_type* fntype = this->get_function_type();
9777 if (fntype == NULL)
9778 return 0;
9779 if (fntype->results() == NULL)
9780 return 0;
9781 return fntype->results()->size();
9784 // Return the temporary that holds the result for a call with multiple
9785 // results.
9787 Temporary_statement*
9788 Call_expression::results() const
9790 if (this->call_temp_ == NULL)
9792 go_assert(saw_errors());
9793 return NULL;
9795 return this->call_temp_;
9798 // Set the number of results expected from a call expression.
9800 void
9801 Call_expression::set_expected_result_count(size_t count)
9803 go_assert(this->expected_result_count_ == 0);
9804 this->expected_result_count_ = count;
9807 // Return whether this is a call to the predeclared function recover.
9809 bool
9810 Call_expression::is_recover_call() const
9812 return this->do_is_recover_call();
9815 // Set the argument to the recover function.
9817 void
9818 Call_expression::set_recover_arg(Expression* arg)
9820 this->do_set_recover_arg(arg);
9823 // Virtual functions also implemented by Builtin_call_expression.
9825 bool
9826 Call_expression::do_is_recover_call() const
9828 return false;
9831 void
9832 Call_expression::do_set_recover_arg(Expression*)
9834 go_unreachable();
9837 // We have found an error with this call expression; return true if
9838 // we should report it.
9840 bool
9841 Call_expression::issue_error()
9843 if (this->issued_error_)
9844 return false;
9845 else
9847 this->issued_error_ = true;
9848 return true;
9852 // Whether or not this call contains errors, either in the call or the
9853 // arguments to the call.
9855 bool
9856 Call_expression::is_erroneous_call()
9858 if (this->is_error_expression() || this->fn()->is_error_expression())
9859 return true;
9861 if (this->args() == NULL)
9862 return false;
9863 for (Expression_list::iterator pa = this->args()->begin();
9864 pa != this->args()->end();
9865 ++pa)
9867 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9868 return true;
9870 return false;
9873 // Get the type.
9875 Type*
9876 Call_expression::do_type()
9878 if (this->type_ != NULL)
9879 return this->type_;
9881 Type* ret;
9882 Function_type* fntype = this->get_function_type();
9883 if (fntype == NULL)
9884 return Type::make_error_type();
9886 const Typed_identifier_list* results = fntype->results();
9887 if (results == NULL)
9888 ret = Type::make_void_type();
9889 else if (results->size() == 1)
9890 ret = results->begin()->type();
9891 else
9892 ret = Type::make_call_multiple_result_type(this);
9894 this->type_ = ret;
9896 return this->type_;
9899 // Determine types for a call expression. We can use the function
9900 // parameter types to set the types of the arguments.
9902 void
9903 Call_expression::do_determine_type(const Type_context*)
9905 if (!this->determining_types())
9906 return;
9908 this->fn_->determine_type_no_context();
9909 Function_type* fntype = this->get_function_type();
9910 const Typed_identifier_list* parameters = NULL;
9911 if (fntype != NULL)
9912 parameters = fntype->parameters();
9913 if (this->args_ != NULL)
9915 Typed_identifier_list::const_iterator pt;
9916 if (parameters != NULL)
9917 pt = parameters->begin();
9918 bool first = true;
9919 for (Expression_list::const_iterator pa = this->args_->begin();
9920 pa != this->args_->end();
9921 ++pa)
9923 if (first)
9925 first = false;
9926 // If this is a method, the first argument is the
9927 // receiver.
9928 if (fntype != NULL && fntype->is_method())
9930 Type* rtype = fntype->receiver()->type();
9931 // The receiver is always passed as a pointer.
9932 if (rtype->points_to() == NULL)
9933 rtype = Type::make_pointer_type(rtype);
9934 Type_context subcontext(rtype, false);
9935 (*pa)->determine_type(&subcontext);
9936 continue;
9940 if (parameters != NULL && pt != parameters->end())
9942 Type_context subcontext(pt->type(), false);
9943 (*pa)->determine_type(&subcontext);
9944 ++pt;
9946 else
9947 (*pa)->determine_type_no_context();
9952 // Called when determining types for a Call_expression. Return true
9953 // if we should go ahead, false if they have already been determined.
9955 bool
9956 Call_expression::determining_types()
9958 if (this->types_are_determined_)
9959 return false;
9960 else
9962 this->types_are_determined_ = true;
9963 return true;
9967 // Check types for parameter I.
9969 bool
9970 Call_expression::check_argument_type(int i, const Type* parameter_type,
9971 const Type* argument_type,
9972 Location argument_location,
9973 bool issued_error)
9975 std::string reason;
9976 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9978 if (!issued_error)
9980 if (reason.empty())
9981 go_error_at(argument_location, "argument %d has incompatible type", i);
9982 else
9983 go_error_at(argument_location,
9984 "argument %d has incompatible type (%s)",
9985 i, reason.c_str());
9987 this->set_is_error();
9988 return false;
9990 return true;
9993 // Check types.
9995 void
9996 Call_expression::do_check_types(Gogo*)
9998 if (this->classification() == EXPRESSION_ERROR)
9999 return;
10001 Function_type* fntype = this->get_function_type();
10002 if (fntype == NULL)
10004 if (!this->fn_->type()->is_error())
10005 this->report_error(_("expected function"));
10006 return;
10009 if (this->expected_result_count_ != 0
10010 && this->expected_result_count_ != this->result_count())
10012 if (this->issue_error())
10013 this->report_error(_("function result count mismatch"));
10014 this->set_is_error();
10015 return;
10018 bool is_method = fntype->is_method();
10019 if (is_method)
10021 go_assert(this->args_ != NULL && !this->args_->empty());
10022 Type* rtype = fntype->receiver()->type();
10023 Expression* first_arg = this->args_->front();
10024 // We dereference the values since receivers are always passed
10025 // as pointers.
10026 std::string reason;
10027 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10028 &reason))
10030 if (reason.empty())
10031 this->report_error(_("incompatible type for receiver"));
10032 else
10034 go_error_at(this->location(),
10035 "incompatible type for receiver (%s)",
10036 reason.c_str());
10037 this->set_is_error();
10042 // Note that varargs was handled by the lower_varargs() method, so
10043 // we don't have to worry about it here unless something is wrong.
10044 if (this->is_varargs_ && !this->varargs_are_lowered_)
10046 if (!fntype->is_varargs())
10048 go_error_at(this->location(),
10049 _("invalid use of %<...%> calling non-variadic function"));
10050 this->set_is_error();
10051 return;
10055 const Typed_identifier_list* parameters = fntype->parameters();
10056 if (this->args_ == NULL || this->args_->size() == 0)
10058 if (parameters != NULL && !parameters->empty())
10059 this->report_error(_("not enough arguments"));
10061 else if (parameters == NULL)
10063 if (!is_method || this->args_->size() > 1)
10064 this->report_error(_("too many arguments"));
10066 else if (this->args_->size() == 1
10067 && this->args_->front()->call_expression() != NULL
10068 && this->args_->front()->call_expression()->result_count() > 1)
10070 // This is F(G()) when G returns more than one result. If the
10071 // results can be matched to parameters, it would have been
10072 // lowered in do_lower. If we get here we know there is a
10073 // mismatch.
10074 if (this->args_->front()->call_expression()->result_count()
10075 < parameters->size())
10076 this->report_error(_("not enough arguments"));
10077 else
10078 this->report_error(_("too many arguments"));
10080 else
10082 int i = 0;
10083 Expression_list::const_iterator pa = this->args_->begin();
10084 if (is_method)
10085 ++pa;
10086 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10087 pt != parameters->end();
10088 ++pt, ++pa, ++i)
10090 if (pa == this->args_->end())
10092 this->report_error(_("not enough arguments"));
10093 return;
10095 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10096 (*pa)->location(), false);
10098 if (pa != this->args_->end())
10099 this->report_error(_("too many arguments"));
10103 Expression*
10104 Call_expression::do_copy()
10106 Call_expression* call =
10107 Expression::make_call(this->fn_->copy(),
10108 (this->args_ == NULL
10109 ? NULL
10110 : this->args_->copy()),
10111 this->is_varargs_, this->location());
10113 if (this->varargs_are_lowered_)
10114 call->set_varargs_are_lowered();
10115 return call;
10118 // Return whether we have to use a temporary variable to ensure that
10119 // we evaluate this call expression in order. If the call returns no
10120 // results then it will inevitably be executed last.
10122 bool
10123 Call_expression::do_must_eval_in_order() const
10125 return this->result_count() > 0;
10128 // Get the function and the first argument to use when calling an
10129 // interface method.
10131 Expression*
10132 Call_expression::interface_method_function(
10133 Interface_field_reference_expression* interface_method,
10134 Expression** first_arg_ptr,
10135 Location location)
10137 Expression* object = interface_method->get_underlying_object();
10138 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10139 *first_arg_ptr =
10140 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10141 return interface_method->get_function();
10144 // Build the call expression.
10146 Bexpression*
10147 Call_expression::do_get_backend(Translate_context* context)
10149 Location location = this->location();
10151 if (this->call_ != NULL)
10153 // If the call returns multiple results, make a new reference to
10154 // the temporary.
10155 if (this->call_temp_ != NULL)
10157 Expression* ref =
10158 Expression::make_temporary_reference(this->call_temp_, location);
10159 return ref->get_backend(context);
10162 return this->call_;
10165 Function_type* fntype = this->get_function_type();
10166 if (fntype == NULL)
10167 return context->backend()->error_expression();
10169 if (this->fn_->is_error_expression())
10170 return context->backend()->error_expression();
10172 Gogo* gogo = context->gogo();
10174 Func_expression* func = this->fn_->func_expression();
10175 Interface_field_reference_expression* interface_method =
10176 this->fn_->interface_field_reference_expression();
10177 const bool has_closure = func != NULL && func->closure() != NULL;
10178 const bool is_interface_method = interface_method != NULL;
10180 bool has_closure_arg;
10181 if (has_closure)
10182 has_closure_arg = true;
10183 else if (func != NULL)
10184 has_closure_arg = false;
10185 else if (is_interface_method)
10186 has_closure_arg = false;
10187 else
10188 has_closure_arg = true;
10190 int nargs;
10191 std::vector<Bexpression*> fn_args;
10192 if (this->args_ == NULL || this->args_->empty())
10194 nargs = is_interface_method ? 1 : 0;
10195 if (nargs > 0)
10196 fn_args.resize(1);
10198 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10200 // Passing a receiver parameter.
10201 go_assert(!is_interface_method
10202 && fntype->is_method()
10203 && this->args_->size() == 1);
10204 nargs = 1;
10205 fn_args.resize(1);
10206 fn_args[0] = this->args_->front()->get_backend(context);
10208 else
10210 const Typed_identifier_list* params = fntype->parameters();
10212 nargs = this->args_->size();
10213 int i = is_interface_method ? 1 : 0;
10214 nargs += i;
10215 fn_args.resize(nargs);
10217 Typed_identifier_list::const_iterator pp = params->begin();
10218 Expression_list::const_iterator pe = this->args_->begin();
10219 if (!is_interface_method && fntype->is_method())
10221 fn_args[i] = (*pe)->get_backend(context);
10222 ++pe;
10223 ++i;
10225 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10227 go_assert(pp != params->end());
10228 Expression* arg =
10229 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10230 location);
10231 fn_args[i] = arg->get_backend(context);
10233 go_assert(pp == params->end());
10234 go_assert(i == nargs);
10237 Expression* fn;
10238 Expression* closure = NULL;
10239 if (func != NULL)
10241 Named_object* no = func->named_object();
10242 fn = Expression::make_func_code_reference(no, location);
10243 if (has_closure)
10244 closure = func->closure();
10246 else if (!is_interface_method)
10248 closure = this->fn_;
10250 // The backend representation of this function type is a pointer
10251 // to a struct whose first field is the actual function to call.
10252 Type* pfntype =
10253 Type::make_pointer_type(
10254 Type::make_pointer_type(Type::make_void_type()));
10255 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10256 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10258 else
10260 Expression* first_arg;
10261 fn = this->interface_method_function(interface_method, &first_arg,
10262 location);
10263 fn_args[0] = first_arg->get_backend(context);
10266 Bexpression* bclosure = NULL;
10267 if (has_closure_arg)
10268 bclosure = closure->get_backend(context);
10269 else
10270 go_assert(closure == NULL);
10272 Bexpression* bfn = fn->get_backend(context);
10274 // When not calling a named function directly, use a type conversion
10275 // in case the type of the function is a recursive type which refers
10276 // to itself. We don't do this for an interface method because 1)
10277 // an interface method never refers to itself, so we always have a
10278 // function type here; 2) we pass an extra first argument to an
10279 // interface method, so fntype is not correct.
10280 if (func == NULL && !is_interface_method)
10282 Btype* bft = fntype->get_backend_fntype(gogo);
10283 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10286 Bfunction* bfunction = NULL;
10287 if (context->function())
10288 bfunction = context->function()->func_value()->get_decl();
10289 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10290 fn_args, bclosure,
10291 location);
10293 if (this->call_temp_ != NULL)
10295 // This case occurs when the call returns multiple results.
10297 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10298 location);
10299 Bexpression* bref = ref->get_backend(context);
10300 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10301 bref, call,
10302 location);
10304 ref = Expression::make_temporary_reference(this->call_temp_, location);
10305 this->call_ = ref->get_backend(context);
10307 return gogo->backend()->compound_expression(bassn, this->call_,
10308 location);
10311 this->call_ = call;
10312 return this->call_;
10315 // Dump ast representation for a call expressin.
10317 void
10318 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10320 this->fn_->dump_expression(ast_dump_context);
10321 ast_dump_context->ostream() << "(";
10322 if (args_ != NULL)
10323 ast_dump_context->dump_expression_list(this->args_);
10325 ast_dump_context->ostream() << ") ";
10328 // Make a call expression.
10330 Call_expression*
10331 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10332 Location location)
10334 return new Call_expression(fn, args, is_varargs, location);
10337 // Class Call_result_expression.
10339 // Traverse a call result.
10342 Call_result_expression::do_traverse(Traverse* traverse)
10344 if (traverse->remember_expression(this->call_))
10346 // We have already traversed the call expression.
10347 return TRAVERSE_CONTINUE;
10349 return Expression::traverse(&this->call_, traverse);
10352 // Get the type.
10354 Type*
10355 Call_result_expression::do_type()
10357 if (this->classification() == EXPRESSION_ERROR)
10358 return Type::make_error_type();
10360 // THIS->CALL_ can be replaced with a temporary reference due to
10361 // Call_expression::do_must_eval_in_order when there is an error.
10362 Call_expression* ce = this->call_->call_expression();
10363 if (ce == NULL)
10365 this->set_is_error();
10366 return Type::make_error_type();
10368 Function_type* fntype = ce->get_function_type();
10369 if (fntype == NULL)
10371 if (ce->issue_error())
10373 if (!ce->fn()->type()->is_error())
10374 this->report_error(_("expected function"));
10376 this->set_is_error();
10377 return Type::make_error_type();
10379 const Typed_identifier_list* results = fntype->results();
10380 if (results == NULL || results->size() < 2)
10382 if (ce->issue_error())
10383 this->report_error(_("number of results does not match "
10384 "number of values"));
10385 return Type::make_error_type();
10387 Typed_identifier_list::const_iterator pr = results->begin();
10388 for (unsigned int i = 0; i < this->index_; ++i)
10390 if (pr == results->end())
10391 break;
10392 ++pr;
10394 if (pr == results->end())
10396 if (ce->issue_error())
10397 this->report_error(_("number of results does not match "
10398 "number of values"));
10399 return Type::make_error_type();
10401 return pr->type();
10404 // Check the type. Just make sure that we trigger the warning in
10405 // do_type.
10407 void
10408 Call_result_expression::do_check_types(Gogo*)
10410 this->type();
10413 // Determine the type. We have nothing to do here, but the 0 result
10414 // needs to pass down to the caller.
10416 void
10417 Call_result_expression::do_determine_type(const Type_context*)
10419 this->call_->determine_type_no_context();
10422 // Return the backend representation. We just refer to the temporary set by the
10423 // call expression. We don't do this at lowering time because it makes it
10424 // hard to evaluate the call at the right time.
10426 Bexpression*
10427 Call_result_expression::do_get_backend(Translate_context* context)
10429 Call_expression* ce = this->call_->call_expression();
10430 if (ce == NULL)
10432 go_assert(this->call_->is_error_expression());
10433 return context->backend()->error_expression();
10435 Temporary_statement* ts = ce->results();
10436 if (ts == NULL)
10438 go_assert(saw_errors());
10439 return context->backend()->error_expression();
10441 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10442 ref = Expression::make_field_reference(ref, this->index_, this->location());
10443 return ref->get_backend(context);
10446 // Dump ast representation for a call result expression.
10448 void
10449 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10450 const
10452 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10453 // (struct) and the fields are referenced instead.
10454 ast_dump_context->ostream() << this->index_ << "@(";
10455 ast_dump_context->dump_expression(this->call_);
10456 ast_dump_context->ostream() << ")";
10459 // Make a reference to a single result of a call which returns
10460 // multiple results.
10462 Expression*
10463 Expression::make_call_result(Call_expression* call, unsigned int index)
10465 return new Call_result_expression(call, index);
10468 // Class Index_expression.
10470 // Traversal.
10473 Index_expression::do_traverse(Traverse* traverse)
10475 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10476 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10477 || (this->end_ != NULL
10478 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10479 || (this->cap_ != NULL
10480 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10481 return TRAVERSE_EXIT;
10482 return TRAVERSE_CONTINUE;
10485 // Lower an index expression. This converts the generic index
10486 // expression into an array index, a string index, or a map index.
10488 Expression*
10489 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10491 Location location = this->location();
10492 Expression* left = this->left_;
10493 Expression* start = this->start_;
10494 Expression* end = this->end_;
10495 Expression* cap = this->cap_;
10497 Type* type = left->type();
10498 if (type->is_error())
10500 go_assert(saw_errors());
10501 return Expression::make_error(location);
10503 else if (left->is_type_expression())
10505 go_error_at(location, "attempt to index type expression");
10506 return Expression::make_error(location);
10508 else if (type->array_type() != NULL)
10509 return Expression::make_array_index(left, start, end, cap, location);
10510 else if (type->points_to() != NULL
10511 && type->points_to()->array_type() != NULL
10512 && !type->points_to()->is_slice_type())
10514 Expression* deref =
10515 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10517 // For an ordinary index into the array, the pointer will be
10518 // dereferenced. For a slice it will not--the resulting slice
10519 // will simply reuse the pointer, which is incorrect if that
10520 // pointer is nil.
10521 if (end != NULL || cap != NULL)
10522 deref->issue_nil_check();
10524 return Expression::make_array_index(deref, start, end, cap, location);
10526 else if (type->is_string_type())
10528 if (cap != NULL)
10530 go_error_at(location, "invalid 3-index slice of string");
10531 return Expression::make_error(location);
10533 return Expression::make_string_index(left, start, end, location);
10535 else if (type->map_type() != NULL)
10537 if (end != NULL || cap != NULL)
10539 go_error_at(location, "invalid slice of map");
10540 return Expression::make_error(location);
10542 return Expression::make_map_index(left, start, location);
10544 else if (cap != NULL)
10546 go_error_at(location,
10547 "invalid 3-index slice of object that is not a slice");
10548 return Expression::make_error(location);
10550 else if (end != NULL)
10552 go_error_at(location,
10553 ("attempt to slice object that is not "
10554 "array, slice, or string"));
10555 return Expression::make_error(location);
10557 else
10559 go_error_at(location,
10560 ("attempt to index object that is not "
10561 "array, slice, string, or map"));
10562 return Expression::make_error(location);
10566 // Write an indexed expression
10567 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10569 void
10570 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10571 const Expression* expr,
10572 const Expression* start,
10573 const Expression* end,
10574 const Expression* cap)
10576 expr->dump_expression(ast_dump_context);
10577 ast_dump_context->ostream() << "[";
10578 start->dump_expression(ast_dump_context);
10579 if (end != NULL)
10581 ast_dump_context->ostream() << ":";
10582 end->dump_expression(ast_dump_context);
10584 if (cap != NULL)
10586 ast_dump_context->ostream() << ":";
10587 cap->dump_expression(ast_dump_context);
10589 ast_dump_context->ostream() << "]";
10592 // Dump ast representation for an index expression.
10594 void
10595 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10596 const
10598 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10599 this->start_, this->end_, this->cap_);
10602 // Make an index expression.
10604 Expression*
10605 Expression::make_index(Expression* left, Expression* start, Expression* end,
10606 Expression* cap, Location location)
10608 return new Index_expression(left, start, end, cap, location);
10611 // Class Array_index_expression.
10613 // Array index traversal.
10616 Array_index_expression::do_traverse(Traverse* traverse)
10618 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10619 return TRAVERSE_EXIT;
10620 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10621 return TRAVERSE_EXIT;
10622 if (this->end_ != NULL)
10624 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10625 return TRAVERSE_EXIT;
10627 if (this->cap_ != NULL)
10629 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10630 return TRAVERSE_EXIT;
10632 return TRAVERSE_CONTINUE;
10635 // Return the type of an array index.
10637 Type*
10638 Array_index_expression::do_type()
10640 if (this->type_ == NULL)
10642 Array_type* type = this->array_->type()->array_type();
10643 if (type == NULL)
10644 this->type_ = Type::make_error_type();
10645 else if (this->end_ == NULL)
10646 this->type_ = type->element_type();
10647 else if (type->is_slice_type())
10649 // A slice of a slice has the same type as the original
10650 // slice.
10651 this->type_ = this->array_->type()->deref();
10653 else
10655 // A slice of an array is a slice.
10656 this->type_ = Type::make_array_type(type->element_type(), NULL);
10659 return this->type_;
10662 // Set the type of an array index.
10664 void
10665 Array_index_expression::do_determine_type(const Type_context*)
10667 this->array_->determine_type_no_context();
10669 Type_context index_context(Type::lookup_integer_type("int"), false);
10670 if (this->start_->is_constant())
10671 this->start_->determine_type(&index_context);
10672 else
10673 this->start_->determine_type_no_context();
10674 if (this->end_ != NULL)
10676 if (this->end_->is_constant())
10677 this->end_->determine_type(&index_context);
10678 else
10679 this->end_->determine_type_no_context();
10681 if (this->cap_ != NULL)
10683 if (this->cap_->is_constant())
10684 this->cap_->determine_type(&index_context);
10685 else
10686 this->cap_->determine_type_no_context();
10690 // Check types of an array index.
10692 void
10693 Array_index_expression::do_check_types(Gogo*)
10695 Numeric_constant nc;
10696 unsigned long v;
10697 if (this->start_->type()->integer_type() == NULL
10698 && !this->start_->type()->is_error()
10699 && (!this->start_->numeric_constant_value(&nc)
10700 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10701 this->report_error(_("index must be integer"));
10702 if (this->end_ != NULL
10703 && this->end_->type()->integer_type() == NULL
10704 && !this->end_->type()->is_error()
10705 && !this->end_->is_nil_expression()
10706 && !this->end_->is_error_expression()
10707 && (!this->end_->numeric_constant_value(&nc)
10708 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10709 this->report_error(_("slice end must be integer"));
10710 if (this->cap_ != NULL
10711 && this->cap_->type()->integer_type() == NULL
10712 && !this->cap_->type()->is_error()
10713 && !this->cap_->is_nil_expression()
10714 && !this->cap_->is_error_expression()
10715 && (!this->cap_->numeric_constant_value(&nc)
10716 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10717 this->report_error(_("slice capacity must be integer"));
10719 Array_type* array_type = this->array_->type()->array_type();
10720 if (array_type == NULL)
10722 go_assert(this->array_->type()->is_error());
10723 return;
10726 unsigned int int_bits =
10727 Type::lookup_integer_type("int")->integer_type()->bits();
10729 Numeric_constant lvalnc;
10730 mpz_t lval;
10731 bool lval_valid = (array_type->length() != NULL
10732 && array_type->length()->numeric_constant_value(&lvalnc)
10733 && lvalnc.to_int(&lval));
10734 Numeric_constant inc;
10735 mpz_t ival;
10736 bool ival_valid = false;
10737 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10739 ival_valid = true;
10740 if (mpz_sgn(ival) < 0
10741 || mpz_sizeinbase(ival, 2) >= int_bits
10742 || (lval_valid
10743 && (this->end_ == NULL
10744 ? mpz_cmp(ival, lval) >= 0
10745 : mpz_cmp(ival, lval) > 0)))
10747 go_error_at(this->start_->location(), "array index out of bounds");
10748 this->set_is_error();
10751 if (this->end_ != NULL && !this->end_->is_nil_expression())
10753 Numeric_constant enc;
10754 mpz_t eval;
10755 bool eval_valid = false;
10756 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10758 eval_valid = true;
10759 if (mpz_sgn(eval) < 0
10760 || mpz_sizeinbase(eval, 2) >= int_bits
10761 || (lval_valid && mpz_cmp(eval, lval) > 0))
10763 go_error_at(this->end_->location(), "array index out of bounds");
10764 this->set_is_error();
10766 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10767 this->report_error(_("inverted slice range"));
10770 Numeric_constant cnc;
10771 mpz_t cval;
10772 if (this->cap_ != NULL
10773 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10775 if (mpz_sgn(cval) < 0
10776 || mpz_sizeinbase(cval, 2) >= int_bits
10777 || (lval_valid && mpz_cmp(cval, lval) > 0))
10779 go_error_at(this->cap_->location(), "array index out of bounds");
10780 this->set_is_error();
10782 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10784 go_error_at(this->cap_->location(),
10785 "invalid slice index: capacity less than start");
10786 this->set_is_error();
10788 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10790 go_error_at(this->cap_->location(),
10791 "invalid slice index: capacity less than length");
10792 this->set_is_error();
10794 mpz_clear(cval);
10797 if (eval_valid)
10798 mpz_clear(eval);
10800 if (ival_valid)
10801 mpz_clear(ival);
10802 if (lval_valid)
10803 mpz_clear(lval);
10805 // A slice of an array requires an addressable array. A slice of a
10806 // slice is always possible.
10807 if (this->end_ != NULL && !array_type->is_slice_type())
10809 if (!this->array_->is_addressable())
10810 this->report_error(_("slice of unaddressable value"));
10811 else
10812 // Set the array address taken but not escape. The escape
10813 // analysis will make it escape to heap when needed.
10814 this->array_->address_taken(false);
10818 // Flatten array indexing by using temporary variables for slices and indexes.
10820 Expression*
10821 Array_index_expression::do_flatten(Gogo*, Named_object*,
10822 Statement_inserter* inserter)
10824 Location loc = this->location();
10825 Expression* array = this->array_;
10826 Expression* start = this->start_;
10827 Expression* end = this->end_;
10828 Expression* cap = this->cap_;
10829 if (array->is_error_expression()
10830 || array->type()->is_error_type()
10831 || start->is_error_expression()
10832 || start->type()->is_error_type()
10833 || (end != NULL
10834 && (end->is_error_expression() || end->type()->is_error_type()))
10835 || (cap != NULL
10836 && (cap->is_error_expression() || cap->type()->is_error_type())))
10838 go_assert(saw_errors());
10839 return Expression::make_error(loc);
10842 Temporary_statement* temp;
10843 if (array->type()->is_slice_type() && !array->is_variable())
10845 temp = Statement::make_temporary(NULL, array, loc);
10846 inserter->insert(temp);
10847 this->array_ = Expression::make_temporary_reference(temp, loc);
10849 if (!start->is_variable())
10851 temp = Statement::make_temporary(NULL, start, loc);
10852 inserter->insert(temp);
10853 this->start_ = Expression::make_temporary_reference(temp, loc);
10855 if (end != NULL
10856 && !end->is_nil_expression()
10857 && !end->is_variable())
10859 temp = Statement::make_temporary(NULL, end, loc);
10860 inserter->insert(temp);
10861 this->end_ = Expression::make_temporary_reference(temp, loc);
10863 if (cap != NULL && !cap->is_variable())
10865 temp = Statement::make_temporary(NULL, cap, loc);
10866 inserter->insert(temp);
10867 this->cap_ = Expression::make_temporary_reference(temp, loc);
10870 return this;
10873 // Return whether this expression is addressable.
10875 bool
10876 Array_index_expression::do_is_addressable() const
10878 // A slice expression is not addressable.
10879 if (this->end_ != NULL)
10880 return false;
10882 // An index into a slice is addressable.
10883 if (this->array_->type()->is_slice_type())
10884 return true;
10886 // An index into an array is addressable if the array is
10887 // addressable.
10888 return this->array_->is_addressable();
10891 void
10892 Array_index_expression::do_address_taken(bool escapes)
10894 // In &x[0], if x is a slice, then x's address is not taken.
10895 if (!this->array_->type()->is_slice_type())
10896 this->array_->address_taken(escapes);
10899 // Get the backend representation for an array index.
10901 Bexpression*
10902 Array_index_expression::do_get_backend(Translate_context* context)
10904 Array_type* array_type = this->array_->type()->array_type();
10905 if (array_type == NULL)
10907 go_assert(this->array_->type()->is_error());
10908 return context->backend()->error_expression();
10910 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10912 Location loc = this->location();
10913 Gogo* gogo = context->gogo();
10915 Type* int_type = Type::lookup_integer_type("int");
10916 Btype* int_btype = int_type->get_backend(gogo);
10918 // We need to convert the length and capacity to the Go "int" type here
10919 // because the length of a fixed-length array could be of type "uintptr"
10920 // and gimple disallows binary operations between "uintptr" and other
10921 // integer types. FIXME.
10922 Bexpression* length = NULL;
10923 if (this->end_ == NULL || this->end_->is_nil_expression())
10925 Expression* len = array_type->get_length(gogo, this->array_);
10926 length = len->get_backend(context);
10927 length = gogo->backend()->convert_expression(int_btype, length, loc);
10930 Bexpression* capacity = NULL;
10931 if (this->end_ != NULL)
10933 Expression* cap = array_type->get_capacity(gogo, this->array_);
10934 capacity = cap->get_backend(context);
10935 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10938 Bexpression* cap_arg = capacity;
10939 if (this->cap_ != NULL)
10941 cap_arg = this->cap_->get_backend(context);
10942 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10945 if (length == NULL)
10946 length = cap_arg;
10948 int code = (array_type->length() != NULL
10949 ? (this->end_ == NULL
10950 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10951 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10952 : (this->end_ == NULL
10953 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10954 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10955 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10957 if (this->start_->type()->integer_type() == NULL
10958 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10960 go_assert(saw_errors());
10961 return context->backend()->error_expression();
10964 Bexpression* bad_index =
10965 Expression::check_bounds(this->start_, loc)->get_backend(context);
10967 Bexpression* start = this->start_->get_backend(context);
10968 start = gogo->backend()->convert_expression(int_btype, start, loc);
10969 Bexpression* start_too_large =
10970 gogo->backend()->binary_expression((this->end_ == NULL
10971 ? OPERATOR_GE
10972 : OPERATOR_GT),
10973 start,
10974 (this->end_ == NULL
10975 ? length
10976 : capacity),
10977 loc);
10978 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10979 bad_index, loc);
10981 Bfunction* bfn = context->function()->func_value()->get_decl();
10982 if (this->end_ == NULL)
10984 // Simple array indexing. This has to return an l-value, so
10985 // wrap the index check into START.
10986 start =
10987 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
10988 crash, start, loc);
10990 Bexpression* ret;
10991 if (array_type->length() != NULL)
10993 Bexpression* array = this->array_->get_backend(context);
10994 ret = gogo->backend()->array_index_expression(array, start, loc);
10996 else
10998 // Slice.
10999 Expression* valptr =
11000 array_type->get_value_pointer(gogo, this->array_,
11001 this->is_lvalue_);
11002 Bexpression* ptr = valptr->get_backend(context);
11003 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11005 Type* ele_type = this->array_->type()->array_type()->element_type();
11006 Btype* ele_btype = ele_type->get_backend(gogo);
11007 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11009 return ret;
11012 // Array slice.
11014 if (this->cap_ != NULL)
11016 Bexpression* bounds_bcheck =
11017 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11018 bad_index =
11019 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11020 bad_index, loc);
11021 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11023 Bexpression* cap_too_small =
11024 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11025 Bexpression* cap_too_large =
11026 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11027 Bexpression* bad_cap =
11028 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11029 cap_too_large, loc);
11030 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11031 bad_index, loc);
11034 Bexpression* end;
11035 if (this->end_->is_nil_expression())
11036 end = length;
11037 else
11039 Bexpression* bounds_bcheck =
11040 Expression::check_bounds(this->end_, loc)->get_backend(context);
11042 bad_index =
11043 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11044 bad_index, loc);
11046 end = this->end_->get_backend(context);
11047 end = gogo->backend()->convert_expression(int_btype, end, loc);
11048 Bexpression* end_too_small =
11049 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11050 Bexpression* end_too_large =
11051 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11052 Bexpression* bad_end =
11053 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11054 end_too_large, loc);
11055 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11056 bad_index, loc);
11059 Bexpression* result_length =
11060 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11062 Bexpression* result_capacity =
11063 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11065 // If the new capacity is zero, don't change val. Otherwise we can
11066 // get a pointer to the next object in memory, keeping it live
11067 // unnecessarily. When the capacity is zero, the actual pointer
11068 // value doesn't matter.
11069 Bexpression* zero =
11070 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11071 Bexpression* cond =
11072 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11073 loc);
11074 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11075 cond, zero,
11076 start, loc);
11077 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11078 this->is_lvalue_);
11079 Bexpression* val = valptr->get_backend(context);
11080 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11082 Btype* struct_btype = this->type()->get_backend(gogo);
11083 std::vector<Bexpression*> init;
11084 init.push_back(val);
11085 init.push_back(result_length);
11086 init.push_back(result_capacity);
11088 Bexpression* ctor =
11089 gogo->backend()->constructor_expression(struct_btype, init, loc);
11090 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11091 crash, ctor, loc);
11094 // Dump ast representation for an array index expression.
11096 void
11097 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11098 const
11100 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11101 this->start_, this->end_, this->cap_);
11104 // Make an array index expression. END and CAP may be NULL.
11106 Expression*
11107 Expression::make_array_index(Expression* array, Expression* start,
11108 Expression* end, Expression* cap,
11109 Location location)
11111 return new Array_index_expression(array, start, end, cap, location);
11114 // Class String_index_expression.
11116 // String index traversal.
11119 String_index_expression::do_traverse(Traverse* traverse)
11121 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11122 return TRAVERSE_EXIT;
11123 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11124 return TRAVERSE_EXIT;
11125 if (this->end_ != NULL)
11127 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11128 return TRAVERSE_EXIT;
11130 return TRAVERSE_CONTINUE;
11133 Expression*
11134 String_index_expression::do_flatten(Gogo*, Named_object*,
11135 Statement_inserter* inserter)
11137 Location loc = this->location();
11138 Expression* string = this->string_;
11139 Expression* start = this->start_;
11140 Expression* end = this->end_;
11141 if (string->is_error_expression()
11142 || string->type()->is_error_type()
11143 || start->is_error_expression()
11144 || start->type()->is_error_type()
11145 || (end != NULL
11146 && (end->is_error_expression() || end->type()->is_error_type())))
11148 go_assert(saw_errors());
11149 return Expression::make_error(loc);
11152 Temporary_statement* temp;
11153 if (!this->string_->is_variable())
11155 temp = Statement::make_temporary(NULL, this->string_, loc);
11156 inserter->insert(temp);
11157 this->string_ = Expression::make_temporary_reference(temp, loc);
11159 if (!this->start_->is_variable())
11161 temp = Statement::make_temporary(NULL, this->start_, loc);
11162 inserter->insert(temp);
11163 this->start_ = Expression::make_temporary_reference(temp, loc);
11165 if (this->end_ != NULL
11166 && !this->end_->is_nil_expression()
11167 && !this->end_->is_variable())
11169 temp = Statement::make_temporary(NULL, this->end_, loc);
11170 inserter->insert(temp);
11171 this->end_ = Expression::make_temporary_reference(temp, loc);
11174 return this;
11177 // Return the type of a string index.
11179 Type*
11180 String_index_expression::do_type()
11182 if (this->end_ == NULL)
11183 return Type::lookup_integer_type("uint8");
11184 else
11185 return this->string_->type();
11188 // Determine the type of a string index.
11190 void
11191 String_index_expression::do_determine_type(const Type_context*)
11193 this->string_->determine_type_no_context();
11195 Type_context index_context(Type::lookup_integer_type("int"), false);
11196 if (this->start_->is_constant())
11197 this->start_->determine_type(&index_context);
11198 else
11199 this->start_->determine_type_no_context();
11200 if (this->end_ != NULL)
11202 if (this->end_->is_constant())
11203 this->end_->determine_type(&index_context);
11204 else
11205 this->end_->determine_type_no_context();
11209 // Check types of a string index.
11211 void
11212 String_index_expression::do_check_types(Gogo*)
11214 Numeric_constant nc;
11215 unsigned long v;
11216 if (this->start_->type()->integer_type() == NULL
11217 && !this->start_->type()->is_error()
11218 && (!this->start_->numeric_constant_value(&nc)
11219 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11220 this->report_error(_("index must be integer"));
11221 if (this->end_ != NULL
11222 && this->end_->type()->integer_type() == NULL
11223 && !this->end_->type()->is_error()
11224 && !this->end_->is_nil_expression()
11225 && !this->end_->is_error_expression()
11226 && (!this->end_->numeric_constant_value(&nc)
11227 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11228 this->report_error(_("slice end must be integer"));
11230 std::string sval;
11231 bool sval_valid = this->string_->string_constant_value(&sval);
11233 Numeric_constant inc;
11234 mpz_t ival;
11235 bool ival_valid = false;
11236 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11238 ival_valid = true;
11239 if (mpz_sgn(ival) < 0
11240 || (sval_valid
11241 && (this->end_ == NULL
11242 ? mpz_cmp_ui(ival, sval.length()) >= 0
11243 : mpz_cmp_ui(ival, sval.length()) > 0)))
11245 go_error_at(this->start_->location(), "string index out of bounds");
11246 this->set_is_error();
11249 if (this->end_ != NULL && !this->end_->is_nil_expression())
11251 Numeric_constant enc;
11252 mpz_t eval;
11253 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11255 if (mpz_sgn(eval) < 0
11256 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11258 go_error_at(this->end_->location(), "string index out of bounds");
11259 this->set_is_error();
11261 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11262 this->report_error(_("inverted slice range"));
11263 mpz_clear(eval);
11266 if (ival_valid)
11267 mpz_clear(ival);
11270 // Get the backend representation for a string index.
11272 Bexpression*
11273 String_index_expression::do_get_backend(Translate_context* context)
11275 Location loc = this->location();
11276 Expression* string_arg = this->string_;
11277 if (this->string_->type()->points_to() != NULL)
11278 string_arg = Expression::make_dereference(this->string_,
11279 NIL_CHECK_NOT_NEEDED, loc);
11281 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11283 int code = (this->end_ == NULL
11284 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11285 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11287 Gogo* gogo = context->gogo();
11288 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11290 Type* int_type = Type::lookup_integer_type("int");
11292 // It is possible that an error occurred earlier because the start index
11293 // cannot be represented as an integer type. In this case, we shouldn't
11294 // try casting the starting index into an integer since
11295 // Type_conversion_expression will fail to get the backend representation.
11296 // FIXME.
11297 if (this->start_->type()->integer_type() == NULL
11298 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11300 go_assert(saw_errors());
11301 return context->backend()->error_expression();
11304 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11305 Bfunction* bfn = context->function()->func_value()->get_decl();
11307 if (this->end_ == NULL)
11309 Expression* length =
11310 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11312 Expression* start_too_large =
11313 Expression::make_binary(OPERATOR_GE, start, length, loc);
11314 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11315 bad_index, loc);
11316 Expression* bytes =
11317 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11319 Bexpression* bstart = start->get_backend(context);
11320 Bexpression* ptr = bytes->get_backend(context);
11321 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11322 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11323 Bexpression* index =
11324 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11326 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11327 Bexpression* index_error = bad_index->get_backend(context);
11328 return gogo->backend()->conditional_expression(bfn, byte_btype,
11329 index_error, crash,
11330 index, loc);
11333 Expression* end = NULL;
11334 if (this->end_->is_nil_expression())
11335 end = Expression::make_integer_sl(-1, int_type, loc);
11336 else
11338 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11339 bad_index =
11340 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11341 end = Expression::make_cast(int_type, this->end_, loc);
11344 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11345 string_arg, start, end);
11346 Bexpression* bstrslice = strslice->get_backend(context);
11348 Btype* str_btype = strslice->type()->get_backend(gogo);
11349 Bexpression* index_error = bad_index->get_backend(context);
11350 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11351 crash, bstrslice, loc);
11354 // Dump ast representation for a string index expression.
11356 void
11357 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11358 const
11360 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11361 this->start_, this->end_, NULL);
11364 // Make a string index expression. END may be NULL.
11366 Expression*
11367 Expression::make_string_index(Expression* string, Expression* start,
11368 Expression* end, Location location)
11370 return new String_index_expression(string, start, end, location);
11373 // Class Map_index.
11375 // Get the type of the map.
11377 Map_type*
11378 Map_index_expression::get_map_type() const
11380 Map_type* mt = this->map_->type()->map_type();
11381 if (mt == NULL)
11382 go_assert(saw_errors());
11383 return mt;
11386 // Map index traversal.
11389 Map_index_expression::do_traverse(Traverse* traverse)
11391 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11392 return TRAVERSE_EXIT;
11393 return Expression::traverse(&this->index_, traverse);
11396 // We need to pass in a pointer to the key, so flatten the index into a
11397 // temporary variable if it isn't already. The value pointer will be
11398 // dereferenced and checked for nil, so flatten into a temporary to avoid
11399 // recomputation.
11401 Expression*
11402 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11403 Statement_inserter* inserter)
11405 Location loc = this->location();
11406 Map_type* mt = this->get_map_type();
11407 if (this->index()->is_error_expression()
11408 || this->index()->type()->is_error_type()
11409 || mt->is_error_type())
11411 go_assert(saw_errors());
11412 return Expression::make_error(loc);
11415 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11417 if (this->index_->type()->interface_type() != NULL
11418 && !this->index_->is_variable())
11420 Temporary_statement* temp =
11421 Statement::make_temporary(NULL, this->index_, loc);
11422 inserter->insert(temp);
11423 this->index_ = Expression::make_temporary_reference(temp, loc);
11425 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11426 this->index_, loc);
11429 if (!this->index_->is_variable())
11431 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11432 loc);
11433 inserter->insert(temp);
11434 this->index_ = Expression::make_temporary_reference(temp, loc);
11437 if (this->value_pointer_ == NULL)
11438 this->get_value_pointer(gogo);
11439 if (this->value_pointer_->is_error_expression()
11440 || this->value_pointer_->type()->is_error_type())
11441 return Expression::make_error(loc);
11442 if (!this->value_pointer_->is_variable())
11444 Temporary_statement* temp =
11445 Statement::make_temporary(NULL, this->value_pointer_, loc);
11446 inserter->insert(temp);
11447 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11450 return this;
11453 // Return the type of a map index.
11455 Type*
11456 Map_index_expression::do_type()
11458 Map_type* mt = this->get_map_type();
11459 if (mt == NULL)
11460 return Type::make_error_type();
11461 return mt->val_type();
11464 // Fix the type of a map index.
11466 void
11467 Map_index_expression::do_determine_type(const Type_context*)
11469 this->map_->determine_type_no_context();
11470 Map_type* mt = this->get_map_type();
11471 Type* key_type = mt == NULL ? NULL : mt->key_type();
11472 Type_context subcontext(key_type, false);
11473 this->index_->determine_type(&subcontext);
11476 // Check types of a map index.
11478 void
11479 Map_index_expression::do_check_types(Gogo*)
11481 std::string reason;
11482 Map_type* mt = this->get_map_type();
11483 if (mt == NULL)
11484 return;
11485 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11487 if (reason.empty())
11488 this->report_error(_("incompatible type for map index"));
11489 else
11491 go_error_at(this->location(), "incompatible type for map index (%s)",
11492 reason.c_str());
11493 this->set_is_error();
11498 // Get the backend representation for a map index.
11500 Bexpression*
11501 Map_index_expression::do_get_backend(Translate_context* context)
11503 Map_type* type = this->get_map_type();
11504 if (type == NULL)
11506 go_assert(saw_errors());
11507 return context->backend()->error_expression();
11510 go_assert(this->value_pointer_ != NULL
11511 && this->value_pointer_->is_variable());
11513 Expression* val = Expression::make_dereference(this->value_pointer_,
11514 NIL_CHECK_NOT_NEEDED,
11515 this->location());
11516 return val->get_backend(context);
11519 // Get an expression for the map index. This returns an expression
11520 // that evaluates to a pointer to a value. If the key is not in the
11521 // map, the pointer will point to a zero value.
11523 Expression*
11524 Map_index_expression::get_value_pointer(Gogo* gogo)
11526 if (this->value_pointer_ == NULL)
11528 Map_type* type = this->get_map_type();
11529 if (type == NULL)
11531 go_assert(saw_errors());
11532 return Expression::make_error(this->location());
11535 Location loc = this->location();
11536 Expression* map_ref = this->map_;
11538 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11539 this->index_,
11540 loc);
11542 Expression* zero = type->fat_zero_value(gogo);
11544 Expression* map_index;
11546 if (zero == NULL)
11547 map_index =
11548 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11549 Expression::make_type_descriptor(type, loc),
11550 map_ref, index_ptr);
11551 else
11552 map_index =
11553 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11554 Expression::make_type_descriptor(type, loc),
11555 map_ref, index_ptr, zero);
11557 Type* val_type = type->val_type();
11558 this->value_pointer_ =
11559 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11560 map_index, this->location());
11563 return this->value_pointer_;
11566 // Dump ast representation for a map index expression
11568 void
11569 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11570 const
11572 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11573 this->index_, NULL, NULL);
11576 // Make a map index expression.
11578 Map_index_expression*
11579 Expression::make_map_index(Expression* map, Expression* index,
11580 Location location)
11582 return new Map_index_expression(map, index, location);
11585 // Class Field_reference_expression.
11587 // Lower a field reference expression. There is nothing to lower, but
11588 // this is where we generate the tracking information for fields with
11589 // the magic go:"track" tag.
11591 Expression*
11592 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11593 Statement_inserter* inserter, int)
11595 Struct_type* struct_type = this->expr_->type()->struct_type();
11596 if (struct_type == NULL)
11598 // Error will be reported elsewhere.
11599 return this;
11601 const Struct_field* field = struct_type->field(this->field_index_);
11602 if (field == NULL)
11603 return this;
11604 if (!field->has_tag())
11605 return this;
11606 if (field->tag().find("go:\"track\"") == std::string::npos)
11607 return this;
11609 // References from functions generated by the compiler don't count.
11610 if (function != NULL && function->func_value()->is_type_specific_function())
11611 return this;
11613 // We have found a reference to a tracked field. Build a call to
11614 // the runtime function __go_fieldtrack with a string that describes
11615 // the field. FIXME: We should only call this once per referenced
11616 // field per function, not once for each reference to the field.
11618 if (this->called_fieldtrack_)
11619 return this;
11620 this->called_fieldtrack_ = true;
11622 Location loc = this->location();
11624 std::string s = "fieldtrack \"";
11625 Named_type* nt = this->expr_->type()->named_type();
11626 if (nt == NULL || nt->named_object()->package() == NULL)
11627 s.append(gogo->pkgpath());
11628 else
11629 s.append(nt->named_object()->package()->pkgpath());
11630 s.push_back('.');
11631 if (nt != NULL)
11632 s.append(Gogo::unpack_hidden_name(nt->name()));
11633 s.push_back('.');
11634 s.append(field->field_name());
11635 s.push_back('"');
11637 // We can't use a string here, because internally a string holds a
11638 // pointer to the actual bytes; when the linker garbage collects the
11639 // string, it won't garbage collect the bytes. So we use a
11640 // [...]byte.
11642 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11644 Type* byte_type = gogo->lookup_global("byte")->type_value();
11645 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11646 array_type->set_is_array_incomparable();
11648 Expression_list* bytes = new Expression_list();
11649 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11651 unsigned char c = static_cast<unsigned char>(*p);
11652 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11655 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11656 bytes, false, loc);
11658 Variable* var = new Variable(array_type, e, true, false, false, loc);
11660 static int count;
11661 char buf[50];
11662 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11663 ++count;
11665 Named_object* no = gogo->add_variable(buf, var);
11666 e = Expression::make_var_reference(no, loc);
11667 e = Expression::make_unary(OPERATOR_AND, e, loc);
11669 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11670 gogo->lower_expression(function, inserter, &call);
11671 inserter->insert(Statement::make_statement(call, false));
11673 // Put this function, and the global variable we just created, into
11674 // unique sections. This will permit the linker to garbage collect
11675 // them if they are not referenced. The effect is that the only
11676 // strings, indicating field references, that will wind up in the
11677 // executable will be those for functions that are actually needed.
11678 if (function != NULL)
11679 function->func_value()->set_in_unique_section();
11680 var->set_in_unique_section();
11682 return this;
11685 // Return the type of a field reference.
11687 Type*
11688 Field_reference_expression::do_type()
11690 Type* type = this->expr_->type();
11691 if (type->is_error())
11692 return type;
11693 Struct_type* struct_type = type->struct_type();
11694 go_assert(struct_type != NULL);
11695 return struct_type->field(this->field_index_)->type();
11698 // Check the types for a field reference.
11700 void
11701 Field_reference_expression::do_check_types(Gogo*)
11703 Type* type = this->expr_->type();
11704 if (type->is_error())
11705 return;
11706 Struct_type* struct_type = type->struct_type();
11707 go_assert(struct_type != NULL);
11708 go_assert(struct_type->field(this->field_index_) != NULL);
11711 // Get the backend representation for a field reference.
11713 Bexpression*
11714 Field_reference_expression::do_get_backend(Translate_context* context)
11716 Bexpression* bstruct = this->expr_->get_backend(context);
11717 return context->gogo()->backend()->struct_field_expression(bstruct,
11718 this->field_index_,
11719 this->location());
11722 // Dump ast representation for a field reference expression.
11724 void
11725 Field_reference_expression::do_dump_expression(
11726 Ast_dump_context* ast_dump_context) const
11728 this->expr_->dump_expression(ast_dump_context);
11729 ast_dump_context->ostream() << "." << this->field_index_;
11732 // Make a reference to a qualified identifier in an expression.
11734 Field_reference_expression*
11735 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11736 Location location)
11738 return new Field_reference_expression(expr, field_index, location);
11741 // Class Interface_field_reference_expression.
11743 // Return an expression for the pointer to the function to call.
11745 Expression*
11746 Interface_field_reference_expression::get_function()
11748 Expression* ref = this->expr_;
11749 Location loc = this->location();
11750 if (ref->type()->points_to() != NULL)
11751 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
11753 Expression* mtable =
11754 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11755 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11757 std::string name = Gogo::unpack_hidden_name(this->name_);
11758 unsigned int index;
11759 const Struct_field* field = mtable_type->find_local_field(name, &index);
11760 go_assert(field != NULL);
11762 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
11763 return Expression::make_field_reference(mtable, index, loc);
11766 // Return an expression for the first argument to pass to the interface
11767 // function.
11769 Expression*
11770 Interface_field_reference_expression::get_underlying_object()
11772 Expression* expr = this->expr_;
11773 if (expr->type()->points_to() != NULL)
11774 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
11775 this->location());
11776 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11777 this->location());
11780 // Traversal.
11783 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11785 return Expression::traverse(&this->expr_, traverse);
11788 // Lower the expression. If this expression is not called, we need to
11789 // evaluate the expression twice when converting to the backend
11790 // interface. So introduce a temporary variable if necessary.
11792 Expression*
11793 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11794 Statement_inserter* inserter)
11796 if (this->expr_->is_error_expression()
11797 || this->expr_->type()->is_error_type())
11799 go_assert(saw_errors());
11800 return Expression::make_error(this->location());
11803 if (!this->expr_->is_variable())
11805 Temporary_statement* temp =
11806 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11807 inserter->insert(temp);
11808 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11809 this->location());
11811 return this;
11814 // Return the type of an interface field reference.
11816 Type*
11817 Interface_field_reference_expression::do_type()
11819 Type* expr_type = this->expr_->type();
11821 Type* points_to = expr_type->points_to();
11822 if (points_to != NULL)
11823 expr_type = points_to;
11825 Interface_type* interface_type = expr_type->interface_type();
11826 if (interface_type == NULL)
11827 return Type::make_error_type();
11829 const Typed_identifier* method = interface_type->find_method(this->name_);
11830 if (method == NULL)
11831 return Type::make_error_type();
11833 return method->type();
11836 // Determine types.
11838 void
11839 Interface_field_reference_expression::do_determine_type(const Type_context*)
11841 this->expr_->determine_type_no_context();
11844 // Check the types for an interface field reference.
11846 void
11847 Interface_field_reference_expression::do_check_types(Gogo*)
11849 Type* type = this->expr_->type();
11851 Type* points_to = type->points_to();
11852 if (points_to != NULL)
11853 type = points_to;
11855 Interface_type* interface_type = type->interface_type();
11856 if (interface_type == NULL)
11858 if (!type->is_error_type())
11859 this->report_error(_("expected interface or pointer to interface"));
11861 else
11863 const Typed_identifier* method =
11864 interface_type->find_method(this->name_);
11865 if (method == NULL)
11867 go_error_at(this->location(), "method %qs not in interface",
11868 Gogo::message_name(this->name_).c_str());
11869 this->set_is_error();
11874 // If an interface field reference is not simply called, then it is
11875 // represented as a closure. The closure will hold a single variable,
11876 // the value of the interface on which the method should be called.
11877 // The function will be a simple thunk that pulls the value from the
11878 // closure and calls the method with the remaining arguments.
11880 // Because method values are not common, we don't build all thunks for
11881 // all possible interface methods, but instead only build them as we
11882 // need them. In particular, we even build them on demand for
11883 // interface methods defined in other packages.
11885 Interface_field_reference_expression::Interface_method_thunks
11886 Interface_field_reference_expression::interface_method_thunks;
11888 // Find or create the thunk to call method NAME on TYPE.
11890 Named_object*
11891 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11892 Interface_type* type,
11893 const std::string& name)
11895 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11896 std::pair<Interface_method_thunks::iterator, bool> ins =
11897 Interface_field_reference_expression::interface_method_thunks.insert(val);
11898 if (ins.second)
11900 // This is the first time we have seen this interface.
11901 ins.first->second = new Method_thunks();
11904 for (Method_thunks::const_iterator p = ins.first->second->begin();
11905 p != ins.first->second->end();
11906 p++)
11907 if (p->first == name)
11908 return p->second;
11910 Location loc = type->location();
11912 const Typed_identifier* method_id = type->find_method(name);
11913 if (method_id == NULL)
11914 return Named_object::make_erroneous_name(Gogo::thunk_name());
11916 Function_type* orig_fntype = method_id->type()->function_type();
11917 if (orig_fntype == NULL)
11918 return Named_object::make_erroneous_name(Gogo::thunk_name());
11920 Struct_field_list* sfl = new Struct_field_list();
11921 // The type here is wrong--it should be the C function type. But it
11922 // doesn't really matter.
11923 Type* vt = Type::make_pointer_type(Type::make_void_type());
11924 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11925 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11926 Struct_type* st = Type::make_struct_type(sfl, loc);
11927 st->set_is_struct_incomparable();
11928 Type* closure_type = Type::make_pointer_type(st);
11930 Function_type* new_fntype = orig_fntype->copy_with_names();
11932 std::string thunk_name = Gogo::thunk_name();
11933 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11934 false, loc);
11936 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11937 cvar->set_is_used();
11938 cvar->set_is_closure();
11939 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11940 NULL, cvar);
11941 new_no->func_value()->set_closure_var(cp);
11943 gogo->start_block(loc);
11945 // Field 0 of the closure is the function code pointer, field 1 is
11946 // the value on which to invoke the method.
11947 Expression* arg = Expression::make_var_reference(cp, loc);
11948 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
11949 arg = Expression::make_field_reference(arg, 1, loc);
11951 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11952 loc);
11954 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11955 Expression_list* args;
11956 if (orig_params == NULL || orig_params->empty())
11957 args = NULL;
11958 else
11960 const Typed_identifier_list* new_params = new_fntype->parameters();
11961 args = new Expression_list();
11962 for (Typed_identifier_list::const_iterator p = new_params->begin();
11963 p != new_params->end();
11964 ++p)
11966 Named_object* p_no = gogo->lookup(p->name(), NULL);
11967 go_assert(p_no != NULL
11968 && p_no->is_variable()
11969 && p_no->var_value()->is_parameter());
11970 args->push_back(Expression::make_var_reference(p_no, loc));
11974 Call_expression* call = Expression::make_call(ifre, args,
11975 orig_fntype->is_varargs(),
11976 loc);
11977 call->set_varargs_are_lowered();
11979 Statement* s = Statement::make_return_from_call(call, loc);
11980 gogo->add_statement(s);
11981 Block* b = gogo->finish_block(loc);
11982 gogo->add_block(b, loc);
11983 gogo->lower_block(new_no, b);
11984 gogo->flatten_block(new_no, b);
11985 gogo->finish_function(loc);
11987 ins.first->second->push_back(std::make_pair(name, new_no));
11988 return new_no;
11991 // Get the backend representation for a method value.
11993 Bexpression*
11994 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11996 Interface_type* type = this->expr_->type()->interface_type();
11997 if (type == NULL)
11999 go_assert(saw_errors());
12000 return context->backend()->error_expression();
12003 Named_object* thunk =
12004 Interface_field_reference_expression::create_thunk(context->gogo(),
12005 type, this->name_);
12006 if (thunk->is_erroneous())
12008 go_assert(saw_errors());
12009 return context->backend()->error_expression();
12012 // FIXME: We should lower this earlier, but we can't it lower it in
12013 // the lowering pass because at that point we don't know whether we
12014 // need to create the thunk or not. If the expression is called, we
12015 // don't need the thunk.
12017 Location loc = this->location();
12019 Struct_field_list* fields = new Struct_field_list();
12020 fields->push_back(Struct_field(Typed_identifier("fn.0",
12021 thunk->func_value()->type(),
12022 loc)));
12023 fields->push_back(Struct_field(Typed_identifier("val.1",
12024 this->expr_->type(),
12025 loc)));
12026 Struct_type* st = Type::make_struct_type(fields, loc);
12027 st->set_is_struct_incomparable();
12029 Expression_list* vals = new Expression_list();
12030 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12031 vals->push_back(this->expr_);
12033 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12034 Bexpression* bclosure =
12035 Expression::make_heap_expression(expr, loc)->get_backend(context);
12037 Gogo* gogo = context->gogo();
12038 Btype* btype = this->type()->get_backend(gogo);
12039 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12041 Expression* nil_check =
12042 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12043 Expression::make_nil(loc), loc);
12044 Bexpression* bnil_check = nil_check->get_backend(context);
12046 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12047 loc)->get_backend(context);
12049 Bfunction* bfn = context->function()->func_value()->get_decl();
12050 Bexpression* bcond =
12051 gogo->backend()->conditional_expression(bfn, NULL,
12052 bnil_check, bcrash, NULL, loc);
12053 Bfunction* bfunction = context->function()->func_value()->get_decl();
12054 Bstatement* cond_statement =
12055 gogo->backend()->expression_statement(bfunction, bcond);
12056 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12059 // Dump ast representation for an interface field reference.
12061 void
12062 Interface_field_reference_expression::do_dump_expression(
12063 Ast_dump_context* ast_dump_context) const
12065 this->expr_->dump_expression(ast_dump_context);
12066 ast_dump_context->ostream() << "." << this->name_;
12069 // Make a reference to a field in an interface.
12071 Expression*
12072 Expression::make_interface_field_reference(Expression* expr,
12073 const std::string& field,
12074 Location location)
12076 return new Interface_field_reference_expression(expr, field, location);
12079 // A general selector. This is a Parser_expression for LEFT.NAME. It
12080 // is lowered after we know the type of the left hand side.
12082 class Selector_expression : public Parser_expression
12084 public:
12085 Selector_expression(Expression* left, const std::string& name,
12086 Location location)
12087 : Parser_expression(EXPRESSION_SELECTOR, location),
12088 left_(left), name_(name)
12091 protected:
12093 do_traverse(Traverse* traverse)
12094 { return Expression::traverse(&this->left_, traverse); }
12096 Expression*
12097 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12099 Expression*
12100 do_copy()
12102 return new Selector_expression(this->left_->copy(), this->name_,
12103 this->location());
12106 void
12107 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12109 private:
12110 Expression*
12111 lower_method_expression(Gogo*);
12113 // The expression on the left hand side.
12114 Expression* left_;
12115 // The name on the right hand side.
12116 std::string name_;
12119 // Lower a selector expression once we know the real type of the left
12120 // hand side.
12122 Expression*
12123 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12124 int)
12126 Expression* left = this->left_;
12127 if (left->is_type_expression())
12128 return this->lower_method_expression(gogo);
12129 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12130 this->location());
12133 // Lower a method expression T.M or (*T).M. We turn this into a
12134 // function literal.
12136 Expression*
12137 Selector_expression::lower_method_expression(Gogo* gogo)
12139 Location location = this->location();
12140 Type* left_type = this->left_->type();
12141 Type* type = left_type;
12142 const std::string& name(this->name_);
12144 bool is_pointer;
12145 if (type->points_to() == NULL)
12146 is_pointer = false;
12147 else
12149 is_pointer = true;
12150 type = type->points_to();
12152 Named_type* nt = type->named_type();
12153 if (nt == NULL)
12155 go_error_at(location,
12156 ("method expression requires named type or "
12157 "pointer to named type"));
12158 return Expression::make_error(location);
12161 bool is_ambiguous;
12162 Method* method = nt->method_function(name, &is_ambiguous);
12163 const Typed_identifier* imethod = NULL;
12164 if (method == NULL && !is_pointer)
12166 Interface_type* it = nt->interface_type();
12167 if (it != NULL)
12168 imethod = it->find_method(name);
12171 if ((method == NULL && imethod == NULL)
12172 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12174 if (!is_ambiguous)
12175 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12176 is_pointer ? "*" : "",
12177 nt->message_name().c_str(),
12178 Gogo::message_name(name).c_str());
12179 else
12180 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12181 Gogo::message_name(name).c_str(),
12182 is_pointer ? "*" : "",
12183 nt->message_name().c_str());
12184 return Expression::make_error(location);
12187 if (method != NULL && !is_pointer && !method->is_value_method())
12189 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12190 nt->message_name().c_str(),
12191 Gogo::message_name(name).c_str());
12192 return Expression::make_error(location);
12195 // Build a new function type in which the receiver becomes the first
12196 // argument.
12197 Function_type* method_type;
12198 if (method != NULL)
12200 method_type = method->type();
12201 go_assert(method_type->is_method());
12203 else
12205 method_type = imethod->type()->function_type();
12206 go_assert(method_type != NULL && !method_type->is_method());
12209 const char* const receiver_name = "$this";
12210 Typed_identifier_list* parameters = new Typed_identifier_list();
12211 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12212 location));
12214 const Typed_identifier_list* method_parameters = method_type->parameters();
12215 if (method_parameters != NULL)
12217 int i = 0;
12218 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12219 p != method_parameters->end();
12220 ++p, ++i)
12222 if (!p->name().empty())
12223 parameters->push_back(*p);
12224 else
12226 char buf[20];
12227 snprintf(buf, sizeof buf, "$param%d", i);
12228 parameters->push_back(Typed_identifier(buf, p->type(),
12229 p->location()));
12234 const Typed_identifier_list* method_results = method_type->results();
12235 Typed_identifier_list* results;
12236 if (method_results == NULL)
12237 results = NULL;
12238 else
12240 results = new Typed_identifier_list();
12241 for (Typed_identifier_list::const_iterator p = method_results->begin();
12242 p != method_results->end();
12243 ++p)
12244 results->push_back(*p);
12247 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12248 location);
12249 if (method_type->is_varargs())
12250 fntype->set_is_varargs();
12252 // We generate methods which always takes a pointer to the receiver
12253 // as their first argument. If this is for a pointer type, we can
12254 // simply reuse the existing function. We use an internal hack to
12255 // get the right type.
12256 // FIXME: This optimization is disabled because it doesn't yet work
12257 // with function descriptors when the method expression is not
12258 // directly called.
12259 if (method != NULL && is_pointer && false)
12261 Named_object* mno = (method->needs_stub_method()
12262 ? method->stub_object()
12263 : method->named_object());
12264 Expression* f = Expression::make_func_reference(mno, NULL, location);
12265 f = Expression::make_cast(fntype, f, location);
12266 Type_conversion_expression* tce =
12267 static_cast<Type_conversion_expression*>(f);
12268 tce->set_may_convert_function_types();
12269 return f;
12272 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12273 location);
12275 Named_object* vno = gogo->lookup(receiver_name, NULL);
12276 go_assert(vno != NULL);
12277 Expression* ve = Expression::make_var_reference(vno, location);
12278 Expression* bm;
12279 if (method != NULL)
12280 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12281 else
12282 bm = Expression::make_interface_field_reference(ve, name, location);
12284 // Even though we found the method above, if it has an error type we
12285 // may see an error here.
12286 if (bm->is_error_expression())
12288 gogo->finish_function(location);
12289 return bm;
12292 Expression_list* args;
12293 if (parameters->size() <= 1)
12294 args = NULL;
12295 else
12297 args = new Expression_list();
12298 Typed_identifier_list::const_iterator p = parameters->begin();
12299 ++p;
12300 for (; p != parameters->end(); ++p)
12302 vno = gogo->lookup(p->name(), NULL);
12303 go_assert(vno != NULL);
12304 args->push_back(Expression::make_var_reference(vno, location));
12308 gogo->start_block(location);
12310 Call_expression* call = Expression::make_call(bm, args,
12311 method_type->is_varargs(),
12312 location);
12314 Statement* s = Statement::make_return_from_call(call, location);
12315 gogo->add_statement(s);
12317 Block* b = gogo->finish_block(location);
12319 gogo->add_block(b, location);
12321 // Lower the call in case there are multiple results.
12322 gogo->lower_block(no, b);
12323 gogo->flatten_block(no, b);
12325 gogo->finish_function(location);
12327 return Expression::make_func_reference(no, NULL, location);
12330 // Dump the ast for a selector expression.
12332 void
12333 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12334 const
12336 ast_dump_context->dump_expression(this->left_);
12337 ast_dump_context->ostream() << ".";
12338 ast_dump_context->ostream() << this->name_;
12341 // Make a selector expression.
12343 Expression*
12344 Expression::make_selector(Expression* left, const std::string& name,
12345 Location location)
12347 return new Selector_expression(left, name, location);
12350 // Class Allocation_expression.
12353 Allocation_expression::do_traverse(Traverse* traverse)
12355 return Type::traverse(this->type_, traverse);
12358 Type*
12359 Allocation_expression::do_type()
12361 return Type::make_pointer_type(this->type_);
12364 void
12365 Allocation_expression::do_check_types(Gogo*)
12367 if (!this->type_->in_heap())
12368 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12371 // Make a copy of an allocation expression.
12373 Expression*
12374 Allocation_expression::do_copy()
12376 Allocation_expression* alloc =
12377 new Allocation_expression(this->type_, this->location());
12378 if (this->allocate_on_stack_)
12379 alloc->set_allocate_on_stack();
12380 return alloc;
12383 // Return the backend representation for an allocation expression.
12385 Bexpression*
12386 Allocation_expression::do_get_backend(Translate_context* context)
12388 Gogo* gogo = context->gogo();
12389 Location loc = this->location();
12390 Btype* btype = this->type_->get_backend(gogo);
12392 if (this->allocate_on_stack_)
12394 int64_t size;
12395 bool ok = this->type_->backend_type_size(gogo, &size);
12396 if (!ok)
12398 go_assert(saw_errors());
12399 return gogo->backend()->error_expression();
12401 Bstatement* decl;
12402 Named_object* fn = context->function();
12403 go_assert(fn != NULL);
12404 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
12405 Bexpression* zero = gogo->backend()->zero_expression(btype);
12406 Bvariable* temp =
12407 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
12408 zero, true, loc, &decl);
12409 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
12410 ret = gogo->backend()->address_expression(ret, loc);
12411 ret = gogo->backend()->compound_expression(decl, ret, loc);
12412 return ret;
12415 Bexpression* space =
12416 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12417 Btype* pbtype = gogo->backend()->pointer_type(btype);
12418 return gogo->backend()->convert_expression(pbtype, space, loc);
12421 // Dump ast representation for an allocation expression.
12423 void
12424 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12425 const
12427 ast_dump_context->ostream() << "new(";
12428 ast_dump_context->dump_type(this->type_);
12429 ast_dump_context->ostream() << ")";
12432 // Make an allocation expression.
12434 Expression*
12435 Expression::make_allocation(Type* type, Location location)
12437 return new Allocation_expression(type, location);
12440 // Class Ordered_value_list.
12443 Ordered_value_list::traverse_vals(Traverse* traverse)
12445 if (this->vals_ != NULL)
12447 if (this->traverse_order_ == NULL)
12449 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12450 return TRAVERSE_EXIT;
12452 else
12454 for (std::vector<unsigned long>::const_iterator p =
12455 this->traverse_order_->begin();
12456 p != this->traverse_order_->end();
12457 ++p)
12459 if (Expression::traverse(&this->vals_->at(*p), traverse)
12460 == TRAVERSE_EXIT)
12461 return TRAVERSE_EXIT;
12465 return TRAVERSE_CONTINUE;
12468 // Class Struct_construction_expression.
12470 // Traversal.
12473 Struct_construction_expression::do_traverse(Traverse* traverse)
12475 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12476 return TRAVERSE_EXIT;
12477 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12478 return TRAVERSE_EXIT;
12479 return TRAVERSE_CONTINUE;
12482 // Return whether this is a constant initializer.
12484 bool
12485 Struct_construction_expression::is_constant_struct() const
12487 if (this->vals() == NULL)
12488 return true;
12489 for (Expression_list::const_iterator pv = this->vals()->begin();
12490 pv != this->vals()->end();
12491 ++pv)
12493 if (*pv != NULL
12494 && !(*pv)->is_constant()
12495 && (!(*pv)->is_composite_literal()
12496 || (*pv)->is_nonconstant_composite_literal()))
12497 return false;
12500 const Struct_field_list* fields = this->type_->struct_type()->fields();
12501 for (Struct_field_list::const_iterator pf = fields->begin();
12502 pf != fields->end();
12503 ++pf)
12505 // There are no constant constructors for interfaces.
12506 if (pf->type()->interface_type() != NULL)
12507 return false;
12510 return true;
12513 // Return whether this struct can be used as a constant initializer.
12515 bool
12516 Struct_construction_expression::do_is_static_initializer() const
12518 if (this->vals() == NULL)
12519 return true;
12520 for (Expression_list::const_iterator pv = this->vals()->begin();
12521 pv != this->vals()->end();
12522 ++pv)
12524 if (*pv != NULL && !(*pv)->is_static_initializer())
12525 return false;
12528 const Struct_field_list* fields = this->type_->struct_type()->fields();
12529 for (Struct_field_list::const_iterator pf = fields->begin();
12530 pf != fields->end();
12531 ++pf)
12533 // There are no constant constructors for interfaces.
12534 if (pf->type()->interface_type() != NULL)
12535 return false;
12538 return true;
12541 // Final type determination.
12543 void
12544 Struct_construction_expression::do_determine_type(const Type_context*)
12546 if (this->vals() == NULL)
12547 return;
12548 const Struct_field_list* fields = this->type_->struct_type()->fields();
12549 Expression_list::const_iterator pv = this->vals()->begin();
12550 for (Struct_field_list::const_iterator pf = fields->begin();
12551 pf != fields->end();
12552 ++pf, ++pv)
12554 if (pv == this->vals()->end())
12555 return;
12556 if (*pv != NULL)
12558 Type_context subcontext(pf->type(), false);
12559 (*pv)->determine_type(&subcontext);
12562 // Extra values are an error we will report elsewhere; we still want
12563 // to determine the type to avoid knockon errors.
12564 for (; pv != this->vals()->end(); ++pv)
12565 (*pv)->determine_type_no_context();
12568 // Check types.
12570 void
12571 Struct_construction_expression::do_check_types(Gogo*)
12573 if (this->vals() == NULL)
12574 return;
12576 Struct_type* st = this->type_->struct_type();
12577 if (this->vals()->size() > st->field_count())
12579 this->report_error(_("too many expressions for struct"));
12580 return;
12583 const Struct_field_list* fields = st->fields();
12584 Expression_list::const_iterator pv = this->vals()->begin();
12585 int i = 0;
12586 for (Struct_field_list::const_iterator pf = fields->begin();
12587 pf != fields->end();
12588 ++pf, ++pv, ++i)
12590 if (pv == this->vals()->end())
12592 this->report_error(_("too few expressions for struct"));
12593 break;
12596 if (*pv == NULL)
12597 continue;
12599 std::string reason;
12600 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12602 if (reason.empty())
12603 go_error_at((*pv)->location(),
12604 "incompatible type for field %d in struct construction",
12605 i + 1);
12606 else
12607 go_error_at((*pv)->location(),
12608 ("incompatible type for field %d in "
12609 "struct construction (%s)"),
12610 i + 1, reason.c_str());
12611 this->set_is_error();
12614 go_assert(pv == this->vals()->end());
12617 // Flatten a struct construction expression. Store the values into
12618 // temporaries in case they need interface conversion.
12620 Expression*
12621 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12622 Statement_inserter* inserter)
12624 if (this->vals() == NULL)
12625 return this;
12627 // If this is a constant struct, we don't need temporaries.
12628 if (this->is_constant_struct() || this->is_static_initializer())
12629 return this;
12631 Location loc = this->location();
12632 for (Expression_list::iterator pv = this->vals()->begin();
12633 pv != this->vals()->end();
12634 ++pv)
12636 if (*pv != NULL)
12638 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12640 go_assert(saw_errors());
12641 return Expression::make_error(loc);
12643 if (!(*pv)->is_variable())
12645 Temporary_statement* temp =
12646 Statement::make_temporary(NULL, *pv, loc);
12647 inserter->insert(temp);
12648 *pv = Expression::make_temporary_reference(temp, loc);
12652 return this;
12655 // Return the backend representation for constructing a struct.
12657 Bexpression*
12658 Struct_construction_expression::do_get_backend(Translate_context* context)
12660 Gogo* gogo = context->gogo();
12662 Btype* btype = this->type_->get_backend(gogo);
12663 if (this->vals() == NULL)
12664 return gogo->backend()->zero_expression(btype);
12666 const Struct_field_list* fields = this->type_->struct_type()->fields();
12667 Expression_list::const_iterator pv = this->vals()->begin();
12668 std::vector<Bexpression*> init;
12669 for (Struct_field_list::const_iterator pf = fields->begin();
12670 pf != fields->end();
12671 ++pf)
12673 Btype* fbtype = pf->type()->get_backend(gogo);
12674 if (pv == this->vals()->end())
12675 init.push_back(gogo->backend()->zero_expression(fbtype));
12676 else if (*pv == NULL)
12678 init.push_back(gogo->backend()->zero_expression(fbtype));
12679 ++pv;
12681 else
12683 Expression* val =
12684 Expression::convert_for_assignment(gogo, pf->type(),
12685 *pv, this->location());
12686 init.push_back(val->get_backend(context));
12687 ++pv;
12690 return gogo->backend()->constructor_expression(btype, init, this->location());
12693 // Export a struct construction.
12695 void
12696 Struct_construction_expression::do_export(Export* exp) const
12698 exp->write_c_string("convert(");
12699 exp->write_type(this->type_);
12700 for (Expression_list::const_iterator pv = this->vals()->begin();
12701 pv != this->vals()->end();
12702 ++pv)
12704 exp->write_c_string(", ");
12705 if (*pv != NULL)
12706 (*pv)->export_expression(exp);
12708 exp->write_c_string(")");
12711 // Dump ast representation of a struct construction expression.
12713 void
12714 Struct_construction_expression::do_dump_expression(
12715 Ast_dump_context* ast_dump_context) const
12717 ast_dump_context->dump_type(this->type_);
12718 ast_dump_context->ostream() << "{";
12719 ast_dump_context->dump_expression_list(this->vals());
12720 ast_dump_context->ostream() << "}";
12723 // Make a struct composite literal. This used by the thunk code.
12725 Expression*
12726 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12727 Location location)
12729 go_assert(type->struct_type() != NULL);
12730 return new Struct_construction_expression(type, vals, location);
12733 // Class Array_construction_expression.
12735 // Traversal.
12738 Array_construction_expression::do_traverse(Traverse* traverse)
12740 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12741 return TRAVERSE_EXIT;
12742 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12743 return TRAVERSE_EXIT;
12744 return TRAVERSE_CONTINUE;
12747 // Return whether this is a constant initializer.
12749 bool
12750 Array_construction_expression::is_constant_array() const
12752 if (this->vals() == NULL)
12753 return true;
12755 // There are no constant constructors for interfaces.
12756 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12757 return false;
12759 for (Expression_list::const_iterator pv = this->vals()->begin();
12760 pv != this->vals()->end();
12761 ++pv)
12763 if (*pv != NULL
12764 && !(*pv)->is_constant()
12765 && (!(*pv)->is_composite_literal()
12766 || (*pv)->is_nonconstant_composite_literal()))
12767 return false;
12769 return true;
12772 // Return whether this can be used a constant initializer.
12774 bool
12775 Array_construction_expression::do_is_static_initializer() const
12777 if (this->vals() == NULL)
12778 return true;
12780 // There are no constant constructors for interfaces.
12781 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12782 return false;
12784 for (Expression_list::const_iterator pv = this->vals()->begin();
12785 pv != this->vals()->end();
12786 ++pv)
12788 if (*pv != NULL && !(*pv)->is_static_initializer())
12789 return false;
12791 return true;
12794 // Final type determination.
12796 void
12797 Array_construction_expression::do_determine_type(const Type_context*)
12799 if (this->vals() == NULL)
12800 return;
12801 Type_context subcontext(this->type_->array_type()->element_type(), false);
12802 for (Expression_list::const_iterator pv = this->vals()->begin();
12803 pv != this->vals()->end();
12804 ++pv)
12806 if (*pv != NULL)
12807 (*pv)->determine_type(&subcontext);
12811 // Check types.
12813 void
12814 Array_construction_expression::do_check_types(Gogo*)
12816 if (this->vals() == NULL)
12817 return;
12819 Array_type* at = this->type_->array_type();
12820 int i = 0;
12821 Type* element_type = at->element_type();
12822 for (Expression_list::const_iterator pv = this->vals()->begin();
12823 pv != this->vals()->end();
12824 ++pv, ++i)
12826 if (*pv != NULL
12827 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12829 go_error_at((*pv)->location(),
12830 "incompatible type for element %d in composite literal",
12831 i + 1);
12832 this->set_is_error();
12837 // Flatten an array construction expression. Store the values into
12838 // temporaries in case they need interface conversion.
12840 Expression*
12841 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12842 Statement_inserter* inserter)
12844 if (this->vals() == NULL)
12845 return this;
12847 // If this is a constant array, we don't need temporaries.
12848 if (this->is_constant_array() || this->is_static_initializer())
12849 return this;
12851 Location loc = this->location();
12852 for (Expression_list::iterator pv = this->vals()->begin();
12853 pv != this->vals()->end();
12854 ++pv)
12856 if (*pv != NULL)
12858 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12860 go_assert(saw_errors());
12861 return Expression::make_error(loc);
12863 if (!(*pv)->is_variable())
12865 Temporary_statement* temp =
12866 Statement::make_temporary(NULL, *pv, loc);
12867 inserter->insert(temp);
12868 *pv = Expression::make_temporary_reference(temp, loc);
12872 return this;
12875 // Get a constructor expression for the array values.
12877 Bexpression*
12878 Array_construction_expression::get_constructor(Translate_context* context,
12879 Btype* array_btype)
12881 Type* element_type = this->type_->array_type()->element_type();
12883 std::vector<unsigned long> indexes;
12884 std::vector<Bexpression*> vals;
12885 Gogo* gogo = context->gogo();
12886 if (this->vals() != NULL)
12888 size_t i = 0;
12889 std::vector<unsigned long>::const_iterator pi;
12890 if (this->indexes_ != NULL)
12891 pi = this->indexes_->begin();
12892 for (Expression_list::const_iterator pv = this->vals()->begin();
12893 pv != this->vals()->end();
12894 ++pv, ++i)
12896 if (this->indexes_ != NULL)
12897 go_assert(pi != this->indexes_->end());
12899 if (this->indexes_ == NULL)
12900 indexes.push_back(i);
12901 else
12902 indexes.push_back(*pi);
12903 if (*pv == NULL)
12905 Btype* ebtype = element_type->get_backend(gogo);
12906 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12907 vals.push_back(zv);
12909 else
12911 Expression* val_expr =
12912 Expression::convert_for_assignment(gogo, element_type, *pv,
12913 this->location());
12914 vals.push_back(val_expr->get_backend(context));
12916 if (this->indexes_ != NULL)
12917 ++pi;
12919 if (this->indexes_ != NULL)
12920 go_assert(pi == this->indexes_->end());
12922 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12923 vals, this->location());
12926 // Export an array construction.
12928 void
12929 Array_construction_expression::do_export(Export* exp) const
12931 exp->write_c_string("convert(");
12932 exp->write_type(this->type_);
12933 if (this->vals() != NULL)
12935 std::vector<unsigned long>::const_iterator pi;
12936 if (this->indexes_ != NULL)
12937 pi = this->indexes_->begin();
12938 for (Expression_list::const_iterator pv = this->vals()->begin();
12939 pv != this->vals()->end();
12940 ++pv)
12942 exp->write_c_string(", ");
12944 if (this->indexes_ != NULL)
12946 char buf[100];
12947 snprintf(buf, sizeof buf, "%lu", *pi);
12948 exp->write_c_string(buf);
12949 exp->write_c_string(":");
12952 if (*pv != NULL)
12953 (*pv)->export_expression(exp);
12955 if (this->indexes_ != NULL)
12956 ++pi;
12959 exp->write_c_string(")");
12962 // Dump ast representation of an array construction expression.
12964 void
12965 Array_construction_expression::do_dump_expression(
12966 Ast_dump_context* ast_dump_context) const
12968 Expression* length = this->type_->array_type()->length();
12970 ast_dump_context->ostream() << "[" ;
12971 if (length != NULL)
12973 ast_dump_context->dump_expression(length);
12975 ast_dump_context->ostream() << "]" ;
12976 ast_dump_context->dump_type(this->type_);
12977 this->dump_slice_storage_expression(ast_dump_context);
12978 ast_dump_context->ostream() << "{" ;
12979 if (this->indexes_ == NULL)
12980 ast_dump_context->dump_expression_list(this->vals());
12981 else
12983 Expression_list::const_iterator pv = this->vals()->begin();
12984 for (std::vector<unsigned long>::const_iterator pi =
12985 this->indexes_->begin();
12986 pi != this->indexes_->end();
12987 ++pi, ++pv)
12989 if (pi != this->indexes_->begin())
12990 ast_dump_context->ostream() << ", ";
12991 ast_dump_context->ostream() << *pi << ':';
12992 ast_dump_context->dump_expression(*pv);
12995 ast_dump_context->ostream() << "}" ;
12999 // Class Fixed_array_construction_expression.
13001 Fixed_array_construction_expression::Fixed_array_construction_expression(
13002 Type* type, const std::vector<unsigned long>* indexes,
13003 Expression_list* vals, Location location)
13004 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13005 type, indexes, vals, location)
13006 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13008 // Return the backend representation for constructing a fixed array.
13010 Bexpression*
13011 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13013 Type* type = this->type();
13014 Btype* btype = type->get_backend(context->gogo());
13015 return this->get_constructor(context, btype);
13018 Expression*
13019 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13020 Location location)
13022 go_assert(type->array_type() != NULL && !type->is_slice_type());
13023 return new Fixed_array_construction_expression(type, NULL, vals, location);
13026 // Class Slice_construction_expression.
13028 Slice_construction_expression::Slice_construction_expression(
13029 Type* type, const std::vector<unsigned long>* indexes,
13030 Expression_list* vals, Location location)
13031 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13032 type, indexes, vals, location),
13033 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13034 storage_escapes_(true)
13036 go_assert(type->is_slice_type());
13038 unsigned long lenval;
13039 Expression* length;
13040 if (vals == NULL || vals->empty())
13041 lenval = 0;
13042 else
13044 if (this->indexes() == NULL)
13045 lenval = vals->size();
13046 else
13047 lenval = indexes->back() + 1;
13049 Type* int_type = Type::lookup_integer_type("int");
13050 length = Expression::make_integer_ul(lenval, int_type, location);
13051 Type* element_type = type->array_type()->element_type();
13052 Array_type* array_type = Type::make_array_type(element_type, length);
13053 array_type->set_is_array_incomparable();
13054 this->valtype_ = array_type;
13057 // Traversal.
13060 Slice_construction_expression::do_traverse(Traverse* traverse)
13062 if (this->Array_construction_expression::do_traverse(traverse)
13063 == TRAVERSE_EXIT)
13064 return TRAVERSE_EXIT;
13065 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13066 return TRAVERSE_EXIT;
13067 if (this->array_val_ != NULL
13068 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13069 return TRAVERSE_EXIT;
13070 if (this->slice_storage_ != NULL
13071 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13072 return TRAVERSE_EXIT;
13073 return TRAVERSE_CONTINUE;
13076 // Helper routine to create fixed array value underlying the slice literal.
13077 // May be called during flattening, or later during do_get_backend().
13079 Expression*
13080 Slice_construction_expression::create_array_val()
13082 Array_type* array_type = this->type()->array_type();
13083 if (array_type == NULL)
13085 go_assert(this->type()->is_error());
13086 return NULL;
13089 Location loc = this->location();
13090 go_assert(this->valtype_ != NULL);
13092 Expression_list* vals = this->vals();
13093 return new Fixed_array_construction_expression(
13094 this->valtype_, this->indexes(), vals, loc);
13097 // If we're previous established that the slice storage does not
13098 // escape, then create a separate array temp val here for it. We
13099 // need to do this as part of flattening so as to be able to insert
13100 // the new temp statement.
13102 Expression*
13103 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13104 Statement_inserter* inserter)
13106 if (this->type()->array_type() == NULL)
13107 return NULL;
13109 // Base class flattening first
13110 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13112 // Create a stack-allocated storage temp if storage won't escape
13113 if (!this->storage_escapes_
13114 && this->slice_storage_ == NULL
13115 && this->element_count() > 0)
13117 Location loc = this->location();
13118 this->array_val_ = this->create_array_val();
13119 go_assert(this->array_val_);
13120 Temporary_statement* temp =
13121 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13122 inserter->insert(temp);
13123 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13125 return this;
13128 // When dumping a slice construction expression that has an explicit
13129 // storeage temp, emit the temp here (if we don't do this the storage
13130 // temp appears unused in the AST dump).
13132 void
13133 Slice_construction_expression::
13134 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13136 if (this->slice_storage_ == NULL)
13137 return;
13138 ast_dump_context->ostream() << "storage=" ;
13139 ast_dump_context->dump_expression(this->slice_storage_);
13142 // Return the backend representation for constructing a slice.
13144 Bexpression*
13145 Slice_construction_expression::do_get_backend(Translate_context* context)
13147 if (this->array_val_ == NULL)
13148 this->array_val_ = this->create_array_val();
13149 if (this->array_val_ == NULL)
13151 go_assert(this->type()->is_error());
13152 return context->backend()->error_expression();
13155 Location loc = this->location();
13157 bool is_static_initializer = this->array_val_->is_static_initializer();
13159 // We have to copy the initial values into heap memory if we are in
13160 // a function or if the values are not constants.
13161 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13163 Expression* space;
13165 if (this->slice_storage_ != NULL)
13167 go_assert(!this->storage_escapes_);
13168 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13170 else if (!copy_to_heap)
13172 // The initializer will only run once.
13173 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13174 space->unary_expression()->set_is_slice_init();
13176 else
13178 go_assert(this->storage_escapes_ || this->element_count() == 0);
13179 space = Expression::make_heap_expression(this->array_val_, loc);
13182 // Build a constructor for the slice.
13183 Expression* len = this->valtype_->array_type()->length();
13184 Expression* slice_val =
13185 Expression::make_slice_value(this->type(), space, len, len, loc);
13186 return slice_val->get_backend(context);
13189 // Make a slice composite literal. This is used by the type
13190 // descriptor code.
13192 Slice_construction_expression*
13193 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13194 Location location)
13196 go_assert(type->is_slice_type());
13197 return new Slice_construction_expression(type, NULL, vals, location);
13200 // Class Map_construction_expression.
13202 // Traversal.
13205 Map_construction_expression::do_traverse(Traverse* traverse)
13207 if (this->vals_ != NULL
13208 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13209 return TRAVERSE_EXIT;
13210 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13211 return TRAVERSE_EXIT;
13212 return TRAVERSE_CONTINUE;
13215 // Flatten constructor initializer into a temporary variable since
13216 // we need to take its address for __go_construct_map.
13218 Expression*
13219 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13220 Statement_inserter* inserter)
13222 if (!this->is_error_expression()
13223 && this->vals_ != NULL
13224 && !this->vals_->empty()
13225 && this->constructor_temp_ == NULL)
13227 Map_type* mt = this->type_->map_type();
13228 Type* key_type = mt->key_type();
13229 Type* val_type = mt->val_type();
13230 this->element_type_ = Type::make_builtin_struct_type(2,
13231 "__key", key_type,
13232 "__val", val_type);
13234 Expression_list* value_pairs = new Expression_list();
13235 Location loc = this->location();
13237 size_t i = 0;
13238 for (Expression_list::const_iterator pv = this->vals_->begin();
13239 pv != this->vals_->end();
13240 ++pv, ++i)
13242 Expression_list* key_value_pair = new Expression_list();
13243 Expression* key = *pv;
13244 if (key->is_error_expression() || key->type()->is_error_type())
13246 go_assert(saw_errors());
13247 return Expression::make_error(loc);
13249 if (key->type()->interface_type() != NULL && !key->is_variable())
13251 Temporary_statement* temp =
13252 Statement::make_temporary(NULL, key, loc);
13253 inserter->insert(temp);
13254 key = Expression::make_temporary_reference(temp, loc);
13256 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13258 ++pv;
13259 Expression* val = *pv;
13260 if (val->is_error_expression() || val->type()->is_error_type())
13262 go_assert(saw_errors());
13263 return Expression::make_error(loc);
13265 if (val->type()->interface_type() != NULL && !val->is_variable())
13267 Temporary_statement* temp =
13268 Statement::make_temporary(NULL, val, loc);
13269 inserter->insert(temp);
13270 val = Expression::make_temporary_reference(temp, loc);
13272 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13274 key_value_pair->push_back(key);
13275 key_value_pair->push_back(val);
13276 value_pairs->push_back(
13277 Expression::make_struct_composite_literal(this->element_type_,
13278 key_value_pair, loc));
13281 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13282 Array_type* ctor_type =
13283 Type::make_array_type(this->element_type_, element_count);
13284 ctor_type->set_is_array_incomparable();
13285 Expression* constructor =
13286 new Fixed_array_construction_expression(ctor_type, NULL,
13287 value_pairs, loc);
13289 this->constructor_temp_ =
13290 Statement::make_temporary(NULL, constructor, loc);
13291 constructor->issue_nil_check();
13292 this->constructor_temp_->set_is_address_taken();
13293 inserter->insert(this->constructor_temp_);
13296 return this;
13299 // Final type determination.
13301 void
13302 Map_construction_expression::do_determine_type(const Type_context*)
13304 if (this->vals_ == NULL)
13305 return;
13307 Map_type* mt = this->type_->map_type();
13308 Type_context key_context(mt->key_type(), false);
13309 Type_context val_context(mt->val_type(), false);
13310 for (Expression_list::const_iterator pv = this->vals_->begin();
13311 pv != this->vals_->end();
13312 ++pv)
13314 (*pv)->determine_type(&key_context);
13315 ++pv;
13316 (*pv)->determine_type(&val_context);
13320 // Check types.
13322 void
13323 Map_construction_expression::do_check_types(Gogo*)
13325 if (this->vals_ == NULL)
13326 return;
13328 Map_type* mt = this->type_->map_type();
13329 int i = 0;
13330 Type* key_type = mt->key_type();
13331 Type* val_type = mt->val_type();
13332 for (Expression_list::const_iterator pv = this->vals_->begin();
13333 pv != this->vals_->end();
13334 ++pv, ++i)
13336 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13338 go_error_at((*pv)->location(),
13339 "incompatible type for element %d key in map construction",
13340 i + 1);
13341 this->set_is_error();
13343 ++pv;
13344 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13346 go_error_at((*pv)->location(),
13347 ("incompatible type for element %d value "
13348 "in map construction"),
13349 i + 1);
13350 this->set_is_error();
13355 // Return the backend representation for constructing a map.
13357 Bexpression*
13358 Map_construction_expression::do_get_backend(Translate_context* context)
13360 if (this->is_error_expression())
13361 return context->backend()->error_expression();
13362 Location loc = this->location();
13364 size_t i = 0;
13365 Expression* ventries;
13366 if (this->vals_ == NULL || this->vals_->empty())
13367 ventries = Expression::make_nil(loc);
13368 else
13370 go_assert(this->constructor_temp_ != NULL);
13371 i = this->vals_->size() / 2;
13373 Expression* ctor_ref =
13374 Expression::make_temporary_reference(this->constructor_temp_, loc);
13375 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13378 Map_type* mt = this->type_->map_type();
13379 if (this->element_type_ == NULL)
13380 this->element_type_ =
13381 Type::make_builtin_struct_type(2,
13382 "__key", mt->key_type(),
13383 "__val", mt->val_type());
13384 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13386 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13387 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13389 Expression* entry_size =
13390 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13392 unsigned int field_index;
13393 const Struct_field* valfield =
13394 this->element_type_->find_local_field("__val", &field_index);
13395 Expression* val_offset =
13396 Expression::make_struct_field_offset(this->element_type_, valfield);
13398 Expression* map_ctor =
13399 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13400 entry_size, val_offset, ventries);
13401 return map_ctor->get_backend(context);
13404 // Export an array construction.
13406 void
13407 Map_construction_expression::do_export(Export* exp) const
13409 exp->write_c_string("convert(");
13410 exp->write_type(this->type_);
13411 for (Expression_list::const_iterator pv = this->vals_->begin();
13412 pv != this->vals_->end();
13413 ++pv)
13415 exp->write_c_string(", ");
13416 (*pv)->export_expression(exp);
13418 exp->write_c_string(")");
13421 // Dump ast representation for a map construction expression.
13423 void
13424 Map_construction_expression::do_dump_expression(
13425 Ast_dump_context* ast_dump_context) const
13427 ast_dump_context->ostream() << "{" ;
13428 ast_dump_context->dump_expression_list(this->vals_, true);
13429 ast_dump_context->ostream() << "}";
13432 // Class Composite_literal_expression.
13434 // Traversal.
13437 Composite_literal_expression::do_traverse(Traverse* traverse)
13439 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13440 return TRAVERSE_EXIT;
13442 // If this is a struct composite literal with keys, then the keys
13443 // are field names, not expressions. We don't want to traverse them
13444 // in that case. If we do, we can give an erroneous error "variable
13445 // initializer refers to itself." See bug482.go in the testsuite.
13446 if (this->has_keys_ && this->vals_ != NULL)
13448 // The type may not be resolvable at this point.
13449 Type* type = this->type_;
13451 for (int depth = 0; depth < this->depth_; ++depth)
13453 if (type->array_type() != NULL)
13454 type = type->array_type()->element_type();
13455 else if (type->map_type() != NULL)
13457 if (this->key_path_[depth])
13458 type = type->map_type()->key_type();
13459 else
13460 type = type->map_type()->val_type();
13462 else
13464 // This error will be reported during lowering.
13465 return TRAVERSE_CONTINUE;
13469 while (true)
13471 if (type->classification() == Type::TYPE_NAMED)
13472 type = type->named_type()->real_type();
13473 else if (type->classification() == Type::TYPE_FORWARD)
13475 Type* t = type->forwarded();
13476 if (t == type)
13477 break;
13478 type = t;
13480 else
13481 break;
13484 if (type->classification() == Type::TYPE_STRUCT)
13486 Expression_list::iterator p = this->vals_->begin();
13487 while (p != this->vals_->end())
13489 // Skip key.
13490 ++p;
13491 go_assert(p != this->vals_->end());
13492 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13493 return TRAVERSE_EXIT;
13494 ++p;
13496 return TRAVERSE_CONTINUE;
13500 if (this->vals_ != NULL)
13501 return this->vals_->traverse(traverse);
13503 return TRAVERSE_CONTINUE;
13506 // Lower a generic composite literal into a specific version based on
13507 // the type.
13509 Expression*
13510 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13511 Statement_inserter* inserter, int)
13513 Type* type = this->type_;
13515 for (int depth = 0; depth < this->depth_; ++depth)
13517 if (type->array_type() != NULL)
13518 type = type->array_type()->element_type();
13519 else if (type->map_type() != NULL)
13521 if (this->key_path_[depth])
13522 type = type->map_type()->key_type();
13523 else
13524 type = type->map_type()->val_type();
13526 else
13528 if (!type->is_error())
13529 go_error_at(this->location(),
13530 ("may only omit types within composite literals "
13531 "of slice, array, or map type"));
13532 return Expression::make_error(this->location());
13536 Type *pt = type->points_to();
13537 bool is_pointer = false;
13538 if (pt != NULL)
13540 is_pointer = true;
13541 type = pt;
13544 Expression* ret;
13545 if (type->is_error())
13546 return Expression::make_error(this->location());
13547 else if (type->struct_type() != NULL)
13548 ret = this->lower_struct(gogo, type);
13549 else if (type->array_type() != NULL)
13550 ret = this->lower_array(type);
13551 else if (type->map_type() != NULL)
13552 ret = this->lower_map(gogo, function, inserter, type);
13553 else
13555 go_error_at(this->location(),
13556 ("expected struct, slice, array, or map type "
13557 "for composite literal"));
13558 return Expression::make_error(this->location());
13561 if (is_pointer)
13562 ret = Expression::make_heap_expression(ret, this->location());
13564 return ret;
13567 // Lower a struct composite literal.
13569 Expression*
13570 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13572 Location location = this->location();
13573 Struct_type* st = type->struct_type();
13574 if (this->vals_ == NULL || !this->has_keys_)
13576 if (this->vals_ != NULL
13577 && !this->vals_->empty()
13578 && type->named_type() != NULL
13579 && type->named_type()->named_object()->package() != NULL)
13581 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13582 pf != st->fields()->end();
13583 ++pf)
13585 if (Gogo::is_hidden_name(pf->field_name())
13586 || pf->is_embedded_builtin(gogo))
13587 go_error_at(this->location(),
13588 "assignment of unexported field %qs in %qs literal",
13589 Gogo::message_name(pf->field_name()).c_str(),
13590 type->named_type()->message_name().c_str());
13594 return new Struct_construction_expression(type, this->vals_, location);
13597 size_t field_count = st->field_count();
13598 std::vector<Expression*> vals(field_count);
13599 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13600 Expression_list::const_iterator p = this->vals_->begin();
13601 Expression* external_expr = NULL;
13602 const Named_object* external_no = NULL;
13603 while (p != this->vals_->end())
13605 Expression* name_expr = *p;
13607 ++p;
13608 go_assert(p != this->vals_->end());
13609 Expression* val = *p;
13611 ++p;
13613 if (name_expr == NULL)
13615 go_error_at(val->location(),
13616 "mixture of field and value initializers");
13617 return Expression::make_error(location);
13620 bool bad_key = false;
13621 std::string name;
13622 const Named_object* no = NULL;
13623 switch (name_expr->classification())
13625 case EXPRESSION_UNKNOWN_REFERENCE:
13626 name = name_expr->unknown_expression()->name();
13627 if (type->named_type() != NULL)
13629 // If the named object found for this field name comes from a
13630 // different package than the struct it is a part of, do not count
13631 // this incorrect lookup as a usage of the object's package.
13632 no = name_expr->unknown_expression()->named_object();
13633 if (no->package() != NULL
13634 && no->package() != type->named_type()->named_object()->package())
13635 no->package()->forget_usage(name_expr);
13637 break;
13639 case EXPRESSION_CONST_REFERENCE:
13640 no = static_cast<Const_expression*>(name_expr)->named_object();
13641 break;
13643 case EXPRESSION_TYPE:
13645 Type* t = name_expr->type();
13646 Named_type* nt = t->named_type();
13647 if (nt == NULL)
13648 bad_key = true;
13649 else
13650 no = nt->named_object();
13652 break;
13654 case EXPRESSION_VAR_REFERENCE:
13655 no = name_expr->var_expression()->named_object();
13656 break;
13658 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13659 no = name_expr->enclosed_var_expression()->variable();
13660 break;
13662 case EXPRESSION_FUNC_REFERENCE:
13663 no = name_expr->func_expression()->named_object();
13664 break;
13666 default:
13667 bad_key = true;
13668 break;
13670 if (bad_key)
13672 go_error_at(name_expr->location(), "expected struct field name");
13673 return Expression::make_error(location);
13676 if (no != NULL)
13678 if (no->package() != NULL && external_expr == NULL)
13680 external_expr = name_expr;
13681 external_no = no;
13684 name = no->name();
13686 // A predefined name won't be packed. If it starts with a
13687 // lower case letter we need to check for that case, because
13688 // the field name will be packed. FIXME.
13689 if (!Gogo::is_hidden_name(name)
13690 && name[0] >= 'a'
13691 && name[0] <= 'z')
13693 Named_object* gno = gogo->lookup_global(name.c_str());
13694 if (gno == no)
13695 name = gogo->pack_hidden_name(name, false);
13699 unsigned int index;
13700 const Struct_field* sf = st->find_local_field(name, &index);
13701 if (sf == NULL)
13703 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13704 Gogo::message_name(name).c_str(),
13705 (type->named_type() != NULL
13706 ? type->named_type()->message_name().c_str()
13707 : "unnamed struct"));
13708 return Expression::make_error(location);
13710 if (vals[index] != NULL)
13712 go_error_at(name_expr->location(),
13713 "duplicate value for field %qs in %qs",
13714 Gogo::message_name(name).c_str(),
13715 (type->named_type() != NULL
13716 ? type->named_type()->message_name().c_str()
13717 : "unnamed struct"));
13718 return Expression::make_error(location);
13721 if (type->named_type() != NULL
13722 && type->named_type()->named_object()->package() != NULL
13723 && (Gogo::is_hidden_name(sf->field_name())
13724 || sf->is_embedded_builtin(gogo)))
13725 go_error_at(name_expr->location(),
13726 "assignment of unexported field %qs in %qs literal",
13727 Gogo::message_name(sf->field_name()).c_str(),
13728 type->named_type()->message_name().c_str());
13730 vals[index] = val;
13731 traverse_order->push_back(static_cast<unsigned long>(index));
13734 if (!this->all_are_names_)
13736 // This is a weird case like bug462 in the testsuite.
13737 if (external_expr == NULL)
13738 go_error_at(this->location(), "unknown field in %qs literal",
13739 (type->named_type() != NULL
13740 ? type->named_type()->message_name().c_str()
13741 : "unnamed struct"));
13742 else
13743 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13744 external_no->message_name().c_str(),
13745 (type->named_type() != NULL
13746 ? type->named_type()->message_name().c_str()
13747 : "unnamed struct"));
13748 return Expression::make_error(location);
13751 Expression_list* list = new Expression_list;
13752 list->reserve(field_count);
13753 for (size_t i = 0; i < field_count; ++i)
13754 list->push_back(vals[i]);
13756 Struct_construction_expression* ret =
13757 new Struct_construction_expression(type, list, location);
13758 ret->set_traverse_order(traverse_order);
13759 return ret;
13762 // Index/value/traversal-order triple.
13764 struct IVT_triple {
13765 unsigned long index;
13766 unsigned long traversal_order;
13767 Expression* expr;
13768 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13769 : index(i), traversal_order(to), expr(e) { }
13770 bool operator<(const IVT_triple& other) const
13771 { return this->index < other.index; }
13774 // Lower an array composite literal.
13776 Expression*
13777 Composite_literal_expression::lower_array(Type* type)
13779 Location location = this->location();
13780 if (this->vals_ == NULL || !this->has_keys_)
13781 return this->make_array(type, NULL, this->vals_);
13783 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13784 indexes->reserve(this->vals_->size());
13785 bool indexes_out_of_order = false;
13786 Expression_list* vals = new Expression_list();
13787 vals->reserve(this->vals_->size());
13788 unsigned long index = 0;
13789 Expression_list::const_iterator p = this->vals_->begin();
13790 while (p != this->vals_->end())
13792 Expression* index_expr = *p;
13794 ++p;
13795 go_assert(p != this->vals_->end());
13796 Expression* val = *p;
13798 ++p;
13800 if (index_expr == NULL)
13802 if (!indexes->empty())
13803 indexes->push_back(index);
13805 else
13807 if (indexes->empty() && !vals->empty())
13809 for (size_t i = 0; i < vals->size(); ++i)
13810 indexes->push_back(i);
13813 Numeric_constant nc;
13814 if (!index_expr->numeric_constant_value(&nc))
13816 go_error_at(index_expr->location(),
13817 "index expression is not integer constant");
13818 return Expression::make_error(location);
13821 switch (nc.to_unsigned_long(&index))
13823 case Numeric_constant::NC_UL_VALID:
13824 break;
13825 case Numeric_constant::NC_UL_NOTINT:
13826 go_error_at(index_expr->location(),
13827 "index expression is not integer constant");
13828 return Expression::make_error(location);
13829 case Numeric_constant::NC_UL_NEGATIVE:
13830 go_error_at(index_expr->location(),
13831 "index expression is negative");
13832 return Expression::make_error(location);
13833 case Numeric_constant::NC_UL_BIG:
13834 go_error_at(index_expr->location(), "index value overflow");
13835 return Expression::make_error(location);
13836 default:
13837 go_unreachable();
13840 Named_type* ntype = Type::lookup_integer_type("int");
13841 Integer_type* inttype = ntype->integer_type();
13842 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13843 && index >> (inttype->bits() - 1) != 0)
13845 go_error_at(index_expr->location(), "index value overflow");
13846 return Expression::make_error(location);
13849 if (std::find(indexes->begin(), indexes->end(), index)
13850 != indexes->end())
13852 go_error_at(index_expr->location(),
13853 "duplicate value for index %lu",
13854 index);
13855 return Expression::make_error(location);
13858 if (!indexes->empty() && index < indexes->back())
13859 indexes_out_of_order = true;
13861 indexes->push_back(index);
13864 vals->push_back(val);
13866 ++index;
13869 if (indexes->empty())
13871 delete indexes;
13872 indexes = NULL;
13875 std::vector<unsigned long>* traverse_order = NULL;
13876 if (indexes_out_of_order)
13878 typedef std::vector<IVT_triple> V;
13880 V v;
13881 v.reserve(indexes->size());
13882 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13883 unsigned long torder = 0;
13884 for (Expression_list::const_iterator pe = vals->begin();
13885 pe != vals->end();
13886 ++pe, ++pi, ++torder)
13887 v.push_back(IVT_triple(*pi, torder, *pe));
13889 std::sort(v.begin(), v.end());
13891 delete indexes;
13892 delete vals;
13894 indexes = new std::vector<unsigned long>();
13895 indexes->reserve(v.size());
13896 vals = new Expression_list();
13897 vals->reserve(v.size());
13898 traverse_order = new std::vector<unsigned long>();
13899 traverse_order->reserve(v.size());
13901 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13903 indexes->push_back(p->index);
13904 vals->push_back(p->expr);
13905 traverse_order->push_back(p->traversal_order);
13909 Expression* ret = this->make_array(type, indexes, vals);
13910 Array_construction_expression* ace = ret->array_literal();
13911 if (ace != NULL && traverse_order != NULL)
13912 ace->set_traverse_order(traverse_order);
13913 return ret;
13916 // Actually build the array composite literal. This handles
13917 // [...]{...}.
13919 Expression*
13920 Composite_literal_expression::make_array(
13921 Type* type,
13922 const std::vector<unsigned long>* indexes,
13923 Expression_list* vals)
13925 Location location = this->location();
13926 Array_type* at = type->array_type();
13928 if (at->length() != NULL && at->length()->is_nil_expression())
13930 size_t size;
13931 if (vals == NULL)
13932 size = 0;
13933 else if (indexes != NULL)
13934 size = indexes->back() + 1;
13935 else
13937 size = vals->size();
13938 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13939 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13940 && size >> (it->bits() - 1) != 0)
13942 go_error_at(location, "too many elements in composite literal");
13943 return Expression::make_error(location);
13947 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13948 at = Type::make_array_type(at->element_type(), elen);
13949 type = at;
13951 else if (at->length() != NULL
13952 && !at->length()->is_error_expression()
13953 && this->vals_ != NULL)
13955 Numeric_constant nc;
13956 unsigned long val;
13957 if (at->length()->numeric_constant_value(&nc)
13958 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13960 if (indexes == NULL)
13962 if (this->vals_->size() > val)
13964 go_error_at(location,
13965 "too many elements in composite literal");
13966 return Expression::make_error(location);
13969 else
13971 unsigned long max = indexes->back();
13972 if (max >= val)
13974 go_error_at(location,
13975 ("some element keys in composite literal "
13976 "are out of range"));
13977 return Expression::make_error(location);
13983 if (at->length() != NULL)
13984 return new Fixed_array_construction_expression(type, indexes, vals,
13985 location);
13986 else
13987 return new Slice_construction_expression(type, indexes, vals, location);
13990 // Lower a map composite literal.
13992 Expression*
13993 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13994 Statement_inserter* inserter,
13995 Type* type)
13997 Location location = this->location();
13998 if (this->vals_ != NULL)
14000 if (!this->has_keys_)
14002 go_error_at(location, "map composite literal must have keys");
14003 return Expression::make_error(location);
14006 for (Expression_list::iterator p = this->vals_->begin();
14007 p != this->vals_->end();
14008 p += 2)
14010 if (*p == NULL)
14012 ++p;
14013 go_error_at((*p)->location(),
14014 ("map composite literal must "
14015 "have keys for every value"));
14016 return Expression::make_error(location);
14018 // Make sure we have lowered the key; it may not have been
14019 // lowered in order to handle keys for struct composite
14020 // literals. Lower it now to get the right error message.
14021 if ((*p)->unknown_expression() != NULL)
14023 (*p)->unknown_expression()->clear_is_composite_literal_key();
14024 gogo->lower_expression(function, inserter, &*p);
14025 go_assert((*p)->is_error_expression());
14026 return Expression::make_error(location);
14031 return new Map_construction_expression(type, this->vals_, location);
14034 // Dump ast representation for a composite literal expression.
14036 void
14037 Composite_literal_expression::do_dump_expression(
14038 Ast_dump_context* ast_dump_context) const
14040 ast_dump_context->ostream() << "composite(";
14041 ast_dump_context->dump_type(this->type_);
14042 ast_dump_context->ostream() << ", {";
14043 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14044 ast_dump_context->ostream() << "})";
14047 // Make a composite literal expression.
14049 Expression*
14050 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14051 Expression_list* vals, bool all_are_names,
14052 Location location)
14054 return new Composite_literal_expression(type, depth, has_keys, vals,
14055 all_are_names, location);
14058 // Return whether this expression is a composite literal.
14060 bool
14061 Expression::is_composite_literal() const
14063 switch (this->classification_)
14065 case EXPRESSION_COMPOSITE_LITERAL:
14066 case EXPRESSION_STRUCT_CONSTRUCTION:
14067 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14068 case EXPRESSION_SLICE_CONSTRUCTION:
14069 case EXPRESSION_MAP_CONSTRUCTION:
14070 return true;
14071 default:
14072 return false;
14076 // Return whether this expression is a composite literal which is not
14077 // constant.
14079 bool
14080 Expression::is_nonconstant_composite_literal() const
14082 switch (this->classification_)
14084 case EXPRESSION_STRUCT_CONSTRUCTION:
14086 const Struct_construction_expression *psce =
14087 static_cast<const Struct_construction_expression*>(this);
14088 return !psce->is_constant_struct();
14090 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14092 const Fixed_array_construction_expression *pace =
14093 static_cast<const Fixed_array_construction_expression*>(this);
14094 return !pace->is_constant_array();
14096 case EXPRESSION_SLICE_CONSTRUCTION:
14098 const Slice_construction_expression *pace =
14099 static_cast<const Slice_construction_expression*>(this);
14100 return !pace->is_constant_array();
14102 case EXPRESSION_MAP_CONSTRUCTION:
14103 return true;
14104 default:
14105 return false;
14109 // Return true if this is a variable or temporary_variable.
14111 bool
14112 Expression::is_variable() const
14114 switch (this->classification_)
14116 case EXPRESSION_VAR_REFERENCE:
14117 case EXPRESSION_TEMPORARY_REFERENCE:
14118 case EXPRESSION_SET_AND_USE_TEMPORARY:
14119 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14120 return true;
14121 default:
14122 return false;
14126 // Return true if this is a reference to a local variable.
14128 bool
14129 Expression::is_local_variable() const
14131 const Var_expression* ve = this->var_expression();
14132 if (ve == NULL)
14133 return false;
14134 const Named_object* no = ve->named_object();
14135 return (no->is_result_variable()
14136 || (no->is_variable() && !no->var_value()->is_global()));
14139 // Class Type_guard_expression.
14141 // Traversal.
14144 Type_guard_expression::do_traverse(Traverse* traverse)
14146 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14147 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14148 return TRAVERSE_EXIT;
14149 return TRAVERSE_CONTINUE;
14152 Expression*
14153 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14154 Statement_inserter* inserter)
14156 if (this->expr_->is_error_expression()
14157 || this->expr_->type()->is_error_type())
14159 go_assert(saw_errors());
14160 return Expression::make_error(this->location());
14163 if (!this->expr_->is_variable())
14165 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14166 this->location());
14167 inserter->insert(temp);
14168 this->expr_ =
14169 Expression::make_temporary_reference(temp, this->location());
14171 return this;
14174 // Check types of a type guard expression. The expression must have
14175 // an interface type, but the actual type conversion is checked at run
14176 // time.
14178 void
14179 Type_guard_expression::do_check_types(Gogo*)
14181 Type* expr_type = this->expr_->type();
14182 if (expr_type->interface_type() == NULL)
14184 if (!expr_type->is_error() && !this->type_->is_error())
14185 this->report_error(_("type assertion only valid for interface types"));
14186 this->set_is_error();
14188 else if (this->type_->interface_type() == NULL)
14190 std::string reason;
14191 if (!expr_type->interface_type()->implements_interface(this->type_,
14192 &reason))
14194 if (!this->type_->is_error())
14196 if (reason.empty())
14197 this->report_error(_("impossible type assertion: "
14198 "type does not implement interface"));
14199 else
14200 go_error_at(this->location(),
14201 ("impossible type assertion: "
14202 "type does not implement interface (%s)"),
14203 reason.c_str());
14205 this->set_is_error();
14210 // Return the backend representation for a type guard expression.
14212 Bexpression*
14213 Type_guard_expression::do_get_backend(Translate_context* context)
14215 Expression* conversion;
14216 if (this->type_->interface_type() != NULL)
14217 conversion =
14218 Expression::convert_interface_to_interface(this->type_, this->expr_,
14219 true, this->location());
14220 else
14221 conversion =
14222 Expression::convert_for_assignment(context->gogo(), this->type_,
14223 this->expr_, this->location());
14225 Gogo* gogo = context->gogo();
14226 Btype* bt = this->type_->get_backend(gogo);
14227 Bexpression* bexpr = conversion->get_backend(context);
14228 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14231 // Dump ast representation for a type guard expression.
14233 void
14234 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14235 const
14237 this->expr_->dump_expression(ast_dump_context);
14238 ast_dump_context->ostream() << ".";
14239 ast_dump_context->dump_type(this->type_);
14242 // Make a type guard expression.
14244 Expression*
14245 Expression::make_type_guard(Expression* expr, Type* type,
14246 Location location)
14248 return new Type_guard_expression(expr, type, location);
14251 // Class Heap_expression.
14253 // Return the type of the expression stored on the heap.
14255 Type*
14256 Heap_expression::do_type()
14257 { return Type::make_pointer_type(this->expr_->type()); }
14259 // Return the backend representation for allocating an expression on the heap.
14261 Bexpression*
14262 Heap_expression::do_get_backend(Translate_context* context)
14264 Type* etype = this->expr_->type();
14265 if (this->expr_->is_error_expression() || etype->is_error())
14266 return context->backend()->error_expression();
14268 Location loc = this->location();
14269 Gogo* gogo = context->gogo();
14270 Btype* btype = this->type()->get_backend(gogo);
14272 Expression* alloc = Expression::make_allocation(etype, loc);
14273 if (this->allocate_on_stack_)
14274 alloc->allocation_expression()->set_allocate_on_stack();
14275 Bexpression* space = alloc->get_backend(context);
14277 Bstatement* decl;
14278 Named_object* fn = context->function();
14279 go_assert(fn != NULL);
14280 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14281 Bvariable* space_temp =
14282 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14283 space, true, loc, &decl);
14284 Btype* expr_btype = etype->get_backend(gogo);
14286 Bexpression* bexpr = this->expr_->get_backend(context);
14288 // If this assignment needs a write barrier, call typedmemmove. We
14289 // don't do this in the write barrier pass because in some cases
14290 // backend conversion can introduce new Heap_expression values.
14291 Bstatement* assn;
14292 if (!etype->has_pointer() || this->allocate_on_stack_)
14294 space = gogo->backend()->var_expression(space_temp, loc);
14295 Bexpression* ref =
14296 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14297 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14299 else
14301 Bstatement* edecl;
14302 Bvariable* btemp =
14303 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14304 expr_btype, bexpr, true, loc,
14305 &edecl);
14306 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14307 loc);
14308 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14310 Expression* td = Expression::make_type_descriptor(etype, loc);
14311 Type* etype_ptr = Type::make_pointer_type(etype);
14312 space = gogo->backend()->var_expression(space_temp, loc);
14313 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14314 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14315 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14316 td, elhs, erhs);
14317 Bexpression* bcall = call->get_backend(context);
14318 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14319 assn = gogo->backend()->compound_statement(edecl, s);
14321 decl = gogo->backend()->compound_statement(decl, assn);
14322 space = gogo->backend()->var_expression(space_temp, loc);
14323 return gogo->backend()->compound_expression(decl, space, loc);
14326 // Dump ast representation for a heap expression.
14328 void
14329 Heap_expression::do_dump_expression(
14330 Ast_dump_context* ast_dump_context) const
14332 ast_dump_context->ostream() << "&(";
14333 ast_dump_context->dump_expression(this->expr_);
14334 ast_dump_context->ostream() << ")";
14337 // Allocate an expression on the heap.
14339 Expression*
14340 Expression::make_heap_expression(Expression* expr, Location location)
14342 return new Heap_expression(expr, location);
14345 // Class Receive_expression.
14347 // Return the type of a receive expression.
14349 Type*
14350 Receive_expression::do_type()
14352 if (this->is_error_expression())
14353 return Type::make_error_type();
14354 Channel_type* channel_type = this->channel_->type()->channel_type();
14355 if (channel_type == NULL)
14357 this->report_error(_("expected channel"));
14358 return Type::make_error_type();
14360 return channel_type->element_type();
14363 // Check types for a receive expression.
14365 void
14366 Receive_expression::do_check_types(Gogo*)
14368 Type* type = this->channel_->type();
14369 if (type->is_error())
14371 go_assert(saw_errors());
14372 this->set_is_error();
14373 return;
14375 if (type->channel_type() == NULL)
14377 this->report_error(_("expected channel"));
14378 return;
14380 if (!type->channel_type()->may_receive())
14382 this->report_error(_("invalid receive on send-only channel"));
14383 return;
14387 // Flattening for receive expressions creates a temporary variable to store
14388 // received data in for receives.
14390 Expression*
14391 Receive_expression::do_flatten(Gogo*, Named_object*,
14392 Statement_inserter* inserter)
14394 Channel_type* channel_type = this->channel_->type()->channel_type();
14395 if (channel_type == NULL)
14397 go_assert(saw_errors());
14398 return this;
14400 else if (this->channel_->is_error_expression())
14402 go_assert(saw_errors());
14403 return Expression::make_error(this->location());
14406 Type* element_type = channel_type->element_type();
14407 if (this->temp_receiver_ == NULL)
14409 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14410 this->location());
14411 this->temp_receiver_->set_is_address_taken();
14412 inserter->insert(this->temp_receiver_);
14415 return this;
14418 // Get the backend representation for a receive expression.
14420 Bexpression*
14421 Receive_expression::do_get_backend(Translate_context* context)
14423 Location loc = this->location();
14425 Channel_type* channel_type = this->channel_->type()->channel_type();
14426 if (channel_type == NULL)
14428 go_assert(this->channel_->type()->is_error());
14429 return context->backend()->error_expression();
14432 Expression* recv_ref =
14433 Expression::make_temporary_reference(this->temp_receiver_, loc);
14434 Expression* recv_addr =
14435 Expression::make_temporary_reference(this->temp_receiver_, loc);
14436 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14437 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
14438 this->channel_, recv_addr);
14439 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14442 // Dump ast representation for a receive expression.
14444 void
14445 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14447 ast_dump_context->ostream() << " <- " ;
14448 ast_dump_context->dump_expression(channel_);
14451 // Make a receive expression.
14453 Receive_expression*
14454 Expression::make_receive(Expression* channel, Location location)
14456 return new Receive_expression(channel, location);
14459 // An expression which evaluates to a pointer to the type descriptor
14460 // of a type.
14462 class Type_descriptor_expression : public Expression
14464 public:
14465 Type_descriptor_expression(Type* type, Location location)
14466 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14467 type_(type)
14470 protected:
14472 do_traverse(Traverse*);
14474 Type*
14475 do_type()
14476 { return Type::make_type_descriptor_ptr_type(); }
14478 bool
14479 do_is_static_initializer() const
14480 { return true; }
14482 void
14483 do_determine_type(const Type_context*)
14486 Expression*
14487 do_copy()
14488 { return this; }
14490 Bexpression*
14491 do_get_backend(Translate_context* context)
14493 return this->type_->type_descriptor_pointer(context->gogo(),
14494 this->location());
14497 void
14498 do_dump_expression(Ast_dump_context*) const;
14500 private:
14501 // The type for which this is the descriptor.
14502 Type* type_;
14506 Type_descriptor_expression::do_traverse(Traverse* traverse)
14508 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14509 return TRAVERSE_EXIT;
14510 return TRAVERSE_CONTINUE;
14513 // Dump ast representation for a type descriptor expression.
14515 void
14516 Type_descriptor_expression::do_dump_expression(
14517 Ast_dump_context* ast_dump_context) const
14519 ast_dump_context->dump_type(this->type_);
14522 // Make a type descriptor expression.
14524 Expression*
14525 Expression::make_type_descriptor(Type* type, Location location)
14527 return new Type_descriptor_expression(type, location);
14530 // An expression which evaluates to a pointer to the Garbage Collection symbol
14531 // of a type.
14533 class GC_symbol_expression : public Expression
14535 public:
14536 GC_symbol_expression(Type* type)
14537 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14538 type_(type)
14541 protected:
14542 Type*
14543 do_type()
14544 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14546 bool
14547 do_is_static_initializer() const
14548 { return true; }
14550 void
14551 do_determine_type(const Type_context*)
14554 Expression*
14555 do_copy()
14556 { return this; }
14558 Bexpression*
14559 do_get_backend(Translate_context* context)
14560 { return this->type_->gc_symbol_pointer(context->gogo()); }
14562 void
14563 do_dump_expression(Ast_dump_context*) const;
14565 private:
14566 // The type which this gc symbol describes.
14567 Type* type_;
14570 // Dump ast representation for a gc symbol expression.
14572 void
14573 GC_symbol_expression::do_dump_expression(
14574 Ast_dump_context* ast_dump_context) const
14576 ast_dump_context->ostream() << "gcdata(";
14577 ast_dump_context->dump_type(this->type_);
14578 ast_dump_context->ostream() << ")";
14581 // Make a gc symbol expression.
14583 Expression*
14584 Expression::make_gc_symbol(Type* type)
14586 return new GC_symbol_expression(type);
14589 // An expression that evaluates to a pointer to a symbol holding the
14590 // ptrmask data of a type.
14592 class Ptrmask_symbol_expression : public Expression
14594 public:
14595 Ptrmask_symbol_expression(Type* type)
14596 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14597 type_(type)
14600 protected:
14601 Type*
14602 do_type()
14603 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14605 bool
14606 do_is_static_initializer() const
14607 { return true; }
14609 void
14610 do_determine_type(const Type_context*)
14613 Expression*
14614 do_copy()
14615 { return this; }
14617 Bexpression*
14618 do_get_backend(Translate_context*);
14620 void
14621 do_dump_expression(Ast_dump_context*) const;
14623 private:
14624 // The type that this ptrmask symbol describes.
14625 Type* type_;
14628 // Return the ptrmask variable.
14630 Bexpression*
14631 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14633 Gogo* gogo = context->gogo();
14635 // If this type does not need a gcprog, then we can use the standard
14636 // GC symbol.
14637 int64_t ptrsize, ptrdata;
14638 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14639 return this->type_->gc_symbol_pointer(gogo);
14641 // Otherwise we have to build a ptrmask variable, and return a
14642 // pointer to it.
14644 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14645 Location bloc = Linemap::predeclared_location();
14646 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
14647 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14649 Type* uint8_type = Type::lookup_integer_type("uint8");
14650 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14651 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14652 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14655 // Dump AST for a ptrmask symbol expression.
14657 void
14658 Ptrmask_symbol_expression::do_dump_expression(
14659 Ast_dump_context* ast_dump_context) const
14661 ast_dump_context->ostream() << "ptrmask(";
14662 ast_dump_context->dump_type(this->type_);
14663 ast_dump_context->ostream() << ")";
14666 // Make a ptrmask symbol expression.
14668 Expression*
14669 Expression::make_ptrmask_symbol(Type* type)
14671 return new Ptrmask_symbol_expression(type);
14674 // An expression which evaluates to some characteristic of a type.
14675 // This is only used to initialize fields of a type descriptor. Using
14676 // a new expression class is slightly inefficient but gives us a good
14677 // separation between the frontend and the middle-end with regard to
14678 // how types are laid out.
14680 class Type_info_expression : public Expression
14682 public:
14683 Type_info_expression(Type* type, Type_info type_info)
14684 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14685 type_(type), type_info_(type_info)
14688 protected:
14689 bool
14690 do_is_static_initializer() const
14691 { return true; }
14693 Type*
14694 do_type();
14696 void
14697 do_determine_type(const Type_context*)
14700 Expression*
14701 do_copy()
14702 { return this; }
14704 Bexpression*
14705 do_get_backend(Translate_context* context);
14707 void
14708 do_dump_expression(Ast_dump_context*) const;
14710 private:
14711 // The type for which we are getting information.
14712 Type* type_;
14713 // What information we want.
14714 Type_info type_info_;
14717 // The type is chosen to match what the type descriptor struct
14718 // expects.
14720 Type*
14721 Type_info_expression::do_type()
14723 switch (this->type_info_)
14725 case TYPE_INFO_SIZE:
14726 case TYPE_INFO_BACKEND_PTRDATA:
14727 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14728 return Type::lookup_integer_type("uintptr");
14729 case TYPE_INFO_ALIGNMENT:
14730 case TYPE_INFO_FIELD_ALIGNMENT:
14731 return Type::lookup_integer_type("uint8");
14732 default:
14733 go_unreachable();
14737 // Return the backend representation for type information.
14739 Bexpression*
14740 Type_info_expression::do_get_backend(Translate_context* context)
14742 Gogo* gogo = context->gogo();
14743 bool ok = true;
14744 int64_t val;
14745 switch (this->type_info_)
14747 case TYPE_INFO_SIZE:
14748 ok = this->type_->backend_type_size(gogo, &val);
14749 break;
14750 case TYPE_INFO_ALIGNMENT:
14751 ok = this->type_->backend_type_align(gogo, &val);
14752 break;
14753 case TYPE_INFO_FIELD_ALIGNMENT:
14754 ok = this->type_->backend_type_field_align(gogo, &val);
14755 break;
14756 case TYPE_INFO_BACKEND_PTRDATA:
14757 ok = this->type_->backend_type_ptrdata(gogo, &val);
14758 break;
14759 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14760 ok = this->type_->descriptor_ptrdata(gogo, &val);
14761 break;
14762 default:
14763 go_unreachable();
14765 if (!ok)
14767 go_assert(saw_errors());
14768 return gogo->backend()->error_expression();
14770 Expression* e = Expression::make_integer_int64(val, this->type(),
14771 this->location());
14772 return e->get_backend(context);
14775 // Dump ast representation for a type info expression.
14777 void
14778 Type_info_expression::do_dump_expression(
14779 Ast_dump_context* ast_dump_context) const
14781 ast_dump_context->ostream() << "typeinfo(";
14782 ast_dump_context->dump_type(this->type_);
14783 ast_dump_context->ostream() << ",";
14784 ast_dump_context->ostream() <<
14785 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14786 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14787 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14788 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14789 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
14790 : "unknown");
14791 ast_dump_context->ostream() << ")";
14794 // Make a type info expression.
14796 Expression*
14797 Expression::make_type_info(Type* type, Type_info type_info)
14799 return new Type_info_expression(type, type_info);
14802 // An expression that evaluates to some characteristic of a slice.
14803 // This is used when indexing, bound-checking, or nil checking a slice.
14805 class Slice_info_expression : public Expression
14807 public:
14808 Slice_info_expression(Expression* slice, Slice_info slice_info,
14809 Location location)
14810 : Expression(EXPRESSION_SLICE_INFO, location),
14811 slice_(slice), slice_info_(slice_info)
14814 protected:
14815 Type*
14816 do_type();
14818 void
14819 do_determine_type(const Type_context*)
14822 Expression*
14823 do_copy()
14825 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14826 this->location());
14829 Bexpression*
14830 do_get_backend(Translate_context* context);
14832 void
14833 do_dump_expression(Ast_dump_context*) const;
14835 void
14836 do_issue_nil_check()
14837 { this->slice_->issue_nil_check(); }
14839 private:
14840 // The slice for which we are getting information.
14841 Expression* slice_;
14842 // What information we want.
14843 Slice_info slice_info_;
14846 // Return the type of the slice info.
14848 Type*
14849 Slice_info_expression::do_type()
14851 switch (this->slice_info_)
14853 case SLICE_INFO_VALUE_POINTER:
14854 return Type::make_pointer_type(
14855 this->slice_->type()->array_type()->element_type());
14856 case SLICE_INFO_LENGTH:
14857 case SLICE_INFO_CAPACITY:
14858 return Type::lookup_integer_type("int");
14859 default:
14860 go_unreachable();
14864 // Return the backend information for slice information.
14866 Bexpression*
14867 Slice_info_expression::do_get_backend(Translate_context* context)
14869 Gogo* gogo = context->gogo();
14870 Bexpression* bslice = this->slice_->get_backend(context);
14871 switch (this->slice_info_)
14873 case SLICE_INFO_VALUE_POINTER:
14874 case SLICE_INFO_LENGTH:
14875 case SLICE_INFO_CAPACITY:
14876 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14877 this->location());
14878 break;
14879 default:
14880 go_unreachable();
14884 // Dump ast representation for a type info expression.
14886 void
14887 Slice_info_expression::do_dump_expression(
14888 Ast_dump_context* ast_dump_context) const
14890 ast_dump_context->ostream() << "sliceinfo(";
14891 this->slice_->dump_expression(ast_dump_context);
14892 ast_dump_context->ostream() << ",";
14893 ast_dump_context->ostream() <<
14894 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14895 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14896 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14897 : "unknown");
14898 ast_dump_context->ostream() << ")";
14901 // Make a slice info expression.
14903 Expression*
14904 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14905 Location location)
14907 return new Slice_info_expression(slice, slice_info, location);
14910 // An expression that represents a slice value: a struct with value pointer,
14911 // length, and capacity fields.
14913 class Slice_value_expression : public Expression
14915 public:
14916 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14917 Expression* cap, Location location)
14918 : Expression(EXPRESSION_SLICE_VALUE, location),
14919 type_(type), valptr_(valptr), len_(len), cap_(cap)
14922 protected:
14924 do_traverse(Traverse*);
14926 Type*
14927 do_type()
14928 { return this->type_; }
14930 void
14931 do_determine_type(const Type_context*)
14932 { go_unreachable(); }
14934 Expression*
14935 do_copy()
14937 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14938 this->len_->copy(), this->cap_->copy(),
14939 this->location());
14942 Bexpression*
14943 do_get_backend(Translate_context* context);
14945 void
14946 do_dump_expression(Ast_dump_context*) const;
14948 private:
14949 // The type of the slice value.
14950 Type* type_;
14951 // The pointer to the values in the slice.
14952 Expression* valptr_;
14953 // The length of the slice.
14954 Expression* len_;
14955 // The capacity of the slice.
14956 Expression* cap_;
14960 Slice_value_expression::do_traverse(Traverse* traverse)
14962 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14963 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14964 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14965 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14966 return TRAVERSE_EXIT;
14967 return TRAVERSE_CONTINUE;
14970 Bexpression*
14971 Slice_value_expression::do_get_backend(Translate_context* context)
14973 std::vector<Bexpression*> vals(3);
14974 vals[0] = this->valptr_->get_backend(context);
14975 vals[1] = this->len_->get_backend(context);
14976 vals[2] = this->cap_->get_backend(context);
14978 Gogo* gogo = context->gogo();
14979 Btype* btype = this->type_->get_backend(gogo);
14980 return gogo->backend()->constructor_expression(btype, vals, this->location());
14983 void
14984 Slice_value_expression::do_dump_expression(
14985 Ast_dump_context* ast_dump_context) const
14987 ast_dump_context->ostream() << "slicevalue(";
14988 ast_dump_context->ostream() << "values: ";
14989 this->valptr_->dump_expression(ast_dump_context);
14990 ast_dump_context->ostream() << ", length: ";
14991 this->len_->dump_expression(ast_dump_context);
14992 ast_dump_context->ostream() << ", capacity: ";
14993 this->cap_->dump_expression(ast_dump_context);
14994 ast_dump_context->ostream() << ")";
14997 Expression*
14998 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14999 Expression* cap, Location location)
15001 go_assert(at->is_slice_type());
15002 return new Slice_value_expression(at, valptr, len, cap, location);
15005 // An expression that evaluates to some characteristic of a non-empty interface.
15006 // This is used to access the method table or underlying object of an interface.
15008 class Interface_info_expression : public Expression
15010 public:
15011 Interface_info_expression(Expression* iface, Interface_info iface_info,
15012 Location location)
15013 : Expression(EXPRESSION_INTERFACE_INFO, location),
15014 iface_(iface), iface_info_(iface_info)
15017 protected:
15018 Type*
15019 do_type();
15021 void
15022 do_determine_type(const Type_context*)
15025 Expression*
15026 do_copy()
15028 return new Interface_info_expression(this->iface_->copy(),
15029 this->iface_info_, this->location());
15032 Bexpression*
15033 do_get_backend(Translate_context* context);
15035 void
15036 do_dump_expression(Ast_dump_context*) const;
15038 void
15039 do_issue_nil_check()
15040 { this->iface_->issue_nil_check(); }
15042 private:
15043 // The interface for which we are getting information.
15044 Expression* iface_;
15045 // What information we want.
15046 Interface_info iface_info_;
15049 // Return the type of the interface info.
15051 Type*
15052 Interface_info_expression::do_type()
15054 switch (this->iface_info_)
15056 case INTERFACE_INFO_METHODS:
15058 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15059 static Hashtable result_types;
15061 Interface_type* itype = this->iface_->type()->interface_type();
15063 Hashtable::const_iterator p = result_types.find(itype);
15064 if (p != result_types.end())
15065 return p->second;
15067 Type* pdt = Type::make_type_descriptor_ptr_type();
15068 if (itype->is_empty())
15070 result_types[itype] = pdt;
15071 return pdt;
15074 Location loc = this->location();
15075 Struct_field_list* sfl = new Struct_field_list();
15076 sfl->push_back(
15077 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15079 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15080 p != itype->methods()->end();
15081 ++p)
15083 Function_type* ft = p->type()->function_type();
15084 go_assert(ft->receiver() == NULL);
15086 const Typed_identifier_list* params = ft->parameters();
15087 Typed_identifier_list* mparams = new Typed_identifier_list();
15088 if (params != NULL)
15089 mparams->reserve(params->size() + 1);
15090 Type* vt = Type::make_pointer_type(Type::make_void_type());
15091 mparams->push_back(Typed_identifier("", vt, ft->location()));
15092 if (params != NULL)
15094 for (Typed_identifier_list::const_iterator pp = params->begin();
15095 pp != params->end();
15096 ++pp)
15097 mparams->push_back(*pp);
15100 Typed_identifier_list* mresults = (ft->results() == NULL
15101 ? NULL
15102 : ft->results()->copy());
15103 Backend_function_type* mft =
15104 Type::make_backend_function_type(NULL, mparams, mresults,
15105 ft->location());
15107 std::string fname = Gogo::unpack_hidden_name(p->name());
15108 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15111 Struct_type* st = Type::make_struct_type(sfl, loc);
15112 st->set_is_struct_incomparable();
15113 Pointer_type *pt = Type::make_pointer_type(st);
15114 result_types[itype] = pt;
15115 return pt;
15117 case INTERFACE_INFO_OBJECT:
15118 return Type::make_pointer_type(Type::make_void_type());
15119 default:
15120 go_unreachable();
15124 // Return the backend representation for interface information.
15126 Bexpression*
15127 Interface_info_expression::do_get_backend(Translate_context* context)
15129 Gogo* gogo = context->gogo();
15130 Bexpression* biface = this->iface_->get_backend(context);
15131 switch (this->iface_info_)
15133 case INTERFACE_INFO_METHODS:
15134 case INTERFACE_INFO_OBJECT:
15135 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15136 this->location());
15137 break;
15138 default:
15139 go_unreachable();
15143 // Dump ast representation for an interface info expression.
15145 void
15146 Interface_info_expression::do_dump_expression(
15147 Ast_dump_context* ast_dump_context) const
15149 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15150 ast_dump_context->ostream() << "interfaceinfo(";
15151 this->iface_->dump_expression(ast_dump_context);
15152 ast_dump_context->ostream() << ",";
15153 ast_dump_context->ostream() <<
15154 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15155 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15156 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15157 : "unknown");
15158 ast_dump_context->ostream() << ")";
15161 // Make an interface info expression.
15163 Expression*
15164 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15165 Location location)
15167 return new Interface_info_expression(iface, iface_info, location);
15170 // An expression that represents an interface value. The first field is either
15171 // a type descriptor for an empty interface or a pointer to the interface method
15172 // table for a non-empty interface. The second field is always the object.
15174 class Interface_value_expression : public Expression
15176 public:
15177 Interface_value_expression(Type* type, Expression* first_field,
15178 Expression* obj, Location location)
15179 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15180 type_(type), first_field_(first_field), obj_(obj)
15183 protected:
15185 do_traverse(Traverse*);
15187 Type*
15188 do_type()
15189 { return this->type_; }
15191 void
15192 do_determine_type(const Type_context*)
15193 { go_unreachable(); }
15195 Expression*
15196 do_copy()
15198 return new Interface_value_expression(this->type_,
15199 this->first_field_->copy(),
15200 this->obj_->copy(), this->location());
15203 Bexpression*
15204 do_get_backend(Translate_context* context);
15206 void
15207 do_dump_expression(Ast_dump_context*) const;
15209 private:
15210 // The type of the interface value.
15211 Type* type_;
15212 // The first field of the interface (either a type descriptor or a pointer
15213 // to the method table.
15214 Expression* first_field_;
15215 // The underlying object of the interface.
15216 Expression* obj_;
15220 Interface_value_expression::do_traverse(Traverse* traverse)
15222 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15223 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15224 return TRAVERSE_EXIT;
15225 return TRAVERSE_CONTINUE;
15228 Bexpression*
15229 Interface_value_expression::do_get_backend(Translate_context* context)
15231 std::vector<Bexpression*> vals(2);
15232 vals[0] = this->first_field_->get_backend(context);
15233 vals[1] = this->obj_->get_backend(context);
15235 Gogo* gogo = context->gogo();
15236 Btype* btype = this->type_->get_backend(gogo);
15237 return gogo->backend()->constructor_expression(btype, vals, this->location());
15240 void
15241 Interface_value_expression::do_dump_expression(
15242 Ast_dump_context* ast_dump_context) const
15244 ast_dump_context->ostream() << "interfacevalue(";
15245 ast_dump_context->ostream() <<
15246 (this->type_->interface_type()->is_empty()
15247 ? "type_descriptor: "
15248 : "methods: ");
15249 this->first_field_->dump_expression(ast_dump_context);
15250 ast_dump_context->ostream() << ", object: ";
15251 this->obj_->dump_expression(ast_dump_context);
15252 ast_dump_context->ostream() << ")";
15255 Expression*
15256 Expression::make_interface_value(Type* type, Expression* first_value,
15257 Expression* object, Location location)
15259 return new Interface_value_expression(type, first_value, object, location);
15262 // An interface method table for a pair of types: an interface type and a type
15263 // that implements that interface.
15265 class Interface_mtable_expression : public Expression
15267 public:
15268 Interface_mtable_expression(Interface_type* itype, Type* type,
15269 bool is_pointer, Location location)
15270 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15271 itype_(itype), type_(type), is_pointer_(is_pointer),
15272 method_table_type_(NULL), bvar_(NULL)
15275 protected:
15277 do_traverse(Traverse*);
15279 Type*
15280 do_type();
15282 bool
15283 do_is_static_initializer() const
15284 { return true; }
15286 void
15287 do_determine_type(const Type_context*)
15288 { go_unreachable(); }
15290 Expression*
15291 do_copy()
15293 return new Interface_mtable_expression(this->itype_, this->type_,
15294 this->is_pointer_, this->location());
15297 bool
15298 do_is_addressable() const
15299 { return true; }
15301 Bexpression*
15302 do_get_backend(Translate_context* context);
15304 void
15305 do_dump_expression(Ast_dump_context*) const;
15307 private:
15308 // The interface type for which the methods are defined.
15309 Interface_type* itype_;
15310 // The type to construct the interface method table for.
15311 Type* type_;
15312 // Whether this table contains the method set for the receiver type or the
15313 // pointer receiver type.
15314 bool is_pointer_;
15315 // The type of the method table.
15316 Type* method_table_type_;
15317 // The backend variable that refers to the interface method table.
15318 Bvariable* bvar_;
15322 Interface_mtable_expression::do_traverse(Traverse* traverse)
15324 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15325 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15326 return TRAVERSE_EXIT;
15327 return TRAVERSE_CONTINUE;
15330 Type*
15331 Interface_mtable_expression::do_type()
15333 if (this->method_table_type_ != NULL)
15334 return this->method_table_type_;
15336 const Typed_identifier_list* interface_methods = this->itype_->methods();
15337 go_assert(!interface_methods->empty());
15339 Struct_field_list* sfl = new Struct_field_list;
15340 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15341 this->location());
15342 sfl->push_back(Struct_field(tid));
15343 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15344 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15345 p != interface_methods->end();
15346 ++p)
15348 // We want C function pointers here, not func descriptors; model
15349 // using void* pointers.
15350 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15351 sfl->push_back(Struct_field(method));
15353 Struct_type* st = Type::make_struct_type(sfl, this->location());
15354 st->set_is_struct_incomparable();
15355 this->method_table_type_ = st;
15356 return this->method_table_type_;
15359 Bexpression*
15360 Interface_mtable_expression::do_get_backend(Translate_context* context)
15362 Gogo* gogo = context->gogo();
15363 Location loc = Linemap::predeclared_location();
15364 if (this->bvar_ != NULL)
15365 return gogo->backend()->var_expression(this->bvar_, this->location());
15367 const Typed_identifier_list* interface_methods = this->itype_->methods();
15368 go_assert(!interface_methods->empty());
15370 std::string mangled_name =
15371 gogo->interface_method_table_name(this->itype_, this->type_,
15372 this->is_pointer_);
15374 // Set is_public if we are converting a named type to an interface
15375 // type that is defined in the same package as the named type, and
15376 // the interface has hidden methods. In that case the interface
15377 // method table will be defined by the package that defines the
15378 // types.
15379 bool is_public = false;
15380 if (this->type_->named_type() != NULL
15381 && (this->type_->named_type()->named_object()->package()
15382 == this->itype_->package()))
15384 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15385 p != interface_methods->end();
15386 ++p)
15388 if (Gogo::is_hidden_name(p->name()))
15390 is_public = true;
15391 break;
15396 if (is_public
15397 && this->type_->named_type()->named_object()->package() != NULL)
15399 // The interface conversion table is defined elsewhere.
15400 Btype* btype = this->type()->get_backend(gogo);
15401 std::string asm_name(go_selectively_encode_id(mangled_name));
15402 this->bvar_ =
15403 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15404 btype, loc);
15405 return gogo->backend()->var_expression(this->bvar_, this->location());
15408 // The first element is the type descriptor.
15409 Type* td_type;
15410 if (!this->is_pointer_)
15411 td_type = this->type_;
15412 else
15413 td_type = Type::make_pointer_type(this->type_);
15415 std::vector<Backend::Btyped_identifier> bstructfields;
15417 // Build an interface method table for a type: a type descriptor followed by a
15418 // list of function pointers, one for each interface method. This is used for
15419 // interfaces.
15420 Expression_list* svals = new Expression_list();
15421 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15422 svals->push_back(tdescriptor);
15424 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15425 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15426 bstructfields.push_back(btd);
15428 Named_type* nt = this->type_->named_type();
15429 Struct_type* st = this->type_->struct_type();
15430 go_assert(nt != NULL || st != NULL);
15432 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15433 p != interface_methods->end();
15434 ++p)
15436 bool is_ambiguous;
15437 Method* m;
15438 if (nt != NULL)
15439 m = nt->method_function(p->name(), &is_ambiguous);
15440 else
15441 m = st->method_function(p->name(), &is_ambiguous);
15442 go_assert(m != NULL);
15443 Named_object* no = m->named_object();
15445 go_assert(no->is_function() || no->is_function_declaration());
15447 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15448 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15449 bstructfields.push_back(bmtype);
15451 svals->push_back(Expression::make_func_code_reference(no, loc));
15454 Btype *btype = gogo->backend()->struct_type(bstructfields);
15455 std::vector<Bexpression*> ctor_bexprs;
15456 for (Expression_list::const_iterator pe = svals->begin();
15457 pe != svals->end();
15458 ++pe)
15460 ctor_bexprs.push_back((*pe)->get_backend(context));
15462 Bexpression* ctor =
15463 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
15465 std::string asm_name(go_selectively_encode_id(mangled_name));
15466 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15467 !is_public, btype, loc);
15468 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15469 !is_public, btype, loc, ctor);
15470 return gogo->backend()->var_expression(this->bvar_, loc);
15473 void
15474 Interface_mtable_expression::do_dump_expression(
15475 Ast_dump_context* ast_dump_context) const
15477 ast_dump_context->ostream() << "__go_"
15478 << (this->is_pointer_ ? "pimt__" : "imt_");
15479 ast_dump_context->dump_type(this->itype_);
15480 ast_dump_context->ostream() << "__";
15481 ast_dump_context->dump_type(this->type_);
15484 Expression*
15485 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15486 bool is_pointer, Location location)
15488 return new Interface_mtable_expression(itype, type, is_pointer, location);
15491 // An expression which evaluates to the offset of a field within a
15492 // struct. This, like Type_info_expression, q.v., is only used to
15493 // initialize fields of a type descriptor.
15495 class Struct_field_offset_expression : public Expression
15497 public:
15498 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15499 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15500 Linemap::predeclared_location()),
15501 type_(type), field_(field)
15504 protected:
15505 bool
15506 do_is_static_initializer() const
15507 { return true; }
15509 Type*
15510 do_type()
15511 { return Type::lookup_integer_type("uintptr"); }
15513 void
15514 do_determine_type(const Type_context*)
15517 Expression*
15518 do_copy()
15519 { return this; }
15521 Bexpression*
15522 do_get_backend(Translate_context* context);
15524 void
15525 do_dump_expression(Ast_dump_context*) const;
15527 private:
15528 // The type of the struct.
15529 Struct_type* type_;
15530 // The field.
15531 const Struct_field* field_;
15534 // Return the backend representation for a struct field offset.
15536 Bexpression*
15537 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15539 const Struct_field_list* fields = this->type_->fields();
15540 Struct_field_list::const_iterator p;
15541 unsigned i = 0;
15542 for (p = fields->begin();
15543 p != fields->end();
15544 ++p, ++i)
15545 if (&*p == this->field_)
15546 break;
15547 go_assert(&*p == this->field_);
15549 Gogo* gogo = context->gogo();
15550 Btype* btype = this->type_->get_backend(gogo);
15552 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15553 Type* uptr_type = Type::lookup_integer_type("uintptr");
15554 Expression* ret =
15555 Expression::make_integer_int64(offset, uptr_type,
15556 Linemap::predeclared_location());
15557 return ret->get_backend(context);
15560 // Dump ast representation for a struct field offset expression.
15562 void
15563 Struct_field_offset_expression::do_dump_expression(
15564 Ast_dump_context* ast_dump_context) const
15566 ast_dump_context->ostream() << "unsafe.Offsetof(";
15567 ast_dump_context->dump_type(this->type_);
15568 ast_dump_context->ostream() << '.';
15569 ast_dump_context->ostream() <<
15570 Gogo::message_name(this->field_->field_name());
15571 ast_dump_context->ostream() << ")";
15574 // Make an expression for a struct field offset.
15576 Expression*
15577 Expression::make_struct_field_offset(Struct_type* type,
15578 const Struct_field* field)
15580 return new Struct_field_offset_expression(type, field);
15583 // An expression which evaluates to the address of an unnamed label.
15585 class Label_addr_expression : public Expression
15587 public:
15588 Label_addr_expression(Label* label, Location location)
15589 : Expression(EXPRESSION_LABEL_ADDR, location),
15590 label_(label)
15593 protected:
15594 Type*
15595 do_type()
15596 { return Type::make_pointer_type(Type::make_void_type()); }
15598 void
15599 do_determine_type(const Type_context*)
15602 Expression*
15603 do_copy()
15604 { return new Label_addr_expression(this->label_, this->location()); }
15606 Bexpression*
15607 do_get_backend(Translate_context* context)
15608 { return this->label_->get_addr(context, this->location()); }
15610 void
15611 do_dump_expression(Ast_dump_context* ast_dump_context) const
15612 { ast_dump_context->ostream() << this->label_->name(); }
15614 private:
15615 // The label whose address we are taking.
15616 Label* label_;
15619 // Make an expression for the address of an unnamed label.
15621 Expression*
15622 Expression::make_label_addr(Label* label, Location location)
15624 return new Label_addr_expression(label, location);
15627 // Class Conditional_expression.
15629 // Traversal.
15632 Conditional_expression::do_traverse(Traverse* traverse)
15634 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15635 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15636 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15637 return TRAVERSE_EXIT;
15638 return TRAVERSE_CONTINUE;
15641 // Return the type of the conditional expression.
15643 Type*
15644 Conditional_expression::do_type()
15646 Type* result_type = Type::make_void_type();
15647 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15648 NULL))
15649 result_type = this->then_->type();
15650 else if (this->then_->is_nil_expression()
15651 || this->else_->is_nil_expression())
15652 result_type = (!this->then_->is_nil_expression()
15653 ? this->then_->type()
15654 : this->else_->type());
15655 return result_type;
15658 // Determine type for a conditional expression.
15660 void
15661 Conditional_expression::do_determine_type(const Type_context* context)
15663 this->cond_->determine_type_no_context();
15664 this->then_->determine_type(context);
15665 this->else_->determine_type(context);
15668 // Get the backend representation of a conditional expression.
15670 Bexpression*
15671 Conditional_expression::do_get_backend(Translate_context* context)
15673 Gogo* gogo = context->gogo();
15674 Btype* result_btype = this->type()->get_backend(gogo);
15675 Bexpression* cond = this->cond_->get_backend(context);
15676 Bexpression* then = this->then_->get_backend(context);
15677 Bexpression* belse = this->else_->get_backend(context);
15678 Bfunction* bfn = context->function()->func_value()->get_decl();
15679 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
15680 belse, this->location());
15683 // Dump ast representation of a conditional expression.
15685 void
15686 Conditional_expression::do_dump_expression(
15687 Ast_dump_context* ast_dump_context) const
15689 ast_dump_context->ostream() << "(";
15690 ast_dump_context->dump_expression(this->cond_);
15691 ast_dump_context->ostream() << " ? ";
15692 ast_dump_context->dump_expression(this->then_);
15693 ast_dump_context->ostream() << " : ";
15694 ast_dump_context->dump_expression(this->else_);
15695 ast_dump_context->ostream() << ") ";
15698 // Make a conditional expression.
15700 Expression*
15701 Expression::make_conditional(Expression* cond, Expression* then,
15702 Expression* else_expr, Location location)
15704 return new Conditional_expression(cond, then, else_expr, location);
15707 // Class Compound_expression.
15709 // Traversal.
15712 Compound_expression::do_traverse(Traverse* traverse)
15714 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15715 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15716 return TRAVERSE_EXIT;
15717 return TRAVERSE_CONTINUE;
15720 // Return the type of the compound expression.
15722 Type*
15723 Compound_expression::do_type()
15725 return this->expr_->type();
15728 // Determine type for a compound expression.
15730 void
15731 Compound_expression::do_determine_type(const Type_context* context)
15733 this->init_->determine_type_no_context();
15734 this->expr_->determine_type(context);
15737 // Get the backend representation of a compound expression.
15739 Bexpression*
15740 Compound_expression::do_get_backend(Translate_context* context)
15742 Gogo* gogo = context->gogo();
15743 Bexpression* binit = this->init_->get_backend(context);
15744 Bfunction* bfunction = context->function()->func_value()->get_decl();
15745 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15746 binit);
15747 Bexpression* bexpr = this->expr_->get_backend(context);
15748 return gogo->backend()->compound_expression(init_stmt, bexpr,
15749 this->location());
15752 // Dump ast representation of a conditional expression.
15754 void
15755 Compound_expression::do_dump_expression(
15756 Ast_dump_context* ast_dump_context) const
15758 ast_dump_context->ostream() << "(";
15759 ast_dump_context->dump_expression(this->init_);
15760 ast_dump_context->ostream() << ",";
15761 ast_dump_context->dump_expression(this->expr_);
15762 ast_dump_context->ostream() << ") ";
15765 // Make a compound expression.
15767 Expression*
15768 Expression::make_compound(Expression* init, Expression* expr, Location location)
15770 return new Compound_expression(init, expr, location);
15773 // Class Backend_expression.
15776 Backend_expression::do_traverse(Traverse*)
15778 return TRAVERSE_CONTINUE;
15781 void
15782 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15784 ast_dump_context->ostream() << "backend_expression<";
15785 ast_dump_context->dump_type(this->type_);
15786 ast_dump_context->ostream() << ">";
15789 Expression*
15790 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15792 return new Backend_expression(bexpr, type, location);
15795 // Import an expression. This comes at the end in order to see the
15796 // various class definitions.
15798 Expression*
15799 Expression::import_expression(Import* imp)
15801 int c = imp->peek_char();
15802 if (imp->match_c_string("- ")
15803 || imp->match_c_string("! ")
15804 || imp->match_c_string("^ "))
15805 return Unary_expression::do_import(imp);
15806 else if (c == '(')
15807 return Binary_expression::do_import(imp);
15808 else if (imp->match_c_string("true")
15809 || imp->match_c_string("false"))
15810 return Boolean_expression::do_import(imp);
15811 else if (c == '"')
15812 return String_expression::do_import(imp);
15813 else if (c == '-' || (c >= '0' && c <= '9'))
15815 // This handles integers, floats and complex constants.
15816 return Integer_expression::do_import(imp);
15818 else if (imp->match_c_string("nil"))
15819 return Nil_expression::do_import(imp);
15820 else if (imp->match_c_string("convert"))
15821 return Type_conversion_expression::do_import(imp);
15822 else
15824 go_error_at(imp->location(), "import error: expected expression");
15825 return Expression::make_error(imp->location());
15829 // Class Expression_list.
15831 // Traverse the list.
15834 Expression_list::traverse(Traverse* traverse)
15836 for (Expression_list::iterator p = this->begin();
15837 p != this->end();
15838 ++p)
15840 if (*p != NULL)
15842 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15843 return TRAVERSE_EXIT;
15846 return TRAVERSE_CONTINUE;
15849 // Copy the list.
15851 Expression_list*
15852 Expression_list::copy()
15854 Expression_list* ret = new Expression_list();
15855 for (Expression_list::iterator p = this->begin();
15856 p != this->end();
15857 ++p)
15859 if (*p == NULL)
15860 ret->push_back(NULL);
15861 else
15862 ret->push_back((*p)->copy());
15864 return ret;
15867 // Return whether an expression list has an error expression.
15869 bool
15870 Expression_list::contains_error() const
15872 for (Expression_list::const_iterator p = this->begin();
15873 p != this->end();
15874 ++p)
15875 if (*p != NULL && (*p)->is_error_expression())
15876 return true;
15877 return false;
15880 // Class Numeric_constant.
15882 // Destructor.
15884 Numeric_constant::~Numeric_constant()
15886 this->clear();
15889 // Copy constructor.
15891 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15892 : classification_(a.classification_), type_(a.type_)
15894 switch (a.classification_)
15896 case NC_INVALID:
15897 break;
15898 case NC_INT:
15899 case NC_RUNE:
15900 mpz_init_set(this->u_.int_val, a.u_.int_val);
15901 break;
15902 case NC_FLOAT:
15903 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15904 break;
15905 case NC_COMPLEX:
15906 mpc_init2(this->u_.complex_val, mpc_precision);
15907 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15908 break;
15909 default:
15910 go_unreachable();
15914 // Assignment operator.
15916 Numeric_constant&
15917 Numeric_constant::operator=(const Numeric_constant& a)
15919 this->clear();
15920 this->classification_ = a.classification_;
15921 this->type_ = a.type_;
15922 switch (a.classification_)
15924 case NC_INVALID:
15925 break;
15926 case NC_INT:
15927 case NC_RUNE:
15928 mpz_init_set(this->u_.int_val, a.u_.int_val);
15929 break;
15930 case NC_FLOAT:
15931 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15932 break;
15933 case NC_COMPLEX:
15934 mpc_init2(this->u_.complex_val, mpc_precision);
15935 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15936 break;
15937 default:
15938 go_unreachable();
15940 return *this;
15943 // Clear the contents.
15945 void
15946 Numeric_constant::clear()
15948 switch (this->classification_)
15950 case NC_INVALID:
15951 break;
15952 case NC_INT:
15953 case NC_RUNE:
15954 mpz_clear(this->u_.int_val);
15955 break;
15956 case NC_FLOAT:
15957 mpfr_clear(this->u_.float_val);
15958 break;
15959 case NC_COMPLEX:
15960 mpc_clear(this->u_.complex_val);
15961 break;
15962 default:
15963 go_unreachable();
15965 this->classification_ = NC_INVALID;
15968 // Set to an unsigned long value.
15970 void
15971 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15973 this->clear();
15974 this->classification_ = NC_INT;
15975 this->type_ = type;
15976 mpz_init_set_ui(this->u_.int_val, val);
15979 // Set to an integer value.
15981 void
15982 Numeric_constant::set_int(Type* type, const mpz_t val)
15984 this->clear();
15985 this->classification_ = NC_INT;
15986 this->type_ = type;
15987 mpz_init_set(this->u_.int_val, val);
15990 // Set to a rune value.
15992 void
15993 Numeric_constant::set_rune(Type* type, const mpz_t val)
15995 this->clear();
15996 this->classification_ = NC_RUNE;
15997 this->type_ = type;
15998 mpz_init_set(this->u_.int_val, val);
16001 // Set to a floating point value.
16003 void
16004 Numeric_constant::set_float(Type* type, const mpfr_t val)
16006 this->clear();
16007 this->classification_ = NC_FLOAT;
16008 this->type_ = type;
16009 // Numeric constants do not have negative zero values, so remove
16010 // them here. They also don't have infinity or NaN values, but we
16011 // should never see them here.
16012 if (mpfr_zero_p(val))
16013 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16014 else
16015 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16018 // Set to a complex value.
16020 void
16021 Numeric_constant::set_complex(Type* type, const mpc_t val)
16023 this->clear();
16024 this->classification_ = NC_COMPLEX;
16025 this->type_ = type;
16026 mpc_init2(this->u_.complex_val, mpc_precision);
16027 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
16030 // Get an int value.
16032 void
16033 Numeric_constant::get_int(mpz_t* val) const
16035 go_assert(this->is_int());
16036 mpz_init_set(*val, this->u_.int_val);
16039 // Get a rune value.
16041 void
16042 Numeric_constant::get_rune(mpz_t* val) const
16044 go_assert(this->is_rune());
16045 mpz_init_set(*val, this->u_.int_val);
16048 // Get a floating point value.
16050 void
16051 Numeric_constant::get_float(mpfr_t* val) const
16053 go_assert(this->is_float());
16054 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16057 // Get a complex value.
16059 void
16060 Numeric_constant::get_complex(mpc_t* val) const
16062 go_assert(this->is_complex());
16063 mpc_init2(*val, mpc_precision);
16064 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16067 // Express value as unsigned long if possible.
16069 Numeric_constant::To_unsigned_long
16070 Numeric_constant::to_unsigned_long(unsigned long* val) const
16072 switch (this->classification_)
16074 case NC_INT:
16075 case NC_RUNE:
16076 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16077 case NC_FLOAT:
16078 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16079 case NC_COMPLEX:
16080 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16081 return NC_UL_NOTINT;
16082 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16083 val);
16084 default:
16085 go_unreachable();
16089 // Express integer value as unsigned long if possible.
16091 Numeric_constant::To_unsigned_long
16092 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16093 unsigned long *val) const
16095 if (mpz_sgn(ival) < 0)
16096 return NC_UL_NEGATIVE;
16097 unsigned long ui = mpz_get_ui(ival);
16098 if (mpz_cmp_ui(ival, ui) != 0)
16099 return NC_UL_BIG;
16100 *val = ui;
16101 return NC_UL_VALID;
16104 // Express floating point value as unsigned long if possible.
16106 Numeric_constant::To_unsigned_long
16107 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16108 unsigned long *val) const
16110 if (!mpfr_integer_p(fval))
16111 return NC_UL_NOTINT;
16112 mpz_t ival;
16113 mpz_init(ival);
16114 mpfr_get_z(ival, fval, GMP_RNDN);
16115 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16116 mpz_clear(ival);
16117 return ret;
16120 // Express value as memory size if possible.
16122 bool
16123 Numeric_constant::to_memory_size(int64_t* val) const
16125 switch (this->classification_)
16127 case NC_INT:
16128 case NC_RUNE:
16129 return this->mpz_to_memory_size(this->u_.int_val, val);
16130 case NC_FLOAT:
16131 return this->mpfr_to_memory_size(this->u_.float_val, val);
16132 case NC_COMPLEX:
16133 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16134 return false;
16135 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16136 default:
16137 go_unreachable();
16141 // Express integer as memory size if possible.
16143 bool
16144 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16146 if (mpz_sgn(ival) < 0)
16147 return false;
16148 if (mpz_fits_slong_p(ival))
16150 *val = static_cast<int64_t>(mpz_get_si(ival));
16151 return true;
16154 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16155 // positive value.
16156 if (mpz_sizeinbase(ival, 2) >= 64)
16157 return false;
16159 mpz_t q, r;
16160 mpz_init(q);
16161 mpz_init(r);
16162 mpz_tdiv_q_2exp(q, ival, 32);
16163 mpz_tdiv_r_2exp(r, ival, 32);
16164 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16165 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16166 + static_cast<int64_t>(mpz_get_ui(r)));
16167 mpz_clear(r);
16168 mpz_clear(q);
16169 return true;
16172 // Express floating point value as memory size if possible.
16174 bool
16175 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16177 if (!mpfr_integer_p(fval))
16178 return false;
16179 mpz_t ival;
16180 mpz_init(ival);
16181 mpfr_get_z(ival, fval, GMP_RNDN);
16182 bool ret = this->mpz_to_memory_size(ival, val);
16183 mpz_clear(ival);
16184 return ret;
16187 // Convert value to integer if possible.
16189 bool
16190 Numeric_constant::to_int(mpz_t* val) const
16192 switch (this->classification_)
16194 case NC_INT:
16195 case NC_RUNE:
16196 mpz_init_set(*val, this->u_.int_val);
16197 return true;
16198 case NC_FLOAT:
16199 if (!mpfr_integer_p(this->u_.float_val))
16200 return false;
16201 mpz_init(*val);
16202 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16203 return true;
16204 case NC_COMPLEX:
16205 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16206 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16207 return false;
16208 mpz_init(*val);
16209 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16210 return true;
16211 default:
16212 go_unreachable();
16216 // Convert value to floating point if possible.
16218 bool
16219 Numeric_constant::to_float(mpfr_t* val) const
16221 switch (this->classification_)
16223 case NC_INT:
16224 case NC_RUNE:
16225 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16226 return true;
16227 case NC_FLOAT:
16228 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16229 return true;
16230 case NC_COMPLEX:
16231 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16232 return false;
16233 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16234 return true;
16235 default:
16236 go_unreachable();
16240 // Convert value to complex.
16242 bool
16243 Numeric_constant::to_complex(mpc_t* val) const
16245 mpc_init2(*val, mpc_precision);
16246 switch (this->classification_)
16248 case NC_INT:
16249 case NC_RUNE:
16250 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16251 return true;
16252 case NC_FLOAT:
16253 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16254 return true;
16255 case NC_COMPLEX:
16256 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16257 return true;
16258 default:
16259 go_unreachable();
16263 // Get the type.
16265 Type*
16266 Numeric_constant::type() const
16268 if (this->type_ != NULL)
16269 return this->type_;
16270 switch (this->classification_)
16272 case NC_INT:
16273 return Type::make_abstract_integer_type();
16274 case NC_RUNE:
16275 return Type::make_abstract_character_type();
16276 case NC_FLOAT:
16277 return Type::make_abstract_float_type();
16278 case NC_COMPLEX:
16279 return Type::make_abstract_complex_type();
16280 default:
16281 go_unreachable();
16285 // If the constant can be expressed in TYPE, then set the type of the
16286 // constant to TYPE and return true. Otherwise return false, and, if
16287 // ISSUE_ERROR is true, report an appropriate error message.
16289 bool
16290 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16292 bool ret;
16293 if (type == NULL || type->is_error())
16294 ret = true;
16295 else if (type->integer_type() != NULL)
16296 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16297 else if (type->float_type() != NULL)
16298 ret = this->check_float_type(type->float_type(), issue_error, loc);
16299 else if (type->complex_type() != NULL)
16300 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16301 else
16303 ret = false;
16304 if (issue_error)
16305 go_assert(saw_errors());
16307 if (ret)
16308 this->type_ = type;
16309 return ret;
16312 // Check whether the constant can be expressed in an integer type.
16314 bool
16315 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
16316 Location location)
16318 mpz_t val;
16319 switch (this->classification_)
16321 case NC_INT:
16322 case NC_RUNE:
16323 mpz_init_set(val, this->u_.int_val);
16324 break;
16326 case NC_FLOAT:
16327 if (!mpfr_integer_p(this->u_.float_val))
16329 if (issue_error)
16331 go_error_at(location,
16332 "floating point constant truncated to integer");
16333 this->set_invalid();
16335 return false;
16337 mpz_init(val);
16338 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16339 break;
16341 case NC_COMPLEX:
16342 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16343 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16345 if (issue_error)
16347 go_error_at(location, "complex constant truncated to integer");
16348 this->set_invalid();
16350 return false;
16352 mpz_init(val);
16353 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16354 break;
16356 default:
16357 go_unreachable();
16360 bool ret;
16361 if (type->is_abstract())
16362 ret = true;
16363 else
16365 int bits = mpz_sizeinbase(val, 2);
16366 if (type->is_unsigned())
16368 // For an unsigned type we can only accept a nonnegative
16369 // number, and we must be able to represents at least BITS.
16370 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16372 else
16374 // For a signed type we need an extra bit to indicate the
16375 // sign. We have to handle the most negative integer
16376 // specially.
16377 ret = (bits + 1 <= type->bits()
16378 || (bits <= type->bits()
16379 && mpz_sgn(val) < 0
16380 && (mpz_scan1(val, 0)
16381 == static_cast<unsigned long>(type->bits() - 1))
16382 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16386 if (!ret && issue_error)
16388 go_error_at(location, "integer constant overflow");
16389 this->set_invalid();
16392 return ret;
16395 // Check whether the constant can be expressed in a floating point
16396 // type.
16398 bool
16399 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
16400 Location location)
16402 mpfr_t val;
16403 switch (this->classification_)
16405 case NC_INT:
16406 case NC_RUNE:
16407 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16408 break;
16410 case NC_FLOAT:
16411 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16412 break;
16414 case NC_COMPLEX:
16415 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16417 if (issue_error)
16419 this->set_invalid();
16420 go_error_at(location, "complex constant truncated to float");
16422 return false;
16424 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16425 break;
16427 default:
16428 go_unreachable();
16431 bool ret;
16432 if (type->is_abstract())
16433 ret = true;
16434 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16436 // A NaN or Infinity always fits in the range of the type.
16437 ret = true;
16439 else
16441 mp_exp_t exp = mpfr_get_exp(val);
16442 mp_exp_t max_exp;
16443 switch (type->bits())
16445 case 32:
16446 max_exp = 128;
16447 break;
16448 case 64:
16449 max_exp = 1024;
16450 break;
16451 default:
16452 go_unreachable();
16455 ret = exp <= max_exp;
16457 if (ret)
16459 // Round the constant to the desired type.
16460 mpfr_t t;
16461 mpfr_init(t);
16462 switch (type->bits())
16464 case 32:
16465 mpfr_set_prec(t, 24);
16466 break;
16467 case 64:
16468 mpfr_set_prec(t, 53);
16469 break;
16470 default:
16471 go_unreachable();
16473 mpfr_set(t, val, GMP_RNDN);
16474 mpfr_set(val, t, GMP_RNDN);
16475 mpfr_clear(t);
16477 this->set_float(type, val);
16481 mpfr_clear(val);
16483 if (!ret && issue_error)
16485 go_error_at(location, "floating point constant overflow");
16486 this->set_invalid();
16489 return ret;
16492 // Check whether the constant can be expressed in a complex type.
16494 bool
16495 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16496 Location location)
16498 if (type->is_abstract())
16499 return true;
16501 mp_exp_t max_exp;
16502 switch (type->bits())
16504 case 64:
16505 max_exp = 128;
16506 break;
16507 case 128:
16508 max_exp = 1024;
16509 break;
16510 default:
16511 go_unreachable();
16514 mpc_t val;
16515 mpc_init2(val, mpc_precision);
16516 switch (this->classification_)
16518 case NC_INT:
16519 case NC_RUNE:
16520 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16521 break;
16523 case NC_FLOAT:
16524 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16525 break;
16527 case NC_COMPLEX:
16528 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16529 break;
16531 default:
16532 go_unreachable();
16535 bool ret = true;
16536 if (!mpfr_nan_p(mpc_realref(val))
16537 && !mpfr_inf_p(mpc_realref(val))
16538 && !mpfr_zero_p(mpc_realref(val))
16539 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16541 if (issue_error)
16543 go_error_at(location, "complex real part overflow");
16544 this->set_invalid();
16546 ret = false;
16549 if (!mpfr_nan_p(mpc_imagref(val))
16550 && !mpfr_inf_p(mpc_imagref(val))
16551 && !mpfr_zero_p(mpc_imagref(val))
16552 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16554 if (issue_error)
16556 go_error_at(location, "complex imaginary part overflow");
16557 this->set_invalid();
16559 ret = false;
16562 if (ret)
16564 // Round the constant to the desired type.
16565 mpc_t t;
16566 switch (type->bits())
16568 case 64:
16569 mpc_init2(t, 24);
16570 break;
16571 case 128:
16572 mpc_init2(t, 53);
16573 break;
16574 default:
16575 go_unreachable();
16577 mpc_set(t, val, MPC_RNDNN);
16578 mpc_set(val, t, MPC_RNDNN);
16579 mpc_clear(t);
16581 this->set_complex(type, val);
16584 mpc_clear(val);
16586 return ret;
16589 // Return an Expression for this value.
16591 Expression*
16592 Numeric_constant::expression(Location loc) const
16594 switch (this->classification_)
16596 case NC_INT:
16597 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16598 case NC_RUNE:
16599 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16600 case NC_FLOAT:
16601 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16602 case NC_COMPLEX:
16603 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16604 case NC_INVALID:
16605 go_assert(saw_errors());
16606 return Expression::make_error(loc);
16607 default:
16608 go_unreachable();