Daily bump.
[gcc.git] / gcc / go / gofrontend / expressions.cc
1 // expressions.cc -- Go frontend expression handling.
2
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.
6
7 #include "go-system.h"
8
9 #include <algorithm>
10
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"
24
25 // Class Expression.
26
27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
30 {
31 }
32
33 Expression::~Expression()
34 {
35 }
36
37 // Traverse the expressions.
38
39 int
40 Expression::traverse(Expression** pexpr, Traverse* traverse)
41 {
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
44 {
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;
50 }
51 return expr->do_traverse(traverse);
52 }
53
54 // Traverse subexpressions of this expression.
55
56 int
57 Expression::traverse_subexpressions(Traverse* traverse)
58 {
59 return this->do_traverse(traverse);
60 }
61
62 // A traversal used to set the location of subexpressions.
63
64 class Set_location : public Traverse
65 {
66 public:
67 Set_location(Location loc)
68 : Traverse(traverse_expressions),
69 loc_(loc)
70 { }
71
72 int
73 expression(Expression** pexpr);
74
75 private:
76 Location loc_;
77 };
78
79 // Set the location of an expression.
80
81 int
82 Set_location::expression(Expression** pexpr)
83 {
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())
89 {
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;
107 }
108
109 (*pexpr)->location_ = this->loc_;
110 return TRAVERSE_CONTINUE;
111 }
112
113 // Set the location of an expression and its subexpressions.
114
115 void
116 Expression::set_location(Location loc)
117 {
118 this->location_ = loc;
119 Set_location sl(loc);
120 this->traverse_subexpressions(&sl);
121 }
122
123 // Default implementation for do_traverse for child classes.
124
125 int
126 Expression::do_traverse(Traverse*)
127 {
128 return TRAVERSE_CONTINUE;
129 }
130
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.
134
135 bool
136 Expression::do_discarding_value()
137 {
138 this->unused_value_error();
139 return false;
140 }
141
142 // This virtual function is called to export expressions. This will
143 // only be used by expressions which may be constant.
144
145 void
146 Expression::do_export(Export_function_body*) const
147 {
148 go_unreachable();
149 }
150
151 // Write a name to the export data.
152
153 void
154 Expression::export_name(Export_function_body* efb, const Named_object* no)
155 {
156 if (no->package() != NULL)
157 {
158 char buf[50];
159 snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
160 efb->write_c_string(buf);
161 }
162
163 if (!Gogo::is_hidden_name(no->name()))
164 efb->write_string(no->name());
165 else
166 {
167 efb->write_c_string(".");
168 efb->write_string(Gogo::unpack_hidden_name(no->name()));
169 }
170 }
171
172 // Give an error saying that the value of the expression is not used.
173
174 void
175 Expression::unused_value_error()
176 {
177 if (this->type()->is_error())
178 {
179 go_assert(saw_errors());
180 this->set_is_error();
181 }
182 else
183 this->report_error(_("value computed is not used"));
184 }
185
186 // Note that this expression is an error. This is called by children
187 // when they discover an error.
188
189 void
190 Expression::set_is_error()
191 {
192 this->classification_ = EXPRESSION_ERROR;
193 }
194
195 // For children to call to report an error conveniently.
196
197 void
198 Expression::report_error(const char* msg)
199 {
200 go_error_at(this->location_, "%s", msg);
201 this->set_is_error();
202 }
203
204 // Set types of variables and constants. This is implemented by the
205 // child class.
206
207 void
208 Expression::determine_type(const Type_context* context)
209 {
210 this->do_determine_type(context);
211 }
212
213 // Set types when there is no context.
214
215 void
216 Expression::determine_type_no_context()
217 {
218 Type_context context;
219 this->do_determine_type(&context);
220 }
221
222 // Return true if two expressions refer to the same variable or struct
223 // field. This can only be true when there are no side effects.
224
225 bool
226 Expression::is_same_variable(Expression* a, Expression* b)
227 {
228 if (a->classification() != b->classification())
229 return false;
230
231 Var_expression* av = a->var_expression();
232 if (av != NULL)
233 return av->named_object() == b->var_expression()->named_object();
234
235 Field_reference_expression* af = a->field_reference_expression();
236 if (af != NULL)
237 {
238 Field_reference_expression* bf = b->field_reference_expression();
239 return (af->field_index() == bf->field_index()
240 && Expression::is_same_variable(af->expr(), bf->expr()));
241 }
242
243 Unary_expression* au = a->unary_expression();
244 if (au != NULL)
245 {
246 Unary_expression* bu = b->unary_expression();
247 return (au->op() == OPERATOR_MULT
248 && bu->op() == OPERATOR_MULT
249 && Expression::is_same_variable(au->operand(),
250 bu->operand()));
251 }
252
253 Array_index_expression* aie = a->array_index_expression();
254 if (aie != NULL)
255 {
256 Array_index_expression* bie = b->array_index_expression();
257 return (aie->end() == NULL
258 && bie->end() == NULL
259 && Expression::is_same_variable(aie->array(), bie->array())
260 && Expression::is_same_variable(aie->start(), bie->start()));
261 }
262
263 Numeric_constant aval;
264 if (a->numeric_constant_value(&aval))
265 {
266 Numeric_constant bval;
267 if (b->numeric_constant_value(&bval))
268 return aval.equals(bval);
269 }
270
271 return false;
272 }
273
274 // Return an expression handling any conversions which must be done during
275 // assignment.
276
277 Expression*
278 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
279 Expression* rhs, Location location)
280 {
281 Type* rhs_type = rhs->type();
282 if (lhs_type->is_error()
283 || rhs_type->is_error()
284 || rhs->is_error_expression())
285 return Expression::make_error(location);
286
287 bool are_identical = Type::are_identical(lhs_type, rhs_type,
288 (Type::COMPARE_ERRORS
289 | Type::COMPARE_TAGS),
290 NULL);
291 if (!are_identical && lhs_type->interface_type() != NULL)
292 {
293 // Type to interface conversions have been made explicit early.
294 go_assert(rhs_type->interface_type() != NULL);
295 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
296 location);
297 }
298 else if (!are_identical && rhs_type->interface_type() != NULL)
299 return Expression::convert_interface_to_type(gogo, lhs_type, rhs, location);
300 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
301 {
302 // Assigning nil to a slice.
303 Expression* nil = Expression::make_nil(location);
304 Expression* zero = Expression::make_integer_ul(0, NULL, location);
305 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
306 }
307 else if (rhs_type->is_nil_type())
308 return Expression::make_nil(location);
309 else if (are_identical)
310 {
311 if (lhs_type->forwarded() != rhs_type->forwarded())
312 {
313 // Different but identical types require an explicit
314 // conversion. This happens with type aliases.
315 return Expression::make_cast(lhs_type, rhs, location);
316 }
317
318 // No conversion is needed.
319 return rhs;
320 }
321 else if (lhs_type->points_to() != NULL)
322 return Expression::make_unsafe_cast(lhs_type, rhs, location);
323 else if (lhs_type->is_numeric_type())
324 return Expression::make_cast(lhs_type, rhs, location);
325 else if ((lhs_type->struct_type() != NULL
326 && rhs_type->struct_type() != NULL)
327 || (lhs_type->array_type() != NULL
328 && rhs_type->array_type() != NULL))
329 {
330 // This conversion must be permitted by Go, or we wouldn't have
331 // gotten here.
332 return Expression::make_unsafe_cast(lhs_type, rhs, location);
333 }
334 else
335 return rhs;
336 }
337
338 // Return an expression for a conversion from a non-interface type to an
339 // interface type. If ON_STACK is true, it can allocate the storage on
340 // stack.
341
342 Expression*
343 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
344 bool on_stack, Location location)
345 {
346 Interface_type* lhs_interface_type = lhs_type->interface_type();
347 bool lhs_is_empty = lhs_interface_type->is_empty();
348
349 // Since RHS_TYPE is a static type, we can create the interface
350 // method table at compile time.
351
352 // When setting an interface to nil, we just set both fields to
353 // NULL.
354 Type* rhs_type = rhs->type();
355 if (rhs_type->is_nil_type())
356 {
357 Expression* nil = Expression::make_nil(location);
358 return Expression::make_interface_value(lhs_type, nil, nil, location);
359 }
360
361 // This should have been checked already.
362 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
363 {
364 go_assert(saw_errors());
365 return Expression::make_error(location);
366 }
367
368 // An interface is a tuple. If LHS_TYPE is an empty interface type,
369 // then the first field is the type descriptor for RHS_TYPE.
370 // Otherwise it is the interface method table for RHS_TYPE.
371 Expression* first_field;
372 if (lhs_is_empty)
373 first_field = Expression::make_type_descriptor(rhs_type, location);
374 else
375 {
376 // Build the interface method table for this interface and this
377 // object type: a list of function pointers for each interface
378 // method.
379 Named_type* rhs_named_type = rhs_type->named_type();
380 Struct_type* rhs_struct_type = rhs_type->struct_type();
381 bool is_pointer = false;
382 if (rhs_named_type == NULL && rhs_struct_type == NULL)
383 {
384 rhs_named_type = rhs_type->deref()->named_type();
385 rhs_struct_type = rhs_type->deref()->struct_type();
386 is_pointer = true;
387 }
388 if (rhs_named_type != NULL)
389 first_field =
390 rhs_named_type->interface_method_table(lhs_interface_type,
391 is_pointer);
392 else if (rhs_struct_type != NULL)
393 first_field =
394 rhs_struct_type->interface_method_table(lhs_interface_type,
395 is_pointer);
396 else
397 first_field = Expression::make_nil(location);
398 }
399
400 Expression* obj;
401 if (rhs_type->is_direct_iface_type())
402 {
403 // We are assigning a pointer to the interface; the interface
404 // holds the pointer itself.
405 obj = unpack_direct_iface(rhs, location);
406 }
407 else
408 {
409 // We are assigning a non-pointer value to the interface; the
410 // interface gets a copy of the value in the heap if it escapes.
411 if (rhs->is_constant())
412 obj = Expression::make_unary(OPERATOR_AND, rhs, location);
413 else
414 {
415 obj = Expression::make_heap_expression(rhs, location);
416 if (on_stack)
417 obj->heap_expression()->set_allocate_on_stack();
418 }
419 }
420
421 return Expression::make_interface_value(lhs_type, first_field, obj, location);
422 }
423
424 // Return an expression for the pointer-typed value of a direct interface
425 // type. Specifically, for single field struct or array, get the single
426 // field, and do this recursively. The reason for this is that we don't
427 // want to assign a struct or an array to a pointer-typed field. The
428 // backend may not like that.
429
430 Expression*
431 Expression::unpack_direct_iface(Expression* rhs, Location loc)
432 {
433 Struct_type* st = rhs->type()->struct_type();
434 if (st != NULL)
435 {
436 go_assert(st->field_count() == 1);
437 Expression* field = Expression::make_field_reference(rhs, 0, loc);
438 return unpack_direct_iface(field, loc);
439 }
440 Array_type* at = rhs->type()->array_type();
441 if (at != NULL)
442 {
443 int64_t len;
444 bool ok = at->int_length(&len);
445 go_assert(ok && len == 1);
446 Type* int_type = Type::lookup_integer_type("int");
447 Expression* index = Expression::make_integer_ul(0, int_type, loc);
448 Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
449 return unpack_direct_iface(elem, loc);
450 }
451 return rhs;
452 }
453
454 // The opposite of unpack_direct_iface.
455
456 Expression*
457 Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
458 {
459 if (rhs->type() == t)
460 return rhs;
461 Struct_type* st = t->struct_type();
462 if (st != NULL)
463 {
464 Expression_list* vals = new Expression_list();
465 vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
466 return Expression::make_struct_composite_literal(t, vals, loc);
467 }
468 Array_type* at = t->array_type();
469 if (at != NULL)
470 {
471 Expression_list* vals = new Expression_list();
472 vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
473 return Expression::make_array_composite_literal(t, vals, loc);
474 }
475 return Expression::make_unsafe_cast(t, rhs, loc);
476 }
477
478 // Return an expression for the type descriptor of RHS.
479
480 Expression*
481 Expression::get_interface_type_descriptor(Expression* rhs)
482 {
483 go_assert(rhs->type()->interface_type() != NULL);
484 Location location = rhs->location();
485
486 // The type descriptor is the first field of an empty interface.
487 if (rhs->type()->interface_type()->is_empty())
488 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
489 location);
490
491 Expression* mtable =
492 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
493
494 Expression* descriptor =
495 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
496 descriptor = Expression::make_field_reference(descriptor, 0, location);
497 Expression* nil = Expression::make_nil(location);
498
499 Expression* eq =
500 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
501 return Expression::make_conditional(eq, nil, descriptor, location);
502 }
503
504 // Return an expression for the conversion of an interface type to an
505 // interface type.
506
507 Expression*
508 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
509 bool for_type_guard,
510 Location location)
511 {
512 if (Type::are_identical(lhs_type, rhs->type(),
513 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
514 NULL))
515 return rhs;
516
517 Interface_type* lhs_interface_type = lhs_type->interface_type();
518 bool lhs_is_empty = lhs_interface_type->is_empty();
519
520 // In the general case this requires runtime examination of the type
521 // method table to match it up with the interface methods.
522
523 // FIXME: If all of the methods in the right hand side interface
524 // also appear in the left hand side interface, then we don't need
525 // to do a runtime check, although we still need to build a new
526 // method table.
527
528 // We are going to evaluate RHS multiple times.
529 go_assert(rhs->is_variable());
530
531 // Get the type descriptor for the right hand side. This will be
532 // NULL for a nil interface.
533 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
534 Expression* lhs_type_expr =
535 Expression::make_type_descriptor(lhs_type, location);
536
537 Expression* first_field;
538 if (for_type_guard)
539 {
540 // A type assertion fails when converting a nil interface.
541 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
542 lhs_type_expr, rhs_type_expr);
543 }
544 else if (lhs_is_empty)
545 {
546 // A conversion to an empty interface always succeeds, and the
547 // first field is just the type descriptor of the object.
548 first_field = rhs_type_expr;
549 }
550 else
551 {
552 // A conversion to a non-empty interface may fail, but unlike a
553 // type assertion converting nil will always succeed.
554 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
555 lhs_type_expr, rhs_type_expr);
556 }
557
558 // The second field is simply the object pointer.
559 Expression* obj =
560 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
561 return Expression::make_interface_value(lhs_type, first_field, obj, location);
562 }
563
564 // Return an expression for the conversion of an interface type to a
565 // non-interface type.
566
567 Expression*
568 Expression::convert_interface_to_type(Gogo* gogo, Type *lhs_type, Expression* rhs,
569 Location location)
570 {
571 // We are going to evaluate RHS multiple times.
572 go_assert(rhs->is_variable());
573
574 // Build an expression to check that the type is valid. It will
575 // panic with an appropriate runtime type error if the type is not
576 // valid.
577 // (lhs_type == rhs_type ? nil /*dummy*/ :
578 // panicdottype(lhs_type, rhs_type, inter_type))
579 // For some Oses, we need to call runtime.eqtype instead of
580 // lhs_type == rhs_type, as we may have unmerged type descriptors
581 // from shared libraries.
582 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
583 location);
584 Expression* rhs_descriptor =
585 Expression::get_interface_type_descriptor(rhs);
586
587 Type* rhs_type = rhs->type();
588 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
589 location);
590
591 Expression* cond;
592 if (gogo->need_eqtype()) {
593 cond = Runtime::make_call(Runtime::EQTYPE, location,
594 2, lhs_type_expr,
595 rhs_descriptor);
596 } else {
597 cond = Expression::make_binary(OPERATOR_EQEQ, lhs_type_expr,
598 rhs_descriptor, location);
599 }
600
601 rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
602 Expression* panic = Runtime::make_call(Runtime::PANICDOTTYPE, location,
603 3, lhs_type_expr->copy(),
604 rhs_descriptor,
605 rhs_inter_expr);
606 Expression* nil = Expression::make_nil(location);
607 Expression* check = Expression::make_conditional(cond, nil, panic,
608 location);
609
610 // If the conversion succeeds, pull out the value.
611 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
612 location);
613
614 // If the value is a direct interface, then it is the value we want.
615 // Otherwise it points to the value.
616 if (lhs_type->is_direct_iface_type())
617 obj = Expression::pack_direct_iface(lhs_type, obj, location);
618 else
619 {
620 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
621 location);
622 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
623 location);
624 }
625 return Expression::make_compound(check, obj, location);
626 }
627
628 // Convert an expression to its backend representation. This is implemented by
629 // the child class. Not that it is not in general safe to call this multiple
630 // times for a single expression, but that we don't catch such errors.
631
632 Bexpression*
633 Expression::get_backend(Translate_context* context)
634 {
635 // The child may have marked this expression as having an error.
636 if (this->classification_ == EXPRESSION_ERROR)
637 {
638 go_assert(saw_errors());
639 return context->backend()->error_expression();
640 }
641
642 return this->do_get_backend(context);
643 }
644
645 // Return a backend expression for VAL.
646 Bexpression*
647 Expression::backend_numeric_constant_expression(Translate_context* context,
648 Numeric_constant* val)
649 {
650 Gogo* gogo = context->gogo();
651 Type* type = val->type();
652 if (type == NULL)
653 return gogo->backend()->error_expression();
654
655 Btype* btype = type->get_backend(gogo);
656 Bexpression* ret;
657 if (type->integer_type() != NULL)
658 {
659 mpz_t ival;
660 if (!val->to_int(&ival))
661 {
662 go_assert(saw_errors());
663 return gogo->backend()->error_expression();
664 }
665 ret = gogo->backend()->integer_constant_expression(btype, ival);
666 mpz_clear(ival);
667 }
668 else if (type->float_type() != NULL)
669 {
670 mpfr_t fval;
671 if (!val->to_float(&fval))
672 {
673 go_assert(saw_errors());
674 return gogo->backend()->error_expression();
675 }
676 ret = gogo->backend()->float_constant_expression(btype, fval);
677 mpfr_clear(fval);
678 }
679 else if (type->complex_type() != NULL)
680 {
681 mpc_t cval;
682 if (!val->to_complex(&cval))
683 {
684 go_assert(saw_errors());
685 return gogo->backend()->error_expression();
686 }
687 ret = gogo->backend()->complex_constant_expression(btype, cval);
688 mpc_clear(cval);
689 }
690 else
691 go_unreachable();
692
693 return ret;
694 }
695
696 // Insert bounds checks for an index expression. Check that that VAL
697 // >= 0 and that it fits in an int. Then check that VAL OP BOUND is
698 // true. If any condition is false, call one of the CODE runtime
699 // functions, which will panic.
700
701 void
702 Expression::check_bounds(Expression* val, Operator op, Expression* bound,
703 Runtime::Function code,
704 Runtime::Function code_u,
705 Runtime::Function code_extend,
706 Runtime::Function code_extend_u,
707 Statement_inserter* inserter,
708 Location loc)
709 {
710 go_assert(val->is_variable() || val->is_constant());
711 go_assert(bound->is_variable() || bound->is_constant());
712
713 Type* int_type = Type::lookup_integer_type("int");
714 int int_type_size = int_type->integer_type()->bits();
715
716 Type* val_type = val->type();
717 if (val_type->integer_type() == NULL)
718 {
719 go_assert(saw_errors());
720 return;
721 }
722 int val_type_size = val_type->integer_type()->bits();
723 bool val_is_unsigned = val_type->integer_type()->is_unsigned();
724
725 // Check that VAL >= 0.
726 Expression* check = NULL;
727 if (!val_is_unsigned)
728 {
729 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
730 check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
731 }
732
733 // If VAL's type is larger than int, check that VAL fits in an int.
734 if (val_type_size > int_type_size
735 || (val_type_size == int_type_size
736 && val_is_unsigned))
737 {
738 mpz_t one;
739 mpz_init_set_ui(one, 1UL);
740
741 // maxval = 2^(int_type_size - 1) - 1
742 mpz_t maxval;
743 mpz_init(maxval);
744 mpz_mul_2exp(maxval, one, int_type_size - 1);
745 mpz_sub_ui(maxval, maxval, 1);
746 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
747 mpz_clear(one);
748 mpz_clear(maxval);
749
750 Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
751 max, loc);
752 if (check == NULL)
753 check = cmp;
754 else
755 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
756 }
757
758 // For the final check we can assume that VAL fits in an int.
759 Expression* ival;
760 if (val_type == int_type)
761 ival = val->copy();
762 else
763 ival = Expression::make_cast(int_type, val->copy(), loc);
764
765 // BOUND is assumed to fit in an int. Either it comes from len or
766 // cap, or it was checked by an earlier call.
767 Expression* ibound;
768 if (bound->type() == int_type)
769 ibound = bound->copy();
770 else
771 ibound = Expression::make_cast(int_type, bound->copy(), loc);
772
773 Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
774 if (check == NULL)
775 check = cmp;
776 else
777 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
778
779 Runtime::Function c;
780 if (val_type_size > int_type_size)
781 {
782 if (val_is_unsigned)
783 c = code_extend_u;
784 else
785 c = code_extend;
786 }
787 else
788 {
789 if (val_is_unsigned)
790 c = code_u;
791 else
792 c = code;
793 }
794
795 Expression* ignore = Expression::make_boolean(true, loc);
796 Expression* crash = Runtime::make_call(c, loc, 2,
797 val->copy(), bound->copy());
798 Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
799 inserter->insert(Statement::make_statement(cond, true));
800 }
801
802 void
803 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
804 {
805 this->do_dump_expression(ast_dump_context);
806 }
807
808 // Error expressions. This are used to avoid cascading errors.
809
810 class Error_expression : public Expression
811 {
812 public:
813 Error_expression(Location location)
814 : Expression(EXPRESSION_ERROR, location)
815 { }
816
817 protected:
818 bool
819 do_is_constant() const
820 { return true; }
821
822 bool
823 do_numeric_constant_value(Numeric_constant* nc) const
824 {
825 nc->set_unsigned_long(NULL, 0);
826 return true;
827 }
828
829 bool
830 do_discarding_value()
831 { return true; }
832
833 Type*
834 do_type()
835 { return Type::make_error_type(); }
836
837 void
838 do_determine_type(const Type_context*)
839 { }
840
841 Expression*
842 do_copy()
843 { return this; }
844
845 bool
846 do_is_addressable() const
847 { return true; }
848
849 Bexpression*
850 do_get_backend(Translate_context* context)
851 { return context->backend()->error_expression(); }
852
853 void
854 do_dump_expression(Ast_dump_context*) const;
855 };
856
857 // Dump the ast representation for an error expression to a dump context.
858
859 void
860 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
861 {
862 ast_dump_context->ostream() << "_Error_" ;
863 }
864
865 Expression*
866 Expression::make_error(Location location)
867 {
868 return new Error_expression(location);
869 }
870
871 // An expression which is really a type. This is used during parsing.
872 // It is an error if these survive after lowering.
873
874 class
875 Type_expression : public Expression
876 {
877 public:
878 Type_expression(Type* type, Location location)
879 : Expression(EXPRESSION_TYPE, location),
880 type_(type)
881 { }
882
883 protected:
884 int
885 do_traverse(Traverse* traverse)
886 { return Type::traverse(this->type_, traverse); }
887
888 Type*
889 do_type()
890 { return this->type_; }
891
892 void
893 do_determine_type(const Type_context*)
894 { }
895
896 void
897 do_check_types(Gogo*);
898
899 Expression*
900 do_copy()
901 { return this; }
902
903 Bexpression*
904 do_get_backend(Translate_context*)
905 { go_unreachable(); }
906
907 void do_dump_expression(Ast_dump_context*) const;
908
909 private:
910 // The type which we are representing as an expression.
911 Type* type_;
912 };
913
914 void
915 Type_expression::do_check_types(Gogo*)
916 {
917 if (this->type_->is_error())
918 {
919 go_assert(saw_errors());
920 this->set_is_error();
921 }
922 else
923 this->report_error(_("invalid use of type"));
924 }
925
926 void
927 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
928 {
929 ast_dump_context->dump_type(this->type_);
930 }
931
932 Expression*
933 Expression::make_type(Type* type, Location location)
934 {
935 return new Type_expression(type, location);
936 }
937
938 // Class Parser_expression.
939
940 Type*
941 Parser_expression::do_type()
942 {
943 // We should never really ask for the type of a Parser_expression.
944 // However, it can happen, at least when we have an invalid const
945 // whose initializer refers to the const itself. In that case we
946 // may ask for the type when lowering the const itself.
947 go_assert(saw_errors());
948 return Type::make_error_type();
949 }
950
951 // Class Var_expression.
952
953 // Lower a variable expression. Here we just make sure that the
954 // initialization expression of the variable has been lowered. This
955 // ensures that we will be able to determine the type of the variable
956 // if necessary.
957
958 Expression*
959 Var_expression::do_lower(Gogo* gogo, Named_object* function,
960 Statement_inserter* inserter, int)
961 {
962 if (this->variable_->is_variable())
963 {
964 Variable* var = this->variable_->var_value();
965 // This is either a local variable or a global variable. A
966 // reference to a variable which is local to an enclosing
967 // function will be a reference to a field in a closure.
968 if (var->is_global())
969 {
970 function = NULL;
971 inserter = NULL;
972 }
973 var->lower_init_expression(gogo, function, inserter);
974 }
975 return this;
976 }
977
978 // Return the type of a reference to a variable.
979
980 Type*
981 Var_expression::do_type()
982 {
983 if (this->variable_->is_variable())
984 return this->variable_->var_value()->type();
985 else if (this->variable_->is_result_variable())
986 return this->variable_->result_var_value()->type();
987 else
988 go_unreachable();
989 }
990
991 // Determine the type of a reference to a variable.
992
993 void
994 Var_expression::do_determine_type(const Type_context*)
995 {
996 if (this->variable_->is_variable())
997 this->variable_->var_value()->determine_type();
998 }
999
1000 // Something takes the address of this variable. This means that we
1001 // may want to move the variable onto the heap.
1002
1003 void
1004 Var_expression::do_address_taken(bool escapes)
1005 {
1006 if (!escapes)
1007 {
1008 if (this->variable_->is_variable())
1009 this->variable_->var_value()->set_non_escaping_address_taken();
1010 else if (this->variable_->is_result_variable())
1011 this->variable_->result_var_value()->set_non_escaping_address_taken();
1012 else
1013 go_unreachable();
1014 }
1015 else
1016 {
1017 if (this->variable_->is_variable())
1018 this->variable_->var_value()->set_address_taken();
1019 else if (this->variable_->is_result_variable())
1020 this->variable_->result_var_value()->set_address_taken();
1021 else
1022 go_unreachable();
1023 }
1024
1025 if (this->variable_->is_variable()
1026 && this->variable_->var_value()->is_in_heap())
1027 {
1028 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
1029 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1030 }
1031 }
1032
1033 // Export a reference to a variable.
1034
1035 void
1036 Var_expression::do_export(Export_function_body* efb) const
1037 {
1038 Named_object* no = this->variable_;
1039 if (no->is_result_variable() || !no->var_value()->is_global())
1040 efb->write_string(Gogo::unpack_hidden_name(no->name()));
1041 else
1042 Expression::export_name(efb, no);
1043 }
1044
1045 // Get the backend representation for a reference to a variable.
1046
1047 Bexpression*
1048 Var_expression::do_get_backend(Translate_context* context)
1049 {
1050 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
1051 context->function());
1052 bool is_in_heap;
1053 Location loc = this->location();
1054 Btype* btype;
1055 Gogo* gogo = context->gogo();
1056 if (this->variable_->is_variable())
1057 {
1058 is_in_heap = this->variable_->var_value()->is_in_heap();
1059 btype = this->variable_->var_value()->type()->get_backend(gogo);
1060 }
1061 else if (this->variable_->is_result_variable())
1062 {
1063 is_in_heap = this->variable_->result_var_value()->is_in_heap();
1064 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
1065 }
1066 else
1067 go_unreachable();
1068
1069 Bexpression* ret =
1070 context->backend()->var_expression(bvar, loc);
1071 if (is_in_heap)
1072 ret = context->backend()->indirect_expression(btype, ret, true, loc);
1073 return ret;
1074 }
1075
1076 // Ast dump for variable expression.
1077
1078 void
1079 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1080 {
1081 ast_dump_context->ostream() << this->variable_->message_name() ;
1082 }
1083
1084 // Make a reference to a variable in an expression.
1085
1086 Expression*
1087 Expression::make_var_reference(Named_object* var, Location location)
1088 {
1089 if (var->is_sink())
1090 return Expression::make_sink(location);
1091
1092 // FIXME: Creating a new object for each reference to a variable is
1093 // wasteful.
1094 return new Var_expression(var, location);
1095 }
1096
1097 // Class Enclosed_var_expression.
1098
1099 int
1100 Enclosed_var_expression::do_traverse(Traverse*)
1101 {
1102 return TRAVERSE_CONTINUE;
1103 }
1104
1105 // Lower the reference to the enclosed variable.
1106
1107 Expression*
1108 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
1109 Statement_inserter* inserter, int)
1110 {
1111 gogo->lower_expression(function, inserter, &this->reference_);
1112 return this;
1113 }
1114
1115 // Flatten the reference to the enclosed variable.
1116
1117 Expression*
1118 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
1119 Statement_inserter* inserter)
1120 {
1121 gogo->flatten_expression(function, inserter, &this->reference_);
1122 return this;
1123 }
1124
1125 void
1126 Enclosed_var_expression::do_address_taken(bool escapes)
1127 {
1128 if (!escapes)
1129 {
1130 if (this->variable_->is_variable())
1131 this->variable_->var_value()->set_non_escaping_address_taken();
1132 else if (this->variable_->is_result_variable())
1133 this->variable_->result_var_value()->set_non_escaping_address_taken();
1134 else
1135 go_unreachable();
1136 }
1137 else
1138 {
1139 if (this->variable_->is_variable())
1140 this->variable_->var_value()->set_address_taken();
1141 else if (this->variable_->is_result_variable())
1142 this->variable_->result_var_value()->set_address_taken();
1143 else
1144 go_unreachable();
1145 }
1146
1147 if (this->variable_->is_variable()
1148 && this->variable_->var_value()->is_in_heap())
1149 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1150 }
1151
1152 // Ast dump for enclosed variable expression.
1153
1154 void
1155 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
1156 {
1157 adc->ostream() << this->variable_->message_name();
1158 }
1159
1160 // Make a reference to a variable within an enclosing function.
1161
1162 Expression*
1163 Expression::make_enclosing_var_reference(Expression* reference,
1164 Named_object* var, Location location)
1165 {
1166 return new Enclosed_var_expression(reference, var, location);
1167 }
1168
1169 // Class Temporary_reference_expression.
1170
1171 // The type.
1172
1173 Type*
1174 Temporary_reference_expression::do_type()
1175 {
1176 return this->statement_->type();
1177 }
1178
1179 // Called if something takes the address of this temporary variable.
1180 // We never have to move temporary variables to the heap, but we do
1181 // need to know that they must live in the stack rather than in a
1182 // register.
1183
1184 void
1185 Temporary_reference_expression::do_address_taken(bool)
1186 {
1187 this->statement_->set_is_address_taken();
1188 }
1189
1190 // Export a reference to a temporary.
1191
1192 void
1193 Temporary_reference_expression::do_export(Export_function_body* efb) const
1194 {
1195 unsigned int idx = efb->temporary_index(this->statement_);
1196 char buf[50];
1197 snprintf(buf, sizeof buf, "$t%u", idx);
1198 efb->write_c_string(buf);
1199 }
1200
1201 // Import a reference to a temporary.
1202
1203 Expression*
1204 Temporary_reference_expression::do_import(Import_function_body* ifb,
1205 Location loc)
1206 {
1207 std::string id = ifb->read_identifier();
1208 go_assert(id[0] == '$' && id[1] == 't');
1209 const char *p = id.c_str();
1210 char *end;
1211 long idx = strtol(p + 2, &end, 10);
1212 if (*end != '\0' || idx > 0x7fffffff)
1213 {
1214 if (!ifb->saw_error())
1215 go_error_at(loc,
1216 ("invalid export data for %qs: "
1217 "invalid temporary reference index at %lu"),
1218 ifb->name().c_str(),
1219 static_cast<unsigned long>(ifb->off()));
1220 ifb->set_saw_error();
1221 return Expression::make_error(loc);
1222 }
1223
1224 Temporary_statement* temp =
1225 ifb->temporary_statement(static_cast<unsigned int>(idx));
1226 if (temp == NULL)
1227 {
1228 if (!ifb->saw_error())
1229 go_error_at(loc,
1230 ("invalid export data for %qs: "
1231 "undefined temporary reference index at %lu"),
1232 ifb->name().c_str(),
1233 static_cast<unsigned long>(ifb->off()));
1234 ifb->set_saw_error();
1235 return Expression::make_error(loc);
1236 }
1237
1238 return Expression::make_temporary_reference(temp, loc);
1239 }
1240
1241 // Get a backend expression referring to the variable.
1242
1243 Bexpression*
1244 Temporary_reference_expression::do_get_backend(Translate_context* context)
1245 {
1246 Gogo* gogo = context->gogo();
1247 Bvariable* bvar = this->statement_->get_backend_variable(context);
1248 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1249
1250 // The backend can't always represent the same set of recursive types
1251 // that the Go frontend can. In some cases this means that a
1252 // temporary variable won't have the right backend type. Correct
1253 // that here by adding a type cast. We need to use base() to push
1254 // the circularity down one level.
1255 Type* stype = this->statement_->type();
1256 if (!this->is_lvalue_
1257 && stype->points_to() != NULL
1258 && stype->points_to()->is_void_type())
1259 {
1260 Btype* btype = this->type()->base()->get_backend(gogo);
1261 ret = gogo->backend()->convert_expression(btype, ret, this->location());
1262 }
1263 return ret;
1264 }
1265
1266 // Ast dump for temporary reference.
1267
1268 void
1269 Temporary_reference_expression::do_dump_expression(
1270 Ast_dump_context* ast_dump_context) const
1271 {
1272 ast_dump_context->dump_temp_variable_name(this->statement_);
1273 }
1274
1275 // Make a reference to a temporary variable.
1276
1277 Temporary_reference_expression*
1278 Expression::make_temporary_reference(Temporary_statement* statement,
1279 Location location)
1280 {
1281 statement->add_use();
1282 return new Temporary_reference_expression(statement, location);
1283 }
1284
1285 // Class Set_and_use_temporary_expression.
1286
1287 // Return the type.
1288
1289 Type*
1290 Set_and_use_temporary_expression::do_type()
1291 {
1292 return this->statement_->type();
1293 }
1294
1295 // Determine the type of the expression.
1296
1297 void
1298 Set_and_use_temporary_expression::do_determine_type(
1299 const Type_context* context)
1300 {
1301 this->expr_->determine_type(context);
1302 }
1303
1304 // Take the address.
1305
1306 void
1307 Set_and_use_temporary_expression::do_address_taken(bool)
1308 {
1309 this->statement_->set_is_address_taken();
1310 }
1311
1312 // Return the backend representation.
1313
1314 Bexpression*
1315 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1316 {
1317 Location loc = this->location();
1318 Gogo* gogo = context->gogo();
1319 Bvariable* bvar = this->statement_->get_backend_variable(context);
1320 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1321
1322 Named_object* fn = context->function();
1323 go_assert(fn != NULL);
1324 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1325 Bexpression* bexpr = this->expr_->get_backend(context);
1326 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1327 bexpr, loc);
1328 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1329 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1330 return ret;
1331 }
1332
1333 // Dump.
1334
1335 void
1336 Set_and_use_temporary_expression::do_dump_expression(
1337 Ast_dump_context* ast_dump_context) const
1338 {
1339 ast_dump_context->ostream() << '(';
1340 ast_dump_context->dump_temp_variable_name(this->statement_);
1341 ast_dump_context->ostream() << " = ";
1342 this->expr_->dump_expression(ast_dump_context);
1343 ast_dump_context->ostream() << ')';
1344 }
1345
1346 // Make a set-and-use temporary.
1347
1348 Set_and_use_temporary_expression*
1349 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1350 Expression* expr, Location location)
1351 {
1352 return new Set_and_use_temporary_expression(statement, expr, location);
1353 }
1354
1355 // A sink expression--a use of the blank identifier _.
1356
1357 class Sink_expression : public Expression
1358 {
1359 public:
1360 Sink_expression(Location location)
1361 : Expression(EXPRESSION_SINK, location),
1362 type_(NULL), bvar_(NULL)
1363 { }
1364
1365 protected:
1366 bool
1367 do_discarding_value()
1368 { return true; }
1369
1370 Type*
1371 do_type();
1372
1373 void
1374 do_determine_type(const Type_context*);
1375
1376 Expression*
1377 do_copy()
1378 { return new Sink_expression(this->location()); }
1379
1380 Bexpression*
1381 do_get_backend(Translate_context*);
1382
1383 void
1384 do_dump_expression(Ast_dump_context*) const;
1385
1386 private:
1387 // The type of this sink variable.
1388 Type* type_;
1389 // The temporary variable we generate.
1390 Bvariable* bvar_;
1391 };
1392
1393 // Return the type of a sink expression.
1394
1395 Type*
1396 Sink_expression::do_type()
1397 {
1398 if (this->type_ == NULL)
1399 return Type::make_sink_type();
1400 return this->type_;
1401 }
1402
1403 // Determine the type of a sink expression.
1404
1405 void
1406 Sink_expression::do_determine_type(const Type_context* context)
1407 {
1408 if (context->type != NULL)
1409 this->type_ = context->type;
1410 }
1411
1412 // Return a temporary variable for a sink expression. This will
1413 // presumably be a write-only variable which the middle-end will drop.
1414
1415 Bexpression*
1416 Sink_expression::do_get_backend(Translate_context* context)
1417 {
1418 Location loc = this->location();
1419 Gogo* gogo = context->gogo();
1420 if (this->bvar_ == NULL)
1421 {
1422 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1423 Named_object* fn = context->function();
1424 go_assert(fn != NULL);
1425 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1426 Btype* bt = this->type_->get_backend(context->gogo());
1427 Bstatement* decl;
1428 this->bvar_ =
1429 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1430 false, loc, &decl);
1431 Bexpression* var_ref =
1432 gogo->backend()->var_expression(this->bvar_, loc);
1433 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1434 return var_ref;
1435 }
1436 return gogo->backend()->var_expression(this->bvar_, loc);
1437 }
1438
1439 // Ast dump for sink expression.
1440
1441 void
1442 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1443 {
1444 ast_dump_context->ostream() << "_" ;
1445 }
1446
1447 // Make a sink expression.
1448
1449 Expression*
1450 Expression::make_sink(Location location)
1451 {
1452 return new Sink_expression(location);
1453 }
1454
1455 // Class Func_expression.
1456
1457 // FIXME: Can a function expression appear in a constant expression?
1458 // The value is unchanging. Initializing a constant to the address of
1459 // a function seems like it could work, though there might be little
1460 // point to it.
1461
1462 // Traversal.
1463
1464 int
1465 Func_expression::do_traverse(Traverse* traverse)
1466 {
1467 return (this->closure_ == NULL
1468 ? TRAVERSE_CONTINUE
1469 : Expression::traverse(&this->closure_, traverse));
1470 }
1471
1472 // Return the type of a function expression.
1473
1474 Type*
1475 Func_expression::do_type()
1476 {
1477 if (this->function_->is_function())
1478 return this->function_->func_value()->type();
1479 else if (this->function_->is_function_declaration())
1480 return this->function_->func_declaration_value()->type();
1481 else
1482 go_unreachable();
1483 }
1484
1485 // Get the backend representation for the code of a function expression.
1486
1487 Bexpression*
1488 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1489 {
1490 Function_type* fntype;
1491 if (no->is_function())
1492 fntype = no->func_value()->type();
1493 else if (no->is_function_declaration())
1494 fntype = no->func_declaration_value()->type();
1495 else
1496 go_unreachable();
1497
1498 // Builtin functions are handled specially by Call_expression. We
1499 // can't take their address.
1500 if (fntype->is_builtin())
1501 {
1502 go_error_at(loc,
1503 ("invalid use of special built-in function %qs; "
1504 "must be called"),
1505 no->message_name().c_str());
1506 return gogo->backend()->error_expression();
1507 }
1508
1509 Bfunction* fndecl;
1510 if (no->is_function())
1511 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1512 else if (no->is_function_declaration())
1513 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1514 else
1515 go_unreachable();
1516
1517 return gogo->backend()->function_code_expression(fndecl, loc);
1518 }
1519
1520 // Get the backend representation for a function expression. This is used when
1521 // we take the address of a function rather than simply calling it. A func
1522 // value is represented as a pointer to a block of memory. The first
1523 // word of that memory is a pointer to the function code. The
1524 // remaining parts of that memory are the addresses of variables that
1525 // the function closes over.
1526
1527 Bexpression*
1528 Func_expression::do_get_backend(Translate_context* context)
1529 {
1530 // If there is no closure, just use the function descriptor.
1531 if (this->closure_ == NULL)
1532 {
1533 Gogo* gogo = context->gogo();
1534 Named_object* no = this->function_;
1535 Expression* descriptor;
1536 if (no->is_function())
1537 descriptor = no->func_value()->descriptor(gogo, no);
1538 else if (no->is_function_declaration())
1539 {
1540 if (no->func_declaration_value()->type()->is_builtin())
1541 {
1542 go_error_at(this->location(),
1543 ("invalid use of special built-in function %qs; "
1544 "must be called"),
1545 no->message_name().c_str());
1546 return gogo->backend()->error_expression();
1547 }
1548 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1549 }
1550 else
1551 go_unreachable();
1552
1553 Bexpression* bdesc = descriptor->get_backend(context);
1554 return gogo->backend()->address_expression(bdesc, this->location());
1555 }
1556
1557 go_assert(this->function_->func_value()->enclosing() != NULL);
1558
1559 // If there is a closure, then the closure is itself the function
1560 // expression. It is a pointer to a struct whose first field points
1561 // to the function code and whose remaining fields are the addresses
1562 // of the closed-over variables.
1563 Bexpression *bexpr = this->closure_->get_backend(context);
1564
1565 // Introduce a backend type conversion, to account for any differences
1566 // between the argument type (function descriptor, struct with a
1567 // single field) and the closure (struct with multiple fields).
1568 Gogo* gogo = context->gogo();
1569 Btype *btype = this->type()->get_backend(gogo);
1570 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1571 }
1572
1573 // The cost of inlining a function reference.
1574
1575 int
1576 Func_expression::do_inlining_cost() const
1577 {
1578 // FIXME: We don't inline references to nested functions.
1579 if (this->closure_ != NULL)
1580 return 0x100000;
1581 if (this->function_->is_function()
1582 && this->function_->func_value()->enclosing() != NULL)
1583 return 0x100000;
1584
1585 return 1;
1586 }
1587
1588 // Export a reference to a function.
1589
1590 void
1591 Func_expression::do_export(Export_function_body* efb) const
1592 {
1593 Expression::export_name(efb, this->function_);
1594 }
1595
1596 // Ast dump for function.
1597
1598 void
1599 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1600 {
1601 ast_dump_context->ostream() << this->function_->name();
1602 if (this->closure_ != NULL)
1603 {
1604 ast_dump_context->ostream() << " {closure = ";
1605 this->closure_->dump_expression(ast_dump_context);
1606 ast_dump_context->ostream() << "}";
1607 }
1608 }
1609
1610 // Make a reference to a function in an expression.
1611
1612 Expression*
1613 Expression::make_func_reference(Named_object* function, Expression* closure,
1614 Location location)
1615 {
1616 Func_expression* fe = new Func_expression(function, closure, location);
1617
1618 // Detect references to builtin functions and set the runtime code if
1619 // appropriate.
1620 if (function->is_function_declaration())
1621 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1622 return fe;
1623 }
1624
1625 // Class Func_descriptor_expression.
1626
1627 // Constructor.
1628
1629 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1630 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1631 fn_(fn), dvar_(NULL)
1632 {
1633 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1634 }
1635
1636 // Traversal.
1637
1638 int
1639 Func_descriptor_expression::do_traverse(Traverse*)
1640 {
1641 return TRAVERSE_CONTINUE;
1642 }
1643
1644 // All function descriptors have the same type.
1645
1646 Type* Func_descriptor_expression::descriptor_type;
1647
1648 void
1649 Func_descriptor_expression::make_func_descriptor_type()
1650 {
1651 if (Func_descriptor_expression::descriptor_type != NULL)
1652 return;
1653 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1654 Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1655 Func_descriptor_expression::descriptor_type =
1656 Type::make_builtin_named_type("functionDescriptor", struct_type);
1657 }
1658
1659 Type*
1660 Func_descriptor_expression::do_type()
1661 {
1662 Func_descriptor_expression::make_func_descriptor_type();
1663 return Func_descriptor_expression::descriptor_type;
1664 }
1665
1666 // The backend representation for a function descriptor.
1667
1668 Bexpression*
1669 Func_descriptor_expression::do_get_backend(Translate_context* context)
1670 {
1671 Named_object* no = this->fn_;
1672 Location loc = no->location();
1673 if (this->dvar_ != NULL)
1674 return context->backend()->var_expression(this->dvar_, loc);
1675
1676 Gogo* gogo = context->gogo();
1677 Backend_name bname;
1678 gogo->function_descriptor_backend_name(no, &bname);
1679 bool is_descriptor = false;
1680 if (no->is_function_declaration()
1681 && !no->func_declaration_value()->asm_name().empty()
1682 && Linemap::is_predeclared_location(no->location()))
1683 is_descriptor = true;
1684
1685 // The runtime package implements some functions defined in the
1686 // syscall package. Let the syscall package define the descriptor
1687 // in this case.
1688 if (gogo->compiling_runtime()
1689 && gogo->package_name() == "runtime"
1690 && no->is_function()
1691 && !no->func_value()->asm_name().empty()
1692 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1693 is_descriptor = true;
1694
1695 Btype* btype = this->type()->get_backend(gogo);
1696
1697 Bvariable* bvar;
1698 if (no->package() != NULL || is_descriptor)
1699 bvar =
1700 context->backend()->immutable_struct_reference(bname.name(),
1701 bname.optional_asm_name(),
1702 btype, loc);
1703 else
1704 {
1705 Location bloc = Linemap::predeclared_location();
1706
1707 // The runtime package has hash/equality functions that are
1708 // referenced by type descriptors outside of the runtime, so the
1709 // function descriptors must be visible even though they are not
1710 // exported.
1711 bool is_exported_runtime = false;
1712 if (gogo->compiling_runtime()
1713 && gogo->package_name() == "runtime"
1714 && (no->name().find("hash") != std::string::npos
1715 || no->name().find("equal") != std::string::npos))
1716 is_exported_runtime = true;
1717
1718 bool is_hidden = ((no->is_function()
1719 && no->func_value()->enclosing() != NULL)
1720 || (Gogo::is_hidden_name(no->name())
1721 && !is_exported_runtime)
1722 || Gogo::is_thunk(no));
1723
1724 if (no->is_function() && no->func_value()->is_referenced_by_inline())
1725 is_hidden = false;
1726
1727 bvar = context->backend()->immutable_struct(bname.name(),
1728 bname.optional_asm_name(),
1729 is_hidden, false,
1730 btype, bloc);
1731 Expression_list* vals = new Expression_list();
1732 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1733 Expression* init =
1734 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1735 Translate_context bcontext(gogo, NULL, NULL, NULL);
1736 bcontext.set_is_const();
1737 Bexpression* binit = init->get_backend(&bcontext);
1738 context->backend()->immutable_struct_set_init(bvar, bname.name(),
1739 is_hidden, false, btype,
1740 bloc, binit);
1741 }
1742
1743 this->dvar_ = bvar;
1744 return gogo->backend()->var_expression(bvar, loc);
1745 }
1746
1747 // Print a function descriptor expression.
1748
1749 void
1750 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1751 {
1752 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1753 }
1754
1755 // Make a function descriptor expression.
1756
1757 Func_descriptor_expression*
1758 Expression::make_func_descriptor(Named_object* fn)
1759 {
1760 return new Func_descriptor_expression(fn);
1761 }
1762
1763 // Make the function descriptor type, so that it can be converted.
1764
1765 void
1766 Expression::make_func_descriptor_type()
1767 {
1768 Func_descriptor_expression::make_func_descriptor_type();
1769 }
1770
1771 // A reference to just the code of a function.
1772
1773 class Func_code_reference_expression : public Expression
1774 {
1775 public:
1776 Func_code_reference_expression(Named_object* function, Location location)
1777 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1778 function_(function)
1779 { }
1780
1781 protected:
1782 int
1783 do_traverse(Traverse*)
1784 { return TRAVERSE_CONTINUE; }
1785
1786 bool
1787 do_is_static_initializer() const
1788 { return true; }
1789
1790 Type*
1791 do_type()
1792 { return Type::make_pointer_type(Type::make_void_type()); }
1793
1794 void
1795 do_determine_type(const Type_context*)
1796 { }
1797
1798 Expression*
1799 do_copy()
1800 {
1801 return Expression::make_func_code_reference(this->function_,
1802 this->location());
1803 }
1804
1805 Bexpression*
1806 do_get_backend(Translate_context*);
1807
1808 void
1809 do_dump_expression(Ast_dump_context* context) const
1810 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1811
1812 private:
1813 // The function.
1814 Named_object* function_;
1815 };
1816
1817 // Get the backend representation for a reference to function code.
1818
1819 Bexpression*
1820 Func_code_reference_expression::do_get_backend(Translate_context* context)
1821 {
1822 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1823 this->location());
1824 }
1825
1826 // Make a reference to the code of a function.
1827
1828 Expression*
1829 Expression::make_func_code_reference(Named_object* function, Location location)
1830 {
1831 return new Func_code_reference_expression(function, location);
1832 }
1833
1834 // Class Unknown_expression.
1835
1836 // Return the name of an unknown expression.
1837
1838 const std::string&
1839 Unknown_expression::name() const
1840 {
1841 return this->named_object_->name();
1842 }
1843
1844 // Lower a reference to an unknown name.
1845
1846 Expression*
1847 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1848 {
1849 Location location = this->location();
1850 Named_object* no = this->named_object_;
1851 Named_object* real;
1852 if (!no->is_unknown())
1853 real = no;
1854 else
1855 {
1856 real = no->unknown_value()->real_named_object();
1857 if (real == NULL)
1858 {
1859 if (!this->no_error_message_)
1860 go_error_at(location, "reference to undefined name %qs",
1861 this->named_object_->message_name().c_str());
1862 return Expression::make_error(location);
1863 }
1864 }
1865 switch (real->classification())
1866 {
1867 case Named_object::NAMED_OBJECT_CONST:
1868 return Expression::make_const_reference(real, location);
1869 case Named_object::NAMED_OBJECT_TYPE:
1870 return Expression::make_type(real->type_value(), location);
1871 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1872 if (!this->no_error_message_)
1873 go_error_at(location, "reference to undefined type %qs",
1874 real->message_name().c_str());
1875 return Expression::make_error(location);
1876 case Named_object::NAMED_OBJECT_VAR:
1877 real->var_value()->set_is_used();
1878 return Expression::make_var_reference(real, location);
1879 case Named_object::NAMED_OBJECT_FUNC:
1880 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1881 return Expression::make_func_reference(real, NULL, location);
1882 case Named_object::NAMED_OBJECT_PACKAGE:
1883 if (!this->no_error_message_)
1884 go_error_at(location, "unexpected reference to package");
1885 return Expression::make_error(location);
1886 default:
1887 go_unreachable();
1888 }
1889 }
1890
1891 // Dump the ast representation for an unknown expression to a dump context.
1892
1893 void
1894 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1895 {
1896 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1897 << ")";
1898 }
1899
1900 // Make a reference to an unknown name.
1901
1902 Unknown_expression*
1903 Expression::make_unknown_reference(Named_object* no, Location location)
1904 {
1905 return new Unknown_expression(no, location);
1906 }
1907
1908 // Start exporting a type conversion for a constant, if needed. This
1909 // returns whether we need to export a closing parenthesis.
1910
1911 bool
1912 Expression::export_constant_type(Export_function_body* efb, Type* type)
1913 {
1914 if (type == NULL
1915 || type->is_abstract()
1916 || type == efb->type_context())
1917 return false;
1918 efb->write_c_string("$convert(");
1919 efb->write_type(type);
1920 efb->write_c_string(", ");
1921 return true;
1922 }
1923
1924 // Finish a type conversion for a constant.
1925
1926 void
1927 Expression::finish_export_constant_type(Export_function_body* efb, bool needed)
1928 {
1929 if (needed)
1930 efb->write_c_string(")");
1931 }
1932
1933 // A boolean expression.
1934
1935 class Boolean_expression : public Expression
1936 {
1937 public:
1938 Boolean_expression(bool val, Location location)
1939 : Expression(EXPRESSION_BOOLEAN, location),
1940 val_(val), type_(NULL)
1941 { }
1942
1943 static Expression*
1944 do_import(Import_expression*, Location);
1945
1946 protected:
1947 int
1948 do_traverse(Traverse*);
1949
1950 bool
1951 do_is_constant() const
1952 { return true; }
1953
1954 bool
1955 do_is_zero_value() const
1956 { return this->val_ == false; }
1957
1958 bool
1959 do_boolean_constant_value(bool* val) const
1960 {
1961 *val = this->val_;
1962 return true;
1963 }
1964
1965 bool
1966 do_is_static_initializer() const
1967 { return true; }
1968
1969 Type*
1970 do_type();
1971
1972 void
1973 do_determine_type(const Type_context*);
1974
1975 Expression*
1976 do_copy()
1977 { return this; }
1978
1979 Bexpression*
1980 do_get_backend(Translate_context* context)
1981 { return context->backend()->boolean_constant_expression(this->val_); }
1982
1983 int
1984 do_inlining_cost() const
1985 { return 1; }
1986
1987 void
1988 do_export(Export_function_body* efb) const;
1989
1990 void
1991 do_dump_expression(Ast_dump_context* ast_dump_context) const
1992 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1993
1994 private:
1995 // The constant.
1996 bool val_;
1997 // The type as determined by context.
1998 Type* type_;
1999 };
2000
2001 // Traverse a boolean expression. We just need to traverse the type
2002 // if there is one.
2003
2004 int
2005 Boolean_expression::do_traverse(Traverse* traverse)
2006 {
2007 if (this->type_ != NULL)
2008 return Type::traverse(this->type_, traverse);
2009 return TRAVERSE_CONTINUE;
2010 }
2011
2012 // Get the type.
2013
2014 Type*
2015 Boolean_expression::do_type()
2016 {
2017 if (this->type_ == NULL)
2018 this->type_ = Type::make_boolean_type();
2019 return this->type_;
2020 }
2021
2022 // Set the type from the context.
2023
2024 void
2025 Boolean_expression::do_determine_type(const Type_context* context)
2026 {
2027 if (this->type_ != NULL && !this->type_->is_abstract())
2028 ;
2029 else if (context->type != NULL && context->type->is_boolean_type())
2030 this->type_ = context->type;
2031 else if (!context->may_be_abstract)
2032 this->type_ = Type::lookup_bool_type();
2033 }
2034
2035 // Export a boolean constant.
2036
2037 void
2038 Boolean_expression::do_export(Export_function_body* efb) const
2039 {
2040 bool exported_type = Expression::export_constant_type(efb, this->type_);
2041 efb->write_c_string(this->val_ ? "$true" : "$false");
2042 Expression::finish_export_constant_type(efb, exported_type);
2043 }
2044
2045 // Import a boolean constant.
2046
2047 Expression*
2048 Boolean_expression::do_import(Import_expression* imp, Location loc)
2049 {
2050 if (imp->version() >= EXPORT_FORMAT_V3)
2051 imp->require_c_string("$");
2052 if (imp->peek_char() == 't')
2053 {
2054 imp->require_c_string("true");
2055 return Expression::make_boolean(true, loc);
2056 }
2057 else
2058 {
2059 imp->require_c_string("false");
2060 return Expression::make_boolean(false, loc);
2061 }
2062 }
2063
2064 // Make a boolean expression.
2065
2066 Expression*
2067 Expression::make_boolean(bool val, Location location)
2068 {
2069 return new Boolean_expression(val, location);
2070 }
2071
2072 // Class String_expression.
2073
2074 // Traverse a string expression. We just need to traverse the type
2075 // if there is one.
2076
2077 int
2078 String_expression::do_traverse(Traverse* traverse)
2079 {
2080 if (this->type_ != NULL)
2081 return Type::traverse(this->type_, traverse);
2082 return TRAVERSE_CONTINUE;
2083 }
2084
2085 // Get the type.
2086
2087 Type*
2088 String_expression::do_type()
2089 {
2090 if (this->type_ == NULL)
2091 this->type_ = Type::make_string_type();
2092 return this->type_;
2093 }
2094
2095 // Set the type from the context.
2096
2097 void
2098 String_expression::do_determine_type(const Type_context* context)
2099 {
2100 if (this->type_ != NULL && !this->type_->is_abstract())
2101 ;
2102 else if (context->type != NULL && context->type->is_string_type())
2103 this->type_ = context->type;
2104 else if (!context->may_be_abstract)
2105 this->type_ = Type::lookup_string_type();
2106 }
2107
2108 // Build a string constant.
2109
2110 Bexpression*
2111 String_expression::do_get_backend(Translate_context* context)
2112 {
2113 Gogo* gogo = context->gogo();
2114 Btype* btype = Type::make_string_type()->get_backend(gogo);
2115
2116 Location loc = this->location();
2117 std::vector<Bexpression*> init(2);
2118 Bexpression* str_cst =
2119 gogo->backend()->string_constant_expression(this->val_);
2120 init[0] = gogo->backend()->address_expression(str_cst, loc);
2121
2122 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
2123 mpz_t lenval;
2124 mpz_init_set_ui(lenval, this->val_.length());
2125 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
2126 mpz_clear(lenval);
2127
2128 return gogo->backend()->constructor_expression(btype, init, loc);
2129 }
2130
2131 // Write string literal to string dump.
2132
2133 void
2134 String_expression::export_string(String_dump* exp,
2135 const String_expression* str)
2136 {
2137 std::string s;
2138 s.reserve(str->val_.length() * 4 + 2);
2139 s += '"';
2140 for (std::string::const_iterator p = str->val_.begin();
2141 p != str->val_.end();
2142 ++p)
2143 {
2144 if (*p == '\\' || *p == '"')
2145 {
2146 s += '\\';
2147 s += *p;
2148 }
2149 else if (*p >= 0x20 && *p < 0x7f)
2150 s += *p;
2151 else if (*p == '\n')
2152 s += "\\n";
2153 else if (*p == '\t')
2154 s += "\\t";
2155 else
2156 {
2157 s += "\\x";
2158 unsigned char c = *p;
2159 unsigned int dig = c >> 4;
2160 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2161 dig = c & 0xf;
2162 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2163 }
2164 }
2165 s += '"';
2166 exp->write_string(s);
2167 }
2168
2169 // Export a string expression.
2170
2171 void
2172 String_expression::do_export(Export_function_body* efb) const
2173 {
2174 bool exported_type = Expression::export_constant_type(efb, this->type_);
2175 String_expression::export_string(efb, this);
2176 Expression::finish_export_constant_type(efb, exported_type);
2177 }
2178
2179 // Import a string expression.
2180
2181 Expression*
2182 String_expression::do_import(Import_expression* imp, Location loc)
2183 {
2184 imp->require_c_string("\"");
2185 std::string val;
2186 while (true)
2187 {
2188 int c = imp->get_char();
2189 if (c == '"' || c == -1)
2190 break;
2191 if (c != '\\')
2192 val += static_cast<char>(c);
2193 else
2194 {
2195 c = imp->get_char();
2196 if (c == '\\' || c == '"')
2197 val += static_cast<char>(c);
2198 else if (c == 'n')
2199 val += '\n';
2200 else if (c == 't')
2201 val += '\t';
2202 else if (c == 'x')
2203 {
2204 c = imp->get_char();
2205 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2206 c = imp->get_char();
2207 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2208 char v = (vh << 4) | vl;
2209 val += v;
2210 }
2211 else
2212 {
2213 go_error_at(imp->location(), "bad string constant");
2214 return Expression::make_error(loc);
2215 }
2216 }
2217 }
2218 return Expression::make_string(val, loc);
2219 }
2220
2221 // Ast dump for string expression.
2222
2223 void
2224 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2225 {
2226 String_expression::export_string(ast_dump_context, this);
2227 }
2228
2229 // Make a string expression with abstract string type (common case).
2230
2231 Expression*
2232 Expression::make_string(const std::string& val, Location location)
2233 {
2234 return new String_expression(val, NULL, location);
2235 }
2236
2237 // Make a string expression with a specific string type.
2238
2239 Expression*
2240 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2241 {
2242 return new String_expression(val, type, location);
2243 }
2244
2245 // An expression that evaluates to some characteristic of a string.
2246 // This is used when indexing, bound-checking, or nil checking a string.
2247
2248 class String_info_expression : public Expression
2249 {
2250 public:
2251 String_info_expression(Expression* string, String_info string_info,
2252 Location location)
2253 : Expression(EXPRESSION_STRING_INFO, location),
2254 string_(string), string_info_(string_info)
2255 { }
2256
2257 protected:
2258 Type*
2259 do_type();
2260
2261 void
2262 do_determine_type(const Type_context*)
2263 { go_unreachable(); }
2264
2265 Expression*
2266 do_copy()
2267 {
2268 return new String_info_expression(this->string_->copy(), this->string_info_,
2269 this->location());
2270 }
2271
2272 Bexpression*
2273 do_get_backend(Translate_context* context);
2274
2275 void
2276 do_dump_expression(Ast_dump_context*) const;
2277
2278 void
2279 do_issue_nil_check()
2280 { this->string_->issue_nil_check(); }
2281
2282 private:
2283 // The string for which we are getting information.
2284 Expression* string_;
2285 // What information we want.
2286 String_info string_info_;
2287 };
2288
2289 // Return the type of the string info.
2290
2291 Type*
2292 String_info_expression::do_type()
2293 {
2294 switch (this->string_info_)
2295 {
2296 case STRING_INFO_DATA:
2297 {
2298 Type* byte_type = Type::lookup_integer_type("uint8");
2299 return Type::make_pointer_type(byte_type);
2300 }
2301 case STRING_INFO_LENGTH:
2302 return Type::lookup_integer_type("int");
2303 default:
2304 go_unreachable();
2305 }
2306 }
2307
2308 // Return string information in GENERIC.
2309
2310 Bexpression*
2311 String_info_expression::do_get_backend(Translate_context* context)
2312 {
2313 Gogo* gogo = context->gogo();
2314
2315 Bexpression* bstring = this->string_->get_backend(context);
2316 switch (this->string_info_)
2317 {
2318 case STRING_INFO_DATA:
2319 case STRING_INFO_LENGTH:
2320 return gogo->backend()->struct_field_expression(bstring,
2321 this->string_info_,
2322 this->location());
2323 break;
2324 default:
2325 go_unreachable();
2326 }
2327 }
2328
2329 // Dump ast representation for a type info expression.
2330
2331 void
2332 String_info_expression::do_dump_expression(
2333 Ast_dump_context* ast_dump_context) const
2334 {
2335 ast_dump_context->ostream() << "stringinfo(";
2336 this->string_->dump_expression(ast_dump_context);
2337 ast_dump_context->ostream() << ",";
2338 ast_dump_context->ostream() <<
2339 (this->string_info_ == STRING_INFO_DATA ? "data"
2340 : this->string_info_ == STRING_INFO_LENGTH ? "length"
2341 : "unknown");
2342 ast_dump_context->ostream() << ")";
2343 }
2344
2345 // Make a string info expression.
2346
2347 Expression*
2348 Expression::make_string_info(Expression* string, String_info string_info,
2349 Location location)
2350 {
2351 return new String_info_expression(string, string_info, location);
2352 }
2353
2354 // An expression that represents an string value: a struct with value pointer
2355 // and length fields.
2356
2357 class String_value_expression : public Expression
2358 {
2359 public:
2360 String_value_expression(Expression* valptr, Expression* len, Location location)
2361 : Expression(EXPRESSION_STRING_VALUE, location),
2362 valptr_(valptr), len_(len)
2363 { }
2364
2365 protected:
2366 int
2367 do_traverse(Traverse*);
2368
2369 Type*
2370 do_type()
2371 { return Type::make_string_type(); }
2372
2373 void
2374 do_determine_type(const Type_context*)
2375 { go_unreachable(); }
2376
2377 Expression*
2378 do_copy()
2379 {
2380 return new String_value_expression(this->valptr_->copy(),
2381 this->len_->copy(),
2382 this->location());
2383 }
2384
2385 Bexpression*
2386 do_get_backend(Translate_context* context);
2387
2388 void
2389 do_dump_expression(Ast_dump_context*) const;
2390
2391 private:
2392 // The value pointer.
2393 Expression* valptr_;
2394 // The length.
2395 Expression* len_;
2396 };
2397
2398 int
2399 String_value_expression::do_traverse(Traverse* traverse)
2400 {
2401 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2402 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2403 return TRAVERSE_EXIT;
2404 return TRAVERSE_CONTINUE;
2405 }
2406
2407 Bexpression*
2408 String_value_expression::do_get_backend(Translate_context* context)
2409 {
2410 std::vector<Bexpression*> vals(2);
2411 vals[0] = this->valptr_->get_backend(context);
2412 vals[1] = this->len_->get_backend(context);
2413
2414 Gogo* gogo = context->gogo();
2415 Btype* btype = Type::make_string_type()->get_backend(gogo);
2416 return gogo->backend()->constructor_expression(btype, vals, this->location());
2417 }
2418
2419 void
2420 String_value_expression::do_dump_expression(
2421 Ast_dump_context* ast_dump_context) const
2422 {
2423 ast_dump_context->ostream() << "stringvalue(";
2424 ast_dump_context->ostream() << "value: ";
2425 this->valptr_->dump_expression(ast_dump_context);
2426 ast_dump_context->ostream() << ", length: ";
2427 this->len_->dump_expression(ast_dump_context);
2428 ast_dump_context->ostream() << ")";
2429 }
2430
2431 Expression*
2432 Expression::make_string_value(Expression* valptr, Expression* len,
2433 Location location)
2434 {
2435 return new String_value_expression(valptr, len, location);
2436 }
2437
2438 // Make an integer expression.
2439
2440 class Integer_expression : public Expression
2441 {
2442 public:
2443 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2444 Location location)
2445 : Expression(EXPRESSION_INTEGER, location),
2446 type_(type), is_character_constant_(is_character_constant)
2447 { mpz_init_set(this->val_, *val); }
2448
2449 static Expression*
2450 do_import(Import_expression*, Location);
2451
2452 // Write VAL to string dump.
2453 static void
2454 export_integer(String_dump* exp, const mpz_t val);
2455
2456 // Write VAL to dump context.
2457 static void
2458 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2459
2460 protected:
2461 int
2462 do_traverse(Traverse*);
2463
2464 bool
2465 do_is_constant() const
2466 { return true; }
2467
2468 bool
2469 do_is_zero_value() const
2470 { return mpz_sgn(this->val_) == 0; }
2471
2472 bool
2473 do_is_static_initializer() const
2474 { return true; }
2475
2476 bool
2477 do_numeric_constant_value(Numeric_constant* nc) const;
2478
2479 Type*
2480 do_type();
2481
2482 void
2483 do_determine_type(const Type_context* context);
2484
2485 void
2486 do_check_types(Gogo*);
2487
2488 Bexpression*
2489 do_get_backend(Translate_context*);
2490
2491 Expression*
2492 do_copy()
2493 {
2494 if (this->is_character_constant_)
2495 return Expression::make_character(&this->val_,
2496 (this->type_ == NULL
2497 ? NULL
2498 : this->type_->copy_expressions()),
2499 this->location());
2500 else
2501 return Expression::make_integer_z(&this->val_,
2502 (this->type_ == NULL
2503 ? NULL
2504 : this->type_->copy_expressions()),
2505 this->location());
2506 }
2507
2508 int
2509 do_inlining_cost() const
2510 { return 1; }
2511
2512 void
2513 do_export(Export_function_body*) const;
2514
2515 void
2516 do_dump_expression(Ast_dump_context*) const;
2517
2518 private:
2519 // The integer value.
2520 mpz_t val_;
2521 // The type so far.
2522 Type* type_;
2523 // Whether this is a character constant.
2524 bool is_character_constant_;
2525 };
2526
2527 // Traverse an integer expression. We just need to traverse the type
2528 // if there is one.
2529
2530 int
2531 Integer_expression::do_traverse(Traverse* traverse)
2532 {
2533 if (this->type_ != NULL)
2534 return Type::traverse(this->type_, traverse);
2535 return TRAVERSE_CONTINUE;
2536 }
2537
2538 // Return a numeric constant for this expression. We have to mark
2539 // this as a character when appropriate.
2540
2541 bool
2542 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2543 {
2544 if (this->is_character_constant_)
2545 nc->set_rune(this->type_, this->val_);
2546 else
2547 nc->set_int(this->type_, this->val_);
2548 return true;
2549 }
2550
2551 // Return the current type. If we haven't set the type yet, we return
2552 // an abstract integer type.
2553
2554 Type*
2555 Integer_expression::do_type()
2556 {
2557 if (this->type_ == NULL)
2558 {
2559 if (this->is_character_constant_)
2560 this->type_ = Type::make_abstract_character_type();
2561 else
2562 this->type_ = Type::make_abstract_integer_type();
2563 }
2564 return this->type_;
2565 }
2566
2567 // Set the type of the integer value. Here we may switch from an
2568 // abstract type to a real type.
2569
2570 void
2571 Integer_expression::do_determine_type(const Type_context* context)
2572 {
2573 if (this->type_ != NULL && !this->type_->is_abstract())
2574 ;
2575 else if (context->type != NULL && context->type->is_numeric_type())
2576 this->type_ = context->type;
2577 else if (!context->may_be_abstract)
2578 {
2579 if (this->is_character_constant_)
2580 this->type_ = Type::lookup_integer_type("int32");
2581 else
2582 this->type_ = Type::lookup_integer_type("int");
2583 }
2584 }
2585
2586 // Check the type of an integer constant.
2587
2588 void
2589 Integer_expression::do_check_types(Gogo*)
2590 {
2591 Type* type = this->type_;
2592 if (type == NULL)
2593 return;
2594 Numeric_constant nc;
2595 if (this->is_character_constant_)
2596 nc.set_rune(NULL, this->val_);
2597 else
2598 nc.set_int(NULL, this->val_);
2599 if (!nc.set_type(type, true, this->location()))
2600 this->set_is_error();
2601 }
2602
2603 // Get the backend representation for an integer constant.
2604
2605 Bexpression*
2606 Integer_expression::do_get_backend(Translate_context* context)
2607 {
2608 if (this->is_error_expression()
2609 || (this->type_ != NULL && this->type_->is_error_type()))
2610 {
2611 go_assert(saw_errors());
2612 return context->gogo()->backend()->error_expression();
2613 }
2614
2615 Type* resolved_type = NULL;
2616 if (this->type_ != NULL && !this->type_->is_abstract())
2617 resolved_type = this->type_;
2618 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2619 {
2620 // We are converting to an abstract floating point type.
2621 resolved_type = Type::lookup_float_type("float64");
2622 }
2623 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2624 {
2625 // We are converting to an abstract complex type.
2626 resolved_type = Type::lookup_complex_type("complex128");
2627 }
2628 else
2629 {
2630 // If we still have an abstract type here, then this is being
2631 // used in a constant expression which didn't get reduced for
2632 // some reason. Use a type which will fit the value. We use <,
2633 // not <=, because we need an extra bit for the sign bit.
2634 int bits = mpz_sizeinbase(this->val_, 2);
2635 Type* int_type = Type::lookup_integer_type("int");
2636 if (bits < int_type->integer_type()->bits())
2637 resolved_type = int_type;
2638 else if (bits < 64)
2639 resolved_type = Type::lookup_integer_type("int64");
2640 else
2641 {
2642 if (!saw_errors())
2643 go_error_at(this->location(),
2644 "unknown type for large integer constant");
2645 return context->gogo()->backend()->error_expression();
2646 }
2647 }
2648 Numeric_constant nc;
2649 nc.set_int(resolved_type, this->val_);
2650 return Expression::backend_numeric_constant_expression(context, &nc);
2651 }
2652
2653 // Write VAL to export data.
2654
2655 void
2656 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2657 {
2658 char* s = mpz_get_str(NULL, 10, val);
2659 exp->write_c_string(s);
2660 free(s);
2661 }
2662
2663 // Export an integer in a constant expression.
2664
2665 void
2666 Integer_expression::do_export(Export_function_body* efb) const
2667 {
2668 bool exported_type = Expression::export_constant_type(efb, this->type_);
2669
2670 Integer_expression::export_integer(efb, this->val_);
2671 if (this->is_character_constant_)
2672 efb->write_c_string("'");
2673 // A trailing space lets us reliably identify the end of the number.
2674 efb->write_c_string(" ");
2675
2676 Expression::finish_export_constant_type(efb, exported_type);
2677 }
2678
2679 // Import an integer, floating point, or complex value. This handles
2680 // all these types because they all start with digits.
2681
2682 Expression*
2683 Integer_expression::do_import(Import_expression* imp, Location loc)
2684 {
2685 std::string num = imp->read_identifier();
2686 imp->require_c_string(" ");
2687 if (!num.empty() && num[num.length() - 1] == 'i')
2688 {
2689 mpfr_t real;
2690 size_t plus_pos = num.find('+', 1);
2691 size_t minus_pos = num.find('-', 1);
2692 size_t pos;
2693 if (plus_pos == std::string::npos)
2694 pos = minus_pos;
2695 else if (minus_pos == std::string::npos)
2696 pos = plus_pos;
2697 else
2698 {
2699 go_error_at(imp->location(), "bad number in import data: %qs",
2700 num.c_str());
2701 return Expression::make_error(loc);
2702 }
2703 if (pos == std::string::npos)
2704 mpfr_set_ui(real, 0, MPFR_RNDN);
2705 else
2706 {
2707 std::string real_str = num.substr(0, pos);
2708 if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2709 {
2710 go_error_at(imp->location(), "bad number in import data: %qs",
2711 real_str.c_str());
2712 return Expression::make_error(loc);
2713 }
2714 }
2715
2716 std::string imag_str;
2717 if (pos == std::string::npos)
2718 imag_str = num;
2719 else
2720 imag_str = num.substr(pos);
2721 imag_str = imag_str.substr(0, imag_str.size() - 1);
2722 mpfr_t imag;
2723 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2724 {
2725 go_error_at(imp->location(), "bad number in import data: %qs",
2726 imag_str.c_str());
2727 return Expression::make_error(loc);
2728 }
2729 mpc_t cval;
2730 mpc_init2(cval, mpc_precision);
2731 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2732 mpfr_clear(real);
2733 mpfr_clear(imag);
2734 Expression* ret = Expression::make_complex(&cval, NULL, loc);
2735 mpc_clear(cval);
2736 return ret;
2737 }
2738 else if (num.find('.') == std::string::npos
2739 && num.find('E') == std::string::npos)
2740 {
2741 bool is_character_constant = (!num.empty()
2742 && num[num.length() - 1] == '\'');
2743 if (is_character_constant)
2744 num = num.substr(0, num.length() - 1);
2745 mpz_t val;
2746 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2747 {
2748 go_error_at(imp->location(), "bad number in import data: %qs",
2749 num.c_str());
2750 return Expression::make_error(loc);
2751 }
2752 Expression* ret;
2753 if (is_character_constant)
2754 ret = Expression::make_character(&val, NULL, loc);
2755 else
2756 ret = Expression::make_integer_z(&val, NULL, loc);
2757 mpz_clear(val);
2758 return ret;
2759 }
2760 else
2761 {
2762 mpfr_t val;
2763 if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
2764 {
2765 go_error_at(imp->location(), "bad number in import data: %qs",
2766 num.c_str());
2767 return Expression::make_error(loc);
2768 }
2769 Expression* ret = Expression::make_float(&val, NULL, loc);
2770 mpfr_clear(val);
2771 return ret;
2772 }
2773 }
2774 // Ast dump for integer expression.
2775
2776 void
2777 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2778 {
2779 if (this->is_character_constant_)
2780 ast_dump_context->ostream() << '\'';
2781 Integer_expression::export_integer(ast_dump_context, this->val_);
2782 if (this->is_character_constant_)
2783 ast_dump_context->ostream() << '\'';
2784 }
2785
2786 // Build a new integer value from a multi-precision integer.
2787
2788 Expression*
2789 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2790 {
2791 return new Integer_expression(val, type, false, location);
2792 }
2793
2794 // Build a new integer value from an unsigned long.
2795
2796 Expression*
2797 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2798 {
2799 mpz_t zval;
2800 mpz_init_set_ui(zval, val);
2801 Expression* ret = Expression::make_integer_z(&zval, type, location);
2802 mpz_clear(zval);
2803 return ret;
2804 }
2805
2806 // Build a new integer value from a signed long.
2807
2808 Expression*
2809 Expression::make_integer_sl(long val, Type *type, Location location)
2810 {
2811 mpz_t zval;
2812 mpz_init_set_si(zval, val);
2813 Expression* ret = Expression::make_integer_z(&zval, type, location);
2814 mpz_clear(zval);
2815 return ret;
2816 }
2817
2818 // Store an int64_t in an uninitialized mpz_t.
2819
2820 static void
2821 set_mpz_from_int64(mpz_t* zval, int64_t val)
2822 {
2823 if (val >= 0)
2824 {
2825 unsigned long ul = static_cast<unsigned long>(val);
2826 if (static_cast<int64_t>(ul) == val)
2827 {
2828 mpz_init_set_ui(*zval, ul);
2829 return;
2830 }
2831 }
2832 uint64_t uv;
2833 if (val >= 0)
2834 uv = static_cast<uint64_t>(val);
2835 else
2836 uv = static_cast<uint64_t>(- val);
2837 unsigned long ul = uv & 0xffffffffUL;
2838 mpz_init_set_ui(*zval, ul);
2839 mpz_t hval;
2840 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2841 mpz_mul_2exp(hval, hval, 32);
2842 mpz_add(*zval, *zval, hval);
2843 mpz_clear(hval);
2844 if (val < 0)
2845 mpz_neg(*zval, *zval);
2846 }
2847
2848 // Build a new integer value from an int64_t.
2849
2850 Expression*
2851 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2852 {
2853 mpz_t zval;
2854 set_mpz_from_int64(&zval, val);
2855 Expression* ret = Expression::make_integer_z(&zval, type, location);
2856 mpz_clear(zval);
2857 return ret;
2858 }
2859
2860 // Build a new character constant value.
2861
2862 Expression*
2863 Expression::make_character(const mpz_t* val, Type* type, Location location)
2864 {
2865 return new Integer_expression(val, type, true, location);
2866 }
2867
2868 // Floats.
2869
2870 class Float_expression : public Expression
2871 {
2872 public:
2873 Float_expression(const mpfr_t* val, Type* type, Location location)
2874 : Expression(EXPRESSION_FLOAT, location),
2875 type_(type)
2876 {
2877 mpfr_init_set(this->val_, *val, MPFR_RNDN);
2878 }
2879
2880 // Write VAL to export data.
2881 static void
2882 export_float(String_dump* exp, const mpfr_t val);
2883
2884 // Write VAL to dump file.
2885 static void
2886 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2887
2888 protected:
2889 int
2890 do_traverse(Traverse*);
2891
2892 bool
2893 do_is_constant() const
2894 { return true; }
2895
2896 bool
2897 do_is_zero_value() const
2898 {
2899 return mpfr_zero_p(this->val_) != 0
2900 && mpfr_signbit(this->val_) == 0;
2901 }
2902
2903 bool
2904 do_is_static_initializer() const
2905 { return true; }
2906
2907 bool
2908 do_numeric_constant_value(Numeric_constant* nc) const
2909 {
2910 nc->set_float(this->type_, this->val_);
2911 return true;
2912 }
2913
2914 Type*
2915 do_type();
2916
2917 void
2918 do_determine_type(const Type_context*);
2919
2920 void
2921 do_check_types(Gogo*);
2922
2923 Expression*
2924 do_copy()
2925 { return Expression::make_float(&this->val_,
2926 (this->type_ == NULL
2927 ? NULL
2928 : this->type_->copy_expressions()),
2929 this->location()); }
2930
2931 Bexpression*
2932 do_get_backend(Translate_context*);
2933
2934 int
2935 do_inlining_cost() const
2936 { return 1; }
2937
2938 void
2939 do_export(Export_function_body*) const;
2940
2941 void
2942 do_dump_expression(Ast_dump_context*) const;
2943
2944 private:
2945 // The floating point value.
2946 mpfr_t val_;
2947 // The type so far.
2948 Type* type_;
2949 };
2950
2951 // Traverse a float expression. We just need to traverse the type if
2952 // there is one.
2953
2954 int
2955 Float_expression::do_traverse(Traverse* traverse)
2956 {
2957 if (this->type_ != NULL)
2958 return Type::traverse(this->type_, traverse);
2959 return TRAVERSE_CONTINUE;
2960 }
2961
2962 // Return the current type. If we haven't set the type yet, we return
2963 // an abstract float type.
2964
2965 Type*
2966 Float_expression::do_type()
2967 {
2968 if (this->type_ == NULL)
2969 this->type_ = Type::make_abstract_float_type();
2970 return this->type_;
2971 }
2972
2973 // Set the type of the float value. Here we may switch from an
2974 // abstract type to a real type.
2975
2976 void
2977 Float_expression::do_determine_type(const Type_context* context)
2978 {
2979 if (this->type_ != NULL && !this->type_->is_abstract())
2980 ;
2981 else if (context->type != NULL
2982 && (context->type->integer_type() != NULL
2983 || context->type->float_type() != NULL
2984 || context->type->complex_type() != NULL))
2985 this->type_ = context->type;
2986 else if (!context->may_be_abstract)
2987 this->type_ = Type::lookup_float_type("float64");
2988 }
2989
2990 // Check the type of a float value.
2991
2992 void
2993 Float_expression::do_check_types(Gogo*)
2994 {
2995 Type* type = this->type_;
2996 if (type == NULL)
2997 return;
2998 Numeric_constant nc;
2999 nc.set_float(NULL, this->val_);
3000 if (!nc.set_type(this->type_, true, this->location()))
3001 this->set_is_error();
3002 }
3003
3004 // Get the backend representation for a float constant.
3005
3006 Bexpression*
3007 Float_expression::do_get_backend(Translate_context* context)
3008 {
3009 if (this->is_error_expression()
3010 || (this->type_ != NULL && this->type_->is_error_type()))
3011 {
3012 go_assert(saw_errors());
3013 return context->gogo()->backend()->error_expression();
3014 }
3015
3016 Type* resolved_type;
3017 if (this->type_ != NULL && !this->type_->is_abstract())
3018 resolved_type = this->type_;
3019 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3020 {
3021 // We have an abstract integer type. We just hope for the best.
3022 resolved_type = Type::lookup_integer_type("int");
3023 }
3024 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
3025 {
3026 // We are converting to an abstract complex type.
3027 resolved_type = Type::lookup_complex_type("complex128");
3028 }
3029 else
3030 {
3031 // If we still have an abstract type here, then this is being
3032 // used in a constant expression which didn't get reduced. We
3033 // just use float64 and hope for the best.
3034 resolved_type = Type::lookup_float_type("float64");
3035 }
3036
3037 Numeric_constant nc;
3038 nc.set_float(resolved_type, this->val_);
3039 return Expression::backend_numeric_constant_expression(context, &nc);
3040 }
3041
3042 // Write a floating point number to a string dump.
3043
3044 void
3045 Float_expression::export_float(String_dump *exp, const mpfr_t val)
3046 {
3047 mpfr_exp_t exponent;
3048 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
3049 if (*s == '-')
3050 exp->write_c_string("-");
3051 exp->write_c_string("0.");
3052 exp->write_c_string(*s == '-' ? s + 1 : s);
3053 mpfr_free_str(s);
3054 char buf[30];
3055 snprintf(buf, sizeof buf, "E%ld", exponent);
3056 exp->write_c_string(buf);
3057 }
3058
3059 // Export a floating point number in a constant expression.
3060
3061 void
3062 Float_expression::do_export(Export_function_body* efb) const
3063 {
3064 bool exported_type = Expression::export_constant_type(efb, this->type_);
3065
3066 Float_expression::export_float(efb, this->val_);
3067 // A trailing space lets us reliably identify the end of the number.
3068 efb->write_c_string(" ");
3069
3070 Expression::finish_export_constant_type(efb, exported_type);
3071 }
3072
3073 // Dump a floating point number to the dump file.
3074
3075 void
3076 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3077 {
3078 Float_expression::export_float(ast_dump_context, this->val_);
3079 }
3080
3081 // Make a float expression.
3082
3083 Expression*
3084 Expression::make_float(const mpfr_t* val, Type* type, Location location)
3085 {
3086 return new Float_expression(val, type, location);
3087 }
3088
3089 // Complex numbers.
3090
3091 class Complex_expression : public Expression
3092 {
3093 public:
3094 Complex_expression(const mpc_t* val, Type* type, Location location)
3095 : Expression(EXPRESSION_COMPLEX, location),
3096 type_(type)
3097 {
3098 mpc_init2(this->val_, mpc_precision);
3099 mpc_set(this->val_, *val, MPC_RNDNN);
3100 }
3101
3102 // Write VAL to string dump.
3103 static void
3104 export_complex(String_dump* exp, const mpc_t val);
3105
3106 // Write REAL/IMAG to dump context.
3107 static void
3108 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
3109
3110 protected:
3111 int
3112 do_traverse(Traverse*);
3113
3114 bool
3115 do_is_constant() const
3116 { return true; }
3117
3118 bool
3119 do_is_zero_value() const
3120 {
3121 return mpfr_zero_p(mpc_realref(this->val_)) != 0
3122 && mpfr_signbit(mpc_realref(this->val_)) == 0
3123 && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3124 && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3125 }
3126
3127 bool
3128 do_is_static_initializer() const
3129 { return true; }
3130
3131 bool
3132 do_numeric_constant_value(Numeric_constant* nc) const
3133 {
3134 nc->set_complex(this->type_, this->val_);
3135 return true;
3136 }
3137
3138 Type*
3139 do_type();
3140
3141 void
3142 do_determine_type(const Type_context*);
3143
3144 void
3145 do_check_types(Gogo*);
3146
3147 Expression*
3148 do_copy()
3149 {
3150 return Expression::make_complex(&this->val_,
3151 (this->type_ == NULL
3152 ? NULL
3153 : this->type_->copy_expressions()),
3154 this->location());
3155 }
3156
3157 Bexpression*
3158 do_get_backend(Translate_context*);
3159
3160 int
3161 do_inlining_cost() const
3162 { return 2; }
3163
3164 void
3165 do_export(Export_function_body*) const;
3166
3167 void
3168 do_dump_expression(Ast_dump_context*) const;
3169
3170 private:
3171 // The complex value.
3172 mpc_t val_;
3173 // The type if known.
3174 Type* type_;
3175 };
3176
3177 // Traverse a complex expression. We just need to traverse the type
3178 // if there is one.
3179
3180 int
3181 Complex_expression::do_traverse(Traverse* traverse)
3182 {
3183 if (this->type_ != NULL)
3184 return Type::traverse(this->type_, traverse);
3185 return TRAVERSE_CONTINUE;
3186 }
3187
3188 // Return the current type. If we haven't set the type yet, we return
3189 // an abstract complex type.
3190
3191 Type*
3192 Complex_expression::do_type()
3193 {
3194 if (this->type_ == NULL)
3195 this->type_ = Type::make_abstract_complex_type();
3196 return this->type_;
3197 }
3198
3199 // Set the type of the complex value. Here we may switch from an
3200 // abstract type to a real type.
3201
3202 void
3203 Complex_expression::do_determine_type(const Type_context* context)
3204 {
3205 if (this->type_ != NULL && !this->type_->is_abstract())
3206 ;
3207 else if (context->type != NULL && context->type->is_numeric_type())
3208 this->type_ = context->type;
3209 else if (!context->may_be_abstract)
3210 this->type_ = Type::lookup_complex_type("complex128");
3211 }
3212
3213 // Check the type of a complex value.
3214
3215 void
3216 Complex_expression::do_check_types(Gogo*)
3217 {
3218 Type* type = this->type_;
3219 if (type == NULL)
3220 return;
3221 Numeric_constant nc;
3222 nc.set_complex(NULL, this->val_);
3223 if (!nc.set_type(this->type_, true, this->location()))
3224 this->set_is_error();
3225 }
3226
3227 // Get the backend representation for a complex constant.
3228
3229 Bexpression*
3230 Complex_expression::do_get_backend(Translate_context* context)
3231 {
3232 if (this->is_error_expression()
3233 || (this->type_ != NULL && this->type_->is_error_type()))
3234 {
3235 go_assert(saw_errors());
3236 return context->gogo()->backend()->error_expression();
3237 }
3238
3239 Type* resolved_type;
3240 if (this->type_ != NULL && !this->type_->is_abstract())
3241 resolved_type = this->type_;
3242 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3243 {
3244 // We are converting to an abstract integer type.
3245 resolved_type = Type::lookup_integer_type("int");
3246 }
3247 else if (this->type_ != NULL && this->type_->float_type() != NULL)
3248 {
3249 // We are converting to an abstract float type.
3250 resolved_type = Type::lookup_float_type("float64");
3251 }
3252 else
3253 {
3254 // If we still have an abstract type here, this is being
3255 // used in a constant expression which didn't get reduced. We
3256 // just use complex128 and hope for the best.
3257 resolved_type = Type::lookup_complex_type("complex128");
3258 }
3259
3260 Numeric_constant nc;
3261 nc.set_complex(resolved_type, this->val_);
3262 return Expression::backend_numeric_constant_expression(context, &nc);
3263 }
3264
3265 // Write REAL/IMAG to export data.
3266
3267 void
3268 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3269 {
3270 if (!mpfr_zero_p(mpc_realref(val)))
3271 {
3272 Float_expression::export_float(exp, mpc_realref(val));
3273 if (mpfr_sgn(mpc_imagref(val)) >= 0)
3274 exp->write_c_string("+");
3275 }
3276 Float_expression::export_float(exp, mpc_imagref(val));
3277 exp->write_c_string("i");
3278 }
3279
3280 // Export a complex number in a constant expression.
3281
3282 void
3283 Complex_expression::do_export(Export_function_body* efb) const
3284 {
3285 bool exported_type = Expression::export_constant_type(efb, this->type_);
3286
3287 Complex_expression::export_complex(efb, this->val_);
3288 // A trailing space lets us reliably identify the end of the number.
3289 efb->write_c_string(" ");
3290
3291 Expression::finish_export_constant_type(efb, exported_type);
3292 }
3293
3294 // Dump a complex expression to the dump file.
3295
3296 void
3297 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3298 {
3299 Complex_expression::export_complex(ast_dump_context, this->val_);
3300 }
3301
3302 // Make a complex expression.
3303
3304 Expression*
3305 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3306 {
3307 return new Complex_expression(val, type, location);
3308 }
3309
3310 // Find a named object in an expression.
3311
3312 class Find_named_object : public Traverse
3313 {
3314 public:
3315 Find_named_object(Named_object* no)
3316 : Traverse(traverse_expressions),
3317 no_(no), found_(false)
3318 { }
3319
3320 // Whether we found the object.
3321 bool
3322 found() const
3323 { return this->found_; }
3324
3325 protected:
3326 int
3327 expression(Expression**);
3328
3329 private:
3330 // The object we are looking for.
3331 Named_object* no_;
3332 // Whether we found it.
3333 bool found_;
3334 };
3335
3336 // A reference to a const in an expression.
3337
3338 class Const_expression : public Expression
3339 {
3340 public:
3341 Const_expression(Named_object* constant, Location location)
3342 : Expression(EXPRESSION_CONST_REFERENCE, location),
3343 constant_(constant), type_(NULL), seen_(false)
3344 { }
3345
3346 Named_object*
3347 named_object()
3348 { return this->constant_; }
3349
3350 const Named_object*
3351 named_object() const
3352 { return this->constant_; }
3353
3354 // Check that the initializer does not refer to the constant itself.
3355 void
3356 check_for_init_loop();
3357
3358 protected:
3359 int
3360 do_traverse(Traverse*);
3361
3362 Expression*
3363 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3364
3365 bool
3366 do_is_constant() const
3367 { return true; }
3368
3369 bool
3370 do_is_zero_value() const
3371 { return this->constant_->const_value()->expr()->is_zero_value(); }
3372
3373 bool
3374 do_is_static_initializer() const
3375 { return true; }
3376
3377 bool
3378 do_numeric_constant_value(Numeric_constant* nc) const;
3379
3380 bool
3381 do_string_constant_value(std::string* val) const;
3382
3383 bool
3384 do_boolean_constant_value(bool* val) const;
3385
3386 Type*
3387 do_type();
3388
3389 // The type of a const is set by the declaration, not the use.
3390 void
3391 do_determine_type(const Type_context*);
3392
3393 void
3394 do_check_types(Gogo*);
3395
3396 Expression*
3397 do_copy()
3398 { return this; }
3399
3400 Bexpression*
3401 do_get_backend(Translate_context* context);
3402
3403 int
3404 do_inlining_cost() const
3405 { return 1; }
3406
3407 // When exporting a reference to a const as part of a const
3408 // expression, we export the value. We ignore the fact that it has
3409 // a name.
3410 void
3411 do_export(Export_function_body* efb) const
3412 { this->constant_->const_value()->expr()->export_expression(efb); }
3413
3414 void
3415 do_dump_expression(Ast_dump_context*) const;
3416
3417 private:
3418 // The constant.
3419 Named_object* constant_;
3420 // The type of this reference. This is used if the constant has an
3421 // abstract type.
3422 Type* type_;
3423 // Used to prevent infinite recursion when a constant incorrectly
3424 // refers to itself.
3425 mutable bool seen_;
3426 };
3427
3428 // Traversal.
3429
3430 int
3431 Const_expression::do_traverse(Traverse* traverse)
3432 {
3433 if (this->type_ != NULL)
3434 return Type::traverse(this->type_, traverse);
3435 return TRAVERSE_CONTINUE;
3436 }
3437
3438 // Lower a constant expression. This is where we convert the
3439 // predeclared constant iota into an integer value.
3440
3441 Expression*
3442 Const_expression::do_lower(Gogo* gogo, Named_object*,
3443 Statement_inserter*, int iota_value)
3444 {
3445 if (this->constant_->const_value()->expr()->classification()
3446 == EXPRESSION_IOTA)
3447 {
3448 if (iota_value == -1)
3449 {
3450 go_error_at(this->location(),
3451 "iota is only defined in const declarations");
3452 iota_value = 0;
3453 }
3454 return Expression::make_integer_ul(iota_value, NULL, this->location());
3455 }
3456
3457 // Make sure that the constant itself has been lowered.
3458 gogo->lower_constant(this->constant_);
3459
3460 return this;
3461 }
3462
3463 // Return a numeric constant value.
3464
3465 bool
3466 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
3467 {
3468 if (this->seen_)
3469 return false;
3470
3471 Expression* e = this->constant_->const_value()->expr();
3472
3473 this->seen_ = true;
3474
3475 bool r = e->numeric_constant_value(nc);
3476
3477 this->seen_ = false;
3478
3479 Type* ctype;
3480 if (this->type_ != NULL)
3481 ctype = this->type_;
3482 else
3483 ctype = this->constant_->const_value()->type();
3484 if (r && ctype != NULL)
3485 {
3486 if (!nc->set_type(ctype, false, this->location()))
3487 return false;
3488 }
3489
3490 return r;
3491 }
3492
3493 bool
3494 Const_expression::do_string_constant_value(std::string* val) const
3495 {
3496 if (this->seen_)
3497 return false;
3498
3499 Expression* e = this->constant_->const_value()->expr();
3500
3501 this->seen_ = true;
3502 bool ok = e->string_constant_value(val);
3503 this->seen_ = false;
3504
3505 return ok;
3506 }
3507
3508 bool
3509 Const_expression::do_boolean_constant_value(bool* val) const
3510 {
3511 if (this->seen_)
3512 return false;
3513
3514 Expression* e = this->constant_->const_value()->expr();
3515
3516 this->seen_ = true;
3517 bool ok = e->boolean_constant_value(val);
3518 this->seen_ = false;
3519
3520 return ok;
3521 }
3522
3523 // Return the type of the const reference.
3524
3525 Type*
3526 Const_expression::do_type()
3527 {
3528 if (this->type_ != NULL)
3529 return this->type_;
3530
3531 Named_constant* nc = this->constant_->const_value();
3532
3533 if (this->seen_ || nc->lowering())
3534 {
3535 if (nc->type() == NULL || !nc->type()->is_error_type())
3536 {
3537 Location loc = this->location();
3538 if (!this->seen_)
3539 loc = nc->location();
3540 go_error_at(loc, "constant refers to itself");
3541 }
3542 this->set_is_error();
3543 this->type_ = Type::make_error_type();
3544 nc->set_type(this->type_);
3545 return this->type_;
3546 }
3547
3548 this->seen_ = true;
3549
3550 Type* ret = nc->type();
3551
3552 if (ret != NULL)
3553 {
3554 this->seen_ = false;
3555 return ret;
3556 }
3557
3558 // During parsing, a named constant may have a NULL type, but we
3559 // must not return a NULL type here.
3560 ret = nc->expr()->type();
3561
3562 this->seen_ = false;
3563
3564 if (ret->is_error_type())
3565 nc->set_type(ret);
3566
3567 return ret;
3568 }
3569
3570 // Set the type of the const reference.
3571
3572 void
3573 Const_expression::do_determine_type(const Type_context* context)
3574 {
3575 Type* ctype = this->constant_->const_value()->type();
3576 Type* cetype = (ctype != NULL
3577 ? ctype
3578 : this->constant_->const_value()->expr()->type());
3579 if (ctype != NULL && !ctype->is_abstract())
3580 ;
3581 else if (context->type != NULL
3582 && context->type->is_numeric_type()
3583 && cetype->is_numeric_type())
3584 this->type_ = context->type;
3585 else if (context->type != NULL
3586 && context->type->is_string_type()
3587 && cetype->is_string_type())
3588 this->type_ = context->type;
3589 else if (context->type != NULL
3590 && context->type->is_boolean_type()
3591 && cetype->is_boolean_type())
3592 this->type_ = context->type;
3593 else if (!context->may_be_abstract)
3594 {
3595 if (cetype->is_abstract())
3596 cetype = cetype->make_non_abstract_type();
3597 this->type_ = cetype;
3598 }
3599 }
3600
3601 // Check for a loop in which the initializer of a constant refers to
3602 // the constant itself.
3603
3604 void
3605 Const_expression::check_for_init_loop()
3606 {
3607 if (this->type_ != NULL && this->type_->is_error())
3608 return;
3609
3610 if (this->seen_)
3611 {
3612 this->report_error(_("constant refers to itself"));
3613 this->type_ = Type::make_error_type();
3614 return;
3615 }
3616
3617 Expression* init = this->constant_->const_value()->expr();
3618 Find_named_object find_named_object(this->constant_);
3619
3620 this->seen_ = true;
3621 Expression::traverse(&init, &find_named_object);
3622 this->seen_ = false;
3623
3624 if (find_named_object.found())
3625 {
3626 if (this->type_ == NULL || !this->type_->is_error())
3627 {
3628 this->report_error(_("constant refers to itself"));
3629 this->type_ = Type::make_error_type();
3630 }
3631 return;
3632 }
3633 }
3634
3635 // Check types of a const reference.
3636
3637 void
3638 Const_expression::do_check_types(Gogo*)
3639 {
3640 if (this->type_ != NULL && this->type_->is_error())
3641 return;
3642
3643 this->check_for_init_loop();
3644
3645 // Check that numeric constant fits in type.
3646 if (this->type_ != NULL && this->type_->is_numeric_type())
3647 {
3648 Numeric_constant nc;
3649 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3650 {
3651 if (!nc.set_type(this->type_, true, this->location()))
3652 this->set_is_error();
3653 }
3654 }
3655 }
3656
3657 // Return the backend representation for a const reference.
3658
3659 Bexpression*
3660 Const_expression::do_get_backend(Translate_context* context)
3661 {
3662 if (this->is_error_expression()
3663 || (this->type_ != NULL && this->type_->is_error()))
3664 {
3665 go_assert(saw_errors());
3666 return context->backend()->error_expression();
3667 }
3668
3669 // If the type has been set for this expression, but the underlying
3670 // object is an abstract int or float, we try to get the abstract
3671 // value. Otherwise we may lose something in the conversion.
3672 Expression* expr = this->constant_->const_value()->expr();
3673 if (this->type_ != NULL
3674 && this->type_->is_numeric_type()
3675 && (this->constant_->const_value()->type() == NULL
3676 || this->constant_->const_value()->type()->is_abstract()))
3677 {
3678 Numeric_constant nc;
3679 if (expr->numeric_constant_value(&nc)
3680 && nc.set_type(this->type_, false, this->location()))
3681 {
3682 Expression* e = nc.expression(this->location());
3683 return e->get_backend(context);
3684 }
3685 }
3686
3687 if (this->type_ != NULL)
3688 expr = Expression::make_cast(this->type_, expr, this->location());
3689 return expr->get_backend(context);
3690 }
3691
3692 // Dump ast representation for constant expression.
3693
3694 void
3695 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3696 {
3697 ast_dump_context->ostream() << this->constant_->name();
3698 }
3699
3700 // Make a reference to a constant in an expression.
3701
3702 Expression*
3703 Expression::make_const_reference(Named_object* constant,
3704 Location location)
3705 {
3706 return new Const_expression(constant, location);
3707 }
3708
3709 // Find a named object in an expression.
3710
3711 int
3712 Find_named_object::expression(Expression** pexpr)
3713 {
3714 switch ((*pexpr)->classification())
3715 {
3716 case Expression::EXPRESSION_CONST_REFERENCE:
3717 {
3718 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3719 if (ce->named_object() == this->no_)
3720 break;
3721
3722 // We need to check a constant initializer explicitly, as
3723 // loops here will not be caught by the loop checking for
3724 // variable initializers.
3725 ce->check_for_init_loop();
3726
3727 return TRAVERSE_CONTINUE;
3728 }
3729
3730 case Expression::EXPRESSION_VAR_REFERENCE:
3731 if ((*pexpr)->var_expression()->named_object() == this->no_)
3732 break;
3733 return TRAVERSE_CONTINUE;
3734 case Expression::EXPRESSION_FUNC_REFERENCE:
3735 if ((*pexpr)->func_expression()->named_object() == this->no_)
3736 break;
3737 return TRAVERSE_CONTINUE;
3738 default:
3739 return TRAVERSE_CONTINUE;
3740 }
3741 this->found_ = true;
3742 return TRAVERSE_EXIT;
3743 }
3744
3745 // The nil value.
3746
3747 class Nil_expression : public Expression
3748 {
3749 public:
3750 Nil_expression(Location location)
3751 : Expression(EXPRESSION_NIL, location)
3752 { }
3753
3754 static Expression*
3755 do_import(Import_expression*, Location);
3756
3757 protected:
3758 bool
3759 do_is_constant() const
3760 { return true; }
3761
3762 bool
3763 do_is_zero_value() const
3764 { return true; }
3765
3766 bool
3767 do_is_static_initializer() const
3768 { return true; }
3769
3770 Type*
3771 do_type()
3772 { return Type::make_nil_type(); }
3773
3774 void
3775 do_determine_type(const Type_context*)
3776 { }
3777
3778 Expression*
3779 do_copy()
3780 { return this; }
3781
3782 Bexpression*
3783 do_get_backend(Translate_context* context)
3784 { return context->backend()->nil_pointer_expression(); }
3785
3786 int
3787 do_inlining_cost() const
3788 { return 1; }
3789
3790 void
3791 do_export(Export_function_body* efb) const
3792 { efb->write_c_string("$nil"); }
3793
3794 void
3795 do_dump_expression(Ast_dump_context* ast_dump_context) const
3796 { ast_dump_context->ostream() << "nil"; }
3797 };
3798
3799 // Import a nil expression.
3800
3801 Expression*
3802 Nil_expression::do_import(Import_expression* imp, Location loc)
3803 {
3804 if (imp->version() >= EXPORT_FORMAT_V3)
3805 imp->require_c_string("$");
3806 imp->require_c_string("nil");
3807 return Expression::make_nil(loc);
3808 }
3809
3810 // Make a nil expression.
3811
3812 Expression*
3813 Expression::make_nil(Location location)
3814 {
3815 return new Nil_expression(location);
3816 }
3817
3818 // The value of the predeclared constant iota. This is little more
3819 // than a marker. This will be lowered to an integer in
3820 // Const_expression::do_lower, which is where we know the value that
3821 // it should have.
3822
3823 class Iota_expression : public Parser_expression
3824 {
3825 public:
3826 Iota_expression(Location location)
3827 : Parser_expression(EXPRESSION_IOTA, location)
3828 { }
3829
3830 protected:
3831 Expression*
3832 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3833 { go_unreachable(); }
3834
3835 // There should only ever be one of these.
3836 Expression*
3837 do_copy()
3838 { go_unreachable(); }
3839
3840 void
3841 do_dump_expression(Ast_dump_context* ast_dump_context) const
3842 { ast_dump_context->ostream() << "iota"; }
3843 };
3844
3845 // Make an iota expression. This is only called for one case: the
3846 // value of the predeclared constant iota.
3847
3848 Expression*
3849 Expression::make_iota()
3850 {
3851 static Iota_expression iota_expression(Linemap::unknown_location());
3852 return &iota_expression;
3853 }
3854
3855 // Class Type_conversion_expression.
3856
3857 // Traversal.
3858
3859 int
3860 Type_conversion_expression::do_traverse(Traverse* traverse)
3861 {
3862 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3863 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3864 return TRAVERSE_EXIT;
3865 return TRAVERSE_CONTINUE;
3866 }
3867
3868 // Convert to a constant at lowering time.
3869
3870 Expression*
3871 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3872 Statement_inserter*, int)
3873 {
3874 Type* type = this->type_;
3875 Expression* val = this->expr_;
3876 Location location = this->location();
3877
3878 if (type->is_numeric_type())
3879 {
3880 Numeric_constant nc;
3881 if (val->numeric_constant_value(&nc))
3882 {
3883 if (!nc.set_type(type, true, location))
3884 return Expression::make_error(location);
3885 return nc.expression(location);
3886 }
3887 }
3888
3889 // According to the language specification on string conversions
3890 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3891 // When converting an integer into a string, the string will be a UTF-8
3892 // representation of the integer and integers "outside the range of valid
3893 // Unicode code points are converted to '\uFFFD'."
3894 if (type->is_string_type())
3895 {
3896 Numeric_constant nc;
3897 if (val->numeric_constant_value(&nc) && nc.is_int())
3898 {
3899 // An integer value doesn't fit in the Unicode code point range if it
3900 // overflows the Go "int" type or is negative.
3901 unsigned long ul;
3902 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3903 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3904 return Expression::make_string("\ufffd", location);
3905 }
3906 }
3907
3908 if (type->is_slice_type())
3909 {
3910 Type* element_type = type->array_type()->element_type()->forwarded();
3911 bool is_byte = (element_type->integer_type() != NULL
3912 && element_type->integer_type()->is_byte());
3913 bool is_rune = (element_type->integer_type() != NULL
3914 && element_type->integer_type()->is_rune());
3915 if (is_byte || is_rune)
3916 {
3917 std::string s;
3918 if (val->string_constant_value(&s))
3919 {
3920 Expression_list* vals = new Expression_list();
3921 if (is_byte)
3922 {
3923 for (std::string::const_iterator p = s.begin();
3924 p != s.end();
3925 p++)
3926 {
3927 unsigned char c = static_cast<unsigned char>(*p);
3928 vals->push_back(Expression::make_integer_ul(c,
3929 element_type,
3930 location));
3931 }
3932 }
3933 else
3934 {
3935 const char *p = s.data();
3936 const char *pend = s.data() + s.length();
3937 while (p < pend)
3938 {
3939 unsigned int c;
3940 int adv = Lex::fetch_char(p, &c);
3941 if (adv == 0)
3942 {
3943 go_warning_at(this->location(), 0,
3944 "invalid UTF-8 encoding");
3945 adv = 1;
3946 }
3947 p += adv;
3948 vals->push_back(Expression::make_integer_ul(c,
3949 element_type,
3950 location));
3951 }
3952 }
3953
3954 return Expression::make_slice_composite_literal(type, vals,
3955 location);
3956 }
3957 }
3958 }
3959
3960 return this;
3961 }
3962
3963 // Flatten a type conversion by using a temporary variable for the slice
3964 // in slice to string conversions.
3965
3966 Expression*
3967 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3968 Statement_inserter* inserter)
3969 {
3970 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3971 {
3972 go_assert(saw_errors());
3973 return Expression::make_error(this->location());
3974 }
3975
3976 if (((this->type()->is_string_type()
3977 && this->expr_->type()->is_slice_type())
3978 || this->expr_->type()->interface_type() != NULL)
3979 && !this->expr_->is_variable())
3980 {
3981 Temporary_statement* temp =
3982 Statement::make_temporary(NULL, this->expr_, this->location());
3983 inserter->insert(temp);
3984 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3985 }
3986
3987 // For interface conversion and string to/from slice conversions,
3988 // decide if we can allocate on stack.
3989 if (this->type()->interface_type() != NULL
3990 || this->type()->is_string_type()
3991 || this->expr_->type()->is_string_type())
3992 {
3993 Node* n = Node::make_node(this);
3994 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
3995 this->no_escape_ = true;
3996 }
3997 return this;
3998 }
3999
4000 // Return whether a type conversion is a constant.
4001
4002 bool
4003 Type_conversion_expression::do_is_constant() const
4004 {
4005 if (!this->expr_->is_constant())
4006 return false;
4007
4008 // A conversion to a type that may not be used as a constant is not
4009 // a constant. For example, []byte(nil).
4010 Type* type = this->type_;
4011 if (type->integer_type() == NULL
4012 && type->float_type() == NULL
4013 && type->complex_type() == NULL
4014 && !type->is_boolean_type()
4015 && !type->is_string_type())
4016 return false;
4017
4018 return true;
4019 }
4020
4021 // Return whether a type conversion is a zero value.
4022
4023 bool
4024 Type_conversion_expression::do_is_zero_value() const
4025 {
4026 if (!this->expr_->is_zero_value())
4027 return false;
4028
4029 // Some type conversion from zero value is still not zero value.
4030 // For example, []byte("") or interface{}(0).
4031 // Conservatively, only report true if the RHS is nil.
4032 Type* type = this->type_;
4033 if (type->integer_type() == NULL
4034 && type->float_type() == NULL
4035 && type->complex_type() == NULL
4036 && !type->is_boolean_type()
4037 && !type->is_string_type())
4038 return this->expr_->is_nil_expression();
4039
4040 return true;
4041 }
4042
4043 // Return whether a type conversion can be used in a constant
4044 // initializer.
4045
4046 bool
4047 Type_conversion_expression::do_is_static_initializer() const
4048 {
4049 Type* type = this->type_;
4050 Type* expr_type = this->expr_->type();
4051
4052 if (type->interface_type() != NULL
4053 || expr_type->interface_type() != NULL)
4054 return false;
4055
4056 if (!this->expr_->is_static_initializer())
4057 return false;
4058
4059 if (Type::are_identical(type, expr_type,
4060 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4061 NULL))
4062 return true;
4063
4064 if (type->is_string_type() && expr_type->is_string_type())
4065 return true;
4066
4067 if ((type->is_numeric_type()
4068 || type->is_boolean_type()
4069 || type->points_to() != NULL)
4070 && (expr_type->is_numeric_type()
4071 || expr_type->is_boolean_type()
4072 || expr_type->points_to() != NULL))
4073 return true;
4074
4075 return false;
4076 }
4077
4078 // Return the constant numeric value if there is one.
4079
4080 bool
4081 Type_conversion_expression::do_numeric_constant_value(
4082 Numeric_constant* nc) const
4083 {
4084 if (!this->type_->is_numeric_type())
4085 return false;
4086 if (!this->expr_->numeric_constant_value(nc))
4087 return false;
4088 return nc->set_type(this->type_, false, this->location());
4089 }
4090
4091 // Return the constant string value if there is one.
4092
4093 bool
4094 Type_conversion_expression::do_string_constant_value(std::string* val) const
4095 {
4096 if (this->type_->is_string_type()
4097 && this->expr_->type()->integer_type() != NULL)
4098 {
4099 Numeric_constant nc;
4100 if (this->expr_->numeric_constant_value(&nc))
4101 {
4102 unsigned long ival;
4103 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4104 {
4105 unsigned int cval = static_cast<unsigned int>(ival);
4106 if (static_cast<unsigned long>(cval) != ival)
4107 {
4108 go_warning_at(this->location(), 0,
4109 "unicode code point 0x%lx out of range",
4110 ival);
4111 cval = 0xfffd; // Unicode "replacement character."
4112 }
4113 val->clear();
4114 Lex::append_char(cval, true, val, this->location());
4115 return true;
4116 }
4117 }
4118 }
4119
4120 // FIXME: Could handle conversion from const []int here.
4121
4122 return false;
4123 }
4124
4125 // Return the constant boolean value if there is one.
4126
4127 bool
4128 Type_conversion_expression::do_boolean_constant_value(bool* val) const
4129 {
4130 if (!this->type_->is_boolean_type())
4131 return false;
4132 return this->expr_->boolean_constant_value(val);
4133 }
4134
4135 // Determine the resulting type of the conversion.
4136
4137 void
4138 Type_conversion_expression::do_determine_type(const Type_context*)
4139 {
4140 Type_context subcontext(this->type_, false);
4141 this->expr_->determine_type(&subcontext);
4142 }
4143
4144 // Check that types are convertible.
4145
4146 void
4147 Type_conversion_expression::do_check_types(Gogo*)
4148 {
4149 Type* type = this->type_;
4150 Type* expr_type = this->expr_->type();
4151 std::string reason;
4152
4153 if (type->is_error() || expr_type->is_error())
4154 {
4155 this->set_is_error();
4156 return;
4157 }
4158
4159 if (this->may_convert_function_types_
4160 && type->function_type() != NULL
4161 && expr_type->function_type() != NULL)
4162 return;
4163
4164 if (Type::are_convertible(type, expr_type, &reason))
4165 return;
4166
4167 go_error_at(this->location(), "%s", reason.c_str());
4168 this->set_is_error();
4169 }
4170
4171 // Copy.
4172
4173 Expression*
4174 Type_conversion_expression::do_copy()
4175 {
4176 Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4177 this->expr_->copy(),
4178 this->location());
4179 ret->conversion_expression()->set_no_copy(this->no_copy_);
4180 return ret;
4181 }
4182
4183 // Get the backend representation for a type conversion.
4184
4185 Bexpression*
4186 Type_conversion_expression::do_get_backend(Translate_context* context)
4187 {
4188 Type* type = this->type_;
4189 Type* expr_type = this->expr_->type();
4190
4191 Gogo* gogo = context->gogo();
4192 Btype* btype = type->get_backend(gogo);
4193 Location loc = this->location();
4194
4195 if (Type::are_identical(type, expr_type,
4196 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4197 NULL))
4198 {
4199 Bexpression* bexpr = this->expr_->get_backend(context);
4200 return gogo->backend()->convert_expression(btype, bexpr, loc);
4201 }
4202 else if (type->interface_type() != NULL
4203 && expr_type->interface_type() == NULL)
4204 {
4205 Expression* conversion =
4206 Expression::convert_type_to_interface(type, this->expr_,
4207 this->no_escape_, loc);
4208 return conversion->get_backend(context);
4209 }
4210 else if (type->interface_type() != NULL
4211 || expr_type->interface_type() != NULL)
4212 {
4213 Expression* conversion =
4214 Expression::convert_for_assignment(gogo, type, this->expr_,
4215 loc);
4216 return conversion->get_backend(context);
4217 }
4218 else if (type->is_string_type()
4219 && expr_type->integer_type() != NULL)
4220 {
4221 mpz_t intval;
4222 Numeric_constant nc;
4223 if (this->expr_->numeric_constant_value(&nc)
4224 && nc.to_int(&intval))
4225 {
4226 std::string s;
4227 unsigned int x;
4228 if (mpz_fits_uint_p(intval))
4229 x = mpz_get_ui(intval);
4230 else
4231 {
4232 char* ms = mpz_get_str(NULL, 16, intval);
4233 go_warning_at(loc, 0,
4234 "unicode code point 0x%s out of range in string",
4235 ms);
4236 free(ms);
4237 x = 0xfffd;
4238 }
4239 Lex::append_char(x, true, &s, loc);
4240 mpz_clear(intval);
4241 Expression* se = Expression::make_string(s, loc);
4242 return se->get_backend(context);
4243 }
4244
4245 Expression* buf;
4246 if (this->no_escape_)
4247 {
4248 Type* byte_type = Type::lookup_integer_type("uint8");
4249 Expression* buflen =
4250 Expression::make_integer_ul(4, NULL, loc);
4251 Type* array_type = Type::make_array_type(byte_type, buflen);
4252 buf = Expression::make_allocation(array_type, loc);
4253 buf->allocation_expression()->set_allocate_on_stack();
4254 buf->allocation_expression()->set_no_zero();
4255 }
4256 else
4257 buf = Expression::make_nil(loc);
4258 Expression* i2s_expr =
4259 Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
4260 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
4261 }
4262 else if (type->is_string_type() && expr_type->is_slice_type())
4263 {
4264 Array_type* a = expr_type->array_type();
4265 Type* e = a->element_type()->forwarded();
4266 go_assert(e->integer_type() != NULL);
4267 go_assert(this->expr_->is_variable());
4268
4269 Expression* buf;
4270 if (this->no_escape_ && !this->no_copy_)
4271 {
4272 Type* byte_type = Type::lookup_integer_type("uint8");
4273 Expression* buflen =
4274 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4275 Type* array_type = Type::make_array_type(byte_type, buflen);
4276 buf = Expression::make_allocation(array_type, loc);
4277 buf->allocation_expression()->set_allocate_on_stack();
4278 buf->allocation_expression()->set_no_zero();
4279 }
4280 else
4281 buf = Expression::make_nil(loc);
4282
4283 if (e->integer_type()->is_byte())
4284 {
4285 Expression* ptr =
4286 Expression::make_slice_info(this->expr_, SLICE_INFO_VALUE_POINTER,
4287 loc);
4288 Expression* len =
4289 Expression::make_slice_info(this->expr_, SLICE_INFO_LENGTH, loc);
4290 if (this->no_copy_)
4291 {
4292 if (gogo->debug_optimization())
4293 go_debug(loc, "no copy string([]byte)");
4294 Expression* str = Expression::make_string_value(ptr, len, loc);
4295 return str->get_backend(context);
4296 }
4297 return Runtime::make_call(Runtime::SLICEBYTETOSTRING, loc, 3, buf,
4298 ptr, len)->get_backend(context);
4299 }
4300 else
4301 {
4302 go_assert(e->integer_type()->is_rune());
4303 return Runtime::make_call(Runtime::SLICERUNETOSTRING, loc, 2, buf,
4304 this->expr_)->get_backend(context);
4305 }
4306 }
4307 else if (type->is_slice_type() && expr_type->is_string_type())
4308 {
4309 Type* e = type->array_type()->element_type()->forwarded();
4310 go_assert(e->integer_type() != NULL);
4311
4312 Runtime::Function code;
4313 if (e->integer_type()->is_byte())
4314 code = Runtime::STRINGTOSLICEBYTE;
4315 else
4316 {
4317 go_assert(e->integer_type()->is_rune());
4318 code = Runtime::STRINGTOSLICERUNE;
4319 }
4320
4321 Expression* buf;
4322 if (this->no_escape_)
4323 {
4324 Expression* buflen =
4325 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4326 Type* array_type = Type::make_array_type(e, buflen);
4327 buf = Expression::make_allocation(array_type, loc);
4328 buf->allocation_expression()->set_allocate_on_stack();
4329 buf->allocation_expression()->set_no_zero();
4330 }
4331 else
4332 buf = Expression::make_nil(loc);
4333 Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
4334 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
4335 }
4336 else if (type->is_numeric_type())
4337 {
4338 go_assert(Type::are_convertible(type, expr_type, NULL));
4339 Bexpression* bexpr = this->expr_->get_backend(context);
4340 return gogo->backend()->convert_expression(btype, bexpr, loc);
4341 }
4342 else if ((type->is_unsafe_pointer_type()
4343 && (expr_type->points_to() != NULL
4344 || expr_type->integer_type()))
4345 || (expr_type->is_unsafe_pointer_type()
4346 && type->points_to() != NULL)
4347 || (this->may_convert_function_types_
4348 && type->function_type() != NULL
4349 && expr_type->function_type() != NULL))
4350 {
4351 Bexpression* bexpr = this->expr_->get_backend(context);
4352 return gogo->backend()->convert_expression(btype, bexpr, loc);
4353 }
4354 else
4355 {
4356 Expression* conversion =
4357 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4358 return conversion->get_backend(context);
4359 }
4360 }
4361
4362 // Cost of inlining a type conversion.
4363
4364 int
4365 Type_conversion_expression::do_inlining_cost() const
4366 {
4367 Type* type = this->type_;
4368 Type* expr_type = this->expr_->type();
4369 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4370 return 10;
4371 else if (type->is_string_type() && expr_type->integer_type() != NULL)
4372 return 10;
4373 else if (type->is_string_type() && expr_type->is_slice_type())
4374 return 10;
4375 else if (type->is_slice_type() && expr_type->is_string_type())
4376 return 10;
4377 else
4378 return 1;
4379 }
4380
4381 // Output a type conversion in a constant expression.
4382
4383 void
4384 Type_conversion_expression::do_export(Export_function_body* efb) const
4385 {
4386 efb->write_c_string("$convert(");
4387 efb->write_type(this->type_);
4388 efb->write_c_string(", ");
4389
4390 Type* old_context = efb->type_context();
4391 efb->set_type_context(this->type_);
4392
4393 this->expr_->export_expression(efb);
4394
4395 efb->set_type_context(old_context);
4396
4397 efb->write_c_string(")");
4398 }
4399
4400 // Import a type conversion or a struct construction.
4401
4402 Expression*
4403 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4404 {
4405 imp->require_c_string("$convert(");
4406 Type* type = imp->read_type();
4407 imp->require_c_string(", ");
4408 Expression* val = Expression::import_expression(imp, loc);
4409 imp->require_c_string(")");
4410 return Expression::make_cast(type, val, loc);
4411 }
4412
4413 // Dump ast representation for a type conversion expression.
4414
4415 void
4416 Type_conversion_expression::do_dump_expression(
4417 Ast_dump_context* ast_dump_context) const
4418 {
4419 ast_dump_context->dump_type(this->type_);
4420 ast_dump_context->ostream() << "(";
4421 ast_dump_context->dump_expression(this->expr_);
4422 ast_dump_context->ostream() << ") ";
4423 }
4424
4425 // Make a type cast expression.
4426
4427 Expression*
4428 Expression::make_cast(Type* type, Expression* val, Location location)
4429 {
4430 if (type->is_error_type() || val->is_error_expression())
4431 return Expression::make_error(location);
4432 return new Type_conversion_expression(type, val, location);
4433 }
4434
4435 // Class Unsafe_type_conversion_expression.
4436
4437 // Traversal.
4438
4439 int
4440 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4441 {
4442 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4443 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4444 return TRAVERSE_EXIT;
4445 return TRAVERSE_CONTINUE;
4446 }
4447
4448 // Return whether an unsafe type conversion can be used as a constant
4449 // initializer.
4450
4451 bool
4452 Unsafe_type_conversion_expression::do_is_static_initializer() const
4453 {
4454 Type* type = this->type_;
4455 Type* expr_type = this->expr_->type();
4456
4457 if (type->interface_type() != NULL
4458 || expr_type->interface_type() != NULL)
4459 return false;
4460
4461 if (!this->expr_->is_static_initializer())
4462 return false;
4463
4464 if (Type::are_convertible(type, expr_type, NULL))
4465 return true;
4466
4467 if (type->is_string_type() && expr_type->is_string_type())
4468 return true;
4469
4470 if ((type->is_numeric_type()
4471 || type->is_boolean_type()
4472 || type->points_to() != NULL)
4473 && (expr_type->is_numeric_type()
4474 || expr_type->is_boolean_type()
4475 || expr_type->points_to() != NULL))
4476 return true;
4477
4478 return false;
4479 }
4480
4481 // Copy.
4482
4483 Expression*
4484 Unsafe_type_conversion_expression::do_copy()
4485 {
4486 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4487 this->expr_->copy(),
4488 this->location());
4489 }
4490
4491 // Convert to backend representation.
4492
4493 Bexpression*
4494 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4495 {
4496 // We are only called for a limited number of cases.
4497
4498 Type* t = this->type_;
4499 Type* et = this->expr_->type();
4500
4501 if (t->is_error_type()
4502 || this->expr_->is_error_expression()
4503 || et->is_error_type())
4504 {
4505 go_assert(saw_errors());
4506 return context->backend()->error_expression();
4507 }
4508
4509 if (t->array_type() != NULL)
4510 go_assert(et->array_type() != NULL
4511 && t->is_slice_type() == et->is_slice_type());
4512 else if (t->struct_type() != NULL)
4513 {
4514 if (t->named_type() != NULL
4515 && et->named_type() != NULL
4516 && !Type::are_convertible(t, et, NULL))
4517 {
4518 go_assert(saw_errors());
4519 return context->backend()->error_expression();
4520 }
4521
4522 go_assert(et->struct_type() != NULL
4523 && Type::are_convertible(t, et, NULL));
4524 }
4525 else if (t->map_type() != NULL)
4526 go_assert(et->map_type() != NULL || et->points_to() != NULL);
4527 else if (t->channel_type() != NULL)
4528 go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4529 else if (t->points_to() != NULL)
4530 go_assert(et->points_to() != NULL
4531 || et->channel_type() != NULL
4532 || et->map_type() != NULL
4533 || et->function_type() != NULL
4534 || et->integer_type() != NULL
4535 || et->is_nil_type());
4536 else if (t->function_type() != NULL)
4537 go_assert(et->points_to() != NULL);
4538 else if (et->is_unsafe_pointer_type())
4539 go_assert(t->points_to() != NULL
4540 || (t->integer_type() != NULL
4541 && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4542 else if (t->interface_type() != NULL)
4543 {
4544 bool empty_iface = t->interface_type()->is_empty();
4545 go_assert(et->interface_type() != NULL
4546 && et->interface_type()->is_empty() == empty_iface);
4547 }
4548 else if (t->integer_type() != NULL)
4549 go_assert(et->is_boolean_type()
4550 || et->integer_type() != NULL
4551 || et->function_type() != NULL
4552 || et->points_to() != NULL
4553 || et->map_type() != NULL
4554 || et->channel_type() != NULL
4555 || et->is_nil_type());
4556 else
4557 go_unreachable();
4558
4559 Gogo* gogo = context->gogo();
4560 Btype* btype = t->get_backend(gogo);
4561 Bexpression* bexpr = this->expr_->get_backend(context);
4562 Location loc = this->location();
4563 return gogo->backend()->convert_expression(btype, bexpr, loc);
4564 }
4565
4566 // Dump ast representation for an unsafe type conversion expression.
4567
4568 void
4569 Unsafe_type_conversion_expression::do_dump_expression(
4570 Ast_dump_context* ast_dump_context) const
4571 {
4572 ast_dump_context->dump_type(this->type_);
4573 ast_dump_context->ostream() << "(";
4574 ast_dump_context->dump_expression(this->expr_);
4575 ast_dump_context->ostream() << ") ";
4576 }
4577
4578 // Make an unsafe type conversion expression.
4579
4580 Expression*
4581 Expression::make_unsafe_cast(Type* type, Expression* expr,
4582 Location location)
4583 {
4584 return new Unsafe_type_conversion_expression(type, expr, location);
4585 }
4586
4587 // Class Unary_expression.
4588
4589 // Call the address_taken method of the operand if needed. This is
4590 // called after escape analysis but before inserting write barriers.
4591
4592 void
4593 Unary_expression::check_operand_address_taken(Gogo*)
4594 {
4595 if (this->op_ != OPERATOR_AND)
4596 return;
4597
4598 // If this->escapes_ is false at this point, then it was set to
4599 // false by an explicit call to set_does_not_escape, and the value
4600 // does not escape. If this->escapes_ is true, we may be able to
4601 // set it to false based on the escape analysis pass.
4602 if (this->escapes_)
4603 {
4604 Node* n = Node::make_node(this);
4605 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4606 this->escapes_ = false;
4607 }
4608
4609 this->expr_->address_taken(this->escapes_);
4610 }
4611
4612 // If we are taking the address of a composite literal, and the
4613 // contents are not constant, then we want to make a heap expression
4614 // instead.
4615
4616 Expression*
4617 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4618 {
4619 Location loc = this->location();
4620 Operator op = this->op_;
4621 Expression* expr = this->expr_;
4622
4623 if (op == OPERATOR_MULT && expr->is_type_expression())
4624 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4625
4626 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
4627 // moving x to the heap. FIXME: Is it worth doing a real escape
4628 // analysis here? This case is found in math/unsafe.go and is
4629 // therefore worth special casing.
4630 if (op == OPERATOR_MULT)
4631 {
4632 Expression* e = expr;
4633 while (e->classification() == EXPRESSION_CONVERSION)
4634 {
4635 Type_conversion_expression* te
4636 = static_cast<Type_conversion_expression*>(e);
4637 e = te->expr();
4638 }
4639
4640 if (e->classification() == EXPRESSION_UNARY)
4641 {
4642 Unary_expression* ue = static_cast<Unary_expression*>(e);
4643 if (ue->op_ == OPERATOR_AND)
4644 {
4645 if (e == expr)
4646 {
4647 // *&x == x.
4648 if (!ue->expr_->is_addressable() && !ue->create_temp_)
4649 {
4650 go_error_at(ue->location(),
4651 "invalid operand for unary %<&%>");
4652 this->set_is_error();
4653 }
4654 return ue->expr_;
4655 }
4656 ue->set_does_not_escape();
4657 }
4658 }
4659 }
4660
4661 // Catching an invalid indirection of unsafe.Pointer here avoid
4662 // having to deal with TYPE_VOID in other places.
4663 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4664 {
4665 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4666 return Expression::make_error(this->location());
4667 }
4668
4669 // Check for an invalid pointer dereference. We need to do this
4670 // here because Unary_expression::do_type will return an error type
4671 // in this case. That can cause code to appear erroneous, and
4672 // therefore disappear at lowering time, without any error message.
4673 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4674 {
4675 this->report_error(_("expected pointer"));
4676 return Expression::make_error(this->location());
4677 }
4678
4679 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4680 {
4681 Numeric_constant nc;
4682 if (expr->numeric_constant_value(&nc))
4683 {
4684 Numeric_constant result;
4685 bool issued_error;
4686 if (Unary_expression::eval_constant(op, &nc, loc, &result,
4687 &issued_error))
4688 return result.expression(loc);
4689 else if (issued_error)
4690 return Expression::make_error(this->location());
4691 }
4692 }
4693
4694 return this;
4695 }
4696
4697 // Flatten expression if a nil check must be performed and create temporary
4698 // variables if necessary.
4699
4700 Expression*
4701 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4702 Statement_inserter* inserter)
4703 {
4704 if (this->is_error_expression()
4705 || this->expr_->is_error_expression()
4706 || this->expr_->type()->is_error_type())
4707 {
4708 go_assert(saw_errors());
4709 return Expression::make_error(this->location());
4710 }
4711
4712 Location location = this->location();
4713 if (this->op_ == OPERATOR_MULT
4714 && !this->expr_->is_variable())
4715 {
4716 go_assert(this->expr_->type()->points_to() != NULL);
4717 switch (this->requires_nil_check(gogo))
4718 {
4719 case NIL_CHECK_ERROR_ENCOUNTERED:
4720 {
4721 go_assert(saw_errors());
4722 return Expression::make_error(this->location());
4723 }
4724 case NIL_CHECK_NOT_NEEDED:
4725 break;
4726 case NIL_CHECK_NEEDED:
4727 this->create_temp_ = true;
4728 break;
4729 case NIL_CHECK_DEFAULT:
4730 go_unreachable();
4731 }
4732 }
4733
4734 if (this->create_temp_ && !this->expr_->is_variable())
4735 {
4736 Temporary_statement* temp =
4737 Statement::make_temporary(NULL, this->expr_, location);
4738 inserter->insert(temp);
4739 this->expr_ = Expression::make_temporary_reference(temp, location);
4740 }
4741
4742 return this;
4743 }
4744
4745 // Return whether a unary expression is a constant.
4746
4747 bool
4748 Unary_expression::do_is_constant() const
4749 {
4750 if (this->op_ == OPERATOR_MULT)
4751 {
4752 // Indirecting through a pointer is only constant if the object
4753 // to which the expression points is constant, but we currently
4754 // have no way to determine that.
4755 return false;
4756 }
4757 else if (this->op_ == OPERATOR_AND)
4758 {
4759 // Taking the address of a variable is constant if it is a
4760 // global variable, not constant otherwise. In other cases taking the
4761 // address is probably not a constant.
4762 Var_expression* ve = this->expr_->var_expression();
4763 if (ve != NULL)
4764 {
4765 Named_object* no = ve->named_object();
4766 return no->is_variable() && no->var_value()->is_global();
4767 }
4768 return false;
4769 }
4770 else
4771 return this->expr_->is_constant();
4772 }
4773
4774 // Return whether a unary expression can be used as a constant
4775 // initializer.
4776
4777 bool
4778 Unary_expression::do_is_static_initializer() const
4779 {
4780 if (this->op_ == OPERATOR_MULT)
4781 return false;
4782 else if (this->op_ == OPERATOR_AND)
4783 return Unary_expression::base_is_static_initializer(this->expr_);
4784 else
4785 return this->expr_->is_static_initializer();
4786 }
4787
4788 // Return whether the address of EXPR can be used as a static
4789 // initializer.
4790
4791 bool
4792 Unary_expression::base_is_static_initializer(Expression* expr)
4793 {
4794 // The address of a field reference can be a static initializer if
4795 // the base can be a static initializer.
4796 Field_reference_expression* fre = expr->field_reference_expression();
4797 if (fre != NULL)
4798 return Unary_expression::base_is_static_initializer(fre->expr());
4799
4800 // The address of an index expression can be a static initializer if
4801 // the base can be a static initializer and the index is constant.
4802 Array_index_expression* aind = expr->array_index_expression();
4803 if (aind != NULL)
4804 return (aind->end() == NULL
4805 && aind->start()->is_constant()
4806 && Unary_expression::base_is_static_initializer(aind->array()));
4807
4808 // The address of a global variable can be a static initializer.
4809 Var_expression* ve = expr->var_expression();
4810 if (ve != NULL)
4811 {
4812 Named_object* no = ve->named_object();
4813 return no->is_variable() && no->var_value()->is_global();
4814 }
4815
4816 // The address of a composite literal can be used as a static
4817 // initializer if the composite literal is itself usable as a
4818 // static initializer.
4819 if (expr->is_composite_literal() && expr->is_static_initializer())
4820 return true;
4821
4822 // The address of a string constant can be used as a static
4823 // initializer. This can not be written in Go itself but this is
4824 // used when building a type descriptor.
4825 if (expr->string_expression() != NULL)
4826 return true;
4827
4828 return false;
4829 }
4830
4831 // Return whether this dereference expression requires an explicit nil
4832 // check. If we are dereferencing the pointer to a large struct
4833 // (greater than the specified size threshold), we need to check for
4834 // nil. We don't bother to check for small structs because we expect
4835 // the system to crash on a nil pointer dereference. However, if we
4836 // know the address of this expression is being taken, we must always
4837 // check for nil.
4838 Unary_expression::Nil_check_classification
4839 Unary_expression::requires_nil_check(Gogo* gogo)
4840 {
4841 go_assert(this->op_ == OPERATOR_MULT);
4842 go_assert(this->expr_->type()->points_to() != NULL);
4843
4844 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4845 return NIL_CHECK_NEEDED;
4846 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4847 return NIL_CHECK_NOT_NEEDED;
4848
4849 Type* ptype = this->expr_->type()->points_to();
4850 int64_t type_size = -1;
4851 if (!ptype->is_void_type())
4852 {
4853 bool ok = ptype->backend_type_size(gogo, &type_size);
4854 if (!ok)
4855 return NIL_CHECK_ERROR_ENCOUNTERED;
4856 }
4857
4858 int64_t size_cutoff = gogo->nil_check_size_threshold();
4859 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4860 this->issue_nil_check_ = NIL_CHECK_NEEDED;
4861 else
4862 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4863 return this->issue_nil_check_;
4864 }
4865
4866 // Apply unary opcode OP to UNC, setting NC. Return true if this
4867 // could be done, false if not. On overflow, issues an error and sets
4868 // *ISSUED_ERROR.
4869
4870 bool
4871 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4872 Location location, Numeric_constant* nc,
4873 bool* issued_error)
4874 {
4875 *issued_error = false;
4876 switch (op)
4877 {
4878 case OPERATOR_PLUS:
4879 *nc = *unc;
4880 return true;
4881
4882 case OPERATOR_MINUS:
4883 if (unc->is_int() || unc->is_rune())
4884 break;
4885 else if (unc->is_float())
4886 {
4887 mpfr_t uval;
4888 unc->get_float(&uval);
4889 mpfr_t val;
4890 mpfr_init(val);
4891 mpfr_neg(val, uval, MPFR_RNDN);
4892 nc->set_float(unc->type(), val);
4893 mpfr_clear(uval);
4894 mpfr_clear(val);
4895 return true;
4896 }
4897 else if (unc->is_complex())
4898 {
4899 mpc_t uval;
4900 unc->get_complex(&uval);
4901 mpc_t val;
4902 mpc_init2(val, mpc_precision);
4903 mpc_neg(val, uval, MPC_RNDNN);
4904 nc->set_complex(unc->type(), val);
4905 mpc_clear(uval);
4906 mpc_clear(val);
4907 return true;
4908 }
4909 else
4910 go_unreachable();
4911
4912 case OPERATOR_XOR:
4913 break;
4914
4915 case OPERATOR_NOT:
4916 case OPERATOR_AND:
4917 case OPERATOR_MULT:
4918 return false;
4919
4920 default:
4921 go_unreachable();
4922 }
4923
4924 if (!unc->is_int() && !unc->is_rune())
4925 return false;
4926
4927 mpz_t uval;
4928 if (unc->is_rune())
4929 unc->get_rune(&uval);
4930 else
4931 unc->get_int(&uval);
4932 mpz_t val;
4933 mpz_init(val);
4934
4935 switch (op)
4936 {
4937 case OPERATOR_MINUS:
4938 mpz_neg(val, uval);
4939 break;
4940
4941 case OPERATOR_NOT:
4942 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4943 break;
4944
4945 case OPERATOR_XOR:
4946 {
4947 Type* utype = unc->type();
4948 if (utype->integer_type() == NULL
4949 || utype->integer_type()->is_abstract())
4950 mpz_com(val, uval);
4951 else
4952 {
4953 // The number of HOST_WIDE_INTs that it takes to represent
4954 // UVAL.
4955 size_t count = ((mpz_sizeinbase(uval, 2)
4956 + HOST_BITS_PER_WIDE_INT
4957 - 1)
4958 / HOST_BITS_PER_WIDE_INT);
4959
4960 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4961 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4962
4963 size_t obits = utype->integer_type()->bits();
4964
4965 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4966 {
4967 mpz_t adj;
4968 mpz_init_set_ui(adj, 1);
4969 mpz_mul_2exp(adj, adj, obits);
4970 mpz_add(uval, uval, adj);
4971 mpz_clear(adj);
4972 }
4973
4974 size_t ecount;
4975 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4976 go_assert(ecount <= count);
4977
4978 // Trim down to the number of words required by the type.
4979 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4980 / HOST_BITS_PER_WIDE_INT);
4981 go_assert(ocount <= count);
4982
4983 for (size_t i = 0; i < ocount; ++i)
4984 phwi[i] = ~phwi[i];
4985
4986 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4987 if (clearbits != 0)
4988 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4989 >> clearbits);
4990
4991 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4992
4993 if (!utype->integer_type()->is_unsigned()
4994 && mpz_tstbit(val, obits - 1))
4995 {
4996 mpz_t adj;
4997 mpz_init_set_ui(adj, 1);
4998 mpz_mul_2exp(adj, adj, obits);
4999 mpz_sub(val, val, adj);
5000 mpz_clear(adj);
5001 }
5002
5003 delete[] phwi;
5004 }
5005 }
5006 break;
5007
5008 default:
5009 go_unreachable();
5010 }
5011
5012 if (unc->is_rune())
5013 nc->set_rune(NULL, val);
5014 else
5015 nc->set_int(NULL, val);
5016
5017 mpz_clear(uval);
5018 mpz_clear(val);
5019
5020 if (!nc->set_type(unc->type(), true, location))
5021 {
5022 *issued_error = true;
5023 return false;
5024 }
5025 return true;
5026 }
5027
5028 // Return the integral constant value of a unary expression, if it has one.
5029
5030 bool
5031 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5032 {
5033 Numeric_constant unc;
5034 if (!this->expr_->numeric_constant_value(&unc))
5035 return false;
5036 bool issued_error;
5037 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
5038 nc, &issued_error);
5039 }
5040
5041 // Return the boolean constant value of a unary expression, if it has one.
5042
5043 bool
5044 Unary_expression::do_boolean_constant_value(bool* val) const
5045 {
5046 if (this->op_ == OPERATOR_NOT
5047 && this->expr_->boolean_constant_value(val))
5048 {
5049 *val = !*val;
5050 return true;
5051 }
5052 return false;
5053 }
5054
5055 // Return the type of a unary expression.
5056
5057 Type*
5058 Unary_expression::do_type()
5059 {
5060 switch (this->op_)
5061 {
5062 case OPERATOR_PLUS:
5063 case OPERATOR_MINUS:
5064 case OPERATOR_NOT:
5065 case OPERATOR_XOR:
5066 return this->expr_->type();
5067
5068 case OPERATOR_AND:
5069 return Type::make_pointer_type(this->expr_->type());
5070
5071 case OPERATOR_MULT:
5072 {
5073 Type* subtype = this->expr_->type();
5074 Type* points_to = subtype->points_to();
5075 if (points_to == NULL)
5076 return Type::make_error_type();
5077 return points_to;
5078 }
5079
5080 default:
5081 go_unreachable();
5082 }
5083 }
5084
5085 // Determine abstract types for a unary expression.
5086
5087 void
5088 Unary_expression::do_determine_type(const Type_context* context)
5089 {
5090 switch (this->op_)
5091 {
5092 case OPERATOR_PLUS:
5093 case OPERATOR_MINUS:
5094 case OPERATOR_NOT:
5095 case OPERATOR_XOR:
5096 this->expr_->determine_type(context);
5097 break;
5098
5099 case OPERATOR_AND:
5100 // Taking the address of something.
5101 {
5102 Type* subtype = (context->type == NULL
5103 ? NULL
5104 : context->type->points_to());
5105 Type_context subcontext(subtype, false);
5106 this->expr_->determine_type(&subcontext);
5107 }
5108 break;
5109
5110 case OPERATOR_MULT:
5111 // Indirecting through a pointer.
5112 {
5113 Type* subtype = (context->type == NULL
5114 ? NULL
5115 : Type::make_pointer_type(context->type));
5116 Type_context subcontext(subtype, false);
5117 this->expr_->determine_type(&subcontext);
5118 }
5119 break;
5120
5121 default:
5122 go_unreachable();
5123 }
5124 }
5125
5126 // Check types for a unary expression.
5127
5128 void
5129 Unary_expression::do_check_types(Gogo*)
5130 {
5131 Type* type = this->expr_->type();
5132 if (type->is_error())
5133 {
5134 this->set_is_error();
5135 return;
5136 }
5137
5138 switch (this->op_)
5139 {
5140 case OPERATOR_PLUS:
5141 case OPERATOR_MINUS:
5142 if (type->integer_type() == NULL
5143 && type->float_type() == NULL
5144 && type->complex_type() == NULL)
5145 this->report_error(_("expected numeric type"));
5146 break;
5147
5148 case OPERATOR_NOT:
5149 if (!type->is_boolean_type())
5150 this->report_error(_("expected boolean type"));
5151 break;
5152
5153 case OPERATOR_XOR:
5154 if (type->integer_type() == NULL)
5155 this->report_error(_("expected integer"));
5156 break;
5157
5158 case OPERATOR_AND:
5159 if (!this->expr_->is_addressable())
5160 {
5161 if (!this->create_temp_)
5162 {
5163 go_error_at(this->location(), "invalid operand for unary %<&%>");
5164 this->set_is_error();
5165 }
5166 }
5167 else
5168 this->expr_->issue_nil_check();
5169 break;
5170
5171 case OPERATOR_MULT:
5172 // Indirecting through a pointer.
5173 if (type->points_to() == NULL)
5174 this->report_error(_("expected pointer"));
5175 if (type->points_to()->is_error())
5176 this->set_is_error();
5177 break;
5178
5179 default:
5180 go_unreachable();
5181 }
5182 }
5183
5184 // Get the backend representation for a unary expression.
5185
5186 Bexpression*
5187 Unary_expression::do_get_backend(Translate_context* context)
5188 {
5189 Gogo* gogo = context->gogo();
5190 Location loc = this->location();
5191
5192 // Taking the address of a set-and-use-temporary expression requires
5193 // setting the temporary and then taking the address.
5194 if (this->op_ == OPERATOR_AND)
5195 {
5196 Set_and_use_temporary_expression* sut =
5197 this->expr_->set_and_use_temporary_expression();
5198 if (sut != NULL)
5199 {
5200 Temporary_statement* temp = sut->temporary();
5201 Bvariable* bvar = temp->get_backend_variable(context);
5202 Bexpression* bvar_expr =
5203 gogo->backend()->var_expression(bvar, loc);
5204 Bexpression* bval = sut->expression()->get_backend(context);
5205
5206 Named_object* fn = context->function();
5207 go_assert(fn != NULL);
5208 Bfunction* bfn =
5209 fn->func_value()->get_or_make_decl(gogo, fn);
5210 Bstatement* bassign =
5211 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5212 Bexpression* bvar_addr =
5213 gogo->backend()->address_expression(bvar_expr, loc);
5214 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5215 }
5216 }
5217
5218 Bexpression* ret;
5219 Bexpression* bexpr = this->expr_->get_backend(context);
5220 Btype* btype = this->expr_->type()->get_backend(gogo);
5221 switch (this->op_)
5222 {
5223 case OPERATOR_PLUS:
5224 ret = bexpr;
5225 break;
5226
5227 case OPERATOR_MINUS:
5228 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5229 ret = gogo->backend()->convert_expression(btype, ret, loc);
5230 break;
5231
5232 case OPERATOR_NOT:
5233 case OPERATOR_XOR:
5234 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5235 break;
5236
5237 case OPERATOR_AND:
5238 if (!this->create_temp_)
5239 {
5240 // We should not see a non-constant constructor here; cases
5241 // where we would see one should have been moved onto the
5242 // heap at parse time. Taking the address of a nonconstant
5243 // constructor will not do what the programmer expects.
5244
5245 go_assert(!this->expr_->is_composite_literal()
5246 || this->expr_->is_static_initializer());
5247 if (this->expr_->classification() == EXPRESSION_UNARY)
5248 {
5249 Unary_expression* ue =
5250 static_cast<Unary_expression*>(this->expr_);
5251 go_assert(ue->op() != OPERATOR_AND);
5252 }
5253 }
5254
5255 if (this->is_gc_root_ || this->is_slice_init_)
5256 {
5257 std::string var_name;
5258 bool copy_to_heap = false;
5259 if (this->is_gc_root_)
5260 {
5261 // Build a decl for a GC root variable. GC roots are mutable, so
5262 // they cannot be represented as an immutable_struct in the
5263 // backend.
5264 var_name = gogo->gc_root_name();
5265 }
5266 else
5267 {
5268 // Build a decl for a slice value initializer. An immutable slice
5269 // value initializer may have to be copied to the heap if it
5270 // contains pointers in a non-constant context.
5271 var_name = gogo->initializer_name();
5272
5273 Array_type* at = this->expr_->type()->array_type();
5274 go_assert(at != NULL);
5275
5276 // If we are not copying the value to the heap, we will only
5277 // initialize the value once, so we can use this directly
5278 // rather than copying it. In that case we can't make it
5279 // read-only, because the program is permitted to change it.
5280 copy_to_heap = (context->function() != NULL
5281 || context->is_const());
5282 }
5283 Bvariable* implicit =
5284 gogo->backend()->implicit_variable(var_name, "", btype, true,
5285 copy_to_heap, false, 0);
5286 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5287 true, copy_to_heap, false,
5288 bexpr);
5289 bexpr = gogo->backend()->var_expression(implicit, loc);
5290
5291 // If we are not copying a slice initializer to the heap,
5292 // then it can be changed by the program, so if it can
5293 // contain pointers we must register it as a GC root.
5294 if (this->is_slice_init_
5295 && !copy_to_heap
5296 && this->expr_->type()->has_pointer())
5297 {
5298 Bexpression* root =
5299 gogo->backend()->var_expression(implicit, loc);
5300 root = gogo->backend()->address_expression(root, loc);
5301 Type* type = Type::make_pointer_type(this->expr_->type());
5302 gogo->add_gc_root(Expression::make_backend(root, type, loc));
5303 }
5304 }
5305 else if ((this->expr_->is_composite_literal()
5306 || this->expr_->string_expression() != NULL)
5307 && this->expr_->is_static_initializer())
5308 {
5309 std::string var_name(gogo->initializer_name());
5310 Bvariable* decl =
5311 gogo->backend()->immutable_struct(var_name, "", true, false,
5312 btype, loc);
5313 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
5314 false, btype, loc, bexpr);
5315 bexpr = gogo->backend()->var_expression(decl, loc);
5316 }
5317 else if (this->expr_->is_constant())
5318 {
5319 std::string var_name(gogo->initializer_name());
5320 Bvariable* decl =
5321 gogo->backend()->implicit_variable(var_name, "", btype,
5322 true, true, false, 0);
5323 gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5324 true, true, false,
5325 bexpr);
5326 bexpr = gogo->backend()->var_expression(decl, loc);
5327 }
5328
5329 go_assert(!this->create_temp_ || this->expr_->is_variable());
5330 ret = gogo->backend()->address_expression(bexpr, loc);
5331 break;
5332
5333 case OPERATOR_MULT:
5334 {
5335 go_assert(this->expr_->type()->points_to() != NULL);
5336
5337 Type* ptype = this->expr_->type()->points_to();
5338 Btype* pbtype = ptype->get_backend(gogo);
5339 switch (this->requires_nil_check(gogo))
5340 {
5341 case NIL_CHECK_NOT_NEEDED:
5342 break;
5343 case NIL_CHECK_ERROR_ENCOUNTERED:
5344 {
5345 go_assert(saw_errors());
5346 return gogo->backend()->error_expression();
5347 }
5348 case NIL_CHECK_NEEDED:
5349 {
5350 go_assert(this->expr_->is_variable());
5351
5352 // If we're nil-checking the result of a set-and-use-temporary
5353 // expression, then pick out the target temp and use that
5354 // for the final result of the conditional.
5355 Bexpression* tbexpr = bexpr;
5356 Bexpression* ubexpr = bexpr;
5357 Set_and_use_temporary_expression* sut =
5358 this->expr_->set_and_use_temporary_expression();
5359 if (sut != NULL) {
5360 Temporary_statement* temp = sut->temporary();
5361 Bvariable* bvar = temp->get_backend_variable(context);
5362 ubexpr = gogo->backend()->var_expression(bvar, loc);
5363 }
5364 Bexpression* nil =
5365 Expression::make_nil(loc)->get_backend(context);
5366 Bexpression* compare =
5367 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5368 nil, loc);
5369 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
5370 loc, 0);
5371 Bexpression* bcrash = crash->get_backend(context);
5372 Bfunction* bfn = context->function()->func_value()->get_decl();
5373 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5374 compare,
5375 bcrash, ubexpr,
5376 loc);
5377 break;
5378 }
5379 case NIL_CHECK_DEFAULT:
5380 go_unreachable();
5381 }
5382 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
5383 }
5384 break;
5385
5386 default:
5387 go_unreachable();
5388 }
5389
5390 return ret;
5391 }
5392
5393 // Export a unary expression.
5394
5395 void
5396 Unary_expression::do_export(Export_function_body* efb) const
5397 {
5398 switch (this->op_)
5399 {
5400 case OPERATOR_PLUS:
5401 efb->write_c_string("+");
5402 break;
5403 case OPERATOR_MINUS:
5404 efb->write_c_string("-");
5405 break;
5406 case OPERATOR_NOT:
5407 efb->write_c_string("!");
5408 break;
5409 case OPERATOR_XOR:
5410 efb->write_c_string("^");
5411 break;
5412 case OPERATOR_AND:
5413 efb->write_c_string("&");
5414 break;
5415 case OPERATOR_MULT:
5416 efb->write_c_string("*");
5417 break;
5418 default:
5419 go_unreachable();
5420 }
5421 this->expr_->export_expression(efb);
5422 }
5423
5424 // Import a unary expression.
5425
5426 Expression*
5427 Unary_expression::do_import(Import_expression* imp, Location loc)
5428 {
5429 Operator op;
5430 switch (imp->get_char())
5431 {
5432 case '+':
5433 op = OPERATOR_PLUS;
5434 break;
5435 case '-':
5436 op = OPERATOR_MINUS;
5437 break;
5438 case '!':
5439 op = OPERATOR_NOT;
5440 break;
5441 case '^':
5442 op = OPERATOR_XOR;
5443 break;
5444 case '&':
5445 op = OPERATOR_AND;
5446 break;
5447 case '*':
5448 op = OPERATOR_MULT;
5449 break;
5450 default:
5451 go_unreachable();
5452 }
5453 if (imp->version() < EXPORT_FORMAT_V3)
5454 imp->require_c_string(" ");
5455 Expression* expr = Expression::import_expression(imp, loc);
5456 return Expression::make_unary(op, expr, loc);
5457 }
5458
5459 // Dump ast representation of an unary expression.
5460
5461 void
5462 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5463 {
5464 ast_dump_context->dump_operator(this->op_);
5465 ast_dump_context->ostream() << "(";
5466 ast_dump_context->dump_expression(this->expr_);
5467 ast_dump_context->ostream() << ") ";
5468 }
5469
5470 // Make a unary expression.
5471
5472 Expression*
5473 Expression::make_unary(Operator op, Expression* expr, Location location)
5474 {
5475 return new Unary_expression(op, expr, location);
5476 }
5477
5478 Expression*
5479 Expression::make_dereference(Expression* ptr,
5480 Nil_check_classification docheck,
5481 Location location)
5482 {
5483 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5484 if (docheck == NIL_CHECK_NEEDED)
5485 deref->unary_expression()->set_requires_nil_check(true);
5486 else if (docheck == NIL_CHECK_NOT_NEEDED)
5487 deref->unary_expression()->set_requires_nil_check(false);
5488 return deref;
5489 }
5490
5491 // If this is an indirection through a pointer, return the expression
5492 // being pointed through. Otherwise return this.
5493
5494 Expression*
5495 Expression::deref()
5496 {
5497 if (this->classification_ == EXPRESSION_UNARY)
5498 {
5499 Unary_expression* ue = static_cast<Unary_expression*>(this);
5500 if (ue->op() == OPERATOR_MULT)
5501 return ue->operand();
5502 }
5503 return this;
5504 }
5505
5506 // Class Binary_expression.
5507
5508 // Traversal.
5509
5510 int
5511 Binary_expression::do_traverse(Traverse* traverse)
5512 {
5513 int t = Expression::traverse(&this->left_, traverse);
5514 if (t == TRAVERSE_EXIT)
5515 return TRAVERSE_EXIT;
5516 return Expression::traverse(&this->right_, traverse);
5517 }
5518
5519 // Return whether this expression may be used as a static initializer.
5520
5521 bool
5522 Binary_expression::do_is_static_initializer() const
5523 {
5524 if (!this->left_->is_static_initializer()
5525 || !this->right_->is_static_initializer())
5526 return false;
5527
5528 // Addresses can be static initializers, but we can't implement
5529 // arbitray binary expressions of them.
5530 Unary_expression* lu = this->left_->unary_expression();
5531 Unary_expression* ru = this->right_->unary_expression();
5532 if (lu != NULL && lu->op() == OPERATOR_AND)
5533 {
5534 if (ru != NULL && ru->op() == OPERATOR_AND)
5535 return this->op_ == OPERATOR_MINUS;
5536 else
5537 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5538 }
5539 else if (ru != NULL && ru->op() == OPERATOR_AND)
5540 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5541
5542 // Other cases should resolve in the backend.
5543 return true;
5544 }
5545
5546 // Return the type to use for a binary operation on operands of
5547 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
5548 // such may be NULL or abstract.
5549
5550 bool
5551 Binary_expression::operation_type(Operator op, Type* left_type,
5552 Type* right_type, Type** result_type)
5553 {
5554 if (left_type != right_type
5555 && !left_type->is_abstract()
5556 && !right_type->is_abstract()
5557 && left_type->base() != right_type->base()
5558 && op != OPERATOR_LSHIFT
5559 && op != OPERATOR_RSHIFT)
5560 {
5561 // May be a type error--let it be diagnosed elsewhere.
5562 return false;
5563 }
5564
5565 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5566 {
5567 if (left_type->integer_type() != NULL)
5568 *result_type = left_type;
5569 else
5570 *result_type = Type::make_abstract_integer_type();
5571 }
5572 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
5573 *result_type = left_type;
5574 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
5575 *result_type = right_type;
5576 else if (!left_type->is_abstract())
5577 *result_type = left_type;
5578 else if (!right_type->is_abstract())
5579 *result_type = right_type;
5580 else if (left_type->complex_type() != NULL)
5581 *result_type = left_type;
5582 else if (right_type->complex_type() != NULL)
5583 *result_type = right_type;
5584 else if (left_type->float_type() != NULL)
5585 *result_type = left_type;
5586 else if (right_type->float_type() != NULL)
5587 *result_type = right_type;
5588 else if (left_type->integer_type() != NULL
5589 && left_type->integer_type()->is_rune())
5590 *result_type = left_type;
5591 else if (right_type->integer_type() != NULL
5592 && right_type->integer_type()->is_rune())
5593 *result_type = right_type;
5594 else
5595 *result_type = left_type;
5596
5597 return true;
5598 }
5599
5600 // Convert an integer comparison code and an operator to a boolean
5601 // value.
5602
5603 bool
5604 Binary_expression::cmp_to_bool(Operator op, int cmp)
5605 {
5606 switch (op)
5607 {
5608 case OPERATOR_EQEQ:
5609 return cmp == 0;
5610 break;
5611 case OPERATOR_NOTEQ:
5612 return cmp != 0;
5613 break;
5614 case OPERATOR_LT:
5615 return cmp < 0;
5616 break;
5617 case OPERATOR_LE:
5618 return cmp <= 0;
5619 case OPERATOR_GT:
5620 return cmp > 0;
5621 case OPERATOR_GE:
5622 return cmp >= 0;
5623 default:
5624 go_unreachable();
5625 }
5626 }
5627
5628 // Compare constants according to OP.
5629
5630 bool
5631 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
5632 Numeric_constant* right_nc,
5633 Location location, bool* result)
5634 {
5635 Type* left_type = left_nc->type();
5636 Type* right_type = right_nc->type();
5637
5638 Type* type;
5639 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5640 return false;
5641
5642 // When comparing an untyped operand to a typed operand, we are
5643 // effectively coercing the untyped operand to the other operand's
5644 // type, so make sure that is valid.
5645 if (!left_nc->set_type(type, true, location)
5646 || !right_nc->set_type(type, true, location))
5647 return false;
5648
5649 bool ret;
5650 int cmp;
5651 if (type->complex_type() != NULL)
5652 {
5653 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
5654 return false;
5655 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
5656 }
5657 else if (type->float_type() != NULL)
5658 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5659 else
5660 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5661
5662 if (ret)
5663 *result = Binary_expression::cmp_to_bool(op, cmp);
5664
5665 return ret;
5666 }
5667
5668 // Compare integer constants.
5669
5670 bool
5671 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5672 const Numeric_constant* right_nc,
5673 int* cmp)
5674 {
5675 mpz_t left_val;
5676 if (!left_nc->to_int(&left_val))
5677 return false;
5678 mpz_t right_val;
5679 if (!right_nc->to_int(&right_val))
5680 {
5681 mpz_clear(left_val);
5682 return false;
5683 }
5684
5685 *cmp = mpz_cmp(left_val, right_val);
5686
5687 mpz_clear(left_val);
5688 mpz_clear(right_val);
5689
5690 return true;
5691 }
5692
5693 // Compare floating point constants.
5694
5695 bool
5696 Binary_expression::compare_float(const Numeric_constant* left_nc,
5697 const Numeric_constant* right_nc,
5698 int* cmp)
5699 {
5700 mpfr_t left_val;
5701 if (!left_nc->to_float(&left_val))
5702 return false;
5703 mpfr_t right_val;
5704 if (!right_nc->to_float(&right_val))
5705 {
5706 mpfr_clear(left_val);
5707 return false;
5708 }
5709
5710 // We already coerced both operands to the same type. If that type
5711 // is not an abstract type, we need to round the values accordingly.
5712 Type* type = left_nc->type();
5713 if (!type->is_abstract() && type->float_type() != NULL)
5714 {
5715 int bits = type->float_type()->bits();
5716 mpfr_prec_round(left_val, bits, MPFR_RNDN);
5717 mpfr_prec_round(right_val, bits, MPFR_RNDN);
5718 }
5719
5720 *cmp = mpfr_cmp(left_val, right_val);
5721
5722 mpfr_clear(left_val);
5723 mpfr_clear(right_val);
5724
5725 return true;
5726 }
5727
5728 // Compare complex constants. Complex numbers may only be compared
5729 // for equality.
5730
5731 bool
5732 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5733 const Numeric_constant* right_nc,
5734 int* cmp)
5735 {
5736 mpc_t left_val;
5737 if (!left_nc->to_complex(&left_val))
5738 return false;
5739 mpc_t right_val;
5740 if (!right_nc->to_complex(&right_val))
5741 {
5742 mpc_clear(left_val);
5743 return false;
5744 }
5745
5746 // We already coerced both operands to the same type. If that type
5747 // is not an abstract type, we need to round the values accordingly.
5748 Type* type = left_nc->type();
5749 if (!type->is_abstract() && type->complex_type() != NULL)
5750 {
5751 int bits = type->complex_type()->bits();
5752 mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
5753 mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
5754 mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
5755 mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
5756 }
5757
5758 *cmp = mpc_cmp(left_val, right_val) != 0;
5759
5760 mpc_clear(left_val);
5761 mpc_clear(right_val);
5762
5763 return true;
5764 }
5765
5766 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
5767 // true if this could be done, false if not. Issue errors at LOCATION
5768 // as appropriate, and sets *ISSUED_ERROR if it did.
5769
5770 bool
5771 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5772 Numeric_constant* right_nc,
5773 Location location, Numeric_constant* nc,
5774 bool* issued_error)
5775 {
5776 *issued_error = false;
5777 switch (op)
5778 {
5779 case OPERATOR_OROR:
5780 case OPERATOR_ANDAND:
5781 case OPERATOR_EQEQ:
5782 case OPERATOR_NOTEQ:
5783 case OPERATOR_LT:
5784 case OPERATOR_LE:
5785 case OPERATOR_GT:
5786 case OPERATOR_GE:
5787 // These return boolean values, not numeric.
5788 return false;
5789 default:
5790 break;
5791 }
5792
5793 Type* left_type = left_nc->type();
5794 Type* right_type = right_nc->type();
5795
5796 Type* type;
5797 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5798 return false;
5799
5800 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5801
5802 // When combining an untyped operand with a typed operand, we are
5803 // effectively coercing the untyped operand to the other operand's
5804 // type, so make sure that is valid.
5805 if (!left_nc->set_type(type, true, location))
5806 return false;
5807 if (!is_shift && !right_nc->set_type(type, true, location))
5808 return false;
5809 if (is_shift
5810 && ((left_type->integer_type() == NULL
5811 && !left_type->is_abstract())
5812 || (right_type->integer_type() == NULL
5813 && !right_type->is_abstract())))
5814 return false;
5815
5816 bool r;
5817 if (type->complex_type() != NULL)
5818 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5819 else if (type->float_type() != NULL)
5820 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5821 else
5822 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5823
5824 if (r)
5825 {
5826 r = nc->set_type(type, true, location);
5827 if (!r)
5828 *issued_error = true;
5829 }
5830
5831 return r;
5832 }
5833
5834 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5835 // integer operations. Return true if this could be done, false if
5836 // not.
5837
5838 bool
5839 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5840 const Numeric_constant* right_nc,
5841 Location location, Numeric_constant* nc)
5842 {
5843 mpz_t left_val;
5844 if (!left_nc->to_int(&left_val))
5845 return false;
5846 mpz_t right_val;
5847 if (!right_nc->to_int(&right_val))
5848 {
5849 mpz_clear(left_val);
5850 return false;
5851 }
5852
5853 mpz_t val;
5854 mpz_init(val);
5855
5856 switch (op)
5857 {
5858 case OPERATOR_PLUS:
5859 mpz_add(val, left_val, right_val);
5860 if (mpz_sizeinbase(val, 2) > 0x100000)
5861 {
5862 go_error_at(location, "constant addition overflow");
5863 nc->set_invalid();
5864 mpz_set_ui(val, 1);
5865 }
5866 break;
5867 case OPERATOR_MINUS:
5868 mpz_sub(val, left_val, right_val);
5869 if (mpz_sizeinbase(val, 2) > 0x100000)
5870 {
5871 go_error_at(location, "constant subtraction overflow");
5872 nc->set_invalid();
5873 mpz_set_ui(val, 1);
5874 }
5875 break;
5876 case OPERATOR_OR:
5877 mpz_ior(val, left_val, right_val);
5878 break;
5879 case OPERATOR_XOR:
5880 mpz_xor(val, left_val, right_val);
5881 break;
5882 case OPERATOR_MULT:
5883 mpz_mul(val, left_val, right_val);
5884 if (mpz_sizeinbase(val, 2) > 0x100000)
5885 {
5886 go_error_at(location, "constant multiplication overflow");
5887 nc->set_invalid();
5888 mpz_set_ui(val, 1);
5889 }
5890 break;
5891 case OPERATOR_DIV:
5892 if (mpz_sgn(right_val) != 0)
5893 mpz_tdiv_q(val, left_val, right_val);
5894 else
5895 {
5896 go_error_at(location, "division by zero");
5897 nc->set_invalid();
5898 mpz_set_ui(val, 0);
5899 }
5900 break;
5901 case OPERATOR_MOD:
5902 if (mpz_sgn(right_val) != 0)
5903 mpz_tdiv_r(val, left_val, right_val);
5904 else
5905 {
5906 go_error_at(location, "division by zero");
5907 nc->set_invalid();
5908 mpz_set_ui(val, 0);
5909 }
5910 break;
5911 case OPERATOR_LSHIFT:
5912 {
5913 unsigned long shift = mpz_get_ui(right_val);
5914 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5915 mpz_mul_2exp(val, left_val, shift);
5916 else
5917 {
5918 go_error_at(location, "shift count overflow");
5919 nc->set_invalid();
5920 mpz_set_ui(val, 1);
5921 }
5922 break;
5923 }
5924 break;
5925 case OPERATOR_RSHIFT:
5926 {
5927 unsigned long shift = mpz_get_ui(right_val);
5928 if (mpz_cmp_ui(right_val, shift) != 0)
5929 {
5930 go_error_at(location, "shift count overflow");
5931 nc->set_invalid();
5932 mpz_set_ui(val, 1);
5933 }
5934 else
5935 {
5936 if (mpz_cmp_ui(left_val, 0) >= 0)
5937 mpz_tdiv_q_2exp(val, left_val, shift);
5938 else
5939 mpz_fdiv_q_2exp(val, left_val, shift);
5940 }
5941 break;
5942 }
5943 break;
5944 case OPERATOR_AND:
5945 mpz_and(val, left_val, right_val);
5946 break;
5947 case OPERATOR_BITCLEAR:
5948 {
5949 mpz_t tval;
5950 mpz_init(tval);
5951 mpz_com(tval, right_val);
5952 mpz_and(val, left_val, tval);
5953 mpz_clear(tval);
5954 }
5955 break;
5956 default:
5957 go_unreachable();
5958 }
5959
5960 mpz_clear(left_val);
5961 mpz_clear(right_val);
5962
5963 if (left_nc->is_rune()
5964 || (op != OPERATOR_LSHIFT
5965 && op != OPERATOR_RSHIFT
5966 && right_nc->is_rune()))
5967 nc->set_rune(NULL, val);
5968 else
5969 nc->set_int(NULL, val);
5970
5971 mpz_clear(val);
5972
5973 return true;
5974 }
5975
5976 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5977 // floating point operations. Return true if this could be done,
5978 // false if not.
5979
5980 bool
5981 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5982 const Numeric_constant* right_nc,
5983 Location location, Numeric_constant* nc)
5984 {
5985 mpfr_t left_val;
5986 if (!left_nc->to_float(&left_val))
5987 return false;
5988 mpfr_t right_val;
5989 if (!right_nc->to_float(&right_val))
5990 {
5991 mpfr_clear(left_val);
5992 return false;
5993 }
5994
5995 mpfr_t val;
5996 mpfr_init(val);
5997
5998 bool ret = true;
5999 switch (op)
6000 {
6001 case OPERATOR_PLUS:
6002 mpfr_add(val, left_val, right_val, MPFR_RNDN);
6003 break;
6004 case OPERATOR_MINUS:
6005 mpfr_sub(val, left_val, right_val, MPFR_RNDN);
6006 break;
6007 case OPERATOR_OR:
6008 case OPERATOR_XOR:
6009 case OPERATOR_AND:
6010 case OPERATOR_BITCLEAR:
6011 case OPERATOR_MOD:
6012 case OPERATOR_LSHIFT:
6013 case OPERATOR_RSHIFT:
6014 mpfr_set_ui(val, 0, MPFR_RNDN);
6015 ret = false;
6016 break;
6017 case OPERATOR_MULT:
6018 mpfr_mul(val, left_val, right_val, MPFR_RNDN);
6019 break;
6020 case OPERATOR_DIV:
6021 if (!mpfr_zero_p(right_val))
6022 mpfr_div(val, left_val, right_val, MPFR_RNDN);
6023 else
6024 {
6025 go_error_at(location, "division by zero");
6026 nc->set_invalid();
6027 mpfr_set_ui(val, 0, MPFR_RNDN);
6028 }
6029 break;
6030 default:
6031 go_unreachable();
6032 }
6033
6034 mpfr_clear(left_val);
6035 mpfr_clear(right_val);
6036
6037 nc->set_float(NULL, val);
6038 mpfr_clear(val);
6039
6040 return ret;
6041 }
6042
6043 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6044 // complex operations. Return true if this could be done, false if
6045 // not.
6046
6047 bool
6048 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
6049 const Numeric_constant* right_nc,
6050 Location location, Numeric_constant* nc)
6051 {
6052 mpc_t left_val;
6053 if (!left_nc->to_complex(&left_val))
6054 return false;
6055 mpc_t right_val;
6056 if (!right_nc->to_complex(&right_val))
6057 {
6058 mpc_clear(left_val);
6059 return false;
6060 }
6061
6062 mpc_t val;
6063 mpc_init2(val, mpc_precision);
6064
6065 bool ret = true;
6066 switch (op)
6067 {
6068 case OPERATOR_PLUS:
6069 mpc_add(val, left_val, right_val, MPC_RNDNN);
6070 break;
6071 case OPERATOR_MINUS:
6072 mpc_sub(val, left_val, right_val, MPC_RNDNN);
6073 break;
6074 case OPERATOR_OR:
6075 case OPERATOR_XOR:
6076 case OPERATOR_AND:
6077 case OPERATOR_BITCLEAR:
6078 case OPERATOR_MOD:
6079 case OPERATOR_LSHIFT:
6080 case OPERATOR_RSHIFT:
6081 mpc_set_ui(val, 0, MPC_RNDNN);
6082 ret = false;
6083 break;
6084 case OPERATOR_MULT:
6085 mpc_mul(val, left_val, right_val, MPC_RNDNN);
6086 break;
6087 case OPERATOR_DIV:
6088 if (mpc_cmp_si(right_val, 0) == 0)
6089 {
6090 go_error_at(location, "division by zero");
6091 nc->set_invalid();
6092 mpc_set_ui(val, 0, MPC_RNDNN);
6093 break;
6094 }
6095 mpc_div(val, left_val, right_val, MPC_RNDNN);
6096 break;
6097 default:
6098 go_unreachable();
6099 }
6100
6101 mpc_clear(left_val);
6102 mpc_clear(right_val);
6103
6104 nc->set_complex(NULL, val);
6105 mpc_clear(val);
6106
6107 return ret;
6108 }
6109
6110 // Lower a binary expression. We have to evaluate constant
6111 // expressions now, in order to implement Go's unlimited precision
6112 // constants.
6113
6114 Expression*
6115 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6116 Statement_inserter* inserter, int)
6117 {
6118 Location location = this->location();
6119 Operator op = this->op_;
6120 Expression* left = this->left_;
6121 Expression* right = this->right_;
6122
6123 const bool is_comparison = (op == OPERATOR_EQEQ
6124 || op == OPERATOR_NOTEQ
6125 || op == OPERATOR_LT
6126 || op == OPERATOR_LE
6127 || op == OPERATOR_GT
6128 || op == OPERATOR_GE);
6129
6130 // Numeric constant expressions.
6131 {
6132 Numeric_constant left_nc;
6133 Numeric_constant right_nc;
6134 if (left->numeric_constant_value(&left_nc)
6135 && right->numeric_constant_value(&right_nc))
6136 {
6137 if (is_comparison)
6138 {
6139 bool result;
6140 if (!Binary_expression::compare_constant(op, &left_nc,
6141 &right_nc, location,
6142 &result))
6143 return this;
6144 return Expression::make_boolean(result, location);
6145 }
6146 else
6147 {
6148 Numeric_constant nc;
6149 bool issued_error;
6150 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6151 location, &nc,
6152 &issued_error))
6153 {
6154 if (issued_error)
6155 return Expression::make_error(location);
6156 return this;
6157 }
6158 return nc.expression(location);
6159 }
6160 }
6161 }
6162
6163 // String constant expressions.
6164 //
6165 // Avoid constant folding here if the left and right types are incompatible
6166 // (leave the operation intact so that the type checker can complain about it
6167 // later on). If concatenating an abstract string with a named string type,
6168 // result type needs to be of the named type (see issue 31412).
6169 if (left->type()->is_string_type()
6170 && right->type()->is_string_type()
6171 && (left->type()->named_type() == NULL
6172 || right->type()->named_type() == NULL
6173 || left->type()->named_type() == right->type()->named_type()))
6174 {
6175 std::string left_string;
6176 std::string right_string;
6177 if (left->string_constant_value(&left_string)
6178 && right->string_constant_value(&right_string))
6179 {
6180 if (op == OPERATOR_PLUS)
6181 {
6182 Type* result_type = (left->type()->named_type() != NULL
6183 ? left->type()
6184 : right->type());
6185 delete left;
6186 delete right;
6187 return Expression::make_string_typed(left_string + right_string,
6188 result_type, location);
6189 }
6190 else if (is_comparison)
6191 {
6192 int cmp = left_string.compare(right_string);
6193 bool r = Binary_expression::cmp_to_bool(op, cmp);
6194 delete left;
6195 delete right;
6196 return Expression::make_boolean(r, location);
6197 }
6198 }
6199 }
6200
6201 // Lower struct, array, and some interface comparisons.
6202 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6203 {
6204 if (left->type()->struct_type() != NULL
6205 && right->type()->struct_type() != NULL)
6206 return this->lower_struct_comparison(gogo, inserter);
6207 else if (left->type()->array_type() != NULL
6208 && !left->type()->is_slice_type()
6209 && right->type()->array_type() != NULL
6210 && !right->type()->is_slice_type())
6211 return this->lower_array_comparison(gogo, inserter);
6212 else if ((left->type()->interface_type() != NULL
6213 && right->type()->interface_type() == NULL)
6214 || (left->type()->interface_type() == NULL
6215 && right->type()->interface_type() != NULL))
6216 return this->lower_interface_value_comparison(gogo, inserter);
6217 }
6218
6219 // Lower string concatenation to String_concat_expression, so that
6220 // we can group sequences of string additions.
6221 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6222 {
6223 Expression_list* exprs;
6224 String_concat_expression* left_sce =
6225 this->left_->string_concat_expression();
6226 if (left_sce != NULL)
6227 exprs = left_sce->exprs();
6228 else
6229 {
6230 exprs = new Expression_list();
6231 exprs->push_back(this->left_);
6232 }
6233
6234 String_concat_expression* right_sce =
6235 this->right_->string_concat_expression();
6236 if (right_sce != NULL)
6237 exprs->append(right_sce->exprs());
6238 else
6239 exprs->push_back(this->right_);
6240
6241 return Expression::make_string_concat(exprs);
6242 }
6243
6244 return this;
6245 }
6246
6247 // Lower a struct comparison.
6248
6249 Expression*
6250 Binary_expression::lower_struct_comparison(Gogo* gogo,
6251 Statement_inserter* inserter)
6252 {
6253 Struct_type* st = this->left_->type()->struct_type();
6254 Struct_type* st2 = this->right_->type()->struct_type();
6255 if (st2 == NULL)
6256 return this;
6257 if (st != st2
6258 && !Type::are_identical(st, st2,
6259 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6260 NULL))
6261 return this;
6262 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6263 this->right_->type(), NULL))
6264 return this;
6265
6266 // See if we can compare using memcmp. As a heuristic, we use
6267 // memcmp rather than field references and comparisons if there are
6268 // more than two fields.
6269 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6270 return this->lower_compare_to_memcmp(gogo, inserter);
6271
6272 Location loc = this->location();
6273
6274 Expression* left = this->left_;
6275 Temporary_statement* left_temp = NULL;
6276 if (left->var_expression() == NULL
6277 && left->temporary_reference_expression() == NULL)
6278 {
6279 left_temp = Statement::make_temporary(left->type(), NULL, loc);
6280 inserter->insert(left_temp);
6281 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6282 }
6283
6284 Expression* right = this->right_;
6285 Temporary_statement* right_temp = NULL;
6286 if (right->var_expression() == NULL
6287 && right->temporary_reference_expression() == NULL)
6288 {
6289 right_temp = Statement::make_temporary(right->type(), NULL, loc);
6290 inserter->insert(right_temp);
6291 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6292 }
6293
6294 Expression* ret = Expression::make_boolean(true, loc);
6295 const Struct_field_list* fields = st->fields();
6296 unsigned int field_index = 0;
6297 for (Struct_field_list::const_iterator pf = fields->begin();
6298 pf != fields->end();
6299 ++pf, ++field_index)
6300 {
6301 if (Gogo::is_sink_name(pf->field_name()))
6302 continue;
6303
6304 if (field_index > 0)
6305 {
6306 if (left_temp == NULL)
6307 left = left->copy();
6308 else
6309 left = Expression::make_temporary_reference(left_temp, loc);
6310 if (right_temp == NULL)
6311 right = right->copy();
6312 else
6313 right = Expression::make_temporary_reference(right_temp, loc);
6314 }
6315 Expression* f1 = Expression::make_field_reference(left, field_index,
6316 loc);
6317 Expression* f2 = Expression::make_field_reference(right, field_index,
6318 loc);
6319 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6320 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6321 }
6322
6323 if (this->op_ == OPERATOR_NOTEQ)
6324 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6325
6326 return ret;
6327 }
6328
6329 // Lower an array comparison.
6330
6331 Expression*
6332 Binary_expression::lower_array_comparison(Gogo* gogo,
6333 Statement_inserter* inserter)
6334 {
6335 Array_type* at = this->left_->type()->array_type();
6336 Array_type* at2 = this->right_->type()->array_type();
6337 if (at2 == NULL)
6338 return this;
6339 if (at != at2
6340 && !Type::are_identical(at, at2,
6341 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6342 NULL))
6343 return this;
6344 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6345 this->right_->type(), NULL))
6346 return this;
6347
6348 // Call memcmp directly if possible. This may let the middle-end
6349 // optimize the call.
6350 if (at->compare_is_identity(gogo))
6351 return this->lower_compare_to_memcmp(gogo, inserter);
6352
6353 // Call the array comparison function.
6354 Named_object* equal_fn =
6355 at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6356
6357 Location loc = this->location();
6358
6359 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6360
6361 Expression_list* args = new Expression_list();
6362 args->push_back(this->operand_address(inserter, this->left_));
6363 args->push_back(this->operand_address(inserter, this->right_));
6364
6365 Call_expression* ce = Expression::make_call(func, args, false, loc);
6366
6367 // Record that this is a call to a generated equality function. We
6368 // need to do this because a comparison returns an abstract boolean
6369 // type, but the function necessarily returns "bool". The
6370 // difference shows up in code like
6371 // type mybool bool
6372 // var b mybool = [10]string{} == [10]string{}
6373 // The comparison function returns "bool", but since a comparison
6374 // has an abstract boolean type we need an implicit conversion to
6375 // "mybool". The implicit conversion is inserted in
6376 // Call_expression::do_flatten.
6377 ce->set_is_equal_function();
6378
6379 Expression* ret = ce;
6380 if (this->op_ == OPERATOR_NOTEQ)
6381 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6382
6383 return ret;
6384 }
6385
6386 // Lower an interface to value comparison.
6387
6388 Expression*
6389 Binary_expression::lower_interface_value_comparison(Gogo*,
6390 Statement_inserter* inserter)
6391 {
6392 Type* left_type = this->left_->type();
6393 Type* right_type = this->right_->type();
6394 Interface_type* ift;
6395 if (left_type->interface_type() != NULL)
6396 {
6397 ift = left_type->interface_type();
6398 if (!ift->implements_interface(right_type, NULL))
6399 return this;
6400 }
6401 else
6402 {
6403 ift = right_type->interface_type();
6404 if (!ift->implements_interface(left_type, NULL))
6405 return this;
6406 }
6407 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6408 return this;
6409
6410 Location loc = this->location();
6411
6412 if (left_type->interface_type() == NULL
6413 && left_type->points_to() == NULL
6414 && !this->left_->is_addressable())
6415 {
6416 Temporary_statement* temp =
6417 Statement::make_temporary(left_type, NULL, loc);
6418 inserter->insert(temp);
6419 this->left_ =
6420 Expression::make_set_and_use_temporary(temp, this->left_, loc);
6421 }
6422
6423 if (right_type->interface_type() == NULL
6424 && right_type->points_to() == NULL
6425 && !this->right_->is_addressable())
6426 {
6427 Temporary_statement* temp =
6428 Statement::make_temporary(right_type, NULL, loc);
6429 inserter->insert(temp);
6430 this->right_ =
6431 Expression::make_set_and_use_temporary(temp, this->right_, loc);
6432 }
6433
6434 return this;
6435 }
6436
6437 // Lower a struct or array comparison to a call to memcmp.
6438
6439 Expression*
6440 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6441 {
6442 Location loc = this->location();
6443
6444 Expression* a1 = this->operand_address(inserter, this->left_);
6445 Expression* a2 = this->operand_address(inserter, this->right_);
6446 Expression* len = Expression::make_type_info(this->left_->type(),
6447 TYPE_INFO_SIZE);
6448
6449 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6450 Type* int32_type = Type::lookup_integer_type("int32");
6451 Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
6452 return Expression::make_binary(this->op_, call, zero, loc);
6453 }
6454
6455 Expression*
6456 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
6457 Statement_inserter* inserter)
6458 {
6459 Location loc = this->location();
6460 if (this->left_->type()->is_error_type()
6461 || this->right_->type()->is_error_type()
6462 || this->left_->is_error_expression()
6463 || this->right_->is_error_expression())
6464 {
6465 go_assert(saw_errors());
6466 return Expression::make_error(loc);
6467 }
6468
6469 Temporary_statement* temp;
6470
6471 Type* left_type = this->left_->type();
6472 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6473 || this->op_ == OPERATOR_RSHIFT);
6474 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
6475 left_type->integer_type() != NULL)
6476 || this->op_ == OPERATOR_MOD);
6477 bool is_string_op = (left_type->is_string_type()
6478 && this->right_->type()->is_string_type());
6479
6480 if (is_string_op)
6481 {
6482 // Mark string([]byte) operands to reuse the backing store.
6483 // String comparison does not keep the reference, so it is safe.
6484 Type_conversion_expression* lce =
6485 this->left_->conversion_expression();
6486 if (lce != NULL && lce->expr()->type()->is_slice_type())
6487 lce->set_no_copy(true);
6488 Type_conversion_expression* rce =
6489 this->right_->conversion_expression();
6490 if (rce != NULL && rce->expr()->type()->is_slice_type())
6491 rce->set_no_copy(true);
6492 }
6493
6494 if (is_shift_op
6495 || (is_idiv_op
6496 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
6497 || is_string_op)
6498 {
6499 if (!this->left_->is_variable() && !this->left_->is_constant())
6500 {
6501 temp = Statement::make_temporary(NULL, this->left_, loc);
6502 inserter->insert(temp);
6503 this->left_ = Expression::make_temporary_reference(temp, loc);
6504 }
6505 if (!this->right_->is_variable() && !this->right_->is_constant())
6506 {
6507 temp =
6508 Statement::make_temporary(NULL, this->right_, loc);
6509 this->right_ = Expression::make_temporary_reference(temp, loc);
6510 inserter->insert(temp);
6511 }
6512 }
6513 return this;
6514 }
6515
6516
6517 // Return the address of EXPR, cast to unsafe.Pointer.
6518
6519 Expression*
6520 Binary_expression::operand_address(Statement_inserter* inserter,
6521 Expression* expr)
6522 {
6523 Location loc = this->location();
6524
6525 if (!expr->is_addressable())
6526 {
6527 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6528 loc);
6529 inserter->insert(temp);
6530 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6531 }
6532 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6533 static_cast<Unary_expression*>(expr)->set_does_not_escape();
6534 Type* void_type = Type::make_void_type();
6535 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6536 return Expression::make_cast(unsafe_pointer_type, expr, loc);
6537 }
6538
6539 // Return the numeric constant value, if it has one.
6540
6541 bool
6542 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
6543 {
6544 Numeric_constant left_nc;
6545 if (!this->left_->numeric_constant_value(&left_nc))
6546 return false;
6547 Numeric_constant right_nc;
6548 if (!this->right_->numeric_constant_value(&right_nc))
6549 return false;
6550 bool issued_error;
6551 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
6552 this->location(), nc, &issued_error);
6553 }
6554
6555 // Return the boolean constant value, if it has one.
6556
6557 bool
6558 Binary_expression::do_boolean_constant_value(bool* val) const
6559 {
6560 bool is_comparison = false;
6561 switch (this->op_)
6562 {
6563 case OPERATOR_EQEQ:
6564 case OPERATOR_NOTEQ:
6565 case OPERATOR_LT:
6566 case OPERATOR_LE:
6567 case OPERATOR_GT:
6568 case OPERATOR_GE:
6569 is_comparison = true;
6570 break;
6571 case OPERATOR_ANDAND:
6572 case OPERATOR_OROR:
6573 break;
6574 default:
6575 return false;
6576 }
6577
6578 Numeric_constant left_nc, right_nc;
6579 if (is_comparison
6580 && this->left_->numeric_constant_value(&left_nc)
6581 && this->right_->numeric_constant_value(&right_nc))
6582 return Binary_expression::compare_constant(this->op_, &left_nc,
6583 &right_nc,
6584 this->location(),
6585 val);
6586
6587 std::string left_str, right_str;
6588 if (is_comparison
6589 && this->left_->string_constant_value(&left_str)
6590 && this->right_->string_constant_value(&right_str))
6591 {
6592 *val = Binary_expression::cmp_to_bool(this->op_,
6593 left_str.compare(right_str));
6594 return true;
6595 }
6596
6597 bool left_bval;
6598 if (this->left_->boolean_constant_value(&left_bval))
6599 {
6600 if (this->op_ == OPERATOR_ANDAND && !left_bval)
6601 {
6602 *val = false;
6603 return true;
6604 }
6605 else if (this->op_ == OPERATOR_OROR && left_bval)
6606 {
6607 *val = true;
6608 return true;
6609 }
6610
6611 bool right_bval;
6612 if (this->right_->boolean_constant_value(&right_bval))
6613 {
6614 switch (this->op_)
6615 {
6616 case OPERATOR_EQEQ:
6617 *val = (left_bval == right_bval);
6618 return true;
6619 case OPERATOR_NOTEQ:
6620 *val = (left_bval != right_bval);
6621 return true;
6622 case OPERATOR_ANDAND:
6623 case OPERATOR_OROR:
6624 *val = right_bval;
6625 return true;
6626 default:
6627 go_unreachable();
6628 }
6629 }
6630 }
6631
6632 return false;
6633 }
6634
6635 // Note that the value is being discarded.
6636
6637 bool
6638 Binary_expression::do_discarding_value()
6639 {
6640 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6641 return this->right_->discarding_value();
6642 else
6643 {
6644 this->unused_value_error();
6645 return false;
6646 }
6647 }
6648
6649 // Get type.
6650
6651 Type*
6652 Binary_expression::do_type()
6653 {
6654 if (this->classification() == EXPRESSION_ERROR)
6655 return Type::make_error_type();
6656
6657 switch (this->op_)
6658 {
6659 case OPERATOR_EQEQ:
6660 case OPERATOR_NOTEQ:
6661 case OPERATOR_LT:
6662 case OPERATOR_LE:
6663 case OPERATOR_GT:
6664 case OPERATOR_GE:
6665 if (this->type_ == NULL)
6666 this->type_ = Type::make_boolean_type();
6667 return this->type_;
6668
6669 case OPERATOR_PLUS:
6670 case OPERATOR_MINUS:
6671 case OPERATOR_OR:
6672 case OPERATOR_XOR:
6673 case OPERATOR_MULT:
6674 case OPERATOR_DIV:
6675 case OPERATOR_MOD:
6676 case OPERATOR_AND:
6677 case OPERATOR_BITCLEAR:
6678 case OPERATOR_OROR:
6679 case OPERATOR_ANDAND:
6680 {
6681 Type* type;
6682 if (!Binary_expression::operation_type(this->op_,
6683 this->left_->type(),
6684 this->right_->type(),
6685 &type))
6686 return Type::make_error_type();
6687 return type;
6688 }
6689
6690 case OPERATOR_LSHIFT:
6691 case OPERATOR_RSHIFT:
6692 return this->left_->type();
6693
6694 default:
6695 go_unreachable();
6696 }
6697 }
6698
6699 // Set type for a binary expression.
6700
6701 void
6702 Binary_expression::do_determine_type(const Type_context* context)
6703 {
6704 Type* tleft = this->left_->type();
6705 Type* tright = this->right_->type();
6706
6707 // Both sides should have the same type, except for the shift
6708 // operations. For a comparison, we should ignore the incoming
6709 // type.
6710
6711 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6712 || this->op_ == OPERATOR_RSHIFT);
6713
6714 bool is_comparison = (this->op_ == OPERATOR_EQEQ
6715 || this->op_ == OPERATOR_NOTEQ
6716 || this->op_ == OPERATOR_LT
6717 || this->op_ == OPERATOR_LE
6718 || this->op_ == OPERATOR_GT
6719 || this->op_ == OPERATOR_GE);
6720
6721 // For constant expressions, the context of the result is not useful in
6722 // determining the types of the operands. It is only legal to use abstract
6723 // boolean, numeric, and string constants as operands where it is legal to
6724 // use non-abstract boolean, numeric, and string constants, respectively.
6725 // Any issues with the operation will be resolved in the check_types pass.
6726 bool is_constant_expr = (this->left_->is_constant()
6727 && this->right_->is_constant());
6728
6729 Type_context subcontext(*context);
6730
6731 if (is_constant_expr && !is_shift_op)
6732 {
6733 subcontext.type = NULL;
6734 subcontext.may_be_abstract = true;
6735 }
6736 else if (is_comparison)
6737 {
6738 // In a comparison, the context does not determine the types of
6739 // the operands.
6740 subcontext.type = NULL;
6741 }
6742
6743 // Set the context for the left hand operand.
6744 if (is_shift_op)
6745 {
6746 // The right hand operand of a shift plays no role in
6747 // determining the type of the left hand operand.
6748 }
6749 else if (!tleft->is_abstract())
6750 subcontext.type = tleft;
6751 else if (!tright->is_abstract())
6752 subcontext.type = tright;
6753 else if (subcontext.type == NULL)
6754 {
6755 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6756 || (tleft->float_type() != NULL && tright->float_type() != NULL)
6757 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6758 {
6759 // Both sides have an abstract integer, abstract float, or
6760 // abstract complex type. Just let CONTEXT determine
6761 // whether they may remain abstract or not.
6762 }
6763 else if (tleft->complex_type() != NULL)
6764 subcontext.type = tleft;
6765 else if (tright->complex_type() != NULL)
6766 subcontext.type = tright;
6767 else if (tleft->float_type() != NULL)
6768 subcontext.type = tleft;
6769 else if (tright->float_type() != NULL)
6770 subcontext.type = tright;
6771 else
6772 subcontext.type = tleft;
6773
6774 if (subcontext.type != NULL && !context->may_be_abstract)
6775 subcontext.type = subcontext.type->make_non_abstract_type();
6776 }
6777
6778 this->left_->determine_type(&subcontext);
6779
6780 if (is_shift_op)
6781 {
6782 // We may have inherited an unusable type for the shift operand.
6783 // Give a useful error if that happened.
6784 if (tleft->is_abstract()
6785 && subcontext.type != NULL
6786 && !subcontext.may_be_abstract
6787 && subcontext.type->interface_type() == NULL
6788 && subcontext.type->integer_type() == NULL)
6789 this->report_error(("invalid context-determined non-integer type "
6790 "for left operand of shift"));
6791
6792 // The context for the right hand operand is the same as for the
6793 // left hand operand, except for a shift operator.
6794 subcontext.type = Type::lookup_integer_type("uint");
6795 subcontext.may_be_abstract = false;
6796 }
6797
6798 this->right_->determine_type(&subcontext);
6799
6800 if (is_comparison)
6801 {
6802 if (this->type_ != NULL && !this->type_->is_abstract())
6803 ;
6804 else if (context->type != NULL && context->type->is_boolean_type())
6805 this->type_ = context->type;
6806 else if (!context->may_be_abstract)
6807 this->type_ = Type::lookup_bool_type();
6808 }
6809 }
6810
6811 // Report an error if the binary operator OP does not support TYPE.
6812 // OTYPE is the type of the other operand. Return whether the
6813 // operation is OK. This should not be used for shift.
6814
6815 bool
6816 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6817 Location location)
6818 {
6819 switch (op)
6820 {
6821 case OPERATOR_OROR:
6822 case OPERATOR_ANDAND:
6823 if (!type->is_boolean_type()
6824 || !otype->is_boolean_type())
6825 {
6826 go_error_at(location, "expected boolean type");
6827 return false;
6828 }
6829 break;
6830
6831 case OPERATOR_EQEQ:
6832 case OPERATOR_NOTEQ:
6833 {
6834 std::string reason;
6835 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6836 {
6837 go_error_at(location, "%s", reason.c_str());
6838 return false;
6839 }
6840 }
6841 break;
6842
6843 case OPERATOR_LT:
6844 case OPERATOR_LE:
6845 case OPERATOR_GT:
6846 case OPERATOR_GE:
6847 {
6848 std::string reason;
6849 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6850 {
6851 go_error_at(location, "%s", reason.c_str());
6852 return false;
6853 }
6854 }
6855 break;
6856
6857 case OPERATOR_PLUS:
6858 case OPERATOR_PLUSEQ:
6859 if ((!type->is_numeric_type() && !type->is_string_type())
6860 || (!otype->is_numeric_type() && !otype->is_string_type()))
6861 {
6862 go_error_at(location,
6863 "expected integer, floating, complex, or string type");
6864 return false;
6865 }
6866 break;
6867
6868 case OPERATOR_MINUS:
6869 case OPERATOR_MINUSEQ:
6870 case OPERATOR_MULT:
6871 case OPERATOR_MULTEQ:
6872 case OPERATOR_DIV:
6873 case OPERATOR_DIVEQ:
6874 if (!type->is_numeric_type() || !otype->is_numeric_type())
6875 {
6876 go_error_at(location, "expected integer, floating, or complex type");
6877 return false;
6878 }
6879 break;
6880
6881 case OPERATOR_MOD:
6882 case OPERATOR_MODEQ:
6883 case OPERATOR_OR:
6884 case OPERATOR_OREQ:
6885 case OPERATOR_AND:
6886 case OPERATOR_ANDEQ:
6887 case OPERATOR_XOR:
6888 case OPERATOR_XOREQ:
6889 case OPERATOR_BITCLEAR:
6890 case OPERATOR_BITCLEAREQ:
6891 if (type->integer_type() == NULL || otype->integer_type() == NULL)
6892 {
6893 go_error_at(location, "expected integer type");
6894 return false;
6895 }
6896 break;
6897
6898 default:
6899 go_unreachable();
6900 }
6901
6902 return true;
6903 }
6904
6905 // Check types.
6906
6907 void
6908 Binary_expression::do_check_types(Gogo*)
6909 {
6910 if (this->classification() == EXPRESSION_ERROR)
6911 return;
6912
6913 Type* left_type = this->left_->type();
6914 Type* right_type = this->right_->type();
6915 if (left_type->is_error() || right_type->is_error())
6916 {
6917 this->set_is_error();
6918 return;
6919 }
6920
6921 if (this->op_ == OPERATOR_EQEQ
6922 || this->op_ == OPERATOR_NOTEQ
6923 || this->op_ == OPERATOR_LT
6924 || this->op_ == OPERATOR_LE
6925 || this->op_ == OPERATOR_GT
6926 || this->op_ == OPERATOR_GE)
6927 {
6928 if (left_type->is_nil_type() && right_type->is_nil_type())
6929 {
6930 this->report_error(_("invalid comparison of nil with nil"));
6931 return;
6932 }
6933 if (!Type::are_assignable(left_type, right_type, NULL)
6934 && !Type::are_assignable(right_type, left_type, NULL))
6935 {
6936 this->report_error(_("incompatible types in binary expression"));
6937 return;
6938 }
6939 if (!Binary_expression::check_operator_type(this->op_, left_type,
6940 right_type,
6941 this->location())
6942 || !Binary_expression::check_operator_type(this->op_, right_type,
6943 left_type,
6944 this->location()))
6945 {
6946 this->set_is_error();
6947 return;
6948 }
6949 }
6950 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6951 {
6952 if (!Type::are_compatible_for_binop(left_type, right_type))
6953 {
6954 this->report_error(_("incompatible types in binary expression"));
6955 return;
6956 }
6957 if (!Binary_expression::check_operator_type(this->op_, left_type,
6958 right_type,
6959 this->location()))
6960 {
6961 this->set_is_error();
6962 return;
6963 }
6964 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
6965 {
6966 // Division by a zero integer constant is an error.
6967 Numeric_constant rconst;
6968 unsigned long rval;
6969 if (left_type->integer_type() != NULL
6970 && this->right_->numeric_constant_value(&rconst)
6971 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6972 && rval == 0)
6973 {
6974 this->report_error(_("integer division by zero"));
6975 return;
6976 }
6977 }
6978 }
6979 else
6980 {
6981 if (left_type->integer_type() == NULL)
6982 this->report_error(_("shift of non-integer operand"));
6983
6984 if (right_type->is_string_type())
6985 this->report_error(_("shift count not integer"));
6986 else if (!right_type->is_abstract()
6987 && right_type->integer_type() == NULL)
6988 this->report_error(_("shift count not integer"));
6989 else
6990 {
6991 Numeric_constant nc;
6992 if (this->right_->numeric_constant_value(&nc))
6993 {
6994 mpz_t val;
6995 if (!nc.to_int(&val))
6996 this->report_error(_("shift count not integer"));
6997 else
6998 {
6999 if (mpz_sgn(val) < 0)
7000 {
7001 this->report_error(_("negative shift count"));
7002 Location rloc = this->right_->location();
7003 this->right_ = Expression::make_integer_ul(0, right_type,
7004 rloc);
7005 }
7006 mpz_clear(val);
7007 }
7008 }
7009 }
7010 }
7011 }
7012
7013 // Get the backend representation for a binary expression.
7014
7015 Bexpression*
7016 Binary_expression::do_get_backend(Translate_context* context)
7017 {
7018 Gogo* gogo = context->gogo();
7019 Location loc = this->location();
7020 Type* left_type = this->left_->type();
7021 Type* right_type = this->right_->type();
7022
7023 bool use_left_type = true;
7024 bool is_shift_op = false;
7025 bool is_idiv_op = false;
7026 switch (this->op_)
7027 {
7028 case OPERATOR_EQEQ:
7029 case OPERATOR_NOTEQ:
7030 case OPERATOR_LT:
7031 case OPERATOR_LE:
7032 case OPERATOR_GT:
7033 case OPERATOR_GE:
7034 return Expression::comparison(context, this->type_, this->op_,
7035 this->left_, this->right_, loc);
7036
7037 case OPERATOR_OROR:
7038 case OPERATOR_ANDAND:
7039 use_left_type = false;
7040 break;
7041 case OPERATOR_PLUS:
7042 case OPERATOR_MINUS:
7043 case OPERATOR_OR:
7044 case OPERATOR_XOR:
7045 case OPERATOR_MULT:
7046 break;
7047 case OPERATOR_DIV:
7048 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
7049 break;
7050 // Fall through.
7051 case OPERATOR_MOD:
7052 is_idiv_op = true;
7053 break;
7054 case OPERATOR_LSHIFT:
7055 case OPERATOR_RSHIFT:
7056 is_shift_op = true;
7057 break;
7058 case OPERATOR_BITCLEAR:
7059 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
7060 case OPERATOR_AND:
7061 break;
7062 default:
7063 go_unreachable();
7064 }
7065
7066 // The only binary operation for string is +, and that should have
7067 // been converted to a String_concat_expression in do_lower.
7068 go_assert(!left_type->is_string_type());
7069
7070 Bexpression* left = this->left_->get_backend(context);
7071 Bexpression* right = this->right_->get_backend(context);
7072
7073 Type* type = use_left_type ? left_type : right_type;
7074 Btype* btype = type->get_backend(gogo);
7075
7076 Bexpression* ret =
7077 gogo->backend()->binary_expression(this->op_, left, right, loc);
7078 ret = gogo->backend()->convert_expression(btype, ret, loc);
7079
7080 // Initialize overflow constants.
7081 Bexpression* overflow;
7082 mpz_t zero;
7083 mpz_init_set_ui(zero, 0UL);
7084 mpz_t one;
7085 mpz_init_set_ui(one, 1UL);
7086 mpz_t neg_one;
7087 mpz_init_set_si(neg_one, -1);
7088
7089 Btype* left_btype = left_type->get_backend(gogo);
7090 Btype* right_btype = right_type->get_backend(gogo);
7091
7092 // In Go, a shift larger than the size of the type is well-defined.
7093 // This is not true in C, so we need to insert a conditional.
7094 // We also need to check for a negative shift count.
7095 if (is_shift_op)
7096 {
7097 go_assert(left_type->integer_type() != NULL);
7098 go_assert(right_type->integer_type() != NULL);
7099
7100 int bits = left_type->integer_type()->bits();
7101
7102 Numeric_constant nc;
7103 unsigned long ul;
7104 if (!this->right_->numeric_constant_value(&nc)
7105 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7106 || ul >= static_cast<unsigned long>(bits))
7107 {
7108 mpz_t bitsval;
7109 mpz_init_set_ui(bitsval, bits);
7110 Bexpression* bits_expr =
7111 gogo->backend()->integer_constant_expression(right_btype, bitsval);
7112 Bexpression* compare =
7113 gogo->backend()->binary_expression(OPERATOR_LT,
7114 right, bits_expr, loc);
7115
7116 Bexpression* zero_expr =
7117 gogo->backend()->integer_constant_expression(left_btype, zero);
7118 overflow = zero_expr;
7119 Bfunction* bfn = context->function()->func_value()->get_decl();
7120 if (this->op_ == OPERATOR_RSHIFT
7121 && !left_type->integer_type()->is_unsigned())
7122 {
7123 Bexpression* neg_expr =
7124 gogo->backend()->binary_expression(OPERATOR_LT, left,
7125 zero_expr, loc);
7126 Bexpression* neg_one_expr =
7127 gogo->backend()->integer_constant_expression(left_btype,
7128 neg_one);
7129 overflow = gogo->backend()->conditional_expression(bfn,
7130 btype,
7131 neg_expr,
7132 neg_one_expr,
7133 zero_expr,
7134 loc);
7135 }
7136 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7137 ret, overflow, loc);
7138 mpz_clear(bitsval);
7139 }
7140
7141 if (!right_type->integer_type()->is_unsigned()
7142 && (!this->right_->numeric_constant_value(&nc)
7143 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7144 {
7145 Bexpression* zero_expr =
7146 gogo->backend()->integer_constant_expression(right_btype, zero);
7147 Bexpression* compare =
7148 gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7149 loc);
7150 Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
7151 loc, 0);
7152 Bexpression* bcrash = crash->get_backend(context);
7153 Bfunction* bfn = context->function()->func_value()->get_decl();
7154 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7155 bcrash, ret, loc);
7156 }
7157 }
7158
7159 // Add checks for division by zero and division overflow as needed.
7160 if (is_idiv_op)
7161 {
7162 if (gogo->check_divide_by_zero())
7163 {
7164 // right == 0
7165 Bexpression* zero_expr =
7166 gogo->backend()->integer_constant_expression(right_btype, zero);
7167 Bexpression* check =
7168 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7169 right, zero_expr, loc);
7170
7171 Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
7172 loc, 0);
7173 Bexpression* bcrash = crash->get_backend(context);
7174
7175 // right == 0 ? (panicdivide(), 0) : ret
7176 Bfunction* bfn = context->function()->func_value()->get_decl();
7177 ret = gogo->backend()->conditional_expression(bfn, btype,
7178 check, bcrash,
7179 ret, loc);
7180 }
7181
7182 if (gogo->check_divide_overflow())
7183 {
7184 // right == -1
7185 // FIXME: It would be nice to say that this test is expected
7186 // to return false.
7187
7188 Bexpression* neg_one_expr =
7189 gogo->backend()->integer_constant_expression(right_btype, neg_one);
7190 Bexpression* check =
7191 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7192 right, neg_one_expr, loc);
7193
7194 Bexpression* zero_expr =
7195 gogo->backend()->integer_constant_expression(btype, zero);
7196 Bexpression* one_expr =
7197 gogo->backend()->integer_constant_expression(btype, one);
7198 Bfunction* bfn = context->function()->func_value()->get_decl();
7199
7200 if (type->integer_type()->is_unsigned())
7201 {
7202 // An unsigned -1 is the largest possible number, so
7203 // dividing is always 1 or 0.
7204
7205 Bexpression* cmp =
7206 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7207 left, right, loc);
7208 if (this->op_ == OPERATOR_DIV)
7209 overflow =
7210 gogo->backend()->conditional_expression(bfn, btype, cmp,
7211 one_expr, zero_expr,
7212 loc);
7213 else
7214 overflow =
7215 gogo->backend()->conditional_expression(bfn, btype, cmp,
7216 zero_expr, left,
7217 loc);
7218 }
7219 else
7220 {
7221 // Computing left / -1 is the same as computing - left,
7222 // which does not overflow since Go sets -fwrapv.
7223 if (this->op_ == OPERATOR_DIV)
7224 {
7225 Expression* negate_expr =
7226 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7227 overflow = negate_expr->get_backend(context);
7228 }
7229 else
7230 overflow = zero_expr;
7231 }
7232 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7233
7234 // right == -1 ? - left : ret
7235 ret = gogo->backend()->conditional_expression(bfn, btype,
7236 check, overflow,
7237 ret, loc);
7238 }
7239 }
7240
7241 mpz_clear(zero);
7242 mpz_clear(one);
7243 mpz_clear(neg_one);
7244 return ret;
7245 }
7246
7247 // Export a binary expression.
7248
7249 void
7250 Binary_expression::do_export(Export_function_body* efb) const
7251 {
7252 efb->write_c_string("(");
7253 this->left_->export_expression(efb);
7254 switch (this->op_)
7255 {
7256 case OPERATOR_OROR:
7257 efb->write_c_string(" || ");
7258 break;
7259 case OPERATOR_ANDAND:
7260 efb->write_c_string(" && ");
7261 break;
7262 case OPERATOR_EQEQ:
7263 efb->write_c_string(" == ");
7264 break;
7265 case OPERATOR_NOTEQ:
7266 efb->write_c_string(" != ");
7267 break;
7268 case OPERATOR_LT:
7269 efb->write_c_string(" < ");
7270 break;
7271 case OPERATOR_LE:
7272 efb->write_c_string(" <= ");
7273 break;
7274 case OPERATOR_GT:
7275 efb->write_c_string(" > ");
7276 break;
7277 case OPERATOR_GE:
7278 efb->write_c_string(" >= ");
7279 break;
7280 case OPERATOR_PLUS:
7281 efb->write_c_string(" + ");
7282 break;
7283 case OPERATOR_MINUS:
7284 efb->write_c_string(" - ");
7285 break;
7286 case OPERATOR_OR:
7287 efb->write_c_string(" | ");
7288 break;
7289 case OPERATOR_XOR:
7290 efb->write_c_string(" ^ ");
7291 break;
7292 case OPERATOR_MULT:
7293 efb->write_c_string(" * ");
7294 break;
7295 case OPERATOR_DIV:
7296 efb->write_c_string(" / ");
7297 break;
7298 case OPERATOR_MOD:
7299 efb->write_c_string(" % ");
7300 break;
7301 case OPERATOR_LSHIFT:
7302 efb->write_c_string(" << ");
7303 break;
7304 case OPERATOR_RSHIFT:
7305 efb->write_c_string(" >> ");
7306 break;
7307 case OPERATOR_AND:
7308 efb->write_c_string(" & ");
7309 break;
7310 case OPERATOR_BITCLEAR:
7311 efb->write_c_string(" &^ ");
7312 break;
7313 default:
7314 go_unreachable();
7315 }
7316 this->right_->export_expression(efb);
7317 efb->write_c_string(")");
7318 }
7319
7320 // Import a binary expression.
7321
7322 Expression*
7323 Binary_expression::do_import(Import_expression* imp, Location loc)
7324 {
7325 imp->require_c_string("(");
7326
7327 Expression* left = Expression::import_expression(imp, loc);
7328
7329 Operator op;
7330 if (imp->match_c_string(" || "))
7331 {
7332 op = OPERATOR_OROR;
7333 imp->advance(4);
7334 }
7335 else if (imp->match_c_string(" && "))
7336 {
7337 op = OPERATOR_ANDAND;
7338 imp->advance(4);
7339 }
7340 else if (imp->match_c_string(" == "))
7341 {
7342 op = OPERATOR_EQEQ;
7343 imp->advance(4);
7344 }
7345 else if (imp->match_c_string(" != "))
7346 {
7347 op = OPERATOR_NOTEQ;
7348 imp->advance(4);
7349 }
7350 else if (imp->match_c_string(" < "))
7351 {
7352 op = OPERATOR_LT;
7353 imp->advance(3);
7354 }
7355 else if (imp->match_c_string(" <= "))
7356 {
7357 op = OPERATOR_LE;
7358 imp->advance(4);
7359 }
7360 else if (imp->match_c_string(" > "))
7361 {
7362 op = OPERATOR_GT;
7363 imp->advance(3);
7364 }
7365 else if (imp->match_c_string(" >= "))
7366 {
7367 op = OPERATOR_GE;
7368 imp->advance(4);
7369 }
7370 else if (imp->match_c_string(" + "))
7371 {
7372 op = OPERATOR_PLUS;
7373 imp->advance(3);
7374 }
7375 else if (imp->match_c_string(" - "))
7376 {
7377 op = OPERATOR_MINUS;
7378 imp->advance(3);
7379 }
7380 else if (imp->match_c_string(" | "))
7381 {
7382 op = OPERATOR_OR;
7383 imp->advance(3);
7384 }
7385 else if (imp->match_c_string(" ^ "))
7386 {
7387 op = OPERATOR_XOR;
7388 imp->advance(3);
7389 }
7390 else if (imp->match_c_string(" * "))
7391 {
7392 op = OPERATOR_MULT;
7393 imp->advance(3);
7394 }
7395 else if (imp->match_c_string(" / "))
7396 {
7397 op = OPERATOR_DIV;
7398 imp->advance(3);
7399 }
7400 else if (imp->match_c_string(" % "))
7401 {
7402 op = OPERATOR_MOD;
7403 imp->advance(3);
7404 }
7405 else if (imp->match_c_string(" << "))
7406 {
7407 op = OPERATOR_LSHIFT;
7408 imp->advance(4);
7409 }
7410 else if (imp->match_c_string(" >> "))
7411 {
7412 op = OPERATOR_RSHIFT;
7413 imp->advance(4);
7414 }
7415 else if (imp->match_c_string(" & "))
7416 {
7417 op = OPERATOR_AND;
7418 imp->advance(3);
7419 }
7420 else if (imp->match_c_string(" &^ "))
7421 {
7422 op = OPERATOR_BITCLEAR;
7423 imp->advance(4);
7424 }
7425 else if (imp->match_c_string(")"))
7426 {
7427 // Not a binary operator after all.
7428 imp->advance(1);
7429 return left;
7430 }
7431 else
7432 {
7433 go_error_at(imp->location(), "unrecognized binary operator");
7434 return Expression::make_error(loc);
7435 }
7436
7437 Expression* right = Expression::import_expression(imp, loc);
7438
7439 imp->require_c_string(")");
7440
7441 return Expression::make_binary(op, left, right, loc);
7442 }
7443
7444 // Dump ast representation of a binary expression.
7445
7446 void
7447 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7448 {
7449 ast_dump_context->ostream() << "(";
7450 ast_dump_context->dump_expression(this->left_);
7451 ast_dump_context->ostream() << " ";
7452 ast_dump_context->dump_operator(this->op_);
7453 ast_dump_context->ostream() << " ";
7454 ast_dump_context->dump_expression(this->right_);
7455 ast_dump_context->ostream() << ") ";
7456 }
7457
7458 // Make a binary expression.
7459
7460 Expression*
7461 Expression::make_binary(Operator op, Expression* left, Expression* right,
7462 Location location)
7463 {
7464 return new Binary_expression(op, left, right, location);
7465 }
7466
7467 // Implement a comparison.
7468
7469 Bexpression*
7470 Expression::comparison(Translate_context* context, Type* result_type,
7471 Operator op, Expression* left, Expression* right,
7472 Location location)
7473 {
7474 Type* left_type = left->type();
7475 Type* right_type = right->type();
7476
7477 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
7478
7479 if (left_type->is_string_type() && right_type->is_string_type())
7480 {
7481 go_assert(left->is_variable() || left->is_constant());
7482 go_assert(right->is_variable() || right->is_constant());
7483
7484 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
7485 {
7486 // (l.len == r.len
7487 // ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
7488 // : false)
7489 Expression* llen = Expression::make_string_info(left,
7490 STRING_INFO_LENGTH,
7491 location);
7492 Expression* rlen = Expression::make_string_info(right,
7493 STRING_INFO_LENGTH,
7494 location);
7495 Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
7496 location);
7497 Expression* lptr = Expression::make_string_info(left->copy(),
7498 STRING_INFO_DATA,
7499 location);
7500 Expression* rptr = Expression::make_string_info(right->copy(),
7501 STRING_INFO_DATA,
7502 location);
7503 Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
7504 location);
7505 Expression* btrue = Expression::make_boolean(true, location);
7506 Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
7507 lptr->copy(), rptr->copy(),
7508 rlen->copy());
7509 Type* int32_type = Type::lookup_integer_type("int32");
7510 Expression* zero = Expression::make_integer_ul(0, int32_type, location);
7511 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
7512 location);
7513 Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
7514 location);
7515 Expression* bfalse = Expression::make_boolean(false, location);
7516 left = Expression::make_conditional(leneq, cond, bfalse, location);
7517 right = Expression::make_boolean(true, location);
7518 }
7519 else
7520 {
7521 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
7522 left, right);
7523 right = zexpr;
7524 }
7525 }
7526 else if ((left_type->interface_type() != NULL
7527 && right_type->interface_type() == NULL
7528 && !right_type->is_nil_type())
7529 || (left_type->interface_type() == NULL
7530 && !left_type->is_nil_type()
7531 && right_type->interface_type() != NULL))
7532 {
7533 // Comparing an interface value to a non-interface value.
7534 if (left_type->interface_type() == NULL)
7535 {
7536 std::swap(left_type, right_type);
7537 std::swap(left, right);
7538 }
7539
7540 // The right operand is not an interface. We need to take its
7541 // address if it is not a direct interface type.
7542 Expression* pointer_arg = NULL;
7543 if (right_type->is_direct_iface_type())
7544 pointer_arg = Expression::unpack_direct_iface(right, location);
7545 else
7546 {
7547 go_assert(right->is_addressable());
7548 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
7549 location);
7550 }
7551
7552 Expression* descriptor =
7553 Expression::make_type_descriptor(right_type, location);
7554 left =
7555 Runtime::make_call((left_type->interface_type()->is_empty()
7556 ? Runtime::EFACEVALEQ
7557 : Runtime::IFACEVALEQ),
7558 location, 3, left, descriptor,
7559 pointer_arg);
7560 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7561 right = Expression::make_boolean(true, location);
7562 }
7563 else if (left_type->interface_type() != NULL
7564 && right_type->interface_type() != NULL)
7565 {
7566 Runtime::Function compare_function;
7567 if (left_type->interface_type()->is_empty()
7568 && right_type->interface_type()->is_empty())
7569 compare_function = Runtime::EFACEEQ;
7570 else if (!left_type->interface_type()->is_empty()
7571 && !right_type->interface_type()->is_empty())
7572 compare_function = Runtime::IFACEEQ;
7573 else
7574 {
7575 if (left_type->interface_type()->is_empty())
7576 {
7577 std::swap(left_type, right_type);
7578 std::swap(left, right);
7579 }
7580 go_assert(!left_type->interface_type()->is_empty());
7581 go_assert(right_type->interface_type()->is_empty());
7582 compare_function = Runtime::IFACEEFACEEQ;
7583 }
7584
7585 left = Runtime::make_call(compare_function, location, 2, left, right);
7586 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7587 right = Expression::make_boolean(true, location);
7588 }
7589
7590 if (left_type->is_nil_type()
7591 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7592 {
7593 std::swap(left_type, right_type);
7594 std::swap(left, right);
7595 }
7596
7597 if (right_type->is_nil_type())
7598 {
7599 right = Expression::make_nil(location);
7600 if (left_type->array_type() != NULL
7601 && left_type->array_type()->length() == NULL)
7602 {
7603 Array_type* at = left_type->array_type();
7604 bool is_lvalue = false;
7605 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
7606 }
7607 else if (left_type->interface_type() != NULL)
7608 {
7609 // An interface is nil if the first field is nil.
7610 left = Expression::make_field_reference(left, 0, location);
7611 }
7612 }
7613
7614 Bexpression* left_bexpr = left->get_backend(context);
7615 Bexpression* right_bexpr = right->get_backend(context);
7616
7617 Gogo* gogo = context->gogo();
7618 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
7619 right_bexpr, location);
7620 if (result_type != NULL)
7621 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
7622 ret, location);
7623 return ret;
7624 }
7625
7626 // Class String_concat_expression.
7627
7628 bool
7629 String_concat_expression::do_is_constant() const
7630 {
7631 for (Expression_list::const_iterator pe = this->exprs_->begin();
7632 pe != this->exprs_->end();
7633 ++pe)
7634 {
7635 if (!(*pe)->is_constant())
7636 return false;
7637 }
7638 return true;
7639 }
7640
7641 bool
7642 String_concat_expression::do_is_zero_value() const
7643 {
7644 for (Expression_list::const_iterator pe = this->exprs_->begin();
7645 pe != this->exprs_->end();
7646 ++pe)
7647 {
7648 if (!(*pe)->is_zero_value())
7649 return false;
7650 }
7651 return true;
7652 }
7653
7654 bool
7655 String_concat_expression::do_is_static_initializer() const
7656 {
7657 for (Expression_list::const_iterator pe = this->exprs_->begin();
7658 pe != this->exprs_->end();
7659 ++pe)
7660 {
7661 if (!(*pe)->is_static_initializer())
7662 return false;
7663 }
7664 return true;
7665 }
7666
7667 Type*
7668 String_concat_expression::do_type()
7669 {
7670 Type* t = this->exprs_->front()->type();
7671 Expression_list::iterator pe = this->exprs_->begin();
7672 ++pe;
7673 for (; pe != this->exprs_->end(); ++pe)
7674 {
7675 Type* t1;
7676 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
7677 (*pe)->type(),
7678 &t1))
7679 return Type::make_error_type();
7680 t = t1;
7681 }
7682 return t;
7683 }
7684
7685 void
7686 String_concat_expression::do_determine_type(const Type_context* context)
7687 {
7688 Type_context subcontext(*context);
7689 for (Expression_list::iterator pe = this->exprs_->begin();
7690 pe != this->exprs_->end();
7691 ++pe)
7692 {
7693 Type* t = (*pe)->type();
7694 if (!t->is_abstract())
7695 {
7696 subcontext.type = t;
7697 break;
7698 }
7699 }
7700 if (subcontext.type == NULL)
7701 subcontext.type = this->exprs_->front()->type();
7702 for (Expression_list::iterator pe = this->exprs_->begin();
7703 pe != this->exprs_->end();
7704 ++pe)
7705 (*pe)->determine_type(&subcontext);
7706 }
7707
7708 void
7709 String_concat_expression::do_check_types(Gogo*)
7710 {
7711 if (this->is_error_expression())
7712 return;
7713 Type* t = this->exprs_->front()->type();
7714 if (t->is_error())
7715 {
7716 this->set_is_error();
7717 return;
7718 }
7719 Expression_list::iterator pe = this->exprs_->begin();
7720 ++pe;
7721 for (; pe != this->exprs_->end(); ++pe)
7722 {
7723 Type* t1 = (*pe)->type();
7724 if (!Type::are_compatible_for_binop(t, t1))
7725 {
7726 this->report_error("incompatible types in binary expression");
7727 return;
7728 }
7729 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
7730 this->location()))
7731 {
7732 this->set_is_error();
7733 return;
7734 }
7735 }
7736 }
7737
7738 Expression*
7739 String_concat_expression::do_flatten(Gogo*, Named_object*,
7740 Statement_inserter* inserter)
7741 {
7742 if (this->is_error_expression())
7743 return this;
7744 Location loc = this->location();
7745 Type* type = this->type();
7746
7747 // Mark string([]byte) operands to reuse the backing store.
7748 // runtime.concatstrings does not keep the reference.
7749 //
7750 // Note: in the gc runtime, if all but one inputs are empty,
7751 // concatstrings returns the only nonempty input without copy.
7752 // So it is not safe to reuse the backing store if it is a
7753 // string([]byte) conversion. So the gc compiler does the
7754 // no-copy optimization only when there is at least one
7755 // constant nonempty input. Currently the gccgo runtime
7756 // doesn't do this, so we don't do the check.
7757 for (Expression_list::iterator p = this->exprs_->begin();
7758 p != this->exprs_->end();
7759 ++p)
7760 {
7761 Type_conversion_expression* tce = (*p)->conversion_expression();
7762 if (tce != NULL)
7763 tce->set_no_copy(true);
7764 }
7765
7766 Expression* buf = NULL;
7767 Node* n = Node::make_node(this);
7768 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7769 {
7770 size_t size = 0;
7771 for (Expression_list::iterator p = this->exprs_->begin();
7772 p != this->exprs_->end();
7773 ++p)
7774 {
7775 std::string s;
7776 if ((*p)->string_constant_value(&s))
7777 size += s.length();
7778 }
7779 // Make a buffer on stack if the result does not escape.
7780 // But don't do this if we know it won't fit.
7781 if (size < (size_t)tmp_string_buf_size)
7782 {
7783 Type* byte_type = Type::lookup_integer_type("uint8");
7784 Expression* buflen =
7785 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7786 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7787 Type* array_type = Type::make_array_type(byte_type, buflen);
7788 buf = Expression::make_allocation(array_type, loc);
7789 buf->allocation_expression()->set_allocate_on_stack();
7790 buf->allocation_expression()->set_no_zero();
7791 }
7792 }
7793 if (buf == NULL)
7794 buf = Expression::make_nil(loc);
7795 go_assert(this->exprs_->size() > 1);
7796 Expression* len =
7797 Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
7798 Array_type* array_type = Type::make_array_type(type, len);
7799 array_type->set_is_array_incomparable();
7800 Expression* array =
7801 Expression::make_array_composite_literal(array_type, this->exprs_,
7802 loc);
7803 Temporary_statement* ts =
7804 Statement::make_temporary(array_type, array, loc);
7805 inserter->insert(ts);
7806 Expression* ref = Expression::make_temporary_reference(ts, loc);
7807 ref = Expression::make_unary(OPERATOR_AND, ref, loc);
7808 Expression* call =
7809 Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
7810 ref, len->copy());
7811 return Expression::make_cast(type, call, loc);
7812 }
7813
7814 void
7815 String_concat_expression::do_dump_expression(
7816 Ast_dump_context* ast_dump_context) const
7817 {
7818 ast_dump_context->ostream() << "concat(";
7819 ast_dump_context->dump_expression_list(this->exprs_, false);
7820 ast_dump_context->ostream() << ")";
7821 }
7822
7823 Expression*
7824 Expression::make_string_concat(Expression_list* exprs)
7825 {
7826 return new String_concat_expression(exprs);
7827 }
7828
7829 // Class Bound_method_expression.
7830
7831 // Traversal.
7832
7833 int
7834 Bound_method_expression::do_traverse(Traverse* traverse)
7835 {
7836 return Expression::traverse(&this->expr_, traverse);
7837 }
7838
7839 // Return the type of a bound method expression. The type of this
7840 // object is simply the type of the method with no receiver.
7841
7842 Type*
7843 Bound_method_expression::do_type()
7844 {
7845 Named_object* fn = this->method_->named_object();
7846 Function_type* fntype;
7847 if (fn->is_function())
7848 fntype = fn->func_value()->type();
7849 else if (fn->is_function_declaration())
7850 fntype = fn->func_declaration_value()->type();
7851 else
7852 return Type::make_error_type();
7853 return fntype->copy_without_receiver();
7854 }
7855
7856 // Determine the types of a method expression.
7857
7858 void
7859 Bound_method_expression::do_determine_type(const Type_context*)
7860 {
7861 Named_object* fn = this->method_->named_object();
7862 Function_type* fntype;
7863 if (fn->is_function())
7864 fntype = fn->func_value()->type();
7865 else if (fn->is_function_declaration())
7866 fntype = fn->func_declaration_value()->type();
7867 else
7868 fntype = NULL;
7869 if (fntype == NULL || !fntype->is_method())
7870 this->expr_->determine_type_no_context();
7871 else
7872 {
7873 Type_context subcontext(fntype->receiver()->type(), false);
7874 this->expr_->determine_type(&subcontext);
7875 }
7876 }
7877
7878 // Check the types of a method expression.
7879
7880 void
7881 Bound_method_expression::do_check_types(Gogo*)
7882 {
7883 Named_object* fn = this->method_->named_object();
7884 if (!fn->is_function() && !fn->is_function_declaration())
7885 {
7886 this->report_error(_("object is not a method"));
7887 return;
7888 }
7889
7890 Function_type* fntype;
7891 if (fn->is_function())
7892 fntype = fn->func_value()->type();
7893 else if (fn->is_function_declaration())
7894 fntype = fn->func_declaration_value()->type();
7895 else
7896 go_unreachable();
7897 Type* rtype = fntype->receiver()->type()->deref();
7898 Type* etype = (this->expr_type_ != NULL
7899 ? this->expr_type_
7900 : this->expr_->type());
7901 etype = etype->deref();
7902 if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7903 this->report_error(_("method type does not match object type"));
7904 }
7905
7906 // If a bound method expression is not simply called, then it is
7907 // represented as a closure. The closure will hold a single variable,
7908 // the receiver to pass to the method. The function will be a simple
7909 // thunk that pulls that value from the closure and calls the method
7910 // with the remaining arguments.
7911 //
7912 // Because method values are not common, we don't build all thunks for
7913 // every methods, but instead only build them as we need them. In
7914 // particular, we even build them on demand for methods defined in
7915 // other packages.
7916
7917 Bound_method_expression::Method_value_thunks
7918 Bound_method_expression::method_value_thunks;
7919
7920 // Find or create the thunk for METHOD.
7921
7922 Named_object*
7923 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7924 Named_object* fn)
7925 {
7926 std::pair<Named_object*, Named_object*> val(fn, NULL);
7927 std::pair<Method_value_thunks::iterator, bool> ins =
7928 Bound_method_expression::method_value_thunks.insert(val);
7929 if (!ins.second)
7930 {
7931 // We have seen this method before.
7932 go_assert(ins.first->second != NULL);
7933 return ins.first->second;
7934 }
7935
7936 Location loc = fn->location();
7937
7938 Function_type* orig_fntype;
7939 if (fn->is_function())
7940 orig_fntype = fn->func_value()->type();
7941 else if (fn->is_function_declaration())
7942 orig_fntype = fn->func_declaration_value()->type();
7943 else
7944 orig_fntype = NULL;
7945
7946 if (orig_fntype == NULL || !orig_fntype->is_method())
7947 {
7948 ins.first->second =
7949 Named_object::make_erroneous_name(gogo->thunk_name());
7950 return ins.first->second;
7951 }
7952
7953 Struct_field_list* sfl = new Struct_field_list();
7954 // The type here is wrong--it should be the C function type. But it
7955 // doesn't really matter.
7956 Type* vt = Type::make_pointer_type(Type::make_void_type());
7957 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
7958 sfl->push_back(Struct_field(Typed_identifier("val",
7959 orig_fntype->receiver()->type(),
7960 loc)));
7961 Struct_type* st = Type::make_struct_type(sfl, loc);
7962 st->set_is_struct_incomparable();
7963 Type* closure_type = Type::make_pointer_type(st);
7964
7965 Function_type* new_fntype = orig_fntype->copy_with_names();
7966
7967 std::string thunk_name = gogo->thunk_name();
7968 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
7969 false, loc);
7970
7971 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
7972 cvar->set_is_used();
7973 cvar->set_is_closure();
7974 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
7975 NULL, cvar);
7976 new_no->func_value()->set_closure_var(cp);
7977
7978 gogo->start_block(loc);
7979
7980 // Field 0 of the closure is the function code pointer, field 1 is
7981 // the value on which to invoke the method.
7982 Expression* arg = Expression::make_var_reference(cp, loc);
7983 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
7984 arg = Expression::make_field_reference(arg, 1, loc);
7985
7986 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
7987
7988 const Typed_identifier_list* orig_params = orig_fntype->parameters();
7989 Expression_list* args;
7990 if (orig_params == NULL || orig_params->empty())
7991 args = NULL;
7992 else
7993 {
7994 const Typed_identifier_list* new_params = new_fntype->parameters();
7995 args = new Expression_list();
7996 for (Typed_identifier_list::const_iterator p = new_params->begin();
7997 p != new_params->end();
7998 ++p)
7999 {
8000 Named_object* p_no = gogo->lookup(p->name(), NULL);
8001 go_assert(p_no != NULL
8002 && p_no->is_variable()
8003 && p_no->var_value()->is_parameter());
8004 args->push_back(Expression::make_var_reference(p_no, loc));
8005 }
8006 }
8007
8008 Call_expression* call = Expression::make_call(bme, args,
8009 orig_fntype->is_varargs(),
8010 loc);
8011 call->set_varargs_are_lowered();
8012
8013 Statement* s = Statement::make_return_from_call(call, loc);
8014 gogo->add_statement(s);
8015 Block* b = gogo->finish_block(loc);
8016 gogo->add_block(b, loc);
8017 gogo->lower_block(new_no, b);
8018 gogo->flatten_block(new_no, b);
8019 gogo->finish_function(loc);
8020
8021 ins.first->second = new_no;
8022 return new_no;
8023 }
8024
8025 // Return an expression to check *REF for nil while dereferencing
8026 // according to FIELD_INDEXES. Update *REF to build up the field
8027 // reference. This is a static function so that we don't have to
8028 // worry about declaring Field_indexes in expressions.h.
8029
8030 static Expression*
8031 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
8032 Expression** ref)
8033 {
8034 if (field_indexes == NULL)
8035 return Expression::make_boolean(false, loc);
8036 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
8037 Struct_type* stype = (*ref)->type()->deref()->struct_type();
8038 go_assert(stype != NULL
8039 && field_indexes->field_index < stype->field_count());
8040 if ((*ref)->type()->struct_type() == NULL)
8041 {
8042 go_assert((*ref)->type()->points_to() != NULL);
8043 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
8044 Expression::make_nil(loc),
8045 loc);
8046 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
8047 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
8048 loc);
8049 go_assert((*ref)->type()->struct_type() == stype);
8050 }
8051 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
8052 loc);
8053 return cond;
8054 }
8055
8056 // Flatten a method value into a struct with nil checks. We can't do
8057 // this in the lowering phase, because if the method value is called
8058 // directly we don't need a thunk. That case will have been handled
8059 // by Call_expression::do_lower, so if we get here then we do need a
8060 // thunk.
8061
8062 Expression*
8063 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
8064 Statement_inserter* inserter)
8065 {
8066 Location loc = this->location();
8067
8068 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
8069 this->method_,
8070 this->function_);
8071 if (thunk->is_erroneous())
8072 {
8073 go_assert(saw_errors());
8074 return Expression::make_error(loc);
8075 }
8076
8077 // Force the expression into a variable. This is only necessary if
8078 // we are going to do nil checks below, but it's easy enough to
8079 // always do it.
8080 Expression* expr = this->expr_;
8081 if (!expr->is_variable())
8082 {
8083 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
8084 inserter->insert(etemp);
8085 expr = Expression::make_temporary_reference(etemp, loc);
8086 }
8087
8088 // If the method expects a value, and we have a pointer, we need to
8089 // dereference the pointer.
8090
8091 Named_object* fn = this->method_->named_object();
8092 Function_type *fntype;
8093 if (fn->is_function())
8094 fntype = fn->func_value()->type();
8095 else if (fn->is_function_declaration())
8096 fntype = fn->func_declaration_value()->type();
8097 else
8098 go_unreachable();
8099
8100 Expression* val = expr;
8101 if (fntype->receiver()->type()->points_to() == NULL
8102 && val->type()->points_to() != NULL)
8103 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8104
8105 // Note that we are ignoring this->expr_type_ here. The thunk will
8106 // expect a closure whose second field has type this->expr_type_ (if
8107 // that is not NULL). We are going to pass it a closure whose
8108 // second field has type this->expr_->type(). Since
8109 // this->expr_type_ is only not-NULL for pointer types, we can get
8110 // away with this.
8111
8112 Struct_field_list* fields = new Struct_field_list();
8113 fields->push_back(Struct_field(Typed_identifier("fn",
8114 thunk->func_value()->type(),
8115 loc)));
8116 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8117 Struct_type* st = Type::make_struct_type(fields, loc);
8118 st->set_is_struct_incomparable();
8119
8120 Expression_list* vals = new Expression_list();
8121 vals->push_back(Expression::make_func_code_reference(thunk, loc));
8122 vals->push_back(val);
8123
8124 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8125 ret = Expression::make_heap_expression(ret, loc);
8126
8127 Node* node = Node::make_node(this);
8128 if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8129 ret->heap_expression()->set_allocate_on_stack();
8130 else if (gogo->compiling_runtime()
8131 && gogo->package_name() == "runtime"
8132 && !saw_errors())
8133 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8134 node->ast_format(gogo).c_str());
8135
8136 // If necessary, check whether the expression or any embedded
8137 // pointers are nil.
8138
8139 Expression* nil_check = NULL;
8140 if (this->method_->field_indexes() != NULL)
8141 {
8142 Expression* ref = expr;
8143 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8144 expr = ref;
8145 }
8146
8147 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8148 {
8149 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8150 Expression::make_nil(loc),
8151 loc);
8152 if (nil_check == NULL)
8153 nil_check = n;
8154 else
8155 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8156 }
8157
8158 if (nil_check != NULL)
8159 {
8160 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
8161 // Fix the type of the conditional expression by pretending to
8162 // evaluate to RET either way through the conditional.
8163 crash = Expression::make_compound(crash, ret, loc);
8164 ret = Expression::make_conditional(nil_check, crash, ret, loc);
8165 }
8166
8167 // RET is a pointer to a struct, but we want a function type.
8168 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8169
8170 return ret;
8171 }
8172
8173 // Dump ast representation of a bound method expression.
8174
8175 void
8176 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8177 const
8178 {
8179 if (this->expr_type_ != NULL)
8180 ast_dump_context->ostream() << "(";
8181 ast_dump_context->dump_expression(this->expr_);
8182 if (this->expr_type_ != NULL)
8183 {
8184 ast_dump_context->ostream() << ":";
8185 ast_dump_context->dump_type(this->expr_type_);
8186 ast_dump_context->ostream() << ")";
8187 }
8188
8189 ast_dump_context->ostream() << "." << this->function_->name();
8190 }
8191
8192 // Make a method expression.
8193
8194 Bound_method_expression*
8195 Expression::make_bound_method(Expression* expr, const Method* method,
8196 Named_object* function, Location location)
8197 {
8198 return new Bound_method_expression(expr, method, function, location);
8199 }
8200
8201 // Class Builtin_call_expression. This is used for a call to a
8202 // builtin function.
8203
8204 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
8205 Expression* fn,
8206 Expression_list* args,
8207 bool is_varargs,
8208 Location location)
8209 : Call_expression(fn, args, is_varargs, location),
8210 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
8211 recover_arg_is_set_(false)
8212 {
8213 Func_expression* fnexp = this->fn()->func_expression();
8214 if (fnexp == NULL)
8215 {
8216 this->code_ = BUILTIN_INVALID;
8217 return;
8218 }
8219 const std::string& name(fnexp->named_object()->name());
8220 if (name == "append")
8221 this->code_ = BUILTIN_APPEND;
8222 else if (name == "cap")
8223 this->code_ = BUILTIN_CAP;
8224 else if (name == "close")
8225 this->code_ = BUILTIN_CLOSE;
8226 else if (name == "complex")
8227 this->code_ = BUILTIN_COMPLEX;
8228 else if (name == "copy")
8229 this->code_ = BUILTIN_COPY;
8230 else if (name == "delete")
8231 this->code_ = BUILTIN_DELETE;
8232 else if (name == "imag")
8233 this->code_ = BUILTIN_IMAG;
8234 else if (name == "len")
8235 this->code_ = BUILTIN_LEN;
8236 else if (name == "make")
8237 this->code_ = BUILTIN_MAKE;
8238 else if (name == "new")
8239 this->code_ = BUILTIN_NEW;
8240 else if (name == "panic")
8241 this->code_ = BUILTIN_PANIC;
8242 else if (name == "print")
8243 this->code_ = BUILTIN_PRINT;
8244 else if (name == "println")
8245 this->code_ = BUILTIN_PRINTLN;
8246 else if (name == "real")
8247 this->code_ = BUILTIN_REAL;
8248 else if (name == "recover")
8249 this->code_ = BUILTIN_RECOVER;
8250 else if (name == "Alignof")
8251 this->code_ = BUILTIN_ALIGNOF;
8252 else if (name == "Offsetof")
8253 this->code_ = BUILTIN_OFFSETOF;
8254 else if (name == "Sizeof")
8255 this->code_ = BUILTIN_SIZEOF;
8256 else
8257 go_unreachable();
8258 }
8259
8260 // Return whether this is a call to recover. This is a virtual
8261 // function called from the parent class.
8262
8263 bool
8264 Builtin_call_expression::do_is_recover_call() const
8265 {
8266 if (this->classification() == EXPRESSION_ERROR)
8267 return false;
8268 return this->code_ == BUILTIN_RECOVER;
8269 }
8270
8271 // Set the argument for a call to recover.
8272
8273 void
8274 Builtin_call_expression::do_set_recover_arg(Expression* arg)
8275 {
8276 const Expression_list* args = this->args();
8277 go_assert(args == NULL || args->empty());
8278 Expression_list* new_args = new Expression_list();
8279 new_args->push_back(arg);
8280 this->set_args(new_args);
8281 this->recover_arg_is_set_ = true;
8282 }
8283
8284 // Lower a builtin call expression. This turns new and make into
8285 // specific expressions. We also convert to a constant if we can.
8286
8287 Expression*
8288 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
8289 Statement_inserter* inserter, int)
8290 {
8291 if (this->is_error_expression())
8292 return this;
8293
8294 Location loc = this->location();
8295
8296 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
8297 {
8298 this->report_error(_("invalid use of %<...%> with builtin function"));
8299 return Expression::make_error(loc);
8300 }
8301
8302 if (this->code_ == BUILTIN_OFFSETOF)
8303 {
8304 Expression* arg = this->one_arg();
8305
8306 if (arg->bound_method_expression() != NULL
8307 || arg->interface_field_reference_expression() != NULL)
8308 {
8309 this->report_error(_("invalid use of method value as argument "
8310 "of Offsetof"));
8311 return this;
8312 }
8313
8314 Field_reference_expression* farg = arg->field_reference_expression();
8315 while (farg != NULL)
8316 {
8317 if (!farg->implicit())
8318 break;
8319 // When the selector refers to an embedded field,
8320 // it must not be reached through pointer indirections.
8321 if (farg->expr()->deref() != farg->expr())
8322 {
8323 this->report_error(_("argument of Offsetof implies "
8324 "indirection of an embedded field"));
8325 return this;
8326 }
8327 // Go up until we reach the original base.
8328 farg = farg->expr()->field_reference_expression();
8329 }
8330 }
8331
8332 if (this->is_constant())
8333 {
8334 Numeric_constant nc;
8335 if (this->numeric_constant_value(&nc))
8336 return nc.expression(loc);
8337 }
8338
8339 switch (this->code_)
8340 {
8341 default:
8342 break;
8343
8344 case BUILTIN_NEW:
8345 {
8346 const Expression_list* args = this->args();
8347 if (args == NULL || args->size() < 1)
8348 this->report_error(_("not enough arguments"));
8349 else if (args->size() > 1)
8350 this->report_error(_("too many arguments"));
8351 else
8352 {
8353 Expression* arg = args->front();
8354 if (!arg->is_type_expression())
8355 {
8356 go_error_at(arg->location(), "expected type");
8357 this->set_is_error();
8358 }
8359 else
8360 return Expression::make_allocation(arg->type(), loc);
8361 }
8362 }
8363 break;
8364
8365 case BUILTIN_MAKE:
8366 return this->lower_make(inserter);
8367
8368 case BUILTIN_RECOVER:
8369 if (function != NULL)
8370 function->func_value()->set_calls_recover();
8371 else
8372 {
8373 // Calling recover outside of a function always returns the
8374 // nil empty interface.
8375 Type* eface = Type::make_empty_interface_type(loc);
8376 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
8377 }
8378 break;
8379
8380 case BUILTIN_DELETE:
8381 {
8382 const Expression_list* args = this->args();
8383 if (args == NULL || args->size() < 2)
8384 this->report_error(_("not enough arguments"));
8385 else if (args->size() > 2)
8386 this->report_error(_("too many arguments"));
8387 else if (args->front()->type()->map_type() == NULL)
8388 this->report_error(_("argument 1 must be a map"));
8389 else
8390 {
8391 Type* key_type =
8392 args->front()->type()->map_type()->key_type();
8393 Expression_list::iterator pa = this->args()->begin();
8394 pa++;
8395 Type* arg_type = (*pa)->type();
8396 std::string reason;
8397 if (!Type::are_assignable(key_type, arg_type, &reason))
8398 {
8399 if (reason.empty())
8400 go_error_at(loc, "argument 2 has incompatible type");
8401 else
8402 go_error_at(loc, "argument 2 has incompatible type (%s)",
8403 reason.c_str());
8404 this->set_is_error();
8405 }
8406 else if (!Type::are_identical(key_type, arg_type, 0, NULL))
8407 *pa = Expression::make_cast(key_type, *pa, loc);
8408 }
8409 }
8410 break;
8411
8412 case BUILTIN_PRINT:
8413 case BUILTIN_PRINTLN:
8414 // Force all the arguments into temporary variables, so that we
8415 // don't try to evaluate something while holding the print lock.
8416 if (this->args() == NULL)
8417 break;
8418 for (Expression_list::iterator pa = this->args()->begin();
8419 pa != this->args()->end();
8420 ++pa)
8421 {
8422 if (!(*pa)->is_variable() && !(*pa)->is_constant())
8423 {
8424 Temporary_statement* temp =
8425 Statement::make_temporary(NULL, *pa, loc);
8426 inserter->insert(temp);
8427 *pa = Expression::make_temporary_reference(temp, loc);
8428 }
8429 }
8430 break;
8431 }
8432
8433 return this;
8434 }
8435
8436 // Flatten a builtin call expression. This turns the arguments of some
8437 // builtin calls into temporary expressions. Also expand copy and append
8438 // to runtime calls.
8439
8440 Expression*
8441 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
8442 Statement_inserter* inserter)
8443 {
8444 if (this->is_error_expression())
8445 {
8446 go_assert(saw_errors());
8447 return this;
8448 }
8449
8450 Location loc = this->location();
8451
8452 switch (this->code_)
8453 {
8454 default:
8455 break;
8456
8457 case BUILTIN_APPEND:
8458 return this->flatten_append(gogo, function, inserter, NULL, NULL);
8459
8460 case BUILTIN_COPY:
8461 {
8462 Type* at = this->args()->front()->type();
8463 for (Expression_list::iterator pa = this->args()->begin();
8464 pa != this->args()->end();
8465 ++pa)
8466 {
8467 if ((*pa)->is_nil_expression())
8468 {
8469 Expression* nil = Expression::make_nil(loc);
8470 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
8471 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
8472 }
8473 if (!(*pa)->is_variable())
8474 {
8475 Temporary_statement* temp =
8476 Statement::make_temporary(NULL, *pa, loc);
8477 inserter->insert(temp);
8478 *pa = Expression::make_temporary_reference(temp, loc);
8479 }
8480 }
8481
8482 // Lower to runtime call.
8483 const Expression_list* args = this->args();
8484 go_assert(args != NULL && args->size() == 2);
8485 Expression* arg1 = args->front();
8486 Expression* arg2 = args->back();
8487 go_assert(arg1->is_variable());
8488 go_assert(arg2->is_variable());
8489 bool arg2_is_string = arg2->type()->is_string_type();
8490
8491 Expression* ret;
8492 Type* et = at->array_type()->element_type();
8493 if (et->has_pointer())
8494 {
8495 Expression* td = Expression::make_type_descriptor(et, loc);
8496 Expression* pd =
8497 Expression::make_slice_info(arg1, SLICE_INFO_VALUE_POINTER, loc);
8498 Expression* ld =
8499 Expression::make_slice_info(arg1, SLICE_INFO_LENGTH, loc);
8500 Expression* ps =
8501 Expression::make_slice_info(arg2, SLICE_INFO_VALUE_POINTER, loc);
8502 Expression* ls =
8503 Expression::make_slice_info(arg2, SLICE_INFO_LENGTH, loc);
8504 ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
8505 5, td, pd, ld, ps, ls);
8506 }
8507 else
8508 {
8509 Type* int_type = Type::lookup_integer_type("int");
8510 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8511
8512 // l1 = len(arg1)
8513 Named_object* lenfn = gogo->lookup_global("len");
8514 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8515 Expression_list* len_args = new Expression_list();
8516 len_args->push_back(arg1->copy());
8517 Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
8518 gogo->lower_expression(function, inserter, &len1);
8519 gogo->flatten_expression(function, inserter, &len1);
8520 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
8521 inserter->insert(l1tmp);
8522
8523 // l2 = len(arg2)
8524 len_args = new Expression_list();
8525 len_args->push_back(arg2->copy());
8526 Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
8527 gogo->lower_expression(function, inserter, &len2);
8528 gogo->flatten_expression(function, inserter, &len2);
8529 Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
8530 inserter->insert(l2tmp);
8531
8532 // n = (l1 < l2 ? l1 : l2)
8533 Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
8534 Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
8535 Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
8536 Expression* n = Expression::make_conditional(cond,
8537 l1ref->copy(),
8538 l2ref->copy(),
8539 loc);
8540 Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
8541 inserter->insert(ntmp);
8542
8543 // sz = n * sizeof(elem_type)
8544 Expression* nref = Expression::make_temporary_reference(ntmp, loc);
8545 nref = Expression::make_cast(uintptr_type, nref, loc);
8546 Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
8547 sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
8548
8549 // memmove(arg1.ptr, arg2.ptr, sz)
8550 Expression* p1 = Expression::make_slice_info(arg1,
8551 SLICE_INFO_VALUE_POINTER,
8552 loc);
8553 Expression* p2 = (arg2_is_string
8554 ? Expression::make_string_info(arg2,
8555 STRING_INFO_DATA,
8556 loc)
8557 : Expression::make_slice_info(arg2,
8558 SLICE_INFO_VALUE_POINTER,
8559 loc));
8560 Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
8561 p1, p2, sz);
8562
8563 // n is the return value of copy
8564 nref = Expression::make_temporary_reference(ntmp, loc);
8565 ret = Expression::make_compound(call, nref, loc);
8566 }
8567 return ret;
8568 }
8569 break;
8570
8571 case BUILTIN_PANIC:
8572 for (Expression_list::iterator pa = this->args()->begin();
8573 pa != this->args()->end();
8574 ++pa)
8575 {
8576 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
8577 {
8578 Temporary_statement* temp =
8579 Statement::make_temporary(NULL, *pa, loc);
8580 inserter->insert(temp);
8581 *pa = Expression::make_temporary_reference(temp, loc);
8582 }
8583 }
8584 break;
8585
8586 case BUILTIN_LEN:
8587 case BUILTIN_CAP:
8588 {
8589 Expression_list::iterator pa = this->args()->begin();
8590 if (!(*pa)->is_variable()
8591 && ((*pa)->type()->map_type() != NULL
8592 || (*pa)->type()->channel_type() != NULL))
8593 {
8594 Temporary_statement* temp =
8595 Statement::make_temporary(NULL, *pa, loc);
8596 inserter->insert(temp);
8597 *pa = Expression::make_temporary_reference(temp, loc);
8598 }
8599 }
8600 break;
8601
8602 case BUILTIN_DELETE:
8603 {
8604 // Lower to a runtime function call.
8605 const Expression_list* args = this->args();
8606
8607 // Since this function returns no value it must appear in
8608 // a statement by itself, so we don't have to worry about
8609 // order of evaluation of values around it. Evaluate the
8610 // map first to get order of evaluation right.
8611 Map_type* mt = args->front()->type()->map_type();
8612 Temporary_statement* map_temp =
8613 Statement::make_temporary(mt, args->front(), loc);
8614 inserter->insert(map_temp);
8615
8616 Temporary_statement* key_temp =
8617 Statement::make_temporary(mt->key_type(), args->back(), loc);
8618 inserter->insert(key_temp);
8619
8620 Expression* e1 = Expression::make_type_descriptor(mt, loc);
8621 Expression* e2 = Expression::make_temporary_reference(map_temp,
8622 loc);
8623 Expression* e3 = Expression::make_temporary_reference(key_temp,
8624 loc);
8625
8626 Runtime::Function code;
8627 switch (mt->algorithm(gogo))
8628 {
8629 case Map_type::MAP_ALG_FAST32:
8630 case Map_type::MAP_ALG_FAST32PTR:
8631 {
8632 code = Runtime::MAPDELETE_FAST32;
8633 Type* uint32_type = Type::lookup_integer_type("uint32");
8634 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
8635 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8636 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
8637 loc);
8638 e3 = Expression::make_dereference(e3,
8639 Expression::NIL_CHECK_NOT_NEEDED,
8640 loc);
8641 break;
8642 }
8643 case Map_type::MAP_ALG_FAST64:
8644 case Map_type::MAP_ALG_FAST64PTR:
8645 {
8646 code = Runtime::MAPDELETE_FAST64;
8647 Type* uint64_type = Type::lookup_integer_type("uint64");
8648 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
8649 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8650 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
8651 loc);
8652 e3 = Expression::make_dereference(e3,
8653 Expression::NIL_CHECK_NOT_NEEDED,
8654 loc);
8655 break;
8656 }
8657 case Map_type::MAP_ALG_FASTSTR:
8658 code = Runtime::MAPDELETE_FASTSTR;
8659 break;
8660 default:
8661 code = Runtime::MAPDELETE;
8662
8663 // If the call to delete is deferred, and is in a loop,
8664 // then the loop will only have a single instance of the
8665 // temporary variable. Passing the address of the
8666 // temporary variable here means that the deferred call
8667 // will see the last value in the loop, not the current
8668 // value. So for this unusual case copy the value into
8669 // the heap.
8670 if (!this->is_deferred())
8671 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8672 else
8673 {
8674 Expression* a = Expression::make_allocation(mt->key_type(),
8675 loc);
8676 Temporary_statement* atemp =
8677 Statement::make_temporary(NULL, a, loc);
8678 inserter->insert(atemp);
8679
8680 a = Expression::make_temporary_reference(atemp, loc);
8681 a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
8682 Statement* s = Statement::make_assignment(a, e3, loc);
8683 inserter->insert(s);
8684
8685 e3 = Expression::make_temporary_reference(atemp, loc);
8686 }
8687 }
8688
8689 return Runtime::make_call(code, loc, 3, e1, e2, e3);
8690 }
8691 }
8692
8693 return this;
8694 }
8695
8696 // Lower a make expression.
8697
8698 Expression*
8699 Builtin_call_expression::lower_make(Statement_inserter* inserter)
8700 {
8701 Location loc = this->location();
8702
8703 const Expression_list* args = this->args();
8704 if (args == NULL || args->size() < 1)
8705 {
8706 this->report_error(_("not enough arguments"));
8707 return Expression::make_error(this->location());
8708 }
8709
8710 Expression_list::const_iterator parg = args->begin();
8711
8712 Expression* first_arg = *parg;
8713 if (!first_arg->is_type_expression())
8714 {
8715 go_error_at(first_arg->location(), "expected type");
8716 this->set_is_error();
8717 return Expression::make_error(this->location());
8718 }
8719 Type* type = first_arg->type();
8720
8721 if (!type->in_heap())
8722 go_error_at(first_arg->location(),
8723 "cannot make slice of go:notinheap type");
8724
8725 bool is_slice = false;
8726 bool is_map = false;
8727 bool is_chan = false;
8728 if (type->is_slice_type())
8729 is_slice = true;
8730 else if (type->map_type() != NULL)
8731 is_map = true;
8732 else if (type->channel_type() != NULL)
8733 is_chan = true;
8734 else
8735 {
8736 this->report_error(_("invalid type for make function"));
8737 return Expression::make_error(this->location());
8738 }
8739
8740 Type_context int_context(Type::lookup_integer_type("int"), false);
8741
8742 ++parg;
8743 Expression* len_arg;
8744 bool len_small = false;
8745 if (parg == args->end())
8746 {
8747 if (is_slice)
8748 {
8749 this->report_error(_("length required when allocating a slice"));
8750 return Expression::make_error(this->location());
8751 }
8752 len_arg = Expression::make_integer_ul(0, NULL, loc);
8753 len_small = true;
8754 }
8755 else
8756 {
8757 len_arg = *parg;
8758 len_arg->determine_type(&int_context);
8759 if (len_arg->type()->integer_type() == NULL)
8760 {
8761 go_error_at(len_arg->location(), "non-integer len argument in make");
8762 return Expression::make_error(this->location());
8763 }
8764 if (!this->check_int_value(len_arg, true, &len_small))
8765 return Expression::make_error(this->location());
8766 ++parg;
8767 }
8768
8769 Expression* cap_arg = NULL;
8770 bool cap_small = false;
8771 Numeric_constant nclen;
8772 Numeric_constant nccap;
8773 unsigned long vlen;
8774 unsigned long vcap;
8775 if (is_slice && parg != args->end())
8776 {
8777 cap_arg = *parg;
8778 cap_arg->determine_type(&int_context);
8779 if (cap_arg->type()->integer_type() == NULL)
8780 {
8781 go_error_at(cap_arg->location(), "non-integer cap argument in make");
8782 return Expression::make_error(this->location());
8783 }
8784 if (!this->check_int_value(cap_arg, false, &cap_small))
8785 return Expression::make_error(this->location());
8786
8787 if (len_arg->numeric_constant_value(&nclen)
8788 && cap_arg->numeric_constant_value(&nccap)
8789 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8790 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
8791 && vlen > vcap)
8792 {
8793 this->report_error(_("len larger than cap"));
8794 return Expression::make_error(this->location());
8795 }
8796
8797 ++parg;
8798 }
8799
8800 if (parg != args->end())
8801 {
8802 this->report_error(_("too many arguments to make"));
8803 return Expression::make_error(this->location());
8804 }
8805
8806 Location type_loc = first_arg->location();
8807
8808 Expression* call;
8809 if (is_slice)
8810 {
8811 Temporary_statement* len_temp = NULL;
8812 if (!len_arg->is_constant())
8813 {
8814 len_temp = Statement::make_temporary(NULL, len_arg, loc);
8815 inserter->insert(len_temp);
8816 len_arg = Expression::make_temporary_reference(len_temp, loc);
8817 }
8818
8819 if (cap_arg == NULL)
8820 {
8821 cap_small = len_small;
8822 if (len_temp == NULL)
8823 cap_arg = len_arg->copy();
8824 else
8825 cap_arg = Expression::make_temporary_reference(len_temp, loc);
8826 }
8827 else if (!cap_arg->is_constant())
8828 {
8829 Temporary_statement* cap_temp = Statement::make_temporary(NULL,
8830 cap_arg,
8831 loc);
8832 inserter->insert(cap_temp);
8833 cap_arg = Expression::make_temporary_reference(cap_temp, loc);
8834 }
8835
8836 Type* et = type->array_type()->element_type();
8837 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
8838 Runtime::Function code = Runtime::MAKESLICE;
8839 if (!len_small || !cap_small)
8840 code = Runtime::MAKESLICE64;
8841 Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
8842 cap_arg);
8843 mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
8844 loc);
8845 Type* int_type = Type::lookup_integer_type("int");
8846 len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
8847 cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
8848 call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
8849 }
8850 else if (is_map)
8851 {
8852 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8853 if (!len_small)
8854 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
8855 len_arg,
8856 Expression::make_nil(loc));
8857 else
8858 {
8859 if (len_arg->numeric_constant_value(&nclen)
8860 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8861 && vlen <= Map_type::bucket_size)
8862 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
8863 else
8864 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
8865 len_arg,
8866 Expression::make_nil(loc));
8867 }
8868 }
8869 else if (is_chan)
8870 {
8871 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8872 Runtime::Function code = Runtime::MAKECHAN;
8873 if (!len_small)
8874 code = Runtime::MAKECHAN64;
8875 call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
8876 }
8877 else
8878 go_unreachable();
8879
8880 return Expression::make_unsafe_cast(type, call, loc);
8881 }
8882
8883 // Flatten a call to the predeclared append function. We do this in
8884 // the flatten phase, not the lowering phase, so that we run after
8885 // type checking and after order_evaluations. If ASSIGN_LHS is not
8886 // NULL, this append is the right-hand-side of an assignment and
8887 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
8888 // rather than returning a slice. This lets us omit a write barrier
8889 // in common cases like a = append(a, ...) when the slice does not
8890 // need to grow. ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
8891
8892 Expression*
8893 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
8894 Statement_inserter* inserter,
8895 Expression* assign_lhs,
8896 Block* enclosing)
8897 {
8898 if (this->is_error_expression())
8899 return this;
8900
8901 Location loc = this->location();
8902
8903 const Expression_list* args = this->args();
8904 go_assert(args != NULL && !args->empty());
8905
8906 Type* slice_type = args->front()->type();
8907 go_assert(slice_type->is_slice_type());
8908 Type* element_type = slice_type->array_type()->element_type();
8909
8910 if (args->size() == 1)
8911 {
8912 // append(s) evaluates to s.
8913 if (assign_lhs != NULL)
8914 return NULL;
8915 return args->front();
8916 }
8917
8918 Type* int_type = Type::lookup_integer_type("int");
8919 Type* uint_type = Type::lookup_integer_type("uint");
8920
8921 // Implementing
8922 // append(s1, s2...)
8923 // or
8924 // append(s1, a1, a2, a3, ...)
8925
8926 // s1tmp := s1
8927 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
8928 loc);
8929 inserter->insert(s1tmp);
8930
8931 // l1tmp := len(s1tmp)
8932 Named_object* lenfn = gogo->lookup_global("len");
8933 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8934 Expression_list* call_args = new Expression_list();
8935 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8936 Expression* len = Expression::make_call(lenref, call_args, false, loc);
8937 gogo->lower_expression(function, inserter, &len);
8938 gogo->flatten_expression(function, inserter, &len);
8939 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
8940 inserter->insert(l1tmp);
8941
8942 Temporary_statement* s2tmp = NULL;
8943 Temporary_statement* l2tmp = NULL;
8944 Expression_list* add = NULL;
8945 Expression* len2;
8946 Call_expression* makecall = NULL;
8947 if (this->is_varargs())
8948 {
8949 go_assert(args->size() == 2);
8950
8951 std::pair<Call_expression*, Temporary_statement*> p =
8952 Expression::find_makeslice_call(args->back());
8953 makecall = p.first;
8954 if (makecall != NULL)
8955 {
8956 // We are handling
8957 // append(s, make([]T, len[, cap])...))
8958 // which has already been lowered to
8959 // append(s, runtime.makeslice(T, len, cap)).
8960 // We will optimize this to directly zeroing the tail,
8961 // instead of allocating a new slice then copy.
8962
8963 // Retrieve the length and capacity. Cannot reference s2 as
8964 // we will remove the makeslice call.
8965 Expression* len_arg = makecall->args()->at(1);
8966 len_arg = Expression::make_cast(int_type, len_arg, loc);
8967 l2tmp = Statement::make_temporary(int_type, len_arg, loc);
8968 inserter->insert(l2tmp);
8969
8970 Expression* cap_arg = makecall->args()->at(2);
8971 cap_arg = Expression::make_cast(int_type, cap_arg, loc);
8972 Temporary_statement* c2tmp =
8973 Statement::make_temporary(int_type, cap_arg, loc);
8974 inserter->insert(c2tmp);
8975
8976 // Check bad len/cap here.
8977 // checkmakeslice(type, len, cap)
8978 // (Note that if len and cap are constants, we won't see a
8979 // makeslice call here, as it will be rewritten to a stack
8980 // allocated array by Mark_address_taken::expression.)
8981 Expression* elem = Expression::make_type_descriptor(element_type,
8982 loc);
8983 len2 = Expression::make_temporary_reference(l2tmp, loc);
8984 Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
8985 Expression* check = Runtime::make_call(Runtime::CHECK_MAKE_SLICE,
8986 loc, 3, elem, len2, cap2);
8987 gogo->lower_expression(function, inserter, &check);
8988 gogo->flatten_expression(function, inserter, &check);
8989 Statement* s = Statement::make_statement(check, false);
8990 inserter->insert(s);
8991
8992 // Remove the original makeslice call.
8993 Temporary_statement* ts = p.second;
8994 if (ts != NULL && ts->uses() == 1)
8995 ts->set_init(Expression::make_nil(loc));
8996 }
8997 else
8998 {
8999 // s2tmp := s2
9000 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
9001 inserter->insert(s2tmp);
9002
9003 // l2tmp := len(s2tmp)
9004 lenref = Expression::make_func_reference(lenfn, NULL, loc);
9005 call_args = new Expression_list();
9006 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
9007 len = Expression::make_call(lenref, call_args, false, loc);
9008 gogo->lower_expression(function, inserter, &len);
9009 gogo->flatten_expression(function, inserter, &len);
9010 l2tmp = Statement::make_temporary(int_type, len, loc);
9011 inserter->insert(l2tmp);
9012 }
9013
9014 // len2 = l2tmp
9015 len2 = Expression::make_temporary_reference(l2tmp, loc);
9016 }
9017 else
9018 {
9019 // We have to ensure that all the arguments are in variables
9020 // now, because otherwise if one of them is an index expression
9021 // into the current slice we could overwrite it before we fetch
9022 // it.
9023 add = new Expression_list();
9024 Expression_list::const_iterator pa = args->begin();
9025 for (++pa; pa != args->end(); ++pa)
9026 {
9027 if ((*pa)->is_variable())
9028 add->push_back(*pa);
9029 else
9030 {
9031 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
9032 loc);
9033 inserter->insert(tmp);
9034 add->push_back(Expression::make_temporary_reference(tmp, loc));
9035 }
9036 }
9037
9038 // len2 = len(add)
9039 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
9040 }
9041
9042 // ntmp := l1tmp + len2
9043 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
9044 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
9045 gogo->lower_expression(function, inserter, &sum);
9046 gogo->flatten_expression(function, inserter, &sum);
9047 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
9048 inserter->insert(ntmp);
9049
9050 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
9051 // growslice(type, s1tmp, ntmp) :
9052 // s1tmp[:ntmp]
9053 // Using uint here means that if the computation of ntmp overflowed,
9054 // we will call growslice which will panic.
9055
9056 Named_object* capfn = gogo->lookup_global("cap");
9057 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
9058 call_args = new Expression_list();
9059 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
9060 Expression* cap = Expression::make_call(capref, call_args, false, loc);
9061 gogo->lower_expression(function, inserter, &cap);
9062 gogo->flatten_expression(function, inserter, &cap);
9063 Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
9064 inserter->insert(c1tmp);
9065
9066 Expression* left = Expression::make_temporary_reference(ntmp, loc);
9067 left = Expression::make_cast(uint_type, left, loc);
9068 Expression* right = Expression::make_temporary_reference(c1tmp, loc);
9069 right = Expression::make_cast(uint_type, right, loc);
9070
9071 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
9072
9073 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
9074 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
9075 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
9076 a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
9077 a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
9078 Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
9079 Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
9080 Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
9081 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
9082 a1, a2, a3, a4, a5);
9083 call = Expression::make_unsafe_cast(slice_type, call, loc);
9084
9085 ref = Expression::make_temporary_reference(s1tmp, loc);
9086 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
9087 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
9088 ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
9089 ref->array_index_expression()->set_needs_bounds_check(false);
9090
9091 if (assign_lhs == NULL)
9092 {
9093 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
9094
9095 gogo->lower_expression(function, inserter, &rhs);
9096 gogo->flatten_expression(function, inserter, &rhs);
9097
9098 ref = Expression::make_temporary_reference(s1tmp, loc);
9099 Statement* assign = Statement::make_assignment(ref, rhs, loc);
9100 inserter->insert(assign);
9101 }
9102 else
9103 {
9104 gogo->lower_expression(function, inserter, &cond);
9105 gogo->flatten_expression(function, inserter, &cond);
9106 gogo->lower_expression(function, inserter, &call);
9107 gogo->flatten_expression(function, inserter, &call);
9108 gogo->lower_expression(function, inserter, &ref);
9109 gogo->flatten_expression(function, inserter, &ref);
9110
9111 Block* then_block = new Block(enclosing, loc);
9112 Assignment_statement* assign =
9113 Statement::make_assignment(assign_lhs, call, loc);
9114 then_block->add_statement(assign);
9115
9116 Block* else_block = new Block(enclosing, loc);
9117 assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
9118 // This assignment will not change the pointer value, so it does
9119 // not need a write barrier.
9120 assign->set_omit_write_barrier();
9121 else_block->add_statement(assign);
9122
9123 Statement* s = Statement::make_if_statement(cond, then_block,
9124 else_block, loc);
9125 inserter->insert(s);
9126
9127 ref = Expression::make_temporary_reference(s1tmp, loc);
9128 assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
9129 inserter->insert(assign);
9130 }
9131
9132 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9133
9134 if (this->is_varargs())
9135 {
9136 if (makecall != NULL)
9137 {
9138 // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
9139 a1 = Expression::make_temporary_reference(s1tmp, loc);
9140 ref = Expression::make_temporary_reference(l1tmp, loc);
9141 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9142 a1->array_index_expression()->set_needs_bounds_check(false);
9143 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9144
9145 ref = Expression::make_temporary_reference(l2tmp, loc);
9146 ref = Expression::make_cast(uintptr_type, ref, loc);
9147 a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9148 a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
9149
9150 if (element_type->has_pointer())
9151 call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
9152 else
9153 {
9154 Type* int32_type = Type::lookup_integer_type("int32");
9155 zero = Expression::make_integer_ul(0, int32_type, loc);
9156 call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
9157 zero, a2);
9158 }
9159
9160 if (element_type->has_pointer())
9161 {
9162 // For a slice containing pointers, growslice already zeroed
9163 // the memory. We only need to zero in non-growing case.
9164 // Note: growslice does not zero the memory in non-pointer case.
9165 ref = Expression::make_temporary_reference(ntmp, loc);
9166 ref = Expression::make_cast(uint_type, ref, loc);
9167 ref2 = Expression::make_temporary_reference(c1tmp, loc);
9168 ref2 = Expression::make_cast(uint_type, ref2, loc);
9169 cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
9170 zero = Expression::make_integer_ul(0, int_type, loc);
9171 call = Expression::make_conditional(cond, call, zero, loc);
9172 }
9173 }
9174 else
9175 {
9176 if (element_type->has_pointer())
9177 {
9178 // copy(s1tmp[l1tmp:], s2tmp)
9179 a1 = Expression::make_temporary_reference(s1tmp, loc);
9180 ref = Expression::make_temporary_reference(l1tmp, loc);
9181 Expression* nil = Expression::make_nil(loc);
9182 a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
9183 a1->array_index_expression()->set_needs_bounds_check(false);
9184
9185 a2 = Expression::make_temporary_reference(s2tmp, loc);
9186
9187 Named_object* copyfn = gogo->lookup_global("copy");
9188 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
9189 call_args = new Expression_list();
9190 call_args->push_back(a1);
9191 call_args->push_back(a2);
9192 call = Expression::make_call(copyref, call_args, false, loc);
9193 }
9194 else
9195 {
9196 // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
9197 a1 = Expression::make_temporary_reference(s1tmp, loc);
9198 ref = Expression::make_temporary_reference(l1tmp, loc);
9199 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9200 a1->array_index_expression()->set_needs_bounds_check(false);
9201 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9202
9203 a2 = Expression::make_temporary_reference(s2tmp, loc);
9204 a2 = (a2->type()->is_string_type()
9205 ? Expression::make_string_info(a2,
9206 STRING_INFO_DATA,
9207 loc)
9208 : Expression::make_slice_info(a2,
9209 SLICE_INFO_VALUE_POINTER,
9210 loc));
9211
9212 ref = Expression::make_temporary_reference(l2tmp, loc);
9213 ref = Expression::make_cast(uintptr_type, ref, loc);
9214 a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9215 a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
9216
9217 call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
9218 a1, a2, a3);
9219 }
9220 }
9221 gogo->lower_expression(function, inserter, &call);
9222 gogo->flatten_expression(function, inserter, &call);
9223 inserter->insert(Statement::make_statement(call, false));
9224 }
9225 else
9226 {
9227 // For each argument:
9228 // s1tmp[l1tmp+i] = a
9229 unsigned long i = 0;
9230 for (Expression_list::const_iterator pa = add->begin();
9231 pa != add->end();
9232 ++pa, ++i)
9233 {
9234 ref = Expression::make_temporary_reference(s1tmp, loc);
9235 ref2 = Expression::make_temporary_reference(l1tmp, loc);
9236 Expression* off = Expression::make_integer_ul(i, int_type, loc);
9237 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
9238 Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
9239 NULL, loc);
9240 lhs->array_index_expression()->set_needs_bounds_check(false);
9241 gogo->lower_expression(function, inserter, &lhs);
9242 gogo->flatten_expression(function, inserter, &lhs);
9243 Expression* elem = *pa;
9244 if (!Type::are_identical(element_type, elem->type(), 0, NULL)
9245 && element_type->interface_type() != NULL)
9246 elem = Expression::make_cast(element_type, elem, loc);
9247 // The flatten pass runs after the write barrier pass, so we
9248 // need to insert a write barrier here if necessary.
9249 // However, if ASSIGN_LHS is not NULL, we have been called
9250 // directly before the write barrier pass.
9251 Statement* assign;
9252 if (assign_lhs != NULL
9253 || !gogo->assign_needs_write_barrier(lhs, NULL))
9254 assign = Statement::make_assignment(lhs, elem, loc);
9255 else
9256 {
9257 Function* f = function == NULL ? NULL : function->func_value();
9258 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
9259 lhs, elem, loc);
9260 }
9261 inserter->insert(assign);
9262 }
9263 }
9264
9265 if (assign_lhs != NULL)
9266 return NULL;
9267
9268 return Expression::make_temporary_reference(s1tmp, loc);
9269 }
9270
9271 // Return whether an expression has an integer value. Report an error
9272 // if not. This is used when handling calls to the predeclared make
9273 // function. Set *SMALL if the value is known to fit in type "int".
9274
9275 bool
9276 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
9277 bool *small)
9278 {
9279 *small = false;
9280
9281 Numeric_constant nc;
9282 if (e->numeric_constant_value(&nc))
9283 {
9284 unsigned long v;
9285 switch (nc.to_unsigned_long(&v))
9286 {
9287 case Numeric_constant::NC_UL_VALID:
9288 break;
9289 case Numeric_constant::NC_UL_NOTINT:
9290 go_error_at(e->location(), "non-integer %s argument to make",
9291 is_length ? "len" : "cap");
9292 return false;
9293 case Numeric_constant::NC_UL_NEGATIVE:
9294 go_error_at(e->location(), "negative %s argument to make",
9295 is_length ? "len" : "cap");
9296 return false;
9297 case Numeric_constant::NC_UL_BIG:
9298 // We don't want to give a compile-time error for a 64-bit
9299 // value on a 32-bit target.
9300 break;
9301 }
9302
9303 mpz_t val;
9304 if (!nc.to_int(&val))
9305 go_unreachable();
9306 int bits = mpz_sizeinbase(val, 2);
9307 mpz_clear(val);
9308 Type* int_type = Type::lookup_integer_type("int");
9309 if (bits >= int_type->integer_type()->bits())
9310 {
9311 go_error_at(e->location(), "%s argument too large for make",
9312 is_length ? "len" : "cap");
9313 return false;
9314 }
9315
9316 *small = true;
9317 return true;
9318 }
9319
9320 if (e->type()->integer_type() != NULL)
9321 {
9322 int ebits = e->type()->integer_type()->bits();
9323 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
9324
9325 // We can treat ebits == intbits as small even for an unsigned
9326 // integer type, because we will convert the value to int and
9327 // then reject it in the runtime if it is negative.
9328 *small = ebits <= intbits;
9329
9330 return true;
9331 }
9332
9333 go_error_at(e->location(), "non-integer %s argument to make",
9334 is_length ? "len" : "cap");
9335 return false;
9336 }
9337
9338 // Return the type of the real or imag functions, given the type of
9339 // the argument. We need to map complex64 to float32 and complex128
9340 // to float64, so it has to be done by name. This returns NULL if it
9341 // can't figure out the type.
9342
9343 Type*
9344 Builtin_call_expression::real_imag_type(Type* arg_type)
9345 {
9346 if (arg_type == NULL || arg_type->is_abstract())
9347 return NULL;
9348 Named_type* nt = arg_type->named_type();
9349 if (nt == NULL)
9350 return NULL;
9351 while (nt->real_type()->named_type() != NULL)
9352 nt = nt->real_type()->named_type();
9353 if (nt->name() == "complex64")
9354 return Type::lookup_float_type("float32");
9355 else if (nt->name() == "complex128")
9356 return Type::lookup_float_type("float64");
9357 else
9358 return NULL;
9359 }
9360
9361 // Return the type of the complex function, given the type of one of the
9362 // argments. Like real_imag_type, we have to map by name.
9363
9364 Type*
9365 Builtin_call_expression::complex_type(Type* arg_type)
9366 {
9367 if (arg_type == NULL || arg_type->is_abstract())
9368 return NULL;
9369 Named_type* nt = arg_type->named_type();
9370 if (nt == NULL)
9371 return NULL;
9372 while (nt->real_type()->named_type() != NULL)
9373 nt = nt->real_type()->named_type();
9374 if (nt->name() == "float32")
9375 return Type::lookup_complex_type("complex64");
9376 else if (nt->name() == "float64")
9377 return Type::lookup_complex_type("complex128");
9378 else
9379 return NULL;
9380 }
9381
9382 // Return a single argument, or NULL if there isn't one.
9383
9384 Expression*
9385 Builtin_call_expression::one_arg() const
9386 {
9387 const Expression_list* args = this->args();
9388 if (args == NULL || args->size() != 1)
9389 return NULL;
9390 return args->front();
9391 }
9392
9393 // A traversal class which looks for a call or receive expression.
9394
9395 class Find_call_expression : public Traverse
9396 {
9397 public:
9398 Find_call_expression()
9399 : Traverse(traverse_expressions),
9400 found_(false)
9401 { }
9402
9403 int
9404 expression(Expression**);
9405
9406 bool
9407 found()
9408 { return this->found_; }
9409
9410 private:
9411 bool found_;
9412 };
9413
9414 int
9415 Find_call_expression::expression(Expression** pexpr)
9416 {
9417 Expression* expr = *pexpr;
9418 if (!expr->is_constant()
9419 && (expr->call_expression() != NULL
9420 || expr->receive_expression() != NULL))
9421 {
9422 this->found_ = true;
9423 return TRAVERSE_EXIT;
9424 }
9425 return TRAVERSE_CONTINUE;
9426 }
9427
9428 // Return whether calling len or cap on EXPR, of array type, is a
9429 // constant. The language spec says "the expressions len(s) and
9430 // cap(s) are constants if the type of s is an array or pointer to an
9431 // array and the expression s does not contain channel receives or
9432 // (non-constant) function calls."
9433
9434 bool
9435 Builtin_call_expression::array_len_is_constant(Expression* expr)
9436 {
9437 go_assert(expr->type()->deref()->array_type() != NULL
9438 && !expr->type()->deref()->is_slice_type());
9439 if (expr->is_constant())
9440 return true;
9441 Find_call_expression find_call;
9442 Expression::traverse(&expr, &find_call);
9443 return !find_call.found();
9444 }
9445
9446 // Return whether this is constant: len of a string constant, or len
9447 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
9448 // unsafe.Alignof.
9449
9450 bool
9451 Builtin_call_expression::do_is_constant() const
9452 {
9453 if (this->is_error_expression())
9454 return true;
9455 switch (this->code_)
9456 {
9457 case BUILTIN_LEN:
9458 case BUILTIN_CAP:
9459 {
9460 if (this->seen_)
9461 return false;
9462
9463 Expression* arg = this->one_arg();
9464 if (arg == NULL)
9465 return false;
9466 Type* arg_type = arg->type();
9467 if (arg_type->is_error())
9468 return true;
9469
9470 if (arg_type->points_to() != NULL
9471 && arg_type->points_to()->array_type() != NULL
9472 && !arg_type->points_to()->is_slice_type())
9473 arg_type = arg_type->points_to();
9474
9475 if (arg_type->array_type() != NULL
9476 && arg_type->array_type()->length() != NULL)
9477 {
9478 this->seen_ = true;
9479 bool ret = Builtin_call_expression::array_len_is_constant(arg);
9480 this->seen_ = false;
9481 return ret;
9482 }
9483
9484 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9485 {
9486 this->seen_ = true;
9487 bool ret = arg->is_constant();
9488 this->seen_ = false;
9489 return ret;
9490 }
9491 }
9492 break;
9493
9494 case BUILTIN_SIZEOF:
9495 case BUILTIN_ALIGNOF:
9496 return this->one_arg() != NULL;
9497
9498 case BUILTIN_OFFSETOF:
9499 {
9500 Expression* arg = this->one_arg();
9501 if (arg == NULL)
9502 return false;
9503 return arg->field_reference_expression() != NULL;
9504 }
9505
9506 case BUILTIN_COMPLEX:
9507 {
9508 const Expression_list* args = this->args();
9509 if (args != NULL && args->size() == 2)
9510 return args->front()->is_constant() && args->back()->is_constant();
9511 }
9512 break;
9513
9514 case BUILTIN_REAL:
9515 case BUILTIN_IMAG:
9516 {
9517 Expression* arg = this->one_arg();
9518 return arg != NULL && arg->is_constant();
9519 }
9520
9521 default:
9522 break;
9523 }
9524
9525 return false;
9526 }
9527
9528 // Return a numeric constant if possible.
9529
9530 bool
9531 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
9532 {
9533 if (this->code_ == BUILTIN_LEN
9534 || this->code_ == BUILTIN_CAP)
9535 {
9536 Expression* arg = this->one_arg();
9537 if (arg == NULL)
9538 return false;
9539 Type* arg_type = arg->type();
9540 if (arg_type->is_error())
9541 return false;
9542
9543 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9544 {
9545 std::string sval;
9546 if (arg->string_constant_value(&sval))
9547 {
9548 nc->set_unsigned_long(Type::lookup_integer_type("int"),
9549 sval.length());
9550 return true;
9551 }
9552 }
9553
9554 if (arg_type->points_to() != NULL
9555 && arg_type->points_to()->array_type() != NULL
9556 && !arg_type->points_to()->is_slice_type())
9557 arg_type = arg_type->points_to();
9558
9559 if (arg_type->array_type() != NULL
9560 && arg_type->array_type()->length() != NULL)
9561 {
9562 if (this->seen_)
9563 return false;
9564
9565 // We may be replacing this expression with a constant
9566 // during lowering, so verify the type to report any errors.
9567 // It's OK to verify an array type more than once.
9568 arg_type->verify();
9569 if (!arg_type->is_error())
9570 {
9571 Expression* e = arg_type->array_type()->length();
9572 this->seen_ = true;
9573 bool r = e->numeric_constant_value(nc);
9574 this->seen_ = false;
9575 if (r)
9576 {
9577 if (!nc->set_type(Type::lookup_integer_type("int"), false,
9578 this->location()))
9579 r = false;
9580 }
9581 return r;
9582 }
9583 }
9584 }
9585 else if (this->code_ == BUILTIN_SIZEOF
9586 || this->code_ == BUILTIN_ALIGNOF)
9587 {
9588 Expression* arg = this->one_arg();
9589 if (arg == NULL)
9590 return false;
9591 Type* arg_type = arg->type();
9592 if (arg_type->is_error())
9593 return false;
9594 if (arg_type->is_abstract())
9595 arg_type = arg_type->make_non_abstract_type();
9596 if (this->seen_)
9597 return false;
9598
9599 int64_t ret;
9600 if (this->code_ == BUILTIN_SIZEOF)
9601 {
9602 this->seen_ = true;
9603 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
9604 this->seen_ = false;
9605 if (!ok)
9606 return false;
9607 }
9608 else if (this->code_ == BUILTIN_ALIGNOF)
9609 {
9610 bool ok;
9611 this->seen_ = true;
9612 if (arg->field_reference_expression() == NULL)
9613 ok = arg_type->backend_type_align(this->gogo_, &ret);
9614 else
9615 {
9616 // Calling unsafe.Alignof(s.f) returns the alignment of
9617 // the type of f when it is used as a field in a struct.
9618 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
9619 }
9620 this->seen_ = false;
9621 if (!ok)
9622 return false;
9623 }
9624 else
9625 go_unreachable();
9626
9627 mpz_t zval;
9628 set_mpz_from_int64(&zval, ret);
9629 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9630 mpz_clear(zval);
9631 return true;
9632 }
9633 else if (this->code_ == BUILTIN_OFFSETOF)
9634 {
9635 Expression* arg = this->one_arg();
9636 if (arg == NULL)
9637 return false;
9638 Field_reference_expression* farg = arg->field_reference_expression();
9639 if (farg == NULL)
9640 return false;
9641 if (this->seen_)
9642 return false;
9643
9644 int64_t total_offset = 0;
9645 while (true)
9646 {
9647 Expression* struct_expr = farg->expr();
9648 Type* st = struct_expr->type();
9649 if (st->struct_type() == NULL)
9650 return false;
9651 if (st->named_type() != NULL)
9652 st->named_type()->convert(this->gogo_);
9653 if (st->is_error_type())
9654 {
9655 go_assert(saw_errors());
9656 return false;
9657 }
9658 int64_t offset;
9659 this->seen_ = true;
9660 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
9661 farg->field_index(),
9662 &offset);
9663 this->seen_ = false;
9664 if (!ok)
9665 return false;
9666 total_offset += offset;
9667 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
9668 {
9669 // Go up until we reach the original base.
9670 farg = struct_expr->field_reference_expression();
9671 continue;
9672 }
9673 break;
9674 }
9675 mpz_t zval;
9676 set_mpz_from_int64(&zval, total_offset);
9677 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9678 mpz_clear(zval);
9679 return true;
9680 }
9681 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
9682 {
9683 Expression* arg = this->one_arg();
9684 if (arg == NULL)
9685 return false;
9686
9687 Numeric_constant argnc;
9688 if (!arg->numeric_constant_value(&argnc))
9689 return false;
9690
9691 mpc_t val;
9692 if (!argnc.to_complex(&val))
9693 return false;
9694
9695 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
9696 if (this->code_ == BUILTIN_REAL)
9697 nc->set_float(type, mpc_realref(val));
9698 else
9699 nc->set_float(type, mpc_imagref(val));
9700 mpc_clear(val);
9701 return true;
9702 }
9703 else if (this->code_ == BUILTIN_COMPLEX)
9704 {
9705 const Expression_list* args = this->args();
9706 if (args == NULL || args->size() != 2)
9707 return false;
9708
9709 Numeric_constant rnc;
9710 if (!args->front()->numeric_constant_value(&rnc))
9711 return false;
9712 Numeric_constant inc;
9713 if (!args->back()->numeric_constant_value(&inc))
9714 return false;
9715
9716 if (rnc.type() != NULL
9717 && !rnc.type()->is_abstract()
9718 && inc.type() != NULL
9719 && !inc.type()->is_abstract()
9720 && !Type::are_identical(rnc.type(), inc.type(),
9721 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
9722 NULL))
9723 return false;
9724
9725 mpfr_t r;
9726 if (!rnc.to_float(&r))
9727 return false;
9728 mpfr_t i;
9729 if (!inc.to_float(&i))
9730 {
9731 mpfr_clear(r);
9732 return false;
9733 }
9734
9735 Type* arg_type = rnc.type();
9736 if (arg_type == NULL || arg_type->is_abstract())
9737 arg_type = inc.type();
9738
9739 mpc_t val;
9740 mpc_init2(val, mpc_precision);
9741 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
9742 mpfr_clear(r);
9743 mpfr_clear(i);
9744
9745 Type* type = Builtin_call_expression::complex_type(arg_type);
9746 nc->set_complex(type, val);
9747
9748 mpc_clear(val);
9749
9750 return true;
9751 }
9752
9753 return false;
9754 }
9755
9756 // Give an error if we are discarding the value of an expression which
9757 // should not normally be discarded. We don't give an error for
9758 // discarding the value of an ordinary function call, but we do for
9759 // builtin functions, purely for consistency with the gc compiler.
9760
9761 bool
9762 Builtin_call_expression::do_discarding_value()
9763 {
9764 switch (this->code_)
9765 {
9766 case BUILTIN_INVALID:
9767 default:
9768 go_unreachable();
9769
9770 case BUILTIN_APPEND:
9771 case BUILTIN_CAP:
9772 case BUILTIN_COMPLEX:
9773 case BUILTIN_IMAG:
9774 case BUILTIN_LEN:
9775 case BUILTIN_MAKE:
9776 case BUILTIN_NEW:
9777 case BUILTIN_REAL:
9778 case BUILTIN_ALIGNOF:
9779 case BUILTIN_OFFSETOF:
9780 case BUILTIN_SIZEOF:
9781 this->unused_value_error();
9782 return false;
9783
9784 case BUILTIN_CLOSE:
9785 case BUILTIN_COPY:
9786 case BUILTIN_DELETE:
9787 case BUILTIN_PANIC:
9788 case BUILTIN_PRINT:
9789 case BUILTIN_PRINTLN:
9790 case BUILTIN_RECOVER:
9791 return true;
9792 }
9793 }
9794
9795 // Return the type.
9796
9797 Type*
9798 Builtin_call_expression::do_type()
9799 {
9800 if (this->is_error_expression())
9801 return Type::make_error_type();
9802 switch (this->code_)
9803 {
9804 case BUILTIN_INVALID:
9805 default:
9806 return Type::make_error_type();
9807
9808 case BUILTIN_NEW:
9809 {
9810 const Expression_list* args = this->args();
9811 if (args == NULL || args->empty())
9812 return Type::make_error_type();
9813 return Type::make_pointer_type(args->front()->type());
9814 }
9815
9816 case BUILTIN_MAKE:
9817 {
9818 const Expression_list* args = this->args();
9819 if (args == NULL || args->empty())
9820 return Type::make_error_type();
9821 return args->front()->type();
9822 }
9823
9824 case BUILTIN_CAP:
9825 case BUILTIN_COPY:
9826 case BUILTIN_LEN:
9827 return Type::lookup_integer_type("int");
9828
9829 case BUILTIN_ALIGNOF:
9830 case BUILTIN_OFFSETOF:
9831 case BUILTIN_SIZEOF:
9832 return Type::lookup_integer_type("uintptr");
9833
9834 case BUILTIN_CLOSE:
9835 case BUILTIN_DELETE:
9836 case BUILTIN_PANIC:
9837 case BUILTIN_PRINT:
9838 case BUILTIN_PRINTLN:
9839 return Type::make_void_type();
9840
9841 case BUILTIN_RECOVER:
9842 return Type::make_empty_interface_type(Linemap::predeclared_location());
9843
9844 case BUILTIN_APPEND:
9845 {
9846 const Expression_list* args = this->args();
9847 if (args == NULL || args->empty())
9848 return Type::make_error_type();
9849 Type *ret = args->front()->type();
9850 if (!ret->is_slice_type())
9851 return Type::make_error_type();
9852 return ret;
9853 }
9854
9855 case BUILTIN_REAL:
9856 case BUILTIN_IMAG:
9857 {
9858 Expression* arg = this->one_arg();
9859 if (arg == NULL)
9860 return Type::make_error_type();
9861 Type* t = arg->type();
9862 if (t->is_abstract())
9863 t = t->make_non_abstract_type();
9864 t = Builtin_call_expression::real_imag_type(t);
9865 if (t == NULL)
9866 t = Type::make_error_type();
9867 return t;
9868 }
9869
9870 case BUILTIN_COMPLEX:
9871 {
9872 const Expression_list* args = this->args();
9873 if (args == NULL || args->size() != 2)
9874 return Type::make_error_type();
9875 Type* t = args->front()->type();
9876 if (t->is_abstract())
9877 {
9878 t = args->back()->type();
9879 if (t->is_abstract())
9880 t = t->make_non_abstract_type();
9881 }
9882 t = Builtin_call_expression::complex_type(t);
9883 if (t == NULL)
9884 t = Type::make_error_type();
9885 return t;
9886 }
9887 }
9888 }
9889
9890 // Determine the type.
9891
9892 void
9893 Builtin_call_expression::do_determine_type(const Type_context* context)
9894 {
9895 if (!this->determining_types())
9896 return;
9897
9898 this->fn()->determine_type_no_context();
9899
9900 const Expression_list* args = this->args();
9901
9902 bool is_print;
9903 Type* arg_type = NULL;
9904 Type* trailing_arg_types = NULL;
9905 switch (this->code_)
9906 {
9907 case BUILTIN_PRINT:
9908 case BUILTIN_PRINTLN:
9909 // Do not force a large integer constant to "int".
9910 is_print = true;
9911 break;
9912
9913 case BUILTIN_REAL:
9914 case BUILTIN_IMAG:
9915 arg_type = Builtin_call_expression::complex_type(context->type);
9916 if (arg_type == NULL)
9917 arg_type = Type::lookup_complex_type("complex128");
9918 is_print = false;
9919 break;
9920
9921 case BUILTIN_COMPLEX:
9922 {
9923 // For the complex function the type of one operand can
9924 // determine the type of the other, as in a binary expression.
9925 arg_type = Builtin_call_expression::real_imag_type(context->type);
9926 if (arg_type == NULL)
9927 arg_type = Type::lookup_float_type("float64");
9928 if (args != NULL && args->size() == 2)
9929 {
9930 Type* t1 = args->front()->type();
9931 Type* t2 = args->back()->type();
9932 if (!t1->is_abstract())
9933 arg_type = t1;
9934 else if (!t2->is_abstract())
9935 arg_type = t2;
9936 }
9937 is_print = false;
9938 }
9939 break;
9940
9941 case BUILTIN_APPEND:
9942 if (!this->is_varargs()
9943 && args != NULL
9944 && !args->empty()
9945 && args->front()->type()->is_slice_type())
9946 trailing_arg_types =
9947 args->front()->type()->array_type()->element_type();
9948 is_print = false;
9949 break;
9950
9951 default:
9952 is_print = false;
9953 break;
9954 }
9955
9956 if (args != NULL)
9957 {
9958 for (Expression_list::const_iterator pa = args->begin();
9959 pa != args->end();
9960 ++pa)
9961 {
9962 Type_context subcontext;
9963 subcontext.type = arg_type;
9964
9965 if (is_print)
9966 {
9967 // We want to print large constants, we so can't just
9968 // use the appropriate nonabstract type. Use uint64 for
9969 // an integer if we know it is nonnegative, otherwise
9970 // use int64 for a integer, otherwise use float64 for a
9971 // float or complex128 for a complex.
9972 Type* want_type = NULL;
9973 Type* atype = (*pa)->type();
9974 if (atype->is_abstract())
9975 {
9976 if (atype->integer_type() != NULL)
9977 {
9978 Numeric_constant nc;
9979 if (this->numeric_constant_value(&nc))
9980 {
9981 mpz_t val;
9982 if (nc.to_int(&val))
9983 {
9984 if (mpz_sgn(val) >= 0)
9985 want_type = Type::lookup_integer_type("uint64");
9986 mpz_clear(val);
9987 }
9988 }
9989 if (want_type == NULL)
9990 want_type = Type::lookup_integer_type("int64");
9991 }
9992 else if (atype->float_type() != NULL)
9993 want_type = Type::lookup_float_type("float64");
9994 else if (atype->complex_type() != NULL)
9995 want_type = Type::lookup_complex_type("complex128");
9996 else if (atype->is_abstract_string_type())
9997 want_type = Type::lookup_string_type();
9998 else if (atype->is_abstract_boolean_type())
9999 want_type = Type::lookup_bool_type();
10000 else
10001 go_unreachable();
10002 subcontext.type = want_type;
10003 }
10004 }
10005
10006 (*pa)->determine_type(&subcontext);
10007
10008 if (trailing_arg_types != NULL)
10009 {
10010 arg_type = trailing_arg_types;
10011 trailing_arg_types = NULL;
10012 }
10013 }
10014 }
10015 }
10016
10017 // If there is exactly one argument, return true. Otherwise give an
10018 // error message and return false.
10019
10020 bool
10021 Builtin_call_expression::check_one_arg()
10022 {
10023 const Expression_list* args = this->args();
10024 if (args == NULL || args->size() < 1)
10025 {
10026 this->report_error(_("not enough arguments"));
10027 return false;
10028 }
10029 else if (args->size() > 1)
10030 {
10031 this->report_error(_("too many arguments"));
10032 return false;
10033 }
10034 if (args->front()->is_error_expression()
10035 || args->front()->type()->is_error())
10036 {
10037 this->set_is_error();
10038 return false;
10039 }
10040 return true;
10041 }
10042
10043 // Check argument types for a builtin function.
10044
10045 void
10046 Builtin_call_expression::do_check_types(Gogo*)
10047 {
10048 if (this->is_error_expression())
10049 return;
10050 switch (this->code_)
10051 {
10052 case BUILTIN_INVALID:
10053 case BUILTIN_NEW:
10054 case BUILTIN_MAKE:
10055 case BUILTIN_DELETE:
10056 return;
10057
10058 case BUILTIN_LEN:
10059 case BUILTIN_CAP:
10060 {
10061 // The single argument may be either a string or an array or a
10062 // map or a channel, or a pointer to a closed array.
10063 if (this->check_one_arg())
10064 {
10065 Type* arg_type = this->one_arg()->type();
10066 if (arg_type->points_to() != NULL
10067 && arg_type->points_to()->array_type() != NULL
10068 && !arg_type->points_to()->is_slice_type())
10069 arg_type = arg_type->points_to();
10070 if (this->code_ == BUILTIN_CAP)
10071 {
10072 if (!arg_type->is_error()
10073 && arg_type->array_type() == NULL
10074 && arg_type->channel_type() == NULL)
10075 this->report_error(_("argument must be array or slice "
10076 "or channel"));
10077 }
10078 else
10079 {
10080 if (!arg_type->is_error()
10081 && !arg_type->is_string_type()
10082 && arg_type->array_type() == NULL
10083 && arg_type->map_type() == NULL
10084 && arg_type->channel_type() == NULL)
10085 this->report_error(_("argument must be string or "
10086 "array or slice or map or channel"));
10087 }
10088 }
10089 }
10090 break;
10091
10092 case BUILTIN_PRINT:
10093 case BUILTIN_PRINTLN:
10094 {
10095 const Expression_list* args = this->args();
10096 if (args == NULL)
10097 {
10098 if (this->code_ == BUILTIN_PRINT)
10099 go_warning_at(this->location(), 0,
10100 "no arguments for built-in function %<%s%>",
10101 (this->code_ == BUILTIN_PRINT
10102 ? "print"
10103 : "println"));
10104 }
10105 else
10106 {
10107 for (Expression_list::const_iterator p = args->begin();
10108 p != args->end();
10109 ++p)
10110 {
10111 Type* type = (*p)->type();
10112 if (type->is_error()
10113 || type->is_string_type()
10114 || type->integer_type() != NULL
10115 || type->float_type() != NULL
10116 || type->complex_type() != NULL
10117 || type->is_boolean_type()
10118 || type->points_to() != NULL
10119 || type->interface_type() != NULL
10120 || type->channel_type() != NULL
10121 || type->map_type() != NULL
10122 || type->function_type() != NULL
10123 || type->is_slice_type())
10124 ;
10125 else if ((*p)->is_type_expression())
10126 {
10127 // If this is a type expression it's going to give
10128 // an error anyhow, so we don't need one here.
10129 }
10130 else
10131 this->report_error(_("unsupported argument type to "
10132 "builtin function"));
10133 }
10134 }
10135 }
10136 break;
10137
10138 case BUILTIN_CLOSE:
10139 if (this->check_one_arg())
10140 {
10141 if (this->one_arg()->type()->channel_type() == NULL)
10142 this->report_error(_("argument must be channel"));
10143 else if (!this->one_arg()->type()->channel_type()->may_send())
10144 this->report_error(_("cannot close receive-only channel"));
10145 }
10146 break;
10147
10148 case BUILTIN_PANIC:
10149 case BUILTIN_SIZEOF:
10150 case BUILTIN_ALIGNOF:
10151 this->check_one_arg();
10152 break;
10153
10154 case BUILTIN_RECOVER:
10155 if (this->args() != NULL
10156 && !this->args()->empty()
10157 && !this->recover_arg_is_set_)
10158 this->report_error(_("too many arguments"));
10159 break;
10160
10161 case BUILTIN_OFFSETOF:
10162 if (this->check_one_arg())
10163 {
10164 Expression* arg = this->one_arg();
10165 if (arg->field_reference_expression() == NULL)
10166 this->report_error(_("argument must be a field reference"));
10167 }
10168 break;
10169
10170 case BUILTIN_COPY:
10171 {
10172 const Expression_list* args = this->args();
10173 if (args == NULL || args->size() < 2)
10174 {
10175 this->report_error(_("not enough arguments"));
10176 break;
10177 }
10178 else if (args->size() > 2)
10179 {
10180 this->report_error(_("too many arguments"));
10181 break;
10182 }
10183 Type* arg1_type = args->front()->type();
10184 Type* arg2_type = args->back()->type();
10185 if (arg1_type->is_error() || arg2_type->is_error())
10186 {
10187 this->set_is_error();
10188 break;
10189 }
10190
10191 Type* e1;
10192 if (arg1_type->is_slice_type())
10193 e1 = arg1_type->array_type()->element_type();
10194 else
10195 {
10196 this->report_error(_("left argument must be a slice"));
10197 break;
10198 }
10199
10200 if (arg2_type->is_slice_type())
10201 {
10202 Type* e2 = arg2_type->array_type()->element_type();
10203 if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
10204 this->report_error(_("element types must be the same"));
10205 }
10206 else if (arg2_type->is_string_type())
10207 {
10208 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
10209 this->report_error(_("first argument must be []byte"));
10210 }
10211 else
10212 this->report_error(_("second argument must be slice or string"));
10213 }
10214 break;
10215
10216 case BUILTIN_APPEND:
10217 {
10218 const Expression_list* args = this->args();
10219 if (args == NULL || args->empty())
10220 {
10221 this->report_error(_("not enough arguments"));
10222 break;
10223 }
10224
10225 Type* slice_type = args->front()->type();
10226 if (!slice_type->is_slice_type())
10227 {
10228 if (slice_type->is_error_type())
10229 break;
10230 if (slice_type->is_nil_type())
10231 go_error_at(args->front()->location(), "use of untyped nil");
10232 else
10233 go_error_at(args->front()->location(),
10234 "argument 1 must be a slice");
10235 this->set_is_error();
10236 break;
10237 }
10238
10239 Type* element_type = slice_type->array_type()->element_type();
10240 if (!element_type->in_heap())
10241 go_error_at(args->front()->location(),
10242 "cannot append to slice of go:notinheap type");
10243 if (this->is_varargs())
10244 {
10245 if (!args->back()->type()->is_slice_type()
10246 && !args->back()->type()->is_string_type())
10247 {
10248 go_error_at(args->back()->location(),
10249 "invalid use of %<...%> with non-slice/non-string");
10250 this->set_is_error();
10251 break;
10252 }
10253
10254 if (args->size() < 2)
10255 {
10256 this->report_error(_("not enough arguments"));
10257 break;
10258 }
10259 if (args->size() > 2)
10260 {
10261 this->report_error(_("too many arguments"));
10262 break;
10263 }
10264
10265 if (args->back()->type()->is_string_type()
10266 && element_type->integer_type() != NULL
10267 && element_type->integer_type()->is_byte())
10268 {
10269 // Permit append(s1, s2...) when s1 is a slice of
10270 // bytes and s2 is a string type.
10271 }
10272 else
10273 {
10274 // We have to test for assignment compatibility to a
10275 // slice of the element type, which is not necessarily
10276 // the same as the type of the first argument: the
10277 // first argument might have a named type.
10278 Type* check_type = Type::make_array_type(element_type, NULL);
10279 std::string reason;
10280 if (!Type::are_assignable(check_type, args->back()->type(),
10281 &reason))
10282 {
10283 if (reason.empty())
10284 go_error_at(args->back()->location(),
10285 "argument 2 has invalid type");
10286 else
10287 go_error_at(args->back()->location(),
10288 "argument 2 has invalid type (%s)",
10289 reason.c_str());
10290 this->set_is_error();
10291 break;
10292 }
10293 }
10294 }
10295 else
10296 {
10297 Expression_list::const_iterator pa = args->begin();
10298 int i = 2;
10299 for (++pa; pa != args->end(); ++pa, ++i)
10300 {
10301 std::string reason;
10302 if (!Type::are_assignable(element_type, (*pa)->type(),
10303 &reason))
10304 {
10305 if (reason.empty())
10306 go_error_at((*pa)->location(),
10307 "argument %d has incompatible type", i);
10308 else
10309 go_error_at((*pa)->location(),
10310 "argument %d has incompatible type (%s)",
10311 i, reason.c_str());
10312 this->set_is_error();
10313 }
10314 }
10315 }
10316 }
10317 break;
10318
10319 case BUILTIN_REAL:
10320 case BUILTIN_IMAG:
10321 if (this->check_one_arg())
10322 {
10323 if (this->one_arg()->type()->complex_type() == NULL)
10324 this->report_error(_("argument must have complex type"));
10325 }
10326 break;
10327
10328 case BUILTIN_COMPLEX:
10329 {
10330 const Expression_list* args = this->args();
10331 if (args == NULL || args->size() < 2)
10332 this->report_error(_("not enough arguments"));
10333 else if (args->size() > 2)
10334 this->report_error(_("too many arguments"));
10335 else if (args->front()->is_error_expression()
10336 || args->front()->type()->is_error()
10337 || args->back()->is_error_expression()
10338 || args->back()->type()->is_error())
10339 this->set_is_error();
10340 else if (!Type::are_identical(args->front()->type(),
10341 args->back()->type(),
10342 Type::COMPARE_TAGS, NULL))
10343 this->report_error(_("complex arguments must have identical types"));
10344 else if (args->front()->type()->float_type() == NULL)
10345 this->report_error(_("complex arguments must have "
10346 "floating-point type"));
10347 }
10348 break;
10349
10350 default:
10351 go_unreachable();
10352 }
10353 }
10354
10355 Expression*
10356 Builtin_call_expression::do_copy()
10357 {
10358 Call_expression* bce =
10359 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
10360 (this->args() == NULL
10361 ? NULL
10362 : this->args()->copy()),
10363 this->is_varargs(),
10364 this->location());
10365
10366 if (this->varargs_are_lowered())
10367 bce->set_varargs_are_lowered();
10368 if (this->is_deferred())
10369 bce->set_is_deferred();
10370 if (this->is_concurrent())
10371 bce->set_is_concurrent();
10372 return bce;
10373 }
10374
10375 // Return the backend representation for a builtin function.
10376
10377 Bexpression*
10378 Builtin_call_expression::do_get_backend(Translate_context* context)
10379 {
10380 Gogo* gogo = context->gogo();
10381 Location location = this->location();
10382
10383 if (this->is_erroneous_call())
10384 {
10385 go_assert(saw_errors());
10386 return gogo->backend()->error_expression();
10387 }
10388
10389 switch (this->code_)
10390 {
10391 case BUILTIN_INVALID:
10392 case BUILTIN_NEW:
10393 case BUILTIN_MAKE:
10394 go_unreachable();
10395
10396 case BUILTIN_LEN:
10397 case BUILTIN_CAP:
10398 {
10399 const Expression_list* args = this->args();
10400 go_assert(args != NULL && args->size() == 1);
10401 Expression* arg = args->front();
10402 Type* arg_type = arg->type();
10403
10404 if (this->seen_)
10405 {
10406 go_assert(saw_errors());
10407 return context->backend()->error_expression();
10408 }
10409 this->seen_ = true;
10410 this->seen_ = false;
10411 if (arg_type->points_to() != NULL)
10412 {
10413 arg_type = arg_type->points_to();
10414 go_assert(arg_type->array_type() != NULL
10415 && !arg_type->is_slice_type());
10416 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
10417 location);
10418 }
10419
10420 Type* int_type = Type::lookup_integer_type("int");
10421 Expression* val;
10422 if (this->code_ == BUILTIN_LEN)
10423 {
10424 if (arg_type->is_string_type())
10425 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
10426 location);
10427 else if (arg_type->array_type() != NULL)
10428 {
10429 if (this->seen_)
10430 {
10431 go_assert(saw_errors());
10432 return context->backend()->error_expression();
10433 }
10434 this->seen_ = true;
10435 val = arg_type->array_type()->get_length(gogo, arg);
10436 this->seen_ = false;
10437 }
10438 else if (arg_type->map_type() != NULL
10439 || arg_type->channel_type() != NULL)
10440 {
10441 // The first field is the length. If the pointer is
10442 // nil, the length is zero.
10443 Type* pint_type = Type::make_pointer_type(int_type);
10444 arg = Expression::make_unsafe_cast(pint_type, arg, location);
10445 Expression* nil = Expression::make_nil(location);
10446 nil = Expression::make_cast(pint_type, nil, location);
10447 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10448 arg, nil, location);
10449 Expression* zero = Expression::make_integer_ul(0, int_type,
10450 location);
10451 Expression* indir =
10452 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
10453 location);
10454 val = Expression::make_conditional(cmp, zero, indir, location);
10455 }
10456 else
10457 go_unreachable();
10458 }
10459 else
10460 {
10461 if (arg_type->array_type() != NULL)
10462 {
10463 if (this->seen_)
10464 {
10465 go_assert(saw_errors());
10466 return context->backend()->error_expression();
10467 }
10468 this->seen_ = true;
10469 val = arg_type->array_type()->get_capacity(gogo, arg);
10470 this->seen_ = false;
10471 }
10472 else if (arg_type->channel_type() != NULL)
10473 {
10474 // The second field is the capacity. If the pointer
10475 // is nil, the capacity is zero.
10476 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10477 Type* pint_type = Type::make_pointer_type(int_type);
10478 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
10479 arg,
10480 location);
10481 int off = int_type->integer_type()->bits() / 8;
10482 Expression* eoff = Expression::make_integer_ul(off,
10483 uintptr_type,
10484 location);
10485 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
10486 location);
10487 parg = Expression::make_unsafe_cast(pint_type, parg, location);
10488 Expression* nil = Expression::make_nil(location);
10489 nil = Expression::make_cast(pint_type, nil, location);
10490 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10491 arg, nil, location);
10492 Expression* zero = Expression::make_integer_ul(0, int_type,
10493 location);
10494 Expression* indir =
10495 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
10496 location);
10497 val = Expression::make_conditional(cmp, zero, indir, location);
10498 }
10499 else
10500 go_unreachable();
10501 }
10502
10503 return Expression::make_cast(int_type, val,
10504 location)->get_backend(context);
10505 }
10506
10507 case BUILTIN_PRINT:
10508 case BUILTIN_PRINTLN:
10509 {
10510 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
10511
10512 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
10513 location, 0);
10514
10515 const Expression_list* call_args = this->args();
10516 if (call_args != NULL)
10517 {
10518 for (Expression_list::const_iterator p = call_args->begin();
10519 p != call_args->end();
10520 ++p)
10521 {
10522 if (is_ln && p != call_args->begin())
10523 {
10524 Expression* print_space =
10525 Runtime::make_call(Runtime::PRINTSP, location, 0);
10526
10527 print_stmts =
10528 Expression::make_compound(print_stmts, print_space,
10529 location);
10530 }
10531
10532 Expression* arg = *p;
10533 Type* type = arg->type();
10534 Runtime::Function code;
10535 if (type->is_string_type())
10536 code = Runtime::PRINTSTRING;
10537 else if (type->integer_type() != NULL
10538 && type->integer_type()->is_unsigned())
10539 {
10540 Type* itype = Type::lookup_integer_type("uint64");
10541 arg = Expression::make_cast(itype, arg, location);
10542 if (gogo->compiling_runtime()
10543 && type->named_type() != NULL
10544 && gogo->unpack_hidden_name(type->named_type()->name())
10545 == "hex")
10546 code = Runtime::PRINTHEX;
10547 else
10548 code = Runtime::PRINTUINT;
10549 }
10550 else if (type->integer_type() != NULL)
10551 {
10552 Type* itype = Type::lookup_integer_type("int64");
10553 arg = Expression::make_cast(itype, arg, location);
10554 code = Runtime::PRINTINT;
10555 }
10556 else if (type->float_type() != NULL)
10557 {
10558 Type* dtype = Type::lookup_float_type("float64");
10559 arg = Expression::make_cast(dtype, arg, location);
10560 code = Runtime::PRINTFLOAT;
10561 }
10562 else if (type->complex_type() != NULL)
10563 {
10564 Type* ctype = Type::lookup_complex_type("complex128");
10565 arg = Expression::make_cast(ctype, arg, location);
10566 code = Runtime::PRINTCOMPLEX;
10567 }
10568 else if (type->is_boolean_type())
10569 code = Runtime::PRINTBOOL;
10570 else if (type->points_to() != NULL
10571 || type->channel_type() != NULL
10572 || type->map_type() != NULL
10573 || type->function_type() != NULL)
10574 {
10575 arg = Expression::make_cast(type, arg, location);
10576 code = Runtime::PRINTPOINTER;
10577 }
10578 else if (type->interface_type() != NULL)
10579 {
10580 if (type->interface_type()->is_empty())
10581 code = Runtime::PRINTEFACE;
10582 else
10583 code = Runtime::PRINTIFACE;
10584 }
10585 else if (type->is_slice_type())
10586 code = Runtime::PRINTSLICE;
10587 else
10588 {
10589 go_assert(saw_errors());
10590 return context->backend()->error_expression();
10591 }
10592
10593 Expression* call = Runtime::make_call(code, location, 1, arg);
10594 print_stmts = Expression::make_compound(print_stmts, call,
10595 location);
10596 }
10597 }
10598
10599 if (is_ln)
10600 {
10601 Expression* print_nl =
10602 Runtime::make_call(Runtime::PRINTNL, location, 0);
10603 print_stmts = Expression::make_compound(print_stmts, print_nl,
10604 location);
10605 }
10606
10607 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
10608 location, 0);
10609 print_stmts = Expression::make_compound(print_stmts, unlock, location);
10610
10611 return print_stmts->get_backend(context);
10612 }
10613
10614 case BUILTIN_PANIC:
10615 {
10616 const Expression_list* args = this->args();
10617 go_assert(args != NULL && args->size() == 1);
10618 Expression* arg = args->front();
10619 Type *empty =
10620 Type::make_empty_interface_type(Linemap::predeclared_location());
10621 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
10622
10623 Expression* panic =
10624 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
10625 return panic->get_backend(context);
10626 }
10627
10628 case BUILTIN_RECOVER:
10629 {
10630 // The argument is set when building recover thunks. It's a
10631 // boolean value which is true if we can recover a value now.
10632 const Expression_list* args = this->args();
10633 go_assert(args != NULL && args->size() == 1);
10634 Expression* arg = args->front();
10635 Type *empty =
10636 Type::make_empty_interface_type(Linemap::predeclared_location());
10637
10638 Expression* nil = Expression::make_nil(location);
10639 nil = Expression::make_interface_value(empty, nil, nil, location);
10640
10641 // We need to handle a deferred call to recover specially,
10642 // because it changes whether it can recover a panic or not.
10643 // See test7 in test/recover1.go.
10644 Expression* recover = Runtime::make_call((this->is_deferred()
10645 ? Runtime::DEFERREDRECOVER
10646 : Runtime::GORECOVER),
10647 location, 0);
10648 Expression* cond =
10649 Expression::make_conditional(arg, recover, nil, location);
10650 return cond->get_backend(context);
10651 }
10652
10653 case BUILTIN_CLOSE:
10654 {
10655 const Expression_list* args = this->args();
10656 go_assert(args != NULL && args->size() == 1);
10657 Expression* arg = args->front();
10658 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
10659 1, arg);
10660 return close->get_backend(context);
10661 }
10662
10663 case BUILTIN_SIZEOF:
10664 case BUILTIN_OFFSETOF:
10665 case BUILTIN_ALIGNOF:
10666 {
10667 Numeric_constant nc;
10668 unsigned long val;
10669 if (!this->numeric_constant_value(&nc)
10670 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
10671 {
10672 go_assert(saw_errors());
10673 return context->backend()->error_expression();
10674 }
10675 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10676 mpz_t ival;
10677 nc.get_int(&ival);
10678 Expression* int_cst =
10679 Expression::make_integer_z(&ival, uintptr_type, location);
10680 mpz_clear(ival);
10681 return int_cst->get_backend(context);
10682 }
10683
10684 case BUILTIN_COPY:
10685 // Handled in Builtin_call_expression::do_flatten.
10686 go_unreachable();
10687
10688 case BUILTIN_APPEND:
10689 // Handled in Builtin_call_expression::flatten_append.
10690 go_unreachable();
10691
10692 case BUILTIN_REAL:
10693 case BUILTIN_IMAG:
10694 {
10695 const Expression_list* args = this->args();
10696 go_assert(args != NULL && args->size() == 1);
10697
10698 Bexpression* ret;
10699 Bexpression* bcomplex = args->front()->get_backend(context);
10700 if (this->code_ == BUILTIN_REAL)
10701 ret = gogo->backend()->real_part_expression(bcomplex, location);
10702 else
10703 ret = gogo->backend()->imag_part_expression(bcomplex, location);
10704 return ret;
10705 }
10706
10707 case BUILTIN_COMPLEX:
10708 {
10709 const Expression_list* args = this->args();
10710 go_assert(args != NULL && args->size() == 2);
10711 Bexpression* breal = args->front()->get_backend(context);
10712 Bexpression* bimag = args->back()->get_backend(context);
10713 return gogo->backend()->complex_expression(breal, bimag, location);
10714 }
10715
10716 default:
10717 go_unreachable();
10718 }
10719 }
10720
10721 // We have to support exporting a builtin call expression, because
10722 // code can set a constant to the result of a builtin expression.
10723
10724 void
10725 Builtin_call_expression::do_export(Export_function_body* efb) const
10726 {
10727 Numeric_constant nc;
10728 if (this->numeric_constant_value(&nc))
10729 {
10730 if (nc.is_int())
10731 {
10732 mpz_t val;
10733 nc.get_int(&val);
10734 Integer_expression::export_integer(efb, val);
10735 mpz_clear(val);
10736 }
10737 else if (nc.is_float())
10738 {
10739 mpfr_t fval;
10740 nc.get_float(&fval);
10741 Float_expression::export_float(efb, fval);
10742 mpfr_clear(fval);
10743 }
10744 else if (nc.is_complex())
10745 {
10746 mpc_t cval;
10747 nc.get_complex(&cval);
10748 Complex_expression::export_complex(efb, cval);
10749 mpc_clear(cval);
10750 }
10751 else
10752 go_unreachable();
10753
10754 // A trailing space lets us reliably identify the end of the number.
10755 efb->write_c_string(" ");
10756 }
10757 else
10758 {
10759 const char *s = NULL;
10760 switch (this->code_)
10761 {
10762 default:
10763 go_unreachable();
10764 case BUILTIN_APPEND:
10765 s = "append";
10766 break;
10767 case BUILTIN_COPY:
10768 s = "copy";
10769 break;
10770 case BUILTIN_LEN:
10771 s = "len";
10772 break;
10773 case BUILTIN_CAP:
10774 s = "cap";
10775 break;
10776 case BUILTIN_DELETE:
10777 s = "delete";
10778 break;
10779 case BUILTIN_PRINT:
10780 s = "print";
10781 break;
10782 case BUILTIN_PRINTLN:
10783 s = "println";
10784 break;
10785 case BUILTIN_PANIC:
10786 s = "panic";
10787 break;
10788 case BUILTIN_RECOVER:
10789 s = "recover";
10790 break;
10791 case BUILTIN_CLOSE:
10792 s = "close";
10793 break;
10794 case BUILTIN_REAL:
10795 s = "real";
10796 break;
10797 case BUILTIN_IMAG:
10798 s = "imag";
10799 break;
10800 case BUILTIN_COMPLEX:
10801 s = "complex";
10802 break;
10803 }
10804 efb->write_c_string(s);
10805 this->export_arguments(efb);
10806 }
10807 }
10808
10809 // Class Call_expression.
10810
10811 // A Go function can be viewed in a couple of different ways. The
10812 // code of a Go function becomes a backend function with parameters
10813 // whose types are simply the backend representation of the Go types.
10814 // If there are multiple results, they are returned as a backend
10815 // struct.
10816
10817 // However, when Go code refers to a function other than simply
10818 // calling it, the backend type of that function is actually a struct.
10819 // The first field of the struct points to the Go function code
10820 // (sometimes a wrapper as described below). The remaining fields
10821 // hold addresses of closed-over variables. This struct is called a
10822 // closure.
10823
10824 // There are a few cases to consider.
10825
10826 // A direct function call of a known function in package scope. In
10827 // this case there are no closed-over variables, and we know the name
10828 // of the function code. We can simply produce a backend call to the
10829 // function directly, and not worry about the closure.
10830
10831 // A direct function call of a known function literal. In this case
10832 // we know the function code and we know the closure. We generate the
10833 // function code such that it expects an additional final argument of
10834 // the closure type. We pass the closure as the last argument, after
10835 // the other arguments.
10836
10837 // An indirect function call. In this case we have a closure. We
10838 // load the pointer to the function code from the first field of the
10839 // closure. We pass the address of the closure as the last argument.
10840
10841 // A call to a method of an interface. Type methods are always at
10842 // package scope, so we call the function directly, and don't worry
10843 // about the closure.
10844
10845 // This means that for a function at package scope we have two cases.
10846 // One is the direct call, which has no closure. The other is the
10847 // indirect call, which does have a closure. We can't simply ignore
10848 // the closure, even though it is the last argument, because that will
10849 // fail on targets where the function pops its arguments. So when
10850 // generating a closure for a package-scope function we set the
10851 // function code pointer in the closure to point to a wrapper
10852 // function. This wrapper function accepts a final argument that
10853 // points to the closure, ignores it, and calls the real function as a
10854 // direct function call. This wrapper will normally be efficient, and
10855 // can often simply be a tail call to the real function.
10856
10857 // We don't use GCC's static chain pointer because 1) we don't need
10858 // it; 2) GCC only permits using a static chain to call a known
10859 // function, so we can't use it for an indirect call anyhow. Since we
10860 // can't use it for an indirect call, we may as well not worry about
10861 // using it for a direct call either.
10862
10863 // We pass the closure last rather than first because it means that
10864 // the function wrapper we put into a closure for a package-scope
10865 // function can normally just be a tail call to the real function.
10866
10867 // For method expressions we generate a wrapper that loads the
10868 // receiver from the closure and then calls the method. This
10869 // unfortunately forces reshuffling the arguments, since there is a
10870 // new first argument, but we can't avoid reshuffling either for
10871 // method expressions or for indirect calls of package-scope
10872 // functions, and since the latter are more common we reshuffle for
10873 // method expressions.
10874
10875 // Note that the Go code retains the Go types. The extra final
10876 // argument only appears when we convert to the backend
10877 // representation.
10878
10879 // Traversal.
10880
10881 int
10882 Call_expression::do_traverse(Traverse* traverse)
10883 {
10884 // If we are calling a function in a different package that returns
10885 // an unnamed type, this may be the only chance we get to traverse
10886 // that type. We don't traverse this->type_ because it may be a
10887 // Call_multiple_result_type that will just lead back here.
10888 if (this->type_ != NULL && !this->type_->is_error_type())
10889 {
10890 Function_type *fntype = this->get_function_type();
10891 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
10892 return TRAVERSE_EXIT;
10893 }
10894 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
10895 return TRAVERSE_EXIT;
10896 if (this->args_ != NULL)
10897 {
10898 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
10899 return TRAVERSE_EXIT;
10900 }
10901 return TRAVERSE_CONTINUE;
10902 }
10903
10904 // Lower a call statement.
10905
10906 Expression*
10907 Call_expression::do_lower(Gogo* gogo, Named_object* function,
10908 Statement_inserter* inserter, int)
10909 {
10910 Location loc = this->location();
10911
10912 // A type cast can look like a function call.
10913 if (this->fn_->is_type_expression()
10914 && this->args_ != NULL
10915 && this->args_->size() == 1)
10916 return Expression::make_cast(this->fn_->type(), this->args_->front(),
10917 loc);
10918
10919 // Because do_type will return an error type and thus prevent future
10920 // errors, check for that case now to ensure that the error gets
10921 // reported.
10922 Function_type* fntype = this->get_function_type();
10923 if (fntype == NULL)
10924 {
10925 if (!this->fn_->type()->is_error())
10926 this->report_error(_("expected function"));
10927 this->set_is_error();
10928 return this;
10929 }
10930
10931 // Handle an argument which is a call to a function which returns
10932 // multiple results.
10933 if (this->args_ != NULL
10934 && this->args_->size() == 1
10935 && this->args_->front()->call_expression() != NULL)
10936 {
10937 size_t rc = this->args_->front()->call_expression()->result_count();
10938 if (rc > 1
10939 && ((fntype->parameters() != NULL
10940 && (fntype->parameters()->size() == rc
10941 || (fntype->is_varargs()
10942 && fntype->parameters()->size() - 1 <= rc)))
10943 || fntype->is_builtin()))
10944 {
10945 Call_expression* call = this->args_->front()->call_expression();
10946 call->set_is_multi_value_arg();
10947 if (this->is_varargs_)
10948 {
10949 // It is not clear which result of a multiple result call
10950 // the ellipsis operator should be applied to. If we unpack the
10951 // the call into its individual results here, the ellipsis will be
10952 // applied to the last result.
10953 go_error_at(call->location(),
10954 _("multiple-value argument in single-value context"));
10955 return Expression::make_error(call->location());
10956 }
10957
10958 Expression_list* args = new Expression_list;
10959 for (size_t i = 0; i < rc; ++i)
10960 args->push_back(Expression::make_call_result(call, i));
10961 // We can't return a new call expression here, because this
10962 // one may be referenced by Call_result expressions. We
10963 // also can't delete the old arguments, because we may still
10964 // traverse them somewhere up the call stack. FIXME.
10965 this->args_ = args;
10966 }
10967 }
10968
10969 // Recognize a call to a builtin function.
10970 if (fntype->is_builtin())
10971 {
10972 Builtin_call_expression* bce =
10973 new Builtin_call_expression(gogo, this->fn_, this->args_,
10974 this->is_varargs_, loc);
10975 if (this->is_deferred_)
10976 bce->set_is_deferred();
10977 if (this->is_concurrent_)
10978 bce->set_is_concurrent();
10979 return bce;
10980 }
10981
10982 // If this call returns multiple results, create a temporary
10983 // variable to hold them.
10984 if (this->result_count() > 1 && this->call_temp_ == NULL)
10985 {
10986 Struct_field_list* sfl = new Struct_field_list();
10987 const Typed_identifier_list* results = fntype->results();
10988
10989 int i = 0;
10990 char buf[20];
10991 for (Typed_identifier_list::const_iterator p = results->begin();
10992 p != results->end();
10993 ++p, ++i)
10994 {
10995 snprintf(buf, sizeof buf, "res%d", i);
10996 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
10997 }
10998
10999 Struct_type* st = Type::make_struct_type(sfl, loc);
11000 st->set_is_struct_incomparable();
11001 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
11002 inserter->insert(this->call_temp_);
11003 }
11004
11005 // Handle a call to a varargs function by packaging up the extra
11006 // parameters.
11007 if (fntype->is_varargs())
11008 {
11009 const Typed_identifier_list* parameters = fntype->parameters();
11010 go_assert(parameters != NULL && !parameters->empty());
11011 Type* varargs_type = parameters->back().type();
11012 this->lower_varargs(gogo, function, inserter, varargs_type,
11013 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
11014 }
11015
11016 // If this is call to a method, call the method directly passing the
11017 // object as the first parameter.
11018 Bound_method_expression* bme = this->fn_->bound_method_expression();
11019 if (bme != NULL)
11020 {
11021 Named_object* methodfn = bme->function();
11022 Function_type* mft = (methodfn->is_function()
11023 ? methodfn->func_value()->type()
11024 : methodfn->func_declaration_value()->type());
11025 Expression* first_arg = bme->first_argument();
11026
11027 // We always pass a pointer when calling a method, except for
11028 // direct interface types when calling a value method.
11029 if (!first_arg->type()->is_error()
11030 && !first_arg->type()->is_direct_iface_type())
11031 {
11032 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
11033 // We may need to create a temporary variable so that we can
11034 // take the address. We can't do that here because it will
11035 // mess up the order of evaluation.
11036 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
11037 ue->set_create_temp();
11038 }
11039 else if (mft->receiver()->type()->points_to() == NULL
11040 && first_arg->type()->points_to() != NULL
11041 && first_arg->type()->points_to()->is_direct_iface_type())
11042 first_arg = Expression::make_dereference(first_arg,
11043 Expression::NIL_CHECK_DEFAULT,
11044 loc);
11045
11046 // If we are calling a method which was inherited from an
11047 // embedded struct, and the method did not get a stub, then the
11048 // first type may be wrong.
11049 Type* fatype = bme->first_argument_type();
11050 if (fatype != NULL)
11051 {
11052 if (fatype->points_to() == NULL)
11053 fatype = Type::make_pointer_type(fatype);
11054 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
11055 }
11056
11057 Expression_list* new_args = new Expression_list();
11058 new_args->push_back(first_arg);
11059 if (this->args_ != NULL)
11060 {
11061 for (Expression_list::const_iterator p = this->args_->begin();
11062 p != this->args_->end();
11063 ++p)
11064 new_args->push_back(*p);
11065 }
11066
11067 // We have to change in place because this structure may be
11068 // referenced by Call_result_expressions. We can't delete the
11069 // old arguments, because we may be traversing them up in some
11070 // caller. FIXME.
11071 this->args_ = new_args;
11072 this->fn_ = Expression::make_func_reference(methodfn, NULL,
11073 bme->location());
11074 }
11075
11076 // If this is a call to an imported function for which we have an
11077 // inlinable function body, add it to the list of functions to give
11078 // to the backend as inlining opportunities.
11079 Func_expression* fe = this->fn_->func_expression();
11080 if (fe != NULL
11081 && fe->named_object()->is_function_declaration()
11082 && fe->named_object()->func_declaration_value()->has_imported_body())
11083 gogo->add_imported_inlinable_function(fe->named_object());
11084
11085 return this;
11086 }
11087
11088 // Lower a call to a varargs function. FUNCTION is the function in
11089 // which the call occurs--it's not the function we are calling.
11090 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
11091 // PARAM_COUNT is the number of parameters of the function we are
11092 // calling; the last of these parameters will be the varargs
11093 // parameter.
11094
11095 void
11096 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
11097 Statement_inserter* inserter,
11098 Type* varargs_type, size_t param_count,
11099 Slice_storage_escape_disp escape_disp)
11100 {
11101 if (this->varargs_are_lowered_)
11102 return;
11103
11104 Location loc = this->location();
11105
11106 go_assert(param_count > 0);
11107 go_assert(varargs_type->is_slice_type());
11108
11109 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
11110 if (arg_count < param_count - 1)
11111 {
11112 // Not enough arguments; will be caught in check_types.
11113 return;
11114 }
11115
11116 Expression_list* old_args = this->args_;
11117 Expression_list* new_args = new Expression_list();
11118 bool push_empty_arg = false;
11119 if (old_args == NULL || old_args->empty())
11120 {
11121 go_assert(param_count == 1);
11122 push_empty_arg = true;
11123 }
11124 else
11125 {
11126 Expression_list::const_iterator pa;
11127 int i = 1;
11128 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
11129 {
11130 if (static_cast<size_t>(i) == param_count)
11131 break;
11132 new_args->push_back(*pa);
11133 }
11134
11135 // We have reached the varargs parameter.
11136
11137 bool issued_error = false;
11138 if (pa == old_args->end())
11139 push_empty_arg = true;
11140 else if (pa + 1 == old_args->end() && this->is_varargs_)
11141 new_args->push_back(*pa);
11142 else if (this->is_varargs_)
11143 {
11144 if ((*pa)->type()->is_slice_type())
11145 this->report_error(_("too many arguments"));
11146 else
11147 {
11148 go_error_at(this->location(),
11149 _("invalid use of %<...%> with non-slice"));
11150 this->set_is_error();
11151 }
11152 return;
11153 }
11154 else
11155 {
11156 Type* element_type = varargs_type->array_type()->element_type();
11157 Expression_list* vals = new Expression_list;
11158 for (; pa != old_args->end(); ++pa, ++i)
11159 {
11160 // Check types here so that we get a better message.
11161 Type* patype = (*pa)->type();
11162 Location paloc = (*pa)->location();
11163 if (!this->check_argument_type(i, element_type, patype,
11164 paloc, issued_error))
11165 continue;
11166 vals->push_back(*pa);
11167 }
11168 Slice_construction_expression* sce =
11169 Expression::make_slice_composite_literal(varargs_type, vals, loc);
11170 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
11171 sce->set_storage_does_not_escape();
11172 Expression* val = sce;
11173 gogo->lower_expression(function, inserter, &val);
11174 new_args->push_back(val);
11175 }
11176 }
11177
11178 if (push_empty_arg)
11179 new_args->push_back(Expression::make_nil(loc));
11180
11181 // We can't return a new call expression here, because this one may
11182 // be referenced by Call_result expressions. FIXME. We can't
11183 // delete OLD_ARGS because we may have both a Call_expression and a
11184 // Builtin_call_expression which refer to them. FIXME.
11185 this->args_ = new_args;
11186 this->varargs_are_lowered_ = true;
11187 }
11188
11189 // Flatten a call with multiple results into a temporary.
11190
11191 Expression*
11192 Call_expression::do_flatten(Gogo* gogo, Named_object*,
11193 Statement_inserter* inserter)
11194 {
11195 if (this->is_erroneous_call())
11196 {
11197 go_assert(saw_errors());
11198 return Expression::make_error(this->location());
11199 }
11200
11201 if (this->is_flattened_)
11202 return this;
11203 this->is_flattened_ = true;
11204
11205 // Add temporary variables for all arguments that require type
11206 // conversion.
11207 Function_type* fntype = this->get_function_type();
11208 if (fntype == NULL)
11209 {
11210 go_assert(saw_errors());
11211 return this;
11212 }
11213 if (this->args_ != NULL && !this->args_->empty()
11214 && fntype->parameters() != NULL && !fntype->parameters()->empty())
11215 {
11216 bool is_interface_method =
11217 this->fn_->interface_field_reference_expression() != NULL;
11218
11219 Expression_list *args = new Expression_list();
11220 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11221 Expression_list::const_iterator pa = this->args_->begin();
11222 if (!is_interface_method && fntype->is_method())
11223 {
11224 // The receiver argument.
11225 args->push_back(*pa);
11226 ++pa;
11227 }
11228 for (; pa != this->args_->end(); ++pa, ++pp)
11229 {
11230 go_assert(pp != fntype->parameters()->end());
11231 if (Type::are_identical(pp->type(), (*pa)->type(),
11232 Type::COMPARE_TAGS, NULL))
11233 args->push_back(*pa);
11234 else
11235 {
11236 Location loc = (*pa)->location();
11237 Expression* arg = *pa;
11238 if (!arg->is_variable())
11239 {
11240 Temporary_statement *temp =
11241 Statement::make_temporary(NULL, arg, loc);
11242 inserter->insert(temp);
11243 arg = Expression::make_temporary_reference(temp, loc);
11244 }
11245 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
11246 loc);
11247 args->push_back(arg);
11248 }
11249 }
11250 delete this->args_;
11251 this->args_ = args;
11252 }
11253
11254 // Lower to compiler intrinsic if possible.
11255 Func_expression* fe = this->fn_->func_expression();
11256 if (!this->is_concurrent_ && !this->is_deferred_
11257 && fe != NULL
11258 && (fe->named_object()->is_function_declaration()
11259 || fe->named_object()->is_function()))
11260 {
11261 Expression* ret = this->intrinsify(gogo, inserter);
11262 if (ret != NULL)
11263 return ret;
11264 }
11265
11266 // Add an implicit conversion to a boolean type, if needed. See the
11267 // comment in Binary_expression::lower_array_comparison.
11268 if (this->is_equal_function_
11269 && this->type_ != NULL
11270 && this->type_ != Type::lookup_bool_type())
11271 return Expression::make_cast(this->type_, this, this->location());
11272
11273 return this;
11274 }
11275
11276 // Lower a call to a compiler intrinsic if possible.
11277 // Returns NULL if it is not an intrinsic.
11278
11279 Expression*
11280 Call_expression::intrinsify(Gogo* gogo,
11281 Statement_inserter* inserter)
11282 {
11283 Func_expression* fe = this->fn_->func_expression();
11284 Named_object* no = fe->named_object();
11285 std::string name = Gogo::unpack_hidden_name(no->name());
11286 std::string package = (no->package() != NULL
11287 ? no->package()->pkgpath()
11288 : gogo->pkgpath());
11289 Location loc = this->location();
11290
11291 Type* int_type = Type::lookup_integer_type("int");
11292 Type* int32_type = Type::lookup_integer_type("int32");
11293 Type* int64_type = Type::lookup_integer_type("int64");
11294 Type* uint_type = Type::lookup_integer_type("uint");
11295 Type* uint32_type = Type::lookup_integer_type("uint32");
11296 Type* uint64_type = Type::lookup_integer_type("uint64");
11297 Type* uintptr_type = Type::lookup_integer_type("uintptr");
11298 Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
11299
11300 int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
11301 int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
11302
11303 if (package == "sync/atomic")
11304 {
11305 // sync/atomic functions and runtime/internal/atomic functions
11306 // are very similar. In order not to duplicate code, we just
11307 // redirect to the latter and let the code below to handle them.
11308 // In case there is no equivalent functions (slight variance
11309 // in types), we just make an artificial name (begin with '$').
11310 // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
11311 // as they need write barriers.
11312 if (name == "LoadInt32")
11313 name = "$Loadint32";
11314 else if (name == "LoadInt64")
11315 name = "Loadint64";
11316 else if (name == "LoadUint32")
11317 name = "Load";
11318 else if (name == "LoadUint64")
11319 name = "Load64";
11320 else if (name == "LoadUintptr")
11321 name = "Loaduintptr";
11322 else if (name == "LoadPointer")
11323 name = "Loadp";
11324 else if (name == "StoreInt32")
11325 name = "$Storeint32";
11326 else if (name == "StoreInt64")
11327 name = "$Storeint64";
11328 else if (name == "StoreUint32")
11329 name = "Store";
11330 else if (name == "StoreUint64")
11331 name = "Store64";
11332 else if (name == "StoreUintptr")
11333 name = "Storeuintptr";
11334 else if (name == "AddInt32")
11335 name = "$Xaddint32";
11336 else if (name == "AddInt64")
11337 name = "Xaddint64";
11338 else if (name == "AddUint32")
11339 name = "Xadd";
11340 else if (name == "AddUint64")
11341 name = "Xadd64";
11342 else if (name == "AddUintptr")
11343 name = "Xadduintptr";
11344 else if (name == "SwapInt32")
11345 name = "$Xchgint32";
11346 else if (name == "SwapInt64")
11347 name = "$Xchgint64";
11348 else if (name == "SwapUint32")
11349 name = "Xchg";
11350 else if (name == "SwapUint64")
11351 name = "Xchg64";
11352 else if (name == "SwapUintptr")
11353 name = "Xchguintptr";
11354 else if (name == "CompareAndSwapInt32")
11355 name = "$Casint32";
11356 else if (name == "CompareAndSwapInt64")
11357 name = "$Casint64";
11358 else if (name == "CompareAndSwapUint32")
11359 name = "Cas";
11360 else if (name == "CompareAndSwapUint64")
11361 name = "Cas64";
11362 else if (name == "CompareAndSwapUintptr")
11363 name = "Casuintptr";
11364 else
11365 return NULL;
11366
11367 package = "runtime/internal/atomic";
11368 }
11369
11370 if (package == "runtime/internal/sys")
11371 {
11372 // runtime/internal/sys functions and math/bits functions
11373 // are very similar. In order not to duplicate code, we just
11374 // redirect to the latter and let the code below to handle them.
11375 if (name == "Bswap32")
11376 name = "ReverseBytes32";
11377 else if (name == "Bswap64")
11378 name = "ReverseBytes64";
11379 else if (name == "Ctz32")
11380 name = "TrailingZeros32";
11381 else if (name == "Ctz64")
11382 name = "TrailingZeros64";
11383 else
11384 return NULL;
11385
11386 package = "math/bits";
11387 }
11388
11389 if (package == "runtime")
11390 {
11391 // Handle a couple of special runtime functions. In the runtime
11392 // package, getcallerpc returns the PC of the caller, and
11393 // getcallersp returns the frame pointer of the caller. Implement
11394 // these by turning them into calls to GCC builtin functions. We
11395 // could implement them in normal code, but then we would have to
11396 // explicitly unwind the stack. These functions are intended to be
11397 // efficient. Note that this technique obviously only works for
11398 // direct calls, but that is the only way they are used.
11399 if (name == "getcallerpc"
11400 && (this->args_ == NULL || this->args_->size() == 0))
11401 {
11402 Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
11403 Expression* call =
11404 Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
11405 1, arg);
11406 // The builtin functions return void*, but the Go functions return uintptr.
11407 return Expression::make_cast(uintptr_type, call, loc);
11408 }
11409 else if (name == "getcallersp"
11410 && (this->args_ == NULL || this->args_->size() == 0))
11411
11412 {
11413 Expression* call =
11414 Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
11415 // The builtin functions return void*, but the Go functions return uintptr.
11416 return Expression::make_cast(uintptr_type, call, loc);
11417 }
11418 }
11419 else if (package == "math/bits")
11420 {
11421 if ((name == "ReverseBytes16" || name == "ReverseBytes32"
11422 || name == "ReverseBytes64" || name == "ReverseBytes")
11423 && this->args_ != NULL && this->args_->size() == 1)
11424 {
11425 Runtime::Function code;
11426 if (name == "ReverseBytes16")
11427 code = Runtime::BUILTIN_BSWAP16;
11428 else if (name == "ReverseBytes32")
11429 code = Runtime::BUILTIN_BSWAP32;
11430 else if (name == "ReverseBytes64")
11431 code = Runtime::BUILTIN_BSWAP64;
11432 else if (name == "ReverseBytes")
11433 code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
11434 else
11435 go_unreachable();
11436 Expression* arg = this->args_->front();
11437 Expression* call = Runtime::make_call(code, loc, 1, arg);
11438 if (name == "ReverseBytes")
11439 return Expression::make_cast(uint_type, call, loc);
11440 return call;
11441 }
11442 else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
11443 && this->args_ != NULL && this->args_->size() == 1)
11444 {
11445 // GCC does not have a ctz8 or ctz16 intrinsic. We do
11446 // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
11447 Expression* arg = this->args_->front();
11448 arg = Expression::make_cast(uint32_type, arg, loc);
11449 unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
11450 Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
11451 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11452 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
11453 return Expression::make_cast(int_type, call, loc);
11454 }
11455 else if ((name == "TrailingZeros32"
11456 || (name == "TrailingZeros" && int_size == 4))
11457 && this->args_ != NULL && this->args_->size() == 1)
11458 {
11459 Expression* arg = this->args_->front();
11460 if (!arg->is_variable())
11461 {
11462 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11463 inserter->insert(ts);
11464 arg = Expression::make_temporary_reference(ts, loc);
11465 }
11466 // arg == 0 ? 32 : __builtin_ctz(arg)
11467 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11468 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11469 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11470 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
11471 call = Expression::make_cast(int_type, call, loc);
11472 return Expression::make_conditional(cmp, c32, call, loc);
11473 }
11474 else if ((name == "TrailingZeros64"
11475 || (name == "TrailingZeros" && int_size == 8))
11476 && this->args_ != NULL && this->args_->size() == 1)
11477 {
11478 Expression* arg = this->args_->front();
11479 if (!arg->is_variable())
11480 {
11481 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11482 inserter->insert(ts);
11483 arg = Expression::make_temporary_reference(ts, loc);
11484 }
11485 // arg == 0 ? 64 : __builtin_ctzll(arg)
11486 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11487 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11488 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11489 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
11490 call = Expression::make_cast(int_type, call, loc);
11491 return Expression::make_conditional(cmp, c64, call, loc);
11492 }
11493 else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
11494 || name == "Len8" || name == "Len16")
11495 && this->args_ != NULL && this->args_->size() == 1)
11496 {
11497 // GCC does not have a clz8 ir clz16 intrinsic. We do
11498 // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
11499 Expression* arg = this->args_->front();
11500 arg = Expression::make_cast(uint32_type, arg, loc);
11501 unsigned long shift =
11502 ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
11503 Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
11504 arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
11505 unsigned long mask =
11506 ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
11507 c = Expression::make_integer_ul(mask, uint32_type, loc);
11508 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11509 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
11510 call = Expression::make_cast(int_type, call, loc);
11511 // len = width - clz
11512 if (name == "Len8")
11513 {
11514 c = Expression::make_integer_ul(8, int_type, loc);
11515 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11516 }
11517 else if (name == "Len16")
11518 {
11519 c = Expression::make_integer_ul(16, int_type, loc);
11520 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11521 }
11522 return call;
11523 }
11524 else if ((name == "LeadingZeros32" || name == "Len32"
11525 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
11526 && this->args_ != NULL && this->args_->size() == 1)
11527 {
11528 Expression* arg = this->args_->front();
11529 if (!arg->is_variable())
11530 {
11531 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11532 inserter->insert(ts);
11533 arg = Expression::make_temporary_reference(ts, loc);
11534 }
11535 // arg == 0 ? 32 : __builtin_clz(arg)
11536 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11537 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11538 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11539 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
11540 call = Expression::make_cast(int_type, call, loc);
11541 Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
11542 // len = 32 - clz
11543 if (name == "Len32" || name == "Len")
11544 return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
11545 return cond;
11546 }
11547 else if ((name == "LeadingZeros64" || name == "Len64"
11548 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
11549 && this->args_ != NULL && this->args_->size() == 1)
11550 {
11551 Expression* arg = this->args_->front();
11552 if (!arg->is_variable())
11553 {
11554 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11555 inserter->insert(ts);
11556 arg = Expression::make_temporary_reference(ts, loc);
11557 }
11558 // arg == 0 ? 64 : __builtin_clzll(arg)
11559 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11560 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11561 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11562 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
11563 call = Expression::make_cast(int_type, call, loc);
11564 Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
11565 // len = 64 - clz
11566 if (name == "Len64" || name == "Len")
11567 return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
11568 return cond;
11569 }
11570 else if ((name == "OnesCount8" || name == "OnesCount16"
11571 || name == "OnesCount32" || name == "OnesCount64"
11572 || name == "OnesCount")
11573 && this->args_ != NULL && this->args_->size() == 1)
11574 {
11575 Runtime::Function code;
11576 if (name == "OnesCount64")
11577 code = Runtime::BUILTIN_POPCOUNTLL;
11578 else if (name == "OnesCount")
11579 code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
11580 else
11581 code = Runtime::BUILTIN_POPCOUNT;
11582 Expression* arg = this->args_->front();
11583 Expression* call = Runtime::make_call(code, loc, 1, arg);
11584 return Expression::make_cast(int_type, call, loc);
11585 }
11586 }
11587 else if (package == "runtime/internal/atomic")
11588 {
11589 int memorder = __ATOMIC_SEQ_CST;
11590
11591 if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
11592 || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
11593 || name == "$Loadint32")
11594 && this->args_ != NULL && this->args_->size() == 1)
11595 {
11596 if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
11597 // On 32-bit architectures we need to check alignment.
11598 // Not intrinsify for now.
11599 return NULL;
11600
11601 Runtime::Function code;
11602 Type* res_type;
11603 if (name == "Load")
11604 {
11605 code = Runtime::ATOMIC_LOAD_4;
11606 res_type = uint32_type;
11607 }
11608 else if (name == "Load64")
11609 {
11610 code = Runtime::ATOMIC_LOAD_8;
11611 res_type = uint64_type;
11612 }
11613 else if (name == "$Loadint32")
11614 {
11615 code = Runtime::ATOMIC_LOAD_4;
11616 res_type = int32_type;
11617 }
11618 else if (name == "Loadint64")
11619 {
11620 code = Runtime::ATOMIC_LOAD_8;
11621 res_type = int64_type;
11622 }
11623 else if (name == "Loaduint")
11624 {
11625 code = (int_size == 8
11626 ? Runtime::ATOMIC_LOAD_8
11627 : Runtime::ATOMIC_LOAD_4);
11628 res_type = uint_type;
11629 }
11630 else if (name == "Loaduintptr")
11631 {
11632 code = (ptr_size == 8
11633 ? Runtime::ATOMIC_LOAD_8
11634 : Runtime::ATOMIC_LOAD_4);
11635 res_type = uintptr_type;
11636 }
11637 else if (name == "Loadp")
11638 {
11639 code = (ptr_size == 8
11640 ? Runtime::ATOMIC_LOAD_8
11641 : Runtime::ATOMIC_LOAD_4);
11642 res_type = pointer_type;
11643 }
11644 else if (name == "LoadAcq")
11645 {
11646 code = Runtime::ATOMIC_LOAD_4;
11647 res_type = uint32_type;
11648 memorder = __ATOMIC_ACQUIRE;
11649 }
11650 else
11651 go_unreachable();
11652 Expression* a1 = this->args_->front();
11653 Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
11654 Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
11655 return Expression::make_unsafe_cast(res_type, call, loc);
11656 }
11657
11658 if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
11659 || name == "Storeuintptr" || name == "StoreRel"
11660 || name == "$Storeint32" || name == "$Storeint64")
11661 && this->args_ != NULL && this->args_->size() == 2)
11662 {
11663 if (int_size < 8 && (name == "Store64" || name == "$Storeint64"))
11664 return NULL;
11665
11666 Runtime::Function code;
11667 Expression* a1 = this->args_->at(0);
11668 Expression* a2 = this->args_->at(1);
11669 if (name == "Store")
11670 code = Runtime::ATOMIC_STORE_4;
11671 else if (name == "Store64")
11672 code = Runtime::ATOMIC_STORE_8;
11673 else if (name == "$Storeint32")
11674 code = Runtime::ATOMIC_STORE_4;
11675 else if (name == "$Storeint64")
11676 code = Runtime::ATOMIC_STORE_8;
11677 else if (name == "Storeuintptr")
11678 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11679 else if (name == "StorepNoWB")
11680 {
11681 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11682 a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
11683 a2 = Expression::make_cast(uint64_type, a2, loc);
11684 }
11685 else if (name == "StoreRel")
11686 {
11687 code = Runtime::ATOMIC_STORE_4;
11688 memorder = __ATOMIC_RELEASE;
11689 }
11690 else
11691 go_unreachable();
11692 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11693 return Runtime::make_call(code, loc, 3, a1, a2, a3);
11694 }
11695
11696 if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
11697 || name == "$Xchgint32" || name == "$Xchgint64")
11698 && this->args_ != NULL && this->args_->size() == 2)
11699 {
11700 if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
11701 return NULL;
11702
11703 Runtime::Function code;
11704 Type* res_type;
11705 if (name == "Xchg")
11706 {
11707 code = Runtime::ATOMIC_EXCHANGE_4;
11708 res_type = uint32_type;
11709 }
11710 else if (name == "Xchg64")
11711 {
11712 code = Runtime::ATOMIC_EXCHANGE_8;
11713 res_type = uint64_type;
11714 }
11715 else if (name == "$Xchgint32")
11716 {
11717 code = Runtime::ATOMIC_EXCHANGE_4;
11718 res_type = int32_type;
11719 }
11720 else if (name == "$Xchgint64")
11721 {
11722 code = Runtime::ATOMIC_EXCHANGE_8;
11723 res_type = int64_type;
11724 }
11725 else if (name == "Xchguintptr")
11726 {
11727 code = (ptr_size == 8
11728 ? Runtime::ATOMIC_EXCHANGE_8
11729 : Runtime::ATOMIC_EXCHANGE_4);
11730 res_type = uintptr_type;
11731 }
11732 else
11733 go_unreachable();
11734 Expression* a1 = this->args_->at(0);
11735 Expression* a2 = this->args_->at(1);
11736 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11737 Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11738 return Expression::make_cast(res_type, call, loc);
11739 }
11740
11741 if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
11742 || name == "Casp1" || name == "CasRel"
11743 || name == "$Casint32" || name == "$Casint64")
11744 && this->args_ != NULL && this->args_->size() == 3)
11745 {
11746 if (int_size < 8 && (name == "Cas64" || name == "$Casint64"))
11747 return NULL;
11748
11749 Runtime::Function code;
11750 Expression* a1 = this->args_->at(0);
11751
11752 // Builtin cas takes a pointer to the old value.
11753 // Store it in a temporary and take the address.
11754 Expression* a2 = this->args_->at(1);
11755 Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
11756 inserter->insert(ts);
11757 a2 = Expression::make_temporary_reference(ts, loc);
11758 a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
11759
11760 Expression* a3 = this->args_->at(2);
11761 if (name == "Cas")
11762 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11763 else if (name == "Cas64")
11764 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11765 else if (name == "$Casint32")
11766 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11767 else if (name == "$Casint64")
11768 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11769 else if (name == "Casuintptr")
11770 code = (ptr_size == 8
11771 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11772 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11773 else if (name == "Casp1")
11774 {
11775 code = (ptr_size == 8
11776 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11777 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11778 a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
11779 a3 = Expression::make_cast(uint64_type, a3, loc);
11780 }
11781 else if (name == "CasRel")
11782 {
11783 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11784 memorder = __ATOMIC_RELEASE;
11785 }
11786 else
11787 go_unreachable();
11788 Expression* a4 = Expression::make_boolean(false, loc);
11789 Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
11790 Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
11791 return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
11792 }
11793
11794 if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
11795 || name == "Xadduintptr" || name == "$Xaddint32")
11796 && this->args_ != NULL && this->args_->size() == 2)
11797 {
11798 if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
11799 return NULL;
11800
11801 Runtime::Function code;
11802 Type* res_type;
11803 if (name == "Xadd")
11804 {
11805 code = Runtime::ATOMIC_ADD_FETCH_4;
11806 res_type = uint32_type;
11807 }
11808 else if (name == "Xadd64")
11809 {
11810 code = Runtime::ATOMIC_ADD_FETCH_8;
11811 res_type = uint64_type;
11812 }
11813 else if (name == "$Xaddint32")
11814 {
11815 code = Runtime::ATOMIC_ADD_FETCH_4;
11816 res_type = int32_type;
11817 }
11818 else if (name == "Xaddint64")
11819 {
11820 code = Runtime::ATOMIC_ADD_FETCH_8;
11821 res_type = int64_type;
11822 }
11823 else if (name == "Xadduintptr")
11824 {
11825 code = (ptr_size == 8
11826 ? Runtime::ATOMIC_ADD_FETCH_8
11827 : Runtime::ATOMIC_ADD_FETCH_4);
11828 res_type = uintptr_type;
11829 }
11830 else
11831 go_unreachable();
11832 Expression* a1 = this->args_->at(0);
11833 Expression* a2 = this->args_->at(1);
11834 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11835 Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11836 return Expression::make_cast(res_type, call, loc);
11837 }
11838
11839 if ((name == "And8" || name == "Or8")
11840 && this->args_ != NULL && this->args_->size() == 2)
11841 {
11842 Runtime::Function code;
11843 if (name == "And8")
11844 code = Runtime::ATOMIC_AND_FETCH_1;
11845 else if (name == "Or8")
11846 code = Runtime::ATOMIC_OR_FETCH_1;
11847 else
11848 go_unreachable();
11849 Expression* a1 = this->args_->at(0);
11850 Expression* a2 = this->args_->at(1);
11851 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11852 return Runtime::make_call(code, loc, 3, a1, a2, a3);
11853 }
11854 }
11855
11856 return NULL;
11857 }
11858
11859 // Make implicit type conversions explicit.
11860
11861 void
11862 Call_expression::do_add_conversions()
11863 {
11864 // Skip call that requires a thunk. We generate conversions inside the thunk.
11865 if (this->is_concurrent_ || this->is_deferred_)
11866 return;
11867
11868 if (this->args_ == NULL || this->args_->empty())
11869 return;
11870
11871 Function_type* fntype = this->get_function_type();
11872 if (fntype == NULL)
11873 {
11874 go_assert(saw_errors());
11875 return;
11876 }
11877 if (fntype->parameters() == NULL || fntype->parameters()->empty())
11878 return;
11879
11880 Location loc = this->location();
11881 Expression_list::iterator pa = this->args_->begin();
11882 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11883 bool is_interface_method =
11884 this->fn_->interface_field_reference_expression() != NULL;
11885 size_t argcount = this->args_->size();
11886 if (!is_interface_method && fntype->is_method())
11887 {
11888 // Skip the receiver argument, which cannot be interface.
11889 pa++;
11890 argcount--;
11891 }
11892 if (argcount != fntype->parameters()->size())
11893 {
11894 go_assert(saw_errors());
11895 return;
11896 }
11897 for (; pa != this->args_->end(); ++pa, ++pp)
11898 {
11899 Type* pt = pp->type();
11900 if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
11901 && pt->interface_type() != NULL)
11902 *pa = Expression::make_cast(pt, *pa, loc);
11903 }
11904 }
11905
11906 // Get the function type. This can return NULL in error cases.
11907
11908 Function_type*
11909 Call_expression::get_function_type() const
11910 {
11911 return this->fn_->type()->function_type();
11912 }
11913
11914 // Return the number of values which this call will return.
11915
11916 size_t
11917 Call_expression::result_count() const
11918 {
11919 const Function_type* fntype = this->get_function_type();
11920 if (fntype == NULL)
11921 return 0;
11922 if (fntype->results() == NULL)
11923 return 0;
11924 return fntype->results()->size();
11925 }
11926
11927 // Return the temporary that holds the result for a call with multiple
11928 // results.
11929
11930 Temporary_statement*
11931 Call_expression::results() const
11932 {
11933 if (this->call_temp_ == NULL)
11934 {
11935 go_assert(saw_errors());
11936 return NULL;
11937 }
11938 return this->call_temp_;
11939 }
11940
11941 // Set the number of results expected from a call expression.
11942
11943 void
11944 Call_expression::set_expected_result_count(size_t count)
11945 {
11946 go_assert(this->expected_result_count_ == 0);
11947 this->expected_result_count_ = count;
11948 }
11949
11950 // Return whether this is a call to the predeclared function recover.
11951
11952 bool
11953 Call_expression::is_recover_call() const
11954 {
11955 return this->do_is_recover_call();
11956 }
11957
11958 // Set the argument to the recover function.
11959
11960 void
11961 Call_expression::set_recover_arg(Expression* arg)
11962 {
11963 this->do_set_recover_arg(arg);
11964 }
11965
11966 // Virtual functions also implemented by Builtin_call_expression.
11967
11968 bool
11969 Call_expression::do_is_recover_call() const
11970 {
11971 return false;
11972 }
11973
11974 void
11975 Call_expression::do_set_recover_arg(Expression*)
11976 {
11977 go_unreachable();
11978 }
11979
11980 // We have found an error with this call expression; return true if
11981 // we should report it.
11982
11983 bool
11984 Call_expression::issue_error()
11985 {
11986 if (this->issued_error_)
11987 return false;
11988 else
11989 {
11990 this->issued_error_ = true;
11991 return true;
11992 }
11993 }
11994
11995 // Whether or not this call contains errors, either in the call or the
11996 // arguments to the call.
11997
11998 bool
11999 Call_expression::is_erroneous_call()
12000 {
12001 if (this->is_error_expression() || this->fn()->is_error_expression())
12002 return true;
12003
12004 if (this->args() == NULL)
12005 return false;
12006 for (Expression_list::iterator pa = this->args()->begin();
12007 pa != this->args()->end();
12008 ++pa)
12009 {
12010 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
12011 return true;
12012 }
12013 return false;
12014 }
12015
12016 // Get the type.
12017
12018 Type*
12019 Call_expression::do_type()
12020 {
12021 if (this->is_error_expression())
12022 return Type::make_error_type();
12023 if (this->type_ != NULL)
12024 return this->type_;
12025
12026 Type* ret;
12027 Function_type* fntype = this->get_function_type();
12028 if (fntype == NULL)
12029 return Type::make_error_type();
12030
12031 const Typed_identifier_list* results = fntype->results();
12032 if (results == NULL)
12033 ret = Type::make_void_type();
12034 else if (results->size() == 1)
12035 ret = results->begin()->type();
12036 else
12037 ret = Type::make_call_multiple_result_type(this);
12038
12039 this->type_ = ret;
12040
12041 return this->type_;
12042 }
12043
12044 // Determine types for a call expression. We can use the function
12045 // parameter types to set the types of the arguments.
12046
12047 void
12048 Call_expression::do_determine_type(const Type_context* context)
12049 {
12050 if (!this->determining_types())
12051 return;
12052
12053 this->fn_->determine_type_no_context();
12054 Function_type* fntype = this->get_function_type();
12055 const Typed_identifier_list* parameters = NULL;
12056 if (fntype != NULL)
12057 parameters = fntype->parameters();
12058 if (this->args_ != NULL)
12059 {
12060 Typed_identifier_list::const_iterator pt;
12061 if (parameters != NULL)
12062 pt = parameters->begin();
12063 bool first = true;
12064 for (Expression_list::const_iterator pa = this->args_->begin();
12065 pa != this->args_->end();
12066 ++pa)
12067 {
12068 if (first)
12069 {
12070 first = false;
12071 // If this is a method, the first argument is the
12072 // receiver.
12073 if (fntype != NULL && fntype->is_method())
12074 {
12075 Type* rtype = fntype->receiver()->type();
12076 // The receiver is always passed as a pointer.
12077 if (rtype->points_to() == NULL)
12078 rtype = Type::make_pointer_type(rtype);
12079 Type_context subcontext(rtype, false);
12080 (*pa)->determine_type(&subcontext);
12081 continue;
12082 }
12083 }
12084
12085 if (parameters != NULL && pt != parameters->end())
12086 {
12087 Type_context subcontext(pt->type(), false);
12088 (*pa)->determine_type(&subcontext);
12089 ++pt;
12090 }
12091 else
12092 (*pa)->determine_type_no_context();
12093 }
12094 }
12095
12096 // If this is a call to a generated equality function, we determine
12097 // the type based on the context. See the comment in
12098 // Binary_expression::lower_array_comparison.
12099 if (this->is_equal_function_
12100 && !context->may_be_abstract
12101 && context->type != NULL
12102 && context->type->is_boolean_type()
12103 && context->type != Type::lookup_bool_type())
12104 {
12105 go_assert(this->type_ == NULL
12106 || this->type_ == Type::lookup_bool_type()
12107 || this->type_ == context->type
12108 || this->type_->is_error());
12109 this->type_ = context->type;
12110 }
12111 }
12112
12113 // Called when determining types for a Call_expression. Return true
12114 // if we should go ahead, false if they have already been determined.
12115
12116 bool
12117 Call_expression::determining_types()
12118 {
12119 if (this->types_are_determined_)
12120 return false;
12121 else
12122 {
12123 this->types_are_determined_ = true;
12124 return true;
12125 }
12126 }
12127
12128 // Check types for parameter I.
12129
12130 bool
12131 Call_expression::check_argument_type(int i, const Type* parameter_type,
12132 const Type* argument_type,
12133 Location argument_location,
12134 bool issued_error)
12135 {
12136 std::string reason;
12137 if (!Type::are_assignable(parameter_type, argument_type, &reason))
12138 {
12139 if (!issued_error)
12140 {
12141 if (reason.empty())
12142 go_error_at(argument_location, "argument %d has incompatible type", i);
12143 else
12144 go_error_at(argument_location,
12145 "argument %d has incompatible type (%s)",
12146 i, reason.c_str());
12147 }
12148 this->set_is_error();
12149 return false;
12150 }
12151 return true;
12152 }
12153
12154 // Check types.
12155
12156 void
12157 Call_expression::do_check_types(Gogo*)
12158 {
12159 if (this->classification() == EXPRESSION_ERROR)
12160 return;
12161
12162 Function_type* fntype = this->get_function_type();
12163 if (fntype == NULL)
12164 {
12165 if (!this->fn_->type()->is_error())
12166 this->report_error(_("expected function"));
12167 return;
12168 }
12169
12170 if (this->expected_result_count_ != 0
12171 && this->expected_result_count_ != this->result_count())
12172 {
12173 if (this->issue_error())
12174 this->report_error(_("function result count mismatch"));
12175 this->set_is_error();
12176 return;
12177 }
12178
12179 bool is_method = fntype->is_method();
12180 if (is_method)
12181 {
12182 go_assert(this->args_ != NULL && !this->args_->empty());
12183 Type* rtype = fntype->receiver()->type();
12184 Expression* first_arg = this->args_->front();
12185 // We dereference the values since receivers are always passed
12186 // as pointers.
12187 std::string reason;
12188 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
12189 &reason))
12190 {
12191 if (reason.empty())
12192 this->report_error(_("incompatible type for receiver"));
12193 else
12194 {
12195 go_error_at(this->location(),
12196 "incompatible type for receiver (%s)",
12197 reason.c_str());
12198 this->set_is_error();
12199 }
12200 }
12201 }
12202
12203 // Note that varargs was handled by the lower_varargs() method, so
12204 // we don't have to worry about it here unless something is wrong.
12205 if (this->is_varargs_ && !this->varargs_are_lowered_)
12206 {
12207 if (!fntype->is_varargs())
12208 {
12209 go_error_at(this->location(),
12210 _("invalid use of %<...%> calling non-variadic function"));
12211 this->set_is_error();
12212 return;
12213 }
12214 }
12215
12216 const Typed_identifier_list* parameters = fntype->parameters();
12217 if (this->args_ == NULL || this->args_->size() == 0)
12218 {
12219 if (parameters != NULL && !parameters->empty())
12220 this->report_error(_("not enough arguments"));
12221 }
12222 else if (parameters == NULL)
12223 {
12224 if (!is_method || this->args_->size() > 1)
12225 this->report_error(_("too many arguments"));
12226 }
12227 else if (this->args_->size() == 1
12228 && this->args_->front()->call_expression() != NULL
12229 && this->args_->front()->call_expression()->result_count() > 1)
12230 {
12231 // This is F(G()) when G returns more than one result. If the
12232 // results can be matched to parameters, it would have been
12233 // lowered in do_lower. If we get here we know there is a
12234 // mismatch.
12235 if (this->args_->front()->call_expression()->result_count()
12236 < parameters->size())
12237 this->report_error(_("not enough arguments"));
12238 else
12239 this->report_error(_("too many arguments"));
12240 }
12241 else
12242 {
12243 int i = 0;
12244 Expression_list::const_iterator pa = this->args_->begin();
12245 if (is_method)
12246 ++pa;
12247 for (Typed_identifier_list::const_iterator pt = parameters->begin();
12248 pt != parameters->end();
12249 ++pt, ++pa, ++i)
12250 {
12251 if (pa == this->args_->end())
12252 {
12253 this->report_error(_("not enough arguments"));
12254 return;
12255 }
12256 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
12257 (*pa)->location(), false);
12258 }
12259 if (pa != this->args_->end())
12260 this->report_error(_("too many arguments"));
12261 }
12262 }
12263
12264 Expression*
12265 Call_expression::do_copy()
12266 {
12267 Call_expression* call =
12268 Expression::make_call(this->fn_->copy(),
12269 (this->args_ == NULL
12270 ? NULL
12271 : this->args_->copy()),
12272 this->is_varargs_, this->location());
12273
12274 if (this->varargs_are_lowered_)
12275 call->set_varargs_are_lowered();
12276 if (this->is_deferred_)
12277 call->set_is_deferred();
12278 if (this->is_concurrent_)
12279 call->set_is_concurrent();
12280 return call;
12281 }
12282
12283 // Return whether we have to use a temporary variable to ensure that
12284 // we evaluate this call expression in order. If the call returns no
12285 // results then it will inevitably be executed last.
12286
12287 bool
12288 Call_expression::do_must_eval_in_order() const
12289 {
12290 return this->result_count() > 0;
12291 }
12292
12293 // Get the function and the first argument to use when calling an
12294 // interface method.
12295
12296 Expression*
12297 Call_expression::interface_method_function(
12298 Interface_field_reference_expression* interface_method,
12299 Expression** first_arg_ptr,
12300 Location location)
12301 {
12302 Expression* object = interface_method->get_underlying_object();
12303 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
12304 *first_arg_ptr =
12305 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
12306 return interface_method->get_function();
12307 }
12308
12309 // Build the call expression.
12310
12311 Bexpression*
12312 Call_expression::do_get_backend(Translate_context* context)
12313 {
12314 Location location = this->location();
12315
12316 if (this->call_ != NULL)
12317 {
12318 // If the call returns multiple results, make a new reference to
12319 // the temporary.
12320 if (this->call_temp_ != NULL)
12321 {
12322 Expression* ref =
12323 Expression::make_temporary_reference(this->call_temp_, location);
12324 return ref->get_backend(context);
12325 }
12326
12327 return this->call_;
12328 }
12329
12330 Function_type* fntype = this->get_function_type();
12331 if (fntype == NULL)
12332 return context->backend()->error_expression();
12333
12334 if (this->fn_->is_error_expression())
12335 return context->backend()->error_expression();
12336
12337 Gogo* gogo = context->gogo();
12338
12339 Func_expression* func = this->fn_->func_expression();
12340 Interface_field_reference_expression* interface_method =
12341 this->fn_->interface_field_reference_expression();
12342 const bool has_closure = func != NULL && func->closure() != NULL;
12343 const bool is_interface_method = interface_method != NULL;
12344
12345 bool has_closure_arg;
12346 if (has_closure)
12347 has_closure_arg = true;
12348 else if (func != NULL)
12349 has_closure_arg = false;
12350 else if (is_interface_method)
12351 has_closure_arg = false;
12352 else
12353 has_closure_arg = true;
12354
12355 Expression* first_arg = NULL;
12356 if (!is_interface_method && fntype->is_method())
12357 {
12358 first_arg = this->args_->front();
12359 if (first_arg->type()->points_to() == NULL
12360 && first_arg->type()->is_direct_iface_type())
12361 first_arg = Expression::unpack_direct_iface(first_arg,
12362 first_arg->location());
12363 }
12364
12365 int nargs;
12366 std::vector<Bexpression*> fn_args;
12367 if (this->args_ == NULL || this->args_->empty())
12368 {
12369 nargs = is_interface_method ? 1 : 0;
12370 if (nargs > 0)
12371 fn_args.resize(1);
12372 }
12373 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
12374 {
12375 // Passing a receiver parameter.
12376 go_assert(!is_interface_method
12377 && fntype->is_method()
12378 && this->args_->size() == 1);
12379 nargs = 1;
12380 fn_args.resize(1);
12381 fn_args[0] = first_arg->get_backend(context);
12382 }
12383 else
12384 {
12385 const Typed_identifier_list* params = fntype->parameters();
12386
12387 nargs = this->args_->size();
12388 int i = is_interface_method ? 1 : 0;
12389 nargs += i;
12390 fn_args.resize(nargs);
12391
12392 Typed_identifier_list::const_iterator pp = params->begin();
12393 Expression_list::const_iterator pe = this->args_->begin();
12394 if (!is_interface_method && fntype->is_method())
12395 {
12396 fn_args[i] = first_arg->get_backend(context);
12397 ++pe;
12398 ++i;
12399 }
12400 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
12401 {
12402 go_assert(pp != params->end());
12403 Expression* arg =
12404 Expression::convert_for_assignment(gogo, pp->type(), *pe,
12405 location);
12406 fn_args[i] = arg->get_backend(context);
12407 }
12408 go_assert(pp == params->end());
12409 go_assert(i == nargs);
12410 }
12411
12412 Expression* fn;
12413 Expression* closure = NULL;
12414 if (func != NULL)
12415 {
12416 Named_object* no = func->named_object();
12417 fn = Expression::make_func_code_reference(no, location);
12418 if (has_closure)
12419 closure = func->closure();
12420 }
12421 else if (!is_interface_method)
12422 {
12423 closure = this->fn_;
12424
12425 // The backend representation of this function type is a pointer
12426 // to a struct whose first field is the actual function to call.
12427 Type* pfntype =
12428 Type::make_pointer_type(
12429 Type::make_pointer_type(Type::make_void_type()));
12430 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
12431 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
12432 }
12433 else
12434 {
12435 Expression* arg0;
12436 fn = this->interface_method_function(interface_method, &arg0,
12437 location);
12438 fn_args[0] = arg0->get_backend(context);
12439 }
12440
12441 Bexpression* bclosure = NULL;
12442 if (has_closure_arg)
12443 bclosure = closure->get_backend(context);
12444 else
12445 go_assert(closure == NULL);
12446
12447 Bexpression* bfn = fn->get_backend(context);
12448
12449 // When not calling a named function directly, use a type conversion
12450 // in case the type of the function is a recursive type which refers
12451 // to itself. We don't do this for an interface method because 1)
12452 // an interface method never refers to itself, so we always have a
12453 // function type here; 2) we pass an extra first argument to an
12454 // interface method, so fntype is not correct.
12455 if (func == NULL && !is_interface_method)
12456 {
12457 Btype* bft = fntype->get_backend_fntype(gogo);
12458 bfn = gogo->backend()->convert_expression(bft, bfn, location);
12459 }
12460
12461 Bfunction* bfunction = NULL;
12462 if (context->function())
12463 bfunction = context->function()->func_value()->get_decl();
12464 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
12465 fn_args, bclosure,
12466 location);
12467
12468 if (this->call_temp_ != NULL)
12469 {
12470 // This case occurs when the call returns multiple results.
12471
12472 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
12473 location);
12474 Bexpression* bref = ref->get_backend(context);
12475 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
12476 bref, call,
12477 location);
12478
12479 ref = Expression::make_temporary_reference(this->call_temp_, location);
12480 this->call_ = ref->get_backend(context);
12481
12482 return gogo->backend()->compound_expression(bassn, this->call_,
12483 location);
12484 }
12485
12486 this->call_ = call;
12487 return this->call_;
12488 }
12489
12490 // The cost of inlining a call expression.
12491
12492 int
12493 Call_expression::do_inlining_cost() const
12494 {
12495 Func_expression* fn = this->fn_->func_expression();
12496
12497 // FIXME: We don't yet support all kinds of calls.
12498 if (fn != NULL && fn->closure() != NULL)
12499 return 0x100000;
12500 if (this->fn_->interface_field_reference_expression())
12501 return 0x100000;
12502 if (this->get_function_type()->is_method())
12503 return 0x100000;
12504
12505 return 5;
12506 }
12507
12508 // Export a call expression.
12509
12510 void
12511 Call_expression::do_export(Export_function_body* efb) const
12512 {
12513 bool simple_call = (this->fn_->func_expression() != NULL);
12514 if (!simple_call)
12515 efb->write_c_string("(");
12516 this->fn_->export_expression(efb);
12517 if (!simple_call)
12518 efb->write_c_string(")");
12519 this->export_arguments(efb);
12520 }
12521
12522 // Export call expression arguments.
12523
12524 void
12525 Call_expression::export_arguments(Export_function_body* efb) const
12526 {
12527 efb->write_c_string("(");
12528 if (this->args_ != NULL && !this->args_->empty())
12529 {
12530 Expression_list::const_iterator pa = this->args_->begin();
12531 (*pa)->export_expression(efb);
12532 for (pa++; pa != this->args_->end(); pa++)
12533 {
12534 efb->write_c_string(", ");
12535 (*pa)->export_expression(efb);
12536 }
12537 if (this->is_varargs_)
12538 efb->write_c_string("...");
12539 }
12540 efb->write_c_string(")");
12541 }
12542
12543 // Dump ast representation for a call expression.
12544
12545 void
12546 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12547 {
12548 this->fn_->dump_expression(ast_dump_context);
12549 ast_dump_context->ostream() << "(";
12550 if (args_ != NULL)
12551 ast_dump_context->dump_expression_list(this->args_);
12552
12553 ast_dump_context->ostream() << ") ";
12554 }
12555
12556 // Make a call expression.
12557
12558 Call_expression*
12559 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
12560 Location location)
12561 {
12562 return new Call_expression(fn, args, is_varargs, location);
12563 }
12564
12565 // Class Call_result_expression.
12566
12567 // Traverse a call result.
12568
12569 int
12570 Call_result_expression::do_traverse(Traverse* traverse)
12571 {
12572 if (traverse->remember_expression(this->call_))
12573 {
12574 // We have already traversed the call expression.
12575 return TRAVERSE_CONTINUE;
12576 }
12577 return Expression::traverse(&this->call_, traverse);
12578 }
12579
12580 // Get the type.
12581
12582 Type*
12583 Call_result_expression::do_type()
12584 {
12585 if (this->classification() == EXPRESSION_ERROR)
12586 return Type::make_error_type();
12587
12588 // THIS->CALL_ can be replaced with a temporary reference due to
12589 // Call_expression::do_must_eval_in_order when there is an error.
12590 Call_expression* ce = this->call_->call_expression();
12591 if (ce == NULL)
12592 {
12593 this->set_is_error();
12594 return Type::make_error_type();
12595 }
12596 Function_type* fntype = ce->get_function_type();
12597 if (fntype == NULL)
12598 {
12599 if (ce->issue_error())
12600 {
12601 if (!ce->fn()->type()->is_error())
12602 this->report_error(_("expected function"));
12603 }
12604 this->set_is_error();
12605 return Type::make_error_type();
12606 }
12607 const Typed_identifier_list* results = fntype->results();
12608 if (results == NULL || results->size() < 2)
12609 {
12610 if (ce->issue_error())
12611 this->report_error(_("number of results does not match "
12612 "number of values"));
12613 return Type::make_error_type();
12614 }
12615 Typed_identifier_list::const_iterator pr = results->begin();
12616 for (unsigned int i = 0; i < this->index_; ++i)
12617 {
12618 if (pr == results->end())
12619 break;
12620 ++pr;
12621 }
12622 if (pr == results->end())
12623 {
12624 if (ce->issue_error())
12625 this->report_error(_("number of results does not match "
12626 "number of values"));
12627 return Type::make_error_type();
12628 }
12629 return pr->type();
12630 }
12631
12632 // Check the type. Just make sure that we trigger the warning in
12633 // do_type.
12634
12635 void
12636 Call_result_expression::do_check_types(Gogo*)
12637 {
12638 this->type();
12639 }
12640
12641 // Determine the type. We have nothing to do here, but the 0 result
12642 // needs to pass down to the caller.
12643
12644 void
12645 Call_result_expression::do_determine_type(const Type_context*)
12646 {
12647 this->call_->determine_type_no_context();
12648 }
12649
12650 // Return the backend representation. We just refer to the temporary set by the
12651 // call expression. We don't do this at lowering time because it makes it
12652 // hard to evaluate the call at the right time.
12653
12654 Bexpression*
12655 Call_result_expression::do_get_backend(Translate_context* context)
12656 {
12657 Call_expression* ce = this->call_->call_expression();
12658 if (ce == NULL)
12659 {
12660 go_assert(this->call_->is_error_expression());
12661 return context->backend()->error_expression();
12662 }
12663 Temporary_statement* ts = ce->results();
12664 if (ts == NULL)
12665 {
12666 go_assert(saw_errors());
12667 return context->backend()->error_expression();
12668 }
12669 Expression* ref = Expression::make_temporary_reference(ts, this->location());
12670 ref = Expression::make_field_reference(ref, this->index_, this->location());
12671 return ref->get_backend(context);
12672 }
12673
12674 // Dump ast representation for a call result expression.
12675
12676 void
12677 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12678 const
12679 {
12680 // FIXME: Wouldn't it be better if the call is assigned to a temporary
12681 // (struct) and the fields are referenced instead.
12682 ast_dump_context->ostream() << this->index_ << "@(";
12683 ast_dump_context->dump_expression(this->call_);
12684 ast_dump_context->ostream() << ")";
12685 }
12686
12687 // Make a reference to a single result of a call which returns
12688 // multiple results.
12689
12690 Expression*
12691 Expression::make_call_result(Call_expression* call, unsigned int index)
12692 {
12693 return new Call_result_expression(call, index);
12694 }
12695
12696 // Class Index_expression.
12697
12698 // Traversal.
12699
12700 int
12701 Index_expression::do_traverse(Traverse* traverse)
12702 {
12703 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
12704 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
12705 || (this->end_ != NULL
12706 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12707 || (this->cap_ != NULL
12708 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
12709 return TRAVERSE_EXIT;
12710 return TRAVERSE_CONTINUE;
12711 }
12712
12713 // Lower an index expression. This converts the generic index
12714 // expression into an array index, a string index, or a map index.
12715
12716 Expression*
12717 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
12718 {
12719 Location location = this->location();
12720 Expression* left = this->left_;
12721 Expression* start = this->start_;
12722 Expression* end = this->end_;
12723 Expression* cap = this->cap_;
12724
12725 Type* type = left->type();
12726 if (type->is_error())
12727 {
12728 go_assert(saw_errors());
12729 return Expression::make_error(location);
12730 }
12731 else if (left->is_type_expression())
12732 {
12733 go_error_at(location, "attempt to index type expression");
12734 return Expression::make_error(location);
12735 }
12736 else if (type->array_type() != NULL)
12737 return Expression::make_array_index(left, start, end, cap, location);
12738 else if (type->points_to() != NULL
12739 && type->points_to()->array_type() != NULL
12740 && !type->points_to()->is_slice_type())
12741 {
12742 Expression* deref =
12743 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
12744
12745 // For an ordinary index into the array, the pointer will be
12746 // dereferenced. For a slice it will not--the resulting slice
12747 // will simply reuse the pointer, which is incorrect if that
12748 // pointer is nil.
12749 if (end != NULL || cap != NULL)
12750 deref->issue_nil_check();
12751
12752 return Expression::make_array_index(deref, start, end, cap, location);
12753 }
12754 else if (type->is_string_type())
12755 {
12756 if (cap != NULL)
12757 {
12758 go_error_at(location, "invalid 3-index slice of string");
12759 return Expression::make_error(location);
12760 }
12761 return Expression::make_string_index(left, start, end, location);
12762 }
12763 else if (type->map_type() != NULL)
12764 {
12765 if (end != NULL || cap != NULL)
12766 {
12767 go_error_at(location, "invalid slice of map");
12768 return Expression::make_error(location);
12769 }
12770 return Expression::make_map_index(left, start, location);
12771 }
12772 else if (cap != NULL)
12773 {
12774 go_error_at(location,
12775 "invalid 3-index slice of object that is not a slice");
12776 return Expression::make_error(location);
12777 }
12778 else if (end != NULL)
12779 {
12780 go_error_at(location,
12781 ("attempt to slice object that is not "
12782 "array, slice, or string"));
12783 return Expression::make_error(location);
12784 }
12785 else
12786 {
12787 go_error_at(location,
12788 ("attempt to index object that is not "
12789 "array, slice, string, or map"));
12790 return Expression::make_error(location);
12791 }
12792 }
12793
12794 // Write an indexed expression
12795 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
12796
12797 void
12798 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
12799 const Expression* expr,
12800 const Expression* start,
12801 const Expression* end,
12802 const Expression* cap)
12803 {
12804 expr->dump_expression(ast_dump_context);
12805 ast_dump_context->ostream() << "[";
12806 start->dump_expression(ast_dump_context);
12807 if (end != NULL)
12808 {
12809 ast_dump_context->ostream() << ":";
12810 end->dump_expression(ast_dump_context);
12811 }
12812 if (cap != NULL)
12813 {
12814 ast_dump_context->ostream() << ":";
12815 cap->dump_expression(ast_dump_context);
12816 }
12817 ast_dump_context->ostream() << "]";
12818 }
12819
12820 // Dump ast representation for an index expression.
12821
12822 void
12823 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12824 const
12825 {
12826 Index_expression::dump_index_expression(ast_dump_context, this->left_,
12827 this->start_, this->end_, this->cap_);
12828 }
12829
12830 // Make an index expression.
12831
12832 Expression*
12833 Expression::make_index(Expression* left, Expression* start, Expression* end,
12834 Expression* cap, Location location)
12835 {
12836 return new Index_expression(left, start, end, cap, location);
12837 }
12838
12839 // Class Array_index_expression.
12840
12841 // Array index traversal.
12842
12843 int
12844 Array_index_expression::do_traverse(Traverse* traverse)
12845 {
12846 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
12847 return TRAVERSE_EXIT;
12848 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
12849 return TRAVERSE_EXIT;
12850 if (this->end_ != NULL)
12851 {
12852 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12853 return TRAVERSE_EXIT;
12854 }
12855 if (this->cap_ != NULL)
12856 {
12857 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
12858 return TRAVERSE_EXIT;
12859 }
12860 return TRAVERSE_CONTINUE;
12861 }
12862
12863 // Return the type of an array index.
12864
12865 Type*
12866 Array_index_expression::do_type()
12867 {
12868 if (this->type_ == NULL)
12869 {
12870 Array_type* type = this->array_->type()->array_type();
12871 if (type == NULL)
12872 this->type_ = Type::make_error_type();
12873 else if (this->end_ == NULL)
12874 this->type_ = type->element_type();
12875 else if (type->is_slice_type())
12876 {
12877 // A slice of a slice has the same type as the original
12878 // slice.
12879 this->type_ = this->array_->type()->deref();
12880 }
12881 else
12882 {
12883 // A slice of an array is a slice.
12884 this->type_ = Type::make_array_type(type->element_type(), NULL);
12885 }
12886 }
12887 return this->type_;
12888 }
12889
12890 // Set the type of an array index.
12891
12892 void
12893 Array_index_expression::do_determine_type(const Type_context*)
12894 {
12895 this->array_->determine_type_no_context();
12896
12897 Type_context index_context(Type::lookup_integer_type("int"), false);
12898 this->start_->determine_type(&index_context);
12899 if (this->end_ != NULL)
12900 this->end_->determine_type(&index_context);
12901 if (this->cap_ != NULL)
12902 this->cap_->determine_type(&index_context);
12903 }
12904
12905 // Check types of an array index.
12906
12907 void
12908 Array_index_expression::do_check_types(Gogo*)
12909 {
12910 Numeric_constant nc;
12911 unsigned long v;
12912 if (this->start_->type()->integer_type() == NULL
12913 && !this->start_->type()->is_error()
12914 && (!this->start_->type()->is_abstract()
12915 || !this->start_->numeric_constant_value(&nc)
12916 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12917 this->report_error(_("index must be integer"));
12918 if (this->end_ != NULL
12919 && this->end_->type()->integer_type() == NULL
12920 && !this->end_->type()->is_error()
12921 && !this->end_->is_nil_expression()
12922 && !this->end_->is_error_expression()
12923 && (!this->end_->type()->is_abstract()
12924 || !this->end_->numeric_constant_value(&nc)
12925 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12926 this->report_error(_("slice end must be integer"));
12927 if (this->cap_ != NULL
12928 && this->cap_->type()->integer_type() == NULL
12929 && !this->cap_->type()->is_error()
12930 && !this->cap_->is_nil_expression()
12931 && !this->cap_->is_error_expression()
12932 && (!this->cap_->type()->is_abstract()
12933 || !this->cap_->numeric_constant_value(&nc)
12934 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12935 this->report_error(_("slice capacity must be integer"));
12936
12937 Array_type* array_type = this->array_->type()->array_type();
12938 if (array_type == NULL)
12939 {
12940 go_assert(this->array_->type()->is_error());
12941 return;
12942 }
12943
12944 unsigned int int_bits =
12945 Type::lookup_integer_type("int")->integer_type()->bits();
12946
12947 Numeric_constant lvalnc;
12948 mpz_t lval;
12949 bool lval_valid = (array_type->length() != NULL
12950 && array_type->length()->numeric_constant_value(&lvalnc)
12951 && lvalnc.to_int(&lval));
12952 Numeric_constant inc;
12953 mpz_t ival;
12954 bool ival_valid = false;
12955 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
12956 {
12957 ival_valid = true;
12958 if (mpz_sgn(ival) < 0
12959 || mpz_sizeinbase(ival, 2) >= int_bits
12960 || (lval_valid
12961 && (this->end_ == NULL
12962 ? mpz_cmp(ival, lval) >= 0
12963 : mpz_cmp(ival, lval) > 0)))
12964 {
12965 go_error_at(this->start_->location(), "array index out of bounds");
12966 this->set_is_error();
12967 }
12968 }
12969 if (this->end_ != NULL && !this->end_->is_nil_expression())
12970 {
12971 Numeric_constant enc;
12972 mpz_t eval;
12973 bool eval_valid = false;
12974 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
12975 {
12976 eval_valid = true;
12977 if (mpz_sgn(eval) < 0
12978 || mpz_sizeinbase(eval, 2) >= int_bits
12979 || (lval_valid && mpz_cmp(eval, lval) > 0))
12980 {
12981 go_error_at(this->end_->location(), "array index out of bounds");
12982 this->set_is_error();
12983 }
12984 else if (ival_valid && mpz_cmp(ival, eval) > 0)
12985 this->report_error(_("inverted slice range"));
12986 }
12987
12988 Numeric_constant cnc;
12989 mpz_t cval;
12990 if (this->cap_ != NULL
12991 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
12992 {
12993 if (mpz_sgn(cval) < 0
12994 || mpz_sizeinbase(cval, 2) >= int_bits
12995 || (lval_valid && mpz_cmp(cval, lval) > 0))
12996 {
12997 go_error_at(this->cap_->location(), "array index out of bounds");
12998 this->set_is_error();
12999 }
13000 else if (ival_valid && mpz_cmp(ival, cval) > 0)
13001 {
13002 go_error_at(this->cap_->location(),
13003 "invalid slice index: capacity less than start");
13004 this->set_is_error();
13005 }
13006 else if (eval_valid && mpz_cmp(eval, cval) > 0)
13007 {
13008 go_error_at(this->cap_->location(),
13009 "invalid slice index: capacity less than length");
13010 this->set_is_error();
13011 }
13012 mpz_clear(cval);
13013 }
13014
13015 if (eval_valid)
13016 mpz_clear(eval);
13017 }
13018 if (ival_valid)
13019 mpz_clear(ival);
13020 if (lval_valid)
13021 mpz_clear(lval);
13022
13023 // A slice of an array requires an addressable array. A slice of a
13024 // slice is always possible.
13025 if (this->end_ != NULL && !array_type->is_slice_type())
13026 {
13027 if (!this->array_->is_addressable())
13028 this->report_error(_("slice of unaddressable value"));
13029 else
13030 // Set the array address taken but not escape. The escape
13031 // analysis will make it escape to heap when needed.
13032 this->array_->address_taken(false);
13033 }
13034 }
13035
13036 // The subexpressions of an array index must be evaluated in order.
13037 // If this is indexing into an array, rather than a slice, then only
13038 // the index should be evaluated. Since this is called for values on
13039 // the left hand side of an assigment, evaluating the array, meaning
13040 // copying the array, will cause a different array to be modified.
13041
13042 bool
13043 Array_index_expression::do_must_eval_subexpressions_in_order(
13044 int* skip) const
13045 {
13046 *skip = this->array_->type()->is_slice_type() ? 0 : 1;
13047 return true;
13048 }
13049
13050 // Flatten array indexing: add temporary variables and bounds checks.
13051
13052 Expression*
13053 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
13054 Statement_inserter* inserter)
13055 {
13056 if (this->is_flattened_)
13057 return this;
13058 this->is_flattened_ = true;
13059
13060 Location loc = this->location();
13061
13062 if (this->is_error_expression())
13063 return Expression::make_error(loc);
13064
13065 Expression* array = this->array_;
13066 Expression* start = this->start_;
13067 Expression* end = this->end_;
13068 Expression* cap = this->cap_;
13069 if (array->is_error_expression()
13070 || array->type()->is_error_type()
13071 || start->is_error_expression()
13072 || start->type()->is_error_type()
13073 || (end != NULL
13074 && (end->is_error_expression() || end->type()->is_error_type()))
13075 || (cap != NULL
13076 && (cap->is_error_expression() || cap->type()->is_error_type())))
13077 {
13078 go_assert(saw_errors());
13079 return Expression::make_error(loc);
13080 }
13081
13082 Array_type* array_type = this->array_->type()->array_type();
13083 if (array_type == NULL)
13084 {
13085 go_assert(saw_errors());
13086 return Expression::make_error(loc);
13087 }
13088
13089 Temporary_statement* temp;
13090 if (array_type->is_slice_type() && !array->is_variable())
13091 {
13092 temp = Statement::make_temporary(NULL, array, loc);
13093 inserter->insert(temp);
13094 this->array_ = Expression::make_temporary_reference(temp, loc);
13095 array = this->array_;
13096 }
13097 if (!start->is_variable() && !start->is_constant())
13098 {
13099 temp = Statement::make_temporary(NULL, start, loc);
13100 inserter->insert(temp);
13101 this->start_ = Expression::make_temporary_reference(temp, loc);
13102 start = this->start_;
13103 }
13104 if (end != NULL
13105 && !end->is_nil_expression()
13106 && !end->is_variable()
13107 && !end->is_constant())
13108 {
13109 temp = Statement::make_temporary(NULL, end, loc);
13110 inserter->insert(temp);
13111 this->end_ = Expression::make_temporary_reference(temp, loc);
13112 end = this->end_;
13113 }
13114 if (cap != NULL && !cap->is_variable() && !cap->is_constant())
13115 {
13116 temp = Statement::make_temporary(NULL, cap, loc);
13117 inserter->insert(temp);
13118 this->cap_ = Expression::make_temporary_reference(temp, loc);
13119 cap = this->cap_;
13120 }
13121
13122 if (!this->needs_bounds_check_)
13123 return this;
13124
13125 Expression* len;
13126 if (!array_type->is_slice_type())
13127 {
13128 len = array_type->get_length(gogo, this->array_);
13129 go_assert(len->is_constant());
13130 }
13131 else
13132 {
13133 len = array_type->get_length(gogo, this->array_->copy());
13134 temp = Statement::make_temporary(NULL, len, loc);
13135 inserter->insert(temp);
13136 len = Expression::make_temporary_reference(temp, loc);
13137 }
13138
13139 Expression* scap = NULL;
13140 if (array_type->is_slice_type())
13141 {
13142 scap = array_type->get_capacity(gogo, this->array_->copy());
13143 temp = Statement::make_temporary(NULL, scap, loc);
13144 inserter->insert(temp);
13145 scap = Expression::make_temporary_reference(temp, loc);
13146 }
13147
13148 // The order of bounds checks here matches the order used by the gc
13149 // compiler, as tested by issue30116[u].go.
13150
13151 if (cap != NULL)
13152 {
13153 if (array_type->is_slice_type())
13154 Expression::check_bounds(cap, OPERATOR_LE, scap,
13155 Runtime::PANIC_SLICE3_ACAP,
13156 Runtime::PANIC_SLICE3_ACAP_U,
13157 Runtime::PANIC_EXTEND_SLICE3_ACAP,
13158 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
13159 inserter, loc);
13160 else
13161 Expression::check_bounds(cap, OPERATOR_LE, len,
13162 Runtime::PANIC_SLICE3_ALEN,
13163 Runtime::PANIC_SLICE3_ALEN_U,
13164 Runtime::PANIC_EXTEND_SLICE3_ALEN,
13165 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
13166 inserter, loc);
13167
13168 Expression* start_bound = cap;
13169 if (end != NULL && !end->is_nil_expression())
13170 {
13171 Expression::check_bounds(end, OPERATOR_LE, cap,
13172 Runtime::PANIC_SLICE3_B,
13173 Runtime::PANIC_SLICE3_B_U,
13174 Runtime::PANIC_EXTEND_SLICE3_B,
13175 Runtime::PANIC_EXTEND_SLICE3_B_U,
13176 inserter, loc);
13177 start_bound = end;
13178 }
13179
13180 Expression::check_bounds(start, OPERATOR_LE, start_bound,
13181 Runtime::PANIC_SLICE3_C,
13182 Runtime::PANIC_SLICE3_C_U,
13183 Runtime::PANIC_EXTEND_SLICE3_C,
13184 Runtime::PANIC_EXTEND_SLICE3_C_U,
13185 inserter, loc);
13186 }
13187 else if (end != NULL && !end->is_nil_expression())
13188 {
13189 if (array_type->is_slice_type())
13190 Expression::check_bounds(end, OPERATOR_LE, scap,
13191 Runtime::PANIC_SLICE_ACAP,
13192 Runtime::PANIC_SLICE_ACAP_U,
13193 Runtime::PANIC_EXTEND_SLICE_ACAP,
13194 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
13195 inserter, loc);
13196 else
13197 Expression::check_bounds(end, OPERATOR_LE, len,
13198 Runtime::PANIC_SLICE_ALEN,
13199 Runtime::PANIC_SLICE_ALEN_U,
13200 Runtime::PANIC_EXTEND_SLICE_ALEN,
13201 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13202 inserter, loc);
13203
13204 Expression::check_bounds(start, OPERATOR_LE, end,
13205 Runtime::PANIC_SLICE_B,
13206 Runtime::PANIC_SLICE_B_U,
13207 Runtime::PANIC_EXTEND_SLICE_B,
13208 Runtime::PANIC_EXTEND_SLICE_B_U,
13209 inserter, loc);
13210 }
13211 else if (end != NULL)
13212 {
13213 Expression* start_bound;
13214 if (array_type->is_slice_type())
13215 start_bound = scap;
13216 else
13217 start_bound = len;
13218 Expression::check_bounds(start, OPERATOR_LE, start_bound,
13219 Runtime::PANIC_SLICE_B,
13220 Runtime::PANIC_SLICE_B_U,
13221 Runtime::PANIC_EXTEND_SLICE_B,
13222 Runtime::PANIC_EXTEND_SLICE_B_U,
13223 inserter, loc);
13224 }
13225 else
13226 Expression::check_bounds(start, OPERATOR_LT, len,
13227 Runtime::PANIC_INDEX,
13228 Runtime::PANIC_INDEX_U,
13229 Runtime::PANIC_EXTEND_INDEX,
13230 Runtime::PANIC_EXTEND_INDEX_U,
13231 inserter, loc);
13232
13233 return this;
13234 }
13235
13236 // Return whether this expression is addressable.
13237
13238 bool
13239 Array_index_expression::do_is_addressable() const
13240 {
13241 // A slice expression is not addressable.
13242 if (this->end_ != NULL)
13243 return false;
13244
13245 // An index into a slice is addressable.
13246 if (this->array_->type()->is_slice_type())
13247 return true;
13248
13249 // An index into an array is addressable if the array is
13250 // addressable.
13251 return this->array_->is_addressable();
13252 }
13253
13254 void
13255 Array_index_expression::do_address_taken(bool escapes)
13256 {
13257 // In &x[0], if x is a slice, then x's address is not taken.
13258 if (!this->array_->type()->is_slice_type())
13259 this->array_->address_taken(escapes);
13260 }
13261
13262 // Get the backend representation for an array index.
13263
13264 Bexpression*
13265 Array_index_expression::do_get_backend(Translate_context* context)
13266 {
13267 Array_type* array_type = this->array_->type()->array_type();
13268 if (array_type == NULL)
13269 {
13270 go_assert(this->array_->type()->is_error());
13271 return context->backend()->error_expression();
13272 }
13273 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
13274
13275 Location loc = this->location();
13276 Gogo* gogo = context->gogo();
13277
13278 Type* int_type = Type::lookup_integer_type("int");
13279 Btype* int_btype = int_type->get_backend(gogo);
13280
13281 // Convert the length and capacity to "int". FIXME: Do we need to
13282 // do this?
13283 Bexpression* length = NULL;
13284 if (this->end_ == NULL || this->end_->is_nil_expression())
13285 {
13286 Expression* len = array_type->get_length(gogo, this->array_);
13287 length = len->get_backend(context);
13288 length = gogo->backend()->convert_expression(int_btype, length, loc);
13289 }
13290
13291 Bexpression* capacity = NULL;
13292 if (this->end_ != NULL)
13293 {
13294 Expression* cap = array_type->get_capacity(gogo, this->array_);
13295 capacity = cap->get_backend(context);
13296 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
13297 }
13298
13299 Bexpression* cap_arg = capacity;
13300 if (this->cap_ != NULL)
13301 {
13302 cap_arg = this->cap_->get_backend(context);
13303 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
13304 }
13305
13306 if (length == NULL)
13307 length = cap_arg;
13308
13309 if (this->start_->type()->integer_type() == NULL
13310 && !Type::are_convertible(int_type, this->start_->type(), NULL))
13311 {
13312 go_assert(saw_errors());
13313 return context->backend()->error_expression();
13314 }
13315
13316 Bexpression* start = this->start_->get_backend(context);
13317 start = gogo->backend()->convert_expression(int_btype, start, loc);
13318
13319 Bfunction* bfn = context->function()->func_value()->get_decl();
13320 if (this->end_ == NULL)
13321 {
13322 // Simple array indexing.
13323 Bexpression* ret;
13324 if (!array_type->is_slice_type())
13325 {
13326 Bexpression* array = this->array_->get_backend(context);
13327 ret = gogo->backend()->array_index_expression(array, start, loc);
13328 }
13329 else
13330 {
13331 Expression* valptr =
13332 array_type->get_value_pointer(gogo, this->array_,
13333 this->is_lvalue_);
13334 Bexpression* ptr = valptr->get_backend(context);
13335 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
13336
13337 Type* ele_type = this->array_->type()->array_type()->element_type();
13338 Btype* ele_btype = ele_type->get_backend(gogo);
13339 ret = gogo->backend()->indirect_expression(ele_btype, ptr, false,
13340 loc);
13341 }
13342 return ret;
13343 }
13344
13345 // Slice expression.
13346
13347 Bexpression* end;
13348 if (this->end_->is_nil_expression())
13349 end = length;
13350 else
13351 {
13352 end = this->end_->get_backend(context);
13353 end = gogo->backend()->convert_expression(int_btype, end, loc);
13354 }
13355
13356 Bexpression* result_length =
13357 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
13358
13359 Bexpression* result_capacity =
13360 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
13361
13362 // If the new capacity is zero, don't change val. Otherwise we can
13363 // get a pointer to the next object in memory, keeping it live
13364 // unnecessarily. When the capacity is zero, the actual pointer
13365 // value doesn't matter.
13366 Bexpression* zero =
13367 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13368 Bexpression* cond =
13369 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
13370 loc);
13371 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
13372 cond, zero,
13373 start, loc);
13374 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
13375 this->is_lvalue_);
13376 Bexpression* val = valptr->get_backend(context);
13377 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
13378
13379 Btype* struct_btype = this->type()->get_backend(gogo);
13380 std::vector<Bexpression*> init;
13381 init.push_back(val);
13382 init.push_back(result_length);
13383 init.push_back(result_capacity);
13384
13385 return gogo->backend()->constructor_expression(struct_btype, init, loc);
13386 }
13387
13388 // Export an array index expression.
13389
13390 void
13391 Array_index_expression::do_export(Export_function_body* efb) const
13392 {
13393 efb->write_c_string("(");
13394 this->array_->export_expression(efb);
13395 efb->write_c_string(")[");
13396
13397 Type* old_context = efb->type_context();
13398 efb->set_type_context(Type::lookup_integer_type("int"));
13399
13400 this->start_->export_expression(efb);
13401 if (this->end_ == NULL)
13402 go_assert(this->cap_ == NULL);
13403 else
13404 {
13405 efb->write_c_string(":");
13406 if (!this->end_->is_nil_expression())
13407 this->end_->export_expression(efb);
13408 if (this->cap_ != NULL)
13409 {
13410 efb->write_c_string(":");
13411 this->cap_->export_expression(efb);
13412 }
13413 }
13414
13415 efb->set_type_context(old_context);
13416
13417 efb->write_c_string("]");
13418 }
13419
13420 // Dump ast representation for an array index expression.
13421
13422 void
13423 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13424 const
13425 {
13426 Index_expression::dump_index_expression(ast_dump_context, this->array_,
13427 this->start_, this->end_, this->cap_);
13428 }
13429
13430 // Make an array index expression. END and CAP may be NULL.
13431
13432 Expression*
13433 Expression::make_array_index(Expression* array, Expression* start,
13434 Expression* end, Expression* cap,
13435 Location location)
13436 {
13437 return new Array_index_expression(array, start, end, cap, location);
13438 }
13439
13440 // Class String_index_expression.
13441
13442 // String index traversal.
13443
13444 int
13445 String_index_expression::do_traverse(Traverse* traverse)
13446 {
13447 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
13448 return TRAVERSE_EXIT;
13449 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13450 return TRAVERSE_EXIT;
13451 if (this->end_ != NULL)
13452 {
13453 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13454 return TRAVERSE_EXIT;
13455 }
13456 return TRAVERSE_CONTINUE;
13457 }
13458
13459 Expression*
13460 String_index_expression::do_flatten(Gogo*, Named_object*,
13461 Statement_inserter* inserter)
13462 {
13463 if (this->is_flattened_)
13464 return this;
13465 this->is_flattened_ = true;
13466
13467 Location loc = this->location();
13468
13469 if (this->is_error_expression())
13470 return Expression::make_error(loc);
13471
13472 Expression* string = this->string_;
13473 Expression* start = this->start_;
13474 Expression* end = this->end_;
13475 if (string->is_error_expression()
13476 || string->type()->is_error_type()
13477 || start->is_error_expression()
13478 || start->type()->is_error_type()
13479 || (end != NULL
13480 && (end->is_error_expression() || end->type()->is_error_type())))
13481 {
13482 go_assert(saw_errors());
13483 return Expression::make_error(loc);
13484 }
13485
13486 Temporary_statement* temp;
13487 if (!string->is_variable())
13488 {
13489 temp = Statement::make_temporary(NULL, string, loc);
13490 inserter->insert(temp);
13491 this->string_ = Expression::make_temporary_reference(temp, loc);
13492 string = this->string_;
13493 }
13494 if (!start->is_variable())
13495 {
13496 temp = Statement::make_temporary(NULL, start, loc);
13497 inserter->insert(temp);
13498 this->start_ = Expression::make_temporary_reference(temp, loc);
13499 start = this->start_;
13500 }
13501 if (end != NULL
13502 && !end->is_nil_expression()
13503 && !end->is_variable())
13504 {
13505 temp = Statement::make_temporary(NULL, end, loc);
13506 inserter->insert(temp);
13507 this->end_ = Expression::make_temporary_reference(temp, loc);
13508 end = this->end_;
13509 }
13510
13511 Expression* len = Expression::make_string_info(string->copy(),
13512 STRING_INFO_LENGTH, loc);
13513 temp = Statement::make_temporary(NULL, len, loc);
13514 inserter->insert(temp);
13515 len = Expression::make_temporary_reference(temp, loc);
13516
13517 // The order of bounds checks here matches the order used by the gc
13518 // compiler, as tested by issue30116[u].go.
13519
13520 if (end != NULL && !end->is_nil_expression())
13521 {
13522 Expression::check_bounds(end, OPERATOR_LE, len,
13523 Runtime::PANIC_SLICE_ALEN,
13524 Runtime::PANIC_SLICE_ALEN_U,
13525 Runtime::PANIC_EXTEND_SLICE_ALEN,
13526 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13527 inserter, loc);
13528 Expression::check_bounds(start, OPERATOR_LE, end,
13529 Runtime::PANIC_SLICE_B,
13530 Runtime::PANIC_SLICE_B_U,
13531 Runtime::PANIC_EXTEND_SLICE_B,
13532 Runtime::PANIC_EXTEND_SLICE_B_U,
13533 inserter, loc);
13534 }
13535 else if (end != NULL)
13536 Expression::check_bounds(start, OPERATOR_LE, len,
13537 Runtime::PANIC_SLICE_B,
13538 Runtime::PANIC_SLICE_B_U,
13539 Runtime::PANIC_EXTEND_SLICE_B,
13540 Runtime::PANIC_EXTEND_SLICE_B_U,
13541 inserter, loc);
13542 else
13543 Expression::check_bounds(start, OPERATOR_LT, len,
13544 Runtime::PANIC_INDEX,
13545 Runtime::PANIC_INDEX_U,
13546 Runtime::PANIC_EXTEND_INDEX,
13547 Runtime::PANIC_EXTEND_INDEX_U,
13548 inserter, loc);
13549
13550 return this;
13551 }
13552
13553 // Return the type of a string index.
13554
13555 Type*
13556 String_index_expression::do_type()
13557 {
13558 if (this->end_ == NULL)
13559 return Type::lookup_integer_type("byte");
13560 else
13561 return this->string_->type();
13562 }
13563
13564 // Determine the type of a string index.
13565
13566 void
13567 String_index_expression::do_determine_type(const Type_context*)
13568 {
13569 this->string_->determine_type_no_context();
13570
13571 Type_context index_context(Type::lookup_integer_type("int"), false);
13572 this->start_->determine_type(&index_context);
13573 if (this->end_ != NULL)
13574 this->end_->determine_type(&index_context);
13575 }
13576
13577 // Check types of a string index.
13578
13579 void
13580 String_index_expression::do_check_types(Gogo*)
13581 {
13582 Numeric_constant nc;
13583 unsigned long v;
13584 if (this->start_->type()->integer_type() == NULL
13585 && !this->start_->type()->is_error()
13586 && (!this->start_->type()->is_abstract()
13587 || !this->start_->numeric_constant_value(&nc)
13588 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13589 this->report_error(_("index must be integer"));
13590 if (this->end_ != NULL
13591 && this->end_->type()->integer_type() == NULL
13592 && !this->end_->type()->is_error()
13593 && !this->end_->is_nil_expression()
13594 && !this->end_->is_error_expression()
13595 && (!this->end_->type()->is_abstract()
13596 || !this->end_->numeric_constant_value(&nc)
13597 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13598 this->report_error(_("slice end must be integer"));
13599
13600 std::string sval;
13601 bool sval_valid = this->string_->string_constant_value(&sval);
13602
13603 Numeric_constant inc;
13604 mpz_t ival;
13605 bool ival_valid = false;
13606 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13607 {
13608 ival_valid = true;
13609 if (mpz_sgn(ival) < 0
13610 || (sval_valid
13611 && (this->end_ == NULL
13612 ? mpz_cmp_ui(ival, sval.length()) >= 0
13613 : mpz_cmp_ui(ival, sval.length()) > 0)))
13614 {
13615 go_error_at(this->start_->location(), "string index out of bounds");
13616 this->set_is_error();
13617 }
13618 }
13619 if (this->end_ != NULL && !this->end_->is_nil_expression())
13620 {
13621 Numeric_constant enc;
13622 mpz_t eval;
13623 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13624 {
13625 if (mpz_sgn(eval) < 0
13626 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
13627 {
13628 go_error_at(this->end_->location(), "string index out of bounds");
13629 this->set_is_error();
13630 }
13631 else if (ival_valid && mpz_cmp(ival, eval) > 0)
13632 this->report_error(_("inverted slice range"));
13633 mpz_clear(eval);
13634 }
13635 }
13636 if (ival_valid)
13637 mpz_clear(ival);
13638 }
13639
13640 // Get the backend representation for a string index.
13641
13642 Bexpression*
13643 String_index_expression::do_get_backend(Translate_context* context)
13644 {
13645 Location loc = this->location();
13646 Gogo* gogo = context->gogo();
13647
13648 Type* int_type = Type::lookup_integer_type("int");
13649
13650 // It is possible that an error occurred earlier because the start index
13651 // cannot be represented as an integer type. In this case, we shouldn't
13652 // try casting the starting index into an integer since
13653 // Type_conversion_expression will fail to get the backend representation.
13654 // FIXME.
13655 if (this->start_->type()->integer_type() == NULL
13656 && !Type::are_convertible(int_type, this->start_->type(), NULL))
13657 {
13658 go_assert(saw_errors());
13659 return context->backend()->error_expression();
13660 }
13661
13662 go_assert(this->string_->is_variable());
13663 go_assert(this->start_->is_variable());
13664
13665 Expression* start = Expression::make_cast(int_type, this->start_, loc);
13666 Bfunction* bfn = context->function()->func_value()->get_decl();
13667
13668 Expression* length =
13669 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
13670 Expression* bytes =
13671 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
13672
13673 Bexpression* bstart = start->get_backend(context);
13674 Bexpression* ptr = bytes->get_backend(context);
13675
13676 if (this->end_ == NULL)
13677 {
13678 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
13679 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
13680 return gogo->backend()->indirect_expression(ubtype, ptr, false, loc);
13681 }
13682
13683 Expression* end = NULL;
13684 if (this->end_->is_nil_expression())
13685 end = length;
13686 else
13687 {
13688 go_assert(this->end_->is_variable());
13689 end = Expression::make_cast(int_type, this->end_, loc);
13690 }
13691
13692 end = end->copy();
13693 Bexpression* bend = end->get_backend(context);
13694 Bexpression* new_length =
13695 gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
13696
13697 // If the new length is zero, don't change pointer. Otherwise we can
13698 // get a pointer to the next object in memory, keeping it live
13699 // unnecessarily. When the length is zero, the actual pointer
13700 // value doesn't matter.
13701 Btype* int_btype = int_type->get_backend(gogo);
13702 Bexpression* zero =
13703 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13704 Bexpression* cond =
13705 gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
13706 loc);
13707 Bexpression* offset =
13708 gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
13709 bstart, loc);
13710
13711 ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
13712
13713 Btype* str_btype = this->type()->get_backend(gogo);
13714 std::vector<Bexpression*> init;
13715 init.push_back(ptr);
13716 init.push_back(new_length);
13717 return gogo->backend()->constructor_expression(str_btype, init, loc);
13718 }
13719
13720 // Export a string index expression.
13721
13722 void
13723 String_index_expression::do_export(Export_function_body* efb) const
13724 {
13725 efb->write_c_string("(");
13726 this->string_->export_expression(efb);
13727 efb->write_c_string(")[");
13728
13729 Type* old_context = efb->type_context();
13730 efb->set_type_context(Type::lookup_integer_type("int"));
13731
13732 this->start_->export_expression(efb);
13733 if (this->end_ != NULL)
13734 {
13735 efb->write_c_string(":");
13736 if (!this->end_->is_nil_expression())
13737 this->end_->export_expression(efb);
13738 }
13739
13740 efb->set_type_context(old_context);
13741
13742 efb->write_c_string("]");
13743 }
13744
13745 // Dump ast representation for a string index expression.
13746
13747 void
13748 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13749 const
13750 {
13751 Index_expression::dump_index_expression(ast_dump_context, this->string_,
13752 this->start_, this->end_, NULL);
13753 }
13754
13755 // Make a string index expression. END may be NULL.
13756
13757 Expression*
13758 Expression::make_string_index(Expression* string, Expression* start,
13759 Expression* end, Location location)
13760 {
13761 return new String_index_expression(string, start, end, location);
13762 }
13763
13764 // Class Map_index.
13765
13766 // Get the type of the map.
13767
13768 Map_type*
13769 Map_index_expression::get_map_type() const
13770 {
13771 Map_type* mt = this->map_->type()->map_type();
13772 if (mt == NULL)
13773 go_assert(saw_errors());
13774 return mt;
13775 }
13776
13777 // Map index traversal.
13778
13779 int
13780 Map_index_expression::do_traverse(Traverse* traverse)
13781 {
13782 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
13783 return TRAVERSE_EXIT;
13784 return Expression::traverse(&this->index_, traverse);
13785 }
13786
13787 // We need to pass in a pointer to the key, so flatten the index into a
13788 // temporary variable if it isn't already. The value pointer will be
13789 // dereferenced and checked for nil, so flatten into a temporary to avoid
13790 // recomputation.
13791
13792 Expression*
13793 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
13794 Statement_inserter* inserter)
13795 {
13796 Location loc = this->location();
13797 Map_type* mt = this->get_map_type();
13798 if (this->index()->is_error_expression()
13799 || this->index()->type()->is_error_type()
13800 || mt->is_error_type())
13801 {
13802 go_assert(saw_errors());
13803 return Expression::make_error(loc);
13804 }
13805
13806 // Avoid copy for string([]byte) conversions used in map keys.
13807 // mapaccess doesn't keep the reference, so this is safe.
13808 Type_conversion_expression* ce = this->index_->conversion_expression();
13809 if (ce != NULL && ce->type()->is_string_type()
13810 && ce->expr()->type()->is_slice_type())
13811 ce->set_no_copy(true);
13812
13813 if (!Type::are_identical(mt->key_type(), this->index_->type(),
13814 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
13815 NULL))
13816 {
13817 if (this->index_->type()->interface_type() != NULL
13818 && !this->index_->is_variable())
13819 {
13820 Temporary_statement* temp =
13821 Statement::make_temporary(NULL, this->index_, loc);
13822 inserter->insert(temp);
13823 this->index_ = Expression::make_temporary_reference(temp, loc);
13824 }
13825 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
13826 this->index_, loc);
13827 }
13828
13829 if (!this->index_->is_variable())
13830 {
13831 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
13832 loc);
13833 inserter->insert(temp);
13834 this->index_ = Expression::make_temporary_reference(temp, loc);
13835 }
13836
13837 if (this->value_pointer_ == NULL)
13838 this->get_value_pointer(gogo);
13839 if (this->value_pointer_->is_error_expression()
13840 || this->value_pointer_->type()->is_error_type())
13841 return Expression::make_error(loc);
13842 if (!this->value_pointer_->is_variable())
13843 {
13844 Temporary_statement* temp =
13845 Statement::make_temporary(NULL, this->value_pointer_, loc);
13846 inserter->insert(temp);
13847 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
13848 }
13849
13850 return this;
13851 }
13852
13853 // Return the type of a map index.
13854
13855 Type*
13856 Map_index_expression::do_type()
13857 {
13858 Map_type* mt = this->get_map_type();
13859 if (mt == NULL)
13860 return Type::make_error_type();
13861 return mt->val_type();
13862 }
13863
13864 // Fix the type of a map index.
13865
13866 void
13867 Map_index_expression::do_determine_type(const Type_context*)
13868 {
13869 this->map_->determine_type_no_context();
13870 Map_type* mt = this->get_map_type();
13871 Type* key_type = mt == NULL ? NULL : mt->key_type();
13872 Type_context subcontext(key_type, false);
13873 this->index_->determine_type(&subcontext);
13874 }
13875
13876 // Check types of a map index.
13877
13878 void
13879 Map_index_expression::do_check_types(Gogo*)
13880 {
13881 std::string reason;
13882 Map_type* mt = this->get_map_type();
13883 if (mt == NULL)
13884 return;
13885 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
13886 {
13887 if (reason.empty())
13888 this->report_error(_("incompatible type for map index"));
13889 else
13890 {
13891 go_error_at(this->location(), "incompatible type for map index (%s)",
13892 reason.c_str());
13893 this->set_is_error();
13894 }
13895 }
13896 }
13897
13898 // Add explicit type conversions.
13899
13900 void
13901 Map_index_expression::do_add_conversions()
13902 {
13903 Map_type* mt = this->get_map_type();
13904 if (mt == NULL)
13905 return;
13906 Type* lt = mt->key_type();
13907 Type* rt = this->index_->type();
13908 if (!Type::are_identical(lt, rt, 0, NULL)
13909 && lt->interface_type() != NULL)
13910 this->index_ = Expression::make_cast(lt, this->index_, this->location());
13911 }
13912
13913 // Get the backend representation for a map index.
13914
13915 Bexpression*
13916 Map_index_expression::do_get_backend(Translate_context* context)
13917 {
13918 Map_type* type = this->get_map_type();
13919 if (type == NULL)
13920 {
13921 go_assert(saw_errors());
13922 return context->backend()->error_expression();
13923 }
13924
13925 go_assert(this->value_pointer_ != NULL
13926 && this->value_pointer_->is_variable());
13927
13928 Expression* val = Expression::make_dereference(this->value_pointer_,
13929 NIL_CHECK_NOT_NEEDED,
13930 this->location());
13931 return val->get_backend(context);
13932 }
13933
13934 // Get an expression for the map index. This returns an expression
13935 // that evaluates to a pointer to a value. If the key is not in the
13936 // map, the pointer will point to a zero value.
13937
13938 Expression*
13939 Map_index_expression::get_value_pointer(Gogo* gogo)
13940 {
13941 if (this->value_pointer_ == NULL)
13942 {
13943 Map_type* type = this->get_map_type();
13944 if (type == NULL)
13945 {
13946 go_assert(saw_errors());
13947 return Expression::make_error(this->location());
13948 }
13949
13950 Location loc = this->location();
13951 Expression* map_ref = this->map_;
13952
13953 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
13954 this->index_,
13955 loc);
13956
13957 Expression* type_expr = Expression::make_type_descriptor(type, loc);
13958 Expression* zero = type->fat_zero_value(gogo);
13959 Expression* map_index;
13960 if (zero == NULL)
13961 {
13962 Runtime::Function code;
13963 Expression* key;
13964 switch (type->algorithm(gogo))
13965 {
13966 case Map_type::MAP_ALG_FAST32:
13967 case Map_type::MAP_ALG_FAST32PTR:
13968 {
13969 Type* uint32_type = Type::lookup_integer_type("uint32");
13970 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
13971 key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
13972 loc);
13973 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13974 loc);
13975 code = Runtime::MAPACCESS1_FAST32;
13976 break;
13977 }
13978 case Map_type::MAP_ALG_FAST64:
13979 case Map_type::MAP_ALG_FAST64PTR:
13980 {
13981 Type* uint64_type = Type::lookup_integer_type("uint64");
13982 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
13983 key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
13984 loc);
13985 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13986 loc);
13987 code = Runtime::MAPACCESS1_FAST64;
13988 break;
13989 }
13990 case Map_type::MAP_ALG_FASTSTR:
13991 key = this->index_;
13992 code = Runtime::MAPACCESS1_FASTSTR;
13993 break;
13994 default:
13995 key = index_ptr;
13996 code = Runtime::MAPACCESS1;
13997 break;
13998 }
13999 map_index = Runtime::make_call(code, loc, 3,
14000 type_expr, map_ref, key);
14001 }
14002 else
14003 map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
14004 type_expr, map_ref, index_ptr, zero);
14005
14006 Type* val_type = type->val_type();
14007 this->value_pointer_ =
14008 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
14009 map_index, this->location());
14010 }
14011
14012 return this->value_pointer_;
14013 }
14014
14015 // Export a map index expression.
14016
14017 void
14018 Map_index_expression::do_export(Export_function_body* efb) const
14019 {
14020 efb->write_c_string("(");
14021 this->map_->export_expression(efb);
14022 efb->write_c_string(")[");
14023
14024 Type* old_context = efb->type_context();
14025 efb->set_type_context(this->get_map_type()->key_type());
14026
14027 this->index_->export_expression(efb);
14028
14029 efb->set_type_context(old_context);
14030
14031 efb->write_c_string("]");
14032 }
14033
14034 // Dump ast representation for a map index expression
14035
14036 void
14037 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14038 const
14039 {
14040 Index_expression::dump_index_expression(ast_dump_context, this->map_,
14041 this->index_, NULL, NULL);
14042 }
14043
14044 // Make a map index expression.
14045
14046 Map_index_expression*
14047 Expression::make_map_index(Expression* map, Expression* index,
14048 Location location)
14049 {
14050 return new Map_index_expression(map, index, location);
14051 }
14052
14053 // Class Field_reference_expression.
14054
14055 // Lower a field reference expression. There is nothing to lower, but
14056 // this is where we generate the tracking information for fields with
14057 // the magic go:"track" tag.
14058
14059 Expression*
14060 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
14061 Statement_inserter* inserter, int)
14062 {
14063 Struct_type* struct_type = this->expr_->type()->struct_type();
14064 if (struct_type == NULL)
14065 {
14066 // Error will be reported elsewhere.
14067 return this;
14068 }
14069 const Struct_field* field = struct_type->field(this->field_index_);
14070 if (field == NULL)
14071 return this;
14072 if (!field->has_tag())
14073 return this;
14074 if (field->tag().find("go:\"track\"") == std::string::npos)
14075 return this;
14076
14077 // References from functions generated by the compiler don't count.
14078 if (function != NULL && function->func_value()->is_type_specific_function())
14079 return this;
14080
14081 // We have found a reference to a tracked field. Build a call to
14082 // the runtime function __go_fieldtrack with a string that describes
14083 // the field. FIXME: We should only call this once per referenced
14084 // field per function, not once for each reference to the field.
14085
14086 if (this->called_fieldtrack_)
14087 return this;
14088 this->called_fieldtrack_ = true;
14089
14090 Location loc = this->location();
14091
14092 std::string s = "fieldtrack \"";
14093 Named_type* nt = this->expr_->type()->unalias()->named_type();
14094 if (nt == NULL || nt->named_object()->package() == NULL)
14095 s.append(gogo->pkgpath());
14096 else
14097 s.append(nt->named_object()->package()->pkgpath());
14098 s.push_back('.');
14099 if (nt != NULL)
14100 s.append(Gogo::unpack_hidden_name(nt->name()));
14101 s.push_back('.');
14102 s.append(Gogo::unpack_hidden_name(field->field_name()));
14103 s.push_back('"');
14104
14105 // We can't use a string here, because internally a string holds a
14106 // pointer to the actual bytes; when the linker garbage collects the
14107 // string, it won't garbage collect the bytes. So we use a
14108 // [...]byte.
14109
14110 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
14111
14112 Type* byte_type = Type::lookup_integer_type("byte");
14113 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
14114 array_type->set_is_array_incomparable();
14115
14116 Expression_list* bytes = new Expression_list();
14117 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
14118 {
14119 unsigned char c = static_cast<unsigned char>(*p);
14120 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
14121 }
14122
14123 Expression* e = Expression::make_composite_literal(array_type, 0, false,
14124 bytes, false, loc);
14125
14126 Variable* var = new Variable(array_type, e, true, false, false, loc);
14127
14128 static int count;
14129 char buf[50];
14130 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
14131 ++count;
14132
14133 Named_object* no = gogo->add_variable(buf, var);
14134 e = Expression::make_var_reference(no, loc);
14135 e = Expression::make_unary(OPERATOR_AND, e, loc);
14136
14137 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
14138 gogo->lower_expression(function, inserter, &call);
14139 inserter->insert(Statement::make_statement(call, false));
14140
14141 // Put this function, and the global variable we just created, into
14142 // unique sections. This will permit the linker to garbage collect
14143 // them if they are not referenced. The effect is that the only
14144 // strings, indicating field references, that will wind up in the
14145 // executable will be those for functions that are actually needed.
14146 if (function != NULL)
14147 function->func_value()->set_in_unique_section();
14148 var->set_in_unique_section();
14149
14150 return this;
14151 }
14152
14153 // Return the type of a field reference.
14154
14155 Type*
14156 Field_reference_expression::do_type()
14157 {
14158 Type* type = this->expr_->type();
14159 if (type->is_error())
14160 return type;
14161 Struct_type* struct_type = type->struct_type();
14162 go_assert(struct_type != NULL);
14163 return struct_type->field(this->field_index_)->type();
14164 }
14165
14166 // Check the types for a field reference.
14167
14168 void
14169 Field_reference_expression::do_check_types(Gogo*)
14170 {
14171 Type* type = this->expr_->type();
14172 if (type->is_error())
14173 return;
14174 Struct_type* struct_type = type->struct_type();
14175 go_assert(struct_type != NULL);
14176 go_assert(struct_type->field(this->field_index_) != NULL);
14177 }
14178
14179 // Get the backend representation for a field reference.
14180
14181 Bexpression*
14182 Field_reference_expression::do_get_backend(Translate_context* context)
14183 {
14184 Bexpression* bstruct = this->expr_->get_backend(context);
14185 return context->gogo()->backend()->struct_field_expression(bstruct,
14186 this->field_index_,
14187 this->location());
14188 }
14189
14190 // Dump ast representation for a field reference expression.
14191
14192 void
14193 Field_reference_expression::do_dump_expression(
14194 Ast_dump_context* ast_dump_context) const
14195 {
14196 this->expr_->dump_expression(ast_dump_context);
14197 ast_dump_context->ostream() << "." << this->field_index_;
14198 }
14199
14200 // Make a reference to a qualified identifier in an expression.
14201
14202 Field_reference_expression*
14203 Expression::make_field_reference(Expression* expr, unsigned int field_index,
14204 Location location)
14205 {
14206 return new Field_reference_expression(expr, field_index, location);
14207 }
14208
14209 // Class Interface_field_reference_expression.
14210
14211 // Return an expression for the pointer to the function to call.
14212
14213 Expression*
14214 Interface_field_reference_expression::get_function()
14215 {
14216 Expression* ref = this->expr_;
14217 Location loc = this->location();
14218 if (ref->type()->points_to() != NULL)
14219 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
14220
14221 Expression* mtable =
14222 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
14223 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
14224
14225 std::string name = Gogo::unpack_hidden_name(this->name_);
14226 unsigned int index;
14227 const Struct_field* field = mtable_type->find_local_field(name, &index);
14228 go_assert(field != NULL);
14229
14230 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
14231 return Expression::make_field_reference(mtable, index, loc);
14232 }
14233
14234 // Return an expression for the first argument to pass to the interface
14235 // function.
14236
14237 Expression*
14238 Interface_field_reference_expression::get_underlying_object()
14239 {
14240 Expression* expr = this->expr_;
14241 if (expr->type()->points_to() != NULL)
14242 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
14243 this->location());
14244 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
14245 this->location());
14246 }
14247
14248 // Traversal.
14249
14250 int
14251 Interface_field_reference_expression::do_traverse(Traverse* traverse)
14252 {
14253 return Expression::traverse(&this->expr_, traverse);
14254 }
14255
14256 // Lower the expression. If this expression is not called, we need to
14257 // evaluate the expression twice when converting to the backend
14258 // interface. So introduce a temporary variable if necessary.
14259
14260 Expression*
14261 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
14262 Statement_inserter* inserter)
14263 {
14264 if (this->expr_->is_error_expression()
14265 || this->expr_->type()->is_error_type())
14266 {
14267 go_assert(saw_errors());
14268 return Expression::make_error(this->location());
14269 }
14270
14271 if (!this->expr_->is_variable())
14272 {
14273 Temporary_statement* temp =
14274 Statement::make_temporary(NULL, this->expr_, this->location());
14275 inserter->insert(temp);
14276 this->expr_ = Expression::make_temporary_reference(temp, this->location());
14277 }
14278 return this;
14279 }
14280
14281 // Return the type of an interface field reference.
14282
14283 Type*
14284 Interface_field_reference_expression::do_type()
14285 {
14286 Type* expr_type = this->expr_->type();
14287
14288 Type* points_to = expr_type->points_to();
14289 if (points_to != NULL)
14290 expr_type = points_to;
14291
14292 Interface_type* interface_type = expr_type->interface_type();
14293 if (interface_type == NULL)
14294 return Type::make_error_type();
14295
14296 const Typed_identifier* method = interface_type->find_method(this->name_);
14297 if (method == NULL)
14298 return Type::make_error_type();
14299
14300 return method->type();
14301 }
14302
14303 // Determine types.
14304
14305 void
14306 Interface_field_reference_expression::do_determine_type(const Type_context*)
14307 {
14308 this->expr_->determine_type_no_context();
14309 }
14310
14311 // Check the types for an interface field reference.
14312
14313 void
14314 Interface_field_reference_expression::do_check_types(Gogo*)
14315 {
14316 Type* type = this->expr_->type();
14317
14318 Type* points_to = type->points_to();
14319 if (points_to != NULL)
14320 type = points_to;
14321
14322 Interface_type* interface_type = type->interface_type();
14323 if (interface_type == NULL)
14324 {
14325 if (!type->is_error_type())
14326 this->report_error(_("expected interface or pointer to interface"));
14327 }
14328 else
14329 {
14330 const Typed_identifier* method =
14331 interface_type->find_method(this->name_);
14332 if (method == NULL)
14333 {
14334 go_error_at(this->location(), "method %qs not in interface",
14335 Gogo::message_name(this->name_).c_str());
14336 this->set_is_error();
14337 }
14338 }
14339 }
14340
14341 // If an interface field reference is not simply called, then it is
14342 // represented as a closure. The closure will hold a single variable,
14343 // the value of the interface on which the method should be called.
14344 // The function will be a simple thunk that pulls the value from the
14345 // closure and calls the method with the remaining arguments.
14346
14347 // Because method values are not common, we don't build all thunks for
14348 // all possible interface methods, but instead only build them as we
14349 // need them. In particular, we even build them on demand for
14350 // interface methods defined in other packages.
14351
14352 Interface_field_reference_expression::Interface_method_thunks
14353 Interface_field_reference_expression::interface_method_thunks;
14354
14355 // Find or create the thunk to call method NAME on TYPE.
14356
14357 Named_object*
14358 Interface_field_reference_expression::create_thunk(Gogo* gogo,
14359 Interface_type* type,
14360 const std::string& name)
14361 {
14362 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
14363 std::pair<Interface_method_thunks::iterator, bool> ins =
14364 Interface_field_reference_expression::interface_method_thunks.insert(val);
14365 if (ins.second)
14366 {
14367 // This is the first time we have seen this interface.
14368 ins.first->second = new Method_thunks();
14369 }
14370
14371 for (Method_thunks::const_iterator p = ins.first->second->begin();
14372 p != ins.first->second->end();
14373 p++)
14374 if (p->first == name)
14375 return p->second;
14376
14377 Location loc = type->location();
14378
14379 const Typed_identifier* method_id = type->find_method(name);
14380 if (method_id == NULL)
14381 return Named_object::make_erroneous_name(gogo->thunk_name());
14382
14383 Function_type* orig_fntype = method_id->type()->function_type();
14384 if (orig_fntype == NULL)
14385 return Named_object::make_erroneous_name(gogo->thunk_name());
14386
14387 Struct_field_list* sfl = new Struct_field_list();
14388 // The type here is wrong--it should be the C function type. But it
14389 // doesn't really matter.
14390 Type* vt = Type::make_pointer_type(Type::make_void_type());
14391 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
14392 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
14393 Struct_type* st = Type::make_struct_type(sfl, loc);
14394 st->set_is_struct_incomparable();
14395 Type* closure_type = Type::make_pointer_type(st);
14396
14397 Function_type* new_fntype = orig_fntype->copy_with_names();
14398
14399 std::string thunk_name = gogo->thunk_name();
14400 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
14401 false, loc);
14402
14403 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
14404 cvar->set_is_used();
14405 cvar->set_is_closure();
14406 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
14407 NULL, cvar);
14408 new_no->func_value()->set_closure_var(cp);
14409
14410 gogo->start_block(loc);
14411
14412 // Field 0 of the closure is the function code pointer, field 1 is
14413 // the value on which to invoke the method.
14414 Expression* arg = Expression::make_var_reference(cp, loc);
14415 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
14416 arg = Expression::make_field_reference(arg, 1, loc);
14417
14418 Expression *ifre = Expression::make_interface_field_reference(arg, name,
14419 loc);
14420
14421 const Typed_identifier_list* orig_params = orig_fntype->parameters();
14422 Expression_list* args;
14423 if (orig_params == NULL || orig_params->empty())
14424 args = NULL;
14425 else
14426 {
14427 const Typed_identifier_list* new_params = new_fntype->parameters();
14428 args = new Expression_list();
14429 for (Typed_identifier_list::const_iterator p = new_params->begin();
14430 p != new_params->end();
14431 ++p)
14432 {
14433 Named_object* p_no = gogo->lookup(p->name(), NULL);
14434 go_assert(p_no != NULL
14435 && p_no->is_variable()
14436 && p_no->var_value()->is_parameter());
14437 args->push_back(Expression::make_var_reference(p_no, loc));
14438 }
14439 }
14440
14441 Call_expression* call = Expression::make_call(ifre, args,
14442 orig_fntype->is_varargs(),
14443 loc);
14444 call->set_varargs_are_lowered();
14445
14446 Statement* s = Statement::make_return_from_call(call, loc);
14447 gogo->add_statement(s);
14448 Block* b = gogo->finish_block(loc);
14449 gogo->add_block(b, loc);
14450 gogo->lower_block(new_no, b);
14451 gogo->flatten_block(new_no, b);
14452 gogo->finish_function(loc);
14453
14454 ins.first->second->push_back(std::make_pair(name, new_no));
14455 return new_no;
14456 }
14457
14458 // Get the backend representation for a method value.
14459
14460 Bexpression*
14461 Interface_field_reference_expression::do_get_backend(Translate_context* context)
14462 {
14463 Interface_type* type = this->expr_->type()->interface_type();
14464 if (type == NULL)
14465 {
14466 go_assert(saw_errors());
14467 return context->backend()->error_expression();
14468 }
14469
14470 Named_object* thunk =
14471 Interface_field_reference_expression::create_thunk(context->gogo(),
14472 type, this->name_);
14473 if (thunk->is_erroneous())
14474 {
14475 go_assert(saw_errors());
14476 return context->backend()->error_expression();
14477 }
14478
14479 // FIXME: We should lower this earlier, but we can't it lower it in
14480 // the lowering pass because at that point we don't know whether we
14481 // need to create the thunk or not. If the expression is called, we
14482 // don't need the thunk.
14483
14484 Location loc = this->location();
14485
14486 Struct_field_list* fields = new Struct_field_list();
14487 fields->push_back(Struct_field(Typed_identifier("fn",
14488 thunk->func_value()->type(),
14489 loc)));
14490 fields->push_back(Struct_field(Typed_identifier("val",
14491 this->expr_->type(),
14492 loc)));
14493 Struct_type* st = Type::make_struct_type(fields, loc);
14494 st->set_is_struct_incomparable();
14495
14496 Expression_list* vals = new Expression_list();
14497 vals->push_back(Expression::make_func_code_reference(thunk, loc));
14498 vals->push_back(this->expr_);
14499
14500 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
14501 Bexpression* bclosure =
14502 Expression::make_heap_expression(expr, loc)->get_backend(context);
14503
14504 Gogo* gogo = context->gogo();
14505 Btype* btype = this->type()->get_backend(gogo);
14506 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
14507
14508 Expression* nil_check =
14509 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
14510 Expression::make_nil(loc), loc);
14511 Bexpression* bnil_check = nil_check->get_backend(context);
14512
14513 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
14514 Bexpression* bcrash = crash->get_backend(context);
14515
14516 Bfunction* bfn = context->function()->func_value()->get_decl();
14517 Bexpression* bcond =
14518 gogo->backend()->conditional_expression(bfn, NULL,
14519 bnil_check, bcrash, NULL, loc);
14520 Bfunction* bfunction = context->function()->func_value()->get_decl();
14521 Bstatement* cond_statement =
14522 gogo->backend()->expression_statement(bfunction, bcond);
14523 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
14524 }
14525
14526 // Dump ast representation for an interface field reference.
14527
14528 void
14529 Interface_field_reference_expression::do_dump_expression(
14530 Ast_dump_context* ast_dump_context) const
14531 {
14532 this->expr_->dump_expression(ast_dump_context);
14533 ast_dump_context->ostream() << "." << this->name_;
14534 }
14535
14536 // Make a reference to a field in an interface.
14537
14538 Expression*
14539 Expression::make_interface_field_reference(Expression* expr,
14540 const std::string& field,
14541 Location location)
14542 {
14543 return new Interface_field_reference_expression(expr, field, location);
14544 }
14545
14546 // A general selector. This is a Parser_expression for LEFT.NAME. It
14547 // is lowered after we know the type of the left hand side.
14548
14549 class Selector_expression : public Parser_expression
14550 {
14551 public:
14552 Selector_expression(Expression* left, const std::string& name,
14553 Location location)
14554 : Parser_expression(EXPRESSION_SELECTOR, location),
14555 left_(left), name_(name)
14556 { }
14557
14558 protected:
14559 int
14560 do_traverse(Traverse* traverse)
14561 { return Expression::traverse(&this->left_, traverse); }
14562
14563 Expression*
14564 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
14565
14566 Expression*
14567 do_copy()
14568 {
14569 return new Selector_expression(this->left_->copy(), this->name_,
14570 this->location());
14571 }
14572
14573 void
14574 do_dump_expression(Ast_dump_context* ast_dump_context) const;
14575
14576 private:
14577 Expression*
14578 lower_method_expression(Gogo*);
14579
14580 // The expression on the left hand side.
14581 Expression* left_;
14582 // The name on the right hand side.
14583 std::string name_;
14584 };
14585
14586 // Lower a selector expression once we know the real type of the left
14587 // hand side.
14588
14589 Expression*
14590 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
14591 int)
14592 {
14593 Expression* left = this->left_;
14594 if (left->is_type_expression())
14595 return this->lower_method_expression(gogo);
14596 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
14597 this->location());
14598 }
14599
14600 // Lower a method expression T.M or (*T).M. We turn this into a
14601 // function literal.
14602
14603 Expression*
14604 Selector_expression::lower_method_expression(Gogo* gogo)
14605 {
14606 Location location = this->location();
14607 Type* left_type = this->left_->type();
14608 Type* type = left_type;
14609 const std::string& name(this->name_);
14610
14611 bool is_pointer;
14612 if (type->points_to() == NULL)
14613 is_pointer = false;
14614 else
14615 {
14616 is_pointer = true;
14617 type = type->points_to();
14618 }
14619
14620 Named_type* nt = type->named_type();
14621 Struct_type* st = type->struct_type();
14622 bool is_ambiguous;
14623 Method* method = NULL;
14624 if (nt != NULL)
14625 method = nt->method_function(name, &is_ambiguous);
14626 else if (st != NULL)
14627 method = st->method_function(name, &is_ambiguous);
14628 const Typed_identifier* imethod = NULL;
14629 if (method == NULL && !is_pointer)
14630 {
14631 Interface_type* it = type->interface_type();
14632 if (it != NULL)
14633 imethod = it->find_method(name);
14634 }
14635
14636 if ((method == NULL && imethod == NULL)
14637 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
14638 {
14639 if (nt != NULL)
14640 {
14641 if (!is_ambiguous)
14642 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
14643 is_pointer ? "*" : "",
14644 nt->message_name().c_str(),
14645 Gogo::message_name(name).c_str());
14646 else
14647 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
14648 Gogo::message_name(name).c_str(),
14649 is_pointer ? "*" : "",
14650 nt->message_name().c_str());
14651 }
14652 else
14653 {
14654 if (!is_ambiguous)
14655 go_error_at(location, "type has no method %<%s%>",
14656 Gogo::message_name(name).c_str());
14657 else
14658 go_error_at(location, "method %<%s%> is ambiguous",
14659 Gogo::message_name(name).c_str());
14660 }
14661 return Expression::make_error(location);
14662 }
14663
14664 if (method != NULL && !is_pointer && !method->is_value_method())
14665 {
14666 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
14667 nt->message_name().c_str(),
14668 Gogo::message_name(name).c_str());
14669 return Expression::make_error(location);
14670 }
14671
14672 // Build a new function type in which the receiver becomes the first
14673 // argument.
14674 Function_type* method_type;
14675 if (method != NULL)
14676 {
14677 method_type = method->type();
14678 go_assert(method_type->is_method());
14679 }
14680 else
14681 {
14682 method_type = imethod->type()->function_type();
14683 go_assert(method_type != NULL && !method_type->is_method());
14684 }
14685
14686 const char* const receiver_name = "$this";
14687 Typed_identifier_list* parameters = new Typed_identifier_list();
14688 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
14689 location));
14690
14691 const Typed_identifier_list* method_parameters = method_type->parameters();
14692 if (method_parameters != NULL)
14693 {
14694 int i = 0;
14695 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
14696 p != method_parameters->end();
14697 ++p, ++i)
14698 {
14699 if (!p->name().empty())
14700 parameters->push_back(*p);
14701 else
14702 {
14703 char buf[20];
14704 snprintf(buf, sizeof buf, "$param%d", i);
14705 parameters->push_back(Typed_identifier(buf, p->type(),
14706 p->location()));
14707 }
14708 }
14709 }
14710
14711 const Typed_identifier_list* method_results = method_type->results();
14712 Typed_identifier_list* results;
14713 if (method_results == NULL)
14714 results = NULL;
14715 else
14716 {
14717 results = new Typed_identifier_list();
14718 for (Typed_identifier_list::const_iterator p = method_results->begin();
14719 p != method_results->end();
14720 ++p)
14721 results->push_back(*p);
14722 }
14723
14724 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
14725 location);
14726 if (method_type->is_varargs())
14727 fntype->set_is_varargs();
14728
14729 // We generate methods which always takes a pointer to the receiver
14730 // as their first argument. If this is for a pointer type, we can
14731 // simply reuse the existing function. We use an internal hack to
14732 // get the right type.
14733 // FIXME: This optimization is disabled because it doesn't yet work
14734 // with function descriptors when the method expression is not
14735 // directly called.
14736 if (method != NULL && is_pointer && false)
14737 {
14738 Named_object* mno = (method->needs_stub_method()
14739 ? method->stub_object()
14740 : method->named_object());
14741 Expression* f = Expression::make_func_reference(mno, NULL, location);
14742 f = Expression::make_cast(fntype, f, location);
14743 Type_conversion_expression* tce =
14744 static_cast<Type_conversion_expression*>(f);
14745 tce->set_may_convert_function_types();
14746 return f;
14747 }
14748
14749 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
14750 location);
14751
14752 Named_object* vno = gogo->lookup(receiver_name, NULL);
14753 go_assert(vno != NULL);
14754 Expression* ve = Expression::make_var_reference(vno, location);
14755 Expression* bm;
14756 if (method != NULL)
14757 bm = Type::bind_field_or_method(gogo, type, ve, name, location);
14758 else
14759 bm = Expression::make_interface_field_reference(ve, name, location);
14760
14761 // Even though we found the method above, if it has an error type we
14762 // may see an error here.
14763 if (bm->is_error_expression())
14764 {
14765 gogo->finish_function(location);
14766 return bm;
14767 }
14768
14769 Expression_list* args;
14770 if (parameters->size() <= 1)
14771 args = NULL;
14772 else
14773 {
14774 args = new Expression_list();
14775 Typed_identifier_list::const_iterator p = parameters->begin();
14776 ++p;
14777 for (; p != parameters->end(); ++p)
14778 {
14779 vno = gogo->lookup(p->name(), NULL);
14780 go_assert(vno != NULL);
14781 args->push_back(Expression::make_var_reference(vno, location));
14782 }
14783 }
14784
14785 gogo->start_block(location);
14786
14787 Call_expression* call = Expression::make_call(bm, args,
14788 method_type->is_varargs(),
14789 location);
14790
14791 Statement* s = Statement::make_return_from_call(call, location);
14792 gogo->add_statement(s);
14793
14794 Block* b = gogo->finish_block(location);
14795
14796 gogo->add_block(b, location);
14797
14798 // Lower the call in case there are multiple results.
14799 gogo->lower_block(no, b);
14800 gogo->flatten_block(no, b);
14801
14802 gogo->finish_function(location);
14803
14804 return Expression::make_func_reference(no, NULL, location);
14805 }
14806
14807 // Dump the ast for a selector expression.
14808
14809 void
14810 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14811 const
14812 {
14813 ast_dump_context->dump_expression(this->left_);
14814 ast_dump_context->ostream() << ".";
14815 ast_dump_context->ostream() << this->name_;
14816 }
14817
14818 // Make a selector expression.
14819
14820 Expression*
14821 Expression::make_selector(Expression* left, const std::string& name,
14822 Location location)
14823 {
14824 return new Selector_expression(left, name, location);
14825 }
14826
14827 // Class Allocation_expression.
14828
14829 int
14830 Allocation_expression::do_traverse(Traverse* traverse)
14831 {
14832 return Type::traverse(this->type_, traverse);
14833 }
14834
14835 Type*
14836 Allocation_expression::do_type()
14837 {
14838 return Type::make_pointer_type(this->type_);
14839 }
14840
14841 void
14842 Allocation_expression::do_check_types(Gogo*)
14843 {
14844 if (!this->type_->in_heap())
14845 go_error_at(this->location(), "cannot heap allocate go:notinheap type");
14846 }
14847
14848 // Make a copy of an allocation expression.
14849
14850 Expression*
14851 Allocation_expression::do_copy()
14852 {
14853 Allocation_expression* alloc =
14854 new Allocation_expression(this->type_->copy_expressions(),
14855 this->location());
14856 if (this->allocate_on_stack_)
14857 alloc->set_allocate_on_stack();
14858 if (this->no_zero_)
14859 alloc->set_no_zero();
14860 return alloc;
14861 }
14862
14863 // Return the backend representation for an allocation expression.
14864
14865 Bexpression*
14866 Allocation_expression::do_get_backend(Translate_context* context)
14867 {
14868 Gogo* gogo = context->gogo();
14869 Location loc = this->location();
14870 Btype* btype = this->type_->get_backend(gogo);
14871
14872 if (this->allocate_on_stack_)
14873 {
14874 int64_t size;
14875 bool ok = this->type_->backend_type_size(gogo, &size);
14876 if (!ok)
14877 {
14878 go_assert(saw_errors());
14879 return gogo->backend()->error_expression();
14880 }
14881 Bstatement* decl;
14882 Named_object* fn = context->function();
14883 go_assert(fn != NULL);
14884 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14885 Bexpression* init = (this->no_zero_
14886 ? NULL
14887 : gogo->backend()->zero_expression(btype));
14888 Bvariable* temp =
14889 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14890 init, true, loc, &decl);
14891 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
14892 ret = gogo->backend()->address_expression(ret, loc);
14893 ret = gogo->backend()->compound_expression(decl, ret, loc);
14894 return ret;
14895 }
14896
14897 Bexpression* space =
14898 gogo->allocate_memory(this->type_, loc)->get_backend(context);
14899 Btype* pbtype = gogo->backend()->pointer_type(btype);
14900 return gogo->backend()->convert_expression(pbtype, space, loc);
14901 }
14902
14903 // Dump ast representation for an allocation expression.
14904
14905 void
14906 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14907 const
14908 {
14909 ast_dump_context->ostream() << "new(";
14910 ast_dump_context->dump_type(this->type_);
14911 ast_dump_context->ostream() << ")";
14912 }
14913
14914 // Make an allocation expression.
14915
14916 Expression*
14917 Expression::make_allocation(Type* type, Location location)
14918 {
14919 return new Allocation_expression(type, location);
14920 }
14921
14922 // Class Ordered_value_list.
14923
14924 int
14925 Ordered_value_list::traverse_vals(Traverse* traverse)
14926 {
14927 if (this->vals_ != NULL)
14928 {
14929 if (this->traverse_order_ == NULL)
14930 {
14931 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
14932 return TRAVERSE_EXIT;
14933 }
14934 else
14935 {
14936 for (std::vector<unsigned long>::const_iterator p =
14937 this->traverse_order_->begin();
14938 p != this->traverse_order_->end();
14939 ++p)
14940 {
14941 if (Expression::traverse(&this->vals_->at(*p), traverse)
14942 == TRAVERSE_EXIT)
14943 return TRAVERSE_EXIT;
14944 }
14945 }
14946 }
14947 return TRAVERSE_CONTINUE;
14948 }
14949
14950 // Class Struct_construction_expression.
14951
14952 // Traversal.
14953
14954 int
14955 Struct_construction_expression::do_traverse(Traverse* traverse)
14956 {
14957 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
14958 return TRAVERSE_EXIT;
14959 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14960 return TRAVERSE_EXIT;
14961 return TRAVERSE_CONTINUE;
14962 }
14963
14964 // Return whether this is a constant initializer.
14965
14966 bool
14967 Struct_construction_expression::is_constant_struct() const
14968 {
14969 if (this->vals() == NULL)
14970 return true;
14971 for (Expression_list::const_iterator pv = this->vals()->begin();
14972 pv != this->vals()->end();
14973 ++pv)
14974 {
14975 if (*pv != NULL
14976 && !(*pv)->is_constant()
14977 && (!(*pv)->is_composite_literal()
14978 || (*pv)->is_nonconstant_composite_literal()))
14979 return false;
14980 }
14981
14982 const Struct_field_list* fields = this->type_->struct_type()->fields();
14983 for (Struct_field_list::const_iterator pf = fields->begin();
14984 pf != fields->end();
14985 ++pf)
14986 {
14987 // There are no constant constructors for interfaces.
14988 if (pf->type()->interface_type() != NULL)
14989 return false;
14990 }
14991
14992 return true;
14993 }
14994
14995 // Return whether this is a zero value.
14996
14997 bool
14998 Struct_construction_expression::do_is_zero_value() const
14999 {
15000 if (this->vals() == NULL)
15001 return true;
15002 for (Expression_list::const_iterator pv = this->vals()->begin();
15003 pv != this->vals()->end();
15004 ++pv)
15005 if (*pv != NULL && !(*pv)->is_zero_value())
15006 return false;
15007
15008 const Struct_field_list* fields = this->type_->struct_type()->fields();
15009 for (Struct_field_list::const_iterator pf = fields->begin();
15010 pf != fields->end();
15011 ++pf)
15012 {
15013 // Interface conversion may cause a zero value being converted
15014 // to a non-zero value, like interface{}(0). Be conservative.
15015 if (pf->type()->interface_type() != NULL)
15016 return false;
15017 }
15018
15019 return true;
15020 }
15021
15022 // Return whether this struct can be used as a constant initializer.
15023
15024 bool
15025 Struct_construction_expression::do_is_static_initializer() const
15026 {
15027 if (this->vals() == NULL)
15028 return true;
15029 for (Expression_list::const_iterator pv = this->vals()->begin();
15030 pv != this->vals()->end();
15031 ++pv)
15032 {
15033 if (*pv != NULL && !(*pv)->is_static_initializer())
15034 return false;
15035 }
15036
15037 const Struct_field_list* fields = this->type_->struct_type()->fields();
15038 for (Struct_field_list::const_iterator pf = fields->begin();
15039 pf != fields->end();
15040 ++pf)
15041 {
15042 // There are no constant constructors for interfaces.
15043 if (pf->type()->interface_type() != NULL)
15044 return false;
15045 }
15046
15047 return true;
15048 }
15049
15050 // Final type determination.
15051
15052 void
15053 Struct_construction_expression::do_determine_type(const Type_context*)
15054 {
15055 if (this->vals() == NULL)
15056 return;
15057 const Struct_field_list* fields = this->type_->struct_type()->fields();
15058 Expression_list::const_iterator pv = this->vals()->begin();
15059 for (Struct_field_list::const_iterator pf = fields->begin();
15060 pf != fields->end();
15061 ++pf, ++pv)
15062 {
15063 if (pv == this->vals()->end())
15064 return;
15065 if (*pv != NULL)
15066 {
15067 Type_context subcontext(pf->type(), false);
15068 (*pv)->determine_type(&subcontext);
15069 }
15070 }
15071 // Extra values are an error we will report elsewhere; we still want
15072 // to determine the type to avoid knockon errors.
15073 for (; pv != this->vals()->end(); ++pv)
15074 (*pv)->determine_type_no_context();
15075 }
15076
15077 // Check types.
15078
15079 void
15080 Struct_construction_expression::do_check_types(Gogo*)
15081 {
15082 if (this->vals() == NULL)
15083 return;
15084
15085 Struct_type* st = this->type_->struct_type();
15086 if (this->vals()->size() > st->field_count())
15087 {
15088 this->report_error(_("too many expressions for struct"));
15089 return;
15090 }
15091
15092 const Struct_field_list* fields = st->fields();
15093 Expression_list::const_iterator pv = this->vals()->begin();
15094 int i = 0;
15095 for (Struct_field_list::const_iterator pf = fields->begin();
15096 pf != fields->end();
15097 ++pf, ++pv, ++i)
15098 {
15099 if (pv == this->vals()->end())
15100 {
15101 this->report_error(_("too few expressions for struct"));
15102 break;
15103 }
15104
15105 if (*pv == NULL)
15106 continue;
15107
15108 std::string reason;
15109 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
15110 {
15111 if (reason.empty())
15112 go_error_at((*pv)->location(),
15113 "incompatible type for field %d in struct construction",
15114 i + 1);
15115 else
15116 go_error_at((*pv)->location(),
15117 ("incompatible type for field %d in "
15118 "struct construction (%s)"),
15119 i + 1, reason.c_str());
15120 this->set_is_error();
15121 }
15122 }
15123 go_assert(pv == this->vals()->end());
15124 }
15125
15126 // Copy.
15127
15128 Expression*
15129 Struct_construction_expression::do_copy()
15130 {
15131 Struct_construction_expression* ret =
15132 new Struct_construction_expression(this->type_->copy_expressions(),
15133 (this->vals() == NULL
15134 ? NULL
15135 : this->vals()->copy()),
15136 this->location());
15137 if (this->traverse_order() != NULL)
15138 ret->set_traverse_order(this->traverse_order());
15139 return ret;
15140 }
15141
15142 // Flatten a struct construction expression. Store the values into
15143 // temporaries in case they need interface conversion.
15144
15145 Expression*
15146 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
15147 Statement_inserter* inserter)
15148 {
15149 if (this->vals() == NULL)
15150 return this;
15151
15152 // If this is a constant struct, we don't need temporaries.
15153 if (this->is_constant_struct() || this->is_static_initializer())
15154 return this;
15155
15156 Location loc = this->location();
15157 for (Expression_list::iterator pv = this->vals()->begin();
15158 pv != this->vals()->end();
15159 ++pv)
15160 {
15161 if (*pv != NULL)
15162 {
15163 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15164 {
15165 go_assert(saw_errors());
15166 return Expression::make_error(loc);
15167 }
15168 if (!(*pv)->is_variable())
15169 {
15170 Temporary_statement* temp =
15171 Statement::make_temporary(NULL, *pv, loc);
15172 inserter->insert(temp);
15173 *pv = Expression::make_temporary_reference(temp, loc);
15174 }
15175 }
15176 }
15177 return this;
15178 }
15179
15180 // Make implicit type conversions explicit.
15181
15182 void
15183 Struct_construction_expression::do_add_conversions()
15184 {
15185 if (this->vals() == NULL)
15186 return;
15187
15188 Location loc = this->location();
15189 const Struct_field_list* fields = this->type_->struct_type()->fields();
15190 Expression_list::iterator pv = this->vals()->begin();
15191 for (Struct_field_list::const_iterator pf = fields->begin();
15192 pf != fields->end();
15193 ++pf, ++pv)
15194 {
15195 if (pv == this->vals()->end())
15196 break;
15197 if (*pv != NULL)
15198 {
15199 Type* ft = pf->type();
15200 if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
15201 && ft->interface_type() != NULL)
15202 *pv = Expression::make_cast(ft, *pv, loc);
15203 }
15204 }
15205 }
15206
15207 // Return the backend representation for constructing a struct.
15208
15209 Bexpression*
15210 Struct_construction_expression::do_get_backend(Translate_context* context)
15211 {
15212 Gogo* gogo = context->gogo();
15213
15214 Btype* btype = this->type_->get_backend(gogo);
15215 if (this->vals() == NULL)
15216 return gogo->backend()->zero_expression(btype);
15217
15218 const Struct_field_list* fields = this->type_->struct_type()->fields();
15219 Expression_list::const_iterator pv = this->vals()->begin();
15220 std::vector<Bexpression*> init;
15221 for (Struct_field_list::const_iterator pf = fields->begin();
15222 pf != fields->end();
15223 ++pf)
15224 {
15225 Btype* fbtype = pf->type()->get_backend(gogo);
15226 if (pv == this->vals()->end())
15227 init.push_back(gogo->backend()->zero_expression(fbtype));
15228 else if (*pv == NULL)
15229 {
15230 init.push_back(gogo->backend()->zero_expression(fbtype));
15231 ++pv;
15232 }
15233 else
15234 {
15235 Expression* val =
15236 Expression::convert_for_assignment(gogo, pf->type(),
15237 *pv, this->location());
15238 init.push_back(val->get_backend(context));
15239 ++pv;
15240 }
15241 }
15242 if (this->type_->struct_type()->has_padding())
15243 {
15244 // Feed an extra value if there is a padding field.
15245 Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15246 init.push_back(gogo->backend()->zero_expression(fbtype));
15247 }
15248 return gogo->backend()->constructor_expression(btype, init, this->location());
15249 }
15250
15251 // Export a struct construction.
15252
15253 void
15254 Struct_construction_expression::do_export(Export_function_body* efb) const
15255 {
15256 efb->write_c_string("$convert(");
15257 efb->write_type(this->type_);
15258 for (Expression_list::const_iterator pv = this->vals()->begin();
15259 pv != this->vals()->end();
15260 ++pv)
15261 {
15262 efb->write_c_string(", ");
15263 if (*pv != NULL)
15264 (*pv)->export_expression(efb);
15265 }
15266 efb->write_c_string(")");
15267 }
15268
15269 // Dump ast representation of a struct construction expression.
15270
15271 void
15272 Struct_construction_expression::do_dump_expression(
15273 Ast_dump_context* ast_dump_context) const
15274 {
15275 ast_dump_context->dump_type(this->type_);
15276 ast_dump_context->ostream() << "{";
15277 ast_dump_context->dump_expression_list(this->vals());
15278 ast_dump_context->ostream() << "}";
15279 }
15280
15281 // Make a struct composite literal. This used by the thunk code.
15282
15283 Expression*
15284 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
15285 Location location)
15286 {
15287 go_assert(type->struct_type() != NULL);
15288 return new Struct_construction_expression(type, vals, location);
15289 }
15290
15291 // Class Array_construction_expression.
15292
15293 // Traversal.
15294
15295 int
15296 Array_construction_expression::do_traverse(Traverse* traverse)
15297 {
15298 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15299 return TRAVERSE_EXIT;
15300 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15301 return TRAVERSE_EXIT;
15302 return TRAVERSE_CONTINUE;
15303 }
15304
15305 // Return whether this is a constant initializer.
15306
15307 bool
15308 Array_construction_expression::is_constant_array() const
15309 {
15310 if (this->vals() == NULL)
15311 return true;
15312
15313 // There are no constant constructors for interfaces.
15314 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15315 return false;
15316
15317 for (Expression_list::const_iterator pv = this->vals()->begin();
15318 pv != this->vals()->end();
15319 ++pv)
15320 {
15321 if (*pv != NULL
15322 && !(*pv)->is_constant()
15323 && (!(*pv)->is_composite_literal()
15324 || (*pv)->is_nonconstant_composite_literal()))
15325 return false;
15326 }
15327 return true;
15328 }
15329
15330 // Return whether this is a zero value.
15331
15332 bool
15333 Array_construction_expression::do_is_zero_value() const
15334 {
15335 if (this->vals() == NULL)
15336 return true;
15337
15338 // Interface conversion may cause a zero value being converted
15339 // to a non-zero value, like interface{}(0). Be conservative.
15340 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15341 return false;
15342
15343 for (Expression_list::const_iterator pv = this->vals()->begin();
15344 pv != this->vals()->end();
15345 ++pv)
15346 if (*pv != NULL && !(*pv)->is_zero_value())
15347 return false;
15348
15349 return true;
15350 }
15351
15352 // Return whether this can be used a constant initializer.
15353
15354 bool
15355 Array_construction_expression::do_is_static_initializer() const
15356 {
15357 if (this->vals() == NULL)
15358 return true;
15359
15360 // There are no constant constructors for interfaces.
15361 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15362 return false;
15363
15364 for (Expression_list::const_iterator pv = this->vals()->begin();
15365 pv != this->vals()->end();
15366 ++pv)
15367 {
15368 if (*pv != NULL && !(*pv)->is_static_initializer())
15369 return false;
15370 }
15371 return true;
15372 }
15373
15374 // Final type determination.
15375
15376 void
15377 Array_construction_expression::do_determine_type(const Type_context*)
15378 {
15379 if (this->is_error_expression())
15380 {
15381 go_assert(saw_errors());
15382 return;
15383 }
15384
15385 if (this->vals() == NULL)
15386 return;
15387 Array_type* at = this->type_->array_type();
15388 if (at == NULL || at->is_error() || at->element_type()->is_error())
15389 {
15390 go_assert(saw_errors());
15391 this->set_is_error();
15392 return;
15393 }
15394 Type_context subcontext(at->element_type(), false);
15395 for (Expression_list::const_iterator pv = this->vals()->begin();
15396 pv != this->vals()->end();
15397 ++pv)
15398 {
15399 if (*pv != NULL)
15400 (*pv)->determine_type(&subcontext);
15401 }
15402 }
15403
15404 // Check types.
15405
15406 void
15407 Array_construction_expression::do_check_types(Gogo*)
15408 {
15409 if (this->is_error_expression())
15410 {
15411 go_assert(saw_errors());
15412 return;
15413 }
15414
15415 if (this->vals() == NULL)
15416 return;
15417
15418 Array_type* at = this->type_->array_type();
15419 if (at == NULL || at->is_error() || at->element_type()->is_error())
15420 {
15421 go_assert(saw_errors());
15422 this->set_is_error();
15423 return;
15424 }
15425 int i = 0;
15426 Type* element_type = at->element_type();
15427 for (Expression_list::const_iterator pv = this->vals()->begin();
15428 pv != this->vals()->end();
15429 ++pv, ++i)
15430 {
15431 if (*pv != NULL
15432 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
15433 {
15434 go_error_at((*pv)->location(),
15435 "incompatible type for element %d in composite literal",
15436 i + 1);
15437 this->set_is_error();
15438 }
15439 }
15440 }
15441
15442 // Flatten an array construction expression. Store the values into
15443 // temporaries in case they need interface conversion.
15444
15445 Expression*
15446 Array_construction_expression::do_flatten(Gogo*, Named_object*,
15447 Statement_inserter* inserter)
15448 {
15449 if (this->is_error_expression())
15450 {
15451 go_assert(saw_errors());
15452 return this;
15453 }
15454
15455 if (this->vals() == NULL)
15456 return this;
15457
15458 // If this is a constant array, we don't need temporaries.
15459 if (this->is_constant_array() || this->is_static_initializer())
15460 return this;
15461
15462 Location loc = this->location();
15463 for (Expression_list::iterator pv = this->vals()->begin();
15464 pv != this->vals()->end();
15465 ++pv)
15466 {
15467 if (*pv != NULL)
15468 {
15469 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15470 {
15471 go_assert(saw_errors());
15472 return Expression::make_error(loc);
15473 }
15474 if (!(*pv)->is_variable())
15475 {
15476 Temporary_statement* temp =
15477 Statement::make_temporary(NULL, *pv, loc);
15478 inserter->insert(temp);
15479 *pv = Expression::make_temporary_reference(temp, loc);
15480 }
15481 }
15482 }
15483 return this;
15484 }
15485
15486 // Make implicit type conversions explicit.
15487
15488 void
15489 Array_construction_expression::do_add_conversions()
15490 {
15491 if (this->is_error_expression())
15492 {
15493 go_assert(saw_errors());
15494 return;
15495 }
15496
15497 if (this->vals() == NULL)
15498 return;
15499
15500 Type* et = this->type_->array_type()->element_type();
15501 if (et->interface_type() == NULL)
15502 return;
15503
15504 Location loc = this->location();
15505 for (Expression_list::iterator pv = this->vals()->begin();
15506 pv != this->vals()->end();
15507 ++pv)
15508 if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
15509 *pv = Expression::make_cast(et, *pv, loc);
15510 }
15511
15512 // Get a constructor expression for the array values.
15513
15514 Bexpression*
15515 Array_construction_expression::get_constructor(Translate_context* context,
15516 Btype* array_btype)
15517 {
15518 Type* element_type = this->type_->array_type()->element_type();
15519
15520 std::vector<unsigned long> indexes;
15521 std::vector<Bexpression*> vals;
15522 Gogo* gogo = context->gogo();
15523 if (this->vals() != NULL)
15524 {
15525 size_t i = 0;
15526 std::vector<unsigned long>::const_iterator pi;
15527 if (this->indexes_ != NULL)
15528 pi = this->indexes_->begin();
15529 for (Expression_list::const_iterator pv = this->vals()->begin();
15530 pv != this->vals()->end();
15531 ++pv, ++i)
15532 {
15533 if (this->indexes_ != NULL)
15534 go_assert(pi != this->indexes_->end());
15535
15536 if (this->indexes_ == NULL)
15537 indexes.push_back(i);
15538 else
15539 indexes.push_back(*pi);
15540 if (*pv == NULL)
15541 {
15542 Btype* ebtype = element_type->get_backend(gogo);
15543 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
15544 vals.push_back(zv);
15545 }
15546 else
15547 {
15548 Expression* val_expr =
15549 Expression::convert_for_assignment(gogo, element_type, *pv,
15550 this->location());
15551 vals.push_back(val_expr->get_backend(context));
15552 }
15553 if (this->indexes_ != NULL)
15554 ++pi;
15555 }
15556 if (this->indexes_ != NULL)
15557 go_assert(pi == this->indexes_->end());
15558 }
15559 return gogo->backend()->array_constructor_expression(array_btype, indexes,
15560 vals, this->location());
15561 }
15562
15563 // Export an array construction.
15564
15565 void
15566 Array_construction_expression::do_export(Export_function_body* efb) const
15567 {
15568 efb->write_c_string("$convert(");
15569 efb->write_type(this->type_);
15570 if (this->vals() != NULL)
15571 {
15572 std::vector<unsigned long>::const_iterator pi;
15573 if (this->indexes_ != NULL)
15574 pi = this->indexes_->begin();
15575 for (Expression_list::const_iterator pv = this->vals()->begin();
15576 pv != this->vals()->end();
15577 ++pv)
15578 {
15579 efb->write_c_string(", ");
15580
15581 if (this->indexes_ != NULL)
15582 {
15583 char buf[100];
15584 snprintf(buf, sizeof buf, "%lu", *pi);
15585 efb->write_c_string(buf);
15586 efb->write_c_string(":");
15587 }
15588
15589 if (*pv != NULL)
15590 (*pv)->export_expression(efb);
15591
15592 if (this->indexes_ != NULL)
15593 ++pi;
15594 }
15595 }
15596 efb->write_c_string(")");
15597 }
15598
15599 // Dump ast representation of an array construction expression.
15600
15601 void
15602 Array_construction_expression::do_dump_expression(
15603 Ast_dump_context* ast_dump_context) const
15604 {
15605 Expression* length = this->type_->array_type()->length();
15606
15607 ast_dump_context->ostream() << "[" ;
15608 if (length != NULL)
15609 {
15610 ast_dump_context->dump_expression(length);
15611 }
15612 ast_dump_context->ostream() << "]" ;
15613 ast_dump_context->dump_type(this->type_);
15614 this->dump_slice_storage_expression(ast_dump_context);
15615 ast_dump_context->ostream() << "{" ;
15616 if (this->indexes_ == NULL)
15617 ast_dump_context->dump_expression_list(this->vals());
15618 else
15619 {
15620 Expression_list::const_iterator pv = this->vals()->begin();
15621 for (std::vector<unsigned long>::const_iterator pi =
15622 this->indexes_->begin();
15623 pi != this->indexes_->end();
15624 ++pi, ++pv)
15625 {
15626 if (pi != this->indexes_->begin())
15627 ast_dump_context->ostream() << ", ";
15628 ast_dump_context->ostream() << *pi << ':';
15629 ast_dump_context->dump_expression(*pv);
15630 }
15631 }
15632 ast_dump_context->ostream() << "}" ;
15633
15634 }
15635
15636 // Class Fixed_array_construction_expression.
15637
15638 Fixed_array_construction_expression::Fixed_array_construction_expression(
15639 Type* type, const std::vector<unsigned long>* indexes,
15640 Expression_list* vals, Location location)
15641 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
15642 type, indexes, vals, location)
15643 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
15644
15645
15646 // Copy.
15647
15648 Expression*
15649 Fixed_array_construction_expression::do_copy()
15650 {
15651 Type* t = this->type()->copy_expressions();
15652 return new Fixed_array_construction_expression(t, this->indexes(),
15653 (this->vals() == NULL
15654 ? NULL
15655 : this->vals()->copy()),
15656 this->location());
15657 }
15658
15659 // Return the backend representation for constructing a fixed array.
15660
15661 Bexpression*
15662 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
15663 {
15664 Type* type = this->type();
15665 Btype* btype = type->get_backend(context->gogo());
15666 return this->get_constructor(context, btype);
15667 }
15668
15669 Expression*
15670 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
15671 Location location)
15672 {
15673 go_assert(type->array_type() != NULL && !type->is_slice_type());
15674 return new Fixed_array_construction_expression(type, NULL, vals, location);
15675 }
15676
15677 // Class Slice_construction_expression.
15678
15679 Slice_construction_expression::Slice_construction_expression(
15680 Type* type, const std::vector<unsigned long>* indexes,
15681 Expression_list* vals, Location location)
15682 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
15683 type, indexes, vals, location),
15684 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
15685 storage_escapes_(true)
15686 {
15687 go_assert(type->is_slice_type());
15688
15689 unsigned long lenval;
15690 Expression* length;
15691 if (vals == NULL || vals->empty())
15692 lenval = 0;
15693 else
15694 {
15695 if (this->indexes() == NULL)
15696 lenval = vals->size();
15697 else
15698 lenval = indexes->back() + 1;
15699 }
15700 Type* int_type = Type::lookup_integer_type("int");
15701 length = Expression::make_integer_ul(lenval, int_type, location);
15702 Type* element_type = type->array_type()->element_type();
15703 Array_type* array_type = Type::make_array_type(element_type, length);
15704 array_type->set_is_array_incomparable();
15705 this->valtype_ = array_type;
15706 }
15707
15708 // Traversal.
15709
15710 int
15711 Slice_construction_expression::do_traverse(Traverse* traverse)
15712 {
15713 if (this->Array_construction_expression::do_traverse(traverse)
15714 == TRAVERSE_EXIT)
15715 return TRAVERSE_EXIT;
15716 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
15717 return TRAVERSE_EXIT;
15718 if (this->array_val_ != NULL
15719 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
15720 return TRAVERSE_EXIT;
15721 if (this->slice_storage_ != NULL
15722 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
15723 return TRAVERSE_EXIT;
15724 return TRAVERSE_CONTINUE;
15725 }
15726
15727 // Helper routine to create fixed array value underlying the slice literal.
15728 // May be called during flattening, or later during do_get_backend().
15729
15730 Expression*
15731 Slice_construction_expression::create_array_val()
15732 {
15733 Array_type* array_type = this->type()->array_type();
15734 if (array_type == NULL)
15735 {
15736 go_assert(this->type()->is_error());
15737 return NULL;
15738 }
15739
15740 Location loc = this->location();
15741 go_assert(this->valtype_ != NULL);
15742
15743 Expression_list* vals = this->vals();
15744 return new Fixed_array_construction_expression(
15745 this->valtype_, this->indexes(), vals, loc);
15746 }
15747
15748 // If we're previous established that the slice storage does not
15749 // escape, then create a separate array temp val here for it. We
15750 // need to do this as part of flattening so as to be able to insert
15751 // the new temp statement.
15752
15753 Expression*
15754 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
15755 Statement_inserter* inserter)
15756 {
15757 if (this->type()->array_type() == NULL)
15758 return NULL;
15759
15760 // Base class flattening first
15761 this->Array_construction_expression::do_flatten(gogo, no, inserter);
15762
15763 // Create a stack-allocated storage temp if storage won't escape
15764 if (!this->storage_escapes_
15765 && this->slice_storage_ == NULL
15766 && this->element_count() > 0)
15767 {
15768 Location loc = this->location();
15769 this->array_val_ = this->create_array_val();
15770 go_assert(this->array_val_);
15771 Temporary_statement* temp =
15772 Statement::make_temporary(this->valtype_, this->array_val_, loc);
15773 inserter->insert(temp);
15774 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
15775 }
15776 return this;
15777 }
15778
15779 // When dumping a slice construction expression that has an explicit
15780 // storeage temp, emit the temp here (if we don't do this the storage
15781 // temp appears unused in the AST dump).
15782
15783 void
15784 Slice_construction_expression::
15785 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
15786 {
15787 if (this->slice_storage_ == NULL)
15788 return;
15789 ast_dump_context->ostream() << "storage=" ;
15790 ast_dump_context->dump_expression(this->slice_storage_);
15791 }
15792
15793 // Copy.
15794
15795 Expression*
15796 Slice_construction_expression::do_copy()
15797 {
15798 return new Slice_construction_expression(this->type()->copy_expressions(),
15799 this->indexes(),
15800 (this->vals() == NULL
15801 ? NULL
15802 : this->vals()->copy()),
15803 this->location());
15804 }
15805
15806 // Return the backend representation for constructing a slice.
15807
15808 Bexpression*
15809 Slice_construction_expression::do_get_backend(Translate_context* context)
15810 {
15811 if (this->array_val_ == NULL)
15812 this->array_val_ = this->create_array_val();
15813 if (this->array_val_ == NULL)
15814 {
15815 go_assert(this->type()->is_error());
15816 return context->backend()->error_expression();
15817 }
15818
15819 Location loc = this->location();
15820
15821 bool is_static_initializer = this->array_val_->is_static_initializer();
15822
15823 // We have to copy the initial values into heap memory if we are in
15824 // a function or if the values are not constants.
15825 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
15826
15827 Expression* space;
15828
15829 if (this->slice_storage_ != NULL)
15830 {
15831 go_assert(!this->storage_escapes_);
15832 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
15833 }
15834 else if (!copy_to_heap)
15835 {
15836 // The initializer will only run once.
15837 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
15838 space->unary_expression()->set_is_slice_init();
15839 }
15840 else
15841 {
15842 go_assert(this->storage_escapes_ || this->element_count() == 0);
15843 space = Expression::make_heap_expression(this->array_val_, loc);
15844 }
15845 Array_type* at = this->valtype_->array_type();
15846 Type* et = at->element_type();
15847 space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
15848 space, loc);
15849
15850 // Build a constructor for the slice.
15851 Expression* len = at->length();
15852 Expression* slice_val =
15853 Expression::make_slice_value(this->type(), space, len, len, loc);
15854 return slice_val->get_backend(context);
15855 }
15856
15857 // Make a slice composite literal. This is used by the type
15858 // descriptor code.
15859
15860 Slice_construction_expression*
15861 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
15862 Location location)
15863 {
15864 go_assert(type->is_slice_type());
15865 return new Slice_construction_expression(type, NULL, vals, location);
15866 }
15867
15868 // Class Map_construction_expression.
15869
15870 // Traversal.
15871
15872 int
15873 Map_construction_expression::do_traverse(Traverse* traverse)
15874 {
15875 if (this->vals_ != NULL
15876 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
15877 return TRAVERSE_EXIT;
15878 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15879 return TRAVERSE_EXIT;
15880 return TRAVERSE_CONTINUE;
15881 }
15882
15883 // Flatten constructor initializer into a temporary variable since
15884 // we need to take its address for __go_construct_map.
15885
15886 Expression*
15887 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
15888 Statement_inserter* inserter)
15889 {
15890 if (!this->is_error_expression()
15891 && this->vals_ != NULL
15892 && !this->vals_->empty()
15893 && this->constructor_temp_ == NULL)
15894 {
15895 Map_type* mt = this->type_->map_type();
15896 Type* key_type = mt->key_type();
15897 Type* val_type = mt->val_type();
15898 this->element_type_ = Type::make_builtin_struct_type(2,
15899 "__key", key_type,
15900 "__val", val_type);
15901
15902 Expression_list* value_pairs = new Expression_list();
15903 Location loc = this->location();
15904
15905 size_t i = 0;
15906 for (Expression_list::const_iterator pv = this->vals_->begin();
15907 pv != this->vals_->end();
15908 ++pv, ++i)
15909 {
15910 Expression_list* key_value_pair = new Expression_list();
15911 Expression* key = *pv;
15912 if (key->is_error_expression() || key->type()->is_error_type())
15913 {
15914 go_assert(saw_errors());
15915 return Expression::make_error(loc);
15916 }
15917 if (key->type()->interface_type() != NULL && !key->is_variable())
15918 {
15919 Temporary_statement* temp =
15920 Statement::make_temporary(NULL, key, loc);
15921 inserter->insert(temp);
15922 key = Expression::make_temporary_reference(temp, loc);
15923 }
15924 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
15925
15926 ++pv;
15927 Expression* val = *pv;
15928 if (val->is_error_expression() || val->type()->is_error_type())
15929 {
15930 go_assert(saw_errors());
15931 return Expression::make_error(loc);
15932 }
15933 if (val->type()->interface_type() != NULL && !val->is_variable())
15934 {
15935 Temporary_statement* temp =
15936 Statement::make_temporary(NULL, val, loc);
15937 inserter->insert(temp);
15938 val = Expression::make_temporary_reference(temp, loc);
15939 }
15940 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
15941
15942 key_value_pair->push_back(key);
15943 key_value_pair->push_back(val);
15944 value_pairs->push_back(
15945 Expression::make_struct_composite_literal(this->element_type_,
15946 key_value_pair, loc));
15947 }
15948
15949 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
15950 Array_type* ctor_type =
15951 Type::make_array_type(this->element_type_, element_count);
15952 ctor_type->set_is_array_incomparable();
15953 Expression* constructor =
15954 new Fixed_array_construction_expression(ctor_type, NULL,
15955 value_pairs, loc);
15956
15957 this->constructor_temp_ =
15958 Statement::make_temporary(NULL, constructor, loc);
15959 constructor->issue_nil_check();
15960 this->constructor_temp_->set_is_address_taken();
15961 inserter->insert(this->constructor_temp_);
15962 }
15963
15964 return this;
15965 }
15966
15967 // Final type determination.
15968
15969 void
15970 Map_construction_expression::do_determine_type(const Type_context*)
15971 {
15972 if (this->vals_ == NULL)
15973 return;
15974
15975 Map_type* mt = this->type_->map_type();
15976 Type_context key_context(mt->key_type(), false);
15977 Type_context val_context(mt->val_type(), false);
15978 for (Expression_list::const_iterator pv = this->vals_->begin();
15979 pv != this->vals_->end();
15980 ++pv)
15981 {
15982 (*pv)->determine_type(&key_context);
15983 ++pv;
15984 (*pv)->determine_type(&val_context);
15985 }
15986 }
15987
15988 // Check types.
15989
15990 void
15991 Map_construction_expression::do_check_types(Gogo*)
15992 {
15993 if (this->vals_ == NULL)
15994 return;
15995
15996 Map_type* mt = this->type_->map_type();
15997 int i = 0;
15998 Type* key_type = mt->key_type();
15999 Type* val_type = mt->val_type();
16000 for (Expression_list::const_iterator pv = this->vals_->begin();
16001 pv != this->vals_->end();
16002 ++pv, ++i)
16003 {
16004 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
16005 {
16006 go_error_at((*pv)->location(),
16007 "incompatible type for element %d key in map construction",
16008 i + 1);
16009 this->set_is_error();
16010 }
16011 ++pv;
16012 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
16013 {
16014 go_error_at((*pv)->location(),
16015 ("incompatible type for element %d value "
16016 "in map construction"),
16017 i + 1);
16018 this->set_is_error();
16019 }
16020 }
16021 }
16022
16023 // Copy.
16024
16025 Expression*
16026 Map_construction_expression::do_copy()
16027 {
16028 return new Map_construction_expression(this->type_->copy_expressions(),
16029 (this->vals_ == NULL
16030 ? NULL
16031 : this->vals_->copy()),
16032 this->location());
16033 }
16034
16035 // Make implicit type conversions explicit.
16036
16037 void
16038 Map_construction_expression::do_add_conversions()
16039 {
16040 if (this->vals_ == NULL || this->vals_->empty())
16041 return;
16042
16043 Map_type* mt = this->type_->map_type();
16044 Type* kt = mt->key_type();
16045 Type* vt = mt->val_type();
16046 bool key_is_interface = (kt->interface_type() != NULL);
16047 bool val_is_interface = (vt->interface_type() != NULL);
16048 if (!key_is_interface && !val_is_interface)
16049 return;
16050
16051 Location loc = this->location();
16052 for (Expression_list::iterator pv = this->vals_->begin();
16053 pv != this->vals_->end();
16054 ++pv)
16055 {
16056 if (key_is_interface &&
16057 !Type::are_identical(kt, (*pv)->type(), 0, NULL))
16058 *pv = Expression::make_cast(kt, *pv, loc);
16059 ++pv;
16060 if (val_is_interface &&
16061 !Type::are_identical(vt, (*pv)->type(), 0, NULL))
16062 *pv = Expression::make_cast(vt, *pv, loc);
16063 }
16064 }
16065
16066 // Return the backend representation for constructing a map.
16067
16068 Bexpression*
16069 Map_construction_expression::do_get_backend(Translate_context* context)
16070 {
16071 if (this->is_error_expression())
16072 return context->backend()->error_expression();
16073 Location loc = this->location();
16074
16075 size_t i = 0;
16076 Expression* ventries;
16077 if (this->vals_ == NULL || this->vals_->empty())
16078 ventries = Expression::make_nil(loc);
16079 else
16080 {
16081 go_assert(this->constructor_temp_ != NULL);
16082 i = this->vals_->size() / 2;
16083
16084 Expression* ctor_ref =
16085 Expression::make_temporary_reference(this->constructor_temp_, loc);
16086 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
16087 }
16088
16089 Map_type* mt = this->type_->map_type();
16090 if (this->element_type_ == NULL)
16091 this->element_type_ =
16092 Type::make_builtin_struct_type(2,
16093 "__key", mt->key_type(),
16094 "__val", mt->val_type());
16095 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
16096
16097 Type* uintptr_t = Type::lookup_integer_type("uintptr");
16098 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
16099
16100 Expression* entry_size =
16101 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
16102
16103 unsigned int field_index;
16104 const Struct_field* valfield =
16105 this->element_type_->find_local_field("__val", &field_index);
16106 Expression* val_offset =
16107 Expression::make_struct_field_offset(this->element_type_, valfield);
16108
16109 Expression* map_ctor =
16110 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
16111 entry_size, val_offset, ventries);
16112 return map_ctor->get_backend(context);
16113 }
16114
16115 // Export an array construction.
16116
16117 void
16118 Map_construction_expression::do_export(Export_function_body* efb) const
16119 {
16120 efb->write_c_string("$convert(");
16121 efb->write_type(this->type_);
16122 for (Expression_list::const_iterator pv = this->vals_->begin();
16123 pv != this->vals_->end();
16124 ++pv)
16125 {
16126 efb->write_c_string(", ");
16127 (*pv)->export_expression(efb);
16128 }
16129 efb->write_c_string(")");
16130 }
16131
16132 // Dump ast representation for a map construction expression.
16133
16134 void
16135 Map_construction_expression::do_dump_expression(
16136 Ast_dump_context* ast_dump_context) const
16137 {
16138 ast_dump_context->ostream() << "{" ;
16139 ast_dump_context->dump_expression_list(this->vals_, true);
16140 ast_dump_context->ostream() << "}";
16141 }
16142
16143 // A composite literal key. This is seen during parsing, but is not
16144 // resolved to a named_object in case this is a composite literal of
16145 // struct type.
16146
16147 class Composite_literal_key_expression : public Parser_expression
16148 {
16149 public:
16150 Composite_literal_key_expression(const std::string& name, Location location)
16151 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
16152 name_(name)
16153 { }
16154
16155 const std::string&
16156 name() const
16157 { return this->name_; }
16158
16159 protected:
16160 Expression*
16161 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
16162
16163 Expression*
16164 do_copy()
16165 {
16166 return new Composite_literal_key_expression(this->name_, this->location());
16167 }
16168
16169 void
16170 do_dump_expression(Ast_dump_context*) const;
16171
16172 private:
16173 // The name.
16174 std::string name_;
16175 };
16176
16177 // Lower a composite literal key. We will never get here for keys in
16178 // composite literals of struct types, because that is prevented by
16179 // Composite_literal_expression::do_traverse. So if we do get here,
16180 // this must be a regular name reference after all.
16181
16182 Expression*
16183 Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
16184 Statement_inserter*, int)
16185 {
16186 Named_object* no = gogo->lookup(this->name_, NULL);
16187 if (no == NULL)
16188 {
16189 // Gogo::lookup doesn't look in the global namespace, and names
16190 // used in composite literal keys aren't seen by
16191 // Gogo::define_global_names, so we have to look in the global
16192 // namespace ourselves.
16193 no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
16194 if (no == NULL)
16195 {
16196 go_error_at(this->location(), "reference to undefined name %qs",
16197 Gogo::message_name(this->name_).c_str());
16198 return Expression::make_error(this->location());
16199 }
16200 }
16201 return Expression::make_unknown_reference(no, this->location());
16202 }
16203
16204 // Dump a composite literal key.
16205
16206 void
16207 Composite_literal_key_expression::do_dump_expression(
16208 Ast_dump_context* ast_dump_context) const
16209 {
16210 ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
16211 }
16212
16213 // Make a composite literal key.
16214
16215 Expression*
16216 Expression::make_composite_literal_key(const std::string& name,
16217 Location location)
16218 {
16219 return new Composite_literal_key_expression(name, location);
16220 }
16221
16222 // Class Composite_literal_expression.
16223
16224 // Traversal.
16225
16226 int
16227 Composite_literal_expression::do_traverse(Traverse* traverse)
16228 {
16229 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16230 return TRAVERSE_EXIT;
16231
16232 // If this is a struct composite literal with keys, then the keys
16233 // are field names, not expressions. We don't want to traverse them
16234 // in that case. If we do, we can give an erroneous error "variable
16235 // initializer refers to itself." See bug482.go in the testsuite.
16236 if (this->has_keys_ && this->vals_ != NULL)
16237 {
16238 // The type may not be resolvable at this point.
16239 Type* type = this->type_;
16240
16241 for (int depth = 0; depth < this->depth_; ++depth)
16242 {
16243 type = type->deref();
16244 if (type->array_type() != NULL)
16245 type = type->array_type()->element_type();
16246 else if (type->map_type() != NULL)
16247 {
16248 if (this->key_path_[depth])
16249 type = type->map_type()->key_type();
16250 else
16251 type = type->map_type()->val_type();
16252 }
16253 else
16254 {
16255 // This error will be reported during lowering.
16256 return TRAVERSE_CONTINUE;
16257 }
16258 }
16259 type = type->deref();
16260
16261 while (true)
16262 {
16263 if (type->classification() == Type::TYPE_NAMED)
16264 type = type->named_type()->real_type();
16265 else if (type->classification() == Type::TYPE_FORWARD)
16266 {
16267 Type* t = type->forwarded();
16268 if (t == type)
16269 break;
16270 type = t;
16271 }
16272 else
16273 break;
16274 }
16275
16276 if (type->classification() == Type::TYPE_STRUCT)
16277 {
16278 Expression_list::iterator p = this->vals_->begin();
16279 while (p != this->vals_->end())
16280 {
16281 // Skip key.
16282 ++p;
16283 go_assert(p != this->vals_->end());
16284 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16285 return TRAVERSE_EXIT;
16286 ++p;
16287 }
16288 return TRAVERSE_CONTINUE;
16289 }
16290 }
16291
16292 if (this->vals_ != NULL)
16293 return this->vals_->traverse(traverse);
16294
16295 return TRAVERSE_CONTINUE;
16296 }
16297
16298 // Lower a generic composite literal into a specific version based on
16299 // the type.
16300
16301 Expression*
16302 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
16303 Statement_inserter* inserter, int)
16304 {
16305 Type* type = this->type_;
16306
16307 for (int depth = 0; depth < this->depth_; ++depth)
16308 {
16309 type = type->deref();
16310 if (type->array_type() != NULL)
16311 type = type->array_type()->element_type();
16312 else if (type->map_type() != NULL)
16313 {
16314 if (this->key_path_[depth])
16315 type = type->map_type()->key_type();
16316 else
16317 type = type->map_type()->val_type();
16318 }
16319 else
16320 {
16321 if (!type->is_error())
16322 go_error_at(this->location(),
16323 ("may only omit types within composite literals "
16324 "of slice, array, or map type"));
16325 return Expression::make_error(this->location());
16326 }
16327 }
16328
16329 Type *pt = type->points_to();
16330 bool is_pointer = false;
16331 if (pt != NULL)
16332 {
16333 is_pointer = true;
16334 type = pt;
16335 }
16336
16337 Expression* ret;
16338 if (type->is_error())
16339 return Expression::make_error(this->location());
16340 else if (type->struct_type() != NULL)
16341 ret = this->lower_struct(gogo, type);
16342 else if (type->array_type() != NULL)
16343 ret = this->lower_array(type);
16344 else if (type->map_type() != NULL)
16345 ret = this->lower_map(gogo, function, inserter, type);
16346 else
16347 {
16348 go_error_at(this->location(),
16349 ("expected struct, slice, array, or map type "
16350 "for composite literal"));
16351 return Expression::make_error(this->location());
16352 }
16353
16354 if (is_pointer)
16355 ret = Expression::make_heap_expression(ret, this->location());
16356
16357 return ret;
16358 }
16359
16360 // Lower a struct composite literal.
16361
16362 Expression*
16363 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
16364 {
16365 Location location = this->location();
16366 Struct_type* st = type->struct_type();
16367 if (this->vals_ == NULL || !this->has_keys_)
16368 {
16369 if (this->vals_ != NULL
16370 && !this->vals_->empty()
16371 && type->named_type() != NULL
16372 && type->named_type()->named_object()->package() != NULL)
16373 {
16374 for (Struct_field_list::const_iterator pf = st->fields()->begin();
16375 pf != st->fields()->end();
16376 ++pf)
16377 {
16378 if (Gogo::is_hidden_name(pf->field_name())
16379 || pf->is_embedded_builtin(gogo))
16380 go_error_at(this->location(),
16381 "assignment of unexported field %qs in %qs literal",
16382 Gogo::message_name(pf->field_name()).c_str(),
16383 type->named_type()->message_name().c_str());
16384 }
16385 }
16386
16387 return new Struct_construction_expression(type, this->vals_, location);
16388 }
16389
16390 size_t field_count = st->field_count();
16391 std::vector<Expression*> vals(field_count);
16392 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
16393 Expression_list::const_iterator p = this->vals_->begin();
16394 Expression* external_expr = NULL;
16395 const Named_object* external_no = NULL;
16396 while (p != this->vals_->end())
16397 {
16398 Expression* name_expr = *p;
16399
16400 ++p;
16401 go_assert(p != this->vals_->end());
16402 Expression* val = *p;
16403
16404 ++p;
16405
16406 if (name_expr == NULL)
16407 {
16408 go_error_at(val->location(),
16409 "mixture of field and value initializers");
16410 return Expression::make_error(location);
16411 }
16412
16413 bool bad_key = false;
16414 std::string name;
16415 const Named_object* no = NULL;
16416 switch (name_expr->classification())
16417 {
16418 case EXPRESSION_COMPOSITE_LITERAL_KEY:
16419 name =
16420 static_cast<Composite_literal_key_expression*>(name_expr)->name();
16421 break;
16422
16423 case EXPRESSION_UNKNOWN_REFERENCE:
16424 name = name_expr->unknown_expression()->name();
16425 if (type->named_type() != NULL)
16426 {
16427 // If the named object found for this field name comes from a
16428 // different package than the struct it is a part of, do not count
16429 // this incorrect lookup as a usage of the object's package.
16430 no = name_expr->unknown_expression()->named_object();
16431 if (no->package() != NULL
16432 && no->package() != type->named_type()->named_object()->package())
16433 no->package()->forget_usage(name_expr);
16434 }
16435 break;
16436
16437 case EXPRESSION_CONST_REFERENCE:
16438 no = static_cast<Const_expression*>(name_expr)->named_object();
16439 break;
16440
16441 case EXPRESSION_TYPE:
16442 {
16443 Type* t = name_expr->type();
16444 Named_type* nt = t->named_type();
16445 if (nt == NULL)
16446 bad_key = true;
16447 else
16448 no = nt->named_object();
16449 }
16450 break;
16451
16452 case EXPRESSION_VAR_REFERENCE:
16453 no = name_expr->var_expression()->named_object();
16454 break;
16455
16456 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16457 no = name_expr->enclosed_var_expression()->variable();
16458 break;
16459
16460 case EXPRESSION_FUNC_REFERENCE:
16461 no = name_expr->func_expression()->named_object();
16462 break;
16463
16464 default:
16465 bad_key = true;
16466 break;
16467 }
16468 if (bad_key)
16469 {
16470 go_error_at(name_expr->location(), "expected struct field name");
16471 return Expression::make_error(location);
16472 }
16473
16474 if (no != NULL)
16475 {
16476 if (no->package() != NULL && external_expr == NULL)
16477 {
16478 external_expr = name_expr;
16479 external_no = no;
16480 }
16481
16482 name = no->name();
16483
16484 // A predefined name won't be packed. If it starts with a
16485 // lower case letter we need to check for that case, because
16486 // the field name will be packed. FIXME.
16487 if (!Gogo::is_hidden_name(name)
16488 && name[0] >= 'a'
16489 && name[0] <= 'z')
16490 {
16491 Named_object* gno = gogo->lookup_global(name.c_str());
16492 if (gno == no)
16493 name = gogo->pack_hidden_name(name, false);
16494 }
16495 }
16496
16497 unsigned int index;
16498 const Struct_field* sf = st->find_local_field(name, &index);
16499 if (sf == NULL)
16500 {
16501 go_error_at(name_expr->location(), "unknown field %qs in %qs",
16502 Gogo::message_name(name).c_str(),
16503 (type->named_type() != NULL
16504 ? type->named_type()->message_name().c_str()
16505 : "unnamed struct"));
16506 return Expression::make_error(location);
16507 }
16508 if (vals[index] != NULL)
16509 {
16510 go_error_at(name_expr->location(),
16511 "duplicate value for field %qs in %qs",
16512 Gogo::message_name(name).c_str(),
16513 (type->named_type() != NULL
16514 ? type->named_type()->message_name().c_str()
16515 : "unnamed struct"));
16516 return Expression::make_error(location);
16517 }
16518
16519 if (type->named_type() != NULL
16520 && type->named_type()->named_object()->package() != NULL
16521 && (Gogo::is_hidden_name(sf->field_name())
16522 || sf->is_embedded_builtin(gogo)))
16523 go_error_at(name_expr->location(),
16524 "assignment of unexported field %qs in %qs literal",
16525 Gogo::message_name(sf->field_name()).c_str(),
16526 type->named_type()->message_name().c_str());
16527
16528 vals[index] = val;
16529 traverse_order->push_back(static_cast<unsigned long>(index));
16530 }
16531
16532 if (!this->all_are_names_)
16533 {
16534 // This is a weird case like bug462 in the testsuite.
16535 if (external_expr == NULL)
16536 go_error_at(this->location(), "unknown field in %qs literal",
16537 (type->named_type() != NULL
16538 ? type->named_type()->message_name().c_str()
16539 : "unnamed struct"));
16540 else
16541 go_error_at(external_expr->location(), "unknown field %qs in %qs",
16542 external_no->message_name().c_str(),
16543 (type->named_type() != NULL
16544 ? type->named_type()->message_name().c_str()
16545 : "unnamed struct"));
16546 return Expression::make_error(location);
16547 }
16548
16549 Expression_list* list = new Expression_list;
16550 list->reserve(field_count);
16551 for (size_t i = 0; i < field_count; ++i)
16552 list->push_back(vals[i]);
16553
16554 Struct_construction_expression* ret =
16555 new Struct_construction_expression(type, list, location);
16556 ret->set_traverse_order(traverse_order);
16557 return ret;
16558 }
16559
16560 // Index/value/traversal-order triple.
16561
16562 struct IVT_triple {
16563 unsigned long index;
16564 unsigned long traversal_order;
16565 Expression* expr;
16566 IVT_triple(unsigned long i, unsigned long to, Expression *e)
16567 : index(i), traversal_order(to), expr(e) { }
16568 bool operator<(const IVT_triple& other) const
16569 { return this->index < other.index; }
16570 };
16571
16572 // Lower an array composite literal.
16573
16574 Expression*
16575 Composite_literal_expression::lower_array(Type* type)
16576 {
16577 Location location = this->location();
16578 if (this->vals_ == NULL || !this->has_keys_)
16579 return this->make_array(type, NULL, this->vals_);
16580
16581 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
16582 indexes->reserve(this->vals_->size());
16583 bool indexes_out_of_order = false;
16584 Expression_list* vals = new Expression_list();
16585 vals->reserve(this->vals_->size());
16586 unsigned long index = 0;
16587 Expression_list::const_iterator p = this->vals_->begin();
16588 while (p != this->vals_->end())
16589 {
16590 Expression* index_expr = *p;
16591
16592 ++p;
16593 go_assert(p != this->vals_->end());
16594 Expression* val = *p;
16595
16596 ++p;
16597
16598 if (index_expr == NULL)
16599 {
16600 if (std::find(indexes->begin(), indexes->end(), index)
16601 != indexes->end())
16602 {
16603 go_error_at(val->location(),
16604 "duplicate value for index %lu", index);
16605 return Expression::make_error(location);
16606 }
16607 if (!indexes->empty())
16608 indexes->push_back(index);
16609 }
16610 else
16611 {
16612 if (indexes->empty() && !vals->empty())
16613 {
16614 for (size_t i = 0; i < vals->size(); ++i)
16615 indexes->push_back(i);
16616 }
16617
16618 Numeric_constant nc;
16619 if (!index_expr->numeric_constant_value(&nc))
16620 {
16621 go_error_at(index_expr->location(),
16622 "index expression is not integer constant");
16623 return Expression::make_error(location);
16624 }
16625
16626 switch (nc.to_unsigned_long(&index))
16627 {
16628 case Numeric_constant::NC_UL_VALID:
16629 break;
16630 case Numeric_constant::NC_UL_NOTINT:
16631 go_error_at(index_expr->location(),
16632 "index expression is not integer constant");
16633 return Expression::make_error(location);
16634 case Numeric_constant::NC_UL_NEGATIVE:
16635 go_error_at(index_expr->location(),
16636 "index expression is negative");
16637 return Expression::make_error(location);
16638 case Numeric_constant::NC_UL_BIG:
16639 go_error_at(index_expr->location(), "index value overflow");
16640 return Expression::make_error(location);
16641 default:
16642 go_unreachable();
16643 }
16644
16645 Named_type* ntype = Type::lookup_integer_type("int");
16646 Integer_type* inttype = ntype->integer_type();
16647 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
16648 && index >> (inttype->bits() - 1) != 0)
16649 {
16650 go_error_at(index_expr->location(), "index value overflow");
16651 return Expression::make_error(location);
16652 }
16653
16654 if (std::find(indexes->begin(), indexes->end(), index)
16655 != indexes->end())
16656 {
16657 go_error_at(index_expr->location(),
16658 "duplicate value for index %lu",
16659 index);
16660 return Expression::make_error(location);
16661 }
16662
16663 if (!indexes->empty() && index < indexes->back())
16664 indexes_out_of_order = true;
16665
16666 indexes->push_back(index);
16667 }
16668
16669 vals->push_back(val);
16670
16671 ++index;
16672 }
16673
16674 if (indexes->empty())
16675 {
16676 delete indexes;
16677 indexes = NULL;
16678 }
16679
16680 std::vector<unsigned long>* traverse_order = NULL;
16681 if (indexes_out_of_order)
16682 {
16683 typedef std::vector<IVT_triple> V;
16684
16685 V v;
16686 v.reserve(indexes->size());
16687 std::vector<unsigned long>::const_iterator pi = indexes->begin();
16688 unsigned long torder = 0;
16689 for (Expression_list::const_iterator pe = vals->begin();
16690 pe != vals->end();
16691 ++pe, ++pi, ++torder)
16692 v.push_back(IVT_triple(*pi, torder, *pe));
16693
16694 std::sort(v.begin(), v.end());
16695
16696 delete indexes;
16697 delete vals;
16698
16699 indexes = new std::vector<unsigned long>();
16700 indexes->reserve(v.size());
16701 vals = new Expression_list();
16702 vals->reserve(v.size());
16703 traverse_order = new std::vector<unsigned long>();
16704 traverse_order->reserve(v.size());
16705
16706 for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
16707 {
16708 indexes->push_back(pv->index);
16709 vals->push_back(pv->expr);
16710 traverse_order->push_back(pv->traversal_order);
16711 }
16712 }
16713
16714 Expression* ret = this->make_array(type, indexes, vals);
16715 Array_construction_expression* ace = ret->array_literal();
16716 if (ace != NULL && traverse_order != NULL)
16717 ace->set_traverse_order(traverse_order);
16718 return ret;
16719 }
16720
16721 // Actually build the array composite literal. This handles
16722 // [...]{...}.
16723
16724 Expression*
16725 Composite_literal_expression::make_array(
16726 Type* type,
16727 const std::vector<unsigned long>* indexes,
16728 Expression_list* vals)
16729 {
16730 Location location = this->location();
16731 Array_type* at = type->array_type();
16732
16733 if (at->length() != NULL && at->length()->is_nil_expression())
16734 {
16735 size_t size;
16736 if (vals == NULL)
16737 size = 0;
16738 else if (indexes != NULL)
16739 size = indexes->back() + 1;
16740 else
16741 {
16742 size = vals->size();
16743 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
16744 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
16745 && size >> (it->bits() - 1) != 0)
16746 {
16747 go_error_at(location, "too many elements in composite literal");
16748 return Expression::make_error(location);
16749 }
16750 }
16751
16752 Expression* elen = Expression::make_integer_ul(size, NULL, location);
16753 at = Type::make_array_type(at->element_type(), elen);
16754 type = at;
16755 }
16756 else if (at->length() != NULL
16757 && !at->length()->is_error_expression()
16758 && this->vals_ != NULL)
16759 {
16760 Numeric_constant nc;
16761 unsigned long val;
16762 if (at->length()->numeric_constant_value(&nc)
16763 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
16764 {
16765 if (indexes == NULL)
16766 {
16767 if (this->vals_->size() > val)
16768 {
16769 go_error_at(location,
16770 "too many elements in composite literal");
16771 return Expression::make_error(location);
16772 }
16773 }
16774 else
16775 {
16776 unsigned long max = indexes->back();
16777 if (max >= val)
16778 {
16779 go_error_at(location,
16780 ("some element keys in composite literal "
16781 "are out of range"));
16782 return Expression::make_error(location);
16783 }
16784 }
16785 }
16786 }
16787
16788 if (at->length() != NULL)
16789 return new Fixed_array_construction_expression(type, indexes, vals,
16790 location);
16791 else
16792 return new Slice_construction_expression(type, indexes, vals, location);
16793 }
16794
16795 // Lower a map composite literal.
16796
16797 Expression*
16798 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
16799 Statement_inserter* inserter,
16800 Type* type)
16801 {
16802 Location location = this->location();
16803 Unordered_map(unsigned int, std::vector<Expression*>) st;
16804 Unordered_map(unsigned int, std::vector<Expression*>) nt;
16805 if (this->vals_ != NULL)
16806 {
16807 if (!this->has_keys_)
16808 {
16809 go_error_at(location, "map composite literal must have keys");
16810 return Expression::make_error(location);
16811 }
16812
16813 for (Expression_list::iterator p = this->vals_->begin();
16814 p != this->vals_->end();
16815 p += 2)
16816 {
16817 if (*p == NULL)
16818 {
16819 ++p;
16820 go_error_at((*p)->location(),
16821 ("map composite literal must "
16822 "have keys for every value"));
16823 return Expression::make_error(location);
16824 }
16825 // Make sure we have lowered the key; it may not have been
16826 // lowered in order to handle keys for struct composite
16827 // literals. Lower it now to get the right error message.
16828 if ((*p)->unknown_expression() != NULL)
16829 {
16830 gogo->lower_expression(function, inserter, &*p);
16831 go_assert((*p)->is_error_expression());
16832 return Expression::make_error(location);
16833 }
16834 // Check if there are duplicate constant keys.
16835 if (!(*p)->is_constant())
16836 continue;
16837 std::string sval;
16838 Numeric_constant nval;
16839 if ((*p)->string_constant_value(&sval)) // Check string keys.
16840 {
16841 unsigned int h = Gogo::hash_string(sval, 0);
16842 // Search the index h in the hash map.
16843 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16844 mit = st.find(h);
16845 if (mit == st.end())
16846 {
16847 // No duplicate since h is a new index.
16848 // Create a new vector indexed by h and add it to the hash map.
16849 std::vector<Expression*> l;
16850 l.push_back(*p);
16851 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16852 st.insert(val);
16853 }
16854 else
16855 {
16856 // Do further check since index h already exists.
16857 for (std::vector<Expression*>::iterator lit =
16858 mit->second.begin();
16859 lit != mit->second.end();
16860 lit++)
16861 {
16862 std::string s;
16863 bool ok = (*lit)->string_constant_value(&s);
16864 go_assert(ok);
16865 if (s == sval)
16866 {
16867 go_error_at((*p)->location(), ("duplicate key "
16868 "in map literal"));
16869 return Expression::make_error(location);
16870 }
16871 }
16872 // Add this new string key to the vector indexed by h.
16873 mit->second.push_back(*p);
16874 }
16875 }
16876 else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
16877 {
16878 unsigned int h = nval.hash(0);
16879 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16880 mit = nt.find(h);
16881 if (mit == nt.end())
16882 {
16883 // No duplicate since h is a new code.
16884 // Create a new vector indexed by h and add it to the hash map.
16885 std::vector<Expression*> l;
16886 l.push_back(*p);
16887 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16888 nt.insert(val);
16889 }
16890 else
16891 {
16892 // Do further check since h already exists.
16893 for (std::vector<Expression*>::iterator lit =
16894 mit->second.begin();
16895 lit != mit->second.end();
16896 lit++)
16897 {
16898 Numeric_constant rval;
16899 bool ok = (*lit)->numeric_constant_value(&rval);
16900 go_assert(ok);
16901 if (nval.equals(rval))
16902 {
16903 go_error_at((*p)->location(),
16904 "duplicate key in map literal");
16905 return Expression::make_error(location);
16906 }
16907 }
16908 // Add this new numeric key to the vector indexed by h.
16909 mit->second.push_back(*p);
16910 }
16911 }
16912 }
16913 }
16914
16915 return new Map_construction_expression(type, this->vals_, location);
16916 }
16917
16918 // Copy.
16919
16920 Expression*
16921 Composite_literal_expression::do_copy()
16922 {
16923 Composite_literal_expression* ret =
16924 new Composite_literal_expression(this->type_->copy_expressions(),
16925 this->depth_, this->has_keys_,
16926 (this->vals_ == NULL
16927 ? NULL
16928 : this->vals_->copy()),
16929 this->all_are_names_,
16930 this->location());
16931 ret->key_path_ = this->key_path_;
16932 return ret;
16933 }
16934
16935 // Dump ast representation for a composite literal expression.
16936
16937 void
16938 Composite_literal_expression::do_dump_expression(
16939 Ast_dump_context* ast_dump_context) const
16940 {
16941 ast_dump_context->ostream() << "composite(";
16942 ast_dump_context->dump_type(this->type_);
16943 ast_dump_context->ostream() << ", {";
16944 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
16945 ast_dump_context->ostream() << "})";
16946 }
16947
16948 // Make a composite literal expression.
16949
16950 Expression*
16951 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
16952 Expression_list* vals, bool all_are_names,
16953 Location location)
16954 {
16955 return new Composite_literal_expression(type, depth, has_keys, vals,
16956 all_are_names, location);
16957 }
16958
16959 // Return whether this expression is a composite literal.
16960
16961 bool
16962 Expression::is_composite_literal() const
16963 {
16964 switch (this->classification_)
16965 {
16966 case EXPRESSION_COMPOSITE_LITERAL:
16967 case EXPRESSION_STRUCT_CONSTRUCTION:
16968 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16969 case EXPRESSION_SLICE_CONSTRUCTION:
16970 case EXPRESSION_MAP_CONSTRUCTION:
16971 return true;
16972 default:
16973 return false;
16974 }
16975 }
16976
16977 // Return whether this expression is a composite literal which is not
16978 // constant.
16979
16980 bool
16981 Expression::is_nonconstant_composite_literal() const
16982 {
16983 switch (this->classification_)
16984 {
16985 case EXPRESSION_STRUCT_CONSTRUCTION:
16986 {
16987 const Struct_construction_expression *psce =
16988 static_cast<const Struct_construction_expression*>(this);
16989 return !psce->is_constant_struct();
16990 }
16991 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16992 {
16993 const Fixed_array_construction_expression *pace =
16994 static_cast<const Fixed_array_construction_expression*>(this);
16995 return !pace->is_constant_array();
16996 }
16997 case EXPRESSION_SLICE_CONSTRUCTION:
16998 {
16999 const Slice_construction_expression *pace =
17000 static_cast<const Slice_construction_expression*>(this);
17001 return !pace->is_constant_array();
17002 }
17003 case EXPRESSION_MAP_CONSTRUCTION:
17004 return true;
17005 default:
17006 return false;
17007 }
17008 }
17009
17010 // Return true if this is a variable or temporary_variable.
17011
17012 bool
17013 Expression::is_variable() const
17014 {
17015 switch (this->classification_)
17016 {
17017 case EXPRESSION_VAR_REFERENCE:
17018 case EXPRESSION_TEMPORARY_REFERENCE:
17019 case EXPRESSION_SET_AND_USE_TEMPORARY:
17020 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
17021 return true;
17022 default:
17023 return false;
17024 }
17025 }
17026
17027 // Return true if this is a reference to a local variable.
17028
17029 bool
17030 Expression::is_local_variable() const
17031 {
17032 const Var_expression* ve = this->var_expression();
17033 if (ve == NULL)
17034 return false;
17035 const Named_object* no = ve->named_object();
17036 return (no->is_result_variable()
17037 || (no->is_variable() && !no->var_value()->is_global()));
17038 }
17039
17040 const Named_object*
17041 Expression::named_constant() const
17042 {
17043 if (this->classification() != EXPRESSION_CONST_REFERENCE)
17044 return NULL;
17045 const Const_expression* ce = static_cast<const Const_expression*>(this);
17046 return ce->named_object();
17047 }
17048
17049 // Class Type_guard_expression.
17050
17051 // Traversal.
17052
17053 int
17054 Type_guard_expression::do_traverse(Traverse* traverse)
17055 {
17056 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
17057 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17058 return TRAVERSE_EXIT;
17059 return TRAVERSE_CONTINUE;
17060 }
17061
17062 Expression*
17063 Type_guard_expression::do_flatten(Gogo*, Named_object*,
17064 Statement_inserter* inserter)
17065 {
17066 if (this->expr_->is_error_expression()
17067 || this->expr_->type()->is_error_type())
17068 {
17069 go_assert(saw_errors());
17070 return Expression::make_error(this->location());
17071 }
17072
17073 if (!this->expr_->is_variable())
17074 {
17075 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
17076 this->location());
17077 inserter->insert(temp);
17078 this->expr_ =
17079 Expression::make_temporary_reference(temp, this->location());
17080 }
17081 return this;
17082 }
17083
17084 // Check types of a type guard expression. The expression must have
17085 // an interface type, but the actual type conversion is checked at run
17086 // time.
17087
17088 void
17089 Type_guard_expression::do_check_types(Gogo*)
17090 {
17091 Type* expr_type = this->expr_->type();
17092 if (expr_type->interface_type() == NULL)
17093 {
17094 if (!expr_type->is_error() && !this->type_->is_error())
17095 this->report_error(_("type assertion only valid for interface types"));
17096 this->set_is_error();
17097 }
17098 else if (this->type_->interface_type() == NULL)
17099 {
17100 std::string reason;
17101 if (!expr_type->interface_type()->implements_interface(this->type_,
17102 &reason))
17103 {
17104 if (!this->type_->is_error())
17105 {
17106 if (reason.empty())
17107 this->report_error(_("impossible type assertion: "
17108 "type does not implement interface"));
17109 else
17110 go_error_at(this->location(),
17111 ("impossible type assertion: "
17112 "type does not implement interface (%s)"),
17113 reason.c_str());
17114 }
17115 this->set_is_error();
17116 }
17117 }
17118 }
17119
17120 // Copy.
17121
17122 Expression*
17123 Type_guard_expression::do_copy()
17124 {
17125 return new Type_guard_expression(this->expr_->copy(),
17126 this->type_->copy_expressions(),
17127 this->location());
17128 }
17129
17130 // Return the backend representation for a type guard expression.
17131
17132 Bexpression*
17133 Type_guard_expression::do_get_backend(Translate_context* context)
17134 {
17135 Expression* conversion;
17136 if (this->type_->interface_type() != NULL)
17137 conversion =
17138 Expression::convert_interface_to_interface(this->type_, this->expr_,
17139 true, this->location());
17140 else
17141 conversion =
17142 Expression::convert_for_assignment(context->gogo(), this->type_,
17143 this->expr_, this->location());
17144
17145 Gogo* gogo = context->gogo();
17146 Btype* bt = this->type_->get_backend(gogo);
17147 Bexpression* bexpr = conversion->get_backend(context);
17148 return gogo->backend()->convert_expression(bt, bexpr, this->location());
17149 }
17150
17151 // Dump ast representation for a type guard expression.
17152
17153 void
17154 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
17155 const
17156 {
17157 this->expr_->dump_expression(ast_dump_context);
17158 ast_dump_context->ostream() << ".";
17159 ast_dump_context->dump_type(this->type_);
17160 }
17161
17162 // Make a type guard expression.
17163
17164 Expression*
17165 Expression::make_type_guard(Expression* expr, Type* type,
17166 Location location)
17167 {
17168 return new Type_guard_expression(expr, type, location);
17169 }
17170
17171 // Class Heap_expression.
17172
17173 // Return the type of the expression stored on the heap.
17174
17175 Type*
17176 Heap_expression::do_type()
17177 { return Type::make_pointer_type(this->expr_->type()); }
17178
17179 // Return the backend representation for allocating an expression on the heap.
17180
17181 Bexpression*
17182 Heap_expression::do_get_backend(Translate_context* context)
17183 {
17184 Type* etype = this->expr_->type();
17185 if (this->expr_->is_error_expression() || etype->is_error())
17186 return context->backend()->error_expression();
17187
17188 Location loc = this->location();
17189 Gogo* gogo = context->gogo();
17190 Btype* btype = this->type()->get_backend(gogo);
17191
17192 Expression* alloc = Expression::make_allocation(etype, loc);
17193 if (this->allocate_on_stack_)
17194 alloc->allocation_expression()->set_allocate_on_stack();
17195 Bexpression* space = alloc->get_backend(context);
17196
17197 Bstatement* decl;
17198 Named_object* fn = context->function();
17199 go_assert(fn != NULL);
17200 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
17201 Bvariable* space_temp =
17202 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
17203 space, true, loc, &decl);
17204 Btype* expr_btype = etype->get_backend(gogo);
17205
17206 Bexpression* bexpr = this->expr_->get_backend(context);
17207
17208 // If this assignment needs a write barrier, call typedmemmove. We
17209 // don't do this in the write barrier pass because in some cases
17210 // backend conversion can introduce new Heap_expression values.
17211 Bstatement* assn;
17212 if (!etype->has_pointer() || this->allocate_on_stack_)
17213 {
17214 space = gogo->backend()->var_expression(space_temp, loc);
17215 Bexpression* ref =
17216 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17217 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
17218 }
17219 else
17220 {
17221 Bstatement* edecl;
17222 Bvariable* btemp =
17223 gogo->backend()->temporary_variable(fndecl, context->bblock(),
17224 expr_btype, bexpr, true, loc,
17225 &edecl);
17226 Bexpression* btempref = gogo->backend()->var_expression(btemp,
17227 loc);
17228 space = gogo->backend()->var_expression(space_temp, loc);
17229 Type* etype_ptr = Type::make_pointer_type(etype);
17230 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
17231 Expression* erhs;
17232 Expression* call;
17233 if (etype->is_direct_iface_type())
17234 {
17235 // Single pointer.
17236 Type* uintptr_type = Type::lookup_integer_type("uintptr");
17237 erhs = Expression::make_backend(btempref, etype, loc);
17238 erhs = Expression::unpack_direct_iface(erhs, loc);
17239 erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
17240 call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
17241 elhs, erhs);
17242 }
17243 else
17244 {
17245 Expression* td = Expression::make_type_descriptor(etype, loc);
17246 Bexpression* addr =
17247 gogo->backend()->address_expression(btempref, loc);
17248 erhs = Expression::make_backend(addr, etype_ptr, loc);
17249 call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
17250 td, elhs, erhs);
17251 }
17252 Statement* cs = Statement::make_statement(call, false);
17253
17254 space = gogo->backend()->var_expression(space_temp, loc);
17255 Bexpression* ref =
17256 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17257 Expression* eref = Expression::make_backend(ref, etype, loc);
17258 btempref = gogo->backend()->var_expression(btemp, loc);
17259 erhs = Expression::make_backend(btempref, etype, loc);
17260 Statement* as = Statement::make_assignment(eref, erhs, loc);
17261
17262 as = gogo->check_write_barrier(context->block(), as, cs);
17263 Bstatement* s = as->get_backend(context);
17264
17265 assn = gogo->backend()->compound_statement(edecl, s);
17266 }
17267 decl = gogo->backend()->compound_statement(decl, assn);
17268 space = gogo->backend()->var_expression(space_temp, loc);
17269 return gogo->backend()->compound_expression(decl, space, loc);
17270 }
17271
17272 // Dump ast representation for a heap expression.
17273
17274 void
17275 Heap_expression::do_dump_expression(
17276 Ast_dump_context* ast_dump_context) const
17277 {
17278 ast_dump_context->ostream() << "&(";
17279 ast_dump_context->dump_expression(this->expr_);
17280 ast_dump_context->ostream() << ")";
17281 }
17282
17283 // Allocate an expression on the heap.
17284
17285 Expression*
17286 Expression::make_heap_expression(Expression* expr, Location location)
17287 {
17288 return new Heap_expression(expr, location);
17289 }
17290
17291 // Class Receive_expression.
17292
17293 // Return the type of a receive expression.
17294
17295 Type*
17296 Receive_expression::do_type()
17297 {
17298 if (this->is_error_expression())
17299 return Type::make_error_type();
17300 Channel_type* channel_type = this->channel_->type()->channel_type();
17301 if (channel_type == NULL)
17302 {
17303 this->report_error(_("expected channel"));
17304 return Type::make_error_type();
17305 }
17306 return channel_type->element_type();
17307 }
17308
17309 // Check types for a receive expression.
17310
17311 void
17312 Receive_expression::do_check_types(Gogo*)
17313 {
17314 Type* type = this->channel_->type();
17315 if (type->is_error())
17316 {
17317 go_assert(saw_errors());
17318 this->set_is_error();
17319 return;
17320 }
17321 if (type->channel_type() == NULL)
17322 {
17323 this->report_error(_("expected channel"));
17324 return;
17325 }
17326 if (!type->channel_type()->may_receive())
17327 {
17328 this->report_error(_("invalid receive on send-only channel"));
17329 return;
17330 }
17331 }
17332
17333 // Flattening for receive expressions creates a temporary variable to store
17334 // received data in for receives.
17335
17336 Expression*
17337 Receive_expression::do_flatten(Gogo*, Named_object*,
17338 Statement_inserter* inserter)
17339 {
17340 Channel_type* channel_type = this->channel_->type()->channel_type();
17341 if (channel_type == NULL)
17342 {
17343 go_assert(saw_errors());
17344 return this;
17345 }
17346 else if (this->channel_->is_error_expression())
17347 {
17348 go_assert(saw_errors());
17349 return Expression::make_error(this->location());
17350 }
17351
17352 Type* element_type = channel_type->element_type();
17353 if (this->temp_receiver_ == NULL)
17354 {
17355 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
17356 this->location());
17357 this->temp_receiver_->set_is_address_taken();
17358 inserter->insert(this->temp_receiver_);
17359 }
17360
17361 return this;
17362 }
17363
17364 // Get the backend representation for a receive expression.
17365
17366 Bexpression*
17367 Receive_expression::do_get_backend(Translate_context* context)
17368 {
17369 Location loc = this->location();
17370
17371 Channel_type* channel_type = this->channel_->type()->channel_type();
17372 if (channel_type == NULL)
17373 {
17374 go_assert(this->channel_->type()->is_error());
17375 return context->backend()->error_expression();
17376 }
17377
17378 Expression* recv_ref =
17379 Expression::make_temporary_reference(this->temp_receiver_, loc);
17380 Expression* recv_addr =
17381 Expression::make_temporary_reference(this->temp_receiver_, loc);
17382 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
17383 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
17384 this->channel_, recv_addr);
17385 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
17386 }
17387
17388 // Export a receive expression.
17389
17390 void
17391 Receive_expression::do_export(Export_function_body* efb) const
17392 {
17393 efb->write_c_string("<-");
17394 this->channel_->export_expression(efb);
17395 }
17396
17397 // Dump ast representation for a receive expression.
17398
17399 void
17400 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
17401 {
17402 ast_dump_context->ostream() << " <- " ;
17403 ast_dump_context->dump_expression(channel_);
17404 }
17405
17406 // Import a receive expression.
17407
17408 Expression*
17409 Receive_expression::do_import(Import_expression* imp, Location loc)
17410 {
17411 imp->require_c_string("<-");
17412 Expression* expr = Expression::import_expression(imp, loc);
17413 return Expression::make_receive(expr, loc);
17414 }
17415
17416 // Make a receive expression.
17417
17418 Receive_expression*
17419 Expression::make_receive(Expression* channel, Location location)
17420 {
17421 return new Receive_expression(channel, location);
17422 }
17423
17424 // An expression which evaluates to a pointer to the type descriptor
17425 // of a type.
17426
17427 class Type_descriptor_expression : public Expression
17428 {
17429 public:
17430 Type_descriptor_expression(Type* type, Location location)
17431 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
17432 type_(type)
17433 { }
17434
17435 protected:
17436 int
17437 do_traverse(Traverse*);
17438
17439 Type*
17440 do_type()
17441 { return Type::make_type_descriptor_ptr_type(); }
17442
17443 bool
17444 do_is_static_initializer() const
17445 { return true; }
17446
17447 void
17448 do_determine_type(const Type_context*)
17449 { }
17450
17451 Expression*
17452 do_copy()
17453 { return this; }
17454
17455 Bexpression*
17456 do_get_backend(Translate_context* context)
17457 {
17458 return this->type_->type_descriptor_pointer(context->gogo(),
17459 this->location());
17460 }
17461
17462 void
17463 do_dump_expression(Ast_dump_context*) const;
17464
17465 private:
17466 // The type for which this is the descriptor.
17467 Type* type_;
17468 };
17469
17470 int
17471 Type_descriptor_expression::do_traverse(Traverse* traverse)
17472 {
17473 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17474 return TRAVERSE_EXIT;
17475 return TRAVERSE_CONTINUE;
17476 }
17477
17478 // Dump ast representation for a type descriptor expression.
17479
17480 void
17481 Type_descriptor_expression::do_dump_expression(
17482 Ast_dump_context* ast_dump_context) const
17483 {
17484 ast_dump_context->dump_type(this->type_);
17485 }
17486
17487 // Make a type descriptor expression.
17488
17489 Expression*
17490 Expression::make_type_descriptor(Type* type, Location location)
17491 {
17492 return new Type_descriptor_expression(type, location);
17493 }
17494
17495 // An expression which evaluates to a pointer to the Garbage Collection symbol
17496 // of a type.
17497
17498 class GC_symbol_expression : public Expression
17499 {
17500 public:
17501 GC_symbol_expression(Type* type)
17502 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
17503 type_(type)
17504 {}
17505
17506 protected:
17507 Type*
17508 do_type()
17509 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17510
17511 bool
17512 do_is_static_initializer() const
17513 { return true; }
17514
17515 void
17516 do_determine_type(const Type_context*)
17517 { }
17518
17519 Expression*
17520 do_copy()
17521 { return this; }
17522
17523 Bexpression*
17524 do_get_backend(Translate_context* context)
17525 { return this->type_->gc_symbol_pointer(context->gogo()); }
17526
17527 void
17528 do_dump_expression(Ast_dump_context*) const;
17529
17530 private:
17531 // The type which this gc symbol describes.
17532 Type* type_;
17533 };
17534
17535 // Dump ast representation for a gc symbol expression.
17536
17537 void
17538 GC_symbol_expression::do_dump_expression(
17539 Ast_dump_context* ast_dump_context) const
17540 {
17541 ast_dump_context->ostream() << "gcdata(";
17542 ast_dump_context->dump_type(this->type_);
17543 ast_dump_context->ostream() << ")";
17544 }
17545
17546 // Make a gc symbol expression.
17547
17548 Expression*
17549 Expression::make_gc_symbol(Type* type)
17550 {
17551 return new GC_symbol_expression(type);
17552 }
17553
17554 // An expression that evaluates to a pointer to a symbol holding the
17555 // ptrmask data of a type.
17556
17557 class Ptrmask_symbol_expression : public Expression
17558 {
17559 public:
17560 Ptrmask_symbol_expression(Type* type)
17561 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
17562 type_(type)
17563 {}
17564
17565 protected:
17566 Type*
17567 do_type()
17568 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17569
17570 bool
17571 do_is_static_initializer() const
17572 { return true; }
17573
17574 void
17575 do_determine_type(const Type_context*)
17576 { }
17577
17578 Expression*
17579 do_copy()
17580 { return this; }
17581
17582 Bexpression*
17583 do_get_backend(Translate_context*);
17584
17585 void
17586 do_dump_expression(Ast_dump_context*) const;
17587
17588 private:
17589 // The type that this ptrmask symbol describes.
17590 Type* type_;
17591 };
17592
17593 // Return the ptrmask variable.
17594
17595 Bexpression*
17596 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
17597 {
17598 Gogo* gogo = context->gogo();
17599
17600 // If this type does not need a gcprog, then we can use the standard
17601 // GC symbol.
17602 int64_t ptrsize, ptrdata;
17603 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
17604 return this->type_->gc_symbol_pointer(gogo);
17605
17606 // Otherwise we have to build a ptrmask variable, and return a
17607 // pointer to it.
17608
17609 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
17610 Location bloc = Linemap::predeclared_location();
17611 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
17612 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
17613
17614 Type* uint8_type = Type::lookup_integer_type("uint8");
17615 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
17616 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
17617 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
17618 }
17619
17620 // Dump AST for a ptrmask symbol expression.
17621
17622 void
17623 Ptrmask_symbol_expression::do_dump_expression(
17624 Ast_dump_context* ast_dump_context) const
17625 {
17626 ast_dump_context->ostream() << "ptrmask(";
17627 ast_dump_context->dump_type(this->type_);
17628 ast_dump_context->ostream() << ")";
17629 }
17630
17631 // Make a ptrmask symbol expression.
17632
17633 Expression*
17634 Expression::make_ptrmask_symbol(Type* type)
17635 {
17636 return new Ptrmask_symbol_expression(type);
17637 }
17638
17639 // An expression which evaluates to some characteristic of a type.
17640 // This is only used to initialize fields of a type descriptor. Using
17641 // a new expression class is slightly inefficient but gives us a good
17642 // separation between the frontend and the middle-end with regard to
17643 // how types are laid out.
17644
17645 class Type_info_expression : public Expression
17646 {
17647 public:
17648 Type_info_expression(Type* type, Type_info type_info)
17649 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
17650 type_(type), type_info_(type_info)
17651 { }
17652
17653 protected:
17654 bool
17655 do_is_static_initializer() const
17656 { return true; }
17657
17658 Type*
17659 do_type();
17660
17661 void
17662 do_determine_type(const Type_context*)
17663 { }
17664
17665 Expression*
17666 do_copy()
17667 { return this; }
17668
17669 Bexpression*
17670 do_get_backend(Translate_context* context);
17671
17672 void
17673 do_dump_expression(Ast_dump_context*) const;
17674
17675 private:
17676 // The type for which we are getting information.
17677 Type* type_;
17678 // What information we want.
17679 Type_info type_info_;
17680 };
17681
17682 // The type is chosen to match what the type descriptor struct
17683 // expects.
17684
17685 Type*
17686 Type_info_expression::do_type()
17687 {
17688 switch (this->type_info_)
17689 {
17690 case TYPE_INFO_SIZE:
17691 case TYPE_INFO_BACKEND_PTRDATA:
17692 case TYPE_INFO_DESCRIPTOR_PTRDATA:
17693 return Type::lookup_integer_type("uintptr");
17694 case TYPE_INFO_ALIGNMENT:
17695 case TYPE_INFO_FIELD_ALIGNMENT:
17696 return Type::lookup_integer_type("uint8");
17697 default:
17698 go_unreachable();
17699 }
17700 }
17701
17702 // Return the backend representation for type information.
17703
17704 Bexpression*
17705 Type_info_expression::do_get_backend(Translate_context* context)
17706 {
17707 Gogo* gogo = context->gogo();
17708 bool ok = true;
17709 int64_t val;
17710 switch (this->type_info_)
17711 {
17712 case TYPE_INFO_SIZE:
17713 ok = this->type_->backend_type_size(gogo, &val);
17714 break;
17715 case TYPE_INFO_ALIGNMENT:
17716 ok = this->type_->backend_type_align(gogo, &val);
17717 break;
17718 case TYPE_INFO_FIELD_ALIGNMENT:
17719 ok = this->type_->backend_type_field_align(gogo, &val);
17720 break;
17721 case TYPE_INFO_BACKEND_PTRDATA:
17722 ok = this->type_->backend_type_ptrdata(gogo, &val);
17723 break;
17724 case TYPE_INFO_DESCRIPTOR_PTRDATA:
17725 ok = this->type_->descriptor_ptrdata(gogo, &val);
17726 break;
17727 default:
17728 go_unreachable();
17729 }
17730 if (!ok)
17731 {
17732 go_assert(saw_errors());
17733 return gogo->backend()->error_expression();
17734 }
17735 Expression* e = Expression::make_integer_int64(val, this->type(),
17736 this->location());
17737 return e->get_backend(context);
17738 }
17739
17740 // Dump ast representation for a type info expression.
17741
17742 void
17743 Type_info_expression::do_dump_expression(
17744 Ast_dump_context* ast_dump_context) const
17745 {
17746 ast_dump_context->ostream() << "typeinfo(";
17747 ast_dump_context->dump_type(this->type_);
17748 ast_dump_context->ostream() << ",";
17749 ast_dump_context->ostream() <<
17750 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
17751 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
17752 : this->type_info_ == TYPE_INFO_SIZE ? "size"
17753 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
17754 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
17755 : "unknown");
17756 ast_dump_context->ostream() << ")";
17757 }
17758
17759 // Make a type info expression.
17760
17761 Expression*
17762 Expression::make_type_info(Type* type, Type_info type_info)
17763 {
17764 return new Type_info_expression(type, type_info);
17765 }
17766
17767 // An expression that evaluates to some characteristic of a slice.
17768 // This is used when indexing, bound-checking, or nil checking a slice.
17769
17770 class Slice_info_expression : public Expression
17771 {
17772 public:
17773 Slice_info_expression(Expression* slice, Slice_info slice_info,
17774 Location location)
17775 : Expression(EXPRESSION_SLICE_INFO, location),
17776 slice_(slice), slice_info_(slice_info)
17777 { }
17778
17779 protected:
17780 Type*
17781 do_type();
17782
17783 void
17784 do_determine_type(const Type_context*)
17785 { }
17786
17787 Expression*
17788 do_copy()
17789 {
17790 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
17791 this->location());
17792 }
17793
17794 Bexpression*
17795 do_get_backend(Translate_context* context);
17796
17797 void
17798 do_dump_expression(Ast_dump_context*) const;
17799
17800 void
17801 do_issue_nil_check()
17802 { this->slice_->issue_nil_check(); }
17803
17804 private:
17805 // The slice for which we are getting information.
17806 Expression* slice_;
17807 // What information we want.
17808 Slice_info slice_info_;
17809 };
17810
17811 // Return the type of the slice info.
17812
17813 Type*
17814 Slice_info_expression::do_type()
17815 {
17816 switch (this->slice_info_)
17817 {
17818 case SLICE_INFO_VALUE_POINTER:
17819 return Type::make_pointer_type(
17820 this->slice_->type()->array_type()->element_type());
17821 case SLICE_INFO_LENGTH:
17822 case SLICE_INFO_CAPACITY:
17823 return Type::lookup_integer_type("int");
17824 default:
17825 go_unreachable();
17826 }
17827 }
17828
17829 // Return the backend information for slice information.
17830
17831 Bexpression*
17832 Slice_info_expression::do_get_backend(Translate_context* context)
17833 {
17834 Gogo* gogo = context->gogo();
17835 Bexpression* bslice = this->slice_->get_backend(context);
17836 switch (this->slice_info_)
17837 {
17838 case SLICE_INFO_VALUE_POINTER:
17839 case SLICE_INFO_LENGTH:
17840 case SLICE_INFO_CAPACITY:
17841 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
17842 this->location());
17843 break;
17844 default:
17845 go_unreachable();
17846 }
17847 }
17848
17849 // Dump ast representation for a type info expression.
17850
17851 void
17852 Slice_info_expression::do_dump_expression(
17853 Ast_dump_context* ast_dump_context) const
17854 {
17855 ast_dump_context->ostream() << "sliceinfo(";
17856 this->slice_->dump_expression(ast_dump_context);
17857 ast_dump_context->ostream() << ",";
17858 ast_dump_context->ostream() <<
17859 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
17860 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
17861 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
17862 : "unknown");
17863 ast_dump_context->ostream() << ")";
17864 }
17865
17866 // Make a slice info expression.
17867
17868 Expression*
17869 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
17870 Location location)
17871 {
17872 return new Slice_info_expression(slice, slice_info, location);
17873 }
17874
17875 // Class Slice_value_expression.
17876
17877 int
17878 Slice_value_expression::do_traverse(Traverse* traverse)
17879 {
17880 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
17881 || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
17882 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
17883 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
17884 return TRAVERSE_EXIT;
17885 return TRAVERSE_CONTINUE;
17886 }
17887
17888 Expression*
17889 Slice_value_expression::do_copy()
17890 {
17891 return new Slice_value_expression(this->type_->copy_expressions(),
17892 this->valmem_->copy(),
17893 this->len_->copy(), this->cap_->copy(),
17894 this->location());
17895 }
17896
17897 Bexpression*
17898 Slice_value_expression::do_get_backend(Translate_context* context)
17899 {
17900 std::vector<Bexpression*> vals(3);
17901 vals[0] = this->valmem_->get_backend(context);
17902 vals[1] = this->len_->get_backend(context);
17903 vals[2] = this->cap_->get_backend(context);
17904
17905 Gogo* gogo = context->gogo();
17906 Btype* btype = this->type_->get_backend(gogo);
17907 return gogo->backend()->constructor_expression(btype, vals, this->location());
17908 }
17909
17910 void
17911 Slice_value_expression::do_dump_expression(
17912 Ast_dump_context* ast_dump_context) const
17913 {
17914 ast_dump_context->ostream() << "slicevalue(";
17915 ast_dump_context->ostream() << "values: ";
17916 this->valmem_->dump_expression(ast_dump_context);
17917 ast_dump_context->ostream() << ", length: ";
17918 this->len_->dump_expression(ast_dump_context);
17919 ast_dump_context->ostream() << ", capacity: ";
17920 this->cap_->dump_expression(ast_dump_context);
17921 ast_dump_context->ostream() << ")";
17922 }
17923
17924 Expression*
17925 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
17926 Expression* cap, Location location)
17927 {
17928 go_assert(at->is_slice_type());
17929 go_assert(valmem->is_nil_expression()
17930 || (at->array_type()->element_type()
17931 == valmem->type()->points_to()));
17932 return new Slice_value_expression(at, valmem, len, cap, location);
17933 }
17934
17935 // Look through the expression of a Slice_value_expression's valmem to
17936 // find an call to makeslice. If found, return the call expression and
17937 // the containing temporary statement (if any).
17938
17939 std::pair<Call_expression*, Temporary_statement*>
17940 Expression::find_makeslice_call(Expression* expr)
17941 {
17942 Unsafe_type_conversion_expression* utce =
17943 expr->unsafe_conversion_expression();
17944 if (utce != NULL)
17945 expr = utce->expr();
17946
17947 Slice_value_expression* sve = expr->slice_value_expression();
17948 if (sve == NULL)
17949 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17950 expr = sve->valmem();
17951
17952 utce = expr->unsafe_conversion_expression();
17953 if (utce != NULL)
17954 expr = utce->expr();
17955
17956 Temporary_reference_expression* tre = expr->temporary_reference_expression();
17957 Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
17958 if (ts != NULL && ts->init() != NULL && !ts->assigned()
17959 && !ts->is_address_taken())
17960 expr = ts->init();
17961
17962 Call_expression* call = expr->call_expression();
17963 if (call == NULL)
17964 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17965
17966 Func_expression* fe = call->fn()->func_expression();
17967 if (fe != NULL
17968 && fe->runtime_code() == Runtime::MAKESLICE)
17969 return std::make_pair(call, ts);
17970
17971 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17972 }
17973
17974 // An expression that evaluates to some characteristic of a non-empty interface.
17975 // This is used to access the method table or underlying object of an interface.
17976
17977 class Interface_info_expression : public Expression
17978 {
17979 public:
17980 Interface_info_expression(Expression* iface, Interface_info iface_info,
17981 Location location)
17982 : Expression(EXPRESSION_INTERFACE_INFO, location),
17983 iface_(iface), iface_info_(iface_info)
17984 { }
17985
17986 protected:
17987 Type*
17988 do_type();
17989
17990 void
17991 do_determine_type(const Type_context*)
17992 { }
17993
17994 Expression*
17995 do_copy()
17996 {
17997 return new Interface_info_expression(this->iface_->copy(),
17998 this->iface_info_, this->location());
17999 }
18000
18001 Bexpression*
18002 do_get_backend(Translate_context* context);
18003
18004 void
18005 do_dump_expression(Ast_dump_context*) const;
18006
18007 void
18008 do_issue_nil_check()
18009 { this->iface_->issue_nil_check(); }
18010
18011 private:
18012 // The interface for which we are getting information.
18013 Expression* iface_;
18014 // What information we want.
18015 Interface_info iface_info_;
18016 };
18017
18018 // Return the type of the interface info.
18019
18020 Type*
18021 Interface_info_expression::do_type()
18022 {
18023 switch (this->iface_info_)
18024 {
18025 case INTERFACE_INFO_METHODS:
18026 {
18027 typedef Unordered_map(Interface_type*, Type*) Hashtable;
18028 static Hashtable result_types;
18029
18030 Interface_type* itype = this->iface_->type()->interface_type();
18031
18032 Hashtable::const_iterator pr = result_types.find(itype);
18033 if (pr != result_types.end())
18034 return pr->second;
18035
18036 Type* pdt = Type::make_type_descriptor_ptr_type();
18037 if (itype->is_empty())
18038 {
18039 result_types[itype] = pdt;
18040 return pdt;
18041 }
18042
18043 Location loc = this->location();
18044 Struct_field_list* sfl = new Struct_field_list();
18045 sfl->push_back(
18046 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
18047
18048 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
18049 p != itype->methods()->end();
18050 ++p)
18051 {
18052 Function_type* ft = p->type()->function_type();
18053 go_assert(ft->receiver() == NULL);
18054
18055 const Typed_identifier_list* params = ft->parameters();
18056 Typed_identifier_list* mparams = new Typed_identifier_list();
18057 if (params != NULL)
18058 mparams->reserve(params->size() + 1);
18059 Type* vt = Type::make_pointer_type(Type::make_void_type());
18060 mparams->push_back(Typed_identifier("", vt, ft->location()));
18061 if (params != NULL)
18062 {
18063 for (Typed_identifier_list::const_iterator pp = params->begin();
18064 pp != params->end();
18065 ++pp)
18066 mparams->push_back(*pp);
18067 }
18068
18069 Typed_identifier_list* mresults = (ft->results() == NULL
18070 ? NULL
18071 : ft->results()->copy());
18072 Backend_function_type* mft =
18073 Type::make_backend_function_type(NULL, mparams, mresults,
18074 ft->location());
18075
18076 std::string fname = Gogo::unpack_hidden_name(p->name());
18077 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
18078 }
18079
18080 Struct_type* st = Type::make_struct_type(sfl, loc);
18081 st->set_is_struct_incomparable();
18082 Pointer_type *pt = Type::make_pointer_type(st);
18083 result_types[itype] = pt;
18084 return pt;
18085 }
18086 case INTERFACE_INFO_OBJECT:
18087 return Type::make_pointer_type(Type::make_void_type());
18088 default:
18089 go_unreachable();
18090 }
18091 }
18092
18093 // Return the backend representation for interface information.
18094
18095 Bexpression*
18096 Interface_info_expression::do_get_backend(Translate_context* context)
18097 {
18098 Gogo* gogo = context->gogo();
18099 Bexpression* biface = this->iface_->get_backend(context);
18100 switch (this->iface_info_)
18101 {
18102 case INTERFACE_INFO_METHODS:
18103 case INTERFACE_INFO_OBJECT:
18104 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
18105 this->location());
18106 break;
18107 default:
18108 go_unreachable();
18109 }
18110 }
18111
18112 // Dump ast representation for an interface info expression.
18113
18114 void
18115 Interface_info_expression::do_dump_expression(
18116 Ast_dump_context* ast_dump_context) const
18117 {
18118 bool is_empty = this->iface_->type()->interface_type()->is_empty();
18119 ast_dump_context->ostream() << "interfaceinfo(";
18120 this->iface_->dump_expression(ast_dump_context);
18121 ast_dump_context->ostream() << ",";
18122 ast_dump_context->ostream() <<
18123 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
18124 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
18125 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
18126 : "unknown");
18127 ast_dump_context->ostream() << ")";
18128 }
18129
18130 // Make an interface info expression.
18131
18132 Expression*
18133 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
18134 Location location)
18135 {
18136 return new Interface_info_expression(iface, iface_info, location);
18137 }
18138
18139 // An expression that represents an interface value. The first field is either
18140 // a type descriptor for an empty interface or a pointer to the interface method
18141 // table for a non-empty interface. The second field is always the object.
18142
18143 class Interface_value_expression : public Expression
18144 {
18145 public:
18146 Interface_value_expression(Type* type, Expression* first_field,
18147 Expression* obj, Location location)
18148 : Expression(EXPRESSION_INTERFACE_VALUE, location),
18149 type_(type), first_field_(first_field), obj_(obj)
18150 { }
18151
18152 protected:
18153 int
18154 do_traverse(Traverse*);
18155
18156 Type*
18157 do_type()
18158 { return this->type_; }
18159
18160 void
18161 do_determine_type(const Type_context*)
18162 { go_unreachable(); }
18163
18164 Expression*
18165 do_copy()
18166 {
18167 return new Interface_value_expression(this->type_->copy_expressions(),
18168 this->first_field_->copy(),
18169 this->obj_->copy(), this->location());
18170 }
18171
18172 Bexpression*
18173 do_get_backend(Translate_context* context);
18174
18175 void
18176 do_dump_expression(Ast_dump_context*) const;
18177
18178 private:
18179 // The type of the interface value.
18180 Type* type_;
18181 // The first field of the interface (either a type descriptor or a pointer
18182 // to the method table.
18183 Expression* first_field_;
18184 // The underlying object of the interface.
18185 Expression* obj_;
18186 };
18187
18188 int
18189 Interface_value_expression::do_traverse(Traverse* traverse)
18190 {
18191 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
18192 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
18193 return TRAVERSE_EXIT;
18194 return TRAVERSE_CONTINUE;
18195 }
18196
18197 Bexpression*
18198 Interface_value_expression::do_get_backend(Translate_context* context)
18199 {
18200 std::vector<Bexpression*> vals(2);
18201 vals[0] = this->first_field_->get_backend(context);
18202 vals[1] = this->obj_->get_backend(context);
18203
18204 Gogo* gogo = context->gogo();
18205 Btype* btype = this->type_->get_backend(gogo);
18206 return gogo->backend()->constructor_expression(btype, vals, this->location());
18207 }
18208
18209 void
18210 Interface_value_expression::do_dump_expression(
18211 Ast_dump_context* ast_dump_context) const
18212 {
18213 ast_dump_context->ostream() << "interfacevalue(";
18214 ast_dump_context->ostream() <<
18215 (this->type_->interface_type()->is_empty()
18216 ? "type_descriptor: "
18217 : "methods: ");
18218 this->first_field_->dump_expression(ast_dump_context);
18219 ast_dump_context->ostream() << ", object: ";
18220 this->obj_->dump_expression(ast_dump_context);
18221 ast_dump_context->ostream() << ")";
18222 }
18223
18224 Expression*
18225 Expression::make_interface_value(Type* type, Expression* first_value,
18226 Expression* object, Location location)
18227 {
18228 return new Interface_value_expression(type, first_value, object, location);
18229 }
18230
18231 // An interface method table for a pair of types: an interface type and a type
18232 // that implements that interface.
18233
18234 class Interface_mtable_expression : public Expression
18235 {
18236 public:
18237 Interface_mtable_expression(Interface_type* itype, Type* type,
18238 bool is_pointer, Location location)
18239 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
18240 itype_(itype), type_(type), is_pointer_(is_pointer),
18241 method_table_type_(NULL), bvar_(NULL)
18242 { }
18243
18244 protected:
18245 int
18246 do_traverse(Traverse*);
18247
18248 Type*
18249 do_type();
18250
18251 bool
18252 do_is_static_initializer() const
18253 { return true; }
18254
18255 void
18256 do_determine_type(const Type_context*)
18257 { go_unreachable(); }
18258
18259 Expression*
18260 do_copy()
18261 {
18262 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
18263 return new Interface_mtable_expression(itype,
18264 this->type_->copy_expressions(),
18265 this->is_pointer_, this->location());
18266 }
18267
18268 bool
18269 do_is_addressable() const
18270 { return true; }
18271
18272 Bexpression*
18273 do_get_backend(Translate_context* context);
18274
18275 void
18276 do_dump_expression(Ast_dump_context*) const;
18277
18278 private:
18279 // The interface type for which the methods are defined.
18280 Interface_type* itype_;
18281 // The type to construct the interface method table for.
18282 Type* type_;
18283 // Whether this table contains the method set for the receiver type or the
18284 // pointer receiver type.
18285 bool is_pointer_;
18286 // The type of the method table.
18287 Type* method_table_type_;
18288 // The backend variable that refers to the interface method table.
18289 Bvariable* bvar_;
18290 };
18291
18292 int
18293 Interface_mtable_expression::do_traverse(Traverse* traverse)
18294 {
18295 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
18296 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18297 return TRAVERSE_EXIT;
18298 return TRAVERSE_CONTINUE;
18299 }
18300
18301 Type*
18302 Interface_mtable_expression::do_type()
18303 {
18304 if (this->method_table_type_ != NULL)
18305 return this->method_table_type_;
18306
18307 const Typed_identifier_list* interface_methods = this->itype_->methods();
18308 go_assert(!interface_methods->empty());
18309
18310 Struct_field_list* sfl = new Struct_field_list;
18311 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
18312 this->location());
18313 sfl->push_back(Struct_field(tid));
18314 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
18315 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18316 p != interface_methods->end();
18317 ++p)
18318 {
18319 // We want C function pointers here, not func descriptors; model
18320 // using void* pointers.
18321 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
18322 sfl->push_back(Struct_field(method));
18323 }
18324 Struct_type* st = Type::make_struct_type(sfl, this->location());
18325 st->set_is_struct_incomparable();
18326 this->method_table_type_ = st;
18327 return this->method_table_type_;
18328 }
18329
18330 Bexpression*
18331 Interface_mtable_expression::do_get_backend(Translate_context* context)
18332 {
18333 Gogo* gogo = context->gogo();
18334 Location loc = Linemap::predeclared_location();
18335 if (this->bvar_ != NULL)
18336 return gogo->backend()->var_expression(this->bvar_, this->location());
18337
18338 const Typed_identifier_list* interface_methods = this->itype_->methods();
18339 go_assert(!interface_methods->empty());
18340
18341 std::string mangled_name =
18342 gogo->interface_method_table_name(this->itype_, this->type_,
18343 this->is_pointer_);
18344
18345 // Set is_public if we are converting a named type to an interface
18346 // type that is defined in the same package as the named type, and
18347 // the interface has hidden methods. In that case the interface
18348 // method table will be defined by the package that defines the
18349 // types.
18350 bool is_public = false;
18351 if (this->type_->named_type() != NULL
18352 && (this->type_->named_type()->named_object()->package()
18353 == this->itype_->package()))
18354 {
18355 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18356 p != interface_methods->end();
18357 ++p)
18358 {
18359 if (Gogo::is_hidden_name(p->name()))
18360 {
18361 is_public = true;
18362 break;
18363 }
18364 }
18365 }
18366
18367 if (is_public
18368 && this->type_->named_type()->named_object()->package() != NULL)
18369 {
18370 // The interface conversion table is defined elsewhere.
18371 Btype* btype = this->type()->get_backend(gogo);
18372 this->bvar_ =
18373 gogo->backend()->immutable_struct_reference(mangled_name, "",
18374 btype, loc);
18375 return gogo->backend()->var_expression(this->bvar_, this->location());
18376 }
18377
18378 // The first element is the type descriptor.
18379 Type* td_type;
18380 if (!this->is_pointer_)
18381 td_type = this->type_;
18382 else
18383 td_type = Type::make_pointer_type(this->type_);
18384
18385 std::vector<Backend::Btyped_identifier> bstructfields;
18386
18387 // Build an interface method table for a type: a type descriptor followed by a
18388 // list of function pointers, one for each interface method. This is used for
18389 // interfaces.
18390 Expression_list* svals = new Expression_list();
18391 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
18392 svals->push_back(tdescriptor);
18393
18394 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
18395 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
18396 bstructfields.push_back(btd);
18397
18398 Named_type* nt = this->type_->named_type();
18399 Struct_type* st = this->type_->struct_type();
18400 go_assert(nt != NULL || st != NULL);
18401
18402 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18403 p != interface_methods->end();
18404 ++p)
18405 {
18406 bool is_ambiguous;
18407 Method* m;
18408 if (nt != NULL)
18409 m = nt->method_function(p->name(), &is_ambiguous);
18410 else
18411 m = st->method_function(p->name(), &is_ambiguous);
18412 go_assert(m != NULL);
18413 Named_object* no =
18414 (this->is_pointer_
18415 && this->type_->is_direct_iface_type()
18416 && m->is_value_method()
18417 ? m->iface_stub_object()
18418 : m->named_object());
18419
18420 go_assert(no->is_function() || no->is_function_declaration());
18421
18422 Function_type* fcn_type = (no->is_function()
18423 ? no->func_value()->type()
18424 : no->func_declaration_value()->type());
18425 Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
18426 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
18427 bstructfields.push_back(bmtype);
18428
18429 svals->push_back(Expression::make_func_code_reference(no, loc));
18430 }
18431
18432 Btype *btype = gogo->backend()->struct_type(bstructfields);
18433 std::vector<Bexpression*> ctor_bexprs;
18434 for (Expression_list::const_iterator pe = svals->begin();
18435 pe != svals->end();
18436 ++pe)
18437 {
18438 ctor_bexprs.push_back((*pe)->get_backend(context));
18439 }
18440 Bexpression* ctor =
18441 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
18442
18443 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, "", false,
18444 !is_public, btype, loc);
18445 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
18446 !is_public, btype, loc, ctor);
18447 return gogo->backend()->var_expression(this->bvar_, loc);
18448 }
18449
18450 void
18451 Interface_mtable_expression::do_dump_expression(
18452 Ast_dump_context* ast_dump_context) const
18453 {
18454 ast_dump_context->ostream() << "__go_"
18455 << (this->is_pointer_ ? "pimt__" : "imt_");
18456 ast_dump_context->dump_type(this->itype_);
18457 ast_dump_context->ostream() << "__";
18458 ast_dump_context->dump_type(this->type_);
18459 }
18460
18461 Expression*
18462 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
18463 bool is_pointer, Location location)
18464 {
18465 return new Interface_mtable_expression(itype, type, is_pointer, location);
18466 }
18467
18468 // An expression which evaluates to the offset of a field within a
18469 // struct. This, like Type_info_expression, q.v., is only used to
18470 // initialize fields of a type descriptor.
18471
18472 class Struct_field_offset_expression : public Expression
18473 {
18474 public:
18475 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
18476 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
18477 Linemap::predeclared_location()),
18478 type_(type), field_(field)
18479 { }
18480
18481 protected:
18482 bool
18483 do_is_static_initializer() const
18484 { return true; }
18485
18486 Type*
18487 do_type()
18488 { return Type::lookup_integer_type("uintptr"); }
18489
18490 void
18491 do_determine_type(const Type_context*)
18492 { }
18493
18494 Expression*
18495 do_copy()
18496 { return this; }
18497
18498 Bexpression*
18499 do_get_backend(Translate_context* context);
18500
18501 void
18502 do_dump_expression(Ast_dump_context*) const;
18503
18504 private:
18505 // The type of the struct.
18506 Struct_type* type_;
18507 // The field.
18508 const Struct_field* field_;
18509 };
18510
18511 // Return the backend representation for a struct field offset.
18512
18513 Bexpression*
18514 Struct_field_offset_expression::do_get_backend(Translate_context* context)
18515 {
18516 const Struct_field_list* fields = this->type_->fields();
18517 Struct_field_list::const_iterator p;
18518 unsigned i = 0;
18519 for (p = fields->begin();
18520 p != fields->end();
18521 ++p, ++i)
18522 if (&*p == this->field_)
18523 break;
18524 go_assert(&*p == this->field_);
18525
18526 Gogo* gogo = context->gogo();
18527 Btype* btype = this->type_->get_backend(gogo);
18528
18529 int64_t offset = gogo->backend()->type_field_offset(btype, i);
18530 Type* uptr_type = Type::lookup_integer_type("uintptr");
18531 Expression* ret =
18532 Expression::make_integer_int64(offset, uptr_type,
18533 Linemap::predeclared_location());
18534 return ret->get_backend(context);
18535 }
18536
18537 // Dump ast representation for a struct field offset expression.
18538
18539 void
18540 Struct_field_offset_expression::do_dump_expression(
18541 Ast_dump_context* ast_dump_context) const
18542 {
18543 ast_dump_context->ostream() << "unsafe.Offsetof(";
18544 ast_dump_context->dump_type(this->type_);
18545 ast_dump_context->ostream() << '.';
18546 ast_dump_context->ostream() <<
18547 Gogo::message_name(this->field_->field_name());
18548 ast_dump_context->ostream() << ")";
18549 }
18550
18551 // Make an expression for a struct field offset.
18552
18553 Expression*
18554 Expression::make_struct_field_offset(Struct_type* type,
18555 const Struct_field* field)
18556 {
18557 return new Struct_field_offset_expression(type, field);
18558 }
18559
18560 // An expression which evaluates to the address of an unnamed label.
18561
18562 class Label_addr_expression : public Expression
18563 {
18564 public:
18565 Label_addr_expression(Label* label, Location location)
18566 : Expression(EXPRESSION_LABEL_ADDR, location),
18567 label_(label)
18568 { }
18569
18570 protected:
18571 Type*
18572 do_type()
18573 { return Type::make_pointer_type(Type::make_void_type()); }
18574
18575 void
18576 do_determine_type(const Type_context*)
18577 { }
18578
18579 Expression*
18580 do_copy()
18581 { return new Label_addr_expression(this->label_, this->location()); }
18582
18583 Bexpression*
18584 do_get_backend(Translate_context* context)
18585 { return this->label_->get_addr(context, this->location()); }
18586
18587 void
18588 do_dump_expression(Ast_dump_context* ast_dump_context) const
18589 { ast_dump_context->ostream() << this->label_->name(); }
18590
18591 private:
18592 // The label whose address we are taking.
18593 Label* label_;
18594 };
18595
18596 // Make an expression for the address of an unnamed label.
18597
18598 Expression*
18599 Expression::make_label_addr(Label* label, Location location)
18600 {
18601 return new Label_addr_expression(label, location);
18602 }
18603
18604 // Class Conditional_expression.
18605
18606 // Traversal.
18607
18608 int
18609 Conditional_expression::do_traverse(Traverse* traverse)
18610 {
18611 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
18612 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
18613 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
18614 return TRAVERSE_EXIT;
18615 return TRAVERSE_CONTINUE;
18616 }
18617
18618 // Return the type of the conditional expression.
18619
18620 Type*
18621 Conditional_expression::do_type()
18622 {
18623 Type* result_type = Type::make_void_type();
18624 if (Type::are_identical(this->then_->type(), this->else_->type(),
18625 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
18626 NULL))
18627 result_type = this->then_->type();
18628 else if (this->then_->is_nil_expression()
18629 || this->else_->is_nil_expression())
18630 result_type = (!this->then_->is_nil_expression()
18631 ? this->then_->type()
18632 : this->else_->type());
18633 return result_type;
18634 }
18635
18636 // Determine type for a conditional expression.
18637
18638 void
18639 Conditional_expression::do_determine_type(const Type_context* context)
18640 {
18641 this->cond_->determine_type_no_context();
18642 this->then_->determine_type(context);
18643 this->else_->determine_type(context);
18644 }
18645
18646 // Get the backend representation of a conditional expression.
18647
18648 Bexpression*
18649 Conditional_expression::do_get_backend(Translate_context* context)
18650 {
18651 Gogo* gogo = context->gogo();
18652 Btype* result_btype = this->type()->get_backend(gogo);
18653 Bexpression* cond = this->cond_->get_backend(context);
18654 Bexpression* then = this->then_->get_backend(context);
18655 Bexpression* belse = this->else_->get_backend(context);
18656 Bfunction* bfn = context->function()->func_value()->get_decl();
18657 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
18658 belse, this->location());
18659 }
18660
18661 // Dump ast representation of a conditional expression.
18662
18663 void
18664 Conditional_expression::do_dump_expression(
18665 Ast_dump_context* ast_dump_context) const
18666 {
18667 ast_dump_context->ostream() << "(";
18668 ast_dump_context->dump_expression(this->cond_);
18669 ast_dump_context->ostream() << " ? ";
18670 ast_dump_context->dump_expression(this->then_);
18671 ast_dump_context->ostream() << " : ";
18672 ast_dump_context->dump_expression(this->else_);
18673 ast_dump_context->ostream() << ") ";
18674 }
18675
18676 // Make a conditional expression.
18677
18678 Expression*
18679 Expression::make_conditional(Expression* cond, Expression* then,
18680 Expression* else_expr, Location location)
18681 {
18682 return new Conditional_expression(cond, then, else_expr, location);
18683 }
18684
18685 // Class Compound_expression.
18686
18687 // Traversal.
18688
18689 int
18690 Compound_expression::do_traverse(Traverse* traverse)
18691 {
18692 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
18693 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
18694 return TRAVERSE_EXIT;
18695 return TRAVERSE_CONTINUE;
18696 }
18697
18698 // Return the type of the compound expression.
18699
18700 Type*
18701 Compound_expression::do_type()
18702 {
18703 return this->expr_->type();
18704 }
18705
18706 // Determine type for a compound expression.
18707
18708 void
18709 Compound_expression::do_determine_type(const Type_context* context)
18710 {
18711 this->init_->determine_type_no_context();
18712 this->expr_->determine_type(context);
18713 }
18714
18715 // Get the backend representation of a compound expression.
18716
18717 Bexpression*
18718 Compound_expression::do_get_backend(Translate_context* context)
18719 {
18720 Gogo* gogo = context->gogo();
18721 Bexpression* binit = this->init_->get_backend(context);
18722 Bfunction* bfunction = context->function()->func_value()->get_decl();
18723 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
18724 binit);
18725 Bexpression* bexpr = this->expr_->get_backend(context);
18726 return gogo->backend()->compound_expression(init_stmt, bexpr,
18727 this->location());
18728 }
18729
18730 // Dump ast representation of a conditional expression.
18731
18732 void
18733 Compound_expression::do_dump_expression(
18734 Ast_dump_context* ast_dump_context) const
18735 {
18736 ast_dump_context->ostream() << "(";
18737 ast_dump_context->dump_expression(this->init_);
18738 ast_dump_context->ostream() << ",";
18739 ast_dump_context->dump_expression(this->expr_);
18740 ast_dump_context->ostream() << ") ";
18741 }
18742
18743 // Make a compound expression.
18744
18745 Expression*
18746 Expression::make_compound(Expression* init, Expression* expr, Location location)
18747 {
18748 return new Compound_expression(init, expr, location);
18749 }
18750
18751 // Class Backend_expression.
18752
18753 int
18754 Backend_expression::do_traverse(Traverse*)
18755 {
18756 return TRAVERSE_CONTINUE;
18757 }
18758
18759 Expression*
18760 Backend_expression::do_copy()
18761 {
18762 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
18763 this->location());
18764 }
18765
18766 void
18767 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
18768 {
18769 ast_dump_context->ostream() << "backend_expression<";
18770 ast_dump_context->dump_type(this->type_);
18771 ast_dump_context->ostream() << ">";
18772 }
18773
18774 Expression*
18775 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
18776 {
18777 return new Backend_expression(bexpr, type, location);
18778 }
18779
18780 // Import an expression. This comes at the end in order to see the
18781 // various class definitions.
18782
18783 Expression*
18784 Expression::import_expression(Import_expression* imp, Location loc)
18785 {
18786 Expression* expr = Expression::import_expression_without_suffix(imp, loc);
18787 while (true)
18788 {
18789 if (imp->match_c_string("("))
18790 {
18791 imp->advance(1);
18792 Expression_list* args = new Expression_list();
18793 bool is_varargs = false;
18794 while (!imp->match_c_string(")"))
18795 {
18796 Expression* arg = Expression::import_expression(imp, loc);
18797 if (arg->is_error_expression())
18798 return arg;
18799 args->push_back(arg);
18800 if (imp->match_c_string(")"))
18801 break;
18802 else if (imp->match_c_string("...)"))
18803 {
18804 imp->advance(3);
18805 is_varargs = true;
18806 break;
18807 }
18808 imp->require_c_string(", ");
18809 }
18810 imp->require_c_string(")");
18811 expr = Expression::make_call(expr, args, is_varargs, loc);
18812 expr->call_expression()->set_varargs_are_lowered();
18813 }
18814 else if (imp->match_c_string("["))
18815 {
18816 imp->advance(1);
18817 Expression* start = Expression::import_expression(imp, loc);
18818 Expression* end = NULL;
18819 Expression* cap = NULL;
18820 if (imp->match_c_string(":"))
18821 {
18822 imp->advance(1);
18823 int c = imp->peek_char();
18824 if (c == ':' || c == ']')
18825 end = Expression::make_nil(loc);
18826 else
18827 end = Expression::import_expression(imp, loc);
18828 if (imp->match_c_string(":"))
18829 {
18830 imp->advance(1);
18831 cap = Expression::import_expression(imp, loc);
18832 }
18833 }
18834 imp->require_c_string("]");
18835 expr = Expression::make_index(expr, start, end, cap, loc);
18836 }
18837 else
18838 break;
18839 }
18840
18841 return expr;
18842 }
18843
18844 // Import an expression without considering a suffix (function
18845 // arguments, index operations, etc.).
18846
18847 Expression*
18848 Expression::import_expression_without_suffix(Import_expression* imp,
18849 Location loc)
18850 {
18851 int c = imp->peek_char();
18852 if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
18853 return Unary_expression::do_import(imp, loc);
18854 else if (c == '(')
18855 return Binary_expression::do_import(imp, loc);
18856 else if (imp->match_c_string("$true")
18857 || imp->match_c_string("$false")
18858 || (imp->version() < EXPORT_FORMAT_V3
18859 && (imp->match_c_string("true")
18860 || imp->match_c_string("false"))))
18861 return Boolean_expression::do_import(imp, loc);
18862 else if (c == '"')
18863 return String_expression::do_import(imp, loc);
18864 else if (c == '-' || (c >= '0' && c <= '9'))
18865 {
18866 // This handles integers, floats and complex constants.
18867 return Integer_expression::do_import(imp, loc);
18868 }
18869 else if (imp->match_c_string("<-"))
18870 return Receive_expression::do_import(imp, loc);
18871 else if (imp->match_c_string("$nil")
18872 || (imp->version() < EXPORT_FORMAT_V3
18873 && imp->match_c_string("nil")))
18874 return Nil_expression::do_import(imp, loc);
18875 else if (imp->match_c_string("$convert")
18876 || (imp->version() < EXPORT_FORMAT_V3
18877 && imp->match_c_string("convert")))
18878 return Type_conversion_expression::do_import(imp, loc);
18879
18880 Import_function_body* ifb = imp->ifb();
18881 if (ifb == NULL)
18882 {
18883 go_error_at(imp->location(), "import error: expected expression");
18884 return Expression::make_error(loc);
18885 }
18886 if (ifb->saw_error())
18887 return Expression::make_error(loc);
18888
18889 if (ifb->match_c_string("$t"))
18890 return Temporary_reference_expression::do_import(ifb, loc);
18891
18892 return Expression::import_identifier(ifb, loc);
18893 }
18894
18895 // Import an identifier in an expression. This is a reference to a
18896 // variable or function.
18897
18898 Expression*
18899 Expression::import_identifier(Import_function_body* ifb, Location loc)
18900 {
18901 std::string id;
18902 Package* pkg;
18903 bool is_exported;
18904 if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
18905 {
18906 if (!ifb->saw_error())
18907 go_error_at(ifb->location(),
18908 "import error for %qs: bad qualified identifier at %lu",
18909 ifb->name().c_str(),
18910 static_cast<unsigned long>(ifb->off()));
18911 ifb->set_saw_error();
18912 return Expression::make_error(loc);
18913 }
18914
18915 Named_object* no = NULL;
18916 if (pkg == NULL && is_exported)
18917 no = ifb->block()->bindings()->lookup(id);
18918 if (no == NULL)
18919 {
18920 const Package* ipkg = pkg;
18921 if (ipkg == NULL)
18922 ipkg = ifb->function()->package();
18923 if (!is_exported)
18924 id = '.' + ipkg->pkgpath() + '.' + id;
18925 no = ipkg->bindings()->lookup(id);
18926 }
18927 if (no == NULL)
18928 no = ifb->gogo()->lookup_global(id.c_str());
18929
18930 if (no == NULL)
18931 {
18932 if (!ifb->saw_error())
18933 go_error_at(ifb->location(),
18934 "import error for %qs: lookup of %qs failed",
18935 ifb->name().c_str(), id.c_str());
18936 ifb->set_saw_error();
18937 return Expression::make_error(loc);
18938 }
18939
18940 if (no->is_variable() || no->is_result_variable())
18941 return Expression::make_var_reference(no, loc);
18942 else if (no->is_function() || no->is_function_declaration())
18943 return Expression::make_func_reference(no, NULL, loc);
18944 else
18945 {
18946 if (!ifb->saw_error())
18947 go_error_at(ifb->location(),
18948 ("import error for %qs: "
18949 "unexpected type of identifier %qs (%d)"),
18950 ifb->name().c_str(),
18951 id.c_str(), no->classification());
18952 ifb->set_saw_error();
18953 return Expression::make_error(loc);
18954 }
18955 }
18956
18957 // Class Expression_list.
18958
18959 // Traverse the list.
18960
18961 int
18962 Expression_list::traverse(Traverse* traverse)
18963 {
18964 for (Expression_list::iterator p = this->begin();
18965 p != this->end();
18966 ++p)
18967 {
18968 if (*p != NULL)
18969 {
18970 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
18971 return TRAVERSE_EXIT;
18972 }
18973 }
18974 return TRAVERSE_CONTINUE;
18975 }
18976
18977 // Copy the list.
18978
18979 Expression_list*
18980 Expression_list::copy()
18981 {
18982 Expression_list* ret = new Expression_list();
18983 for (Expression_list::iterator p = this->begin();
18984 p != this->end();
18985 ++p)
18986 {
18987 if (*p == NULL)
18988 ret->push_back(NULL);
18989 else
18990 ret->push_back((*p)->copy());
18991 }
18992 return ret;
18993 }
18994
18995 // Return whether an expression list has an error expression.
18996
18997 bool
18998 Expression_list::contains_error() const
18999 {
19000 for (Expression_list::const_iterator p = this->begin();
19001 p != this->end();
19002 ++p)
19003 if (*p != NULL && (*p)->is_error_expression())
19004 return true;
19005 return false;
19006 }
19007
19008 // Class Numeric_constant.
19009
19010 // Destructor.
19011
19012 Numeric_constant::~Numeric_constant()
19013 {
19014 this->clear();
19015 }
19016
19017 // Copy constructor.
19018
19019 Numeric_constant::Numeric_constant(const Numeric_constant& a)
19020 : classification_(a.classification_), type_(a.type_)
19021 {
19022 switch (a.classification_)
19023 {
19024 case NC_INVALID:
19025 break;
19026 case NC_INT:
19027 case NC_RUNE:
19028 mpz_init_set(this->u_.int_val, a.u_.int_val);
19029 break;
19030 case NC_FLOAT:
19031 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19032 break;
19033 case NC_COMPLEX:
19034 mpc_init2(this->u_.complex_val, mpc_precision);
19035 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19036 break;
19037 default:
19038 go_unreachable();
19039 }
19040 }
19041
19042 // Assignment operator.
19043
19044 Numeric_constant&
19045 Numeric_constant::operator=(const Numeric_constant& a)
19046 {
19047 this->clear();
19048 this->classification_ = a.classification_;
19049 this->type_ = a.type_;
19050 switch (a.classification_)
19051 {
19052 case NC_INVALID:
19053 break;
19054 case NC_INT:
19055 case NC_RUNE:
19056 mpz_init_set(this->u_.int_val, a.u_.int_val);
19057 break;
19058 case NC_FLOAT:
19059 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19060 break;
19061 case NC_COMPLEX:
19062 mpc_init2(this->u_.complex_val, mpc_precision);
19063 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19064 break;
19065 default:
19066 go_unreachable();
19067 }
19068 return *this;
19069 }
19070
19071 // Check equality with another numeric constant.
19072
19073 bool
19074 Numeric_constant::equals(const Numeric_constant& a) const
19075 {
19076 if (this->classification_ != a.classification_)
19077 return false;
19078
19079 if (this->type_ != NULL && a.type_ != NULL
19080 && !Type::are_identical(this->type_, a.type_,
19081 Type::COMPARE_ALIASES, NULL))
19082 return false;
19083
19084 switch (a.classification_)
19085 {
19086 case NC_INVALID:
19087 break;
19088 case NC_INT:
19089 case NC_RUNE:
19090 return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
19091 case NC_FLOAT:
19092 return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
19093 case NC_COMPLEX:
19094 return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
19095 default:
19096 go_unreachable();
19097 }
19098 return false;
19099 }
19100
19101 // Clear the contents.
19102
19103 void
19104 Numeric_constant::clear()
19105 {
19106 switch (this->classification_)
19107 {
19108 case NC_INVALID:
19109 break;
19110 case NC_INT:
19111 case NC_RUNE:
19112 mpz_clear(this->u_.int_val);
19113 break;
19114 case NC_FLOAT:
19115 mpfr_clear(this->u_.float_val);
19116 break;
19117 case NC_COMPLEX:
19118 mpc_clear(this->u_.complex_val);
19119 break;
19120 default:
19121 go_unreachable();
19122 }
19123 this->classification_ = NC_INVALID;
19124 }
19125
19126 // Set to an unsigned long value.
19127
19128 void
19129 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
19130 {
19131 this->clear();
19132 this->classification_ = NC_INT;
19133 this->type_ = type;
19134 mpz_init_set_ui(this->u_.int_val, val);
19135 }
19136
19137 // Set to an integer value.
19138
19139 void
19140 Numeric_constant::set_int(Type* type, const mpz_t val)
19141 {
19142 this->clear();
19143 this->classification_ = NC_INT;
19144 this->type_ = type;
19145 mpz_init_set(this->u_.int_val, val);
19146 }
19147
19148 // Set to a rune value.
19149
19150 void
19151 Numeric_constant::set_rune(Type* type, const mpz_t val)
19152 {
19153 this->clear();
19154 this->classification_ = NC_RUNE;
19155 this->type_ = type;
19156 mpz_init_set(this->u_.int_val, val);
19157 }
19158
19159 // Set to a floating point value.
19160
19161 void
19162 Numeric_constant::set_float(Type* type, const mpfr_t val)
19163 {
19164 this->clear();
19165 this->classification_ = NC_FLOAT;
19166 this->type_ = type;
19167
19168 // Numeric constants do not have negative zero values, so remove
19169 // them here. They also don't have infinity or NaN values, but we
19170 // should never see them here.
19171 int bits = 0;
19172 if (type != NULL
19173 && type->float_type() != NULL
19174 && !type->float_type()->is_abstract())
19175 bits = type->float_type()->bits();
19176 if (Numeric_constant::is_float_neg_zero(val, bits))
19177 mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
19178 else
19179 mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
19180 }
19181
19182 // Set to a complex value.
19183
19184 void
19185 Numeric_constant::set_complex(Type* type, const mpc_t val)
19186 {
19187 this->clear();
19188 this->classification_ = NC_COMPLEX;
19189 this->type_ = type;
19190
19191 // Avoid negative zero as in set_float.
19192 int bits = 0;
19193 if (type != NULL
19194 && type->complex_type() != NULL
19195 && !type->complex_type()->is_abstract())
19196 bits = type->complex_type()->bits() / 2;
19197
19198 mpfr_t real;
19199 mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
19200 if (Numeric_constant::is_float_neg_zero(real, bits))
19201 mpfr_set_ui(real, 0, MPFR_RNDN);
19202
19203 mpfr_t imag;
19204 mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
19205 if (Numeric_constant::is_float_neg_zero(imag, bits))
19206 mpfr_set_ui(imag, 0, MPFR_RNDN);
19207
19208 mpc_init2(this->u_.complex_val, mpc_precision);
19209 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
19210
19211 mpfr_clear(real);
19212 mpfr_clear(imag);
19213 }
19214
19215 // Return whether VAL, at a precision of BITS, is a negative zero.
19216 // BITS may be zero in which case it is ignored.
19217
19218 bool
19219 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
19220 {
19221 if (!mpfr_signbit(val))
19222 return false;
19223 if (mpfr_zero_p(val))
19224 return true;
19225 mpfr_exp_t min_exp;
19226 switch (bits)
19227 {
19228 case 0:
19229 return false;
19230 case 32:
19231 // In a denormalized float32 the exponent is -126, and there are
19232 // 24 bits of which at least the last must be 1, so the smallest
19233 // representable non-zero exponent is -126 - (24 - 1) == -149.
19234 min_exp = -149;
19235 break;
19236 case 64:
19237 // Minimum exponent is -1022, there are 53 bits.
19238 min_exp = -1074;
19239 break;
19240 default:
19241 go_unreachable();
19242 }
19243 return mpfr_get_exp(val) < min_exp;
19244 }
19245
19246 // Get an int value.
19247
19248 void
19249 Numeric_constant::get_int(mpz_t* val) const
19250 {
19251 go_assert(this->is_int());
19252 mpz_init_set(*val, this->u_.int_val);
19253 }
19254
19255 // Get a rune value.
19256
19257 void
19258 Numeric_constant::get_rune(mpz_t* val) const
19259 {
19260 go_assert(this->is_rune());
19261 mpz_init_set(*val, this->u_.int_val);
19262 }
19263
19264 // Get a floating point value.
19265
19266 void
19267 Numeric_constant::get_float(mpfr_t* val) const
19268 {
19269 go_assert(this->is_float());
19270 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19271 }
19272
19273 // Get a complex value.
19274
19275 void
19276 Numeric_constant::get_complex(mpc_t* val) const
19277 {
19278 go_assert(this->is_complex());
19279 mpc_init2(*val, mpc_precision);
19280 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19281 }
19282
19283 // Express value as unsigned long if possible.
19284
19285 Numeric_constant::To_unsigned_long
19286 Numeric_constant::to_unsigned_long(unsigned long* val) const
19287 {
19288 switch (this->classification_)
19289 {
19290 case NC_INT:
19291 case NC_RUNE:
19292 return this->mpz_to_unsigned_long(this->u_.int_val, val);
19293 case NC_FLOAT:
19294 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
19295 case NC_COMPLEX:
19296 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19297 return NC_UL_NOTINT;
19298 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
19299 val);
19300 default:
19301 go_unreachable();
19302 }
19303 }
19304
19305 // Express integer value as unsigned long if possible.
19306
19307 Numeric_constant::To_unsigned_long
19308 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
19309 unsigned long *val) const
19310 {
19311 if (mpz_sgn(ival) < 0)
19312 return NC_UL_NEGATIVE;
19313 unsigned long ui = mpz_get_ui(ival);
19314 if (mpz_cmp_ui(ival, ui) != 0)
19315 return NC_UL_BIG;
19316 *val = ui;
19317 return NC_UL_VALID;
19318 }
19319
19320 // Express floating point value as unsigned long if possible.
19321
19322 Numeric_constant::To_unsigned_long
19323 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
19324 unsigned long *val) const
19325 {
19326 if (!mpfr_integer_p(fval))
19327 return NC_UL_NOTINT;
19328 mpz_t ival;
19329 mpz_init(ival);
19330 mpfr_get_z(ival, fval, MPFR_RNDN);
19331 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
19332 mpz_clear(ival);
19333 return ret;
19334 }
19335
19336 // Express value as memory size if possible.
19337
19338 bool
19339 Numeric_constant::to_memory_size(int64_t* val) const
19340 {
19341 switch (this->classification_)
19342 {
19343 case NC_INT:
19344 case NC_RUNE:
19345 return this->mpz_to_memory_size(this->u_.int_val, val);
19346 case NC_FLOAT:
19347 return this->mpfr_to_memory_size(this->u_.float_val, val);
19348 case NC_COMPLEX:
19349 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19350 return false;
19351 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
19352 default:
19353 go_unreachable();
19354 }
19355 }
19356
19357 // Express integer as memory size if possible.
19358
19359 bool
19360 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
19361 {
19362 if (mpz_sgn(ival) < 0)
19363 return false;
19364 if (mpz_fits_slong_p(ival))
19365 {
19366 *val = static_cast<int64_t>(mpz_get_si(ival));
19367 return true;
19368 }
19369
19370 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
19371 // positive value.
19372 if (mpz_sizeinbase(ival, 2) >= 64)
19373 return false;
19374
19375 mpz_t q, r;
19376 mpz_init(q);
19377 mpz_init(r);
19378 mpz_tdiv_q_2exp(q, ival, 32);
19379 mpz_tdiv_r_2exp(r, ival, 32);
19380 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
19381 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
19382 + static_cast<int64_t>(mpz_get_ui(r)));
19383 mpz_clear(r);
19384 mpz_clear(q);
19385 return true;
19386 }
19387
19388 // Express floating point value as memory size if possible.
19389
19390 bool
19391 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
19392 {
19393 if (!mpfr_integer_p(fval))
19394 return false;
19395 mpz_t ival;
19396 mpz_init(ival);
19397 mpfr_get_z(ival, fval, MPFR_RNDN);
19398 bool ret = this->mpz_to_memory_size(ival, val);
19399 mpz_clear(ival);
19400 return ret;
19401 }
19402
19403 // Convert value to integer if possible.
19404
19405 bool
19406 Numeric_constant::to_int(mpz_t* val) const
19407 {
19408 switch (this->classification_)
19409 {
19410 case NC_INT:
19411 case NC_RUNE:
19412 mpz_init_set(*val, this->u_.int_val);
19413 return true;
19414 case NC_FLOAT:
19415 if (!mpfr_integer_p(this->u_.float_val))
19416 return false;
19417 mpz_init(*val);
19418 mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
19419 return true;
19420 case NC_COMPLEX:
19421 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
19422 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
19423 return false;
19424 mpz_init(*val);
19425 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19426 return true;
19427 default:
19428 go_unreachable();
19429 }
19430 }
19431
19432 // Convert value to floating point if possible.
19433
19434 bool
19435 Numeric_constant::to_float(mpfr_t* val) const
19436 {
19437 switch (this->classification_)
19438 {
19439 case NC_INT:
19440 case NC_RUNE:
19441 mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
19442 return true;
19443 case NC_FLOAT:
19444 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19445 return true;
19446 case NC_COMPLEX:
19447 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19448 return false;
19449 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19450 return true;
19451 default:
19452 go_unreachable();
19453 }
19454 }
19455
19456 // Convert value to complex.
19457
19458 bool
19459 Numeric_constant::to_complex(mpc_t* val) const
19460 {
19461 mpc_init2(*val, mpc_precision);
19462 switch (this->classification_)
19463 {
19464 case NC_INT:
19465 case NC_RUNE:
19466 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
19467 return true;
19468 case NC_FLOAT:
19469 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
19470 return true;
19471 case NC_COMPLEX:
19472 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19473 return true;
19474 default:
19475 go_unreachable();
19476 }
19477 }
19478
19479 // Get the type.
19480
19481 Type*
19482 Numeric_constant::type() const
19483 {
19484 if (this->type_ != NULL)
19485 return this->type_;
19486 switch (this->classification_)
19487 {
19488 case NC_INT:
19489 return Type::make_abstract_integer_type();
19490 case NC_RUNE:
19491 return Type::make_abstract_character_type();
19492 case NC_FLOAT:
19493 return Type::make_abstract_float_type();
19494 case NC_COMPLEX:
19495 return Type::make_abstract_complex_type();
19496 default:
19497 go_unreachable();
19498 }
19499 }
19500
19501 // If the constant can be expressed in TYPE, then set the type of the
19502 // constant to TYPE and return true. Otherwise return false, and, if
19503 // ISSUE_ERROR is true, report an appropriate error message.
19504
19505 bool
19506 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
19507 {
19508 bool ret;
19509 if (type == NULL || type->is_error())
19510 ret = true;
19511 else if (type->integer_type() != NULL)
19512 ret = this->check_int_type(type->integer_type(), issue_error, loc);
19513 else if (type->float_type() != NULL)
19514 ret = this->check_float_type(type->float_type(), issue_error, loc);
19515 else if (type->complex_type() != NULL)
19516 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
19517 else
19518 {
19519 ret = false;
19520 if (issue_error)
19521 go_assert(saw_errors());
19522 }
19523 if (ret)
19524 this->type_ = type;
19525 return ret;
19526 }
19527
19528 // Check whether the constant can be expressed in an integer type.
19529
19530 bool
19531 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
19532 Location location)
19533 {
19534 mpz_t val;
19535 switch (this->classification_)
19536 {
19537 case NC_INT:
19538 case NC_RUNE:
19539 mpz_init_set(val, this->u_.int_val);
19540 break;
19541
19542 case NC_FLOAT:
19543 if (!mpfr_integer_p(this->u_.float_val))
19544 {
19545 if (issue_error)
19546 {
19547 go_error_at(location,
19548 "floating-point constant truncated to integer");
19549 this->set_invalid();
19550 }
19551 return false;
19552 }
19553 mpz_init(val);
19554 mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
19555 break;
19556
19557 case NC_COMPLEX:
19558 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
19559 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19560 {
19561 if (issue_error)
19562 {
19563 go_error_at(location, "complex constant truncated to integer");
19564 this->set_invalid();
19565 }
19566 return false;
19567 }
19568 mpz_init(val);
19569 mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19570 break;
19571
19572 default:
19573 go_unreachable();
19574 }
19575
19576 bool ret;
19577 if (type->is_abstract())
19578 ret = true;
19579 else
19580 {
19581 int bits = mpz_sizeinbase(val, 2);
19582 if (type->is_unsigned())
19583 {
19584 // For an unsigned type we can only accept a nonnegative
19585 // number, and we must be able to represents at least BITS.
19586 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
19587 }
19588 else
19589 {
19590 // For a signed type we need an extra bit to indicate the
19591 // sign. We have to handle the most negative integer
19592 // specially.
19593 ret = (bits + 1 <= type->bits()
19594 || (bits <= type->bits()
19595 && mpz_sgn(val) < 0
19596 && (mpz_scan1(val, 0)
19597 == static_cast<unsigned long>(type->bits() - 1))
19598 && mpz_scan0(val, type->bits()) == ULONG_MAX));
19599 }
19600 }
19601
19602 if (!ret && issue_error)
19603 {
19604 go_error_at(location, "integer constant overflow");
19605 this->set_invalid();
19606 }
19607
19608 return ret;
19609 }
19610
19611 // Check whether the constant can be expressed in a floating point
19612 // type.
19613
19614 bool
19615 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
19616 Location location)
19617 {
19618 mpfr_t val;
19619 switch (this->classification_)
19620 {
19621 case NC_INT:
19622 case NC_RUNE:
19623 mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
19624 break;
19625
19626 case NC_FLOAT:
19627 mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
19628 break;
19629
19630 case NC_COMPLEX:
19631 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19632 {
19633 if (issue_error)
19634 {
19635 this->set_invalid();
19636 go_error_at(location,
19637 "complex constant truncated to floating-point");
19638 }
19639 return false;
19640 }
19641 mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19642 break;
19643
19644 default:
19645 go_unreachable();
19646 }
19647
19648 bool ret;
19649 if (type->is_abstract())
19650 ret = true;
19651 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
19652 {
19653 // A NaN or Infinity always fits in the range of the type.
19654 ret = true;
19655 }
19656 else
19657 {
19658 mpfr_exp_t exp = mpfr_get_exp(val);
19659 mpfr_exp_t max_exp;
19660 switch (type->bits())
19661 {
19662 case 32:
19663 max_exp = 128;
19664 break;
19665 case 64:
19666 max_exp = 1024;
19667 break;
19668 default:
19669 go_unreachable();
19670 }
19671
19672 ret = exp <= max_exp;
19673
19674 if (ret)
19675 {
19676 // Round the constant to the desired type.
19677 mpfr_t t;
19678 mpfr_init(t);
19679 switch (type->bits())
19680 {
19681 case 32:
19682 mpfr_set_prec(t, 24);
19683 break;
19684 case 64:
19685 mpfr_set_prec(t, 53);
19686 break;
19687 default:
19688 go_unreachable();
19689 }
19690 mpfr_set(t, val, MPFR_RNDN);
19691 mpfr_set(val, t, MPFR_RNDN);
19692 mpfr_clear(t);
19693
19694 this->set_float(type, val);
19695 }
19696 }
19697
19698 mpfr_clear(val);
19699
19700 if (!ret && issue_error)
19701 {
19702 go_error_at(location, "floating-point constant overflow");
19703 this->set_invalid();
19704 }
19705
19706 return ret;
19707 }
19708
19709 // Check whether the constant can be expressed in a complex type.
19710
19711 bool
19712 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
19713 Location location)
19714 {
19715 if (type->is_abstract())
19716 return true;
19717
19718 mpfr_exp_t max_exp;
19719 switch (type->bits())
19720 {
19721 case 64:
19722 max_exp = 128;
19723 break;
19724 case 128:
19725 max_exp = 1024;
19726 break;
19727 default:
19728 go_unreachable();
19729 }
19730
19731 mpc_t val;
19732 mpc_init2(val, mpc_precision);
19733 switch (this->classification_)
19734 {
19735 case NC_INT:
19736 case NC_RUNE:
19737 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
19738 break;
19739
19740 case NC_FLOAT:
19741 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
19742 break;
19743
19744 case NC_COMPLEX:
19745 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
19746 break;
19747
19748 default:
19749 go_unreachable();
19750 }
19751
19752 bool ret = true;
19753 if (!mpfr_nan_p(mpc_realref(val))
19754 && !mpfr_inf_p(mpc_realref(val))
19755 && !mpfr_zero_p(mpc_realref(val))
19756 && mpfr_get_exp(mpc_realref(val)) > max_exp)
19757 {
19758 if (issue_error)
19759 {
19760 go_error_at(location, "complex real part overflow");
19761 this->set_invalid();
19762 }
19763 ret = false;
19764 }
19765
19766 if (!mpfr_nan_p(mpc_imagref(val))
19767 && !mpfr_inf_p(mpc_imagref(val))
19768 && !mpfr_zero_p(mpc_imagref(val))
19769 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
19770 {
19771 if (issue_error)
19772 {
19773 go_error_at(location, "complex imaginary part overflow");
19774 this->set_invalid();
19775 }
19776 ret = false;
19777 }
19778
19779 if (ret)
19780 {
19781 // Round the constant to the desired type.
19782 mpc_t t;
19783 switch (type->bits())
19784 {
19785 case 64:
19786 mpc_init2(t, 24);
19787 break;
19788 case 128:
19789 mpc_init2(t, 53);
19790 break;
19791 default:
19792 go_unreachable();
19793 }
19794 mpc_set(t, val, MPC_RNDNN);
19795 mpc_set(val, t, MPC_RNDNN);
19796 mpc_clear(t);
19797
19798 this->set_complex(type, val);
19799 }
19800
19801 mpc_clear(val);
19802
19803 return ret;
19804 }
19805
19806 // Return an Expression for this value.
19807
19808 Expression*
19809 Numeric_constant::expression(Location loc) const
19810 {
19811 switch (this->classification_)
19812 {
19813 case NC_INT:
19814 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
19815 case NC_RUNE:
19816 return Expression::make_character(&this->u_.int_val, this->type_, loc);
19817 case NC_FLOAT:
19818 return Expression::make_float(&this->u_.float_val, this->type_, loc);
19819 case NC_COMPLEX:
19820 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
19821 case NC_INVALID:
19822 go_assert(saw_errors());
19823 return Expression::make_error(loc);
19824 default:
19825 go_unreachable();
19826 }
19827 }
19828
19829 // Calculate a hash code with a given seed.
19830
19831 unsigned int
19832 Numeric_constant::hash(unsigned int seed) const
19833 {
19834 unsigned long val;
19835 const unsigned int PRIME = 97;
19836 long e = 0;
19837 double f = 1.0;
19838 mpfr_t m;
19839
19840 switch (this->classification_)
19841 {
19842 case NC_INVALID:
19843 return PRIME;
19844 case NC_INT:
19845 case NC_RUNE:
19846 val = mpz_get_ui(this->u_.int_val);
19847 break;
19848 case NC_COMPLEX:
19849 mpfr_init(m);
19850 mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
19851 val = mpfr_get_ui(m, MPFR_RNDN);
19852 mpfr_clear(m);
19853 break;
19854 case NC_FLOAT:
19855 f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
19856 val = static_cast<unsigned long>(e + static_cast<long>(f));
19857 break;
19858 default:
19859 go_unreachable();
19860 }
19861
19862 return (static_cast<unsigned int>(val) + seed) * PRIME;
19863 }