i386: Allow all register_operand SUBREGs in x86_ternlog_idx.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob238d5a56ca2ae70ba1dc49de9016a2b8574c0f6b
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 // A traversal used to set the location of subexpressions.
64 class Set_location : public Traverse
66 public:
67 Set_location(Location loc)
68 : Traverse(traverse_expressions),
69 loc_(loc)
70 { }
72 int
73 expression(Expression** pexpr);
75 private:
76 Location loc_;
79 // Set the location of an expression.
81 int
82 Set_location::expression(Expression** pexpr)
84 // Some expressions are shared or don't have an independent
85 // location, so we shouldn't change their location. This is the set
86 // of expressions for which do_copy is just "return this" or
87 // otherwise does not pass down the location.
88 switch ((*pexpr)->classification())
90 case Expression::EXPRESSION_ERROR:
91 case Expression::EXPRESSION_VAR_REFERENCE:
92 case Expression::EXPRESSION_ENCLOSED_VAR_REFERENCE:
93 case Expression::EXPRESSION_STRING:
94 case Expression::EXPRESSION_FUNC_DESCRIPTOR:
95 case Expression::EXPRESSION_TYPE:
96 case Expression::EXPRESSION_BOOLEAN:
97 case Expression::EXPRESSION_CONST_REFERENCE:
98 case Expression::EXPRESSION_NIL:
99 case Expression::EXPRESSION_TYPE_DESCRIPTOR:
100 case Expression::EXPRESSION_GC_SYMBOL:
101 case Expression::EXPRESSION_PTRMASK_SYMBOL:
102 case Expression::EXPRESSION_TYPE_INFO:
103 case Expression::EXPRESSION_STRUCT_FIELD_OFFSET:
104 return TRAVERSE_CONTINUE;
105 default:
106 break;
109 (*pexpr)->location_ = this->loc_;
110 return TRAVERSE_CONTINUE;
113 // Set the location of an expression and its subexpressions.
115 void
116 Expression::set_location(Location loc)
118 this->location_ = loc;
119 Set_location sl(loc);
120 this->traverse_subexpressions(&sl);
123 // Default implementation for do_traverse for child classes.
126 Expression::do_traverse(Traverse*)
128 return TRAVERSE_CONTINUE;
131 // This virtual function is called by the parser if the value of this
132 // expression is being discarded. By default, we give an error.
133 // Expressions with side effects override.
135 bool
136 Expression::do_discarding_value()
138 this->unused_value_error();
139 return false;
142 // This virtual function is called to export expressions. This will
143 // only be used by expressions which may be constant.
145 void
146 Expression::do_export(Export_function_body*) const
148 go_unreachable();
151 // Write a name to the export data.
153 void
154 Expression::export_name(Export_function_body* efb, const Named_object* no)
156 if (no->package() != NULL)
158 char buf[50];
159 snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
160 efb->write_c_string(buf);
163 if (!Gogo::is_hidden_name(no->name()))
164 efb->write_string(no->name());
165 else
167 efb->write_c_string(".");
168 efb->write_string(Gogo::unpack_hidden_name(no->name()));
172 // Give an error saying that the value of the expression is not used.
174 void
175 Expression::unused_value_error()
177 if (this->type()->is_error())
179 go_assert(saw_errors());
180 this->set_is_error();
182 else
183 this->report_error(_("value computed is not used"));
186 // Note that this expression is an error. This is called by children
187 // when they discover an error.
189 void
190 Expression::set_is_error()
192 this->classification_ = EXPRESSION_ERROR;
195 // For children to call to report an error conveniently.
197 void
198 Expression::report_error(const char* msg)
200 go_error_at(this->location_, "%s", msg);
201 this->set_is_error();
204 // A convenience function for handling a type in do_is_untyped. If
205 // TYPE is not abstract, return false. Otherwise set *PTYPE to TYPE
206 // and return true.
208 bool
209 Expression::is_untyped_type(Type* type, Type** ptype)
211 if (!type->is_abstract())
212 return false;
213 *ptype = type;
214 return true;
217 // Report whether this is a type expression.
219 bool
220 Expression::is_type_expression() const
222 if (this->classification_ == EXPRESSION_TYPE)
223 return true;
224 if (this->unknown_expression() != NULL)
226 Named_object* no = this->unknown_expression()->named_object();
227 if (no->is_unknown())
229 no = no->unknown_value()->real_named_object();
230 if (no == NULL)
231 return false;
233 return no->is_type();
235 if (this->unary_expression() != NULL
236 && this->unary_expression()->op() == OPERATOR_MULT
237 && this->unary_expression()->operand()->is_type_expression())
238 return true;
239 return false;
242 // Set types of variables and constants. This is implemented by the
243 // child class.
245 void
246 Expression::determine_type(Gogo* gogo, const Type_context* context)
248 this->do_determine_type(gogo, context);
251 // Set types when there is no context.
253 void
254 Expression::determine_type_no_context(Gogo* gogo)
256 Type_context context;
257 this->do_determine_type(gogo, &context);
260 // Return true if two expressions refer to the same variable or struct
261 // field. This can only be true when there are no side effects.
263 bool
264 Expression::is_same_variable(Expression* a, Expression* b)
266 if (a->classification() != b->classification())
267 return false;
269 Var_expression* av = a->var_expression();
270 if (av != NULL)
271 return av->named_object() == b->var_expression()->named_object();
273 Field_reference_expression* af = a->field_reference_expression();
274 if (af != NULL)
276 Field_reference_expression* bf = b->field_reference_expression();
277 return (af->field_index() == bf->field_index()
278 && Expression::is_same_variable(af->expr(), bf->expr()));
281 Unary_expression* au = a->unary_expression();
282 if (au != NULL)
284 Unary_expression* bu = b->unary_expression();
285 return (au->op() == OPERATOR_MULT
286 && bu->op() == OPERATOR_MULT
287 && Expression::is_same_variable(au->operand(),
288 bu->operand()));
291 Array_index_expression* aie = a->array_index_expression();
292 if (aie != NULL)
294 Array_index_expression* bie = b->array_index_expression();
295 return (aie->end() == NULL
296 && bie->end() == NULL
297 && Expression::is_same_variable(aie->array(), bie->array())
298 && Expression::is_same_variable(aie->start(), bie->start()));
301 Numeric_constant aval;
302 if (a->numeric_constant_value(&aval))
304 Numeric_constant bval;
305 if (b->numeric_constant_value(&bval))
306 return aval.equals(bval);
309 return false;
312 // Return an expression handling any conversions which must be done during
313 // assignment.
315 Expression*
316 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
317 Expression* rhs, Location location)
319 Type* rhs_type = rhs->type();
320 if (lhs_type->is_error()
321 || rhs_type->is_error()
322 || rhs->is_error_expression())
323 return Expression::make_error(location);
325 bool are_identical = Type::are_identical(lhs_type, rhs_type,
326 (Type::COMPARE_ERRORS
327 | Type::COMPARE_TAGS),
328 NULL);
329 Expression* ret;
330 if (!are_identical && lhs_type->interface_type() != NULL)
332 // Type to interface conversions have been made explicit early.
333 go_assert(rhs_type->interface_type() != NULL);
334 ret = Expression::convert_interface_to_interface(gogo, lhs_type, rhs,
335 false, location);
337 else if (!are_identical && rhs_type->interface_type() != NULL)
338 ret = Expression::convert_interface_to_type(gogo, lhs_type, rhs, location);
339 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
341 // Assigning nil to a slice.
342 Expression* nil = Expression::make_nil(location);
343 Expression* zero = Expression::make_integer_ul(0, NULL, location);
344 ret = Expression::make_slice_value(lhs_type, nil, zero, zero, location);
346 else if (rhs_type->is_nil_type())
347 ret = Expression::make_nil(location);
348 else if (are_identical)
350 if (lhs_type->forwarded() != rhs_type->forwarded())
352 // Different but identical types require an explicit
353 // conversion. This happens with type aliases.
354 return Expression::make_cast(lhs_type, rhs, location);
357 // No conversion is needed.
358 return rhs;
360 else if (lhs_type->points_to() != NULL)
361 ret = Expression::make_unsafe_cast(lhs_type, rhs, location);
362 else if (lhs_type->is_numeric_type())
363 ret = Expression::make_cast(lhs_type, rhs, location);
364 else if ((lhs_type->struct_type() != NULL
365 && rhs_type->struct_type() != NULL)
366 || (lhs_type->array_type() != NULL
367 && rhs_type->array_type() != NULL))
369 // This conversion must be permitted by Go, or we wouldn't have
370 // gotten here.
371 ret = Expression::make_unsafe_cast(lhs_type, rhs, location);
373 else
374 return rhs;
376 Type_context context(lhs_type, false);
377 ret->determine_type(gogo, &context);
378 return ret;
381 // Return an expression for a conversion from a non-interface type to an
382 // interface type. If ON_STACK is true, it can allocate the storage on
383 // stack.
385 Expression*
386 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
387 bool on_stack, Location location)
389 Interface_type* lhs_interface_type = lhs_type->interface_type();
390 bool lhs_is_empty = lhs_interface_type->is_empty();
392 // Since RHS_TYPE is a static type, we can create the interface
393 // method table at compile time.
395 // When setting an interface to nil, we just set both fields to
396 // NULL.
397 Type* rhs_type = rhs->type();
398 if (rhs_type->is_nil_type())
400 Expression* nil = Expression::make_nil(location);
401 return Expression::make_interface_value(lhs_type, nil, nil, location);
404 // This should have been checked already.
405 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
407 go_assert(saw_errors());
408 return Expression::make_error(location);
411 // An interface is a tuple. If LHS_TYPE is an empty interface type,
412 // then the first field is the type descriptor for RHS_TYPE.
413 // Otherwise it is the interface method table for RHS_TYPE.
414 Expression* first_field;
415 if (lhs_is_empty)
416 first_field = Expression::make_type_descriptor(rhs_type, location);
417 else
419 // Build the interface method table for this interface and this
420 // object type: a list of function pointers for each interface
421 // method.
422 Named_type* rhs_named_type = rhs_type->named_type();
423 Struct_type* rhs_struct_type = rhs_type->struct_type();
424 bool is_pointer = false;
425 if (rhs_named_type == NULL && rhs_struct_type == NULL)
427 rhs_named_type = rhs_type->deref()->named_type();
428 rhs_struct_type = rhs_type->deref()->struct_type();
429 is_pointer = true;
431 if (rhs_named_type != NULL)
432 first_field =
433 rhs_named_type->interface_method_table(lhs_interface_type,
434 is_pointer);
435 else if (rhs_struct_type != NULL)
436 first_field =
437 rhs_struct_type->interface_method_table(lhs_interface_type,
438 is_pointer);
439 else
440 first_field = Expression::make_nil(location);
443 Expression* obj;
444 if (rhs_type->is_direct_iface_type())
446 // We are assigning a pointer to the interface; the interface
447 // holds the pointer itself.
448 obj = unpack_direct_iface(rhs, location);
450 else
452 // We are assigning a non-pointer value to the interface; the
453 // interface gets a copy of the value in the heap if it escapes.
455 // An exception is &global if global is notinheap, which is a
456 // pointer value but not a direct-iface type and we can't simply
457 // take its address.
458 bool is_address = (rhs->unary_expression() != NULL
459 && rhs->unary_expression()->op() == OPERATOR_AND);
461 if (rhs->is_constant() && !is_address)
462 obj = Expression::make_unary(OPERATOR_AND, rhs, location);
463 else
465 obj = Expression::make_heap_expression(rhs, location);
466 if (on_stack)
467 obj->heap_expression()->set_allocate_on_stack();
471 return Expression::make_interface_value(lhs_type, first_field, obj, location);
474 // Return an expression for the pointer-typed value of a direct interface
475 // type. Specifically, for single field struct or array, get the single
476 // field, and do this recursively. The reason for this is that we don't
477 // want to assign a struct or an array to a pointer-typed field. The
478 // backend may not like that.
480 Expression*
481 Expression::unpack_direct_iface(Expression* rhs, Location loc)
483 Struct_type* st = rhs->type()->struct_type();
484 if (st != NULL)
486 go_assert(st->field_count() == 1);
487 Expression* field = Expression::make_field_reference(rhs, 0, loc);
488 return unpack_direct_iface(field, loc);
490 Array_type* at = rhs->type()->array_type();
491 if (at != NULL)
493 int64_t len;
494 bool ok = at->int_length(&len);
495 go_assert(ok && len == 1);
496 Type* int_type = Type::lookup_integer_type("int");
497 Expression* index = Expression::make_integer_ul(0, int_type, loc);
498 Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
499 return unpack_direct_iface(elem, loc);
501 return rhs;
504 // The opposite of unpack_direct_iface.
506 Expression*
507 Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
509 if (rhs->type() == t)
510 return rhs;
511 Struct_type* st = t->struct_type();
512 if (st != NULL)
514 Expression_list* vals = new Expression_list();
515 vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
516 return Expression::make_struct_composite_literal(t, vals, loc);
518 Array_type* at = t->array_type();
519 if (at != NULL)
521 Expression_list* vals = new Expression_list();
522 vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
523 return Expression::make_array_composite_literal(t, vals, loc);
525 return Expression::make_unsafe_cast(t, rhs, loc);
528 // Return an expression for the type descriptor of RHS.
530 Expression*
531 Expression::get_interface_type_descriptor(Expression* rhs)
533 go_assert(rhs->type()->interface_type() != NULL);
534 Location location = rhs->location();
536 // The type descriptor is the first field of an empty interface.
537 if (rhs->type()->interface_type()->is_empty())
538 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
539 location);
541 Expression* mtable =
542 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
544 Expression* descriptor =
545 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
546 descriptor = Expression::make_field_reference(descriptor, 0, location);
547 Expression* nil = Expression::make_nil(location);
549 Expression* eq =
550 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
551 return Expression::make_conditional(eq, nil, descriptor, location);
554 // Return an expression for the conversion of an interface type to an
555 // interface type.
557 Expression*
558 Expression::convert_interface_to_interface(Gogo* gogo, Type *lhs_type,
559 Expression* rhs,
560 bool for_type_guard,
561 Location location)
563 if (Type::are_identical(lhs_type, rhs->type(),
564 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
565 NULL))
566 return rhs;
568 Interface_type* lhs_interface_type = lhs_type->interface_type();
569 bool lhs_is_empty = lhs_interface_type->is_empty();
571 // In the general case this requires runtime examination of the type
572 // method table to match it up with the interface methods.
574 // FIXME: If all of the methods in the right hand side interface
575 // also appear in the left hand side interface, then we don't need
576 // to do a runtime check, although we still need to build a new
577 // method table.
579 // We are going to evaluate RHS multiple times.
580 go_assert(rhs->is_multi_eval_safe());
582 // Get the type descriptor for the right hand side. This will be
583 // NULL for a nil interface.
584 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
585 Expression* lhs_type_expr =
586 Expression::make_type_descriptor(lhs_type, location);
588 Expression* first_field;
589 if (for_type_guard)
591 // A type assertion fails when converting a nil interface.
592 first_field = Runtime::make_call(gogo, Runtime::ASSERTITAB, location, 2,
593 lhs_type_expr, rhs_type_expr);
595 else if (lhs_is_empty)
597 // A conversion to an empty interface always succeeds, and the
598 // first field is just the type descriptor of the object.
599 first_field = rhs_type_expr;
601 else
603 // A conversion to a non-empty interface may fail, but unlike a
604 // type assertion converting nil will always succeed.
605 first_field = Runtime::make_call(gogo, Runtime::REQUIREITAB, location, 2,
606 lhs_type_expr, rhs_type_expr);
609 // The second field is simply the object pointer.
610 Expression* obj =
611 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
612 Expression* ret = Expression::make_interface_value(lhs_type, first_field,
613 obj, location);
614 Type_context context(lhs_type, false);
615 ret->determine_type(gogo, &context);
616 return ret;
619 // Return an expression for the conversion of an interface type to a
620 // non-interface type.
622 Expression*
623 Expression::convert_interface_to_type(Gogo* gogo, Type *lhs_type, Expression* rhs,
624 Location location)
626 // We are going to evaluate RHS multiple times.
627 go_assert(rhs->is_multi_eval_safe());
629 // Build an expression to check that the type is valid. It will
630 // panic with an appropriate runtime type error if the type is not
631 // valid.
632 // (lhs_type == rhs_type ? nil /*dummy*/ :
633 // panicdottype(lhs_type, rhs_type, inter_type))
634 // For some Oses, we need to call runtime.eqtype instead of
635 // lhs_type == rhs_type, as we may have unmerged type descriptors
636 // from shared libraries.
637 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
638 location);
639 Expression* rhs_descriptor =
640 Expression::get_interface_type_descriptor(rhs);
642 Type* rhs_type = rhs->type();
643 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
644 location);
646 Expression* cond;
647 if (gogo->need_eqtype()) {
648 cond = Runtime::make_call(gogo, Runtime::EQTYPE, location,
649 2, lhs_type_expr,
650 rhs_descriptor);
651 } else {
652 cond = Expression::make_binary(OPERATOR_EQEQ, lhs_type_expr,
653 rhs_descriptor, location);
656 rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
657 Expression* panic = Runtime::make_call(gogo, Runtime::PANICDOTTYPE, location,
658 3, lhs_type_expr->copy(),
659 rhs_descriptor,
660 rhs_inter_expr);
661 Expression* nil = Expression::make_nil(location);
662 Expression* check = Expression::make_conditional(cond, nil, panic,
663 location);
665 // If the conversion succeeds, pull out the value.
666 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
667 location);
669 // If the value is a direct interface, then it is the value we want.
670 // Otherwise it points to the value.
671 if (lhs_type->is_direct_iface_type())
672 obj = Expression::pack_direct_iface(lhs_type, obj, location);
673 else
675 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
676 location);
677 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
678 location);
680 return Expression::make_compound(check, obj, location);
683 // Convert an expression to its backend representation. This is implemented by
684 // the child class. Not that it is not in general safe to call this multiple
685 // times for a single expression, but that we don't catch such errors.
687 Bexpression*
688 Expression::get_backend(Translate_context* context)
690 // The child may have marked this expression as having an error.
691 if (this->classification_ == EXPRESSION_ERROR)
693 go_assert(saw_errors());
694 return context->backend()->error_expression();
697 return this->do_get_backend(context);
700 // Return a backend expression for VAL.
701 Bexpression*
702 Expression::backend_numeric_constant_expression(Translate_context* context,
703 Numeric_constant* val)
705 Gogo* gogo = context->gogo();
706 Type* type = val->type();
707 if (type == NULL)
708 return gogo->backend()->error_expression();
710 Btype* btype = type->get_backend(gogo);
711 Bexpression* ret;
712 if (type->integer_type() != NULL)
714 mpz_t ival;
715 if (!val->to_int(&ival))
717 go_assert(saw_errors());
718 return gogo->backend()->error_expression();
720 ret = gogo->backend()->integer_constant_expression(btype, ival);
721 mpz_clear(ival);
723 else if (type->float_type() != NULL)
725 mpfr_t fval;
726 if (!val->to_float(&fval))
728 go_assert(saw_errors());
729 return gogo->backend()->error_expression();
731 ret = gogo->backend()->float_constant_expression(btype, fval);
732 mpfr_clear(fval);
734 else if (type->complex_type() != NULL)
736 mpc_t cval;
737 if (!val->to_complex(&cval))
739 go_assert(saw_errors());
740 return gogo->backend()->error_expression();
742 ret = gogo->backend()->complex_constant_expression(btype, cval);
743 mpc_clear(cval);
745 else
746 go_unreachable();
748 return ret;
751 // Insert bounds checks for an index expression. Check that that VAL
752 // >= 0 and that it fits in an int. Then check that VAL OP BOUND is
753 // true. If any condition is false, call one of the CODE runtime
754 // functions, which will panic.
756 void
757 Expression::check_bounds(Gogo* gogo, Expression* val, Operator op,
758 Expression* bound,
759 Runtime::Function code,
760 Runtime::Function code_u,
761 Runtime::Function code_extend,
762 Runtime::Function code_extend_u,
763 Statement_inserter* inserter,
764 Location loc)
766 go_assert(val->is_multi_eval_safe());
767 go_assert(bound->is_multi_eval_safe());
769 Type* int_type = Type::lookup_integer_type("int");
770 int int_type_size = int_type->integer_type()->bits();
772 Type* val_type = val->type();
773 if (val_type->integer_type() == NULL)
775 go_assert(saw_errors());
776 return;
778 int val_type_size = val_type->integer_type()->bits();
779 bool val_is_unsigned = val_type->integer_type()->is_unsigned();
781 // Check that VAL >= 0.
782 Expression* check = NULL;
783 if (!val_is_unsigned)
785 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
786 check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
789 // If VAL's type is larger than int, check that VAL fits in an int.
790 if (val_type_size > int_type_size
791 || (val_type_size == int_type_size
792 && val_is_unsigned))
794 mpz_t one;
795 mpz_init_set_ui(one, 1UL);
797 // maxval = 2^(int_type_size - 1) - 1
798 mpz_t maxval;
799 mpz_init(maxval);
800 mpz_mul_2exp(maxval, one, int_type_size - 1);
801 mpz_sub_ui(maxval, maxval, 1);
802 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
803 mpz_clear(one);
804 mpz_clear(maxval);
806 Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
807 max, loc);
808 if (check == NULL)
809 check = cmp;
810 else
811 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
814 // For the final check we can assume that VAL fits in an int.
815 Expression* ival;
816 if (val_type == int_type)
817 ival = val->copy();
818 else
819 ival = Expression::make_cast(int_type, val->copy(), loc);
821 // BOUND is assumed to fit in an int. Either it comes from len or
822 // cap, or it was checked by an earlier call.
823 Expression* ibound;
824 if (bound->type() == int_type)
825 ibound = bound->copy();
826 else
827 ibound = Expression::make_cast(int_type, bound->copy(), loc);
829 Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
830 if (check == NULL)
831 check = cmp;
832 else
833 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
835 Runtime::Function c;
836 if (val_type_size > int_type_size)
838 if (val_is_unsigned)
839 c = code_extend_u;
840 else
841 c = code_extend;
843 else
845 if (val_is_unsigned)
846 c = code_u;
847 else
848 c = code;
851 Expression* ignore = Expression::make_boolean(true, loc);
852 Expression* crash = Runtime::make_call(gogo, c, loc, 2,
853 val->copy(), bound->copy());
854 Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
855 Statement* s = Statement::make_statement(cond, true);
856 s->determine_types(gogo);
857 inserter->insert(s);
860 void
861 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
863 this->do_dump_expression(ast_dump_context);
866 // Error expressions. This are used to avoid cascading errors.
868 class Error_expression : public Expression
870 public:
871 Error_expression(Location location)
872 : Expression(EXPRESSION_ERROR, location)
875 protected:
876 bool
877 do_is_constant() const
878 { return true; }
880 bool
881 do_is_untyped(Type**) const
882 { return false; }
884 bool
885 do_numeric_constant_value(Numeric_constant*)
886 { return false; }
888 bool
889 do_discarding_value()
890 { return true; }
892 Type*
893 do_type()
894 { return Type::make_error_type(); }
896 void
897 do_determine_type(Gogo*, const Type_context*)
900 Expression*
901 do_copy()
902 { return this; }
904 bool
905 do_is_addressable() const
906 { return true; }
908 Bexpression*
909 do_get_backend(Translate_context* context)
910 { return context->backend()->error_expression(); }
912 void
913 do_dump_expression(Ast_dump_context*) const;
916 // Dump the ast representation for an error expression to a dump context.
918 void
919 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
921 ast_dump_context->ostream() << "_Error_" ;
924 Expression*
925 Expression::make_error(Location location)
927 return new Error_expression(location);
930 // An expression which is really a type. This is used during parsing.
931 // It is an error if these survive after lowering.
933 class Type_expression : public Expression
935 public:
936 Type_expression(Type* type, Location location)
937 : Expression(EXPRESSION_TYPE, location),
938 type_(type)
941 protected:
943 do_traverse(Traverse* traverse)
944 { return Type::traverse(this->type_, traverse); }
946 Type*
947 do_type()
948 { return this->type_; }
950 void
951 do_determine_type(Gogo*, const Type_context*)
954 void
955 do_check_types(Gogo*);
957 Expression*
958 do_copy()
959 { return this; }
961 Bexpression*
962 do_get_backend(Translate_context*);
964 void do_dump_expression(Ast_dump_context*) const;
966 private:
967 // The type which we are representing as an expression.
968 Type* type_;
971 void
972 Type_expression::do_check_types(Gogo*)
974 if (this->type_->is_error())
976 go_assert(saw_errors());
977 this->set_is_error();
981 Bexpression*
982 Type_expression::do_get_backend(Translate_context* context)
984 if (!this->is_error_expression())
985 this->report_error("invalid use of type");
986 return context->backend()->error_expression();
989 void
990 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
992 ast_dump_context->dump_type(this->type_);
995 Expression*
996 Expression::make_type(Type* type, Location location)
998 return new Type_expression(type, location);
1001 // Class Var_expression.
1003 // Lower a variable expression. Here we just make sure that the
1004 // initialization expression of the variable has been lowered. This
1005 // ensures that we will be able to determine the type of the variable
1006 // if necessary.
1008 Expression*
1009 Var_expression::do_lower(Gogo* gogo, Named_object* function,
1010 Statement_inserter* inserter)
1012 if (this->variable_->is_variable())
1014 Variable* var = this->variable_->var_value();
1015 // This is either a local variable or a global variable. A
1016 // reference to a variable which is local to an enclosing
1017 // function will be a reference to a field in a closure.
1018 if (var->is_global())
1020 function = NULL;
1021 inserter = NULL;
1023 var->lower_init_expression(gogo, function, inserter);
1025 return this;
1028 // Return the type of a reference to a variable.
1030 Type*
1031 Var_expression::do_type()
1033 if (this->variable_->is_variable())
1034 return this->variable_->var_value()->type();
1035 else if (this->variable_->is_result_variable())
1036 return this->variable_->result_var_value()->type();
1037 else
1038 go_unreachable();
1041 // Determine the type of a reference to a variable.
1043 void
1044 Var_expression::do_determine_type(Gogo* gogo, const Type_context*)
1046 if (this->variable_->is_variable())
1047 this->variable_->var_value()->determine_type(gogo);
1050 // Something takes the address of this variable. This means that we
1051 // may want to move the variable onto the heap.
1053 void
1054 Var_expression::do_address_taken(bool escapes)
1056 if (!escapes)
1058 if (this->variable_->is_variable())
1059 this->variable_->var_value()->set_non_escaping_address_taken();
1060 else if (this->variable_->is_result_variable())
1061 this->variable_->result_var_value()->set_non_escaping_address_taken();
1062 else
1063 go_unreachable();
1065 else
1067 if (this->variable_->is_variable())
1068 this->variable_->var_value()->set_address_taken();
1069 else if (this->variable_->is_result_variable())
1070 this->variable_->result_var_value()->set_address_taken();
1071 else
1072 go_unreachable();
1075 if (this->variable_->is_variable()
1076 && this->variable_->var_value()->is_in_heap())
1078 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
1079 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1083 // Export a reference to a variable.
1085 void
1086 Var_expression::do_export(Export_function_body* efb) const
1088 Named_object* no = this->variable_;
1089 if (no->is_result_variable() || !no->var_value()->is_global())
1090 efb->write_string(Gogo::unpack_hidden_name(no->name()));
1091 else
1092 Expression::export_name(efb, no);
1095 // Get the backend representation for a reference to a variable.
1097 Bexpression*
1098 Var_expression::do_get_backend(Translate_context* context)
1100 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
1101 context->function());
1102 bool is_in_heap;
1103 Location loc = this->location();
1104 Btype* btype;
1105 Gogo* gogo = context->gogo();
1106 if (this->variable_->is_variable())
1108 is_in_heap = this->variable_->var_value()->is_in_heap();
1109 btype = this->variable_->var_value()->type()->get_backend(gogo);
1111 else if (this->variable_->is_result_variable())
1113 is_in_heap = this->variable_->result_var_value()->is_in_heap();
1114 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
1116 else
1117 go_unreachable();
1119 Bexpression* ret =
1120 context->backend()->var_expression(bvar, loc);
1121 if (is_in_heap)
1122 ret = context->backend()->indirect_expression(btype, ret, true, loc);
1123 return ret;
1126 // Ast dump for variable expression.
1128 void
1129 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1131 ast_dump_context->ostream() << this->variable_->message_name() ;
1134 // Make a reference to a variable in an expression.
1136 Expression*
1137 Expression::make_var_reference(Named_object* var, Location location)
1139 if (var->is_sink())
1140 return Expression::make_sink(location);
1141 if (var->is_redefinition())
1142 return Expression::make_error(location);
1144 // FIXME: Creating a new object for each reference to a variable is
1145 // wasteful.
1146 return new Var_expression(var, location);
1149 // Class Enclosed_var_expression.
1152 Enclosed_var_expression::do_traverse(Traverse*)
1154 return TRAVERSE_CONTINUE;
1157 // Lower the reference to the enclosed variable.
1159 Expression*
1160 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
1161 Statement_inserter* inserter)
1163 gogo->lower_expression(function, inserter, &this->reference_);
1164 return this;
1167 // Flatten the reference to the enclosed variable.
1169 Expression*
1170 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
1171 Statement_inserter* inserter)
1173 gogo->flatten_expression(function, inserter, &this->reference_);
1174 return this;
1177 void
1178 Enclosed_var_expression::do_address_taken(bool escapes)
1180 if (!escapes)
1182 if (this->variable_->is_variable())
1183 this->variable_->var_value()->set_non_escaping_address_taken();
1184 else if (this->variable_->is_result_variable())
1185 this->variable_->result_var_value()->set_non_escaping_address_taken();
1186 else
1187 go_unreachable();
1189 else
1191 if (this->variable_->is_variable())
1192 this->variable_->var_value()->set_address_taken();
1193 else if (this->variable_->is_result_variable())
1194 this->variable_->result_var_value()->set_address_taken();
1195 else
1196 go_unreachable();
1199 if (this->variable_->is_variable()
1200 && this->variable_->var_value()->is_in_heap())
1201 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1204 // Ast dump for enclosed variable expression.
1206 void
1207 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
1209 adc->ostream() << this->variable_->message_name();
1212 // Make a reference to a variable within an enclosing function.
1214 Expression*
1215 Expression::make_enclosing_var_reference(Expression* reference,
1216 Named_object* var, Location location)
1218 return new Enclosed_var_expression(reference, var, location);
1221 // Class Temporary_reference_expression.
1223 // The type.
1225 Type*
1226 Temporary_reference_expression::do_type()
1228 return this->statement_->type();
1231 // Called if something takes the address of this temporary variable.
1232 // We never have to move temporary variables to the heap, but we do
1233 // need to know that they must live in the stack rather than in a
1234 // register.
1236 void
1237 Temporary_reference_expression::do_address_taken(bool)
1239 this->statement_->set_is_address_taken();
1242 // Export a reference to a temporary.
1244 void
1245 Temporary_reference_expression::do_export(Export_function_body* efb) const
1247 unsigned int idx = efb->temporary_index(this->statement_);
1248 char buf[50];
1249 snprintf(buf, sizeof buf, "$t%u", idx);
1250 efb->write_c_string(buf);
1253 // Import a reference to a temporary.
1255 Expression*
1256 Temporary_reference_expression::do_import(Import_function_body* ifb,
1257 Location loc)
1259 std::string id = ifb->read_identifier();
1260 go_assert(id[0] == '$' && id[1] == 't');
1261 const char *p = id.c_str();
1262 char *end;
1263 long idx = strtol(p + 2, &end, 10);
1264 if (*end != '\0' || idx > 0x7fffffff)
1266 if (!ifb->saw_error())
1267 go_error_at(loc,
1268 ("invalid export data for %qs: "
1269 "invalid temporary reference index at %lu"),
1270 ifb->name().c_str(),
1271 static_cast<unsigned long>(ifb->off()));
1272 ifb->set_saw_error();
1273 return Expression::make_error(loc);
1276 Temporary_statement* temp =
1277 ifb->temporary_statement(static_cast<unsigned int>(idx));
1278 if (temp == NULL)
1280 if (!ifb->saw_error())
1281 go_error_at(loc,
1282 ("invalid export data for %qs: "
1283 "undefined temporary reference index at %lu"),
1284 ifb->name().c_str(),
1285 static_cast<unsigned long>(ifb->off()));
1286 ifb->set_saw_error();
1287 return Expression::make_error(loc);
1290 return Expression::make_temporary_reference(temp, loc);
1293 // Get a backend expression referring to the variable.
1295 Bexpression*
1296 Temporary_reference_expression::do_get_backend(Translate_context* context)
1298 Gogo* gogo = context->gogo();
1299 Bvariable* bvar = this->statement_->get_backend_variable(context);
1300 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1302 // The backend can't always represent the same set of recursive types
1303 // that the Go frontend can. In some cases this means that a
1304 // temporary variable won't have the right backend type. Correct
1305 // that here by adding a type cast. We need to use base() to push
1306 // the circularity down one level.
1307 Type* stype = this->statement_->type();
1308 if (!this->is_lvalue_
1309 && stype->points_to() != NULL
1310 && stype->points_to()->is_void_type())
1312 Btype* btype = this->type()->base()->get_backend(gogo);
1313 ret = gogo->backend()->convert_expression(btype, ret, this->location());
1315 return ret;
1318 // Ast dump for temporary reference.
1320 void
1321 Temporary_reference_expression::do_dump_expression(
1322 Ast_dump_context* ast_dump_context) const
1324 ast_dump_context->dump_temp_variable_name(this->statement_);
1327 // Make a reference to a temporary variable.
1329 Temporary_reference_expression*
1330 Expression::make_temporary_reference(Temporary_statement* statement,
1331 Location location)
1333 statement->add_use();
1334 return new Temporary_reference_expression(statement, location);
1337 // Class Set_and_use_temporary_expression.
1339 // Return the type.
1341 Type*
1342 Set_and_use_temporary_expression::do_type()
1344 return this->statement_->type();
1347 // Determine the type of the expression.
1349 void
1350 Set_and_use_temporary_expression::do_determine_type(
1351 Gogo* gogo,
1352 const Type_context* context)
1354 this->expr_->determine_type(gogo, context);
1357 // Take the address.
1359 void
1360 Set_and_use_temporary_expression::do_address_taken(bool)
1362 this->statement_->set_is_address_taken();
1365 // Return the backend representation.
1367 Bexpression*
1368 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1370 Location loc = this->location();
1371 Gogo* gogo = context->gogo();
1372 Bvariable* bvar = this->statement_->get_backend_variable(context);
1373 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1375 Named_object* fn = context->function();
1376 go_assert(fn != NULL);
1377 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1378 Bexpression* bexpr = this->expr_->get_backend(context);
1379 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1380 bexpr, loc);
1381 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1382 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1383 return ret;
1386 // Dump.
1388 void
1389 Set_and_use_temporary_expression::do_dump_expression(
1390 Ast_dump_context* ast_dump_context) const
1392 ast_dump_context->ostream() << '(';
1393 ast_dump_context->dump_temp_variable_name(this->statement_);
1394 ast_dump_context->ostream() << " = ";
1395 this->expr_->dump_expression(ast_dump_context);
1396 ast_dump_context->ostream() << ')';
1399 // Make a set-and-use temporary.
1401 Set_and_use_temporary_expression*
1402 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1403 Expression* expr, Location location)
1405 return new Set_and_use_temporary_expression(statement, expr, location);
1408 // A sink expression--a use of the blank identifier _.
1410 class Sink_expression : public Expression
1412 public:
1413 Sink_expression(Location location)
1414 : Expression(EXPRESSION_SINK, location),
1415 type_(NULL), bvar_(NULL)
1418 protected:
1419 bool
1420 do_discarding_value()
1421 { return true; }
1423 Type*
1424 do_type();
1426 void
1427 do_determine_type(Gogo*, const Type_context*);
1429 Expression*
1430 do_copy()
1431 { return new Sink_expression(this->location()); }
1433 Bexpression*
1434 do_get_backend(Translate_context*);
1436 void
1437 do_dump_expression(Ast_dump_context*) const;
1439 private:
1440 // The type of this sink variable.
1441 Type* type_;
1442 // The temporary variable we generate.
1443 Bvariable* bvar_;
1446 // Return the type of a sink expression.
1448 Type*
1449 Sink_expression::do_type()
1451 if (this->type_ == NULL)
1452 return Type::make_sink_type();
1453 return this->type_;
1456 // Determine the type of a sink expression.
1458 void
1459 Sink_expression::do_determine_type(Gogo*, const Type_context* context)
1461 if (context->type != NULL)
1462 this->type_ = context->type;
1465 // Return a temporary variable for a sink expression. This will
1466 // presumably be a write-only variable which the middle-end will drop.
1468 Bexpression*
1469 Sink_expression::do_get_backend(Translate_context* context)
1471 Location loc = this->location();
1472 Gogo* gogo = context->gogo();
1473 if (this->bvar_ == NULL)
1475 if (this->type_ == NULL || this->type_->is_sink_type())
1477 go_assert(saw_errors());
1478 return gogo->backend()->error_expression();
1481 Named_object* fn = context->function();
1482 go_assert(fn != NULL);
1483 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1484 Btype* bt = this->type_->get_backend(context->gogo());
1485 Bstatement* decl;
1486 this->bvar_ =
1487 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1488 0, loc, &decl);
1489 Bexpression* var_ref =
1490 gogo->backend()->var_expression(this->bvar_, loc);
1491 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1492 return var_ref;
1494 return gogo->backend()->var_expression(this->bvar_, loc);
1497 // Ast dump for sink expression.
1499 void
1500 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1502 ast_dump_context->ostream() << "_" ;
1505 // Make a sink expression.
1507 Expression*
1508 Expression::make_sink(Location location)
1510 return new Sink_expression(location);
1513 // Class Func_expression.
1515 // FIXME: Can a function expression appear in a constant expression?
1516 // The value is unchanging. Initializing a constant to the address of
1517 // a function seems like it could work, though there might be little
1518 // point to it.
1520 // Traversal.
1523 Func_expression::do_traverse(Traverse* traverse)
1525 return (this->closure_ == NULL
1526 ? TRAVERSE_CONTINUE
1527 : Expression::traverse(&this->closure_, traverse));
1530 // Return the type of a function expression.
1532 Type*
1533 Func_expression::do_type()
1535 if (this->function_->is_function())
1536 return this->function_->func_value()->type();
1537 else if (this->function_->is_function_declaration())
1538 return this->function_->func_declaration_value()->type();
1539 else
1540 go_unreachable();
1543 // Get the backend representation for the code of a function expression.
1545 Bexpression*
1546 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1548 Function_type* fntype;
1549 if (no->is_function())
1550 fntype = no->func_value()->type();
1551 else if (no->is_function_declaration())
1552 fntype = no->func_declaration_value()->type();
1553 else
1554 go_unreachable();
1556 // Builtin functions are handled specially by Call_expression. We
1557 // can't take their address.
1558 if (fntype->is_builtin())
1560 go_error_at(loc,
1561 ("invalid use of special built-in function %qs; "
1562 "must be called"),
1563 no->message_name().c_str());
1564 return gogo->backend()->error_expression();
1567 Bfunction* fndecl;
1568 if (no->is_function())
1569 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1570 else if (no->is_function_declaration())
1571 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1572 else
1573 go_unreachable();
1575 return gogo->backend()->function_code_expression(fndecl, loc);
1578 // Get the backend representation for a function expression. This is used when
1579 // we take the address of a function rather than simply calling it. A func
1580 // value is represented as a pointer to a block of memory. The first
1581 // word of that memory is a pointer to the function code. The
1582 // remaining parts of that memory are the addresses of variables that
1583 // the function closes over.
1585 Bexpression*
1586 Func_expression::do_get_backend(Translate_context* context)
1588 // If there is no closure, just use the function descriptor.
1589 if (this->closure_ == NULL)
1591 Gogo* gogo = context->gogo();
1592 Named_object* no = this->function_;
1593 Expression* descriptor;
1594 if (no->is_function())
1595 descriptor = no->func_value()->descriptor(gogo, no);
1596 else if (no->is_function_declaration())
1598 if (no->func_declaration_value()->type()->is_builtin())
1600 go_error_at(this->location(),
1601 ("invalid use of special built-in function %qs; "
1602 "must be called"),
1603 no->message_name().c_str());
1604 return gogo->backend()->error_expression();
1606 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1608 else
1609 go_unreachable();
1611 Bexpression* bdesc = descriptor->get_backend(context);
1612 return gogo->backend()->address_expression(bdesc, this->location());
1615 go_assert(this->function_->func_value()->enclosing() != NULL);
1617 // If there is a closure, then the closure is itself the function
1618 // expression. It is a pointer to a struct whose first field points
1619 // to the function code and whose remaining fields are the addresses
1620 // of the closed-over variables.
1621 Bexpression *bexpr = this->closure_->get_backend(context);
1623 // Introduce a backend type conversion, to account for any differences
1624 // between the argument type (function descriptor, struct with a
1625 // single field) and the closure (struct with multiple fields).
1626 Gogo* gogo = context->gogo();
1627 Btype *btype = this->type()->get_backend(gogo);
1628 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1631 // The cost of inlining a function reference.
1634 Func_expression::do_inlining_cost() const
1636 // FIXME: We don't inline references to nested functions.
1637 if (this->closure_ != NULL)
1638 return 0x100000;
1639 if (this->function_->is_function()
1640 && this->function_->func_value()->enclosing() != NULL)
1641 return 0x100000;
1643 return 1;
1646 // Export a reference to a function.
1648 void
1649 Func_expression::do_export(Export_function_body* efb) const
1651 Expression::export_name(efb, this->function_);
1654 // Ast dump for function.
1656 void
1657 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1659 ast_dump_context->ostream() << this->function_->name();
1660 if (this->closure_ != NULL)
1662 ast_dump_context->ostream() << " {closure = ";
1663 this->closure_->dump_expression(ast_dump_context);
1664 ast_dump_context->ostream() << "}";
1668 // Make a reference to a function in an expression.
1670 Expression*
1671 Expression::make_func_reference(Named_object* function, Expression* closure,
1672 Location location)
1674 Func_expression* fe = new Func_expression(function, closure, location);
1676 // Detect references to builtin functions and set the runtime code if
1677 // appropriate.
1678 if (function->is_function_declaration())
1679 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1680 return fe;
1683 // Class Func_descriptor_expression.
1685 // Constructor.
1687 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1688 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1689 fn_(fn), dvar_(NULL)
1691 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1694 // Traversal.
1697 Func_descriptor_expression::do_traverse(Traverse*)
1699 return TRAVERSE_CONTINUE;
1702 // All function descriptors have the same type.
1704 Type* Func_descriptor_expression::descriptor_type;
1706 void
1707 Func_descriptor_expression::make_func_descriptor_type()
1709 if (Func_descriptor_expression::descriptor_type != NULL)
1710 return;
1711 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1712 Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1713 Func_descriptor_expression::descriptor_type =
1714 Type::make_builtin_named_type("functionDescriptor", struct_type);
1717 Type*
1718 Func_descriptor_expression::do_type()
1720 Func_descriptor_expression::make_func_descriptor_type();
1721 return Func_descriptor_expression::descriptor_type;
1724 // The backend representation for a function descriptor.
1726 Bexpression*
1727 Func_descriptor_expression::do_get_backend(Translate_context* context)
1729 Named_object* no = this->fn_;
1730 Location loc = no->location();
1731 if (this->dvar_ != NULL)
1732 return context->backend()->var_expression(this->dvar_, loc);
1734 Gogo* gogo = context->gogo();
1735 Backend_name bname;
1736 gogo->function_descriptor_backend_name(no, &bname);
1737 bool is_descriptor = false;
1738 if (no->is_function_declaration()
1739 && !no->func_declaration_value()->asm_name().empty()
1740 && Linemap::is_predeclared_location(no->location()))
1741 is_descriptor = true;
1743 // The runtime package implements some functions defined in the
1744 // syscall package. Let the syscall package define the descriptor
1745 // in this case.
1746 if (gogo->compiling_runtime()
1747 && gogo->package_name() == "runtime"
1748 && no->is_function()
1749 && !no->func_value()->asm_name().empty()
1750 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1751 is_descriptor = true;
1753 Btype* btype = this->type()->get_backend(gogo);
1755 Bvariable* bvar;
1756 if (no->package() != NULL || is_descriptor)
1757 bvar =
1758 context->backend()->immutable_struct_reference(bname.name(),
1759 bname.optional_asm_name(),
1760 btype, loc);
1761 else
1763 Location bloc = Linemap::predeclared_location();
1765 // The runtime package has hash/equality functions that are
1766 // referenced by type descriptors outside of the runtime, so the
1767 // function descriptors must be visible even though they are not
1768 // exported.
1769 bool is_exported_runtime = false;
1770 if (gogo->compiling_runtime()
1771 && gogo->package_name() == "runtime"
1772 && (no->name().find("hash") != std::string::npos
1773 || no->name().find("equal") != std::string::npos))
1774 is_exported_runtime = true;
1776 bool is_hidden = ((no->is_function()
1777 && no->func_value()->enclosing() != NULL)
1778 || (Gogo::is_hidden_name(no->name())
1779 && !is_exported_runtime)
1780 || Gogo::is_thunk(no));
1782 if (no->is_function() && no->func_value()->is_referenced_by_inline())
1783 is_hidden = false;
1785 unsigned int flags = 0;
1786 if (is_hidden)
1787 flags |= Backend::variable_is_hidden;
1788 bvar = context->backend()->immutable_struct(bname.name(),
1789 bname.optional_asm_name(),
1790 flags, btype, bloc);
1791 Expression_list* vals = new Expression_list();
1792 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1793 Expression* init =
1794 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1795 Translate_context bcontext(gogo, NULL, NULL, NULL);
1796 bcontext.set_is_const();
1797 Bexpression* binit = init->get_backend(&bcontext);
1798 context->backend()->immutable_struct_set_init(bvar, bname.name(),
1799 flags, btype, bloc, binit);
1802 this->dvar_ = bvar;
1803 return gogo->backend()->var_expression(bvar, loc);
1806 // Print a function descriptor expression.
1808 void
1809 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1811 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1814 // Make a function descriptor expression.
1816 Func_descriptor_expression*
1817 Expression::make_func_descriptor(Named_object* fn)
1819 return new Func_descriptor_expression(fn);
1822 // Make the function descriptor type, so that it can be converted.
1824 void
1825 Expression::make_func_descriptor_type()
1827 Func_descriptor_expression::make_func_descriptor_type();
1830 // A reference to just the code of a function.
1832 class Func_code_reference_expression : public Expression
1834 public:
1835 Func_code_reference_expression(Named_object* function, Location location)
1836 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1837 function_(function)
1840 protected:
1842 do_traverse(Traverse*)
1843 { return TRAVERSE_CONTINUE; }
1845 bool
1846 do_is_static_initializer() const
1847 { return true; }
1849 Type*
1850 do_type()
1851 { return Type::make_pointer_type(Type::make_void_type()); }
1853 void
1854 do_determine_type(Gogo*, const Type_context*)
1857 Expression*
1858 do_copy()
1860 return Expression::make_func_code_reference(this->function_,
1861 this->location());
1864 Bexpression*
1865 do_get_backend(Translate_context*);
1867 void
1868 do_dump_expression(Ast_dump_context* context) const
1869 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1871 private:
1872 // The function.
1873 Named_object* function_;
1876 // Get the backend representation for a reference to function code.
1878 Bexpression*
1879 Func_code_reference_expression::do_get_backend(Translate_context* context)
1881 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1882 this->location());
1885 // Make a reference to the code of a function.
1887 Expression*
1888 Expression::make_func_code_reference(Named_object* function, Location location)
1890 return new Func_code_reference_expression(function, location);
1893 // Class Unknown_expression.
1895 // Return the name of an unknown expression.
1897 const std::string&
1898 Unknown_expression::name() const
1900 return this->named_object_->name();
1903 // Set the iota value if this could be a reference to iota.
1905 void
1906 Unknown_expression::set_iota_value(int iota_value)
1908 this->iota_value_ = iota_value;
1909 this->is_iota_ = true;
1912 // Traversal.
1915 Unknown_expression::do_traverse(Traverse* traverse)
1917 if (this->lowered_ != NULL)
1919 if (Expression::traverse(&this->lowered_, traverse) == TRAVERSE_EXIT)
1920 return TRAVERSE_EXIT;
1922 return TRAVERSE_CONTINUE;
1925 // Determine the type of a reference to an unknown name. At this
1926 // point we have to figure out what the name refers to.
1928 void
1929 Unknown_expression::do_determine_type(Gogo* gogo, const Type_context* context)
1931 if (this->is_error_expression())
1932 return;
1934 if (this->lowered_ != NULL)
1936 this->lowered_->determine_type(gogo, context);
1937 return;
1940 Location loc = this->location();
1942 Named_object* no = this->named_object_;
1943 if (no->is_unknown())
1945 Named_object* real = no->unknown_value()->real_named_object();
1946 if (real == NULL)
1948 if (!this->no_error_message_)
1949 go_error_at(loc, "reference to undefined name %qs",
1950 no->message_name().c_str());
1951 this->set_is_error();
1952 return;
1954 no = real;
1955 this->named_object_ = real;
1958 switch (no->classification())
1960 case Named_object::NAMED_OBJECT_TYPE:
1961 this->lowered_ = Expression::make_type(no->type_value(), loc);
1962 break;
1963 case Named_object::NAMED_OBJECT_FUNC:
1964 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1965 this->lowered_ = Expression::make_func_reference(no, NULL, loc);
1966 break;
1967 case Named_object::NAMED_OBJECT_CONST:
1968 this->lowered_ = Expression::make_const_reference(no, loc);
1969 this->lowered_->determine_type(gogo, context);
1970 if (this->is_iota_)
1971 this->lowered_->const_expression()->set_iota_value(this->iota_value_);
1972 break;
1973 case Named_object::NAMED_OBJECT_VAR:
1974 this->lowered_ = Expression::make_var_reference(no, loc);
1975 no->var_value()->set_is_used();
1976 this->lowered_->determine_type(gogo, context);
1977 break;
1978 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1979 if (!this->no_error_message_)
1980 go_error_at(this->location(), "reference to undefined type %qs",
1981 no->message_name().c_str());
1982 this->set_is_error();
1983 break;
1984 case Named_object::NAMED_OBJECT_PACKAGE:
1985 if (!this->no_error_message_)
1986 this->report_error(_("unexpected reference to package"));
1987 this->set_is_error();
1988 break;
1989 default:
1990 go_unreachable();
1994 Type*
1995 Unknown_expression::do_type()
1997 if (this->is_error_expression())
1998 return Type::make_error_type();
1999 go_assert(this->lowered_ != NULL);
2000 return this->lowered_->type();
2003 bool
2004 Unknown_expression::do_is_constant() const
2006 if (this->is_error_expression())
2007 return true;
2008 if (this->lowered_ != NULL)
2009 return this->lowered_->is_constant();
2011 // This can be called before do_determine_types by
2012 // Binary_expression::do_determine_type, which needs to know which
2013 // values are constant before it works out the appropriate
2014 // Type_context to pass down.
2015 Named_object* no = this->named_object_;
2016 if (no->is_unknown())
2018 no = no->unknown_value()->real_named_object();
2019 if (no == NULL)
2020 return true;
2022 return no->is_const();
2025 bool
2026 Unknown_expression::do_is_untyped(Type** ptype) const
2028 if (this->is_error_expression())
2029 return false;
2030 if (this->lowered_ != NULL)
2031 return this->lowered_->is_untyped(ptype);
2033 Named_object* no = this->named_object_;
2034 if (no->is_unknown())
2036 no = no->unknown_value()->real_named_object();
2037 if (no == NULL)
2038 return false;
2041 if (!no->is_const())
2042 return false;
2043 Type* t = no->const_value()->type();
2044 if (t != NULL)
2045 return Expression::is_untyped_type(t, ptype);
2046 return no->const_value()->expr()->is_untyped(ptype);
2049 bool
2050 Unknown_expression::do_numeric_constant_value(Numeric_constant* nc)
2052 if (this->is_error_expression())
2053 return false;
2054 if (this->lowered_ != NULL)
2055 return this->lowered_->numeric_constant_value(nc);
2057 // This can be called before the determine_types pass.
2058 Named_object* no = this->named_object_;
2059 if (no->is_unknown())
2061 no = no->unknown_value()->real_named_object();
2062 if (no == NULL)
2063 return false;
2065 if (!no->is_const())
2066 return false;
2067 return no->const_value()->expr()->numeric_constant_value(nc);
2070 bool
2071 Unknown_expression::do_string_constant_value(std::string* val)
2073 if (this->is_error_expression())
2074 return false;
2075 go_assert(this->lowered_ != NULL);
2076 return this->lowered_->string_constant_value(val);
2079 bool
2080 Unknown_expression::do_boolean_constant_value(bool* val)
2082 if (this->is_error_expression())
2083 return false;
2084 go_assert(this->lowered_ != NULL);
2085 return this->lowered_->boolean_constant_value(val);
2088 bool
2089 Unknown_expression::do_is_addressable() const
2091 if (this->is_error_expression())
2092 return true;
2093 go_assert(this->lowered_ != NULL);
2094 return this->lowered_->is_addressable();
2097 // Lower a reference to an unknown name.
2099 Expression*
2100 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*)
2102 if (this->is_error_expression())
2103 return Expression::make_error(this->location());
2104 go_assert(this->lowered_ != NULL);
2105 return this->lowered_;
2108 // Dump the ast representation for an unknown expression to a dump context.
2110 void
2111 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2113 if (this->lowered_ != NULL)
2114 this->lowered_->dump_expression(ast_dump_context);
2115 else
2116 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
2117 << ")";
2120 // Make a reference to an unknown name.
2122 Unknown_expression*
2123 Expression::make_unknown_reference(Named_object* no, Location location)
2125 return new Unknown_expression(no, location);
2128 // Start exporting a type conversion for a constant, if needed. This
2129 // returns whether we need to export a closing parenthesis.
2131 bool
2132 Expression::export_constant_type(Export_function_body* efb, Type* type)
2134 if (type == NULL
2135 || type->is_abstract()
2136 || type == efb->type_context())
2137 return false;
2138 efb->write_c_string("$convert(");
2139 efb->write_type(type);
2140 efb->write_c_string(", ");
2141 return true;
2144 // Finish a type conversion for a constant.
2146 void
2147 Expression::finish_export_constant_type(Export_function_body* efb, bool needed)
2149 if (needed)
2150 efb->write_c_string(")");
2153 // A boolean expression.
2155 class Boolean_expression : public Expression
2157 public:
2158 Boolean_expression(bool val, Location location)
2159 : Expression(EXPRESSION_BOOLEAN, location),
2160 val_(val), type_(NULL)
2163 static Expression*
2164 do_import(Import_expression*, Location);
2166 protected:
2168 do_traverse(Traverse*);
2170 bool
2171 do_is_constant() const
2172 { return true; }
2174 bool
2175 do_is_untyped(Type**) const;
2177 bool
2178 do_is_zero_value() const
2179 { return this->val_ == false; }
2181 bool
2182 do_boolean_constant_value(bool* val)
2184 *val = this->val_;
2185 return true;
2188 bool
2189 do_is_static_initializer() const
2190 { return true; }
2192 Type*
2193 do_type();
2195 void
2196 do_determine_type(Gogo*, const Type_context*);
2198 Expression*
2199 do_copy()
2200 { return this; }
2202 Bexpression*
2203 do_get_backend(Translate_context* context)
2204 { return context->backend()->boolean_constant_expression(this->val_); }
2207 do_inlining_cost() const
2208 { return 1; }
2210 void
2211 do_export(Export_function_body* efb) const;
2213 void
2214 do_dump_expression(Ast_dump_context* ast_dump_context) const
2215 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
2217 private:
2218 // The constant.
2219 bool val_;
2220 // The type as determined by context.
2221 Type* type_;
2224 // Traverse a boolean expression. We just need to traverse the type
2225 // if there is one.
2228 Boolean_expression::do_traverse(Traverse* traverse)
2230 if (this->type_ != NULL)
2231 return Type::traverse(this->type_, traverse);
2232 return TRAVERSE_CONTINUE;
2235 bool
2236 Boolean_expression::do_is_untyped(Type** ptype) const
2238 if (this->type_ != NULL)
2239 return Expression::is_untyped_type(this->type_, ptype);
2240 *ptype = Type::make_boolean_type();
2241 return true;
2244 // Get the type.
2246 Type*
2247 Boolean_expression::do_type()
2249 if (this->type_ == NULL)
2250 this->type_ = Type::make_boolean_type();
2251 return this->type_;
2254 // Set the type from the context.
2256 void
2257 Boolean_expression::do_determine_type(Gogo*, const Type_context* context)
2259 if (this->type_ != NULL && !this->type_->is_abstract())
2261 else if (context->type != NULL && context->type->is_boolean_type())
2262 this->type_ = context->type;
2263 else if (!context->may_be_abstract)
2264 this->type_ = Type::lookup_bool_type();
2267 // Export a boolean constant.
2269 void
2270 Boolean_expression::do_export(Export_function_body* efb) const
2272 bool exported_type = Expression::export_constant_type(efb, this->type_);
2273 efb->write_c_string(this->val_ ? "$true" : "$false");
2274 Expression::finish_export_constant_type(efb, exported_type);
2277 // Import a boolean constant.
2279 Expression*
2280 Boolean_expression::do_import(Import_expression* imp, Location loc)
2282 if (imp->version() >= EXPORT_FORMAT_V3)
2283 imp->require_c_string("$");
2284 if (imp->peek_char() == 't')
2286 imp->require_c_string("true");
2287 return Expression::make_boolean(true, loc);
2289 else
2291 imp->require_c_string("false");
2292 return Expression::make_boolean(false, loc);
2296 // Make a boolean expression.
2298 Expression*
2299 Expression::make_boolean(bool val, Location location)
2301 return new Boolean_expression(val, location);
2304 // Class String_expression.
2306 // Traverse a string expression. We just need to traverse the type
2307 // if there is one.
2310 String_expression::do_traverse(Traverse* traverse)
2312 if (this->type_ != NULL)
2313 return Type::traverse(this->type_, traverse);
2314 return TRAVERSE_CONTINUE;
2317 bool
2318 String_expression::do_is_untyped(Type** ptype) const
2320 if (this->type_ != NULL)
2321 return Expression::is_untyped_type(this->type_, ptype);
2322 *ptype = Type::make_string_type();
2323 return true;
2326 // Get the type.
2328 Type*
2329 String_expression::do_type()
2331 if (this->type_ == NULL)
2332 this->type_ = Type::make_string_type();
2333 return this->type_;
2336 // Set the type from the context.
2338 void
2339 String_expression::do_determine_type(Gogo*, const Type_context* context)
2341 if (this->type_ != NULL && !this->type_->is_abstract())
2343 else if (context->type != NULL && context->type->is_string_type())
2344 this->type_ = context->type;
2345 else if (!context->may_be_abstract)
2346 this->type_ = Type::lookup_string_type();
2349 // Build a string constant.
2351 Bexpression*
2352 String_expression::do_get_backend(Translate_context* context)
2354 Gogo* gogo = context->gogo();
2355 Btype* btype = Type::make_string_type()->get_backend(gogo);
2357 Location loc = this->location();
2358 std::vector<Bexpression*> init(2);
2360 if (this->val_.size() == 0)
2361 init[0] = gogo->backend()->nil_pointer_expression();
2362 else
2364 Bexpression* str_cst =
2365 gogo->backend()->string_constant_expression(this->val_);
2366 init[0] = gogo->backend()->address_expression(str_cst, loc);
2369 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
2370 mpz_t lenval;
2371 mpz_init_set_ui(lenval, this->val_.length());
2372 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
2373 mpz_clear(lenval);
2375 return gogo->backend()->constructor_expression(btype, init, loc);
2378 // Write string literal to string dump.
2380 void
2381 String_expression::export_string(String_dump* exp,
2382 const String_expression* str)
2384 std::string s;
2385 s.reserve(str->val_.length() * 4 + 2);
2386 s += '"';
2387 for (std::string::const_iterator p = str->val_.begin();
2388 p != str->val_.end();
2389 ++p)
2391 if (*p == '\\' || *p == '"')
2393 s += '\\';
2394 s += *p;
2396 else if (*p >= 0x20 && *p < 0x7f)
2397 s += *p;
2398 else if (*p == '\n')
2399 s += "\\n";
2400 else if (*p == '\t')
2401 s += "\\t";
2402 else
2404 s += "\\x";
2405 unsigned char c = *p;
2406 unsigned int dig = c >> 4;
2407 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2408 dig = c & 0xf;
2409 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2412 s += '"';
2413 exp->write_string(s);
2416 // Export a string expression.
2418 void
2419 String_expression::do_export(Export_function_body* efb) const
2421 bool exported_type = Expression::export_constant_type(efb, this->type_);
2422 String_expression::export_string(efb, this);
2423 Expression::finish_export_constant_type(efb, exported_type);
2426 // Import a string expression.
2428 Expression*
2429 String_expression::do_import(Import_expression* imp, Location loc)
2431 imp->require_c_string("\"");
2432 std::string val;
2433 while (true)
2435 int c = imp->get_char();
2436 if (c == '"' || c == -1)
2437 break;
2438 if (c != '\\')
2439 val += static_cast<char>(c);
2440 else
2442 c = imp->get_char();
2443 if (c == '\\' || c == '"')
2444 val += static_cast<char>(c);
2445 else if (c == 'n')
2446 val += '\n';
2447 else if (c == 't')
2448 val += '\t';
2449 else if (c == 'x')
2451 c = imp->get_char();
2452 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2453 c = imp->get_char();
2454 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2455 char v = (vh << 4) | vl;
2456 val += v;
2458 else
2460 go_error_at(imp->location(), "bad string constant");
2461 return Expression::make_error(loc);
2465 return Expression::make_string(val, loc);
2468 // Ast dump for string expression.
2470 void
2471 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2473 String_expression::export_string(ast_dump_context, this);
2476 // Make a string expression with abstract string type (common case).
2478 Expression*
2479 Expression::make_string(const std::string& val, Location location)
2481 return new String_expression(val, NULL, location);
2484 // Make a string expression with a specific string type.
2486 Expression*
2487 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2489 return new String_expression(val, type, location);
2492 // An expression that evaluates to some characteristic of a string.
2493 // This is used when indexing, bound-checking, or nil checking a string.
2495 class String_info_expression : public Expression
2497 public:
2498 String_info_expression(Expression* string, String_info string_info,
2499 Location location)
2500 : Expression(EXPRESSION_STRING_INFO, location),
2501 string_(string), string_info_(string_info)
2504 protected:
2505 Type*
2506 do_type();
2508 void
2509 do_determine_type(Gogo*, const Type_context*)
2512 Expression*
2513 do_copy()
2515 return new String_info_expression(this->string_->copy(), this->string_info_,
2516 this->location());
2519 Bexpression*
2520 do_get_backend(Translate_context* context);
2522 void
2523 do_dump_expression(Ast_dump_context*) const;
2525 void
2526 do_issue_nil_check()
2527 { this->string_->issue_nil_check(); }
2529 private:
2530 // The string for which we are getting information.
2531 Expression* string_;
2532 // What information we want.
2533 String_info string_info_;
2536 // Return the type of the string info.
2538 Type*
2539 String_info_expression::do_type()
2541 switch (this->string_info_)
2543 case STRING_INFO_DATA:
2545 Type* byte_type = Type::lookup_integer_type("uint8");
2546 return Type::make_pointer_type(byte_type);
2548 case STRING_INFO_LENGTH:
2549 return Type::lookup_integer_type("int");
2550 default:
2551 go_unreachable();
2555 // Return string information in GENERIC.
2557 Bexpression*
2558 String_info_expression::do_get_backend(Translate_context* context)
2560 Gogo* gogo = context->gogo();
2562 Bexpression* bstring = this->string_->get_backend(context);
2563 switch (this->string_info_)
2565 case STRING_INFO_DATA:
2566 case STRING_INFO_LENGTH:
2567 return gogo->backend()->struct_field_expression(bstring,
2568 this->string_info_,
2569 this->location());
2570 break;
2571 default:
2572 go_unreachable();
2576 // Dump ast representation for a type info expression.
2578 void
2579 String_info_expression::do_dump_expression(
2580 Ast_dump_context* ast_dump_context) const
2582 ast_dump_context->ostream() << "stringinfo(";
2583 this->string_->dump_expression(ast_dump_context);
2584 ast_dump_context->ostream() << ",";
2585 ast_dump_context->ostream() <<
2586 (this->string_info_ == STRING_INFO_DATA ? "data"
2587 : this->string_info_ == STRING_INFO_LENGTH ? "length"
2588 : "unknown");
2589 ast_dump_context->ostream() << ")";
2592 // Make a string info expression.
2594 Expression*
2595 Expression::make_string_info(Expression* string, String_info string_info,
2596 Location location)
2598 return new String_info_expression(string, string_info, location);
2601 // An expression that represents an string value: a struct with value pointer
2602 // and length fields.
2604 class String_value_expression : public Expression
2606 public:
2607 String_value_expression(Expression* valptr, Expression* len, Location location)
2608 : Expression(EXPRESSION_STRING_VALUE, location),
2609 valptr_(valptr), len_(len)
2612 protected:
2614 do_traverse(Traverse*);
2616 Type*
2617 do_type()
2618 { return Type::make_string_type(); }
2620 void
2621 do_determine_type(Gogo*, const Type_context*)
2622 { go_unreachable(); }
2624 Expression*
2625 do_copy()
2627 return new String_value_expression(this->valptr_->copy(),
2628 this->len_->copy(),
2629 this->location());
2632 Bexpression*
2633 do_get_backend(Translate_context* context);
2635 void
2636 do_dump_expression(Ast_dump_context*) const;
2638 private:
2639 // The value pointer.
2640 Expression* valptr_;
2641 // The length.
2642 Expression* len_;
2646 String_value_expression::do_traverse(Traverse* traverse)
2648 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2649 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2650 return TRAVERSE_EXIT;
2651 return TRAVERSE_CONTINUE;
2654 Bexpression*
2655 String_value_expression::do_get_backend(Translate_context* context)
2657 std::vector<Bexpression*> vals(2);
2658 vals[0] = this->valptr_->get_backend(context);
2659 vals[1] = this->len_->get_backend(context);
2661 Gogo* gogo = context->gogo();
2662 Btype* btype = Type::make_string_type()->get_backend(gogo);
2663 return gogo->backend()->constructor_expression(btype, vals, this->location());
2666 void
2667 String_value_expression::do_dump_expression(
2668 Ast_dump_context* ast_dump_context) const
2670 ast_dump_context->ostream() << "stringvalue(";
2671 ast_dump_context->ostream() << "value: ";
2672 this->valptr_->dump_expression(ast_dump_context);
2673 ast_dump_context->ostream() << ", length: ";
2674 this->len_->dump_expression(ast_dump_context);
2675 ast_dump_context->ostream() << ")";
2678 Expression*
2679 Expression::make_string_value(Expression* valptr, Expression* len,
2680 Location location)
2682 return new String_value_expression(valptr, len, location);
2685 // Make an integer expression.
2687 class Integer_expression : public Expression
2689 public:
2690 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2691 Location location)
2692 : Expression(EXPRESSION_INTEGER, location),
2693 type_(type), is_character_constant_(is_character_constant)
2694 { mpz_init_set(this->val_, *val); }
2696 static Expression*
2697 do_import(Import_expression*, Location);
2699 // Write VAL to string dump.
2700 static void
2701 export_integer(String_dump* exp, const mpz_t val);
2703 // Write VAL to dump context.
2704 static void
2705 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2707 protected:
2709 do_traverse(Traverse*);
2711 bool
2712 do_is_constant() const
2713 { return true; }
2715 bool
2716 do_is_untyped(Type**) const;
2718 bool
2719 do_is_zero_value() const
2720 { return mpz_sgn(this->val_) == 0; }
2722 bool
2723 do_is_static_initializer() const
2724 { return true; }
2726 bool
2727 do_numeric_constant_value(Numeric_constant* nc);
2729 Type*
2730 do_type();
2732 void
2733 do_determine_type(Gogo*, const Type_context* context);
2735 void
2736 do_check_types(Gogo*);
2738 Bexpression*
2739 do_get_backend(Translate_context*);
2741 Expression*
2742 do_copy()
2744 if (this->is_character_constant_)
2745 return Expression::make_character(&this->val_,
2746 (this->type_ == NULL
2747 ? NULL
2748 : this->type_->copy_expressions()),
2749 this->location());
2750 else
2751 return Expression::make_integer_z(&this->val_,
2752 (this->type_ == NULL
2753 ? NULL
2754 : this->type_->copy_expressions()),
2755 this->location());
2759 do_inlining_cost() const
2760 { return 1; }
2762 void
2763 do_export(Export_function_body*) const;
2765 void
2766 do_dump_expression(Ast_dump_context*) const;
2768 private:
2769 // The integer value.
2770 mpz_t val_;
2771 // The type so far.
2772 Type* type_;
2773 // Whether this is a character constant.
2774 bool is_character_constant_;
2777 // Traverse an integer expression. We just need to traverse the type
2778 // if there is one.
2781 Integer_expression::do_traverse(Traverse* traverse)
2783 if (this->type_ != NULL)
2784 return Type::traverse(this->type_, traverse);
2785 return TRAVERSE_CONTINUE;
2788 // Return a numeric constant for this expression. We have to mark
2789 // this as a character when appropriate.
2791 bool
2792 Integer_expression::do_numeric_constant_value(Numeric_constant* nc)
2794 if (this->is_character_constant_)
2795 nc->set_rune(this->type_, this->val_);
2796 else
2797 nc->set_int(this->type_, this->val_);
2798 return true;
2801 bool
2802 Integer_expression::do_is_untyped(Type** ptype) const
2804 if (this->type_ != NULL)
2805 return Expression::is_untyped_type(this->type_, ptype);
2806 if (this->is_character_constant_)
2807 *ptype = Type::make_abstract_character_type();
2808 else
2809 *ptype = Type::make_abstract_integer_type();
2810 return true;
2813 // Return the current type. If we haven't set the type yet, we return
2814 // an abstract integer type.
2816 Type*
2817 Integer_expression::do_type()
2819 if (this->type_ == NULL)
2821 if (this->is_character_constant_)
2822 this->type_ = Type::make_abstract_character_type();
2823 else
2824 this->type_ = Type::make_abstract_integer_type();
2826 return this->type_;
2829 // Set the type of the integer value. Here we may switch from an
2830 // abstract type to a real type.
2832 void
2833 Integer_expression::do_determine_type(Gogo*, const Type_context* context)
2835 if (this->type_ != NULL && !this->type_->is_abstract())
2837 else if (context->type != NULL && context->type->is_numeric_type())
2838 this->type_ = context->type;
2839 else if (!context->may_be_abstract)
2841 if (this->is_character_constant_)
2842 this->type_ = Type::lookup_integer_type("int32");
2843 else
2844 this->type_ = Type::lookup_integer_type("int");
2848 // Check the type of an integer constant.
2850 void
2851 Integer_expression::do_check_types(Gogo*)
2853 Type* type = this->type_;
2854 if (type == NULL)
2855 return;
2856 Numeric_constant nc;
2857 if (this->is_character_constant_)
2858 nc.set_rune(NULL, this->val_);
2859 else
2860 nc.set_int(NULL, this->val_);
2861 if (!nc.set_type(type, true, this->location()))
2862 this->set_is_error();
2865 // Get the backend representation for an integer constant.
2867 Bexpression*
2868 Integer_expression::do_get_backend(Translate_context* context)
2870 if (this->is_error_expression()
2871 || (this->type_ != NULL && this->type_->is_error_type()))
2873 go_assert(saw_errors());
2874 return context->gogo()->backend()->error_expression();
2877 Type* resolved_type = NULL;
2878 if (this->type_ != NULL && !this->type_->is_abstract())
2879 resolved_type = this->type_;
2880 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2882 // We are converting to an abstract floating point type.
2883 resolved_type = Type::lookup_float_type("float64");
2885 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2887 // We are converting to an abstract complex type.
2888 resolved_type = Type::lookup_complex_type("complex128");
2890 else
2892 // If we still have an abstract type here, then this is being
2893 // used in a constant expression which didn't get reduced for
2894 // some reason. Use a type which will fit the value. We use <,
2895 // not <=, because we need an extra bit for the sign bit.
2896 int bits = mpz_sizeinbase(this->val_, 2);
2897 Type* int_type = Type::lookup_integer_type("int");
2898 if (bits < int_type->integer_type()->bits())
2899 resolved_type = int_type;
2900 else if (bits < 64)
2901 resolved_type = Type::lookup_integer_type("int64");
2902 else
2904 if (!saw_errors())
2905 go_error_at(this->location(), "integer constant overflow");
2906 return context->gogo()->backend()->error_expression();
2909 Numeric_constant nc;
2910 nc.set_int(resolved_type, this->val_);
2911 return Expression::backend_numeric_constant_expression(context, &nc);
2914 // Write VAL to export data.
2916 void
2917 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2919 char* s = mpz_get_str(NULL, 10, val);
2920 exp->write_c_string(s);
2921 free(s);
2924 // Export an integer in a constant expression.
2926 void
2927 Integer_expression::do_export(Export_function_body* efb) const
2929 bool exported_type = Expression::export_constant_type(efb, this->type_);
2931 Integer_expression::export_integer(efb, this->val_);
2932 if (this->is_character_constant_)
2933 efb->write_c_string("'");
2934 // A trailing space lets us reliably identify the end of the number.
2935 efb->write_c_string(" ");
2937 Expression::finish_export_constant_type(efb, exported_type);
2940 // Import an integer, floating point, or complex value. This handles
2941 // all these types because they all start with digits.
2943 Expression*
2944 Integer_expression::do_import(Import_expression* imp, Location loc)
2946 std::string num = imp->read_identifier();
2947 imp->require_c_string(" ");
2948 if (!num.empty() && num[num.length() - 1] == 'i')
2950 mpfr_t real;
2951 size_t plus_pos = num.find('+', 1);
2952 size_t minus_pos = num.find('-', 1);
2953 size_t pos;
2954 if (plus_pos == std::string::npos)
2955 pos = minus_pos;
2956 else if (minus_pos == std::string::npos)
2957 pos = plus_pos;
2958 else
2960 go_error_at(imp->location(), "bad number in import data: %qs",
2961 num.c_str());
2962 return Expression::make_error(loc);
2964 if (pos == std::string::npos)
2965 mpfr_init_set_ui(real, 0, MPFR_RNDN);
2966 else
2968 std::string real_str = num.substr(0, pos);
2969 if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2971 go_error_at(imp->location(), "bad number in import data: %qs",
2972 real_str.c_str());
2973 return Expression::make_error(loc);
2977 std::string imag_str;
2978 if (pos == std::string::npos)
2979 imag_str = num;
2980 else
2981 imag_str = num.substr(pos);
2982 imag_str = imag_str.substr(0, imag_str.size() - 1);
2983 mpfr_t imag;
2984 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2986 go_error_at(imp->location(), "bad number in import data: %qs",
2987 imag_str.c_str());
2988 return Expression::make_error(loc);
2990 mpc_t cval;
2991 mpc_init2(cval, mpc_precision);
2992 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2993 mpfr_clear(real);
2994 mpfr_clear(imag);
2995 Expression* ret = Expression::make_complex(&cval, NULL, loc);
2996 mpc_clear(cval);
2997 return ret;
2999 else if (num.find('.') == std::string::npos
3000 && num.find('E') == std::string::npos)
3002 bool is_character_constant = (!num.empty()
3003 && num[num.length() - 1] == '\'');
3004 if (is_character_constant)
3005 num = num.substr(0, num.length() - 1);
3006 mpz_t val;
3007 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
3009 go_error_at(imp->location(), "bad number in import data: %qs",
3010 num.c_str());
3011 return Expression::make_error(loc);
3013 Expression* ret;
3014 if (is_character_constant)
3015 ret = Expression::make_character(&val, NULL, loc);
3016 else
3017 ret = Expression::make_integer_z(&val, NULL, loc);
3018 mpz_clear(val);
3019 return ret;
3021 else
3023 mpfr_t val;
3024 if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
3026 go_error_at(imp->location(), "bad number in import data: %qs",
3027 num.c_str());
3028 return Expression::make_error(loc);
3030 Expression* ret = Expression::make_float(&val, NULL, loc);
3031 mpfr_clear(val);
3032 return ret;
3035 // Ast dump for integer expression.
3037 void
3038 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3040 if (this->is_character_constant_)
3041 ast_dump_context->ostream() << '\'';
3042 Integer_expression::export_integer(ast_dump_context, this->val_);
3043 if (this->is_character_constant_)
3044 ast_dump_context->ostream() << '\'';
3047 // Build a new integer value from a multi-precision integer.
3049 Expression*
3050 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
3052 return new Integer_expression(val, type, false, location);
3055 // Build a new integer value from an unsigned long.
3057 Expression*
3058 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
3060 mpz_t zval;
3061 mpz_init_set_ui(zval, val);
3062 Expression* ret = Expression::make_integer_z(&zval, type, location);
3063 mpz_clear(zval);
3064 return ret;
3067 // Build a new integer value from a signed long.
3069 Expression*
3070 Expression::make_integer_sl(long val, Type *type, Location location)
3072 mpz_t zval;
3073 mpz_init_set_si(zval, val);
3074 Expression* ret = Expression::make_integer_z(&zval, type, location);
3075 mpz_clear(zval);
3076 return ret;
3079 // Store an int64_t in an uninitialized mpz_t.
3081 static void
3082 set_mpz_from_int64(mpz_t* zval, int64_t val)
3084 if (val >= 0)
3086 unsigned long ul = static_cast<unsigned long>(val);
3087 if (static_cast<int64_t>(ul) == val)
3089 mpz_init_set_ui(*zval, ul);
3090 return;
3093 uint64_t uv;
3094 if (val >= 0)
3095 uv = static_cast<uint64_t>(val);
3096 else
3097 uv = static_cast<uint64_t>(- val);
3098 unsigned long ul = uv & 0xffffffffUL;
3099 mpz_init_set_ui(*zval, ul);
3100 mpz_t hval;
3101 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
3102 mpz_mul_2exp(hval, hval, 32);
3103 mpz_add(*zval, *zval, hval);
3104 mpz_clear(hval);
3105 if (val < 0)
3106 mpz_neg(*zval, *zval);
3109 // Build a new integer value from an int64_t.
3111 Expression*
3112 Expression::make_integer_int64(int64_t val, Type* type, Location location)
3114 mpz_t zval;
3115 set_mpz_from_int64(&zval, val);
3116 Expression* ret = Expression::make_integer_z(&zval, type, location);
3117 mpz_clear(zval);
3118 return ret;
3121 // Build a new character constant value.
3123 Expression*
3124 Expression::make_character(const mpz_t* val, Type* type, Location location)
3126 return new Integer_expression(val, type, true, location);
3129 // Floats.
3131 class Float_expression : public Expression
3133 public:
3134 Float_expression(const mpfr_t* val, Type* type, Location location)
3135 : Expression(EXPRESSION_FLOAT, location),
3136 type_(type)
3138 mpfr_init_set(this->val_, *val, MPFR_RNDN);
3141 // Write VAL to export data.
3142 static void
3143 export_float(String_dump* exp, const mpfr_t val);
3145 // Write VAL to dump file.
3146 static void
3147 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
3149 protected:
3151 do_traverse(Traverse*);
3153 bool
3154 do_is_constant() const
3155 { return true; }
3157 bool
3158 do_is_untyped(Type**) const;
3160 bool
3161 do_is_zero_value() const
3163 return mpfr_zero_p(this->val_) != 0
3164 && mpfr_signbit(this->val_) == 0;
3167 bool
3168 do_is_static_initializer() const
3169 { return true; }
3171 bool
3172 do_numeric_constant_value(Numeric_constant* nc)
3174 nc->set_float(this->type_, this->val_);
3175 return true;
3178 Type*
3179 do_type();
3181 void
3182 do_determine_type(Gogo*, const Type_context*);
3184 void
3185 do_check_types(Gogo*);
3187 Expression*
3188 do_copy()
3189 { return Expression::make_float(&this->val_,
3190 (this->type_ == NULL
3191 ? NULL
3192 : this->type_->copy_expressions()),
3193 this->location()); }
3195 Bexpression*
3196 do_get_backend(Translate_context*);
3199 do_inlining_cost() const
3200 { return 1; }
3202 void
3203 do_export(Export_function_body*) const;
3205 void
3206 do_dump_expression(Ast_dump_context*) const;
3208 private:
3209 // The floating point value.
3210 mpfr_t val_;
3211 // The type so far.
3212 Type* type_;
3215 // Traverse a float expression. We just need to traverse the type if
3216 // there is one.
3219 Float_expression::do_traverse(Traverse* traverse)
3221 if (this->type_ != NULL)
3222 return Type::traverse(this->type_, traverse);
3223 return TRAVERSE_CONTINUE;
3226 bool
3227 Float_expression::do_is_untyped(Type** ptype) const
3229 if (this->type_ != NULL)
3230 return Expression::is_untyped_type(this->type_, ptype);
3231 *ptype = Type::make_abstract_float_type();
3232 return true;
3235 // Return the current type. If we haven't set the type yet, we return
3236 // an abstract float type.
3238 Type*
3239 Float_expression::do_type()
3241 if (this->type_ == NULL)
3242 this->type_ = Type::make_abstract_float_type();
3243 return this->type_;
3246 // Set the type of the float value. Here we may switch from an
3247 // abstract type to a real type.
3249 void
3250 Float_expression::do_determine_type(Gogo*, const Type_context* context)
3252 if (this->type_ != NULL && !this->type_->is_abstract())
3254 else if (context->type != NULL
3255 && (context->type->integer_type() != NULL
3256 || context->type->float_type() != NULL
3257 || context->type->complex_type() != NULL))
3258 this->type_ = context->type;
3259 else if (!context->may_be_abstract)
3260 this->type_ = Type::lookup_float_type("float64");
3263 // Check the type of a float value.
3265 void
3266 Float_expression::do_check_types(Gogo*)
3268 Type* type = this->type_;
3269 if (type == NULL)
3270 return;
3271 Numeric_constant nc;
3272 nc.set_float(NULL, this->val_);
3273 if (!nc.set_type(this->type_, true, this->location()))
3274 this->set_is_error();
3277 // Get the backend representation for a float constant.
3279 Bexpression*
3280 Float_expression::do_get_backend(Translate_context* context)
3282 if (this->is_error_expression()
3283 || (this->type_ != NULL && this->type_->is_error_type()))
3285 go_assert(saw_errors());
3286 return context->gogo()->backend()->error_expression();
3289 Type* resolved_type;
3290 if (this->type_ != NULL && !this->type_->is_abstract())
3291 resolved_type = this->type_;
3292 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3294 // We have an abstract integer type. We just hope for the best.
3295 resolved_type = Type::lookup_integer_type("int");
3297 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
3299 // We are converting to an abstract complex type.
3300 resolved_type = Type::lookup_complex_type("complex128");
3302 else
3304 // If we still have an abstract type here, then this is being
3305 // used in a constant expression which didn't get reduced. We
3306 // just use float64 and hope for the best.
3307 resolved_type = Type::lookup_float_type("float64");
3310 Numeric_constant nc;
3311 nc.set_float(resolved_type, this->val_);
3312 return Expression::backend_numeric_constant_expression(context, &nc);
3315 // Write a floating point number to a string dump.
3317 void
3318 Float_expression::export_float(String_dump *exp, const mpfr_t val)
3320 mpfr_exp_t exponent;
3321 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
3322 if (*s == '-')
3323 exp->write_c_string("-");
3324 exp->write_c_string("0.");
3325 exp->write_c_string(*s == '-' ? s + 1 : s);
3326 mpfr_free_str(s);
3327 char buf[30];
3328 snprintf(buf, sizeof buf, "E%ld", exponent);
3329 exp->write_c_string(buf);
3332 // Export a floating point number in a constant expression.
3334 void
3335 Float_expression::do_export(Export_function_body* efb) const
3337 bool exported_type = Expression::export_constant_type(efb, this->type_);
3339 Float_expression::export_float(efb, this->val_);
3340 // A trailing space lets us reliably identify the end of the number.
3341 efb->write_c_string(" ");
3343 Expression::finish_export_constant_type(efb, exported_type);
3346 // Dump a floating point number to the dump file.
3348 void
3349 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3351 Float_expression::export_float(ast_dump_context, this->val_);
3354 // Make a float expression.
3356 Expression*
3357 Expression::make_float(const mpfr_t* val, Type* type, Location location)
3359 return new Float_expression(val, type, location);
3362 // Complex numbers.
3364 class Complex_expression : public Expression
3366 public:
3367 Complex_expression(const mpc_t* val, Type* type, Location location)
3368 : Expression(EXPRESSION_COMPLEX, location),
3369 type_(type)
3371 mpc_init2(this->val_, mpc_precision);
3372 mpc_set(this->val_, *val, MPC_RNDNN);
3375 // Write VAL to string dump.
3376 static void
3377 export_complex(String_dump* exp, const mpc_t val);
3379 // Write REAL/IMAG to dump context.
3380 static void
3381 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
3383 protected:
3385 do_traverse(Traverse*);
3387 bool
3388 do_is_constant() const
3389 { return true; }
3391 bool
3392 do_is_untyped(Type**) const;
3394 bool
3395 do_is_zero_value() const
3397 return mpfr_zero_p(mpc_realref(this->val_)) != 0
3398 && mpfr_signbit(mpc_realref(this->val_)) == 0
3399 && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3400 && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3403 bool
3404 do_is_static_initializer() const
3405 { return true; }
3407 bool
3408 do_numeric_constant_value(Numeric_constant* nc)
3410 nc->set_complex(this->type_, this->val_);
3411 return true;
3414 Type*
3415 do_type();
3417 void
3418 do_determine_type(Gogo*, const Type_context*);
3420 void
3421 do_check_types(Gogo*);
3423 Expression*
3424 do_copy()
3426 return Expression::make_complex(&this->val_,
3427 (this->type_ == NULL
3428 ? NULL
3429 : this->type_->copy_expressions()),
3430 this->location());
3433 Bexpression*
3434 do_get_backend(Translate_context*);
3437 do_inlining_cost() const
3438 { return 2; }
3440 void
3441 do_export(Export_function_body*) const;
3443 void
3444 do_dump_expression(Ast_dump_context*) const;
3446 private:
3447 // The complex value.
3448 mpc_t val_;
3449 // The type if known.
3450 Type* type_;
3453 // Traverse a complex expression. We just need to traverse the type
3454 // if there is one.
3457 Complex_expression::do_traverse(Traverse* traverse)
3459 if (this->type_ != NULL)
3460 return Type::traverse(this->type_, traverse);
3461 return TRAVERSE_CONTINUE;
3464 bool
3465 Complex_expression::do_is_untyped(Type** ptype) const
3467 if (this->type_ != NULL)
3468 return Expression::is_untyped_type(this->type_, ptype);
3469 *ptype = Type::make_abstract_complex_type();
3470 return true;
3473 // Return the current type. If we haven't set the type yet, we return
3474 // an abstract complex type.
3476 Type*
3477 Complex_expression::do_type()
3479 if (this->type_ == NULL)
3480 this->type_ = Type::make_abstract_complex_type();
3481 return this->type_;
3484 // Set the type of the complex value. Here we may switch from an
3485 // abstract type to a real type.
3487 void
3488 Complex_expression::do_determine_type(Gogo*, const Type_context* context)
3490 if (this->type_ != NULL && !this->type_->is_abstract())
3492 else if (context->type != NULL && context->type->is_numeric_type())
3493 this->type_ = context->type;
3494 else if (!context->may_be_abstract)
3495 this->type_ = Type::lookup_complex_type("complex128");
3498 // Check the type of a complex value.
3500 void
3501 Complex_expression::do_check_types(Gogo*)
3503 Type* type = this->type_;
3504 if (type == NULL)
3505 return;
3506 Numeric_constant nc;
3507 nc.set_complex(NULL, this->val_);
3508 if (!nc.set_type(this->type_, true, this->location()))
3509 this->set_is_error();
3512 // Get the backend representation for a complex constant.
3514 Bexpression*
3515 Complex_expression::do_get_backend(Translate_context* context)
3517 if (this->is_error_expression()
3518 || (this->type_ != NULL && this->type_->is_error_type()))
3520 go_assert(saw_errors());
3521 return context->gogo()->backend()->error_expression();
3524 Type* resolved_type;
3525 if (this->type_ != NULL && !this->type_->is_abstract())
3526 resolved_type = this->type_;
3527 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3529 // We are converting to an abstract integer type.
3530 resolved_type = Type::lookup_integer_type("int");
3532 else if (this->type_ != NULL && this->type_->float_type() != NULL)
3534 // We are converting to an abstract float type.
3535 resolved_type = Type::lookup_float_type("float64");
3537 else
3539 // If we still have an abstract type here, this is being
3540 // used in a constant expression which didn't get reduced. We
3541 // just use complex128 and hope for the best.
3542 resolved_type = Type::lookup_complex_type("complex128");
3545 Numeric_constant nc;
3546 nc.set_complex(resolved_type, this->val_);
3547 return Expression::backend_numeric_constant_expression(context, &nc);
3550 // Write REAL/IMAG to export data.
3552 void
3553 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3555 if (!mpfr_zero_p(mpc_realref(val)))
3557 Float_expression::export_float(exp, mpc_realref(val));
3558 if (mpfr_sgn(mpc_imagref(val)) >= 0)
3559 exp->write_c_string("+");
3561 Float_expression::export_float(exp, mpc_imagref(val));
3562 exp->write_c_string("i");
3565 // Export a complex number in a constant expression.
3567 void
3568 Complex_expression::do_export(Export_function_body* efb) const
3570 bool exported_type = Expression::export_constant_type(efb, this->type_);
3572 Complex_expression::export_complex(efb, this->val_);
3573 // A trailing space lets us reliably identify the end of the number.
3574 efb->write_c_string(" ");
3576 Expression::finish_export_constant_type(efb, exported_type);
3579 // Dump a complex expression to the dump file.
3581 void
3582 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3584 Complex_expression::export_complex(ast_dump_context, this->val_);
3587 // Make a complex expression.
3589 Expression*
3590 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3592 return new Complex_expression(val, type, location);
3595 // Find a named object in an expression.
3597 class Find_named_object : public Traverse
3599 public:
3600 Find_named_object(Named_object* no)
3601 : Traverse(traverse_expressions),
3602 no_(no), found_(false)
3605 // Whether we found the object.
3606 bool
3607 found() const
3608 { return this->found_; }
3610 protected:
3612 expression(Expression**);
3614 private:
3615 // The object we are looking for.
3616 Named_object* no_;
3617 // Whether we found it.
3618 bool found_;
3621 // Class Const_expression.
3623 // Traversal.
3626 Const_expression::do_traverse(Traverse* traverse)
3628 if (this->type_ != NULL)
3629 return Type::traverse(this->type_, traverse);
3630 return TRAVERSE_CONTINUE;
3633 // Whether this is the zero value.
3635 bool
3636 Const_expression::do_is_zero_value() const
3638 return this->constant_->const_value()->expr()->is_zero_value();
3641 // Lower a constant expression. This is where we convert the
3642 // predeclared constant iota into an integer value.
3644 Expression*
3645 Const_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*)
3647 Location loc = this->location();
3649 if (this->is_error_expression())
3650 return Expression::make_error(loc);
3651 if (this->constant_->const_value()->expr()->is_error_expression())
3652 return Expression::make_error(loc);
3654 if (this->is_iota_)
3655 return Expression::make_integer_ul(this->iota_value_, NULL, loc);
3657 // Make sure that the constant itself has been lowered.
3658 gogo->lower_constant(this->constant_);
3660 return this;
3663 // Return a numeric constant value.
3665 bool
3666 Const_expression::do_numeric_constant_value(Numeric_constant* nc)
3668 if (this->seen_)
3669 return false;
3671 Type* ctype;
3672 if (this->type_ != NULL)
3673 ctype = this->type_;
3674 else
3675 ctype = this->constant_->const_value()->type();
3677 if (this->is_iota_)
3679 nc->set_unsigned_long(ctype,
3680 static_cast<unsigned long>(this->iota_value_));
3681 return true;
3684 Expression* e = this->constant_->const_value()->expr();
3686 this->seen_ = true;
3688 bool r = e->numeric_constant_value(nc);
3690 this->seen_ = false;
3692 if (r && ctype != NULL)
3694 if (!nc->set_type(ctype, false, this->location()))
3695 return false;
3698 return r;
3701 bool
3702 Const_expression::do_string_constant_value(std::string* val)
3704 if (this->seen_)
3705 return false;
3706 if (this->is_iota_)
3707 return false;
3709 Expression* e = this->constant_->const_value()->expr();
3711 this->seen_ = true;
3712 bool ok = e->string_constant_value(val);
3713 this->seen_ = false;
3715 return ok;
3718 bool
3719 Const_expression::do_boolean_constant_value(bool* val)
3721 if (this->seen_)
3722 return false;
3723 if (this->is_iota_)
3724 return false;
3726 Expression* e = this->constant_->const_value()->expr();
3728 this->seen_ = true;
3729 bool ok = e->boolean_constant_value(val);
3730 this->seen_ = false;
3732 return ok;
3735 // Whether this is untyped.
3737 bool
3738 Const_expression::do_is_untyped(Type** ptype) const
3740 if (this->type_ != NULL)
3741 return Expression::is_untyped_type(this->type_, ptype);
3743 Named_constant* nc = this->constant_->const_value();
3744 if (nc->type() != NULL)
3745 return Expression::is_untyped_type(nc->type(), ptype);
3747 return nc->expr()->is_untyped(ptype);
3750 // Return the type of the const reference.
3752 Type*
3753 Const_expression::do_type()
3755 if (this->type_ == NULL)
3757 go_assert(saw_errors());
3758 return Type::make_error_type();
3761 return this->type_;
3764 // Set the type of the const reference.
3766 void
3767 Const_expression::do_determine_type(Gogo* gogo, const Type_context* context)
3769 if (this->type_ != NULL)
3770 return;
3772 // The type may depend on the type of other constants. Avoid an
3773 // endless loop.
3774 if (this->seen_)
3776 if (!saw_errors())
3777 go_error_at(this->location(), "constant refers to itself");
3778 this->set_is_error();
3779 this->type_ = Type::make_error_type();
3780 return;
3783 this->seen_ = true;
3785 Named_constant* nc = this->constant_->const_value();
3786 nc->determine_type(gogo);
3788 Type* ctype = nc->type();
3790 this->seen_ = false;
3792 if (ctype == NULL)
3794 go_error_at(nc->expr()->location(), "constant refers to itself");
3795 this->set_is_error();
3796 this->type_ = Type::make_error_type();
3798 else if (!ctype->is_abstract())
3799 this->type_ = ctype;
3800 else if (context->type != NULL
3801 && context->type->is_numeric_type()
3802 && ctype->is_numeric_type())
3803 this->type_ = context->type;
3804 else if (context->type != NULL
3805 && context->type->is_string_type()
3806 && ctype->is_string_type())
3807 this->type_ = context->type;
3808 else if (context->type != NULL
3809 && context->type->is_boolean_type()
3810 && ctype->is_boolean_type())
3811 this->type_ = context->type;
3812 else if (!context->may_be_abstract)
3814 if (ctype->is_abstract())
3815 ctype = ctype->make_non_abstract_type();
3816 this->type_ = ctype;
3818 else
3819 this->type_ = ctype;
3822 // Check for a loop in which the initializer of a constant refers to
3823 // the constant itself.
3825 void
3826 Const_expression::check_for_init_loop()
3828 if (this->is_error_expression())
3829 return;
3830 if (this->type_ != NULL && this->type_->is_error())
3831 return;
3832 if (this->constant_->const_value()->expr()->is_error_expression())
3834 this->set_is_error();
3835 return;
3838 if (this->seen_)
3840 this->report_error(_("constant refers to itself"));
3841 this->type_ = Type::make_error_type();
3842 return;
3845 Expression* init = this->constant_->const_value()->expr();
3846 Find_named_object find_named_object(this->constant_);
3848 this->seen_ = true;
3849 Expression::traverse(&init, &find_named_object);
3850 this->seen_ = false;
3852 if (find_named_object.found())
3854 if (this->type_ == NULL || !this->type_->is_error())
3856 this->report_error(_("constant refers to itself"));
3857 this->type_ = Type::make_error_type();
3859 return;
3863 // Set the iota value if this is a reference to iota.
3865 void
3866 Const_expression::set_iota_value(int iota_value)
3868 Named_constant* nc = this->constant_->const_value();
3869 if (nc->expr()->classification() == EXPRESSION_IOTA)
3871 this->is_iota_ = true;
3872 this->iota_value_ = iota_value;
3876 // Check types of a const reference.
3878 void
3879 Const_expression::do_check_types(Gogo*)
3881 if (this->is_error_expression())
3882 return;
3883 if (this->type_ != NULL && this->type_->is_error())
3884 return;
3885 if (this->constant_->const_value()->expr()->is_error_expression())
3887 this->set_is_error();
3888 return;
3891 Expression* expr = this->constant_->const_value()->expr();
3892 if (expr->classification() == EXPRESSION_IOTA && !this->is_iota_)
3894 go_error_at(this->location(),
3895 "iota is only defined in const declarations");
3896 // Avoid knock-on errors.
3897 this->is_iota_ = true;
3898 this->iota_value_ = 0;
3901 if (this->is_iota_ && this->type_->is_numeric_type())
3903 Numeric_constant nc;
3904 nc.set_unsigned_long(Type::make_abstract_integer_type(),
3905 static_cast<unsigned long>(this->iota_value_));
3906 if (!nc.set_type(this->type_, true, this->location()))
3907 this->set_is_error();
3908 return;
3911 this->check_for_init_loop();
3913 // Check that numeric constant fits in type.
3914 if (this->type_->is_numeric_type())
3916 Numeric_constant nc;
3917 if (expr->numeric_constant_value(&nc))
3919 if (!nc.set_type(this->type_, true, this->location()))
3920 this->set_is_error();
3925 // Return the backend representation for a const reference.
3927 Bexpression*
3928 Const_expression::do_get_backend(Translate_context* context)
3930 if (this->is_error_expression()
3931 || (this->type_ != NULL && this->type_->is_error()))
3933 go_assert(saw_errors());
3934 return context->backend()->error_expression();
3937 go_assert(!this->is_iota_);
3939 // If the type has been set for this expression, but the underlying
3940 // object is an abstract int or float, we try to get the abstract
3941 // value. Otherwise we may lose something in the conversion.
3942 Expression* expr = this->constant_->const_value()->expr();
3943 if (this->type_ != NULL
3944 && this->type_->is_numeric_type()
3945 && (this->constant_->const_value()->type() == NULL
3946 || this->constant_->const_value()->type()->is_abstract()))
3948 Numeric_constant nc;
3949 if (expr->numeric_constant_value(&nc)
3950 && nc.set_type(this->type_, false, this->location()))
3952 Expression* e = nc.expression(this->location());
3953 return e->get_backend(context);
3957 if (this->type_ != NULL)
3958 expr = Expression::make_cast(this->type_, expr, this->location());
3959 return expr->get_backend(context);
3962 // When exporting a reference to a const as part of a const
3963 // expression, we export the value. We ignore the fact that it has
3964 // a name.
3966 void
3967 Const_expression::do_export(Export_function_body* efb) const
3969 this->constant_->const_value()->expr()->export_expression(efb);
3972 // Dump ast representation for constant expression.
3974 void
3975 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3977 ast_dump_context->ostream() << this->constant_->name();
3980 // Make a reference to a constant in an expression.
3982 Expression*
3983 Expression::make_const_reference(Named_object* constant,
3984 Location location)
3986 return new Const_expression(constant, location);
3989 // Find a named object in an expression.
3992 Find_named_object::expression(Expression** pexpr)
3994 switch ((*pexpr)->classification())
3996 case Expression::EXPRESSION_CONST_REFERENCE:
3998 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3999 if (ce->named_object() == this->no_)
4000 break;
4001 return TRAVERSE_CONTINUE;
4004 case Expression::EXPRESSION_VAR_REFERENCE:
4005 if ((*pexpr)->var_expression()->named_object() == this->no_)
4006 break;
4007 return TRAVERSE_CONTINUE;
4008 case Expression::EXPRESSION_FUNC_REFERENCE:
4009 if ((*pexpr)->func_expression()->named_object() == this->no_)
4010 break;
4011 return TRAVERSE_CONTINUE;
4012 case Expression::EXPRESSION_ERROR:
4013 return TRAVERSE_EXIT;
4014 default:
4015 return TRAVERSE_CONTINUE;
4017 this->found_ = true;
4018 return TRAVERSE_EXIT;
4021 // The nil value.
4023 class Nil_expression : public Expression
4025 public:
4026 Nil_expression(Location location)
4027 : Expression(EXPRESSION_NIL, location)
4030 static Expression*
4031 do_import(Import_expression*, Location);
4033 protected:
4034 bool
4035 do_is_constant() const
4036 { return true; }
4038 bool
4039 do_untyped_type(Type** ptype) const
4041 *ptype = Type::make_nil_type();
4042 return true;
4045 bool
4046 do_is_zero_value() const
4047 { return true; }
4049 bool
4050 do_is_static_initializer() const
4051 { return true; }
4053 Type*
4054 do_type()
4055 { return Type::make_nil_type(); }
4057 void
4058 do_determine_type(Gogo*, const Type_context*)
4061 Expression*
4062 do_copy()
4063 { return this; }
4065 Bexpression*
4066 do_get_backend(Translate_context* context)
4067 { return context->backend()->nil_pointer_expression(); }
4070 do_inlining_cost() const
4071 { return 1; }
4073 void
4074 do_export(Export_function_body* efb) const
4075 { efb->write_c_string("$nil"); }
4077 void
4078 do_dump_expression(Ast_dump_context* ast_dump_context) const
4079 { ast_dump_context->ostream() << "nil"; }
4082 // Import a nil expression.
4084 Expression*
4085 Nil_expression::do_import(Import_expression* imp, Location loc)
4087 if (imp->version() >= EXPORT_FORMAT_V3)
4088 imp->require_c_string("$");
4089 imp->require_c_string("nil");
4090 return Expression::make_nil(loc);
4093 // Make a nil expression.
4095 Expression*
4096 Expression::make_nil(Location location)
4098 return new Nil_expression(location);
4101 // The value of the predeclared constant iota. This is little more
4102 // than a marker. This will be lowered to an integer in
4103 // Const_expression::do_lower, which is where we know the value that
4104 // it should have.
4106 class Iota_expression : public Parser_expression
4108 public:
4109 Iota_expression(Location location)
4110 : Parser_expression(EXPRESSION_IOTA, location)
4113 protected:
4114 Type*
4115 do_type()
4116 { return Type::make_abstract_integer_type(); }
4118 void
4119 do_determine_type(Gogo*, const Type_context*)
4122 Expression*
4123 do_lower(Gogo*, Named_object*, Statement_inserter*)
4124 { go_unreachable(); }
4126 // There should only ever be one of these.
4127 Expression*
4128 do_copy()
4129 { go_unreachable(); }
4131 void
4132 do_dump_expression(Ast_dump_context* ast_dump_context) const
4133 { ast_dump_context->ostream() << "iota"; }
4136 // Make an iota expression. This is only called for one case: the
4137 // value of the predeclared constant iota.
4139 Expression*
4140 Expression::make_iota()
4142 static Iota_expression iota_expression(Linemap::unknown_location());
4143 return &iota_expression;
4146 // Class Type_conversion_expression.
4148 // Traversal.
4151 Type_conversion_expression::do_traverse(Traverse* traverse)
4153 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4154 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4155 return TRAVERSE_EXIT;
4156 return TRAVERSE_CONTINUE;
4159 // Return the type of the expression.
4161 Type*
4162 Type_conversion_expression::do_type()
4164 if (this->is_error_expression() || this->expr_->is_error_expression())
4165 return Type::make_error_type();
4166 return this->type_;
4169 // Convert to a constant at lowering time. Also lower conversions
4170 // from slice to pointer-to-array, as they can panic.
4172 Expression*
4173 Type_conversion_expression::do_lower(Gogo* gogo, Named_object*,
4174 Statement_inserter* inserter)
4176 Type* type = this->type_;
4177 Expression* val = this->expr_;
4178 Location location = this->location();
4180 if (type->is_numeric_type())
4182 Numeric_constant nc;
4183 if (val->numeric_constant_value(&nc))
4185 if (!nc.set_type(type, true, location))
4186 return Expression::make_error(location);
4187 return nc.expression(location);
4191 // According to the language specification on string conversions
4192 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
4193 // When converting an integer into a string, the string will be a UTF-8
4194 // representation of the integer and integers "outside the range of valid
4195 // Unicode code points are converted to '\uFFFD'."
4196 if (type->is_string_type())
4198 Numeric_constant nc;
4199 if (val->numeric_constant_value(&nc) && nc.is_int())
4201 // An integer value doesn't fit in the Unicode code point range if it
4202 // overflows the Go "int" type or is negative.
4203 unsigned long ul;
4204 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
4205 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
4206 return Expression::make_string("\ufffd", location);
4210 if (type->is_slice_type())
4212 Type* element_type = type->array_type()->element_type()->forwarded();
4213 bool is_byte = (element_type->integer_type() != NULL
4214 && element_type->integer_type()->is_byte());
4215 bool is_rune = (element_type->integer_type() != NULL
4216 && element_type->integer_type()->is_rune());
4217 if (is_byte || is_rune)
4219 std::string s;
4220 if (val->string_constant_value(&s))
4222 Expression_list* vals = new Expression_list();
4223 if (is_byte)
4225 for (std::string::const_iterator p = s.begin();
4226 p != s.end();
4227 p++)
4229 unsigned char c = static_cast<unsigned char>(*p);
4230 vals->push_back(Expression::make_integer_ul(c,
4231 element_type,
4232 location));
4235 else
4237 const char *p = s.data();
4238 const char *pend = s.data() + s.length();
4239 while (p < pend)
4241 unsigned int c;
4242 int adv = Lex::fetch_char(p, &c);
4243 if (adv == 0)
4245 go_warning_at(this->location(), 0,
4246 "invalid UTF-8 encoding");
4247 adv = 1;
4249 p += adv;
4250 vals->push_back(Expression::make_integer_ul(c,
4251 element_type,
4252 location));
4256 return Expression::make_slice_composite_literal(type, vals,
4257 location);
4262 if (type->points_to() != NULL
4263 && type->points_to()->array_type() != NULL
4264 && !type->points_to()->is_slice_type()
4265 && val->type()->is_slice_type()
4266 && Type::are_identical(type->points_to()->array_type()->element_type(),
4267 val->type()->array_type()->element_type(),
4268 0, NULL))
4270 Temporary_statement* val_temp = NULL;
4271 if (!val->is_multi_eval_safe())
4273 val_temp = Statement::make_temporary(val->type(), NULL, location);
4274 inserter->insert(val_temp);
4275 val = Expression::make_set_and_use_temporary(val_temp, val,
4276 location);
4279 Type* int_type = Type::lookup_integer_type("int");
4280 Temporary_statement* vallen_temp =
4281 Statement::make_temporary(int_type, NULL, location);
4282 inserter->insert(vallen_temp);
4284 Expression* arrlen = type->points_to()->array_type()->length();
4285 Expression* vallen =
4286 Expression::make_slice_info(val, Expression::SLICE_INFO_LENGTH,
4287 location);
4288 vallen = Expression::make_set_and_use_temporary(vallen_temp, vallen,
4289 location);
4290 Expression* cond = Expression::make_binary(OPERATOR_GT, arrlen, vallen,
4291 location);
4293 vallen = Expression::make_temporary_reference(vallen_temp, location);
4294 Expression* panic = Runtime::make_call(gogo,
4295 Runtime::PANIC_SLICE_CONVERT,
4296 location, 2, arrlen, vallen);
4298 Expression* nil = Expression::make_nil(location);
4299 Expression* check = Expression::make_conditional(cond, panic, nil,
4300 location);
4302 if (val_temp == NULL)
4303 val = val->copy();
4304 else
4305 val = Expression::make_temporary_reference(val_temp, location);
4306 Expression* ptr =
4307 Expression::make_slice_info(val, Expression::SLICE_INFO_VALUE_POINTER,
4308 location);
4309 ptr = Expression::make_unsafe_cast(type, ptr, location);
4311 Expression* ret = Expression::make_compound(check, ptr, location);
4312 ret->determine_type_no_context(gogo);
4313 return ret;
4316 return this;
4319 // Flatten a type conversion by using a temporary variable for the slice
4320 // in slice to string conversions.
4322 Expression*
4323 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
4324 Statement_inserter* inserter)
4326 if (this->type()->is_error_type() || this->expr_->is_error_expression())
4328 go_assert(saw_errors());
4329 return Expression::make_error(this->location());
4332 if (((this->type()->is_string_type()
4333 && this->expr_->type()->is_slice_type())
4334 || this->expr_->type()->interface_type() != NULL)
4335 && !this->expr_->is_multi_eval_safe())
4337 Temporary_statement* temp =
4338 Statement::make_temporary(NULL, this->expr_, this->location());
4339 inserter->insert(temp);
4340 this->expr_ = Expression::make_temporary_reference(temp, this->location());
4343 // For interface conversion and string to/from slice conversions,
4344 // decide if we can allocate on stack.
4345 if (this->type()->interface_type() != NULL
4346 || this->type()->is_string_type()
4347 || this->expr_->type()->is_string_type())
4349 Node* n = Node::make_node(this);
4350 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
4351 this->no_escape_ = true;
4353 return this;
4356 // Return whether a type conversion is a constant.
4358 bool
4359 Type_conversion_expression::do_is_constant() const
4361 if (!this->expr_->is_constant())
4362 return false;
4364 // A conversion to a type that may not be used as a constant is not
4365 // a constant. For example, []byte(nil).
4366 Type* type = this->type_;
4367 if (type->integer_type() == NULL
4368 && type->float_type() == NULL
4369 && type->complex_type() == NULL
4370 && !type->is_boolean_type()
4371 && !type->is_string_type())
4372 return false;
4374 return true;
4377 // Return whether a type conversion is a zero value.
4379 bool
4380 Type_conversion_expression::do_is_zero_value() const
4382 if (!this->expr_->is_zero_value())
4383 return false;
4385 // Some type conversion from zero value is still not zero value.
4386 // For example, []byte("") or interface{}(0).
4387 // Conservatively, only report true if the RHS is nil.
4388 Type* type = this->type_;
4389 if (type->integer_type() == NULL
4390 && type->float_type() == NULL
4391 && type->complex_type() == NULL
4392 && !type->is_boolean_type()
4393 && !type->is_string_type())
4394 return this->expr_->is_nil_expression();
4396 return true;
4399 // Return whether a type conversion can be used in a constant
4400 // initializer.
4402 bool
4403 Type_conversion_expression::do_is_static_initializer() const
4405 Type* type = this->type_;
4406 Type* expr_type = this->expr_->type();
4408 if (type->interface_type() != NULL
4409 || expr_type->interface_type() != NULL)
4410 return false;
4412 if (!this->expr_->is_static_initializer())
4413 return false;
4415 if (Type::are_identical(type, expr_type,
4416 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4417 NULL))
4418 return true;
4420 if (type->is_string_type() && expr_type->is_string_type())
4421 return true;
4423 if ((type->is_numeric_type()
4424 || type->is_boolean_type()
4425 || type->points_to() != NULL)
4426 && (expr_type->is_numeric_type()
4427 || expr_type->is_boolean_type()
4428 || expr_type->points_to() != NULL))
4429 return true;
4431 return false;
4434 // Return the constant numeric value if there is one.
4436 bool
4437 Type_conversion_expression::do_numeric_constant_value(
4438 Numeric_constant* nc)
4440 if (!this->type_->is_numeric_type())
4441 return false;
4442 if (!this->expr_->numeric_constant_value(nc))
4443 return false;
4444 return nc->set_type(this->type_, false, this->location());
4447 // Return the constant string value if there is one.
4449 bool
4450 Type_conversion_expression::do_string_constant_value(std::string* val)
4452 if (this->type_->is_string_type() && this->expr_->type()->is_string_type())
4453 return this->expr_->string_constant_value(val);
4455 if (this->type_->is_string_type()
4456 && this->expr_->type()->integer_type() != NULL)
4458 Numeric_constant nc;
4459 if (this->expr_->numeric_constant_value(&nc))
4461 unsigned long ival;
4462 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4464 unsigned int cval = static_cast<unsigned int>(ival);
4465 if (static_cast<unsigned long>(cval) != ival)
4467 go_warning_at(this->location(), 0,
4468 "unicode code point 0x%lx out of range",
4469 ival);
4470 cval = 0xfffd; // Unicode "replacement character."
4472 val->clear();
4473 Lex::append_char(cval, true, val, this->location());
4474 return true;
4479 // FIXME: Could handle conversion from const []int here.
4481 return false;
4484 // Return the constant boolean value if there is one.
4486 bool
4487 Type_conversion_expression::do_boolean_constant_value(bool* val)
4489 if (!this->type_->is_boolean_type())
4490 return false;
4491 return this->expr_->boolean_constant_value(val);
4494 // Determine the resulting type of the conversion.
4496 void
4497 Type_conversion_expression::do_determine_type(Gogo* gogo, const Type_context*)
4499 Type_context subcontext(this->type_, false);
4500 this->expr_->determine_type(gogo, &subcontext);
4503 // Check that types are convertible.
4505 void
4506 Type_conversion_expression::do_check_types(Gogo*)
4508 Type* type = this->type_;
4509 Type* expr_type = this->expr_->type();
4510 std::string reason;
4512 if (type->is_error() || expr_type->is_error())
4514 this->set_is_error();
4515 return;
4518 if (this->may_convert_function_types_
4519 && type->function_type() != NULL
4520 && expr_type->function_type() != NULL)
4521 return;
4523 if (Type::are_convertible(type, expr_type, &reason))
4524 return;
4526 // We can convert all numeric types if the value is a constant.
4527 if (type->is_numeric_type()
4528 && expr_type->is_numeric_type()
4529 && this->expr_->is_constant())
4530 return;
4532 go_error_at(this->location(), "%s", reason.c_str());
4533 this->set_is_error();
4536 // Copy.
4538 Expression*
4539 Type_conversion_expression::do_copy()
4541 Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4542 this->expr_->copy(),
4543 this->location());
4544 ret->conversion_expression()->set_no_copy(this->no_copy_);
4545 return ret;
4548 // Get the backend representation for a type conversion.
4550 Bexpression*
4551 Type_conversion_expression::do_get_backend(Translate_context* context)
4553 Type* type = this->type_;
4554 Type* expr_type = this->expr_->type();
4555 Type_context tcontext(type, false);
4557 Gogo* gogo = context->gogo();
4558 Btype* btype = type->get_backend(gogo);
4559 Location loc = this->location();
4561 if (Type::are_identical(type, expr_type,
4562 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4563 NULL))
4565 Bexpression* bexpr = this->expr_->get_backend(context);
4566 return gogo->backend()->convert_expression(btype, bexpr, loc);
4568 else if (type->interface_type() != NULL
4569 && expr_type->interface_type() == NULL)
4571 Expression* conversion =
4572 Expression::convert_type_to_interface(type, this->expr_,
4573 this->no_escape_, loc);
4574 conversion->determine_type(gogo, &tcontext);
4575 return conversion->get_backend(context);
4577 else if (type->interface_type() != NULL
4578 || expr_type->interface_type() != NULL)
4580 Expression* conversion =
4581 Expression::convert_for_assignment(gogo, type, this->expr_,
4582 loc);
4583 conversion->determine_type(gogo, &tcontext);
4584 return conversion->get_backend(context);
4586 else if (type->is_string_type()
4587 && expr_type->integer_type() != NULL)
4589 mpz_t intval;
4590 Numeric_constant nc;
4591 if (this->expr_->numeric_constant_value(&nc)
4592 && nc.to_int(&intval))
4594 std::string s;
4595 unsigned int x;
4596 if (mpz_fits_uint_p(intval))
4597 x = mpz_get_ui(intval);
4598 else
4600 char* ms = mpz_get_str(NULL, 16, intval);
4601 go_warning_at(loc, 0,
4602 "unicode code point 0x%s out of range in string",
4603 ms);
4604 free(ms);
4605 x = 0xfffd;
4607 Lex::append_char(x, true, &s, loc);
4608 mpz_clear(intval);
4609 Expression* se = Expression::make_string(s, loc);
4610 se->determine_type(gogo, &tcontext);
4611 return se->get_backend(context);
4614 Expression* buf;
4615 if (this->no_escape_)
4617 Type* byte_type = Type::lookup_integer_type("uint8");
4618 Expression* buflen =
4619 Expression::make_integer_ul(4, NULL, loc);
4620 Type* array_type = Type::make_array_type(byte_type, buflen);
4621 buf = Expression::make_allocation(array_type, loc);
4622 buf->allocation_expression()->set_allocate_on_stack();
4623 buf->allocation_expression()->set_no_zero();
4625 else
4626 buf = Expression::make_nil(loc);
4627 Expression* i2s_expr =
4628 Runtime::make_call(gogo, Runtime::INTSTRING, loc, 2, buf, this->expr_);
4629 Expression* ret = Expression::make_cast(type, i2s_expr, loc);
4630 Type_context tcontext(type, false);
4631 ret->determine_type(gogo, &tcontext);
4632 return ret->get_backend(context);
4634 else if (type->is_string_type() && expr_type->is_slice_type())
4636 Array_type* a = expr_type->array_type();
4637 Type* e = a->element_type()->forwarded();
4638 go_assert(e->integer_type() != NULL);
4639 go_assert(this->expr_->is_multi_eval_safe());
4641 Expression* buf;
4642 if (this->no_escape_ && !this->no_copy_)
4644 Type* byte_type = Type::lookup_integer_type("uint8");
4645 Expression* buflen =
4646 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4647 Type* array_type = Type::make_array_type(byte_type, buflen);
4648 buf = Expression::make_allocation(array_type, loc);
4649 buf->allocation_expression()->set_allocate_on_stack();
4650 buf->allocation_expression()->set_no_zero();
4652 else
4653 buf = Expression::make_nil(loc);
4655 if (e->integer_type()->is_byte())
4657 Expression* ptr =
4658 Expression::make_slice_info(this->expr_, SLICE_INFO_VALUE_POINTER,
4659 loc);
4660 Expression* len =
4661 Expression::make_slice_info(this->expr_, SLICE_INFO_LENGTH, loc);
4662 if (this->no_copy_)
4664 if (gogo->debug_optimization())
4665 go_debug(loc, "no copy string([]byte)");
4666 Expression* str = Expression::make_string_value(ptr, len, loc);
4667 return str->get_backend(context);
4669 Expression* ret = Runtime::make_call(gogo, Runtime::SLICEBYTETOSTRING,
4670 loc, 3, buf, ptr, len);
4671 Type_context tcontext(type, false);
4672 ret->determine_type(gogo, &tcontext);
4673 return ret->get_backend(context);
4675 else
4677 go_assert(e->integer_type()->is_rune());
4678 Expression* ret = Runtime::make_call(gogo, Runtime::SLICERUNETOSTRING,
4679 loc, 2, buf, this->expr_);
4680 Type_context tcontext(type, false);
4681 ret->determine_type(gogo, &tcontext);
4682 return ret->get_backend(context);
4685 else if (type->is_slice_type() && expr_type->is_string_type())
4687 Type* e = type->array_type()->element_type()->forwarded();
4688 go_assert(e->integer_type() != NULL);
4690 Runtime::Function code;
4691 if (e->integer_type()->is_byte())
4692 code = Runtime::STRINGTOSLICEBYTE;
4693 else
4695 go_assert(e->integer_type()->is_rune());
4696 code = Runtime::STRINGTOSLICERUNE;
4699 Expression* buf;
4700 if (this->no_escape_)
4702 Expression* buflen =
4703 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4704 Type* array_type = Type::make_array_type(e, buflen);
4705 buf = Expression::make_allocation(array_type, loc);
4706 buf->allocation_expression()->set_allocate_on_stack();
4707 buf->allocation_expression()->set_no_zero();
4709 else
4710 buf = Expression::make_nil(loc);
4711 Expression* s2a = Runtime::make_call(gogo, code, loc, 2, buf,
4712 this->expr_);
4713 Expression* ret = Expression::make_unsafe_cast(type, s2a, loc);
4714 Type_context tcontext(type, false);
4715 ret->determine_type(gogo, &tcontext);
4716 return ret->get_backend(context);
4718 else if (type->is_numeric_type())
4720 go_assert(Type::are_convertible(type, expr_type, NULL));
4721 Bexpression* bexpr = this->expr_->get_backend(context);
4722 return gogo->backend()->convert_expression(btype, bexpr, loc);
4724 else if ((type->is_unsafe_pointer_type()
4725 && (expr_type->points_to() != NULL
4726 || expr_type->integer_type()))
4727 || (expr_type->is_unsafe_pointer_type()
4728 && type->points_to() != NULL)
4729 || (this->may_convert_function_types_
4730 && type->function_type() != NULL
4731 && expr_type->function_type() != NULL))
4733 Bexpression* bexpr = this->expr_->get_backend(context);
4734 return gogo->backend()->convert_expression(btype, bexpr, loc);
4736 else
4738 Expression* conversion =
4739 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4740 conversion->determine_type(gogo, &tcontext);
4741 return conversion->get_backend(context);
4745 // Cost of inlining a type conversion.
4748 Type_conversion_expression::do_inlining_cost() const
4750 Type* type = this->type_;
4751 Type* expr_type = this->expr_->type();
4752 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4753 return 10;
4754 else if (type->is_string_type() && expr_type->integer_type() != NULL)
4755 return 10;
4756 else if (type->is_string_type() && expr_type->is_slice_type())
4757 return 10;
4758 else if (type->is_slice_type() && expr_type->is_string_type())
4759 return 10;
4760 else
4761 return 1;
4764 // Output a type conversion in a constant expression.
4766 void
4767 Type_conversion_expression::do_export(Export_function_body* efb) const
4769 efb->write_c_string("$convert(");
4770 efb->write_type(this->type_);
4771 efb->write_c_string(", ");
4773 Type* old_context = efb->type_context();
4774 efb->set_type_context(this->type_);
4776 this->expr_->export_expression(efb);
4778 efb->set_type_context(old_context);
4780 efb->write_c_string(")");
4783 // Import a type conversion or a struct construction.
4785 Expression*
4786 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4788 imp->require_c_string("$convert(");
4789 Type* type = imp->read_type();
4790 imp->require_c_string(", ");
4791 Expression* val = Expression::import_expression(imp, loc);
4792 imp->require_c_string(")");
4793 return Expression::make_cast(type, val, loc);
4796 // Dump ast representation for a type conversion expression.
4798 void
4799 Type_conversion_expression::do_dump_expression(
4800 Ast_dump_context* ast_dump_context) const
4802 ast_dump_context->dump_type(this->type_);
4803 ast_dump_context->ostream() << "(";
4804 ast_dump_context->dump_expression(this->expr_);
4805 ast_dump_context->ostream() << ") ";
4808 // Make a type cast expression.
4810 Expression*
4811 Expression::make_cast(Type* type, Expression* val, Location location)
4813 if (type->is_error_type() || val->is_error_expression())
4814 return Expression::make_error(location);
4815 return new Type_conversion_expression(type, val, location);
4818 // Class Unsafe_type_conversion_expression.
4820 // Traversal.
4823 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4825 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4826 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4827 return TRAVERSE_EXIT;
4828 return TRAVERSE_CONTINUE;
4831 // Return whether an unsafe type conversion can be used as a constant
4832 // initializer.
4834 bool
4835 Unsafe_type_conversion_expression::do_is_static_initializer() const
4837 Type* type = this->type_;
4838 Type* expr_type = this->expr_->type();
4840 if (type->interface_type() != NULL
4841 || expr_type->interface_type() != NULL)
4842 return false;
4844 if (!this->expr_->is_static_initializer())
4845 return false;
4847 if (Type::are_convertible(type, expr_type, NULL))
4848 return true;
4850 if (type->is_string_type() && expr_type->is_string_type())
4851 return true;
4853 if ((type->is_numeric_type()
4854 || type->is_boolean_type()
4855 || type->points_to() != NULL)
4856 && (expr_type->is_numeric_type()
4857 || expr_type->is_boolean_type()
4858 || expr_type->points_to() != NULL))
4859 return true;
4861 return false;
4864 // Copy.
4866 Expression*
4867 Unsafe_type_conversion_expression::do_copy()
4869 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4870 this->expr_->copy(),
4871 this->location());
4874 // Convert to backend representation.
4876 Bexpression*
4877 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4879 // We are only called for a limited number of cases.
4881 Type* t = this->type_;
4882 Type* et = this->expr_->type();
4884 if (t->is_error_type()
4885 || this->expr_->is_error_expression()
4886 || et->is_error_type())
4888 go_assert(saw_errors());
4889 return context->backend()->error_expression();
4892 if (t->array_type() != NULL)
4893 go_assert(et->array_type() != NULL
4894 && t->is_slice_type() == et->is_slice_type());
4895 else if (t->struct_type() != NULL)
4897 if (t->named_type() != NULL
4898 && et->named_type() != NULL
4899 && !Type::are_convertible(t, et, NULL))
4901 go_assert(saw_errors());
4902 return context->backend()->error_expression();
4905 go_assert(et->struct_type() != NULL
4906 && Type::are_convertible(t, et, NULL));
4908 else if (t->map_type() != NULL)
4909 go_assert(et->map_type() != NULL || et->points_to() != NULL);
4910 else if (t->channel_type() != NULL)
4911 go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4912 else if (t->points_to() != NULL)
4913 go_assert(et->points_to() != NULL
4914 || et->channel_type() != NULL
4915 || et->map_type() != NULL
4916 || et->function_type() != NULL
4917 || et->integer_type() != NULL
4918 || et->is_nil_type());
4919 else if (t->function_type() != NULL)
4920 go_assert(et->points_to() != NULL);
4921 else if (et->is_unsafe_pointer_type())
4922 go_assert(t->points_to() != NULL
4923 || (t->integer_type() != NULL
4924 && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4925 else if (t->interface_type() != NULL)
4927 bool empty_iface = t->interface_type()->is_empty();
4928 go_assert(et->interface_type() != NULL
4929 && et->interface_type()->is_empty() == empty_iface);
4931 else if (t->integer_type() != NULL)
4932 go_assert(et->is_boolean_type()
4933 || et->integer_type() != NULL
4934 || et->function_type() != NULL
4935 || et->points_to() != NULL
4936 || et->map_type() != NULL
4937 || et->channel_type() != NULL
4938 || et->is_nil_type());
4939 else
4940 go_unreachable();
4942 Gogo* gogo = context->gogo();
4943 Btype* btype = t->get_backend(gogo);
4944 Bexpression* bexpr = this->expr_->get_backend(context);
4945 Location loc = this->location();
4946 return gogo->backend()->convert_expression(btype, bexpr, loc);
4949 // Dump ast representation for an unsafe type conversion expression.
4951 void
4952 Unsafe_type_conversion_expression::do_dump_expression(
4953 Ast_dump_context* ast_dump_context) const
4955 ast_dump_context->dump_type(this->type_);
4956 ast_dump_context->ostream() << "(";
4957 ast_dump_context->dump_expression(this->expr_);
4958 ast_dump_context->ostream() << ") ";
4961 // Make an unsafe type conversion expression.
4963 Expression*
4964 Expression::make_unsafe_cast(Type* type, Expression* expr,
4965 Location location)
4967 return new Unsafe_type_conversion_expression(type, expr, location);
4970 // Class Unary_expression.
4972 // Call the address_taken method of the operand if needed. This is
4973 // called after escape analysis but before inserting write barriers.
4975 void
4976 Unary_expression::check_operand_address_taken(Gogo*)
4978 if (this->op_ != OPERATOR_AND)
4979 return;
4981 // If this->escapes_ is false at this point, then it was set to
4982 // false by an explicit call to set_does_not_escape, and the value
4983 // does not escape. If this->escapes_ is true, we may be able to
4984 // set it to false based on the escape analysis pass.
4985 if (this->escapes_)
4987 Node* n = Node::make_node(this);
4988 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4989 this->escapes_ = false;
4992 this->expr_->address_taken(this->escapes_);
4995 // If we are taking the address of a composite literal, and the
4996 // contents are not constant, then we want to make a heap expression
4997 // instead.
4999 Expression*
5000 Unary_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*)
5002 Location loc = this->location();
5004 if (this->is_error_expression())
5005 return Expression::make_error(loc);
5007 Operator op = this->op_;
5008 Expression* expr = this->expr_;
5010 if (expr->is_error_expression())
5011 return Expression::make_error(loc);
5013 if (op == OPERATOR_MULT && expr->is_type_expression())
5015 Expression* ret =
5016 Expression::make_type(Type::make_pointer_type(expr->type()), loc);
5017 ret->determine_type_no_context(gogo);
5018 return ret;
5021 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
5022 // moving x to the heap. FIXME: Is it worth doing a real escape
5023 // analysis here? This case is found in math/unsafe.go and is
5024 // therefore worth special casing.
5025 if (op == OPERATOR_MULT)
5027 Expression* e = expr;
5028 while (e->classification() == EXPRESSION_CONVERSION)
5030 Type_conversion_expression* te
5031 = static_cast<Type_conversion_expression*>(e);
5032 e = te->expr();
5035 if (e->classification() == EXPRESSION_UNARY)
5037 Unary_expression* ue = static_cast<Unary_expression*>(e);
5038 if (ue->op_ == OPERATOR_AND)
5040 if (e == expr)
5042 // *&x == x.
5043 if (!ue->expr_->is_addressable() && !ue->create_temp_)
5045 go_error_at(ue->location(),
5046 "invalid operand for unary %<&%>");
5047 this->set_is_error();
5049 return ue->expr_;
5051 ue->set_does_not_escape();
5056 // Check for an invalid pointer dereference. We need to do this
5057 // here because Unary_expression::do_type will return an error type
5058 // in this case. That can cause code to appear erroneous, and
5059 // therefore disappear at lowering time, without any error message.
5060 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
5062 this->report_error(_("expected pointer"));
5063 return Expression::make_error(this->location());
5066 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
5068 Numeric_constant nc;
5069 if (expr->numeric_constant_value(&nc))
5071 Numeric_constant result;
5072 bool issued_error;
5073 if (Unary_expression::eval_constant(this->type_, op, &nc, loc,
5074 &result, &issued_error))
5076 Expression* ret = result.expression(loc);
5077 Type_context subcontext(this->type_, this->type_->is_abstract());
5078 ret->determine_type(gogo, &subcontext);
5079 ret->check_types(gogo);
5080 return ret;
5082 else if (issued_error)
5083 return Expression::make_error(this->location());
5087 return this;
5090 // Flatten expression if a nil check must be performed and create temporary
5091 // variables if necessary.
5093 Expression*
5094 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
5095 Statement_inserter* inserter)
5097 if (this->is_error_expression()
5098 || this->expr_->is_error_expression()
5099 || this->expr_->type()->is_error_type())
5101 go_assert(saw_errors());
5102 return Expression::make_error(this->location());
5105 Location location = this->location();
5106 if (this->op_ == OPERATOR_MULT
5107 && !this->expr_->is_multi_eval_safe())
5109 go_assert(this->expr_->type()->points_to() != NULL);
5110 switch (this->requires_nil_check(gogo))
5112 case NIL_CHECK_ERROR_ENCOUNTERED:
5114 go_assert(saw_errors());
5115 return Expression::make_error(this->location());
5117 case NIL_CHECK_NOT_NEEDED:
5118 break;
5119 case NIL_CHECK_NEEDED:
5120 this->create_temp_ = true;
5121 break;
5122 case NIL_CHECK_DEFAULT:
5123 go_unreachable();
5127 if (this->create_temp_ && !this->expr_->is_multi_eval_safe())
5129 Temporary_statement* temp =
5130 Statement::make_temporary(NULL, this->expr_, location);
5131 inserter->insert(temp);
5132 this->expr_ = Expression::make_temporary_reference(temp, location);
5135 return this;
5138 // Return whether a unary expression is a constant.
5140 bool
5141 Unary_expression::do_is_constant() const
5143 if (this->op_ == OPERATOR_MULT || this->op_ == OPERATOR_AND)
5145 // These are not constant by Go language rules.
5146 return false;
5148 else
5149 return this->expr_->is_constant();
5152 bool
5153 Unary_expression::do_is_untyped(Type** ptype) const
5155 if (this->type_ != NULL)
5156 return Expression::is_untyped_type(this->type_, ptype);
5158 if (this->op_ == OPERATOR_MULT || this->op_ == OPERATOR_AND)
5159 return false;
5160 return this->expr_->is_untyped(ptype);
5163 // Return whether a unary expression can be used as a constant
5164 // initializer.
5166 bool
5167 Unary_expression::do_is_static_initializer() const
5169 if (this->op_ == OPERATOR_MULT)
5170 return false;
5171 else if (this->op_ == OPERATOR_AND)
5172 return Unary_expression::base_is_static_initializer(this->expr_);
5173 else
5174 return this->expr_->is_static_initializer();
5177 // Return whether the address of EXPR can be used as a static
5178 // initializer.
5180 bool
5181 Unary_expression::base_is_static_initializer(Expression* expr)
5183 // The address of a field reference can be a static initializer if
5184 // the base can be a static initializer.
5185 Field_reference_expression* fre = expr->field_reference_expression();
5186 if (fre != NULL)
5187 return Unary_expression::base_is_static_initializer(fre->expr());
5189 // The address of an index expression can be a static initializer if
5190 // the base can be a static initializer and the index is constant.
5191 Array_index_expression* aind = expr->array_index_expression();
5192 if (aind != NULL)
5193 return (aind->end() == NULL
5194 && aind->start()->is_constant()
5195 && Unary_expression::base_is_static_initializer(aind->array()));
5197 // The address of a global variable can be a static initializer.
5198 Var_expression* ve = expr->var_expression();
5199 if (ve != NULL)
5201 Named_object* no = ve->named_object();
5202 return no->is_variable() && no->var_value()->is_global();
5205 // The address of a composite literal can be used as a static
5206 // initializer if the composite literal is itself usable as a
5207 // static initializer.
5208 if (expr->is_composite_literal() && expr->is_static_initializer())
5209 return true;
5211 // The address of a string constant can be used as a static
5212 // initializer. This can not be written in Go itself but this is
5213 // used when building a type descriptor.
5214 if (expr->string_expression() != NULL)
5215 return true;
5217 return false;
5220 // Return whether this dereference expression requires an explicit nil
5221 // check. If we are dereferencing the pointer to a large struct
5222 // (greater than the specified size threshold), we need to check for
5223 // nil. We don't bother to check for small structs because we expect
5224 // the system to crash on a nil pointer dereference. However, if we
5225 // know the address of this expression is being taken, we must always
5226 // check for nil.
5227 Unary_expression::Nil_check_classification
5228 Unary_expression::requires_nil_check(Gogo* gogo)
5230 go_assert(this->op_ == OPERATOR_MULT);
5231 go_assert(this->expr_->type()->points_to() != NULL);
5233 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
5234 return NIL_CHECK_NEEDED;
5235 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
5236 return NIL_CHECK_NOT_NEEDED;
5238 Type* ptype = this->expr_->type()->points_to();
5239 int64_t type_size = -1;
5240 if (!ptype->is_void_type())
5242 bool ok = ptype->backend_type_size(gogo, &type_size);
5243 if (!ok)
5244 return NIL_CHECK_ERROR_ENCOUNTERED;
5247 int64_t size_cutoff = gogo->nil_check_size_threshold();
5248 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
5249 this->issue_nil_check_ = NIL_CHECK_NEEDED;
5250 else
5251 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
5252 return this->issue_nil_check_;
5255 // Apply unary opcode OP to UNC, setting NC. Return true if this
5256 // could be done, false if not. On overflow, issues an error and sets
5257 // *ISSUED_ERROR.
5259 bool
5260 Unary_expression::eval_constant(Type* type, Operator op,
5261 const Numeric_constant* unc,
5262 Location location, Numeric_constant* nc,
5263 bool* issued_error)
5265 *issued_error = false;
5266 switch (op)
5268 case OPERATOR_PLUS:
5269 *nc = *unc;
5270 return true;
5272 case OPERATOR_MINUS:
5273 if (unc->is_int() || unc->is_rune())
5274 break;
5275 else if (unc->is_float())
5277 mpfr_t uval;
5278 unc->get_float(&uval);
5279 mpfr_t val;
5280 mpfr_init(val);
5281 mpfr_neg(val, uval, MPFR_RNDN);
5282 Type* utype = unc->type();
5283 if (type != NULL
5284 && type->is_abstract()
5285 && type->is_numeric_type())
5286 utype = type;
5287 nc->set_float(utype, val);
5288 mpfr_clear(uval);
5289 mpfr_clear(val);
5290 return true;
5292 else if (unc->is_complex())
5294 mpc_t uval;
5295 unc->get_complex(&uval);
5296 mpc_t val;
5297 mpc_init2(val, mpc_precision);
5298 mpc_neg(val, uval, MPC_RNDNN);
5299 Type* utype = unc->type();
5300 if (type != NULL
5301 && type->is_abstract()
5302 && type->is_numeric_type())
5303 utype = type;
5304 nc->set_complex(utype, val);
5305 mpc_clear(uval);
5306 mpc_clear(val);
5307 return true;
5309 else
5310 go_unreachable();
5312 case OPERATOR_XOR:
5313 break;
5315 case OPERATOR_NOT:
5316 case OPERATOR_AND:
5317 case OPERATOR_MULT:
5318 return false;
5320 default:
5321 go_unreachable();
5324 if (!unc->is_int() && !unc->is_rune())
5325 return false;
5327 mpz_t uval;
5328 if (unc->is_rune())
5329 unc->get_rune(&uval);
5330 else
5331 unc->get_int(&uval);
5332 mpz_t val;
5333 mpz_init(val);
5335 switch (op)
5337 case OPERATOR_MINUS:
5338 mpz_neg(val, uval);
5339 break;
5341 case OPERATOR_NOT:
5342 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
5343 break;
5345 case OPERATOR_XOR:
5347 Type* utype = unc->type();
5348 if (utype->integer_type() == NULL
5349 || utype->integer_type()->is_abstract())
5350 mpz_com(val, uval);
5351 else
5353 // The number of HOST_WIDE_INTs that it takes to represent
5354 // UVAL.
5355 size_t count = ((mpz_sizeinbase(uval, 2)
5356 + HOST_BITS_PER_WIDE_INT
5357 - 1)
5358 / HOST_BITS_PER_WIDE_INT);
5360 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
5361 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
5363 size_t obits = utype->integer_type()->bits();
5365 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
5367 mpz_t adj;
5368 mpz_init_set_ui(adj, 1);
5369 mpz_mul_2exp(adj, adj, obits);
5370 mpz_add(uval, uval, adj);
5371 mpz_clear(adj);
5374 size_t ecount;
5375 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
5376 go_assert(ecount <= count);
5378 // Trim down to the number of words required by the type.
5379 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
5380 / HOST_BITS_PER_WIDE_INT);
5381 go_assert(ocount <= count);
5383 for (size_t i = 0; i < ocount; ++i)
5384 phwi[i] = ~phwi[i];
5386 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
5387 if (clearbits != 0)
5388 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
5389 >> clearbits);
5391 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
5393 if (!utype->integer_type()->is_unsigned()
5394 && mpz_tstbit(val, obits - 1))
5396 mpz_t adj;
5397 mpz_init_set_ui(adj, 1);
5398 mpz_mul_2exp(adj, adj, obits);
5399 mpz_sub(val, val, adj);
5400 mpz_clear(adj);
5403 delete[] phwi;
5406 break;
5408 default:
5409 go_unreachable();
5412 if (unc->is_rune())
5413 nc->set_rune(NULL, val);
5414 else
5415 nc->set_int(NULL, val);
5417 mpz_clear(uval);
5418 mpz_clear(val);
5420 if (!nc->set_type(unc->type(), true, location))
5422 *issued_error = true;
5423 return false;
5425 return true;
5428 // Return the integral constant value of a unary expression, if it has one.
5430 bool
5431 Unary_expression::do_numeric_constant_value(Numeric_constant* nc)
5433 if (this->is_error_expression())
5434 return false;
5436 Numeric_constant unc;
5437 if (!this->expr_->numeric_constant_value(&unc))
5438 return false;
5439 bool issued_error;
5440 bool r = Unary_expression::eval_constant(this->type_, this->op_, &unc,
5441 this->location(), nc,
5442 &issued_error);
5443 if (issued_error)
5444 this->set_is_error();
5445 return r;
5448 // Return the boolean constant value of a unary expression, if it has one.
5450 bool
5451 Unary_expression::do_boolean_constant_value(bool* val)
5453 if (this->op_ == OPERATOR_NOT
5454 && this->expr_->boolean_constant_value(val))
5456 *val = !*val;
5457 return true;
5459 return false;
5462 // Return the type of a unary expression.
5464 Type*
5465 Unary_expression::do_type()
5467 if (this->type_ == NULL)
5469 switch (this->op_)
5471 case OPERATOR_AND:
5472 return Type::make_pointer_type(this->expr_->type());
5474 case OPERATOR_MULT:
5476 if (this->expr_->is_type_expression())
5477 return Type::make_pointer_type(this->expr_->type());
5479 Type* subtype = this->expr_->type();
5480 Type* points_to = subtype->points_to();
5481 if (points_to == NULL)
5483 this->report_error(_("expected pointer"));
5484 this->type_ = Type::make_error_type();
5485 return this->type_;
5487 return points_to;
5490 default:
5491 go_assert(saw_errors());
5492 return Type::make_error_type();
5496 return this->type_;
5499 // Determine abstract types for a unary expression.
5501 void
5502 Unary_expression::do_determine_type(Gogo* gogo, const Type_context* context)
5504 switch (this->op_)
5506 case OPERATOR_PLUS:
5507 case OPERATOR_MINUS:
5508 case OPERATOR_NOT:
5509 case OPERATOR_XOR:
5511 if (this->type_ != NULL)
5512 return;
5514 Type* dummy;
5515 Type_context subcontext(*context);
5516 if (this->expr_->is_untyped(&dummy) && this->expr_->is_constant())
5518 // We evaluate an untyped operator as untyped. Then we
5519 // convert it to the desired type. Otherwise we may, for
5520 // example, give a useless error for one more than the
5521 // most positive integer when it is the operand of a unary
5522 // minus.
5523 subcontext.type = NULL;
5524 subcontext.may_be_abstract = true;
5526 this->expr_->determine_type(gogo, &subcontext);
5528 this->type_ = this->expr_->type();
5530 // If this is an untyped expression in a typed context, use
5531 // the context type. If this doesn't work we'll report an
5532 // error later.
5533 if (this->type_->is_abstract()
5534 && !context->may_be_abstract
5535 && context->type != NULL)
5537 if (context->type->interface_type() == NULL)
5538 this->type_ = context->type;
5539 else
5540 this->type_ = this->type_->make_non_abstract_type();
5543 break;
5545 case OPERATOR_AND:
5546 // Taking the address of something.
5548 Type* subtype = (context->type == NULL
5549 ? NULL
5550 : context->type->points_to());
5551 Type_context subcontext(subtype, false);
5552 this->expr_->determine_type(gogo, &subcontext);
5554 break;
5556 case OPERATOR_MULT:
5558 if (this->expr_->is_type_expression())
5560 this->expr_->determine_type_no_context(gogo);
5561 return;
5564 // Indirecting through a pointer.
5565 Type* subtype = (context->type == NULL
5566 ? NULL
5567 : Type::make_pointer_type(context->type));
5568 Type_context subcontext(subtype, false);
5569 this->expr_->determine_type(gogo, &subcontext);
5571 break;
5573 default:
5574 go_unreachable();
5578 // Check types for a unary expression.
5580 void
5581 Unary_expression::do_check_types(Gogo*)
5583 if (this->is_error_expression())
5584 return;
5586 Type* type = this->expr_->type();
5587 if (type->is_error())
5589 this->set_is_error();
5590 return;
5593 switch (this->op_)
5595 case OPERATOR_PLUS:
5596 case OPERATOR_MINUS:
5597 if (type->integer_type() == NULL
5598 && type->float_type() == NULL
5599 && type->complex_type() == NULL)
5600 this->report_error(_("expected numeric type"));
5601 break;
5603 case OPERATOR_NOT:
5604 if (!type->is_boolean_type())
5605 this->report_error(_("expected boolean type"));
5606 break;
5608 case OPERATOR_XOR:
5609 if (type->integer_type() == NULL)
5610 this->report_error(_("expected integer"));
5611 break;
5613 case OPERATOR_AND:
5614 if (!this->expr_->is_addressable())
5616 if (!this->create_temp_)
5618 go_error_at(this->location(), "invalid operand for unary %<&%>");
5619 this->set_is_error();
5622 else
5623 this->expr_->issue_nil_check();
5624 break;
5626 case OPERATOR_MULT:
5627 if (this->expr_->is_type_expression())
5628 break;
5630 // Catching an invalid indirection of unsafe.Pointer here avoid
5631 // having to deal with TYPE_VOID in other places.
5632 if (this->expr_->type()->is_unsafe_pointer_type())
5634 go_error_at(this->location(),
5635 "invalid indirect of %<unsafe.Pointer%>");
5636 this->set_is_error();
5637 return;
5640 // Indirecting through a pointer.
5641 if (type->points_to() == NULL)
5642 this->report_error(_("expected pointer"));
5643 if (type->points_to()->is_error())
5644 this->set_is_error();
5645 break;
5647 default:
5648 go_unreachable();
5652 // Get the backend representation for a unary expression.
5654 Bexpression*
5655 Unary_expression::do_get_backend(Translate_context* context)
5657 Gogo* gogo = context->gogo();
5658 Location loc = this->location();
5660 // Taking the address of a set-and-use-temporary expression requires
5661 // setting the temporary and then taking the address.
5662 if (this->op_ == OPERATOR_AND)
5664 Set_and_use_temporary_expression* sut =
5665 this->expr_->set_and_use_temporary_expression();
5666 if (sut != NULL)
5668 Temporary_statement* temp = sut->temporary();
5669 Bvariable* bvar = temp->get_backend_variable(context);
5670 Bexpression* bvar_expr =
5671 gogo->backend()->var_expression(bvar, loc);
5672 Bexpression* bval = sut->expression()->get_backend(context);
5674 Named_object* fn = context->function();
5675 go_assert(fn != NULL);
5676 Bfunction* bfn =
5677 fn->func_value()->get_or_make_decl(gogo, fn);
5678 Bstatement* bassign =
5679 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5680 Bexpression* bvar_addr =
5681 gogo->backend()->address_expression(bvar_expr, loc);
5682 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5686 Bexpression* ret;
5687 Bexpression* bexpr = this->expr_->get_backend(context);
5688 Btype* btype = (this->type_ == NULL
5689 ? this->expr_->type()->get_backend(gogo)
5690 : this->type_->get_backend(gogo));
5691 switch (this->op_)
5693 case OPERATOR_PLUS:
5694 ret = gogo->backend()->convert_expression(btype, bexpr, loc);
5695 break;
5697 case OPERATOR_MINUS:
5698 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5699 ret = gogo->backend()->convert_expression(btype, ret, loc);
5700 break;
5702 case OPERATOR_NOT:
5703 case OPERATOR_XOR:
5704 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5705 ret = gogo->backend()->convert_expression(btype, ret, loc);
5706 break;
5708 case OPERATOR_AND:
5709 if (!this->create_temp_)
5711 // We should not see a non-constant constructor here; cases
5712 // where we would see one should have been moved onto the
5713 // heap at parse time. Taking the address of a nonconstant
5714 // constructor will not do what the programmer expects.
5716 go_assert(!this->expr_->is_composite_literal()
5717 || this->expr_->is_static_initializer());
5718 if (this->expr_->classification() == EXPRESSION_UNARY)
5720 Unary_expression* ue =
5721 static_cast<Unary_expression*>(this->expr_);
5722 go_assert(ue->op() != OPERATOR_AND);
5726 if (this->is_gc_root_ || this->is_slice_init_)
5728 std::string var_name;
5729 bool copy_to_heap = false;
5730 if (this->is_gc_root_)
5732 // Build a decl for a GC root variable. GC roots are mutable, so
5733 // they cannot be represented as an immutable_struct in the
5734 // backend.
5735 var_name = gogo->gc_root_name();
5737 else
5739 // Build a decl for a slice value initializer. An immutable slice
5740 // value initializer may have to be copied to the heap if it
5741 // contains pointers in a non-constant context.
5742 var_name = gogo->initializer_name();
5744 Array_type* at = this->expr_->type()->array_type();
5745 go_assert(at != NULL);
5747 // If we are not copying the value to the heap, we will only
5748 // initialize the value once, so we can use this directly
5749 // rather than copying it. In that case we can't make it
5750 // read-only, because the program is permitted to change it.
5751 copy_to_heap = (context->function() != NULL
5752 || context->is_const());
5754 unsigned int flags = (Backend::variable_is_hidden
5755 | Backend::variable_address_is_taken);
5756 if (copy_to_heap)
5757 flags |= Backend::variable_is_constant;
5758 Bvariable* implicit =
5759 gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
5760 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5761 flags, bexpr);
5762 bexpr = gogo->backend()->var_expression(implicit, loc);
5764 // If we are not copying a slice initializer to the heap,
5765 // then it can be changed by the program, so if it can
5766 // contain pointers we must register it as a GC root.
5767 if (this->is_slice_init_
5768 && !copy_to_heap
5769 && this->expr_->type()->has_pointer())
5771 Bexpression* root =
5772 gogo->backend()->var_expression(implicit, loc);
5773 root = gogo->backend()->address_expression(root, loc);
5774 Type* type = Type::make_pointer_type(this->expr_->type());
5775 gogo->add_gc_root(Expression::make_backend(root, type, loc));
5778 else if ((this->expr_->is_composite_literal()
5779 || this->expr_->string_expression() != NULL)
5780 && this->expr_->is_static_initializer())
5782 std::string var_name(gogo->initializer_name());
5783 unsigned int flags = (Backend::variable_is_hidden
5784 | Backend::variable_address_is_taken);
5785 Bvariable* decl =
5786 gogo->backend()->immutable_struct(var_name, "", flags, btype, loc);
5787 gogo->backend()->immutable_struct_set_init(decl, var_name, flags,
5788 btype, loc, bexpr);
5789 bexpr = gogo->backend()->var_expression(decl, loc);
5791 else if (this->expr_->is_constant())
5793 std::string var_name(gogo->initializer_name());
5794 unsigned int flags = (Backend::variable_is_hidden
5795 | Backend::variable_is_constant
5796 | Backend::variable_address_is_taken);
5797 Bvariable* decl =
5798 gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
5799 gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5800 flags, bexpr);
5801 bexpr = gogo->backend()->var_expression(decl, loc);
5804 go_assert(!this->create_temp_ || this->expr_->is_multi_eval_safe());
5805 ret = gogo->backend()->address_expression(bexpr, loc);
5806 break;
5808 case OPERATOR_MULT:
5810 go_assert(this->expr_->type()->points_to() != NULL);
5812 Type* ptype = this->expr_->type()->points_to();
5813 Btype* pbtype = ptype->get_backend(gogo);
5814 switch (this->requires_nil_check(gogo))
5816 case NIL_CHECK_NOT_NEEDED:
5817 break;
5818 case NIL_CHECK_ERROR_ENCOUNTERED:
5820 go_assert(saw_errors());
5821 return gogo->backend()->error_expression();
5823 case NIL_CHECK_NEEDED:
5825 go_assert(this->expr_->is_multi_eval_safe());
5827 // If we're nil-checking the result of a set-and-use-temporary
5828 // expression, then pick out the target temp and use that
5829 // for the final result of the conditional.
5830 Bexpression* tbexpr = bexpr;
5831 Bexpression* ubexpr = bexpr;
5832 Set_and_use_temporary_expression* sut =
5833 this->expr_->set_and_use_temporary_expression();
5834 if (sut != NULL) {
5835 Temporary_statement* temp = sut->temporary();
5836 Bvariable* bvar = temp->get_backend_variable(context);
5837 ubexpr = gogo->backend()->var_expression(bvar, loc);
5839 Bexpression* nil =
5840 Expression::make_nil(loc)->get_backend(context);
5841 Bexpression* compare =
5842 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5843 nil, loc);
5844 Expression* crash = Runtime::make_call(gogo, Runtime::PANIC_MEM,
5845 loc, 0);
5846 crash->determine_type_no_context(gogo);
5847 Bexpression* bcrash = crash->get_backend(context);
5848 Bfunction* bfn = context->function()->func_value()->get_decl();
5849 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5850 compare,
5851 bcrash, ubexpr,
5852 loc);
5853 break;
5855 case NIL_CHECK_DEFAULT:
5856 go_unreachable();
5858 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
5860 break;
5862 default:
5863 go_unreachable();
5866 return ret;
5869 // Export a unary expression.
5871 void
5872 Unary_expression::do_export(Export_function_body* efb) const
5874 switch (this->op_)
5876 case OPERATOR_PLUS:
5877 efb->write_c_string("+");
5878 break;
5879 case OPERATOR_MINUS:
5880 efb->write_c_string("-");
5881 break;
5882 case OPERATOR_NOT:
5883 efb->write_c_string("!");
5884 break;
5885 case OPERATOR_XOR:
5886 efb->write_c_string("^");
5887 break;
5888 case OPERATOR_AND:
5889 efb->write_c_string("&");
5890 break;
5891 case OPERATOR_MULT:
5892 efb->write_c_string("*");
5893 break;
5894 default:
5895 go_unreachable();
5897 this->expr_->export_expression(efb);
5900 // Import a unary expression.
5902 Expression*
5903 Unary_expression::do_import(Import_expression* imp, Location loc)
5905 Operator op;
5906 switch (imp->get_char())
5908 case '+':
5909 op = OPERATOR_PLUS;
5910 break;
5911 case '-':
5912 op = OPERATOR_MINUS;
5913 break;
5914 case '!':
5915 op = OPERATOR_NOT;
5916 break;
5917 case '^':
5918 op = OPERATOR_XOR;
5919 break;
5920 case '&':
5921 op = OPERATOR_AND;
5922 break;
5923 case '*':
5924 op = OPERATOR_MULT;
5925 break;
5926 default:
5927 go_unreachable();
5929 if (imp->version() < EXPORT_FORMAT_V3)
5930 imp->require_c_string(" ");
5931 Expression* expr = Expression::import_expression(imp, loc);
5932 return Expression::make_unary(op, expr, loc);
5935 // Dump ast representation of an unary expression.
5937 void
5938 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5940 ast_dump_context->dump_operator(this->op_);
5941 ast_dump_context->ostream() << "(";
5942 ast_dump_context->dump_expression(this->expr_);
5943 ast_dump_context->ostream() << ") ";
5946 // Make a unary expression.
5948 Expression*
5949 Expression::make_unary(Operator op, Expression* expr, Location location)
5951 return new Unary_expression(op, expr, location);
5954 Expression*
5955 Expression::make_dereference(Expression* ptr,
5956 Nil_check_classification docheck,
5957 Location location)
5959 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5960 if (docheck == NIL_CHECK_NEEDED)
5961 deref->unary_expression()->set_requires_nil_check(true);
5962 else if (docheck == NIL_CHECK_NOT_NEEDED)
5963 deref->unary_expression()->set_requires_nil_check(false);
5964 return deref;
5967 // If this is an indirection through a pointer, return the expression
5968 // being pointed through. Otherwise return this.
5970 Expression*
5971 Expression::deref()
5973 if (this->classification_ == EXPRESSION_UNARY)
5975 Unary_expression* ue = static_cast<Unary_expression*>(this);
5976 if (ue->op() == OPERATOR_MULT)
5977 return ue->operand();
5979 return this;
5982 // Class Binary_expression.
5984 // Traversal.
5987 Binary_expression::do_traverse(Traverse* traverse)
5989 int t = Expression::traverse(&this->left_, traverse);
5990 if (t == TRAVERSE_EXIT)
5991 return TRAVERSE_EXIT;
5992 return Expression::traverse(&this->right_, traverse);
5995 // Return whether a binary expression is untyped.
5997 bool
5998 Binary_expression::do_is_untyped(Type** ptype) const
6000 if (this->type_ != NULL)
6001 return Expression::is_untyped_type(this->type_, ptype);
6003 switch (this->op_)
6005 case OPERATOR_EQEQ:
6006 case OPERATOR_NOTEQ:
6007 case OPERATOR_LT:
6008 case OPERATOR_LE:
6009 case OPERATOR_GT:
6010 case OPERATOR_GE:
6011 // Comparisons are untyped by default.
6012 *ptype = Type::make_boolean_type();
6013 return true;
6015 case OPERATOR_LSHIFT:
6016 case OPERATOR_RSHIFT:
6017 // A shift operation is untyped if the left hand expression is
6018 // untyped. The right hand expression is irrelevant.
6019 return this->left_->is_untyped(ptype);
6021 default:
6022 break;
6025 Type* tleft;
6026 Type* tright;
6027 if (!this->left_->is_untyped(&tleft)
6028 || !this->right_->is_untyped(&tright))
6029 return false;
6031 // If both sides are numeric, pick a type based on the kind.
6032 enum kind { INT, RUNE, FLOAT, COMPLEX };
6033 enum kind kleft, kright;
6035 if (tleft->integer_type() != NULL)
6036 kleft = tleft->integer_type()->is_rune() ? RUNE : INT;
6037 else if (tleft->float_type() != NULL)
6038 kleft = FLOAT;
6039 else if (tleft->complex_type() != NULL)
6040 kleft = COMPLEX;
6041 else
6043 // Not numeric. If the types are different, we will report an
6044 // error later.
6045 *ptype = tleft;
6046 return true;
6049 if (tright->integer_type() != NULL)
6050 kright = tright->integer_type()->is_rune() ? RUNE : INT;
6051 else if (tright->float_type() != NULL)
6052 kright = FLOAT;
6053 else if (tright->complex_type() != NULL)
6054 kright = COMPLEX;
6055 else
6057 // Types are different. We will report an error later.
6058 *ptype = tleft;
6059 return true;
6062 if (kleft > kright)
6063 *ptype = tleft;
6064 else
6065 *ptype = tright;
6067 return true;
6070 // Return whether this expression may be used as a static initializer.
6072 bool
6073 Binary_expression::do_is_static_initializer() const
6075 if (!this->left_->is_static_initializer()
6076 || !this->right_->is_static_initializer())
6077 return false;
6079 // Addresses can be static initializers, but we can't implement
6080 // arbitray binary expressions of them.
6081 Unary_expression* lu = this->left_->unary_expression();
6082 Unary_expression* ru = this->right_->unary_expression();
6083 if (lu != NULL && lu->op() == OPERATOR_AND)
6085 if (ru != NULL && ru->op() == OPERATOR_AND)
6086 return this->op_ == OPERATOR_MINUS;
6087 else
6088 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
6090 else if (ru != NULL && ru->op() == OPERATOR_AND)
6091 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
6093 // Other cases should resolve in the backend.
6094 return true;
6097 // Return the type to use for a binary operation on operands of
6098 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
6099 // such may be NULL or abstract.
6101 bool
6102 Binary_expression::operation_type(Operator op, Type* left_type,
6103 Type* right_type, Type** result_type)
6105 if (left_type != right_type
6106 && !left_type->is_abstract()
6107 && !right_type->is_abstract()
6108 && left_type->base() != right_type->base()
6109 && op != OPERATOR_LSHIFT
6110 && op != OPERATOR_RSHIFT)
6112 // May be a type error--let it be diagnosed elsewhere.
6113 return false;
6116 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
6118 if (left_type->integer_type() != NULL)
6119 *result_type = left_type;
6120 else
6121 *result_type = Type::make_abstract_integer_type();
6123 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
6124 *result_type = left_type;
6125 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
6126 *result_type = right_type;
6127 else if (!left_type->is_abstract())
6128 *result_type = left_type;
6129 else if (!right_type->is_abstract())
6130 *result_type = right_type;
6131 else if (left_type->complex_type() != NULL)
6132 *result_type = left_type;
6133 else if (right_type->complex_type() != NULL)
6134 *result_type = right_type;
6135 else if (left_type->float_type() != NULL)
6136 *result_type = left_type;
6137 else if (right_type->float_type() != NULL)
6138 *result_type = right_type;
6139 else if (left_type->integer_type() != NULL
6140 && left_type->integer_type()->is_rune())
6141 *result_type = left_type;
6142 else if (right_type->integer_type() != NULL
6143 && right_type->integer_type()->is_rune())
6144 *result_type = right_type;
6145 else
6146 *result_type = left_type;
6148 return true;
6151 // Convert an integer comparison code and an operator to a boolean
6152 // value.
6154 bool
6155 Binary_expression::cmp_to_bool(Operator op, int cmp)
6157 switch (op)
6159 case OPERATOR_EQEQ:
6160 return cmp == 0;
6161 break;
6162 case OPERATOR_NOTEQ:
6163 return cmp != 0;
6164 break;
6165 case OPERATOR_LT:
6166 return cmp < 0;
6167 break;
6168 case OPERATOR_LE:
6169 return cmp <= 0;
6170 case OPERATOR_GT:
6171 return cmp > 0;
6172 case OPERATOR_GE:
6173 return cmp >= 0;
6174 default:
6175 go_unreachable();
6179 // Compare constants according to OP.
6181 bool
6182 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
6183 Numeric_constant* right_nc,
6184 Location location, bool* result)
6186 Type* left_type = left_nc->type();
6187 Type* right_type = right_nc->type();
6189 Type* type;
6190 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
6191 return false;
6193 // When comparing an untyped operand to a typed operand, we are
6194 // effectively coercing the untyped operand to the other operand's
6195 // type, so make sure that is valid.
6196 if (!left_nc->set_type(type, true, location)
6197 || !right_nc->set_type(type, true, location))
6198 return false;
6200 bool ret;
6201 int cmp;
6202 if (type->complex_type() != NULL)
6204 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
6205 return false;
6206 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
6208 else if (type->float_type() != NULL)
6209 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
6210 else
6211 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
6213 if (ret)
6214 *result = Binary_expression::cmp_to_bool(op, cmp);
6216 return ret;
6219 // Compare integer constants.
6221 bool
6222 Binary_expression::compare_integer(const Numeric_constant* left_nc,
6223 const Numeric_constant* right_nc,
6224 int* cmp)
6226 mpz_t left_val;
6227 if (!left_nc->to_int(&left_val))
6228 return false;
6229 mpz_t right_val;
6230 if (!right_nc->to_int(&right_val))
6232 mpz_clear(left_val);
6233 return false;
6236 *cmp = mpz_cmp(left_val, right_val);
6238 mpz_clear(left_val);
6239 mpz_clear(right_val);
6241 return true;
6244 // Compare floating point constants.
6246 bool
6247 Binary_expression::compare_float(const Numeric_constant* left_nc,
6248 const Numeric_constant* right_nc,
6249 int* cmp)
6251 mpfr_t left_val;
6252 if (!left_nc->to_float(&left_val))
6253 return false;
6254 mpfr_t right_val;
6255 if (!right_nc->to_float(&right_val))
6257 mpfr_clear(left_val);
6258 return false;
6261 // We already coerced both operands to the same type. If that type
6262 // is not an abstract type, we need to round the values accordingly.
6263 Type* type = left_nc->type();
6264 if (!type->is_abstract() && type->float_type() != NULL)
6266 int bits = type->float_type()->bits();
6267 mpfr_prec_round(left_val, bits, MPFR_RNDN);
6268 mpfr_prec_round(right_val, bits, MPFR_RNDN);
6271 *cmp = mpfr_cmp(left_val, right_val);
6273 mpfr_clear(left_val);
6274 mpfr_clear(right_val);
6276 return true;
6279 // Compare complex constants. Complex numbers may only be compared
6280 // for equality.
6282 bool
6283 Binary_expression::compare_complex(const Numeric_constant* left_nc,
6284 const Numeric_constant* right_nc,
6285 int* cmp)
6287 mpc_t left_val;
6288 if (!left_nc->to_complex(&left_val))
6289 return false;
6290 mpc_t right_val;
6291 if (!right_nc->to_complex(&right_val))
6293 mpc_clear(left_val);
6294 return false;
6297 // We already coerced both operands to the same type. If that type
6298 // is not an abstract type, we need to round the values accordingly.
6299 Type* type = left_nc->type();
6300 if (!type->is_abstract() && type->complex_type() != NULL)
6302 int bits = type->complex_type()->bits();
6303 mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
6304 mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
6305 mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
6306 mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
6309 *cmp = mpc_cmp(left_val, right_val) != 0;
6311 mpc_clear(left_val);
6312 mpc_clear(right_val);
6314 return true;
6317 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
6318 // true if this could be done, false if not. Issue errors at LOCATION
6319 // as appropriate, and sets *ISSUED_ERROR if it did.
6321 bool
6322 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
6323 Numeric_constant* right_nc,
6324 Location location, Numeric_constant* nc,
6325 bool* issued_error)
6327 *issued_error = false;
6328 switch (op)
6330 case OPERATOR_OROR:
6331 case OPERATOR_ANDAND:
6332 case OPERATOR_EQEQ:
6333 case OPERATOR_NOTEQ:
6334 case OPERATOR_LT:
6335 case OPERATOR_LE:
6336 case OPERATOR_GT:
6337 case OPERATOR_GE:
6338 // These return boolean values, not numeric.
6339 return false;
6340 default:
6341 break;
6344 Type* left_type = left_nc->type();
6345 Type* right_type = right_nc->type();
6347 Type* type;
6348 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
6349 return false;
6351 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
6353 // When combining an untyped operand with a typed operand, we are
6354 // effectively coercing the untyped operand to the other operand's
6355 // type, so make sure that is valid.
6356 if (!left_nc->set_type(type, true, location))
6357 return false;
6358 if (!is_shift && !right_nc->set_type(type, true, location))
6359 return false;
6360 if (is_shift
6361 && right_type->integer_type() == NULL
6362 && !right_type->is_abstract())
6363 return false;
6365 bool r;
6366 if (type->complex_type() != NULL)
6367 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc,
6368 issued_error);
6369 else if (type->float_type() != NULL)
6370 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc,
6371 issued_error);
6372 else
6373 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc,
6374 issued_error);
6376 if (r)
6378 r = nc->set_type(type, true, location);
6379 if (!r)
6380 *issued_error = true;
6383 return r;
6386 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6387 // integer operations. Return true if this could be done, false if
6388 // not.
6390 bool
6391 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
6392 const Numeric_constant* right_nc,
6393 Location location, Numeric_constant* nc,
6394 bool* issued_error)
6396 mpz_t left_val;
6397 if (!left_nc->to_int(&left_val))
6398 return false;
6399 mpz_t right_val;
6400 if (!right_nc->to_int(&right_val))
6402 mpz_clear(left_val);
6403 return false;
6406 mpz_t val;
6407 mpz_init(val);
6409 switch (op)
6411 case OPERATOR_PLUS:
6412 mpz_add(val, left_val, right_val);
6413 if (mpz_sizeinbase(val, 2) > 0x100000)
6415 go_error_at(location, "constant addition overflow");
6416 nc->set_invalid();
6417 mpz_set_ui(val, 1);
6418 *issued_error = true;
6420 break;
6421 case OPERATOR_MINUS:
6422 mpz_sub(val, left_val, right_val);
6423 if (mpz_sizeinbase(val, 2) > 0x100000)
6425 go_error_at(location, "constant subtraction overflow");
6426 nc->set_invalid();
6427 mpz_set_ui(val, 1);
6428 *issued_error = true;
6430 break;
6431 case OPERATOR_OR:
6432 mpz_ior(val, left_val, right_val);
6433 break;
6434 case OPERATOR_XOR:
6435 mpz_xor(val, left_val, right_val);
6436 break;
6437 case OPERATOR_MULT:
6438 mpz_mul(val, left_val, right_val);
6439 if (mpz_sizeinbase(val, 2) > 0x100000)
6441 go_error_at(location, "constant multiplication overflow");
6442 nc->set_invalid();
6443 mpz_set_ui(val, 1);
6444 *issued_error = true;
6446 break;
6447 case OPERATOR_DIV:
6448 if (mpz_sgn(right_val) != 0)
6449 mpz_tdiv_q(val, left_val, right_val);
6450 else
6452 go_error_at(location, "division by zero");
6453 nc->set_invalid();
6454 mpz_set_ui(val, 0);
6455 *issued_error = true;
6457 break;
6458 case OPERATOR_MOD:
6459 if (mpz_sgn(right_val) != 0)
6460 mpz_tdiv_r(val, left_val, right_val);
6461 else
6463 go_error_at(location, "division by zero");
6464 nc->set_invalid();
6465 mpz_set_ui(val, 0);
6466 *issued_error = true;
6468 break;
6469 case OPERATOR_LSHIFT:
6471 unsigned long shift = mpz_get_ui(right_val);
6472 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
6473 mpz_mul_2exp(val, left_val, shift);
6474 else
6476 go_error_at(location, "shift count overflow");
6477 nc->set_invalid();
6478 mpz_set_ui(val, 1);
6479 *issued_error = true;
6481 break;
6483 break;
6484 case OPERATOR_RSHIFT:
6486 unsigned long shift = mpz_get_ui(right_val);
6487 if (mpz_cmp_ui(right_val, shift) != 0)
6489 go_error_at(location, "shift count overflow");
6490 nc->set_invalid();
6491 mpz_set_ui(val, 1);
6492 *issued_error = true;
6494 else
6496 if (mpz_cmp_ui(left_val, 0) >= 0)
6497 mpz_tdiv_q_2exp(val, left_val, shift);
6498 else
6499 mpz_fdiv_q_2exp(val, left_val, shift);
6501 break;
6503 break;
6504 case OPERATOR_AND:
6505 mpz_and(val, left_val, right_val);
6506 break;
6507 case OPERATOR_BITCLEAR:
6509 mpz_t tval;
6510 mpz_init(tval);
6511 mpz_com(tval, right_val);
6512 mpz_and(val, left_val, tval);
6513 mpz_clear(tval);
6515 break;
6516 default:
6517 go_unreachable();
6520 mpz_clear(left_val);
6521 mpz_clear(right_val);
6523 if (left_nc->is_rune()
6524 || (op != OPERATOR_LSHIFT
6525 && op != OPERATOR_RSHIFT
6526 && right_nc->is_rune()))
6527 nc->set_rune(NULL, val);
6528 else
6529 nc->set_int(NULL, val);
6531 mpz_clear(val);
6533 return true;
6536 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6537 // floating point operations. Return true if this could be done,
6538 // false if not.
6540 bool
6541 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
6542 const Numeric_constant* right_nc,
6543 Location location, Numeric_constant* nc,
6544 bool* issued_error)
6546 mpfr_t left_val;
6547 if (!left_nc->to_float(&left_val))
6548 return false;
6549 mpfr_t right_val;
6550 if (!right_nc->to_float(&right_val))
6552 mpfr_clear(left_val);
6553 return false;
6556 mpfr_t val;
6557 mpfr_init(val);
6559 bool ret = true;
6560 switch (op)
6562 case OPERATOR_PLUS:
6563 mpfr_add(val, left_val, right_val, MPFR_RNDN);
6564 break;
6565 case OPERATOR_MINUS:
6566 mpfr_sub(val, left_val, right_val, MPFR_RNDN);
6567 break;
6568 case OPERATOR_OR:
6569 case OPERATOR_XOR:
6570 case OPERATOR_AND:
6571 case OPERATOR_BITCLEAR:
6572 case OPERATOR_MOD:
6573 case OPERATOR_LSHIFT:
6574 case OPERATOR_RSHIFT:
6575 mpfr_set_ui(val, 0, MPFR_RNDN);
6576 ret = false;
6577 break;
6578 case OPERATOR_MULT:
6579 mpfr_mul(val, left_val, right_val, MPFR_RNDN);
6580 break;
6581 case OPERATOR_DIV:
6582 if (!mpfr_zero_p(right_val))
6583 mpfr_div(val, left_val, right_val, MPFR_RNDN);
6584 else
6586 go_error_at(location, "division by zero");
6587 nc->set_invalid();
6588 mpfr_set_ui(val, 0, MPFR_RNDN);
6589 *issued_error = true;
6591 break;
6592 default:
6593 go_unreachable();
6596 mpfr_clear(left_val);
6597 mpfr_clear(right_val);
6599 nc->set_float(NULL, val);
6600 mpfr_clear(val);
6602 return ret;
6605 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6606 // complex operations. Return true if this could be done, false if
6607 // not.
6609 bool
6610 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
6611 const Numeric_constant* right_nc,
6612 Location location, Numeric_constant* nc,
6613 bool* issued_error)
6615 mpc_t left_val;
6616 if (!left_nc->to_complex(&left_val))
6617 return false;
6618 mpc_t right_val;
6619 if (!right_nc->to_complex(&right_val))
6621 mpc_clear(left_val);
6622 return false;
6625 mpc_t val;
6626 mpc_init2(val, mpc_precision);
6628 bool ret = true;
6629 switch (op)
6631 case OPERATOR_PLUS:
6632 mpc_add(val, left_val, right_val, MPC_RNDNN);
6633 break;
6634 case OPERATOR_MINUS:
6635 mpc_sub(val, left_val, right_val, MPC_RNDNN);
6636 break;
6637 case OPERATOR_OR:
6638 case OPERATOR_XOR:
6639 case OPERATOR_AND:
6640 case OPERATOR_BITCLEAR:
6641 case OPERATOR_MOD:
6642 case OPERATOR_LSHIFT:
6643 case OPERATOR_RSHIFT:
6644 mpc_set_ui(val, 0, MPC_RNDNN);
6645 ret = false;
6646 break;
6647 case OPERATOR_MULT:
6648 mpc_mul(val, left_val, right_val, MPC_RNDNN);
6649 break;
6650 case OPERATOR_DIV:
6651 if (mpc_cmp_si(right_val, 0) == 0)
6653 go_error_at(location, "division by zero");
6654 nc->set_invalid();
6655 mpc_set_ui(val, 0, MPC_RNDNN);
6656 *issued_error = true;
6657 break;
6659 mpc_div(val, left_val, right_val, MPC_RNDNN);
6660 break;
6661 default:
6662 go_unreachable();
6665 mpc_clear(left_val);
6666 mpc_clear(right_val);
6668 nc->set_complex(NULL, val);
6669 mpc_clear(val);
6671 return ret;
6674 // Lower a binary expression. We have to evaluate constant
6675 // expressions now, in order to implement Go's unlimited precision
6676 // constants.
6678 Expression*
6679 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6680 Statement_inserter* inserter)
6682 Location location = this->location();
6684 if (this->is_error_expression())
6685 return Expression::make_error(location);
6687 Operator op = this->op_;
6688 Expression* left = this->left_;
6689 Expression* right = this->right_;
6691 if (left->is_error_expression() || right->is_error_expression())
6692 return Expression::make_error(location);
6694 const bool is_comparison = (op == OPERATOR_EQEQ
6695 || op == OPERATOR_NOTEQ
6696 || op == OPERATOR_LT
6697 || op == OPERATOR_LE
6698 || op == OPERATOR_GT
6699 || op == OPERATOR_GE);
6701 // Numeric constant expressions.
6703 Numeric_constant left_nc;
6704 Numeric_constant right_nc;
6705 if (left->numeric_constant_value(&left_nc)
6706 && right->numeric_constant_value(&right_nc))
6708 Expression* ret;
6709 if (is_comparison)
6711 bool result;
6712 if (!Binary_expression::compare_constant(op, &left_nc,
6713 &right_nc, location,
6714 &result))
6715 return this;
6716 ret = Expression::make_boolean(result, location);
6718 else
6720 Numeric_constant nc;
6721 bool issued_error;
6722 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6723 location, &nc,
6724 &issued_error))
6726 if (issued_error)
6727 return Expression::make_error(location);
6728 return this;
6730 ret = nc.expression(location);
6733 Type_context subcontext(this->type_, this->type_->is_abstract());
6734 ret->determine_type(gogo, &subcontext);
6735 ret->check_types(gogo);
6736 return ret;
6740 // String constant expressions.
6742 // Avoid constant folding here if the left and right types are incompatible
6743 // (leave the operation intact so that the type checker can complain about it
6744 // later on). If concatenating an abstract string with a named string type,
6745 // result type needs to be of the named type (see issue 31412).
6746 if (left->type()->is_string_type()
6747 && right->type()->is_string_type()
6748 && (left->type()->named_type() == NULL
6749 || right->type()->named_type() == NULL
6750 || left->type()->named_type() == right->type()->named_type()))
6752 std::string left_string;
6753 std::string right_string;
6754 if (left->string_constant_value(&left_string)
6755 && right->string_constant_value(&right_string))
6757 Expression* ret = NULL;
6758 if (op == OPERATOR_PLUS)
6760 delete left;
6761 delete right;
6762 ret = Expression::make_string_typed(left_string + right_string,
6763 this->type_, location);
6765 else if (is_comparison)
6767 int cmp = left_string.compare(right_string);
6768 bool r = Binary_expression::cmp_to_bool(op, cmp);
6769 delete left;
6770 delete right;
6771 ret = Expression::make_boolean(r, location);
6774 if (ret != NULL)
6776 Type_context subcontext(this->type_, this->type_->is_abstract());
6777 ret->determine_type(gogo, &subcontext);
6778 ret->check_types(gogo);
6779 return ret;
6784 // Lower struct, array, and some interface comparisons.
6785 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6787 if (left->type()->struct_type() != NULL
6788 && right->type()->struct_type() != NULL)
6789 return this->lower_struct_comparison(gogo, inserter);
6790 else if (left->type()->array_type() != NULL
6791 && !left->type()->is_slice_type()
6792 && right->type()->array_type() != NULL
6793 && !right->type()->is_slice_type())
6794 return this->lower_array_comparison(gogo, inserter);
6795 else if ((left->type()->interface_type() != NULL
6796 && right->type()->interface_type() == NULL)
6797 || (left->type()->interface_type() == NULL
6798 && right->type()->interface_type() != NULL))
6799 return this->lower_interface_value_comparison(gogo, inserter);
6802 // Lower string concatenation to String_concat_expression, so that
6803 // we can group sequences of string additions.
6804 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6806 Expression_list* exprs;
6807 String_concat_expression* left_sce =
6808 this->left_->string_concat_expression();
6809 if (left_sce != NULL)
6810 exprs = left_sce->exprs();
6811 else
6813 exprs = new Expression_list();
6814 exprs->push_back(this->left_);
6817 String_concat_expression* right_sce =
6818 this->right_->string_concat_expression();
6819 if (right_sce != NULL)
6820 exprs->append(right_sce->exprs());
6821 else
6822 exprs->push_back(this->right_);
6824 return Expression::make_string_concat(exprs);
6827 return this;
6830 // Lower a struct comparison.
6832 Expression*
6833 Binary_expression::lower_struct_comparison(Gogo* gogo,
6834 Statement_inserter* inserter)
6836 Struct_type* st = this->left_->type()->struct_type();
6837 Struct_type* st2 = this->right_->type()->struct_type();
6838 if (st2 == NULL)
6839 return this;
6840 if (st != st2
6841 && !Type::are_identical(st, st2,
6842 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6843 NULL))
6844 return this;
6845 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6846 this->right_->type(), NULL))
6847 return this;
6849 // See if we can compare using memcmp. As a heuristic, we use
6850 // memcmp rather than field references and comparisons if there are
6851 // more than two fields.
6852 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6853 return this->lower_compare_to_memcmp(gogo, inserter);
6855 Location loc = this->location();
6857 Expression* left = this->left_;
6858 Temporary_statement* left_temp = NULL;
6859 if (left->var_expression() == NULL
6860 && left->temporary_reference_expression() == NULL)
6862 left_temp = Statement::make_temporary(left->type(), NULL, loc);
6863 inserter->insert(left_temp);
6864 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6867 Expression* right = this->right_;
6868 Temporary_statement* right_temp = NULL;
6869 if (right->var_expression() == NULL
6870 && right->temporary_reference_expression() == NULL)
6872 right_temp = Statement::make_temporary(right->type(), NULL, loc);
6873 inserter->insert(right_temp);
6874 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6877 Expression* ret = Expression::make_boolean(true, loc);
6878 const Struct_field_list* fields = st->fields();
6879 unsigned int field_index = 0;
6880 for (Struct_field_list::const_iterator pf = fields->begin();
6881 pf != fields->end();
6882 ++pf, ++field_index)
6884 if (Gogo::is_sink_name(pf->field_name()))
6885 continue;
6887 if (field_index > 0)
6889 if (left_temp == NULL)
6890 left = left->copy();
6891 else
6892 left = Expression::make_temporary_reference(left_temp, loc);
6893 if (right_temp == NULL)
6894 right = right->copy();
6895 else
6896 right = Expression::make_temporary_reference(right_temp, loc);
6898 Expression* f1 = Expression::make_field_reference(left, field_index,
6899 loc);
6900 Expression* f2 = Expression::make_field_reference(right, field_index,
6901 loc);
6902 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6903 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6906 if (this->op_ == OPERATOR_NOTEQ)
6907 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6909 ret->determine_type_no_context(gogo);
6911 return ret;
6914 // Lower an array comparison.
6916 Expression*
6917 Binary_expression::lower_array_comparison(Gogo* gogo,
6918 Statement_inserter* inserter)
6920 Array_type* at = this->left_->type()->array_type();
6921 Array_type* at2 = this->right_->type()->array_type();
6922 if (at2 == NULL)
6923 return this;
6924 if (at != at2
6925 && !Type::are_identical(at, at2,
6926 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6927 NULL))
6928 return this;
6929 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6930 this->right_->type(), NULL))
6931 return this;
6933 // Call memcmp directly if possible. This may let the middle-end
6934 // optimize the call.
6935 if (at->compare_is_identity(gogo))
6936 return this->lower_compare_to_memcmp(gogo, inserter);
6938 // Call the array comparison function.
6939 Named_object* equal_fn =
6940 at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6942 Location loc = this->location();
6944 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6946 Expression_list* args = new Expression_list();
6947 args->push_back(this->operand_address(inserter, this->left_));
6948 args->push_back(this->operand_address(inserter, this->right_));
6950 Call_expression* ce = Expression::make_call(func, args, false, loc);
6952 // Record that this is a call to a generated equality function. We
6953 // need to do this because a comparison returns an abstract boolean
6954 // type, but the function necessarily returns "bool". The
6955 // difference shows up in code like
6956 // type mybool bool
6957 // var b mybool = [10]string{} == [10]string{}
6958 // The comparison function returns "bool", but since a comparison
6959 // has an abstract boolean type we need an implicit conversion to
6960 // "mybool". The implicit conversion is inserted in
6961 // Call_expression::do_flatten.
6962 ce->set_is_equal_function();
6964 Expression* ret = ce;
6965 if (this->op_ == OPERATOR_NOTEQ)
6966 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6968 ret->determine_type_no_context(gogo);
6970 return ret;
6973 // Lower an interface to value comparison.
6975 Expression*
6976 Binary_expression::lower_interface_value_comparison(Gogo*,
6977 Statement_inserter* inserter)
6979 Type* left_type = this->left_->type();
6980 Type* right_type = this->right_->type();
6981 Interface_type* ift;
6982 if (left_type->interface_type() != NULL)
6984 ift = left_type->interface_type();
6985 if (!ift->implements_interface(right_type, NULL))
6986 return this;
6988 else
6990 ift = right_type->interface_type();
6991 if (!ift->implements_interface(left_type, NULL))
6992 return this;
6994 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6995 return this;
6997 Location loc = this->location();
6999 if (left_type->interface_type() == NULL
7000 && left_type->points_to() == NULL
7001 && !this->left_->is_addressable())
7003 Temporary_statement* temp =
7004 Statement::make_temporary(left_type, NULL, loc);
7005 inserter->insert(temp);
7006 this->left_ =
7007 Expression::make_set_and_use_temporary(temp, this->left_, loc);
7010 if (right_type->interface_type() == NULL
7011 && right_type->points_to() == NULL
7012 && !this->right_->is_addressable())
7014 Temporary_statement* temp =
7015 Statement::make_temporary(right_type, NULL, loc);
7016 inserter->insert(temp);
7017 this->right_ =
7018 Expression::make_set_and_use_temporary(temp, this->right_, loc);
7021 return this;
7024 // Lower a struct or array comparison to a call to memcmp.
7026 Expression*
7027 Binary_expression::lower_compare_to_memcmp(Gogo* gogo,
7028 Statement_inserter* inserter)
7030 Location loc = this->location();
7032 Expression* a1 = this->operand_address(inserter, this->left_);
7033 Expression* a2 = this->operand_address(inserter, this->right_);
7034 Expression* len = Expression::make_type_info(this->left_->type(),
7035 TYPE_INFO_SIZE);
7037 Expression* call = Runtime::make_call(gogo, Runtime::MEMCMP, loc, 3,
7038 a1, a2, len);
7039 Type* int32_type = Type::lookup_integer_type("int32");
7040 Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
7041 Expression* ret = Expression::make_binary(this->op_, call, zero, loc);
7042 Type_context context(this->type_, this->type_->is_abstract());
7043 ret->determine_type(gogo, &context);
7044 return ret;
7047 Expression*
7048 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
7049 Statement_inserter* inserter)
7051 Location loc = this->location();
7052 if (this->left_->type()->is_error_type()
7053 || this->right_->type()->is_error_type()
7054 || this->left_->is_error_expression()
7055 || this->right_->is_error_expression())
7057 go_assert(saw_errors());
7058 return Expression::make_error(loc);
7061 Temporary_statement* temp;
7063 Type* left_type = this->left_->type();
7064 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
7065 || this->op_ == OPERATOR_RSHIFT);
7066 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
7067 left_type->integer_type() != NULL)
7068 || this->op_ == OPERATOR_MOD);
7069 bool is_string_op = (left_type->is_string_type()
7070 && this->right_->type()->is_string_type());
7072 if (is_string_op)
7074 // Mark string([]byte) operands to reuse the backing store.
7075 // String comparison does not keep the reference, so it is safe.
7076 Type_conversion_expression* lce =
7077 this->left_->conversion_expression();
7078 if (lce != NULL && lce->expr()->type()->is_slice_type())
7079 lce->set_no_copy(true);
7080 Type_conversion_expression* rce =
7081 this->right_->conversion_expression();
7082 if (rce != NULL && rce->expr()->type()->is_slice_type())
7083 rce->set_no_copy(true);
7086 if (is_shift_op
7087 || (is_idiv_op
7088 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
7089 || is_string_op)
7091 if (!this->left_->is_multi_eval_safe())
7093 temp = Statement::make_temporary(NULL, this->left_, loc);
7094 inserter->insert(temp);
7095 this->left_ = Expression::make_temporary_reference(temp, loc);
7097 if (!this->right_->is_multi_eval_safe())
7099 temp =
7100 Statement::make_temporary(NULL, this->right_, loc);
7101 this->right_ = Expression::make_temporary_reference(temp, loc);
7102 inserter->insert(temp);
7105 return this;
7109 // Return the address of EXPR, cast to unsafe.Pointer.
7111 Expression*
7112 Binary_expression::operand_address(Statement_inserter* inserter,
7113 Expression* expr)
7115 Location loc = this->location();
7117 if (!expr->is_addressable())
7119 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
7120 loc);
7121 inserter->insert(temp);
7122 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
7124 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
7125 static_cast<Unary_expression*>(expr)->set_does_not_escape();
7126 Type* void_type = Type::make_void_type();
7127 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
7128 return Expression::make_cast(unsafe_pointer_type, expr, loc);
7131 // Return the numeric constant value, if it has one.
7133 bool
7134 Binary_expression::do_numeric_constant_value(Numeric_constant* nc)
7136 if (this->is_error_expression())
7137 return false;
7139 Numeric_constant left_nc;
7140 if (!this->left_->numeric_constant_value(&left_nc))
7141 return false;
7142 Numeric_constant right_nc;
7143 if (!this->right_->numeric_constant_value(&right_nc))
7144 return false;
7145 bool issued_error;
7146 bool r = Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
7147 this->location(), nc,
7148 &issued_error);
7149 if (issued_error)
7150 this->set_is_error();
7151 return r;
7154 // Return the boolean constant value, if it has one.
7156 bool
7157 Binary_expression::do_boolean_constant_value(bool* val)
7159 if (this->is_error_expression())
7160 return false;
7162 bool is_comparison = false;
7163 switch (this->op_)
7165 case OPERATOR_EQEQ:
7166 case OPERATOR_NOTEQ:
7167 case OPERATOR_LT:
7168 case OPERATOR_LE:
7169 case OPERATOR_GT:
7170 case OPERATOR_GE:
7171 is_comparison = true;
7172 break;
7173 case OPERATOR_ANDAND:
7174 case OPERATOR_OROR:
7175 break;
7176 default:
7177 return false;
7180 Numeric_constant left_nc, right_nc;
7181 if (is_comparison
7182 && this->left_->numeric_constant_value(&left_nc)
7183 && this->right_->numeric_constant_value(&right_nc))
7184 return Binary_expression::compare_constant(this->op_, &left_nc,
7185 &right_nc,
7186 this->location(),
7187 val);
7189 std::string left_str, right_str;
7190 if (is_comparison
7191 && this->left_->string_constant_value(&left_str)
7192 && this->right_->string_constant_value(&right_str))
7194 *val = Binary_expression::cmp_to_bool(this->op_,
7195 left_str.compare(right_str));
7196 return true;
7199 bool left_bval;
7200 if (this->left_->boolean_constant_value(&left_bval))
7202 if (this->op_ == OPERATOR_ANDAND && !left_bval)
7204 *val = false;
7205 return true;
7207 else if (this->op_ == OPERATOR_OROR && left_bval)
7209 *val = true;
7210 return true;
7213 bool right_bval;
7214 if (this->right_->boolean_constant_value(&right_bval))
7216 switch (this->op_)
7218 case OPERATOR_EQEQ:
7219 *val = (left_bval == right_bval);
7220 return true;
7221 case OPERATOR_NOTEQ:
7222 *val = (left_bval != right_bval);
7223 return true;
7224 case OPERATOR_ANDAND:
7225 case OPERATOR_OROR:
7226 *val = right_bval;
7227 return true;
7228 default:
7229 go_unreachable();
7234 return false;
7237 // Note that the value is being discarded.
7239 bool
7240 Binary_expression::do_discarding_value()
7242 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
7243 return this->right_->discarding_value();
7244 else
7246 this->unused_value_error();
7247 return false;
7251 // Get type.
7253 Type*
7254 Binary_expression::do_type()
7256 if (this->type_ == NULL)
7258 go_assert(saw_errors());
7259 return Type::make_error_type();
7262 return this->type_;
7265 // Set type for a binary expression.
7267 void
7268 Binary_expression::do_determine_type(Gogo* gogo, const Type_context* context)
7270 if (this->type_ != NULL)
7271 return;
7273 // For a shift operation, the type of the binary expression is the
7274 // type of the left operand. If the left operand is a constant,
7275 // then it gets its type from the context.
7276 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
7277 || this->op_ == OPERATOR_RSHIFT);
7279 // For a comparison operation, the type of the binary expression is
7280 // a boolean type.
7281 bool is_comparison = (this->op_ == OPERATOR_EQEQ
7282 || this->op_ == OPERATOR_NOTEQ
7283 || this->op_ == OPERATOR_LT
7284 || this->op_ == OPERATOR_LE
7285 || this->op_ == OPERATOR_GT
7286 || this->op_ == OPERATOR_GE);
7288 // For constant expressions, the context of the result is not useful in
7289 // determining the types of the operands. It is only legal to use abstract
7290 // boolean, numeric, and string constants as operands where it is legal to
7291 // use non-abstract boolean, numeric, and string constants, respectively.
7292 // Any issues with the operation will be resolved in the check_types pass.
7293 bool left_is_constant = this->left_->is_constant();
7294 bool right_is_constant = this->right_->is_constant();
7295 bool is_constant_expr = left_is_constant && right_is_constant;
7297 Type_context subcontext(*context);
7298 if (is_comparison)
7299 subcontext.type = NULL;
7301 Type* tleft;
7302 bool left_is_untyped = this->left_->is_untyped(&tleft);
7303 if (!left_is_untyped)
7305 this->left_->determine_type(gogo, &subcontext);
7306 tleft = this->left_->type();
7309 Type* tright;
7310 bool right_is_untyped = this->right_->is_untyped(&tright);
7311 if (!right_is_untyped)
7313 // For a shift operation, the right operand should always be an
7314 // integer.
7315 if (is_shift_op)
7317 subcontext.type = Type::lookup_integer_type("uint");
7318 subcontext.may_be_abstract = false;
7321 this->right_->determine_type(gogo, &subcontext);
7322 tright = this->right_->type();
7325 // For each operand we have the real type or, if the operand is a
7326 // untyped, a guess at the type. Use this to determine the types of
7327 // untyped operands.
7329 subcontext = *context;
7330 if (left_is_untyped && (right_is_untyped || is_shift_op) && is_constant_expr)
7332 // We evaluate the operands of an untyped expression as untyped
7333 // values. Then we convert to the desired type. Otherwise we
7334 // may, for example, mishandle a floating-point constant
7335 // division as an integer division.
7336 subcontext.type = NULL;
7337 subcontext.may_be_abstract = true;
7339 else if (is_comparison)
7341 // In a comparison, the context does not determine the types of
7342 // the operands.
7343 subcontext.type = NULL;
7346 // Set the context for the left hand operand.
7348 if (is_shift_op)
7350 // The right hand operand of a shift plays no role in
7351 // determining the type of the left hand operand.
7352 if (subcontext.type == NULL
7353 && right_is_constant
7354 && context->may_be_abstract)
7355 subcontext.type = Type::make_abstract_integer_type();
7357 else if (!tleft->is_abstract())
7358 subcontext.type = tleft;
7359 else if (!tright->is_abstract())
7360 subcontext.type = tright;
7361 else if (subcontext.type == NULL)
7363 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
7364 || (tleft->float_type() != NULL && tright->float_type() != NULL)
7365 || (tleft->complex_type() != NULL && tright->complex_type() != NULL)
7366 || (tleft->is_boolean_type() && tright->is_boolean_type()))
7368 // Both sides have an abstract integer, abstract float,
7369 // abstract complex, or abstract boolean type. Just let
7370 // CONTEXT determine whether they may remain abstract or not.
7372 else if (tleft->complex_type() != NULL)
7373 subcontext.type = tleft;
7374 else if (tright->complex_type() != NULL)
7375 subcontext.type = tright;
7376 else if (tleft->float_type() != NULL)
7377 subcontext.type = tleft;
7378 else if (tright->float_type() != NULL)
7379 subcontext.type = tright;
7380 else
7381 subcontext.type = tleft;
7384 if (left_is_untyped)
7386 this->left_->determine_type(gogo, &subcontext);
7387 tleft = this->left_->type();
7390 if (is_shift_op)
7392 // We may have inherited an unusable type for the shift operand.
7393 // Give a useful error if that happened.
7394 if (left_is_untyped
7395 && !is_constant_expr
7396 && subcontext.type != NULL
7397 && !subcontext.may_be_abstract
7398 && subcontext.type->interface_type() == NULL
7399 && subcontext.type->integer_type() == NULL
7400 && !tleft->is_error()
7401 && !tright->is_error())
7402 this->report_error(("invalid context-determined non-integer type "
7403 "for left operand of shift"));
7405 // The context for the right hand operand is the same as for the
7406 // left hand operand, except for a shift operator.
7407 subcontext.type = Type::lookup_integer_type("uint");
7408 subcontext.may_be_abstract = false;
7411 if (right_is_untyped)
7413 this->right_->determine_type(gogo, &subcontext);
7414 tright = this->right_->type();
7417 if (this->left_->is_error_expression()
7418 || tleft->is_error()
7419 || this->right_->is_error_expression()
7420 || tright->is_error())
7422 this->set_is_error();
7423 return;
7426 if (is_comparison)
7428 if (context->type != NULL && context->type->is_boolean_type())
7429 this->type_ = context->type;
7430 else if (!context->may_be_abstract)
7431 this->type_ = Type::lookup_bool_type();
7432 else
7433 this->type_ = Type::make_boolean_type();
7435 else
7437 if (is_shift_op)
7439 // Shifts only work with integers, so force an abstract
7440 // floating-point type (such as 1.0 << 1) into an integer.
7441 if (tleft->is_abstract()
7442 && tleft->integer_type() == NULL
7443 && context->type == NULL)
7445 this->type_ = Type::make_abstract_integer_type();
7446 if (!context->may_be_abstract)
7447 this->type_ = this->type_->make_non_abstract_type();
7449 else
7450 this->type_ = tleft;
7452 else
7454 if (!Binary_expression::operation_type(this->op_, tleft, tright,
7455 &this->type_))
7457 this->report_error("incompatible types in binary expression");
7458 this->type_ = Type::make_error_type();
7459 return;
7463 // If this is an untyped expression in a typed context, use the
7464 // context type. If this doesn't work we'll report an error
7465 // later.
7466 if (this->type_->is_abstract()
7467 && !context->may_be_abstract
7468 && context->type != NULL)
7470 if (context->type->interface_type() == NULL
7471 && ((this->type_->is_numeric_type()
7472 && context->type->is_numeric_type())
7473 || (this->type_->is_string_type()
7474 && context->type->is_string_type())
7475 || (this->type_->is_boolean_type()
7476 && context->type->is_boolean_type())))
7477 this->type_ = context->type;
7478 else if (context->type->interface_type() != NULL)
7479 this->type_ = this->type_->make_non_abstract_type();
7484 // Report an error if the binary operator OP does not support TYPE.
7485 // OTYPE is the type of the other operand. Return whether the
7486 // operation is OK. This should not be used for shift.
7488 bool
7489 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
7490 Location location)
7492 switch (op)
7494 case OPERATOR_OROR:
7495 case OPERATOR_ANDAND:
7496 if (!type->is_boolean_type()
7497 || !otype->is_boolean_type())
7499 go_error_at(location, "expected boolean type");
7500 return false;
7502 break;
7504 case OPERATOR_EQEQ:
7505 case OPERATOR_NOTEQ:
7507 std::string reason;
7508 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
7510 go_error_at(location, "%s", reason.c_str());
7511 return false;
7514 break;
7516 case OPERATOR_LT:
7517 case OPERATOR_LE:
7518 case OPERATOR_GT:
7519 case OPERATOR_GE:
7521 std::string reason;
7522 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
7524 go_error_at(location, "%s", reason.c_str());
7525 return false;
7528 break;
7530 case OPERATOR_PLUS:
7531 case OPERATOR_PLUSEQ:
7532 if ((!type->is_numeric_type() && !type->is_string_type())
7533 || (!otype->is_numeric_type() && !otype->is_string_type()))
7535 go_error_at(location,
7536 "expected integer, floating, complex, or string type");
7537 return false;
7539 break;
7541 case OPERATOR_MINUS:
7542 case OPERATOR_MINUSEQ:
7543 case OPERATOR_MULT:
7544 case OPERATOR_MULTEQ:
7545 case OPERATOR_DIV:
7546 case OPERATOR_DIVEQ:
7547 if (!type->is_numeric_type() || !otype->is_numeric_type())
7549 go_error_at(location, "expected integer, floating, or complex type");
7550 return false;
7552 break;
7554 case OPERATOR_MOD:
7555 case OPERATOR_MODEQ:
7556 case OPERATOR_OR:
7557 case OPERATOR_OREQ:
7558 case OPERATOR_AND:
7559 case OPERATOR_ANDEQ:
7560 case OPERATOR_XOR:
7561 case OPERATOR_XOREQ:
7562 case OPERATOR_BITCLEAR:
7563 case OPERATOR_BITCLEAREQ:
7564 if (type->integer_type() == NULL || otype->integer_type() == NULL)
7566 go_error_at(location, "expected integer type");
7567 return false;
7569 break;
7571 default:
7572 go_unreachable();
7575 return true;
7578 // Check types.
7580 void
7581 Binary_expression::do_check_types(Gogo*)
7583 if (this->classification() == EXPRESSION_ERROR)
7584 return;
7586 Type* left_type = this->left_->type();
7587 Type* right_type = this->right_->type();
7588 if (left_type->is_error() || right_type->is_error())
7590 this->set_is_error();
7591 return;
7594 if (this->op_ == OPERATOR_EQEQ
7595 || this->op_ == OPERATOR_NOTEQ
7596 || this->op_ == OPERATOR_LT
7597 || this->op_ == OPERATOR_LE
7598 || this->op_ == OPERATOR_GT
7599 || this->op_ == OPERATOR_GE)
7601 if (left_type->is_nil_type() && right_type->is_nil_type())
7603 this->report_error(_("invalid comparison of nil with nil"));
7604 return;
7606 if (!Type::are_assignable(left_type, right_type, NULL)
7607 && !Type::are_assignable(right_type, left_type, NULL))
7609 this->report_error(_("incompatible types in binary expression"));
7610 return;
7612 if (!Binary_expression::check_operator_type(this->op_, left_type,
7613 right_type,
7614 this->location())
7615 || !Binary_expression::check_operator_type(this->op_, right_type,
7616 left_type,
7617 this->location()))
7619 this->set_is_error();
7620 return;
7623 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
7625 if (!Type::are_compatible_for_binop(left_type, right_type))
7627 this->report_error(_("incompatible types in binary expression"));
7628 return;
7630 if (!Binary_expression::check_operator_type(this->op_, left_type,
7631 right_type,
7632 this->location()))
7634 this->set_is_error();
7635 return;
7637 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
7639 // Division by a zero integer constant is an error.
7640 Numeric_constant rconst;
7641 unsigned long rval;
7642 if (left_type->integer_type() != NULL
7643 && this->right_->numeric_constant_value(&rconst)
7644 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
7645 && rval == 0)
7647 this->report_error(_("integer division by zero"));
7648 return;
7652 else
7654 if (left_type->integer_type() == NULL
7655 && !left_type->is_abstract()
7656 && !this->is_constant())
7657 this->report_error(_("shift of non-integer operand"));
7659 if (right_type->is_string_type())
7660 this->report_error(_("shift count not integer"));
7661 else if (!right_type->is_abstract()
7662 && right_type->integer_type() == NULL)
7663 this->report_error(_("shift count not integer"));
7664 else
7666 Numeric_constant nc;
7667 if (this->right_->numeric_constant_value(&nc))
7669 mpz_t val;
7670 if (!nc.to_int(&val))
7671 this->report_error(_("shift count not integer"));
7672 else
7674 if (mpz_sgn(val) < 0)
7676 this->report_error(_("negative shift count"));
7677 Location rloc = this->right_->location();
7678 this->right_ = Expression::make_integer_ul(0, right_type,
7679 rloc);
7681 mpz_clear(val);
7688 // Get the backend representation for a binary expression.
7690 Bexpression*
7691 Binary_expression::do_get_backend(Translate_context* context)
7693 Gogo* gogo = context->gogo();
7694 Location loc = this->location();
7695 Type* left_type = this->left_->type();
7696 Type* right_type = this->right_->type();
7698 bool use_left_type = true;
7699 bool is_shift_op = false;
7700 bool is_idiv_op = false;
7701 switch (this->op_)
7703 case OPERATOR_EQEQ:
7704 case OPERATOR_NOTEQ:
7705 case OPERATOR_LT:
7706 case OPERATOR_LE:
7707 case OPERATOR_GT:
7708 case OPERATOR_GE:
7709 return Expression::comparison(context, this->type_, this->op_,
7710 this->left_, this->right_, loc);
7712 case OPERATOR_OROR:
7713 case OPERATOR_ANDAND:
7714 use_left_type = false;
7715 break;
7716 case OPERATOR_PLUS:
7717 case OPERATOR_MINUS:
7718 case OPERATOR_OR:
7719 case OPERATOR_XOR:
7720 case OPERATOR_MULT:
7721 break;
7722 case OPERATOR_DIV:
7723 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
7724 break;
7725 // Fall through.
7726 case OPERATOR_MOD:
7727 is_idiv_op = true;
7728 break;
7729 case OPERATOR_LSHIFT:
7730 case OPERATOR_RSHIFT:
7731 is_shift_op = true;
7732 break;
7733 case OPERATOR_BITCLEAR:
7734 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
7735 case OPERATOR_AND:
7736 break;
7737 default:
7738 go_unreachable();
7741 // The only binary operation for string is +, and that should have
7742 // been converted to a String_concat_expression in do_lower.
7743 go_assert(!left_type->is_string_type());
7745 Bexpression* left = this->left_->get_backend(context);
7746 Bexpression* right = this->right_->get_backend(context);
7748 Type* type = use_left_type ? left_type : right_type;
7749 Btype* btype = type->get_backend(gogo);
7751 Bexpression* ret =
7752 gogo->backend()->binary_expression(this->op_, left, right, loc);
7753 ret = gogo->backend()->convert_expression(btype, ret, loc);
7755 // Initialize overflow constants.
7756 Bexpression* overflow;
7757 mpz_t zero;
7758 mpz_init_set_ui(zero, 0UL);
7759 mpz_t one;
7760 mpz_init_set_ui(one, 1UL);
7761 mpz_t neg_one;
7762 mpz_init_set_si(neg_one, -1);
7764 Btype* left_btype = left_type->get_backend(gogo);
7765 Btype* right_btype = right_type->get_backend(gogo);
7767 // In Go, a shift larger than the size of the type is well-defined.
7768 // This is not true in C, so we need to insert a conditional.
7769 // We also need to check for a negative shift count.
7770 if (is_shift_op)
7772 go_assert(left_type->integer_type() != NULL);
7773 go_assert(right_type->integer_type() != NULL);
7775 int bits = left_type->integer_type()->bits();
7777 Numeric_constant nc;
7778 unsigned long ul;
7779 if (!this->right_->numeric_constant_value(&nc)
7780 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7781 || ul >= static_cast<unsigned long>(bits))
7783 mpz_t bitsval;
7784 mpz_init_set_ui(bitsval, bits);
7785 Bexpression* bits_expr =
7786 gogo->backend()->integer_constant_expression(right_btype, bitsval);
7787 Bexpression* compare =
7788 gogo->backend()->binary_expression(OPERATOR_LT,
7789 right, bits_expr, loc);
7791 Bexpression* zero_expr =
7792 gogo->backend()->integer_constant_expression(left_btype, zero);
7793 overflow = zero_expr;
7794 Bfunction* bfn = context->function()->func_value()->get_decl();
7795 if (this->op_ == OPERATOR_RSHIFT
7796 && !left_type->integer_type()->is_unsigned())
7798 Bexpression* neg_expr =
7799 gogo->backend()->binary_expression(OPERATOR_LT, left,
7800 zero_expr, loc);
7801 Bexpression* neg_one_expr =
7802 gogo->backend()->integer_constant_expression(left_btype,
7803 neg_one);
7804 overflow = gogo->backend()->conditional_expression(bfn,
7805 btype,
7806 neg_expr,
7807 neg_one_expr,
7808 zero_expr,
7809 loc);
7811 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7812 ret, overflow, loc);
7813 mpz_clear(bitsval);
7816 if (!right_type->integer_type()->is_unsigned()
7817 && (!this->right_->numeric_constant_value(&nc)
7818 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7820 Bexpression* zero_expr =
7821 gogo->backend()->integer_constant_expression(right_btype, zero);
7822 Bexpression* compare =
7823 gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7824 loc);
7825 Expression* crash = Runtime::make_call(gogo, Runtime::PANIC_SHIFT,
7826 loc, 0);
7827 crash->determine_type_no_context(gogo);
7828 Bexpression* bcrash = crash->get_backend(context);
7829 Bfunction* bfn = context->function()->func_value()->get_decl();
7830 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7831 bcrash, ret, loc);
7835 // Add checks for division by zero and division overflow as needed.
7836 if (is_idiv_op)
7838 if (gogo->check_divide_by_zero())
7840 // right == 0
7841 Bexpression* zero_expr =
7842 gogo->backend()->integer_constant_expression(right_btype, zero);
7843 Bexpression* check =
7844 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7845 right, zero_expr, loc);
7847 Expression* crash = Runtime::make_call(gogo, Runtime::PANIC_DIVIDE,
7848 loc, 0);
7849 crash->determine_type_no_context(gogo);
7850 Bexpression* bcrash = crash->get_backend(context);
7852 // right == 0 ? (panicdivide(), 0) : ret
7853 Bfunction* bfn = context->function()->func_value()->get_decl();
7854 ret = gogo->backend()->conditional_expression(bfn, btype,
7855 check, bcrash,
7856 ret, loc);
7859 if (gogo->check_divide_overflow())
7861 // right == -1
7862 // FIXME: It would be nice to say that this test is expected
7863 // to return false.
7865 Bexpression* neg_one_expr =
7866 gogo->backend()->integer_constant_expression(right_btype, neg_one);
7867 Bexpression* check =
7868 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7869 right, neg_one_expr, loc);
7871 Bexpression* zero_expr =
7872 gogo->backend()->integer_constant_expression(btype, zero);
7873 Bexpression* one_expr =
7874 gogo->backend()->integer_constant_expression(btype, one);
7875 Bfunction* bfn = context->function()->func_value()->get_decl();
7877 if (type->integer_type()->is_unsigned())
7879 // An unsigned -1 is the largest possible number, so
7880 // dividing is always 1 or 0.
7882 Bexpression* cmp =
7883 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7884 left, right, loc);
7885 if (this->op_ == OPERATOR_DIV)
7886 overflow =
7887 gogo->backend()->conditional_expression(bfn, btype, cmp,
7888 one_expr, zero_expr,
7889 loc);
7890 else
7891 overflow =
7892 gogo->backend()->conditional_expression(bfn, btype, cmp,
7893 zero_expr, left,
7894 loc);
7896 else
7898 // Computing left / -1 is the same as computing - left,
7899 // which does not overflow since Go sets -fwrapv.
7900 if (this->op_ == OPERATOR_DIV)
7902 Expression* negate_expr =
7903 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7904 overflow = negate_expr->get_backend(context);
7906 else
7907 overflow = zero_expr;
7909 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7911 // right == -1 ? - left : ret
7912 ret = gogo->backend()->conditional_expression(bfn, btype,
7913 check, overflow,
7914 ret, loc);
7918 mpz_clear(zero);
7919 mpz_clear(one);
7920 mpz_clear(neg_one);
7921 return ret;
7924 // Export a binary expression.
7926 void
7927 Binary_expression::do_export(Export_function_body* efb) const
7929 efb->write_c_string("(");
7930 this->left_->export_expression(efb);
7931 switch (this->op_)
7933 case OPERATOR_OROR:
7934 efb->write_c_string(" || ");
7935 break;
7936 case OPERATOR_ANDAND:
7937 efb->write_c_string(" && ");
7938 break;
7939 case OPERATOR_EQEQ:
7940 efb->write_c_string(" == ");
7941 break;
7942 case OPERATOR_NOTEQ:
7943 efb->write_c_string(" != ");
7944 break;
7945 case OPERATOR_LT:
7946 efb->write_c_string(" < ");
7947 break;
7948 case OPERATOR_LE:
7949 efb->write_c_string(" <= ");
7950 break;
7951 case OPERATOR_GT:
7952 efb->write_c_string(" > ");
7953 break;
7954 case OPERATOR_GE:
7955 efb->write_c_string(" >= ");
7956 break;
7957 case OPERATOR_PLUS:
7958 efb->write_c_string(" + ");
7959 break;
7960 case OPERATOR_MINUS:
7961 efb->write_c_string(" - ");
7962 break;
7963 case OPERATOR_OR:
7964 efb->write_c_string(" | ");
7965 break;
7966 case OPERATOR_XOR:
7967 efb->write_c_string(" ^ ");
7968 break;
7969 case OPERATOR_MULT:
7970 efb->write_c_string(" * ");
7971 break;
7972 case OPERATOR_DIV:
7973 efb->write_c_string(" / ");
7974 break;
7975 case OPERATOR_MOD:
7976 efb->write_c_string(" % ");
7977 break;
7978 case OPERATOR_LSHIFT:
7979 efb->write_c_string(" << ");
7980 break;
7981 case OPERATOR_RSHIFT:
7982 efb->write_c_string(" >> ");
7983 break;
7984 case OPERATOR_AND:
7985 efb->write_c_string(" & ");
7986 break;
7987 case OPERATOR_BITCLEAR:
7988 efb->write_c_string(" &^ ");
7989 break;
7990 default:
7991 go_unreachable();
7993 this->right_->export_expression(efb);
7994 efb->write_c_string(")");
7997 // Import a binary expression.
7999 Expression*
8000 Binary_expression::do_import(Import_expression* imp, Location loc)
8002 imp->require_c_string("(");
8004 Expression* left = Expression::import_expression(imp, loc);
8006 Operator op;
8007 if (imp->match_c_string(" || "))
8009 op = OPERATOR_OROR;
8010 imp->advance(4);
8012 else if (imp->match_c_string(" && "))
8014 op = OPERATOR_ANDAND;
8015 imp->advance(4);
8017 else if (imp->match_c_string(" == "))
8019 op = OPERATOR_EQEQ;
8020 imp->advance(4);
8022 else if (imp->match_c_string(" != "))
8024 op = OPERATOR_NOTEQ;
8025 imp->advance(4);
8027 else if (imp->match_c_string(" < "))
8029 op = OPERATOR_LT;
8030 imp->advance(3);
8032 else if (imp->match_c_string(" <= "))
8034 op = OPERATOR_LE;
8035 imp->advance(4);
8037 else if (imp->match_c_string(" > "))
8039 op = OPERATOR_GT;
8040 imp->advance(3);
8042 else if (imp->match_c_string(" >= "))
8044 op = OPERATOR_GE;
8045 imp->advance(4);
8047 else if (imp->match_c_string(" + "))
8049 op = OPERATOR_PLUS;
8050 imp->advance(3);
8052 else if (imp->match_c_string(" - "))
8054 op = OPERATOR_MINUS;
8055 imp->advance(3);
8057 else if (imp->match_c_string(" | "))
8059 op = OPERATOR_OR;
8060 imp->advance(3);
8062 else if (imp->match_c_string(" ^ "))
8064 op = OPERATOR_XOR;
8065 imp->advance(3);
8067 else if (imp->match_c_string(" * "))
8069 op = OPERATOR_MULT;
8070 imp->advance(3);
8072 else if (imp->match_c_string(" / "))
8074 op = OPERATOR_DIV;
8075 imp->advance(3);
8077 else if (imp->match_c_string(" % "))
8079 op = OPERATOR_MOD;
8080 imp->advance(3);
8082 else if (imp->match_c_string(" << "))
8084 op = OPERATOR_LSHIFT;
8085 imp->advance(4);
8087 else if (imp->match_c_string(" >> "))
8089 op = OPERATOR_RSHIFT;
8090 imp->advance(4);
8092 else if (imp->match_c_string(" & "))
8094 op = OPERATOR_AND;
8095 imp->advance(3);
8097 else if (imp->match_c_string(" &^ "))
8099 op = OPERATOR_BITCLEAR;
8100 imp->advance(4);
8102 else if (imp->match_c_string(")"))
8104 // Not a binary operator after all.
8105 imp->advance(1);
8106 return left;
8108 else
8110 go_error_at(imp->location(), "unrecognized binary operator");
8111 return Expression::make_error(loc);
8114 Expression* right = Expression::import_expression(imp, loc);
8116 imp->require_c_string(")");
8118 return Expression::make_binary(op, left, right, loc);
8121 // Dump ast representation of a binary expression.
8123 void
8124 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
8126 ast_dump_context->ostream() << "(";
8127 ast_dump_context->dump_expression(this->left_);
8128 ast_dump_context->ostream() << " ";
8129 ast_dump_context->dump_operator(this->op_);
8130 ast_dump_context->ostream() << " ";
8131 ast_dump_context->dump_expression(this->right_);
8132 ast_dump_context->ostream() << ") ";
8135 // Make a binary expression.
8137 Expression*
8138 Expression::make_binary(Operator op, Expression* left, Expression* right,
8139 Location location)
8141 return new Binary_expression(op, left, right, location);
8144 // Implement a comparison.
8146 Bexpression*
8147 Expression::comparison(Translate_context* context, Type* result_type,
8148 Operator op, Expression* left, Expression* right,
8149 Location location)
8151 Gogo* gogo = context->gogo();
8152 Type* left_type = left->type();
8153 Type* right_type = right->type();
8155 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
8157 if (left_type->is_string_type() && right_type->is_string_type())
8159 go_assert(left->is_multi_eval_safe());
8160 go_assert(right->is_multi_eval_safe());
8162 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
8164 // (l.len == r.len
8165 // ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
8166 // : false)
8167 Expression* llen = Expression::make_string_info(left,
8168 STRING_INFO_LENGTH,
8169 location);
8170 Expression* rlen = Expression::make_string_info(right,
8171 STRING_INFO_LENGTH,
8172 location);
8173 Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
8174 location);
8175 Expression* lptr = Expression::make_string_info(left->copy(),
8176 STRING_INFO_DATA,
8177 location);
8178 Expression* rptr = Expression::make_string_info(right->copy(),
8179 STRING_INFO_DATA,
8180 location);
8181 Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
8182 location);
8183 Expression* btrue = Expression::make_boolean(true, location);
8184 Expression* call = Runtime::make_call(gogo, Runtime::MEMCMP,
8185 location, 3,
8186 lptr->copy(), rptr->copy(),
8187 rlen->copy());
8188 Type* int32_type = Type::lookup_integer_type("int32");
8189 Expression* zero = Expression::make_integer_ul(0, int32_type, location);
8190 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
8191 location);
8192 Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
8193 location);
8194 Expression* bfalse = Expression::make_boolean(false, location);
8195 left = Expression::make_conditional(leneq, cond, bfalse, location);
8196 right = Expression::make_boolean(true, location);
8198 else
8200 left = Runtime::make_call(gogo, Runtime::CMPSTRING, location, 2,
8201 left, right);
8202 right = zexpr;
8205 else if ((left_type->interface_type() != NULL
8206 && right_type->interface_type() == NULL
8207 && !right_type->is_nil_type())
8208 || (left_type->interface_type() == NULL
8209 && !left_type->is_nil_type()
8210 && right_type->interface_type() != NULL))
8212 // Comparing an interface value to a non-interface value.
8213 if (left_type->interface_type() == NULL)
8215 std::swap(left_type, right_type);
8216 std::swap(left, right);
8219 // The right operand is not an interface. We need to take its
8220 // address if it is not a direct interface type.
8221 Expression* pointer_arg = NULL;
8222 if (right_type->is_direct_iface_type())
8223 pointer_arg = Expression::unpack_direct_iface(right, location);
8224 else
8226 go_assert(right->is_addressable());
8227 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
8228 location);
8231 Expression* descriptor =
8232 Expression::make_type_descriptor(right_type, location);
8233 left = Runtime::make_call(gogo,
8234 (left_type->interface_type()->is_empty()
8235 ? Runtime::EFACEVALEQ
8236 : Runtime::IFACEVALEQ),
8237 location, 3, left, descriptor,
8238 pointer_arg);
8239 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
8240 right = Expression::make_boolean(true, location);
8242 else if (left_type->interface_type() != NULL
8243 && right_type->interface_type() != NULL)
8245 Runtime::Function compare_function;
8246 if (left_type->interface_type()->is_empty()
8247 && right_type->interface_type()->is_empty())
8248 compare_function = Runtime::EFACEEQ;
8249 else if (!left_type->interface_type()->is_empty()
8250 && !right_type->interface_type()->is_empty())
8251 compare_function = Runtime::IFACEEQ;
8252 else
8254 if (left_type->interface_type()->is_empty())
8256 std::swap(left_type, right_type);
8257 std::swap(left, right);
8259 go_assert(!left_type->interface_type()->is_empty());
8260 go_assert(right_type->interface_type()->is_empty());
8261 compare_function = Runtime::IFACEEFACEEQ;
8264 left = Runtime::make_call(gogo, compare_function, location, 2,
8265 left, right);
8266 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
8267 right = Expression::make_boolean(true, location);
8270 if (left_type->is_nil_type()
8271 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
8273 std::swap(left_type, right_type);
8274 std::swap(left, right);
8277 if (right_type->is_nil_type())
8279 right = Expression::make_nil(location);
8280 if (left_type->array_type() != NULL
8281 && left_type->array_type()->length() == NULL)
8283 Array_type* at = left_type->array_type();
8284 left = at->get_value_pointer(context->gogo(), left);
8286 else if (left_type->interface_type() != NULL)
8288 // An interface is nil if the first field is nil.
8289 left = Expression::make_field_reference(left, 0, location);
8293 left->determine_type_no_context(gogo);
8294 right->determine_type_no_context(gogo);
8296 Bexpression* left_bexpr = left->get_backend(context);
8297 Bexpression* right_bexpr = right->get_backend(context);
8299 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
8300 right_bexpr, location);
8301 if (result_type != NULL)
8302 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
8303 ret, location);
8304 return ret;
8307 // Class String_concat_expression.
8309 bool
8310 String_concat_expression::do_is_constant() const
8312 for (Expression_list::const_iterator pe = this->exprs_->begin();
8313 pe != this->exprs_->end();
8314 ++pe)
8316 if (!(*pe)->is_constant())
8317 return false;
8319 return true;
8322 bool
8323 String_concat_expression::do_is_untyped(Type** ptype) const
8325 for (Expression_list::iterator pe = this->exprs_->begin();
8326 pe != this->exprs_->end();
8327 ++pe)
8329 if (!(*pe)->is_untyped(ptype))
8330 return false;
8333 *ptype = Type::make_string_type();
8334 return true;
8337 bool
8338 String_concat_expression::do_is_zero_value() const
8340 for (Expression_list::const_iterator pe = this->exprs_->begin();
8341 pe != this->exprs_->end();
8342 ++pe)
8344 if (!(*pe)->is_zero_value())
8345 return false;
8347 return true;
8350 bool
8351 String_concat_expression::do_is_static_initializer() const
8353 for (Expression_list::const_iterator pe = this->exprs_->begin();
8354 pe != this->exprs_->end();
8355 ++pe)
8357 if (!(*pe)->is_static_initializer())
8358 return false;
8360 return true;
8363 Type*
8364 String_concat_expression::do_type()
8366 Type* t = this->exprs_->front()->type();
8367 Expression_list::iterator pe = this->exprs_->begin();
8368 ++pe;
8369 for (; pe != this->exprs_->end(); ++pe)
8371 Type* t1;
8372 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
8373 (*pe)->type(),
8374 &t1))
8375 return Type::make_error_type();
8376 t = t1;
8378 return t;
8381 void
8382 String_concat_expression::do_determine_type(Gogo* gogo,
8383 const Type_context* context)
8385 Type_context subcontext(*context);
8386 for (Expression_list::iterator pe = this->exprs_->begin();
8387 pe != this->exprs_->end();
8388 ++pe)
8390 Type* t = (*pe)->type();
8391 if (!t->is_abstract())
8393 subcontext.type = t;
8394 break;
8397 if (subcontext.type == NULL)
8398 subcontext.type = this->exprs_->front()->type();
8399 for (Expression_list::iterator pe = this->exprs_->begin();
8400 pe != this->exprs_->end();
8401 ++pe)
8402 (*pe)->determine_type(gogo, &subcontext);
8405 void
8406 String_concat_expression::do_check_types(Gogo*)
8408 if (this->is_error_expression())
8409 return;
8410 Type* t = this->exprs_->front()->type();
8411 if (t->is_error())
8413 this->set_is_error();
8414 return;
8416 Expression_list::iterator pe = this->exprs_->begin();
8417 ++pe;
8418 for (; pe != this->exprs_->end(); ++pe)
8420 Type* t1 = (*pe)->type();
8421 if (!Type::are_compatible_for_binop(t, t1))
8423 this->report_error("incompatible types in binary expression");
8424 return;
8426 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
8427 this->location()))
8429 this->set_is_error();
8430 return;
8435 Expression*
8436 String_concat_expression::do_flatten(Gogo* gogo, Named_object*,
8437 Statement_inserter* inserter)
8439 if (this->is_error_expression())
8440 return this;
8441 Location loc = this->location();
8442 Type* type = this->type();
8444 // Mark string([]byte) operands to reuse the backing store.
8445 // runtime.concatstrings does not keep the reference.
8447 // Note: in the gc runtime, if all but one inputs are empty,
8448 // concatstrings returns the only nonempty input without copy.
8449 // So it is not safe to reuse the backing store if it is a
8450 // string([]byte) conversion. So the gc compiler does the
8451 // no-copy optimization only when there is at least one
8452 // constant nonempty input. Currently the gccgo runtime
8453 // doesn't do this, so we don't do the check.
8454 for (Expression_list::iterator p = this->exprs_->begin();
8455 p != this->exprs_->end();
8456 ++p)
8458 Type_conversion_expression* tce = (*p)->conversion_expression();
8459 if (tce != NULL)
8460 tce->set_no_copy(true);
8463 Expression* buf = NULL;
8464 Node* n = Node::make_node(this);
8465 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8467 size_t size = 0;
8468 for (Expression_list::iterator p = this->exprs_->begin();
8469 p != this->exprs_->end();
8470 ++p)
8472 std::string s;
8473 if ((*p)->string_constant_value(&s))
8474 size += s.length();
8476 // Make a buffer on stack if the result does not escape.
8477 // But don't do this if we know it won't fit.
8478 if (size < (size_t)tmp_string_buf_size)
8480 Type* byte_type = Type::lookup_integer_type("uint8");
8481 Expression* buflen =
8482 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
8483 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
8484 Type* array_type = Type::make_array_type(byte_type, buflen);
8485 buf = Expression::make_allocation(array_type, loc);
8486 buf->allocation_expression()->set_allocate_on_stack();
8487 buf->allocation_expression()->set_no_zero();
8490 if (buf == NULL)
8491 buf = Expression::make_nil(loc);
8492 go_assert(this->exprs_->size() > 1);
8493 Expression* len =
8494 Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
8495 Array_type* array_type = Type::make_array_type(type, len);
8496 array_type->set_is_array_incomparable();
8497 Expression* array =
8498 Expression::make_array_composite_literal(array_type, this->exprs_,
8499 loc);
8500 Temporary_statement* ts =
8501 Statement::make_temporary(array_type, array, loc);
8502 ts->determine_types(gogo);
8503 inserter->insert(ts);
8504 Expression* ref = Expression::make_temporary_reference(ts, loc);
8505 ref = Expression::make_unary(OPERATOR_AND, ref, loc);
8506 Expression* call =
8507 Runtime::make_call(gogo, Runtime::CONCATSTRINGS, loc, 3, buf,
8508 ref, len->copy());
8509 Expression* ret = Expression::make_cast(type, call, loc);
8510 Type_context context(type, false);
8511 ret->determine_type(gogo, &context);
8512 return ret;
8515 void
8516 String_concat_expression::do_dump_expression(
8517 Ast_dump_context* ast_dump_context) const
8519 ast_dump_context->ostream() << "concat(";
8520 ast_dump_context->dump_expression_list(this->exprs_, false);
8521 ast_dump_context->ostream() << ")";
8524 Expression*
8525 Expression::make_string_concat(Expression_list* exprs)
8527 return new String_concat_expression(exprs);
8530 // Class Bound_method_expression.
8532 // Traversal.
8535 Bound_method_expression::do_traverse(Traverse* traverse)
8537 return Expression::traverse(&this->expr_, traverse);
8540 // Return the type of a bound method expression. The type of this
8541 // object is simply the type of the method with no receiver.
8543 Type*
8544 Bound_method_expression::do_type()
8546 Named_object* fn = this->method_->named_object();
8547 Function_type* fntype;
8548 if (fn->is_function())
8549 fntype = fn->func_value()->type();
8550 else if (fn->is_function_declaration())
8551 fntype = fn->func_declaration_value()->type();
8552 else
8553 return Type::make_error_type();
8554 return fntype->copy_without_receiver();
8557 // Determine the types of a method expression.
8559 void
8560 Bound_method_expression::do_determine_type(Gogo* gogo, const Type_context*)
8562 Named_object* fn = this->method_->named_object();
8563 Function_type* fntype;
8564 if (fn->is_function())
8565 fntype = fn->func_value()->type();
8566 else if (fn->is_function_declaration())
8567 fntype = fn->func_declaration_value()->type();
8568 else
8569 fntype = NULL;
8570 if (fntype == NULL || !fntype->is_method())
8571 this->expr_->determine_type_no_context(gogo);
8572 else
8574 Type_context subcontext(fntype->receiver()->type(), false);
8575 this->expr_->determine_type(gogo, &subcontext);
8579 // Check the types of a method expression.
8581 void
8582 Bound_method_expression::do_check_types(Gogo*)
8584 Named_object* fn = this->function();
8585 if (!fn->is_function() && !fn->is_function_declaration())
8587 this->report_error(_("object is not a method"));
8588 return;
8591 Function_type* fntype;
8592 if (fn->is_function())
8593 fntype = fn->func_value()->type();
8594 else if (fn->is_function_declaration())
8595 fntype = fn->func_declaration_value()->type();
8596 else
8597 go_unreachable();
8598 Type* rtype = fntype->receiver()->type()->deref();
8599 Type* etype = (this->expr_type_ != NULL
8600 ? this->expr_type_
8601 : this->expr_->type());
8602 etype = etype->deref();
8603 if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
8604 this->report_error(_("method type does not match object type"));
8607 // If a bound method expression is not simply called, then it is
8608 // represented as a closure. The closure will hold a single variable,
8609 // the receiver to pass to the method. The function will be a simple
8610 // thunk that pulls that value from the closure and calls the method
8611 // with the remaining arguments.
8613 // Because method values are not common, we don't build all thunks for
8614 // every methods, but instead only build them as we need them. In
8615 // particular, we even build them on demand for methods defined in
8616 // other packages.
8618 Bound_method_expression::Method_value_thunks
8619 Bound_method_expression::method_value_thunks;
8621 // Find or create the thunk for FN.
8623 Named_object*
8624 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
8625 Named_object* fn)
8627 std::pair<Named_object*, Named_object*> val(fn, NULL);
8628 std::pair<Method_value_thunks::iterator, bool> ins =
8629 Bound_method_expression::method_value_thunks.insert(val);
8630 if (!ins.second)
8632 // We have seen this method before.
8633 go_assert(ins.first->second != NULL);
8634 return ins.first->second;
8637 Location loc = fn->location();
8639 Function_type* orig_fntype;
8640 if (fn->is_function())
8641 orig_fntype = fn->func_value()->type();
8642 else if (fn->is_function_declaration())
8643 orig_fntype = fn->func_declaration_value()->type();
8644 else
8645 orig_fntype = NULL;
8647 if (orig_fntype == NULL || !orig_fntype->is_method())
8649 ins.first->second =
8650 Named_object::make_erroneous_name(gogo->thunk_name());
8651 return ins.first->second;
8654 Struct_field_list* sfl = new Struct_field_list();
8655 // The type here is wrong--it should be the C function type. But it
8656 // doesn't really matter.
8657 Type* vt = Type::make_pointer_type(Type::make_void_type());
8658 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
8659 sfl->push_back(Struct_field(Typed_identifier("val",
8660 orig_fntype->receiver()->type(),
8661 loc)));
8662 Struct_type* st = Type::make_struct_type(sfl, loc);
8663 st->set_is_struct_incomparable();
8664 Type* closure_type = Type::make_pointer_type(st);
8666 Function_type* new_fntype = orig_fntype->copy_with_names();
8668 std::string thunk_name = gogo->thunk_name();
8669 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
8670 false, loc);
8672 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
8673 cvar->set_is_used();
8674 cvar->set_is_closure();
8675 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
8676 NULL, cvar);
8677 new_no->func_value()->set_closure_var(cp);
8679 gogo->start_block(loc);
8681 // Field 0 of the closure is the function code pointer, field 1 is
8682 // the value on which to invoke the method.
8683 Expression* arg = Expression::make_var_reference(cp, loc);
8684 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
8685 arg = Expression::make_field_reference(arg, 1, loc);
8687 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
8689 const Typed_identifier_list* orig_params = orig_fntype->parameters();
8690 Expression_list* args;
8691 if (orig_params == NULL || orig_params->empty())
8692 args = NULL;
8693 else
8695 const Typed_identifier_list* new_params = new_fntype->parameters();
8696 args = new Expression_list();
8697 for (Typed_identifier_list::const_iterator p = new_params->begin();
8698 p != new_params->end();
8699 ++p)
8701 Named_object* p_no = gogo->lookup(p->name(), NULL);
8702 go_assert(p_no != NULL
8703 && p_no->is_variable()
8704 && p_no->var_value()->is_parameter());
8705 args->push_back(Expression::make_var_reference(p_no, loc));
8709 Call_expression* call = Expression::make_call(bme, args,
8710 orig_fntype->is_varargs(),
8711 loc);
8712 call->set_varargs_are_lowered();
8714 Statement* s = Statement::make_return_from_call(new_no, call, loc);
8715 s->determine_types(gogo);
8716 gogo->add_statement(s);
8717 Block* b = gogo->finish_block(loc);
8718 gogo->add_block(b, loc);
8720 // This is called after lowering.
8721 gogo->lower_block(new_no, b);
8723 gogo->finish_function(loc);
8725 ins.first->second = new_no;
8726 return new_no;
8729 // Look up a thunk for FN.
8731 Named_object*
8732 Bound_method_expression::lookup_thunk(Named_object* fn)
8734 Method_value_thunks::const_iterator p =
8735 Bound_method_expression::method_value_thunks.find(fn);
8736 if (p == Bound_method_expression::method_value_thunks.end())
8737 return NULL;
8738 return p->second;
8741 // Return an expression to check *REF for nil while dereferencing
8742 // according to FIELD_INDEXES. Update *REF to build up the field
8743 // reference. This is a static function so that we don't have to
8744 // worry about declaring Field_indexes in expressions.h.
8746 static Expression*
8747 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
8748 Expression** ref)
8750 if (field_indexes == NULL)
8751 return Expression::make_boolean(false, loc);
8752 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
8753 Struct_type* stype = (*ref)->type()->deref()->struct_type();
8754 go_assert(stype != NULL
8755 && field_indexes->field_index < stype->field_count());
8756 if ((*ref)->type()->struct_type() == NULL)
8758 go_assert((*ref)->type()->points_to() != NULL);
8759 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
8760 Expression::make_nil(loc),
8761 loc);
8762 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
8763 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
8764 loc);
8765 go_assert((*ref)->type()->struct_type() == stype);
8767 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
8768 loc);
8769 return cond;
8772 // Flatten a method value into a struct with nil checks. We can't do
8773 // this in the lowering phase, because if the method value is called
8774 // directly we don't need a thunk. That case will have been handled
8775 // by Call_expression::do_lower, so if we get here then we do need a
8776 // thunk.
8778 Expression*
8779 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
8780 Statement_inserter* inserter)
8782 Location loc = this->location();
8784 Named_object* thunk = Bound_method_expression::lookup_thunk(this->function_);
8786 // The thunk should have been created during the
8787 // create_function_descriptors pass.
8788 if (thunk == NULL || thunk->is_erroneous())
8790 go_assert(saw_errors());
8791 return Expression::make_error(loc);
8794 // Force the expression into a variable. This is only necessary if
8795 // we are going to do nil checks below, but it's easy enough to
8796 // always do it.
8797 Expression* expr = this->expr_;
8798 if (!expr->is_multi_eval_safe())
8800 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
8801 inserter->insert(etemp);
8802 expr = Expression::make_temporary_reference(etemp, loc);
8805 // If the method expects a value, and we have a pointer, we need to
8806 // dereference the pointer.
8808 Named_object* fn = this->method_->named_object();
8809 Function_type *fntype;
8810 if (fn->is_function())
8811 fntype = fn->func_value()->type();
8812 else if (fn->is_function_declaration())
8813 fntype = fn->func_declaration_value()->type();
8814 else
8815 go_unreachable();
8817 Expression* val = expr;
8818 if (fntype->receiver()->type()->points_to() == NULL
8819 && val->type()->points_to() != NULL)
8820 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8822 // Note that we are ignoring this->expr_type_ here. The thunk will
8823 // expect a closure whose second field has type this->expr_type_ (if
8824 // that is not NULL). We are going to pass it a closure whose
8825 // second field has type this->expr_->type(). Since
8826 // this->expr_type_ is only not-NULL for pointer types, we can get
8827 // away with this.
8829 Struct_field_list* fields = new Struct_field_list();
8830 fields->push_back(Struct_field(Typed_identifier("fn",
8831 thunk->func_value()->type(),
8832 loc)));
8833 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8834 Struct_type* st = Type::make_struct_type(fields, loc);
8835 st->set_is_struct_incomparable();
8837 Expression_list* vals = new Expression_list();
8838 vals->push_back(Expression::make_func_code_reference(thunk, loc));
8839 vals->push_back(val);
8841 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8842 ret = Expression::make_heap_expression(ret, loc);
8844 Node* node = Node::make_node(this);
8845 if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8846 ret->heap_expression()->set_allocate_on_stack();
8847 else if (gogo->compiling_runtime()
8848 && gogo->package_name() == "runtime"
8849 && !saw_errors())
8850 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8851 node->ast_format(gogo).c_str());
8853 // If necessary, check whether the expression or any embedded
8854 // pointers are nil.
8856 Expression* nil_check = NULL;
8857 if (this->method_->field_indexes() != NULL)
8859 Expression* ref = expr;
8860 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8861 expr = ref;
8864 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8866 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8867 Expression::make_nil(loc),
8868 loc);
8869 if (nil_check == NULL)
8870 nil_check = n;
8871 else
8872 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8875 if (nil_check != NULL)
8877 Expression* crash = Runtime::make_call(gogo, Runtime::PANIC_MEM, loc, 0);
8878 // Fix the type of the conditional expression by pretending to
8879 // evaluate to RET either way through the conditional.
8880 crash->determine_type_no_context(gogo);
8881 crash = Expression::make_compound(crash, ret, loc);
8882 ret = Expression::make_conditional(nil_check, crash, ret, loc);
8885 // RET is a pointer to a struct, but we want a function type.
8886 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8888 ret->determine_type_no_context(gogo);
8890 return ret;
8893 // Dump ast representation of a bound method expression.
8895 void
8896 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8897 const
8899 if (this->expr_type_ != NULL)
8900 ast_dump_context->ostream() << "(";
8901 ast_dump_context->dump_expression(this->expr_);
8902 if (this->expr_type_ != NULL)
8904 ast_dump_context->ostream() << ":";
8905 ast_dump_context->dump_type(this->expr_type_);
8906 ast_dump_context->ostream() << ")";
8909 ast_dump_context->ostream() << "." << this->function_->name();
8912 // Make a method expression.
8914 Bound_method_expression*
8915 Expression::make_bound_method(Expression* expr, const Method* method,
8916 Named_object* function, Location location)
8918 return new Bound_method_expression(expr, method, function, location);
8921 // A general selector. This is a Parser_expression for LEFT.NAME. It
8922 // is lowered after we know the type of the left hand side.
8924 class Selector_expression : public Parser_expression
8926 public:
8927 Selector_expression(Expression* left, const std::string& name,
8928 Location location)
8929 : Parser_expression(EXPRESSION_SELECTOR, location),
8930 left_(left), name_(name), resolved_(NULL)
8933 // Return the resolved selector. This will typically be a
8934 // Field_reference_expression or a Bound_method_expression or an
8935 // Interface_field_reference_expression.
8936 Expression*
8937 resolved()
8938 { return this->resolved_; }
8940 protected:
8942 do_traverse(Traverse* traverse)
8943 { return Expression::traverse(&this->left_, traverse); }
8945 Type*
8946 do_type();
8948 void
8949 do_determine_type(Gogo*, const Type_context*);
8951 bool
8952 do_is_addressable() const;
8954 void
8955 do_issue_nil_check();
8957 Expression*
8958 do_lower(Gogo*, Named_object*, Statement_inserter*);
8960 Expression*
8961 do_copy()
8963 return new Selector_expression(this->left_->copy(), this->name_,
8964 this->location());
8967 void
8968 do_dump_expression(Ast_dump_context* ast_dump_context) const;
8970 private:
8971 Expression*
8972 lower_method_expression(Gogo*);
8974 // The expression on the left hand side.
8975 Expression* left_;
8976 // The name on the right hand side.
8977 std::string name_;
8978 // The resolved expression.
8979 Expression* resolved_;
8982 void
8983 Selector_expression::do_determine_type(Gogo* gogo, const Type_context* context)
8985 if (this->is_error_expression() || this->resolved_ != NULL)
8986 return;
8987 Expression* left = this->left_;
8988 left->determine_type_no_context(gogo);
8989 if (left->is_error_expression())
8990 this->set_is_error();
8991 else
8993 if (left->is_type_expression())
8994 this->resolved_ = this->lower_method_expression(gogo);
8995 else
8996 this->resolved_ = Type::bind_field_or_method(gogo, left->type(), left,
8997 this->name_,
8998 this->location());
8999 this->resolved_->determine_type(gogo, context);
9003 Type*
9004 Selector_expression::do_type()
9006 if (this->is_error_expression())
9007 return Type::make_error_type();
9008 go_assert(this->resolved_ != NULL);
9009 return this->resolved_->type();
9012 bool
9013 Selector_expression::do_is_addressable() const
9015 if (this->is_error_expression())
9016 return true;
9017 go_assert(this->resolved_ != NULL);
9018 return this->resolved_->is_addressable();
9021 void
9022 Selector_expression::do_issue_nil_check()
9024 if (this->is_error_expression())
9025 return;
9026 go_assert(this->resolved_ != NULL);
9027 this->resolved_->issue_nil_check();
9030 // Lower a selector expression to the resolved value.
9032 Expression*
9033 Selector_expression::do_lower(Gogo*, Named_object*, Statement_inserter*)
9035 if (this->is_error_expression() || this->resolved_ == NULL)
9036 return Expression::make_error(this->location());
9037 return this->resolved_;
9040 // Lower a method expression T.M or (*T).M. We turn this into a
9041 // function literal.
9043 Expression*
9044 Selector_expression::lower_method_expression(Gogo* gogo)
9046 Location location = this->location();
9047 Type* left_type = this->left_->type();
9048 Type* type = left_type;
9049 const std::string& name(this->name_);
9051 bool is_pointer;
9052 if (type->points_to() == NULL)
9053 is_pointer = false;
9054 else
9056 is_pointer = true;
9057 type = type->points_to();
9060 Named_type* nt = type->named_type();
9061 Struct_type* st = type->struct_type();
9062 bool is_ambiguous = false;
9063 Method* method = NULL;
9064 if (nt != NULL)
9065 method = nt->method_function(name, &is_ambiguous);
9066 else if (st != NULL)
9067 method = st->method_function(name, &is_ambiguous);
9068 const Typed_identifier* imethod = NULL;
9069 if (method == NULL && !is_pointer)
9071 Interface_type* it = type->interface_type();
9072 if (it != NULL)
9073 imethod = it->find_method(name);
9076 if ((method == NULL && imethod == NULL)
9077 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
9079 if (nt != NULL)
9081 if (!is_ambiguous)
9082 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
9083 is_pointer ? "*" : "",
9084 nt->message_name().c_str(),
9085 Gogo::message_name(name).c_str());
9086 else
9087 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
9088 Gogo::message_name(name).c_str(),
9089 is_pointer ? "*" : "",
9090 nt->message_name().c_str());
9092 else
9094 if (!is_ambiguous)
9095 go_error_at(location, "type has no method %<%s%>",
9096 Gogo::message_name(name).c_str());
9097 else
9098 go_error_at(location, "method %<%s%> is ambiguous",
9099 Gogo::message_name(name).c_str());
9101 return Expression::make_error(location);
9104 if (method != NULL && !is_pointer && !method->is_value_method())
9106 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
9107 nt->message_name().c_str(),
9108 Gogo::message_name(name).c_str());
9109 return Expression::make_error(location);
9112 // Build a new function type in which the receiver becomes the first
9113 // argument.
9114 Function_type* method_type;
9115 if (method != NULL)
9117 method_type = method->type();
9118 go_assert(method_type->is_method());
9120 else
9122 method_type = imethod->type()->function_type();
9123 go_assert(method_type != NULL && !method_type->is_method());
9126 const char* const receiver_name = "$this";
9127 Typed_identifier_list* parameters = new Typed_identifier_list();
9128 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
9129 location));
9131 const Typed_identifier_list* method_parameters = method_type->parameters();
9132 if (method_parameters != NULL)
9134 int i = 0;
9135 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
9136 p != method_parameters->end();
9137 ++p, ++i)
9139 if (!p->name().empty() && !Gogo::is_sink_name(p->name()))
9140 parameters->push_back(*p);
9141 else
9143 char buf[20];
9144 snprintf(buf, sizeof buf, "$param%d", i);
9145 parameters->push_back(Typed_identifier(buf, p->type(),
9146 p->location()));
9151 const Typed_identifier_list* method_results = method_type->results();
9152 Typed_identifier_list* results;
9153 if (method_results == NULL)
9154 results = NULL;
9155 else
9157 results = new Typed_identifier_list();
9158 for (Typed_identifier_list::const_iterator p = method_results->begin();
9159 p != method_results->end();
9160 ++p)
9161 results->push_back(*p);
9164 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
9165 location);
9166 if (method_type->is_varargs())
9167 fntype->set_is_varargs();
9169 // We generate methods which always takes a pointer to the receiver
9170 // as their first argument. If this is for a pointer type, we can
9171 // simply reuse the existing function. We use an internal hack to
9172 // get the right type.
9173 // FIXME: This optimization is disabled because it doesn't yet work
9174 // with function descriptors when the method expression is not
9175 // directly called.
9176 if (method != NULL && is_pointer && false)
9178 Named_object* mno = (method->needs_stub_method()
9179 ? method->stub_object()
9180 : method->named_object());
9181 Expression* f = Expression::make_func_reference(mno, NULL, location);
9182 f = Expression::make_cast(fntype, f, location);
9183 Type_conversion_expression* tce =
9184 static_cast<Type_conversion_expression*>(f);
9185 tce->set_may_convert_function_types();
9186 return f;
9189 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
9190 location);
9192 Named_object* vno = gogo->lookup(receiver_name, NULL);
9193 go_assert(vno != NULL);
9194 Expression* ve = Expression::make_var_reference(vno, location);
9195 Expression* bm;
9196 if (method != NULL)
9197 bm = Type::bind_field_or_method(gogo, type, ve, name, location);
9198 else
9199 bm = Expression::make_interface_field_reference(ve, name, location);
9201 // Even though we found the method above, if it has an error type we
9202 // may see an error here.
9203 if (bm->is_error_expression())
9205 gogo->finish_function(location);
9206 return bm;
9209 Expression_list* args;
9210 if (parameters->size() <= 1)
9211 args = NULL;
9212 else
9214 args = new Expression_list();
9215 Typed_identifier_list::const_iterator p = parameters->begin();
9216 ++p;
9217 for (; p != parameters->end(); ++p)
9219 vno = gogo->lookup(p->name(), NULL);
9220 go_assert(vno != NULL);
9221 args->push_back(Expression::make_var_reference(vno, location));
9225 gogo->start_block(location);
9227 Call_expression* call = Expression::make_call(bm, args,
9228 method_type->is_varargs(),
9229 location);
9231 Statement* s = Statement::make_return_from_call(no, call, location);
9232 s->determine_types(gogo);
9233 gogo->add_statement(s);
9235 Block* b = gogo->finish_block(location);
9237 gogo->add_block(b, location);
9239 gogo->finish_function(location);
9241 return Expression::make_func_reference(no, NULL, location);
9244 // Dump the ast for a selector expression.
9246 void
9247 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9248 const
9250 ast_dump_context->dump_expression(this->left_);
9251 ast_dump_context->ostream() << ".";
9252 ast_dump_context->ostream() << this->name_;
9255 // Make a selector expression.
9257 Expression*
9258 Expression::make_selector(Expression* left, const std::string& name,
9259 Location location)
9261 return new Selector_expression(left, name, location);
9264 // Class Builtin_call_expression. This is used for a call to a
9265 // builtin function.
9267 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
9268 Expression* fn,
9269 Expression_list* args,
9270 bool is_varargs,
9271 Location location)
9272 : Call_expression(fn, args, is_varargs, location),
9273 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
9274 recover_arg_is_set_(false)
9276 const Named_object* no;
9277 if (fn->is_error_expression())
9279 this->code_ = BUILTIN_INVALID;
9280 return;
9282 else if (fn->func_expression() != NULL)
9283 no = fn->func_expression()->named_object();
9284 else if (fn->unknown_expression() != NULL)
9285 no = fn->unknown_expression()->named_object();
9286 else
9287 go_unreachable();
9289 const std::string& name(no->name());
9290 if (name == "append")
9291 this->code_ = BUILTIN_APPEND;
9292 else if (name == "cap")
9293 this->code_ = BUILTIN_CAP;
9294 else if (name == "close")
9295 this->code_ = BUILTIN_CLOSE;
9296 else if (name == "complex")
9297 this->code_ = BUILTIN_COMPLEX;
9298 else if (name == "copy")
9299 this->code_ = BUILTIN_COPY;
9300 else if (name == "delete")
9301 this->code_ = BUILTIN_DELETE;
9302 else if (name == "imag")
9303 this->code_ = BUILTIN_IMAG;
9304 else if (name == "len")
9305 this->code_ = BUILTIN_LEN;
9306 else if (name == "make")
9307 this->code_ = BUILTIN_MAKE;
9308 else if (name == "new")
9309 this->code_ = BUILTIN_NEW;
9310 else if (name == "panic")
9311 this->code_ = BUILTIN_PANIC;
9312 else if (name == "print")
9313 this->code_ = BUILTIN_PRINT;
9314 else if (name == "println")
9315 this->code_ = BUILTIN_PRINTLN;
9316 else if (name == "real")
9317 this->code_ = BUILTIN_REAL;
9318 else if (name == "recover")
9319 this->code_ = BUILTIN_RECOVER;
9320 else if (name == "Add")
9321 this->code_ = BUILTIN_ADD;
9322 else if (name == "Alignof")
9323 this->code_ = BUILTIN_ALIGNOF;
9324 else if (name == "Offsetof")
9325 this->code_ = BUILTIN_OFFSETOF;
9326 else if (name == "Sizeof")
9327 this->code_ = BUILTIN_SIZEOF;
9328 else if (name == "Slice")
9329 this->code_ = BUILTIN_SLICE;
9330 else
9331 go_unreachable();
9334 // Return whether this is a call to recover. This is a virtual
9335 // function called from the parent class.
9337 bool
9338 Builtin_call_expression::do_is_recover_call() const
9340 if (this->classification() == EXPRESSION_ERROR)
9341 return false;
9342 return this->code_ == BUILTIN_RECOVER;
9345 // Set the argument for a call to recover.
9347 void
9348 Builtin_call_expression::do_set_recover_arg(Expression* arg)
9350 const Expression_list* args = this->args();
9351 go_assert(args == NULL || args->empty());
9352 Expression_list* new_args = new Expression_list();
9353 new_args->push_back(arg);
9354 this->set_args(new_args);
9355 this->recover_arg_is_set_ = true;
9358 // Lower a builtin call expression. This turns new and make into
9359 // specific expressions. We also convert to a constant if we can.
9361 Expression*
9362 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
9363 Statement_inserter* inserter)
9365 if (this->is_error_expression())
9366 return this;
9368 Location loc = this->location();
9370 if (this->code_ == BUILTIN_OFFSETOF)
9372 Expression* arg = this->one_arg();
9373 Field_reference_expression* farg = arg->field_reference_expression();
9374 while (farg != NULL)
9376 if (!farg->implicit())
9377 break;
9378 // When the selector refers to an embedded field,
9379 // it must not be reached through pointer indirections.
9380 if (farg->expr()->deref() != farg->expr())
9382 this->report_error(_("argument of Offsetof implies "
9383 "indirection of an embedded field"));
9384 return this;
9386 // Go up until we reach the original base.
9387 farg = farg->expr()->field_reference_expression();
9391 if (this->is_constant())
9393 Numeric_constant nc;
9394 if (this->numeric_constant_value(&nc))
9396 Expression* ret = nc.expression(loc);
9397 Type_context subcontext;
9398 if (this->type() != NULL)
9399 subcontext = Type_context(this->type(),
9400 this->type()->is_abstract());
9401 ret->determine_type(gogo, &subcontext);
9402 return ret;
9406 switch (this->code_)
9408 default:
9409 break;
9411 case BUILTIN_NEW:
9412 return Expression::make_allocation(this->one_arg()->type(), loc);
9414 case BUILTIN_MAKE:
9415 return this->lower_make(gogo, inserter);
9417 case BUILTIN_RECOVER:
9418 if (function != NULL)
9419 function->func_value()->set_calls_recover();
9420 else
9422 // Calling recover outside of a function always returns the
9423 // nil empty interface.
9424 Type* eface = Type::make_empty_interface_type(loc);
9425 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
9427 break;
9429 case BUILTIN_DELETE:
9431 const Expression_list* args = this->args();
9432 Type* key_type =
9433 args->front()->type()->map_type()->key_type();
9434 Expression_list::iterator pa = this->args()->begin();
9435 pa++;
9436 Type* arg_type = (*pa)->type();
9437 if (!Type::are_identical(key_type, arg_type, 0, NULL))
9438 *pa = Expression::make_cast(key_type, *pa, loc);
9440 break;
9442 case BUILTIN_PRINT:
9443 case BUILTIN_PRINTLN:
9444 // Force all the arguments into temporary variables, so that we
9445 // don't try to evaluate something while holding the print lock.
9446 if (this->args() == NULL)
9447 break;
9448 for (Expression_list::iterator pa = this->args()->begin();
9449 pa != this->args()->end();
9450 ++pa)
9452 if (!(*pa)->is_multi_eval_safe())
9454 Temporary_statement* temp =
9455 Statement::make_temporary(NULL, *pa, loc);
9456 inserter->insert(temp);
9457 *pa = Expression::make_temporary_reference(temp, loc);
9460 break;
9463 return this;
9466 // Flatten a builtin call expression. This turns the arguments of some
9467 // builtin calls into temporary expressions. Also expand copy and append
9468 // to runtime calls.
9470 Expression*
9471 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
9472 Statement_inserter* inserter)
9474 if (this->is_error_expression())
9476 go_assert(saw_errors());
9477 return this;
9480 Location loc = this->location();
9482 switch (this->code_)
9484 default:
9485 break;
9487 case BUILTIN_APPEND:
9488 return this->flatten_append(gogo, function, inserter, NULL, NULL);
9490 case BUILTIN_COPY:
9492 Type* at = this->args()->front()->type();
9493 for (Expression_list::iterator pa = this->args()->begin();
9494 pa != this->args()->end();
9495 ++pa)
9497 if ((*pa)->is_error_expression())
9499 go_assert(saw_errors());
9500 return Expression::make_error(loc);
9502 if ((*pa)->is_nil_expression())
9504 Expression* nil = Expression::make_nil(loc);
9505 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
9506 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
9508 if (!(*pa)->is_multi_eval_safe())
9510 Temporary_statement* temp =
9511 Statement::make_temporary(NULL, *pa, loc);
9512 inserter->insert(temp);
9513 *pa = Expression::make_temporary_reference(temp, loc);
9517 // Lower to runtime call.
9518 const Expression_list* args = this->args();
9519 go_assert(args != NULL && args->size() == 2);
9520 Expression* arg1 = args->front();
9521 Expression* arg2 = args->back();
9522 go_assert(arg1->is_multi_eval_safe());
9523 go_assert(arg2->is_multi_eval_safe());
9524 bool arg2_is_string = arg2->type()->is_string_type();
9526 Expression* ret;
9527 Type* et = at->array_type()->element_type();
9528 if (et->has_pointer())
9530 Expression* td = Expression::make_type_descriptor(et, loc);
9531 Expression* pd =
9532 Expression::make_slice_info(arg1, SLICE_INFO_VALUE_POINTER, loc);
9533 Expression* ld =
9534 Expression::make_slice_info(arg1, SLICE_INFO_LENGTH, loc);
9535 Expression* ps =
9536 Expression::make_slice_info(arg2, SLICE_INFO_VALUE_POINTER, loc);
9537 Expression* ls =
9538 Expression::make_slice_info(arg2, SLICE_INFO_LENGTH, loc);
9539 ret = Runtime::make_call(gogo, Runtime::TYPEDSLICECOPY, loc,
9540 5, td, pd, ld, ps, ls);
9542 else
9544 Type* int_type = Type::lookup_integer_type("int");
9545 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9547 // l1 = len(arg1)
9548 Named_object* lenfn = gogo->lookup_global("len");
9549 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
9550 Expression_list* len_args = new Expression_list();
9551 len_args->push_back(arg1->copy());
9552 Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
9553 gogo->lower_expression(function, inserter, &len1);
9554 gogo->flatten_expression(function, inserter, &len1);
9555 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
9556 l1tmp->determine_types(gogo);
9557 inserter->insert(l1tmp);
9559 // l2 = len(arg2)
9560 len_args = new Expression_list();
9561 len_args->push_back(arg2->copy());
9562 Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
9563 gogo->lower_expression(function, inserter, &len2);
9564 gogo->flatten_expression(function, inserter, &len2);
9565 Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
9566 l2tmp->determine_types(gogo);
9567 inserter->insert(l2tmp);
9569 // n = (l1 < l2 ? l1 : l2)
9570 Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
9571 Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
9572 Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
9573 Expression* n = Expression::make_conditional(cond,
9574 l1ref->copy(),
9575 l2ref->copy(),
9576 loc);
9577 Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
9578 ntmp->determine_types(gogo);
9579 inserter->insert(ntmp);
9581 // sz = n * sizeof(elem_type)
9582 Expression* nref = Expression::make_temporary_reference(ntmp, loc);
9583 nref = Expression::make_cast(uintptr_type, nref, loc);
9584 Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
9585 sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
9587 // memmove(arg1.ptr, arg2.ptr, sz)
9588 Expression* p1 = Expression::make_slice_info(arg1,
9589 SLICE_INFO_VALUE_POINTER,
9590 loc);
9591 Expression* p2 = (arg2_is_string
9592 ? Expression::make_string_info(arg2,
9593 STRING_INFO_DATA,
9594 loc)
9595 : Expression::make_slice_info(arg2,
9596 SLICE_INFO_VALUE_POINTER,
9597 loc));
9598 Expression* call = Runtime::make_call(gogo,
9599 Runtime::BUILTIN_MEMMOVE,
9600 loc, 3,
9601 p1, p2, sz);
9603 // n is the return value of copy
9604 nref = Expression::make_temporary_reference(ntmp, loc);
9605 ret = Expression::make_compound(call, nref, loc);
9607 ret->determine_type_no_context(gogo);
9608 return ret;
9610 break;
9612 case BUILTIN_PANIC:
9613 for (Expression_list::iterator pa = this->args()->begin();
9614 pa != this->args()->end();
9615 ++pa)
9617 if (!(*pa)->is_multi_eval_safe()
9618 && (*pa)->type()->interface_type() != NULL)
9620 Temporary_statement* temp =
9621 Statement::make_temporary(NULL, *pa, loc);
9622 inserter->insert(temp);
9623 *pa = Expression::make_temporary_reference(temp, loc);
9626 break;
9628 case BUILTIN_LEN:
9629 case BUILTIN_CAP:
9631 Expression_list::iterator pa = this->args()->begin();
9632 if (!(*pa)->is_multi_eval_safe()
9633 && ((*pa)->type()->map_type() != NULL
9634 || (*pa)->type()->channel_type() != NULL))
9636 Temporary_statement* temp =
9637 Statement::make_temporary(NULL, *pa, loc);
9638 inserter->insert(temp);
9639 *pa = Expression::make_temporary_reference(temp, loc);
9642 break;
9644 case BUILTIN_DELETE:
9646 // Lower to a runtime function call.
9647 const Expression_list* args = this->args();
9649 // Since this function returns no value it must appear in
9650 // a statement by itself, so we don't have to worry about
9651 // order of evaluation of values around it. Evaluate the
9652 // map first to get order of evaluation right.
9653 Map_type* mt = args->front()->type()->map_type();
9654 Temporary_statement* map_temp =
9655 Statement::make_temporary(mt, args->front(), loc);
9656 inserter->insert(map_temp);
9658 Temporary_statement* key_temp =
9659 Statement::make_temporary(mt->key_type(), args->back(), loc);
9660 inserter->insert(key_temp);
9662 Expression* e1 = Expression::make_type_descriptor(mt, loc);
9663 Expression* e2 = Expression::make_temporary_reference(map_temp,
9664 loc);
9665 Expression* e3 = Expression::make_temporary_reference(key_temp,
9666 loc);
9668 Runtime::Function code;
9669 switch (mt->algorithm(gogo))
9671 case Map_type::MAP_ALG_FAST32:
9672 case Map_type::MAP_ALG_FAST32PTR:
9674 code = Runtime::MAPDELETE_FAST32;
9675 Type* uint32_type = Type::lookup_integer_type("uint32");
9676 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
9677 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
9678 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
9679 loc);
9680 e3 = Expression::make_dereference(e3,
9681 Expression::NIL_CHECK_NOT_NEEDED,
9682 loc);
9683 break;
9685 case Map_type::MAP_ALG_FAST64:
9686 case Map_type::MAP_ALG_FAST64PTR:
9688 code = Runtime::MAPDELETE_FAST64;
9689 Type* uint64_type = Type::lookup_integer_type("uint64");
9690 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
9691 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
9692 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
9693 loc);
9694 e3 = Expression::make_dereference(e3,
9695 Expression::NIL_CHECK_NOT_NEEDED,
9696 loc);
9697 break;
9699 case Map_type::MAP_ALG_FASTSTR:
9700 code = Runtime::MAPDELETE_FASTSTR;
9701 break;
9702 default:
9703 code = Runtime::MAPDELETE;
9705 // If the call to delete is deferred, and is in a loop,
9706 // then the loop will only have a single instance of the
9707 // temporary variable. Passing the address of the
9708 // temporary variable here means that the deferred call
9709 // will see the last value in the loop, not the current
9710 // value. So for this unusual case copy the value into
9711 // the heap.
9712 if (!this->is_deferred())
9713 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
9714 else
9716 Expression* a = Expression::make_allocation(mt->key_type(),
9717 loc);
9718 Temporary_statement* atemp =
9719 Statement::make_temporary(NULL, a, loc);
9720 atemp->determine_types(gogo);
9721 inserter->insert(atemp);
9723 a = Expression::make_temporary_reference(atemp, loc);
9724 a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
9725 Statement* s = Statement::make_assignment(a, e3, loc);
9726 s->determine_types(gogo);
9727 inserter->insert(s);
9729 e3 = Expression::make_temporary_reference(atemp, loc);
9733 Expression* ret = Runtime::make_call(gogo, code, loc, 3, e1, e2, e3);
9734 ret->determine_type_no_context(gogo);
9735 return ret;
9738 case BUILTIN_ADD:
9740 Expression* ptr = this->args()->front();
9741 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9742 ptr = Expression::make_cast(uintptr_type, ptr, loc);
9743 Expression* len = this->args()->back();
9744 len = Expression::make_cast(uintptr_type, len, loc);
9745 Expression* add = Expression::make_binary(OPERATOR_PLUS, ptr, len,
9746 loc);
9747 Expression* ret = Expression::make_cast(this->args()->front()->type(),
9748 add, loc);
9749 ret->determine_type_no_context(gogo);
9750 return ret;
9753 case BUILTIN_SLICE:
9755 Expression* ptr = this->args()->front();
9756 Temporary_statement* ptr_temp = NULL;
9757 if (!ptr->is_multi_eval_safe())
9759 ptr_temp = Statement::make_temporary(NULL, ptr, loc);
9760 inserter->insert(ptr_temp);
9761 ptr = Expression::make_temporary_reference(ptr_temp, loc);
9764 Expression* len = this->args()->back();
9765 Temporary_statement* len_temp = NULL;
9766 if (!len->is_multi_eval_safe())
9768 len_temp = Statement::make_temporary(NULL, len, loc);
9769 inserter->insert(len_temp);
9770 len = Expression::make_temporary_reference(len_temp, loc);
9773 bool fits_in_int;
9774 Numeric_constant nc;
9775 if (this->args()->back()->numeric_constant_value(&nc))
9777 // We gave an error for constants that don't fit in int in
9778 // check_types.
9779 fits_in_int = true;
9781 else
9783 Integer_type* itype = this->args()->back()->type()->integer_type();
9784 go_assert(itype != NULL);
9785 int ebits = itype->bits();
9786 int intbits =
9787 Type::lookup_integer_type("int")->integer_type()->bits();
9789 // We can treat ebits == intbits as small even for an
9790 // unsigned integer type, because we will convert the
9791 // value to int and then reject it in the runtime if it is
9792 // negative.
9794 fits_in_int = ebits <= intbits;
9797 Runtime::Function code = (fits_in_int
9798 ? Runtime::UNSAFESLICE
9799 : Runtime::UNSAFESLICE64);
9800 Expression* td =
9801 Expression::make_type_descriptor(ptr->type()->points_to(), loc);
9802 Expression* check = Runtime::make_call(gogo, code, loc, 3,
9803 td, ptr, len);
9805 if (ptr_temp == NULL)
9806 ptr = ptr->copy();
9807 else
9808 ptr = Expression::make_temporary_reference(ptr_temp, loc);
9809 Expression* nil = Expression::make_nil(loc);
9810 nil = Expression::make_cast(ptr->type(), nil, loc);
9811 Expression* is_nil = Expression::make_binary(OPERATOR_EQEQ, ptr, nil,
9812 loc);
9814 if (len_temp == NULL)
9815 len = len->copy();
9816 else
9817 len = Expression::make_temporary_reference(len_temp, loc);
9818 Expression* zero = Expression::make_integer_ul(0, len->type(), loc);
9819 Expression* is_zero = Expression::make_binary(OPERATOR_EQEQ, len, zero,
9820 loc);
9822 Expression* cond = Expression::make_binary(OPERATOR_ANDAND, is_nil,
9823 is_zero, loc);
9825 Type* slice_type = Type::make_array_type(ptr->type()->points_to(),
9826 NULL);
9827 nil = Expression::make_nil(loc);
9828 Expression* nil_slice = Expression::make_cast(slice_type, nil, loc);
9830 if (ptr_temp == NULL)
9831 ptr = ptr->copy();
9832 else
9833 ptr = Expression::make_temporary_reference(ptr_temp, loc);
9835 if (len_temp == NULL)
9836 len = len->copy();
9837 else
9838 len = Expression::make_temporary_reference(len_temp, loc);
9840 Expression* cap;
9841 if (len_temp == NULL)
9842 cap = len->copy();
9843 else
9844 cap = Expression::make_temporary_reference(len_temp, loc);
9846 Expression* slice = Expression::make_slice_value(slice_type, ptr,
9847 len, cap, loc);
9849 slice = Expression::make_conditional(cond, nil_slice, slice, loc);
9851 Expression* ret = Expression::make_compound(check, slice, loc);
9852 ret->determine_type_no_context(gogo);
9853 return ret;
9857 return this;
9860 // Lower a make expression.
9862 Expression*
9863 Builtin_call_expression::lower_make(Gogo* gogo, Statement_inserter* inserter)
9865 Location loc = this->location();
9867 const Expression_list* args = this->args();
9869 Expression_list::const_iterator parg = args->begin();
9871 Expression* first_arg = *parg;
9872 go_assert(first_arg->is_type_expression());
9873 Type* type = first_arg->type();
9875 bool is_slice = false;
9876 bool is_map = false;
9877 bool is_chan = false;
9878 if (type->is_slice_type())
9879 is_slice = true;
9880 else if (type->map_type() != NULL)
9881 is_map = true;
9882 else if (type->channel_type() != NULL)
9883 is_chan = true;
9884 else
9885 go_unreachable();
9887 ++parg;
9888 Expression* len_arg;
9889 bool len_small = false;
9890 if (parg == args->end())
9892 go_assert(!is_slice);
9893 len_arg = Expression::make_integer_ul(0, NULL, loc);
9894 len_small = true;
9896 else
9898 len_arg = *parg;
9899 if (!this->check_int_value(len_arg, true, &len_small))
9900 return Expression::make_error(this->location());
9901 ++parg;
9904 Expression* cap_arg = NULL;
9905 bool cap_small = false;
9906 Numeric_constant nclen;
9907 Numeric_constant nccap;
9908 unsigned long vlen;
9909 unsigned long vcap;
9910 if (is_slice && parg != args->end())
9912 cap_arg = *parg;
9913 if (!this->check_int_value(cap_arg, false, &cap_small))
9914 return Expression::make_error(this->location());
9916 if (len_arg->numeric_constant_value(&nclen)
9917 && cap_arg->numeric_constant_value(&nccap)
9918 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
9919 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
9920 && vlen > vcap)
9922 this->report_error(_("len larger than cap"));
9923 return Expression::make_error(this->location());
9926 ++parg;
9929 go_assert(parg == args->end());
9931 Location type_loc = first_arg->location();
9933 Expression* call;
9934 if (is_slice)
9936 Temporary_statement* len_temp = NULL;
9937 if (!len_arg->is_constant())
9939 len_temp = Statement::make_temporary(NULL, len_arg, loc);
9940 inserter->insert(len_temp);
9941 len_arg = Expression::make_temporary_reference(len_temp, loc);
9944 if (cap_arg == NULL)
9946 cap_small = len_small;
9947 if (len_temp == NULL)
9948 cap_arg = len_arg->copy();
9949 else
9950 cap_arg = Expression::make_temporary_reference(len_temp, loc);
9952 else if (!cap_arg->is_constant())
9954 Temporary_statement* cap_temp = Statement::make_temporary(NULL,
9955 cap_arg,
9956 loc);
9957 inserter->insert(cap_temp);
9958 cap_arg = Expression::make_temporary_reference(cap_temp, loc);
9961 Type* et = type->array_type()->element_type();
9962 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
9963 Runtime::Function code = Runtime::MAKESLICE;
9964 if (!len_small || !cap_small)
9965 code = Runtime::MAKESLICE64;
9966 Expression* mem = Runtime::make_call(gogo, code, loc, 3,
9967 type_arg, len_arg, cap_arg);
9968 mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
9969 loc);
9970 Type* int_type = Type::lookup_integer_type("int");
9971 len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
9972 cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
9973 call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
9975 else if (is_map)
9977 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
9978 if (!len_small)
9979 call = Runtime::make_call(gogo, Runtime::MAKEMAP64, loc, 3, type_arg,
9980 len_arg,
9981 Expression::make_nil(loc));
9982 else
9984 if (len_arg->numeric_constant_value(&nclen)
9985 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
9986 && vlen <= Map_type::bucket_size)
9987 call = Runtime::make_call(gogo, Runtime::MAKEMAP_SMALL, loc, 0);
9988 else
9989 call = Runtime::make_call(gogo, Runtime::MAKEMAP, loc, 3, type_arg,
9990 len_arg,
9991 Expression::make_nil(loc));
9994 else if (is_chan)
9996 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
9997 Runtime::Function code = Runtime::MAKECHAN;
9998 if (!len_small)
9999 code = Runtime::MAKECHAN64;
10000 call = Runtime::make_call(gogo, code, loc, 2, type_arg, len_arg);
10002 else
10003 go_unreachable();
10005 Expression* ret = Expression::make_unsafe_cast(type, call, loc);
10006 ret->determine_type_no_context(gogo);
10007 return ret;
10010 // Flatten a call to the predeclared append function. We do this in
10011 // the flatten phase, not the lowering phase, so that we run after
10012 // type checking and after order_evaluations. If ASSIGN_LHS is not
10013 // NULL, this append is the right-hand-side of an assignment and
10014 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
10015 // rather than returning a slice. This lets us omit a write barrier
10016 // in common cases like a = append(a, ...) when the slice does not
10017 // need to grow. ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
10019 Expression*
10020 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
10021 Statement_inserter* inserter,
10022 Expression* assign_lhs,
10023 Block* enclosing)
10025 if (this->is_error_expression())
10026 return this;
10028 Location loc = this->location();
10030 const Expression_list* args = this->args();
10031 go_assert(args != NULL && !args->empty());
10033 Type* slice_type = args->front()->type();
10034 go_assert(slice_type->is_slice_type());
10035 Type* element_type = slice_type->array_type()->element_type();
10037 if (args->size() == 1)
10039 // append(s) evaluates to s.
10040 if (assign_lhs != NULL)
10041 return NULL;
10042 return args->front();
10045 Type* int_type = Type::lookup_integer_type("int");
10046 Type_context int_context(int_type, false);
10047 Type* uint_type = Type::lookup_integer_type("uint");
10049 // Implementing
10050 // append(s1, s2...)
10051 // or
10052 // append(s1, a1, a2, a3, ...)
10054 // s1tmp := s1
10055 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
10056 loc);
10057 inserter->insert(s1tmp);
10059 // l1tmp := len(s1tmp)
10060 Named_object* lenfn = gogo->lookup_global("len");
10061 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
10062 Expression_list* call_args = new Expression_list();
10063 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
10064 Expression* len = Expression::make_call(lenref, call_args, false, loc);
10065 len->determine_type(gogo, &int_context);
10066 gogo->lower_expression(function, inserter, &len);
10067 gogo->flatten_expression(function, inserter, &len);
10068 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
10069 inserter->insert(l1tmp);
10071 Temporary_statement* s2tmp = NULL;
10072 Temporary_statement* l2tmp = NULL;
10073 Expression_list* add = NULL;
10074 Expression* len2;
10075 Call_expression* makecall = NULL;
10076 if (this->is_varargs())
10078 go_assert(args->size() == 2);
10080 std::pair<Call_expression*, Temporary_statement*> p =
10081 Expression::find_makeslice_call(args->back());
10082 makecall = p.first;
10083 if (makecall != NULL)
10085 // We are handling
10086 // append(s, make([]T, len[, cap])...))
10087 // which has already been lowered to
10088 // append(s, runtime.makeslice(T, len, cap)).
10089 // We will optimize this to directly zeroing the tail,
10090 // instead of allocating a new slice then copy.
10092 // Retrieve the length and capacity. Cannot reference s2 as
10093 // we will remove the makeslice call.
10094 Expression* len_arg = makecall->args()->at(1);
10095 len_arg = Expression::make_cast(int_type, len_arg, loc);
10096 l2tmp = Statement::make_temporary(int_type, len_arg, loc);
10097 l2tmp->determine_types(gogo);
10098 inserter->insert(l2tmp);
10100 Expression* cap_arg = makecall->args()->at(2);
10101 cap_arg = Expression::make_cast(int_type, cap_arg, loc);
10102 Temporary_statement* c2tmp =
10103 Statement::make_temporary(int_type, cap_arg, loc);
10104 c2tmp->determine_types(gogo);
10105 inserter->insert(c2tmp);
10107 // Check bad len/cap here.
10108 // checkmakeslice(type, len, cap)
10109 // (Note that if len and cap are constants, we won't see a
10110 // makeslice call here, as it will be rewritten to a stack
10111 // allocated array by Mark_address_taken::expression.)
10112 Expression* elem = Expression::make_type_descriptor(element_type,
10113 loc);
10114 len2 = Expression::make_temporary_reference(l2tmp, loc);
10115 Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
10116 Expression* check = Runtime::make_call(gogo,
10117 Runtime::CHECK_MAKE_SLICE,
10118 loc, 3, elem, len2, cap2);
10119 check->determine_type_no_context(gogo);
10120 gogo->lower_expression(function, inserter, &check);
10121 gogo->flatten_expression(function, inserter, &check);
10122 Statement* s = Statement::make_statement(check, false);
10123 inserter->insert(s);
10125 // Remove the original makeslice call.
10126 Temporary_statement* ts = p.second;
10127 if (ts != NULL && ts->uses() == 1)
10128 ts->set_init(Expression::make_nil(loc));
10130 else
10132 // s2tmp := s2
10133 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
10134 inserter->insert(s2tmp);
10136 // l2tmp := len(s2tmp)
10137 lenref = Expression::make_func_reference(lenfn, NULL, loc);
10138 call_args = new Expression_list();
10139 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
10140 len = Expression::make_call(lenref, call_args, false, loc);
10141 len->determine_type(gogo, &int_context);
10142 gogo->lower_expression(function, inserter, &len);
10143 gogo->flatten_expression(function, inserter, &len);
10144 l2tmp = Statement::make_temporary(int_type, len, loc);
10145 l2tmp->determine_types(gogo);
10146 inserter->insert(l2tmp);
10149 // len2 = l2tmp
10150 len2 = Expression::make_temporary_reference(l2tmp, loc);
10152 else
10154 // We have to ensure that all the arguments are in variables
10155 // now, because otherwise if one of them is an index expression
10156 // into the current slice we could overwrite it before we fetch
10157 // it.
10158 add = new Expression_list();
10159 Expression_list::const_iterator pa = args->begin();
10160 for (++pa; pa != args->end(); ++pa)
10162 if ((*pa)->is_multi_eval_safe())
10163 add->push_back(*pa);
10164 else
10166 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
10167 loc);
10168 inserter->insert(tmp);
10169 add->push_back(Expression::make_temporary_reference(tmp, loc));
10173 // len2 = len(add)
10174 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
10177 // ntmp := l1tmp + len2
10178 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
10179 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
10180 sum->determine_type(gogo, &int_context);
10181 gogo->lower_expression(function, inserter, &sum);
10182 gogo->flatten_expression(function, inserter, &sum);
10183 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
10184 ntmp->determine_types(gogo);
10185 inserter->insert(ntmp);
10187 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
10188 // growslice(type, s1tmp, ntmp) :
10189 // s1tmp[:ntmp]
10190 // Using uint here means that if the computation of ntmp overflowed,
10191 // we will call growslice which will panic.
10193 Named_object* capfn = gogo->lookup_global("cap");
10194 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
10195 call_args = new Expression_list();
10196 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
10197 Expression* cap = Expression::make_call(capref, call_args, false, loc);
10198 cap->determine_type(gogo, &int_context);
10199 gogo->lower_expression(function, inserter, &cap);
10200 gogo->flatten_expression(function, inserter, &cap);
10201 Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
10202 c1tmp->determine_types(gogo);
10203 inserter->insert(c1tmp);
10205 Expression* left = Expression::make_temporary_reference(ntmp, loc);
10206 left = Expression::make_cast(uint_type, left, loc);
10207 Expression* right = Expression::make_temporary_reference(c1tmp, loc);
10208 right = Expression::make_cast(uint_type, right, loc);
10210 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
10212 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10213 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
10214 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
10215 a2 = slice_type->array_type()->get_value_pointer(gogo, a2);
10216 a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
10217 Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
10218 Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
10219 Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
10220 Expression* call = Runtime::make_call(gogo, Runtime::GROWSLICE, loc, 5,
10221 a1, a2, a3, a4, a5);
10222 call = Expression::make_unsafe_cast(slice_type, call, loc);
10224 ref = Expression::make_temporary_reference(s1tmp, loc);
10225 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
10226 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
10227 ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
10228 ref->array_index_expression()->set_needs_bounds_check(false);
10230 if (assign_lhs == NULL)
10232 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
10234 rhs->determine_type_no_context(gogo);
10235 gogo->lower_expression(function, inserter, &rhs);
10236 gogo->flatten_expression(function, inserter, &rhs);
10238 ref = Expression::make_temporary_reference(s1tmp, loc);
10239 Statement* assign = Statement::make_assignment(ref, rhs, loc);
10240 assign->determine_types(gogo);
10241 inserter->insert(assign);
10243 else
10245 cond->determine_type_no_context(gogo);
10246 gogo->lower_expression(function, inserter, &cond);
10247 gogo->flatten_expression(function, inserter, &cond);
10248 call->determine_type_no_context(gogo);
10249 gogo->lower_expression(function, inserter, &call);
10250 gogo->flatten_expression(function, inserter, &call);
10251 ref->determine_type_no_context(gogo);
10252 gogo->lower_expression(function, inserter, &ref);
10253 gogo->flatten_expression(function, inserter, &ref);
10255 Block* then_block = new Block(enclosing, loc);
10256 Assignment_statement* assign =
10257 Statement::make_assignment(assign_lhs, call, loc);
10258 assign->determine_types(gogo);
10259 then_block->add_statement(assign);
10261 Block* else_block = new Block(enclosing, loc);
10262 assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
10263 // This assignment will not change the pointer value, so it does
10264 // not need a write barrier.
10265 assign->set_omit_write_barrier();
10266 assign->determine_types(gogo);
10267 else_block->add_statement(assign);
10269 Statement* s = Statement::make_if_statement(cond, then_block,
10270 else_block, loc);
10271 s->determine_types(gogo);
10272 inserter->insert(s);
10274 ref = Expression::make_temporary_reference(s1tmp, loc);
10275 assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
10276 assign->determine_types(gogo);
10277 inserter->insert(assign);
10280 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10282 if (this->is_varargs())
10284 if (makecall != NULL)
10286 // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
10287 a1 = Expression::make_temporary_reference(s1tmp, loc);
10288 ref = Expression::make_temporary_reference(l1tmp, loc);
10289 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
10290 a1->array_index_expression()->set_needs_bounds_check(false);
10291 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
10293 ref = Expression::make_temporary_reference(l2tmp, loc);
10294 ref = Expression::make_cast(uintptr_type, ref, loc);
10295 a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
10296 a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
10298 if (element_type->has_pointer())
10299 call = Runtime::make_call(gogo, Runtime::MEMCLRHASPTR, loc, 2,
10300 a1, a2);
10301 else
10303 Type* int32_type = Type::lookup_integer_type("int32");
10304 zero = Expression::make_integer_ul(0, int32_type, loc);
10305 call = Runtime::make_call(gogo, Runtime::BUILTIN_MEMSET, loc, 3,
10306 a1, zero, a2);
10309 if (element_type->has_pointer())
10311 // For a slice containing pointers, growslice already zeroed
10312 // the memory. We only need to zero in non-growing case.
10313 // Note: growslice does not zero the memory in non-pointer case.
10314 ref = Expression::make_temporary_reference(ntmp, loc);
10315 ref = Expression::make_cast(uint_type, ref, loc);
10316 ref2 = Expression::make_temporary_reference(c1tmp, loc);
10317 ref2 = Expression::make_cast(uint_type, ref2, loc);
10318 cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
10319 zero = Expression::make_integer_ul(0, int_type, loc);
10320 call = Expression::make_conditional(cond, zero, call, loc);
10323 else
10325 if (element_type->has_pointer())
10327 // copy(s1tmp[l1tmp:], s2tmp)
10328 a1 = Expression::make_temporary_reference(s1tmp, loc);
10329 ref = Expression::make_temporary_reference(l1tmp, loc);
10330 Expression* nil = Expression::make_nil(loc);
10331 a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
10332 a1->array_index_expression()->set_needs_bounds_check(false);
10334 a2 = Expression::make_temporary_reference(s2tmp, loc);
10336 Named_object* copyfn = gogo->lookup_global("copy");
10337 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
10338 call_args = new Expression_list();
10339 call_args->push_back(a1);
10340 call_args->push_back(a2);
10341 call = Expression::make_call(copyref, call_args, false, loc);
10343 else
10345 // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
10346 a1 = Expression::make_temporary_reference(s1tmp, loc);
10347 ref = Expression::make_temporary_reference(l1tmp, loc);
10348 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
10349 a1->array_index_expression()->set_needs_bounds_check(false);
10350 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
10352 a2 = Expression::make_temporary_reference(s2tmp, loc);
10353 a2 = (a2->type()->is_string_type()
10354 ? Expression::make_string_info(a2,
10355 STRING_INFO_DATA,
10356 loc)
10357 : Expression::make_slice_info(a2,
10358 SLICE_INFO_VALUE_POINTER,
10359 loc));
10361 ref = Expression::make_temporary_reference(l2tmp, loc);
10362 ref = Expression::make_cast(uintptr_type, ref, loc);
10363 a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
10364 a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
10366 call = Runtime::make_call(gogo, Runtime::BUILTIN_MEMMOVE, loc, 3,
10367 a1, a2, a3);
10370 call->determine_type_no_context(gogo);
10371 gogo->lower_expression(function, inserter, &call);
10372 gogo->flatten_expression(function, inserter, &call);
10373 inserter->insert(Statement::make_statement(call, false));
10375 else
10377 // For each argument:
10378 // s1tmp[l1tmp+i] = a
10379 unsigned long i = 0;
10380 for (Expression_list::const_iterator pa = add->begin();
10381 pa != add->end();
10382 ++pa, ++i)
10384 ref = Expression::make_temporary_reference(s1tmp, loc);
10385 ref2 = Expression::make_temporary_reference(l1tmp, loc);
10386 Expression* off = Expression::make_integer_ul(i, int_type, loc);
10387 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
10388 Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
10389 NULL, loc);
10390 lhs->array_index_expression()->set_needs_bounds_check(false);
10391 lhs->determine_type_no_context(gogo);
10392 gogo->lower_expression(function, inserter, &lhs);
10393 gogo->flatten_expression(function, inserter, &lhs);
10394 Expression* elem = *pa;
10395 if (!Type::are_identical(element_type, elem->type(), 0, NULL)
10396 && element_type->interface_type() != NULL)
10397 elem = Expression::make_cast(element_type, elem, loc);
10398 // The flatten pass runs after the write barrier pass, so we
10399 // need to insert a write barrier here if necessary.
10400 // However, if ASSIGN_LHS is not NULL, we have been called
10401 // directly before the write barrier pass.
10402 Statement* assign;
10403 if (assign_lhs != NULL
10404 || !gogo->assign_needs_write_barrier(lhs, NULL))
10405 assign = Statement::make_assignment(lhs, elem, loc);
10406 else
10408 Function* f = function == NULL ? NULL : function->func_value();
10409 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
10410 lhs, elem, loc);
10412 assign->determine_types(gogo);
10413 inserter->insert(assign);
10417 if (assign_lhs != NULL)
10418 return NULL;
10420 return Expression::make_temporary_reference(s1tmp, loc);
10423 // Return whether an expression has an integer value. Report an error
10424 // if not. This is used when handling calls to the predeclared make
10425 // function. Set *SMALL if the value is known to fit in type "int".
10427 bool
10428 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
10429 bool *small)
10431 *small = false;
10433 Numeric_constant nc;
10434 if (e->numeric_constant_value(&nc))
10436 unsigned long v;
10437 switch (nc.to_unsigned_long(&v))
10439 case Numeric_constant::NC_UL_VALID:
10440 break;
10441 case Numeric_constant::NC_UL_NOTINT:
10442 go_error_at(e->location(), "non-integer %s argument to make",
10443 is_length ? "len" : "cap");
10444 return false;
10445 case Numeric_constant::NC_UL_NEGATIVE:
10446 go_error_at(e->location(), "negative %s argument to make",
10447 is_length ? "len" : "cap");
10448 return false;
10449 case Numeric_constant::NC_UL_BIG:
10450 // We don't want to give a compile-time error for a 64-bit
10451 // value on a 32-bit target.
10452 break;
10455 mpz_t val;
10456 if (!nc.to_int(&val))
10457 go_unreachable();
10458 int bits = mpz_sizeinbase(val, 2);
10459 mpz_clear(val);
10460 Type* int_type = Type::lookup_integer_type("int");
10461 if (bits >= int_type->integer_type()->bits())
10463 go_error_at(e->location(), "%s argument too large for make",
10464 is_length ? "len" : "cap");
10465 return false;
10468 *small = true;
10469 return true;
10472 if (e->type()->integer_type() != NULL)
10474 int ebits = e->type()->integer_type()->bits();
10475 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
10477 // We can treat ebits == intbits as small even for an unsigned
10478 // integer type, because we will convert the value to int and
10479 // then reject it in the runtime if it is negative.
10480 *small = ebits <= intbits;
10482 return true;
10485 go_error_at(e->location(), "non-integer %s argument to make",
10486 is_length ? "len" : "cap");
10487 return false;
10490 // Return the type of the real or imag functions, given the type of
10491 // the argument. We need to map complex64 to float32 and complex128
10492 // to float64, so it has to be done by name. This returns NULL if it
10493 // can't figure out the type.
10495 Type*
10496 Builtin_call_expression::real_imag_type(Type* arg_type)
10498 if (arg_type == NULL || arg_type->is_abstract())
10499 return NULL;
10500 Named_type* nt = arg_type->named_type();
10501 if (nt == NULL)
10502 return NULL;
10503 while (nt->real_type()->named_type() != NULL)
10504 nt = nt->real_type()->named_type();
10505 if (nt->name() == "complex64")
10506 return Type::lookup_float_type("float32");
10507 else if (nt->name() == "complex128")
10508 return Type::lookup_float_type("float64");
10509 else
10510 return NULL;
10513 // Return the type of the complex function, given the type of one of the
10514 // argments. Like real_imag_type, we have to map by name.
10516 Type*
10517 Builtin_call_expression::complex_type(Type* arg_type)
10519 if (arg_type == NULL || arg_type->is_abstract())
10520 return NULL;
10521 Named_type* nt = arg_type->named_type();
10522 if (nt == NULL)
10523 return NULL;
10524 while (nt->real_type()->named_type() != NULL)
10525 nt = nt->real_type()->named_type();
10526 if (nt->name() == "float32")
10527 return Type::lookup_complex_type("complex64");
10528 else if (nt->name() == "float64")
10529 return Type::lookup_complex_type("complex128");
10530 else
10531 return NULL;
10534 // Return a single argument, or NULL if there isn't one.
10536 Expression*
10537 Builtin_call_expression::one_arg() const
10539 const Expression_list* args = this->args();
10540 if (args == NULL || args->size() != 1)
10541 return NULL;
10542 return args->front();
10545 // A traversal class which looks for a call or receive expression.
10547 class Find_call_expression : public Traverse
10549 public:
10550 Find_call_expression()
10551 : Traverse(traverse_expressions),
10552 found_(false)
10556 expression(Expression**);
10558 bool
10559 found()
10560 { return this->found_; }
10562 private:
10563 bool found_;
10567 Find_call_expression::expression(Expression** pexpr)
10569 Expression* expr = *pexpr;
10570 if (!expr->is_constant()
10571 && (expr->call_expression() != NULL
10572 || expr->receive_expression() != NULL))
10574 this->found_ = true;
10575 return TRAVERSE_EXIT;
10577 return TRAVERSE_CONTINUE;
10580 // Return whether calling len or cap on EXPR, of array type, is a
10581 // constant. The language spec says "the expressions len(s) and
10582 // cap(s) are constants if the type of s is an array or pointer to an
10583 // array and the expression s does not contain channel receives or
10584 // (non-constant) function calls."
10586 bool
10587 Builtin_call_expression::array_len_is_constant(Expression* expr)
10589 go_assert(expr->type()->deref()->array_type() != NULL
10590 && !expr->type()->deref()->is_slice_type());
10591 if (expr->is_constant())
10592 return true;
10593 Find_call_expression find_call;
10594 Expression::traverse(&expr, &find_call);
10595 return !find_call.found();
10598 // Return whether this is constant: len of a string constant, or len
10599 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
10600 // unsafe.Alignof.
10602 bool
10603 Builtin_call_expression::do_is_constant() const
10605 if (this->is_error_expression())
10606 return true;
10607 switch (this->code_)
10609 case BUILTIN_LEN:
10610 case BUILTIN_CAP:
10612 if (this->seen_)
10613 return false;
10615 Expression* arg = this->one_arg();
10616 if (arg == NULL)
10617 return false;
10619 // We may be called before the determine_types pass.
10620 arg->determine_type_no_context(this->gogo_);
10622 Type* arg_type = arg->type();
10623 if (arg_type->is_error())
10624 return true;
10626 if (arg_type->points_to() != NULL
10627 && arg_type->points_to()->array_type() != NULL
10628 && !arg_type->points_to()->is_slice_type())
10629 arg_type = arg_type->points_to();
10631 if (arg_type->array_type() != NULL
10632 && arg_type->array_type()->length() != NULL)
10634 this->seen_ = true;
10635 bool ret = Builtin_call_expression::array_len_is_constant(arg);
10636 this->seen_ = false;
10637 return ret;
10640 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
10642 this->seen_ = true;
10643 bool ret = arg->is_constant();
10644 this->seen_ = false;
10645 return ret;
10648 break;
10650 case BUILTIN_SIZEOF:
10651 case BUILTIN_ALIGNOF:
10652 return this->one_arg() != NULL;
10654 case BUILTIN_OFFSETOF:
10656 Expression* arg = this->one_arg();
10657 if (arg == NULL)
10658 return false;
10659 return (arg->field_reference_expression() != NULL
10660 || arg->classification() == Expression::EXPRESSION_SELECTOR);
10663 case BUILTIN_COMPLEX:
10665 const Expression_list* args = this->args();
10666 if (args != NULL && args->size() == 2)
10667 return args->front()->is_constant() && args->back()->is_constant();
10669 break;
10671 case BUILTIN_REAL:
10672 case BUILTIN_IMAG:
10674 Expression* arg = this->one_arg();
10675 return arg != NULL && arg->is_constant();
10678 default:
10679 break;
10682 return false;
10685 // Return whether a builtin call is untyped. Most builtin functions
10686 // have a known type, but complex, real, and imag can be untyped.
10688 bool
10689 Builtin_call_expression::do_is_untyped(Type** ptype) const
10691 if (this->is_error_expression())
10692 return false;
10694 switch (this->code_)
10696 default:
10697 return false;
10699 case BUILTIN_COMPLEX:
10701 const Expression_list* args = this->args();
10702 if (args == NULL || args->size() != 2)
10703 return false;
10704 Type* dummy;
10705 if (!args->front()->is_untyped(&dummy)
10706 || !args->back()->is_untyped(&dummy))
10707 return false;
10708 *ptype = Type::make_abstract_complex_type();
10709 return true;
10712 case BUILTIN_REAL:
10713 case BUILTIN_IMAG:
10715 Expression* arg = this->one_arg();
10716 if (arg == NULL)
10717 return false;
10718 if (!arg->is_untyped(ptype))
10719 return false;
10720 *ptype = Type::make_abstract_float_type();
10721 return true;
10726 // Return a numeric constant if possible.
10728 bool
10729 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc)
10731 if (this->code_ == BUILTIN_LEN
10732 || this->code_ == BUILTIN_CAP)
10734 Expression* arg = this->one_arg();
10735 if (arg == NULL)
10736 return false;
10738 // We may be called before the determine_types pass.
10739 arg->determine_type_no_context(this->gogo_);
10741 Type* arg_type = arg->type();
10742 if (arg_type->is_error())
10743 return false;
10745 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
10747 std::string sval;
10748 if (arg->string_constant_value(&sval))
10750 nc->set_unsigned_long(Type::lookup_integer_type("int"),
10751 sval.length());
10752 return true;
10756 if (arg_type->points_to() != NULL
10757 && arg_type->points_to()->array_type() != NULL
10758 && !arg_type->points_to()->is_slice_type())
10759 arg_type = arg_type->points_to();
10761 if (arg_type->array_type() != NULL
10762 && arg_type->array_type()->length() != NULL)
10764 if (this->seen_)
10765 return false;
10767 if (!arg_type->is_error())
10769 Expression* e = arg_type->array_type()->length();
10770 this->seen_ = true;
10771 bool r = e->numeric_constant_value(nc);
10772 this->seen_ = false;
10773 if (r)
10775 if (!nc->set_type(Type::lookup_integer_type("int"), false,
10776 this->location()))
10777 r = false;
10779 return r;
10783 else if (this->code_ == BUILTIN_SIZEOF
10784 || this->code_ == BUILTIN_ALIGNOF)
10786 Expression* arg = this->one_arg();
10787 if (arg == NULL)
10788 return false;
10790 // We may be called before the determine_types pass.
10791 arg->determine_type_no_context(this->gogo_);
10793 Type* arg_type = arg->type();
10794 if (arg_type->is_error())
10795 return false;
10796 if (arg_type->is_abstract())
10797 arg_type = arg_type->make_non_abstract_type();
10798 if (this->seen_)
10799 return false;
10801 int64_t ret;
10802 if (this->code_ == BUILTIN_SIZEOF)
10804 this->seen_ = true;
10805 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
10806 this->seen_ = false;
10807 if (!ok)
10808 return false;
10810 else if (this->code_ == BUILTIN_ALIGNOF)
10812 bool ok;
10813 this->seen_ = true;
10814 if (arg->field_reference_expression() == NULL)
10815 ok = arg_type->backend_type_align(this->gogo_, &ret);
10816 else
10818 // Calling unsafe.Alignof(s.f) returns the alignment of
10819 // the type of f when it is used as a field in a struct.
10820 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
10822 this->seen_ = false;
10823 if (!ok)
10824 return false;
10826 else
10827 go_unreachable();
10829 mpz_t zval;
10830 set_mpz_from_int64(&zval, ret);
10831 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
10832 mpz_clear(zval);
10833 return true;
10835 else if (this->code_ == BUILTIN_OFFSETOF)
10837 Expression* arg = this->one_arg();
10838 if (arg == NULL)
10839 return false;
10841 // We may be called before the determine_types pass.
10842 arg->determine_type_no_context(this->gogo_);
10844 Field_reference_expression* farg = arg->field_reference_expression();
10845 if (farg == NULL)
10846 return false;
10847 if (this->seen_)
10848 return false;
10850 int64_t total_offset = 0;
10851 while (true)
10853 Expression* struct_expr = farg->expr();
10854 Type* st = struct_expr->type();
10855 if (st->struct_type() == NULL)
10856 return false;
10857 if (st->named_type() != NULL)
10858 st->named_type()->convert(this->gogo_);
10859 if (st->is_error_type())
10861 go_assert(saw_errors());
10862 return false;
10864 int64_t offset;
10865 this->seen_ = true;
10866 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
10867 farg->field_index(),
10868 &offset);
10869 this->seen_ = false;
10870 if (!ok)
10871 return false;
10872 total_offset += offset;
10873 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
10875 // Go up until we reach the original base.
10876 farg = struct_expr->field_reference_expression();
10877 continue;
10879 break;
10881 mpz_t zval;
10882 set_mpz_from_int64(&zval, total_offset);
10883 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
10884 mpz_clear(zval);
10885 return true;
10887 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
10889 Expression* arg = this->one_arg();
10890 if (arg == NULL)
10891 return false;
10893 Numeric_constant argnc;
10894 if (!arg->numeric_constant_value(&argnc))
10895 return false;
10897 mpc_t val;
10898 if (!argnc.to_complex(&val))
10899 return false;
10901 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
10902 if (this->code_ == BUILTIN_REAL)
10903 nc->set_float(type, mpc_realref(val));
10904 else
10905 nc->set_float(type, mpc_imagref(val));
10906 mpc_clear(val);
10907 return true;
10909 else if (this->code_ == BUILTIN_COMPLEX)
10911 const Expression_list* args = this->args();
10912 if (args == NULL || args->size() != 2)
10913 return false;
10915 Numeric_constant rnc;
10916 if (!args->front()->numeric_constant_value(&rnc))
10917 return false;
10918 Numeric_constant inc;
10919 if (!args->back()->numeric_constant_value(&inc))
10920 return false;
10922 if (rnc.type() != NULL
10923 && !rnc.type()->is_abstract()
10924 && inc.type() != NULL
10925 && !inc.type()->is_abstract()
10926 && !Type::are_identical(rnc.type(), inc.type(),
10927 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
10928 NULL))
10929 return false;
10931 mpfr_t r;
10932 if (!rnc.to_float(&r))
10933 return false;
10934 mpfr_t i;
10935 if (!inc.to_float(&i))
10937 mpfr_clear(r);
10938 return false;
10941 Type* arg_type = rnc.type();
10942 if (arg_type == NULL || arg_type->is_abstract())
10943 arg_type = inc.type();
10945 mpc_t val;
10946 mpc_init2(val, mpc_precision);
10947 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
10948 mpfr_clear(r);
10949 mpfr_clear(i);
10951 Type* type = Builtin_call_expression::complex_type(arg_type);
10952 nc->set_complex(type, val);
10954 mpc_clear(val);
10956 return true;
10959 return false;
10962 // Give an error if we are discarding the value of an expression which
10963 // should not normally be discarded. We don't give an error for
10964 // discarding the value of an ordinary function call, but we do for
10965 // builtin functions, purely for consistency with the gc compiler.
10967 bool
10968 Builtin_call_expression::do_discarding_value()
10970 switch (this->code_)
10972 case BUILTIN_INVALID:
10973 default:
10974 go_unreachable();
10976 case BUILTIN_APPEND:
10977 case BUILTIN_CAP:
10978 case BUILTIN_COMPLEX:
10979 case BUILTIN_IMAG:
10980 case BUILTIN_LEN:
10981 case BUILTIN_MAKE:
10982 case BUILTIN_NEW:
10983 case BUILTIN_REAL:
10984 case BUILTIN_ADD:
10985 case BUILTIN_ALIGNOF:
10986 case BUILTIN_OFFSETOF:
10987 case BUILTIN_SIZEOF:
10988 case BUILTIN_SLICE:
10989 this->unused_value_error();
10990 return false;
10992 case BUILTIN_CLOSE:
10993 case BUILTIN_COPY:
10994 case BUILTIN_DELETE:
10995 case BUILTIN_PANIC:
10996 case BUILTIN_PRINT:
10997 case BUILTIN_PRINTLN:
10998 case BUILTIN_RECOVER:
10999 return true;
11003 // Return the type.
11005 Type*
11006 Builtin_call_expression::do_type()
11008 if (this->is_error_expression())
11009 return Type::make_error_type();
11011 Type* type = this->type();
11012 if (type != NULL)
11013 return type;
11015 switch (this->code_)
11017 case BUILTIN_INVALID:
11018 default:
11019 return Type::make_error_type();
11021 case BUILTIN_NEW:
11023 const Expression_list* args = this->args();
11024 if (args == NULL || args->empty())
11025 return Type::make_error_type();
11026 return Type::make_pointer_type(args->front()->type());
11029 case BUILTIN_MAKE:
11031 const Expression_list* args = this->args();
11032 if (args == NULL || args->empty())
11033 return Type::make_error_type();
11034 return args->front()->type();
11037 case BUILTIN_CAP:
11038 case BUILTIN_COPY:
11039 case BUILTIN_LEN:
11040 return Type::lookup_integer_type("int");
11042 case BUILTIN_ALIGNOF:
11043 case BUILTIN_OFFSETOF:
11044 case BUILTIN_SIZEOF:
11045 return Type::lookup_integer_type("uintptr");
11047 case BUILTIN_CLOSE:
11048 case BUILTIN_DELETE:
11049 case BUILTIN_PANIC:
11050 case BUILTIN_PRINT:
11051 case BUILTIN_PRINTLN:
11052 return Type::make_void_type();
11054 case BUILTIN_RECOVER:
11055 return Type::make_empty_interface_type(Linemap::predeclared_location());
11057 case BUILTIN_APPEND:
11059 const Expression_list* args = this->args();
11060 if (args == NULL || args->empty())
11061 return Type::make_error_type();
11062 Type *ret = args->front()->type();
11063 if (!ret->is_slice_type())
11064 return Type::make_error_type();
11065 return ret;
11068 case BUILTIN_REAL:
11069 case BUILTIN_IMAG:
11071 Expression* arg = this->one_arg();
11072 if (arg == NULL)
11073 return Type::make_error_type();
11074 Type* t = arg->type();
11075 if (t->is_abstract())
11076 t = t->make_non_abstract_type();
11077 t = Builtin_call_expression::real_imag_type(t);
11078 if (t == NULL)
11079 t = Type::make_error_type();
11080 return t;
11083 case BUILTIN_COMPLEX:
11085 const Expression_list* args = this->args();
11086 if (args == NULL || args->size() != 2)
11087 return Type::make_error_type();
11088 Type* t = args->front()->type();
11089 if (t->is_abstract())
11091 t = args->back()->type();
11092 if (t->is_abstract())
11093 t = t->make_non_abstract_type();
11095 t = Builtin_call_expression::complex_type(t);
11096 if (t == NULL)
11097 t = Type::make_error_type();
11098 return t;
11101 case BUILTIN_ADD:
11102 return Type::make_pointer_type(Type::make_void_type());
11104 case BUILTIN_SLICE:
11105 const Expression_list* args = this->args();
11106 if (args == NULL || args->size() != 2)
11107 return Type::make_error_type();
11108 Type* pt = args->front()->type()->points_to();
11109 if (pt == NULL)
11110 return Type::make_error_type();
11111 return Type::make_array_type(pt, NULL);
11115 // Determine the type.
11117 void
11118 Builtin_call_expression::do_determine_type(Gogo* gogo,
11119 const Type_context* context)
11121 if (!this->determining_types())
11122 return;
11124 this->fn()->determine_type_no_context(gogo);
11126 this->simplify_multiple_results(gogo);
11128 const Expression_list* args = this->args();
11130 bool is_print;
11131 Type* arg_type = NULL;
11132 Type* trailing_arg_types = NULL;
11133 switch (this->code_)
11135 case BUILTIN_MAKE:
11136 trailing_arg_types = Type::lookup_integer_type("int");
11137 is_print = false;
11138 break;
11140 case BUILTIN_PRINT:
11141 case BUILTIN_PRINTLN:
11142 // Do not force a large integer constant to "int".
11143 is_print = true;
11144 break;
11146 case BUILTIN_REAL:
11147 case BUILTIN_IMAG:
11149 // We need the argument to determine the type, so check it now
11150 // before any call to the do_type method.
11151 const Expression_list* args = this->args();
11152 if (args == NULL || args->size() < 1)
11154 this->report_error(_("not enough arguments"));
11155 return;
11157 else if (args->size() > 1)
11159 this->report_error(_("too many arguments"));
11160 return;
11163 Type* dummy;
11164 if (context->type != NULL
11165 && context->type->is_numeric_type()
11166 && this->is_untyped(&dummy))
11168 Type* type = context->type;
11169 if (type->is_abstract() && !context->may_be_abstract)
11170 type = type->make_non_abstract_type();
11171 this->set_type(type);
11173 else if (context->may_be_abstract && this->is_constant())
11174 this->set_type(Type::make_abstract_float_type());
11176 arg_type = Builtin_call_expression::complex_type(context->type);
11177 if (arg_type == NULL)
11179 if (context->may_be_abstract)
11180 arg_type = Type::make_abstract_complex_type();
11181 else
11182 arg_type = Type::lookup_complex_type("complex128");
11185 if (!args->front()->is_untyped(&dummy))
11187 Type_context subcontext(arg_type, context->may_be_abstract);
11188 args->front()->determine_type(gogo, &subcontext);
11191 is_print = false;
11193 break;
11195 case BUILTIN_COMPLEX:
11197 // We need the arguments to determine the type, so check them
11198 // now before any call to the do_type method.
11199 const Expression_list* args = this->args();
11200 if (args == NULL || args->size() < 2)
11202 this->report_error(_("not enough arguments"));
11203 return;
11205 else if (args->size() > 2)
11207 this->report_error(_("too many arguments"));
11208 return;
11211 Type* dummy;
11212 if (context->type != NULL
11213 && context->type->is_numeric_type()
11214 && this->is_untyped(&dummy))
11216 Type* type = context->type;
11217 if (type->is_abstract() && !context->may_be_abstract)
11218 type = type->make_non_abstract_type();
11219 this->set_type(type);
11221 else if (context->may_be_abstract && this->is_constant())
11222 this->set_type(Type::make_abstract_complex_type());
11224 // For the complex function the type of one operand can
11225 // determine the type of the other, as in a binary expression.
11226 arg_type = Builtin_call_expression::real_imag_type(context->type);
11227 if (arg_type == NULL)
11229 if (context->may_be_abstract)
11230 arg_type = Type::make_abstract_float_type();
11231 else
11232 arg_type = Type::lookup_float_type("float64");
11235 Type_context subcontext(arg_type, context->may_be_abstract);
11236 if (!args->front()->is_untyped(&dummy))
11238 args->front()->determine_type(gogo, &subcontext);
11239 arg_type = args->front()->type();
11241 else if (!args->back()->is_untyped(&dummy))
11243 args->back()->determine_type(gogo, &subcontext);
11244 arg_type = args->back()->type();
11247 is_print = false;
11249 break;
11251 case BUILTIN_APPEND:
11252 if (!this->is_varargs()
11253 && args != NULL
11254 && !args->empty())
11256 args->front()->determine_type_no_context(gogo);
11257 if (args->front()->type()->is_slice_type())
11258 trailing_arg_types =
11259 args->front()->type()->array_type()->element_type();
11261 is_print = false;
11262 break;
11264 case BUILTIN_ADD:
11265 case BUILTIN_SLICE:
11266 // Both unsafe.Add and unsafe.Slice take two arguments, and the
11267 // second arguments defaults to "int".
11268 if (args != NULL && args->size() == 2)
11270 if (this->code_ == BUILTIN_SLICE)
11271 args->front()->determine_type_no_context(gogo);
11272 else
11274 Type* pointer = Type::make_pointer_type(Type::make_void_type());
11275 Type_context subcontext(pointer, false);
11276 args->front()->determine_type(gogo, &subcontext);
11278 Type* int_type = Type::lookup_integer_type("int");
11279 Type_context subcontext(int_type, false);
11280 args->back()->determine_type(gogo, &subcontext);
11281 return;
11283 is_print = false;
11284 break;
11286 case BUILTIN_DELETE:
11287 if (args != NULL && args->size() == 2)
11289 args->front()->determine_type_no_context(gogo);
11290 Map_type* mt = args->front()->type()->map_type();
11291 if (mt != NULL)
11292 trailing_arg_types = mt->key_type();
11294 is_print = false;
11295 break;
11297 default:
11298 is_print = false;
11299 break;
11302 if (args != NULL)
11304 for (Expression_list::const_iterator pa = args->begin();
11305 pa != args->end();
11306 ++pa)
11308 Type_context subcontext;
11309 subcontext.type = arg_type;
11311 if (is_print && (*pa)->is_constant())
11313 // We want to print large constants, we so can't just
11314 // use the appropriate nonabstract type. Use uint64 for
11315 // an integer if we know it is nonnegative, otherwise
11316 // use int64 for a integer, otherwise use float64 for a
11317 // float or complex128 for a complex.
11318 Type* atype;
11319 if ((*pa)->is_untyped(&atype))
11321 Type* want_type = NULL;
11322 if (atype->integer_type() != NULL)
11324 Numeric_constant nc;
11325 if (this->numeric_constant_value(&nc))
11327 mpz_t val;
11328 if (nc.to_int(&val))
11330 if (mpz_sgn(val) >= 0)
11331 want_type = Type::lookup_integer_type("uint64");
11332 mpz_clear(val);
11335 if (want_type == NULL)
11336 want_type = Type::lookup_integer_type("int64");
11338 else if (atype->float_type() != NULL)
11339 want_type = Type::lookup_float_type("float64");
11340 else if (atype->complex_type() != NULL)
11341 want_type = Type::lookup_complex_type("complex128");
11342 else if (atype->is_abstract_string_type())
11343 want_type = Type::lookup_string_type();
11344 else if (atype->is_abstract_boolean_type())
11345 want_type = Type::lookup_bool_type();
11346 else
11347 go_unreachable();
11348 subcontext.type = want_type;
11352 (*pa)->determine_type(gogo, &subcontext);
11354 if (trailing_arg_types != NULL)
11356 arg_type = trailing_arg_types;
11357 trailing_arg_types = NULL;
11363 // If there is exactly one argument, return true. Otherwise give an
11364 // error message and return false.
11366 bool
11367 Builtin_call_expression::check_one_arg()
11369 const Expression_list* args = this->args();
11370 if (args == NULL || args->size() < 1)
11372 this->report_error(_("not enough arguments"));
11373 return false;
11375 else if (args->size() > 1)
11377 this->report_error(_("too many arguments"));
11378 return false;
11380 if (args->front()->is_error_expression()
11381 || args->front()->type()->is_error())
11383 this->set_is_error();
11384 return false;
11386 return true;
11389 // Check argument types for a builtin function.
11391 void
11392 Builtin_call_expression::do_check_types(Gogo* gogo)
11394 if (this->is_error_expression())
11395 return;
11397 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
11399 go_error_at(this->location(),
11400 "invalid use of %<...%> with built-in function");
11401 this->set_is_error();
11402 return;
11405 switch (this->code_)
11407 case BUILTIN_INVALID:
11408 return;
11410 case BUILTIN_NEW:
11411 if (this->check_one_arg())
11413 Expression* arg = this->one_arg();
11414 if (!arg->is_type_expression())
11416 go_error_at(arg->location(), "expected type");
11417 this->set_is_error();
11420 break;
11422 case BUILTIN_MAKE:
11424 const Expression_list* args = this->args();
11425 if (args == NULL || args->size() < 1)
11427 this->report_error(_("not enough arguments"));
11428 return;
11431 Expression* first_arg = args->front();
11432 if (!first_arg->is_type_expression())
11434 go_error_at(first_arg->location(), "expected type");
11435 this->set_is_error();
11436 return;
11439 Type* type = first_arg->type();
11440 if (!type->in_heap())
11441 go_error_at(first_arg->location(),
11442 "cannot make slice of go:notinheap type");
11444 bool is_slice = type->is_slice_type();
11445 if (!is_slice
11446 && type->map_type() == NULL
11447 && type->channel_type() == NULL)
11449 this->report_error(_("invalid type for make function"));
11450 return;
11453 Expression_list::const_iterator parg = args->begin();
11454 ++parg;
11455 if (parg == args->end())
11457 if (is_slice)
11459 this->report_error(_("length required when "
11460 "allocating a slice"));
11461 return;
11464 else
11466 if ((*parg)->type()->integer_type() == NULL)
11468 go_error_at((*parg)->location(),
11469 "non-integer len argument in make");
11470 return;
11472 ++parg;
11474 if (is_slice && parg != args->end())
11476 if ((*parg)->type()->integer_type() == NULL)
11478 go_error_at((*parg)->location(),
11479 "non-integer cap argument in make");
11480 return;
11482 ++parg;
11486 if (parg != args->end())
11488 this->report_error(_("too many arguments to make"));
11489 return;
11492 break;
11494 case BUILTIN_DELETE:
11496 const Expression_list* args = this->args();
11497 if (args == NULL || args->size() < 2)
11498 this->report_error(_("not enough arguments"));
11499 else if (args->size() > 2)
11500 this->report_error(_("too many arguments"));
11501 else if (args->front()->type()->map_type() == NULL)
11502 this->report_error(_("argument 1 must be a map"));
11503 else
11505 Type* key_type =
11506 args->front()->type()->map_type()->key_type();
11507 Expression_list::iterator pa = this->args()->begin();
11508 pa++;
11509 Type* arg_type = (*pa)->type();
11510 std::string reason;
11511 if (!Type::are_assignable(key_type, arg_type, &reason))
11513 if (reason.empty())
11514 go_error_at(this->location(),
11515 "argument 2 has incompatible type");
11516 else
11517 go_error_at(this->location(),
11518 "argument 2 has incompatible type (%s)",
11519 reason.c_str());
11520 this->set_is_error();
11524 break;
11526 case BUILTIN_LEN:
11527 case BUILTIN_CAP:
11529 // The single argument may be either a string or an array or a
11530 // map or a channel, or a pointer to a closed array.
11531 if (this->check_one_arg())
11533 Type* arg_type = this->one_arg()->type();
11534 if (arg_type->points_to() != NULL
11535 && arg_type->points_to()->array_type() != NULL
11536 && !arg_type->points_to()->is_slice_type())
11537 arg_type = arg_type->points_to();
11538 if (this->code_ == BUILTIN_CAP)
11540 if (!arg_type->is_error()
11541 && arg_type->array_type() == NULL
11542 && arg_type->channel_type() == NULL)
11543 this->report_error(_("argument must be array or slice "
11544 "or channel"));
11546 else
11548 if (!arg_type->is_error()
11549 && !arg_type->is_string_type()
11550 && arg_type->array_type() == NULL
11551 && arg_type->map_type() == NULL
11552 && arg_type->channel_type() == NULL)
11553 this->report_error(_("argument must be string or "
11554 "array or slice or map or channel"));
11558 break;
11560 case BUILTIN_PRINT:
11561 case BUILTIN_PRINTLN:
11563 const Expression_list* args = this->args();
11564 if (args != NULL)
11566 for (Expression_list::const_iterator p = args->begin();
11567 p != args->end();
11568 ++p)
11570 Type* type = (*p)->type();
11571 if (type->is_error()
11572 || type->is_string_type()
11573 || type->integer_type() != NULL
11574 || type->float_type() != NULL
11575 || type->complex_type() != NULL
11576 || type->is_boolean_type()
11577 || type->points_to() != NULL
11578 || type->interface_type() != NULL
11579 || type->channel_type() != NULL
11580 || type->map_type() != NULL
11581 || type->function_type() != NULL
11582 || type->is_slice_type())
11584 else if ((*p)->is_type_expression())
11586 // If this is a type expression it's going to give
11587 // an error anyhow, so we don't need one here.
11589 else
11591 // Report errors in the expression first.
11592 (*p)->check_types(gogo);
11593 if (!(*p)->is_error_expression())
11594 this->report_error(_("unsupported argument type to "
11595 "builtin function"));
11600 break;
11602 case BUILTIN_CLOSE:
11603 if (this->check_one_arg())
11605 if (this->one_arg()->type()->channel_type() == NULL)
11606 this->report_error(_("argument must be channel"));
11607 else if (!this->one_arg()->type()->channel_type()->may_send())
11608 this->report_error(_("cannot close receive-only channel"));
11610 break;
11612 case BUILTIN_PANIC:
11613 case BUILTIN_SIZEOF:
11614 case BUILTIN_ALIGNOF:
11615 if (this->check_one_arg())
11617 Expression* arg = this->one_arg();
11618 if (arg->type()->is_void_type())
11619 this->report_error(_("argument to builtin has void type"));
11621 break;
11623 case BUILTIN_RECOVER:
11624 if (this->args() != NULL
11625 && !this->args()->empty()
11626 && !this->recover_arg_is_set_)
11627 this->report_error(_("too many arguments"));
11628 break;
11630 case BUILTIN_OFFSETOF:
11631 if (this->check_one_arg())
11633 Expression* arg = this->one_arg();
11634 if (arg->classification() == Expression::EXPRESSION_SELECTOR)
11636 Selector_expression* se = static_cast<Selector_expression*>(arg);
11637 Expression* resolved = se->resolved();
11638 if (resolved != NULL)
11639 arg = resolved;
11641 if (arg->is_error_expression())
11643 else if (arg->bound_method_expression() != NULL
11644 || arg->interface_field_reference_expression() != NULL)
11645 this->report_error(_("invalid use of method value as "
11646 "argument of Offsetof"));
11647 else if (arg->field_reference_expression() == NULL)
11648 this->report_error(_("argument must be a field reference"));
11650 break;
11652 case BUILTIN_COPY:
11654 const Expression_list* args = this->args();
11655 if (args == NULL || args->size() < 2)
11657 this->report_error(_("not enough arguments"));
11658 break;
11660 else if (args->size() > 2)
11662 this->report_error(_("too many arguments"));
11663 break;
11665 Type* arg1_type = args->front()->type();
11666 Type* arg2_type = args->back()->type();
11667 if (arg1_type->is_error() || arg2_type->is_error())
11669 this->set_is_error();
11670 break;
11673 Type* e1;
11674 if (arg1_type->is_slice_type())
11675 e1 = arg1_type->array_type()->element_type();
11676 else
11678 this->report_error(_("left argument must be a slice"));
11679 break;
11682 if (arg2_type->is_slice_type())
11684 Type* e2 = arg2_type->array_type()->element_type();
11685 if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
11686 this->report_error(_("element types must be the same"));
11688 else if (arg2_type->is_string_type())
11690 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
11691 this->report_error(_("first argument must be []byte"));
11693 else
11694 this->report_error(_("second argument must be slice or string"));
11696 break;
11698 case BUILTIN_APPEND:
11700 const Expression_list* args = this->args();
11701 if (args == NULL || args->empty())
11703 this->report_error(_("not enough arguments"));
11704 break;
11707 Type* slice_type = args->front()->type();
11708 if (!slice_type->is_slice_type())
11710 if (slice_type->is_error_type())
11711 break;
11712 if (slice_type->is_nil_type())
11713 go_error_at(args->front()->location(), "use of untyped nil");
11714 else
11715 go_error_at(args->front()->location(),
11716 "argument 1 must be a slice");
11717 this->set_is_error();
11718 break;
11721 Type* element_type = slice_type->array_type()->element_type();
11722 if (!element_type->in_heap())
11723 go_error_at(args->front()->location(),
11724 "cannot append to slice of go:notinheap type");
11725 if (this->is_varargs())
11727 if (!args->back()->type()->is_slice_type()
11728 && !args->back()->type()->is_string_type())
11730 go_error_at(args->back()->location(),
11731 "invalid use of %<...%> with non-slice/non-string");
11732 this->set_is_error();
11733 break;
11736 if (args->size() < 2)
11738 this->report_error(_("not enough arguments"));
11739 break;
11741 if (args->size() > 2)
11743 this->report_error(_("too many arguments"));
11744 break;
11747 if (args->back()->type()->is_string_type()
11748 && element_type->integer_type() != NULL
11749 && element_type->integer_type()->is_byte())
11751 // Permit append(s1, s2...) when s1 is a slice of
11752 // bytes and s2 is a string type.
11754 else
11756 // We have to test for assignment compatibility to a
11757 // slice of the element type, which is not necessarily
11758 // the same as the type of the first argument: the
11759 // first argument might have a named type.
11760 Type* check_type = Type::make_array_type(element_type, NULL);
11761 std::string reason;
11762 if (!Type::are_assignable(check_type, args->back()->type(),
11763 &reason))
11765 if (reason.empty())
11766 go_error_at(args->back()->location(),
11767 "argument 2 has invalid type");
11768 else
11769 go_error_at(args->back()->location(),
11770 "argument 2 has invalid type (%s)",
11771 reason.c_str());
11772 this->set_is_error();
11773 break;
11777 else
11779 Expression_list::const_iterator pa = args->begin();
11780 int i = 2;
11781 for (++pa; pa != args->end(); ++pa, ++i)
11783 std::string reason;
11784 if (!Type::are_assignable(element_type, (*pa)->type(),
11785 &reason))
11787 if (reason.empty())
11788 go_error_at((*pa)->location(),
11789 "argument %d has incompatible type", i);
11790 else
11791 go_error_at((*pa)->location(),
11792 "argument %d has incompatible type (%s)",
11793 i, reason.c_str());
11794 this->set_is_error();
11799 break;
11801 case BUILTIN_REAL:
11802 case BUILTIN_IMAG:
11803 if (this->check_one_arg())
11805 if (this->one_arg()->type()->complex_type() == NULL)
11806 this->report_error(_("argument must have complex type"));
11808 break;
11810 case BUILTIN_COMPLEX:
11812 const Expression_list* args = this->args();
11813 go_assert(args != NULL && args->size() == 2);
11814 if (args->front()->is_error_expression()
11815 || args->front()->type()->is_error()
11816 || args->back()->is_error_expression()
11817 || args->back()->type()->is_error())
11818 this->set_is_error();
11819 else if (!Type::are_identical(args->front()->type(),
11820 args->back()->type(),
11821 Type::COMPARE_TAGS, NULL))
11822 this->report_error(_("complex arguments must have identical types"));
11823 else if (args->front()->type()->float_type() == NULL)
11824 this->report_error(_("complex arguments must have "
11825 "floating-point type"));
11827 break;
11829 case BUILTIN_ADD:
11830 case BUILTIN_SLICE:
11832 Numeric_constant nc;
11833 unsigned long v;
11834 const Expression_list* args = this->args();
11835 if (args == NULL || args->size() < 2)
11836 this->report_error(_("not enough arguments"));
11837 else if (args->size() > 2)
11838 this->report_error(_("too many arguments"));
11839 else if (args->front()->is_error_expression()
11840 || args->front()->type()->is_error()
11841 || args->back()->is_error_expression()
11842 || args->back()->type()->is_error())
11843 this->set_is_error();
11844 else if (args->back()->type()->integer_type() == NULL
11845 && (!args->back()->type()->is_abstract()
11846 || !args->back()->numeric_constant_value(&nc)
11847 || (nc.to_unsigned_long(&v)
11848 == Numeric_constant::NC_UL_NOTINT)))
11850 if (this->code_ == BUILTIN_ADD)
11851 go_error_at(args->back()->location(), "non-integer offset");
11852 else
11853 go_error_at(args->back()->location(), "non-integer size");
11855 else if (this->code_ == BUILTIN_ADD)
11857 Type* pointer_type =
11858 Type::make_pointer_type(Type::make_void_type());
11859 std::string reason;
11860 if (!Type::are_assignable(pointer_type, args->front()->type(),
11861 &reason))
11863 if (reason.empty())
11864 go_error_at(args->front()->location(),
11865 "argument 1 has incompatible type");
11866 else
11867 go_error_at(args->front()->location(),
11868 "argument 1 has incompatible type (%s)",
11869 reason.c_str());
11870 this->set_is_error();
11873 else
11875 if (args->front()->type()->points_to() == NULL)
11877 go_error_at(args->front()->location(),
11878 "argument 1 must be a pointer");
11879 this->set_is_error();
11882 unsigned int int_bits =
11883 Type::lookup_integer_type("int")->integer_type()->bits();
11885 mpz_t ival;
11886 if (args->back()->numeric_constant_value(&nc) && nc.to_int(&ival))
11888 if (mpz_sgn(ival) < 0
11889 || mpz_sizeinbase(ival, 2) >= int_bits)
11891 go_error_at(args->back()->location(),
11892 "slice length out of range");
11893 this->set_is_error();
11895 mpz_clear(ival);
11899 break;
11901 default:
11902 go_unreachable();
11906 Expression*
11907 Builtin_call_expression::do_copy()
11909 Call_expression* bce =
11910 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
11911 (this->args() == NULL
11912 ? NULL
11913 : this->args()->copy()),
11914 this->is_varargs(),
11915 this->location());
11917 if (this->varargs_are_lowered())
11918 bce->set_varargs_are_lowered();
11919 if (this->is_deferred())
11920 bce->set_is_deferred();
11921 if (this->is_concurrent())
11922 bce->set_is_concurrent();
11923 return bce;
11926 // Return the backend representation for a builtin function.
11928 Bexpression*
11929 Builtin_call_expression::do_get_backend(Translate_context* context)
11931 Gogo* gogo = context->gogo();
11932 Location location = this->location();
11934 if (this->is_erroneous_call())
11936 go_assert(saw_errors());
11937 return gogo->backend()->error_expression();
11940 switch (this->code_)
11942 case BUILTIN_INVALID:
11943 case BUILTIN_NEW:
11944 case BUILTIN_MAKE:
11945 case BUILTIN_ADD:
11946 case BUILTIN_SLICE:
11947 go_unreachable();
11949 case BUILTIN_LEN:
11950 case BUILTIN_CAP:
11952 const Expression_list* args = this->args();
11953 go_assert(args != NULL && args->size() == 1);
11954 Expression* arg = args->front();
11955 Type* arg_type = arg->type();
11957 if (this->seen_)
11959 go_assert(saw_errors());
11960 return context->backend()->error_expression();
11962 this->seen_ = true;
11963 this->seen_ = false;
11964 if (arg_type->points_to() != NULL)
11966 arg_type = arg_type->points_to();
11967 go_assert(arg_type->array_type() != NULL
11968 && !arg_type->is_slice_type());
11969 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
11970 location);
11973 Type* int_type = Type::lookup_integer_type("int");
11974 Expression* val;
11975 if (this->code_ == BUILTIN_LEN)
11977 if (arg_type->is_string_type())
11978 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
11979 location);
11980 else if (arg_type->array_type() != NULL)
11982 if (this->seen_)
11984 go_assert(saw_errors());
11985 return context->backend()->error_expression();
11987 this->seen_ = true;
11988 val = arg_type->array_type()->get_length(gogo, arg);
11989 this->seen_ = false;
11991 else if (arg_type->map_type() != NULL
11992 || arg_type->channel_type() != NULL)
11994 // The first field is the length. If the pointer is
11995 // nil, the length is zero.
11996 Type* pint_type = Type::make_pointer_type(int_type);
11997 arg = Expression::make_unsafe_cast(pint_type, arg, location);
11998 Expression* nil = Expression::make_nil(location);
11999 nil = Expression::make_cast(pint_type, nil, location);
12000 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
12001 arg, nil, location);
12002 Expression* zero = Expression::make_integer_ul(0, int_type,
12003 location);
12004 Expression* indir =
12005 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
12006 location);
12007 val = Expression::make_conditional(cmp, zero, indir, location);
12009 else
12010 go_unreachable();
12012 else
12014 if (arg_type->array_type() != NULL)
12016 if (this->seen_)
12018 go_assert(saw_errors());
12019 return context->backend()->error_expression();
12021 this->seen_ = true;
12022 val = arg_type->array_type()->get_capacity(gogo, arg);
12023 this->seen_ = false;
12025 else if (arg_type->channel_type() != NULL)
12027 // The second field is the capacity. If the pointer
12028 // is nil, the capacity is zero.
12029 Type* uintptr_type = Type::lookup_integer_type("uintptr");
12030 Type* pint_type = Type::make_pointer_type(int_type);
12031 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
12032 arg,
12033 location);
12034 int off = int_type->integer_type()->bits() / 8;
12035 Expression* eoff = Expression::make_integer_ul(off,
12036 uintptr_type,
12037 location);
12038 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
12039 location);
12040 parg = Expression::make_unsafe_cast(pint_type, parg, location);
12041 Expression* nil = Expression::make_nil(location);
12042 nil = Expression::make_cast(pint_type, nil, location);
12043 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
12044 arg, nil, location);
12045 Expression* zero = Expression::make_integer_ul(0, int_type,
12046 location);
12047 Expression* indir =
12048 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
12049 location);
12050 val = Expression::make_conditional(cmp, zero, indir, location);
12052 else
12053 go_unreachable();
12056 Expression* e = Expression::make_cast(int_type, val, location);
12057 e->determine_type_no_context(gogo);
12058 return e->get_backend(context);
12061 case BUILTIN_PRINT:
12062 case BUILTIN_PRINTLN:
12064 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
12066 Expression* print_stmts = Runtime::make_call(gogo, Runtime::PRINTLOCK,
12067 location, 0);
12069 const Expression_list* call_args = this->args();
12070 if (call_args != NULL)
12072 for (Expression_list::const_iterator p = call_args->begin();
12073 p != call_args->end();
12074 ++p)
12076 if (is_ln && p != call_args->begin())
12078 Expression* print_space =
12079 Runtime::make_call(gogo, Runtime::PRINTSP, location, 0);
12081 print_stmts =
12082 Expression::make_compound(print_stmts, print_space,
12083 location);
12086 Expression* arg = *p;
12087 Type* type = arg->type();
12088 Runtime::Function code;
12089 if (type->is_string_type())
12090 code = Runtime::PRINTSTRING;
12091 else if (type->integer_type() != NULL
12092 && type->integer_type()->is_unsigned())
12094 Type* itype = Type::lookup_integer_type("uint64");
12095 arg = Expression::make_cast(itype, arg, location);
12096 if (gogo->compiling_runtime()
12097 && type->named_type() != NULL
12098 && gogo->unpack_hidden_name(type->named_type()->name())
12099 == "hex")
12100 code = Runtime::PRINTHEX;
12101 else
12102 code = Runtime::PRINTUINT;
12104 else if (type->integer_type() != NULL)
12106 Type* itype = Type::lookup_integer_type("int64");
12107 arg = Expression::make_cast(itype, arg, location);
12108 code = Runtime::PRINTINT;
12110 else if (type->float_type() != NULL)
12112 Type* dtype = Type::lookup_float_type("float64");
12113 arg = Expression::make_cast(dtype, arg, location);
12114 code = Runtime::PRINTFLOAT;
12116 else if (type->complex_type() != NULL)
12118 Type* ctype = Type::lookup_complex_type("complex128");
12119 arg = Expression::make_cast(ctype, arg, location);
12120 code = Runtime::PRINTCOMPLEX;
12122 else if (type->is_boolean_type())
12123 code = Runtime::PRINTBOOL;
12124 else if (type->points_to() != NULL
12125 || type->channel_type() != NULL
12126 || type->map_type() != NULL
12127 || type->function_type() != NULL)
12129 arg = Expression::make_cast(type, arg, location);
12130 code = Runtime::PRINTPOINTER;
12132 else if (type->interface_type() != NULL)
12134 if (type->interface_type()->is_empty())
12135 code = Runtime::PRINTEFACE;
12136 else
12137 code = Runtime::PRINTIFACE;
12139 else if (type->is_slice_type())
12140 code = Runtime::PRINTSLICE;
12141 else
12143 go_assert(saw_errors());
12144 return context->backend()->error_expression();
12147 Expression* call = Runtime::make_call(gogo, code, location, 1,
12148 arg);
12149 print_stmts = Expression::make_compound(print_stmts, call,
12150 location);
12154 if (is_ln)
12156 Expression* print_nl =
12157 Runtime::make_call(gogo, Runtime::PRINTNL, location, 0);
12158 print_stmts = Expression::make_compound(print_stmts, print_nl,
12159 location);
12162 Expression* unlock = Runtime::make_call(gogo, Runtime::PRINTUNLOCK,
12163 location, 0);
12164 print_stmts = Expression::make_compound(print_stmts, unlock, location);
12166 print_stmts->determine_type_no_context(gogo);
12168 return print_stmts->get_backend(context);
12171 case BUILTIN_PANIC:
12173 const Expression_list* args = this->args();
12174 go_assert(args != NULL && args->size() == 1);
12175 Expression* arg = args->front();
12176 Type *empty =
12177 Type::make_empty_interface_type(Linemap::predeclared_location());
12178 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
12180 Expression* panic =
12181 Runtime::make_call(gogo, Runtime::GOPANIC, location, 1, arg);
12182 panic->determine_type_no_context(gogo);
12183 return panic->get_backend(context);
12186 case BUILTIN_RECOVER:
12188 // The argument is set when building recover thunks. It's a
12189 // boolean value which is true if we can recover a value now.
12190 const Expression_list* args = this->args();
12191 go_assert(args != NULL && args->size() == 1);
12192 Expression* arg = args->front();
12193 Type *empty =
12194 Type::make_empty_interface_type(Linemap::predeclared_location());
12196 Expression* nil = Expression::make_nil(location);
12197 nil = Expression::make_interface_value(empty, nil, nil, location);
12199 // We need to handle a deferred call to recover specially,
12200 // because it changes whether it can recover a panic or not.
12201 // See test7 in test/recover1.go.
12202 Expression* recover = Runtime::make_call(gogo,
12203 (this->is_deferred()
12204 ? Runtime::DEFERREDRECOVER
12205 : Runtime::GORECOVER),
12206 location, 0);
12207 Expression* cond =
12208 Expression::make_conditional(arg, recover, nil, location);
12209 cond->determine_type_no_context(gogo);
12210 return cond->get_backend(context);
12213 case BUILTIN_CLOSE:
12215 const Expression_list* args = this->args();
12216 go_assert(args != NULL && args->size() == 1);
12217 Expression* arg = args->front();
12218 Expression* close = Runtime::make_call(gogo, Runtime::CLOSE, location,
12219 1, arg);
12220 close->determine_type_no_context(gogo);
12221 return close->get_backend(context);
12224 case BUILTIN_SIZEOF:
12225 case BUILTIN_OFFSETOF:
12226 case BUILTIN_ALIGNOF:
12228 Numeric_constant nc;
12229 unsigned long val;
12230 if (!this->numeric_constant_value(&nc)
12231 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
12233 go_assert(saw_errors());
12234 return context->backend()->error_expression();
12236 Type* uintptr_type = Type::lookup_integer_type("uintptr");
12237 mpz_t ival;
12238 nc.get_int(&ival);
12239 Expression* int_cst =
12240 Expression::make_integer_z(&ival, uintptr_type, location);
12241 mpz_clear(ival);
12242 return int_cst->get_backend(context);
12245 case BUILTIN_COPY:
12246 // Handled in Builtin_call_expression::do_flatten.
12247 go_unreachable();
12249 case BUILTIN_APPEND:
12250 // Handled in Builtin_call_expression::flatten_append.
12251 go_unreachable();
12253 case BUILTIN_REAL:
12254 case BUILTIN_IMAG:
12256 const Expression_list* args = this->args();
12257 go_assert(args != NULL && args->size() == 1);
12259 Bexpression* ret;
12260 Bexpression* bcomplex = args->front()->get_backend(context);
12261 if (this->code_ == BUILTIN_REAL)
12262 ret = gogo->backend()->real_part_expression(bcomplex, location);
12263 else
12264 ret = gogo->backend()->imag_part_expression(bcomplex, location);
12265 return ret;
12268 case BUILTIN_COMPLEX:
12270 const Expression_list* args = this->args();
12271 go_assert(args != NULL && args->size() == 2);
12272 Bexpression* breal = args->front()->get_backend(context);
12273 Bexpression* bimag = args->back()->get_backend(context);
12274 return gogo->backend()->complex_expression(breal, bimag, location);
12277 default:
12278 go_unreachable();
12282 // We have to support exporting a builtin call expression, because
12283 // code can set a constant to the result of a builtin expression.
12285 void
12286 Builtin_call_expression::do_export(Export_function_body* efb) const
12288 if (this->code_ == BUILTIN_ADD || this->code_ == BUILTIN_SLICE)
12290 char buf[50];
12291 snprintf(buf, sizeof buf, "<p%d>%s", efb->unsafe_package_index(),
12292 (this->code_ == BUILTIN_ADD ? "Add" : "Slice"));
12293 efb->write_c_string(buf);
12294 this->export_arguments(efb);
12296 else
12298 const char *s = NULL;
12299 switch (this->code_)
12301 default:
12302 go_unreachable();
12303 case BUILTIN_APPEND:
12304 s = "append";
12305 break;
12306 case BUILTIN_COPY:
12307 s = "copy";
12308 break;
12309 case BUILTIN_LEN:
12310 s = "len";
12311 break;
12312 case BUILTIN_CAP:
12313 s = "cap";
12314 break;
12315 case BUILTIN_DELETE:
12316 s = "delete";
12317 break;
12318 case BUILTIN_PRINT:
12319 s = "print";
12320 break;
12321 case BUILTIN_PRINTLN:
12322 s = "println";
12323 break;
12324 case BUILTIN_PANIC:
12325 s = "panic";
12326 break;
12327 case BUILTIN_RECOVER:
12328 s = "recover";
12329 break;
12330 case BUILTIN_CLOSE:
12331 s = "close";
12332 break;
12333 case BUILTIN_REAL:
12334 s = "real";
12335 break;
12336 case BUILTIN_IMAG:
12337 s = "imag";
12338 break;
12339 case BUILTIN_COMPLEX:
12340 s = "complex";
12341 break;
12343 efb->write_c_string(s);
12344 this->export_arguments(efb);
12348 // Class Call_expression.
12350 // A Go function can be viewed in a couple of different ways. The
12351 // code of a Go function becomes a backend function with parameters
12352 // whose types are simply the backend representation of the Go types.
12353 // If there are multiple results, they are returned as a backend
12354 // struct.
12356 // However, when Go code refers to a function other than simply
12357 // calling it, the backend type of that function is actually a struct.
12358 // The first field of the struct points to the Go function code
12359 // (sometimes a wrapper as described below). The remaining fields
12360 // hold addresses of closed-over variables. This struct is called a
12361 // closure.
12363 // There are a few cases to consider.
12365 // A direct function call of a known function in package scope. In
12366 // this case there are no closed-over variables, and we know the name
12367 // of the function code. We can simply produce a backend call to the
12368 // function directly, and not worry about the closure.
12370 // A direct function call of a known function literal. In this case
12371 // we know the function code and we know the closure. We generate the
12372 // function code such that it expects an additional final argument of
12373 // the closure type. We pass the closure as the last argument, after
12374 // the other arguments.
12376 // An indirect function call. In this case we have a closure. We
12377 // load the pointer to the function code from the first field of the
12378 // closure. We pass the address of the closure as the last argument.
12380 // A call to a method of an interface. Type methods are always at
12381 // package scope, so we call the function directly, and don't worry
12382 // about the closure.
12384 // This means that for a function at package scope we have two cases.
12385 // One is the direct call, which has no closure. The other is the
12386 // indirect call, which does have a closure. We can't simply ignore
12387 // the closure, even though it is the last argument, because that will
12388 // fail on targets where the function pops its arguments. So when
12389 // generating a closure for a package-scope function we set the
12390 // function code pointer in the closure to point to a wrapper
12391 // function. This wrapper function accepts a final argument that
12392 // points to the closure, ignores it, and calls the real function as a
12393 // direct function call. This wrapper will normally be efficient, and
12394 // can often simply be a tail call to the real function.
12396 // We don't use GCC's static chain pointer because 1) we don't need
12397 // it; 2) GCC only permits using a static chain to call a known
12398 // function, so we can't use it for an indirect call anyhow. Since we
12399 // can't use it for an indirect call, we may as well not worry about
12400 // using it for a direct call either.
12402 // We pass the closure last rather than first because it means that
12403 // the function wrapper we put into a closure for a package-scope
12404 // function can normally just be a tail call to the real function.
12406 // For method expressions we generate a wrapper that loads the
12407 // receiver from the closure and then calls the method. This
12408 // unfortunately forces reshuffling the arguments, since there is a
12409 // new first argument, but we can't avoid reshuffling either for
12410 // method expressions or for indirect calls of package-scope
12411 // functions, and since the latter are more common we reshuffle for
12412 // method expressions.
12414 // Note that the Go code retains the Go types. The extra final
12415 // argument only appears when we convert to the backend
12416 // representation.
12418 // Traversal.
12421 Call_expression::do_traverse(Traverse* traverse)
12423 if (this->lowered_ != NULL)
12424 return Expression::traverse(&this->lowered_, traverse);
12426 // If we are calling a function in a different package that returns
12427 // an unnamed type, this may be the only chance we get to traverse
12428 // that type. We don't traverse this->type_ because it may be a
12429 // Call_multiple_result_type that will just lead back here.
12430 if (this->type_ != NULL && !this->type_->is_error_type())
12432 Function_type *fntype = this->get_function_type();
12433 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
12434 return TRAVERSE_EXIT;
12436 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
12437 return TRAVERSE_EXIT;
12438 if (this->args_ != NULL)
12440 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
12441 return TRAVERSE_EXIT;
12443 return TRAVERSE_CONTINUE;
12446 // Lower a Call_expression to a Builtin_call_expression. This happens
12447 // early on, before determine_types.
12449 Expression*
12450 Call_expression::lower_builtin(Gogo* gogo)
12452 // This is called before determine_types, so we can't call
12453 // this->fn_->type(). Fortunately builtin calls require a direct
12454 // reference to the builtin.
12455 Expression* fn = this->fn_;
12456 Named_object* no;
12457 if (fn->func_expression() != NULL)
12458 no = fn->func_expression()->named_object();
12459 else if (fn->unknown_expression() != NULL)
12461 no = fn->unknown_expression()->named_object();
12462 if (no->is_unknown())
12464 no = no->unknown_value()->real_named_object();
12465 if (no == NULL)
12466 return this;
12469 else
12470 return this;
12472 if (!no->is_function_declaration())
12473 return this;
12474 if (!no->func_declaration_value()->type()->is_builtin())
12475 return this;
12477 if (fn->unknown_expression() != NULL)
12478 fn = Expression::make_func_reference(no, NULL, fn->location());
12480 Builtin_call_expression* bce = new Builtin_call_expression(gogo, fn,
12481 this->args_,
12482 this->is_varargs_,
12483 this->location());
12484 if (this->is_deferred_)
12485 bce->set_is_deferred();
12486 if (this->is_concurrent_)
12487 bce->set_is_concurrent();
12488 return bce;
12491 // A type conversion can be a constant.
12493 bool
12494 Call_expression::do_is_constant() const
12496 if (this->lowered_ != NULL)
12497 return this->lowered_->is_constant();
12498 if (this->fn_->is_type_expression()
12499 && this->args_ != NULL
12500 && this->args_->size() == 1)
12501 return this->args_->front()->is_constant();
12502 return false;
12505 bool
12506 Call_expression::do_is_untyped(Type** ptype) const
12508 if (this->lowered_ != NULL)
12509 return this->lowered_->is_untyped(ptype);
12510 return false;
12513 bool
12514 Call_expression::do_numeric_constant_value(Numeric_constant* nc)
12516 if (this->lowered_ != NULL)
12517 return this->lowered_->numeric_constant_value(nc);
12518 if (this->fn_->is_type_expression()
12519 && this->args_ != NULL
12520 && this->args_->size() == 1)
12522 // If we get here, it's before the determine_types pass, so we
12523 // have to pull apart the type carefully. This is a hack that
12524 // is needed because the finalize_methods needs to be able to
12525 // determine whether the length of an array is 1.
12527 Type* type;
12528 if (this->fn_->classification() == EXPRESSION_TYPE)
12529 type = this->fn_->type();
12530 else if (this->fn_->unknown_expression() != NULL)
12532 Named_object* no = this->fn_->unknown_expression()->named_object();
12533 if (no->is_unknown())
12535 no = no->unknown_value()->real_named_object();
12536 go_assert(no != NULL);
12538 type = no->type_value();
12540 else
12541 return false;
12543 if (!type->is_numeric_type())
12544 return false;
12545 if (!this->args_->front()->numeric_constant_value(nc))
12546 return false;
12547 return nc->set_type(type, false, this->location());
12549 return false;
12552 bool
12553 Call_expression::do_discarding_value()
12555 if (this->fn_->is_type_expression())
12557 this->unused_value_error();
12558 return false;
12560 return true;
12563 // Lower a call statement.
12565 Expression*
12566 Call_expression::do_lower(Gogo* gogo, Named_object*,
12567 Statement_inserter* inserter)
12569 if (this->lowered_ != NULL)
12570 return this->lowered_;
12572 Location loc = this->location();
12574 if (this->is_error_expression())
12575 return Expression::make_error(loc);
12577 // Although we've already lowered calls to builtin functions, we may
12578 // still see calls generated to builtins elsewhere in the lowering
12579 // pass. It's simpler to handle them here.
12580 Expression* builtin = this->lower_builtin(gogo);
12581 if (builtin != this)
12582 return builtin;
12584 // If this call returns multiple results, create a temporary
12585 // variable to hold them.
12586 if (this->result_count() > 1 && this->call_temp_ == NULL)
12588 Struct_field_list* sfl = new Struct_field_list();
12589 const Typed_identifier_list* results =
12590 this->get_function_type()->results();
12592 int i = 0;
12593 char buf[20];
12594 for (Typed_identifier_list::const_iterator p = results->begin();
12595 p != results->end();
12596 ++p, ++i)
12598 snprintf(buf, sizeof buf, "res%d", i);
12599 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
12602 Struct_type* st = Type::make_struct_type(sfl, loc);
12603 st->set_is_struct_incomparable();
12604 st->set_is_results_struct();
12605 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
12606 inserter->insert(this->call_temp_);
12609 // If this is call to a method, call the method directly passing the
12610 // object as the first parameter.
12611 Bound_method_expression* bme = this->fn_->bound_method_expression();
12612 if (bme != NULL && !this->is_deferred_ && !this->is_concurrent_)
12614 Named_object* methodfn = bme->function();
12615 Function_type* mft = (methodfn->is_function()
12616 ? methodfn->func_value()->type()
12617 : methodfn->func_declaration_value()->type());
12618 Expression* first_arg = bme->first_argument();
12620 // We always pass a pointer when calling a method, except for
12621 // direct interface types when calling a value method.
12622 if (!first_arg->type()->is_error()
12623 && first_arg->type()->points_to() == NULL
12624 && !first_arg->type()->is_direct_iface_type())
12626 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
12627 // We may need to create a temporary variable so that we can
12628 // take the address. We can't do that here because it will
12629 // mess up the order of evaluation.
12630 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
12631 ue->set_create_temp();
12633 else if (mft->receiver()->type()->points_to() == NULL
12634 && first_arg->type()->points_to() != NULL
12635 && first_arg->type()->points_to()->is_direct_iface_type())
12636 first_arg = Expression::make_dereference(first_arg,
12637 Expression::NIL_CHECK_DEFAULT,
12638 loc);
12640 // If we are calling a method which was inherited from an
12641 // embedded struct, and the method did not get a stub, then the
12642 // first type may be wrong.
12643 Type* fatype = bme->first_argument_type();
12644 if (fatype != NULL)
12646 if (fatype->points_to() == NULL)
12647 fatype = Type::make_pointer_type(fatype);
12648 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
12651 first_arg->determine_type_no_context(gogo);
12652 first_arg->check_types(gogo);
12654 Expression_list* new_args = new Expression_list();
12655 new_args->push_back(first_arg);
12656 if (this->args_ != NULL)
12658 for (Expression_list::const_iterator p = this->args_->begin();
12659 p != this->args_->end();
12660 ++p)
12661 new_args->push_back(*p);
12664 // We have to change in place because this structure may be
12665 // referenced by Call_result_expressions. We can't delete the
12666 // old arguments, because we may be traversing them up in some
12667 // caller. FIXME.
12668 this->args_ = new_args;
12669 this->fn_ = Expression::make_func_reference(methodfn, NULL,
12670 bme->location());
12673 // If this is a call to an imported function for which we have an
12674 // inlinable function body, add it to the list of functions to give
12675 // to the backend as inlining opportunities.
12676 Func_expression* fe = this->fn_->func_expression();
12677 if (fe != NULL
12678 && fe->named_object()->is_function_declaration()
12679 && fe->named_object()->func_declaration_value()->has_imported_body())
12680 gogo->add_imported_inlinable_function(fe->named_object());
12682 return this;
12685 // Flatten a call with multiple results into a temporary.
12687 Expression*
12688 Call_expression::do_flatten(Gogo* gogo, Named_object*,
12689 Statement_inserter* inserter)
12691 if (this->is_erroneous_call())
12693 go_assert(saw_errors());
12694 return Expression::make_error(this->location());
12697 if (this->is_flattened_)
12698 return this;
12699 this->is_flattened_ = true;
12701 // Add temporary variables for all arguments that require type
12702 // conversion.
12703 Function_type* fntype = this->get_function_type();
12704 if (fntype == NULL)
12706 go_assert(saw_errors());
12707 return this;
12709 if (this->args_ != NULL && !this->args_->empty()
12710 && fntype->parameters() != NULL && !fntype->parameters()->empty())
12712 bool is_interface_method =
12713 this->fn_->interface_field_reference_expression() != NULL;
12715 Expression_list *args = new Expression_list();
12716 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
12717 Expression_list::const_iterator pa = this->args_->begin();
12718 if (!is_interface_method && fntype->is_method())
12720 // The receiver argument.
12721 args->push_back(*pa);
12722 ++pa;
12724 for (; pa != this->args_->end(); ++pa, ++pp)
12726 go_assert(pp != fntype->parameters()->end());
12727 if (Type::are_identical(pp->type(), (*pa)->type(),
12728 Type::COMPARE_TAGS, NULL))
12729 args->push_back(*pa);
12730 else
12732 Location loc = (*pa)->location();
12733 Expression* arg = *pa;
12734 if (!arg->is_multi_eval_safe())
12736 Temporary_statement *temp =
12737 Statement::make_temporary(NULL, arg, loc);
12738 inserter->insert(temp);
12739 arg = Expression::make_temporary_reference(temp, loc);
12741 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
12742 loc);
12743 args->push_back(arg);
12746 delete this->args_;
12747 this->args_ = args;
12750 // Lower to compiler intrinsic if possible.
12751 Func_expression* fe = this->fn_->func_expression();
12752 if (!this->is_concurrent_ && !this->is_deferred_
12753 && fe != NULL
12754 && (fe->named_object()->is_function_declaration()
12755 || fe->named_object()->is_function()))
12757 Expression* ret = this->intrinsify(gogo, inserter);
12758 if (ret != NULL)
12760 ret->determine_type_no_context(gogo);
12761 return ret;
12765 // Add an implicit conversion to a boolean type, if needed. See the
12766 // comment in Binary_expression::lower_array_comparison.
12767 if (this->is_equal_function_
12768 && this->type_ != NULL
12769 && this->type_ != Type::lookup_bool_type())
12770 return Expression::make_cast(this->type_, this, this->location());
12772 return this;
12775 // Lower a call to a compiler intrinsic if possible.
12776 // Returns NULL if it is not an intrinsic.
12778 Expression*
12779 Call_expression::intrinsify(Gogo* gogo,
12780 Statement_inserter* inserter)
12782 Func_expression* fe = this->fn_->func_expression();
12783 Named_object* no = fe->named_object();
12784 std::string name = Gogo::unpack_hidden_name(no->name());
12785 std::string package = (no->package() != NULL
12786 ? no->package()->pkgpath()
12787 : gogo->pkgpath());
12788 bool is_method = ((no->is_function() && no->func_value()->is_method())
12789 || (no->is_function_declaration()
12790 && no->func_declaration_value()->is_method()));
12791 Location loc = this->location();
12793 Type* int_type = Type::lookup_integer_type("int");
12794 Type* int32_type = Type::lookup_integer_type("int32");
12795 Type* int64_type = Type::lookup_integer_type("int64");
12796 Type* uint_type = Type::lookup_integer_type("uint");
12797 Type* uint8_type = Type::lookup_integer_type("uint8");
12798 Type* uint32_type = Type::lookup_integer_type("uint32");
12799 Type* uint64_type = Type::lookup_integer_type("uint64");
12800 Type* uintptr_type = Type::lookup_integer_type("uintptr");
12801 Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
12803 int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
12804 int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
12806 if (package == "sync/atomic")
12808 if (is_method)
12809 return NULL;
12811 // sync/atomic functions and runtime/internal/atomic functions
12812 // are very similar. In order not to duplicate code, we just
12813 // redirect to the latter and let the code below to handle them.
12814 // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
12815 // as they need write barriers.
12816 if (name == "LoadInt32")
12817 name = "Loadint32";
12818 else if (name == "LoadInt64")
12819 name = "Loadint64";
12820 else if (name == "LoadUint32")
12821 name = "Load";
12822 else if (name == "LoadUint64")
12823 name = "Load64";
12824 else if (name == "LoadUintptr")
12825 name = "Loaduintptr";
12826 else if (name == "LoadPointer")
12827 name = "Loadp";
12828 else if (name == "StoreInt32")
12829 name = "Storeint32";
12830 else if (name == "StoreInt64")
12831 name = "Storeint64";
12832 else if (name == "StoreUint32")
12833 name = "Store";
12834 else if (name == "StoreUint64")
12835 name = "Store64";
12836 else if (name == "StoreUintptr")
12837 name = "Storeuintptr";
12838 else if (name == "AddInt32")
12839 name = "Xaddint32";
12840 else if (name == "AddInt64")
12841 name = "Xaddint64";
12842 else if (name == "AddUint32")
12843 name = "Xadd";
12844 else if (name == "AddUint64")
12845 name = "Xadd64";
12846 else if (name == "AddUintptr")
12847 name = "Xadduintptr";
12848 else if (name == "SwapInt32")
12849 name = "Xchgint32";
12850 else if (name == "SwapInt64")
12851 name = "Xchgint64";
12852 else if (name == "SwapUint32")
12853 name = "Xchg";
12854 else if (name == "SwapUint64")
12855 name = "Xchg64";
12856 else if (name == "SwapUintptr")
12857 name = "Xchguintptr";
12858 else if (name == "CompareAndSwapInt32")
12859 name = "Casint32";
12860 else if (name == "CompareAndSwapInt64")
12861 name = "Casint64";
12862 else if (name == "CompareAndSwapUint32")
12863 name = "Cas";
12864 else if (name == "CompareAndSwapUint64")
12865 name = "Cas64";
12866 else if (name == "CompareAndSwapUintptr")
12867 name = "Casuintptr";
12868 else
12869 return NULL;
12871 package = "runtime/internal/atomic";
12874 if (package == "runtime/internal/sys")
12876 if (is_method)
12877 return NULL;
12879 // runtime/internal/sys functions and math/bits functions
12880 // are very similar. In order not to duplicate code, we just
12881 // redirect to the latter and let the code below to handle them.
12882 if (name == "Bswap32")
12883 name = "ReverseBytes32";
12884 else if (name == "Bswap64")
12885 name = "ReverseBytes64";
12886 else if (name == "Ctz32")
12887 name = "TrailingZeros32";
12888 else if (name == "Ctz64")
12889 name = "TrailingZeros64";
12890 else
12891 return NULL;
12893 package = "math/bits";
12896 if (package == "runtime")
12898 if (is_method)
12899 return NULL;
12901 // Handle a couple of special runtime functions. In the runtime
12902 // package, getcallerpc returns the PC of the caller, and
12903 // getcallersp returns the frame pointer of the caller. Implement
12904 // these by turning them into calls to GCC builtin functions. We
12905 // could implement them in normal code, but then we would have to
12906 // explicitly unwind the stack. These functions are intended to be
12907 // efficient. Note that this technique obviously only works for
12908 // direct calls, but that is the only way they are used.
12909 if (name == "getcallerpc"
12910 && (this->args_ == NULL || this->args_->size() == 0))
12912 Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
12913 Expression* call =
12914 Runtime::make_call(gogo, Runtime::BUILTIN_RETURN_ADDRESS, loc,
12915 1, arg);
12916 // The builtin functions return void*, but the Go functions return uintptr.
12917 return Expression::make_cast(uintptr_type, call, loc);
12919 else if (name == "getcallersp"
12920 && (this->args_ == NULL || this->args_->size() == 0))
12923 Expression* call =
12924 Runtime::make_call(gogo, Runtime::BUILTIN_DWARF_CFA, loc, 0);
12925 // The builtin functions return void*, but the Go functions return uintptr.
12926 return Expression::make_cast(uintptr_type, call, loc);
12929 else if (package == "math/bits")
12931 if (is_method)
12932 return NULL;
12934 if ((name == "ReverseBytes16" || name == "ReverseBytes32"
12935 || name == "ReverseBytes64" || name == "ReverseBytes")
12936 && this->args_ != NULL && this->args_->size() == 1)
12938 Runtime::Function code;
12939 if (name == "ReverseBytes16")
12940 code = Runtime::BUILTIN_BSWAP16;
12941 else if (name == "ReverseBytes32")
12942 code = Runtime::BUILTIN_BSWAP32;
12943 else if (name == "ReverseBytes64")
12944 code = Runtime::BUILTIN_BSWAP64;
12945 else if (name == "ReverseBytes")
12946 code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
12947 else
12948 go_unreachable();
12949 Expression* arg = this->args_->front();
12950 Expression* call = Runtime::make_call(gogo, code, loc, 1, arg);
12951 if (name == "ReverseBytes")
12952 return Expression::make_cast(uint_type, call, loc);
12953 return call;
12955 else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
12956 && this->args_ != NULL && this->args_->size() == 1)
12958 // GCC does not have a ctz8 or ctz16 intrinsic. We do
12959 // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
12960 Expression* arg = this->args_->front();
12961 arg = Expression::make_cast(uint32_type, arg, loc);
12962 unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
12963 Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
12964 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
12965 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CTZ,
12966 loc, 1, arg);
12967 return Expression::make_cast(int_type, call, loc);
12969 else if ((name == "TrailingZeros32"
12970 || (name == "TrailingZeros" && int_size == 4))
12971 && this->args_ != NULL && this->args_->size() == 1)
12973 Expression* arg = this->args_->front();
12974 if (!arg->is_multi_eval_safe())
12976 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
12977 inserter->insert(ts);
12978 arg = Expression::make_temporary_reference(ts, loc);
12980 // arg == 0 ? 32 : __builtin_ctz(arg)
12981 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
12982 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
12983 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
12984 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CTZ,
12985 loc, 1, arg->copy());
12986 call = Expression::make_cast(int_type, call, loc);
12987 return Expression::make_conditional(cmp, c32, call, loc);
12989 else if ((name == "TrailingZeros64"
12990 || (name == "TrailingZeros" && int_size == 8))
12991 && this->args_ != NULL && this->args_->size() == 1)
12993 Expression* arg = this->args_->front();
12994 if (!arg->is_multi_eval_safe())
12996 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
12997 inserter->insert(ts);
12998 arg = Expression::make_temporary_reference(ts, loc);
13000 // arg == 0 ? 64 : __builtin_ctzll(arg)
13001 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
13002 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
13003 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
13004 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CTZLL,
13005 loc, 1, arg->copy());
13006 call = Expression::make_cast(int_type, call, loc);
13007 return Expression::make_conditional(cmp, c64, call, loc);
13009 else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
13010 || name == "Len8" || name == "Len16")
13011 && this->args_ != NULL && this->args_->size() == 1)
13013 // GCC does not have a clz8 ir clz16 intrinsic. We do
13014 // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
13015 Expression* arg = this->args_->front();
13016 arg = Expression::make_cast(uint32_type, arg, loc);
13017 unsigned long shift =
13018 ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
13019 Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
13020 arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
13021 unsigned long mask =
13022 ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
13023 c = Expression::make_integer_ul(mask, uint32_type, loc);
13024 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
13025 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CLZ,
13026 loc, 1, arg);
13027 call = Expression::make_cast(int_type, call, loc);
13028 // len = width - clz
13029 if (name == "Len8")
13031 c = Expression::make_integer_ul(8, int_type, loc);
13032 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
13034 else if (name == "Len16")
13036 c = Expression::make_integer_ul(16, int_type, loc);
13037 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
13039 return call;
13041 else if ((name == "LeadingZeros32" || name == "Len32"
13042 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
13043 && this->args_ != NULL && this->args_->size() == 1)
13045 Expression* arg = this->args_->front();
13046 if (!arg->is_multi_eval_safe())
13048 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
13049 inserter->insert(ts);
13050 arg = Expression::make_temporary_reference(ts, loc);
13052 // arg == 0 ? 32 : __builtin_clz(arg)
13053 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
13054 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
13055 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
13056 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CLZ,
13057 loc, 1, arg->copy());
13058 call = Expression::make_cast(int_type, call, loc);
13059 Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
13060 // len = 32 - clz
13061 if (name == "Len32" || name == "Len")
13062 return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
13063 return cond;
13065 else if ((name == "LeadingZeros64" || name == "Len64"
13066 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
13067 && this->args_ != NULL && this->args_->size() == 1)
13069 Expression* arg = this->args_->front();
13070 if (!arg->is_multi_eval_safe())
13072 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
13073 inserter->insert(ts);
13074 arg = Expression::make_temporary_reference(ts, loc);
13076 // arg == 0 ? 64 : __builtin_clzll(arg)
13077 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
13078 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
13079 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
13080 Expression* call = Runtime::make_call(gogo, Runtime::BUILTIN_CLZLL,
13081 loc, 1, arg->copy());
13082 call = Expression::make_cast(int_type, call, loc);
13083 Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
13084 // len = 64 - clz
13085 if (name == "Len64" || name == "Len")
13086 return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
13087 return cond;
13089 else if ((name == "OnesCount8" || name == "OnesCount16"
13090 || name == "OnesCount32" || name == "OnesCount64"
13091 || name == "OnesCount")
13092 && this->args_ != NULL && this->args_->size() == 1)
13094 Runtime::Function code;
13095 if (name == "OnesCount64")
13096 code = Runtime::BUILTIN_POPCOUNTLL;
13097 else if (name == "OnesCount")
13098 code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
13099 else
13100 code = Runtime::BUILTIN_POPCOUNT;
13101 Expression* arg = this->args_->front();
13102 Expression* call = Runtime::make_call(gogo, code, loc, 1, arg);
13103 return Expression::make_cast(int_type, call, loc);
13106 else if (package == "runtime/internal/atomic")
13108 int memorder = __ATOMIC_SEQ_CST;
13110 if (is_method)
13112 Function_type* ftype = (no->is_function()
13113 ? no->func_value()->type()
13114 : no->func_declaration_value()->type());
13115 Type* rtype = ftype->receiver()->type()->deref();
13116 go_assert(rtype->named_type() != NULL);
13117 const std::string& rname(rtype->named_type()->name());
13118 if (rname == "Int32")
13120 if (name == "Load")
13121 name = "LoadInt32";
13122 else if (name == "Store")
13123 name = "Storeint32";
13124 else if (name == "CompareAndSwap")
13125 name = "Casint32";
13126 else if (name == "Swap")
13127 name = "Xchgint32";
13128 else if (name == "Add")
13129 name = "Xaddint32";
13130 else
13131 go_unreachable();
13133 else if (rname == "Int64")
13135 if (name == "Load")
13136 name = "LoadInt64";
13137 else if (name == "Store")
13138 name = "Storeint64";
13139 else if (name == "CompareAndSwap")
13140 name = "Casint64";
13141 else if (name == "Swap")
13142 name = "Xchgint64";
13143 else if (name == "Add")
13144 name = "Xaddint64";
13145 else
13146 go_unreachable();
13148 else if (rname == "Uint8")
13150 if (name == "Load")
13151 name = "Load8";
13152 else if (name == "Store")
13153 name = "Store8";
13154 else if (name == "And")
13155 name = "And8";
13156 else if (name == "Or")
13157 name = "Or8";
13158 else
13159 go_unreachable();
13161 else if (rname == "Uint32")
13163 if (name == "Load")
13164 name = "Load";
13165 else if (name == "LoadAcquire")
13166 name = "LoadAcq";
13167 else if (name == "Store")
13168 name = "Store";
13169 else if (name == "CompareAndSwap")
13170 name = "Cas";
13171 else if (name == "CompareAndSwapRelease")
13172 name = "CasRel";
13173 else if (name == "Swap")
13174 name = "Xchg";
13175 else if (name == "And")
13176 name = "And";
13177 else if (name == "Or")
13178 name = "Or";
13179 else if (name == "Add")
13180 name = "Xadd";
13181 else
13182 go_unreachable();
13184 else if (rname == "Uint64")
13186 if (name == "Load")
13187 name = "Load64";
13188 else if (name == "Store")
13189 name = "Store64";
13190 else if (name == "CompareAndSwap")
13191 name = "Cas64";
13192 else if (name == "Swap")
13193 name = "Xchgt64";
13194 else if (name == "Add")
13195 name = "Xadd64";
13196 else
13197 go_unreachable();
13199 else if (rname == "Uintptr")
13201 if (name == "Load")
13202 name = "Loaduintptr";
13203 else if (name == "LoadAcquire")
13204 name = "Loadacquintptr";
13205 else if (name == "Store")
13206 name = "Storeuintptr";
13207 else if (name == "StoreRelease")
13208 name = "StoreReluintptr";
13209 else if (name == "CompareAndSwap")
13210 name = "Casuintptr";
13211 else if (name == "Swap")
13212 name = "Xchguintptr";
13213 else if (name == "Add")
13214 name = "Xadduintptr";
13215 else
13216 go_unreachable();
13218 else if (rname == "Float64")
13220 // Needs unsafe type conversion. Don't intrinsify for now.
13221 return NULL;
13223 else if (rname == "UnsafePointer")
13225 if (name == "Load")
13226 name = "Loadp";
13227 else if (name == "StoreNoWB")
13228 name = "StorepoWB";
13229 else if (name == "CompareAndSwapNoWB")
13230 name = "Casp1";
13231 else
13232 go_unreachable();
13234 else
13235 go_unreachable();
13238 if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
13239 || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
13240 || name == "Loadint32" || name == "Load8")
13241 && this->args_ != NULL && this->args_->size() == 1)
13243 if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
13244 // On 32-bit architectures we need to check alignment.
13245 // Not intrinsify for now.
13246 return NULL;
13248 Runtime::Function code;
13249 Type* res_type;
13250 if (name == "Load")
13252 code = Runtime::ATOMIC_LOAD_4;
13253 res_type = uint32_type;
13255 else if (name == "Load64")
13257 code = Runtime::ATOMIC_LOAD_8;
13258 res_type = uint64_type;
13260 else if (name == "Loadint32")
13262 code = Runtime::ATOMIC_LOAD_4;
13263 res_type = int32_type;
13265 else if (name == "Loadint64")
13267 code = Runtime::ATOMIC_LOAD_8;
13268 res_type = int64_type;
13270 else if (name == "Loaduint")
13272 code = (int_size == 8
13273 ? Runtime::ATOMIC_LOAD_8
13274 : Runtime::ATOMIC_LOAD_4);
13275 res_type = uint_type;
13277 else if (name == "Loaduintptr")
13279 code = (ptr_size == 8
13280 ? Runtime::ATOMIC_LOAD_8
13281 : Runtime::ATOMIC_LOAD_4);
13282 res_type = uintptr_type;
13284 else if (name == "Loadp")
13286 code = (ptr_size == 8
13287 ? Runtime::ATOMIC_LOAD_8
13288 : Runtime::ATOMIC_LOAD_4);
13289 res_type = pointer_type;
13291 else if (name == "LoadAcq")
13293 code = Runtime::ATOMIC_LOAD_4;
13294 res_type = uint32_type;
13295 memorder = __ATOMIC_ACQUIRE;
13297 else if (name == "Load8")
13299 code = Runtime::ATOMIC_LOAD_1;
13300 res_type = uint8_type;
13302 else
13303 go_unreachable();
13304 Expression* a1 = this->args_->front();
13305 Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
13306 Expression* call = Runtime::make_call(gogo, code, loc, 2, a1, a2);
13307 return Expression::make_unsafe_cast(res_type, call, loc);
13310 if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
13311 || name == "Storeuintptr" || name == "StoreRel"
13312 || name == "Storeint32" || name == "Storeint64")
13313 && this->args_ != NULL && this->args_->size() == 2)
13315 if (int_size < 8 && (name == "Store64" || name == "Storeint64"))
13316 return NULL;
13318 Runtime::Function code;
13319 Expression* a1 = this->args_->at(0);
13320 Expression* a2 = this->args_->at(1);
13321 if (name == "Store")
13322 code = Runtime::ATOMIC_STORE_4;
13323 else if (name == "Store64")
13324 code = Runtime::ATOMIC_STORE_8;
13325 else if (name == "Storeint32")
13326 code = Runtime::ATOMIC_STORE_4;
13327 else if (name == "Storeint64")
13328 code = Runtime::ATOMIC_STORE_8;
13329 else if (name == "Storeuintptr")
13330 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
13331 else if (name == "StorepNoWB")
13333 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
13334 a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
13335 a2 = Expression::make_cast(uint64_type, a2, loc);
13337 else if (name == "StoreRel")
13339 code = Runtime::ATOMIC_STORE_4;
13340 memorder = __ATOMIC_RELEASE;
13342 else if (name == "Store8")
13343 code = Runtime::ATOMIC_STORE_1;
13344 else
13345 go_unreachable();
13346 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
13347 return Runtime::make_call(gogo, code, loc, 3, a1, a2, a3);
13350 if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
13351 || name == "Xchgint32" || name == "Xchgint64")
13352 && this->args_ != NULL && this->args_->size() == 2)
13354 if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
13355 return NULL;
13357 Runtime::Function code;
13358 Type* res_type;
13359 if (name == "Xchg")
13361 code = Runtime::ATOMIC_EXCHANGE_4;
13362 res_type = uint32_type;
13364 else if (name == "Xchg64")
13366 code = Runtime::ATOMIC_EXCHANGE_8;
13367 res_type = uint64_type;
13369 else if (name == "Xchgint32")
13371 code = Runtime::ATOMIC_EXCHANGE_4;
13372 res_type = int32_type;
13374 else if (name == "Xchgint64")
13376 code = Runtime::ATOMIC_EXCHANGE_8;
13377 res_type = int64_type;
13379 else if (name == "Xchguintptr")
13381 code = (ptr_size == 8
13382 ? Runtime::ATOMIC_EXCHANGE_8
13383 : Runtime::ATOMIC_EXCHANGE_4);
13384 res_type = uintptr_type;
13386 else
13387 go_unreachable();
13388 Expression* a1 = this->args_->at(0);
13389 Expression* a2 = this->args_->at(1);
13390 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
13391 Expression* call = Runtime::make_call(gogo, code, loc, 3, a1, a2, a3);
13392 return Expression::make_cast(res_type, call, loc);
13395 if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
13396 || name == "Casp1" || name == "CasRel"
13397 || name == "Casint32" || name == "Casint64")
13398 && this->args_ != NULL && this->args_->size() == 3)
13400 if (int_size < 8 && (name == "Cas64" || name == "Casint64"))
13401 return NULL;
13403 Runtime::Function code;
13404 Expression* a1 = this->args_->at(0);
13406 // Builtin cas takes a pointer to the old value.
13407 // Store it in a temporary and take the address.
13408 Expression* a2 = this->args_->at(1);
13409 Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
13410 inserter->insert(ts);
13411 a2 = Expression::make_temporary_reference(ts, loc);
13412 a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
13414 Expression* a3 = this->args_->at(2);
13415 if (name == "Cas")
13416 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
13417 else if (name == "Cas64")
13418 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
13419 else if (name == "Casint32")
13420 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
13421 else if (name == "Casint64")
13422 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
13423 else if (name == "Casuintptr")
13424 code = (ptr_size == 8
13425 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
13426 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
13427 else if (name == "Casp1")
13429 code = (ptr_size == 8
13430 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
13431 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
13432 a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
13433 a3 = Expression::make_cast(uint64_type, a3, loc);
13435 else if (name == "CasRel")
13437 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
13438 memorder = __ATOMIC_RELEASE;
13440 else
13441 go_unreachable();
13442 Expression* a4 = Expression::make_boolean(false, loc);
13443 Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
13444 Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
13445 return Runtime::make_call(gogo, code, loc, 6, a1, a2, a3, a4, a5, a6);
13448 if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
13449 || name == "Xadduintptr" || name == "Xaddint32")
13450 && this->args_ != NULL && this->args_->size() == 2)
13452 if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
13453 return NULL;
13455 Runtime::Function code;
13456 Type* res_type;
13457 if (name == "Xadd")
13459 code = Runtime::ATOMIC_ADD_FETCH_4;
13460 res_type = uint32_type;
13462 else if (name == "Xadd64")
13464 code = Runtime::ATOMIC_ADD_FETCH_8;
13465 res_type = uint64_type;
13467 else if (name == "Xaddint32")
13469 code = Runtime::ATOMIC_ADD_FETCH_4;
13470 res_type = int32_type;
13472 else if (name == "Xaddint64")
13474 code = Runtime::ATOMIC_ADD_FETCH_8;
13475 res_type = int64_type;
13477 else if (name == "Xadduintptr")
13479 code = (ptr_size == 8
13480 ? Runtime::ATOMIC_ADD_FETCH_8
13481 : Runtime::ATOMIC_ADD_FETCH_4);
13482 res_type = uintptr_type;
13484 else
13485 go_unreachable();
13486 Expression* a1 = this->args_->at(0);
13487 Expression* a2 = this->args_->at(1);
13488 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
13489 Expression* call = Runtime::make_call(gogo, code, loc, 3, a1, a2, a3);
13490 return Expression::make_cast(res_type, call, loc);
13493 if ((name == "And8" || name == "Or8")
13494 && this->args_ != NULL && this->args_->size() == 2)
13496 Runtime::Function code;
13497 if (name == "And8")
13498 code = Runtime::ATOMIC_AND_FETCH_1;
13499 else if (name == "Or8")
13500 code = Runtime::ATOMIC_OR_FETCH_1;
13501 else
13502 go_unreachable();
13503 Expression* a1 = this->args_->at(0);
13504 Expression* a2 = this->args_->at(1);
13505 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
13506 return Runtime::make_call(gogo, code, loc, 3, a1, a2, a3);
13509 else if (package == "internal/abi"
13510 || package == "bootstrap/internal/abi") // for bootstrapping gc
13512 if (is_method)
13513 return NULL;
13515 if ((name == "FuncPCABI0" || name == "FuncPCABIInternal")
13516 && this->args_ != NULL
13517 && this->args_->size() == 1)
13519 // We expect to see a conversion from the expression to "any".
13520 Expression* expr = this->args_->front();
13521 Type_conversion_expression* tce = expr->conversion_expression();
13522 if (tce != NULL)
13523 expr = tce->expr();
13524 Func_expression* fe = expr->func_expression();
13525 Interface_field_reference_expression* interface_method =
13526 expr->interface_field_reference_expression();
13527 if (fe != NULL)
13529 Named_object* no = fe->named_object();
13530 Expression* ref = Expression::make_func_code_reference(no, loc);
13531 Type* uintptr_type = Type::lookup_integer_type("uintptr");
13532 return Expression::make_cast(uintptr_type, ref, loc);
13534 else if (interface_method != NULL)
13535 return interface_method->get_function();
13536 else
13538 expr = this->args_->front();
13539 go_assert(expr->type()->interface_type() != NULL
13540 && expr->type()->interface_type()->is_empty());
13541 expr = Expression::make_interface_info(expr,
13542 INTERFACE_INFO_OBJECT,
13543 loc);
13544 // Trust that this is a function type, which means that
13545 // it is a direct iface type and we can use EXPR
13546 // directly. The backend representation of this
13547 // function is a pointer to a struct whose first field
13548 // is the actual function to call.
13549 Type* pvoid = Type::make_pointer_type(Type::make_void_type());
13550 Type* pfntype = Type::make_pointer_type(pvoid);
13551 Expression* ref = make_unsafe_cast(pfntype, expr, loc);
13552 return Expression::make_dereference(ref, NIL_CHECK_NOT_NEEDED,
13553 loc);
13558 return NULL;
13561 // Make implicit type conversions explicit.
13563 void
13564 Call_expression::do_add_conversions()
13566 // Skip call that requires a thunk. We generate conversions inside the thunk.
13567 if (this->is_concurrent_ || this->is_deferred_)
13568 return;
13570 if (this->args_ == NULL || this->args_->empty())
13571 return;
13573 Function_type* fntype = this->get_function_type();
13574 if (fntype == NULL)
13576 go_assert(saw_errors());
13577 return;
13579 if (fntype->parameters() == NULL || fntype->parameters()->empty())
13580 return;
13582 Location loc = this->location();
13583 Expression_list::iterator pa = this->args_->begin();
13584 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
13585 bool is_interface_method =
13586 this->fn_->interface_field_reference_expression() != NULL;
13587 size_t argcount = this->args_->size();
13588 if (!is_interface_method && fntype->is_method())
13590 // Skip the receiver argument, which cannot be interface.
13591 pa++;
13592 argcount--;
13594 if (argcount != fntype->parameters()->size())
13596 go_assert(saw_errors());
13597 return;
13599 for (; pa != this->args_->end(); ++pa, ++pp)
13601 Type* pt = pp->type();
13602 if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
13603 && pt->interface_type() != NULL)
13604 *pa = Expression::make_cast(pt, *pa, loc);
13608 // Get the function type. This can return NULL in error cases.
13610 Function_type*
13611 Call_expression::get_function_type() const
13613 return this->fn_->type()->function_type();
13616 // Return the number of values which this call will return.
13618 size_t
13619 Call_expression::result_count() const
13621 const Function_type* fntype = this->get_function_type();
13622 if (fntype == NULL)
13623 return 0;
13624 if (fntype->results() == NULL)
13625 return 0;
13626 return fntype->results()->size();
13629 // Return the temporary that holds the result for a call with multiple
13630 // results.
13632 Temporary_statement*
13633 Call_expression::results() const
13635 if (this->call_temp_ == NULL)
13637 go_assert(saw_errors());
13638 return NULL;
13640 return this->call_temp_;
13643 // Set the number of results expected from a call expression.
13645 void
13646 Call_expression::set_expected_result_count(size_t count)
13648 go_assert(this->expected_result_count_ == 0);
13649 go_assert(!this->types_are_determined_);
13650 this->expected_result_count_ = count;
13653 // Return whether this is a call to the predeclared function recover.
13655 bool
13656 Call_expression::is_recover_call() const
13658 return this->do_is_recover_call();
13661 // Set the argument to the recover function.
13663 void
13664 Call_expression::set_recover_arg(Expression* arg)
13666 this->do_set_recover_arg(arg);
13669 // Virtual functions also implemented by Builtin_call_expression.
13671 bool
13672 Call_expression::do_is_recover_call() const
13674 return false;
13677 void
13678 Call_expression::do_set_recover_arg(Expression*)
13680 go_unreachable();
13683 // We have found an error with this call expression; return true if
13684 // we should report it.
13686 bool
13687 Call_expression::issue_error()
13689 if (this->issued_error_)
13690 return false;
13691 else
13693 this->issued_error_ = true;
13694 return true;
13698 // Whether or not this call contains errors, either in the call or the
13699 // arguments to the call.
13701 bool
13702 Call_expression::is_erroneous_call()
13704 if (this->is_error_expression() || this->fn()->is_error_expression())
13705 return true;
13707 if (this->args() == NULL)
13708 return false;
13709 for (Expression_list::iterator pa = this->args()->begin();
13710 pa != this->args()->end();
13711 ++pa)
13713 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
13714 return true;
13716 return false;
13719 // Get the type.
13721 Type*
13722 Call_expression::do_type()
13724 if (this->is_error_expression())
13725 return Type::make_error_type();
13726 if (this->lowered_ != NULL)
13727 return this->lowered_->type();
13728 go_assert(this->type_ != NULL);
13729 return this->type_;
13732 // Determine types for a call expression. We can use the function
13733 // parameter types to set the types of the arguments. We simplify
13734 // some of the call cases here, storing the result in the lowered_
13735 // field.
13737 void
13738 Call_expression::do_determine_type(Gogo* gogo, const Type_context* context)
13740 if (!this->determining_types())
13741 return;
13743 if (this->lowered_== NULL)
13745 Expression* builtin = this->lower_builtin(gogo);
13746 if (builtin != this)
13747 this->lowered_ = builtin;
13750 if (this->lowered_ != NULL)
13752 this->lowered_->determine_type(gogo, context);
13753 return;
13756 this->fn_->determine_type_no_context(gogo);
13758 // Simplify a type conversion.
13760 if (this->fn_->is_type_expression()
13761 && this->args_ != NULL
13762 && this->args_->size() == 1
13763 && (this->expected_result_count_ == 0
13764 || this->expected_result_count_ == 1))
13766 this->lowered_ = Expression::make_cast(this->fn_->type(),
13767 this->args_->front(),
13768 this->location());
13769 this->lowered_->determine_type(gogo, context);
13770 return;
13773 // Get the type of the function we are calling.
13775 Function_type* fntype = this->get_function_type();
13776 if (fntype == NULL)
13778 // We report the error here so that we can reasonably return an
13779 // error type in do_type.
13780 if (!this->fn_->type()->is_error())
13781 this->report_error(_("expected function"));
13782 else
13783 this->set_is_error();
13784 if (this->args_ != NULL)
13786 for (Expression_list::iterator p = this->args_->begin();
13787 p != this->args_->end();
13788 ++p)
13789 (*p)->determine_type_no_context(gogo);
13791 return;
13794 // Simplify f(g()) where g() returns multiple results.
13796 this->simplify_multiple_results(gogo);
13798 // Set the type of this expression.
13800 go_assert(this->type_ == NULL);
13801 const Typed_identifier_list* results = fntype->results();
13802 if (results == NULL || results->empty())
13803 this->type_ = Type::make_void_type();
13804 else if (results->size() == 1)
13806 // If this is a call to a generated equality function, we
13807 // determine the type based on the context. See the comment in
13808 // Binary_expression::lower_array_comparison.
13809 if (this->is_equal_function_
13810 && !context->may_be_abstract
13811 && context->type != NULL
13812 && context->type->is_boolean_type())
13813 this->type_ = context->type;
13814 else
13815 this->type_ = results->begin()->type();
13817 else
13818 this->type_ = Type::make_call_multiple_result_type();
13820 // Determine the types of the arguments.
13822 if (this->args_ == NULL)
13824 if (fntype->is_varargs())
13826 if (!this->rewrite_varargs())
13827 this->set_is_error();
13829 return;
13832 const Typed_identifier_list* parameters = fntype->parameters();
13833 Typed_identifier_list::const_iterator pt;
13834 if (parameters != NULL)
13835 pt = parameters->begin();
13836 bool first = true;
13837 for (Expression_list::const_iterator pa = this->args_->begin();
13838 pa != this->args_->end();
13839 ++pa)
13841 if (first)
13843 first = false;
13844 // If this is a method, the first argument is the
13845 // receiver.
13846 if (fntype != NULL && fntype->is_method())
13848 Type* rtype = fntype->receiver()->type();
13849 // The receiver is always passed as a pointer.
13850 if (rtype->points_to() == NULL)
13851 rtype = Type::make_pointer_type(rtype);
13852 Type_context subcontext(rtype, false);
13853 (*pa)->determine_type(gogo, &subcontext);
13854 continue;
13858 if ((this->is_varargs_ || this->varargs_are_lowered_)
13859 && fntype->is_varargs()
13860 && pa + 1 == this->args_->end()
13861 && parameters != NULL
13862 && pt + 1 == parameters->end())
13864 Type_context subcontext(pt->type(), false);
13865 (*pa)->determine_type(gogo, &subcontext);
13866 continue;
13869 if (!this->is_varargs_
13870 && fntype->is_varargs()
13871 && parameters != NULL
13872 && pt + 1 == parameters->end())
13874 go_assert(pt->type()->is_slice_type());
13875 Type_context subcontext(pt->type()->array_type()->element_type(),
13876 false);
13877 (*pa)->determine_type(gogo, &subcontext);
13878 continue;
13881 if (parameters != NULL && pt != parameters->end())
13883 Type_context subcontext(pt->type(), false);
13884 (*pa)->determine_type(gogo, &subcontext);
13885 if (!fntype->is_varargs() || pt + 1 != parameters->end())
13886 ++pt;
13888 else
13889 (*pa)->determine_type_no_context(gogo);
13892 if (fntype->is_varargs())
13894 if (!this->rewrite_varargs())
13895 this->set_is_error();
13899 // Called when determining types for a Call_expression. Return true
13900 // if we should go ahead, false if they have already been determined.
13902 bool
13903 Call_expression::determining_types()
13905 if (this->types_are_determined_)
13906 return false;
13907 else
13909 this->types_are_determined_ = true;
13910 return true;
13914 // Simplify f(g()) where g() returns multiple results. Called by
13915 // do_determine_types of both Call_expression and
13916 // Builtin_call_expression.
13918 void
13919 Call_expression::simplify_multiple_results(Gogo* gogo)
13921 if (this->args_ == NULL || this->args_->size() != 1)
13922 return;
13924 Call_expression* call = this->args_->front()->call_expression();
13925 if (call == NULL || call->is_builtin())
13926 return;
13928 call->determine_type_no_context(gogo);
13929 size_t rc = call->result_count();
13930 Function_type* fntype = this->get_function_type();
13931 if (rc > 1
13932 && ((fntype->parameters() != NULL
13933 && (fntype->parameters()->size() == rc
13934 || (fntype->is_varargs()
13935 && fntype->parameters()->size() - 1 <= rc)))
13936 || fntype->is_builtin()))
13938 if (this->is_varargs_)
13940 go_error_at(call->location(),
13941 "multiple-value argument in single-value context");
13942 this->set_is_error();
13945 call->set_is_multi_value_arg();
13946 Expression_list* args = new Expression_list;
13947 for (size_t i = 0; i < rc; ++i)
13948 args->push_back(Expression::make_call_result(call, i));
13949 // We can't create a new Call_expression here because this
13950 // one may be referred to by Call_result expressions.
13951 this->args_ = args;
13955 // Lower a call to a varargs function by rewriting the value(s) passed
13956 // to the varargs argument into a slice. Called during the
13957 // determine_types pass.
13959 bool
13960 Call_expression::rewrite_varargs()
13962 if (this->varargs_are_lowered_)
13963 return true;
13964 this->varargs_are_lowered_ = true;
13966 Function_type* fntype = this->get_function_type();
13968 const Typed_identifier_list* parameters = fntype->parameters();
13969 go_assert(parameters != NULL && !parameters->empty());
13970 size_t param_count = parameters->size();
13972 Type* varargs_type = parameters->back().type();
13973 go_assert(varargs_type->is_slice_type());
13975 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
13976 if (arg_count < param_count - 1)
13978 if (!this->is_error_expression())
13979 this->report_error(_("not enough arguments"));
13980 return false;
13983 bool ret = true;
13984 Expression_list* old_args = this->args_;
13985 Expression_list* new_args = new Expression_list();
13986 bool push_empty_arg = false;
13987 if (old_args == NULL || old_args->empty())
13989 go_assert(param_count == 1);
13990 push_empty_arg = true;
13992 else
13994 Expression_list::const_iterator pa;
13995 size_t i = 1;
13996 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
13998 if (i == param_count)
13999 break;
14000 new_args->push_back(*pa);
14003 // We have reached the varargs parameter.
14005 if (pa == old_args->end())
14006 push_empty_arg = true;
14007 else if (pa + 1 == old_args->end() && this->is_varargs_)
14008 new_args->push_back(*pa);
14009 else if (this->is_varargs_)
14011 if (!this->is_error_expression())
14013 if ((*pa)->type()->is_slice_type())
14014 this->report_error(_("too many arguments"));
14015 else
14017 go_error_at(this->location(),
14018 "invalid use of %<...%> with non-slice");
14019 this->set_is_error();
14022 return false;
14024 else
14026 Type* element_type = varargs_type->array_type()->element_type();
14027 Expression_list* vals = new Expression_list;
14028 for (; pa != old_args->end(); ++pa, ++i)
14030 Type* patype = (*pa)->type();
14031 Location paloc = (*pa)->location();
14032 if (!this->check_argument_type(i, element_type, patype, paloc))
14034 ret = false;
14035 continue;
14037 vals->push_back(*pa);
14039 Expression* val =
14040 Expression::make_slice_composite_literal(varargs_type, vals,
14041 this->location());
14042 new_args->push_back(val);
14046 if (push_empty_arg)
14047 new_args->push_back(Expression::make_nil(this->location()));
14049 // We can't create a new Call_expression here because this
14050 // one may be referred to by Call_result expressions.
14051 this->args_ = new_args;
14053 return ret;
14056 // Check types for parameter I.
14058 bool
14059 Call_expression::check_argument_type(int i, const Type* parameter_type,
14060 const Type* argument_type,
14061 Location argument_location)
14063 std::string reason;
14064 if (!Type::are_assignable(parameter_type, argument_type, &reason))
14066 if (reason.empty())
14067 go_error_at(argument_location, "argument %d has incompatible type", i);
14068 else
14069 go_error_at(argument_location,
14070 "argument %d has incompatible type (%s)",
14071 i, reason.c_str());
14072 this->set_is_error();
14073 return false;
14075 return true;
14078 // Check types.
14080 void
14081 Call_expression::do_check_types(Gogo*)
14083 if (this->is_error_expression()
14084 || this->fn_->is_error_expression()
14085 || this->fn_->type()->is_error())
14086 return;
14087 if (this->lowered_ != NULL)
14088 return;
14090 Function_type* fntype = this->get_function_type();
14091 go_assert(fntype != NULL);
14093 if (this->expected_result_count_ != 0
14094 && this->expected_result_count_ != this->result_count())
14096 if (this->issue_error())
14097 this->report_error(_("function result count mismatch"));
14098 this->set_is_error();
14099 return;
14102 if (this->is_varargs_ && !fntype->is_varargs())
14104 go_error_at(this->location(),
14105 "invalid use of %<...%> calling non-variadic function");
14106 this->set_is_error();
14107 return;
14110 bool is_method = fntype->is_method();
14111 if (is_method)
14113 go_assert(this->args_ != NULL && !this->args_->empty());
14114 Type* rtype = fntype->receiver()->type();
14115 Expression* first_arg = this->args_->front();
14116 // We dereference the values since receivers are always passed
14117 // as pointers.
14118 std::string reason;
14119 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
14120 &reason))
14122 if (reason.empty())
14123 this->report_error(_("incompatible type for receiver"));
14124 else
14126 go_error_at(this->location(),
14127 "incompatible type for receiver (%s)",
14128 reason.c_str());
14129 this->set_is_error();
14134 const Typed_identifier_list* parameters = fntype->parameters();
14135 if (this->args_ == NULL || this->args_->empty())
14137 if (parameters != NULL && !parameters->empty())
14138 this->report_error(_("not enough arguments"));
14140 else if (parameters == NULL)
14142 if (!is_method || this->args_->size() > 1)
14143 this->report_error(_("too many arguments"));
14145 else if (this->args_->size() == 1
14146 && this->args_->front()->call_expression() != NULL
14147 && this->args_->front()->call_expression()->result_count() > 1)
14149 // This is F(G()) when G returns more than one result. If the
14150 // results can be matched to parameters, it would have been
14151 // rewritten in determine_types. If we get here we know there
14152 // is a mismatch.
14153 if (this->args_->front()->call_expression()->result_count()
14154 < parameters->size())
14155 this->report_error(_("not enough arguments"));
14156 else
14157 this->report_error(_("too many arguments"));
14159 else
14161 int i = 0;
14162 Expression_list::const_iterator pa = this->args_->begin();
14163 if (is_method)
14164 ++pa;
14165 for (Typed_identifier_list::const_iterator pt = parameters->begin();
14166 pt != parameters->end();
14167 ++pt, ++pa, ++i)
14169 if (pa == this->args_->end())
14171 this->report_error(_("not enough arguments"));
14172 return;
14174 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
14175 (*pa)->location());
14177 if (pa != this->args_->end())
14178 this->report_error(_("too many arguments"));
14182 Expression*
14183 Call_expression::do_copy()
14185 Call_expression* call =
14186 Expression::make_call(this->fn_->copy(),
14187 (this->args_ == NULL
14188 ? NULL
14189 : this->args_->copy()),
14190 this->is_varargs_, this->location());
14192 if (this->varargs_are_lowered_)
14193 call->set_varargs_are_lowered();
14194 if (this->is_deferred_)
14195 call->set_is_deferred();
14196 if (this->is_concurrent_)
14197 call->set_is_concurrent();
14198 return call;
14201 // Return whether we have to use a temporary variable to ensure that
14202 // we evaluate this call expression in order. If the call returns no
14203 // results then it will inevitably be executed last.
14205 bool
14206 Call_expression::do_must_eval_in_order() const
14208 return this->result_count() > 0;
14211 // Get the function and the first argument to use when calling an
14212 // interface method.
14214 Expression*
14215 Call_expression::interface_method_function(
14216 Interface_field_reference_expression* interface_method,
14217 Expression** first_arg_ptr,
14218 Location location)
14220 Expression* object = interface_method->get_underlying_object();
14221 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
14222 *first_arg_ptr =
14223 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
14224 return interface_method->get_function();
14227 // Build the call expression.
14229 Bexpression*
14230 Call_expression::do_get_backend(Translate_context* context)
14232 Location location = this->location();
14234 if (this->call_ != NULL)
14236 // If the call returns multiple results, make a new reference to
14237 // the temporary.
14238 if (this->call_temp_ != NULL)
14240 Expression* ref =
14241 Expression::make_temporary_reference(this->call_temp_, location);
14242 return ref->get_backend(context);
14245 return this->call_;
14248 Function_type* fntype = this->get_function_type();
14249 if (fntype == NULL)
14250 return context->backend()->error_expression();
14252 if (this->fn_->is_error_expression())
14253 return context->backend()->error_expression();
14255 Gogo* gogo = context->gogo();
14257 Func_expression* func = this->fn_->func_expression();
14258 Interface_field_reference_expression* interface_method =
14259 this->fn_->interface_field_reference_expression();
14260 const bool has_closure = func != NULL && func->closure() != NULL;
14261 const bool is_interface_method = interface_method != NULL;
14263 bool has_closure_arg;
14264 if (has_closure)
14265 has_closure_arg = true;
14266 else if (func != NULL)
14267 has_closure_arg = false;
14268 else if (is_interface_method)
14269 has_closure_arg = false;
14270 else
14271 has_closure_arg = true;
14273 Expression* first_arg = NULL;
14274 if (!is_interface_method && fntype->is_method())
14276 first_arg = this->args_->front();
14277 if (first_arg->type()->points_to() == NULL
14278 && first_arg->type()->is_direct_iface_type())
14279 first_arg = Expression::unpack_direct_iface(first_arg,
14280 first_arg->location());
14283 int nargs;
14284 std::vector<Bexpression*> fn_args;
14285 if (this->args_ == NULL || this->args_->empty())
14287 nargs = is_interface_method ? 1 : 0;
14288 if (nargs > 0)
14289 fn_args.resize(1);
14291 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
14293 // Passing a receiver parameter.
14294 go_assert(!is_interface_method
14295 && fntype->is_method()
14296 && this->args_->size() == 1);
14297 nargs = 1;
14298 fn_args.resize(1);
14299 fn_args[0] = first_arg->get_backend(context);
14301 else
14303 const Typed_identifier_list* params = fntype->parameters();
14305 nargs = this->args_->size();
14306 int i = is_interface_method ? 1 : 0;
14307 nargs += i;
14308 fn_args.resize(nargs);
14310 Typed_identifier_list::const_iterator pp = params->begin();
14311 Expression_list::const_iterator pe = this->args_->begin();
14312 if (!is_interface_method && fntype->is_method())
14314 fn_args[i] = first_arg->get_backend(context);
14315 ++pe;
14316 ++i;
14318 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
14320 go_assert(pp != params->end());
14321 Expression* arg =
14322 Expression::convert_for_assignment(gogo, pp->type(), *pe,
14323 location);
14324 fn_args[i] = arg->get_backend(context);
14326 go_assert(pp == params->end());
14327 go_assert(i == nargs);
14330 Expression* fn;
14331 Expression* closure = NULL;
14332 if (func != NULL)
14334 Named_object* no = func->named_object();
14335 fn = Expression::make_func_code_reference(no, location);
14336 if (has_closure)
14337 closure = func->closure();
14339 else if (!is_interface_method)
14341 closure = this->fn_;
14343 // The backend representation of this function type is a pointer
14344 // to a struct whose first field is the actual function to call.
14345 Type* pfntype =
14346 Type::make_pointer_type(
14347 Type::make_pointer_type(Type::make_void_type()));
14348 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
14349 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
14351 else
14353 Expression* arg0;
14354 fn = this->interface_method_function(interface_method, &arg0,
14355 location);
14356 fn_args[0] = arg0->get_backend(context);
14359 Bexpression* bclosure = NULL;
14360 if (has_closure_arg)
14361 bclosure = closure->get_backend(context);
14362 else
14363 go_assert(closure == NULL);
14365 Bexpression* bfn = fn->get_backend(context);
14367 // When not calling a named function directly, use a type conversion
14368 // in case the type of the function is a recursive type which refers
14369 // to itself. We don't do this for an interface method because 1)
14370 // an interface method never refers to itself, so we always have a
14371 // function type here; 2) we pass an extra first argument to an
14372 // interface method, so fntype is not correct.
14373 if (func == NULL && !is_interface_method)
14375 Btype* bft = fntype->get_backend_fntype(gogo);
14376 bfn = gogo->backend()->convert_expression(bft, bfn, location);
14379 Bfunction* bfunction = NULL;
14380 if (context->function())
14381 bfunction = context->function()->func_value()->get_decl();
14382 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
14383 fn_args, bclosure,
14384 location);
14386 if (this->call_temp_ != NULL)
14388 // This case occurs when the call returns multiple results.
14390 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
14391 location);
14392 Bexpression* bref = ref->get_backend(context);
14393 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
14394 bref, call,
14395 location);
14397 ref = Expression::make_temporary_reference(this->call_temp_, location);
14398 this->call_ = ref->get_backend(context);
14400 return gogo->backend()->compound_expression(bassn, this->call_,
14401 location);
14404 this->call_ = call;
14405 return this->call_;
14408 // The cost of inlining a call expression.
14411 Call_expression::do_inlining_cost() const
14413 Func_expression* fn = this->fn_->func_expression();
14415 // FIXME: We don't yet support all kinds of calls.
14416 if (fn != NULL && fn->closure() != NULL)
14417 return 0x100000;
14418 if (this->fn_->interface_field_reference_expression())
14419 return 0x100000;
14420 if (this->get_function_type()->is_method())
14421 return 0x100000;
14423 return 5;
14426 // Export a call expression.
14428 void
14429 Call_expression::do_export(Export_function_body* efb) const
14431 bool simple_call = (this->fn_->func_expression() != NULL);
14432 if (!simple_call)
14433 efb->write_c_string("(");
14434 this->fn_->export_expression(efb);
14435 if (!simple_call)
14436 efb->write_c_string(")");
14437 this->export_arguments(efb);
14440 // Export call expression arguments.
14442 void
14443 Call_expression::export_arguments(Export_function_body* efb) const
14445 efb->write_c_string("(");
14446 if (this->args_ != NULL && !this->args_->empty())
14448 Expression_list::const_iterator pa = this->args_->begin();
14449 (*pa)->export_expression(efb);
14450 for (pa++; pa != this->args_->end(); pa++)
14452 efb->write_c_string(", ");
14453 (*pa)->export_expression(efb);
14455 if (this->is_varargs_)
14456 efb->write_c_string("...");
14458 efb->write_c_string(")");
14461 // Dump ast representation for a call expression.
14463 void
14464 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14466 this->fn_->dump_expression(ast_dump_context);
14467 ast_dump_context->ostream() << "(";
14468 if (args_ != NULL)
14469 ast_dump_context->dump_expression_list(this->args_);
14471 ast_dump_context->ostream() << ") ";
14474 // Make a call expression.
14476 Call_expression*
14477 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
14478 Location location)
14480 return new Call_expression(fn, args, is_varargs, location);
14483 // Class Call_result_expression.
14485 // Traverse a call result.
14488 Call_result_expression::do_traverse(Traverse* traverse)
14490 if (traverse->remember_expression(this->call_))
14492 // We have already traversed the call expression.
14493 return TRAVERSE_CONTINUE;
14495 return Expression::traverse(&this->call_, traverse);
14498 // Get the type.
14500 Type*
14501 Call_result_expression::do_type()
14503 if (this->classification() == EXPRESSION_ERROR)
14504 return Type::make_error_type();
14506 // THIS->CALL_ can be replaced with a temporary reference due to
14507 // Call_expression::do_must_eval_in_order when there is an error.
14508 Call_expression* ce = this->call_->call_expression();
14509 if (ce == NULL)
14511 this->set_is_error();
14512 return Type::make_error_type();
14514 Function_type* fntype = ce->get_function_type();
14515 if (fntype == NULL)
14517 if (ce->issue_error())
14519 if (!ce->fn()->type()->is_error())
14520 this->report_error(_("expected function"));
14522 this->set_is_error();
14523 return Type::make_error_type();
14525 const Typed_identifier_list* results = fntype->results();
14526 if (results == NULL || results->size() < 2)
14528 if (ce->issue_error())
14529 this->report_error(_("number of results does not match "
14530 "number of values"));
14531 return Type::make_error_type();
14533 Typed_identifier_list::const_iterator pr = results->begin();
14534 for (unsigned int i = 0; i < this->index_; ++i)
14536 if (pr == results->end())
14537 break;
14538 ++pr;
14540 if (pr == results->end())
14542 if (ce->issue_error())
14543 this->report_error(_("number of results does not match "
14544 "number of values"));
14545 return Type::make_error_type();
14547 return pr->type();
14550 // Check the type. Just make sure that we trigger the warning in
14551 // do_type.
14553 void
14554 Call_result_expression::do_check_types(Gogo*)
14556 this->type();
14559 // Determine the type. We have nothing to do here, but the 0 result
14560 // needs to pass down to the caller.
14562 void
14563 Call_result_expression::do_determine_type(Gogo* gogo, const Type_context*)
14565 this->call_->determine_type_no_context(gogo);
14568 // Return the backend representation. We just refer to the temporary set by the
14569 // call expression. We don't do this at lowering time because it makes it
14570 // hard to evaluate the call at the right time.
14572 Bexpression*
14573 Call_result_expression::do_get_backend(Translate_context* context)
14575 Call_expression* ce = this->call_->call_expression();
14576 if (ce == NULL)
14578 go_assert(this->call_->is_error_expression());
14579 return context->backend()->error_expression();
14581 Temporary_statement* ts = ce->results();
14582 if (ts == NULL)
14584 go_assert(saw_errors());
14585 return context->backend()->error_expression();
14587 Expression* ref = Expression::make_temporary_reference(ts, this->location());
14588 ref = Expression::make_field_reference(ref, this->index_, this->location());
14589 return ref->get_backend(context);
14592 // Dump ast representation for a call result expression.
14594 void
14595 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14596 const
14598 // FIXME: Wouldn't it be better if the call is assigned to a temporary
14599 // (struct) and the fields are referenced instead.
14600 ast_dump_context->ostream() << this->index_ << "@(";
14601 ast_dump_context->dump_expression(this->call_);
14602 ast_dump_context->ostream() << ")";
14605 // Make a reference to a single result of a call which returns
14606 // multiple results.
14608 Expression*
14609 Expression::make_call_result(Call_expression* call, unsigned int index)
14611 return new Call_result_expression(call, index);
14614 // Class Index_expression.
14616 // Report whether EXPR is a map index expression. This is called when
14617 // types are determined but before lowering.
14619 bool
14620 Index_expression::is_map_index(Expression* expr)
14622 if (expr->map_index_expression() != NULL)
14623 return true;
14624 if (expr->index_expression() != NULL)
14625 return expr->index_expression()->left_->type()->map_type() != NULL;
14626 return false;
14629 // Traversal.
14632 Index_expression::do_traverse(Traverse* traverse)
14634 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
14635 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
14636 || (this->end_ != NULL
14637 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
14638 || (this->cap_ != NULL
14639 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
14640 return TRAVERSE_EXIT;
14641 return TRAVERSE_CONTINUE;
14644 void
14645 Index_expression::do_determine_type(Gogo* gogo, const Type_context*)
14647 this->left_->determine_type_no_context(gogo);
14649 Type_context end_context;
14650 Type* type = this->left_->type();
14651 if (type->array_type() != NULL
14652 || (type->points_to() != NULL
14653 && type->points_to()->array_type() != NULL
14654 && !type->points_to()->is_slice_type())
14655 || type->is_string_type())
14657 Type_context index_context(Type::lookup_integer_type("int"), false);
14658 this->start_->determine_type(gogo, &index_context);
14659 end_context = index_context;
14661 else if (type->map_type() != NULL)
14663 Type_context key_context(type->map_type()->key_type(), false);
14664 this->start_->determine_type(gogo, &key_context);
14666 else if (type->is_error())
14667 this->set_is_error();
14668 else
14670 if (this->cap_ != NULL)
14671 this->report_error(_("invalid 3-index slice of object "
14672 "that is not a slice"));
14673 else if (this->end_ != NULL)
14674 this->report_error(_("attempt to slice object that is not "
14675 "array, slice, or string"));
14676 else
14677 this->report_error(_("attempt to index object that is not "
14678 "array, slice, string, or map"));
14680 this->start_->determine_type_no_context(gogo);
14683 if (this->end_ != NULL)
14684 this->end_->determine_type(gogo, &end_context);
14685 if (this->cap_ != NULL)
14686 this->cap_->determine_type(gogo, &end_context);
14689 Type*
14690 Index_expression::do_type()
14692 if (this->is_error_expression())
14693 return Type::make_error_type();
14695 Type* type = this->left_->type();
14696 if (this->end_ != NULL)
14698 // A slice of an array is a slice type. A slice of a slice or
14699 // string type is that same type.
14700 Array_type* at = type->deref()->array_type();
14701 if (at != NULL && !at->is_slice_type())
14702 return Type::make_array_type(at->element_type(), NULL);
14703 return type;
14705 if (type->deref()->array_type() != NULL)
14706 return type->deref()->array_type()->element_type();
14707 else if (type->is_string_type())
14708 return Type::lookup_integer_type("byte");
14709 else if (type->map_type() != NULL)
14710 return type->map_type()->val_type();
14711 else
14712 return Type::make_error_type();
14715 void
14716 Index_expression::do_check_types(Gogo*)
14718 if (this->is_error_expression())
14719 return;
14721 Type* ltype = this->left_->type();
14722 if (ltype->is_error())
14724 go_assert(saw_errors());
14725 return;
14728 if (this->left_->is_type_expression())
14730 this->report_error(_("attempt to index type expression"));
14731 return;
14734 if (ltype->array_type() != NULL)
14736 if (!Array_index_expression::check_indexes(this->left_, this->start_,
14737 this->end_, this->cap_,
14738 this->location()))
14739 this->set_is_error();
14741 else if (ltype->points_to() != NULL
14742 && ltype->points_to()->array_type() != NULL
14743 && !ltype->points_to()->is_slice_type())
14745 Expression* deref = Expression::make_dereference(this->left_,
14746 NIL_CHECK_DEFAULT,
14747 this->location());
14748 if (!Array_index_expression::check_indexes(deref, this->start_,
14749 this->end_, this->cap_,
14750 this->location()))
14751 this->set_is_error();
14752 delete deref;
14754 else if (ltype->is_string_type())
14756 if (this->cap_ != NULL)
14757 this->report_error(_("invalid 3-index slice of string"));
14758 else
14760 if (!String_index_expression::check_indexes(this->left_,
14761 this->start_,
14762 this->end_,
14763 this->location()))
14764 this->set_is_error();
14767 else if (ltype->map_type() != NULL)
14769 if (this->end_ != NULL || this->cap_ != NULL)
14770 this->report_error(_("invalid slice of map"));
14771 else
14773 Map_type* mt = ltype->map_type();
14774 std::string reason;
14775 if (!Type::are_assignable(mt->key_type(), this->start_->type(),
14776 &reason))
14778 if (reason.empty())
14779 this->report_error(_("incompatible type for map index"));
14780 else
14782 go_error_at(this->location(),
14783 "incompatible type for map index (%s)",
14784 reason.c_str());
14785 this->set_is_error();
14790 else
14791 go_unreachable();
14794 bool
14795 Index_expression::do_is_addressable() const
14797 if (this->is_error_expression())
14798 return true;
14800 Type* type = this->left_->type();
14801 if (type->is_error())
14802 return true;
14804 // A slice index is addressable, and an index of an addressable
14805 // array is addressable.
14807 bool is_pointer = false;
14808 if (type->points_to() != NULL
14809 && type->points_to()->array_type() != NULL
14810 && !type->points_to()->is_slice_type())
14812 type = type->points_to();
14813 is_pointer = true;
14816 if (type->array_type() == NULL)
14817 return false;
14819 if (this->end_ != NULL)
14820 return false;
14821 if (type->is_slice_type())
14822 return true;
14823 return is_pointer || this->left_->is_addressable();
14826 // We need to do a nil check of any pointer dereference.
14828 void
14829 Index_expression::do_issue_nil_check()
14831 this->left_->issue_nil_check();
14832 this->needs_nil_check_ = true;
14835 // Lower an index expression. This converts the generic index
14836 // expression into an array index, a string index, or a map index.
14838 Expression*
14839 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*)
14841 if (this->is_error_expression())
14842 return Expression::make_error(this->location());
14844 Location location = this->location();
14845 Expression* left = this->left_;
14846 Expression* start = this->start_;
14847 Expression* end = this->end_;
14848 Expression* cap = this->cap_;
14850 Type* type = left->type();
14851 if (type->is_error())
14853 go_assert(saw_errors());
14854 return Expression::make_error(location);
14856 else if (type->array_type() != NULL)
14857 return Expression::make_array_index(left, start, end, cap, location);
14858 else if (type->points_to() != NULL
14859 && type->points_to()->array_type() != NULL
14860 && !type->points_to()->is_slice_type())
14862 Expression* deref =
14863 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
14865 // For an ordinary index into the array, the pointer will be
14866 // dereferenced. For a slice it will not--the resulting slice
14867 // will simply reuse the pointer, which is incorrect if that
14868 // pointer is nil. We may also be in a context that requires a
14869 // nil check.
14870 if (end != NULL || cap != NULL || this->needs_nil_check_)
14871 deref->issue_nil_check();
14873 return Expression::make_array_index(deref, start, end, cap, location);
14875 else if (type->is_string_type())
14877 go_assert(cap == NULL);
14878 return Expression::make_string_index(left, start, end, location);
14880 else if (type->map_type() != NULL)
14882 go_assert(end == NULL && cap == NULL);
14883 return Expression::make_map_index(left, start, location);
14885 else
14886 go_unreachable();
14889 // Write an indexed expression
14890 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
14892 void
14893 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
14894 const Expression* expr,
14895 const Expression* start,
14896 const Expression* end,
14897 const Expression* cap)
14899 expr->dump_expression(ast_dump_context);
14900 ast_dump_context->ostream() << "[";
14901 start->dump_expression(ast_dump_context);
14902 if (end != NULL)
14904 ast_dump_context->ostream() << ":";
14905 end->dump_expression(ast_dump_context);
14907 if (cap != NULL)
14909 ast_dump_context->ostream() << ":";
14910 cap->dump_expression(ast_dump_context);
14912 ast_dump_context->ostream() << "]";
14915 // Dump ast representation for an index expression.
14917 void
14918 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14919 const
14921 Index_expression::dump_index_expression(ast_dump_context, this->left_,
14922 this->start_, this->end_, this->cap_);
14925 // Make an index expression.
14927 Expression*
14928 Expression::make_index(Expression* left, Expression* start, Expression* end,
14929 Expression* cap, Location location)
14931 return new Index_expression(left, start, end, cap, location);
14934 // Class Array_index_expression.
14936 // Array index traversal.
14939 Array_index_expression::do_traverse(Traverse* traverse)
14941 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
14942 return TRAVERSE_EXIT;
14943 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
14944 return TRAVERSE_EXIT;
14945 if (this->end_ != NULL)
14947 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
14948 return TRAVERSE_EXIT;
14950 if (this->cap_ != NULL)
14952 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14953 return TRAVERSE_EXIT;
14955 return TRAVERSE_CONTINUE;
14958 // Return the type of an array index.
14960 Type*
14961 Array_index_expression::do_type()
14963 if (this->type_ == NULL)
14965 Array_type* type = this->array_->type()->array_type();
14966 if (type == NULL)
14967 this->type_ = Type::make_error_type();
14968 else if (this->end_ == NULL)
14969 this->type_ = type->element_type();
14970 else if (type->is_slice_type())
14972 // A slice of a slice has the same type as the original
14973 // slice.
14974 this->type_ = this->array_->type()->deref();
14976 else
14978 // A slice of an array is a slice.
14979 this->type_ = Type::make_array_type(type->element_type(), NULL);
14982 return this->type_;
14985 // Set the type of an array index.
14987 void
14988 Array_index_expression::do_determine_type(Gogo* gogo, const Type_context*)
14990 this->array_->determine_type_no_context(gogo);
14992 Type_context index_context(Type::lookup_integer_type("int"), false);
14993 this->start_->determine_type(gogo, &index_context);
14994 if (this->end_ != NULL)
14995 this->end_->determine_type(gogo, &index_context);
14996 if (this->cap_ != NULL)
14997 this->cap_->determine_type(gogo, &index_context);
15000 // Check types of an array index.
15002 void
15003 Array_index_expression::do_check_types(Gogo*)
15005 if (!Array_index_expression::check_indexes(this->array_, this->start_,
15006 this->end_, this->cap_,
15007 this->location()))
15008 this->set_is_error();
15011 // A static function to check array index types. This is also called
15012 // by Index_expression::do_check_types. It reports whether type
15013 // checking succeeded.
15015 bool
15016 Array_index_expression::check_indexes(Expression* array, Expression* start,
15017 Expression* end, Expression* cap,
15018 Location loc)
15020 bool ret = true;
15022 Numeric_constant nc;
15023 unsigned long v;
15024 if (start->type()->integer_type() == NULL
15025 && !start->type()->is_error()
15026 && (!start->type()->is_abstract()
15027 || !start->numeric_constant_value(&nc)
15028 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
15030 go_error_at(loc, "index must be integer");
15031 ret = false;
15034 if (end != NULL
15035 && end->type()->integer_type() == NULL
15036 && !end->type()->is_error()
15037 && !end->is_nil_expression()
15038 && !end->is_error_expression()
15039 && (!end->type()->is_abstract()
15040 || !end->numeric_constant_value(&nc)
15041 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
15043 go_error_at(loc, "slice end must be integer");
15044 ret = false;
15047 if (cap != NULL
15048 && cap->type()->integer_type() == NULL
15049 && !cap->type()->is_error()
15050 && !cap->is_nil_expression()
15051 && !cap->is_error_expression()
15052 && (!cap->type()->is_abstract()
15053 || !cap->numeric_constant_value(&nc)
15054 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
15056 go_error_at(loc, "slice capacity must be integer");
15057 ret = false;
15060 Array_type* array_type = array->type()->array_type();
15061 if (array_type == NULL)
15063 go_assert(array->type()->is_error());
15064 return false;
15067 unsigned int int_bits =
15068 Type::lookup_integer_type("int")->integer_type()->bits();
15070 Numeric_constant lvalnc;
15071 mpz_t lval;
15072 bool lval_valid = (array_type->length() != NULL
15073 && array_type->length()->numeric_constant_value(&lvalnc)
15074 && lvalnc.to_int(&lval));
15075 Numeric_constant inc;
15076 mpz_t ival;
15077 bool ival_valid = false;
15078 if (start->numeric_constant_value(&inc) && inc.to_int(&ival))
15080 ival_valid = true;
15081 if (mpz_sgn(ival) < 0
15082 || mpz_sizeinbase(ival, 2) >= int_bits
15083 || (lval_valid
15084 && (end == NULL
15085 ? mpz_cmp(ival, lval) >= 0
15086 : mpz_cmp(ival, lval) > 0)))
15088 go_error_at(start->location(), "array index out of bounds");
15089 ret = false;
15093 if (end != NULL && !end->is_nil_expression())
15095 Numeric_constant enc;
15096 mpz_t eval;
15097 bool eval_valid = false;
15098 if (end->numeric_constant_value(&enc) && enc.to_int(&eval))
15100 eval_valid = true;
15101 if (mpz_sgn(eval) < 0
15102 || mpz_sizeinbase(eval, 2) >= int_bits
15103 || (lval_valid && mpz_cmp(eval, lval) > 0))
15105 go_error_at(end->location(), "array index out of bounds");
15106 ret = false;
15108 else if (ival_valid && mpz_cmp(ival, eval) > 0)
15110 go_error_at(loc, "inverted slice range");
15111 ret = false;
15115 Numeric_constant cnc;
15116 mpz_t cval;
15117 if (cap != NULL
15118 && cap->numeric_constant_value(&cnc) && cnc.to_int(&cval))
15120 if (mpz_sgn(cval) < 0
15121 || mpz_sizeinbase(cval, 2) >= int_bits
15122 || (lval_valid && mpz_cmp(cval, lval) > 0))
15124 go_error_at(cap->location(), "array index out of bounds");
15125 ret = false;
15127 else if (ival_valid && mpz_cmp(ival, cval) > 0)
15129 go_error_at(cap->location(),
15130 "invalid slice index: capacity less than start");
15131 ret = false;
15133 else if (eval_valid && mpz_cmp(eval, cval) > 0)
15135 go_error_at(cap->location(),
15136 "invalid slice index: capacity less than length");
15137 ret = false;
15139 mpz_clear(cval);
15142 if (eval_valid)
15143 mpz_clear(eval);
15145 if (ival_valid)
15146 mpz_clear(ival);
15147 if (lval_valid)
15148 mpz_clear(lval);
15150 // A slice of an array requires an addressable array. A slice of a
15151 // slice is always possible.
15152 if (end != NULL && !array_type->is_slice_type())
15154 if (!array->is_addressable())
15156 go_error_at(loc, "slice of unaddressable value");
15157 ret = false;
15159 else
15161 // Set the array address taken but not escape. The escape
15162 // analysis will make it escape to heap when needed.
15163 array->address_taken(false);
15167 return ret;
15170 // The subexpressions of an array index must be evaluated in order.
15171 // If this is indexing into an array, rather than a slice, then only
15172 // the index should be evaluated. Since this is called for values on
15173 // the left hand side of an assigment, evaluating the array, meaning
15174 // copying the array, will cause a different array to be modified.
15176 bool
15177 Array_index_expression::do_must_eval_subexpressions_in_order(
15178 int* skip) const
15180 *skip = this->array_->type()->is_slice_type() ? 0 : 1;
15181 return true;
15184 // Flatten array indexing: add temporary variables and bounds checks.
15186 Expression*
15187 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
15188 Statement_inserter* inserter)
15190 if (this->is_flattened_)
15191 return this;
15192 this->is_flattened_ = true;
15194 Location loc = this->location();
15196 if (this->is_error_expression())
15197 return Expression::make_error(loc);
15199 Expression* array = this->array_;
15200 Expression* start = this->start_;
15201 Expression* end = this->end_;
15202 Expression* cap = this->cap_;
15203 if (array->is_error_expression()
15204 || array->type()->is_error_type()
15205 || start->is_error_expression()
15206 || start->type()->is_error_type()
15207 || (end != NULL
15208 && (end->is_error_expression() || end->type()->is_error_type()))
15209 || (cap != NULL
15210 && (cap->is_error_expression() || cap->type()->is_error_type())))
15212 go_assert(saw_errors());
15213 return Expression::make_error(loc);
15216 Array_type* array_type = this->array_->type()->array_type();
15217 if (array_type == NULL)
15219 go_assert(saw_errors());
15220 return Expression::make_error(loc);
15223 Temporary_statement* temp;
15224 if (array_type->is_slice_type() && !array->is_multi_eval_safe())
15226 temp = Statement::make_temporary(NULL, array, loc);
15227 inserter->insert(temp);
15228 this->array_ = Expression::make_temporary_reference(temp, loc);
15229 array = this->array_;
15231 if (!start->is_multi_eval_safe())
15233 temp = Statement::make_temporary(NULL, start, loc);
15234 inserter->insert(temp);
15235 this->start_ = Expression::make_temporary_reference(temp, loc);
15236 start = this->start_;
15238 if (end != NULL
15239 && !end->is_nil_expression()
15240 && !end->is_multi_eval_safe())
15242 temp = Statement::make_temporary(NULL, end, loc);
15243 inserter->insert(temp);
15244 this->end_ = Expression::make_temporary_reference(temp, loc);
15245 end = this->end_;
15247 if (cap != NULL && !cap->is_multi_eval_safe())
15249 temp = Statement::make_temporary(NULL, cap, loc);
15250 inserter->insert(temp);
15251 this->cap_ = Expression::make_temporary_reference(temp, loc);
15252 cap = this->cap_;
15255 if (!this->needs_bounds_check_)
15256 return this;
15258 Expression* len;
15259 if (!array_type->is_slice_type())
15261 len = array_type->get_length(gogo, this->array_);
15262 go_assert(len->is_constant());
15264 else
15266 len = array_type->get_length(gogo, this->array_->copy());
15267 temp = Statement::make_temporary(NULL, len, loc);
15268 temp->determine_types(gogo);
15269 inserter->insert(temp);
15270 len = Expression::make_temporary_reference(temp, loc);
15273 Expression* scap = NULL;
15274 if (array_type->is_slice_type())
15276 scap = array_type->get_capacity(gogo, this->array_->copy());
15277 temp = Statement::make_temporary(NULL, scap, loc);
15278 temp->determine_types(gogo);
15279 inserter->insert(temp);
15280 scap = Expression::make_temporary_reference(temp, loc);
15283 // The order of bounds checks here matches the order used by the gc
15284 // compiler, as tested by issue30116[u].go.
15286 if (cap != NULL)
15288 if (array_type->is_slice_type())
15289 Expression::check_bounds(gogo, cap, OPERATOR_LE, scap,
15290 Runtime::PANIC_SLICE3_ACAP,
15291 Runtime::PANIC_SLICE3_ACAP_U,
15292 Runtime::PANIC_EXTEND_SLICE3_ACAP,
15293 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
15294 inserter, loc);
15295 else
15296 Expression::check_bounds(gogo, cap, OPERATOR_LE, len,
15297 Runtime::PANIC_SLICE3_ALEN,
15298 Runtime::PANIC_SLICE3_ALEN_U,
15299 Runtime::PANIC_EXTEND_SLICE3_ALEN,
15300 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
15301 inserter, loc);
15303 Expression* start_bound = cap;
15304 if (end != NULL && !end->is_nil_expression())
15306 Expression::check_bounds(gogo, end, OPERATOR_LE, cap,
15307 Runtime::PANIC_SLICE3_B,
15308 Runtime::PANIC_SLICE3_B_U,
15309 Runtime::PANIC_EXTEND_SLICE3_B,
15310 Runtime::PANIC_EXTEND_SLICE3_B_U,
15311 inserter, loc);
15312 start_bound = end;
15315 Expression::check_bounds(gogo, start, OPERATOR_LE, start_bound,
15316 Runtime::PANIC_SLICE3_C,
15317 Runtime::PANIC_SLICE3_C_U,
15318 Runtime::PANIC_EXTEND_SLICE3_C,
15319 Runtime::PANIC_EXTEND_SLICE3_C_U,
15320 inserter, loc);
15322 else if (end != NULL && !end->is_nil_expression())
15324 if (array_type->is_slice_type())
15325 Expression::check_bounds(gogo, end, OPERATOR_LE, scap,
15326 Runtime::PANIC_SLICE_ACAP,
15327 Runtime::PANIC_SLICE_ACAP_U,
15328 Runtime::PANIC_EXTEND_SLICE_ACAP,
15329 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
15330 inserter, loc);
15331 else
15332 Expression::check_bounds(gogo, end, OPERATOR_LE, len,
15333 Runtime::PANIC_SLICE_ALEN,
15334 Runtime::PANIC_SLICE_ALEN_U,
15335 Runtime::PANIC_EXTEND_SLICE_ALEN,
15336 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
15337 inserter, loc);
15339 Expression::check_bounds(gogo, start, OPERATOR_LE, end,
15340 Runtime::PANIC_SLICE_B,
15341 Runtime::PANIC_SLICE_B_U,
15342 Runtime::PANIC_EXTEND_SLICE_B,
15343 Runtime::PANIC_EXTEND_SLICE_B_U,
15344 inserter, loc);
15346 else if (end != NULL)
15348 Expression* start_bound;
15349 if (array_type->is_slice_type())
15350 start_bound = scap;
15351 else
15352 start_bound = len;
15353 Expression::check_bounds(gogo, start, OPERATOR_LE, start_bound,
15354 Runtime::PANIC_SLICE_B,
15355 Runtime::PANIC_SLICE_B_U,
15356 Runtime::PANIC_EXTEND_SLICE_B,
15357 Runtime::PANIC_EXTEND_SLICE_B_U,
15358 inserter, loc);
15360 else
15361 Expression::check_bounds(gogo, start, OPERATOR_LT, len,
15362 Runtime::PANIC_INDEX,
15363 Runtime::PANIC_INDEX_U,
15364 Runtime::PANIC_EXTEND_INDEX,
15365 Runtime::PANIC_EXTEND_INDEX_U,
15366 inserter, loc);
15368 return this;
15371 // Return whether this expression is addressable.
15373 bool
15374 Array_index_expression::do_is_addressable() const
15376 // A slice expression is not addressable.
15377 if (this->end_ != NULL)
15378 return false;
15380 // An index into a slice is addressable.
15381 if (this->array_->type()->is_slice_type())
15382 return true;
15384 // An index into an array is addressable if the array is
15385 // addressable.
15386 return this->array_->is_addressable();
15389 void
15390 Array_index_expression::do_address_taken(bool escapes)
15392 // In &x[0], if x is a slice, then x's address is not taken.
15393 if (!this->array_->type()->is_slice_type())
15394 this->array_->address_taken(escapes);
15397 // Get the backend representation for an array index.
15399 Bexpression*
15400 Array_index_expression::do_get_backend(Translate_context* context)
15402 Array_type* array_type = this->array_->type()->array_type();
15403 if (array_type == NULL)
15405 go_assert(this->array_->type()->is_error());
15406 return context->backend()->error_expression();
15408 go_assert(!array_type->is_slice_type()
15409 || this->array_->is_multi_eval_safe());
15411 Location loc = this->location();
15412 Gogo* gogo = context->gogo();
15414 Type* int_type = Type::lookup_integer_type("int");
15415 Btype* int_btype = int_type->get_backend(gogo);
15417 // Convert the length and capacity to "int". FIXME: Do we need to
15418 // do this?
15419 Bexpression* length = NULL;
15420 if (this->end_ == NULL || this->end_->is_nil_expression())
15422 Expression* len = array_type->get_length(gogo, this->array_);
15423 length = len->get_backend(context);
15424 length = gogo->backend()->convert_expression(int_btype, length, loc);
15427 Bexpression* capacity = NULL;
15428 if (this->end_ != NULL)
15430 Expression* cap = array_type->get_capacity(gogo, this->array_);
15431 capacity = cap->get_backend(context);
15432 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
15435 Bexpression* cap_arg = capacity;
15436 if (this->cap_ != NULL)
15438 cap_arg = this->cap_->get_backend(context);
15439 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
15442 if (length == NULL)
15443 length = cap_arg;
15445 if (this->start_->type()->integer_type() == NULL
15446 && !Type::are_convertible(int_type, this->start_->type(), NULL))
15448 go_assert(saw_errors());
15449 return context->backend()->error_expression();
15452 Bexpression* start = this->start_->get_backend(context);
15453 start = gogo->backend()->convert_expression(int_btype, start, loc);
15455 Bfunction* bfn = context->function()->func_value()->get_decl();
15456 if (this->end_ == NULL)
15458 // Simple array indexing.
15459 Bexpression* ret;
15460 if (!array_type->is_slice_type())
15462 Bexpression* array = this->array_->get_backend(context);
15463 ret = gogo->backend()->array_index_expression(array, start, loc);
15465 else
15467 Expression* valptr = array_type->get_value_pointer(gogo,
15468 this->array_);
15469 Bexpression* ptr = valptr->get_backend(context);
15470 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
15472 Type* ele_type = this->array_->type()->array_type()->element_type();
15473 Btype* ele_btype = ele_type->get_backend(gogo);
15474 ret = gogo->backend()->indirect_expression(ele_btype, ptr, false,
15475 loc);
15477 return ret;
15480 // Slice expression.
15482 Bexpression* end;
15483 if (this->end_->is_nil_expression())
15484 end = length;
15485 else
15487 end = this->end_->get_backend(context);
15488 end = gogo->backend()->convert_expression(int_btype, end, loc);
15491 Bexpression* result_length =
15492 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
15494 Bexpression* result_capacity =
15495 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
15497 // If the new capacity is zero, don't change val. Otherwise we can
15498 // get a pointer to the next object in memory, keeping it live
15499 // unnecessarily. When the capacity is zero, the actual pointer
15500 // value doesn't matter.
15501 Bexpression* zero =
15502 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
15503 Bexpression* cond =
15504 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
15505 loc);
15506 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
15507 cond, zero,
15508 start, loc);
15509 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
15510 Bexpression* val = valptr->get_backend(context);
15511 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
15513 Btype* struct_btype = this->type()->get_backend(gogo);
15514 std::vector<Bexpression*> init;
15515 init.push_back(val);
15516 init.push_back(result_length);
15517 init.push_back(result_capacity);
15519 return gogo->backend()->constructor_expression(struct_btype, init, loc);
15522 // Export an array index expression.
15524 void
15525 Array_index_expression::do_export(Export_function_body* efb) const
15527 efb->write_c_string("(");
15528 this->array_->export_expression(efb);
15529 efb->write_c_string(")[");
15531 Type* old_context = efb->type_context();
15532 efb->set_type_context(Type::lookup_integer_type("int"));
15534 this->start_->export_expression(efb);
15535 if (this->end_ == NULL)
15536 go_assert(this->cap_ == NULL);
15537 else
15539 efb->write_c_string(":");
15540 if (!this->end_->is_nil_expression())
15541 this->end_->export_expression(efb);
15542 if (this->cap_ != NULL)
15544 efb->write_c_string(":");
15545 this->cap_->export_expression(efb);
15549 efb->set_type_context(old_context);
15551 efb->write_c_string("]");
15554 // Dump ast representation for an array index expression.
15556 void
15557 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
15558 const
15560 Index_expression::dump_index_expression(ast_dump_context, this->array_,
15561 this->start_, this->end_, this->cap_);
15564 // Make an array index expression. END and CAP may be NULL.
15566 Expression*
15567 Expression::make_array_index(Expression* array, Expression* start,
15568 Expression* end, Expression* cap,
15569 Location location)
15571 return new Array_index_expression(array, start, end, cap, location);
15574 // Class String_index_expression.
15576 // String index traversal.
15579 String_index_expression::do_traverse(Traverse* traverse)
15581 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
15582 return TRAVERSE_EXIT;
15583 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
15584 return TRAVERSE_EXIT;
15585 if (this->end_ != NULL)
15587 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
15588 return TRAVERSE_EXIT;
15590 return TRAVERSE_CONTINUE;
15593 Expression*
15594 String_index_expression::do_flatten(Gogo* gogo, Named_object*,
15595 Statement_inserter* inserter)
15597 if (this->is_flattened_)
15598 return this;
15599 this->is_flattened_ = true;
15601 Location loc = this->location();
15603 if (this->is_error_expression())
15604 return Expression::make_error(loc);
15606 Expression* string = this->string_;
15607 Expression* start = this->start_;
15608 Expression* end = this->end_;
15609 if (string->is_error_expression()
15610 || string->type()->is_error_type()
15611 || start->is_error_expression()
15612 || start->type()->is_error_type()
15613 || (end != NULL
15614 && (end->is_error_expression() || end->type()->is_error_type())))
15616 go_assert(saw_errors());
15617 return Expression::make_error(loc);
15620 Temporary_statement* temp;
15621 if (!string->is_multi_eval_safe())
15623 temp = Statement::make_temporary(NULL, string, loc);
15624 inserter->insert(temp);
15625 this->string_ = Expression::make_temporary_reference(temp, loc);
15626 string = this->string_;
15628 if (!start->is_multi_eval_safe())
15630 temp = Statement::make_temporary(NULL, start, loc);
15631 inserter->insert(temp);
15632 this->start_ = Expression::make_temporary_reference(temp, loc);
15633 start = this->start_;
15635 if (end != NULL
15636 && !end->is_nil_expression()
15637 && !end->is_multi_eval_safe())
15639 temp = Statement::make_temporary(NULL, end, loc);
15640 inserter->insert(temp);
15641 this->end_ = Expression::make_temporary_reference(temp, loc);
15642 end = this->end_;
15645 Expression* len = Expression::make_string_info(string->copy(),
15646 STRING_INFO_LENGTH, loc);
15647 temp = Statement::make_temporary(NULL, len, loc);
15648 temp->determine_types(gogo);
15649 inserter->insert(temp);
15650 len = Expression::make_temporary_reference(temp, loc);
15652 // The order of bounds checks here matches the order used by the gc
15653 // compiler, as tested by issue30116[u].go.
15655 if (end != NULL && !end->is_nil_expression())
15657 Expression::check_bounds(gogo, end, OPERATOR_LE, len,
15658 Runtime::PANIC_SLICE_ALEN,
15659 Runtime::PANIC_SLICE_ALEN_U,
15660 Runtime::PANIC_EXTEND_SLICE_ALEN,
15661 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
15662 inserter, loc);
15663 Expression::check_bounds(gogo, start, OPERATOR_LE, end,
15664 Runtime::PANIC_SLICE_B,
15665 Runtime::PANIC_SLICE_B_U,
15666 Runtime::PANIC_EXTEND_SLICE_B,
15667 Runtime::PANIC_EXTEND_SLICE_B_U,
15668 inserter, loc);
15670 else if (end != NULL)
15671 Expression::check_bounds(gogo, start, OPERATOR_LE, len,
15672 Runtime::PANIC_SLICE_B,
15673 Runtime::PANIC_SLICE_B_U,
15674 Runtime::PANIC_EXTEND_SLICE_B,
15675 Runtime::PANIC_EXTEND_SLICE_B_U,
15676 inserter, loc);
15677 else
15678 Expression::check_bounds(gogo, start, OPERATOR_LT, len,
15679 Runtime::PANIC_INDEX,
15680 Runtime::PANIC_INDEX_U,
15681 Runtime::PANIC_EXTEND_INDEX,
15682 Runtime::PANIC_EXTEND_INDEX_U,
15683 inserter, loc);
15685 return this;
15688 // Return the type of a string index.
15690 Type*
15691 String_index_expression::do_type()
15693 if (this->end_ == NULL)
15694 return Type::lookup_integer_type("byte");
15695 else
15696 return this->string_->type();
15699 // Determine the type of a string index.
15701 void
15702 String_index_expression::do_determine_type(Gogo* gogo, const Type_context*)
15704 this->string_->determine_type_no_context(gogo);
15706 Type_context index_context(Type::lookup_integer_type("int"), false);
15707 this->start_->determine_type(gogo, &index_context);
15708 if (this->end_ != NULL)
15709 this->end_->determine_type(gogo, &index_context);
15712 // Check types of a string index.
15714 void
15715 String_index_expression::do_check_types(Gogo*)
15717 if (!String_index_expression::check_indexes(this->string_, this->start_,
15718 this->end_, this->location()))
15719 this->set_is_error();
15722 // A static function to check string index types. This is also called
15723 // by Index_expression::do_check_types. It reports whether type
15724 // checking succeeded.
15726 bool
15727 String_index_expression::check_indexes(Expression* string, Expression* start,
15728 Expression* end, Location loc)
15730 bool ret = true;
15732 Numeric_constant nc;
15733 unsigned long v;
15734 if (start->type()->integer_type() == NULL
15735 && !start->type()->is_error()
15736 && (!start->type()->is_abstract()
15737 || !start->numeric_constant_value(&nc)
15738 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
15740 go_error_at(loc, "index must be integer");
15741 ret = false;
15744 if (end != NULL
15745 && end->type()->integer_type() == NULL
15746 && !end->type()->is_error()
15747 && !end->is_nil_expression()
15748 && !end->is_error_expression()
15749 && (!end->type()->is_abstract()
15750 || !end->numeric_constant_value(&nc)
15751 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
15753 go_error_at(loc, "slice end must be integer");
15754 ret = false;
15757 std::string sval;
15758 bool sval_valid = string->string_constant_value(&sval);
15760 Numeric_constant inc;
15761 mpz_t ival;
15762 bool ival_valid = false;
15763 if (start->numeric_constant_value(&inc) && inc.to_int(&ival))
15765 ival_valid = true;
15766 if (mpz_sgn(ival) < 0
15767 || (sval_valid
15768 && (end == NULL
15769 ? mpz_cmp_ui(ival, sval.length()) >= 0
15770 : mpz_cmp_ui(ival, sval.length()) > 0)))
15772 go_error_at(start->location(), "string index out of bounds");
15773 ret = false;
15777 if (end != NULL && !end->is_nil_expression())
15779 Numeric_constant enc;
15780 mpz_t eval;
15781 if (end->numeric_constant_value(&enc) && enc.to_int(&eval))
15783 if (mpz_sgn(eval) < 0
15784 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
15786 go_error_at(end->location(), "string index out of bounds");
15787 ret = false;
15789 else if (ival_valid && mpz_cmp(ival, eval) > 0)
15791 go_error_at(loc, "inverted slice range");
15792 ret = false;
15794 mpz_clear(eval);
15797 if (ival_valid)
15798 mpz_clear(ival);
15800 return ret;
15803 // Get the backend representation for a string index.
15805 Bexpression*
15806 String_index_expression::do_get_backend(Translate_context* context)
15808 Location loc = this->location();
15809 Gogo* gogo = context->gogo();
15811 Type* int_type = Type::lookup_integer_type("int");
15813 // It is possible that an error occurred earlier because the start index
15814 // cannot be represented as an integer type. In this case, we shouldn't
15815 // try casting the starting index into an integer since
15816 // Type_conversion_expression will fail to get the backend representation.
15817 // FIXME.
15818 if (this->start_->type()->integer_type() == NULL
15819 && !Type::are_convertible(int_type, this->start_->type(), NULL))
15821 go_assert(saw_errors());
15822 return context->backend()->error_expression();
15825 go_assert(this->string_->is_multi_eval_safe());
15826 go_assert(this->start_->is_multi_eval_safe());
15828 Expression* start = Expression::make_cast(int_type, this->start_, loc);
15829 Bfunction* bfn = context->function()->func_value()->get_decl();
15831 Expression* length =
15832 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
15833 Expression* bytes =
15834 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
15836 Bexpression* bstart = start->get_backend(context);
15837 Bexpression* ptr = bytes->get_backend(context);
15839 if (this->end_ == NULL)
15841 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
15842 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15843 return gogo->backend()->indirect_expression(ubtype, ptr, false, loc);
15846 Expression* end = NULL;
15847 if (this->end_->is_nil_expression())
15848 end = length;
15849 else
15851 go_assert(this->end_->is_multi_eval_safe());
15852 end = Expression::make_cast(int_type, this->end_, loc);
15855 end = end->copy();
15856 Bexpression* bend = end->get_backend(context);
15857 Bexpression* new_length =
15858 gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
15860 // If the new length is zero, don't change pointer. Otherwise we can
15861 // get a pointer to the next object in memory, keeping it live
15862 // unnecessarily. When the length is zero, the actual pointer
15863 // value doesn't matter.
15864 Btype* int_btype = int_type->get_backend(gogo);
15865 Bexpression* zero =
15866 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
15867 Bexpression* cond =
15868 gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
15869 loc);
15870 Bexpression* offset =
15871 gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
15872 bstart, loc);
15874 ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
15876 Btype* str_btype = this->type()->get_backend(gogo);
15877 std::vector<Bexpression*> init;
15878 init.push_back(ptr);
15879 init.push_back(new_length);
15880 return gogo->backend()->constructor_expression(str_btype, init, loc);
15883 // Export a string index expression.
15885 void
15886 String_index_expression::do_export(Export_function_body* efb) const
15888 efb->write_c_string("(");
15889 this->string_->export_expression(efb);
15890 efb->write_c_string(")[");
15892 Type* old_context = efb->type_context();
15893 efb->set_type_context(Type::lookup_integer_type("int"));
15895 this->start_->export_expression(efb);
15896 if (this->end_ != NULL)
15898 efb->write_c_string(":");
15899 if (!this->end_->is_nil_expression())
15900 this->end_->export_expression(efb);
15903 efb->set_type_context(old_context);
15905 efb->write_c_string("]");
15908 // Dump ast representation for a string index expression.
15910 void
15911 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
15912 const
15914 Index_expression::dump_index_expression(ast_dump_context, this->string_,
15915 this->start_, this->end_, NULL);
15918 // Make a string index expression. END may be NULL.
15920 Expression*
15921 Expression::make_string_index(Expression* string, Expression* start,
15922 Expression* end, Location location)
15924 return new String_index_expression(string, start, end, location);
15927 // Class Map_index.
15929 // Get the type of the map.
15931 Map_type*
15932 Map_index_expression::get_map_type() const
15934 Map_type* mt = this->map_->type()->map_type();
15935 if (mt == NULL)
15936 go_assert(saw_errors());
15937 return mt;
15940 // Map index traversal.
15943 Map_index_expression::do_traverse(Traverse* traverse)
15945 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
15946 return TRAVERSE_EXIT;
15947 return Expression::traverse(&this->index_, traverse);
15950 void
15951 Map_index_expression::do_determine_type(Gogo* gogo, const Type_context*)
15953 this->map_->determine_type_no_context(gogo);
15954 Map_type* mt = this->map_->type()->map_type();
15955 go_assert(mt != NULL);
15956 Type_context index_context(mt->key_type(), false);
15957 this->index_->determine_type(gogo, &index_context);
15958 if (this->value_pointer_ != NULL)
15959 this->value_pointer_->determine_type_no_context(gogo);
15962 void
15963 Map_index_expression::do_check_types(Gogo*)
15965 // Types should have been checked before this was created, so this
15966 // will probably never be called. Check it anyhow to be sure.
15967 Map_type* mt = this->map_->type()->map_type();
15968 go_assert(mt != NULL);
15969 if (!Type::are_assignable(mt->key_type(), this->index_->type(), NULL))
15970 this->report_error(_("incompatible type for map index"));
15973 // We need to pass in a pointer to the key, so flatten the index into a
15974 // temporary variable if it isn't already. The value pointer will be
15975 // dereferenced and checked for nil, so flatten into a temporary to avoid
15976 // recomputation.
15978 Expression*
15979 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
15980 Statement_inserter* inserter)
15982 Location loc = this->location();
15983 Map_type* mt = this->get_map_type();
15984 if (this->index()->is_error_expression()
15985 || this->index()->type()->is_error_type()
15986 || mt->is_error_type())
15988 go_assert(saw_errors());
15989 return Expression::make_error(loc);
15992 // Avoid copy for string([]byte) conversions used in map keys.
15993 // mapaccess doesn't keep the reference, so this is safe.
15994 Type_conversion_expression* ce = this->index_->conversion_expression();
15995 if (ce != NULL && ce->type()->is_string_type()
15996 && ce->expr()->type()->is_slice_type())
15997 ce->set_no_copy(true);
15999 if (!Type::are_identical(mt->key_type(), this->index_->type(),
16000 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
16001 NULL))
16003 if (this->index_->type()->interface_type() != NULL
16004 && !this->index_->is_multi_eval_safe())
16006 Temporary_statement* temp =
16007 Statement::make_temporary(NULL, this->index_, loc);
16008 inserter->insert(temp);
16009 this->index_ = Expression::make_temporary_reference(temp, loc);
16011 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
16012 this->index_, loc);
16015 if (!this->index_->is_multi_eval_safe())
16017 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
16018 loc);
16019 inserter->insert(temp);
16020 this->index_ = Expression::make_temporary_reference(temp, loc);
16023 if (this->value_pointer_ == NULL)
16024 this->get_value_pointer(gogo);
16025 if (this->value_pointer_->is_error_expression()
16026 || this->value_pointer_->type()->is_error_type())
16027 return Expression::make_error(loc);
16028 if (!this->value_pointer_->is_multi_eval_safe())
16030 Temporary_statement* temp =
16031 Statement::make_temporary(NULL, this->value_pointer_, loc);
16032 inserter->insert(temp);
16033 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
16036 return this;
16039 // Return the type of a map index.
16041 Type*
16042 Map_index_expression::do_type()
16044 Map_type* mt = this->get_map_type();
16045 if (mt == NULL)
16046 return Type::make_error_type();
16047 return mt->val_type();
16050 // Add explicit type conversions.
16052 void
16053 Map_index_expression::do_add_conversions()
16055 Map_type* mt = this->get_map_type();
16056 if (mt == NULL)
16057 return;
16058 Type* lt = mt->key_type();
16059 Type* rt = this->index_->type();
16060 if (!Type::are_identical(lt, rt, 0, NULL)
16061 && lt->interface_type() != NULL)
16062 this->index_ = Expression::make_cast(lt, this->index_, this->location());
16065 // Get the backend representation for a map index.
16067 Bexpression*
16068 Map_index_expression::do_get_backend(Translate_context* context)
16070 Map_type* type = this->get_map_type();
16071 if (type == NULL)
16073 go_assert(saw_errors());
16074 return context->backend()->error_expression();
16077 go_assert(this->value_pointer_ != NULL
16078 && this->value_pointer_->is_multi_eval_safe());
16080 Expression* val = Expression::make_dereference(this->value_pointer_,
16081 NIL_CHECK_NOT_NEEDED,
16082 this->location());
16083 return val->get_backend(context);
16086 // Get an expression for the map index. This returns an expression
16087 // that evaluates to a pointer to a value. If the key is not in the
16088 // map, the pointer will point to a zero value.
16090 Expression*
16091 Map_index_expression::get_value_pointer(Gogo* gogo)
16093 if (this->value_pointer_ == NULL)
16095 Map_type* type = this->get_map_type();
16096 if (type == NULL)
16098 go_assert(saw_errors());
16099 return Expression::make_error(this->location());
16102 Location loc = this->location();
16103 Expression* map_ref = this->map_;
16105 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
16106 this->index_,
16107 loc);
16109 Expression* type_expr = Expression::make_type_descriptor(type, loc);
16110 Expression* zero = type->fat_zero_value(gogo);
16111 Expression* map_index;
16112 if (zero == NULL)
16114 Runtime::Function code;
16115 Expression* key;
16116 switch (type->algorithm(gogo))
16118 case Map_type::MAP_ALG_FAST32:
16119 case Map_type::MAP_ALG_FAST32PTR:
16121 Type* uint32_type = Type::lookup_integer_type("uint32");
16122 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
16123 key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
16124 loc);
16125 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
16126 loc);
16127 code = Runtime::MAPACCESS1_FAST32;
16128 break;
16130 case Map_type::MAP_ALG_FAST64:
16131 case Map_type::MAP_ALG_FAST64PTR:
16133 Type* uint64_type = Type::lookup_integer_type("uint64");
16134 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
16135 key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
16136 loc);
16137 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
16138 loc);
16139 code = Runtime::MAPACCESS1_FAST64;
16140 break;
16142 case Map_type::MAP_ALG_FASTSTR:
16143 key = this->index_;
16144 code = Runtime::MAPACCESS1_FASTSTR;
16145 break;
16146 default:
16147 key = index_ptr;
16148 code = Runtime::MAPACCESS1;
16149 break;
16151 map_index = Runtime::make_call(gogo, code, loc, 3,
16152 type_expr, map_ref, key);
16154 else
16155 map_index = Runtime::make_call(gogo, Runtime::MAPACCESS1_FAT, loc, 4,
16156 type_expr, map_ref, index_ptr, zero);
16158 Type* val_type = type->val_type();
16159 this->value_pointer_ =
16160 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
16161 map_index, this->location());
16162 this->value_pointer_->determine_type_no_context(gogo);
16165 return this->value_pointer_;
16168 // Export a map index expression.
16170 void
16171 Map_index_expression::do_export(Export_function_body* efb) const
16173 efb->write_c_string("(");
16174 this->map_->export_expression(efb);
16175 efb->write_c_string(")[");
16177 Type* old_context = efb->type_context();
16178 efb->set_type_context(this->get_map_type()->key_type());
16180 this->index_->export_expression(efb);
16182 efb->set_type_context(old_context);
16184 efb->write_c_string("]");
16187 // Dump ast representation for a map index expression
16189 void
16190 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
16191 const
16193 Index_expression::dump_index_expression(ast_dump_context, this->map_,
16194 this->index_, NULL, NULL);
16197 // Make a map index expression.
16199 Map_index_expression*
16200 Expression::make_map_index(Expression* map, Expression* index,
16201 Location location)
16203 return new Map_index_expression(map, index, location);
16206 // Class Field_reference_expression.
16208 // Lower a field reference expression. There is nothing to lower, but
16209 // this is where we generate the tracking information for fields with
16210 // the magic go:"track" tag.
16212 Expression*
16213 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
16214 Statement_inserter* inserter)
16216 Struct_type* struct_type = this->expr_->type()->struct_type();
16217 if (struct_type == NULL)
16219 // Error will be reported elsewhere.
16220 return this;
16222 const Struct_field* field = struct_type->field(this->field_index_);
16223 if (field == NULL)
16224 return this;
16225 if (!field->has_tag())
16226 return this;
16227 if (field->tag().find("go:\"track\"") == std::string::npos)
16228 return this;
16230 // References from functions generated by the compiler don't count.
16231 if (function != NULL && function->func_value()->is_type_specific_function())
16232 return this;
16234 // We have found a reference to a tracked field. Build a call to
16235 // the runtime function __go_fieldtrack with a string that describes
16236 // the field. FIXME: We should only call this once per referenced
16237 // field per function, not once for each reference to the field.
16239 if (this->called_fieldtrack_)
16240 return this;
16241 this->called_fieldtrack_ = true;
16243 Location loc = this->location();
16245 std::string s = "fieldtrack \"";
16246 Named_type* nt = this->expr_->type()->unalias()->named_type();
16247 if (nt == NULL || nt->named_object()->package() == NULL)
16248 s.append(gogo->pkgpath());
16249 else
16250 s.append(nt->named_object()->package()->pkgpath());
16251 s.push_back('.');
16252 if (nt != NULL)
16253 s.append(Gogo::unpack_hidden_name(nt->name()));
16254 s.push_back('.');
16255 s.append(Gogo::unpack_hidden_name(field->field_name()));
16256 s.push_back('"');
16258 // We can't use a string here, because internally a string holds a
16259 // pointer to the actual bytes; when the linker garbage collects the
16260 // string, it won't garbage collect the bytes. So we use a
16261 // [...]byte.
16263 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
16265 Type* byte_type = Type::lookup_integer_type("byte");
16266 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
16267 array_type->set_is_array_incomparable();
16269 Expression_list* bytes = new Expression_list();
16270 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
16272 unsigned char c = static_cast<unsigned char>(*p);
16273 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
16276 Expression* e = Expression::make_composite_literal(array_type, 0, false,
16277 bytes, false, loc);
16279 Variable* var = new Variable(array_type, e, true, false, false, loc);
16281 static int count;
16282 char buf[50];
16283 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
16284 ++count;
16286 Named_object* no = gogo->add_variable(buf, var);
16287 e = Expression::make_var_reference(no, loc);
16288 e = Expression::make_unary(OPERATOR_AND, e, loc);
16290 Expression* call = Runtime::make_call(gogo, Runtime::FIELDTRACK, loc, 1, e);
16291 call->determine_type_no_context(gogo);
16292 gogo->lower_expression(function, inserter, &call);
16293 inserter->insert(Statement::make_statement(call, false));
16295 // Put this function, and the global variable we just created, into
16296 // unique sections. This will permit the linker to garbage collect
16297 // them if they are not referenced. The effect is that the only
16298 // strings, indicating field references, that will wind up in the
16299 // executable will be those for functions that are actually needed.
16300 if (function != NULL)
16301 function->func_value()->set_in_unique_section();
16302 var->set_in_unique_section();
16304 return this;
16307 // Return the type of a field reference.
16309 Type*
16310 Field_reference_expression::do_type()
16312 Type* type = this->expr_->type();
16313 if (type->is_error())
16314 return type;
16315 Struct_type* struct_type = type->struct_type();
16316 go_assert(struct_type != NULL);
16317 return struct_type->field(this->field_index_)->type();
16320 // Check the types for a field reference.
16322 void
16323 Field_reference_expression::do_check_types(Gogo*)
16325 Type* type = this->expr_->type();
16326 if (type->is_error())
16327 return;
16328 Struct_type* struct_type = type->struct_type();
16329 go_assert(struct_type != NULL);
16330 go_assert(struct_type->field(this->field_index_) != NULL);
16333 // Get the backend representation for a field reference.
16335 Bexpression*
16336 Field_reference_expression::do_get_backend(Translate_context* context)
16338 Bexpression* bstruct = this->expr_->get_backend(context);
16339 return context->gogo()->backend()->struct_field_expression(bstruct,
16340 this->field_index_,
16341 this->location());
16344 // Dump ast representation for a field reference expression.
16346 void
16347 Field_reference_expression::do_dump_expression(
16348 Ast_dump_context* ast_dump_context) const
16350 this->expr_->dump_expression(ast_dump_context);
16351 ast_dump_context->ostream() << "." << this->field_index_;
16354 // Make a reference to a qualified identifier in an expression.
16356 Field_reference_expression*
16357 Expression::make_field_reference(Expression* expr, unsigned int field_index,
16358 Location location)
16360 return new Field_reference_expression(expr, field_index, location);
16363 // Class Interface_field_reference_expression.
16365 // Return an expression for the pointer to the function to call.
16367 Expression*
16368 Interface_field_reference_expression::get_function()
16370 Expression* ref = this->expr_;
16371 Location loc = this->location();
16372 if (ref->type()->points_to() != NULL)
16373 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
16375 Expression* mtable =
16376 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
16377 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
16379 std::string name = Gogo::unpack_hidden_name(this->name_);
16380 unsigned int index;
16381 const Struct_field* field = mtable_type->find_local_field(name, &index);
16382 go_assert(field != NULL);
16384 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
16385 return Expression::make_field_reference(mtable, index, loc);
16388 // Return an expression for the first argument to pass to the interface
16389 // function.
16391 Expression*
16392 Interface_field_reference_expression::get_underlying_object()
16394 Expression* expr = this->expr_;
16395 if (expr->type()->points_to() != NULL)
16396 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
16397 this->location());
16398 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
16399 this->location());
16402 // Traversal.
16405 Interface_field_reference_expression::do_traverse(Traverse* traverse)
16407 return Expression::traverse(&this->expr_, traverse);
16410 // Lower the expression. If this expression is not called, we need to
16411 // evaluate the expression twice when converting to the backend
16412 // interface. So introduce a temporary variable if necessary.
16414 Expression*
16415 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
16416 Statement_inserter* inserter)
16418 if (this->expr_->is_error_expression()
16419 || this->expr_->type()->is_error_type())
16421 go_assert(saw_errors());
16422 return Expression::make_error(this->location());
16425 if (!this->expr_->is_multi_eval_safe())
16427 Temporary_statement* temp =
16428 Statement::make_temporary(NULL, this->expr_, this->location());
16429 inserter->insert(temp);
16430 this->expr_ = Expression::make_temporary_reference(temp, this->location());
16432 return this;
16435 // Return the type of an interface field reference.
16437 Type*
16438 Interface_field_reference_expression::do_type()
16440 Type* expr_type = this->expr_->type();
16442 Type* points_to = expr_type->points_to();
16443 if (points_to != NULL)
16444 expr_type = points_to;
16446 Interface_type* interface_type = expr_type->interface_type();
16447 if (interface_type == NULL)
16448 return Type::make_error_type();
16450 const Typed_identifier* method = interface_type->find_method(this->name_);
16451 if (method == NULL)
16452 return Type::make_error_type();
16454 return method->type();
16457 // Determine types.
16459 void
16460 Interface_field_reference_expression::do_determine_type(Gogo* gogo,
16461 const Type_context*)
16463 this->expr_->determine_type_no_context(gogo);
16466 // Check the types for an interface field reference.
16468 void
16469 Interface_field_reference_expression::do_check_types(Gogo*)
16471 Type* type = this->expr_->type();
16473 Type* points_to = type->points_to();
16474 if (points_to != NULL)
16475 type = points_to;
16477 Interface_type* interface_type = type->interface_type();
16478 if (interface_type == NULL)
16480 if (!type->is_error_type())
16481 this->report_error(_("expected interface or pointer to interface"));
16483 else
16485 const Typed_identifier* method =
16486 interface_type->find_method(this->name_);
16487 if (method == NULL)
16489 go_error_at(this->location(), "method %qs not in interface",
16490 Gogo::message_name(this->name_).c_str());
16491 this->set_is_error();
16496 // If an interface field reference is not simply called, then it is
16497 // represented as a closure. The closure will hold a single variable,
16498 // the value of the interface on which the method should be called.
16499 // The function will be a simple thunk that pulls the value from the
16500 // closure and calls the method with the remaining arguments.
16502 // Because method values are not common, we don't build all thunks for
16503 // all possible interface methods, but instead only build them as we
16504 // need them. In particular, we even build them on demand for
16505 // interface methods defined in other packages.
16507 Interface_field_reference_expression::Interface_method_thunks
16508 Interface_field_reference_expression::interface_method_thunks;
16510 // Find or create the thunk to call method NAME on TYPE.
16512 Named_object*
16513 Interface_field_reference_expression::create_thunk(Gogo* gogo,
16514 Interface_type* type,
16515 const std::string& name)
16517 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
16518 std::pair<Interface_method_thunks::iterator, bool> ins =
16519 Interface_field_reference_expression::interface_method_thunks.insert(val);
16520 if (ins.second)
16522 // This is the first time we have seen this interface.
16523 ins.first->second = new Method_thunks();
16526 for (Method_thunks::const_iterator p = ins.first->second->begin();
16527 p != ins.first->second->end();
16528 p++)
16529 if (p->first == name)
16530 return p->second;
16532 Location loc = type->location();
16534 const Typed_identifier* method_id = type->find_method(name);
16535 if (method_id == NULL)
16536 return Named_object::make_erroneous_name(gogo->thunk_name());
16538 Function_type* orig_fntype = method_id->type()->function_type();
16539 if (orig_fntype == NULL)
16540 return Named_object::make_erroneous_name(gogo->thunk_name());
16542 Struct_field_list* sfl = new Struct_field_list();
16543 // The type here is wrong--it should be the C function type. But it
16544 // doesn't really matter.
16545 Type* vt = Type::make_pointer_type(Type::make_void_type());
16546 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
16547 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
16548 Struct_type* st = Type::make_struct_type(sfl, loc);
16549 st->set_is_struct_incomparable();
16550 Type* closure_type = Type::make_pointer_type(st);
16552 Function_type* new_fntype = orig_fntype->copy_with_names();
16554 std::string thunk_name = gogo->thunk_name();
16555 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
16556 false, loc);
16558 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
16559 cvar->set_is_used();
16560 cvar->set_is_closure();
16561 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
16562 NULL, cvar);
16563 new_no->func_value()->set_closure_var(cp);
16565 gogo->start_block(loc);
16567 // Field 0 of the closure is the function code pointer, field 1 is
16568 // the value on which to invoke the method.
16569 Expression* arg = Expression::make_var_reference(cp, loc);
16570 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
16571 arg = Expression::make_field_reference(arg, 1, loc);
16573 Expression *ifre = Expression::make_interface_field_reference(arg, name,
16574 loc);
16576 const Typed_identifier_list* orig_params = orig_fntype->parameters();
16577 Expression_list* args;
16578 if (orig_params == NULL || orig_params->empty())
16579 args = NULL;
16580 else
16582 const Typed_identifier_list* new_params = new_fntype->parameters();
16583 args = new Expression_list();
16584 for (Typed_identifier_list::const_iterator p = new_params->begin();
16585 p != new_params->end();
16586 ++p)
16588 Named_object* p_no = gogo->lookup(p->name(), NULL);
16589 go_assert(p_no != NULL
16590 && p_no->is_variable()
16591 && p_no->var_value()->is_parameter());
16592 args->push_back(Expression::make_var_reference(p_no, loc));
16596 Call_expression* call = Expression::make_call(ifre, args,
16597 orig_fntype->is_varargs(),
16598 loc);
16599 call->set_varargs_are_lowered();
16601 Statement* s = Statement::make_return_from_call(new_no, call, loc);
16602 s->determine_types(gogo);
16603 gogo->add_statement(s);
16604 Block* b = gogo->finish_block(loc);
16605 gogo->add_block(b, loc);
16607 // This is called after lowering.
16608 gogo->lower_block(new_no, b);
16610 gogo->finish_function(loc);
16612 ins.first->second->push_back(std::make_pair(name, new_no));
16613 return new_no;
16616 // Lookup a thunk to call method NAME on TYPE.
16618 Named_object*
16619 Interface_field_reference_expression::lookup_thunk(Interface_type* type,
16620 const std::string& name)
16622 Interface_method_thunks::const_iterator p =
16623 Interface_field_reference_expression::interface_method_thunks.find(type);
16624 if (p == Interface_field_reference_expression::interface_method_thunks.end())
16625 return NULL;
16626 for (Method_thunks::const_iterator pm = p->second->begin();
16627 pm != p->second->end();
16628 ++pm)
16629 if (pm->first == name)
16630 return pm->second;
16631 return NULL;
16634 // Get the backend representation for a method value.
16636 Bexpression*
16637 Interface_field_reference_expression::do_get_backend(Translate_context* context)
16639 Interface_type* type = this->expr_->type()->interface_type();
16640 if (type == NULL)
16642 go_assert(saw_errors());
16643 return context->backend()->error_expression();
16646 Named_object* thunk =
16647 Interface_field_reference_expression::lookup_thunk(type, this->name_);
16649 // The thunk should have been created during the
16650 // create_function_descriptors pass.
16651 if (thunk == NULL || thunk->is_erroneous())
16653 go_assert(saw_errors());
16654 return context->backend()->error_expression();
16657 // FIXME: We should lower this earlier, but we can't it lower it in
16658 // the lowering pass because at that point we don't know whether we
16659 // need to create the thunk or not. If the expression is called, we
16660 // don't need the thunk.
16662 Location loc = this->location();
16664 Struct_field_list* fields = new Struct_field_list();
16665 fields->push_back(Struct_field(Typed_identifier("fn",
16666 thunk->func_value()->type(),
16667 loc)));
16668 fields->push_back(Struct_field(Typed_identifier("val",
16669 this->expr_->type(),
16670 loc)));
16671 Struct_type* st = Type::make_struct_type(fields, loc);
16672 st->set_is_struct_incomparable();
16674 Expression_list* vals = new Expression_list();
16675 vals->push_back(Expression::make_func_code_reference(thunk, loc));
16676 vals->push_back(this->expr_);
16678 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
16679 Bexpression* bclosure =
16680 Expression::make_heap_expression(expr, loc)->get_backend(context);
16682 Gogo* gogo = context->gogo();
16683 Btype* btype = this->type()->get_backend(gogo);
16684 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
16686 Expression* nil_check =
16687 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
16688 Expression::make_nil(loc), loc);
16689 Bexpression* bnil_check = nil_check->get_backend(context);
16691 Expression* crash = Runtime::make_call(gogo, Runtime::PANIC_MEM, loc, 0);
16692 crash->determine_type_no_context(gogo);
16693 Bexpression* bcrash = crash->get_backend(context);
16695 Bfunction* bfn = context->function()->func_value()->get_decl();
16696 Bexpression* bcond =
16697 gogo->backend()->conditional_expression(bfn, NULL,
16698 bnil_check, bcrash, NULL, loc);
16699 Bfunction* bfunction = context->function()->func_value()->get_decl();
16700 Bstatement* cond_statement =
16701 gogo->backend()->expression_statement(bfunction, bcond);
16702 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
16705 // Dump ast representation for an interface field reference.
16707 void
16708 Interface_field_reference_expression::do_dump_expression(
16709 Ast_dump_context* ast_dump_context) const
16711 this->expr_->dump_expression(ast_dump_context);
16712 ast_dump_context->ostream() << "." << this->name_;
16715 // Make a reference to a field in an interface.
16717 Expression*
16718 Expression::make_interface_field_reference(Expression* expr,
16719 const std::string& field,
16720 Location location)
16722 return new Interface_field_reference_expression(expr, field, location);
16725 // Class Allocation_expression.
16728 Allocation_expression::do_traverse(Traverse* traverse)
16730 return Type::traverse(this->type_, traverse);
16733 Type*
16734 Allocation_expression::do_type()
16736 return Type::make_pointer_type(this->type_);
16739 void
16740 Allocation_expression::do_check_types(Gogo*)
16742 if (!this->type_->in_heap())
16743 go_error_at(this->location(), "cannot heap allocate go:notinheap type");
16746 // Make a copy of an allocation expression.
16748 Expression*
16749 Allocation_expression::do_copy()
16751 Allocation_expression* alloc =
16752 new Allocation_expression(this->type_->copy_expressions(),
16753 this->location());
16754 if (this->allocate_on_stack_)
16755 alloc->set_allocate_on_stack();
16756 if (this->no_zero_)
16757 alloc->set_no_zero();
16758 return alloc;
16761 // Return the backend representation for an allocation expression.
16763 Bexpression*
16764 Allocation_expression::do_get_backend(Translate_context* context)
16766 Gogo* gogo = context->gogo();
16767 Location loc = this->location();
16768 Btype* btype = this->type_->get_backend(gogo);
16770 if (this->allocate_on_stack_)
16772 int64_t size;
16773 bool ok = this->type_->backend_type_size(gogo, &size);
16774 if (!ok)
16776 go_assert(saw_errors());
16777 return gogo->backend()->error_expression();
16779 Bstatement* decl;
16780 Named_object* fn = context->function();
16781 go_assert(fn != NULL);
16782 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
16783 Bexpression* init = (this->no_zero_
16784 ? NULL
16785 : gogo->backend()->zero_expression(btype));
16786 Bvariable* temp =
16787 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
16788 init,
16789 Backend::variable_address_is_taken,
16790 loc, &decl);
16791 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
16792 ret = gogo->backend()->address_expression(ret, loc);
16793 ret = gogo->backend()->compound_expression(decl, ret, loc);
16794 return ret;
16797 Bexpression* space =
16798 gogo->allocate_memory(this->type_, loc)->get_backend(context);
16799 Btype* pbtype = gogo->backend()->pointer_type(btype);
16800 return gogo->backend()->convert_expression(pbtype, space, loc);
16803 // Dump ast representation for an allocation expression.
16805 void
16806 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
16807 const
16809 ast_dump_context->ostream() << "new(";
16810 ast_dump_context->dump_type(this->type_);
16811 ast_dump_context->ostream() << ")";
16814 // Make an allocation expression.
16816 Expression*
16817 Expression::make_allocation(Type* type, Location location)
16819 return new Allocation_expression(type, location);
16822 // Class Ordered_value_list.
16825 Ordered_value_list::traverse_vals(Traverse* traverse)
16827 if (this->vals_ != NULL)
16829 if (this->traverse_order_ == NULL)
16831 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
16832 return TRAVERSE_EXIT;
16834 else
16836 for (std::vector<unsigned long>::const_iterator p =
16837 this->traverse_order_->begin();
16838 p != this->traverse_order_->end();
16839 ++p)
16841 if (Expression::traverse(&this->vals_->at(*p), traverse)
16842 == TRAVERSE_EXIT)
16843 return TRAVERSE_EXIT;
16847 return TRAVERSE_CONTINUE;
16850 // Class Struct_construction_expression.
16852 // Traversal.
16855 Struct_construction_expression::do_traverse(Traverse* traverse)
16857 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
16858 return TRAVERSE_EXIT;
16859 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16860 return TRAVERSE_EXIT;
16861 return TRAVERSE_CONTINUE;
16864 // Return whether this is a constant initializer.
16866 bool
16867 Struct_construction_expression::is_constant_struct() const
16869 if (this->vals() == NULL)
16870 return true;
16871 for (Expression_list::const_iterator pv = this->vals()->begin();
16872 pv != this->vals()->end();
16873 ++pv)
16875 if (*pv != NULL
16876 && !(*pv)->is_constant()
16877 && (!(*pv)->is_composite_literal()
16878 || (*pv)->is_nonconstant_composite_literal()))
16879 return false;
16882 const Struct_field_list* fields = this->type_->struct_type()->fields();
16883 for (Struct_field_list::const_iterator pf = fields->begin();
16884 pf != fields->end();
16885 ++pf)
16887 // There are no constant constructors for interfaces.
16888 if (pf->type()->interface_type() != NULL)
16889 return false;
16892 return true;
16895 // Return whether this is a zero value.
16897 bool
16898 Struct_construction_expression::do_is_zero_value() const
16900 if (this->vals() == NULL)
16901 return true;
16902 for (Expression_list::const_iterator pv = this->vals()->begin();
16903 pv != this->vals()->end();
16904 ++pv)
16905 if (*pv != NULL && !(*pv)->is_zero_value())
16906 return false;
16908 const Struct_field_list* fields = this->type_->struct_type()->fields();
16909 for (Struct_field_list::const_iterator pf = fields->begin();
16910 pf != fields->end();
16911 ++pf)
16913 // Interface conversion may cause a zero value being converted
16914 // to a non-zero value, like interface{}(0). Be conservative.
16915 if (pf->type()->interface_type() != NULL)
16916 return false;
16919 return true;
16922 // Return whether this struct can be used as a constant initializer.
16924 bool
16925 Struct_construction_expression::do_is_static_initializer() const
16927 if (this->vals() == NULL)
16928 return true;
16929 for (Expression_list::const_iterator pv = this->vals()->begin();
16930 pv != this->vals()->end();
16931 ++pv)
16933 if (*pv != NULL && !(*pv)->is_static_initializer())
16934 return false;
16937 const Struct_field_list* fields = this->type_->struct_type()->fields();
16938 for (Struct_field_list::const_iterator pf = fields->begin();
16939 pf != fields->end();
16940 ++pf)
16942 // There are no constant constructors for interfaces.
16943 if (pf->type()->interface_type() != NULL)
16944 return false;
16947 return true;
16950 // Final type determination.
16952 void
16953 Struct_construction_expression::do_determine_type(Gogo* gogo,
16954 const Type_context*)
16956 if (this->vals() == NULL)
16957 return;
16958 const Struct_field_list* fields = this->type_->struct_type()->fields();
16959 Expression_list::const_iterator pv = this->vals()->begin();
16960 for (Struct_field_list::const_iterator pf = fields->begin();
16961 pf != fields->end();
16962 ++pf, ++pv)
16964 if (pv == this->vals()->end())
16965 return;
16966 if (*pv != NULL)
16968 Type_context subcontext(pf->type(), false);
16969 (*pv)->determine_type(gogo, &subcontext);
16972 // Extra values are an error we will report elsewhere; we still want
16973 // to determine the type to avoid knockon errors.
16974 for (; pv != this->vals()->end(); ++pv)
16975 (*pv)->determine_type_no_context(gogo);
16978 // Check types.
16980 void
16981 Struct_construction_expression::do_check_types(Gogo* gogo)
16983 Struct_construction_expression::check_value_types(gogo, this->type_,
16984 this->vals(),
16985 this->location());
16988 // Check types. This static function is also called by
16989 // Composite_literal_expression::do_check_types. Reports whether type
16990 // checking succeeded.
16992 bool
16993 Struct_construction_expression::check_value_types(Gogo* gogo,
16994 Type* type,
16995 Expression_list* vals,
16996 Location loc)
16998 if (vals == NULL || vals->empty())
16999 return true;
17001 Struct_type* st = type->struct_type();
17002 if (vals->size() > st->field_count())
17004 go_error_at(loc, "too many expressions for struct");
17005 return false;
17008 bool imported_type =
17009 (type->named_type() != NULL
17010 && type->named_type()->named_object()->package() != NULL);
17012 bool ret = true;
17013 const Struct_field_list* fields = st->fields();
17014 Expression_list::const_iterator pv = vals->begin();
17015 int i = 0;
17016 for (Struct_field_list::const_iterator pf = fields->begin();
17017 pf != fields->end();
17018 ++pf, ++pv, ++i)
17020 if (pv == vals->end())
17022 go_error_at(loc, "too few expressions for struct");
17023 return false;
17026 if (*pv == NULL)
17027 continue;
17029 if (imported_type
17030 && (Gogo::is_hidden_name(pf->field_name())
17031 || pf->is_embedded_builtin(gogo)))
17033 go_error_at(loc,
17034 "assignment of unexported field %qs in %qs literal",
17035 Gogo::message_name(pf->field_name()).c_str(),
17036 type->named_type()->message_name().c_str());
17037 ret = false;
17040 std::string reason;
17041 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
17043 if (reason.empty())
17044 go_error_at((*pv)->location(),
17045 "incompatible type for field %d in struct construction",
17046 i + 1);
17047 else
17048 go_error_at((*pv)->location(),
17049 ("incompatible type for field %d in "
17050 "struct construction (%s)"),
17051 i + 1, reason.c_str());
17052 ret = false;
17055 go_assert(pv == vals->end());
17056 return ret;
17059 // Copy.
17061 Expression*
17062 Struct_construction_expression::do_copy()
17064 Struct_construction_expression* ret =
17065 new Struct_construction_expression(this->type_->copy_expressions(),
17066 (this->vals() == NULL
17067 ? NULL
17068 : this->vals()->copy()),
17069 this->location());
17070 if (this->traverse_order() != NULL)
17071 ret->set_traverse_order(this->traverse_order());
17072 return ret;
17075 // Make implicit type conversions explicit.
17077 void
17078 Struct_construction_expression::do_add_conversions()
17080 if (this->vals() == NULL)
17081 return;
17083 Location loc = this->location();
17084 const Struct_field_list* fields = this->type_->struct_type()->fields();
17085 Expression_list::iterator pv = this->vals()->begin();
17086 for (Struct_field_list::const_iterator pf = fields->begin();
17087 pf != fields->end();
17088 ++pf, ++pv)
17090 if (pv == this->vals()->end())
17091 break;
17092 if (*pv != NULL)
17094 Type* ft = pf->type();
17095 if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
17096 && ft->interface_type() != NULL)
17097 *pv = Expression::make_cast(ft, *pv, loc);
17102 // Return the backend representation for constructing a struct.
17104 Bexpression*
17105 Struct_construction_expression::do_get_backend(Translate_context* context)
17107 Gogo* gogo = context->gogo();
17109 Btype* btype = this->type_->get_backend(gogo);
17110 if (this->vals() == NULL)
17111 return gogo->backend()->zero_expression(btype);
17113 const Struct_field_list* fields = this->type_->struct_type()->fields();
17114 Expression_list::const_iterator pv = this->vals()->begin();
17115 std::vector<Bexpression*> init;
17116 for (Struct_field_list::const_iterator pf = fields->begin();
17117 pf != fields->end();
17118 ++pf)
17120 Btype* fbtype = pf->type()->get_backend(gogo);
17121 if (pv == this->vals()->end())
17122 init.push_back(gogo->backend()->zero_expression(fbtype));
17123 else if (*pv == NULL)
17125 init.push_back(gogo->backend()->zero_expression(fbtype));
17126 ++pv;
17128 else
17130 Expression* val =
17131 Expression::convert_for_assignment(gogo, pf->type(),
17132 *pv, this->location());
17133 init.push_back(val->get_backend(context));
17134 ++pv;
17137 if (this->type_->struct_type()->has_padding())
17139 // Feed an extra value if there is a padding field.
17140 Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
17141 init.push_back(gogo->backend()->zero_expression(fbtype));
17143 return gogo->backend()->constructor_expression(btype, init, this->location());
17146 // Export a struct construction.
17148 void
17149 Struct_construction_expression::do_export(Export_function_body* efb) const
17151 efb->write_c_string("$convert(");
17152 efb->write_type(this->type_);
17153 for (Expression_list::const_iterator pv = this->vals()->begin();
17154 pv != this->vals()->end();
17155 ++pv)
17157 efb->write_c_string(", ");
17158 if (*pv != NULL)
17159 (*pv)->export_expression(efb);
17161 efb->write_c_string(")");
17164 // Dump ast representation of a struct construction expression.
17166 void
17167 Struct_construction_expression::do_dump_expression(
17168 Ast_dump_context* ast_dump_context) const
17170 ast_dump_context->dump_type(this->type_);
17171 ast_dump_context->ostream() << "{";
17172 ast_dump_context->dump_expression_list(this->vals());
17173 ast_dump_context->ostream() << "}";
17176 // Make a struct composite literal. This used by the thunk code.
17178 Expression*
17179 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
17180 Location location)
17182 go_assert(type->struct_type() != NULL);
17183 return new Struct_construction_expression(type, vals, location);
17186 // Class Array_construction_expression.
17188 // Traversal.
17191 Array_construction_expression::do_traverse(Traverse* traverse)
17193 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
17194 return TRAVERSE_EXIT;
17195 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17196 return TRAVERSE_EXIT;
17197 return TRAVERSE_CONTINUE;
17200 // Return whether this is a constant initializer.
17202 bool
17203 Array_construction_expression::is_constant_array() const
17205 if (this->vals() == NULL)
17206 return true;
17208 // There are no constant constructors for interfaces.
17209 if (this->type_->array_type()->element_type()->interface_type() != NULL)
17210 return false;
17212 for (Expression_list::const_iterator pv = this->vals()->begin();
17213 pv != this->vals()->end();
17214 ++pv)
17216 if (*pv != NULL
17217 && !(*pv)->is_constant()
17218 && (!(*pv)->is_composite_literal()
17219 || (*pv)->is_nonconstant_composite_literal()))
17220 return false;
17222 return true;
17225 // Return whether this is a zero value.
17227 bool
17228 Array_construction_expression::do_is_zero_value() const
17230 if (this->vals() == NULL)
17231 return true;
17233 // Interface conversion may cause a zero value being converted
17234 // to a non-zero value, like interface{}(0). Be conservative.
17235 if (this->type_->array_type()->element_type()->interface_type() != NULL)
17236 return false;
17238 for (Expression_list::const_iterator pv = this->vals()->begin();
17239 pv != this->vals()->end();
17240 ++pv)
17241 if (*pv != NULL && !(*pv)->is_zero_value())
17242 return false;
17244 return true;
17247 // Return whether this can be used a constant initializer.
17249 bool
17250 Array_construction_expression::do_is_static_initializer() const
17252 if (this->vals() == NULL)
17253 return true;
17255 // There are no constant constructors for interfaces.
17256 if (this->type_->array_type()->element_type()->interface_type() != NULL)
17257 return false;
17259 for (Expression_list::const_iterator pv = this->vals()->begin();
17260 pv != this->vals()->end();
17261 ++pv)
17263 if (*pv != NULL && !(*pv)->is_static_initializer())
17264 return false;
17266 return true;
17269 // Final type determination.
17271 void
17272 Array_construction_expression::do_determine_type(Gogo* gogo,
17273 const Type_context*)
17275 if (this->is_error_expression())
17277 go_assert(saw_errors());
17278 return;
17281 if (this->vals() == NULL)
17282 return;
17283 Array_type* at = this->type_->array_type();
17284 if (at == NULL || at->is_error() || at->element_type()->is_error())
17286 go_assert(saw_errors());
17287 this->set_is_error();
17288 return;
17290 Type_context subcontext(at->element_type(), false);
17291 for (Expression_list::const_iterator pv = this->vals()->begin();
17292 pv != this->vals()->end();
17293 ++pv)
17295 if (*pv != NULL)
17296 (*pv)->determine_type(gogo, &subcontext);
17300 // Check types.
17302 void
17303 Array_construction_expression::do_check_types(Gogo*)
17305 if (this->is_error_expression())
17307 go_assert(saw_errors());
17308 return;
17311 if (this->vals() == NULL)
17312 return;
17314 Array_type* at = this->type_->array_type();
17315 if (at == NULL || at->is_error() || at->element_type()->is_error())
17317 go_assert(saw_errors());
17318 this->set_is_error();
17319 return;
17321 int i = 0;
17322 Type* element_type = at->element_type();
17323 for (Expression_list::const_iterator pv = this->vals()->begin();
17324 pv != this->vals()->end();
17325 ++pv, ++i)
17327 if (*pv != NULL
17328 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
17330 go_error_at((*pv)->location(),
17331 "incompatible type for element %d in composite literal",
17332 i + 1);
17333 this->set_is_error();
17338 // Make implicit type conversions explicit.
17340 void
17341 Array_construction_expression::do_add_conversions()
17343 if (this->is_error_expression())
17345 go_assert(saw_errors());
17346 return;
17349 if (this->vals() == NULL)
17350 return;
17352 Type* et = this->type_->array_type()->element_type();
17353 if (et->interface_type() == NULL)
17354 return;
17356 Location loc = this->location();
17357 for (Expression_list::iterator pv = this->vals()->begin();
17358 pv != this->vals()->end();
17359 ++pv)
17360 if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
17361 *pv = Expression::make_cast(et, *pv, loc);
17364 // Get a constructor expression for the array values.
17366 Bexpression*
17367 Array_construction_expression::get_constructor(Translate_context* context,
17368 Btype* array_btype)
17370 Type* element_type = this->type_->array_type()->element_type();
17372 std::vector<unsigned long> indexes;
17373 std::vector<Bexpression*> vals;
17374 Gogo* gogo = context->gogo();
17375 if (this->vals() != NULL)
17377 size_t i = 0;
17378 std::vector<unsigned long>::const_iterator pi;
17379 if (this->indexes_ != NULL)
17380 pi = this->indexes_->begin();
17381 for (Expression_list::const_iterator pv = this->vals()->begin();
17382 pv != this->vals()->end();
17383 ++pv, ++i)
17385 if (this->indexes_ != NULL)
17386 go_assert(pi != this->indexes_->end());
17388 if (this->indexes_ == NULL)
17389 indexes.push_back(i);
17390 else
17391 indexes.push_back(*pi);
17392 if (*pv == NULL)
17394 Btype* ebtype = element_type->get_backend(gogo);
17395 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
17396 vals.push_back(zv);
17398 else
17400 Expression* val_expr =
17401 Expression::convert_for_assignment(gogo, element_type, *pv,
17402 this->location());
17403 vals.push_back(val_expr->get_backend(context));
17405 if (this->indexes_ != NULL)
17406 ++pi;
17408 if (this->indexes_ != NULL)
17409 go_assert(pi == this->indexes_->end());
17411 return gogo->backend()->array_constructor_expression(array_btype, indexes,
17412 vals, this->location());
17415 // Export an array construction.
17417 void
17418 Array_construction_expression::do_export(Export_function_body* efb) const
17420 efb->write_c_string("$convert(");
17421 efb->write_type(this->type_);
17422 if (this->vals() != NULL)
17424 std::vector<unsigned long>::const_iterator pi;
17425 if (this->indexes_ != NULL)
17426 pi = this->indexes_->begin();
17427 for (Expression_list::const_iterator pv = this->vals()->begin();
17428 pv != this->vals()->end();
17429 ++pv)
17431 efb->write_c_string(", ");
17433 if (this->indexes_ != NULL)
17435 char buf[100];
17436 snprintf(buf, sizeof buf, "%lu", *pi);
17437 efb->write_c_string(buf);
17438 efb->write_c_string(":");
17441 if (*pv != NULL)
17442 (*pv)->export_expression(efb);
17444 if (this->indexes_ != NULL)
17445 ++pi;
17448 efb->write_c_string(")");
17451 // Dump ast representation of an array construction expression.
17453 void
17454 Array_construction_expression::do_dump_expression(
17455 Ast_dump_context* ast_dump_context) const
17457 Expression* length = this->type_->array_type()->length();
17459 ast_dump_context->ostream() << "[" ;
17460 if (length != NULL)
17462 ast_dump_context->dump_expression(length);
17464 ast_dump_context->ostream() << "]" ;
17465 ast_dump_context->dump_type(this->type_);
17466 this->dump_slice_storage_expression(ast_dump_context);
17467 ast_dump_context->ostream() << "{" ;
17468 if (this->indexes_ == NULL)
17469 ast_dump_context->dump_expression_list(this->vals());
17470 else
17472 Expression_list::const_iterator pv = this->vals()->begin();
17473 for (std::vector<unsigned long>::const_iterator pi =
17474 this->indexes_->begin();
17475 pi != this->indexes_->end();
17476 ++pi, ++pv)
17478 if (pi != this->indexes_->begin())
17479 ast_dump_context->ostream() << ", ";
17480 ast_dump_context->ostream() << *pi << ':';
17481 ast_dump_context->dump_expression(*pv);
17484 ast_dump_context->ostream() << "}" ;
17488 // Class Fixed_array_construction_expression.
17490 Fixed_array_construction_expression::Fixed_array_construction_expression(
17491 Type* type, const std::vector<unsigned long>* indexes,
17492 Expression_list* vals, Location location)
17493 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
17494 type, indexes, vals, location)
17495 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
17498 // Copy.
17500 Expression*
17501 Fixed_array_construction_expression::do_copy()
17503 Type* t = this->type()->copy_expressions();
17504 return new Fixed_array_construction_expression(t, this->indexes(),
17505 (this->vals() == NULL
17506 ? NULL
17507 : this->vals()->copy()),
17508 this->location());
17511 // Return the backend representation for constructing a fixed array.
17513 Bexpression*
17514 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
17516 Type* type = this->type();
17517 Btype* btype = type->get_backend(context->gogo());
17518 return this->get_constructor(context, btype);
17521 Expression*
17522 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
17523 Location location)
17525 go_assert(type->array_type() != NULL && !type->is_slice_type());
17526 return new Fixed_array_construction_expression(type, NULL, vals, location);
17529 // Class Slice_construction_expression.
17531 Slice_construction_expression::Slice_construction_expression(
17532 Type* type, const std::vector<unsigned long>* indexes,
17533 Expression_list* vals, Location location)
17534 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
17535 type, indexes, vals, location),
17536 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
17537 storage_escapes_(true)
17539 go_assert(type->is_slice_type());
17541 unsigned long lenval;
17542 Expression* length;
17543 if (vals == NULL || vals->empty())
17544 lenval = 0;
17545 else
17547 if (this->indexes() == NULL)
17548 lenval = vals->size();
17549 else
17550 lenval = indexes->back() + 1;
17552 Type* int_type = Type::lookup_integer_type("int");
17553 length = Expression::make_integer_ul(lenval, int_type, location);
17554 Type* element_type = type->array_type()->element_type();
17555 Array_type* array_type = Type::make_array_type(element_type, length);
17556 array_type->set_is_array_incomparable();
17557 this->valtype_ = array_type;
17560 // Traversal.
17563 Slice_construction_expression::do_traverse(Traverse* traverse)
17565 if (this->Array_construction_expression::do_traverse(traverse)
17566 == TRAVERSE_EXIT)
17567 return TRAVERSE_EXIT;
17568 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
17569 return TRAVERSE_EXIT;
17570 if (this->array_val_ != NULL
17571 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
17572 return TRAVERSE_EXIT;
17573 if (this->slice_storage_ != NULL
17574 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
17575 return TRAVERSE_EXIT;
17576 return TRAVERSE_CONTINUE;
17579 // Helper routine to create fixed array value underlying the slice literal.
17580 // May be called during flattening, or later during do_get_backend().
17582 Expression*
17583 Slice_construction_expression::create_array_val()
17585 Array_type* array_type = this->type()->array_type();
17586 if (array_type == NULL)
17588 go_assert(this->type()->is_error());
17589 return NULL;
17592 Location loc = this->location();
17593 go_assert(this->valtype_ != NULL);
17595 Expression_list* vals = this->vals();
17596 return new Fixed_array_construction_expression(
17597 this->valtype_, this->indexes(), vals, loc);
17600 // If we're previous established that the slice storage does not
17601 // escape, then create a separate array temp val here for it. We
17602 // need to do this as part of flattening so as to be able to insert
17603 // the new temp statement.
17605 Expression*
17606 Slice_construction_expression::do_flatten(Gogo*, Named_object*,
17607 Statement_inserter* inserter)
17609 if (this->type()->array_type() == NULL)
17611 go_assert(saw_errors());
17612 return Expression::make_error(this->location());
17615 // Create a stack-allocated storage temp if storage won't escape
17616 if (!this->storage_escapes_
17617 && this->slice_storage_ == NULL
17618 && this->element_count() > 0)
17620 Location loc = this->location();
17621 this->array_val_ = this->create_array_val();
17622 go_assert(this->array_val_ != NULL);
17623 Temporary_statement* temp =
17624 Statement::make_temporary(this->valtype_, this->array_val_, loc);
17625 inserter->insert(temp);
17626 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
17628 return this;
17631 // When dumping a slice construction expression that has an explicit
17632 // storeage temp, emit the temp here (if we don't do this the storage
17633 // temp appears unused in the AST dump).
17635 void
17636 Slice_construction_expression::
17637 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
17639 if (this->slice_storage_ == NULL)
17640 return;
17641 ast_dump_context->ostream() << "storage=" ;
17642 ast_dump_context->dump_expression(this->slice_storage_);
17645 // Copy.
17647 Expression*
17648 Slice_construction_expression::do_copy()
17650 return new Slice_construction_expression(this->type()->copy_expressions(),
17651 this->indexes(),
17652 (this->vals() == NULL
17653 ? NULL
17654 : this->vals()->copy()),
17655 this->location());
17658 // Return the backend representation for constructing a slice.
17660 Bexpression*
17661 Slice_construction_expression::do_get_backend(Translate_context* context)
17663 if (this->array_val_ == NULL)
17664 this->array_val_ = this->create_array_val();
17665 if (this->array_val_ == NULL)
17667 go_assert(this->type()->is_error());
17668 return context->backend()->error_expression();
17671 Location loc = this->location();
17673 bool is_static_initializer = this->array_val_->is_static_initializer();
17675 // We have to copy the initial values into heap memory if we are in
17676 // a function or if the values are not constants.
17677 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
17679 Expression* space;
17681 if (this->slice_storage_ != NULL)
17683 go_assert(!this->storage_escapes_);
17684 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
17686 else if (!copy_to_heap)
17688 // The initializer will only run once.
17689 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
17690 space->unary_expression()->set_is_slice_init();
17692 else
17694 go_assert(this->storage_escapes_ || this->element_count() == 0);
17695 space = Expression::make_heap_expression(this->array_val_, loc);
17697 Array_type* at = this->valtype_->array_type();
17698 Type* et = at->element_type();
17699 space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
17700 space, loc);
17702 // Build a constructor for the slice.
17703 Expression* len = at->length();
17704 Expression* slice_val =
17705 Expression::make_slice_value(this->type(), space, len, len, loc);
17706 return slice_val->get_backend(context);
17709 // Make a slice composite literal. This is used by the type
17710 // descriptor code.
17712 Slice_construction_expression*
17713 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
17714 Location location)
17716 go_assert(type->is_slice_type());
17717 return new Slice_construction_expression(type, NULL, vals, location);
17720 // Class Map_construction_expression.
17722 // Traversal.
17725 Map_construction_expression::do_traverse(Traverse* traverse)
17727 if (this->vals_ != NULL
17728 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
17729 return TRAVERSE_EXIT;
17730 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17731 return TRAVERSE_EXIT;
17732 return TRAVERSE_CONTINUE;
17735 void
17736 Map_construction_expression::do_determine_type(Gogo* gogo, const Type_context*)
17738 Map_type* mt = this->type_->map_type();
17739 go_assert(mt != NULL);
17740 Type_context key_context(mt->key_type(), false);
17741 Type_context val_context(mt->val_type(), false);
17742 if (this->vals_ != NULL)
17744 for (Expression_list::const_iterator pv = this->vals_->begin();
17745 pv != this->vals_->end();
17746 ++pv)
17748 (*pv)->determine_type(gogo, &key_context);
17749 ++pv;
17750 (*pv)->determine_type(gogo, &val_context);
17755 void
17756 Map_construction_expression::do_check_types(Gogo*)
17758 // Types should have been checked before this was created, so this
17759 // will probably never be called. Check it anyhow to be sure.
17761 if (this->vals_ == NULL)
17762 return;
17764 Map_type* mt = this->type_->map_type();
17765 go_assert(mt != NULL);
17766 Type* key_type = mt->key_type();
17767 Type* val_type = mt->val_type();
17768 for (Expression_list::const_iterator pv = this->vals_->begin();
17769 pv != this->vals_->end();
17770 ++pv)
17772 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
17774 go_error_at((*pv)->location(),
17775 "incompatible type for key in map composite literal");
17776 this->set_is_error();
17778 ++pv;
17779 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
17781 go_error_at((*pv)->location(),
17782 "incompatible type for value in map composite literal");
17783 this->set_is_error();
17788 // Flatten constructor initializer into a temporary variable since
17789 // we need to take its address for __go_construct_map.
17791 Expression*
17792 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
17793 Statement_inserter* inserter)
17795 if (!this->is_error_expression()
17796 && this->vals_ != NULL
17797 && !this->vals_->empty()
17798 && this->constructor_temp_ == NULL)
17800 Map_type* mt = this->type_->map_type();
17801 Type* key_type = mt->key_type();
17802 Type* val_type = mt->val_type();
17803 this->element_type_ = Type::make_builtin_struct_type(2,
17804 "__key", key_type,
17805 "__val", val_type);
17807 Expression_list* value_pairs = new Expression_list();
17808 Location loc = this->location();
17810 size_t i = 0;
17811 for (Expression_list::const_iterator pv = this->vals_->begin();
17812 pv != this->vals_->end();
17813 ++pv, ++i)
17815 Expression_list* key_value_pair = new Expression_list();
17816 Expression* key = *pv;
17817 if (key->is_error_expression() || key->type()->is_error_type())
17819 go_assert(saw_errors());
17820 return Expression::make_error(loc);
17822 if (key->type()->interface_type() != NULL
17823 && !key->is_multi_eval_safe())
17825 Temporary_statement* temp =
17826 Statement::make_temporary(NULL, key, loc);
17827 inserter->insert(temp);
17828 key = Expression::make_temporary_reference(temp, loc);
17830 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
17832 ++pv;
17833 Expression* val = *pv;
17834 if (val->is_error_expression() || val->type()->is_error_type())
17836 go_assert(saw_errors());
17837 return Expression::make_error(loc);
17839 if (val->type()->interface_type() != NULL
17840 && !val->is_multi_eval_safe())
17842 Temporary_statement* temp =
17843 Statement::make_temporary(NULL, val, loc);
17844 inserter->insert(temp);
17845 val = Expression::make_temporary_reference(temp, loc);
17847 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
17849 key_value_pair->push_back(key);
17850 key_value_pair->push_back(val);
17851 value_pairs->push_back(
17852 Expression::make_struct_composite_literal(this->element_type_,
17853 key_value_pair, loc));
17856 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
17857 Array_type* ctor_type =
17858 Type::make_array_type(this->element_type_, element_count);
17859 ctor_type->set_is_array_incomparable();
17860 Expression* constructor =
17861 new Fixed_array_construction_expression(ctor_type, NULL,
17862 value_pairs, loc);
17864 this->constructor_temp_ =
17865 Statement::make_temporary(NULL, constructor, loc);
17866 constructor->issue_nil_check();
17867 this->constructor_temp_->set_is_address_taken();
17868 this->constructor_temp_->determine_types(gogo);
17869 inserter->insert(this->constructor_temp_);
17872 return this;
17875 // Copy.
17877 Expression*
17878 Map_construction_expression::do_copy()
17880 return new Map_construction_expression(this->type_->copy_expressions(),
17881 (this->vals_ == NULL
17882 ? NULL
17883 : this->vals_->copy()),
17884 this->location());
17887 // Make implicit type conversions explicit.
17889 void
17890 Map_construction_expression::do_add_conversions()
17892 if (this->vals_ == NULL || this->vals_->empty())
17893 return;
17895 Map_type* mt = this->type_->map_type();
17896 Type* kt = mt->key_type();
17897 Type* vt = mt->val_type();
17898 bool key_is_interface = (kt->interface_type() != NULL);
17899 bool val_is_interface = (vt->interface_type() != NULL);
17900 if (!key_is_interface && !val_is_interface)
17901 return;
17903 Location loc = this->location();
17904 for (Expression_list::iterator pv = this->vals_->begin();
17905 pv != this->vals_->end();
17906 ++pv)
17908 if (key_is_interface &&
17909 !Type::are_identical(kt, (*pv)->type(), 0, NULL))
17910 *pv = Expression::make_cast(kt, *pv, loc);
17911 ++pv;
17912 if (val_is_interface &&
17913 !Type::are_identical(vt, (*pv)->type(), 0, NULL))
17914 *pv = Expression::make_cast(vt, *pv, loc);
17918 // Return the backend representation for constructing a map.
17920 Bexpression*
17921 Map_construction_expression::do_get_backend(Translate_context* context)
17923 if (this->is_error_expression())
17924 return context->backend()->error_expression();
17925 Location loc = this->location();
17927 size_t i = 0;
17928 Expression* ventries;
17929 if (this->vals_ == NULL || this->vals_->empty())
17930 ventries = Expression::make_nil(loc);
17931 else
17933 go_assert(this->constructor_temp_ != NULL);
17934 i = this->vals_->size() / 2;
17936 Expression* ctor_ref =
17937 Expression::make_temporary_reference(this->constructor_temp_, loc);
17938 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
17941 Map_type* mt = this->type_->map_type();
17942 if (this->element_type_ == NULL)
17943 this->element_type_ =
17944 Type::make_builtin_struct_type(2,
17945 "__key", mt->key_type(),
17946 "__val", mt->val_type());
17947 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
17949 Type* uintptr_t = Type::lookup_integer_type("uintptr");
17950 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
17952 Expression* entry_size =
17953 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
17955 unsigned int field_index;
17956 const Struct_field* valfield =
17957 this->element_type_->find_local_field("__val", &field_index);
17958 Expression* val_offset =
17959 Expression::make_struct_field_offset(this->element_type_, valfield);
17961 Gogo* gogo = context->gogo();
17962 Expression* map_ctor =
17963 Runtime::make_call(gogo, Runtime::CONSTRUCT_MAP, loc, 5,
17964 descriptor, count, entry_size, val_offset, ventries);
17965 map_ctor->determine_type_no_context(gogo);
17966 return map_ctor->get_backend(context);
17969 // Export an array construction.
17971 void
17972 Map_construction_expression::do_export(Export_function_body* efb) const
17974 efb->write_c_string("$convert(");
17975 efb->write_type(this->type_);
17976 for (Expression_list::const_iterator pv = this->vals_->begin();
17977 pv != this->vals_->end();
17978 ++pv)
17980 efb->write_c_string(", ");
17981 (*pv)->export_expression(efb);
17983 efb->write_c_string(")");
17986 // Dump ast representation for a map construction expression.
17988 void
17989 Map_construction_expression::do_dump_expression(
17990 Ast_dump_context* ast_dump_context) const
17992 ast_dump_context->ostream() << "{" ;
17993 ast_dump_context->dump_expression_list(this->vals_, true);
17994 ast_dump_context->ostream() << "}";
17997 // A composite literal key. This is seen during parsing, but is not
17998 // resolved to a named_object in case this is a composite literal of
17999 // struct type.
18001 class Composite_literal_key_expression : public Parser_expression
18003 public:
18004 Composite_literal_key_expression(const std::string& name, Location location)
18005 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
18006 name_(name), expr_(NULL)
18009 const std::string&
18010 name() const
18011 { return this->name_; }
18013 protected:
18014 Type*
18015 do_type();
18017 void
18018 do_determine_type(Gogo*, const Type_context*);
18020 Expression*
18021 do_lower(Gogo*, Named_object*, Statement_inserter*);
18023 Expression*
18024 do_copy()
18026 return new Composite_literal_key_expression(this->name_, this->location());
18029 void
18030 do_dump_expression(Ast_dump_context*) const;
18032 private:
18033 // The name.
18034 std::string name_;
18035 // After we look up the name, a corresponding expression.
18036 Expression* expr_;
18039 // Determine the type of a composite literal key. We will never get
18040 // here for keys in composite literals of struct types, because they
18041 // will be handled by Composite_literal_expression::do_determine_type.
18042 // So if we get here, this must be a regular name reference after all.
18044 void
18045 Composite_literal_key_expression::do_determine_type(
18046 Gogo* gogo,
18047 const Type_context* context)
18049 if (this->expr_ != NULL)
18051 // Already resolved.
18052 return;
18055 Named_object* no = gogo->lookup(this->name_, NULL);
18056 if (no == NULL)
18058 // Gogo::lookup doesn't look in the global namespace, and names
18059 // used in composite literal keys aren't seen by
18060 // Gogo::define_global_names, so we have to look in the global
18061 // namespace ourselves.
18062 no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
18063 if (no == NULL)
18065 go_error_at(this->location(), "reference to undefined name %qs",
18066 Gogo::message_name(this->name_).c_str());
18067 this->set_is_error();
18068 return;
18072 this->expr_ = Expression::make_unknown_reference(no, this->location());
18073 this->expr_->determine_type(gogo, context);
18076 Type*
18077 Composite_literal_key_expression::do_type()
18079 if (this->is_error_expression())
18080 return Type::make_error_type();
18081 go_assert(this->expr_ != NULL);
18082 return this->expr_->type();
18085 Expression*
18086 Composite_literal_key_expression::do_lower(Gogo*, Named_object*,
18087 Statement_inserter*)
18089 if (this->is_error_expression())
18090 return Expression::make_error(this->location());
18091 go_assert(this->expr_ != NULL);
18092 return this->expr_;
18095 // Dump a composite literal key.
18097 void
18098 Composite_literal_key_expression::do_dump_expression(
18099 Ast_dump_context* ast_dump_context) const
18101 ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
18104 // Make a composite literal key.
18106 Expression*
18107 Expression::make_composite_literal_key(const std::string& name,
18108 Location location)
18110 return new Composite_literal_key_expression(name, location);
18113 // Class Composite_literal_expression.
18115 // Traversal.
18118 Composite_literal_expression::do_traverse(Traverse* traverse)
18120 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18121 return TRAVERSE_EXIT;
18123 // If this is a struct composite literal with keys, then the keys
18124 // are field names, not expressions. We don't want to traverse them
18125 // in that case. If we do, we can give an erroneous error "variable
18126 // initializer refers to itself." See bug482.go in the testsuite.
18127 if (this->has_keys_ && this->vals_ != NULL)
18129 // The type may not be resolvable at this point.
18130 Type* type = this->type_;
18132 for (int depth = 0; depth < this->depth_; ++depth)
18134 type = type->deref();
18135 if (type->array_type() != NULL)
18136 type = type->array_type()->element_type();
18137 else if (type->map_type() != NULL)
18139 if (this->key_path_[depth])
18140 type = type->map_type()->key_type();
18141 else
18142 type = type->map_type()->val_type();
18144 else
18146 // This error will be reported during lowering.
18147 return TRAVERSE_CONTINUE;
18150 type = type->deref();
18152 while (true)
18154 if (type->classification() == Type::TYPE_NAMED)
18155 type = type->named_type()->real_type();
18156 else if (type->classification() == Type::TYPE_FORWARD)
18158 Type* t = type->forwarded();
18159 if (t == type)
18160 break;
18161 type = t;
18163 else
18164 break;
18167 if (type->classification() == Type::TYPE_STRUCT)
18169 Expression_list::iterator p = this->vals_->begin();
18170 while (p != this->vals_->end())
18172 // Skip key.
18173 ++p;
18174 go_assert(p != this->vals_->end());
18175 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
18176 return TRAVERSE_EXIT;
18177 ++p;
18179 return TRAVERSE_CONTINUE;
18183 if (this->vals_ != NULL)
18184 return this->vals_->traverse(traverse);
18186 return TRAVERSE_CONTINUE;
18189 void
18190 Composite_literal_expression::do_determine_type(Gogo* gogo,
18191 const Type_context*)
18193 // Resolve the type if this composite literal is within another
18194 // composite literal and has omitted the type. The DEPTH_ field
18195 // tells us how deeply this one is embedded.
18196 Type* type = this->type_;
18197 for (int depth = 0; depth < this->depth_; ++depth)
18199 type = type->deref();
18200 if (type->array_type() != NULL)
18201 type = type->array_type()->element_type();
18202 else if (type->map_type() != NULL)
18204 if (this->key_path_[depth])
18205 type = type->map_type()->key_type();
18206 else
18207 type = type->map_type()->val_type();
18209 else
18211 if (!type->is_error())
18212 this->report_error(_("may only omit types within composite "
18213 "literals of slice, array, or map type"));
18214 else
18216 go_assert(saw_errors());
18217 this->set_is_error();
18219 return;
18223 this->type_ = type;
18224 this->depth_ = 0;
18226 type = type->deref();
18228 if (this->vals_ == NULL || this->vals_->empty())
18230 // No value types to determine.
18231 if (type->array_type() != NULL
18232 && type->array_type()->length() != NULL
18233 && type->array_type()->length()->is_nil_expression())
18234 this->resolve_array_length(type);
18235 return;
18238 if (type->struct_type() != NULL && this->has_keys_)
18240 // Rewrite the value list by removing the struct field keys. We
18241 // do this now rather than during lowering because handling
18242 // struct keys is painful. We don't need to do this for
18243 // slice/array/map literals, because it's easy to determine
18244 // their types with or without the keys.
18245 if (!this->resolve_struct_keys(gogo, type))
18247 this->set_is_error();
18248 delete this->vals_;
18249 this->vals_ = NULL;
18250 this->has_keys_ = false;
18251 return;
18255 if (type->struct_type() != NULL)
18257 const Struct_field_list* fields = type->struct_type()->fields();
18258 Expression_list::const_iterator pv = this->vals_->begin();
18259 for (Struct_field_list::const_iterator pf = fields->begin();
18260 pf != fields->end();
18261 ++pf, ++pv)
18263 if (pv == this->vals_->end())
18264 return;
18265 if (*pv != NULL)
18267 Type_context subcontext(pf->type(), false);
18268 (*pv)->determine_type(gogo, &subcontext);
18271 // Extra values are an error we will report in the check_types
18272 // pass; we still want to determine the type to avoid knockon
18273 // errors.
18274 for (; pv != this->vals_->end(); ++pv)
18275 (*pv)->determine_type_no_context(gogo);
18277 else if (type->array_type() != NULL)
18279 Array_type* at = type->array_type();
18280 Type_context intcontext(Type::lookup_integer_type("int"), false);
18281 Type_context subcontext(at->element_type(), false);
18282 for (Expression_list::const_iterator pv = this->vals_->begin();
18283 pv != this->vals_->end();
18284 ++pv)
18286 if (this->has_keys_)
18288 if (*pv != NULL)
18289 (*pv)->determine_type(gogo, &intcontext);
18290 ++pv;
18291 if (pv == this->vals_->end())
18292 break;
18295 if (*pv != NULL)
18296 (*pv)->determine_type(gogo, &subcontext);
18299 if (at->length() != NULL && at->length()->is_nil_expression())
18300 this->resolve_array_length(type);
18302 else if (type->map_type() != NULL)
18304 if (!this->has_keys_)
18306 this->report_error(_("map composite literal must have keys"));
18307 return;
18310 Map_type* mt = type->map_type();
18311 Type_context key_context(mt->key_type(), false);
18312 Type_context val_context(mt->val_type(), false);
18313 for (Expression_list::const_iterator pv = this->vals_->begin();
18314 pv != this->vals_->end();
18315 ++pv)
18317 if (*pv != NULL)
18318 (*pv)->determine_type(gogo, &key_context);
18319 ++pv;
18320 if (*pv != NULL)
18321 (*pv)->determine_type(gogo, &val_context);
18324 else
18326 // We'll report this as an error in the check_types pass.
18327 // Determine types to avoid knockon errors.
18328 for (Expression_list::const_iterator pv = this->vals_->begin();
18329 pv != this->vals_->end();
18330 ++pv)
18332 if (*pv != NULL)
18333 (*pv)->determine_type_no_context(gogo);
18338 Type*
18339 Composite_literal_expression::do_type()
18341 if (this->is_error_expression())
18342 return Type::make_error_type();
18343 go_assert(this->depth_ == 0);
18344 return this->type_;
18347 // Resolve the field keys of a struct composite literal.
18349 bool
18350 Composite_literal_expression::resolve_struct_keys(Gogo* gogo, Type* type)
18352 Struct_type* st = type->struct_type();
18353 size_t field_count = st->field_count();
18354 std::vector<Expression*> vals(field_count);
18355 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
18356 Expression_list::const_iterator p = this->vals_->begin();
18357 Expression* external_expr = NULL;
18358 const Named_object* external_no = NULL;
18359 while (p != this->vals_->end())
18361 Expression* name_expr = *p;
18363 ++p;
18364 go_assert(p != this->vals_->end());
18365 Expression* val = *p;
18367 ++p;
18369 if (name_expr == NULL)
18371 go_error_at(val->location(),
18372 "mixture of field and value initializers");
18373 return false;
18376 bool bad_key = false;
18377 std::string name;
18378 const Named_object* no = NULL;
18379 switch (name_expr->classification())
18381 case EXPRESSION_COMPOSITE_LITERAL_KEY:
18382 name =
18383 static_cast<Composite_literal_key_expression*>(name_expr)->name();
18384 break;
18386 case EXPRESSION_UNKNOWN_REFERENCE:
18387 name = name_expr->unknown_expression()->name();
18388 if (type->named_type() != NULL)
18390 // If the named object found for this field name comes from a
18391 // different package than the struct it is a part of, do not count
18392 // this incorrect lookup as a usage of the object's package.
18393 no = name_expr->unknown_expression()->named_object();
18394 if (no->package() != NULL
18395 && (no->package()
18396 != type->named_type()->named_object()->package()))
18397 no->package()->forget_usage(name_expr);
18399 break;
18401 case EXPRESSION_CONST_REFERENCE:
18402 no = static_cast<Const_expression*>(name_expr)->named_object();
18403 break;
18405 case EXPRESSION_TYPE:
18407 Type* t = name_expr->type();
18408 Named_type* nt = t->named_type();
18409 if (nt == NULL)
18410 bad_key = true;
18411 else
18412 no = nt->named_object();
18414 break;
18416 case EXPRESSION_VAR_REFERENCE:
18417 no = name_expr->var_expression()->named_object();
18418 break;
18420 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
18421 no = name_expr->enclosed_var_expression()->variable();
18422 break;
18424 case EXPRESSION_FUNC_REFERENCE:
18425 no = name_expr->func_expression()->named_object();
18426 break;
18428 default:
18429 bad_key = true;
18430 break;
18432 if (bad_key)
18434 go_error_at(name_expr->location(), "expected struct field name");
18435 return false;
18438 if (no != NULL)
18440 if (no->package() != NULL && external_expr == NULL)
18442 external_expr = name_expr;
18443 external_no = no;
18446 name = no->name();
18448 // A predefined name won't be packed. If it starts with a
18449 // lower case letter we need to check for that case, because
18450 // the field name will be packed. FIXME.
18451 if (!Gogo::is_hidden_name(name)
18452 && name[0] >= 'a'
18453 && name[0] <= 'z')
18455 Named_object* gno = gogo->lookup_global(name.c_str());
18456 if (gno == no)
18457 name = gogo->pack_hidden_name(name, false);
18461 unsigned int index;
18462 const Struct_field* sf = st->find_local_field(name, &index);
18463 if (sf == NULL)
18465 go_error_at(name_expr->location(), "unknown field %qs in %qs",
18466 Gogo::message_name(name).c_str(),
18467 (type->named_type() != NULL
18468 ? type->named_type()->message_name().c_str()
18469 : "unnamed struct"));
18470 return false;
18472 if (vals[index] != NULL)
18474 go_error_at(name_expr->location(),
18475 "duplicate value for field %qs in %qs",
18476 Gogo::message_name(name).c_str(),
18477 (type->named_type() != NULL
18478 ? type->named_type()->message_name().c_str()
18479 : "unnamed struct"));
18480 return false;
18483 vals[index] = val;
18484 traverse_order->push_back(static_cast<unsigned long>(index));
18487 if (!this->all_are_names_)
18489 // This is a weird case like bug462 in the testsuite.
18490 if (external_expr == NULL)
18491 go_error_at(this->location(), "unknown field in %qs literal",
18492 (type->named_type() != NULL
18493 ? type->named_type()->message_name().c_str()
18494 : "unnamed struct"));
18495 else
18496 go_error_at(external_expr->location(), "unknown field %qs in %qs",
18497 external_no->message_name().c_str(),
18498 (type->named_type() != NULL
18499 ? type->named_type()->message_name().c_str()
18500 : "unnamed struct"));
18501 return false;
18504 Expression_list* list = new Expression_list;
18505 list->reserve(field_count);
18506 for (size_t i = 0; i < field_count; ++i)
18507 list->push_back(vals[i]);
18509 this->vals_ = list;
18510 this->traverse_order_ = traverse_order;
18511 this->has_keys_ = false;
18513 return true;
18516 // Handle [...]{...}
18518 void
18519 Composite_literal_expression::resolve_array_length(Type* type)
18521 size_t size;
18522 if (this->vals_ == NULL || this->vals_->empty())
18523 size = 0;
18524 else if (!this->has_keys_)
18525 size = this->vals_->size();
18526 else
18528 unsigned long index = 0;
18529 size = 0;
18530 for (Expression_list::const_iterator pv = this->vals_->begin();
18531 pv != this->vals_->end();
18532 pv += 2)
18534 Expression* index_expr = *pv;
18535 if (index_expr != NULL)
18537 Numeric_constant nc;
18538 unsigned long iv;
18539 if (!index_expr->numeric_constant_value(&nc)
18540 || nc.to_unsigned_long(&iv) != Numeric_constant::NC_UL_VALID)
18542 // We will report an error when lowering.
18543 break;
18545 index = iv;
18548 if (index >= size)
18549 size = index + 1;
18551 ++index;
18555 Expression* elen = Expression::make_integer_ul(size, NULL, this->location());
18556 this->type_ = Type::make_array_type(type->array_type()->element_type(),
18557 elen);
18560 void
18561 Composite_literal_expression::do_check_types(Gogo* gogo)
18563 if (this->is_error_expression() || this->type_->is_error())
18565 go_assert(saw_errors());
18566 return;
18568 go_assert(this->depth_ == 0);
18570 Type* type = this->type_->deref();
18571 if (type->struct_type() != NULL)
18573 go_assert(!this->has_keys_);
18574 if (!Struct_construction_expression::check_value_types(gogo, type,
18575 this->vals_,
18576 this->location()))
18577 this->set_is_error();
18579 else if (type->array_type() != NULL)
18581 Type* element_type = type->array_type()->element_type();
18582 if (element_type->is_error())
18584 go_assert(saw_errors());
18585 return;
18587 if (this->vals_ == NULL || this->vals_->empty())
18588 return;
18589 int i = 0;
18590 for (Expression_list::const_iterator pv = this->vals_->begin();
18591 pv != this->vals_->end();
18592 ++pv, ++i)
18594 if (this->has_keys_)
18596 // We check the key type in the lowering pass.
18597 ++pv;
18598 if (pv == this->vals_->end())
18599 break;
18601 if (*pv != NULL
18602 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
18604 go_error_at((*pv)->location(),
18605 ("incompatible type for element %d "
18606 "in composite literal"),
18607 i + 1);
18608 this->set_is_error();
18612 else if (type->map_type() != NULL)
18614 if (this->vals_ == NULL || this->vals_->empty())
18615 return;
18616 if (!this->has_keys_)
18618 this->report_error(_("map composite literal must have keys"));
18619 return;
18621 int i = 0;
18622 Map_type* mt = type->map_type();
18623 Type* key_type = mt->key_type();
18624 Type* val_type = mt->val_type();
18625 for (Expression_list::const_iterator pv = this->vals_->begin();
18626 pv != this->vals_->end();
18627 ++pv, ++i)
18629 if (*pv != NULL
18630 && !Type::are_assignable(key_type, (*pv)->type(), NULL))
18632 go_error_at((*pv)->location(),
18633 ("incompatible type for element %d key "
18634 "in map construction"),
18635 i + 1);
18636 this->set_is_error();
18638 ++pv;
18639 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
18641 go_error_at((*pv)->location(),
18642 ("incompatible type for element %d value "
18643 "in map construction"),
18644 i + 1);
18645 this->set_is_error();
18649 else
18651 this->report_error(_("expected struct, slice, array, or map type "
18652 "for composite literal"));
18656 // Lower a generic composite literal into a specific version based on
18657 // the type.
18659 Expression*
18660 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
18661 Statement_inserter* inserter)
18663 if (this->is_error_expression() || this->type_->is_error())
18664 return Expression::make_error(this->location());
18665 go_assert(this->depth_ == 0);
18667 Type* type = this->type_;
18668 Type *pt = type->points_to();
18669 bool is_pointer = false;
18670 if (pt != NULL)
18672 is_pointer = true;
18673 type = pt;
18676 Expression* ret;
18677 if (type->is_error())
18678 return Expression::make_error(this->location());
18679 else if (type->struct_type() != NULL)
18680 ret = this->lower_struct(type);
18681 else if (type->array_type() != NULL)
18682 ret = this->lower_array(type);
18683 else if (type->map_type() != NULL)
18684 ret = this->lower_map(gogo, function, inserter, type);
18685 else
18686 go_unreachable();
18688 if (is_pointer)
18689 ret = Expression::make_heap_expression(ret, this->location());
18691 return ret;
18694 // Lower a struct composite literal.
18696 Expression*
18697 Composite_literal_expression::lower_struct(Type* type)
18699 go_assert(!this->has_keys_);
18700 Struct_construction_expression* ret =
18701 new Struct_construction_expression(type, this->vals_, this->location());
18702 ret->set_traverse_order(this->traverse_order_);
18703 return ret;
18706 // Index/value/traversal-order triple.
18708 struct IVT_triple {
18709 unsigned long index;
18710 unsigned long traversal_order;
18711 Expression* expr;
18712 IVT_triple(unsigned long i, unsigned long to, Expression *e)
18713 : index(i), traversal_order(to), expr(e) { }
18714 bool operator<(const IVT_triple& other) const
18715 { return this->index < other.index; }
18718 // Lower an array composite literal.
18720 Expression*
18721 Composite_literal_expression::lower_array(Type* type)
18723 Location location = this->location();
18724 if (this->vals_ == NULL || !this->has_keys_)
18725 return this->make_array(type, NULL, this->vals_);
18727 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
18728 indexes->reserve(this->vals_->size());
18729 bool indexes_out_of_order = false;
18730 Expression_list* vals = new Expression_list();
18731 vals->reserve(this->vals_->size());
18732 unsigned long index = 0;
18733 Expression_list::const_iterator p = this->vals_->begin();
18734 while (p != this->vals_->end())
18736 Expression* index_expr = *p;
18738 ++p;
18739 go_assert(p != this->vals_->end());
18740 Expression* val = *p;
18742 ++p;
18744 if (index_expr == NULL)
18746 if (std::find(indexes->begin(), indexes->end(), index)
18747 != indexes->end())
18749 go_error_at(val->location(),
18750 "duplicate value for index %lu", index);
18751 return Expression::make_error(location);
18753 if (!indexes->empty())
18754 indexes->push_back(index);
18756 else
18758 if (indexes->empty() && !vals->empty())
18760 for (size_t i = 0; i < vals->size(); ++i)
18761 indexes->push_back(i);
18764 Numeric_constant nc;
18765 if (!index_expr->numeric_constant_value(&nc))
18767 go_error_at(index_expr->location(),
18768 "index expression is not integer constant");
18769 return Expression::make_error(location);
18772 switch (nc.to_unsigned_long(&index))
18774 case Numeric_constant::NC_UL_VALID:
18775 break;
18776 case Numeric_constant::NC_UL_NOTINT:
18777 go_error_at(index_expr->location(),
18778 "index expression is not integer constant");
18779 return Expression::make_error(location);
18780 case Numeric_constant::NC_UL_NEGATIVE:
18781 go_error_at(index_expr->location(),
18782 "index expression is negative");
18783 return Expression::make_error(location);
18784 case Numeric_constant::NC_UL_BIG:
18785 go_error_at(index_expr->location(), "index value overflow");
18786 return Expression::make_error(location);
18787 default:
18788 go_unreachable();
18791 Named_type* ntype = Type::lookup_integer_type("int");
18792 Integer_type* inttype = ntype->integer_type();
18793 if (sizeof(index) >= static_cast<size_t>(inttype->bits() / 8)
18794 && index >> (inttype->bits() - 1) != 0)
18796 go_error_at(index_expr->location(), "index value overflow");
18797 return Expression::make_error(location);
18800 if (std::find(indexes->begin(), indexes->end(), index)
18801 != indexes->end())
18803 go_error_at(index_expr->location(),
18804 "duplicate value for index %lu",
18805 index);
18806 return Expression::make_error(location);
18809 if (!indexes->empty() && index < indexes->back())
18810 indexes_out_of_order = true;
18812 indexes->push_back(index);
18815 vals->push_back(val);
18817 ++index;
18820 if (indexes->empty())
18822 delete indexes;
18823 indexes = NULL;
18826 std::vector<unsigned long>* traverse_order = NULL;
18827 if (indexes_out_of_order)
18829 typedef std::vector<IVT_triple> V;
18831 V v;
18832 v.reserve(indexes->size());
18833 std::vector<unsigned long>::const_iterator pi = indexes->begin();
18834 unsigned long torder = 0;
18835 for (Expression_list::const_iterator pe = vals->begin();
18836 pe != vals->end();
18837 ++pe, ++pi, ++torder)
18838 v.push_back(IVT_triple(*pi, torder, *pe));
18840 std::sort(v.begin(), v.end());
18842 delete indexes;
18843 delete vals;
18845 indexes = new std::vector<unsigned long>();
18846 indexes->reserve(v.size());
18847 vals = new Expression_list();
18848 vals->reserve(v.size());
18849 traverse_order = new std::vector<unsigned long>();
18850 traverse_order->reserve(v.size());
18852 for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
18854 indexes->push_back(pv->index);
18855 vals->push_back(pv->expr);
18856 traverse_order->push_back(pv->traversal_order);
18860 Expression* ret = this->make_array(type, indexes, vals);
18861 Array_construction_expression* ace = ret->array_literal();
18862 if (ace != NULL && traverse_order != NULL)
18863 ace->set_traverse_order(traverse_order);
18864 return ret;
18867 // Actually build the array composite literal. This handles
18868 // [...]{...}.
18870 Expression*
18871 Composite_literal_expression::make_array(
18872 Type* type,
18873 const std::vector<unsigned long>* indexes,
18874 Expression_list* vals)
18876 Location location = this->location();
18877 Array_type* at = type->array_type();
18879 if (at->length() != NULL
18880 && !at->length()->is_error_expression()
18881 && this->vals_ != NULL)
18883 Numeric_constant nc;
18884 unsigned long val;
18885 if (at->length()->numeric_constant_value(&nc)
18886 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
18888 if (indexes == NULL)
18890 if (this->vals_->size() > val)
18892 go_error_at(location,
18893 "too many elements in composite literal");
18894 return Expression::make_error(location);
18897 else
18899 unsigned long max = indexes->back();
18900 if (max >= val)
18902 go_error_at(location,
18903 ("some element keys in composite literal "
18904 "are out of range"));
18905 return Expression::make_error(location);
18911 if (at->length() != NULL)
18912 return new Fixed_array_construction_expression(type, indexes, vals,
18913 location);
18914 else
18915 return new Slice_construction_expression(type, indexes, vals, location);
18918 // Lower a map composite literal.
18920 Expression*
18921 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
18922 Statement_inserter* inserter,
18923 Type* type)
18925 Location location = this->location();
18926 Unordered_map(unsigned int, std::vector<Expression*>) st;
18927 Unordered_map(unsigned int, std::vector<Expression*>) nt;
18928 bool saw_false = false;
18929 bool saw_true = false;
18930 if (this->vals_ != NULL)
18932 go_assert(this->has_keys_);
18934 for (Expression_list::iterator p = this->vals_->begin();
18935 p != this->vals_->end();
18936 p += 2)
18938 if (*p == NULL)
18940 ++p;
18941 go_error_at((*p)->location(),
18942 ("map composite literal must "
18943 "have keys for every value"));
18944 return Expression::make_error(location);
18946 // Make sure we have lowered the key; it may not have been
18947 // lowered in order to handle keys for struct composite
18948 // literals. Lower it now to get the right error message.
18949 if ((*p)->unknown_expression() != NULL)
18951 gogo->lower_expression(function, inserter, &*p);
18952 go_assert((*p)->is_error_expression());
18953 return Expression::make_error(location);
18955 // Check if there are duplicate constant keys.
18956 if (!(*p)->is_constant())
18957 continue;
18958 std::string sval;
18959 Numeric_constant nval;
18960 bool bval;
18961 if ((*p)->string_constant_value(&sval)) // Check string keys.
18963 unsigned int h = Gogo::hash_string(sval, 0);
18964 // Search the index h in the hash map.
18965 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
18966 mit = st.find(h);
18967 if (mit == st.end())
18969 // No duplicate since h is a new index.
18970 // Create a new vector indexed by h and add it to the hash map.
18971 std::vector<Expression*> l;
18972 l.push_back(*p);
18973 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
18974 st.insert(val);
18976 else
18978 // Do further check since index h already exists.
18979 for (std::vector<Expression*>::iterator lit =
18980 mit->second.begin();
18981 lit != mit->second.end();
18982 lit++)
18984 std::string s;
18985 bool ok = (*lit)->string_constant_value(&s);
18986 go_assert(ok);
18987 if (s == sval)
18989 go_error_at((*p)->location(), ("duplicate key "
18990 "in map literal"));
18991 return Expression::make_error(location);
18994 // Add this new string key to the vector indexed by h.
18995 mit->second.push_back(*p);
18998 else if ((*p)->numeric_constant_value(&nval))
19000 // Check numeric keys.
19001 unsigned int h = nval.hash(0);
19002 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
19003 mit = nt.find(h);
19004 if (mit == nt.end())
19006 // No duplicate since h is a new code.
19007 // Create a new vector indexed by h and add it to the hash map.
19008 std::vector<Expression*> l;
19009 l.push_back(*p);
19010 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
19011 nt.insert(val);
19013 else
19015 // Do further check since h already exists.
19016 for (std::vector<Expression*>::iterator lit =
19017 mit->second.begin();
19018 lit != mit->second.end();
19019 lit++)
19021 Numeric_constant rval;
19022 bool ok = (*lit)->numeric_constant_value(&rval);
19023 go_assert(ok);
19024 if (nval.equals(rval))
19026 go_error_at((*p)->location(),
19027 "duplicate key in map literal");
19028 return Expression::make_error(location);
19031 // Add this new numeric key to the vector indexed by h.
19032 mit->second.push_back(*p);
19035 else if ((*p)->boolean_constant_value(&bval))
19037 if ((bval && saw_true) || (!bval && saw_false))
19039 go_error_at((*p)->location(),
19040 "duplicate key in map literal");
19041 return Expression::make_error(location);
19043 if (bval)
19044 saw_true = true;
19045 else
19046 saw_false = true;
19051 return new Map_construction_expression(type, this->vals_, location);
19054 // Copy.
19056 Expression*
19057 Composite_literal_expression::do_copy()
19059 Composite_literal_expression* ret =
19060 new Composite_literal_expression(this->type_->copy_expressions(),
19061 this->depth_, this->has_keys_,
19062 (this->vals_ == NULL
19063 ? NULL
19064 : this->vals_->copy()),
19065 this->all_are_names_,
19066 this->location());
19067 ret->key_path_ = this->key_path_;
19068 return ret;
19071 // Dump ast representation for a composite literal expression.
19073 void
19074 Composite_literal_expression::do_dump_expression(
19075 Ast_dump_context* ast_dump_context) const
19077 ast_dump_context->ostream() << "composite(";
19078 ast_dump_context->dump_type(this->type_);
19079 ast_dump_context->ostream() << ", {";
19080 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
19081 ast_dump_context->ostream() << "})";
19084 // Make a composite literal expression.
19086 Expression*
19087 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
19088 Expression_list* vals, bool all_are_names,
19089 Location location)
19091 return new Composite_literal_expression(type, depth, has_keys, vals,
19092 all_are_names, location);
19095 // Return whether this expression is a composite literal.
19097 bool
19098 Expression::is_composite_literal() const
19100 switch (this->classification_)
19102 case EXPRESSION_COMPOSITE_LITERAL:
19103 case EXPRESSION_STRUCT_CONSTRUCTION:
19104 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
19105 case EXPRESSION_SLICE_CONSTRUCTION:
19106 case EXPRESSION_MAP_CONSTRUCTION:
19107 return true;
19108 default:
19109 return false;
19113 // Return whether this expression is a composite literal which is not
19114 // constant.
19116 bool
19117 Expression::is_nonconstant_composite_literal() const
19119 switch (this->classification_)
19121 case EXPRESSION_STRUCT_CONSTRUCTION:
19123 const Struct_construction_expression *psce =
19124 static_cast<const Struct_construction_expression*>(this);
19125 return !psce->is_constant_struct();
19127 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
19129 const Fixed_array_construction_expression *pace =
19130 static_cast<const Fixed_array_construction_expression*>(this);
19131 return !pace->is_constant_array();
19133 case EXPRESSION_SLICE_CONSTRUCTION:
19135 const Slice_construction_expression *pace =
19136 static_cast<const Slice_construction_expression*>(this);
19137 return !pace->is_constant_array();
19139 case EXPRESSION_MAP_CONSTRUCTION:
19140 return true;
19141 default:
19142 return false;
19146 // Return true if this is a variable or temporary_variable.
19148 bool
19149 Expression::is_variable() const
19151 switch (this->classification_)
19153 case EXPRESSION_VAR_REFERENCE:
19154 case EXPRESSION_TEMPORARY_REFERENCE:
19155 case EXPRESSION_SET_AND_USE_TEMPORARY:
19156 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
19157 return true;
19158 default:
19159 return false;
19163 // Return true if this is a reference to a local variable.
19165 bool
19166 Expression::is_local_variable() const
19168 const Var_expression* ve = this->var_expression();
19169 if (ve == NULL)
19170 return false;
19171 const Named_object* no = ve->named_object();
19172 return (no->is_result_variable()
19173 || (no->is_variable() && !no->var_value()->is_global()));
19176 // Return true if multiple evaluations are OK.
19178 bool
19179 Expression::is_multi_eval_safe()
19181 switch (this->classification_)
19183 case EXPRESSION_VAR_REFERENCE:
19185 // A variable is a simple reference if not stored in the heap.
19186 const Named_object* no = this->var_expression()->named_object();
19187 if (no->is_variable())
19188 return !no->var_value()->is_in_heap();
19189 else if (no->is_result_variable())
19190 return !no->result_var_value()->is_in_heap();
19191 else
19192 go_unreachable();
19195 case EXPRESSION_TEMPORARY_REFERENCE:
19196 return true;
19198 default:
19199 break;
19202 if (!this->is_constant())
19203 return false;
19205 // Only numeric and boolean constants are really multi-evaluation
19206 // safe. We don't want multiple copies of string constants.
19207 Type* type = this->type();
19208 return type->is_numeric_type() || type->is_boolean_type();
19211 const Named_object*
19212 Expression::named_constant() const
19214 if (this->classification() != EXPRESSION_CONST_REFERENCE)
19215 return NULL;
19216 const Const_expression* ce = static_cast<const Const_expression*>(this);
19217 return ce->named_object();
19220 // Class Type_guard_expression.
19222 // Traversal.
19225 Type_guard_expression::do_traverse(Traverse* traverse)
19227 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
19228 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
19229 return TRAVERSE_EXIT;
19230 return TRAVERSE_CONTINUE;
19233 Expression*
19234 Type_guard_expression::do_flatten(Gogo*, Named_object*,
19235 Statement_inserter* inserter)
19237 if (this->expr_->is_error_expression()
19238 || this->expr_->type()->is_error_type())
19240 go_assert(saw_errors());
19241 return Expression::make_error(this->location());
19244 if (!this->expr_->is_multi_eval_safe())
19246 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
19247 this->location());
19248 inserter->insert(temp);
19249 this->expr_ =
19250 Expression::make_temporary_reference(temp, this->location());
19252 return this;
19255 // Check types of a type guard expression. The expression must have
19256 // an interface type, but the actual type conversion is checked at run
19257 // time.
19259 void
19260 Type_guard_expression::do_check_types(Gogo*)
19262 Type* expr_type = this->expr_->type();
19263 if (expr_type->interface_type() == NULL)
19265 if (!expr_type->is_error() && !this->type_->is_error())
19266 this->report_error(_("type assertion only valid for interface types"));
19267 this->set_is_error();
19269 else if (this->type_->interface_type() == NULL)
19271 std::string reason;
19272 if (!expr_type->interface_type()->implements_interface(this->type_,
19273 &reason))
19275 if (!this->type_->is_error())
19277 if (reason.empty())
19278 this->report_error(_("impossible type assertion: "
19279 "type does not implement interface"));
19280 else
19281 go_error_at(this->location(),
19282 ("impossible type assertion: "
19283 "type does not implement interface (%s)"),
19284 reason.c_str());
19286 this->set_is_error();
19291 // Copy.
19293 Expression*
19294 Type_guard_expression::do_copy()
19296 return new Type_guard_expression(this->expr_->copy(),
19297 this->type_->copy_expressions(),
19298 this->location());
19301 // Return the backend representation for a type guard expression.
19303 Bexpression*
19304 Type_guard_expression::do_get_backend(Translate_context* context)
19306 Expression* conversion;
19307 if (this->type_->interface_type() != NULL)
19308 conversion = Expression::convert_interface_to_interface(context->gogo(),
19309 this->type_,
19310 this->expr_,
19311 true,
19312 this->location());
19313 else
19314 conversion = Expression::convert_for_assignment(context->gogo(),
19315 this->type_,
19316 this->expr_,
19317 this->location());
19319 Gogo* gogo = context->gogo();
19320 Btype* bt = this->type_->get_backend(gogo);
19321 Bexpression* bexpr = conversion->get_backend(context);
19322 return gogo->backend()->convert_expression(bt, bexpr, this->location());
19325 // Dump ast representation for a type guard expression.
19327 void
19328 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
19329 const
19331 this->expr_->dump_expression(ast_dump_context);
19332 ast_dump_context->ostream() << ".";
19333 ast_dump_context->dump_type(this->type_);
19336 // Make a type guard expression.
19338 Expression*
19339 Expression::make_type_guard(Expression* expr, Type* type,
19340 Location location)
19342 return new Type_guard_expression(expr, type, location);
19345 // Class Heap_expression.
19347 // Return the type of the expression stored on the heap.
19349 Type*
19350 Heap_expression::do_type()
19351 { return Type::make_pointer_type(this->expr_->type()); }
19353 // Return the backend representation for allocating an expression on the heap.
19355 Bexpression*
19356 Heap_expression::do_get_backend(Translate_context* context)
19358 Type* etype = this->expr_->type();
19359 if (this->expr_->is_error_expression() || etype->is_error())
19360 return context->backend()->error_expression();
19362 Location loc = this->location();
19363 Gogo* gogo = context->gogo();
19364 Btype* btype = this->type()->get_backend(gogo);
19366 Expression* alloc = Expression::make_allocation(etype, loc);
19367 if (this->allocate_on_stack_)
19368 alloc->allocation_expression()->set_allocate_on_stack();
19369 Bexpression* space = alloc->get_backend(context);
19371 Bstatement* decl;
19372 Named_object* fn = context->function();
19373 go_assert(fn != NULL);
19374 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
19375 Bvariable* space_temp =
19376 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
19377 space,
19378 Backend::variable_address_is_taken,
19379 loc, &decl);
19380 Btype* expr_btype = etype->get_backend(gogo);
19382 Bexpression* bexpr = this->expr_->get_backend(context);
19384 // If this assignment needs a write barrier, call typedmemmove. We
19385 // don't do this in the write barrier pass because in some cases
19386 // backend conversion can introduce new Heap_expression values.
19387 Bstatement* assn;
19388 if (!etype->has_pointer() || this->allocate_on_stack_)
19390 space = gogo->backend()->var_expression(space_temp, loc);
19391 Bexpression* ref =
19392 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
19393 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
19395 else
19397 Bstatement* edecl;
19398 Bvariable* btemp =
19399 gogo->backend()->temporary_variable(fndecl, context->bblock(),
19400 expr_btype, bexpr,
19401 Backend::variable_address_is_taken,
19402 loc, &edecl);
19403 Bexpression* btempref = gogo->backend()->var_expression(btemp,
19404 loc);
19405 space = gogo->backend()->var_expression(space_temp, loc);
19406 Type* etype_ptr = Type::make_pointer_type(etype);
19407 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
19408 Expression* erhs;
19409 Expression* call;
19410 if (etype->is_direct_iface_type())
19412 // Single pointer.
19413 Type* uintptr_type = Type::lookup_integer_type("uintptr");
19414 erhs = Expression::make_backend(btempref, etype, loc);
19415 erhs = Expression::unpack_direct_iface(erhs, loc);
19416 erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
19417 call = Runtime::make_call(gogo, Runtime::GCWRITEBARRIER, loc, 2,
19418 elhs, erhs);
19420 else
19422 Expression* td = Expression::make_type_descriptor(etype, loc);
19423 Bexpression* addr =
19424 gogo->backend()->address_expression(btempref, loc);
19425 erhs = Expression::make_backend(addr, etype_ptr, loc);
19426 call = Runtime::make_call(gogo, Runtime::TYPEDMEMMOVE, loc, 3,
19427 td, elhs, erhs);
19429 Statement* cs = Statement::make_statement(call, false);
19431 space = gogo->backend()->var_expression(space_temp, loc);
19432 Bexpression* ref =
19433 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
19434 Expression* eref = Expression::make_backend(ref, etype, loc);
19435 btempref = gogo->backend()->var_expression(btemp, loc);
19436 erhs = Expression::make_backend(btempref, etype, loc);
19437 Statement* as = Statement::make_assignment(eref, erhs, loc);
19439 as = gogo->check_write_barrier(context->block(), as, cs);
19440 Bstatement* s = as->get_backend(context);
19442 assn = gogo->backend()->compound_statement(edecl, s);
19444 decl = gogo->backend()->compound_statement(decl, assn);
19445 space = gogo->backend()->var_expression(space_temp, loc);
19446 return gogo->backend()->compound_expression(decl, space, loc);
19449 // Dump ast representation for a heap expression.
19451 void
19452 Heap_expression::do_dump_expression(
19453 Ast_dump_context* ast_dump_context) const
19455 ast_dump_context->ostream() << "&(";
19456 ast_dump_context->dump_expression(this->expr_);
19457 ast_dump_context->ostream() << ")";
19460 // Allocate an expression on the heap.
19462 Expression*
19463 Expression::make_heap_expression(Expression* expr, Location location)
19465 return new Heap_expression(expr, location);
19468 // Class Receive_expression.
19470 // Return the type of a receive expression.
19472 Type*
19473 Receive_expression::do_type()
19475 if (this->is_error_expression())
19476 return Type::make_error_type();
19477 Channel_type* channel_type = this->channel_->type()->channel_type();
19478 if (channel_type == NULL)
19480 this->report_error(_("expected channel"));
19481 return Type::make_error_type();
19483 return channel_type->element_type();
19486 // Check types for a receive expression.
19488 void
19489 Receive_expression::do_check_types(Gogo*)
19491 Type* type = this->channel_->type();
19492 if (type->is_error())
19494 go_assert(saw_errors());
19495 this->set_is_error();
19496 return;
19498 if (type->channel_type() == NULL)
19500 this->report_error(_("expected channel"));
19501 return;
19503 if (!type->channel_type()->may_receive())
19505 this->report_error(_("invalid receive on send-only channel"));
19506 return;
19510 // Flattening for receive expressions creates a temporary variable to store
19511 // received data in for receives.
19513 Expression*
19514 Receive_expression::do_flatten(Gogo*, Named_object*,
19515 Statement_inserter* inserter)
19517 Channel_type* channel_type = this->channel_->type()->channel_type();
19518 if (channel_type == NULL)
19520 go_assert(saw_errors());
19521 return this;
19523 else if (this->channel_->is_error_expression())
19525 go_assert(saw_errors());
19526 return Expression::make_error(this->location());
19529 Type* element_type = channel_type->element_type();
19530 if (this->temp_receiver_ == NULL)
19532 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
19533 this->location());
19534 this->temp_receiver_->set_is_address_taken();
19535 inserter->insert(this->temp_receiver_);
19538 return this;
19541 // Get the backend representation for a receive expression.
19543 Bexpression*
19544 Receive_expression::do_get_backend(Translate_context* context)
19546 Location loc = this->location();
19548 Channel_type* channel_type = this->channel_->type()->channel_type();
19549 if (channel_type == NULL)
19551 go_assert(this->channel_->type()->is_error());
19552 return context->backend()->error_expression();
19555 Gogo* gogo = context->gogo();
19556 Expression* recv_ref =
19557 Expression::make_temporary_reference(this->temp_receiver_, loc);
19558 Expression* recv_addr =
19559 Expression::make_temporary_reference(this->temp_receiver_, loc);
19560 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
19561 Expression* recv = Runtime::make_call(gogo, Runtime::CHANRECV1, loc, 2,
19562 this->channel_, recv_addr);
19563 Expression* ret = Expression::make_compound(recv, recv_ref, loc);
19564 ret->determine_type_no_context(gogo);
19565 return ret->get_backend(context);
19568 // Export a receive expression.
19570 void
19571 Receive_expression::do_export(Export_function_body* efb) const
19573 efb->write_c_string("<-");
19574 this->channel_->export_expression(efb);
19577 // Dump ast representation for a receive expression.
19579 void
19580 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
19582 ast_dump_context->ostream() << " <- " ;
19583 ast_dump_context->dump_expression(channel_);
19586 // Import a receive expression.
19588 Expression*
19589 Receive_expression::do_import(Import_expression* imp, Location loc)
19591 imp->require_c_string("<-");
19592 Expression* expr = Expression::import_expression(imp, loc);
19593 return Expression::make_receive(expr, loc);
19596 // Make a receive expression.
19598 Receive_expression*
19599 Expression::make_receive(Expression* channel, Location location)
19601 return new Receive_expression(channel, location);
19604 // An expression which evaluates to a pointer to the type descriptor
19605 // of a type.
19607 class Type_descriptor_expression : public Expression
19609 public:
19610 Type_descriptor_expression(Type* type, Location location)
19611 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
19612 type_(type)
19615 protected:
19617 do_traverse(Traverse*);
19619 Type*
19620 do_type()
19621 { return Type::make_type_descriptor_ptr_type(); }
19623 bool
19624 do_is_static_initializer() const
19625 { return true; }
19627 void
19628 do_determine_type(Gogo*, const Type_context*)
19631 Expression*
19632 do_copy()
19633 { return this; }
19635 Bexpression*
19636 do_get_backend(Translate_context* context)
19638 return this->type_->type_descriptor_pointer(context->gogo(),
19639 this->location());
19642 void
19643 do_dump_expression(Ast_dump_context*) const;
19645 private:
19646 // The type for which this is the descriptor.
19647 Type* type_;
19651 Type_descriptor_expression::do_traverse(Traverse* traverse)
19653 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
19654 return TRAVERSE_EXIT;
19655 return TRAVERSE_CONTINUE;
19658 // Dump ast representation for a type descriptor expression.
19660 void
19661 Type_descriptor_expression::do_dump_expression(
19662 Ast_dump_context* ast_dump_context) const
19664 ast_dump_context->dump_type(this->type_);
19667 // Make a type descriptor expression.
19669 Expression*
19670 Expression::make_type_descriptor(Type* type, Location location)
19672 return new Type_descriptor_expression(type, location);
19675 // An expression which evaluates to a pointer to the Garbage Collection symbol
19676 // of a type.
19678 class GC_symbol_expression : public Expression
19680 public:
19681 GC_symbol_expression(Type* type)
19682 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
19683 type_(type)
19686 protected:
19687 Type*
19688 do_type()
19689 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
19691 bool
19692 do_is_static_initializer() const
19693 { return true; }
19695 void
19696 do_determine_type(Gogo*, const Type_context*)
19699 Expression*
19700 do_copy()
19701 { return this; }
19703 Bexpression*
19704 do_get_backend(Translate_context* context)
19705 { return this->type_->gc_symbol_pointer(context->gogo()); }
19707 void
19708 do_dump_expression(Ast_dump_context*) const;
19710 private:
19711 // The type which this gc symbol describes.
19712 Type* type_;
19715 // Dump ast representation for a gc symbol expression.
19717 void
19718 GC_symbol_expression::do_dump_expression(
19719 Ast_dump_context* ast_dump_context) const
19721 ast_dump_context->ostream() << "gcdata(";
19722 ast_dump_context->dump_type(this->type_);
19723 ast_dump_context->ostream() << ")";
19726 // Make a gc symbol expression.
19728 Expression*
19729 Expression::make_gc_symbol(Type* type)
19731 return new GC_symbol_expression(type);
19734 // An expression that evaluates to a pointer to a symbol holding the
19735 // ptrmask data of a type.
19737 class Ptrmask_symbol_expression : public Expression
19739 public:
19740 Ptrmask_symbol_expression(Type* type)
19741 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
19742 type_(type)
19745 protected:
19746 Type*
19747 do_type()
19748 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
19750 bool
19751 do_is_static_initializer() const
19752 { return true; }
19754 void
19755 do_determine_type(Gogo*, const Type_context*)
19758 Expression*
19759 do_copy()
19760 { return this; }
19762 Bexpression*
19763 do_get_backend(Translate_context*);
19765 void
19766 do_dump_expression(Ast_dump_context*) const;
19768 private:
19769 // The type that this ptrmask symbol describes.
19770 Type* type_;
19773 // Return the ptrmask variable.
19775 Bexpression*
19776 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
19778 Gogo* gogo = context->gogo();
19780 // If this type does not need a gcprog, then we can use the standard
19781 // GC symbol.
19782 int64_t ptrsize, ptrdata;
19783 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
19784 return this->type_->gc_symbol_pointer(gogo);
19786 // Otherwise we have to build a ptrmask variable, and return a
19787 // pointer to it.
19789 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
19790 Location bloc = Linemap::predeclared_location();
19791 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
19792 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
19794 Type* uint8_type = Type::lookup_integer_type("uint8");
19795 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
19796 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
19797 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
19800 // Dump AST for a ptrmask symbol expression.
19802 void
19803 Ptrmask_symbol_expression::do_dump_expression(
19804 Ast_dump_context* ast_dump_context) const
19806 ast_dump_context->ostream() << "ptrmask(";
19807 ast_dump_context->dump_type(this->type_);
19808 ast_dump_context->ostream() << ")";
19811 // Make a ptrmask symbol expression.
19813 Expression*
19814 Expression::make_ptrmask_symbol(Type* type)
19816 return new Ptrmask_symbol_expression(type);
19819 // An expression which evaluates to some characteristic of a type.
19820 // This is only used to initialize fields of a type descriptor. Using
19821 // a new expression class is slightly inefficient but gives us a good
19822 // separation between the frontend and the middle-end with regard to
19823 // how types are laid out.
19825 class Type_info_expression : public Expression
19827 public:
19828 Type_info_expression(Type* type, Type_info type_info)
19829 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
19830 type_(type), type_info_(type_info)
19833 protected:
19834 bool
19835 do_is_static_initializer() const
19836 { return true; }
19838 Type*
19839 do_type();
19841 void
19842 do_determine_type(Gogo*, const Type_context*)
19845 Expression*
19846 do_copy()
19847 { return this; }
19849 Bexpression*
19850 do_get_backend(Translate_context* context);
19852 void
19853 do_dump_expression(Ast_dump_context*) const;
19855 private:
19856 // The type for which we are getting information.
19857 Type* type_;
19858 // What information we want.
19859 Type_info type_info_;
19862 // The type is chosen to match what the type descriptor struct
19863 // expects.
19865 Type*
19866 Type_info_expression::do_type()
19868 switch (this->type_info_)
19870 case TYPE_INFO_SIZE:
19871 case TYPE_INFO_BACKEND_PTRDATA:
19872 case TYPE_INFO_DESCRIPTOR_PTRDATA:
19873 return Type::lookup_integer_type("uintptr");
19874 case TYPE_INFO_ALIGNMENT:
19875 case TYPE_INFO_FIELD_ALIGNMENT:
19876 return Type::lookup_integer_type("uint8");
19877 default:
19878 go_unreachable();
19882 // Return the backend representation for type information.
19884 Bexpression*
19885 Type_info_expression::do_get_backend(Translate_context* context)
19887 Gogo* gogo = context->gogo();
19888 bool ok = true;
19889 int64_t val;
19890 switch (this->type_info_)
19892 case TYPE_INFO_SIZE:
19893 ok = this->type_->backend_type_size(gogo, &val);
19894 break;
19895 case TYPE_INFO_ALIGNMENT:
19896 ok = this->type_->backend_type_align(gogo, &val);
19897 break;
19898 case TYPE_INFO_FIELD_ALIGNMENT:
19899 ok = this->type_->backend_type_field_align(gogo, &val);
19900 break;
19901 case TYPE_INFO_BACKEND_PTRDATA:
19902 ok = this->type_->backend_type_ptrdata(gogo, &val);
19903 break;
19904 case TYPE_INFO_DESCRIPTOR_PTRDATA:
19905 ok = this->type_->descriptor_ptrdata(gogo, &val);
19906 break;
19907 default:
19908 go_unreachable();
19910 if (!ok)
19912 go_assert(saw_errors());
19913 return gogo->backend()->error_expression();
19915 Expression* e = Expression::make_integer_int64(val, this->type(),
19916 this->location());
19917 return e->get_backend(context);
19920 // Dump ast representation for a type info expression.
19922 void
19923 Type_info_expression::do_dump_expression(
19924 Ast_dump_context* ast_dump_context) const
19926 ast_dump_context->ostream() << "typeinfo(";
19927 ast_dump_context->dump_type(this->type_);
19928 ast_dump_context->ostream() << ",";
19929 ast_dump_context->ostream() <<
19930 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
19931 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
19932 : this->type_info_ == TYPE_INFO_SIZE ? "size"
19933 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
19934 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
19935 : "unknown");
19936 ast_dump_context->ostream() << ")";
19939 // Make a type info expression.
19941 Expression*
19942 Expression::make_type_info(Type* type, Type_info type_info)
19944 return new Type_info_expression(type, type_info);
19947 // Slice_info_expression.
19949 // Return the type of the slice info.
19951 Type*
19952 Slice_info_expression::do_type()
19954 switch (this->slice_info_)
19956 case SLICE_INFO_VALUE_POINTER:
19957 return Type::make_pointer_type(
19958 this->slice_->type()->array_type()->element_type());
19959 case SLICE_INFO_LENGTH:
19960 case SLICE_INFO_CAPACITY:
19961 return Type::lookup_integer_type("int");
19962 default:
19963 go_unreachable();
19967 // Return the backend information for slice information.
19969 Bexpression*
19970 Slice_info_expression::do_get_backend(Translate_context* context)
19972 Gogo* gogo = context->gogo();
19973 Bexpression* bslice = this->slice_->get_backend(context);
19974 switch (this->slice_info_)
19976 case SLICE_INFO_VALUE_POINTER:
19977 case SLICE_INFO_LENGTH:
19978 case SLICE_INFO_CAPACITY:
19979 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
19980 this->location());
19981 break;
19982 default:
19983 go_unreachable();
19987 // Dump ast representation for a type info expression.
19989 void
19990 Slice_info_expression::do_dump_expression(
19991 Ast_dump_context* ast_dump_context) const
19993 ast_dump_context->ostream() << "sliceinfo(";
19994 this->slice_->dump_expression(ast_dump_context);
19995 ast_dump_context->ostream() << ",";
19996 ast_dump_context->ostream() <<
19997 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
19998 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
19999 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
20000 : "unknown");
20001 ast_dump_context->ostream() << ")";
20004 // Make a slice info expression.
20006 Expression*
20007 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
20008 Location location)
20010 return new Slice_info_expression(slice, slice_info, location);
20013 // Class Slice_value_expression.
20016 Slice_value_expression::do_traverse(Traverse* traverse)
20018 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
20019 || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
20020 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
20021 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
20022 return TRAVERSE_EXIT;
20023 return TRAVERSE_CONTINUE;
20026 // Determine type of a slice value.
20028 void
20029 Slice_value_expression::do_determine_type(Gogo* gogo, const Type_context*)
20031 this->valmem_->determine_type_no_context(gogo);
20032 this->len_->determine_type_no_context(gogo);
20033 this->cap_->determine_type_no_context(gogo);
20036 Expression*
20037 Slice_value_expression::do_copy()
20039 return new Slice_value_expression(this->type_->copy_expressions(),
20040 this->valmem_->copy(),
20041 this->len_->copy(), this->cap_->copy(),
20042 this->location());
20045 Bexpression*
20046 Slice_value_expression::do_get_backend(Translate_context* context)
20048 std::vector<Bexpression*> vals(3);
20049 vals[0] = this->valmem_->get_backend(context);
20050 vals[1] = this->len_->get_backend(context);
20051 vals[2] = this->cap_->get_backend(context);
20053 Gogo* gogo = context->gogo();
20054 Btype* btype = this->type_->get_backend(gogo);
20055 return gogo->backend()->constructor_expression(btype, vals, this->location());
20058 void
20059 Slice_value_expression::do_dump_expression(
20060 Ast_dump_context* ast_dump_context) const
20062 ast_dump_context->ostream() << "slicevalue(";
20063 ast_dump_context->ostream() << "values: ";
20064 this->valmem_->dump_expression(ast_dump_context);
20065 ast_dump_context->ostream() << ", length: ";
20066 this->len_->dump_expression(ast_dump_context);
20067 ast_dump_context->ostream() << ", capacity: ";
20068 this->cap_->dump_expression(ast_dump_context);
20069 ast_dump_context->ostream() << ")";
20072 Expression*
20073 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
20074 Expression* cap, Location location)
20076 go_assert(at->is_slice_type());
20077 go_assert(valmem->is_nil_expression()
20078 || (at->array_type()->element_type()
20079 == valmem->type()->points_to()));
20080 return new Slice_value_expression(at, valmem, len, cap, location);
20083 // Look through the expression of a Slice_value_expression's valmem to
20084 // find an call to makeslice. If found, return the call expression and
20085 // the containing temporary statement (if any).
20087 std::pair<Call_expression*, Temporary_statement*>
20088 Expression::find_makeslice_call(Expression* expr)
20090 Unsafe_type_conversion_expression* utce =
20091 expr->unsafe_conversion_expression();
20092 if (utce != NULL)
20093 expr = utce->expr();
20095 Slice_value_expression* sve = expr->slice_value_expression();
20096 if (sve == NULL)
20097 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
20098 expr = sve->valmem();
20100 utce = expr->unsafe_conversion_expression();
20101 if (utce != NULL)
20102 expr = utce->expr();
20104 Temporary_reference_expression* tre = expr->temporary_reference_expression();
20105 Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
20106 if (ts != NULL && ts->init() != NULL && !ts->assigned()
20107 && !ts->is_address_taken())
20108 expr = ts->init();
20110 Call_expression* call = expr->call_expression();
20111 if (call == NULL)
20112 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
20114 Func_expression* fe = call->fn()->func_expression();
20115 if (fe != NULL
20116 && fe->runtime_code() == Runtime::MAKESLICE)
20117 return std::make_pair(call, ts);
20119 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
20122 // An expression that evaluates to some characteristic of a non-empty interface.
20123 // This is used to access the method table or underlying object of an interface.
20125 class Interface_info_expression : public Expression
20127 public:
20128 Interface_info_expression(Expression* iface, Interface_info iface_info,
20129 Location location)
20130 : Expression(EXPRESSION_INTERFACE_INFO, location),
20131 iface_(iface), iface_info_(iface_info)
20134 protected:
20135 Type*
20136 do_type();
20138 void
20139 do_determine_type(Gogo*, const Type_context*)
20142 Expression*
20143 do_copy()
20145 return new Interface_info_expression(this->iface_->copy(),
20146 this->iface_info_, this->location());
20149 Bexpression*
20150 do_get_backend(Translate_context* context);
20152 void
20153 do_dump_expression(Ast_dump_context*) const;
20155 void
20156 do_issue_nil_check()
20157 { this->iface_->issue_nil_check(); }
20159 private:
20160 // The interface for which we are getting information.
20161 Expression* iface_;
20162 // What information we want.
20163 Interface_info iface_info_;
20166 // Return the type of the interface info.
20168 Type*
20169 Interface_info_expression::do_type()
20171 switch (this->iface_info_)
20173 case INTERFACE_INFO_METHODS:
20175 typedef Unordered_map(Interface_type*, Type*) Hashtable;
20176 static Hashtable result_types;
20178 Interface_type* itype = this->iface_->type()->interface_type();
20180 Hashtable::const_iterator pr = result_types.find(itype);
20181 if (pr != result_types.end())
20182 return pr->second;
20184 Type* pdt = Type::make_type_descriptor_ptr_type();
20185 if (itype->is_empty())
20187 result_types[itype] = pdt;
20188 return pdt;
20191 Location loc = this->location();
20192 Struct_field_list* sfl = new Struct_field_list();
20193 sfl->push_back(
20194 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
20196 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
20197 p != itype->methods()->end();
20198 ++p)
20200 Function_type* ft = p->type()->function_type();
20201 go_assert(ft->receiver() == NULL);
20203 const Typed_identifier_list* params = ft->parameters();
20204 Typed_identifier_list* mparams = new Typed_identifier_list();
20205 if (params != NULL)
20206 mparams->reserve(params->size() + 1);
20207 Type* vt = Type::make_pointer_type(Type::make_void_type());
20208 mparams->push_back(Typed_identifier("", vt, ft->location()));
20209 if (params != NULL)
20211 for (Typed_identifier_list::const_iterator pp = params->begin();
20212 pp != params->end();
20213 ++pp)
20214 mparams->push_back(*pp);
20217 Typed_identifier_list* mresults = (ft->results() == NULL
20218 ? NULL
20219 : ft->results()->copy());
20220 Backend_function_type* mft =
20221 Type::make_backend_function_type(NULL, mparams, mresults,
20222 ft->location());
20224 std::string fname = Gogo::unpack_hidden_name(p->name());
20225 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
20228 Struct_type* st = Type::make_struct_type(sfl, loc);
20229 st->set_is_struct_incomparable();
20230 Pointer_type *pt = Type::make_pointer_type(st);
20231 result_types[itype] = pt;
20232 return pt;
20234 case INTERFACE_INFO_OBJECT:
20235 return Type::make_pointer_type(Type::make_void_type());
20236 default:
20237 go_unreachable();
20241 // Return the backend representation for interface information.
20243 Bexpression*
20244 Interface_info_expression::do_get_backend(Translate_context* context)
20246 Gogo* gogo = context->gogo();
20247 Bexpression* biface = this->iface_->get_backend(context);
20248 switch (this->iface_info_)
20250 case INTERFACE_INFO_METHODS:
20251 case INTERFACE_INFO_OBJECT:
20252 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
20253 this->location());
20254 break;
20255 default:
20256 go_unreachable();
20260 // Dump ast representation for an interface info expression.
20262 void
20263 Interface_info_expression::do_dump_expression(
20264 Ast_dump_context* ast_dump_context) const
20266 bool is_empty = this->iface_->type()->interface_type()->is_empty();
20267 ast_dump_context->ostream() << "interfaceinfo(";
20268 this->iface_->dump_expression(ast_dump_context);
20269 ast_dump_context->ostream() << ",";
20270 ast_dump_context->ostream() <<
20271 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
20272 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
20273 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
20274 : "unknown");
20275 ast_dump_context->ostream() << ")";
20278 // Make an interface info expression.
20280 Expression*
20281 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
20282 Location location)
20284 return new Interface_info_expression(iface, iface_info, location);
20287 // An expression that represents an interface value. The first field is either
20288 // a type descriptor for an empty interface or a pointer to the interface method
20289 // table for a non-empty interface. The second field is always the object.
20291 class Interface_value_expression : public Expression
20293 public:
20294 Interface_value_expression(Type* type, Expression* first_field,
20295 Expression* obj, Location location)
20296 : Expression(EXPRESSION_INTERFACE_VALUE, location),
20297 type_(type), first_field_(first_field), obj_(obj)
20300 protected:
20302 do_traverse(Traverse*);
20304 Type*
20305 do_type()
20306 { return this->type_; }
20308 void
20309 do_determine_type(Gogo*, const Type_context*);
20311 Expression*
20312 do_copy()
20314 return new Interface_value_expression(this->type_->copy_expressions(),
20315 this->first_field_->copy(),
20316 this->obj_->copy(), this->location());
20319 Bexpression*
20320 do_get_backend(Translate_context* context);
20322 void
20323 do_dump_expression(Ast_dump_context*) const;
20325 private:
20326 // The type of the interface value.
20327 Type* type_;
20328 // The first field of the interface (either a type descriptor or a pointer
20329 // to the method table.
20330 Expression* first_field_;
20331 // The underlying object of the interface.
20332 Expression* obj_;
20336 Interface_value_expression::do_traverse(Traverse* traverse)
20338 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
20339 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
20340 return TRAVERSE_EXIT;
20341 return TRAVERSE_CONTINUE;
20344 void
20345 Interface_value_expression::do_determine_type(Gogo* gogo, const Type_context*)
20347 this->first_field_->determine_type_no_context(gogo);
20348 this->obj_->determine_type_no_context(gogo);
20351 Bexpression*
20352 Interface_value_expression::do_get_backend(Translate_context* context)
20354 std::vector<Bexpression*> vals(2);
20355 vals[0] = this->first_field_->get_backend(context);
20356 vals[1] = this->obj_->get_backend(context);
20358 Gogo* gogo = context->gogo();
20359 Btype* btype = this->type_->get_backend(gogo);
20360 return gogo->backend()->constructor_expression(btype, vals, this->location());
20363 void
20364 Interface_value_expression::do_dump_expression(
20365 Ast_dump_context* ast_dump_context) const
20367 ast_dump_context->ostream() << "interfacevalue(";
20368 ast_dump_context->ostream() <<
20369 (this->type_->interface_type()->is_empty()
20370 ? "type_descriptor: "
20371 : "methods: ");
20372 this->first_field_->dump_expression(ast_dump_context);
20373 ast_dump_context->ostream() << ", object: ";
20374 this->obj_->dump_expression(ast_dump_context);
20375 ast_dump_context->ostream() << ")";
20378 Expression*
20379 Expression::make_interface_value(Type* type, Expression* first_value,
20380 Expression* object, Location location)
20382 return new Interface_value_expression(type, first_value, object, location);
20385 // An interface method table for a pair of types: an interface type and a type
20386 // that implements that interface.
20388 class Interface_mtable_expression : public Expression
20390 public:
20391 Interface_mtable_expression(Interface_type* itype, Type* type,
20392 bool is_pointer, Location location)
20393 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
20394 itype_(itype), type_(type), is_pointer_(is_pointer),
20395 method_table_type_(NULL), bvar_(NULL)
20398 protected:
20400 do_traverse(Traverse*);
20402 Type*
20403 do_type();
20405 bool
20406 do_is_static_initializer() const
20407 { return true; }
20409 void
20410 do_determine_type(Gogo*, const Type_context*)
20413 Expression*
20414 do_copy()
20416 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
20417 return new Interface_mtable_expression(itype,
20418 this->type_->copy_expressions(),
20419 this->is_pointer_, this->location());
20422 bool
20423 do_is_addressable() const
20424 { return true; }
20426 Bexpression*
20427 do_get_backend(Translate_context* context);
20429 void
20430 do_dump_expression(Ast_dump_context*) const;
20432 private:
20433 // The interface type for which the methods are defined.
20434 Interface_type* itype_;
20435 // The type to construct the interface method table for.
20436 Type* type_;
20437 // Whether this table contains the method set for the receiver type or the
20438 // pointer receiver type.
20439 bool is_pointer_;
20440 // The type of the method table.
20441 Type* method_table_type_;
20442 // The backend variable that refers to the interface method table.
20443 Bvariable* bvar_;
20447 Interface_mtable_expression::do_traverse(Traverse* traverse)
20449 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
20450 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
20451 return TRAVERSE_EXIT;
20452 return TRAVERSE_CONTINUE;
20455 Type*
20456 Interface_mtable_expression::do_type()
20458 if (this->method_table_type_ != NULL)
20459 return this->method_table_type_;
20461 const Typed_identifier_list* interface_methods = this->itype_->methods();
20462 go_assert(!interface_methods->empty());
20464 Struct_field_list* sfl = new Struct_field_list;
20465 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
20466 this->location());
20467 sfl->push_back(Struct_field(tid));
20468 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
20469 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
20470 p != interface_methods->end();
20471 ++p)
20473 // We want C function pointers here, not func descriptors; model
20474 // using void* pointers.
20475 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
20476 sfl->push_back(Struct_field(method));
20478 Struct_type* st = Type::make_struct_type(sfl, this->location());
20479 st->set_is_struct_incomparable();
20480 this->method_table_type_ = st;
20481 return this->method_table_type_;
20484 Bexpression*
20485 Interface_mtable_expression::do_get_backend(Translate_context* context)
20487 Gogo* gogo = context->gogo();
20488 Location loc = Linemap::predeclared_location();
20489 if (this->bvar_ != NULL)
20490 return gogo->backend()->var_expression(this->bvar_, this->location());
20492 const Typed_identifier_list* interface_methods = this->itype_->methods();
20493 go_assert(!interface_methods->empty());
20495 std::string mangled_name =
20496 gogo->interface_method_table_name(this->itype_, this->type_,
20497 this->is_pointer_);
20499 // Set is_public if we are converting a named type to an interface
20500 // type that is defined in the same package as the named type, and
20501 // the interface has hidden methods. In that case the interface
20502 // method table will be defined by the package that defines the
20503 // types.
20504 bool is_public = false;
20505 if (this->type_->named_type() != NULL
20506 && (this->type_->named_type()->named_object()->package()
20507 == this->itype_->package()))
20509 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
20510 p != interface_methods->end();
20511 ++p)
20513 if (Gogo::is_hidden_name(p->name()))
20515 is_public = true;
20516 break;
20521 if (is_public
20522 && this->type_->named_type()->named_object()->package() != NULL)
20524 // The interface conversion table is defined elsewhere.
20525 Btype* btype = this->type()->get_backend(gogo);
20526 this->bvar_ =
20527 gogo->backend()->immutable_struct_reference(mangled_name, "",
20528 btype, loc);
20529 return gogo->backend()->var_expression(this->bvar_, this->location());
20532 // The first element is the type descriptor.
20533 Type* td_type;
20534 if (!this->is_pointer_)
20535 td_type = this->type_;
20536 else
20537 td_type = Type::make_pointer_type(this->type_);
20539 std::vector<Backend::Btyped_identifier> bstructfields;
20541 // Build an interface method table for a type: a type descriptor followed by a
20542 // list of function pointers, one for each interface method. This is used for
20543 // interfaces.
20544 Expression_list* svals = new Expression_list();
20545 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
20546 svals->push_back(tdescriptor);
20548 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
20549 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
20550 bstructfields.push_back(btd);
20552 Named_type* nt = this->type_->named_type();
20553 Struct_type* st = this->type_->struct_type();
20554 go_assert(nt != NULL || st != NULL);
20556 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
20557 p != interface_methods->end();
20558 ++p)
20560 bool is_ambiguous;
20561 Method* m;
20562 if (nt != NULL)
20563 m = nt->method_function(p->name(), &is_ambiguous);
20564 else
20565 m = st->method_function(p->name(), &is_ambiguous);
20566 go_assert(m != NULL);
20568 // See the comment in Type::method_constructor.
20569 bool use_direct_iface_stub = false;
20570 if (m->is_value_method()
20571 && this->is_pointer_
20572 && this->type_->is_direct_iface_type())
20573 use_direct_iface_stub = true;
20574 if (!m->is_value_method()
20575 && this->is_pointer_
20576 && !this->type_->in_heap())
20577 use_direct_iface_stub = true;
20578 Named_object* no = (use_direct_iface_stub
20579 ? m->iface_stub_object()
20580 : m->named_object());
20582 go_assert(no->is_function() || no->is_function_declaration());
20584 Function_type* fcn_type = (no->is_function()
20585 ? no->func_value()->type()
20586 : no->func_declaration_value()->type());
20587 Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
20588 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
20589 bstructfields.push_back(bmtype);
20591 svals->push_back(Expression::make_func_code_reference(no, loc));
20594 Btype *btype = gogo->backend()->struct_type(bstructfields);
20595 std::vector<Bexpression*> ctor_bexprs;
20596 for (Expression_list::const_iterator pe = svals->begin();
20597 pe != svals->end();
20598 ++pe)
20600 ctor_bexprs.push_back((*pe)->get_backend(context));
20602 Bexpression* ctor =
20603 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
20605 unsigned int flags = 0;
20606 if (!is_public)
20607 flags |= Backend::variable_is_hidden;
20608 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, "", flags,
20609 btype, loc);
20610 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, flags,
20611 btype, loc, ctor);
20612 return gogo->backend()->var_expression(this->bvar_, loc);
20615 void
20616 Interface_mtable_expression::do_dump_expression(
20617 Ast_dump_context* ast_dump_context) const
20619 ast_dump_context->ostream() << "__go_"
20620 << (this->is_pointer_ ? "pimt__" : "imt_");
20621 ast_dump_context->dump_type(this->itype_);
20622 ast_dump_context->ostream() << "__";
20623 ast_dump_context->dump_type(this->type_);
20626 Expression*
20627 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
20628 bool is_pointer, Location location)
20630 return new Interface_mtable_expression(itype, type, is_pointer, location);
20633 // An expression which evaluates to the offset of a field within a
20634 // struct. This, like Type_info_expression, q.v., is only used to
20635 // initialize fields of a type descriptor.
20637 class Struct_field_offset_expression : public Expression
20639 public:
20640 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
20641 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
20642 Linemap::predeclared_location()),
20643 type_(type), field_(field)
20646 protected:
20647 bool
20648 do_is_static_initializer() const
20649 { return true; }
20651 Type*
20652 do_type()
20653 { return Type::lookup_integer_type("uintptr"); }
20655 void
20656 do_determine_type(Gogo*, const Type_context*)
20659 Expression*
20660 do_copy()
20661 { return this; }
20663 Bexpression*
20664 do_get_backend(Translate_context* context);
20666 void
20667 do_dump_expression(Ast_dump_context*) const;
20669 private:
20670 // The type of the struct.
20671 Struct_type* type_;
20672 // The field.
20673 const Struct_field* field_;
20676 // Return the backend representation for a struct field offset.
20678 Bexpression*
20679 Struct_field_offset_expression::do_get_backend(Translate_context* context)
20681 const Struct_field_list* fields = this->type_->fields();
20682 Struct_field_list::const_iterator p;
20683 unsigned i = 0;
20684 for (p = fields->begin();
20685 p != fields->end();
20686 ++p, ++i)
20687 if (&*p == this->field_)
20688 break;
20689 go_assert(&*p == this->field_);
20691 Gogo* gogo = context->gogo();
20692 Btype* btype = this->type_->get_backend(gogo);
20694 int64_t offset = gogo->backend()->type_field_offset(btype, i);
20695 Type* uptr_type = Type::lookup_integer_type("uintptr");
20696 Expression* ret =
20697 Expression::make_integer_int64(offset, uptr_type,
20698 Linemap::predeclared_location());
20699 return ret->get_backend(context);
20702 // Dump ast representation for a struct field offset expression.
20704 void
20705 Struct_field_offset_expression::do_dump_expression(
20706 Ast_dump_context* ast_dump_context) const
20708 ast_dump_context->ostream() << "unsafe.Offsetof(";
20709 ast_dump_context->dump_type(this->type_);
20710 ast_dump_context->ostream() << '.';
20711 ast_dump_context->ostream() <<
20712 Gogo::message_name(this->field_->field_name());
20713 ast_dump_context->ostream() << ")";
20716 // Make an expression for a struct field offset.
20718 Expression*
20719 Expression::make_struct_field_offset(Struct_type* type,
20720 const Struct_field* field)
20722 return new Struct_field_offset_expression(type, field);
20725 // An expression which evaluates to the address of an unnamed label.
20727 class Label_addr_expression : public Expression
20729 public:
20730 Label_addr_expression(Label* label, Location location)
20731 : Expression(EXPRESSION_LABEL_ADDR, location),
20732 label_(label)
20735 protected:
20736 Type*
20737 do_type()
20738 { return Type::make_pointer_type(Type::make_void_type()); }
20740 void
20741 do_determine_type(Gogo*, const Type_context*)
20744 Expression*
20745 do_copy()
20746 { return new Label_addr_expression(this->label_, this->location()); }
20748 Bexpression*
20749 do_get_backend(Translate_context* context)
20750 { return this->label_->get_addr(context, this->location()); }
20752 void
20753 do_dump_expression(Ast_dump_context* ast_dump_context) const
20754 { ast_dump_context->ostream() << this->label_->name(); }
20756 private:
20757 // The label whose address we are taking.
20758 Label* label_;
20761 // Make an expression for the address of an unnamed label.
20763 Expression*
20764 Expression::make_label_addr(Label* label, Location location)
20766 return new Label_addr_expression(label, location);
20769 // Class Conditional_expression.
20771 // Traversal.
20774 Conditional_expression::do_traverse(Traverse* traverse)
20776 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
20777 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
20778 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
20779 return TRAVERSE_EXIT;
20780 return TRAVERSE_CONTINUE;
20783 // Return the type of the conditional expression.
20785 Type*
20786 Conditional_expression::do_type()
20788 Type* result_type = Type::make_void_type();
20789 if (Type::are_identical(this->then_->type(), this->else_->type(),
20790 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
20791 NULL))
20792 result_type = this->then_->type();
20793 else if (this->then_->is_nil_expression()
20794 || this->else_->is_nil_expression())
20795 result_type = (!this->then_->is_nil_expression()
20796 ? this->then_->type()
20797 : this->else_->type());
20798 return result_type;
20801 // Determine type for a conditional expression.
20803 void
20804 Conditional_expression::do_determine_type(Gogo* gogo,
20805 const Type_context* context)
20807 this->cond_->determine_type_no_context(gogo);
20808 this->then_->determine_type(gogo, context);
20809 this->else_->determine_type(gogo, context);
20812 // Get the backend representation of a conditional expression.
20814 Bexpression*
20815 Conditional_expression::do_get_backend(Translate_context* context)
20817 Gogo* gogo = context->gogo();
20818 Btype* result_btype = this->type()->get_backend(gogo);
20819 Bexpression* cond = this->cond_->get_backend(context);
20820 Bexpression* then = this->then_->get_backend(context);
20821 Bexpression* belse = this->else_->get_backend(context);
20822 Bfunction* bfn = context->function()->func_value()->get_decl();
20823 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
20824 belse, this->location());
20827 // Dump ast representation of a conditional expression.
20829 void
20830 Conditional_expression::do_dump_expression(
20831 Ast_dump_context* ast_dump_context) const
20833 ast_dump_context->ostream() << "(";
20834 ast_dump_context->dump_expression(this->cond_);
20835 ast_dump_context->ostream() << " ? ";
20836 ast_dump_context->dump_expression(this->then_);
20837 ast_dump_context->ostream() << " : ";
20838 ast_dump_context->dump_expression(this->else_);
20839 ast_dump_context->ostream() << ") ";
20842 // Make a conditional expression.
20844 Expression*
20845 Expression::make_conditional(Expression* cond, Expression* then,
20846 Expression* else_expr, Location location)
20848 return new Conditional_expression(cond, then, else_expr, location);
20851 // Class Compound_expression.
20853 // Traversal.
20856 Compound_expression::do_traverse(Traverse* traverse)
20858 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
20859 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
20860 return TRAVERSE_EXIT;
20861 return TRAVERSE_CONTINUE;
20864 // Return the type of the compound expression.
20866 Type*
20867 Compound_expression::do_type()
20869 return this->expr_->type();
20872 // Determine type for a compound expression.
20874 void
20875 Compound_expression::do_determine_type(Gogo* gogo, const Type_context* context)
20877 this->init_->determine_type_no_context(gogo);
20878 this->expr_->determine_type(gogo, context);
20881 // Get the backend representation of a compound expression.
20883 Bexpression*
20884 Compound_expression::do_get_backend(Translate_context* context)
20886 Gogo* gogo = context->gogo();
20887 Bexpression* binit = this->init_->get_backend(context);
20888 Bfunction* bfunction = context->function()->func_value()->get_decl();
20889 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
20890 binit);
20891 Bexpression* bexpr = this->expr_->get_backend(context);
20892 return gogo->backend()->compound_expression(init_stmt, bexpr,
20893 this->location());
20896 // Dump ast representation of a conditional expression.
20898 void
20899 Compound_expression::do_dump_expression(
20900 Ast_dump_context* ast_dump_context) const
20902 ast_dump_context->ostream() << "(";
20903 ast_dump_context->dump_expression(this->init_);
20904 ast_dump_context->ostream() << ",";
20905 ast_dump_context->dump_expression(this->expr_);
20906 ast_dump_context->ostream() << ") ";
20909 // Make a compound expression.
20911 Expression*
20912 Expression::make_compound(Expression* init, Expression* expr, Location location)
20914 return new Compound_expression(init, expr, location);
20917 // Class Backend_expression.
20920 Backend_expression::do_traverse(Traverse*)
20922 return TRAVERSE_CONTINUE;
20925 Expression*
20926 Backend_expression::do_copy()
20928 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
20929 this->location());
20932 void
20933 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
20935 ast_dump_context->ostream() << "backend_expression<";
20936 ast_dump_context->dump_type(this->type_);
20937 ast_dump_context->ostream() << ">";
20940 Expression*
20941 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
20943 return new Backend_expression(bexpr, type, location);
20946 // Import an expression. This comes at the end in order to see the
20947 // various class definitions.
20949 Expression*
20950 Expression::import_expression(Import_expression* imp, Location loc)
20952 Expression* expr = Expression::import_expression_without_suffix(imp, loc);
20953 while (true)
20955 if (imp->match_c_string("("))
20957 imp->advance(1);
20958 Expression_list* args = new Expression_list();
20959 bool is_varargs = false;
20960 while (!imp->match_c_string(")"))
20962 Expression* arg = Expression::import_expression(imp, loc);
20963 if (arg->is_error_expression())
20964 return arg;
20965 args->push_back(arg);
20966 if (imp->match_c_string(")"))
20967 break;
20968 else if (imp->match_c_string("...)"))
20970 imp->advance(3);
20971 is_varargs = true;
20972 break;
20974 imp->require_c_string(", ");
20976 imp->require_c_string(")");
20977 expr = Expression::make_call(expr, args, is_varargs, loc);
20978 expr->call_expression()->set_varargs_are_lowered();
20980 else if (imp->match_c_string("["))
20982 imp->advance(1);
20983 Expression* start = Expression::import_expression(imp, loc);
20984 Expression* end = NULL;
20985 Expression* cap = NULL;
20986 if (imp->match_c_string(":"))
20988 imp->advance(1);
20989 int c = imp->peek_char();
20990 if (c == ':' || c == ']')
20991 end = Expression::make_nil(loc);
20992 else
20993 end = Expression::import_expression(imp, loc);
20994 if (imp->match_c_string(":"))
20996 imp->advance(1);
20997 cap = Expression::import_expression(imp, loc);
21000 imp->require_c_string("]");
21001 expr = Expression::make_index(expr, start, end, cap, loc);
21003 else
21004 break;
21007 return expr;
21010 // Import an expression without considering a suffix (function
21011 // arguments, index operations, etc.).
21013 Expression*
21014 Expression::import_expression_without_suffix(Import_expression* imp,
21015 Location loc)
21017 int c = imp->peek_char();
21018 if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
21019 return Unary_expression::do_import(imp, loc);
21020 else if (c == '(')
21021 return Binary_expression::do_import(imp, loc);
21022 else if (imp->match_c_string("$true")
21023 || imp->match_c_string("$false")
21024 || (imp->version() < EXPORT_FORMAT_V3
21025 && (imp->match_c_string("true")
21026 || imp->match_c_string("false"))))
21027 return Boolean_expression::do_import(imp, loc);
21028 else if (c == '"')
21029 return String_expression::do_import(imp, loc);
21030 else if (c == '-' || (c >= '0' && c <= '9'))
21032 // This handles integers, floats and complex constants.
21033 return Integer_expression::do_import(imp, loc);
21035 else if (imp->match_c_string("<-"))
21036 return Receive_expression::do_import(imp, loc);
21037 else if (imp->match_c_string("$nil")
21038 || (imp->version() < EXPORT_FORMAT_V3
21039 && imp->match_c_string("nil")))
21040 return Nil_expression::do_import(imp, loc);
21041 else if (imp->match_c_string("$convert")
21042 || (imp->version() < EXPORT_FORMAT_V3
21043 && imp->match_c_string("convert")))
21044 return Type_conversion_expression::do_import(imp, loc);
21046 Import_function_body* ifb = imp->ifb();
21047 if (ifb == NULL)
21049 go_error_at(imp->location(), "import error: expected expression");
21050 return Expression::make_error(loc);
21052 if (ifb->saw_error())
21053 return Expression::make_error(loc);
21055 if (ifb->match_c_string("$t"))
21056 return Temporary_reference_expression::do_import(ifb, loc);
21058 return Expression::import_identifier(ifb, loc);
21061 // Import an identifier in an expression. This is a reference to a
21062 // variable or function.
21064 Expression*
21065 Expression::import_identifier(Import_function_body* ifb, Location loc)
21067 std::string id;
21068 Package* pkg;
21069 bool is_exported;
21070 if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
21072 if (!ifb->saw_error())
21073 go_error_at(ifb->location(),
21074 "import error for %qs: bad qualified identifier at %lu",
21075 ifb->name().c_str(),
21076 static_cast<unsigned long>(ifb->off()));
21077 ifb->set_saw_error();
21078 return Expression::make_error(loc);
21081 Named_object* no = NULL;
21082 if (pkg == NULL && is_exported)
21083 no = ifb->block()->bindings()->lookup(id);
21084 if (no == NULL)
21086 const Package* ipkg = pkg;
21087 if (ipkg == NULL)
21088 ipkg = ifb->function()->package();
21089 if (!is_exported)
21090 id = '.' + ipkg->pkgpath() + '.' + id;
21091 no = ipkg->bindings()->lookup(id);
21093 if (no == NULL)
21094 no = ifb->gogo()->lookup_global(id.c_str());
21096 if (no == NULL)
21098 if (!ifb->saw_error())
21099 go_error_at(ifb->location(),
21100 "import error for %qs: lookup of %qs failed",
21101 ifb->name().c_str(), id.c_str());
21102 ifb->set_saw_error();
21103 return Expression::make_error(loc);
21106 if (no->is_variable() || no->is_result_variable())
21107 return Expression::make_var_reference(no, loc);
21108 else if (no->is_function() || no->is_function_declaration())
21109 return Expression::make_func_reference(no, NULL, loc);
21110 else
21112 if (!ifb->saw_error())
21113 go_error_at(ifb->location(),
21114 ("import error for %qs: "
21115 "unexpected type of identifier %qs (%d)"),
21116 ifb->name().c_str(),
21117 id.c_str(), no->classification());
21118 ifb->set_saw_error();
21119 return Expression::make_error(loc);
21123 // Class Expression_list.
21125 // Traverse the list.
21128 Expression_list::traverse(Traverse* traverse)
21130 for (Expression_list::iterator p = this->begin();
21131 p != this->end();
21132 ++p)
21134 if (*p != NULL)
21136 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
21137 return TRAVERSE_EXIT;
21140 return TRAVERSE_CONTINUE;
21143 // Copy the list.
21145 Expression_list*
21146 Expression_list::copy()
21148 Expression_list* ret = new Expression_list();
21149 for (Expression_list::iterator p = this->begin();
21150 p != this->end();
21151 ++p)
21153 if (*p == NULL)
21154 ret->push_back(NULL);
21155 else
21156 ret->push_back((*p)->copy());
21158 return ret;
21161 // Return whether an expression list has an error expression.
21163 bool
21164 Expression_list::contains_error() const
21166 for (Expression_list::const_iterator p = this->begin();
21167 p != this->end();
21168 ++p)
21169 if (*p != NULL && (*p)->is_error_expression())
21170 return true;
21171 return false;
21174 // Class Numeric_constant.
21176 // Destructor.
21178 Numeric_constant::~Numeric_constant()
21180 this->clear();
21183 // Copy constructor.
21185 Numeric_constant::Numeric_constant(const Numeric_constant& a)
21186 : classification_(a.classification_), type_(a.type_)
21188 switch (a.classification_)
21190 case NC_INVALID:
21191 break;
21192 case NC_INT:
21193 case NC_RUNE:
21194 mpz_init_set(this->u_.int_val, a.u_.int_val);
21195 break;
21196 case NC_FLOAT:
21197 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
21198 break;
21199 case NC_COMPLEX:
21200 mpc_init2(this->u_.complex_val, mpc_precision);
21201 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
21202 break;
21203 default:
21204 go_unreachable();
21208 // Assignment operator.
21210 Numeric_constant&
21211 Numeric_constant::operator=(const Numeric_constant& a)
21213 this->clear();
21214 this->classification_ = a.classification_;
21215 this->type_ = a.type_;
21216 switch (a.classification_)
21218 case NC_INVALID:
21219 break;
21220 case NC_INT:
21221 case NC_RUNE:
21222 mpz_init_set(this->u_.int_val, a.u_.int_val);
21223 break;
21224 case NC_FLOAT:
21225 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
21226 break;
21227 case NC_COMPLEX:
21228 mpc_init2(this->u_.complex_val, mpc_precision);
21229 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
21230 break;
21231 default:
21232 go_unreachable();
21234 return *this;
21237 // Check equality with another numeric constant.
21239 bool
21240 Numeric_constant::equals(const Numeric_constant& a) const
21242 if (this->classification_ != a.classification_)
21243 return false;
21245 if (this->type_ != NULL && a.type_ != NULL
21246 && !Type::are_identical(this->type_, a.type_,
21247 Type::COMPARE_ALIASES, NULL))
21248 return false;
21250 switch (a.classification_)
21252 case NC_INVALID:
21253 break;
21254 case NC_INT:
21255 case NC_RUNE:
21256 return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
21257 case NC_FLOAT:
21258 return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
21259 case NC_COMPLEX:
21260 return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
21261 default:
21262 go_unreachable();
21264 return false;
21267 // Clear the contents.
21269 void
21270 Numeric_constant::clear()
21272 switch (this->classification_)
21274 case NC_INVALID:
21275 break;
21276 case NC_INT:
21277 case NC_RUNE:
21278 mpz_clear(this->u_.int_val);
21279 break;
21280 case NC_FLOAT:
21281 mpfr_clear(this->u_.float_val);
21282 break;
21283 case NC_COMPLEX:
21284 mpc_clear(this->u_.complex_val);
21285 break;
21286 default:
21287 go_unreachable();
21289 this->classification_ = NC_INVALID;
21292 // Set to an unsigned long value.
21294 void
21295 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
21297 this->clear();
21298 this->classification_ = NC_INT;
21299 this->type_ = type;
21300 mpz_init_set_ui(this->u_.int_val, val);
21303 // Set to an integer value.
21305 void
21306 Numeric_constant::set_int(Type* type, const mpz_t val)
21308 this->clear();
21309 this->classification_ = NC_INT;
21310 this->type_ = type;
21311 mpz_init_set(this->u_.int_val, val);
21314 // Set to a rune value.
21316 void
21317 Numeric_constant::set_rune(Type* type, const mpz_t val)
21319 this->clear();
21320 this->classification_ = NC_RUNE;
21321 this->type_ = type;
21322 mpz_init_set(this->u_.int_val, val);
21325 // Set to a floating point value.
21327 void
21328 Numeric_constant::set_float(Type* type, const mpfr_t val)
21330 this->clear();
21331 this->classification_ = NC_FLOAT;
21332 this->type_ = type;
21334 // Numeric constants do not have negative zero values, so remove
21335 // them here. They also don't have infinity or NaN values, but we
21336 // should never see them here.
21337 int bits = 0;
21338 if (type != NULL
21339 && type->float_type() != NULL
21340 && !type->float_type()->is_abstract())
21341 bits = type->float_type()->bits();
21342 if (Numeric_constant::is_float_neg_zero(val, bits))
21343 mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
21344 else
21345 mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
21348 // Set to a complex value.
21350 void
21351 Numeric_constant::set_complex(Type* type, const mpc_t val)
21353 this->clear();
21354 this->classification_ = NC_COMPLEX;
21355 this->type_ = type;
21357 // Avoid negative zero as in set_float.
21358 int bits = 0;
21359 if (type != NULL
21360 && type->complex_type() != NULL
21361 && !type->complex_type()->is_abstract())
21362 bits = type->complex_type()->bits() / 2;
21364 mpfr_t real;
21365 mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
21366 if (Numeric_constant::is_float_neg_zero(real, bits))
21367 mpfr_set_ui(real, 0, MPFR_RNDN);
21369 mpfr_t imag;
21370 mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
21371 if (Numeric_constant::is_float_neg_zero(imag, bits))
21372 mpfr_set_ui(imag, 0, MPFR_RNDN);
21374 mpc_init2(this->u_.complex_val, mpc_precision);
21375 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
21377 mpfr_clear(real);
21378 mpfr_clear(imag);
21381 // Return whether VAL, at a precision of BITS, is a negative zero.
21382 // BITS may be zero in which case it is ignored.
21384 bool
21385 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
21387 if (!mpfr_signbit(val))
21388 return false;
21389 if (mpfr_zero_p(val))
21390 return true;
21391 mpfr_exp_t min_exp;
21392 switch (bits)
21394 case 0:
21395 return false;
21396 case 32:
21397 // In a denormalized float32 the exponent is -126, and there are
21398 // 24 bits of which at least the last must be 1, so the smallest
21399 // representable non-zero exponent is -126 - (24 - 1) == -149.
21400 min_exp = -149;
21401 break;
21402 case 64:
21403 // Minimum exponent is -1022, there are 53 bits.
21404 min_exp = -1074;
21405 break;
21406 default:
21407 go_unreachable();
21409 return mpfr_get_exp(val) < min_exp;
21412 // Get an int value.
21414 void
21415 Numeric_constant::get_int(mpz_t* val) const
21417 go_assert(this->is_int());
21418 mpz_init_set(*val, this->u_.int_val);
21421 // Get a rune value.
21423 void
21424 Numeric_constant::get_rune(mpz_t* val) const
21426 go_assert(this->is_rune());
21427 mpz_init_set(*val, this->u_.int_val);
21430 // Get a floating point value.
21432 void
21433 Numeric_constant::get_float(mpfr_t* val) const
21435 go_assert(this->is_float());
21436 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
21439 // Get a complex value.
21441 void
21442 Numeric_constant::get_complex(mpc_t* val) const
21444 go_assert(this->is_complex());
21445 mpc_init2(*val, mpc_precision);
21446 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
21449 // Express value as unsigned long if possible.
21451 Numeric_constant::To_unsigned_long
21452 Numeric_constant::to_unsigned_long(unsigned long* val) const
21454 switch (this->classification_)
21456 case NC_INT:
21457 case NC_RUNE:
21458 return this->mpz_to_unsigned_long(this->u_.int_val, val);
21459 case NC_FLOAT:
21460 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
21461 case NC_COMPLEX:
21462 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
21463 return NC_UL_NOTINT;
21464 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
21465 val);
21466 default:
21467 go_unreachable();
21471 // Express integer value as unsigned long if possible.
21473 Numeric_constant::To_unsigned_long
21474 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
21475 unsigned long *val) const
21477 if (mpz_sgn(ival) < 0)
21478 return NC_UL_NEGATIVE;
21479 unsigned long ui = mpz_get_ui(ival);
21480 if (mpz_cmp_ui(ival, ui) != 0)
21481 return NC_UL_BIG;
21482 *val = ui;
21483 return NC_UL_VALID;
21486 // Express floating point value as unsigned long if possible.
21488 Numeric_constant::To_unsigned_long
21489 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
21490 unsigned long *val) const
21492 if (!mpfr_integer_p(fval))
21493 return NC_UL_NOTINT;
21494 mpz_t ival;
21495 mpz_init(ival);
21496 mpfr_get_z(ival, fval, MPFR_RNDN);
21497 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
21498 mpz_clear(ival);
21499 return ret;
21502 // Express value as memory size if possible.
21504 bool
21505 Numeric_constant::to_memory_size(int64_t* val) const
21507 switch (this->classification_)
21509 case NC_INT:
21510 case NC_RUNE:
21511 return this->mpz_to_memory_size(this->u_.int_val, val);
21512 case NC_FLOAT:
21513 return this->mpfr_to_memory_size(this->u_.float_val, val);
21514 case NC_COMPLEX:
21515 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
21516 return false;
21517 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
21518 default:
21519 go_unreachable();
21523 // Express integer as memory size if possible.
21525 bool
21526 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
21528 if (mpz_sgn(ival) < 0)
21529 return false;
21530 if (mpz_fits_slong_p(ival))
21532 *val = static_cast<int64_t>(mpz_get_si(ival));
21533 return true;
21536 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
21537 // positive value.
21538 if (mpz_sizeinbase(ival, 2) >= 64)
21539 return false;
21541 mpz_t q, r;
21542 mpz_init(q);
21543 mpz_init(r);
21544 mpz_tdiv_q_2exp(q, ival, 32);
21545 mpz_tdiv_r_2exp(r, ival, 32);
21546 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
21547 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
21548 + static_cast<int64_t>(mpz_get_ui(r)));
21549 mpz_clear(r);
21550 mpz_clear(q);
21551 return true;
21554 // Express floating point value as memory size if possible.
21556 bool
21557 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
21559 if (!mpfr_integer_p(fval))
21560 return false;
21561 mpz_t ival;
21562 mpz_init(ival);
21563 mpfr_get_z(ival, fval, MPFR_RNDN);
21564 bool ret = this->mpz_to_memory_size(ival, val);
21565 mpz_clear(ival);
21566 return ret;
21569 // Convert value to integer if possible.
21571 bool
21572 Numeric_constant::to_int(mpz_t* val) const
21574 switch (this->classification_)
21576 case NC_INT:
21577 case NC_RUNE:
21578 mpz_init_set(*val, this->u_.int_val);
21579 return true;
21580 case NC_FLOAT:
21581 if (!mpfr_integer_p(this->u_.float_val))
21582 return false;
21583 mpz_init(*val);
21584 mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
21585 return true;
21586 case NC_COMPLEX:
21587 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
21588 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
21589 return false;
21590 mpz_init(*val);
21591 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
21592 return true;
21593 default:
21594 go_unreachable();
21598 // Convert value to floating point if possible.
21600 bool
21601 Numeric_constant::to_float(mpfr_t* val) const
21603 switch (this->classification_)
21605 case NC_INT:
21606 case NC_RUNE:
21607 mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
21608 return true;
21609 case NC_FLOAT:
21610 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
21611 return true;
21612 case NC_COMPLEX:
21613 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
21614 return false;
21615 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
21616 return true;
21617 default:
21618 go_unreachable();
21622 // Convert value to complex.
21624 bool
21625 Numeric_constant::to_complex(mpc_t* val) const
21627 mpc_init2(*val, mpc_precision);
21628 switch (this->classification_)
21630 case NC_INT:
21631 case NC_RUNE:
21632 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
21633 return true;
21634 case NC_FLOAT:
21635 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
21636 return true;
21637 case NC_COMPLEX:
21638 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
21639 return true;
21640 default:
21641 go_unreachable();
21645 // Get the type.
21647 Type*
21648 Numeric_constant::type() const
21650 if (this->type_ != NULL)
21651 return this->type_;
21652 switch (this->classification_)
21654 case NC_INT:
21655 return Type::make_abstract_integer_type();
21656 case NC_RUNE:
21657 return Type::make_abstract_character_type();
21658 case NC_FLOAT:
21659 return Type::make_abstract_float_type();
21660 case NC_COMPLEX:
21661 return Type::make_abstract_complex_type();
21662 default:
21663 go_unreachable();
21667 // If the constant can be expressed in TYPE, then set the type of the
21668 // constant to TYPE and return true. Otherwise return false, and, if
21669 // ISSUE_ERROR is true, report an appropriate error message.
21671 bool
21672 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
21674 bool ret;
21675 if (type == NULL || type->is_error())
21676 ret = true;
21677 else if (type->integer_type() != NULL)
21678 ret = this->check_int_type(type->integer_type(), issue_error, loc);
21679 else if (type->float_type() != NULL)
21680 ret = this->check_float_type(type->float_type(), issue_error, loc);
21681 else if (type->complex_type() != NULL)
21682 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
21683 else
21685 ret = false;
21686 if (issue_error)
21687 go_assert(saw_errors());
21689 if (ret)
21690 this->type_ = type;
21691 return ret;
21694 // Check whether the constant can be expressed in an integer type.
21696 bool
21697 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
21698 Location location)
21700 mpz_t val;
21701 switch (this->classification_)
21703 case NC_INT:
21704 case NC_RUNE:
21705 mpz_init_set(val, this->u_.int_val);
21706 break;
21708 case NC_FLOAT:
21709 if (!mpfr_integer_p(this->u_.float_val))
21711 if (issue_error)
21713 go_error_at(location,
21714 "floating-point constant truncated to integer");
21715 this->set_invalid();
21717 return false;
21719 mpz_init(val);
21720 mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
21721 break;
21723 case NC_COMPLEX:
21724 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
21725 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
21727 if (issue_error)
21729 go_error_at(location, "complex constant truncated to integer");
21730 this->set_invalid();
21732 return false;
21734 mpz_init(val);
21735 mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
21736 break;
21738 default:
21739 go_unreachable();
21742 bool ret;
21743 if (type->is_abstract())
21744 ret = true;
21745 else
21747 int bits = mpz_sizeinbase(val, 2);
21748 if (type->is_unsigned())
21750 // For an unsigned type we can only accept a nonnegative
21751 // number, and we must be able to represents at least BITS.
21752 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
21754 else
21756 // For a signed type we need an extra bit to indicate the
21757 // sign. We have to handle the most negative integer
21758 // specially.
21759 ret = (bits + 1 <= type->bits()
21760 || (bits <= type->bits()
21761 && mpz_sgn(val) < 0
21762 && (mpz_scan1(val, 0)
21763 == static_cast<unsigned long>(type->bits() - 1))
21764 && mpz_scan0(val, type->bits()) == ULONG_MAX));
21768 if (!ret && issue_error)
21770 go_error_at(location, "integer constant overflow");
21771 this->set_invalid();
21774 return ret;
21777 // Check whether the constant can be expressed in a floating point
21778 // type.
21780 bool
21781 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
21782 Location location)
21784 mpfr_t val;
21785 switch (this->classification_)
21787 case NC_INT:
21788 case NC_RUNE:
21789 mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
21790 break;
21792 case NC_FLOAT:
21793 mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
21794 break;
21796 case NC_COMPLEX:
21797 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
21799 if (issue_error)
21801 this->set_invalid();
21802 go_error_at(location,
21803 "complex constant truncated to floating-point");
21805 return false;
21807 mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
21808 break;
21810 default:
21811 go_unreachable();
21814 bool ret;
21815 if (type->is_abstract())
21816 ret = true;
21817 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
21819 // A NaN or Infinity always fits in the range of the type.
21820 ret = true;
21822 else
21824 mpfr_exp_t exp = mpfr_get_exp(val);
21825 mpfr_exp_t max_exp;
21826 switch (type->bits())
21828 case 32:
21829 max_exp = 128;
21830 break;
21831 case 64:
21832 max_exp = 1024;
21833 break;
21834 default:
21835 go_unreachable();
21838 ret = exp <= max_exp;
21840 if (ret)
21842 // Round the constant to the desired type.
21843 mpfr_t t;
21844 mpfr_init(t);
21845 switch (type->bits())
21847 case 32:
21848 mpfr_set_prec(t, 24);
21849 break;
21850 case 64:
21851 mpfr_set_prec(t, 53);
21852 break;
21853 default:
21854 go_unreachable();
21856 mpfr_set(t, val, MPFR_RNDN);
21857 mpfr_set(val, t, MPFR_RNDN);
21858 mpfr_clear(t);
21860 this->set_float(type, val);
21864 mpfr_clear(val);
21866 if (!ret && issue_error)
21868 go_error_at(location, "floating-point constant overflow");
21869 this->set_invalid();
21872 return ret;
21875 // Check whether the constant can be expressed in a complex type.
21877 bool
21878 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
21879 Location location)
21881 if (type->is_abstract())
21882 return true;
21884 mpfr_exp_t max_exp;
21885 switch (type->bits())
21887 case 64:
21888 max_exp = 128;
21889 break;
21890 case 128:
21891 max_exp = 1024;
21892 break;
21893 default:
21894 go_unreachable();
21897 mpc_t val;
21898 mpc_init2(val, mpc_precision);
21899 switch (this->classification_)
21901 case NC_INT:
21902 case NC_RUNE:
21903 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
21904 break;
21906 case NC_FLOAT:
21907 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
21908 break;
21910 case NC_COMPLEX:
21911 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
21912 break;
21914 default:
21915 go_unreachable();
21918 bool ret = true;
21919 if (!mpfr_nan_p(mpc_realref(val))
21920 && !mpfr_inf_p(mpc_realref(val))
21921 && !mpfr_zero_p(mpc_realref(val))
21922 && mpfr_get_exp(mpc_realref(val)) > max_exp)
21924 if (issue_error)
21926 go_error_at(location, "complex real part overflow");
21927 this->set_invalid();
21929 ret = false;
21932 if (!mpfr_nan_p(mpc_imagref(val))
21933 && !mpfr_inf_p(mpc_imagref(val))
21934 && !mpfr_zero_p(mpc_imagref(val))
21935 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
21937 if (issue_error)
21939 go_error_at(location, "complex imaginary part overflow");
21940 this->set_invalid();
21942 ret = false;
21945 if (ret)
21947 // Round the constant to the desired type.
21948 mpc_t t;
21949 switch (type->bits())
21951 case 64:
21952 mpc_init2(t, 24);
21953 break;
21954 case 128:
21955 mpc_init2(t, 53);
21956 break;
21957 default:
21958 go_unreachable();
21960 mpc_set(t, val, MPC_RNDNN);
21961 mpc_set(val, t, MPC_RNDNN);
21962 mpc_clear(t);
21964 this->set_complex(type, val);
21967 mpc_clear(val);
21969 return ret;
21972 // Return an Expression for this value.
21974 Expression*
21975 Numeric_constant::expression(Location loc) const
21977 switch (this->classification_)
21979 case NC_INT:
21980 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
21981 case NC_RUNE:
21982 return Expression::make_character(&this->u_.int_val, this->type_, loc);
21983 case NC_FLOAT:
21984 return Expression::make_float(&this->u_.float_val, this->type_, loc);
21985 case NC_COMPLEX:
21986 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
21987 case NC_INVALID:
21988 go_assert(saw_errors());
21989 return Expression::make_error(loc);
21990 default:
21991 go_unreachable();
21995 // Calculate a hash code with a given seed.
21997 unsigned int
21998 Numeric_constant::hash(unsigned int seed) const
22000 unsigned long val;
22001 const unsigned int PRIME = 97;
22002 long e = 0;
22003 double f = 1.0;
22004 mpfr_t m;
22006 switch (this->classification_)
22008 case NC_INVALID:
22009 return PRIME;
22010 case NC_INT:
22011 case NC_RUNE:
22012 val = mpz_get_ui(this->u_.int_val);
22013 break;
22014 case NC_COMPLEX:
22015 mpfr_init(m);
22016 mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
22017 val = mpfr_get_ui(m, MPFR_RNDN);
22018 mpfr_clear(m);
22019 break;
22020 case NC_FLOAT:
22021 f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
22022 val = static_cast<unsigned long>(e + static_cast<long>(f));
22023 break;
22024 default:
22025 go_unreachable();
22028 return (static_cast<unsigned int>(val) + seed) * PRIME;