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 "types.h"
14 #include "export.h"
15 #include "import.h"
16 #include "statements.h"
17 #include "lex.h"
18 #include "runtime.h"
19 #include "backend.h"
20 #include "expressions.h"
21 #include "ast-dump.h"
22
23 // Class Expression.
24
Expression(Expression_classification classification,Location location)25 Expression::Expression(Expression_classification classification,
26 Location location)
27 : classification_(classification), location_(location)
28 {
29 }
30
~Expression()31 Expression::~Expression()
32 {
33 }
34
35 // Traverse the expressions.
36
37 int
traverse(Expression ** pexpr,Traverse * traverse)38 Expression::traverse(Expression** pexpr, Traverse* traverse)
39 {
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
42 {
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
48 }
49 return expr->do_traverse(traverse);
50 }
51
52 // Traverse subexpressions of this expression.
53
54 int
traverse_subexpressions(Traverse * traverse)55 Expression::traverse_subexpressions(Traverse* traverse)
56 {
57 return this->do_traverse(traverse);
58 }
59
60 // Default implementation for do_traverse for child classes.
61
62 int
do_traverse(Traverse *)63 Expression::do_traverse(Traverse*)
64 {
65 return TRAVERSE_CONTINUE;
66 }
67
68 // This virtual function is called by the parser if the value of this
69 // expression is being discarded. By default, we give an error.
70 // Expressions with side effects override.
71
72 bool
do_discarding_value()73 Expression::do_discarding_value()
74 {
75 this->unused_value_error();
76 return false;
77 }
78
79 // This virtual function is called to export expressions. This will
80 // only be used by expressions which may be constant.
81
82 void
do_export(Export *) const83 Expression::do_export(Export*) const
84 {
85 go_unreachable();
86 }
87
88 // Give an error saying that the value of the expression is not used.
89
90 void
unused_value_error()91 Expression::unused_value_error()
92 {
93 this->report_error(_("value computed is not used"));
94 }
95
96 // Note that this expression is an error. This is called by children
97 // when they discover an error.
98
99 void
set_is_error()100 Expression::set_is_error()
101 {
102 this->classification_ = EXPRESSION_ERROR;
103 }
104
105 // For children to call to report an error conveniently.
106
107 void
report_error(const char * msg)108 Expression::report_error(const char* msg)
109 {
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
112 }
113
114 // Set types of variables and constants. This is implemented by the
115 // child class.
116
117 void
determine_type(const Type_context * context)118 Expression::determine_type(const Type_context* context)
119 {
120 this->do_determine_type(context);
121 }
122
123 // Set types when there is no context.
124
125 void
determine_type_no_context()126 Expression::determine_type_no_context()
127 {
128 Type_context context;
129 this->do_determine_type(&context);
130 }
131
132 // Return an expression handling any conversions which must be done during
133 // assignment.
134
135 Expression*
convert_for_assignment(Gogo *,Type * lhs_type,Expression * rhs,Location location)136 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
137 Expression* rhs, Location location)
138 {
139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
144
145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
147 {
148 if (rhs_type->interface_type() == NULL)
149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
150 else
151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
153 }
154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
158 {
159 // Assigning nil to a slice.
160 Expression* nil = Expression::make_nil(location);
161 Expression* zero = Expression::make_integer_ul(0, NULL, location);
162 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
163 }
164 else if (rhs_type->is_nil_type())
165 return Expression::make_nil(location);
166 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
167 {
168 // No conversion is needed.
169 return rhs;
170 }
171 else if (lhs_type->points_to() != NULL)
172 return Expression::make_unsafe_cast(lhs_type, rhs, location);
173 else if (lhs_type->is_numeric_type())
174 return Expression::make_cast(lhs_type, rhs, location);
175 else if ((lhs_type->struct_type() != NULL
176 && rhs_type->struct_type() != NULL)
177 || (lhs_type->array_type() != NULL
178 && rhs_type->array_type() != NULL))
179 {
180 // This conversion must be permitted by Go, or we wouldn't have
181 // gotten here.
182 return Expression::make_unsafe_cast(lhs_type, rhs, location);
183 }
184 else
185 return rhs;
186 }
187
188 // Return an expression for a conversion from a non-interface type to an
189 // interface type.
190
191 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,Location location)192 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
193 Location location)
194 {
195 Interface_type* lhs_interface_type = lhs_type->interface_type();
196 bool lhs_is_empty = lhs_interface_type->is_empty();
197
198 // Since RHS_TYPE is a static type, we can create the interface
199 // method table at compile time.
200
201 // When setting an interface to nil, we just set both fields to
202 // NULL.
203 Type* rhs_type = rhs->type();
204 if (rhs_type->is_nil_type())
205 {
206 Expression* nil = Expression::make_nil(location);
207 return Expression::make_interface_value(lhs_type, nil, nil, location);
208 }
209
210 // This should have been checked already.
211 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
212
213 // An interface is a tuple. If LHS_TYPE is an empty interface type,
214 // then the first field is the type descriptor for RHS_TYPE.
215 // Otherwise it is the interface method table for RHS_TYPE.
216 Expression* first_field;
217 if (lhs_is_empty)
218 first_field = Expression::make_type_descriptor(rhs_type, location);
219 else
220 {
221 // Build the interface method table for this interface and this
222 // object type: a list of function pointers for each interface
223 // method.
224 Named_type* rhs_named_type = rhs_type->named_type();
225 Struct_type* rhs_struct_type = rhs_type->struct_type();
226 bool is_pointer = false;
227 if (rhs_named_type == NULL && rhs_struct_type == NULL)
228 {
229 rhs_named_type = rhs_type->deref()->named_type();
230 rhs_struct_type = rhs_type->deref()->struct_type();
231 is_pointer = true;
232 }
233 if (rhs_named_type != NULL)
234 first_field =
235 rhs_named_type->interface_method_table(lhs_interface_type,
236 is_pointer);
237 else if (rhs_struct_type != NULL)
238 first_field =
239 rhs_struct_type->interface_method_table(lhs_interface_type,
240 is_pointer);
241 else
242 first_field = Expression::make_nil(location);
243 }
244
245 Expression* obj;
246 if (rhs_type->points_to() != NULL)
247 {
248 // We are assigning a pointer to the interface; the interface
249 // holds the pointer itself.
250 obj = rhs;
251 }
252 else
253 {
254 // We are assigning a non-pointer value to the interface; the
255 // interface gets a copy of the value in the heap.
256 obj = Expression::make_heap_expression(rhs, location);
257 }
258
259 return Expression::make_interface_value(lhs_type, first_field, obj, location);
260 }
261
262 // Return an expression for the type descriptor of RHS.
263
264 Expression*
get_interface_type_descriptor(Expression * rhs)265 Expression::get_interface_type_descriptor(Expression* rhs)
266 {
267 go_assert(rhs->type()->interface_type() != NULL);
268 Location location = rhs->location();
269
270 // The type descriptor is the first field of an empty interface.
271 if (rhs->type()->interface_type()->is_empty())
272 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
273 location);
274
275 Expression* mtable =
276 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
277
278 Expression* descriptor =
279 Expression::make_unary(OPERATOR_MULT, mtable, location);
280 descriptor = Expression::make_field_reference(descriptor, 0, location);
281 Expression* nil = Expression::make_nil(location);
282
283 Expression* eq =
284 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
285 return Expression::make_conditional(eq, nil, descriptor, location);
286 }
287
288 // Return an expression for the conversion of an interface type to an
289 // interface type.
290
291 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)292 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
293 bool for_type_guard,
294 Location location)
295 {
296 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
297 return rhs;
298
299 Interface_type* lhs_interface_type = lhs_type->interface_type();
300 bool lhs_is_empty = lhs_interface_type->is_empty();
301
302 // In the general case this requires runtime examination of the type
303 // method table to match it up with the interface methods.
304
305 // FIXME: If all of the methods in the right hand side interface
306 // also appear in the left hand side interface, then we don't need
307 // to do a runtime check, although we still need to build a new
308 // method table.
309
310 // We are going to evaluate RHS multiple times.
311 go_assert(rhs->is_variable());
312
313 // Get the type descriptor for the right hand side. This will be
314 // NULL for a nil interface.
315 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
316 Expression* lhs_type_expr =
317 Expression::make_type_descriptor(lhs_type, location);
318
319 Expression* first_field;
320 if (for_type_guard)
321 {
322 // A type assertion fails when converting a nil interface.
323 first_field =
324 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
325 lhs_type_expr, rhs_type_expr);
326 }
327 else if (lhs_is_empty)
328 {
329 // A conversion to an empty interface always succeeds, and the
330 // first field is just the type descriptor of the object.
331 first_field = rhs_type_expr;
332 }
333 else
334 {
335 // A conversion to a non-empty interface may fail, but unlike a
336 // type assertion converting nil will always succeed.
337 first_field =
338 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
339 lhs_type_expr, rhs_type_expr);
340 }
341
342 // The second field is simply the object pointer.
343 Expression* obj =
344 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
345 return Expression::make_interface_value(lhs_type, first_field, obj, location);
346 }
347
348 // Return an expression for the conversion of an interface type to a
349 // non-interface type.
350
351 Expression*
convert_interface_to_type(Type * lhs_type,Expression * rhs,Location location)352 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
353 Location location)
354 {
355 // We are going to evaluate RHS multiple times.
356 go_assert(rhs->is_variable());
357
358 // Call a function to check that the type is valid. The function
359 // will panic with an appropriate runtime type error if the type is
360 // not valid.
361 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
362 location);
363 Expression* rhs_descriptor =
364 Expression::get_interface_type_descriptor(rhs);
365
366 Type* rhs_type = rhs->type();
367 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
368 location);
369
370 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
371 location, 3, lhs_type_expr,
372 rhs_descriptor, rhs_inter_expr);
373
374 // If the call succeeds, pull out the value.
375 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
376 location);
377
378 // If the value is a pointer, then it is the value we want.
379 // Otherwise it points to the value.
380 if (lhs_type->points_to() == NULL)
381 {
382 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
383 location);
384 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
385 }
386 return Expression::make_compound(check_iface, obj, location);
387 }
388
389 // Convert an expression to its backend representation. This is implemented by
390 // the child class. Not that it is not in general safe to call this multiple
391 // times for a single expression, but that we don't catch such errors.
392
393 Bexpression*
get_backend(Translate_context * context)394 Expression::get_backend(Translate_context* context)
395 {
396 // The child may have marked this expression as having an error.
397 if (this->classification_ == EXPRESSION_ERROR)
398 return context->backend()->error_expression();
399
400 return this->do_get_backend(context);
401 }
402
403 // Return a backend expression for VAL.
404 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)405 Expression::backend_numeric_constant_expression(Translate_context* context,
406 Numeric_constant* val)
407 {
408 Gogo* gogo = context->gogo();
409 Type* type = val->type();
410 if (type == NULL)
411 return gogo->backend()->error_expression();
412
413 Btype* btype = type->get_backend(gogo);
414 Bexpression* ret;
415 if (type->integer_type() != NULL)
416 {
417 mpz_t ival;
418 if (!val->to_int(&ival))
419 {
420 go_assert(saw_errors());
421 return gogo->backend()->error_expression();
422 }
423 ret = gogo->backend()->integer_constant_expression(btype, ival);
424 mpz_clear(ival);
425 }
426 else if (type->float_type() != NULL)
427 {
428 mpfr_t fval;
429 if (!val->to_float(&fval))
430 {
431 go_assert(saw_errors());
432 return gogo->backend()->error_expression();
433 }
434 ret = gogo->backend()->float_constant_expression(btype, fval);
435 mpfr_clear(fval);
436 }
437 else if (type->complex_type() != NULL)
438 {
439 mpc_t cval;
440 if (!val->to_complex(&cval))
441 {
442 go_assert(saw_errors());
443 return gogo->backend()->error_expression();
444 }
445 ret = gogo->backend()->complex_constant_expression(btype, cval);
446 mpc_clear(cval);
447 }
448 else
449 go_unreachable();
450
451 return ret;
452 }
453
454 // Return an expression which evaluates to true if VAL, of arbitrary integer
455 // type, is negative or is more than the maximum value of the Go type "int".
456
457 Expression*
check_bounds(Expression * val,Location loc)458 Expression::check_bounds(Expression* val, Location loc)
459 {
460 Type* val_type = val->type();
461 Type* bound_type = Type::lookup_integer_type("int");
462
463 int val_type_size;
464 bool val_is_unsigned = false;
465 if (val_type->integer_type() != NULL)
466 {
467 val_type_size = val_type->integer_type()->bits();
468 val_is_unsigned = val_type->integer_type()->is_unsigned();
469 }
470 else
471 {
472 if (!val_type->is_numeric_type()
473 || !Type::are_convertible(bound_type, val_type, NULL))
474 {
475 go_assert(saw_errors());
476 return Expression::make_boolean(true, loc);
477 }
478
479 if (val_type->complex_type() != NULL)
480 val_type_size = val_type->complex_type()->bits();
481 else
482 val_type_size = val_type->float_type()->bits();
483 }
484
485 Expression* negative_index = Expression::make_boolean(false, loc);
486 Expression* index_overflows = Expression::make_boolean(false, loc);
487 if (!val_is_unsigned)
488 {
489 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
490 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
491 }
492
493 int bound_type_size = bound_type->integer_type()->bits();
494 if (val_type_size > bound_type_size
495 || (val_type_size == bound_type_size
496 && val_is_unsigned))
497 {
498 mpz_t one;
499 mpz_init_set_ui(one, 1UL);
500
501 // maxval = 2^(bound_type_size - 1) - 1
502 mpz_t maxval;
503 mpz_init(maxval);
504 mpz_mul_2exp(maxval, one, bound_type_size - 1);
505 mpz_sub_ui(maxval, maxval, 1);
506 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
507 mpz_clear(one);
508 mpz_clear(maxval);
509
510 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
511 }
512
513 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
514 loc);
515 }
516
517 void
dump_expression(Ast_dump_context * ast_dump_context) const518 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
519 {
520 this->do_dump_expression(ast_dump_context);
521 }
522
523 // Error expressions. This are used to avoid cascading errors.
524
525 class Error_expression : public Expression
526 {
527 public:
Error_expression(Location location)528 Error_expression(Location location)
529 : Expression(EXPRESSION_ERROR, location)
530 { }
531
532 protected:
533 bool
do_is_constant() const534 do_is_constant() const
535 { return true; }
536
537 bool
do_is_immutable() const538 do_is_immutable() const
539 { return true; }
540
541 bool
do_numeric_constant_value(Numeric_constant * nc) const542 do_numeric_constant_value(Numeric_constant* nc) const
543 {
544 nc->set_unsigned_long(NULL, 0);
545 return true;
546 }
547
548 bool
do_discarding_value()549 do_discarding_value()
550 { return true; }
551
552 Type*
do_type()553 do_type()
554 { return Type::make_error_type(); }
555
556 void
do_determine_type(const Type_context *)557 do_determine_type(const Type_context*)
558 { }
559
560 Expression*
do_copy()561 do_copy()
562 { return this; }
563
564 bool
do_is_addressable() const565 do_is_addressable() const
566 { return true; }
567
568 Bexpression*
do_get_backend(Translate_context * context)569 do_get_backend(Translate_context* context)
570 { return context->backend()->error_expression(); }
571
572 void
573 do_dump_expression(Ast_dump_context*) const;
574 };
575
576 // Dump the ast representation for an error expression to a dump context.
577
578 void
do_dump_expression(Ast_dump_context * ast_dump_context) const579 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
580 {
581 ast_dump_context->ostream() << "_Error_" ;
582 }
583
584 Expression*
make_error(Location location)585 Expression::make_error(Location location)
586 {
587 return new Error_expression(location);
588 }
589
590 // An expression which is really a type. This is used during parsing.
591 // It is an error if these survive after lowering.
592
593 class
594 Type_expression : public Expression
595 {
596 public:
Type_expression(Type * type,Location location)597 Type_expression(Type* type, Location location)
598 : Expression(EXPRESSION_TYPE, location),
599 type_(type)
600 { }
601
602 protected:
603 int
do_traverse(Traverse * traverse)604 do_traverse(Traverse* traverse)
605 { return Type::traverse(this->type_, traverse); }
606
607 Type*
do_type()608 do_type()
609 { return this->type_; }
610
611 void
do_determine_type(const Type_context *)612 do_determine_type(const Type_context*)
613 { }
614
615 void
do_check_types(Gogo *)616 do_check_types(Gogo*)
617 { this->report_error(_("invalid use of type")); }
618
619 Expression*
do_copy()620 do_copy()
621 { return this; }
622
623 Bexpression*
do_get_backend(Translate_context *)624 do_get_backend(Translate_context*)
625 { go_unreachable(); }
626
627 void do_dump_expression(Ast_dump_context*) const;
628
629 private:
630 // The type which we are representing as an expression.
631 Type* type_;
632 };
633
634 void
do_dump_expression(Ast_dump_context * ast_dump_context) const635 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
636 {
637 ast_dump_context->dump_type(this->type_);
638 }
639
640 Expression*
make_type(Type * type,Location location)641 Expression::make_type(Type* type, Location location)
642 {
643 return new Type_expression(type, location);
644 }
645
646 // Class Parser_expression.
647
648 Type*
do_type()649 Parser_expression::do_type()
650 {
651 // We should never really ask for the type of a Parser_expression.
652 // However, it can happen, at least when we have an invalid const
653 // whose initializer refers to the const itself. In that case we
654 // may ask for the type when lowering the const itself.
655 go_assert(saw_errors());
656 return Type::make_error_type();
657 }
658
659 // Class Var_expression.
660
661 // Lower a variable expression. Here we just make sure that the
662 // initialization expression of the variable has been lowered. This
663 // ensures that we will be able to determine the type of the variable
664 // if necessary.
665
666 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)667 Var_expression::do_lower(Gogo* gogo, Named_object* function,
668 Statement_inserter* inserter, int)
669 {
670 if (this->variable_->is_variable())
671 {
672 Variable* var = this->variable_->var_value();
673 // This is either a local variable or a global variable. A
674 // reference to a variable which is local to an enclosing
675 // function will be a reference to a field in a closure.
676 if (var->is_global())
677 {
678 function = NULL;
679 inserter = NULL;
680 }
681 var->lower_init_expression(gogo, function, inserter);
682 }
683 return this;
684 }
685
686 // Return the type of a reference to a variable.
687
688 Type*
do_type()689 Var_expression::do_type()
690 {
691 if (this->variable_->is_variable())
692 return this->variable_->var_value()->type();
693 else if (this->variable_->is_result_variable())
694 return this->variable_->result_var_value()->type();
695 else
696 go_unreachable();
697 }
698
699 // Determine the type of a reference to a variable.
700
701 void
do_determine_type(const Type_context *)702 Var_expression::do_determine_type(const Type_context*)
703 {
704 if (this->variable_->is_variable())
705 this->variable_->var_value()->determine_type();
706 }
707
708 // Something takes the address of this variable. This means that we
709 // may want to move the variable onto the heap.
710
711 void
do_address_taken(bool escapes)712 Var_expression::do_address_taken(bool escapes)
713 {
714 if (!escapes)
715 {
716 if (this->variable_->is_variable())
717 this->variable_->var_value()->set_non_escaping_address_taken();
718 else if (this->variable_->is_result_variable())
719 this->variable_->result_var_value()->set_non_escaping_address_taken();
720 else
721 go_unreachable();
722 }
723 else
724 {
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_address_taken();
729 else
730 go_unreachable();
731 }
732 }
733
734 // Get the backend representation for a reference to a variable.
735
736 Bexpression*
do_get_backend(Translate_context * context)737 Var_expression::do_get_backend(Translate_context* context)
738 {
739 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
740 context->function());
741 bool is_in_heap;
742 Location loc = this->location();
743 Btype* btype;
744 Gogo* gogo = context->gogo();
745 if (this->variable_->is_variable())
746 {
747 is_in_heap = this->variable_->var_value()->is_in_heap();
748 btype = this->variable_->var_value()->type()->get_backend(gogo);
749 }
750 else if (this->variable_->is_result_variable())
751 {
752 is_in_heap = this->variable_->result_var_value()->is_in_heap();
753 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
754 }
755 else
756 go_unreachable();
757
758 Bexpression* ret = context->backend()->var_expression(bvar, loc);
759 if (is_in_heap)
760 ret = context->backend()->indirect_expression(btype, ret, true, loc);
761 return ret;
762 }
763
764 // Ast dump for variable expression.
765
766 void
do_dump_expression(Ast_dump_context * ast_dump_context) const767 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
768 {
769 ast_dump_context->ostream() << this->variable_->name() ;
770 }
771
772 // Make a reference to a variable in an expression.
773
774 Expression*
make_var_reference(Named_object * var,Location location)775 Expression::make_var_reference(Named_object* var, Location location)
776 {
777 if (var->is_sink())
778 return Expression::make_sink(location);
779
780 // FIXME: Creating a new object for each reference to a variable is
781 // wasteful.
782 return new Var_expression(var, location);
783 }
784
785 // Class Temporary_reference_expression.
786
787 // The type.
788
789 Type*
do_type()790 Temporary_reference_expression::do_type()
791 {
792 return this->statement_->type();
793 }
794
795 // Called if something takes the address of this temporary variable.
796 // We never have to move temporary variables to the heap, but we do
797 // need to know that they must live in the stack rather than in a
798 // register.
799
800 void
do_address_taken(bool)801 Temporary_reference_expression::do_address_taken(bool)
802 {
803 this->statement_->set_is_address_taken();
804 }
805
806 // Get a backend expression referring to the variable.
807
808 Bexpression*
do_get_backend(Translate_context * context)809 Temporary_reference_expression::do_get_backend(Translate_context* context)
810 {
811 Gogo* gogo = context->gogo();
812 Bvariable* bvar = this->statement_->get_backend_variable(context);
813 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
814
815 // The backend can't always represent the same set of recursive types
816 // that the Go frontend can. In some cases this means that a
817 // temporary variable won't have the right backend type. Correct
818 // that here by adding a type cast. We need to use base() to push
819 // the circularity down one level.
820 Type* stype = this->statement_->type();
821 if (!this->is_lvalue_
822 && stype->has_pointer()
823 && stype->deref()->is_void_type())
824 {
825 Btype* btype = this->type()->base()->get_backend(gogo);
826 ret = gogo->backend()->convert_expression(btype, ret, this->location());
827 }
828 return ret;
829 }
830
831 // Ast dump for temporary reference.
832
833 void
do_dump_expression(Ast_dump_context * ast_dump_context) const834 Temporary_reference_expression::do_dump_expression(
835 Ast_dump_context* ast_dump_context) const
836 {
837 ast_dump_context->dump_temp_variable_name(this->statement_);
838 }
839
840 // Make a reference to a temporary variable.
841
842 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)843 Expression::make_temporary_reference(Temporary_statement* statement,
844 Location location)
845 {
846 return new Temporary_reference_expression(statement, location);
847 }
848
849 // Class Set_and_use_temporary_expression.
850
851 // Return the type.
852
853 Type*
do_type()854 Set_and_use_temporary_expression::do_type()
855 {
856 return this->statement_->type();
857 }
858
859 // Determine the type of the expression.
860
861 void
do_determine_type(const Type_context * context)862 Set_and_use_temporary_expression::do_determine_type(
863 const Type_context* context)
864 {
865 this->expr_->determine_type(context);
866 }
867
868 // Take the address.
869
870 void
do_address_taken(bool)871 Set_and_use_temporary_expression::do_address_taken(bool)
872 {
873 this->statement_->set_is_address_taken();
874 }
875
876 // Return the backend representation.
877
878 Bexpression*
do_get_backend(Translate_context * context)879 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
880 {
881 Location loc = this->location();
882 Gogo* gogo = context->gogo();
883 Bvariable* bvar = this->statement_->get_backend_variable(context);
884 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
885
886 Bexpression* bexpr = this->expr_->get_backend(context);
887 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
888 var_ref = gogo->backend()->var_expression(bvar, loc);
889 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
890 return ret;
891 }
892
893 // Dump.
894
895 void
do_dump_expression(Ast_dump_context * ast_dump_context) const896 Set_and_use_temporary_expression::do_dump_expression(
897 Ast_dump_context* ast_dump_context) const
898 {
899 ast_dump_context->ostream() << '(';
900 ast_dump_context->dump_temp_variable_name(this->statement_);
901 ast_dump_context->ostream() << " = ";
902 this->expr_->dump_expression(ast_dump_context);
903 ast_dump_context->ostream() << ')';
904 }
905
906 // Make a set-and-use temporary.
907
908 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)909 Expression::make_set_and_use_temporary(Temporary_statement* statement,
910 Expression* expr, Location location)
911 {
912 return new Set_and_use_temporary_expression(statement, expr, location);
913 }
914
915 // A sink expression--a use of the blank identifier _.
916
917 class Sink_expression : public Expression
918 {
919 public:
Sink_expression(Location location)920 Sink_expression(Location location)
921 : Expression(EXPRESSION_SINK, location),
922 type_(NULL), bvar_(NULL)
923 { }
924
925 protected:
926 bool
do_discarding_value()927 do_discarding_value()
928 { return true; }
929
930 Type*
931 do_type();
932
933 void
934 do_determine_type(const Type_context*);
935
936 Expression*
do_copy()937 do_copy()
938 { return new Sink_expression(this->location()); }
939
940 Bexpression*
941 do_get_backend(Translate_context*);
942
943 void
944 do_dump_expression(Ast_dump_context*) const;
945
946 private:
947 // The type of this sink variable.
948 Type* type_;
949 // The temporary variable we generate.
950 Bvariable* bvar_;
951 };
952
953 // Return the type of a sink expression.
954
955 Type*
do_type()956 Sink_expression::do_type()
957 {
958 if (this->type_ == NULL)
959 return Type::make_sink_type();
960 return this->type_;
961 }
962
963 // Determine the type of a sink expression.
964
965 void
do_determine_type(const Type_context * context)966 Sink_expression::do_determine_type(const Type_context* context)
967 {
968 if (context->type != NULL)
969 this->type_ = context->type;
970 }
971
972 // Return a temporary variable for a sink expression. This will
973 // presumably be a write-only variable which the middle-end will drop.
974
975 Bexpression*
do_get_backend(Translate_context * context)976 Sink_expression::do_get_backend(Translate_context* context)
977 {
978 Location loc = this->location();
979 Gogo* gogo = context->gogo();
980 if (this->bvar_ == NULL)
981 {
982 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
983 Named_object* fn = context->function();
984 go_assert(fn != NULL);
985 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
986 Btype* bt = this->type_->get_backend(context->gogo());
987 Bstatement* decl;
988 this->bvar_ =
989 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
990 false, loc, &decl);
991 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
992 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
993 return var_ref;
994 }
995 return gogo->backend()->var_expression(this->bvar_, loc);
996 }
997
998 // Ast dump for sink expression.
999
1000 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1001 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1002 {
1003 ast_dump_context->ostream() << "_" ;
1004 }
1005
1006 // Make a sink expression.
1007
1008 Expression*
make_sink(Location location)1009 Expression::make_sink(Location location)
1010 {
1011 return new Sink_expression(location);
1012 }
1013
1014 // Class Func_expression.
1015
1016 // FIXME: Can a function expression appear in a constant expression?
1017 // The value is unchanging. Initializing a constant to the address of
1018 // a function seems like it could work, though there might be little
1019 // point to it.
1020
1021 // Traversal.
1022
1023 int
do_traverse(Traverse * traverse)1024 Func_expression::do_traverse(Traverse* traverse)
1025 {
1026 return (this->closure_ == NULL
1027 ? TRAVERSE_CONTINUE
1028 : Expression::traverse(&this->closure_, traverse));
1029 }
1030
1031 // Return the type of a function expression.
1032
1033 Type*
do_type()1034 Func_expression::do_type()
1035 {
1036 if (this->function_->is_function())
1037 return this->function_->func_value()->type();
1038 else if (this->function_->is_function_declaration())
1039 return this->function_->func_declaration_value()->type();
1040 else
1041 go_unreachable();
1042 }
1043
1044 // Get the backend representation for the code of a function expression.
1045
1046 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1047 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1048 {
1049 Function_type* fntype;
1050 if (no->is_function())
1051 fntype = no->func_value()->type();
1052 else if (no->is_function_declaration())
1053 fntype = no->func_declaration_value()->type();
1054 else
1055 go_unreachable();
1056
1057 // Builtin functions are handled specially by Call_expression. We
1058 // can't take their address.
1059 if (fntype->is_builtin())
1060 {
1061 error_at(loc,
1062 "invalid use of special builtin function %qs; must be called",
1063 no->message_name().c_str());
1064 return gogo->backend()->error_expression();
1065 }
1066
1067 Bfunction* fndecl;
1068 if (no->is_function())
1069 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1070 else if (no->is_function_declaration())
1071 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1072 else
1073 go_unreachable();
1074
1075 return gogo->backend()->function_code_expression(fndecl, loc);
1076 }
1077
1078 // Get the backend representation for a function expression. This is used when
1079 // we take the address of a function rather than simply calling it. A func
1080 // value is represented as a pointer to a block of memory. The first
1081 // word of that memory is a pointer to the function code. The
1082 // remaining parts of that memory are the addresses of variables that
1083 // the function closes over.
1084
1085 Bexpression*
do_get_backend(Translate_context * context)1086 Func_expression::do_get_backend(Translate_context* context)
1087 {
1088 // If there is no closure, just use the function descriptor.
1089 if (this->closure_ == NULL)
1090 {
1091 Gogo* gogo = context->gogo();
1092 Named_object* no = this->function_;
1093 Expression* descriptor;
1094 if (no->is_function())
1095 descriptor = no->func_value()->descriptor(gogo, no);
1096 else if (no->is_function_declaration())
1097 {
1098 if (no->func_declaration_value()->type()->is_builtin())
1099 {
1100 error_at(this->location(),
1101 ("invalid use of special builtin function %qs; "
1102 "must be called"),
1103 no->message_name().c_str());
1104 return gogo->backend()->error_expression();
1105 }
1106 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1107 }
1108 else
1109 go_unreachable();
1110
1111 Bexpression* bdesc = descriptor->get_backend(context);
1112 return gogo->backend()->address_expression(bdesc, this->location());
1113 }
1114
1115 go_assert(this->function_->func_value()->enclosing() != NULL);
1116
1117 // If there is a closure, then the closure is itself the function
1118 // expression. It is a pointer to a struct whose first field points
1119 // to the function code and whose remaining fields are the addresses
1120 // of the closed-over variables.
1121 return this->closure_->get_backend(context);
1122 }
1123
1124 // Ast dump for function.
1125
1126 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1127 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1128 {
1129 ast_dump_context->ostream() << this->function_->name();
1130 if (this->closure_ != NULL)
1131 {
1132 ast_dump_context->ostream() << " {closure = ";
1133 this->closure_->dump_expression(ast_dump_context);
1134 ast_dump_context->ostream() << "}";
1135 }
1136 }
1137
1138 // Make a reference to a function in an expression.
1139
1140 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1141 Expression::make_func_reference(Named_object* function, Expression* closure,
1142 Location location)
1143 {
1144 return new Func_expression(function, closure, location);
1145 }
1146
1147 // Class Func_descriptor_expression.
1148
1149 // Constructor.
1150
Func_descriptor_expression(Named_object * fn)1151 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1152 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1153 fn_(fn), dvar_(NULL)
1154 {
1155 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1156 }
1157
1158 // Traversal.
1159
1160 int
do_traverse(Traverse *)1161 Func_descriptor_expression::do_traverse(Traverse*)
1162 {
1163 return TRAVERSE_CONTINUE;
1164 }
1165
1166 // All function descriptors have the same type.
1167
1168 Type* Func_descriptor_expression::descriptor_type;
1169
1170 void
make_func_descriptor_type()1171 Func_descriptor_expression::make_func_descriptor_type()
1172 {
1173 if (Func_descriptor_expression::descriptor_type != NULL)
1174 return;
1175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1176 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1177 Func_descriptor_expression::descriptor_type =
1178 Type::make_builtin_named_type("functionDescriptor", struct_type);
1179 }
1180
1181 Type*
do_type()1182 Func_descriptor_expression::do_type()
1183 {
1184 Func_descriptor_expression::make_func_descriptor_type();
1185 return Func_descriptor_expression::descriptor_type;
1186 }
1187
1188 // The backend representation for a function descriptor.
1189
1190 Bexpression*
do_get_backend(Translate_context * context)1191 Func_descriptor_expression::do_get_backend(Translate_context* context)
1192 {
1193 Named_object* no = this->fn_;
1194 Location loc = no->location();
1195 if (this->dvar_ != NULL)
1196 return context->backend()->var_expression(this->dvar_, loc);
1197
1198 Gogo* gogo = context->gogo();
1199 std::string var_name;
1200 bool is_descriptor = false;
1201 if (no->is_function_declaration()
1202 && !no->func_declaration_value()->asm_name().empty()
1203 && Linemap::is_predeclared_location(no->location()))
1204 {
1205 var_name = no->func_declaration_value()->asm_name() + "_descriptor";
1206 is_descriptor = true;
1207 }
1208 else
1209 {
1210 if (no->package() == NULL)
1211 var_name = gogo->pkgpath_symbol();
1212 else
1213 var_name = no->package()->pkgpath_symbol();
1214 var_name.push_back('.');
1215 var_name.append(Gogo::unpack_hidden_name(no->name()));
1216 var_name.append("$descriptor");
1217 }
1218
1219 Btype* btype = this->type()->get_backend(gogo);
1220
1221 Bvariable* bvar;
1222 if (no->package() != NULL || is_descriptor)
1223 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1224 loc);
1225 else
1226 {
1227 Location bloc = Linemap::predeclared_location();
1228 bool is_hidden = ((no->is_function()
1229 && no->func_value()->enclosing() != NULL)
1230 || Gogo::is_thunk(no));
1231 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1232 btype, bloc);
1233 Expression_list* vals = new Expression_list();
1234 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1235 Expression* init =
1236 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1237 Translate_context bcontext(gogo, NULL, NULL, NULL);
1238 bcontext.set_is_const();
1239 Bexpression* binit = init->get_backend(&bcontext);
1240 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1241 false, btype, bloc, binit);
1242 }
1243
1244 this->dvar_ = bvar;
1245 return gogo->backend()->var_expression(bvar, loc);
1246 }
1247
1248 // Print a function descriptor expression.
1249
1250 void
do_dump_expression(Ast_dump_context * context) const1251 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1252 {
1253 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1254 }
1255
1256 // Make a function descriptor expression.
1257
1258 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1259 Expression::make_func_descriptor(Named_object* fn)
1260 {
1261 return new Func_descriptor_expression(fn);
1262 }
1263
1264 // Make the function descriptor type, so that it can be converted.
1265
1266 void
make_func_descriptor_type()1267 Expression::make_func_descriptor_type()
1268 {
1269 Func_descriptor_expression::make_func_descriptor_type();
1270 }
1271
1272 // A reference to just the code of a function.
1273
1274 class Func_code_reference_expression : public Expression
1275 {
1276 public:
Func_code_reference_expression(Named_object * function,Location location)1277 Func_code_reference_expression(Named_object* function, Location location)
1278 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1279 function_(function)
1280 { }
1281
1282 protected:
1283 int
do_traverse(Traverse *)1284 do_traverse(Traverse*)
1285 { return TRAVERSE_CONTINUE; }
1286
1287 bool
do_is_immutable() const1288 do_is_immutable() const
1289 { return true; }
1290
1291 Type*
do_type()1292 do_type()
1293 { return Type::make_pointer_type(Type::make_void_type()); }
1294
1295 void
do_determine_type(const Type_context *)1296 do_determine_type(const Type_context*)
1297 { }
1298
1299 Expression*
do_copy()1300 do_copy()
1301 {
1302 return Expression::make_func_code_reference(this->function_,
1303 this->location());
1304 }
1305
1306 Bexpression*
1307 do_get_backend(Translate_context*);
1308
1309 void
do_dump_expression(Ast_dump_context * context) const1310 do_dump_expression(Ast_dump_context* context) const
1311 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1312
1313 private:
1314 // The function.
1315 Named_object* function_;
1316 };
1317
1318 // Get the backend representation for a reference to function code.
1319
1320 Bexpression*
do_get_backend(Translate_context * context)1321 Func_code_reference_expression::do_get_backend(Translate_context* context)
1322 {
1323 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1324 this->location());
1325 }
1326
1327 // Make a reference to the code of a function.
1328
1329 Expression*
make_func_code_reference(Named_object * function,Location location)1330 Expression::make_func_code_reference(Named_object* function, Location location)
1331 {
1332 return new Func_code_reference_expression(function, location);
1333 }
1334
1335 // Class Unknown_expression.
1336
1337 // Return the name of an unknown expression.
1338
1339 const std::string&
name() const1340 Unknown_expression::name() const
1341 {
1342 return this->named_object_->name();
1343 }
1344
1345 // Lower a reference to an unknown name.
1346
1347 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1348 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1349 {
1350 Location location = this->location();
1351 Named_object* no = this->named_object_;
1352 Named_object* real;
1353 if (!no->is_unknown())
1354 real = no;
1355 else
1356 {
1357 real = no->unknown_value()->real_named_object();
1358 if (real == NULL)
1359 {
1360 if (this->is_composite_literal_key_)
1361 return this;
1362 if (!this->no_error_message_)
1363 error_at(location, "reference to undefined name %qs",
1364 this->named_object_->message_name().c_str());
1365 return Expression::make_error(location);
1366 }
1367 }
1368 switch (real->classification())
1369 {
1370 case Named_object::NAMED_OBJECT_CONST:
1371 return Expression::make_const_reference(real, location);
1372 case Named_object::NAMED_OBJECT_TYPE:
1373 return Expression::make_type(real->type_value(), location);
1374 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1375 if (this->is_composite_literal_key_)
1376 return this;
1377 if (!this->no_error_message_)
1378 error_at(location, "reference to undefined type %qs",
1379 real->message_name().c_str());
1380 return Expression::make_error(location);
1381 case Named_object::NAMED_OBJECT_VAR:
1382 real->var_value()->set_is_used();
1383 return Expression::make_var_reference(real, location);
1384 case Named_object::NAMED_OBJECT_FUNC:
1385 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1386 return Expression::make_func_reference(real, NULL, location);
1387 case Named_object::NAMED_OBJECT_PACKAGE:
1388 if (this->is_composite_literal_key_)
1389 return this;
1390 if (!this->no_error_message_)
1391 error_at(location, "unexpected reference to package");
1392 return Expression::make_error(location);
1393 default:
1394 go_unreachable();
1395 }
1396 }
1397
1398 // Dump the ast representation for an unknown expression to a dump context.
1399
1400 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1401 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1402 {
1403 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1404 << ")";
1405 }
1406
1407 // Make a reference to an unknown name.
1408
1409 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1410 Expression::make_unknown_reference(Named_object* no, Location location)
1411 {
1412 return new Unknown_expression(no, location);
1413 }
1414
1415 // A boolean expression.
1416
1417 class Boolean_expression : public Expression
1418 {
1419 public:
Boolean_expression(bool val,Location location)1420 Boolean_expression(bool val, Location location)
1421 : Expression(EXPRESSION_BOOLEAN, location),
1422 val_(val), type_(NULL)
1423 { }
1424
1425 static Expression*
1426 do_import(Import*);
1427
1428 protected:
1429 bool
do_is_constant() const1430 do_is_constant() const
1431 { return true; }
1432
1433 bool
do_is_immutable() const1434 do_is_immutable() const
1435 { return true; }
1436
1437 Type*
1438 do_type();
1439
1440 void
1441 do_determine_type(const Type_context*);
1442
1443 Expression*
do_copy()1444 do_copy()
1445 { return this; }
1446
1447 Bexpression*
do_get_backend(Translate_context * context)1448 do_get_backend(Translate_context* context)
1449 { return context->backend()->boolean_constant_expression(this->val_); }
1450
1451 void
do_export(Export * exp) const1452 do_export(Export* exp) const
1453 { exp->write_c_string(this->val_ ? "true" : "false"); }
1454
1455 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1456 do_dump_expression(Ast_dump_context* ast_dump_context) const
1457 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1458
1459 private:
1460 // The constant.
1461 bool val_;
1462 // The type as determined by context.
1463 Type* type_;
1464 };
1465
1466 // Get the type.
1467
1468 Type*
do_type()1469 Boolean_expression::do_type()
1470 {
1471 if (this->type_ == NULL)
1472 this->type_ = Type::make_boolean_type();
1473 return this->type_;
1474 }
1475
1476 // Set the type from the context.
1477
1478 void
do_determine_type(const Type_context * context)1479 Boolean_expression::do_determine_type(const Type_context* context)
1480 {
1481 if (this->type_ != NULL && !this->type_->is_abstract())
1482 ;
1483 else if (context->type != NULL && context->type->is_boolean_type())
1484 this->type_ = context->type;
1485 else if (!context->may_be_abstract)
1486 this->type_ = Type::lookup_bool_type();
1487 }
1488
1489 // Import a boolean constant.
1490
1491 Expression*
do_import(Import * imp)1492 Boolean_expression::do_import(Import* imp)
1493 {
1494 if (imp->peek_char() == 't')
1495 {
1496 imp->require_c_string("true");
1497 return Expression::make_boolean(true, imp->location());
1498 }
1499 else
1500 {
1501 imp->require_c_string("false");
1502 return Expression::make_boolean(false, imp->location());
1503 }
1504 }
1505
1506 // Make a boolean expression.
1507
1508 Expression*
make_boolean(bool val,Location location)1509 Expression::make_boolean(bool val, Location location)
1510 {
1511 return new Boolean_expression(val, location);
1512 }
1513
1514 // Class String_expression.
1515
1516 // Get the type.
1517
1518 Type*
do_type()1519 String_expression::do_type()
1520 {
1521 if (this->type_ == NULL)
1522 this->type_ = Type::make_string_type();
1523 return this->type_;
1524 }
1525
1526 // Set the type from the context.
1527
1528 void
do_determine_type(const Type_context * context)1529 String_expression::do_determine_type(const Type_context* context)
1530 {
1531 if (this->type_ != NULL && !this->type_->is_abstract())
1532 ;
1533 else if (context->type != NULL && context->type->is_string_type())
1534 this->type_ = context->type;
1535 else if (!context->may_be_abstract)
1536 this->type_ = Type::lookup_string_type();
1537 }
1538
1539 // Build a string constant.
1540
1541 Bexpression*
do_get_backend(Translate_context * context)1542 String_expression::do_get_backend(Translate_context* context)
1543 {
1544 Gogo* gogo = context->gogo();
1545 Btype* btype = Type::make_string_type()->get_backend(gogo);
1546
1547 Location loc = this->location();
1548 std::vector<Bexpression*> init(2);
1549 Bexpression* str_cst =
1550 gogo->backend()->string_constant_expression(this->val_);
1551 init[0] = gogo->backend()->address_expression(str_cst, loc);
1552
1553 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1554 mpz_t lenval;
1555 mpz_init_set_ui(lenval, this->val_.length());
1556 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1557 mpz_clear(lenval);
1558
1559 return gogo->backend()->constructor_expression(btype, init, loc);
1560 }
1561
1562 // Write string literal to string dump.
1563
1564 void
export_string(String_dump * exp,const String_expression * str)1565 String_expression::export_string(String_dump* exp,
1566 const String_expression* str)
1567 {
1568 std::string s;
1569 s.reserve(str->val_.length() * 4 + 2);
1570 s += '"';
1571 for (std::string::const_iterator p = str->val_.begin();
1572 p != str->val_.end();
1573 ++p)
1574 {
1575 if (*p == '\\' || *p == '"')
1576 {
1577 s += '\\';
1578 s += *p;
1579 }
1580 else if (*p >= 0x20 && *p < 0x7f)
1581 s += *p;
1582 else if (*p == '\n')
1583 s += "\\n";
1584 else if (*p == '\t')
1585 s += "\\t";
1586 else
1587 {
1588 s += "\\x";
1589 unsigned char c = *p;
1590 unsigned int dig = c >> 4;
1591 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1592 dig = c & 0xf;
1593 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1594 }
1595 }
1596 s += '"';
1597 exp->write_string(s);
1598 }
1599
1600 // Export a string expression.
1601
1602 void
do_export(Export * exp) const1603 String_expression::do_export(Export* exp) const
1604 {
1605 String_expression::export_string(exp, this);
1606 }
1607
1608 // Import a string expression.
1609
1610 Expression*
do_import(Import * imp)1611 String_expression::do_import(Import* imp)
1612 {
1613 imp->require_c_string("\"");
1614 std::string val;
1615 while (true)
1616 {
1617 int c = imp->get_char();
1618 if (c == '"' || c == -1)
1619 break;
1620 if (c != '\\')
1621 val += static_cast<char>(c);
1622 else
1623 {
1624 c = imp->get_char();
1625 if (c == '\\' || c == '"')
1626 val += static_cast<char>(c);
1627 else if (c == 'n')
1628 val += '\n';
1629 else if (c == 't')
1630 val += '\t';
1631 else if (c == 'x')
1632 {
1633 c = imp->get_char();
1634 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1635 c = imp->get_char();
1636 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1637 char v = (vh << 4) | vl;
1638 val += v;
1639 }
1640 else
1641 {
1642 error_at(imp->location(), "bad string constant");
1643 return Expression::make_error(imp->location());
1644 }
1645 }
1646 }
1647 return Expression::make_string(val, imp->location());
1648 }
1649
1650 // Ast dump for string expression.
1651
1652 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1653 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1654 {
1655 String_expression::export_string(ast_dump_context, this);
1656 }
1657
1658 // Make a string expression.
1659
1660 Expression*
make_string(const std::string & val,Location location)1661 Expression::make_string(const std::string& val, Location location)
1662 {
1663 return new String_expression(val, location);
1664 }
1665
1666 // An expression that evaluates to some characteristic of a string.
1667 // This is used when indexing, bound-checking, or nil checking a string.
1668
1669 class String_info_expression : public Expression
1670 {
1671 public:
String_info_expression(Expression * string,String_info string_info,Location location)1672 String_info_expression(Expression* string, String_info string_info,
1673 Location location)
1674 : Expression(EXPRESSION_STRING_INFO, location),
1675 string_(string), string_info_(string_info)
1676 { }
1677
1678 protected:
1679 Type*
1680 do_type();
1681
1682 void
do_determine_type(const Type_context *)1683 do_determine_type(const Type_context*)
1684 { go_unreachable(); }
1685
1686 Expression*
do_copy()1687 do_copy()
1688 {
1689 return new String_info_expression(this->string_->copy(), this->string_info_,
1690 this->location());
1691 }
1692
1693 Bexpression*
1694 do_get_backend(Translate_context* context);
1695
1696 void
1697 do_dump_expression(Ast_dump_context*) const;
1698
1699 void
do_issue_nil_check()1700 do_issue_nil_check()
1701 { this->string_->issue_nil_check(); }
1702
1703 private:
1704 // The string for which we are getting information.
1705 Expression* string_;
1706 // What information we want.
1707 String_info string_info_;
1708 };
1709
1710 // Return the type of the string info.
1711
1712 Type*
do_type()1713 String_info_expression::do_type()
1714 {
1715 switch (this->string_info_)
1716 {
1717 case STRING_INFO_DATA:
1718 {
1719 Type* byte_type = Type::lookup_integer_type("uint8");
1720 return Type::make_pointer_type(byte_type);
1721 }
1722 case STRING_INFO_LENGTH:
1723 return Type::lookup_integer_type("int");
1724 default:
1725 go_unreachable();
1726 }
1727 }
1728
1729 // Return string information in GENERIC.
1730
1731 Bexpression*
do_get_backend(Translate_context * context)1732 String_info_expression::do_get_backend(Translate_context* context)
1733 {
1734 Gogo* gogo = context->gogo();
1735
1736 Bexpression* bstring = this->string_->get_backend(context);
1737 switch (this->string_info_)
1738 {
1739 case STRING_INFO_DATA:
1740 case STRING_INFO_LENGTH:
1741 return gogo->backend()->struct_field_expression(bstring,
1742 this->string_info_,
1743 this->location());
1744 break;
1745 default:
1746 go_unreachable();
1747 }
1748 }
1749
1750 // Dump ast representation for a type info expression.
1751
1752 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1753 String_info_expression::do_dump_expression(
1754 Ast_dump_context* ast_dump_context) const
1755 {
1756 ast_dump_context->ostream() << "stringinfo(";
1757 this->string_->dump_expression(ast_dump_context);
1758 ast_dump_context->ostream() << ",";
1759 ast_dump_context->ostream() <<
1760 (this->string_info_ == STRING_INFO_DATA ? "data"
1761 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1762 : "unknown");
1763 ast_dump_context->ostream() << ")";
1764 }
1765
1766 // Make a string info expression.
1767
1768 Expression*
make_string_info(Expression * string,String_info string_info,Location location)1769 Expression::make_string_info(Expression* string, String_info string_info,
1770 Location location)
1771 {
1772 return new String_info_expression(string, string_info, location);
1773 }
1774
1775 // Make an integer expression.
1776
1777 class Integer_expression : public Expression
1778 {
1779 public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)1780 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1781 Location location)
1782 : Expression(EXPRESSION_INTEGER, location),
1783 type_(type), is_character_constant_(is_character_constant)
1784 { mpz_init_set(this->val_, *val); }
1785
1786 static Expression*
1787 do_import(Import*);
1788
1789 // Write VAL to string dump.
1790 static void
1791 export_integer(String_dump* exp, const mpz_t val);
1792
1793 // Write VAL to dump context.
1794 static void
1795 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1796
1797 protected:
1798 bool
do_is_constant() const1799 do_is_constant() const
1800 { return true; }
1801
1802 bool
do_is_immutable() const1803 do_is_immutable() const
1804 { return true; }
1805
1806 bool
1807 do_numeric_constant_value(Numeric_constant* nc) const;
1808
1809 Type*
1810 do_type();
1811
1812 void
1813 do_determine_type(const Type_context* context);
1814
1815 void
1816 do_check_types(Gogo*);
1817
1818 Bexpression*
1819 do_get_backend(Translate_context*);
1820
1821 Expression*
do_copy()1822 do_copy()
1823 {
1824 if (this->is_character_constant_)
1825 return Expression::make_character(&this->val_, this->type_,
1826 this->location());
1827 else
1828 return Expression::make_integer_z(&this->val_, this->type_,
1829 this->location());
1830 }
1831
1832 void
1833 do_export(Export*) const;
1834
1835 void
1836 do_dump_expression(Ast_dump_context*) const;
1837
1838 private:
1839 // The integer value.
1840 mpz_t val_;
1841 // The type so far.
1842 Type* type_;
1843 // Whether this is a character constant.
1844 bool is_character_constant_;
1845 };
1846
1847 // Return a numeric constant for this expression. We have to mark
1848 // this as a character when appropriate.
1849
1850 bool
do_numeric_constant_value(Numeric_constant * nc) const1851 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1852 {
1853 if (this->is_character_constant_)
1854 nc->set_rune(this->type_, this->val_);
1855 else
1856 nc->set_int(this->type_, this->val_);
1857 return true;
1858 }
1859
1860 // Return the current type. If we haven't set the type yet, we return
1861 // an abstract integer type.
1862
1863 Type*
do_type()1864 Integer_expression::do_type()
1865 {
1866 if (this->type_ == NULL)
1867 {
1868 if (this->is_character_constant_)
1869 this->type_ = Type::make_abstract_character_type();
1870 else
1871 this->type_ = Type::make_abstract_integer_type();
1872 }
1873 return this->type_;
1874 }
1875
1876 // Set the type of the integer value. Here we may switch from an
1877 // abstract type to a real type.
1878
1879 void
do_determine_type(const Type_context * context)1880 Integer_expression::do_determine_type(const Type_context* context)
1881 {
1882 if (this->type_ != NULL && !this->type_->is_abstract())
1883 ;
1884 else if (context->type != NULL && context->type->is_numeric_type())
1885 this->type_ = context->type;
1886 else if (!context->may_be_abstract)
1887 {
1888 if (this->is_character_constant_)
1889 this->type_ = Type::lookup_integer_type("int32");
1890 else
1891 this->type_ = Type::lookup_integer_type("int");
1892 }
1893 }
1894
1895 // Check the type of an integer constant.
1896
1897 void
do_check_types(Gogo *)1898 Integer_expression::do_check_types(Gogo*)
1899 {
1900 Type* type = this->type_;
1901 if (type == NULL)
1902 return;
1903 Numeric_constant nc;
1904 if (this->is_character_constant_)
1905 nc.set_rune(NULL, this->val_);
1906 else
1907 nc.set_int(NULL, this->val_);
1908 if (!nc.set_type(type, true, this->location()))
1909 this->set_is_error();
1910 }
1911
1912 // Get the backend representation for an integer constant.
1913
1914 Bexpression*
do_get_backend(Translate_context * context)1915 Integer_expression::do_get_backend(Translate_context* context)
1916 {
1917 if (this->is_error_expression()
1918 || (this->type_ != NULL && this->type_->is_error_type()))
1919 {
1920 go_assert(saw_errors());
1921 return context->gogo()->backend()->error_expression();
1922 }
1923
1924 Type* resolved_type = NULL;
1925 if (this->type_ != NULL && !this->type_->is_abstract())
1926 resolved_type = this->type_;
1927 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1928 {
1929 // We are converting to an abstract floating point type.
1930 resolved_type = Type::lookup_float_type("float64");
1931 }
1932 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1933 {
1934 // We are converting to an abstract complex type.
1935 resolved_type = Type::lookup_complex_type("complex128");
1936 }
1937 else
1938 {
1939 // If we still have an abstract type here, then this is being
1940 // used in a constant expression which didn't get reduced for
1941 // some reason. Use a type which will fit the value. We use <,
1942 // not <=, because we need an extra bit for the sign bit.
1943 int bits = mpz_sizeinbase(this->val_, 2);
1944 Type* int_type = Type::lookup_integer_type("int");
1945 if (bits < int_type->integer_type()->bits())
1946 resolved_type = int_type;
1947 else if (bits < 64)
1948 resolved_type = Type::lookup_integer_type("int64");
1949 else
1950 {
1951 if (!saw_errors())
1952 error_at(this->location(),
1953 "unknown type for large integer constant");
1954 return context->gogo()->backend()->error_expression();
1955 }
1956 }
1957 Numeric_constant nc;
1958 nc.set_int(resolved_type, this->val_);
1959 return Expression::backend_numeric_constant_expression(context, &nc);
1960 }
1961
1962 // Write VAL to export data.
1963
1964 void
export_integer(String_dump * exp,const mpz_t val)1965 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1966 {
1967 char* s = mpz_get_str(NULL, 10, val);
1968 exp->write_c_string(s);
1969 free(s);
1970 }
1971
1972 // Export an integer in a constant expression.
1973
1974 void
do_export(Export * exp) const1975 Integer_expression::do_export(Export* exp) const
1976 {
1977 Integer_expression::export_integer(exp, this->val_);
1978 if (this->is_character_constant_)
1979 exp->write_c_string("'");
1980 // A trailing space lets us reliably identify the end of the number.
1981 exp->write_c_string(" ");
1982 }
1983
1984 // Import an integer, floating point, or complex value. This handles
1985 // all these types because they all start with digits.
1986
1987 Expression*
do_import(Import * imp)1988 Integer_expression::do_import(Import* imp)
1989 {
1990 std::string num = imp->read_identifier();
1991 imp->require_c_string(" ");
1992 if (!num.empty() && num[num.length() - 1] == 'i')
1993 {
1994 mpfr_t real;
1995 size_t plus_pos = num.find('+', 1);
1996 size_t minus_pos = num.find('-', 1);
1997 size_t pos;
1998 if (plus_pos == std::string::npos)
1999 pos = minus_pos;
2000 else if (minus_pos == std::string::npos)
2001 pos = plus_pos;
2002 else
2003 {
2004 error_at(imp->location(), "bad number in import data: %qs",
2005 num.c_str());
2006 return Expression::make_error(imp->location());
2007 }
2008 if (pos == std::string::npos)
2009 mpfr_set_ui(real, 0, GMP_RNDN);
2010 else
2011 {
2012 std::string real_str = num.substr(0, pos);
2013 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2014 {
2015 error_at(imp->location(), "bad number in import data: %qs",
2016 real_str.c_str());
2017 return Expression::make_error(imp->location());
2018 }
2019 }
2020
2021 std::string imag_str;
2022 if (pos == std::string::npos)
2023 imag_str = num;
2024 else
2025 imag_str = num.substr(pos);
2026 imag_str = imag_str.substr(0, imag_str.size() - 1);
2027 mpfr_t imag;
2028 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2029 {
2030 error_at(imp->location(), "bad number in import data: %qs",
2031 imag_str.c_str());
2032 return Expression::make_error(imp->location());
2033 }
2034 mpc_t cval;
2035 mpc_init2(cval, mpc_precision);
2036 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2037 mpfr_clear(real);
2038 mpfr_clear(imag);
2039 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2040 mpc_clear(cval);
2041 return ret;
2042 }
2043 else if (num.find('.') == std::string::npos
2044 && num.find('E') == std::string::npos)
2045 {
2046 bool is_character_constant = (!num.empty()
2047 && num[num.length() - 1] == '\'');
2048 if (is_character_constant)
2049 num = num.substr(0, num.length() - 1);
2050 mpz_t val;
2051 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2052 {
2053 error_at(imp->location(), "bad number in import data: %qs",
2054 num.c_str());
2055 return Expression::make_error(imp->location());
2056 }
2057 Expression* ret;
2058 if (is_character_constant)
2059 ret = Expression::make_character(&val, NULL, imp->location());
2060 else
2061 ret = Expression::make_integer_z(&val, NULL, imp->location());
2062 mpz_clear(val);
2063 return ret;
2064 }
2065 else
2066 {
2067 mpfr_t val;
2068 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2069 {
2070 error_at(imp->location(), "bad number in import data: %qs",
2071 num.c_str());
2072 return Expression::make_error(imp->location());
2073 }
2074 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2075 mpfr_clear(val);
2076 return ret;
2077 }
2078 }
2079 // Ast dump for integer expression.
2080
2081 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2082 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2083 {
2084 if (this->is_character_constant_)
2085 ast_dump_context->ostream() << '\'';
2086 Integer_expression::export_integer(ast_dump_context, this->val_);
2087 if (this->is_character_constant_)
2088 ast_dump_context->ostream() << '\'';
2089 }
2090
2091 // Build a new integer value from a multi-precision integer.
2092
2093 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2094 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2095 {
2096 return new Integer_expression(val, type, false, location);
2097 }
2098
2099 // Build a new integer value from an unsigned long.
2100
2101 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2102 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2103 {
2104 mpz_t zval;
2105 mpz_init_set_ui(zval, val);
2106 Expression* ret = Expression::make_integer_z(&zval, type, location);
2107 mpz_clear(zval);
2108 return ret;
2109 }
2110
2111 // Build a new integer value from a signed long.
2112
2113 Expression*
make_integer_sl(long val,Type * type,Location location)2114 Expression::make_integer_sl(long val, Type *type, Location location)
2115 {
2116 mpz_t zval;
2117 mpz_init_set_si(zval, val);
2118 Expression* ret = Expression::make_integer_z(&zval, type, location);
2119 mpz_clear(zval);
2120 return ret;
2121 }
2122
2123 // Store an int64_t in an uninitialized mpz_t.
2124
2125 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2126 set_mpz_from_int64(mpz_t* zval, int64_t val)
2127 {
2128 if (val >= 0)
2129 {
2130 unsigned long ul = static_cast<unsigned long>(val);
2131 if (static_cast<int64_t>(ul) == val)
2132 {
2133 mpz_init_set_ui(*zval, ul);
2134 return;
2135 }
2136 }
2137 uint64_t uv;
2138 if (val >= 0)
2139 uv = static_cast<uint64_t>(val);
2140 else
2141 uv = static_cast<uint64_t>(- val);
2142 unsigned long ul = uv & 0xffffffffUL;
2143 mpz_init_set_ui(*zval, ul);
2144 mpz_t hval;
2145 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2146 mpz_mul_2exp(hval, hval, 32);
2147 mpz_add(*zval, *zval, hval);
2148 mpz_clear(hval);
2149 if (val < 0)
2150 mpz_neg(*zval, *zval);
2151 }
2152
2153 // Build a new integer value from an int64_t.
2154
2155 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2156 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2157 {
2158 mpz_t zval;
2159 set_mpz_from_int64(&zval, val);
2160 Expression* ret = Expression::make_integer_z(&zval, type, location);
2161 mpz_clear(zval);
2162 return ret;
2163 }
2164
2165 // Build a new character constant value.
2166
2167 Expression*
make_character(const mpz_t * val,Type * type,Location location)2168 Expression::make_character(const mpz_t* val, Type* type, Location location)
2169 {
2170 return new Integer_expression(val, type, true, location);
2171 }
2172
2173 // Floats.
2174
2175 class Float_expression : public Expression
2176 {
2177 public:
Float_expression(const mpfr_t * val,Type * type,Location location)2178 Float_expression(const mpfr_t* val, Type* type, Location location)
2179 : Expression(EXPRESSION_FLOAT, location),
2180 type_(type)
2181 {
2182 mpfr_init_set(this->val_, *val, GMP_RNDN);
2183 }
2184
2185 // Write VAL to export data.
2186 static void
2187 export_float(String_dump* exp, const mpfr_t val);
2188
2189 // Write VAL to dump file.
2190 static void
2191 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2192
2193 protected:
2194 bool
do_is_constant() const2195 do_is_constant() const
2196 { return true; }
2197
2198 bool
do_is_immutable() const2199 do_is_immutable() const
2200 { return true; }
2201
2202 bool
do_numeric_constant_value(Numeric_constant * nc) const2203 do_numeric_constant_value(Numeric_constant* nc) const
2204 {
2205 nc->set_float(this->type_, this->val_);
2206 return true;
2207 }
2208
2209 Type*
2210 do_type();
2211
2212 void
2213 do_determine_type(const Type_context*);
2214
2215 void
2216 do_check_types(Gogo*);
2217
2218 Expression*
do_copy()2219 do_copy()
2220 { return Expression::make_float(&this->val_, this->type_,
2221 this->location()); }
2222
2223 Bexpression*
2224 do_get_backend(Translate_context*);
2225
2226 void
2227 do_export(Export*) const;
2228
2229 void
2230 do_dump_expression(Ast_dump_context*) const;
2231
2232 private:
2233 // The floating point value.
2234 mpfr_t val_;
2235 // The type so far.
2236 Type* type_;
2237 };
2238
2239 // Return the current type. If we haven't set the type yet, we return
2240 // an abstract float type.
2241
2242 Type*
do_type()2243 Float_expression::do_type()
2244 {
2245 if (this->type_ == NULL)
2246 this->type_ = Type::make_abstract_float_type();
2247 return this->type_;
2248 }
2249
2250 // Set the type of the float value. Here we may switch from an
2251 // abstract type to a real type.
2252
2253 void
do_determine_type(const Type_context * context)2254 Float_expression::do_determine_type(const Type_context* context)
2255 {
2256 if (this->type_ != NULL && !this->type_->is_abstract())
2257 ;
2258 else if (context->type != NULL
2259 && (context->type->integer_type() != NULL
2260 || context->type->float_type() != NULL
2261 || context->type->complex_type() != NULL))
2262 this->type_ = context->type;
2263 else if (!context->may_be_abstract)
2264 this->type_ = Type::lookup_float_type("float64");
2265 }
2266
2267 // Check the type of a float value.
2268
2269 void
do_check_types(Gogo *)2270 Float_expression::do_check_types(Gogo*)
2271 {
2272 Type* type = this->type_;
2273 if (type == NULL)
2274 return;
2275 Numeric_constant nc;
2276 nc.set_float(NULL, this->val_);
2277 if (!nc.set_type(this->type_, true, this->location()))
2278 this->set_is_error();
2279 }
2280
2281 // Get the backend representation for a float constant.
2282
2283 Bexpression*
do_get_backend(Translate_context * context)2284 Float_expression::do_get_backend(Translate_context* context)
2285 {
2286 if (this->is_error_expression()
2287 || (this->type_ != NULL && this->type_->is_error_type()))
2288 {
2289 go_assert(saw_errors());
2290 return context->gogo()->backend()->error_expression();
2291 }
2292
2293 Type* resolved_type;
2294 if (this->type_ != NULL && !this->type_->is_abstract())
2295 resolved_type = this->type_;
2296 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2297 {
2298 // We have an abstract integer type. We just hope for the best.
2299 resolved_type = Type::lookup_integer_type("int");
2300 }
2301 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2302 {
2303 // We are converting to an abstract complex type.
2304 resolved_type = Type::lookup_complex_type("complex128");
2305 }
2306 else
2307 {
2308 // If we still have an abstract type here, then this is being
2309 // used in a constant expression which didn't get reduced. We
2310 // just use float64 and hope for the best.
2311 resolved_type = Type::lookup_float_type("float64");
2312 }
2313
2314 Numeric_constant nc;
2315 nc.set_float(resolved_type, this->val_);
2316 return Expression::backend_numeric_constant_expression(context, &nc);
2317 }
2318
2319 // Write a floating point number to a string dump.
2320
2321 void
export_float(String_dump * exp,const mpfr_t val)2322 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2323 {
2324 mp_exp_t exponent;
2325 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2326 if (*s == '-')
2327 exp->write_c_string("-");
2328 exp->write_c_string("0.");
2329 exp->write_c_string(*s == '-' ? s + 1 : s);
2330 mpfr_free_str(s);
2331 char buf[30];
2332 snprintf(buf, sizeof buf, "E%ld", exponent);
2333 exp->write_c_string(buf);
2334 }
2335
2336 // Export a floating point number in a constant expression.
2337
2338 void
do_export(Export * exp) const2339 Float_expression::do_export(Export* exp) const
2340 {
2341 Float_expression::export_float(exp, this->val_);
2342 // A trailing space lets us reliably identify the end of the number.
2343 exp->write_c_string(" ");
2344 }
2345
2346 // Dump a floating point number to the dump file.
2347
2348 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2349 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2350 {
2351 Float_expression::export_float(ast_dump_context, this->val_);
2352 }
2353
2354 // Make a float expression.
2355
2356 Expression*
make_float(const mpfr_t * val,Type * type,Location location)2357 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2358 {
2359 return new Float_expression(val, type, location);
2360 }
2361
2362 // Complex numbers.
2363
2364 class Complex_expression : public Expression
2365 {
2366 public:
Complex_expression(const mpc_t * val,Type * type,Location location)2367 Complex_expression(const mpc_t* val, Type* type, Location location)
2368 : Expression(EXPRESSION_COMPLEX, location),
2369 type_(type)
2370 {
2371 mpc_init2(this->val_, mpc_precision);
2372 mpc_set(this->val_, *val, MPC_RNDNN);
2373 }
2374
2375 // Write VAL to string dump.
2376 static void
2377 export_complex(String_dump* exp, const mpc_t val);
2378
2379 // Write REAL/IMAG to dump context.
2380 static void
2381 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2382
2383 protected:
2384 bool
do_is_constant() const2385 do_is_constant() const
2386 { return true; }
2387
2388 bool
do_is_immutable() const2389 do_is_immutable() const
2390 { return true; }
2391
2392 bool
do_numeric_constant_value(Numeric_constant * nc) const2393 do_numeric_constant_value(Numeric_constant* nc) const
2394 {
2395 nc->set_complex(this->type_, this->val_);
2396 return true;
2397 }
2398
2399 Type*
2400 do_type();
2401
2402 void
2403 do_determine_type(const Type_context*);
2404
2405 void
2406 do_check_types(Gogo*);
2407
2408 Expression*
do_copy()2409 do_copy()
2410 {
2411 return Expression::make_complex(&this->val_, this->type_,
2412 this->location());
2413 }
2414
2415 Bexpression*
2416 do_get_backend(Translate_context*);
2417
2418 void
2419 do_export(Export*) const;
2420
2421 void
2422 do_dump_expression(Ast_dump_context*) const;
2423
2424 private:
2425 // The complex value.
2426 mpc_t val_;
2427 // The type if known.
2428 Type* type_;
2429 };
2430
2431 // Return the current type. If we haven't set the type yet, we return
2432 // an abstract complex type.
2433
2434 Type*
do_type()2435 Complex_expression::do_type()
2436 {
2437 if (this->type_ == NULL)
2438 this->type_ = Type::make_abstract_complex_type();
2439 return this->type_;
2440 }
2441
2442 // Set the type of the complex value. Here we may switch from an
2443 // abstract type to a real type.
2444
2445 void
do_determine_type(const Type_context * context)2446 Complex_expression::do_determine_type(const Type_context* context)
2447 {
2448 if (this->type_ != NULL && !this->type_->is_abstract())
2449 ;
2450 else if (context->type != NULL && context->type->is_numeric_type())
2451 this->type_ = context->type;
2452 else if (!context->may_be_abstract)
2453 this->type_ = Type::lookup_complex_type("complex128");
2454 }
2455
2456 // Check the type of a complex value.
2457
2458 void
do_check_types(Gogo *)2459 Complex_expression::do_check_types(Gogo*)
2460 {
2461 Type* type = this->type_;
2462 if (type == NULL)
2463 return;
2464 Numeric_constant nc;
2465 nc.set_complex(NULL, this->val_);
2466 if (!nc.set_type(this->type_, true, this->location()))
2467 this->set_is_error();
2468 }
2469
2470 // Get the backend representation for a complex constant.
2471
2472 Bexpression*
do_get_backend(Translate_context * context)2473 Complex_expression::do_get_backend(Translate_context* context)
2474 {
2475 if (this->is_error_expression()
2476 || (this->type_ != NULL && this->type_->is_error_type()))
2477 {
2478 go_assert(saw_errors());
2479 return context->gogo()->backend()->error_expression();
2480 }
2481
2482 Type* resolved_type;
2483 if (this->type_ != NULL && !this->type_->is_abstract())
2484 resolved_type = this->type_;
2485 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2486 {
2487 // We are converting to an abstract integer type.
2488 resolved_type = Type::lookup_integer_type("int");
2489 }
2490 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2491 {
2492 // We are converting to an abstract float type.
2493 resolved_type = Type::lookup_float_type("float64");
2494 }
2495 else
2496 {
2497 // If we still have an abstract type here, this is being
2498 // used in a constant expression which didn't get reduced. We
2499 // just use complex128 and hope for the best.
2500 resolved_type = Type::lookup_complex_type("complex128");
2501 }
2502
2503 Numeric_constant nc;
2504 nc.set_complex(resolved_type, this->val_);
2505 return Expression::backend_numeric_constant_expression(context, &nc);
2506 }
2507
2508 // Write REAL/IMAG to export data.
2509
2510 void
export_complex(String_dump * exp,const mpc_t val)2511 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2512 {
2513 if (!mpfr_zero_p(mpc_realref(val)))
2514 {
2515 Float_expression::export_float(exp, mpc_realref(val));
2516 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2517 exp->write_c_string("+");
2518 }
2519 Float_expression::export_float(exp, mpc_imagref(val));
2520 exp->write_c_string("i");
2521 }
2522
2523 // Export a complex number in a constant expression.
2524
2525 void
do_export(Export * exp) const2526 Complex_expression::do_export(Export* exp) const
2527 {
2528 Complex_expression::export_complex(exp, this->val_);
2529 // A trailing space lets us reliably identify the end of the number.
2530 exp->write_c_string(" ");
2531 }
2532
2533 // Dump a complex expression to the dump file.
2534
2535 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2536 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2537 {
2538 Complex_expression::export_complex(ast_dump_context, this->val_);
2539 }
2540
2541 // Make a complex expression.
2542
2543 Expression*
make_complex(const mpc_t * val,Type * type,Location location)2544 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2545 {
2546 return new Complex_expression(val, type, location);
2547 }
2548
2549 // Find a named object in an expression.
2550
2551 class Find_named_object : public Traverse
2552 {
2553 public:
Find_named_object(Named_object * no)2554 Find_named_object(Named_object* no)
2555 : Traverse(traverse_expressions),
2556 no_(no), found_(false)
2557 { }
2558
2559 // Whether we found the object.
2560 bool
found() const2561 found() const
2562 { return this->found_; }
2563
2564 protected:
2565 int
2566 expression(Expression**);
2567
2568 private:
2569 // The object we are looking for.
2570 Named_object* no_;
2571 // Whether we found it.
2572 bool found_;
2573 };
2574
2575 // A reference to a const in an expression.
2576
2577 class Const_expression : public Expression
2578 {
2579 public:
Const_expression(Named_object * constant,Location location)2580 Const_expression(Named_object* constant, Location location)
2581 : Expression(EXPRESSION_CONST_REFERENCE, location),
2582 constant_(constant), type_(NULL), seen_(false)
2583 { }
2584
2585 Named_object*
named_object()2586 named_object()
2587 { return this->constant_; }
2588
2589 // Check that the initializer does not refer to the constant itself.
2590 void
2591 check_for_init_loop();
2592
2593 protected:
2594 int
2595 do_traverse(Traverse*);
2596
2597 Expression*
2598 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2599
2600 bool
do_is_constant() const2601 do_is_constant() const
2602 { return true; }
2603
2604 bool
do_is_immutable() const2605 do_is_immutable() const
2606 { return true; }
2607
2608 bool
2609 do_numeric_constant_value(Numeric_constant* nc) const;
2610
2611 bool
2612 do_string_constant_value(std::string* val) const;
2613
2614 Type*
2615 do_type();
2616
2617 // The type of a const is set by the declaration, not the use.
2618 void
2619 do_determine_type(const Type_context*);
2620
2621 void
2622 do_check_types(Gogo*);
2623
2624 Expression*
do_copy()2625 do_copy()
2626 { return this; }
2627
2628 Bexpression*
2629 do_get_backend(Translate_context* context);
2630
2631 // When exporting a reference to a const as part of a const
2632 // expression, we export the value. We ignore the fact that it has
2633 // a name.
2634 void
do_export(Export * exp) const2635 do_export(Export* exp) const
2636 { this->constant_->const_value()->expr()->export_expression(exp); }
2637
2638 void
2639 do_dump_expression(Ast_dump_context*) const;
2640
2641 private:
2642 // The constant.
2643 Named_object* constant_;
2644 // The type of this reference. This is used if the constant has an
2645 // abstract type.
2646 Type* type_;
2647 // Used to prevent infinite recursion when a constant incorrectly
2648 // refers to itself.
2649 mutable bool seen_;
2650 };
2651
2652 // Traversal.
2653
2654 int
do_traverse(Traverse * traverse)2655 Const_expression::do_traverse(Traverse* traverse)
2656 {
2657 if (this->type_ != NULL)
2658 return Type::traverse(this->type_, traverse);
2659 return TRAVERSE_CONTINUE;
2660 }
2661
2662 // Lower a constant expression. This is where we convert the
2663 // predeclared constant iota into an integer value.
2664
2665 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)2666 Const_expression::do_lower(Gogo* gogo, Named_object*,
2667 Statement_inserter*, int iota_value)
2668 {
2669 if (this->constant_->const_value()->expr()->classification()
2670 == EXPRESSION_IOTA)
2671 {
2672 if (iota_value == -1)
2673 {
2674 error_at(this->location(),
2675 "iota is only defined in const declarations");
2676 iota_value = 0;
2677 }
2678 return Expression::make_integer_ul(iota_value, NULL, this->location());
2679 }
2680
2681 // Make sure that the constant itself has been lowered.
2682 gogo->lower_constant(this->constant_);
2683
2684 return this;
2685 }
2686
2687 // Return a numeric constant value.
2688
2689 bool
do_numeric_constant_value(Numeric_constant * nc) const2690 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2691 {
2692 if (this->seen_)
2693 return false;
2694
2695 Expression* e = this->constant_->const_value()->expr();
2696
2697 this->seen_ = true;
2698
2699 bool r = e->numeric_constant_value(nc);
2700
2701 this->seen_ = false;
2702
2703 Type* ctype;
2704 if (this->type_ != NULL)
2705 ctype = this->type_;
2706 else
2707 ctype = this->constant_->const_value()->type();
2708 if (r && ctype != NULL)
2709 {
2710 if (!nc->set_type(ctype, false, this->location()))
2711 return false;
2712 }
2713
2714 return r;
2715 }
2716
2717 bool
do_string_constant_value(std::string * val) const2718 Const_expression::do_string_constant_value(std::string* val) const
2719 {
2720 if (this->seen_)
2721 return false;
2722
2723 Expression* e = this->constant_->const_value()->expr();
2724
2725 this->seen_ = true;
2726 bool ok = e->string_constant_value(val);
2727 this->seen_ = false;
2728
2729 return ok;
2730 }
2731
2732 // Return the type of the const reference.
2733
2734 Type*
do_type()2735 Const_expression::do_type()
2736 {
2737 if (this->type_ != NULL)
2738 return this->type_;
2739
2740 Named_constant* nc = this->constant_->const_value();
2741
2742 if (this->seen_ || nc->lowering())
2743 {
2744 this->report_error(_("constant refers to itself"));
2745 this->type_ = Type::make_error_type();
2746 return this->type_;
2747 }
2748
2749 this->seen_ = true;
2750
2751 Type* ret = nc->type();
2752
2753 if (ret != NULL)
2754 {
2755 this->seen_ = false;
2756 return ret;
2757 }
2758
2759 // During parsing, a named constant may have a NULL type, but we
2760 // must not return a NULL type here.
2761 ret = nc->expr()->type();
2762
2763 this->seen_ = false;
2764
2765 return ret;
2766 }
2767
2768 // Set the type of the const reference.
2769
2770 void
do_determine_type(const Type_context * context)2771 Const_expression::do_determine_type(const Type_context* context)
2772 {
2773 Type* ctype = this->constant_->const_value()->type();
2774 Type* cetype = (ctype != NULL
2775 ? ctype
2776 : this->constant_->const_value()->expr()->type());
2777 if (ctype != NULL && !ctype->is_abstract())
2778 ;
2779 else if (context->type != NULL
2780 && context->type->is_numeric_type()
2781 && cetype->is_numeric_type())
2782 this->type_ = context->type;
2783 else if (context->type != NULL
2784 && context->type->is_string_type()
2785 && cetype->is_string_type())
2786 this->type_ = context->type;
2787 else if (context->type != NULL
2788 && context->type->is_boolean_type()
2789 && cetype->is_boolean_type())
2790 this->type_ = context->type;
2791 else if (!context->may_be_abstract)
2792 {
2793 if (cetype->is_abstract())
2794 cetype = cetype->make_non_abstract_type();
2795 this->type_ = cetype;
2796 }
2797 }
2798
2799 // Check for a loop in which the initializer of a constant refers to
2800 // the constant itself.
2801
2802 void
check_for_init_loop()2803 Const_expression::check_for_init_loop()
2804 {
2805 if (this->type_ != NULL && this->type_->is_error())
2806 return;
2807
2808 if (this->seen_)
2809 {
2810 this->report_error(_("constant refers to itself"));
2811 this->type_ = Type::make_error_type();
2812 return;
2813 }
2814
2815 Expression* init = this->constant_->const_value()->expr();
2816 Find_named_object find_named_object(this->constant_);
2817
2818 this->seen_ = true;
2819 Expression::traverse(&init, &find_named_object);
2820 this->seen_ = false;
2821
2822 if (find_named_object.found())
2823 {
2824 if (this->type_ == NULL || !this->type_->is_error())
2825 {
2826 this->report_error(_("constant refers to itself"));
2827 this->type_ = Type::make_error_type();
2828 }
2829 return;
2830 }
2831 }
2832
2833 // Check types of a const reference.
2834
2835 void
do_check_types(Gogo *)2836 Const_expression::do_check_types(Gogo*)
2837 {
2838 if (this->type_ != NULL && this->type_->is_error())
2839 return;
2840
2841 this->check_for_init_loop();
2842
2843 // Check that numeric constant fits in type.
2844 if (this->type_ != NULL && this->type_->is_numeric_type())
2845 {
2846 Numeric_constant nc;
2847 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2848 {
2849 if (!nc.set_type(this->type_, true, this->location()))
2850 this->set_is_error();
2851 }
2852 }
2853 }
2854
2855 // Return the backend representation for a const reference.
2856
2857 Bexpression*
do_get_backend(Translate_context * context)2858 Const_expression::do_get_backend(Translate_context* context)
2859 {
2860 if (this->is_error_expression()
2861 || (this->type_ != NULL && this->type_->is_error()))
2862 {
2863 go_assert(saw_errors());
2864 return context->backend()->error_expression();
2865 }
2866
2867 // If the type has been set for this expression, but the underlying
2868 // object is an abstract int or float, we try to get the abstract
2869 // value. Otherwise we may lose something in the conversion.
2870 Expression* expr = this->constant_->const_value()->expr();
2871 if (this->type_ != NULL
2872 && this->type_->is_numeric_type()
2873 && (this->constant_->const_value()->type() == NULL
2874 || this->constant_->const_value()->type()->is_abstract()))
2875 {
2876 Numeric_constant nc;
2877 if (expr->numeric_constant_value(&nc)
2878 && nc.set_type(this->type_, false, this->location()))
2879 {
2880 Expression* e = nc.expression(this->location());
2881 return e->get_backend(context);
2882 }
2883 }
2884
2885 if (this->type_ != NULL)
2886 expr = Expression::make_cast(this->type_, expr, this->location());
2887 return expr->get_backend(context);
2888 }
2889
2890 // Dump ast representation for constant expression.
2891
2892 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2893 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2894 {
2895 ast_dump_context->ostream() << this->constant_->name();
2896 }
2897
2898 // Make a reference to a constant in an expression.
2899
2900 Expression*
make_const_reference(Named_object * constant,Location location)2901 Expression::make_const_reference(Named_object* constant,
2902 Location location)
2903 {
2904 return new Const_expression(constant, location);
2905 }
2906
2907 // Find a named object in an expression.
2908
2909 int
expression(Expression ** pexpr)2910 Find_named_object::expression(Expression** pexpr)
2911 {
2912 switch ((*pexpr)->classification())
2913 {
2914 case Expression::EXPRESSION_CONST_REFERENCE:
2915 {
2916 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2917 if (ce->named_object() == this->no_)
2918 break;
2919
2920 // We need to check a constant initializer explicitly, as
2921 // loops here will not be caught by the loop checking for
2922 // variable initializers.
2923 ce->check_for_init_loop();
2924
2925 return TRAVERSE_CONTINUE;
2926 }
2927
2928 case Expression::EXPRESSION_VAR_REFERENCE:
2929 if ((*pexpr)->var_expression()->named_object() == this->no_)
2930 break;
2931 return TRAVERSE_CONTINUE;
2932 case Expression::EXPRESSION_FUNC_REFERENCE:
2933 if ((*pexpr)->func_expression()->named_object() == this->no_)
2934 break;
2935 return TRAVERSE_CONTINUE;
2936 default:
2937 return TRAVERSE_CONTINUE;
2938 }
2939 this->found_ = true;
2940 return TRAVERSE_EXIT;
2941 }
2942
2943 // The nil value.
2944
2945 class Nil_expression : public Expression
2946 {
2947 public:
Nil_expression(Location location)2948 Nil_expression(Location location)
2949 : Expression(EXPRESSION_NIL, location)
2950 { }
2951
2952 static Expression*
2953 do_import(Import*);
2954
2955 protected:
2956 bool
do_is_constant() const2957 do_is_constant() const
2958 { return true; }
2959
2960 bool
do_is_immutable() const2961 do_is_immutable() const
2962 { return true; }
2963
2964 Type*
do_type()2965 do_type()
2966 { return Type::make_nil_type(); }
2967
2968 void
do_determine_type(const Type_context *)2969 do_determine_type(const Type_context*)
2970 { }
2971
2972 Expression*
do_copy()2973 do_copy()
2974 { return this; }
2975
2976 Bexpression*
do_get_backend(Translate_context * context)2977 do_get_backend(Translate_context* context)
2978 { return context->backend()->nil_pointer_expression(); }
2979
2980 void
do_export(Export * exp) const2981 do_export(Export* exp) const
2982 { exp->write_c_string("nil"); }
2983
2984 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2985 do_dump_expression(Ast_dump_context* ast_dump_context) const
2986 { ast_dump_context->ostream() << "nil"; }
2987 };
2988
2989 // Import a nil expression.
2990
2991 Expression*
do_import(Import * imp)2992 Nil_expression::do_import(Import* imp)
2993 {
2994 imp->require_c_string("nil");
2995 return Expression::make_nil(imp->location());
2996 }
2997
2998 // Make a nil expression.
2999
3000 Expression*
make_nil(Location location)3001 Expression::make_nil(Location location)
3002 {
3003 return new Nil_expression(location);
3004 }
3005
3006 // The value of the predeclared constant iota. This is little more
3007 // than a marker. This will be lowered to an integer in
3008 // Const_expression::do_lower, which is where we know the value that
3009 // it should have.
3010
3011 class Iota_expression : public Parser_expression
3012 {
3013 public:
Iota_expression(Location location)3014 Iota_expression(Location location)
3015 : Parser_expression(EXPRESSION_IOTA, location)
3016 { }
3017
3018 protected:
3019 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3020 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3021 { go_unreachable(); }
3022
3023 // There should only ever be one of these.
3024 Expression*
do_copy()3025 do_copy()
3026 { go_unreachable(); }
3027
3028 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3029 do_dump_expression(Ast_dump_context* ast_dump_context) const
3030 { ast_dump_context->ostream() << "iota"; }
3031 };
3032
3033 // Make an iota expression. This is only called for one case: the
3034 // value of the predeclared constant iota.
3035
3036 Expression*
make_iota()3037 Expression::make_iota()
3038 {
3039 static Iota_expression iota_expression(Linemap::unknown_location());
3040 return &iota_expression;
3041 }
3042
3043 // Class Type_conversion_expression.
3044
3045 // Traversal.
3046
3047 int
do_traverse(Traverse * traverse)3048 Type_conversion_expression::do_traverse(Traverse* traverse)
3049 {
3050 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3051 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3052 return TRAVERSE_EXIT;
3053 return TRAVERSE_CONTINUE;
3054 }
3055
3056 // Convert to a constant at lowering time.
3057
3058 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3059 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3060 Statement_inserter*, int)
3061 {
3062 Type* type = this->type_;
3063 Expression* val = this->expr_;
3064 Location location = this->location();
3065
3066 if (type->is_numeric_type())
3067 {
3068 Numeric_constant nc;
3069 if (val->numeric_constant_value(&nc))
3070 {
3071 if (!nc.set_type(type, true, location))
3072 return Expression::make_error(location);
3073 return nc.expression(location);
3074 }
3075 }
3076
3077 // According to the language specification on string conversions
3078 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3079 // When converting an integer into a string, the string will be a UTF-8
3080 // representation of the integer and integers "outside the range of valid
3081 // Unicode code points are converted to '\uFFFD'."
3082 if (type->is_string_type())
3083 {
3084 Numeric_constant nc;
3085 if (val->numeric_constant_value(&nc) && nc.is_int())
3086 {
3087 // An integer value doesn't fit in the Unicode code point range if it
3088 // overflows the Go "int" type or is negative.
3089 unsigned long ul;
3090 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3091 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3092 return Expression::make_string("\ufffd", location);
3093 }
3094 }
3095
3096 if (type->is_slice_type())
3097 {
3098 Type* element_type = type->array_type()->element_type()->forwarded();
3099 bool is_byte = (element_type->integer_type() != NULL
3100 && element_type->integer_type()->is_byte());
3101 bool is_rune = (element_type->integer_type() != NULL
3102 && element_type->integer_type()->is_rune());
3103 if (is_byte || is_rune)
3104 {
3105 std::string s;
3106 if (val->string_constant_value(&s))
3107 {
3108 Expression_list* vals = new Expression_list();
3109 if (is_byte)
3110 {
3111 for (std::string::const_iterator p = s.begin();
3112 p != s.end();
3113 p++)
3114 {
3115 unsigned char c = static_cast<unsigned char>(*p);
3116 vals->push_back(Expression::make_integer_ul(c,
3117 element_type,
3118 location));
3119 }
3120 }
3121 else
3122 {
3123 const char *p = s.data();
3124 const char *pend = s.data() + s.length();
3125 while (p < pend)
3126 {
3127 unsigned int c;
3128 int adv = Lex::fetch_char(p, &c);
3129 if (adv == 0)
3130 {
3131 warning_at(this->location(), 0,
3132 "invalid UTF-8 encoding");
3133 adv = 1;
3134 }
3135 p += adv;
3136 vals->push_back(Expression::make_integer_ul(c,
3137 element_type,
3138 location));
3139 }
3140 }
3141
3142 return Expression::make_slice_composite_literal(type, vals,
3143 location);
3144 }
3145 }
3146 }
3147
3148 return this;
3149 }
3150
3151 // Flatten a type conversion by using a temporary variable for the slice
3152 // in slice to string conversions.
3153
3154 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3155 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3156 Statement_inserter* inserter)
3157 {
3158 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3159 {
3160 go_assert(saw_errors());
3161 return Expression::make_error(this->location());
3162 }
3163
3164 if (((this->type()->is_string_type()
3165 && this->expr_->type()->is_slice_type())
3166 || this->expr_->type()->interface_type() != NULL)
3167 && !this->expr_->is_variable())
3168 {
3169 Temporary_statement* temp =
3170 Statement::make_temporary(NULL, this->expr_, this->location());
3171 inserter->insert(temp);
3172 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3173 }
3174 return this;
3175 }
3176
3177 // Return whether a type conversion is a constant.
3178
3179 bool
do_is_constant() const3180 Type_conversion_expression::do_is_constant() const
3181 {
3182 if (!this->expr_->is_constant())
3183 return false;
3184
3185 // A conversion to a type that may not be used as a constant is not
3186 // a constant. For example, []byte(nil).
3187 Type* type = this->type_;
3188 if (type->integer_type() == NULL
3189 && type->float_type() == NULL
3190 && type->complex_type() == NULL
3191 && !type->is_boolean_type()
3192 && !type->is_string_type())
3193 return false;
3194
3195 return true;
3196 }
3197
3198 // Return whether a type conversion is immutable.
3199
3200 bool
do_is_immutable() const3201 Type_conversion_expression::do_is_immutable() const
3202 {
3203 Type* type = this->type_;
3204 Type* expr_type = this->expr_->type();
3205
3206 if (type->interface_type() != NULL
3207 || expr_type->interface_type() != NULL)
3208 return false;
3209
3210 if (!this->expr_->is_immutable())
3211 return false;
3212
3213 if (Type::are_identical(type, expr_type, false, NULL))
3214 return true;
3215
3216 return type->is_basic_type() && expr_type->is_basic_type();
3217 }
3218
3219 // Return the constant numeric value if there is one.
3220
3221 bool
do_numeric_constant_value(Numeric_constant * nc) const3222 Type_conversion_expression::do_numeric_constant_value(
3223 Numeric_constant* nc) const
3224 {
3225 if (!this->type_->is_numeric_type())
3226 return false;
3227 if (!this->expr_->numeric_constant_value(nc))
3228 return false;
3229 return nc->set_type(this->type_, false, this->location());
3230 }
3231
3232 // Return the constant string value if there is one.
3233
3234 bool
do_string_constant_value(std::string * val) const3235 Type_conversion_expression::do_string_constant_value(std::string* val) const
3236 {
3237 if (this->type_->is_string_type()
3238 && this->expr_->type()->integer_type() != NULL)
3239 {
3240 Numeric_constant nc;
3241 if (this->expr_->numeric_constant_value(&nc))
3242 {
3243 unsigned long ival;
3244 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3245 {
3246 val->clear();
3247 Lex::append_char(ival, true, val, this->location());
3248 return true;
3249 }
3250 }
3251 }
3252
3253 // FIXME: Could handle conversion from const []int here.
3254
3255 return false;
3256 }
3257
3258 // Determine the resulting type of the conversion.
3259
3260 void
do_determine_type(const Type_context *)3261 Type_conversion_expression::do_determine_type(const Type_context*)
3262 {
3263 Type_context subcontext(this->type_, false);
3264 this->expr_->determine_type(&subcontext);
3265 }
3266
3267 // Check that types are convertible.
3268
3269 void
do_check_types(Gogo *)3270 Type_conversion_expression::do_check_types(Gogo*)
3271 {
3272 Type* type = this->type_;
3273 Type* expr_type = this->expr_->type();
3274 std::string reason;
3275
3276 if (type->is_error() || expr_type->is_error())
3277 {
3278 this->set_is_error();
3279 return;
3280 }
3281
3282 if (this->may_convert_function_types_
3283 && type->function_type() != NULL
3284 && expr_type->function_type() != NULL)
3285 return;
3286
3287 if (Type::are_convertible(type, expr_type, &reason))
3288 return;
3289
3290 error_at(this->location(), "%s", reason.c_str());
3291 this->set_is_error();
3292 }
3293
3294 // Get the backend representation for a type conversion.
3295
3296 Bexpression*
do_get_backend(Translate_context * context)3297 Type_conversion_expression::do_get_backend(Translate_context* context)
3298 {
3299 Type* type = this->type_;
3300 Type* expr_type = this->expr_->type();
3301
3302 Gogo* gogo = context->gogo();
3303 Btype* btype = type->get_backend(gogo);
3304 Bexpression* bexpr = this->expr_->get_backend(context);
3305 Location loc = this->location();
3306
3307 if (Type::are_identical(type, expr_type, false, NULL))
3308 return gogo->backend()->convert_expression(btype, bexpr, loc);
3309 else if (type->interface_type() != NULL
3310 || expr_type->interface_type() != NULL)
3311 {
3312 Expression* conversion =
3313 Expression::convert_for_assignment(gogo, type, this->expr_,
3314 this->location());
3315 return conversion->get_backend(context);
3316 }
3317 else if (type->is_string_type()
3318 && expr_type->integer_type() != NULL)
3319 {
3320 mpz_t intval;
3321 Numeric_constant nc;
3322 if (this->expr_->numeric_constant_value(&nc)
3323 && nc.to_int(&intval)
3324 && mpz_fits_ushort_p(intval))
3325 {
3326 std::string s;
3327 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3328 mpz_clear(intval);
3329 Expression* se = Expression::make_string(s, loc);
3330 return se->get_backend(context);
3331 }
3332
3333 Expression* i2s_expr =
3334 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3335 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3336 }
3337 else if (type->is_string_type() && expr_type->is_slice_type())
3338 {
3339 Array_type* a = expr_type->array_type();
3340 Type* e = a->element_type()->forwarded();
3341 go_assert(e->integer_type() != NULL);
3342 go_assert(this->expr_->is_variable());
3343
3344 Runtime::Function code;
3345 if (e->integer_type()->is_byte())
3346 code = Runtime::BYTE_ARRAY_TO_STRING;
3347 else
3348 {
3349 go_assert(e->integer_type()->is_rune());
3350 code = Runtime::INT_ARRAY_TO_STRING;
3351 }
3352 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3353 Expression* len = a->get_length(gogo, this->expr_);
3354 return Runtime::make_call(code, loc, 2, valptr,
3355 len)->get_backend(context);
3356 }
3357 else if (type->is_slice_type() && expr_type->is_string_type())
3358 {
3359 Type* e = type->array_type()->element_type()->forwarded();
3360 go_assert(e->integer_type() != NULL);
3361
3362 Runtime::Function code;
3363 if (e->integer_type()->is_byte())
3364 code = Runtime::STRING_TO_BYTE_ARRAY;
3365 else
3366 {
3367 go_assert(e->integer_type()->is_rune());
3368 code = Runtime::STRING_TO_INT_ARRAY;
3369 }
3370 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3371 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3372 }
3373 else if (type->is_numeric_type())
3374 {
3375 go_assert(Type::are_convertible(type, expr_type, NULL));
3376 return gogo->backend()->convert_expression(btype, bexpr, loc);
3377 }
3378 else if ((type->is_unsafe_pointer_type()
3379 && (expr_type->points_to() != NULL
3380 || expr_type->integer_type()))
3381 || (expr_type->is_unsafe_pointer_type()
3382 && type->points_to() != NULL)
3383 || (this->may_convert_function_types_
3384 && type->function_type() != NULL
3385 && expr_type->function_type() != NULL))
3386 return gogo->backend()->convert_expression(btype, bexpr, loc);
3387 else
3388 {
3389 Expression* conversion =
3390 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3391 return conversion->get_backend(context);
3392 }
3393 }
3394
3395 // Output a type conversion in a constant expression.
3396
3397 void
do_export(Export * exp) const3398 Type_conversion_expression::do_export(Export* exp) const
3399 {
3400 exp->write_c_string("convert(");
3401 exp->write_type(this->type_);
3402 exp->write_c_string(", ");
3403 this->expr_->export_expression(exp);
3404 exp->write_c_string(")");
3405 }
3406
3407 // Import a type conversion or a struct construction.
3408
3409 Expression*
do_import(Import * imp)3410 Type_conversion_expression::do_import(Import* imp)
3411 {
3412 imp->require_c_string("convert(");
3413 Type* type = imp->read_type();
3414 imp->require_c_string(", ");
3415 Expression* val = Expression::import_expression(imp);
3416 imp->require_c_string(")");
3417 return Expression::make_cast(type, val, imp->location());
3418 }
3419
3420 // Dump ast representation for a type conversion expression.
3421
3422 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3423 Type_conversion_expression::do_dump_expression(
3424 Ast_dump_context* ast_dump_context) const
3425 {
3426 ast_dump_context->dump_type(this->type_);
3427 ast_dump_context->ostream() << "(";
3428 ast_dump_context->dump_expression(this->expr_);
3429 ast_dump_context->ostream() << ") ";
3430 }
3431
3432 // Make a type cast expression.
3433
3434 Expression*
make_cast(Type * type,Expression * val,Location location)3435 Expression::make_cast(Type* type, Expression* val, Location location)
3436 {
3437 if (type->is_error_type() || val->is_error_expression())
3438 return Expression::make_error(location);
3439 return new Type_conversion_expression(type, val, location);
3440 }
3441
3442 // Class Unsafe_type_conversion_expression.
3443
3444 // Traversal.
3445
3446 int
do_traverse(Traverse * traverse)3447 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3448 {
3449 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3450 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3451 return TRAVERSE_EXIT;
3452 return TRAVERSE_CONTINUE;
3453 }
3454
3455 // Return whether an unsafe type conversion is immutable.
3456
3457 bool
do_is_immutable() const3458 Unsafe_type_conversion_expression::do_is_immutable() const
3459 {
3460 Type* type = this->type_;
3461 Type* expr_type = this->expr_->type();
3462
3463 if (type->interface_type() != NULL
3464 || expr_type->interface_type() != NULL)
3465 return false;
3466
3467 if (!this->expr_->is_immutable())
3468 return false;
3469
3470 if (Type::are_convertible(type, expr_type, NULL))
3471 return true;
3472
3473 return type->is_basic_type() && expr_type->is_basic_type();
3474 }
3475
3476 // Convert to backend representation.
3477
3478 Bexpression*
do_get_backend(Translate_context * context)3479 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3480 {
3481 // We are only called for a limited number of cases.
3482
3483 Type* t = this->type_;
3484 Type* et = this->expr_->type();
3485
3486 if (t->is_error_type()
3487 || this->expr_->is_error_expression()
3488 || et->is_error_type())
3489 {
3490 go_assert(saw_errors());
3491 return context->backend()->error_expression();
3492 }
3493
3494 if (t->array_type() != NULL)
3495 go_assert(et->array_type() != NULL
3496 && t->is_slice_type() == et->is_slice_type());
3497 else if (t->struct_type() != NULL)
3498 {
3499 if (t->named_type() != NULL
3500 && et->named_type() != NULL
3501 && !Type::are_convertible(t, et, NULL))
3502 {
3503 go_assert(saw_errors());
3504 return context->backend()->error_expression();
3505 }
3506
3507 go_assert(et->struct_type() != NULL
3508 && Type::are_convertible(t, et, NULL));
3509 }
3510 else if (t->map_type() != NULL)
3511 go_assert(et->map_type() != NULL);
3512 else if (t->channel_type() != NULL)
3513 go_assert(et->channel_type() != NULL);
3514 else if (t->points_to() != NULL)
3515 go_assert(et->points_to() != NULL
3516 || et->channel_type() != NULL
3517 || et->map_type() != NULL
3518 || et->function_type() != NULL
3519 || et->is_nil_type());
3520 else if (et->is_unsafe_pointer_type())
3521 go_assert(t->points_to() != NULL);
3522 else if (t->interface_type() != NULL)
3523 {
3524 bool empty_iface = t->interface_type()->is_empty();
3525 go_assert(et->interface_type() != NULL
3526 && et->interface_type()->is_empty() == empty_iface);
3527 }
3528 else if (t->integer_type() != NULL)
3529 go_assert(et->is_boolean_type()
3530 || et->integer_type() != NULL
3531 || et->function_type() != NULL
3532 || et->points_to() != NULL
3533 || et->map_type() != NULL
3534 || et->channel_type() != NULL
3535 || et->is_nil_type());
3536 else
3537 go_unreachable();
3538
3539 Gogo* gogo = context->gogo();
3540 Btype* btype = t->get_backend(gogo);
3541 Bexpression* bexpr = this->expr_->get_backend(context);
3542 Location loc = this->location();
3543 return gogo->backend()->convert_expression(btype, bexpr, loc);
3544 }
3545
3546 // Dump ast representation for an unsafe type conversion expression.
3547
3548 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3549 Unsafe_type_conversion_expression::do_dump_expression(
3550 Ast_dump_context* ast_dump_context) const
3551 {
3552 ast_dump_context->dump_type(this->type_);
3553 ast_dump_context->ostream() << "(";
3554 ast_dump_context->dump_expression(this->expr_);
3555 ast_dump_context->ostream() << ") ";
3556 }
3557
3558 // Make an unsafe type conversion expression.
3559
3560 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)3561 Expression::make_unsafe_cast(Type* type, Expression* expr,
3562 Location location)
3563 {
3564 return new Unsafe_type_conversion_expression(type, expr, location);
3565 }
3566
3567 // Class Unary_expression.
3568
3569 // If we are taking the address of a composite literal, and the
3570 // contents are not constant, then we want to make a heap expression
3571 // instead.
3572
3573 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3574 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3575 {
3576 Location loc = this->location();
3577 Operator op = this->op_;
3578 Expression* expr = this->expr_;
3579
3580 if (op == OPERATOR_MULT && expr->is_type_expression())
3581 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3582
3583 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3584 // moving x to the heap. FIXME: Is it worth doing a real escape
3585 // analysis here? This case is found in math/unsafe.go and is
3586 // therefore worth special casing.
3587 if (op == OPERATOR_MULT)
3588 {
3589 Expression* e = expr;
3590 while (e->classification() == EXPRESSION_CONVERSION)
3591 {
3592 Type_conversion_expression* te
3593 = static_cast<Type_conversion_expression*>(e);
3594 e = te->expr();
3595 }
3596
3597 if (e->classification() == EXPRESSION_UNARY)
3598 {
3599 Unary_expression* ue = static_cast<Unary_expression*>(e);
3600 if (ue->op_ == OPERATOR_AND)
3601 {
3602 if (e == expr)
3603 {
3604 // *&x == x.
3605 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3606 {
3607 error_at(ue->location(),
3608 "invalid operand for unary %<&%>");
3609 this->set_is_error();
3610 }
3611 return ue->expr_;
3612 }
3613 ue->set_does_not_escape();
3614 }
3615 }
3616 }
3617
3618 // Catching an invalid indirection of unsafe.Pointer here avoid
3619 // having to deal with TYPE_VOID in other places.
3620 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3621 {
3622 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3623 return Expression::make_error(this->location());
3624 }
3625
3626 // Check for an invalid pointer dereference. We need to do this
3627 // here because Unary_expression::do_type will return an error type
3628 // in this case. That can cause code to appear erroneous, and
3629 // therefore disappear at lowering time, without any error message.
3630 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3631 {
3632 this->report_error(_("expected pointer"));
3633 return Expression::make_error(this->location());
3634 }
3635
3636 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3637 {
3638 Numeric_constant nc;
3639 if (expr->numeric_constant_value(&nc))
3640 {
3641 Numeric_constant result;
3642 bool issued_error;
3643 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3644 &issued_error))
3645 return result.expression(loc);
3646 else if (issued_error)
3647 return Expression::make_error(this->location());
3648 }
3649 }
3650
3651 return this;
3652 }
3653
3654 // Flatten expression if a nil check must be performed and create temporary
3655 // variables if necessary.
3656
3657 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)3658 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3659 Statement_inserter* inserter)
3660 {
3661 if (this->is_error_expression()
3662 || this->expr_->is_error_expression()
3663 || this->expr_->type()->is_error_type())
3664 {
3665 go_assert(saw_errors());
3666 return Expression::make_error(this->location());
3667 }
3668
3669 Location location = this->location();
3670 if (this->op_ == OPERATOR_MULT
3671 && !this->expr_->is_variable())
3672 {
3673 go_assert(this->expr_->type()->points_to() != NULL);
3674 Type* ptype = this->expr_->type()->points_to();
3675 if (!ptype->is_void_type())
3676 {
3677 int64_t s;
3678 bool ok = ptype->backend_type_size(gogo, &s);
3679 if (!ok)
3680 {
3681 go_assert(saw_errors());
3682 return Expression::make_error(this->location());
3683 }
3684 if (s >= 4096 || this->issue_nil_check_)
3685 {
3686 Temporary_statement* temp =
3687 Statement::make_temporary(NULL, this->expr_, location);
3688 inserter->insert(temp);
3689 this->expr_ =
3690 Expression::make_temporary_reference(temp, location);
3691 }
3692 }
3693 }
3694
3695 if (this->op_ == OPERATOR_AND)
3696 {
3697 // If this->escapes_ is false at this point, then it was set to
3698 // false by an explicit call to set_does_not_escape, and the
3699 // value does not escape. If this->escapes_ is true, we may be
3700 // able to set it to false if taking the address of a variable
3701 // that does not escape.
3702 if (this->escapes_ && this->expr_->var_expression() != NULL)
3703 {
3704 Named_object* var = this->expr_->var_expression()->named_object();
3705 if (var->is_variable())
3706 this->escapes_ = var->var_value()->escapes();
3707 if (var->is_result_variable())
3708 this->escapes_ = var->result_var_value()->escapes();
3709 }
3710 this->expr_->address_taken(this->escapes_);
3711 }
3712
3713 if (this->create_temp_ && !this->expr_->is_variable())
3714 {
3715 Temporary_statement* temp =
3716 Statement::make_temporary(NULL, this->expr_, location);
3717 inserter->insert(temp);
3718 this->expr_ = Expression::make_temporary_reference(temp, location);
3719 }
3720
3721 return this;
3722 }
3723
3724 // Return whether a unary expression is a constant.
3725
3726 bool
do_is_constant() const3727 Unary_expression::do_is_constant() const
3728 {
3729 if (this->op_ == OPERATOR_MULT)
3730 {
3731 // Indirecting through a pointer is only constant if the object
3732 // to which the expression points is constant, but we currently
3733 // have no way to determine that.
3734 return false;
3735 }
3736 else if (this->op_ == OPERATOR_AND)
3737 {
3738 // Taking the address of a variable is constant if it is a
3739 // global variable, not constant otherwise. In other cases taking the
3740 // address is probably not a constant.
3741 Var_expression* ve = this->expr_->var_expression();
3742 if (ve != NULL)
3743 {
3744 Named_object* no = ve->named_object();
3745 return no->is_variable() && no->var_value()->is_global();
3746 }
3747 return false;
3748 }
3749 else
3750 return this->expr_->is_constant();
3751 }
3752
3753 // Apply unary opcode OP to UNC, setting NC. Return true if this
3754 // could be done, false if not. On overflow, issues an error and sets
3755 // *ISSUED_ERROR.
3756
3757 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)3758 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3759 Location location, Numeric_constant* nc,
3760 bool* issued_error)
3761 {
3762 *issued_error = false;
3763 switch (op)
3764 {
3765 case OPERATOR_PLUS:
3766 *nc = *unc;
3767 return true;
3768
3769 case OPERATOR_MINUS:
3770 if (unc->is_int() || unc->is_rune())
3771 break;
3772 else if (unc->is_float())
3773 {
3774 mpfr_t uval;
3775 unc->get_float(&uval);
3776 mpfr_t val;
3777 mpfr_init(val);
3778 mpfr_neg(val, uval, GMP_RNDN);
3779 nc->set_float(unc->type(), val);
3780 mpfr_clear(uval);
3781 mpfr_clear(val);
3782 return true;
3783 }
3784 else if (unc->is_complex())
3785 {
3786 mpc_t uval;
3787 unc->get_complex(&uval);
3788 mpc_t val;
3789 mpc_init2(val, mpc_precision);
3790 mpc_neg(val, uval, MPC_RNDNN);
3791 nc->set_complex(unc->type(), val);
3792 mpc_clear(uval);
3793 mpc_clear(val);
3794 return true;
3795 }
3796 else
3797 go_unreachable();
3798
3799 case OPERATOR_XOR:
3800 break;
3801
3802 case OPERATOR_NOT:
3803 case OPERATOR_AND:
3804 case OPERATOR_MULT:
3805 return false;
3806
3807 default:
3808 go_unreachable();
3809 }
3810
3811 if (!unc->is_int() && !unc->is_rune())
3812 return false;
3813
3814 mpz_t uval;
3815 if (unc->is_rune())
3816 unc->get_rune(&uval);
3817 else
3818 unc->get_int(&uval);
3819 mpz_t val;
3820 mpz_init(val);
3821
3822 switch (op)
3823 {
3824 case OPERATOR_MINUS:
3825 mpz_neg(val, uval);
3826 break;
3827
3828 case OPERATOR_NOT:
3829 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3830 break;
3831
3832 case OPERATOR_XOR:
3833 {
3834 Type* utype = unc->type();
3835 if (utype->integer_type() == NULL
3836 || utype->integer_type()->is_abstract())
3837 mpz_com(val, uval);
3838 else
3839 {
3840 // The number of HOST_WIDE_INTs that it takes to represent
3841 // UVAL.
3842 size_t count = ((mpz_sizeinbase(uval, 2)
3843 + HOST_BITS_PER_WIDE_INT
3844 - 1)
3845 / HOST_BITS_PER_WIDE_INT);
3846
3847 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3848 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3849
3850 size_t obits = utype->integer_type()->bits();
3851
3852 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3853 {
3854 mpz_t adj;
3855 mpz_init_set_ui(adj, 1);
3856 mpz_mul_2exp(adj, adj, obits);
3857 mpz_add(uval, uval, adj);
3858 mpz_clear(adj);
3859 }
3860
3861 size_t ecount;
3862 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3863 go_assert(ecount <= count);
3864
3865 // Trim down to the number of words required by the type.
3866 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3867 / HOST_BITS_PER_WIDE_INT);
3868 go_assert(ocount <= count);
3869
3870 for (size_t i = 0; i < ocount; ++i)
3871 phwi[i] = ~phwi[i];
3872
3873 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3874 if (clearbits != 0)
3875 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3876 >> clearbits);
3877
3878 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3879
3880 if (!utype->integer_type()->is_unsigned()
3881 && mpz_tstbit(val, obits - 1))
3882 {
3883 mpz_t adj;
3884 mpz_init_set_ui(adj, 1);
3885 mpz_mul_2exp(adj, adj, obits);
3886 mpz_sub(val, val, adj);
3887 mpz_clear(adj);
3888 }
3889
3890 delete[] phwi;
3891 }
3892 }
3893 break;
3894
3895 default:
3896 go_unreachable();
3897 }
3898
3899 if (unc->is_rune())
3900 nc->set_rune(NULL, val);
3901 else
3902 nc->set_int(NULL, val);
3903
3904 mpz_clear(uval);
3905 mpz_clear(val);
3906
3907 if (!nc->set_type(unc->type(), true, location))
3908 {
3909 *issued_error = true;
3910 return false;
3911 }
3912 return true;
3913 }
3914
3915 // Return the integral constant value of a unary expression, if it has one.
3916
3917 bool
do_numeric_constant_value(Numeric_constant * nc) const3918 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3919 {
3920 Numeric_constant unc;
3921 if (!this->expr_->numeric_constant_value(&unc))
3922 return false;
3923 bool issued_error;
3924 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3925 nc, &issued_error);
3926 }
3927
3928 // Return the type of a unary expression.
3929
3930 Type*
do_type()3931 Unary_expression::do_type()
3932 {
3933 switch (this->op_)
3934 {
3935 case OPERATOR_PLUS:
3936 case OPERATOR_MINUS:
3937 case OPERATOR_NOT:
3938 case OPERATOR_XOR:
3939 return this->expr_->type();
3940
3941 case OPERATOR_AND:
3942 return Type::make_pointer_type(this->expr_->type());
3943
3944 case OPERATOR_MULT:
3945 {
3946 Type* subtype = this->expr_->type();
3947 Type* points_to = subtype->points_to();
3948 if (points_to == NULL)
3949 return Type::make_error_type();
3950 return points_to;
3951 }
3952
3953 default:
3954 go_unreachable();
3955 }
3956 }
3957
3958 // Determine abstract types for a unary expression.
3959
3960 void
do_determine_type(const Type_context * context)3961 Unary_expression::do_determine_type(const Type_context* context)
3962 {
3963 switch (this->op_)
3964 {
3965 case OPERATOR_PLUS:
3966 case OPERATOR_MINUS:
3967 case OPERATOR_NOT:
3968 case OPERATOR_XOR:
3969 this->expr_->determine_type(context);
3970 break;
3971
3972 case OPERATOR_AND:
3973 // Taking the address of something.
3974 {
3975 Type* subtype = (context->type == NULL
3976 ? NULL
3977 : context->type->points_to());
3978 Type_context subcontext(subtype, false);
3979 this->expr_->determine_type(&subcontext);
3980 }
3981 break;
3982
3983 case OPERATOR_MULT:
3984 // Indirecting through a pointer.
3985 {
3986 Type* subtype = (context->type == NULL
3987 ? NULL
3988 : Type::make_pointer_type(context->type));
3989 Type_context subcontext(subtype, false);
3990 this->expr_->determine_type(&subcontext);
3991 }
3992 break;
3993
3994 default:
3995 go_unreachable();
3996 }
3997 }
3998
3999 // Check types for a unary expression.
4000
4001 void
do_check_types(Gogo *)4002 Unary_expression::do_check_types(Gogo*)
4003 {
4004 Type* type = this->expr_->type();
4005 if (type->is_error())
4006 {
4007 this->set_is_error();
4008 return;
4009 }
4010
4011 switch (this->op_)
4012 {
4013 case OPERATOR_PLUS:
4014 case OPERATOR_MINUS:
4015 if (type->integer_type() == NULL
4016 && type->float_type() == NULL
4017 && type->complex_type() == NULL)
4018 this->report_error(_("expected numeric type"));
4019 break;
4020
4021 case OPERATOR_NOT:
4022 if (!type->is_boolean_type())
4023 this->report_error(_("expected boolean type"));
4024 break;
4025
4026 case OPERATOR_XOR:
4027 if (type->integer_type() == NULL)
4028 this->report_error(_("expected integer"));
4029 break;
4030
4031 case OPERATOR_AND:
4032 if (!this->expr_->is_addressable())
4033 {
4034 if (!this->create_temp_)
4035 {
4036 error_at(this->location(), "invalid operand for unary %<&%>");
4037 this->set_is_error();
4038 }
4039 }
4040 else
4041 this->expr_->issue_nil_check();
4042 break;
4043
4044 case OPERATOR_MULT:
4045 // Indirecting through a pointer.
4046 if (type->points_to() == NULL)
4047 this->report_error(_("expected pointer"));
4048 if (type->points_to()->is_error())
4049 this->set_is_error();
4050 break;
4051
4052 default:
4053 go_unreachable();
4054 }
4055 }
4056
4057 // Get the backend representation for a unary expression.
4058
4059 Bexpression*
do_get_backend(Translate_context * context)4060 Unary_expression::do_get_backend(Translate_context* context)
4061 {
4062 Gogo* gogo = context->gogo();
4063 Location loc = this->location();
4064
4065 // Taking the address of a set-and-use-temporary expression requires
4066 // setting the temporary and then taking the address.
4067 if (this->op_ == OPERATOR_AND)
4068 {
4069 Set_and_use_temporary_expression* sut =
4070 this->expr_->set_and_use_temporary_expression();
4071 if (sut != NULL)
4072 {
4073 Temporary_statement* temp = sut->temporary();
4074 Bvariable* bvar = temp->get_backend_variable(context);
4075 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4076 Bexpression* bval = sut->expression()->get_backend(context);
4077
4078 Bstatement* bassign =
4079 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4080 Bexpression* bvar_addr =
4081 gogo->backend()->address_expression(bvar_expr, loc);
4082 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4083 }
4084 }
4085
4086 Bexpression* ret;
4087 Bexpression* bexpr = this->expr_->get_backend(context);
4088 Btype* btype = this->expr_->type()->get_backend(gogo);
4089 switch (this->op_)
4090 {
4091 case OPERATOR_PLUS:
4092 ret = bexpr;
4093 break;
4094
4095 case OPERATOR_MINUS:
4096 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4097 ret = gogo->backend()->convert_expression(btype, ret, loc);
4098 break;
4099
4100 case OPERATOR_NOT:
4101 case OPERATOR_XOR:
4102 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4103 break;
4104
4105 case OPERATOR_AND:
4106 if (!this->create_temp_)
4107 {
4108 // We should not see a non-constant constructor here; cases
4109 // where we would see one should have been moved onto the
4110 // heap at parse time. Taking the address of a nonconstant
4111 // constructor will not do what the programmer expects.
4112
4113 go_assert(!this->expr_->is_composite_literal()
4114 || this->expr_->is_immutable());
4115 if (this->expr_->classification() == EXPRESSION_UNARY)
4116 {
4117 Unary_expression* ue =
4118 static_cast<Unary_expression*>(this->expr_);
4119 go_assert(ue->op() != OPERATOR_AND);
4120 }
4121 }
4122
4123 static unsigned int counter;
4124 char buf[100];
4125 if (this->is_gc_root_ || this->is_slice_init_)
4126 {
4127 bool copy_to_heap = false;
4128 if (this->is_gc_root_)
4129 {
4130 // Build a decl for a GC root variable. GC roots are mutable, so
4131 // they cannot be represented as an immutable_struct in the
4132 // backend.
4133 static unsigned int root_counter;
4134 snprintf(buf, sizeof buf, "gc%u", root_counter);
4135 ++root_counter;
4136 }
4137 else
4138 {
4139 // Build a decl for a slice value initializer. An immutable slice
4140 // value initializer may have to be copied to the heap if it
4141 // contains pointers in a non-constant context.
4142 snprintf(buf, sizeof buf, "C%u", counter);
4143 ++counter;
4144
4145 Array_type* at = this->expr_->type()->array_type();
4146 go_assert(at != NULL);
4147
4148 // If we are not copying the value to the heap, we will only
4149 // initialize the value once, so we can use this directly
4150 // rather than copying it. In that case we can't make it
4151 // read-only, because the program is permitted to change it.
4152 copy_to_heap = (at->element_type()->has_pointer()
4153 && !context->is_const());
4154 }
4155 Bvariable* implicit =
4156 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
4157 false, 0);
4158 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4159 true, copy_to_heap, false,
4160 bexpr);
4161 bexpr = gogo->backend()->var_expression(implicit, loc);
4162 }
4163 else if ((this->expr_->is_composite_literal()
4164 || this->expr_->string_expression() != NULL)
4165 && this->expr_->is_immutable())
4166 {
4167 // Build a decl for a constant constructor.
4168 snprintf(buf, sizeof buf, "C%u", counter);
4169 ++counter;
4170
4171 Bvariable* decl =
4172 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4173 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4174 btype, loc, bexpr);
4175 bexpr = gogo->backend()->var_expression(decl, loc);
4176 }
4177
4178 go_assert(!this->create_temp_ || this->expr_->is_variable());
4179 ret = gogo->backend()->address_expression(bexpr, loc);
4180 break;
4181
4182 case OPERATOR_MULT:
4183 {
4184 go_assert(this->expr_->type()->points_to() != NULL);
4185
4186 // If we are dereferencing the pointer to a large struct, we
4187 // need to check for nil. We don't bother to check for small
4188 // structs because we expect the system to crash on a nil
4189 // pointer dereference. However, if we know the address of this
4190 // expression is being taken, we must always check for nil.
4191
4192 Type* ptype = this->expr_->type()->points_to();
4193 Btype* pbtype = ptype->get_backend(gogo);
4194 if (!ptype->is_void_type())
4195 {
4196 int64_t s;
4197 bool ok = ptype->backend_type_size(gogo, &s);
4198 if (!ok)
4199 {
4200 go_assert(saw_errors());
4201 return gogo->backend()->error_expression();
4202 }
4203 if (s >= 4096 || this->issue_nil_check_)
4204 {
4205 go_assert(this->expr_->is_variable());
4206 Bexpression* nil =
4207 Expression::make_nil(loc)->get_backend(context);
4208 Bexpression* compare =
4209 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4210 nil, loc);
4211 Bexpression* crash =
4212 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4213 loc)->get_backend(context);
4214 bexpr = gogo->backend()->conditional_expression(btype, compare,
4215 crash, bexpr,
4216 loc);
4217
4218 }
4219 }
4220 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4221 }
4222 break;
4223
4224 default:
4225 go_unreachable();
4226 }
4227
4228 return ret;
4229 }
4230
4231 // Export a unary expression.
4232
4233 void
do_export(Export * exp) const4234 Unary_expression::do_export(Export* exp) const
4235 {
4236 switch (this->op_)
4237 {
4238 case OPERATOR_PLUS:
4239 exp->write_c_string("+ ");
4240 break;
4241 case OPERATOR_MINUS:
4242 exp->write_c_string("- ");
4243 break;
4244 case OPERATOR_NOT:
4245 exp->write_c_string("! ");
4246 break;
4247 case OPERATOR_XOR:
4248 exp->write_c_string("^ ");
4249 break;
4250 case OPERATOR_AND:
4251 case OPERATOR_MULT:
4252 default:
4253 go_unreachable();
4254 }
4255 this->expr_->export_expression(exp);
4256 }
4257
4258 // Import a unary expression.
4259
4260 Expression*
do_import(Import * imp)4261 Unary_expression::do_import(Import* imp)
4262 {
4263 Operator op;
4264 switch (imp->get_char())
4265 {
4266 case '+':
4267 op = OPERATOR_PLUS;
4268 break;
4269 case '-':
4270 op = OPERATOR_MINUS;
4271 break;
4272 case '!':
4273 op = OPERATOR_NOT;
4274 break;
4275 case '^':
4276 op = OPERATOR_XOR;
4277 break;
4278 default:
4279 go_unreachable();
4280 }
4281 imp->require_c_string(" ");
4282 Expression* expr = Expression::import_expression(imp);
4283 return Expression::make_unary(op, expr, imp->location());
4284 }
4285
4286 // Dump ast representation of an unary expression.
4287
4288 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4289 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4290 {
4291 ast_dump_context->dump_operator(this->op_);
4292 ast_dump_context->ostream() << "(";
4293 ast_dump_context->dump_expression(this->expr_);
4294 ast_dump_context->ostream() << ") ";
4295 }
4296
4297 // Make a unary expression.
4298
4299 Expression*
make_unary(Operator op,Expression * expr,Location location)4300 Expression::make_unary(Operator op, Expression* expr, Location location)
4301 {
4302 return new Unary_expression(op, expr, location);
4303 }
4304
4305 // If this is an indirection through a pointer, return the expression
4306 // being pointed through. Otherwise return this.
4307
4308 Expression*
deref()4309 Expression::deref()
4310 {
4311 if (this->classification_ == EXPRESSION_UNARY)
4312 {
4313 Unary_expression* ue = static_cast<Unary_expression*>(this);
4314 if (ue->op() == OPERATOR_MULT)
4315 return ue->operand();
4316 }
4317 return this;
4318 }
4319
4320 // Class Binary_expression.
4321
4322 // Traversal.
4323
4324 int
do_traverse(Traverse * traverse)4325 Binary_expression::do_traverse(Traverse* traverse)
4326 {
4327 int t = Expression::traverse(&this->left_, traverse);
4328 if (t == TRAVERSE_EXIT)
4329 return TRAVERSE_EXIT;
4330 return Expression::traverse(&this->right_, traverse);
4331 }
4332
4333 // Return the type to use for a binary operation on operands of
4334 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4335 // such may be NULL or abstract.
4336
4337 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)4338 Binary_expression::operation_type(Operator op, Type* left_type,
4339 Type* right_type, Type** result_type)
4340 {
4341 if (left_type != right_type
4342 && !left_type->is_abstract()
4343 && !right_type->is_abstract()
4344 && left_type->base() != right_type->base()
4345 && op != OPERATOR_LSHIFT
4346 && op != OPERATOR_RSHIFT)
4347 {
4348 // May be a type error--let it be diagnosed elsewhere.
4349 return false;
4350 }
4351
4352 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4353 {
4354 if (left_type->integer_type() != NULL)
4355 *result_type = left_type;
4356 else
4357 *result_type = Type::make_abstract_integer_type();
4358 }
4359 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4360 *result_type = left_type;
4361 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4362 *result_type = right_type;
4363 else if (!left_type->is_abstract())
4364 *result_type = left_type;
4365 else if (!right_type->is_abstract())
4366 *result_type = right_type;
4367 else if (left_type->complex_type() != NULL)
4368 *result_type = left_type;
4369 else if (right_type->complex_type() != NULL)
4370 *result_type = right_type;
4371 else if (left_type->float_type() != NULL)
4372 *result_type = left_type;
4373 else if (right_type->float_type() != NULL)
4374 *result_type = right_type;
4375 else if (left_type->integer_type() != NULL
4376 && left_type->integer_type()->is_rune())
4377 *result_type = left_type;
4378 else if (right_type->integer_type() != NULL
4379 && right_type->integer_type()->is_rune())
4380 *result_type = right_type;
4381 else
4382 *result_type = left_type;
4383
4384 return true;
4385 }
4386
4387 // Convert an integer comparison code and an operator to a boolean
4388 // value.
4389
4390 bool
cmp_to_bool(Operator op,int cmp)4391 Binary_expression::cmp_to_bool(Operator op, int cmp)
4392 {
4393 switch (op)
4394 {
4395 case OPERATOR_EQEQ:
4396 return cmp == 0;
4397 break;
4398 case OPERATOR_NOTEQ:
4399 return cmp != 0;
4400 break;
4401 case OPERATOR_LT:
4402 return cmp < 0;
4403 break;
4404 case OPERATOR_LE:
4405 return cmp <= 0;
4406 case OPERATOR_GT:
4407 return cmp > 0;
4408 case OPERATOR_GE:
4409 return cmp >= 0;
4410 default:
4411 go_unreachable();
4412 }
4413 }
4414
4415 // Compare constants according to OP.
4416
4417 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)4418 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4419 Numeric_constant* right_nc,
4420 Location location, bool* result)
4421 {
4422 Type* left_type = left_nc->type();
4423 Type* right_type = right_nc->type();
4424
4425 Type* type;
4426 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4427 return false;
4428
4429 // When comparing an untyped operand to a typed operand, we are
4430 // effectively coercing the untyped operand to the other operand's
4431 // type, so make sure that is valid.
4432 if (!left_nc->set_type(type, true, location)
4433 || !right_nc->set_type(type, true, location))
4434 return false;
4435
4436 bool ret;
4437 int cmp;
4438 if (type->complex_type() != NULL)
4439 {
4440 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4441 return false;
4442 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4443 }
4444 else if (type->float_type() != NULL)
4445 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4446 else
4447 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4448
4449 if (ret)
4450 *result = Binary_expression::cmp_to_bool(op, cmp);
4451
4452 return ret;
4453 }
4454
4455 // Compare integer constants.
4456
4457 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4458 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4459 const Numeric_constant* right_nc,
4460 int* cmp)
4461 {
4462 mpz_t left_val;
4463 if (!left_nc->to_int(&left_val))
4464 return false;
4465 mpz_t right_val;
4466 if (!right_nc->to_int(&right_val))
4467 {
4468 mpz_clear(left_val);
4469 return false;
4470 }
4471
4472 *cmp = mpz_cmp(left_val, right_val);
4473
4474 mpz_clear(left_val);
4475 mpz_clear(right_val);
4476
4477 return true;
4478 }
4479
4480 // Compare floating point constants.
4481
4482 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4483 Binary_expression::compare_float(const Numeric_constant* left_nc,
4484 const Numeric_constant* right_nc,
4485 int* cmp)
4486 {
4487 mpfr_t left_val;
4488 if (!left_nc->to_float(&left_val))
4489 return false;
4490 mpfr_t right_val;
4491 if (!right_nc->to_float(&right_val))
4492 {
4493 mpfr_clear(left_val);
4494 return false;
4495 }
4496
4497 // We already coerced both operands to the same type. If that type
4498 // is not an abstract type, we need to round the values accordingly.
4499 Type* type = left_nc->type();
4500 if (!type->is_abstract() && type->float_type() != NULL)
4501 {
4502 int bits = type->float_type()->bits();
4503 mpfr_prec_round(left_val, bits, GMP_RNDN);
4504 mpfr_prec_round(right_val, bits, GMP_RNDN);
4505 }
4506
4507 *cmp = mpfr_cmp(left_val, right_val);
4508
4509 mpfr_clear(left_val);
4510 mpfr_clear(right_val);
4511
4512 return true;
4513 }
4514
4515 // Compare complex constants. Complex numbers may only be compared
4516 // for equality.
4517
4518 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)4519 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4520 const Numeric_constant* right_nc,
4521 int* cmp)
4522 {
4523 mpc_t left_val;
4524 if (!left_nc->to_complex(&left_val))
4525 return false;
4526 mpc_t right_val;
4527 if (!right_nc->to_complex(&right_val))
4528 {
4529 mpc_clear(left_val);
4530 return false;
4531 }
4532
4533 // We already coerced both operands to the same type. If that type
4534 // is not an abstract type, we need to round the values accordingly.
4535 Type* type = left_nc->type();
4536 if (!type->is_abstract() && type->complex_type() != NULL)
4537 {
4538 int bits = type->complex_type()->bits();
4539 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4540 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4541 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4542 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4543 }
4544
4545 *cmp = mpc_cmp(left_val, right_val) != 0;
4546
4547 mpc_clear(left_val);
4548 mpc_clear(right_val);
4549
4550 return true;
4551 }
4552
4553 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4554 // true if this could be done, false if not. Issue errors at LOCATION
4555 // as appropriate, and sets *ISSUED_ERROR if it did.
4556
4557 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)4558 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4559 Numeric_constant* right_nc,
4560 Location location, Numeric_constant* nc,
4561 bool* issued_error)
4562 {
4563 *issued_error = false;
4564 switch (op)
4565 {
4566 case OPERATOR_OROR:
4567 case OPERATOR_ANDAND:
4568 case OPERATOR_EQEQ:
4569 case OPERATOR_NOTEQ:
4570 case OPERATOR_LT:
4571 case OPERATOR_LE:
4572 case OPERATOR_GT:
4573 case OPERATOR_GE:
4574 // These return boolean values, not numeric.
4575 return false;
4576 default:
4577 break;
4578 }
4579
4580 Type* left_type = left_nc->type();
4581 Type* right_type = right_nc->type();
4582
4583 Type* type;
4584 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4585 return false;
4586
4587 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4588
4589 // When combining an untyped operand with a typed operand, we are
4590 // effectively coercing the untyped operand to the other operand's
4591 // type, so make sure that is valid.
4592 if (!left_nc->set_type(type, true, location))
4593 return false;
4594 if (!is_shift && !right_nc->set_type(type, true, location))
4595 return false;
4596 if (is_shift
4597 && ((left_type->integer_type() == NULL
4598 && !left_type->is_abstract())
4599 || (right_type->integer_type() == NULL
4600 && !right_type->is_abstract())))
4601 return false;
4602
4603 bool r;
4604 if (type->complex_type() != NULL)
4605 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4606 else if (type->float_type() != NULL)
4607 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4608 else
4609 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4610
4611 if (r)
4612 {
4613 r = nc->set_type(type, true, location);
4614 if (!r)
4615 *issued_error = true;
4616 }
4617
4618 return r;
4619 }
4620
4621 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4622 // integer operations. Return true if this could be done, false if
4623 // not.
4624
4625 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)4626 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4627 const Numeric_constant* right_nc,
4628 Location location, Numeric_constant* nc)
4629 {
4630 mpz_t left_val;
4631 if (!left_nc->to_int(&left_val))
4632 return false;
4633 mpz_t right_val;
4634 if (!right_nc->to_int(&right_val))
4635 {
4636 mpz_clear(left_val);
4637 return false;
4638 }
4639
4640 mpz_t val;
4641 mpz_init(val);
4642
4643 switch (op)
4644 {
4645 case OPERATOR_PLUS:
4646 mpz_add(val, left_val, right_val);
4647 if (mpz_sizeinbase(val, 2) > 0x100000)
4648 {
4649 error_at(location, "constant addition overflow");
4650 nc->set_invalid();
4651 mpz_set_ui(val, 1);
4652 }
4653 break;
4654 case OPERATOR_MINUS:
4655 mpz_sub(val, left_val, right_val);
4656 if (mpz_sizeinbase(val, 2) > 0x100000)
4657 {
4658 error_at(location, "constant subtraction overflow");
4659 nc->set_invalid();
4660 mpz_set_ui(val, 1);
4661 }
4662 break;
4663 case OPERATOR_OR:
4664 mpz_ior(val, left_val, right_val);
4665 break;
4666 case OPERATOR_XOR:
4667 mpz_xor(val, left_val, right_val);
4668 break;
4669 case OPERATOR_MULT:
4670 mpz_mul(val, left_val, right_val);
4671 if (mpz_sizeinbase(val, 2) > 0x100000)
4672 {
4673 error_at(location, "constant multiplication overflow");
4674 nc->set_invalid();
4675 mpz_set_ui(val, 1);
4676 }
4677 break;
4678 case OPERATOR_DIV:
4679 if (mpz_sgn(right_val) != 0)
4680 mpz_tdiv_q(val, left_val, right_val);
4681 else
4682 {
4683 error_at(location, "division by zero");
4684 nc->set_invalid();
4685 mpz_set_ui(val, 0);
4686 }
4687 break;
4688 case OPERATOR_MOD:
4689 if (mpz_sgn(right_val) != 0)
4690 mpz_tdiv_r(val, left_val, right_val);
4691 else
4692 {
4693 error_at(location, "division by zero");
4694 nc->set_invalid();
4695 mpz_set_ui(val, 0);
4696 }
4697 break;
4698 case OPERATOR_LSHIFT:
4699 {
4700 unsigned long shift = mpz_get_ui(right_val);
4701 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4702 mpz_mul_2exp(val, left_val, shift);
4703 else
4704 {
4705 error_at(location, "shift count overflow");
4706 nc->set_invalid();
4707 mpz_set_ui(val, 1);
4708 }
4709 break;
4710 }
4711 break;
4712 case OPERATOR_RSHIFT:
4713 {
4714 unsigned long shift = mpz_get_ui(right_val);
4715 if (mpz_cmp_ui(right_val, shift) != 0)
4716 {
4717 error_at(location, "shift count overflow");
4718 nc->set_invalid();
4719 mpz_set_ui(val, 1);
4720 }
4721 else
4722 {
4723 if (mpz_cmp_ui(left_val, 0) >= 0)
4724 mpz_tdiv_q_2exp(val, left_val, shift);
4725 else
4726 mpz_fdiv_q_2exp(val, left_val, shift);
4727 }
4728 break;
4729 }
4730 break;
4731 case OPERATOR_AND:
4732 mpz_and(val, left_val, right_val);
4733 break;
4734 case OPERATOR_BITCLEAR:
4735 {
4736 mpz_t tval;
4737 mpz_init(tval);
4738 mpz_com(tval, right_val);
4739 mpz_and(val, left_val, tval);
4740 mpz_clear(tval);
4741 }
4742 break;
4743 default:
4744 go_unreachable();
4745 }
4746
4747 mpz_clear(left_val);
4748 mpz_clear(right_val);
4749
4750 if (left_nc->is_rune()
4751 || (op != OPERATOR_LSHIFT
4752 && op != OPERATOR_RSHIFT
4753 && right_nc->is_rune()))
4754 nc->set_rune(NULL, val);
4755 else
4756 nc->set_int(NULL, val);
4757
4758 mpz_clear(val);
4759
4760 return true;
4761 }
4762
4763 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4764 // floating point operations. Return true if this could be done,
4765 // false if not.
4766
4767 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)4768 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4769 const Numeric_constant* right_nc,
4770 Location location, Numeric_constant* nc)
4771 {
4772 mpfr_t left_val;
4773 if (!left_nc->to_float(&left_val))
4774 return false;
4775 mpfr_t right_val;
4776 if (!right_nc->to_float(&right_val))
4777 {
4778 mpfr_clear(left_val);
4779 return false;
4780 }
4781
4782 mpfr_t val;
4783 mpfr_init(val);
4784
4785 bool ret = true;
4786 switch (op)
4787 {
4788 case OPERATOR_PLUS:
4789 mpfr_add(val, left_val, right_val, GMP_RNDN);
4790 break;
4791 case OPERATOR_MINUS:
4792 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4793 break;
4794 case OPERATOR_OR:
4795 case OPERATOR_XOR:
4796 case OPERATOR_AND:
4797 case OPERATOR_BITCLEAR:
4798 case OPERATOR_MOD:
4799 case OPERATOR_LSHIFT:
4800 case OPERATOR_RSHIFT:
4801 mpfr_set_ui(val, 0, GMP_RNDN);
4802 ret = false;
4803 break;
4804 case OPERATOR_MULT:
4805 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4806 break;
4807 case OPERATOR_DIV:
4808 if (!mpfr_zero_p(right_val))
4809 mpfr_div(val, left_val, right_val, GMP_RNDN);
4810 else
4811 {
4812 error_at(location, "division by zero");
4813 nc->set_invalid();
4814 mpfr_set_ui(val, 0, GMP_RNDN);
4815 }
4816 break;
4817 default:
4818 go_unreachable();
4819 }
4820
4821 mpfr_clear(left_val);
4822 mpfr_clear(right_val);
4823
4824 nc->set_float(NULL, val);
4825 mpfr_clear(val);
4826
4827 return ret;
4828 }
4829
4830 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4831 // complex operations. Return true if this could be done, false if
4832 // not.
4833
4834 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)4835 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4836 const Numeric_constant* right_nc,
4837 Location location, Numeric_constant* nc)
4838 {
4839 mpc_t left_val;
4840 if (!left_nc->to_complex(&left_val))
4841 return false;
4842 mpc_t right_val;
4843 if (!right_nc->to_complex(&right_val))
4844 {
4845 mpc_clear(left_val);
4846 return false;
4847 }
4848
4849 mpc_t val;
4850 mpc_init2(val, mpc_precision);
4851
4852 bool ret = true;
4853 switch (op)
4854 {
4855 case OPERATOR_PLUS:
4856 mpc_add(val, left_val, right_val, MPC_RNDNN);
4857 break;
4858 case OPERATOR_MINUS:
4859 mpc_sub(val, left_val, right_val, MPC_RNDNN);
4860 break;
4861 case OPERATOR_OR:
4862 case OPERATOR_XOR:
4863 case OPERATOR_AND:
4864 case OPERATOR_BITCLEAR:
4865 case OPERATOR_MOD:
4866 case OPERATOR_LSHIFT:
4867 case OPERATOR_RSHIFT:
4868 mpc_set_ui(val, 0, MPC_RNDNN);
4869 ret = false;
4870 break;
4871 case OPERATOR_MULT:
4872 mpc_mul(val, left_val, right_val, MPC_RNDNN);
4873 break;
4874 case OPERATOR_DIV:
4875 if (mpc_cmp_si(right_val, 0) == 0)
4876 {
4877 error_at(location, "division by zero");
4878 nc->set_invalid();
4879 mpc_set_ui(val, 0, MPC_RNDNN);
4880 break;
4881 }
4882 mpc_div(val, left_val, right_val, MPC_RNDNN);
4883 break;
4884 default:
4885 go_unreachable();
4886 }
4887
4888 mpc_clear(left_val);
4889 mpc_clear(right_val);
4890
4891 nc->set_complex(NULL, val);
4892 mpc_clear(val);
4893
4894 return ret;
4895 }
4896
4897 // Lower a binary expression. We have to evaluate constant
4898 // expressions now, in order to implement Go's unlimited precision
4899 // constants.
4900
4901 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)4902 Binary_expression::do_lower(Gogo* gogo, Named_object*,
4903 Statement_inserter* inserter, int)
4904 {
4905 Location location = this->location();
4906 Operator op = this->op_;
4907 Expression* left = this->left_;
4908 Expression* right = this->right_;
4909
4910 const bool is_comparison = (op == OPERATOR_EQEQ
4911 || op == OPERATOR_NOTEQ
4912 || op == OPERATOR_LT
4913 || op == OPERATOR_LE
4914 || op == OPERATOR_GT
4915 || op == OPERATOR_GE);
4916
4917 // Numeric constant expressions.
4918 {
4919 Numeric_constant left_nc;
4920 Numeric_constant right_nc;
4921 if (left->numeric_constant_value(&left_nc)
4922 && right->numeric_constant_value(&right_nc))
4923 {
4924 if (is_comparison)
4925 {
4926 bool result;
4927 if (!Binary_expression::compare_constant(op, &left_nc,
4928 &right_nc, location,
4929 &result))
4930 return this;
4931 return Expression::make_cast(Type::make_boolean_type(),
4932 Expression::make_boolean(result,
4933 location),
4934 location);
4935 }
4936 else
4937 {
4938 Numeric_constant nc;
4939 bool issued_error;
4940 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
4941 location, &nc,
4942 &issued_error))
4943 {
4944 if (issued_error)
4945 return Expression::make_error(location);
4946 return this;
4947 }
4948 return nc.expression(location);
4949 }
4950 }
4951 }
4952
4953 // String constant expressions.
4954 if (left->type()->is_string_type() && right->type()->is_string_type())
4955 {
4956 std::string left_string;
4957 std::string right_string;
4958 if (left->string_constant_value(&left_string)
4959 && right->string_constant_value(&right_string))
4960 {
4961 if (op == OPERATOR_PLUS)
4962 return Expression::make_string(left_string + right_string,
4963 location);
4964 else if (is_comparison)
4965 {
4966 int cmp = left_string.compare(right_string);
4967 bool r = Binary_expression::cmp_to_bool(op, cmp);
4968 return Expression::make_boolean(r, location);
4969 }
4970 }
4971 }
4972
4973 // Lower struct, array, and some interface comparisons.
4974 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
4975 {
4976 if (left->type()->struct_type() != NULL
4977 && right->type()->struct_type() != NULL)
4978 return this->lower_struct_comparison(gogo, inserter);
4979 else if (left->type()->array_type() != NULL
4980 && !left->type()->is_slice_type()
4981 && right->type()->array_type() != NULL
4982 && !right->type()->is_slice_type())
4983 return this->lower_array_comparison(gogo, inserter);
4984 else if ((left->type()->interface_type() != NULL
4985 && right->type()->interface_type() == NULL)
4986 || (left->type()->interface_type() == NULL
4987 && right->type()->interface_type() != NULL))
4988 return this->lower_interface_value_comparison(gogo, inserter);
4989 }
4990
4991 return this;
4992 }
4993
4994 // Lower a struct comparison.
4995
4996 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)4997 Binary_expression::lower_struct_comparison(Gogo* gogo,
4998 Statement_inserter* inserter)
4999 {
5000 Struct_type* st = this->left_->type()->struct_type();
5001 Struct_type* st2 = this->right_->type()->struct_type();
5002 if (st2 == NULL)
5003 return this;
5004 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5005 return this;
5006 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5007 this->right_->type(), NULL))
5008 return this;
5009
5010 // See if we can compare using memcmp. As a heuristic, we use
5011 // memcmp rather than field references and comparisons if there are
5012 // more than two fields.
5013 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5014 return this->lower_compare_to_memcmp(gogo, inserter);
5015
5016 Location loc = this->location();
5017
5018 Expression* left = this->left_;
5019 Temporary_statement* left_temp = NULL;
5020 if (left->var_expression() == NULL
5021 && left->temporary_reference_expression() == NULL)
5022 {
5023 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5024 inserter->insert(left_temp);
5025 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5026 }
5027
5028 Expression* right = this->right_;
5029 Temporary_statement* right_temp = NULL;
5030 if (right->var_expression() == NULL
5031 && right->temporary_reference_expression() == NULL)
5032 {
5033 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5034 inserter->insert(right_temp);
5035 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5036 }
5037
5038 Expression* ret = Expression::make_boolean(true, loc);
5039 const Struct_field_list* fields = st->fields();
5040 unsigned int field_index = 0;
5041 for (Struct_field_list::const_iterator pf = fields->begin();
5042 pf != fields->end();
5043 ++pf, ++field_index)
5044 {
5045 if (Gogo::is_sink_name(pf->field_name()))
5046 continue;
5047
5048 if (field_index > 0)
5049 {
5050 if (left_temp == NULL)
5051 left = left->copy();
5052 else
5053 left = Expression::make_temporary_reference(left_temp, loc);
5054 if (right_temp == NULL)
5055 right = right->copy();
5056 else
5057 right = Expression::make_temporary_reference(right_temp, loc);
5058 }
5059 Expression* f1 = Expression::make_field_reference(left, field_index,
5060 loc);
5061 Expression* f2 = Expression::make_field_reference(right, field_index,
5062 loc);
5063 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5064 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5065 }
5066
5067 if (this->op_ == OPERATOR_NOTEQ)
5068 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5069
5070 return ret;
5071 }
5072
5073 // Lower an array comparison.
5074
5075 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)5076 Binary_expression::lower_array_comparison(Gogo* gogo,
5077 Statement_inserter* inserter)
5078 {
5079 Array_type* at = this->left_->type()->array_type();
5080 Array_type* at2 = this->right_->type()->array_type();
5081 if (at2 == NULL)
5082 return this;
5083 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5084 return this;
5085 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5086 this->right_->type(), NULL))
5087 return this;
5088
5089 // Call memcmp directly if possible. This may let the middle-end
5090 // optimize the call.
5091 if (at->compare_is_identity(gogo))
5092 return this->lower_compare_to_memcmp(gogo, inserter);
5093
5094 // Call the array comparison function.
5095 Named_object* hash_fn;
5096 Named_object* equal_fn;
5097 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5098 &hash_fn, &equal_fn);
5099
5100 Location loc = this->location();
5101
5102 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5103
5104 Expression_list* args = new Expression_list();
5105 args->push_back(this->operand_address(inserter, this->left_));
5106 args->push_back(this->operand_address(inserter, this->right_));
5107 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5108
5109 Expression* ret = Expression::make_call(func, args, false, loc);
5110
5111 if (this->op_ == OPERATOR_NOTEQ)
5112 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5113
5114 return ret;
5115 }
5116
5117 // Lower an interface to value comparison.
5118
5119 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)5120 Binary_expression::lower_interface_value_comparison(Gogo*,
5121 Statement_inserter* inserter)
5122 {
5123 Type* left_type = this->left_->type();
5124 Type* right_type = this->right_->type();
5125 Interface_type* ift;
5126 if (left_type->interface_type() != NULL)
5127 {
5128 ift = left_type->interface_type();
5129 if (!ift->implements_interface(right_type, NULL))
5130 return this;
5131 }
5132 else
5133 {
5134 ift = right_type->interface_type();
5135 if (!ift->implements_interface(left_type, NULL))
5136 return this;
5137 }
5138 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5139 return this;
5140
5141 Location loc = this->location();
5142
5143 if (left_type->interface_type() == NULL
5144 && left_type->points_to() == NULL
5145 && !this->left_->is_addressable())
5146 {
5147 Temporary_statement* temp =
5148 Statement::make_temporary(left_type, NULL, loc);
5149 inserter->insert(temp);
5150 this->left_ =
5151 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5152 }
5153
5154 if (right_type->interface_type() == NULL
5155 && right_type->points_to() == NULL
5156 && !this->right_->is_addressable())
5157 {
5158 Temporary_statement* temp =
5159 Statement::make_temporary(right_type, NULL, loc);
5160 inserter->insert(temp);
5161 this->right_ =
5162 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5163 }
5164
5165 return this;
5166 }
5167
5168 // Lower a struct or array comparison to a call to memcmp.
5169
5170 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)5171 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5172 {
5173 Location loc = this->location();
5174
5175 Expression* a1 = this->operand_address(inserter, this->left_);
5176 Expression* a2 = this->operand_address(inserter, this->right_);
5177 Expression* len = Expression::make_type_info(this->left_->type(),
5178 TYPE_INFO_SIZE);
5179
5180 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5181 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5182 return Expression::make_binary(this->op_, call, zero, loc);
5183 }
5184
5185 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)5186 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5187 Statement_inserter* inserter)
5188 {
5189 Location loc = this->location();
5190 if (this->left_->type()->is_error_type()
5191 || this->right_->type()->is_error_type()
5192 || this->left_->is_error_expression()
5193 || this->right_->is_error_expression())
5194 {
5195 go_assert(saw_errors());
5196 return Expression::make_error(loc);
5197 }
5198
5199 Temporary_statement* temp;
5200 if (this->left_->type()->is_string_type()
5201 && this->op_ == OPERATOR_PLUS)
5202 {
5203 if (!this->left_->is_variable()
5204 && !this->left_->is_constant())
5205 {
5206 temp = Statement::make_temporary(NULL, this->left_, loc);
5207 inserter->insert(temp);
5208 this->left_ = Expression::make_temporary_reference(temp, loc);
5209 }
5210 if (!this->right_->is_variable()
5211 && !this->right_->is_constant())
5212 {
5213 temp =
5214 Statement::make_temporary(this->left_->type(), this->right_, loc);
5215 this->right_ = Expression::make_temporary_reference(temp, loc);
5216 inserter->insert(temp);
5217 }
5218 }
5219
5220 Type* left_type = this->left_->type();
5221 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5222 || this->op_ == OPERATOR_RSHIFT);
5223 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5224 left_type->integer_type() != NULL)
5225 || this->op_ == OPERATOR_MOD);
5226
5227 if (is_shift_op
5228 || (is_idiv_op
5229 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5230 {
5231 if (!this->left_->is_variable() && !this->left_->is_constant())
5232 {
5233 temp = Statement::make_temporary(NULL, this->left_, loc);
5234 inserter->insert(temp);
5235 this->left_ = Expression::make_temporary_reference(temp, loc);
5236 }
5237 if (!this->right_->is_variable() && !this->right_->is_constant())
5238 {
5239 temp =
5240 Statement::make_temporary(NULL, this->right_, loc);
5241 this->right_ = Expression::make_temporary_reference(temp, loc);
5242 inserter->insert(temp);
5243 }
5244 }
5245 return this;
5246 }
5247
5248
5249 // Return the address of EXPR, cast to unsafe.Pointer.
5250
5251 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)5252 Binary_expression::operand_address(Statement_inserter* inserter,
5253 Expression* expr)
5254 {
5255 Location loc = this->location();
5256
5257 if (!expr->is_addressable())
5258 {
5259 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5260 loc);
5261 inserter->insert(temp);
5262 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5263 }
5264 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5265 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5266 Type* void_type = Type::make_void_type();
5267 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5268 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5269 }
5270
5271 // Return the numeric constant value, if it has one.
5272
5273 bool
do_numeric_constant_value(Numeric_constant * nc) const5274 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5275 {
5276 Numeric_constant left_nc;
5277 if (!this->left_->numeric_constant_value(&left_nc))
5278 return false;
5279 Numeric_constant right_nc;
5280 if (!this->right_->numeric_constant_value(&right_nc))
5281 return false;
5282 bool issued_error;
5283 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5284 this->location(), nc, &issued_error);
5285 }
5286
5287 // Note that the value is being discarded.
5288
5289 bool
do_discarding_value()5290 Binary_expression::do_discarding_value()
5291 {
5292 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5293 return this->right_->discarding_value();
5294 else
5295 {
5296 this->unused_value_error();
5297 return false;
5298 }
5299 }
5300
5301 // Get type.
5302
5303 Type*
do_type()5304 Binary_expression::do_type()
5305 {
5306 if (this->classification() == EXPRESSION_ERROR)
5307 return Type::make_error_type();
5308
5309 switch (this->op_)
5310 {
5311 case OPERATOR_EQEQ:
5312 case OPERATOR_NOTEQ:
5313 case OPERATOR_LT:
5314 case OPERATOR_LE:
5315 case OPERATOR_GT:
5316 case OPERATOR_GE:
5317 if (this->type_ == NULL)
5318 this->type_ = Type::make_boolean_type();
5319 return this->type_;
5320
5321 case OPERATOR_PLUS:
5322 case OPERATOR_MINUS:
5323 case OPERATOR_OR:
5324 case OPERATOR_XOR:
5325 case OPERATOR_MULT:
5326 case OPERATOR_DIV:
5327 case OPERATOR_MOD:
5328 case OPERATOR_AND:
5329 case OPERATOR_BITCLEAR:
5330 case OPERATOR_OROR:
5331 case OPERATOR_ANDAND:
5332 {
5333 Type* type;
5334 if (!Binary_expression::operation_type(this->op_,
5335 this->left_->type(),
5336 this->right_->type(),
5337 &type))
5338 return Type::make_error_type();
5339 return type;
5340 }
5341
5342 case OPERATOR_LSHIFT:
5343 case OPERATOR_RSHIFT:
5344 return this->left_->type();
5345
5346 default:
5347 go_unreachable();
5348 }
5349 }
5350
5351 // Set type for a binary expression.
5352
5353 void
do_determine_type(const Type_context * context)5354 Binary_expression::do_determine_type(const Type_context* context)
5355 {
5356 Type* tleft = this->left_->type();
5357 Type* tright = this->right_->type();
5358
5359 // Both sides should have the same type, except for the shift
5360 // operations. For a comparison, we should ignore the incoming
5361 // type.
5362
5363 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5364 || this->op_ == OPERATOR_RSHIFT);
5365
5366 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5367 || this->op_ == OPERATOR_NOTEQ
5368 || this->op_ == OPERATOR_LT
5369 || this->op_ == OPERATOR_LE
5370 || this->op_ == OPERATOR_GT
5371 || this->op_ == OPERATOR_GE);
5372
5373 // For constant expressions, the context of the result is not useful in
5374 // determining the types of the operands. It is only legal to use abstract
5375 // boolean, numeric, and string constants as operands where it is legal to
5376 // use non-abstract boolean, numeric, and string constants, respectively.
5377 // Any issues with the operation will be resolved in the check_types pass.
5378 bool is_constant_expr = (this->left_->is_constant()
5379 && this->right_->is_constant());
5380
5381 Type_context subcontext(*context);
5382
5383 if (is_constant_expr)
5384 {
5385 subcontext.type = NULL;
5386 subcontext.may_be_abstract = true;
5387 }
5388 else if (is_comparison)
5389 {
5390 // In a comparison, the context does not determine the types of
5391 // the operands.
5392 subcontext.type = NULL;
5393 }
5394
5395 // Set the context for the left hand operand.
5396 if (is_shift_op)
5397 {
5398 // The right hand operand of a shift plays no role in
5399 // determining the type of the left hand operand.
5400 }
5401 else if (!tleft->is_abstract())
5402 subcontext.type = tleft;
5403 else if (!tright->is_abstract())
5404 subcontext.type = tright;
5405 else if (subcontext.type == NULL)
5406 {
5407 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5408 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5409 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5410 {
5411 // Both sides have an abstract integer, abstract float, or
5412 // abstract complex type. Just let CONTEXT determine
5413 // whether they may remain abstract or not.
5414 }
5415 else if (tleft->complex_type() != NULL)
5416 subcontext.type = tleft;
5417 else if (tright->complex_type() != NULL)
5418 subcontext.type = tright;
5419 else if (tleft->float_type() != NULL)
5420 subcontext.type = tleft;
5421 else if (tright->float_type() != NULL)
5422 subcontext.type = tright;
5423 else
5424 subcontext.type = tleft;
5425
5426 if (subcontext.type != NULL && !context->may_be_abstract)
5427 subcontext.type = subcontext.type->make_non_abstract_type();
5428 }
5429
5430 this->left_->determine_type(&subcontext);
5431
5432 if (is_shift_op)
5433 {
5434 // We may have inherited an unusable type for the shift operand.
5435 // Give a useful error if that happened.
5436 if (tleft->is_abstract()
5437 && subcontext.type != NULL
5438 && !subcontext.may_be_abstract
5439 && subcontext.type->interface_type() == NULL
5440 && subcontext.type->integer_type() == NULL)
5441 this->report_error(("invalid context-determined non-integer type "
5442 "for left operand of shift"));
5443
5444 // The context for the right hand operand is the same as for the
5445 // left hand operand, except for a shift operator.
5446 subcontext.type = Type::lookup_integer_type("uint");
5447 subcontext.may_be_abstract = false;
5448 }
5449
5450 this->right_->determine_type(&subcontext);
5451
5452 if (is_comparison)
5453 {
5454 if (this->type_ != NULL && !this->type_->is_abstract())
5455 ;
5456 else if (context->type != NULL && context->type->is_boolean_type())
5457 this->type_ = context->type;
5458 else if (!context->may_be_abstract)
5459 this->type_ = Type::lookup_bool_type();
5460 }
5461 }
5462
5463 // Report an error if the binary operator OP does not support TYPE.
5464 // OTYPE is the type of the other operand. Return whether the
5465 // operation is OK. This should not be used for shift.
5466
5467 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)5468 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5469 Location location)
5470 {
5471 switch (op)
5472 {
5473 case OPERATOR_OROR:
5474 case OPERATOR_ANDAND:
5475 if (!type->is_boolean_type()
5476 || !otype->is_boolean_type())
5477 {
5478 error_at(location, "expected boolean type");
5479 return false;
5480 }
5481 break;
5482
5483 case OPERATOR_EQEQ:
5484 case OPERATOR_NOTEQ:
5485 {
5486 std::string reason;
5487 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5488 {
5489 error_at(location, "%s", reason.c_str());
5490 return false;
5491 }
5492 }
5493 break;
5494
5495 case OPERATOR_LT:
5496 case OPERATOR_LE:
5497 case OPERATOR_GT:
5498 case OPERATOR_GE:
5499 {
5500 std::string reason;
5501 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5502 {
5503 error_at(location, "%s", reason.c_str());
5504 return false;
5505 }
5506 }
5507 break;
5508
5509 case OPERATOR_PLUS:
5510 case OPERATOR_PLUSEQ:
5511 if ((!type->is_numeric_type() && !type->is_string_type())
5512 || (!otype->is_numeric_type() && !otype->is_string_type()))
5513 {
5514 error_at(location,
5515 "expected integer, floating, complex, or string type");
5516 return false;
5517 }
5518 break;
5519
5520 case OPERATOR_MINUS:
5521 case OPERATOR_MINUSEQ:
5522 case OPERATOR_MULT:
5523 case OPERATOR_MULTEQ:
5524 case OPERATOR_DIV:
5525 case OPERATOR_DIVEQ:
5526 if (!type->is_numeric_type() || !otype->is_numeric_type())
5527 {
5528 error_at(location, "expected integer, floating, or complex type");
5529 return false;
5530 }
5531 break;
5532
5533 case OPERATOR_MOD:
5534 case OPERATOR_MODEQ:
5535 case OPERATOR_OR:
5536 case OPERATOR_OREQ:
5537 case OPERATOR_AND:
5538 case OPERATOR_ANDEQ:
5539 case OPERATOR_XOR:
5540 case OPERATOR_XOREQ:
5541 case OPERATOR_BITCLEAR:
5542 case OPERATOR_BITCLEAREQ:
5543 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5544 {
5545 error_at(location, "expected integer type");
5546 return false;
5547 }
5548 break;
5549
5550 default:
5551 go_unreachable();
5552 }
5553
5554 return true;
5555 }
5556
5557 // Check types.
5558
5559 void
do_check_types(Gogo *)5560 Binary_expression::do_check_types(Gogo*)
5561 {
5562 if (this->classification() == EXPRESSION_ERROR)
5563 return;
5564
5565 Type* left_type = this->left_->type();
5566 Type* right_type = this->right_->type();
5567 if (left_type->is_error() || right_type->is_error())
5568 {
5569 this->set_is_error();
5570 return;
5571 }
5572
5573 if (this->op_ == OPERATOR_EQEQ
5574 || this->op_ == OPERATOR_NOTEQ
5575 || this->op_ == OPERATOR_LT
5576 || this->op_ == OPERATOR_LE
5577 || this->op_ == OPERATOR_GT
5578 || this->op_ == OPERATOR_GE)
5579 {
5580 if (left_type->is_nil_type() && right_type->is_nil_type())
5581 {
5582 this->report_error(_("invalid comparison of nil with nil"));
5583 return;
5584 }
5585 if (!Type::are_assignable(left_type, right_type, NULL)
5586 && !Type::are_assignable(right_type, left_type, NULL))
5587 {
5588 this->report_error(_("incompatible types in binary expression"));
5589 return;
5590 }
5591 if (!Binary_expression::check_operator_type(this->op_, left_type,
5592 right_type,
5593 this->location())
5594 || !Binary_expression::check_operator_type(this->op_, right_type,
5595 left_type,
5596 this->location()))
5597 {
5598 this->set_is_error();
5599 return;
5600 }
5601 }
5602 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5603 {
5604 if (!Type::are_compatible_for_binop(left_type, right_type))
5605 {
5606 this->report_error(_("incompatible types in binary expression"));
5607 return;
5608 }
5609 if (!Binary_expression::check_operator_type(this->op_, left_type,
5610 right_type,
5611 this->location()))
5612 {
5613 this->set_is_error();
5614 return;
5615 }
5616 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5617 {
5618 // Division by a zero integer constant is an error.
5619 Numeric_constant rconst;
5620 unsigned long rval;
5621 if (left_type->integer_type() != NULL
5622 && this->right_->numeric_constant_value(&rconst)
5623 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5624 && rval == 0)
5625 {
5626 this->report_error(_("integer division by zero"));
5627 return;
5628 }
5629 }
5630 }
5631 else
5632 {
5633 if (left_type->integer_type() == NULL)
5634 this->report_error(_("shift of non-integer operand"));
5635
5636 if (right_type->is_string_type())
5637 this->report_error(_("shift count not unsigned integer"));
5638 else if (!right_type->is_abstract()
5639 && (right_type->integer_type() == NULL
5640 || !right_type->integer_type()->is_unsigned()))
5641 this->report_error(_("shift count not unsigned integer"));
5642 else
5643 {
5644 Numeric_constant nc;
5645 if (this->right_->numeric_constant_value(&nc))
5646 {
5647 mpz_t val;
5648 if (!nc.to_int(&val))
5649 this->report_error(_("shift count not unsigned integer"));
5650 else
5651 {
5652 if (mpz_sgn(val) < 0)
5653 {
5654 this->report_error(_("negative shift count"));
5655 Location rloc = this->right_->location();
5656 this->right_ = Expression::make_integer_ul(0, right_type,
5657 rloc);
5658 }
5659 mpz_clear(val);
5660 }
5661 }
5662 }
5663 }
5664 }
5665
5666 // Get the backend representation for a binary expression.
5667
5668 Bexpression*
do_get_backend(Translate_context * context)5669 Binary_expression::do_get_backend(Translate_context* context)
5670 {
5671 Gogo* gogo = context->gogo();
5672 Location loc = this->location();
5673 Type* left_type = this->left_->type();
5674 Type* right_type = this->right_->type();
5675
5676 bool use_left_type = true;
5677 bool is_shift_op = false;
5678 bool is_idiv_op = false;
5679 switch (this->op_)
5680 {
5681 case OPERATOR_EQEQ:
5682 case OPERATOR_NOTEQ:
5683 case OPERATOR_LT:
5684 case OPERATOR_LE:
5685 case OPERATOR_GT:
5686 case OPERATOR_GE:
5687 return Expression::comparison(context, this->type_, this->op_,
5688 this->left_, this->right_, loc);
5689
5690 case OPERATOR_OROR:
5691 case OPERATOR_ANDAND:
5692 use_left_type = false;
5693 break;
5694 case OPERATOR_PLUS:
5695 case OPERATOR_MINUS:
5696 case OPERATOR_OR:
5697 case OPERATOR_XOR:
5698 case OPERATOR_MULT:
5699 break;
5700 case OPERATOR_DIV:
5701 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5702 break;
5703 case OPERATOR_MOD:
5704 is_idiv_op = true;
5705 break;
5706 case OPERATOR_LSHIFT:
5707 case OPERATOR_RSHIFT:
5708 is_shift_op = true;
5709 break;
5710 case OPERATOR_BITCLEAR:
5711 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5712 case OPERATOR_AND:
5713 break;
5714 default:
5715 go_unreachable();
5716 }
5717
5718 if (left_type->is_string_type())
5719 {
5720 go_assert(this->op_ == OPERATOR_PLUS);
5721 Expression* string_plus =
5722 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5723 this->left_, this->right_);
5724 return string_plus->get_backend(context);
5725 }
5726
5727 // For complex division Go might want slightly different results than the
5728 // backend implementation provides, so we have our own runtime routine.
5729 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5730 {
5731 Runtime::Function complex_code;
5732 switch (this->left_->type()->complex_type()->bits())
5733 {
5734 case 64:
5735 complex_code = Runtime::COMPLEX64_DIV;
5736 break;
5737 case 128:
5738 complex_code = Runtime::COMPLEX128_DIV;
5739 break;
5740 default:
5741 go_unreachable();
5742 }
5743 Expression* complex_div =
5744 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5745 return complex_div->get_backend(context);
5746 }
5747
5748 Bexpression* left = this->left_->get_backend(context);
5749 Bexpression* right = this->right_->get_backend(context);
5750
5751 Type* type = use_left_type ? left_type : right_type;
5752 Btype* btype = type->get_backend(gogo);
5753
5754 Bexpression* ret =
5755 gogo->backend()->binary_expression(this->op_, left, right, loc);
5756 ret = gogo->backend()->convert_expression(btype, ret, loc);
5757
5758 // Initialize overflow constants.
5759 Bexpression* overflow;
5760 mpz_t zero;
5761 mpz_init_set_ui(zero, 0UL);
5762 mpz_t one;
5763 mpz_init_set_ui(one, 1UL);
5764 mpz_t neg_one;
5765 mpz_init_set_si(neg_one, -1);
5766
5767 Btype* left_btype = left_type->get_backend(gogo);
5768 Btype* right_btype = right_type->get_backend(gogo);
5769
5770 // In Go, a shift larger than the size of the type is well-defined.
5771 // This is not true in C, so we need to insert a conditional.
5772 if (is_shift_op)
5773 {
5774 go_assert(left_type->integer_type() != NULL);
5775
5776 mpz_t bitsval;
5777 int bits = left_type->integer_type()->bits();
5778 mpz_init_set_ui(bitsval, bits);
5779 Bexpression* bits_expr =
5780 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5781 Bexpression* compare =
5782 gogo->backend()->binary_expression(OPERATOR_LT,
5783 right, bits_expr, loc);
5784
5785 Bexpression* zero_expr =
5786 gogo->backend()->integer_constant_expression(left_btype, zero);
5787 overflow = zero_expr;
5788 if (this->op_ == OPERATOR_RSHIFT
5789 && !left_type->integer_type()->is_unsigned())
5790 {
5791 Bexpression* neg_expr =
5792 gogo->backend()->binary_expression(OPERATOR_LT, left,
5793 zero_expr, loc);
5794 Bexpression* neg_one_expr =
5795 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5796 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5797 neg_one_expr,
5798 zero_expr, loc);
5799 }
5800 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5801 overflow, loc);
5802 mpz_clear(bitsval);
5803 }
5804
5805 // Add checks for division by zero and division overflow as needed.
5806 if (is_idiv_op)
5807 {
5808 if (gogo->check_divide_by_zero())
5809 {
5810 // right == 0
5811 Bexpression* zero_expr =
5812 gogo->backend()->integer_constant_expression(right_btype, zero);
5813 Bexpression* check =
5814 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5815 right, zero_expr, loc);
5816
5817 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
5818 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5819 Bexpression* crash = gogo->runtime_error(errcode,
5820 loc)->get_backend(context);
5821
5822 // right == 0 ? (__go_runtime_error(...), 0) : ret
5823 ret = gogo->backend()->conditional_expression(btype, check, crash,
5824 ret, loc);
5825 }
5826
5827 if (gogo->check_divide_overflow())
5828 {
5829 // right == -1
5830 // FIXME: It would be nice to say that this test is expected
5831 // to return false.
5832
5833 Bexpression* neg_one_expr =
5834 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5835 Bexpression* check =
5836 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5837 right, neg_one_expr, loc);
5838
5839 Bexpression* zero_expr =
5840 gogo->backend()->integer_constant_expression(btype, zero);
5841 Bexpression* one_expr =
5842 gogo->backend()->integer_constant_expression(btype, one);
5843
5844 if (type->integer_type()->is_unsigned())
5845 {
5846 // An unsigned -1 is the largest possible number, so
5847 // dividing is always 1 or 0.
5848
5849 Bexpression* cmp =
5850 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5851 left, right, loc);
5852 if (this->op_ == OPERATOR_DIV)
5853 overflow =
5854 gogo->backend()->conditional_expression(btype, cmp,
5855 one_expr, zero_expr,
5856 loc);
5857 else
5858 overflow =
5859 gogo->backend()->conditional_expression(btype, cmp,
5860 zero_expr, left,
5861 loc);
5862 }
5863 else
5864 {
5865 // Computing left / -1 is the same as computing - left,
5866 // which does not overflow since Go sets -fwrapv.
5867 if (this->op_ == OPERATOR_DIV)
5868 {
5869 Expression* negate_expr =
5870 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
5871 overflow = negate_expr->get_backend(context);
5872 }
5873 else
5874 overflow = zero_expr;
5875 }
5876 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
5877
5878 // right == -1 ? - left : ret
5879 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5880 ret, loc);
5881 }
5882 }
5883
5884 mpz_clear(zero);
5885 mpz_clear(one);
5886 mpz_clear(neg_one);
5887 return ret;
5888 }
5889
5890 // Export a binary expression.
5891
5892 void
do_export(Export * exp) const5893 Binary_expression::do_export(Export* exp) const
5894 {
5895 exp->write_c_string("(");
5896 this->left_->export_expression(exp);
5897 switch (this->op_)
5898 {
5899 case OPERATOR_OROR:
5900 exp->write_c_string(" || ");
5901 break;
5902 case OPERATOR_ANDAND:
5903 exp->write_c_string(" && ");
5904 break;
5905 case OPERATOR_EQEQ:
5906 exp->write_c_string(" == ");
5907 break;
5908 case OPERATOR_NOTEQ:
5909 exp->write_c_string(" != ");
5910 break;
5911 case OPERATOR_LT:
5912 exp->write_c_string(" < ");
5913 break;
5914 case OPERATOR_LE:
5915 exp->write_c_string(" <= ");
5916 break;
5917 case OPERATOR_GT:
5918 exp->write_c_string(" > ");
5919 break;
5920 case OPERATOR_GE:
5921 exp->write_c_string(" >= ");
5922 break;
5923 case OPERATOR_PLUS:
5924 exp->write_c_string(" + ");
5925 break;
5926 case OPERATOR_MINUS:
5927 exp->write_c_string(" - ");
5928 break;
5929 case OPERATOR_OR:
5930 exp->write_c_string(" | ");
5931 break;
5932 case OPERATOR_XOR:
5933 exp->write_c_string(" ^ ");
5934 break;
5935 case OPERATOR_MULT:
5936 exp->write_c_string(" * ");
5937 break;
5938 case OPERATOR_DIV:
5939 exp->write_c_string(" / ");
5940 break;
5941 case OPERATOR_MOD:
5942 exp->write_c_string(" % ");
5943 break;
5944 case OPERATOR_LSHIFT:
5945 exp->write_c_string(" << ");
5946 break;
5947 case OPERATOR_RSHIFT:
5948 exp->write_c_string(" >> ");
5949 break;
5950 case OPERATOR_AND:
5951 exp->write_c_string(" & ");
5952 break;
5953 case OPERATOR_BITCLEAR:
5954 exp->write_c_string(" &^ ");
5955 break;
5956 default:
5957 go_unreachable();
5958 }
5959 this->right_->export_expression(exp);
5960 exp->write_c_string(")");
5961 }
5962
5963 // Import a binary expression.
5964
5965 Expression*
do_import(Import * imp)5966 Binary_expression::do_import(Import* imp)
5967 {
5968 imp->require_c_string("(");
5969
5970 Expression* left = Expression::import_expression(imp);
5971
5972 Operator op;
5973 if (imp->match_c_string(" || "))
5974 {
5975 op = OPERATOR_OROR;
5976 imp->advance(4);
5977 }
5978 else if (imp->match_c_string(" && "))
5979 {
5980 op = OPERATOR_ANDAND;
5981 imp->advance(4);
5982 }
5983 else if (imp->match_c_string(" == "))
5984 {
5985 op = OPERATOR_EQEQ;
5986 imp->advance(4);
5987 }
5988 else if (imp->match_c_string(" != "))
5989 {
5990 op = OPERATOR_NOTEQ;
5991 imp->advance(4);
5992 }
5993 else if (imp->match_c_string(" < "))
5994 {
5995 op = OPERATOR_LT;
5996 imp->advance(3);
5997 }
5998 else if (imp->match_c_string(" <= "))
5999 {
6000 op = OPERATOR_LE;
6001 imp->advance(4);
6002 }
6003 else if (imp->match_c_string(" > "))
6004 {
6005 op = OPERATOR_GT;
6006 imp->advance(3);
6007 }
6008 else if (imp->match_c_string(" >= "))
6009 {
6010 op = OPERATOR_GE;
6011 imp->advance(4);
6012 }
6013 else if (imp->match_c_string(" + "))
6014 {
6015 op = OPERATOR_PLUS;
6016 imp->advance(3);
6017 }
6018 else if (imp->match_c_string(" - "))
6019 {
6020 op = OPERATOR_MINUS;
6021 imp->advance(3);
6022 }
6023 else if (imp->match_c_string(" | "))
6024 {
6025 op = OPERATOR_OR;
6026 imp->advance(3);
6027 }
6028 else if (imp->match_c_string(" ^ "))
6029 {
6030 op = OPERATOR_XOR;
6031 imp->advance(3);
6032 }
6033 else if (imp->match_c_string(" * "))
6034 {
6035 op = OPERATOR_MULT;
6036 imp->advance(3);
6037 }
6038 else if (imp->match_c_string(" / "))
6039 {
6040 op = OPERATOR_DIV;
6041 imp->advance(3);
6042 }
6043 else if (imp->match_c_string(" % "))
6044 {
6045 op = OPERATOR_MOD;
6046 imp->advance(3);
6047 }
6048 else if (imp->match_c_string(" << "))
6049 {
6050 op = OPERATOR_LSHIFT;
6051 imp->advance(4);
6052 }
6053 else if (imp->match_c_string(" >> "))
6054 {
6055 op = OPERATOR_RSHIFT;
6056 imp->advance(4);
6057 }
6058 else if (imp->match_c_string(" & "))
6059 {
6060 op = OPERATOR_AND;
6061 imp->advance(3);
6062 }
6063 else if (imp->match_c_string(" &^ "))
6064 {
6065 op = OPERATOR_BITCLEAR;
6066 imp->advance(4);
6067 }
6068 else
6069 {
6070 error_at(imp->location(), "unrecognized binary operator");
6071 return Expression::make_error(imp->location());
6072 }
6073
6074 Expression* right = Expression::import_expression(imp);
6075
6076 imp->require_c_string(")");
6077
6078 return Expression::make_binary(op, left, right, imp->location());
6079 }
6080
6081 // Dump ast representation of a binary expression.
6082
6083 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6084 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6085 {
6086 ast_dump_context->ostream() << "(";
6087 ast_dump_context->dump_expression(this->left_);
6088 ast_dump_context->ostream() << " ";
6089 ast_dump_context->dump_operator(this->op_);
6090 ast_dump_context->ostream() << " ";
6091 ast_dump_context->dump_expression(this->right_);
6092 ast_dump_context->ostream() << ") ";
6093 }
6094
6095 // Make a binary expression.
6096
6097 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)6098 Expression::make_binary(Operator op, Expression* left, Expression* right,
6099 Location location)
6100 {
6101 return new Binary_expression(op, left, right, location);
6102 }
6103
6104 // Implement a comparison.
6105
6106 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)6107 Expression::comparison(Translate_context* context, Type* result_type,
6108 Operator op, Expression* left, Expression* right,
6109 Location location)
6110 {
6111 Type* left_type = left->type();
6112 Type* right_type = right->type();
6113
6114 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6115
6116 if (left_type->is_string_type() && right_type->is_string_type())
6117 {
6118 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6119 left, right);
6120 right = zexpr;
6121 }
6122 else if ((left_type->interface_type() != NULL
6123 && right_type->interface_type() == NULL
6124 && !right_type->is_nil_type())
6125 || (left_type->interface_type() == NULL
6126 && !left_type->is_nil_type()
6127 && right_type->interface_type() != NULL))
6128 {
6129 // Comparing an interface value to a non-interface value.
6130 if (left_type->interface_type() == NULL)
6131 {
6132 std::swap(left_type, right_type);
6133 std::swap(left, right);
6134 }
6135
6136 // The right operand is not an interface. We need to take its
6137 // address if it is not a pointer.
6138 Expression* pointer_arg = NULL;
6139 if (right_type->points_to() != NULL)
6140 pointer_arg = right;
6141 else
6142 {
6143 go_assert(right->is_addressable());
6144 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6145 location);
6146 }
6147
6148 Expression* descriptor =
6149 Expression::make_type_descriptor(right_type, location);
6150 left =
6151 Runtime::make_call((left_type->interface_type()->is_empty()
6152 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6153 : Runtime::INTERFACE_VALUE_COMPARE),
6154 location, 3, left, descriptor,
6155 pointer_arg);
6156 right = zexpr;
6157 }
6158 else if (left_type->interface_type() != NULL
6159 && right_type->interface_type() != NULL)
6160 {
6161 Runtime::Function compare_function;
6162 if (left_type->interface_type()->is_empty()
6163 && right_type->interface_type()->is_empty())
6164 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6165 else if (!left_type->interface_type()->is_empty()
6166 && !right_type->interface_type()->is_empty())
6167 compare_function = Runtime::INTERFACE_COMPARE;
6168 else
6169 {
6170 if (left_type->interface_type()->is_empty())
6171 {
6172 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6173 std::swap(left_type, right_type);
6174 std::swap(left, right);
6175 }
6176 go_assert(!left_type->interface_type()->is_empty());
6177 go_assert(right_type->interface_type()->is_empty());
6178 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6179 }
6180
6181 left = Runtime::make_call(compare_function, location, 2, left, right);
6182 right = zexpr;
6183 }
6184
6185 if (left_type->is_nil_type()
6186 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6187 {
6188 std::swap(left_type, right_type);
6189 std::swap(left, right);
6190 }
6191
6192 if (right_type->is_nil_type())
6193 {
6194 right = Expression::make_nil(location);
6195 if (left_type->array_type() != NULL
6196 && left_type->array_type()->length() == NULL)
6197 {
6198 Array_type* at = left_type->array_type();
6199 left = at->get_value_pointer(context->gogo(), left);
6200 }
6201 else if (left_type->interface_type() != NULL)
6202 {
6203 // An interface is nil if the first field is nil.
6204 left = Expression::make_field_reference(left, 0, location);
6205 }
6206 }
6207
6208 Bexpression* left_bexpr = left->get_backend(context);
6209 Bexpression* right_bexpr = right->get_backend(context);
6210
6211 Gogo* gogo = context->gogo();
6212 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6213 right_bexpr, location);
6214 if (result_type != NULL)
6215 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6216 ret, location);
6217 return ret;
6218 }
6219
6220 // Class Bound_method_expression.
6221
6222 // Traversal.
6223
6224 int
do_traverse(Traverse * traverse)6225 Bound_method_expression::do_traverse(Traverse* traverse)
6226 {
6227 return Expression::traverse(&this->expr_, traverse);
6228 }
6229
6230 // Lower the expression. If this is a method value rather than being
6231 // called, and the method is accessed via a pointer, we may need to
6232 // add nil checks. Introduce a temporary variable so that those nil
6233 // checks do not cause multiple evaluation.
6234
6235 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter * inserter,int)6236 Bound_method_expression::do_lower(Gogo*, Named_object*,
6237 Statement_inserter* inserter, int)
6238 {
6239 // For simplicity we use a temporary for every call to an embedded
6240 // method, even though some of them might be pure value methods and
6241 // not require a temporary.
6242 if (this->expr_->var_expression() == NULL
6243 && this->expr_->temporary_reference_expression() == NULL
6244 && this->expr_->set_and_use_temporary_expression() == NULL
6245 && (this->method_->field_indexes() != NULL
6246 || (this->method_->is_value_method()
6247 && this->expr_->type()->points_to() != NULL)))
6248 {
6249 Temporary_statement* temp =
6250 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6251 inserter->insert(temp);
6252 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6253 this->location());
6254 }
6255 return this;
6256 }
6257
6258 // Return the type of a bound method expression. The type of this
6259 // object is simply the type of the method with no receiver.
6260
6261 Type*
do_type()6262 Bound_method_expression::do_type()
6263 {
6264 Named_object* fn = this->method_->named_object();
6265 Function_type* fntype;
6266 if (fn->is_function())
6267 fntype = fn->func_value()->type();
6268 else if (fn->is_function_declaration())
6269 fntype = fn->func_declaration_value()->type();
6270 else
6271 return Type::make_error_type();
6272 return fntype->copy_without_receiver();
6273 }
6274
6275 // Determine the types of a method expression.
6276
6277 void
do_determine_type(const Type_context *)6278 Bound_method_expression::do_determine_type(const Type_context*)
6279 {
6280 Named_object* fn = this->method_->named_object();
6281 Function_type* fntype;
6282 if (fn->is_function())
6283 fntype = fn->func_value()->type();
6284 else if (fn->is_function_declaration())
6285 fntype = fn->func_declaration_value()->type();
6286 else
6287 fntype = NULL;
6288 if (fntype == NULL || !fntype->is_method())
6289 this->expr_->determine_type_no_context();
6290 else
6291 {
6292 Type_context subcontext(fntype->receiver()->type(), false);
6293 this->expr_->determine_type(&subcontext);
6294 }
6295 }
6296
6297 // Check the types of a method expression.
6298
6299 void
do_check_types(Gogo *)6300 Bound_method_expression::do_check_types(Gogo*)
6301 {
6302 Named_object* fn = this->method_->named_object();
6303 if (!fn->is_function() && !fn->is_function_declaration())
6304 {
6305 this->report_error(_("object is not a method"));
6306 return;
6307 }
6308
6309 Function_type* fntype;
6310 if (fn->is_function())
6311 fntype = fn->func_value()->type();
6312 else if (fn->is_function_declaration())
6313 fntype = fn->func_declaration_value()->type();
6314 else
6315 go_unreachable();
6316 Type* rtype = fntype->receiver()->type()->deref();
6317 Type* etype = (this->expr_type_ != NULL
6318 ? this->expr_type_
6319 : this->expr_->type());
6320 etype = etype->deref();
6321 if (!Type::are_identical(rtype, etype, true, NULL))
6322 this->report_error(_("method type does not match object type"));
6323 }
6324
6325 // If a bound method expression is not simply called, then it is
6326 // represented as a closure. The closure will hold a single variable,
6327 // the receiver to pass to the method. The function will be a simple
6328 // thunk that pulls that value from the closure and calls the method
6329 // with the remaining arguments.
6330 //
6331 // Because method values are not common, we don't build all thunks for
6332 // every methods, but instead only build them as we need them. In
6333 // particular, we even build them on demand for methods defined in
6334 // other packages.
6335
6336 Bound_method_expression::Method_value_thunks
6337 Bound_method_expression::method_value_thunks;
6338
6339 // Find or create the thunk for METHOD.
6340
6341 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)6342 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6343 Named_object* fn)
6344 {
6345 std::pair<Named_object*, Named_object*> val(fn, NULL);
6346 std::pair<Method_value_thunks::iterator, bool> ins =
6347 Bound_method_expression::method_value_thunks.insert(val);
6348 if (!ins.second)
6349 {
6350 // We have seen this method before.
6351 go_assert(ins.first->second != NULL);
6352 return ins.first->second;
6353 }
6354
6355 Location loc = fn->location();
6356
6357 Function_type* orig_fntype;
6358 if (fn->is_function())
6359 orig_fntype = fn->func_value()->type();
6360 else if (fn->is_function_declaration())
6361 orig_fntype = fn->func_declaration_value()->type();
6362 else
6363 orig_fntype = NULL;
6364
6365 if (orig_fntype == NULL || !orig_fntype->is_method())
6366 {
6367 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6368 return ins.first->second;
6369 }
6370
6371 Struct_field_list* sfl = new Struct_field_list();
6372 // The type here is wrong--it should be the C function type. But it
6373 // doesn't really matter.
6374 Type* vt = Type::make_pointer_type(Type::make_void_type());
6375 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6376 sfl->push_back(Struct_field(Typed_identifier("val.1",
6377 orig_fntype->receiver()->type(),
6378 loc)));
6379 Type* closure_type = Type::make_struct_type(sfl, loc);
6380 closure_type = Type::make_pointer_type(closure_type);
6381
6382 Function_type* new_fntype = orig_fntype->copy_with_names();
6383
6384 std::string thunk_name = Gogo::thunk_name();
6385 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6386 false, loc);
6387
6388 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6389 cvar->set_is_used();
6390 cvar->set_is_closure();
6391 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6392 NULL, cvar);
6393 new_no->func_value()->set_closure_var(cp);
6394
6395 gogo->start_block(loc);
6396
6397 // Field 0 of the closure is the function code pointer, field 1 is
6398 // the value on which to invoke the method.
6399 Expression* arg = Expression::make_var_reference(cp, loc);
6400 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6401 arg = Expression::make_field_reference(arg, 1, loc);
6402
6403 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6404
6405 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6406 Expression_list* args;
6407 if (orig_params == NULL || orig_params->empty())
6408 args = NULL;
6409 else
6410 {
6411 const Typed_identifier_list* new_params = new_fntype->parameters();
6412 args = new Expression_list();
6413 for (Typed_identifier_list::const_iterator p = new_params->begin();
6414 p != new_params->end();
6415 ++p)
6416 {
6417 Named_object* p_no = gogo->lookup(p->name(), NULL);
6418 go_assert(p_no != NULL
6419 && p_no->is_variable()
6420 && p_no->var_value()->is_parameter());
6421 args->push_back(Expression::make_var_reference(p_no, loc));
6422 }
6423 }
6424
6425 Call_expression* call = Expression::make_call(bme, args,
6426 orig_fntype->is_varargs(),
6427 loc);
6428 call->set_varargs_are_lowered();
6429
6430 Statement* s = Statement::make_return_from_call(call, loc);
6431 gogo->add_statement(s);
6432 Block* b = gogo->finish_block(loc);
6433 gogo->add_block(b, loc);
6434 gogo->lower_block(new_no, b);
6435 gogo->flatten_block(new_no, b);
6436 gogo->finish_function(loc);
6437
6438 ins.first->second = new_no;
6439 return new_no;
6440 }
6441
6442 // Return an expression to check *REF for nil while dereferencing
6443 // according to FIELD_INDEXES. Update *REF to build up the field
6444 // reference. This is a static function so that we don't have to
6445 // worry about declaring Field_indexes in expressions.h.
6446
6447 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)6448 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6449 Expression** ref)
6450 {
6451 if (field_indexes == NULL)
6452 return Expression::make_boolean(false, loc);
6453 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6454 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6455 go_assert(stype != NULL
6456 && field_indexes->field_index < stype->field_count());
6457 if ((*ref)->type()->struct_type() == NULL)
6458 {
6459 go_assert((*ref)->type()->points_to() != NULL);
6460 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6461 Expression::make_nil(loc),
6462 loc);
6463 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6464 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6465 go_assert((*ref)->type()->struct_type() == stype);
6466 }
6467 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6468 loc);
6469 return cond;
6470 }
6471
6472 // Get the backend representation for a method value.
6473
6474 Bexpression*
do_get_backend(Translate_context * context)6475 Bound_method_expression::do_get_backend(Translate_context* context)
6476 {
6477 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6478 this->method_,
6479 this->function_);
6480 if (thunk->is_erroneous())
6481 {
6482 go_assert(saw_errors());
6483 return context->backend()->error_expression();
6484 }
6485
6486 // FIXME: We should lower this earlier, but we can't lower it in the
6487 // lowering pass because at that point we don't know whether we need
6488 // to create the thunk or not. If the expression is called, we
6489 // don't need the thunk.
6490
6491 Location loc = this->location();
6492
6493 // If the method expects a value, and we have a pointer, we need to
6494 // dereference the pointer.
6495
6496 Named_object* fn = this->method_->named_object();
6497 Function_type* fntype;
6498 if (fn->is_function())
6499 fntype = fn->func_value()->type();
6500 else if (fn->is_function_declaration())
6501 fntype = fn->func_declaration_value()->type();
6502 else
6503 go_unreachable();
6504
6505 Expression* val = this->expr_;
6506 if (fntype->receiver()->type()->points_to() == NULL
6507 && val->type()->points_to() != NULL)
6508 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6509
6510 // Note that we are ignoring this->expr_type_ here. The thunk will
6511 // expect a closure whose second field has type this->expr_type_ (if
6512 // that is not NULL). We are going to pass it a closure whose
6513 // second field has type this->expr_->type(). Since
6514 // this->expr_type_ is only not-NULL for pointer types, we can get
6515 // away with this.
6516
6517 Struct_field_list* fields = new Struct_field_list();
6518 fields->push_back(Struct_field(Typed_identifier("fn.0",
6519 thunk->func_value()->type(),
6520 loc)));
6521 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6522 Struct_type* st = Type::make_struct_type(fields, loc);
6523
6524 Expression_list* vals = new Expression_list();
6525 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6526 vals->push_back(val);
6527
6528 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6529 ret = Expression::make_heap_expression(ret, loc);
6530
6531 // See whether the expression or any embedded pointers are nil.
6532
6533 Expression* nil_check = NULL;
6534 Expression* expr = this->expr_;
6535 if (this->method_->field_indexes() != NULL)
6536 {
6537 // Note that we are evaluating this->expr_ twice, but that is OK
6538 // because in the lowering pass we forced it into a temporary
6539 // variable.
6540 Expression* ref = expr;
6541 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6542 expr = ref;
6543 }
6544
6545 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6546 {
6547 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6548 Expression::make_nil(loc),
6549 loc);
6550 if (nil_check == NULL)
6551 nil_check = n;
6552 else
6553 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6554 }
6555
6556 Bexpression* bme = ret->get_backend(context);
6557 if (nil_check != NULL)
6558 {
6559 Gogo* gogo = context->gogo();
6560 Bexpression* crash =
6561 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6562 loc)->get_backend(context);
6563 Btype* btype = ret->type()->get_backend(gogo);
6564 Bexpression* bcheck = nil_check->get_backend(context);
6565 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6566 bme, loc);
6567 }
6568 return bme;
6569 }
6570
6571 // Dump ast representation of a bound method expression.
6572
6573 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6574 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6575 const
6576 {
6577 if (this->expr_type_ != NULL)
6578 ast_dump_context->ostream() << "(";
6579 ast_dump_context->dump_expression(this->expr_);
6580 if (this->expr_type_ != NULL)
6581 {
6582 ast_dump_context->ostream() << ":";
6583 ast_dump_context->dump_type(this->expr_type_);
6584 ast_dump_context->ostream() << ")";
6585 }
6586
6587 ast_dump_context->ostream() << "." << this->function_->name();
6588 }
6589
6590 // Make a method expression.
6591
6592 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)6593 Expression::make_bound_method(Expression* expr, const Method* method,
6594 Named_object* function, Location location)
6595 {
6596 return new Bound_method_expression(expr, method, function, location);
6597 }
6598
6599 // Class Builtin_call_expression. This is used for a call to a
6600 // builtin function.
6601
6602 class Builtin_call_expression : public Call_expression
6603 {
6604 public:
6605 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6606 bool is_varargs, Location location);
6607
6608 protected:
6609 // This overrides Call_expression::do_lower.
6610 Expression*
6611 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6612
6613 Expression*
6614 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6615
6616 bool
6617 do_is_constant() const;
6618
6619 bool
6620 do_numeric_constant_value(Numeric_constant*) const;
6621
6622 bool
6623 do_discarding_value();
6624
6625 Type*
6626 do_type();
6627
6628 void
6629 do_determine_type(const Type_context*);
6630
6631 void
6632 do_check_types(Gogo*);
6633
6634 Expression*
6635 do_copy();
6636
6637 Bexpression*
6638 do_get_backend(Translate_context*);
6639
6640 void
6641 do_export(Export*) const;
6642
6643 virtual bool
6644 do_is_recover_call() const;
6645
6646 virtual void
6647 do_set_recover_arg(Expression*);
6648
6649 private:
6650 // The builtin functions.
6651 enum Builtin_function_code
6652 {
6653 BUILTIN_INVALID,
6654
6655 // Predeclared builtin functions.
6656 BUILTIN_APPEND,
6657 BUILTIN_CAP,
6658 BUILTIN_CLOSE,
6659 BUILTIN_COMPLEX,
6660 BUILTIN_COPY,
6661 BUILTIN_DELETE,
6662 BUILTIN_IMAG,
6663 BUILTIN_LEN,
6664 BUILTIN_MAKE,
6665 BUILTIN_NEW,
6666 BUILTIN_PANIC,
6667 BUILTIN_PRINT,
6668 BUILTIN_PRINTLN,
6669 BUILTIN_REAL,
6670 BUILTIN_RECOVER,
6671
6672 // Builtin functions from the unsafe package.
6673 BUILTIN_ALIGNOF,
6674 BUILTIN_OFFSETOF,
6675 BUILTIN_SIZEOF
6676 };
6677
6678 Expression*
6679 one_arg() const;
6680
6681 bool
6682 check_one_arg();
6683
6684 static Type*
6685 real_imag_type(Type*);
6686
6687 static Type*
6688 complex_type(Type*);
6689
6690 Expression*
6691 lower_make();
6692
6693 bool
6694 check_int_value(Expression*, bool is_length);
6695
6696 // A pointer back to the general IR structure. This avoids a global
6697 // variable, or passing it around everywhere.
6698 Gogo* gogo_;
6699 // The builtin function being called.
6700 Builtin_function_code code_;
6701 // Used to stop endless loops when the length of an array uses len
6702 // or cap of the array itself.
6703 mutable bool seen_;
6704 // Whether the argument is set for calls to BUILTIN_RECOVER.
6705 bool recover_arg_is_set_;
6706 };
6707
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)6708 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6709 Expression* fn,
6710 Expression_list* args,
6711 bool is_varargs,
6712 Location location)
6713 : Call_expression(fn, args, is_varargs, location),
6714 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6715 recover_arg_is_set_(false)
6716 {
6717 Func_expression* fnexp = this->fn()->func_expression();
6718 if (fnexp == NULL)
6719 {
6720 this->code_ = BUILTIN_INVALID;
6721 return;
6722 }
6723 const std::string& name(fnexp->named_object()->name());
6724 if (name == "append")
6725 this->code_ = BUILTIN_APPEND;
6726 else if (name == "cap")
6727 this->code_ = BUILTIN_CAP;
6728 else if (name == "close")
6729 this->code_ = BUILTIN_CLOSE;
6730 else if (name == "complex")
6731 this->code_ = BUILTIN_COMPLEX;
6732 else if (name == "copy")
6733 this->code_ = BUILTIN_COPY;
6734 else if (name == "delete")
6735 this->code_ = BUILTIN_DELETE;
6736 else if (name == "imag")
6737 this->code_ = BUILTIN_IMAG;
6738 else if (name == "len")
6739 this->code_ = BUILTIN_LEN;
6740 else if (name == "make")
6741 this->code_ = BUILTIN_MAKE;
6742 else if (name == "new")
6743 this->code_ = BUILTIN_NEW;
6744 else if (name == "panic")
6745 this->code_ = BUILTIN_PANIC;
6746 else if (name == "print")
6747 this->code_ = BUILTIN_PRINT;
6748 else if (name == "println")
6749 this->code_ = BUILTIN_PRINTLN;
6750 else if (name == "real")
6751 this->code_ = BUILTIN_REAL;
6752 else if (name == "recover")
6753 this->code_ = BUILTIN_RECOVER;
6754 else if (name == "Alignof")
6755 this->code_ = BUILTIN_ALIGNOF;
6756 else if (name == "Offsetof")
6757 this->code_ = BUILTIN_OFFSETOF;
6758 else if (name == "Sizeof")
6759 this->code_ = BUILTIN_SIZEOF;
6760 else
6761 go_unreachable();
6762 }
6763
6764 // Return whether this is a call to recover. This is a virtual
6765 // function called from the parent class.
6766
6767 bool
do_is_recover_call() const6768 Builtin_call_expression::do_is_recover_call() const
6769 {
6770 if (this->classification() == EXPRESSION_ERROR)
6771 return false;
6772 return this->code_ == BUILTIN_RECOVER;
6773 }
6774
6775 // Set the argument for a call to recover.
6776
6777 void
do_set_recover_arg(Expression * arg)6778 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6779 {
6780 const Expression_list* args = this->args();
6781 go_assert(args == NULL || args->empty());
6782 Expression_list* new_args = new Expression_list();
6783 new_args->push_back(arg);
6784 this->set_args(new_args);
6785 this->recover_arg_is_set_ = true;
6786 }
6787
6788 // Lower a builtin call expression. This turns new and make into
6789 // specific expressions. We also convert to a constant if we can.
6790
6791 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)6792 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6793 Statement_inserter* inserter, int)
6794 {
6795 if (this->is_error_expression())
6796 return this;
6797
6798 Location loc = this->location();
6799
6800 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6801 {
6802 this->report_error(_("invalid use of %<...%> with builtin function"));
6803 return Expression::make_error(loc);
6804 }
6805
6806 if (this->code_ == BUILTIN_OFFSETOF)
6807 {
6808 Expression* arg = this->one_arg();
6809
6810 if (arg->bound_method_expression() != NULL
6811 || arg->interface_field_reference_expression() != NULL)
6812 {
6813 this->report_error(_("invalid use of method value as argument "
6814 "of Offsetof"));
6815 return this;
6816 }
6817
6818 Field_reference_expression* farg = arg->field_reference_expression();
6819 while (farg != NULL)
6820 {
6821 if (!farg->implicit())
6822 break;
6823 // When the selector refers to an embedded field,
6824 // it must not be reached through pointer indirections.
6825 if (farg->expr()->deref() != farg->expr())
6826 {
6827 this->report_error(_("argument of Offsetof implies "
6828 "indirection of an embedded field"));
6829 return this;
6830 }
6831 // Go up until we reach the original base.
6832 farg = farg->expr()->field_reference_expression();
6833 }
6834 }
6835
6836 if (this->is_constant())
6837 {
6838 Numeric_constant nc;
6839 if (this->numeric_constant_value(&nc))
6840 return nc.expression(loc);
6841 }
6842
6843 switch (this->code_)
6844 {
6845 default:
6846 break;
6847
6848 case BUILTIN_NEW:
6849 {
6850 const Expression_list* args = this->args();
6851 if (args == NULL || args->size() < 1)
6852 this->report_error(_("not enough arguments"));
6853 else if (args->size() > 1)
6854 this->report_error(_("too many arguments"));
6855 else
6856 {
6857 Expression* arg = args->front();
6858 if (!arg->is_type_expression())
6859 {
6860 error_at(arg->location(), "expected type");
6861 this->set_is_error();
6862 }
6863 else
6864 return Expression::make_allocation(arg->type(), loc);
6865 }
6866 }
6867 break;
6868
6869 case BUILTIN_MAKE:
6870 return this->lower_make();
6871
6872 case BUILTIN_RECOVER:
6873 if (function != NULL)
6874 function->func_value()->set_calls_recover();
6875 else
6876 {
6877 // Calling recover outside of a function always returns the
6878 // nil empty interface.
6879 Type* eface = Type::make_empty_interface_type(loc);
6880 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6881 }
6882 break;
6883
6884 case BUILTIN_APPEND:
6885 {
6886 // Lower the varargs.
6887 const Expression_list* args = this->args();
6888 if (args == NULL || args->empty())
6889 return this;
6890 Type* slice_type = args->front()->type();
6891 if (!slice_type->is_slice_type())
6892 {
6893 if (slice_type->is_nil_type())
6894 error_at(args->front()->location(), "use of untyped nil");
6895 else
6896 error_at(args->front()->location(),
6897 "argument 1 must be a slice");
6898 this->set_is_error();
6899 return this;
6900 }
6901 Type* element_type = slice_type->array_type()->element_type();
6902 this->lower_varargs(gogo, function, inserter,
6903 Type::make_array_type(element_type, NULL),
6904 2);
6905 }
6906 break;
6907
6908 case BUILTIN_DELETE:
6909 {
6910 // Lower to a runtime function call.
6911 const Expression_list* args = this->args();
6912 if (args == NULL || args->size() < 2)
6913 this->report_error(_("not enough arguments"));
6914 else if (args->size() > 2)
6915 this->report_error(_("too many arguments"));
6916 else if (args->front()->type()->map_type() == NULL)
6917 this->report_error(_("argument 1 must be a map"));
6918 else
6919 {
6920 // Since this function returns no value it must appear in
6921 // a statement by itself, so we don't have to worry about
6922 // order of evaluation of values around it. Evaluate the
6923 // map first to get order of evaluation right.
6924 Map_type* mt = args->front()->type()->map_type();
6925 Temporary_statement* map_temp =
6926 Statement::make_temporary(mt, args->front(), loc);
6927 inserter->insert(map_temp);
6928
6929 Temporary_statement* key_temp =
6930 Statement::make_temporary(mt->key_type(), args->back(), loc);
6931 inserter->insert(key_temp);
6932
6933 Expression* e1 = Expression::make_temporary_reference(map_temp,
6934 loc);
6935 Expression* e2 = Expression::make_temporary_reference(key_temp,
6936 loc);
6937 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6938 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6939 2, e1, e2);
6940 }
6941 }
6942 break;
6943 }
6944
6945 return this;
6946 }
6947
6948 // Flatten a builtin call expression. This turns the arguments of copy and
6949 // append into temporary expressions.
6950
6951 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)6952 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
6953 Statement_inserter* inserter)
6954 {
6955 Location loc = this->location();
6956
6957 switch (this->code_)
6958 {
6959 default:
6960 break;
6961
6962 case BUILTIN_APPEND:
6963 case BUILTIN_COPY:
6964 {
6965 Type* at = this->args()->front()->type();
6966 for (Expression_list::iterator pa = this->args()->begin();
6967 pa != this->args()->end();
6968 ++pa)
6969 {
6970 if ((*pa)->is_nil_expression())
6971 {
6972 Expression* nil = Expression::make_nil(loc);
6973 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
6974 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
6975 }
6976 if (!(*pa)->is_variable())
6977 {
6978 Temporary_statement* temp =
6979 Statement::make_temporary(NULL, *pa, loc);
6980 inserter->insert(temp);
6981 *pa = Expression::make_temporary_reference(temp, loc);
6982 }
6983 }
6984 }
6985 break;
6986
6987 case BUILTIN_PANIC:
6988 for (Expression_list::iterator pa = this->args()->begin();
6989 pa != this->args()->end();
6990 ++pa)
6991 {
6992 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
6993 {
6994 Temporary_statement* temp =
6995 Statement::make_temporary(NULL, *pa, loc);
6996 inserter->insert(temp);
6997 *pa = Expression::make_temporary_reference(temp, loc);
6998 }
6999 }
7000 }
7001
7002 return this;
7003 }
7004
7005 // Lower a make expression.
7006
7007 Expression*
lower_make()7008 Builtin_call_expression::lower_make()
7009 {
7010 Location loc = this->location();
7011
7012 const Expression_list* args = this->args();
7013 if (args == NULL || args->size() < 1)
7014 {
7015 this->report_error(_("not enough arguments"));
7016 return Expression::make_error(this->location());
7017 }
7018
7019 Expression_list::const_iterator parg = args->begin();
7020
7021 Expression* first_arg = *parg;
7022 if (!first_arg->is_type_expression())
7023 {
7024 error_at(first_arg->location(), "expected type");
7025 this->set_is_error();
7026 return Expression::make_error(this->location());
7027 }
7028 Type* type = first_arg->type();
7029
7030 bool is_slice = false;
7031 bool is_map = false;
7032 bool is_chan = false;
7033 if (type->is_slice_type())
7034 is_slice = true;
7035 else if (type->map_type() != NULL)
7036 is_map = true;
7037 else if (type->channel_type() != NULL)
7038 is_chan = true;
7039 else
7040 {
7041 this->report_error(_("invalid type for make function"));
7042 return Expression::make_error(this->location());
7043 }
7044
7045 bool have_big_args = false;
7046 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7047 int uintptr_bits = uintptr_type->integer_type()->bits();
7048
7049 Type_context int_context(Type::lookup_integer_type("int"), false);
7050
7051 ++parg;
7052 Expression* len_arg;
7053 if (parg == args->end())
7054 {
7055 if (is_slice)
7056 {
7057 this->report_error(_("length required when allocating a slice"));
7058 return Expression::make_error(this->location());
7059 }
7060 len_arg = Expression::make_integer_ul(0, NULL, loc);
7061 }
7062 else
7063 {
7064 len_arg = *parg;
7065 len_arg->determine_type(&int_context);
7066 if (!this->check_int_value(len_arg, true))
7067 return Expression::make_error(this->location());
7068 if (len_arg->type()->integer_type() != NULL
7069 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7070 have_big_args = true;
7071 ++parg;
7072 }
7073
7074 Expression* cap_arg = NULL;
7075 if (is_slice && parg != args->end())
7076 {
7077 cap_arg = *parg;
7078 cap_arg->determine_type(&int_context);
7079 if (!this->check_int_value(cap_arg, false))
7080 return Expression::make_error(this->location());
7081
7082 Numeric_constant nclen;
7083 Numeric_constant nccap;
7084 unsigned long vlen;
7085 unsigned long vcap;
7086 if (len_arg->numeric_constant_value(&nclen)
7087 && cap_arg->numeric_constant_value(&nccap)
7088 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7089 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7090 && vlen > vcap)
7091 {
7092 this->report_error(_("len larger than cap"));
7093 return Expression::make_error(this->location());
7094 }
7095
7096 if (cap_arg->type()->integer_type() != NULL
7097 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7098 have_big_args = true;
7099 ++parg;
7100 }
7101
7102 if (parg != args->end())
7103 {
7104 this->report_error(_("too many arguments to make"));
7105 return Expression::make_error(this->location());
7106 }
7107
7108 Location type_loc = first_arg->location();
7109 Expression* type_arg;
7110 if (is_slice || is_chan)
7111 type_arg = Expression::make_type_descriptor(type, type_loc);
7112 else if (is_map)
7113 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7114 else
7115 go_unreachable();
7116
7117 Expression* call;
7118 if (is_slice)
7119 {
7120 if (cap_arg == NULL)
7121 call = Runtime::make_call((have_big_args
7122 ? Runtime::MAKESLICE1BIG
7123 : Runtime::MAKESLICE1),
7124 loc, 2, type_arg, len_arg);
7125 else
7126 call = Runtime::make_call((have_big_args
7127 ? Runtime::MAKESLICE2BIG
7128 : Runtime::MAKESLICE2),
7129 loc, 3, type_arg, len_arg, cap_arg);
7130 }
7131 else if (is_map)
7132 call = Runtime::make_call((have_big_args
7133 ? Runtime::MAKEMAPBIG
7134 : Runtime::MAKEMAP),
7135 loc, 2, type_arg, len_arg);
7136 else if (is_chan)
7137 call = Runtime::make_call((have_big_args
7138 ? Runtime::MAKECHANBIG
7139 : Runtime::MAKECHAN),
7140 loc, 2, type_arg, len_arg);
7141 else
7142 go_unreachable();
7143
7144 return Expression::make_unsafe_cast(type, call, loc);
7145 }
7146
7147 // Return whether an expression has an integer value. Report an error
7148 // if not. This is used when handling calls to the predeclared make
7149 // function.
7150
7151 bool
check_int_value(Expression * e,bool is_length)7152 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7153 {
7154 Numeric_constant nc;
7155 if (e->numeric_constant_value(&nc))
7156 {
7157 unsigned long v;
7158 switch (nc.to_unsigned_long(&v))
7159 {
7160 case Numeric_constant::NC_UL_VALID:
7161 break;
7162 case Numeric_constant::NC_UL_NOTINT:
7163 error_at(e->location(), "non-integer %s argument to make",
7164 is_length ? "len" : "cap");
7165 return false;
7166 case Numeric_constant::NC_UL_NEGATIVE:
7167 error_at(e->location(), "negative %s argument to make",
7168 is_length ? "len" : "cap");
7169 return false;
7170 case Numeric_constant::NC_UL_BIG:
7171 // We don't want to give a compile-time error for a 64-bit
7172 // value on a 32-bit target.
7173 break;
7174 }
7175
7176 mpz_t val;
7177 if (!nc.to_int(&val))
7178 go_unreachable();
7179 int bits = mpz_sizeinbase(val, 2);
7180 mpz_clear(val);
7181 Type* int_type = Type::lookup_integer_type("int");
7182 if (bits >= int_type->integer_type()->bits())
7183 {
7184 error_at(e->location(), "%s argument too large for make",
7185 is_length ? "len" : "cap");
7186 return false;
7187 }
7188
7189 return true;
7190 }
7191
7192 if (e->type()->integer_type() != NULL)
7193 return true;
7194
7195 error_at(e->location(), "non-integer %s argument to make",
7196 is_length ? "len" : "cap");
7197 return false;
7198 }
7199
7200 // Return the type of the real or imag functions, given the type of
7201 // the argument. We need to map complex64 to float32 and complex128
7202 // to float64, so it has to be done by name. This returns NULL if it
7203 // can't figure out the type.
7204
7205 Type*
real_imag_type(Type * arg_type)7206 Builtin_call_expression::real_imag_type(Type* arg_type)
7207 {
7208 if (arg_type == NULL || arg_type->is_abstract())
7209 return NULL;
7210 Named_type* nt = arg_type->named_type();
7211 if (nt == NULL)
7212 return NULL;
7213 while (nt->real_type()->named_type() != NULL)
7214 nt = nt->real_type()->named_type();
7215 if (nt->name() == "complex64")
7216 return Type::lookup_float_type("float32");
7217 else if (nt->name() == "complex128")
7218 return Type::lookup_float_type("float64");
7219 else
7220 return NULL;
7221 }
7222
7223 // Return the type of the complex function, given the type of one of the
7224 // argments. Like real_imag_type, we have to map by name.
7225
7226 Type*
complex_type(Type * arg_type)7227 Builtin_call_expression::complex_type(Type* arg_type)
7228 {
7229 if (arg_type == NULL || arg_type->is_abstract())
7230 return NULL;
7231 Named_type* nt = arg_type->named_type();
7232 if (nt == NULL)
7233 return NULL;
7234 while (nt->real_type()->named_type() != NULL)
7235 nt = nt->real_type()->named_type();
7236 if (nt->name() == "float32")
7237 return Type::lookup_complex_type("complex64");
7238 else if (nt->name() == "float64")
7239 return Type::lookup_complex_type("complex128");
7240 else
7241 return NULL;
7242 }
7243
7244 // Return a single argument, or NULL if there isn't one.
7245
7246 Expression*
one_arg() const7247 Builtin_call_expression::one_arg() const
7248 {
7249 const Expression_list* args = this->args();
7250 if (args == NULL || args->size() != 1)
7251 return NULL;
7252 return args->front();
7253 }
7254
7255 // A traversal class which looks for a call or receive expression.
7256
7257 class Find_call_expression : public Traverse
7258 {
7259 public:
Find_call_expression()7260 Find_call_expression()
7261 : Traverse(traverse_expressions),
7262 found_(false)
7263 { }
7264
7265 int
7266 expression(Expression**);
7267
7268 bool
found()7269 found()
7270 { return this->found_; }
7271
7272 private:
7273 bool found_;
7274 };
7275
7276 int
expression(Expression ** pexpr)7277 Find_call_expression::expression(Expression** pexpr)
7278 {
7279 if ((*pexpr)->call_expression() != NULL
7280 || (*pexpr)->receive_expression() != NULL)
7281 {
7282 this->found_ = true;
7283 return TRAVERSE_EXIT;
7284 }
7285 return TRAVERSE_CONTINUE;
7286 }
7287
7288 // Return whether this is constant: len of a string constant, or len
7289 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7290 // unsafe.Alignof.
7291
7292 bool
do_is_constant() const7293 Builtin_call_expression::do_is_constant() const
7294 {
7295 if (this->is_error_expression())
7296 return true;
7297 switch (this->code_)
7298 {
7299 case BUILTIN_LEN:
7300 case BUILTIN_CAP:
7301 {
7302 if (this->seen_)
7303 return false;
7304
7305 Expression* arg = this->one_arg();
7306 if (arg == NULL)
7307 return false;
7308 Type* arg_type = arg->type();
7309
7310 if (arg_type->points_to() != NULL
7311 && arg_type->points_to()->array_type() != NULL
7312 && !arg_type->points_to()->is_slice_type())
7313 arg_type = arg_type->points_to();
7314
7315 // The len and cap functions are only constant if there are no
7316 // function calls or channel operations in the arguments.
7317 // Otherwise we have to make the call.
7318 if (!arg->is_constant())
7319 {
7320 Find_call_expression find_call;
7321 Expression::traverse(&arg, &find_call);
7322 if (find_call.found())
7323 return false;
7324 }
7325
7326 if (arg_type->array_type() != NULL
7327 && arg_type->array_type()->length() != NULL)
7328 return true;
7329
7330 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7331 {
7332 this->seen_ = true;
7333 bool ret = arg->is_constant();
7334 this->seen_ = false;
7335 return ret;
7336 }
7337 }
7338 break;
7339
7340 case BUILTIN_SIZEOF:
7341 case BUILTIN_ALIGNOF:
7342 return this->one_arg() != NULL;
7343
7344 case BUILTIN_OFFSETOF:
7345 {
7346 Expression* arg = this->one_arg();
7347 if (arg == NULL)
7348 return false;
7349 return arg->field_reference_expression() != NULL;
7350 }
7351
7352 case BUILTIN_COMPLEX:
7353 {
7354 const Expression_list* args = this->args();
7355 if (args != NULL && args->size() == 2)
7356 return args->front()->is_constant() && args->back()->is_constant();
7357 }
7358 break;
7359
7360 case BUILTIN_REAL:
7361 case BUILTIN_IMAG:
7362 {
7363 Expression* arg = this->one_arg();
7364 return arg != NULL && arg->is_constant();
7365 }
7366
7367 default:
7368 break;
7369 }
7370
7371 return false;
7372 }
7373
7374 // Return a numeric constant if possible.
7375
7376 bool
do_numeric_constant_value(Numeric_constant * nc) const7377 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7378 {
7379 if (this->code_ == BUILTIN_LEN
7380 || this->code_ == BUILTIN_CAP)
7381 {
7382 Expression* arg = this->one_arg();
7383 if (arg == NULL)
7384 return false;
7385 Type* arg_type = arg->type();
7386
7387 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7388 {
7389 std::string sval;
7390 if (arg->string_constant_value(&sval))
7391 {
7392 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7393 sval.length());
7394 return true;
7395 }
7396 }
7397
7398 if (arg_type->points_to() != NULL
7399 && arg_type->points_to()->array_type() != NULL
7400 && !arg_type->points_to()->is_slice_type())
7401 arg_type = arg_type->points_to();
7402
7403 if (arg_type->array_type() != NULL
7404 && arg_type->array_type()->length() != NULL)
7405 {
7406 if (this->seen_)
7407 return false;
7408 Expression* e = arg_type->array_type()->length();
7409 this->seen_ = true;
7410 bool r = e->numeric_constant_value(nc);
7411 this->seen_ = false;
7412 if (r)
7413 {
7414 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7415 this->location()))
7416 r = false;
7417 }
7418 return r;
7419 }
7420 }
7421 else if (this->code_ == BUILTIN_SIZEOF
7422 || this->code_ == BUILTIN_ALIGNOF)
7423 {
7424 Expression* arg = this->one_arg();
7425 if (arg == NULL)
7426 return false;
7427 Type* arg_type = arg->type();
7428 if (arg_type->is_error())
7429 return false;
7430 if (arg_type->is_abstract())
7431 return false;
7432 if (this->seen_)
7433 return false;
7434
7435 int64_t ret;
7436 if (this->code_ == BUILTIN_SIZEOF)
7437 {
7438 this->seen_ = true;
7439 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7440 this->seen_ = false;
7441 if (!ok)
7442 return false;
7443 }
7444 else if (this->code_ == BUILTIN_ALIGNOF)
7445 {
7446 bool ok;
7447 this->seen_ = true;
7448 if (arg->field_reference_expression() == NULL)
7449 ok = arg_type->backend_type_align(this->gogo_, &ret);
7450 else
7451 {
7452 // Calling unsafe.Alignof(s.f) returns the alignment of
7453 // the type of f when it is used as a field in a struct.
7454 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7455 }
7456 this->seen_ = false;
7457 if (!ok)
7458 return false;
7459 }
7460 else
7461 go_unreachable();
7462
7463 mpz_t zval;
7464 set_mpz_from_int64(&zval, ret);
7465 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7466 mpz_clear(zval);
7467 return true;
7468 }
7469 else if (this->code_ == BUILTIN_OFFSETOF)
7470 {
7471 Expression* arg = this->one_arg();
7472 if (arg == NULL)
7473 return false;
7474 Field_reference_expression* farg = arg->field_reference_expression();
7475 if (farg == NULL)
7476 return false;
7477 if (this->seen_)
7478 return false;
7479
7480 int64_t total_offset = 0;
7481 while (true)
7482 {
7483 Expression* struct_expr = farg->expr();
7484 Type* st = struct_expr->type();
7485 if (st->struct_type() == NULL)
7486 return false;
7487 if (st->named_type() != NULL)
7488 st->named_type()->convert(this->gogo_);
7489 int64_t offset;
7490 this->seen_ = true;
7491 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7492 farg->field_index(),
7493 &offset);
7494 this->seen_ = false;
7495 if (!ok)
7496 return false;
7497 total_offset += offset;
7498 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7499 {
7500 // Go up until we reach the original base.
7501 farg = struct_expr->field_reference_expression();
7502 continue;
7503 }
7504 break;
7505 }
7506 mpz_t zval;
7507 set_mpz_from_int64(&zval, total_offset);
7508 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7509 mpz_clear(zval);
7510 return true;
7511 }
7512 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7513 {
7514 Expression* arg = this->one_arg();
7515 if (arg == NULL)
7516 return false;
7517
7518 Numeric_constant argnc;
7519 if (!arg->numeric_constant_value(&argnc))
7520 return false;
7521
7522 mpc_t val;
7523 if (!argnc.to_complex(&val))
7524 return false;
7525
7526 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7527 if (this->code_ == BUILTIN_REAL)
7528 nc->set_float(type, mpc_realref(val));
7529 else
7530 nc->set_float(type, mpc_imagref(val));
7531 mpc_clear(val);
7532 return true;
7533 }
7534 else if (this->code_ == BUILTIN_COMPLEX)
7535 {
7536 const Expression_list* args = this->args();
7537 if (args == NULL || args->size() != 2)
7538 return false;
7539
7540 Numeric_constant rnc;
7541 if (!args->front()->numeric_constant_value(&rnc))
7542 return false;
7543 Numeric_constant inc;
7544 if (!args->back()->numeric_constant_value(&inc))
7545 return false;
7546
7547 if (rnc.type() != NULL
7548 && !rnc.type()->is_abstract()
7549 && inc.type() != NULL
7550 && !inc.type()->is_abstract()
7551 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7552 return false;
7553
7554 mpfr_t r;
7555 if (!rnc.to_float(&r))
7556 return false;
7557 mpfr_t i;
7558 if (!inc.to_float(&i))
7559 {
7560 mpfr_clear(r);
7561 return false;
7562 }
7563
7564 Type* arg_type = rnc.type();
7565 if (arg_type == NULL || arg_type->is_abstract())
7566 arg_type = inc.type();
7567
7568 mpc_t val;
7569 mpc_init2(val, mpc_precision);
7570 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
7571 mpfr_clear(r);
7572 mpfr_clear(i);
7573
7574 Type* type = Builtin_call_expression::complex_type(arg_type);
7575 nc->set_complex(type, val);
7576
7577 mpc_clear(val);
7578
7579 return true;
7580 }
7581
7582 return false;
7583 }
7584
7585 // Give an error if we are discarding the value of an expression which
7586 // should not normally be discarded. We don't give an error for
7587 // discarding the value of an ordinary function call, but we do for
7588 // builtin functions, purely for consistency with the gc compiler.
7589
7590 bool
do_discarding_value()7591 Builtin_call_expression::do_discarding_value()
7592 {
7593 switch (this->code_)
7594 {
7595 case BUILTIN_INVALID:
7596 default:
7597 go_unreachable();
7598
7599 case BUILTIN_APPEND:
7600 case BUILTIN_CAP:
7601 case BUILTIN_COMPLEX:
7602 case BUILTIN_IMAG:
7603 case BUILTIN_LEN:
7604 case BUILTIN_MAKE:
7605 case BUILTIN_NEW:
7606 case BUILTIN_REAL:
7607 case BUILTIN_ALIGNOF:
7608 case BUILTIN_OFFSETOF:
7609 case BUILTIN_SIZEOF:
7610 this->unused_value_error();
7611 return false;
7612
7613 case BUILTIN_CLOSE:
7614 case BUILTIN_COPY:
7615 case BUILTIN_DELETE:
7616 case BUILTIN_PANIC:
7617 case BUILTIN_PRINT:
7618 case BUILTIN_PRINTLN:
7619 case BUILTIN_RECOVER:
7620 return true;
7621 }
7622 }
7623
7624 // Return the type.
7625
7626 Type*
do_type()7627 Builtin_call_expression::do_type()
7628 {
7629 if (this->is_error_expression())
7630 return Type::make_error_type();
7631 switch (this->code_)
7632 {
7633 case BUILTIN_INVALID:
7634 default:
7635 return Type::make_error_type();
7636
7637 case BUILTIN_NEW:
7638 case BUILTIN_MAKE:
7639 {
7640 const Expression_list* args = this->args();
7641 if (args == NULL || args->empty())
7642 return Type::make_error_type();
7643 return Type::make_pointer_type(args->front()->type());
7644 }
7645
7646 case BUILTIN_CAP:
7647 case BUILTIN_COPY:
7648 case BUILTIN_LEN:
7649 return Type::lookup_integer_type("int");
7650
7651 case BUILTIN_ALIGNOF:
7652 case BUILTIN_OFFSETOF:
7653 case BUILTIN_SIZEOF:
7654 return Type::lookup_integer_type("uintptr");
7655
7656 case BUILTIN_CLOSE:
7657 case BUILTIN_DELETE:
7658 case BUILTIN_PANIC:
7659 case BUILTIN_PRINT:
7660 case BUILTIN_PRINTLN:
7661 return Type::make_void_type();
7662
7663 case BUILTIN_RECOVER:
7664 return Type::make_empty_interface_type(Linemap::predeclared_location());
7665
7666 case BUILTIN_APPEND:
7667 {
7668 const Expression_list* args = this->args();
7669 if (args == NULL || args->empty())
7670 return Type::make_error_type();
7671 Type *ret = args->front()->type();
7672 if (!ret->is_slice_type())
7673 return Type::make_error_type();
7674 return ret;
7675 }
7676
7677 case BUILTIN_REAL:
7678 case BUILTIN_IMAG:
7679 {
7680 Expression* arg = this->one_arg();
7681 if (arg == NULL)
7682 return Type::make_error_type();
7683 Type* t = arg->type();
7684 if (t->is_abstract())
7685 t = t->make_non_abstract_type();
7686 t = Builtin_call_expression::real_imag_type(t);
7687 if (t == NULL)
7688 t = Type::make_error_type();
7689 return t;
7690 }
7691
7692 case BUILTIN_COMPLEX:
7693 {
7694 const Expression_list* args = this->args();
7695 if (args == NULL || args->size() != 2)
7696 return Type::make_error_type();
7697 Type* t = args->front()->type();
7698 if (t->is_abstract())
7699 {
7700 t = args->back()->type();
7701 if (t->is_abstract())
7702 t = t->make_non_abstract_type();
7703 }
7704 t = Builtin_call_expression::complex_type(t);
7705 if (t == NULL)
7706 t = Type::make_error_type();
7707 return t;
7708 }
7709 }
7710 }
7711
7712 // Determine the type.
7713
7714 void
do_determine_type(const Type_context * context)7715 Builtin_call_expression::do_determine_type(const Type_context* context)
7716 {
7717 if (!this->determining_types())
7718 return;
7719
7720 this->fn()->determine_type_no_context();
7721
7722 const Expression_list* args = this->args();
7723
7724 bool is_print;
7725 Type* arg_type = NULL;
7726 switch (this->code_)
7727 {
7728 case BUILTIN_PRINT:
7729 case BUILTIN_PRINTLN:
7730 // Do not force a large integer constant to "int".
7731 is_print = true;
7732 break;
7733
7734 case BUILTIN_REAL:
7735 case BUILTIN_IMAG:
7736 arg_type = Builtin_call_expression::complex_type(context->type);
7737 if (arg_type == NULL)
7738 arg_type = Type::lookup_complex_type("complex128");
7739 is_print = false;
7740 break;
7741
7742 case BUILTIN_COMPLEX:
7743 {
7744 // For the complex function the type of one operand can
7745 // determine the type of the other, as in a binary expression.
7746 arg_type = Builtin_call_expression::real_imag_type(context->type);
7747 if (arg_type == NULL)
7748 arg_type = Type::lookup_float_type("float64");
7749 if (args != NULL && args->size() == 2)
7750 {
7751 Type* t1 = args->front()->type();
7752 Type* t2 = args->back()->type();
7753 if (!t1->is_abstract())
7754 arg_type = t1;
7755 else if (!t2->is_abstract())
7756 arg_type = t2;
7757 }
7758 is_print = false;
7759 }
7760 break;
7761
7762 default:
7763 is_print = false;
7764 break;
7765 }
7766
7767 if (args != NULL)
7768 {
7769 for (Expression_list::const_iterator pa = args->begin();
7770 pa != args->end();
7771 ++pa)
7772 {
7773 Type_context subcontext;
7774 subcontext.type = arg_type;
7775
7776 if (is_print)
7777 {
7778 // We want to print large constants, we so can't just
7779 // use the appropriate nonabstract type. Use uint64 for
7780 // an integer if we know it is nonnegative, otherwise
7781 // use int64 for a integer, otherwise use float64 for a
7782 // float or complex128 for a complex.
7783 Type* want_type = NULL;
7784 Type* atype = (*pa)->type();
7785 if (atype->is_abstract())
7786 {
7787 if (atype->integer_type() != NULL)
7788 {
7789 Numeric_constant nc;
7790 if (this->numeric_constant_value(&nc))
7791 {
7792 mpz_t val;
7793 if (nc.to_int(&val))
7794 {
7795 if (mpz_sgn(val) >= 0)
7796 want_type = Type::lookup_integer_type("uint64");
7797 mpz_clear(val);
7798 }
7799 }
7800 if (want_type == NULL)
7801 want_type = Type::lookup_integer_type("int64");
7802 }
7803 else if (atype->float_type() != NULL)
7804 want_type = Type::lookup_float_type("float64");
7805 else if (atype->complex_type() != NULL)
7806 want_type = Type::lookup_complex_type("complex128");
7807 else if (atype->is_abstract_string_type())
7808 want_type = Type::lookup_string_type();
7809 else if (atype->is_abstract_boolean_type())
7810 want_type = Type::lookup_bool_type();
7811 else
7812 go_unreachable();
7813 subcontext.type = want_type;
7814 }
7815 }
7816
7817 (*pa)->determine_type(&subcontext);
7818 }
7819 }
7820 }
7821
7822 // If there is exactly one argument, return true. Otherwise give an
7823 // error message and return false.
7824
7825 bool
check_one_arg()7826 Builtin_call_expression::check_one_arg()
7827 {
7828 const Expression_list* args = this->args();
7829 if (args == NULL || args->size() < 1)
7830 {
7831 this->report_error(_("not enough arguments"));
7832 return false;
7833 }
7834 else if (args->size() > 1)
7835 {
7836 this->report_error(_("too many arguments"));
7837 return false;
7838 }
7839 if (args->front()->is_error_expression()
7840 || args->front()->type()->is_error())
7841 {
7842 this->set_is_error();
7843 return false;
7844 }
7845 return true;
7846 }
7847
7848 // Check argument types for a builtin function.
7849
7850 void
do_check_types(Gogo *)7851 Builtin_call_expression::do_check_types(Gogo*)
7852 {
7853 if (this->is_error_expression())
7854 return;
7855 switch (this->code_)
7856 {
7857 case BUILTIN_INVALID:
7858 case BUILTIN_NEW:
7859 case BUILTIN_MAKE:
7860 case BUILTIN_DELETE:
7861 return;
7862
7863 case BUILTIN_LEN:
7864 case BUILTIN_CAP:
7865 {
7866 // The single argument may be either a string or an array or a
7867 // map or a channel, or a pointer to a closed array.
7868 if (this->check_one_arg())
7869 {
7870 Type* arg_type = this->one_arg()->type();
7871 if (arg_type->points_to() != NULL
7872 && arg_type->points_to()->array_type() != NULL
7873 && !arg_type->points_to()->is_slice_type())
7874 arg_type = arg_type->points_to();
7875 if (this->code_ == BUILTIN_CAP)
7876 {
7877 if (!arg_type->is_error()
7878 && arg_type->array_type() == NULL
7879 && arg_type->channel_type() == NULL)
7880 this->report_error(_("argument must be array or slice "
7881 "or channel"));
7882 }
7883 else
7884 {
7885 if (!arg_type->is_error()
7886 && !arg_type->is_string_type()
7887 && arg_type->array_type() == NULL
7888 && arg_type->map_type() == NULL
7889 && arg_type->channel_type() == NULL)
7890 this->report_error(_("argument must be string or "
7891 "array or slice or map or channel"));
7892 }
7893 }
7894 }
7895 break;
7896
7897 case BUILTIN_PRINT:
7898 case BUILTIN_PRINTLN:
7899 {
7900 const Expression_list* args = this->args();
7901 if (args == NULL)
7902 {
7903 if (this->code_ == BUILTIN_PRINT)
7904 warning_at(this->location(), 0,
7905 "no arguments for builtin function %<%s%>",
7906 (this->code_ == BUILTIN_PRINT
7907 ? "print"
7908 : "println"));
7909 }
7910 else
7911 {
7912 for (Expression_list::const_iterator p = args->begin();
7913 p != args->end();
7914 ++p)
7915 {
7916 Type* type = (*p)->type();
7917 if (type->is_error()
7918 || type->is_string_type()
7919 || type->integer_type() != NULL
7920 || type->float_type() != NULL
7921 || type->complex_type() != NULL
7922 || type->is_boolean_type()
7923 || type->points_to() != NULL
7924 || type->interface_type() != NULL
7925 || type->channel_type() != NULL
7926 || type->map_type() != NULL
7927 || type->function_type() != NULL
7928 || type->is_slice_type())
7929 ;
7930 else if ((*p)->is_type_expression())
7931 {
7932 // If this is a type expression it's going to give
7933 // an error anyhow, so we don't need one here.
7934 }
7935 else
7936 this->report_error(_("unsupported argument type to "
7937 "builtin function"));
7938 }
7939 }
7940 }
7941 break;
7942
7943 case BUILTIN_CLOSE:
7944 if (this->check_one_arg())
7945 {
7946 if (this->one_arg()->type()->channel_type() == NULL)
7947 this->report_error(_("argument must be channel"));
7948 else if (!this->one_arg()->type()->channel_type()->may_send())
7949 this->report_error(_("cannot close receive-only channel"));
7950 }
7951 break;
7952
7953 case BUILTIN_PANIC:
7954 case BUILTIN_SIZEOF:
7955 case BUILTIN_ALIGNOF:
7956 this->check_one_arg();
7957 break;
7958
7959 case BUILTIN_RECOVER:
7960 if (this->args() != NULL
7961 && !this->args()->empty()
7962 && !this->recover_arg_is_set_)
7963 this->report_error(_("too many arguments"));
7964 break;
7965
7966 case BUILTIN_OFFSETOF:
7967 if (this->check_one_arg())
7968 {
7969 Expression* arg = this->one_arg();
7970 if (arg->field_reference_expression() == NULL)
7971 this->report_error(_("argument must be a field reference"));
7972 }
7973 break;
7974
7975 case BUILTIN_COPY:
7976 {
7977 const Expression_list* args = this->args();
7978 if (args == NULL || args->size() < 2)
7979 {
7980 this->report_error(_("not enough arguments"));
7981 break;
7982 }
7983 else if (args->size() > 2)
7984 {
7985 this->report_error(_("too many arguments"));
7986 break;
7987 }
7988 Type* arg1_type = args->front()->type();
7989 Type* arg2_type = args->back()->type();
7990 if (arg1_type->is_error() || arg2_type->is_error())
7991 {
7992 this->set_is_error();
7993 break;
7994 }
7995
7996 Type* e1;
7997 if (arg1_type->is_slice_type())
7998 e1 = arg1_type->array_type()->element_type();
7999 else
8000 {
8001 this->report_error(_("left argument must be a slice"));
8002 break;
8003 }
8004
8005 if (arg2_type->is_slice_type())
8006 {
8007 Type* e2 = arg2_type->array_type()->element_type();
8008 if (!Type::are_identical(e1, e2, true, NULL))
8009 this->report_error(_("element types must be the same"));
8010 }
8011 else if (arg2_type->is_string_type())
8012 {
8013 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8014 this->report_error(_("first argument must be []byte"));
8015 }
8016 else
8017 this->report_error(_("second argument must be slice or string"));
8018 }
8019 break;
8020
8021 case BUILTIN_APPEND:
8022 {
8023 const Expression_list* args = this->args();
8024 if (args == NULL || args->size() < 2)
8025 {
8026 this->report_error(_("not enough arguments"));
8027 break;
8028 }
8029 if (args->size() > 2)
8030 {
8031 this->report_error(_("too many arguments"));
8032 break;
8033 }
8034 if (args->front()->type()->is_error()
8035 || args->back()->type()->is_error())
8036 {
8037 this->set_is_error();
8038 break;
8039 }
8040
8041 Array_type* at = args->front()->type()->array_type();
8042 Type* e = at->element_type();
8043
8044 // The language permits appending a string to a []byte, as a
8045 // special case.
8046 if (args->back()->type()->is_string_type())
8047 {
8048 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8049 break;
8050 }
8051
8052 // The language says that the second argument must be
8053 // assignable to a slice of the element type of the first
8054 // argument. We already know the first argument is a slice
8055 // type.
8056 Type* arg2_type = Type::make_array_type(e, NULL);
8057 std::string reason;
8058 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8059 {
8060 if (reason.empty())
8061 this->report_error(_("argument 2 has invalid type"));
8062 else
8063 {
8064 error_at(this->location(), "argument 2 has invalid type (%s)",
8065 reason.c_str());
8066 this->set_is_error();
8067 }
8068 }
8069 break;
8070 }
8071
8072 case BUILTIN_REAL:
8073 case BUILTIN_IMAG:
8074 if (this->check_one_arg())
8075 {
8076 if (this->one_arg()->type()->complex_type() == NULL)
8077 this->report_error(_("argument must have complex type"));
8078 }
8079 break;
8080
8081 case BUILTIN_COMPLEX:
8082 {
8083 const Expression_list* args = this->args();
8084 if (args == NULL || args->size() < 2)
8085 this->report_error(_("not enough arguments"));
8086 else if (args->size() > 2)
8087 this->report_error(_("too many arguments"));
8088 else if (args->front()->is_error_expression()
8089 || args->front()->type()->is_error()
8090 || args->back()->is_error_expression()
8091 || args->back()->type()->is_error())
8092 this->set_is_error();
8093 else if (!Type::are_identical(args->front()->type(),
8094 args->back()->type(), true, NULL))
8095 this->report_error(_("complex arguments must have identical types"));
8096 else if (args->front()->type()->float_type() == NULL)
8097 this->report_error(_("complex arguments must have "
8098 "floating-point type"));
8099 }
8100 break;
8101
8102 default:
8103 go_unreachable();
8104 }
8105 }
8106
8107 Expression*
do_copy()8108 Builtin_call_expression::do_copy()
8109 {
8110 Call_expression* bce =
8111 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8112 (this->args() == NULL
8113 ? NULL
8114 : this->args()->copy()),
8115 this->is_varargs(),
8116 this->location());
8117
8118 if (this->varargs_are_lowered())
8119 bce->set_varargs_are_lowered();
8120 return bce;
8121 }
8122
8123 // Return the backend representation for a builtin function.
8124
8125 Bexpression*
do_get_backend(Translate_context * context)8126 Builtin_call_expression::do_get_backend(Translate_context* context)
8127 {
8128 Gogo* gogo = context->gogo();
8129 Location location = this->location();
8130
8131 if (this->is_erroneous_call())
8132 {
8133 go_assert(saw_errors());
8134 return gogo->backend()->error_expression();
8135 }
8136
8137 switch (this->code_)
8138 {
8139 case BUILTIN_INVALID:
8140 case BUILTIN_NEW:
8141 case BUILTIN_MAKE:
8142 go_unreachable();
8143
8144 case BUILTIN_LEN:
8145 case BUILTIN_CAP:
8146 {
8147 const Expression_list* args = this->args();
8148 go_assert(args != NULL && args->size() == 1);
8149 Expression* arg = args->front();
8150 Type* arg_type = arg->type();
8151
8152 if (this->seen_)
8153 {
8154 go_assert(saw_errors());
8155 return context->backend()->error_expression();
8156 }
8157 this->seen_ = true;
8158 this->seen_ = false;
8159 if (arg_type->points_to() != NULL)
8160 {
8161 arg_type = arg_type->points_to();
8162 go_assert(arg_type->array_type() != NULL
8163 && !arg_type->is_slice_type());
8164 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8165 }
8166
8167 Type* int_type = Type::lookup_integer_type("int");
8168 Expression* val;
8169 if (this->code_ == BUILTIN_LEN)
8170 {
8171 if (arg_type->is_string_type())
8172 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8173 location);
8174 else if (arg_type->array_type() != NULL)
8175 {
8176 if (this->seen_)
8177 {
8178 go_assert(saw_errors());
8179 return context->backend()->error_expression();
8180 }
8181 this->seen_ = true;
8182 val = arg_type->array_type()->get_length(gogo, arg);
8183 this->seen_ = false;
8184 }
8185 else if (arg_type->map_type() != NULL)
8186 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8187 else if (arg_type->channel_type() != NULL)
8188 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8189 else
8190 go_unreachable();
8191 }
8192 else
8193 {
8194 if (arg_type->array_type() != NULL)
8195 {
8196 if (this->seen_)
8197 {
8198 go_assert(saw_errors());
8199 return context->backend()->error_expression();
8200 }
8201 this->seen_ = true;
8202 val = arg_type->array_type()->get_capacity(gogo, arg);
8203 this->seen_ = false;
8204 }
8205 else if (arg_type->channel_type() != NULL)
8206 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8207 else
8208 go_unreachable();
8209 }
8210
8211 return Expression::make_cast(int_type, val,
8212 location)->get_backend(context);
8213 }
8214
8215 case BUILTIN_PRINT:
8216 case BUILTIN_PRINTLN:
8217 {
8218 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8219 Expression* print_stmts = NULL;
8220
8221 const Expression_list* call_args = this->args();
8222 if (call_args != NULL)
8223 {
8224 for (Expression_list::const_iterator p = call_args->begin();
8225 p != call_args->end();
8226 ++p)
8227 {
8228 if (is_ln && p != call_args->begin())
8229 {
8230 Expression* print_space =
8231 Runtime::make_call(Runtime::PRINT_SPACE,
8232 this->location(), 0);
8233
8234 print_stmts =
8235 Expression::make_compound(print_stmts, print_space,
8236 location);
8237 }
8238
8239 Expression* arg = *p;
8240 Type* type = arg->type();
8241 Runtime::Function code;
8242 if (type->is_string_type())
8243 code = Runtime::PRINT_STRING;
8244 else if (type->integer_type() != NULL
8245 && type->integer_type()->is_unsigned())
8246 {
8247 Type* itype = Type::lookup_integer_type("uint64");
8248 arg = Expression::make_cast(itype, arg, location);
8249 code = Runtime::PRINT_UINT64;
8250 }
8251 else if (type->integer_type() != NULL)
8252 {
8253 Type* itype = Type::lookup_integer_type("int64");
8254 arg = Expression::make_cast(itype, arg, location);
8255 code = Runtime::PRINT_INT64;
8256 }
8257 else if (type->float_type() != NULL)
8258 {
8259 Type* dtype = Type::lookup_float_type("float64");
8260 arg = Expression::make_cast(dtype, arg, location);
8261 code = Runtime::PRINT_DOUBLE;
8262 }
8263 else if (type->complex_type() != NULL)
8264 {
8265 Type* ctype = Type::lookup_complex_type("complex128");
8266 arg = Expression::make_cast(ctype, arg, location);
8267 code = Runtime::PRINT_COMPLEX;
8268 }
8269 else if (type->is_boolean_type())
8270 code = Runtime::PRINT_BOOL;
8271 else if (type->points_to() != NULL
8272 || type->channel_type() != NULL
8273 || type->map_type() != NULL
8274 || type->function_type() != NULL)
8275 {
8276 arg = Expression::make_cast(type, arg, location);
8277 code = Runtime::PRINT_POINTER;
8278 }
8279 else if (type->interface_type() != NULL)
8280 {
8281 if (type->interface_type()->is_empty())
8282 code = Runtime::PRINT_EMPTY_INTERFACE;
8283 else
8284 code = Runtime::PRINT_INTERFACE;
8285 }
8286 else if (type->is_slice_type())
8287 code = Runtime::PRINT_SLICE;
8288 else
8289 {
8290 go_assert(saw_errors());
8291 return context->backend()->error_expression();
8292 }
8293
8294 Expression* call = Runtime::make_call(code, location, 1, arg);
8295 if (print_stmts == NULL)
8296 print_stmts = call;
8297 else
8298 print_stmts = Expression::make_compound(print_stmts, call,
8299 location);
8300 }
8301 }
8302
8303 if (is_ln)
8304 {
8305 Expression* print_nl =
8306 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8307 if (print_stmts == NULL)
8308 print_stmts = print_nl;
8309 else
8310 print_stmts = Expression::make_compound(print_stmts, print_nl,
8311 location);
8312 }
8313
8314 // There aren't any arguments to the print builtin. The compiler
8315 // issues a warning for this so we should avoid getting the backend
8316 // representation for this call. Instead, perform a no-op.
8317 if (print_stmts == NULL)
8318 return context->backend()->boolean_constant_expression(false);
8319
8320 return print_stmts->get_backend(context);
8321 }
8322
8323 case BUILTIN_PANIC:
8324 {
8325 const Expression_list* args = this->args();
8326 go_assert(args != NULL && args->size() == 1);
8327 Expression* arg = args->front();
8328 Type *empty =
8329 Type::make_empty_interface_type(Linemap::predeclared_location());
8330 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8331
8332 Expression* panic =
8333 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8334 return panic->get_backend(context);
8335 }
8336
8337 case BUILTIN_RECOVER:
8338 {
8339 // The argument is set when building recover thunks. It's a
8340 // boolean value which is true if we can recover a value now.
8341 const Expression_list* args = this->args();
8342 go_assert(args != NULL && args->size() == 1);
8343 Expression* arg = args->front();
8344 Type *empty =
8345 Type::make_empty_interface_type(Linemap::predeclared_location());
8346
8347 Expression* nil = Expression::make_nil(location);
8348 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8349
8350 // We need to handle a deferred call to recover specially,
8351 // because it changes whether it can recover a panic or not.
8352 // See test7 in test/recover1.go.
8353 Expression* recover = Runtime::make_call((this->is_deferred()
8354 ? Runtime::DEFERRED_RECOVER
8355 : Runtime::RECOVER),
8356 location, 0);
8357 Expression* cond =
8358 Expression::make_conditional(arg, recover, nil, location);
8359 return cond->get_backend(context);
8360 }
8361
8362 case BUILTIN_CLOSE:
8363 {
8364 const Expression_list* args = this->args();
8365 go_assert(args != NULL && args->size() == 1);
8366 Expression* arg = args->front();
8367 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8368 1, arg);
8369 return close->get_backend(context);
8370 }
8371
8372 case BUILTIN_SIZEOF:
8373 case BUILTIN_OFFSETOF:
8374 case BUILTIN_ALIGNOF:
8375 {
8376 Numeric_constant nc;
8377 unsigned long val;
8378 if (!this->numeric_constant_value(&nc)
8379 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8380 {
8381 go_assert(saw_errors());
8382 return context->backend()->error_expression();
8383 }
8384 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8385 mpz_t ival;
8386 nc.get_int(&ival);
8387 Expression* int_cst =
8388 Expression::make_integer_z(&ival, uintptr_type, location);
8389 mpz_clear(ival);
8390 return int_cst->get_backend(context);
8391 }
8392
8393 case BUILTIN_COPY:
8394 {
8395 const Expression_list* args = this->args();
8396 go_assert(args != NULL && args->size() == 2);
8397 Expression* arg1 = args->front();
8398 Expression* arg2 = args->back();
8399
8400 Type* arg1_type = arg1->type();
8401 Array_type* at = arg1_type->array_type();
8402 go_assert(arg1->is_variable());
8403 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8404 Expression* arg1_len = at->get_length(gogo, arg1);
8405
8406 Type* arg2_type = arg2->type();
8407 go_assert(arg2->is_variable());
8408 Expression* arg2_val;
8409 Expression* arg2_len;
8410 if (arg2_type->is_slice_type())
8411 {
8412 at = arg2_type->array_type();
8413 arg2_val = at->get_value_pointer(gogo, arg2);
8414 arg2_len = at->get_length(gogo, arg2);
8415 }
8416 else
8417 {
8418 go_assert(arg2->is_variable());
8419 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8420 location);
8421 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8422 location);
8423 }
8424 Expression* cond =
8425 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8426 Expression* length =
8427 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8428
8429 Type* element_type = at->element_type();
8430 int64_t element_size;
8431 bool ok = element_type->backend_type_size(gogo, &element_size);
8432 if (!ok)
8433 {
8434 go_assert(saw_errors());
8435 return gogo->backend()->error_expression();
8436 }
8437
8438 Expression* size_expr = Expression::make_integer_int64(element_size,
8439 length->type(),
8440 location);
8441 Expression* bytecount =
8442 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8443 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8444 arg1_val, arg2_val, bytecount);
8445
8446 Expression* compound = Expression::make_compound(copy, length, location);
8447 return compound->get_backend(context);
8448 }
8449
8450 case BUILTIN_APPEND:
8451 {
8452 const Expression_list* args = this->args();
8453 go_assert(args != NULL && args->size() == 2);
8454 Expression* arg1 = args->front();
8455 Expression* arg2 = args->back();
8456
8457 Array_type* at = arg1->type()->array_type();
8458 Type* element_type = at->element_type()->forwarded();
8459
8460 go_assert(arg2->is_variable());
8461 Expression* arg2_val;
8462 Expression* arg2_len;
8463 int64_t size;
8464 if (arg2->type()->is_string_type()
8465 && element_type->integer_type() != NULL
8466 && element_type->integer_type()->is_byte())
8467 {
8468 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8469 location);
8470 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8471 location);
8472 size = 1;
8473 }
8474 else
8475 {
8476 arg2_val = at->get_value_pointer(gogo, arg2);
8477 arg2_len = at->get_length(gogo, arg2);
8478 bool ok = element_type->backend_type_size(gogo, &size);
8479 if (!ok)
8480 {
8481 go_assert(saw_errors());
8482 return gogo->backend()->error_expression();
8483 }
8484 }
8485 Expression* element_size =
8486 Expression::make_integer_int64(size, NULL, location);
8487
8488 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8489 arg1, arg2_val, arg2_len,
8490 element_size);
8491 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8492 return append->get_backend(context);
8493 }
8494
8495 case BUILTIN_REAL:
8496 case BUILTIN_IMAG:
8497 {
8498 const Expression_list* args = this->args();
8499 go_assert(args != NULL && args->size() == 1);
8500
8501 Bexpression* ret;
8502 Bexpression* bcomplex = args->front()->get_backend(context);
8503 if (this->code_ == BUILTIN_REAL)
8504 ret = gogo->backend()->real_part_expression(bcomplex, location);
8505 else
8506 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8507 return ret;
8508 }
8509
8510 case BUILTIN_COMPLEX:
8511 {
8512 const Expression_list* args = this->args();
8513 go_assert(args != NULL && args->size() == 2);
8514 Bexpression* breal = args->front()->get_backend(context);
8515 Bexpression* bimag = args->back()->get_backend(context);
8516 return gogo->backend()->complex_expression(breal, bimag, location);
8517 }
8518
8519 default:
8520 go_unreachable();
8521 }
8522 }
8523
8524 // We have to support exporting a builtin call expression, because
8525 // code can set a constant to the result of a builtin expression.
8526
8527 void
do_export(Export * exp) const8528 Builtin_call_expression::do_export(Export* exp) const
8529 {
8530 Numeric_constant nc;
8531 if (!this->numeric_constant_value(&nc))
8532 {
8533 error_at(this->location(), "value is not constant");
8534 return;
8535 }
8536
8537 if (nc.is_int())
8538 {
8539 mpz_t val;
8540 nc.get_int(&val);
8541 Integer_expression::export_integer(exp, val);
8542 mpz_clear(val);
8543 }
8544 else if (nc.is_float())
8545 {
8546 mpfr_t fval;
8547 nc.get_float(&fval);
8548 Float_expression::export_float(exp, fval);
8549 mpfr_clear(fval);
8550 }
8551 else if (nc.is_complex())
8552 {
8553 mpc_t cval;
8554 nc.get_complex(&cval);
8555 Complex_expression::export_complex(exp, cval);
8556 mpc_clear(cval);
8557 }
8558 else
8559 go_unreachable();
8560
8561 // A trailing space lets us reliably identify the end of the number.
8562 exp->write_c_string(" ");
8563 }
8564
8565 // Class Call_expression.
8566
8567 // A Go function can be viewed in a couple of different ways. The
8568 // code of a Go function becomes a backend function with parameters
8569 // whose types are simply the backend representation of the Go types.
8570 // If there are multiple results, they are returned as a backend
8571 // struct.
8572
8573 // However, when Go code refers to a function other than simply
8574 // calling it, the backend type of that function is actually a struct.
8575 // The first field of the struct points to the Go function code
8576 // (sometimes a wrapper as described below). The remaining fields
8577 // hold addresses of closed-over variables. This struct is called a
8578 // closure.
8579
8580 // There are a few cases to consider.
8581
8582 // A direct function call of a known function in package scope. In
8583 // this case there are no closed-over variables, and we know the name
8584 // of the function code. We can simply produce a backend call to the
8585 // function directly, and not worry about the closure.
8586
8587 // A direct function call of a known function literal. In this case
8588 // we know the function code and we know the closure. We generate the
8589 // function code such that it expects an additional final argument of
8590 // the closure type. We pass the closure as the last argument, after
8591 // the other arguments.
8592
8593 // An indirect function call. In this case we have a closure. We
8594 // load the pointer to the function code from the first field of the
8595 // closure. We pass the address of the closure as the last argument.
8596
8597 // A call to a method of an interface. Type methods are always at
8598 // package scope, so we call the function directly, and don't worry
8599 // about the closure.
8600
8601 // This means that for a function at package scope we have two cases.
8602 // One is the direct call, which has no closure. The other is the
8603 // indirect call, which does have a closure. We can't simply ignore
8604 // the closure, even though it is the last argument, because that will
8605 // fail on targets where the function pops its arguments. So when
8606 // generating a closure for a package-scope function we set the
8607 // function code pointer in the closure to point to a wrapper
8608 // function. This wrapper function accepts a final argument that
8609 // points to the closure, ignores it, and calls the real function as a
8610 // direct function call. This wrapper will normally be efficient, and
8611 // can often simply be a tail call to the real function.
8612
8613 // We don't use GCC's static chain pointer because 1) we don't need
8614 // it; 2) GCC only permits using a static chain to call a known
8615 // function, so we can't use it for an indirect call anyhow. Since we
8616 // can't use it for an indirect call, we may as well not worry about
8617 // using it for a direct call either.
8618
8619 // We pass the closure last rather than first because it means that
8620 // the function wrapper we put into a closure for a package-scope
8621 // function can normally just be a tail call to the real function.
8622
8623 // For method expressions we generate a wrapper that loads the
8624 // receiver from the closure and then calls the method. This
8625 // unfortunately forces reshuffling the arguments, since there is a
8626 // new first argument, but we can't avoid reshuffling either for
8627 // method expressions or for indirect calls of package-scope
8628 // functions, and since the latter are more common we reshuffle for
8629 // method expressions.
8630
8631 // Note that the Go code retains the Go types. The extra final
8632 // argument only appears when we convert to the backend
8633 // representation.
8634
8635 // Traversal.
8636
8637 int
do_traverse(Traverse * traverse)8638 Call_expression::do_traverse(Traverse* traverse)
8639 {
8640 // If we are calling a function in a different package that returns
8641 // an unnamed type, this may be the only chance we get to traverse
8642 // that type. We don't traverse this->type_ because it may be a
8643 // Call_multiple_result_type that will just lead back here.
8644 if (this->type_ != NULL && !this->type_->is_error_type())
8645 {
8646 Function_type *fntype = this->get_function_type();
8647 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
8648 return TRAVERSE_EXIT;
8649 }
8650 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8651 return TRAVERSE_EXIT;
8652 if (this->args_ != NULL)
8653 {
8654 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8655 return TRAVERSE_EXIT;
8656 }
8657 return TRAVERSE_CONTINUE;
8658 }
8659
8660 // Lower a call statement.
8661
8662 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)8663 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8664 Statement_inserter* inserter, int)
8665 {
8666 Location loc = this->location();
8667
8668 // A type cast can look like a function call.
8669 if (this->fn_->is_type_expression()
8670 && this->args_ != NULL
8671 && this->args_->size() == 1)
8672 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8673 loc);
8674
8675 // Because do_type will return an error type and thus prevent future
8676 // errors, check for that case now to ensure that the error gets
8677 // reported.
8678 Function_type* fntype = this->get_function_type();
8679 if (fntype == NULL)
8680 {
8681 if (!this->fn_->type()->is_error())
8682 this->report_error(_("expected function"));
8683 this->set_is_error();
8684 return this;
8685 }
8686
8687 // Handle an argument which is a call to a function which returns
8688 // multiple results.
8689 if (this->args_ != NULL
8690 && this->args_->size() == 1
8691 && this->args_->front()->call_expression() != NULL)
8692 {
8693 size_t rc = this->args_->front()->call_expression()->result_count();
8694 if (rc > 1
8695 && ((fntype->parameters() != NULL
8696 && (fntype->parameters()->size() == rc
8697 || (fntype->is_varargs()
8698 && fntype->parameters()->size() - 1 <= rc)))
8699 || fntype->is_builtin()))
8700 {
8701 Call_expression* call = this->args_->front()->call_expression();
8702 call->set_is_multi_value_arg();
8703 if (this->is_varargs_)
8704 {
8705 // It is not clear which result of a multiple result call
8706 // the ellipsis operator should be applied to. If we unpack the
8707 // the call into its individual results here, the ellipsis will be
8708 // applied to the last result.
8709 error_at(call->location(),
8710 _("multiple-value argument in single-value context"));
8711 return Expression::make_error(call->location());
8712 }
8713
8714 Expression_list* args = new Expression_list;
8715 for (size_t i = 0; i < rc; ++i)
8716 args->push_back(Expression::make_call_result(call, i));
8717 // We can't return a new call expression here, because this
8718 // one may be referenced by Call_result expressions. We
8719 // also can't delete the old arguments, because we may still
8720 // traverse them somewhere up the call stack. FIXME.
8721 this->args_ = args;
8722 }
8723 }
8724
8725 // Recognize a call to a builtin function.
8726 if (fntype->is_builtin())
8727 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8728 this->is_varargs_, loc);
8729
8730 // If this call returns multiple results, create a temporary
8731 // variable for each result.
8732 size_t rc = this->result_count();
8733 if (rc > 1 && this->results_ == NULL)
8734 {
8735 std::vector<Temporary_statement*>* temps =
8736 new std::vector<Temporary_statement*>;
8737 temps->reserve(rc);
8738 const Typed_identifier_list* results = fntype->results();
8739 for (Typed_identifier_list::const_iterator p = results->begin();
8740 p != results->end();
8741 ++p)
8742 {
8743 Temporary_statement* temp = Statement::make_temporary(p->type(),
8744 NULL, loc);
8745 inserter->insert(temp);
8746 temps->push_back(temp);
8747 }
8748 this->results_ = temps;
8749 }
8750
8751 // Handle a call to a varargs function by packaging up the extra
8752 // parameters.
8753 if (fntype->is_varargs())
8754 {
8755 const Typed_identifier_list* parameters = fntype->parameters();
8756 go_assert(parameters != NULL && !parameters->empty());
8757 Type* varargs_type = parameters->back().type();
8758 this->lower_varargs(gogo, function, inserter, varargs_type,
8759 parameters->size());
8760 }
8761
8762 // If this is call to a method, call the method directly passing the
8763 // object as the first parameter.
8764 Bound_method_expression* bme = this->fn_->bound_method_expression();
8765 if (bme != NULL)
8766 {
8767 Named_object* methodfn = bme->function();
8768 Expression* first_arg = bme->first_argument();
8769
8770 // We always pass a pointer when calling a method.
8771 if (first_arg->type()->points_to() == NULL
8772 && !first_arg->type()->is_error())
8773 {
8774 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8775 // We may need to create a temporary variable so that we can
8776 // take the address. We can't do that here because it will
8777 // mess up the order of evaluation.
8778 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8779 ue->set_create_temp();
8780 }
8781
8782 // If we are calling a method which was inherited from an
8783 // embedded struct, and the method did not get a stub, then the
8784 // first type may be wrong.
8785 Type* fatype = bme->first_argument_type();
8786 if (fatype != NULL)
8787 {
8788 if (fatype->points_to() == NULL)
8789 fatype = Type::make_pointer_type(fatype);
8790 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8791 }
8792
8793 Expression_list* new_args = new Expression_list();
8794 new_args->push_back(first_arg);
8795 if (this->args_ != NULL)
8796 {
8797 for (Expression_list::const_iterator p = this->args_->begin();
8798 p != this->args_->end();
8799 ++p)
8800 new_args->push_back(*p);
8801 }
8802
8803 // We have to change in place because this structure may be
8804 // referenced by Call_result_expressions. We can't delete the
8805 // old arguments, because we may be traversing them up in some
8806 // caller. FIXME.
8807 this->args_ = new_args;
8808 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8809 bme->location());
8810 }
8811
8812 return this;
8813 }
8814
8815 // Lower a call to a varargs function. FUNCTION is the function in
8816 // which the call occurs--it's not the function we are calling.
8817 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8818 // PARAM_COUNT is the number of parameters of the function we are
8819 // calling; the last of these parameters will be the varargs
8820 // parameter.
8821
8822 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count)8823 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8824 Statement_inserter* inserter,
8825 Type* varargs_type, size_t param_count)
8826 {
8827 if (this->varargs_are_lowered_)
8828 return;
8829
8830 Location loc = this->location();
8831
8832 go_assert(param_count > 0);
8833 go_assert(varargs_type->is_slice_type());
8834
8835 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8836 if (arg_count < param_count - 1)
8837 {
8838 // Not enough arguments; will be caught in check_types.
8839 return;
8840 }
8841
8842 Expression_list* old_args = this->args_;
8843 Expression_list* new_args = new Expression_list();
8844 bool push_empty_arg = false;
8845 if (old_args == NULL || old_args->empty())
8846 {
8847 go_assert(param_count == 1);
8848 push_empty_arg = true;
8849 }
8850 else
8851 {
8852 Expression_list::const_iterator pa;
8853 int i = 1;
8854 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8855 {
8856 if (static_cast<size_t>(i) == param_count)
8857 break;
8858 new_args->push_back(*pa);
8859 }
8860
8861 // We have reached the varargs parameter.
8862
8863 bool issued_error = false;
8864 if (pa == old_args->end())
8865 push_empty_arg = true;
8866 else if (pa + 1 == old_args->end() && this->is_varargs_)
8867 new_args->push_back(*pa);
8868 else if (this->is_varargs_)
8869 {
8870 if ((*pa)->type()->is_slice_type())
8871 this->report_error(_("too many arguments"));
8872 else
8873 {
8874 error_at(this->location(),
8875 _("invalid use of %<...%> with non-slice"));
8876 this->set_is_error();
8877 }
8878 return;
8879 }
8880 else
8881 {
8882 Type* element_type = varargs_type->array_type()->element_type();
8883 Expression_list* vals = new Expression_list;
8884 for (; pa != old_args->end(); ++pa, ++i)
8885 {
8886 // Check types here so that we get a better message.
8887 Type* patype = (*pa)->type();
8888 Location paloc = (*pa)->location();
8889 if (!this->check_argument_type(i, element_type, patype,
8890 paloc, issued_error))
8891 continue;
8892 vals->push_back(*pa);
8893 }
8894 Expression* val =
8895 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8896 gogo->lower_expression(function, inserter, &val);
8897 new_args->push_back(val);
8898 }
8899 }
8900
8901 if (push_empty_arg)
8902 new_args->push_back(Expression::make_nil(loc));
8903
8904 // We can't return a new call expression here, because this one may
8905 // be referenced by Call_result expressions. FIXME. We can't
8906 // delete OLD_ARGS because we may have both a Call_expression and a
8907 // Builtin_call_expression which refer to them. FIXME.
8908 this->args_ = new_args;
8909 this->varargs_are_lowered_ = true;
8910 }
8911
8912 // Flatten a call with multiple results into a temporary.
8913
8914 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)8915 Call_expression::do_flatten(Gogo* gogo, Named_object*,
8916 Statement_inserter* inserter)
8917 {
8918 if (this->is_erroneous_call())
8919 {
8920 go_assert(saw_errors());
8921 return Expression::make_error(this->location());
8922 }
8923
8924 if (this->is_flattened_)
8925 return this;
8926 this->is_flattened_ = true;
8927
8928 // Add temporary variables for all arguments that require type
8929 // conversion.
8930 Function_type* fntype = this->get_function_type();
8931 if (fntype == NULL)
8932 {
8933 go_assert(saw_errors());
8934 return this;
8935 }
8936 if (this->args_ != NULL && !this->args_->empty()
8937 && fntype->parameters() != NULL && !fntype->parameters()->empty())
8938 {
8939 bool is_interface_method =
8940 this->fn_->interface_field_reference_expression() != NULL;
8941
8942 Expression_list *args = new Expression_list();
8943 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
8944 Expression_list::const_iterator pa = this->args_->begin();
8945 if (!is_interface_method && fntype->is_method())
8946 {
8947 // The receiver argument.
8948 args->push_back(*pa);
8949 ++pa;
8950 }
8951 for (; pa != this->args_->end(); ++pa, ++pp)
8952 {
8953 go_assert(pp != fntype->parameters()->end());
8954 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
8955 args->push_back(*pa);
8956 else
8957 {
8958 Location loc = (*pa)->location();
8959 Expression* arg = *pa;
8960 if (!arg->is_variable())
8961 {
8962 Temporary_statement *temp =
8963 Statement::make_temporary(NULL, arg, loc);
8964 inserter->insert(temp);
8965 arg = Expression::make_temporary_reference(temp, loc);
8966 }
8967 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
8968 loc);
8969 args->push_back(arg);
8970 }
8971 }
8972 delete this->args_;
8973 this->args_ = args;
8974 }
8975
8976 size_t rc = this->result_count();
8977 if (rc > 1 && this->call_temp_ == NULL)
8978 {
8979 Struct_field_list* sfl = new Struct_field_list();
8980 Function_type* fntype = this->get_function_type();
8981 const Typed_identifier_list* results = fntype->results();
8982 Location loc = this->location();
8983
8984 int i = 0;
8985 char buf[10];
8986 for (Typed_identifier_list::const_iterator p = results->begin();
8987 p != results->end();
8988 ++p, ++i)
8989 {
8990 snprintf(buf, sizeof buf, "res%d", i);
8991 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
8992 }
8993
8994 Struct_type* st = Type::make_struct_type(sfl, loc);
8995 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
8996 inserter->insert(this->call_temp_);
8997 }
8998
8999 return this;
9000 }
9001
9002 // Get the function type. This can return NULL in error cases.
9003
9004 Function_type*
get_function_type() const9005 Call_expression::get_function_type() const
9006 {
9007 return this->fn_->type()->function_type();
9008 }
9009
9010 // Return the number of values which this call will return.
9011
9012 size_t
result_count() const9013 Call_expression::result_count() const
9014 {
9015 const Function_type* fntype = this->get_function_type();
9016 if (fntype == NULL)
9017 return 0;
9018 if (fntype->results() == NULL)
9019 return 0;
9020 return fntype->results()->size();
9021 }
9022
9023 // Return the temporary which holds a result.
9024
9025 Temporary_statement*
result(size_t i) const9026 Call_expression::result(size_t i) const
9027 {
9028 if (this->results_ == NULL || this->results_->size() <= i)
9029 {
9030 go_assert(saw_errors());
9031 return NULL;
9032 }
9033 return (*this->results_)[i];
9034 }
9035
9036 // Set the number of results expected from a call expression.
9037
9038 void
set_expected_result_count(size_t count)9039 Call_expression::set_expected_result_count(size_t count)
9040 {
9041 go_assert(this->expected_result_count_ == 0);
9042 this->expected_result_count_ = count;
9043 }
9044
9045 // Return whether this is a call to the predeclared function recover.
9046
9047 bool
is_recover_call() const9048 Call_expression::is_recover_call() const
9049 {
9050 return this->do_is_recover_call();
9051 }
9052
9053 // Set the argument to the recover function.
9054
9055 void
set_recover_arg(Expression * arg)9056 Call_expression::set_recover_arg(Expression* arg)
9057 {
9058 this->do_set_recover_arg(arg);
9059 }
9060
9061 // Virtual functions also implemented by Builtin_call_expression.
9062
9063 bool
do_is_recover_call() const9064 Call_expression::do_is_recover_call() const
9065 {
9066 return false;
9067 }
9068
9069 void
do_set_recover_arg(Expression *)9070 Call_expression::do_set_recover_arg(Expression*)
9071 {
9072 go_unreachable();
9073 }
9074
9075 // We have found an error with this call expression; return true if
9076 // we should report it.
9077
9078 bool
issue_error()9079 Call_expression::issue_error()
9080 {
9081 if (this->issued_error_)
9082 return false;
9083 else
9084 {
9085 this->issued_error_ = true;
9086 return true;
9087 }
9088 }
9089
9090 // Whether or not this call contains errors, either in the call or the
9091 // arguments to the call.
9092
9093 bool
is_erroneous_call()9094 Call_expression::is_erroneous_call()
9095 {
9096 if (this->is_error_expression() || this->fn()->is_error_expression())
9097 return true;
9098
9099 if (this->args() == NULL)
9100 return false;
9101 for (Expression_list::iterator pa = this->args()->begin();
9102 pa != this->args()->end();
9103 ++pa)
9104 {
9105 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9106 return true;
9107 }
9108 return false;
9109 }
9110
9111 // Get the type.
9112
9113 Type*
do_type()9114 Call_expression::do_type()
9115 {
9116 if (this->type_ != NULL)
9117 return this->type_;
9118
9119 Type* ret;
9120 Function_type* fntype = this->get_function_type();
9121 if (fntype == NULL)
9122 return Type::make_error_type();
9123
9124 const Typed_identifier_list* results = fntype->results();
9125 if (results == NULL)
9126 ret = Type::make_void_type();
9127 else if (results->size() == 1)
9128 ret = results->begin()->type();
9129 else
9130 ret = Type::make_call_multiple_result_type(this);
9131
9132 this->type_ = ret;
9133
9134 return this->type_;
9135 }
9136
9137 // Determine types for a call expression. We can use the function
9138 // parameter types to set the types of the arguments.
9139
9140 void
do_determine_type(const Type_context *)9141 Call_expression::do_determine_type(const Type_context*)
9142 {
9143 if (!this->determining_types())
9144 return;
9145
9146 this->fn_->determine_type_no_context();
9147 Function_type* fntype = this->get_function_type();
9148 const Typed_identifier_list* parameters = NULL;
9149 if (fntype != NULL)
9150 parameters = fntype->parameters();
9151 if (this->args_ != NULL)
9152 {
9153 Typed_identifier_list::const_iterator pt;
9154 if (parameters != NULL)
9155 pt = parameters->begin();
9156 bool first = true;
9157 for (Expression_list::const_iterator pa = this->args_->begin();
9158 pa != this->args_->end();
9159 ++pa)
9160 {
9161 if (first)
9162 {
9163 first = false;
9164 // If this is a method, the first argument is the
9165 // receiver.
9166 if (fntype != NULL && fntype->is_method())
9167 {
9168 Type* rtype = fntype->receiver()->type();
9169 // The receiver is always passed as a pointer.
9170 if (rtype->points_to() == NULL)
9171 rtype = Type::make_pointer_type(rtype);
9172 Type_context subcontext(rtype, false);
9173 (*pa)->determine_type(&subcontext);
9174 continue;
9175 }
9176 }
9177
9178 if (parameters != NULL && pt != parameters->end())
9179 {
9180 Type_context subcontext(pt->type(), false);
9181 (*pa)->determine_type(&subcontext);
9182 ++pt;
9183 }
9184 else
9185 (*pa)->determine_type_no_context();
9186 }
9187 }
9188 }
9189
9190 // Called when determining types for a Call_expression. Return true
9191 // if we should go ahead, false if they have already been determined.
9192
9193 bool
determining_types()9194 Call_expression::determining_types()
9195 {
9196 if (this->types_are_determined_)
9197 return false;
9198 else
9199 {
9200 this->types_are_determined_ = true;
9201 return true;
9202 }
9203 }
9204
9205 // Check types for parameter I.
9206
9207 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)9208 Call_expression::check_argument_type(int i, const Type* parameter_type,
9209 const Type* argument_type,
9210 Location argument_location,
9211 bool issued_error)
9212 {
9213 std::string reason;
9214 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9215 {
9216 if (!issued_error)
9217 {
9218 if (reason.empty())
9219 error_at(argument_location, "argument %d has incompatible type", i);
9220 else
9221 error_at(argument_location,
9222 "argument %d has incompatible type (%s)",
9223 i, reason.c_str());
9224 }
9225 this->set_is_error();
9226 return false;
9227 }
9228 return true;
9229 }
9230
9231 // Check types.
9232
9233 void
do_check_types(Gogo *)9234 Call_expression::do_check_types(Gogo*)
9235 {
9236 if (this->classification() == EXPRESSION_ERROR)
9237 return;
9238
9239 Function_type* fntype = this->get_function_type();
9240 if (fntype == NULL)
9241 {
9242 if (!this->fn_->type()->is_error())
9243 this->report_error(_("expected function"));
9244 return;
9245 }
9246
9247 if (this->expected_result_count_ != 0
9248 && this->expected_result_count_ != this->result_count())
9249 {
9250 if (this->issue_error())
9251 this->report_error(_("function result count mismatch"));
9252 this->set_is_error();
9253 return;
9254 }
9255
9256 bool is_method = fntype->is_method();
9257 if (is_method)
9258 {
9259 go_assert(this->args_ != NULL && !this->args_->empty());
9260 Type* rtype = fntype->receiver()->type();
9261 Expression* first_arg = this->args_->front();
9262 // We dereference the values since receivers are always passed
9263 // as pointers.
9264 std::string reason;
9265 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9266 &reason))
9267 {
9268 if (reason.empty())
9269 this->report_error(_("incompatible type for receiver"));
9270 else
9271 {
9272 error_at(this->location(),
9273 "incompatible type for receiver (%s)",
9274 reason.c_str());
9275 this->set_is_error();
9276 }
9277 }
9278 }
9279
9280 // Note that varargs was handled by the lower_varargs() method, so
9281 // we don't have to worry about it here unless something is wrong.
9282 if (this->is_varargs_ && !this->varargs_are_lowered_)
9283 {
9284 if (!fntype->is_varargs())
9285 {
9286 error_at(this->location(),
9287 _("invalid use of %<...%> calling non-variadic function"));
9288 this->set_is_error();
9289 return;
9290 }
9291 }
9292
9293 const Typed_identifier_list* parameters = fntype->parameters();
9294 if (this->args_ == NULL)
9295 {
9296 if (parameters != NULL && !parameters->empty())
9297 this->report_error(_("not enough arguments"));
9298 }
9299 else if (parameters == NULL)
9300 {
9301 if (!is_method || this->args_->size() > 1)
9302 this->report_error(_("too many arguments"));
9303 }
9304 else if (this->args_->size() == 1
9305 && this->args_->front()->call_expression() != NULL
9306 && this->args_->front()->call_expression()->result_count() > 1)
9307 {
9308 // This is F(G()) when G returns more than one result. If the
9309 // results can be matched to parameters, it would have been
9310 // lowered in do_lower. If we get here we know there is a
9311 // mismatch.
9312 if (this->args_->front()->call_expression()->result_count()
9313 < parameters->size())
9314 this->report_error(_("not enough arguments"));
9315 else
9316 this->report_error(_("too many arguments"));
9317 }
9318 else
9319 {
9320 int i = 0;
9321 Expression_list::const_iterator pa = this->args_->begin();
9322 if (is_method)
9323 ++pa;
9324 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9325 pt != parameters->end();
9326 ++pt, ++pa, ++i)
9327 {
9328 if (pa == this->args_->end())
9329 {
9330 this->report_error(_("not enough arguments"));
9331 return;
9332 }
9333 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9334 (*pa)->location(), false);
9335 }
9336 if (pa != this->args_->end())
9337 this->report_error(_("too many arguments"));
9338 }
9339 }
9340
9341 Expression*
do_copy()9342 Call_expression::do_copy()
9343 {
9344 Call_expression* call =
9345 Expression::make_call(this->fn_->copy(),
9346 (this->args_ == NULL
9347 ? NULL
9348 : this->args_->copy()),
9349 this->is_varargs_, this->location());
9350
9351 if (this->varargs_are_lowered_)
9352 call->set_varargs_are_lowered();
9353 return call;
9354 }
9355
9356 // Return whether we have to use a temporary variable to ensure that
9357 // we evaluate this call expression in order. If the call returns no
9358 // results then it will inevitably be executed last.
9359
9360 bool
do_must_eval_in_order() const9361 Call_expression::do_must_eval_in_order() const
9362 {
9363 return this->result_count() > 0;
9364 }
9365
9366 // Get the function and the first argument to use when calling an
9367 // interface method.
9368
9369 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr)9370 Call_expression::interface_method_function(
9371 Interface_field_reference_expression* interface_method,
9372 Expression** first_arg_ptr)
9373 {
9374 *first_arg_ptr = interface_method->get_underlying_object();
9375 return interface_method->get_function();
9376 }
9377
9378 // Build the call expression.
9379
9380 Bexpression*
do_get_backend(Translate_context * context)9381 Call_expression::do_get_backend(Translate_context* context)
9382 {
9383 if (this->call_ != NULL)
9384 return this->call_;
9385
9386 Function_type* fntype = this->get_function_type();
9387 if (fntype == NULL)
9388 return context->backend()->error_expression();
9389
9390 if (this->fn_->is_error_expression())
9391 return context->backend()->error_expression();
9392
9393 Gogo* gogo = context->gogo();
9394 Location location = this->location();
9395
9396 Func_expression* func = this->fn_->func_expression();
9397 Interface_field_reference_expression* interface_method =
9398 this->fn_->interface_field_reference_expression();
9399 const bool has_closure = func != NULL && func->closure() != NULL;
9400 const bool is_interface_method = interface_method != NULL;
9401
9402 bool has_closure_arg;
9403 if (has_closure)
9404 has_closure_arg = true;
9405 else if (func != NULL)
9406 has_closure_arg = false;
9407 else if (is_interface_method)
9408 has_closure_arg = false;
9409 else
9410 has_closure_arg = true;
9411
9412 int nargs;
9413 std::vector<Bexpression*> fn_args;
9414 if (this->args_ == NULL || this->args_->empty())
9415 {
9416 nargs = is_interface_method ? 1 : 0;
9417 if (nargs > 0)
9418 fn_args.resize(1);
9419 }
9420 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9421 {
9422 // Passing a receiver parameter.
9423 go_assert(!is_interface_method
9424 && fntype->is_method()
9425 && this->args_->size() == 1);
9426 nargs = 1;
9427 fn_args.resize(1);
9428 fn_args[0] = this->args_->front()->get_backend(context);
9429 }
9430 else
9431 {
9432 const Typed_identifier_list* params = fntype->parameters();
9433
9434 nargs = this->args_->size();
9435 int i = is_interface_method ? 1 : 0;
9436 nargs += i;
9437 fn_args.resize(nargs);
9438
9439 Typed_identifier_list::const_iterator pp = params->begin();
9440 Expression_list::const_iterator pe = this->args_->begin();
9441 if (!is_interface_method && fntype->is_method())
9442 {
9443 fn_args[i] = (*pe)->get_backend(context);
9444 ++pe;
9445 ++i;
9446 }
9447 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9448 {
9449 go_assert(pp != params->end());
9450 Expression* arg =
9451 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9452 location);
9453 fn_args[i] = arg->get_backend(context);
9454 }
9455 go_assert(pp == params->end());
9456 go_assert(i == nargs);
9457 }
9458
9459 Expression* fn;
9460 Expression* closure = NULL;
9461 if (func != NULL)
9462 {
9463 Named_object* no = func->named_object();
9464 fn = Expression::make_func_code_reference(no, location);
9465 if (has_closure)
9466 closure = func->closure();
9467 }
9468 else if (!is_interface_method)
9469 {
9470 closure = this->fn_;
9471
9472 // The backend representation of this function type is a pointer
9473 // to a struct whose first field is the actual function to call.
9474 Type* pfntype =
9475 Type::make_pointer_type(
9476 Type::make_pointer_type(Type::make_void_type()));
9477 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9478 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9479 }
9480 else
9481 {
9482 Expression* first_arg;
9483 fn = this->interface_method_function(interface_method, &first_arg);
9484 fn_args[0] = first_arg->get_backend(context);
9485 }
9486
9487 Bexpression* bclosure = NULL;
9488 if (has_closure_arg)
9489 bclosure = closure->get_backend(context);
9490 else
9491 go_assert(closure == NULL);
9492
9493 Bexpression* bfn = fn->get_backend(context);
9494
9495 // When not calling a named function directly, use a type conversion
9496 // in case the type of the function is a recursive type which refers
9497 // to itself. We don't do this for an interface method because 1)
9498 // an interface method never refers to itself, so we always have a
9499 // function type here; 2) we pass an extra first argument to an
9500 // interface method, so fntype is not correct.
9501 if (func == NULL && !is_interface_method)
9502 {
9503 Btype* bft = fntype->get_backend_fntype(gogo);
9504 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9505 }
9506
9507 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
9508 bclosure, location);
9509
9510 if (this->results_ != NULL)
9511 {
9512 go_assert(this->call_temp_ != NULL);
9513 Expression* call_ref =
9514 Expression::make_temporary_reference(this->call_temp_, location);
9515 Bexpression* bcall_ref = call_ref->get_backend(context);
9516 Bstatement* assn_stmt =
9517 gogo->backend()->assignment_statement(bcall_ref, call, location);
9518
9519 this->call_ = this->set_results(context, bcall_ref);
9520
9521 Bexpression* set_and_call =
9522 gogo->backend()->compound_expression(assn_stmt, this->call_,
9523 location);
9524 return set_and_call;
9525 }
9526
9527 this->call_ = call;
9528 return this->call_;
9529 }
9530
9531 // Set the result variables if this call returns multiple results.
9532
9533 Bexpression*
set_results(Translate_context * context,Bexpression * call)9534 Call_expression::set_results(Translate_context* context, Bexpression* call)
9535 {
9536 Gogo* gogo = context->gogo();
9537
9538 Bexpression* results = NULL;
9539 Location loc = this->location();
9540
9541 size_t rc = this->result_count();
9542 for (size_t i = 0; i < rc; ++i)
9543 {
9544 Temporary_statement* temp = this->result(i);
9545 if (temp == NULL)
9546 {
9547 go_assert(saw_errors());
9548 return gogo->backend()->error_expression();
9549 }
9550 Temporary_reference_expression* ref =
9551 Expression::make_temporary_reference(temp, loc);
9552 ref->set_is_lvalue();
9553
9554 Bexpression* result_ref = ref->get_backend(context);
9555 Bexpression* call_result =
9556 gogo->backend()->struct_field_expression(call, i, loc);
9557 Bstatement* assn_stmt =
9558 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9559
9560 Bexpression* result =
9561 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9562
9563 if (results == NULL)
9564 results = result;
9565 else
9566 {
9567 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9568 results =
9569 gogo->backend()->compound_expression(expr_stmt, results, loc);
9570 }
9571 }
9572 return results;
9573 }
9574
9575 // Dump ast representation for a call expressin.
9576
9577 void
do_dump_expression(Ast_dump_context * ast_dump_context) const9578 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9579 {
9580 this->fn_->dump_expression(ast_dump_context);
9581 ast_dump_context->ostream() << "(";
9582 if (args_ != NULL)
9583 ast_dump_context->dump_expression_list(this->args_);
9584
9585 ast_dump_context->ostream() << ") ";
9586 }
9587
9588 // Make a call expression.
9589
9590 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)9591 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9592 Location location)
9593 {
9594 return new Call_expression(fn, args, is_varargs, location);
9595 }
9596
9597 // Class Call_result_expression.
9598
9599 // Traverse a call result.
9600
9601 int
do_traverse(Traverse * traverse)9602 Call_result_expression::do_traverse(Traverse* traverse)
9603 {
9604 if (traverse->remember_expression(this->call_))
9605 {
9606 // We have already traversed the call expression.
9607 return TRAVERSE_CONTINUE;
9608 }
9609 return Expression::traverse(&this->call_, traverse);
9610 }
9611
9612 // Get the type.
9613
9614 Type*
do_type()9615 Call_result_expression::do_type()
9616 {
9617 if (this->classification() == EXPRESSION_ERROR)
9618 return Type::make_error_type();
9619
9620 // THIS->CALL_ can be replaced with a temporary reference due to
9621 // Call_expression::do_must_eval_in_order when there is an error.
9622 Call_expression* ce = this->call_->call_expression();
9623 if (ce == NULL)
9624 {
9625 this->set_is_error();
9626 return Type::make_error_type();
9627 }
9628 Function_type* fntype = ce->get_function_type();
9629 if (fntype == NULL)
9630 {
9631 if (ce->issue_error())
9632 {
9633 if (!ce->fn()->type()->is_error())
9634 this->report_error(_("expected function"));
9635 }
9636 this->set_is_error();
9637 return Type::make_error_type();
9638 }
9639 const Typed_identifier_list* results = fntype->results();
9640 if (results == NULL || results->size() < 2)
9641 {
9642 if (ce->issue_error())
9643 this->report_error(_("number of results does not match "
9644 "number of values"));
9645 return Type::make_error_type();
9646 }
9647 Typed_identifier_list::const_iterator pr = results->begin();
9648 for (unsigned int i = 0; i < this->index_; ++i)
9649 {
9650 if (pr == results->end())
9651 break;
9652 ++pr;
9653 }
9654 if (pr == results->end())
9655 {
9656 if (ce->issue_error())
9657 this->report_error(_("number of results does not match "
9658 "number of values"));
9659 return Type::make_error_type();
9660 }
9661 return pr->type();
9662 }
9663
9664 // Check the type. Just make sure that we trigger the warning in
9665 // do_type.
9666
9667 void
do_check_types(Gogo *)9668 Call_result_expression::do_check_types(Gogo*)
9669 {
9670 this->type();
9671 }
9672
9673 // Determine the type. We have nothing to do here, but the 0 result
9674 // needs to pass down to the caller.
9675
9676 void
do_determine_type(const Type_context *)9677 Call_result_expression::do_determine_type(const Type_context*)
9678 {
9679 this->call_->determine_type_no_context();
9680 }
9681
9682 // Return the backend representation. We just refer to the temporary set by the
9683 // call expression. We don't do this at lowering time because it makes it
9684 // hard to evaluate the call at the right time.
9685
9686 Bexpression*
do_get_backend(Translate_context * context)9687 Call_result_expression::do_get_backend(Translate_context* context)
9688 {
9689 Call_expression* ce = this->call_->call_expression();
9690 if (ce == NULL)
9691 {
9692 go_assert(this->call_->is_error_expression());
9693 return context->backend()->error_expression();
9694 }
9695 Temporary_statement* ts = ce->result(this->index_);
9696 if (ts == NULL)
9697 {
9698 go_assert(saw_errors());
9699 return context->backend()->error_expression();
9700 }
9701 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9702 return ref->get_backend(context);
9703 }
9704
9705 // Dump ast representation for a call result expression.
9706
9707 void
do_dump_expression(Ast_dump_context * ast_dump_context) const9708 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9709 const
9710 {
9711 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9712 // (struct) and the fields are referenced instead.
9713 ast_dump_context->ostream() << this->index_ << "@(";
9714 ast_dump_context->dump_expression(this->call_);
9715 ast_dump_context->ostream() << ")";
9716 }
9717
9718 // Make a reference to a single result of a call which returns
9719 // multiple results.
9720
9721 Expression*
make_call_result(Call_expression * call,unsigned int index)9722 Expression::make_call_result(Call_expression* call, unsigned int index)
9723 {
9724 return new Call_result_expression(call, index);
9725 }
9726
9727 // Class Index_expression.
9728
9729 // Traversal.
9730
9731 int
do_traverse(Traverse * traverse)9732 Index_expression::do_traverse(Traverse* traverse)
9733 {
9734 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9735 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9736 || (this->end_ != NULL
9737 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9738 || (this->cap_ != NULL
9739 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9740 return TRAVERSE_EXIT;
9741 return TRAVERSE_CONTINUE;
9742 }
9743
9744 // Lower an index expression. This converts the generic index
9745 // expression into an array index, a string index, or a map index.
9746
9747 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)9748 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9749 {
9750 Location location = this->location();
9751 Expression* left = this->left_;
9752 Expression* start = this->start_;
9753 Expression* end = this->end_;
9754 Expression* cap = this->cap_;
9755
9756 Type* type = left->type();
9757 if (type->is_error())
9758 {
9759 go_assert(saw_errors());
9760 return Expression::make_error(location);
9761 }
9762 else if (left->is_type_expression())
9763 {
9764 error_at(location, "attempt to index type expression");
9765 return Expression::make_error(location);
9766 }
9767 else if (type->array_type() != NULL)
9768 return Expression::make_array_index(left, start, end, cap, location);
9769 else if (type->points_to() != NULL
9770 && type->points_to()->array_type() != NULL
9771 && !type->points_to()->is_slice_type())
9772 {
9773 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9774 location);
9775
9776 // For an ordinary index into the array, the pointer will be
9777 // dereferenced. For a slice it will not--the resulting slice
9778 // will simply reuse the pointer, which is incorrect if that
9779 // pointer is nil.
9780 if (end != NULL || cap != NULL)
9781 deref->issue_nil_check();
9782
9783 return Expression::make_array_index(deref, start, end, cap, location);
9784 }
9785 else if (type->is_string_type())
9786 {
9787 if (cap != NULL)
9788 {
9789 error_at(location, "invalid 3-index slice of string");
9790 return Expression::make_error(location);
9791 }
9792 return Expression::make_string_index(left, start, end, location);
9793 }
9794 else if (type->map_type() != NULL)
9795 {
9796 if (end != NULL || cap != NULL)
9797 {
9798 error_at(location, "invalid slice of map");
9799 return Expression::make_error(location);
9800 }
9801 Map_index_expression* ret = Expression::make_map_index(left, start,
9802 location);
9803 if (this->is_lvalue_)
9804 ret->set_is_lvalue();
9805 return ret;
9806 }
9807 else
9808 {
9809 error_at(location,
9810 "attempt to index object which is not array, string, or map");
9811 return Expression::make_error(location);
9812 }
9813 }
9814
9815 // Write an indexed expression
9816 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9817
9818 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)9819 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9820 const Expression* expr,
9821 const Expression* start,
9822 const Expression* end,
9823 const Expression* cap)
9824 {
9825 expr->dump_expression(ast_dump_context);
9826 ast_dump_context->ostream() << "[";
9827 start->dump_expression(ast_dump_context);
9828 if (end != NULL)
9829 {
9830 ast_dump_context->ostream() << ":";
9831 end->dump_expression(ast_dump_context);
9832 }
9833 if (cap != NULL)
9834 {
9835 ast_dump_context->ostream() << ":";
9836 cap->dump_expression(ast_dump_context);
9837 }
9838 ast_dump_context->ostream() << "]";
9839 }
9840
9841 // Dump ast representation for an index expression.
9842
9843 void
do_dump_expression(Ast_dump_context * ast_dump_context) const9844 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9845 const
9846 {
9847 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9848 this->start_, this->end_, this->cap_);
9849 }
9850
9851 // Make an index expression.
9852
9853 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)9854 Expression::make_index(Expression* left, Expression* start, Expression* end,
9855 Expression* cap, Location location)
9856 {
9857 return new Index_expression(left, start, end, cap, location);
9858 }
9859
9860 // Class Array_index_expression.
9861
9862 // Array index traversal.
9863
9864 int
do_traverse(Traverse * traverse)9865 Array_index_expression::do_traverse(Traverse* traverse)
9866 {
9867 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9868 return TRAVERSE_EXIT;
9869 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9870 return TRAVERSE_EXIT;
9871 if (this->end_ != NULL)
9872 {
9873 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9874 return TRAVERSE_EXIT;
9875 }
9876 if (this->cap_ != NULL)
9877 {
9878 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9879 return TRAVERSE_EXIT;
9880 }
9881 return TRAVERSE_CONTINUE;
9882 }
9883
9884 // Return the type of an array index.
9885
9886 Type*
do_type()9887 Array_index_expression::do_type()
9888 {
9889 if (this->type_ == NULL)
9890 {
9891 Array_type* type = this->array_->type()->array_type();
9892 if (type == NULL)
9893 this->type_ = Type::make_error_type();
9894 else if (this->end_ == NULL)
9895 this->type_ = type->element_type();
9896 else if (type->is_slice_type())
9897 {
9898 // A slice of a slice has the same type as the original
9899 // slice.
9900 this->type_ = this->array_->type()->deref();
9901 }
9902 else
9903 {
9904 // A slice of an array is a slice.
9905 this->type_ = Type::make_array_type(type->element_type(), NULL);
9906 }
9907 }
9908 return this->type_;
9909 }
9910
9911 // Set the type of an array index.
9912
9913 void
do_determine_type(const Type_context *)9914 Array_index_expression::do_determine_type(const Type_context*)
9915 {
9916 this->array_->determine_type_no_context();
9917
9918 Type_context index_context(Type::lookup_integer_type("int"), false);
9919 if (this->start_->is_constant())
9920 this->start_->determine_type(&index_context);
9921 else
9922 this->start_->determine_type_no_context();
9923 if (this->end_ != NULL)
9924 {
9925 if (this->end_->is_constant())
9926 this->end_->determine_type(&index_context);
9927 else
9928 this->end_->determine_type_no_context();
9929 }
9930 if (this->cap_ != NULL)
9931 {
9932 if (this->cap_->is_constant())
9933 this->cap_->determine_type(&index_context);
9934 else
9935 this->cap_->determine_type_no_context();
9936 }
9937 }
9938
9939 // Check types of an array index.
9940
9941 void
do_check_types(Gogo *)9942 Array_index_expression::do_check_types(Gogo*)
9943 {
9944 Numeric_constant nc;
9945 unsigned long v;
9946 if (this->start_->type()->integer_type() == NULL
9947 && !this->start_->type()->is_error()
9948 && (!this->start_->numeric_constant_value(&nc)
9949 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9950 this->report_error(_("index must be integer"));
9951 if (this->end_ != NULL
9952 && this->end_->type()->integer_type() == NULL
9953 && !this->end_->type()->is_error()
9954 && !this->end_->is_nil_expression()
9955 && !this->end_->is_error_expression()
9956 && (!this->end_->numeric_constant_value(&nc)
9957 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9958 this->report_error(_("slice end must be integer"));
9959 if (this->cap_ != NULL
9960 && this->cap_->type()->integer_type() == NULL
9961 && !this->cap_->type()->is_error()
9962 && !this->cap_->is_nil_expression()
9963 && !this->cap_->is_error_expression()
9964 && (!this->cap_->numeric_constant_value(&nc)
9965 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9966 this->report_error(_("slice capacity must be integer"));
9967
9968 Array_type* array_type = this->array_->type()->array_type();
9969 if (array_type == NULL)
9970 {
9971 go_assert(this->array_->type()->is_error());
9972 return;
9973 }
9974
9975 unsigned int int_bits =
9976 Type::lookup_integer_type("int")->integer_type()->bits();
9977
9978 Numeric_constant lvalnc;
9979 mpz_t lval;
9980 bool lval_valid = (array_type->length() != NULL
9981 && array_type->length()->numeric_constant_value(&lvalnc)
9982 && lvalnc.to_int(&lval));
9983 Numeric_constant inc;
9984 mpz_t ival;
9985 bool ival_valid = false;
9986 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9987 {
9988 ival_valid = true;
9989 if (mpz_sgn(ival) < 0
9990 || mpz_sizeinbase(ival, 2) >= int_bits
9991 || (lval_valid
9992 && (this->end_ == NULL
9993 ? mpz_cmp(ival, lval) >= 0
9994 : mpz_cmp(ival, lval) > 0)))
9995 {
9996 error_at(this->start_->location(), "array index out of bounds");
9997 this->set_is_error();
9998 }
9999 }
10000 if (this->end_ != NULL && !this->end_->is_nil_expression())
10001 {
10002 Numeric_constant enc;
10003 mpz_t eval;
10004 bool eval_valid = false;
10005 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10006 {
10007 eval_valid = true;
10008 if (mpz_sgn(eval) < 0
10009 || mpz_sizeinbase(eval, 2) >= int_bits
10010 || (lval_valid && mpz_cmp(eval, lval) > 0))
10011 {
10012 error_at(this->end_->location(), "array index out of bounds");
10013 this->set_is_error();
10014 }
10015 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10016 this->report_error(_("inverted slice range"));
10017 }
10018
10019 Numeric_constant cnc;
10020 mpz_t cval;
10021 if (this->cap_ != NULL
10022 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10023 {
10024 if (mpz_sgn(cval) < 0
10025 || mpz_sizeinbase(cval, 2) >= int_bits
10026 || (lval_valid && mpz_cmp(cval, lval) > 0))
10027 {
10028 error_at(this->cap_->location(), "array index out of bounds");
10029 this->set_is_error();
10030 }
10031 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10032 {
10033 error_at(this->cap_->location(),
10034 "invalid slice index: capacity less than start");
10035 this->set_is_error();
10036 }
10037 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10038 {
10039 error_at(this->cap_->location(),
10040 "invalid slice index: capacity less than length");
10041 this->set_is_error();
10042 }
10043 mpz_clear(cval);
10044 }
10045
10046 if (eval_valid)
10047 mpz_clear(eval);
10048 }
10049 if (ival_valid)
10050 mpz_clear(ival);
10051 if (lval_valid)
10052 mpz_clear(lval);
10053
10054 // A slice of an array requires an addressable array. A slice of a
10055 // slice is always possible.
10056 if (this->end_ != NULL && !array_type->is_slice_type())
10057 {
10058 if (!this->array_->is_addressable())
10059 this->report_error(_("slice of unaddressable value"));
10060 else
10061 this->array_->address_taken(true);
10062 }
10063 }
10064
10065 // Flatten array indexing by using temporary variables for slices and indexes.
10066
10067 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)10068 Array_index_expression::do_flatten(Gogo*, Named_object*,
10069 Statement_inserter* inserter)
10070 {
10071 Location loc = this->location();
10072 Expression* array = this->array_;
10073 Expression* start = this->start_;
10074 Expression* end = this->end_;
10075 Expression* cap = this->cap_;
10076 if (array->is_error_expression()
10077 || array->type()->is_error_type()
10078 || start->is_error_expression()
10079 || start->type()->is_error_type()
10080 || (end != NULL
10081 && (end->is_error_expression() || end->type()->is_error_type()))
10082 || (cap != NULL
10083 && (cap->is_error_expression() || cap->type()->is_error_type())))
10084 {
10085 go_assert(saw_errors());
10086 return Expression::make_error(loc);
10087 }
10088
10089 Temporary_statement* temp;
10090 if (array->type()->is_slice_type() && !array->is_variable())
10091 {
10092 temp = Statement::make_temporary(NULL, array, loc);
10093 inserter->insert(temp);
10094 this->array_ = Expression::make_temporary_reference(temp, loc);
10095 }
10096 if (!start->is_variable())
10097 {
10098 temp = Statement::make_temporary(NULL, start, loc);
10099 inserter->insert(temp);
10100 this->start_ = Expression::make_temporary_reference(temp, loc);
10101 }
10102 if (end != NULL
10103 && !end->is_nil_expression()
10104 && !end->is_variable())
10105 {
10106 temp = Statement::make_temporary(NULL, end, loc);
10107 inserter->insert(temp);
10108 this->end_ = Expression::make_temporary_reference(temp, loc);
10109 }
10110 if (cap!= NULL && !cap->is_variable())
10111 {
10112 temp = Statement::make_temporary(NULL, cap, loc);
10113 inserter->insert(temp);
10114 this->cap_ = Expression::make_temporary_reference(temp, loc);
10115 }
10116
10117 return this;
10118 }
10119
10120 // Return whether this expression is addressable.
10121
10122 bool
do_is_addressable() const10123 Array_index_expression::do_is_addressable() const
10124 {
10125 // A slice expression is not addressable.
10126 if (this->end_ != NULL)
10127 return false;
10128
10129 // An index into a slice is addressable.
10130 if (this->array_->type()->is_slice_type())
10131 return true;
10132
10133 // An index into an array is addressable if the array is
10134 // addressable.
10135 return this->array_->is_addressable();
10136 }
10137
10138 // Get the backend representation for an array index.
10139
10140 Bexpression*
do_get_backend(Translate_context * context)10141 Array_index_expression::do_get_backend(Translate_context* context)
10142 {
10143 Array_type* array_type = this->array_->type()->array_type();
10144 if (array_type == NULL)
10145 {
10146 go_assert(this->array_->type()->is_error());
10147 return context->backend()->error_expression();
10148 }
10149 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10150
10151 Location loc = this->location();
10152 Gogo* gogo = context->gogo();
10153
10154 Type* int_type = Type::lookup_integer_type("int");
10155 Btype* int_btype = int_type->get_backend(gogo);
10156
10157 // We need to convert the length and capacity to the Go "int" type here
10158 // because the length of a fixed-length array could be of type "uintptr"
10159 // and gimple disallows binary operations between "uintptr" and other
10160 // integer types. FIXME.
10161 Bexpression* length = NULL;
10162 if (this->end_ == NULL || this->end_->is_nil_expression())
10163 {
10164 Expression* len = array_type->get_length(gogo, this->array_);
10165 length = len->get_backend(context);
10166 length = gogo->backend()->convert_expression(int_btype, length, loc);
10167 }
10168
10169 Bexpression* capacity = NULL;
10170 if (this->end_ != NULL)
10171 {
10172 Expression* cap = array_type->get_capacity(gogo, this->array_);
10173 capacity = cap->get_backend(context);
10174 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10175 }
10176
10177 Bexpression* cap_arg = capacity;
10178 if (this->cap_ != NULL)
10179 {
10180 cap_arg = this->cap_->get_backend(context);
10181 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10182 }
10183
10184 if (length == NULL)
10185 length = cap_arg;
10186
10187 int code = (array_type->length() != NULL
10188 ? (this->end_ == NULL
10189 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10190 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10191 : (this->end_ == NULL
10192 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10193 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10194 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10195
10196 if (this->start_->type()->integer_type() == NULL
10197 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10198 {
10199 go_assert(saw_errors());
10200 return context->backend()->error_expression();
10201 }
10202
10203 Bexpression* bad_index =
10204 Expression::check_bounds(this->start_, loc)->get_backend(context);
10205
10206 Bexpression* start = this->start_->get_backend(context);
10207 start = gogo->backend()->convert_expression(int_btype, start, loc);
10208 Bexpression* start_too_large =
10209 gogo->backend()->binary_expression((this->end_ == NULL
10210 ? OPERATOR_GE
10211 : OPERATOR_GT),
10212 start,
10213 (this->end_ == NULL
10214 ? length
10215 : capacity),
10216 loc);
10217 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10218 bad_index, loc);
10219
10220 if (this->end_ == NULL)
10221 {
10222 // Simple array indexing. This has to return an l-value, so
10223 // wrap the index check into START.
10224 start =
10225 gogo->backend()->conditional_expression(int_btype, bad_index,
10226 crash, start, loc);
10227
10228 Bexpression* ret;
10229 if (array_type->length() != NULL)
10230 {
10231 Bexpression* array = this->array_->get_backend(context);
10232 ret = gogo->backend()->array_index_expression(array, start, loc);
10233 }
10234 else
10235 {
10236 // Slice.
10237 Expression* valptr =
10238 array_type->get_value_pointer(gogo, this->array_);
10239 Bexpression* ptr = valptr->get_backend(context);
10240 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10241
10242 Type* ele_type = this->array_->type()->array_type()->element_type();
10243 Btype* ele_btype = ele_type->get_backend(gogo);
10244 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10245 }
10246 return ret;
10247 }
10248
10249 // Array slice.
10250
10251 if (this->cap_ != NULL)
10252 {
10253 Bexpression* bounds_bcheck =
10254 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10255 bad_index =
10256 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10257 bad_index, loc);
10258 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10259
10260 Bexpression* cap_too_small =
10261 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10262 Bexpression* cap_too_large =
10263 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10264 Bexpression* bad_cap =
10265 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10266 cap_too_large, loc);
10267 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10268 bad_index, loc);
10269 }
10270
10271 Bexpression* end;
10272 if (this->end_->is_nil_expression())
10273 end = length;
10274 else
10275 {
10276 Bexpression* bounds_bcheck =
10277 Expression::check_bounds(this->end_, loc)->get_backend(context);
10278
10279 bad_index =
10280 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10281 bad_index, loc);
10282
10283 end = this->end_->get_backend(context);
10284 end = gogo->backend()->convert_expression(int_btype, end, loc);
10285 Bexpression* end_too_small =
10286 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10287 Bexpression* end_too_large =
10288 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10289 Bexpression* bad_end =
10290 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10291 end_too_large, loc);
10292 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10293 bad_index, loc);
10294 }
10295
10296 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10297 Bexpression* val = valptr->get_backend(context);
10298 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10299
10300 Bexpression* result_length =
10301 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10302
10303 Bexpression* result_capacity =
10304 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10305
10306 Btype* struct_btype = this->type()->get_backend(gogo);
10307 std::vector<Bexpression*> init;
10308 init.push_back(val);
10309 init.push_back(result_length);
10310 init.push_back(result_capacity);
10311
10312 Bexpression* ctor =
10313 gogo->backend()->constructor_expression(struct_btype, init, loc);
10314 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10315 crash, ctor, loc);
10316 }
10317
10318 // Dump ast representation for an array index expression.
10319
10320 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10321 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10322 const
10323 {
10324 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10325 this->start_, this->end_, this->cap_);
10326 }
10327
10328 // Make an array index expression. END and CAP may be NULL.
10329
10330 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)10331 Expression::make_array_index(Expression* array, Expression* start,
10332 Expression* end, Expression* cap,
10333 Location location)
10334 {
10335 return new Array_index_expression(array, start, end, cap, location);
10336 }
10337
10338 // A string index. This is used for both indexing and slicing.
10339
10340 class String_index_expression : public Expression
10341 {
10342 public:
String_index_expression(Expression * string,Expression * start,Expression * end,Location location)10343 String_index_expression(Expression* string, Expression* start,
10344 Expression* end, Location location)
10345 : Expression(EXPRESSION_STRING_INDEX, location),
10346 string_(string), start_(start), end_(end)
10347 { }
10348
10349 protected:
10350 int
10351 do_traverse(Traverse*);
10352
10353 Expression*
10354 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10355
10356 Type*
10357 do_type();
10358
10359 void
10360 do_determine_type(const Type_context*);
10361
10362 void
10363 do_check_types(Gogo*);
10364
10365 Expression*
do_copy()10366 do_copy()
10367 {
10368 return Expression::make_string_index(this->string_->copy(),
10369 this->start_->copy(),
10370 (this->end_ == NULL
10371 ? NULL
10372 : this->end_->copy()),
10373 this->location());
10374 }
10375
10376 bool
do_must_eval_subexpressions_in_order(int * skip) const10377 do_must_eval_subexpressions_in_order(int* skip) const
10378 {
10379 *skip = 1;
10380 return true;
10381 }
10382
10383 Bexpression*
10384 do_get_backend(Translate_context*);
10385
10386 void
10387 do_dump_expression(Ast_dump_context*) const;
10388
10389 private:
10390 // The string we are getting a value from.
10391 Expression* string_;
10392 // The start or only index.
10393 Expression* start_;
10394 // The end index of a slice. This may be NULL for a single index,
10395 // or it may be a nil expression for the length of the string.
10396 Expression* end_;
10397 };
10398
10399 // String index traversal.
10400
10401 int
do_traverse(Traverse * traverse)10402 String_index_expression::do_traverse(Traverse* traverse)
10403 {
10404 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10405 return TRAVERSE_EXIT;
10406 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10407 return TRAVERSE_EXIT;
10408 if (this->end_ != NULL)
10409 {
10410 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10411 return TRAVERSE_EXIT;
10412 }
10413 return TRAVERSE_CONTINUE;
10414 }
10415
10416 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)10417 String_index_expression::do_flatten(Gogo*, Named_object*,
10418 Statement_inserter* inserter)
10419 {
10420 Location loc = this->location();
10421 Expression* string = this->string_;
10422 Expression* start = this->start_;
10423 Expression* end = this->end_;
10424 if (string->is_error_expression()
10425 || string->type()->is_error_type()
10426 || start->is_error_expression()
10427 || start->type()->is_error_type()
10428 || (end != NULL
10429 && (end->is_error_expression() || end->type()->is_error_type())))
10430 {
10431 go_assert(saw_errors());
10432 return Expression::make_error(loc);
10433 }
10434
10435 Temporary_statement* temp;
10436 if (!this->string_->is_variable())
10437 {
10438 temp = Statement::make_temporary(NULL, this->string_, loc);
10439 inserter->insert(temp);
10440 this->string_ = Expression::make_temporary_reference(temp, loc);
10441 }
10442 if (!this->start_->is_variable())
10443 {
10444 temp = Statement::make_temporary(NULL, this->start_, loc);
10445 inserter->insert(temp);
10446 this->start_ = Expression::make_temporary_reference(temp, loc);
10447 }
10448 if (this->end_ != NULL
10449 && !this->end_->is_nil_expression()
10450 && !this->end_->is_variable())
10451 {
10452 temp = Statement::make_temporary(NULL, this->end_, loc);
10453 inserter->insert(temp);
10454 this->end_ = Expression::make_temporary_reference(temp, loc);
10455 }
10456
10457 return this;
10458 }
10459
10460 // Return the type of a string index.
10461
10462 Type*
do_type()10463 String_index_expression::do_type()
10464 {
10465 if (this->end_ == NULL)
10466 return Type::lookup_integer_type("uint8");
10467 else
10468 return this->string_->type();
10469 }
10470
10471 // Determine the type of a string index.
10472
10473 void
do_determine_type(const Type_context *)10474 String_index_expression::do_determine_type(const Type_context*)
10475 {
10476 this->string_->determine_type_no_context();
10477
10478 Type_context index_context(Type::lookup_integer_type("int"), false);
10479 if (this->start_->is_constant())
10480 this->start_->determine_type(&index_context);
10481 else
10482 this->start_->determine_type_no_context();
10483 if (this->end_ != NULL)
10484 {
10485 if (this->end_->is_constant())
10486 this->end_->determine_type(&index_context);
10487 else
10488 this->end_->determine_type_no_context();
10489 }
10490 }
10491
10492 // Check types of a string index.
10493
10494 void
do_check_types(Gogo *)10495 String_index_expression::do_check_types(Gogo*)
10496 {
10497 Numeric_constant nc;
10498 unsigned long v;
10499 if (this->start_->type()->integer_type() == NULL
10500 && !this->start_->type()->is_error()
10501 && (!this->start_->numeric_constant_value(&nc)
10502 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10503 this->report_error(_("index must be integer"));
10504 if (this->end_ != NULL
10505 && this->end_->type()->integer_type() == NULL
10506 && !this->end_->type()->is_error()
10507 && !this->end_->is_nil_expression()
10508 && !this->end_->is_error_expression()
10509 && (!this->end_->numeric_constant_value(&nc)
10510 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10511 this->report_error(_("slice end must be integer"));
10512
10513 std::string sval;
10514 bool sval_valid = this->string_->string_constant_value(&sval);
10515
10516 Numeric_constant inc;
10517 mpz_t ival;
10518 bool ival_valid = false;
10519 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10520 {
10521 ival_valid = true;
10522 if (mpz_sgn(ival) < 0
10523 || (sval_valid
10524 && (this->end_ == NULL
10525 ? mpz_cmp_ui(ival, sval.length()) >= 0
10526 : mpz_cmp_ui(ival, sval.length()) > 0)))
10527 {
10528 error_at(this->start_->location(), "string index out of bounds");
10529 this->set_is_error();
10530 }
10531 }
10532 if (this->end_ != NULL && !this->end_->is_nil_expression())
10533 {
10534 Numeric_constant enc;
10535 mpz_t eval;
10536 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10537 {
10538 if (mpz_sgn(eval) < 0
10539 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10540 {
10541 error_at(this->end_->location(), "string index out of bounds");
10542 this->set_is_error();
10543 }
10544 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10545 this->report_error(_("inverted slice range"));
10546 mpz_clear(eval);
10547 }
10548 }
10549 if (ival_valid)
10550 mpz_clear(ival);
10551 }
10552
10553 // Get the backend representation for a string index.
10554
10555 Bexpression*
do_get_backend(Translate_context * context)10556 String_index_expression::do_get_backend(Translate_context* context)
10557 {
10558 Location loc = this->location();
10559 Expression* string_arg = this->string_;
10560 if (this->string_->type()->points_to() != NULL)
10561 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10562
10563 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10564
10565 int code = (this->end_ == NULL
10566 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10567 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10568
10569 Gogo* gogo = context->gogo();
10570 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10571
10572 Type* int_type = Type::lookup_integer_type("int");
10573
10574 // It is possible that an error occurred earlier because the start index
10575 // cannot be represented as an integer type. In this case, we shouldn't
10576 // try casting the starting index into an integer since
10577 // Type_conversion_expression will fail to get the backend representation.
10578 // FIXME.
10579 if (this->start_->type()->integer_type() == NULL
10580 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10581 {
10582 go_assert(saw_errors());
10583 return context->backend()->error_expression();
10584 }
10585
10586 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10587
10588 if (this->end_ == NULL)
10589 {
10590 Expression* length =
10591 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10592
10593 Expression* start_too_large =
10594 Expression::make_binary(OPERATOR_GE, start, length, loc);
10595 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10596 bad_index, loc);
10597 Expression* bytes =
10598 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10599
10600 Bexpression* bstart = start->get_backend(context);
10601 Bexpression* ptr = bytes->get_backend(context);
10602 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10603 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10604 Bexpression* index =
10605 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10606
10607 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10608 Bexpression* index_error = bad_index->get_backend(context);
10609 return gogo->backend()->conditional_expression(byte_btype, index_error,
10610 crash, index, loc);
10611 }
10612
10613 Expression* end = NULL;
10614 if (this->end_->is_nil_expression())
10615 end = Expression::make_integer_sl(-1, int_type, loc);
10616 else
10617 {
10618 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10619 bad_index =
10620 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10621 end = Expression::make_cast(int_type, this->end_, loc);
10622 }
10623
10624 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10625 string_arg, start, end);
10626 Bexpression* bstrslice = strslice->get_backend(context);
10627
10628 Btype* str_btype = strslice->type()->get_backend(gogo);
10629 Bexpression* index_error = bad_index->get_backend(context);
10630 return gogo->backend()->conditional_expression(str_btype, index_error,
10631 crash, bstrslice, loc);
10632 }
10633
10634 // Dump ast representation for a string index expression.
10635
10636 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10637 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10638 const
10639 {
10640 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10641 this->start_, this->end_, NULL);
10642 }
10643
10644 // Make a string index expression. END may be NULL.
10645
10646 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)10647 Expression::make_string_index(Expression* string, Expression* start,
10648 Expression* end, Location location)
10649 {
10650 return new String_index_expression(string, start, end, location);
10651 }
10652
10653 // Class Map_index.
10654
10655 // Get the type of the map.
10656
10657 Map_type*
get_map_type() const10658 Map_index_expression::get_map_type() const
10659 {
10660 Map_type* mt = this->map_->type()->deref()->map_type();
10661 if (mt == NULL)
10662 go_assert(saw_errors());
10663 return mt;
10664 }
10665
10666 // Map index traversal.
10667
10668 int
do_traverse(Traverse * traverse)10669 Map_index_expression::do_traverse(Traverse* traverse)
10670 {
10671 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10672 return TRAVERSE_EXIT;
10673 return Expression::traverse(&this->index_, traverse);
10674 }
10675
10676 // We need to pass in a pointer to the key, so flatten the index into a
10677 // temporary variable if it isn't already. The value pointer will be
10678 // dereferenced and checked for nil, so flatten into a temporary to avoid
10679 // recomputation.
10680
10681 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)10682 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
10683 Statement_inserter* inserter)
10684 {
10685 Location loc = this->location();
10686 Map_type* mt = this->get_map_type();
10687 if (this->index()->is_error_expression()
10688 || this->index()->type()->is_error_type()
10689 || mt->is_error_type())
10690 {
10691 go_assert(saw_errors());
10692 return Expression::make_error(loc);
10693 }
10694
10695 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
10696 {
10697 if (this->index_->type()->interface_type() != NULL
10698 && !this->index_->is_variable())
10699 {
10700 Temporary_statement* temp =
10701 Statement::make_temporary(NULL, this->index_, loc);
10702 inserter->insert(temp);
10703 this->index_ = Expression::make_temporary_reference(temp, loc);
10704 }
10705 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
10706 this->index_, loc);
10707 }
10708
10709 if (!this->index_->is_variable())
10710 {
10711 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10712 loc);
10713 inserter->insert(temp);
10714 this->index_ = Expression::make_temporary_reference(temp, loc);
10715 }
10716
10717 if (this->value_pointer_ == NULL)
10718 this->get_value_pointer(this->is_lvalue_);
10719 if (this->value_pointer_->is_error_expression()
10720 || this->value_pointer_->type()->is_error_type())
10721 return Expression::make_error(loc);
10722 if (!this->value_pointer_->is_variable())
10723 {
10724 Temporary_statement* temp =
10725 Statement::make_temporary(NULL, this->value_pointer_, loc);
10726 inserter->insert(temp);
10727 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
10728 }
10729
10730 return this;
10731 }
10732
10733 // Return the type of a map index.
10734
10735 Type*
do_type()10736 Map_index_expression::do_type()
10737 {
10738 Map_type* mt = this->get_map_type();
10739 if (mt == NULL)
10740 return Type::make_error_type();
10741 Type* type = mt->val_type();
10742 // If this map index is in a tuple assignment, we actually return a
10743 // pointer to the value type. Tuple_map_assignment_statement is
10744 // responsible for handling this correctly. We need to get the type
10745 // right in case this gets assigned to a temporary variable.
10746 if (this->is_in_tuple_assignment_)
10747 type = Type::make_pointer_type(type);
10748 return type;
10749 }
10750
10751 // Fix the type of a map index.
10752
10753 void
do_determine_type(const Type_context *)10754 Map_index_expression::do_determine_type(const Type_context*)
10755 {
10756 this->map_->determine_type_no_context();
10757 Map_type* mt = this->get_map_type();
10758 Type* key_type = mt == NULL ? NULL : mt->key_type();
10759 Type_context subcontext(key_type, false);
10760 this->index_->determine_type(&subcontext);
10761 }
10762
10763 // Check types of a map index.
10764
10765 void
do_check_types(Gogo *)10766 Map_index_expression::do_check_types(Gogo*)
10767 {
10768 std::string reason;
10769 Map_type* mt = this->get_map_type();
10770 if (mt == NULL)
10771 return;
10772 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10773 {
10774 if (reason.empty())
10775 this->report_error(_("incompatible type for map index"));
10776 else
10777 {
10778 error_at(this->location(), "incompatible type for map index (%s)",
10779 reason.c_str());
10780 this->set_is_error();
10781 }
10782 }
10783 }
10784
10785 // Get the backend representation for a map index.
10786
10787 Bexpression*
do_get_backend(Translate_context * context)10788 Map_index_expression::do_get_backend(Translate_context* context)
10789 {
10790 Map_type* type = this->get_map_type();
10791 if (type == NULL)
10792 {
10793 go_assert(saw_errors());
10794 return context->backend()->error_expression();
10795 }
10796
10797 go_assert(this->value_pointer_ != NULL
10798 && this->value_pointer_->is_variable());
10799
10800 Bexpression* ret;
10801 if (this->is_lvalue_)
10802 {
10803 Expression* val =
10804 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10805 this->location());
10806 ret = val->get_backend(context);
10807 }
10808 else if (this->is_in_tuple_assignment_)
10809 {
10810 // Tuple_map_assignment_statement is responsible for using this
10811 // appropriately.
10812 ret = this->value_pointer_->get_backend(context);
10813 }
10814 else
10815 {
10816 Location loc = this->location();
10817
10818 Expression* nil_check =
10819 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10820 Expression::make_nil(loc), loc);
10821 Bexpression* bnil_check = nil_check->get_backend(context);
10822 Expression* val =
10823 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10824 Bexpression* bval = val->get_backend(context);
10825
10826 Gogo* gogo = context->gogo();
10827 Btype* val_btype = type->val_type()->get_backend(gogo);
10828 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10829 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10830 val_zero, bval, loc);
10831 }
10832 return ret;
10833 }
10834
10835 // Get an expression for the map index. This returns an expression which
10836 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10837 // not in the map.
10838
10839 Expression*
get_value_pointer(bool insert)10840 Map_index_expression::get_value_pointer(bool insert)
10841 {
10842 if (this->value_pointer_ == NULL)
10843 {
10844 Map_type* type = this->get_map_type();
10845 if (type == NULL)
10846 {
10847 go_assert(saw_errors());
10848 return Expression::make_error(this->location());
10849 }
10850
10851 Location loc = this->location();
10852 Expression* map_ref = this->map_;
10853 if (this->map_->type()->points_to() != NULL)
10854 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10855
10856 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10857 loc);
10858 Expression* map_index =
10859 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10860 map_ref, index_ptr,
10861 Expression::make_boolean(insert, loc));
10862
10863 Type* val_type = type->val_type();
10864 this->value_pointer_ =
10865 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10866 map_index, this->location());
10867 }
10868 return this->value_pointer_;
10869 }
10870
10871 // Dump ast representation for a map index expression
10872
10873 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10874 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10875 const
10876 {
10877 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10878 this->index_, NULL, NULL);
10879 }
10880
10881 // Make a map index expression.
10882
10883 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)10884 Expression::make_map_index(Expression* map, Expression* index,
10885 Location location)
10886 {
10887 return new Map_index_expression(map, index, location);
10888 }
10889
10890 // Class Field_reference_expression.
10891
10892 // Lower a field reference expression. There is nothing to lower, but
10893 // this is where we generate the tracking information for fields with
10894 // the magic go:"track" tag.
10895
10896 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)10897 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10898 Statement_inserter* inserter, int)
10899 {
10900 Struct_type* struct_type = this->expr_->type()->struct_type();
10901 if (struct_type == NULL)
10902 {
10903 // Error will be reported elsewhere.
10904 return this;
10905 }
10906 const Struct_field* field = struct_type->field(this->field_index_);
10907 if (field == NULL)
10908 return this;
10909 if (!field->has_tag())
10910 return this;
10911 if (field->tag().find("go:\"track\"") == std::string::npos)
10912 return this;
10913
10914 // References from functions generated by the compiler don't count.
10915 if (function != NULL && function->func_value()->is_type_specific_function())
10916 return this;
10917
10918 // We have found a reference to a tracked field. Build a call to
10919 // the runtime function __go_fieldtrack with a string that describes
10920 // the field. FIXME: We should only call this once per referenced
10921 // field per function, not once for each reference to the field.
10922
10923 if (this->called_fieldtrack_)
10924 return this;
10925 this->called_fieldtrack_ = true;
10926
10927 Location loc = this->location();
10928
10929 std::string s = "fieldtrack \"";
10930 Named_type* nt = this->expr_->type()->named_type();
10931 if (nt == NULL || nt->named_object()->package() == NULL)
10932 s.append(gogo->pkgpath());
10933 else
10934 s.append(nt->named_object()->package()->pkgpath());
10935 s.push_back('.');
10936 if (nt != NULL)
10937 s.append(Gogo::unpack_hidden_name(nt->name()));
10938 s.push_back('.');
10939 s.append(field->field_name());
10940 s.push_back('"');
10941
10942 // We can't use a string here, because internally a string holds a
10943 // pointer to the actual bytes; when the linker garbage collects the
10944 // string, it won't garbage collect the bytes. So we use a
10945 // [...]byte.
10946
10947 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
10948
10949 Type* byte_type = gogo->lookup_global("byte")->type_value();
10950 Type* array_type = Type::make_array_type(byte_type, length_expr);
10951
10952 Expression_list* bytes = new Expression_list();
10953 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10954 {
10955 unsigned char c = static_cast<unsigned char>(*p);
10956 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
10957 }
10958
10959 Expression* e = Expression::make_composite_literal(array_type, 0, false,
10960 bytes, false, loc);
10961
10962 Variable* var = new Variable(array_type, e, true, false, false, loc);
10963
10964 static int count;
10965 char buf[50];
10966 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10967 ++count;
10968
10969 Named_object* no = gogo->add_variable(buf, var);
10970 e = Expression::make_var_reference(no, loc);
10971 e = Expression::make_unary(OPERATOR_AND, e, loc);
10972
10973 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
10974 gogo->lower_expression(function, inserter, &call);
10975 inserter->insert(Statement::make_statement(call, false));
10976
10977 // Put this function, and the global variable we just created, into
10978 // unique sections. This will permit the linker to garbage collect
10979 // them if they are not referenced. The effect is that the only
10980 // strings, indicating field references, that will wind up in the
10981 // executable will be those for functions that are actually needed.
10982 if (function != NULL)
10983 function->func_value()->set_in_unique_section();
10984 var->set_in_unique_section();
10985
10986 return this;
10987 }
10988
10989 // Return the type of a field reference.
10990
10991 Type*
do_type()10992 Field_reference_expression::do_type()
10993 {
10994 Type* type = this->expr_->type();
10995 if (type->is_error())
10996 return type;
10997 Struct_type* struct_type = type->struct_type();
10998 go_assert(struct_type != NULL);
10999 return struct_type->field(this->field_index_)->type();
11000 }
11001
11002 // Check the types for a field reference.
11003
11004 void
do_check_types(Gogo *)11005 Field_reference_expression::do_check_types(Gogo*)
11006 {
11007 Type* type = this->expr_->type();
11008 if (type->is_error())
11009 return;
11010 Struct_type* struct_type = type->struct_type();
11011 go_assert(struct_type != NULL);
11012 go_assert(struct_type->field(this->field_index_) != NULL);
11013 }
11014
11015 // Get the backend representation for a field reference.
11016
11017 Bexpression*
do_get_backend(Translate_context * context)11018 Field_reference_expression::do_get_backend(Translate_context* context)
11019 {
11020 Bexpression* bstruct = this->expr_->get_backend(context);
11021 return context->gogo()->backend()->struct_field_expression(bstruct,
11022 this->field_index_,
11023 this->location());
11024 }
11025
11026 // Dump ast representation for a field reference expression.
11027
11028 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11029 Field_reference_expression::do_dump_expression(
11030 Ast_dump_context* ast_dump_context) const
11031 {
11032 this->expr_->dump_expression(ast_dump_context);
11033 ast_dump_context->ostream() << "." << this->field_index_;
11034 }
11035
11036 // Make a reference to a qualified identifier in an expression.
11037
11038 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)11039 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11040 Location location)
11041 {
11042 return new Field_reference_expression(expr, field_index, location);
11043 }
11044
11045 // Class Interface_field_reference_expression.
11046
11047 // Return an expression for the pointer to the function to call.
11048
11049 Expression*
get_function()11050 Interface_field_reference_expression::get_function()
11051 {
11052 Expression* ref = this->expr_;
11053 Location loc = this->location();
11054 if (ref->type()->points_to() != NULL)
11055 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11056
11057 Expression* mtable =
11058 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11059 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11060
11061 std::string name = Gogo::unpack_hidden_name(this->name_);
11062 unsigned int index;
11063 const Struct_field* field = mtable_type->find_local_field(name, &index);
11064 go_assert(field != NULL);
11065 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11066 return Expression::make_field_reference(mtable, index, loc);
11067 }
11068
11069 // Return an expression for the first argument to pass to the interface
11070 // function.
11071
11072 Expression*
get_underlying_object()11073 Interface_field_reference_expression::get_underlying_object()
11074 {
11075 Expression* expr = this->expr_;
11076 if (expr->type()->points_to() != NULL)
11077 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11078 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11079 this->location());
11080 }
11081
11082 // Traversal.
11083
11084 int
do_traverse(Traverse * traverse)11085 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11086 {
11087 return Expression::traverse(&this->expr_, traverse);
11088 }
11089
11090 // Lower the expression. If this expression is not called, we need to
11091 // evaluate the expression twice when converting to the backend
11092 // interface. So introduce a temporary variable if necessary.
11093
11094 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11095 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11096 Statement_inserter* inserter)
11097 {
11098 if (this->expr_->is_error_expression()
11099 || this->expr_->type()->is_error_type())
11100 {
11101 go_assert(saw_errors());
11102 return Expression::make_error(this->location());
11103 }
11104
11105 if (!this->expr_->is_variable())
11106 {
11107 Temporary_statement* temp =
11108 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11109 inserter->insert(temp);
11110 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11111 this->location());
11112 }
11113 return this;
11114 }
11115
11116 // Return the type of an interface field reference.
11117
11118 Type*
do_type()11119 Interface_field_reference_expression::do_type()
11120 {
11121 Type* expr_type = this->expr_->type();
11122
11123 Type* points_to = expr_type->points_to();
11124 if (points_to != NULL)
11125 expr_type = points_to;
11126
11127 Interface_type* interface_type = expr_type->interface_type();
11128 if (interface_type == NULL)
11129 return Type::make_error_type();
11130
11131 const Typed_identifier* method = interface_type->find_method(this->name_);
11132 if (method == NULL)
11133 return Type::make_error_type();
11134
11135 return method->type();
11136 }
11137
11138 // Determine types.
11139
11140 void
do_determine_type(const Type_context *)11141 Interface_field_reference_expression::do_determine_type(const Type_context*)
11142 {
11143 this->expr_->determine_type_no_context();
11144 }
11145
11146 // Check the types for an interface field reference.
11147
11148 void
do_check_types(Gogo *)11149 Interface_field_reference_expression::do_check_types(Gogo*)
11150 {
11151 Type* type = this->expr_->type();
11152
11153 Type* points_to = type->points_to();
11154 if (points_to != NULL)
11155 type = points_to;
11156
11157 Interface_type* interface_type = type->interface_type();
11158 if (interface_type == NULL)
11159 {
11160 if (!type->is_error_type())
11161 this->report_error(_("expected interface or pointer to interface"));
11162 }
11163 else
11164 {
11165 const Typed_identifier* method =
11166 interface_type->find_method(this->name_);
11167 if (method == NULL)
11168 {
11169 error_at(this->location(), "method %qs not in interface",
11170 Gogo::message_name(this->name_).c_str());
11171 this->set_is_error();
11172 }
11173 }
11174 }
11175
11176 // If an interface field reference is not simply called, then it is
11177 // represented as a closure. The closure will hold a single variable,
11178 // the value of the interface on which the method should be called.
11179 // The function will be a simple thunk that pulls the value from the
11180 // closure and calls the method with the remaining arguments.
11181
11182 // Because method values are not common, we don't build all thunks for
11183 // all possible interface methods, but instead only build them as we
11184 // need them. In particular, we even build them on demand for
11185 // interface methods defined in other packages.
11186
11187 Interface_field_reference_expression::Interface_method_thunks
11188 Interface_field_reference_expression::interface_method_thunks;
11189
11190 // Find or create the thunk to call method NAME on TYPE.
11191
11192 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)11193 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11194 Interface_type* type,
11195 const std::string& name)
11196 {
11197 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11198 std::pair<Interface_method_thunks::iterator, bool> ins =
11199 Interface_field_reference_expression::interface_method_thunks.insert(val);
11200 if (ins.second)
11201 {
11202 // This is the first time we have seen this interface.
11203 ins.first->second = new Method_thunks();
11204 }
11205
11206 for (Method_thunks::const_iterator p = ins.first->second->begin();
11207 p != ins.first->second->end();
11208 p++)
11209 if (p->first == name)
11210 return p->second;
11211
11212 Location loc = type->location();
11213
11214 const Typed_identifier* method_id = type->find_method(name);
11215 if (method_id == NULL)
11216 return Named_object::make_erroneous_name(Gogo::thunk_name());
11217
11218 Function_type* orig_fntype = method_id->type()->function_type();
11219 if (orig_fntype == NULL)
11220 return Named_object::make_erroneous_name(Gogo::thunk_name());
11221
11222 Struct_field_list* sfl = new Struct_field_list();
11223 // The type here is wrong--it should be the C function type. But it
11224 // doesn't really matter.
11225 Type* vt = Type::make_pointer_type(Type::make_void_type());
11226 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11227 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11228 Type* closure_type = Type::make_struct_type(sfl, loc);
11229 closure_type = Type::make_pointer_type(closure_type);
11230
11231 Function_type* new_fntype = orig_fntype->copy_with_names();
11232
11233 std::string thunk_name = Gogo::thunk_name();
11234 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11235 false, loc);
11236
11237 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11238 cvar->set_is_used();
11239 cvar->set_is_closure();
11240 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11241 NULL, cvar);
11242 new_no->func_value()->set_closure_var(cp);
11243
11244 gogo->start_block(loc);
11245
11246 // Field 0 of the closure is the function code pointer, field 1 is
11247 // the value on which to invoke the method.
11248 Expression* arg = Expression::make_var_reference(cp, loc);
11249 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11250 arg = Expression::make_field_reference(arg, 1, loc);
11251
11252 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11253 loc);
11254
11255 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11256 Expression_list* args;
11257 if (orig_params == NULL || orig_params->empty())
11258 args = NULL;
11259 else
11260 {
11261 const Typed_identifier_list* new_params = new_fntype->parameters();
11262 args = new Expression_list();
11263 for (Typed_identifier_list::const_iterator p = new_params->begin();
11264 p != new_params->end();
11265 ++p)
11266 {
11267 Named_object* p_no = gogo->lookup(p->name(), NULL);
11268 go_assert(p_no != NULL
11269 && p_no->is_variable()
11270 && p_no->var_value()->is_parameter());
11271 args->push_back(Expression::make_var_reference(p_no, loc));
11272 }
11273 }
11274
11275 Call_expression* call = Expression::make_call(ifre, args,
11276 orig_fntype->is_varargs(),
11277 loc);
11278 call->set_varargs_are_lowered();
11279
11280 Statement* s = Statement::make_return_from_call(call, loc);
11281 gogo->add_statement(s);
11282 Block* b = gogo->finish_block(loc);
11283 gogo->add_block(b, loc);
11284 gogo->lower_block(new_no, b);
11285 gogo->flatten_block(new_no, b);
11286 gogo->finish_function(loc);
11287
11288 ins.first->second->push_back(std::make_pair(name, new_no));
11289 return new_no;
11290 }
11291
11292 // Get the backend representation for a method value.
11293
11294 Bexpression*
do_get_backend(Translate_context * context)11295 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11296 {
11297 Interface_type* type = this->expr_->type()->interface_type();
11298 if (type == NULL)
11299 {
11300 go_assert(saw_errors());
11301 return context->backend()->error_expression();
11302 }
11303
11304 Named_object* thunk =
11305 Interface_field_reference_expression::create_thunk(context->gogo(),
11306 type, this->name_);
11307 if (thunk->is_erroneous())
11308 {
11309 go_assert(saw_errors());
11310 return context->backend()->error_expression();
11311 }
11312
11313 // FIXME: We should lower this earlier, but we can't it lower it in
11314 // the lowering pass because at that point we don't know whether we
11315 // need to create the thunk or not. If the expression is called, we
11316 // don't need the thunk.
11317
11318 Location loc = this->location();
11319
11320 Struct_field_list* fields = new Struct_field_list();
11321 fields->push_back(Struct_field(Typed_identifier("fn.0",
11322 thunk->func_value()->type(),
11323 loc)));
11324 fields->push_back(Struct_field(Typed_identifier("val.1",
11325 this->expr_->type(),
11326 loc)));
11327 Struct_type* st = Type::make_struct_type(fields, loc);
11328
11329 Expression_list* vals = new Expression_list();
11330 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11331 vals->push_back(this->expr_);
11332
11333 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11334 Bexpression* bclosure =
11335 Expression::make_heap_expression(expr, loc)->get_backend(context);
11336
11337 Expression* nil_check =
11338 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11339 Expression::make_nil(loc), loc);
11340 Bexpression* bnil_check = nil_check->get_backend(context);
11341
11342 Gogo* gogo = context->gogo();
11343 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11344 loc)->get_backend(context);
11345
11346 Bexpression* bcond =
11347 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11348 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11349 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11350 }
11351
11352 // Dump ast representation for an interface field reference.
11353
11354 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11355 Interface_field_reference_expression::do_dump_expression(
11356 Ast_dump_context* ast_dump_context) const
11357 {
11358 this->expr_->dump_expression(ast_dump_context);
11359 ast_dump_context->ostream() << "." << this->name_;
11360 }
11361
11362 // Make a reference to a field in an interface.
11363
11364 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)11365 Expression::make_interface_field_reference(Expression* expr,
11366 const std::string& field,
11367 Location location)
11368 {
11369 return new Interface_field_reference_expression(expr, field, location);
11370 }
11371
11372 // A general selector. This is a Parser_expression for LEFT.NAME. It
11373 // is lowered after we know the type of the left hand side.
11374
11375 class Selector_expression : public Parser_expression
11376 {
11377 public:
Selector_expression(Expression * left,const std::string & name,Location location)11378 Selector_expression(Expression* left, const std::string& name,
11379 Location location)
11380 : Parser_expression(EXPRESSION_SELECTOR, location),
11381 left_(left), name_(name)
11382 { }
11383
11384 protected:
11385 int
do_traverse(Traverse * traverse)11386 do_traverse(Traverse* traverse)
11387 { return Expression::traverse(&this->left_, traverse); }
11388
11389 Expression*
11390 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11391
11392 Expression*
do_copy()11393 do_copy()
11394 {
11395 return new Selector_expression(this->left_->copy(), this->name_,
11396 this->location());
11397 }
11398
11399 void
11400 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11401
11402 private:
11403 Expression*
11404 lower_method_expression(Gogo*);
11405
11406 // The expression on the left hand side.
11407 Expression* left_;
11408 // The name on the right hand side.
11409 std::string name_;
11410 };
11411
11412 // Lower a selector expression once we know the real type of the left
11413 // hand side.
11414
11415 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)11416 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11417 int)
11418 {
11419 Expression* left = this->left_;
11420 if (left->is_type_expression())
11421 return this->lower_method_expression(gogo);
11422 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11423 this->location());
11424 }
11425
11426 // Lower a method expression T.M or (*T).M. We turn this into a
11427 // function literal.
11428
11429 Expression*
lower_method_expression(Gogo * gogo)11430 Selector_expression::lower_method_expression(Gogo* gogo)
11431 {
11432 Location location = this->location();
11433 Type* type = this->left_->type();
11434 const std::string& name(this->name_);
11435
11436 bool is_pointer;
11437 if (type->points_to() == NULL)
11438 is_pointer = false;
11439 else
11440 {
11441 is_pointer = true;
11442 type = type->points_to();
11443 }
11444 Named_type* nt = type->named_type();
11445 if (nt == NULL)
11446 {
11447 error_at(location,
11448 ("method expression requires named type or "
11449 "pointer to named type"));
11450 return Expression::make_error(location);
11451 }
11452
11453 bool is_ambiguous;
11454 Method* method = nt->method_function(name, &is_ambiguous);
11455 const Typed_identifier* imethod = NULL;
11456 if (method == NULL && !is_pointer)
11457 {
11458 Interface_type* it = nt->interface_type();
11459 if (it != NULL)
11460 imethod = it->find_method(name);
11461 }
11462
11463 if (method == NULL && imethod == NULL)
11464 {
11465 if (!is_ambiguous)
11466 error_at(location, "type %<%s%s%> has no method %<%s%>",
11467 is_pointer ? "*" : "",
11468 nt->message_name().c_str(),
11469 Gogo::message_name(name).c_str());
11470 else
11471 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11472 Gogo::message_name(name).c_str(),
11473 is_pointer ? "*" : "",
11474 nt->message_name().c_str());
11475 return Expression::make_error(location);
11476 }
11477
11478 if (method != NULL && !is_pointer && !method->is_value_method())
11479 {
11480 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11481 nt->message_name().c_str(),
11482 Gogo::message_name(name).c_str());
11483 return Expression::make_error(location);
11484 }
11485
11486 // Build a new function type in which the receiver becomes the first
11487 // argument.
11488 Function_type* method_type;
11489 if (method != NULL)
11490 {
11491 method_type = method->type();
11492 go_assert(method_type->is_method());
11493 }
11494 else
11495 {
11496 method_type = imethod->type()->function_type();
11497 go_assert(method_type != NULL && !method_type->is_method());
11498 }
11499
11500 const char* const receiver_name = "$this";
11501 Typed_identifier_list* parameters = new Typed_identifier_list();
11502 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11503 location));
11504
11505 const Typed_identifier_list* method_parameters = method_type->parameters();
11506 if (method_parameters != NULL)
11507 {
11508 int i = 0;
11509 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11510 p != method_parameters->end();
11511 ++p, ++i)
11512 {
11513 if (!p->name().empty())
11514 parameters->push_back(*p);
11515 else
11516 {
11517 char buf[20];
11518 snprintf(buf, sizeof buf, "$param%d", i);
11519 parameters->push_back(Typed_identifier(buf, p->type(),
11520 p->location()));
11521 }
11522 }
11523 }
11524
11525 const Typed_identifier_list* method_results = method_type->results();
11526 Typed_identifier_list* results;
11527 if (method_results == NULL)
11528 results = NULL;
11529 else
11530 {
11531 results = new Typed_identifier_list();
11532 for (Typed_identifier_list::const_iterator p = method_results->begin();
11533 p != method_results->end();
11534 ++p)
11535 results->push_back(*p);
11536 }
11537
11538 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11539 location);
11540 if (method_type->is_varargs())
11541 fntype->set_is_varargs();
11542
11543 // We generate methods which always takes a pointer to the receiver
11544 // as their first argument. If this is for a pointer type, we can
11545 // simply reuse the existing function. We use an internal hack to
11546 // get the right type.
11547 // FIXME: This optimization is disabled because it doesn't yet work
11548 // with function descriptors when the method expression is not
11549 // directly called.
11550 if (method != NULL && is_pointer && false)
11551 {
11552 Named_object* mno = (method->needs_stub_method()
11553 ? method->stub_object()
11554 : method->named_object());
11555 Expression* f = Expression::make_func_reference(mno, NULL, location);
11556 f = Expression::make_cast(fntype, f, location);
11557 Type_conversion_expression* tce =
11558 static_cast<Type_conversion_expression*>(f);
11559 tce->set_may_convert_function_types();
11560 return f;
11561 }
11562
11563 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11564 location);
11565
11566 Named_object* vno = gogo->lookup(receiver_name, NULL);
11567 go_assert(vno != NULL);
11568 Expression* ve = Expression::make_var_reference(vno, location);
11569 Expression* bm;
11570 if (method != NULL)
11571 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11572 else
11573 bm = Expression::make_interface_field_reference(ve, name, location);
11574
11575 // Even though we found the method above, if it has an error type we
11576 // may see an error here.
11577 if (bm->is_error_expression())
11578 {
11579 gogo->finish_function(location);
11580 return bm;
11581 }
11582
11583 Expression_list* args;
11584 if (parameters->size() <= 1)
11585 args = NULL;
11586 else
11587 {
11588 args = new Expression_list();
11589 Typed_identifier_list::const_iterator p = parameters->begin();
11590 ++p;
11591 for (; p != parameters->end(); ++p)
11592 {
11593 vno = gogo->lookup(p->name(), NULL);
11594 go_assert(vno != NULL);
11595 args->push_back(Expression::make_var_reference(vno, location));
11596 }
11597 }
11598
11599 gogo->start_block(location);
11600
11601 Call_expression* call = Expression::make_call(bm, args,
11602 method_type->is_varargs(),
11603 location);
11604
11605 Statement* s = Statement::make_return_from_call(call, location);
11606 gogo->add_statement(s);
11607
11608 Block* b = gogo->finish_block(location);
11609
11610 gogo->add_block(b, location);
11611
11612 // Lower the call in case there are multiple results.
11613 gogo->lower_block(no, b);
11614 gogo->flatten_block(no, b);
11615
11616 gogo->finish_function(location);
11617
11618 return Expression::make_func_reference(no, NULL, location);
11619 }
11620
11621 // Dump the ast for a selector expression.
11622
11623 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11624 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11625 const
11626 {
11627 ast_dump_context->dump_expression(this->left_);
11628 ast_dump_context->ostream() << ".";
11629 ast_dump_context->ostream() << this->name_;
11630 }
11631
11632 // Make a selector expression.
11633
11634 Expression*
make_selector(Expression * left,const std::string & name,Location location)11635 Expression::make_selector(Expression* left, const std::string& name,
11636 Location location)
11637 {
11638 return new Selector_expression(left, name, location);
11639 }
11640
11641 // Class Allocation_expression.
11642
11643 int
do_traverse(Traverse * traverse)11644 Allocation_expression::do_traverse(Traverse* traverse)
11645 {
11646 return Type::traverse(this->type_, traverse);
11647 }
11648
11649 Type*
do_type()11650 Allocation_expression::do_type()
11651 {
11652 return Type::make_pointer_type(this->type_);
11653 }
11654
11655 // Make a copy of an allocation expression.
11656
11657 Expression*
do_copy()11658 Allocation_expression::do_copy()
11659 {
11660 Allocation_expression* alloc =
11661 new Allocation_expression(this->type_, this->location());
11662 if (this->allocate_on_stack_)
11663 alloc->set_allocate_on_stack();
11664 return alloc;
11665 }
11666
11667 // Return the backend representation for an allocation expression.
11668
11669 Bexpression*
do_get_backend(Translate_context * context)11670 Allocation_expression::do_get_backend(Translate_context* context)
11671 {
11672 Gogo* gogo = context->gogo();
11673 Location loc = this->location();
11674
11675 if (this->allocate_on_stack_)
11676 {
11677 int64_t size;
11678 bool ok = this->type_->backend_type_size(gogo, &size);
11679 if (!ok)
11680 {
11681 go_assert(saw_errors());
11682 return gogo->backend()->error_expression();
11683 }
11684 return gogo->backend()->stack_allocation_expression(size, loc);
11685 }
11686
11687 Btype* btype = this->type_->get_backend(gogo);
11688 Bexpression* space =
11689 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11690 Btype* pbtype = gogo->backend()->pointer_type(btype);
11691 return gogo->backend()->convert_expression(pbtype, space, loc);
11692 }
11693
11694 // Dump ast representation for an allocation expression.
11695
11696 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11697 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11698 const
11699 {
11700 ast_dump_context->ostream() << "new(";
11701 ast_dump_context->dump_type(this->type_);
11702 ast_dump_context->ostream() << ")";
11703 }
11704
11705 // Make an allocation expression.
11706
11707 Expression*
make_allocation(Type * type,Location location)11708 Expression::make_allocation(Type* type, Location location)
11709 {
11710 return new Allocation_expression(type, location);
11711 }
11712
11713 // Class Struct_construction_expression.
11714
11715 // Traversal.
11716
11717 int
do_traverse(Traverse * traverse)11718 Struct_construction_expression::do_traverse(Traverse* traverse)
11719 {
11720 if (this->vals_ != NULL)
11721 {
11722 if (this->traverse_order_ == NULL)
11723 {
11724 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11725 return TRAVERSE_EXIT;
11726 }
11727 else
11728 {
11729 for (std::vector<int>::const_iterator p =
11730 this->traverse_order_->begin();
11731 p != this->traverse_order_->end();
11732 ++p)
11733 {
11734 if (Expression::traverse(&this->vals_->at(*p), traverse)
11735 == TRAVERSE_EXIT)
11736 return TRAVERSE_EXIT;
11737 }
11738 }
11739 }
11740 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11741 return TRAVERSE_EXIT;
11742 return TRAVERSE_CONTINUE;
11743 }
11744
11745 // Return whether this is a constant initializer.
11746
11747 bool
is_constant_struct() const11748 Struct_construction_expression::is_constant_struct() const
11749 {
11750 if (this->vals_ == NULL)
11751 return true;
11752 for (Expression_list::const_iterator pv = this->vals_->begin();
11753 pv != this->vals_->end();
11754 ++pv)
11755 {
11756 if (*pv != NULL
11757 && !(*pv)->is_constant()
11758 && (!(*pv)->is_composite_literal()
11759 || (*pv)->is_nonconstant_composite_literal()))
11760 return false;
11761 }
11762
11763 const Struct_field_list* fields = this->type_->struct_type()->fields();
11764 for (Struct_field_list::const_iterator pf = fields->begin();
11765 pf != fields->end();
11766 ++pf)
11767 {
11768 // There are no constant constructors for interfaces.
11769 if (pf->type()->interface_type() != NULL)
11770 return false;
11771 }
11772
11773 return true;
11774 }
11775
11776 // Return whether this struct is immutable.
11777
11778 bool
do_is_immutable() const11779 Struct_construction_expression::do_is_immutable() const
11780 {
11781 if (this->vals_ == NULL)
11782 return true;
11783 for (Expression_list::const_iterator pv = this->vals_->begin();
11784 pv != this->vals_->end();
11785 ++pv)
11786 {
11787 if (*pv != NULL && !(*pv)->is_immutable())
11788 return false;
11789 }
11790 return true;
11791 }
11792
11793 // Final type determination.
11794
11795 void
do_determine_type(const Type_context *)11796 Struct_construction_expression::do_determine_type(const Type_context*)
11797 {
11798 if (this->vals_ == NULL)
11799 return;
11800 const Struct_field_list* fields = this->type_->struct_type()->fields();
11801 Expression_list::const_iterator pv = this->vals_->begin();
11802 for (Struct_field_list::const_iterator pf = fields->begin();
11803 pf != fields->end();
11804 ++pf, ++pv)
11805 {
11806 if (pv == this->vals_->end())
11807 return;
11808 if (*pv != NULL)
11809 {
11810 Type_context subcontext(pf->type(), false);
11811 (*pv)->determine_type(&subcontext);
11812 }
11813 }
11814 // Extra values are an error we will report elsewhere; we still want
11815 // to determine the type to avoid knockon errors.
11816 for (; pv != this->vals_->end(); ++pv)
11817 (*pv)->determine_type_no_context();
11818 }
11819
11820 // Check types.
11821
11822 void
do_check_types(Gogo *)11823 Struct_construction_expression::do_check_types(Gogo*)
11824 {
11825 if (this->vals_ == NULL)
11826 return;
11827
11828 Struct_type* st = this->type_->struct_type();
11829 if (this->vals_->size() > st->field_count())
11830 {
11831 this->report_error(_("too many expressions for struct"));
11832 return;
11833 }
11834
11835 const Struct_field_list* fields = st->fields();
11836 Expression_list::const_iterator pv = this->vals_->begin();
11837 int i = 0;
11838 for (Struct_field_list::const_iterator pf = fields->begin();
11839 pf != fields->end();
11840 ++pf, ++pv, ++i)
11841 {
11842 if (pv == this->vals_->end())
11843 {
11844 this->report_error(_("too few expressions for struct"));
11845 break;
11846 }
11847
11848 if (*pv == NULL)
11849 continue;
11850
11851 std::string reason;
11852 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11853 {
11854 if (reason.empty())
11855 error_at((*pv)->location(),
11856 "incompatible type for field %d in struct construction",
11857 i + 1);
11858 else
11859 error_at((*pv)->location(),
11860 ("incompatible type for field %d in "
11861 "struct construction (%s)"),
11862 i + 1, reason.c_str());
11863 this->set_is_error();
11864 }
11865 }
11866 go_assert(pv == this->vals_->end());
11867 }
11868
11869 // Flatten a struct construction expression. Store the values into
11870 // temporaries in case they need interface conversion.
11871
11872 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11873 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
11874 Statement_inserter* inserter)
11875 {
11876 if (this->vals_ == NULL)
11877 return this;
11878
11879 // If this is a constant struct, we don't need temporaries.
11880 if (this->is_constant_struct())
11881 return this;
11882
11883 Location loc = this->location();
11884 for (Expression_list::iterator pv = this->vals_->begin();
11885 pv != this->vals_->end();
11886 ++pv)
11887 {
11888 if (*pv != NULL)
11889 {
11890 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
11891 {
11892 go_assert(saw_errors());
11893 return Expression::make_error(loc);
11894 }
11895 if (!(*pv)->is_variable())
11896 {
11897 Temporary_statement* temp =
11898 Statement::make_temporary(NULL, *pv, loc);
11899 inserter->insert(temp);
11900 *pv = Expression::make_temporary_reference(temp, loc);
11901 }
11902 }
11903 }
11904 return this;
11905 }
11906
11907 // Return the backend representation for constructing a struct.
11908
11909 Bexpression*
do_get_backend(Translate_context * context)11910 Struct_construction_expression::do_get_backend(Translate_context* context)
11911 {
11912 Gogo* gogo = context->gogo();
11913
11914 Btype* btype = this->type_->get_backend(gogo);
11915 if (this->vals_ == NULL)
11916 return gogo->backend()->zero_expression(btype);
11917
11918 const Struct_field_list* fields = this->type_->struct_type()->fields();
11919 Expression_list::const_iterator pv = this->vals_->begin();
11920 std::vector<Bexpression*> init;
11921 for (Struct_field_list::const_iterator pf = fields->begin();
11922 pf != fields->end();
11923 ++pf)
11924 {
11925 Btype* fbtype = pf->type()->get_backend(gogo);
11926 if (pv == this->vals_->end())
11927 init.push_back(gogo->backend()->zero_expression(fbtype));
11928 else if (*pv == NULL)
11929 {
11930 init.push_back(gogo->backend()->zero_expression(fbtype));
11931 ++pv;
11932 }
11933 else
11934 {
11935 Expression* val =
11936 Expression::convert_for_assignment(gogo, pf->type(),
11937 *pv, this->location());
11938 init.push_back(val->get_backend(context));
11939 ++pv;
11940 }
11941 }
11942 return gogo->backend()->constructor_expression(btype, init, this->location());
11943 }
11944
11945 // Export a struct construction.
11946
11947 void
do_export(Export * exp) const11948 Struct_construction_expression::do_export(Export* exp) const
11949 {
11950 exp->write_c_string("convert(");
11951 exp->write_type(this->type_);
11952 for (Expression_list::const_iterator pv = this->vals_->begin();
11953 pv != this->vals_->end();
11954 ++pv)
11955 {
11956 exp->write_c_string(", ");
11957 if (*pv != NULL)
11958 (*pv)->export_expression(exp);
11959 }
11960 exp->write_c_string(")");
11961 }
11962
11963 // Dump ast representation of a struct construction expression.
11964
11965 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11966 Struct_construction_expression::do_dump_expression(
11967 Ast_dump_context* ast_dump_context) const
11968 {
11969 ast_dump_context->dump_type(this->type_);
11970 ast_dump_context->ostream() << "{";
11971 ast_dump_context->dump_expression_list(this->vals_);
11972 ast_dump_context->ostream() << "}";
11973 }
11974
11975 // Make a struct composite literal. This used by the thunk code.
11976
11977 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)11978 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11979 Location location)
11980 {
11981 go_assert(type->struct_type() != NULL);
11982 return new Struct_construction_expression(type, vals, location);
11983 }
11984
11985 // Class Array_construction_expression.
11986
11987 // Traversal.
11988
11989 int
do_traverse(Traverse * traverse)11990 Array_construction_expression::do_traverse(Traverse* traverse)
11991 {
11992 if (this->vals_ != NULL
11993 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11994 return TRAVERSE_EXIT;
11995 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11996 return TRAVERSE_EXIT;
11997 return TRAVERSE_CONTINUE;
11998 }
11999
12000 // Return whether this is a constant initializer.
12001
12002 bool
is_constant_array() const12003 Array_construction_expression::is_constant_array() const
12004 {
12005 if (this->vals_ == NULL)
12006 return true;
12007
12008 // There are no constant constructors for interfaces.
12009 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12010 return false;
12011
12012 for (Expression_list::const_iterator pv = this->vals_->begin();
12013 pv != this->vals_->end();
12014 ++pv)
12015 {
12016 if (*pv != NULL
12017 && !(*pv)->is_constant()
12018 && (!(*pv)->is_composite_literal()
12019 || (*pv)->is_nonconstant_composite_literal()))
12020 return false;
12021 }
12022 return true;
12023 }
12024
12025 // Return whether this is an immutable array initializer.
12026
12027 bool
do_is_immutable() const12028 Array_construction_expression::do_is_immutable() const
12029 {
12030 if (this->vals_ == NULL)
12031 return true;
12032 for (Expression_list::const_iterator pv = this->vals_->begin();
12033 pv != this->vals_->end();
12034 ++pv)
12035 {
12036 if (*pv != NULL && !(*pv)->is_immutable())
12037 return false;
12038 }
12039 return true;
12040 }
12041
12042 // Final type determination.
12043
12044 void
do_determine_type(const Type_context *)12045 Array_construction_expression::do_determine_type(const Type_context*)
12046 {
12047 if (this->vals_ == NULL)
12048 return;
12049 Type_context subcontext(this->type_->array_type()->element_type(), false);
12050 for (Expression_list::const_iterator pv = this->vals_->begin();
12051 pv != this->vals_->end();
12052 ++pv)
12053 {
12054 if (*pv != NULL)
12055 (*pv)->determine_type(&subcontext);
12056 }
12057 }
12058
12059 // Check types.
12060
12061 void
do_check_types(Gogo *)12062 Array_construction_expression::do_check_types(Gogo*)
12063 {
12064 if (this->vals_ == NULL)
12065 return;
12066
12067 Array_type* at = this->type_->array_type();
12068 int i = 0;
12069 Type* element_type = at->element_type();
12070 for (Expression_list::const_iterator pv = this->vals_->begin();
12071 pv != this->vals_->end();
12072 ++pv, ++i)
12073 {
12074 if (*pv != NULL
12075 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12076 {
12077 error_at((*pv)->location(),
12078 "incompatible type for element %d in composite literal",
12079 i + 1);
12080 this->set_is_error();
12081 }
12082 }
12083 }
12084
12085 // Flatten an array construction expression. Store the values into
12086 // temporaries in case they need interface conversion.
12087
12088 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)12089 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12090 Statement_inserter* inserter)
12091 {
12092 if (this->vals_ == NULL)
12093 return this;
12094
12095 // If this is a constant array, we don't need temporaries.
12096 if (this->is_constant_array())
12097 return this;
12098
12099 Location loc = this->location();
12100 for (Expression_list::iterator pv = this->vals_->begin();
12101 pv != this->vals_->end();
12102 ++pv)
12103 {
12104 if (*pv != NULL)
12105 {
12106 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12107 {
12108 go_assert(saw_errors());
12109 return Expression::make_error(loc);
12110 }
12111 if (!(*pv)->is_variable())
12112 {
12113 Temporary_statement* temp =
12114 Statement::make_temporary(NULL, *pv, loc);
12115 inserter->insert(temp);
12116 *pv = Expression::make_temporary_reference(temp, loc);
12117 }
12118 }
12119 }
12120 return this;
12121 }
12122
12123 // Get a constructor expression for the array values.
12124
12125 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)12126 Array_construction_expression::get_constructor(Translate_context* context,
12127 Btype* array_btype)
12128 {
12129 Type* element_type = this->type_->array_type()->element_type();
12130
12131 std::vector<unsigned long> indexes;
12132 std::vector<Bexpression*> vals;
12133 Gogo* gogo = context->gogo();
12134 if (this->vals_ != NULL)
12135 {
12136 size_t i = 0;
12137 std::vector<unsigned long>::const_iterator pi;
12138 if (this->indexes_ != NULL)
12139 pi = this->indexes_->begin();
12140 for (Expression_list::const_iterator pv = this->vals_->begin();
12141 pv != this->vals_->end();
12142 ++pv, ++i)
12143 {
12144 if (this->indexes_ != NULL)
12145 go_assert(pi != this->indexes_->end());
12146
12147 if (this->indexes_ == NULL)
12148 indexes.push_back(i);
12149 else
12150 indexes.push_back(*pi);
12151 if (*pv == NULL)
12152 {
12153 Btype* ebtype = element_type->get_backend(gogo);
12154 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12155 vals.push_back(zv);
12156 }
12157 else
12158 {
12159 Expression* val_expr =
12160 Expression::convert_for_assignment(gogo, element_type, *pv,
12161 this->location());
12162 vals.push_back(val_expr->get_backend(context));
12163 }
12164 if (this->indexes_ != NULL)
12165 ++pi;
12166 }
12167 if (this->indexes_ != NULL)
12168 go_assert(pi == this->indexes_->end());
12169 }
12170 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12171 vals, this->location());
12172 }
12173
12174 // Export an array construction.
12175
12176 void
do_export(Export * exp) const12177 Array_construction_expression::do_export(Export* exp) const
12178 {
12179 exp->write_c_string("convert(");
12180 exp->write_type(this->type_);
12181 if (this->vals_ != NULL)
12182 {
12183 std::vector<unsigned long>::const_iterator pi;
12184 if (this->indexes_ != NULL)
12185 pi = this->indexes_->begin();
12186 for (Expression_list::const_iterator pv = this->vals_->begin();
12187 pv != this->vals_->end();
12188 ++pv)
12189 {
12190 exp->write_c_string(", ");
12191
12192 if (this->indexes_ != NULL)
12193 {
12194 char buf[100];
12195 snprintf(buf, sizeof buf, "%lu", *pi);
12196 exp->write_c_string(buf);
12197 exp->write_c_string(":");
12198 }
12199
12200 if (*pv != NULL)
12201 (*pv)->export_expression(exp);
12202
12203 if (this->indexes_ != NULL)
12204 ++pi;
12205 }
12206 }
12207 exp->write_c_string(")");
12208 }
12209
12210 // Dump ast representation of an array construction expressin.
12211
12212 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12213 Array_construction_expression::do_dump_expression(
12214 Ast_dump_context* ast_dump_context) const
12215 {
12216 Expression* length = this->type_->array_type()->length();
12217
12218 ast_dump_context->ostream() << "[" ;
12219 if (length != NULL)
12220 {
12221 ast_dump_context->dump_expression(length);
12222 }
12223 ast_dump_context->ostream() << "]" ;
12224 ast_dump_context->dump_type(this->type_);
12225 ast_dump_context->ostream() << "{" ;
12226 if (this->indexes_ == NULL)
12227 ast_dump_context->dump_expression_list(this->vals_);
12228 else
12229 {
12230 Expression_list::const_iterator pv = this->vals_->begin();
12231 for (std::vector<unsigned long>::const_iterator pi =
12232 this->indexes_->begin();
12233 pi != this->indexes_->end();
12234 ++pi, ++pv)
12235 {
12236 if (pi != this->indexes_->begin())
12237 ast_dump_context->ostream() << ", ";
12238 ast_dump_context->ostream() << *pi << ':';
12239 ast_dump_context->dump_expression(*pv);
12240 }
12241 }
12242 ast_dump_context->ostream() << "}" ;
12243
12244 }
12245
12246 // Class Fixed_array_construction_expression.
12247
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)12248 Fixed_array_construction_expression::Fixed_array_construction_expression(
12249 Type* type, const std::vector<unsigned long>* indexes,
12250 Expression_list* vals, Location location)
12251 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12252 type, indexes, vals, location)
12253 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12254
12255 // Return the backend representation for constructing a fixed array.
12256
12257 Bexpression*
do_get_backend(Translate_context * context)12258 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12259 {
12260 Type* type = this->type();
12261 Btype* btype = type->get_backend(context->gogo());
12262 return this->get_constructor(context, btype);
12263 }
12264
12265 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)12266 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12267 Location location)
12268 {
12269 go_assert(type->array_type() != NULL && !type->is_slice_type());
12270 return new Fixed_array_construction_expression(type, NULL, vals, location);
12271 }
12272
12273 // Class Slice_construction_expression.
12274
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)12275 Slice_construction_expression::Slice_construction_expression(
12276 Type* type, const std::vector<unsigned long>* indexes,
12277 Expression_list* vals, Location location)
12278 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12279 type, indexes, vals, location),
12280 valtype_(NULL)
12281 {
12282 go_assert(type->is_slice_type());
12283
12284 unsigned long lenval;
12285 Expression* length;
12286 if (vals == NULL || vals->empty())
12287 lenval = 0;
12288 else
12289 {
12290 if (this->indexes() == NULL)
12291 lenval = vals->size();
12292 else
12293 lenval = indexes->back() + 1;
12294 }
12295 Type* int_type = Type::lookup_integer_type("int");
12296 length = Expression::make_integer_ul(lenval, int_type, location);
12297 Type* element_type = type->array_type()->element_type();
12298 this->valtype_ = Type::make_array_type(element_type, length);
12299 }
12300
12301
12302 // Traversal.
12303
12304 int
do_traverse(Traverse * traverse)12305 Slice_construction_expression::do_traverse(Traverse* traverse)
12306 {
12307 if (this->Array_construction_expression::do_traverse(traverse)
12308 == TRAVERSE_EXIT)
12309 return TRAVERSE_EXIT;
12310 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12311 return TRAVERSE_EXIT;
12312 return TRAVERSE_CONTINUE;
12313 }
12314
12315 // Return the backend representation for constructing a slice.
12316
12317 Bexpression*
do_get_backend(Translate_context * context)12318 Slice_construction_expression::do_get_backend(Translate_context* context)
12319 {
12320 Array_type* array_type = this->type()->array_type();
12321 if (array_type == NULL)
12322 {
12323 go_assert(this->type()->is_error());
12324 return context->backend()->error_expression();
12325 }
12326
12327 Location loc = this->location();
12328 Type* element_type = array_type->element_type();
12329 go_assert(this->valtype_ != NULL);
12330
12331 Expression_list* vals = this->vals();
12332 if (this->vals() == NULL || this->vals()->empty())
12333 {
12334 // We need to create a unique value for the empty array literal.
12335 vals = new Expression_list;
12336 vals->push_back(NULL);
12337 }
12338 Expression* array_val =
12339 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12340 vals, loc);
12341
12342 bool is_constant_initializer = array_val->is_immutable();
12343
12344 // We have to copy the initial values into heap memory if we are in
12345 // a function or if the values are not constants. We also have to
12346 // copy them if they may contain pointers in a non-constant context,
12347 // as otherwise the garbage collector won't see them.
12348 bool copy_to_heap = (context->function() != NULL
12349 || !is_constant_initializer
12350 || (element_type->has_pointer()
12351 && !context->is_const()));
12352
12353 Expression* space;
12354 if (!copy_to_heap)
12355 {
12356 // The initializer will only run once.
12357 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12358 space->unary_expression()->set_is_slice_init();
12359 }
12360 else
12361 space = Expression::make_heap_expression(array_val, loc);
12362
12363 // Build a constructor for the slice.
12364
12365 Expression* len = this->valtype_->array_type()->length();
12366 Expression* slice_val =
12367 Expression::make_slice_value(this->type(), space, len, len, loc);
12368 return slice_val->get_backend(context);
12369 }
12370
12371 // Make a slice composite literal. This is used by the type
12372 // descriptor code.
12373
12374 Expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)12375 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12376 Location location)
12377 {
12378 go_assert(type->is_slice_type());
12379 return new Slice_construction_expression(type, NULL, vals, location);
12380 }
12381
12382 // Class Map_construction_expression.
12383
12384 // Traversal.
12385
12386 int
do_traverse(Traverse * traverse)12387 Map_construction_expression::do_traverse(Traverse* traverse)
12388 {
12389 if (this->vals_ != NULL
12390 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12391 return TRAVERSE_EXIT;
12392 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12393 return TRAVERSE_EXIT;
12394 return TRAVERSE_CONTINUE;
12395 }
12396
12397 // Flatten constructor initializer into a temporary variable since
12398 // we need to take its address for __go_construct_map.
12399
12400 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)12401 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12402 Statement_inserter* inserter)
12403 {
12404 if (!this->is_error_expression()
12405 && this->vals_ != NULL
12406 && !this->vals_->empty()
12407 && this->constructor_temp_ == NULL)
12408 {
12409 Map_type* mt = this->type_->map_type();
12410 Type* key_type = mt->key_type();
12411 Type* val_type = mt->val_type();
12412 this->element_type_ = Type::make_builtin_struct_type(2,
12413 "__key", key_type,
12414 "__val", val_type);
12415
12416 Expression_list* value_pairs = new Expression_list();
12417 Location loc = this->location();
12418
12419 size_t i = 0;
12420 for (Expression_list::const_iterator pv = this->vals_->begin();
12421 pv != this->vals_->end();
12422 ++pv, ++i)
12423 {
12424 Expression_list* key_value_pair = new Expression_list();
12425 Expression* key = *pv;
12426 if (key->is_error_expression() || key->type()->is_error_type())
12427 {
12428 go_assert(saw_errors());
12429 return Expression::make_error(loc);
12430 }
12431 if (key->type()->interface_type() != NULL && !key->is_variable())
12432 {
12433 Temporary_statement* temp =
12434 Statement::make_temporary(NULL, key, loc);
12435 inserter->insert(temp);
12436 key = Expression::make_temporary_reference(temp, loc);
12437 }
12438 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
12439
12440 ++pv;
12441 Expression* val = *pv;
12442 if (val->is_error_expression() || val->type()->is_error_type())
12443 {
12444 go_assert(saw_errors());
12445 return Expression::make_error(loc);
12446 }
12447 if (val->type()->interface_type() != NULL && !val->is_variable())
12448 {
12449 Temporary_statement* temp =
12450 Statement::make_temporary(NULL, val, loc);
12451 inserter->insert(temp);
12452 val = Expression::make_temporary_reference(temp, loc);
12453 }
12454 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
12455
12456 key_value_pair->push_back(key);
12457 key_value_pair->push_back(val);
12458 value_pairs->push_back(
12459 Expression::make_struct_composite_literal(this->element_type_,
12460 key_value_pair, loc));
12461 }
12462
12463 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
12464 Type* ctor_type =
12465 Type::make_array_type(this->element_type_, element_count);
12466 Expression* constructor =
12467 new Fixed_array_construction_expression(ctor_type, NULL,
12468 value_pairs, loc);
12469
12470 this->constructor_temp_ =
12471 Statement::make_temporary(NULL, constructor, loc);
12472 constructor->issue_nil_check();
12473 this->constructor_temp_->set_is_address_taken();
12474 inserter->insert(this->constructor_temp_);
12475 }
12476
12477 return this;
12478 }
12479
12480 // Final type determination.
12481
12482 void
do_determine_type(const Type_context *)12483 Map_construction_expression::do_determine_type(const Type_context*)
12484 {
12485 if (this->vals_ == NULL)
12486 return;
12487
12488 Map_type* mt = this->type_->map_type();
12489 Type_context key_context(mt->key_type(), false);
12490 Type_context val_context(mt->val_type(), false);
12491 for (Expression_list::const_iterator pv = this->vals_->begin();
12492 pv != this->vals_->end();
12493 ++pv)
12494 {
12495 (*pv)->determine_type(&key_context);
12496 ++pv;
12497 (*pv)->determine_type(&val_context);
12498 }
12499 }
12500
12501 // Check types.
12502
12503 void
do_check_types(Gogo *)12504 Map_construction_expression::do_check_types(Gogo*)
12505 {
12506 if (this->vals_ == NULL)
12507 return;
12508
12509 Map_type* mt = this->type_->map_type();
12510 int i = 0;
12511 Type* key_type = mt->key_type();
12512 Type* val_type = mt->val_type();
12513 for (Expression_list::const_iterator pv = this->vals_->begin();
12514 pv != this->vals_->end();
12515 ++pv, ++i)
12516 {
12517 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12518 {
12519 error_at((*pv)->location(),
12520 "incompatible type for element %d key in map construction",
12521 i + 1);
12522 this->set_is_error();
12523 }
12524 ++pv;
12525 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12526 {
12527 error_at((*pv)->location(),
12528 ("incompatible type for element %d value "
12529 "in map construction"),
12530 i + 1);
12531 this->set_is_error();
12532 }
12533 }
12534 }
12535
12536 // Return the backend representation for constructing a map.
12537
12538 Bexpression*
do_get_backend(Translate_context * context)12539 Map_construction_expression::do_get_backend(Translate_context* context)
12540 {
12541 if (this->is_error_expression())
12542 return context->backend()->error_expression();
12543 Location loc = this->location();
12544
12545 size_t i = 0;
12546 Expression* ventries;
12547 if (this->vals_ == NULL || this->vals_->empty())
12548 ventries = Expression::make_nil(loc);
12549 else
12550 {
12551 go_assert(this->constructor_temp_ != NULL);
12552 i = this->vals_->size() / 2;
12553
12554 Expression* ctor_ref =
12555 Expression::make_temporary_reference(this->constructor_temp_, loc);
12556 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12557 }
12558
12559 Map_type* mt = this->type_->map_type();
12560 if (this->element_type_ == NULL)
12561 this->element_type_ =
12562 Type::make_builtin_struct_type(2,
12563 "__key", mt->key_type(),
12564 "__val", mt->val_type());
12565 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12566
12567 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12568 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
12569
12570 Expression* entry_size =
12571 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12572
12573 unsigned int field_index;
12574 const Struct_field* valfield =
12575 this->element_type_->find_local_field("__val", &field_index);
12576 Expression* val_offset =
12577 Expression::make_struct_field_offset(this->element_type_, valfield);
12578 Expression* val_size =
12579 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12580
12581 Expression* map_ctor =
12582 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12583 entry_size, val_offset, val_size, ventries);
12584 return map_ctor->get_backend(context);
12585 }
12586
12587 // Export an array construction.
12588
12589 void
do_export(Export * exp) const12590 Map_construction_expression::do_export(Export* exp) const
12591 {
12592 exp->write_c_string("convert(");
12593 exp->write_type(this->type_);
12594 for (Expression_list::const_iterator pv = this->vals_->begin();
12595 pv != this->vals_->end();
12596 ++pv)
12597 {
12598 exp->write_c_string(", ");
12599 (*pv)->export_expression(exp);
12600 }
12601 exp->write_c_string(")");
12602 }
12603
12604 // Dump ast representation for a map construction expression.
12605
12606 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12607 Map_construction_expression::do_dump_expression(
12608 Ast_dump_context* ast_dump_context) const
12609 {
12610 ast_dump_context->ostream() << "{" ;
12611 ast_dump_context->dump_expression_list(this->vals_, true);
12612 ast_dump_context->ostream() << "}";
12613 }
12614
12615 // Class Composite_literal_expression.
12616
12617 // Traversal.
12618
12619 int
do_traverse(Traverse * traverse)12620 Composite_literal_expression::do_traverse(Traverse* traverse)
12621 {
12622 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12623 return TRAVERSE_EXIT;
12624
12625 // If this is a struct composite literal with keys, then the keys
12626 // are field names, not expressions. We don't want to traverse them
12627 // in that case. If we do, we can give an erroneous error "variable
12628 // initializer refers to itself." See bug482.go in the testsuite.
12629 if (this->has_keys_ && this->vals_ != NULL)
12630 {
12631 // The type may not be resolvable at this point.
12632 Type* type = this->type_;
12633
12634 for (int depth = 0; depth < this->depth_; ++depth)
12635 {
12636 if (type->array_type() != NULL)
12637 type = type->array_type()->element_type();
12638 else if (type->map_type() != NULL)
12639 {
12640 if (this->key_path_[depth])
12641 type = type->map_type()->key_type();
12642 else
12643 type = type->map_type()->val_type();
12644 }
12645 else
12646 {
12647 // This error will be reported during lowering.
12648 return TRAVERSE_CONTINUE;
12649 }
12650 }
12651
12652 while (true)
12653 {
12654 if (type->classification() == Type::TYPE_NAMED)
12655 type = type->named_type()->real_type();
12656 else if (type->classification() == Type::TYPE_FORWARD)
12657 {
12658 Type* t = type->forwarded();
12659 if (t == type)
12660 break;
12661 type = t;
12662 }
12663 else
12664 break;
12665 }
12666
12667 if (type->classification() == Type::TYPE_STRUCT)
12668 {
12669 Expression_list::iterator p = this->vals_->begin();
12670 while (p != this->vals_->end())
12671 {
12672 // Skip key.
12673 ++p;
12674 go_assert(p != this->vals_->end());
12675 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12676 return TRAVERSE_EXIT;
12677 ++p;
12678 }
12679 return TRAVERSE_CONTINUE;
12680 }
12681 }
12682
12683 if (this->vals_ != NULL)
12684 return this->vals_->traverse(traverse);
12685
12686 return TRAVERSE_CONTINUE;
12687 }
12688
12689 // Lower a generic composite literal into a specific version based on
12690 // the type.
12691
12692 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)12693 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12694 Statement_inserter* inserter, int)
12695 {
12696 Type* type = this->type_;
12697
12698 for (int depth = 0; depth < this->depth_; ++depth)
12699 {
12700 if (type->array_type() != NULL)
12701 type = type->array_type()->element_type();
12702 else if (type->map_type() != NULL)
12703 {
12704 if (this->key_path_[depth])
12705 type = type->map_type()->key_type();
12706 else
12707 type = type->map_type()->val_type();
12708 }
12709 else
12710 {
12711 if (!type->is_error())
12712 error_at(this->location(),
12713 ("may only omit types within composite literals "
12714 "of slice, array, or map type"));
12715 return Expression::make_error(this->location());
12716 }
12717 }
12718
12719 Type *pt = type->points_to();
12720 bool is_pointer = false;
12721 if (pt != NULL)
12722 {
12723 is_pointer = true;
12724 type = pt;
12725 }
12726
12727 Expression* ret;
12728 if (type->is_error())
12729 return Expression::make_error(this->location());
12730 else if (type->struct_type() != NULL)
12731 ret = this->lower_struct(gogo, type);
12732 else if (type->array_type() != NULL)
12733 ret = this->lower_array(type);
12734 else if (type->map_type() != NULL)
12735 ret = this->lower_map(gogo, function, inserter, type);
12736 else
12737 {
12738 error_at(this->location(),
12739 ("expected struct, slice, array, or map type "
12740 "for composite literal"));
12741 return Expression::make_error(this->location());
12742 }
12743
12744 if (is_pointer)
12745 ret = Expression::make_heap_expression(ret, this->location());
12746
12747 return ret;
12748 }
12749
12750 // Lower a struct composite literal.
12751
12752 Expression*
lower_struct(Gogo * gogo,Type * type)12753 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12754 {
12755 Location location = this->location();
12756 Struct_type* st = type->struct_type();
12757 if (this->vals_ == NULL || !this->has_keys_)
12758 {
12759 if (this->vals_ != NULL
12760 && !this->vals_->empty()
12761 && type->named_type() != NULL
12762 && type->named_type()->named_object()->package() != NULL)
12763 {
12764 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12765 pf != st->fields()->end();
12766 ++pf)
12767 {
12768 if (Gogo::is_hidden_name(pf->field_name())
12769 || pf->is_embedded_builtin(gogo))
12770 error_at(this->location(),
12771 "assignment of unexported field %qs in %qs literal",
12772 Gogo::message_name(pf->field_name()).c_str(),
12773 type->named_type()->message_name().c_str());
12774 }
12775 }
12776
12777 return new Struct_construction_expression(type, this->vals_, location);
12778 }
12779
12780 size_t field_count = st->field_count();
12781 std::vector<Expression*> vals(field_count);
12782 std::vector<int>* traverse_order = new(std::vector<int>);
12783 Expression_list::const_iterator p = this->vals_->begin();
12784 Expression* external_expr = NULL;
12785 const Named_object* external_no = NULL;
12786 while (p != this->vals_->end())
12787 {
12788 Expression* name_expr = *p;
12789
12790 ++p;
12791 go_assert(p != this->vals_->end());
12792 Expression* val = *p;
12793
12794 ++p;
12795
12796 if (name_expr == NULL)
12797 {
12798 error_at(val->location(), "mixture of field and value initializers");
12799 return Expression::make_error(location);
12800 }
12801
12802 bool bad_key = false;
12803 std::string name;
12804 const Named_object* no = NULL;
12805 switch (name_expr->classification())
12806 {
12807 case EXPRESSION_UNKNOWN_REFERENCE:
12808 name = name_expr->unknown_expression()->name();
12809 if (type->named_type() != NULL)
12810 {
12811 // If the named object found for this field name comes from a
12812 // different package than the struct it is a part of, do not count
12813 // this incorrect lookup as a usage of the object's package.
12814 no = name_expr->unknown_expression()->named_object();
12815 if (no->package() != NULL
12816 && no->package() != type->named_type()->named_object()->package())
12817 no->package()->forget_usage(name_expr);
12818 }
12819 break;
12820
12821 case EXPRESSION_CONST_REFERENCE:
12822 no = static_cast<Const_expression*>(name_expr)->named_object();
12823 break;
12824
12825 case EXPRESSION_TYPE:
12826 {
12827 Type* t = name_expr->type();
12828 Named_type* nt = t->named_type();
12829 if (nt == NULL)
12830 bad_key = true;
12831 else
12832 no = nt->named_object();
12833 }
12834 break;
12835
12836 case EXPRESSION_VAR_REFERENCE:
12837 no = name_expr->var_expression()->named_object();
12838 break;
12839
12840 case EXPRESSION_FUNC_REFERENCE:
12841 no = name_expr->func_expression()->named_object();
12842 break;
12843
12844 case EXPRESSION_UNARY:
12845 // If there is a local variable around with the same name as
12846 // the field, and this occurs in the closure, then the
12847 // parser may turn the field reference into an indirection
12848 // through the closure. FIXME: This is a mess.
12849 {
12850 bad_key = true;
12851 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12852 if (ue->op() == OPERATOR_MULT)
12853 {
12854 Field_reference_expression* fre =
12855 ue->operand()->field_reference_expression();
12856 if (fre != NULL)
12857 {
12858 Struct_type* st =
12859 fre->expr()->type()->deref()->struct_type();
12860 if (st != NULL)
12861 {
12862 const Struct_field* sf = st->field(fre->field_index());
12863 name = sf->field_name();
12864
12865 // See below. FIXME.
12866 if (!Gogo::is_hidden_name(name)
12867 && name[0] >= 'a'
12868 && name[0] <= 'z')
12869 {
12870 if (gogo->lookup_global(name.c_str()) != NULL)
12871 name = gogo->pack_hidden_name(name, false);
12872 }
12873
12874 char buf[20];
12875 snprintf(buf, sizeof buf, "%u", fre->field_index());
12876 size_t buflen = strlen(buf);
12877 if (name.compare(name.length() - buflen, buflen, buf)
12878 == 0)
12879 {
12880 name = name.substr(0, name.length() - buflen);
12881 bad_key = false;
12882 }
12883 }
12884 }
12885 }
12886 }
12887 break;
12888
12889 default:
12890 bad_key = true;
12891 break;
12892 }
12893 if (bad_key)
12894 {
12895 error_at(name_expr->location(), "expected struct field name");
12896 return Expression::make_error(location);
12897 }
12898
12899 if (no != NULL)
12900 {
12901 if (no->package() != NULL && external_expr == NULL)
12902 {
12903 external_expr = name_expr;
12904 external_no = no;
12905 }
12906
12907 name = no->name();
12908
12909 // A predefined name won't be packed. If it starts with a
12910 // lower case letter we need to check for that case, because
12911 // the field name will be packed. FIXME.
12912 if (!Gogo::is_hidden_name(name)
12913 && name[0] >= 'a'
12914 && name[0] <= 'z')
12915 {
12916 Named_object* gno = gogo->lookup_global(name.c_str());
12917 if (gno == no)
12918 name = gogo->pack_hidden_name(name, false);
12919 }
12920 }
12921
12922 unsigned int index;
12923 const Struct_field* sf = st->find_local_field(name, &index);
12924 if (sf == NULL)
12925 {
12926 error_at(name_expr->location(), "unknown field %qs in %qs",
12927 Gogo::message_name(name).c_str(),
12928 (type->named_type() != NULL
12929 ? type->named_type()->message_name().c_str()
12930 : "unnamed struct"));
12931 return Expression::make_error(location);
12932 }
12933 if (vals[index] != NULL)
12934 {
12935 error_at(name_expr->location(),
12936 "duplicate value for field %qs in %qs",
12937 Gogo::message_name(name).c_str(),
12938 (type->named_type() != NULL
12939 ? type->named_type()->message_name().c_str()
12940 : "unnamed struct"));
12941 return Expression::make_error(location);
12942 }
12943
12944 if (type->named_type() != NULL
12945 && type->named_type()->named_object()->package() != NULL
12946 && (Gogo::is_hidden_name(sf->field_name())
12947 || sf->is_embedded_builtin(gogo)))
12948 error_at(name_expr->location(),
12949 "assignment of unexported field %qs in %qs literal",
12950 Gogo::message_name(sf->field_name()).c_str(),
12951 type->named_type()->message_name().c_str());
12952
12953 vals[index] = val;
12954 traverse_order->push_back(index);
12955 }
12956
12957 if (!this->all_are_names_)
12958 {
12959 // This is a weird case like bug462 in the testsuite.
12960 if (external_expr == NULL)
12961 error_at(this->location(), "unknown field in %qs literal",
12962 (type->named_type() != NULL
12963 ? type->named_type()->message_name().c_str()
12964 : "unnamed struct"));
12965 else
12966 error_at(external_expr->location(), "unknown field %qs in %qs",
12967 external_no->message_name().c_str(),
12968 (type->named_type() != NULL
12969 ? type->named_type()->message_name().c_str()
12970 : "unnamed struct"));
12971 return Expression::make_error(location);
12972 }
12973
12974 Expression_list* list = new Expression_list;
12975 list->reserve(field_count);
12976 for (size_t i = 0; i < field_count; ++i)
12977 list->push_back(vals[i]);
12978
12979 Struct_construction_expression* ret =
12980 new Struct_construction_expression(type, list, location);
12981 ret->set_traverse_order(traverse_order);
12982 return ret;
12983 }
12984
12985 // Used to sort an index/value array.
12986
12987 class Index_value_compare
12988 {
12989 public:
12990 bool
operator ()(const std::pair<unsigned long,Expression * > & a,const std::pair<unsigned long,Expression * > & b)12991 operator()(const std::pair<unsigned long, Expression*>& a,
12992 const std::pair<unsigned long, Expression*>& b)
12993 { return a.first < b.first; }
12994 };
12995
12996 // Lower an array composite literal.
12997
12998 Expression*
lower_array(Type * type)12999 Composite_literal_expression::lower_array(Type* type)
13000 {
13001 Location location = this->location();
13002 if (this->vals_ == NULL || !this->has_keys_)
13003 return this->make_array(type, NULL, this->vals_);
13004
13005 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13006 indexes->reserve(this->vals_->size());
13007 bool indexes_out_of_order = false;
13008 Expression_list* vals = new Expression_list();
13009 vals->reserve(this->vals_->size());
13010 unsigned long index = 0;
13011 Expression_list::const_iterator p = this->vals_->begin();
13012 while (p != this->vals_->end())
13013 {
13014 Expression* index_expr = *p;
13015
13016 ++p;
13017 go_assert(p != this->vals_->end());
13018 Expression* val = *p;
13019
13020 ++p;
13021
13022 if (index_expr == NULL)
13023 {
13024 if (!indexes->empty())
13025 indexes->push_back(index);
13026 }
13027 else
13028 {
13029 if (indexes->empty() && !vals->empty())
13030 {
13031 for (size_t i = 0; i < vals->size(); ++i)
13032 indexes->push_back(i);
13033 }
13034
13035 Numeric_constant nc;
13036 if (!index_expr->numeric_constant_value(&nc))
13037 {
13038 error_at(index_expr->location(),
13039 "index expression is not integer constant");
13040 return Expression::make_error(location);
13041 }
13042
13043 switch (nc.to_unsigned_long(&index))
13044 {
13045 case Numeric_constant::NC_UL_VALID:
13046 break;
13047 case Numeric_constant::NC_UL_NOTINT:
13048 error_at(index_expr->location(),
13049 "index expression is not integer constant");
13050 return Expression::make_error(location);
13051 case Numeric_constant::NC_UL_NEGATIVE:
13052 error_at(index_expr->location(), "index expression is negative");
13053 return Expression::make_error(location);
13054 case Numeric_constant::NC_UL_BIG:
13055 error_at(index_expr->location(), "index value overflow");
13056 return Expression::make_error(location);
13057 default:
13058 go_unreachable();
13059 }
13060
13061 Named_type* ntype = Type::lookup_integer_type("int");
13062 Integer_type* inttype = ntype->integer_type();
13063 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13064 && index >> (inttype->bits() - 1) != 0)
13065 {
13066 error_at(index_expr->location(), "index value overflow");
13067 return Expression::make_error(location);
13068 }
13069
13070 if (std::find(indexes->begin(), indexes->end(), index)
13071 != indexes->end())
13072 {
13073 error_at(index_expr->location(), "duplicate value for index %lu",
13074 index);
13075 return Expression::make_error(location);
13076 }
13077
13078 if (!indexes->empty() && index < indexes->back())
13079 indexes_out_of_order = true;
13080
13081 indexes->push_back(index);
13082 }
13083
13084 vals->push_back(val);
13085
13086 ++index;
13087 }
13088
13089 if (indexes->empty())
13090 {
13091 delete indexes;
13092 indexes = NULL;
13093 }
13094
13095 if (indexes_out_of_order)
13096 {
13097 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13098
13099 V v;
13100 v.reserve(indexes->size());
13101 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13102 for (Expression_list::const_iterator pe = vals->begin();
13103 pe != vals->end();
13104 ++pe, ++pi)
13105 v.push_back(std::make_pair(*pi, *pe));
13106
13107 std::sort(v.begin(), v.end(), Index_value_compare());
13108
13109 delete indexes;
13110 delete vals;
13111 indexes = new std::vector<unsigned long>();
13112 indexes->reserve(v.size());
13113 vals = new Expression_list();
13114 vals->reserve(v.size());
13115
13116 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13117 {
13118 indexes->push_back(p->first);
13119 vals->push_back(p->second);
13120 }
13121 }
13122
13123 return this->make_array(type, indexes, vals);
13124 }
13125
13126 // Actually build the array composite literal. This handles
13127 // [...]{...}.
13128
13129 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)13130 Composite_literal_expression::make_array(
13131 Type* type,
13132 const std::vector<unsigned long>* indexes,
13133 Expression_list* vals)
13134 {
13135 Location location = this->location();
13136 Array_type* at = type->array_type();
13137
13138 if (at->length() != NULL && at->length()->is_nil_expression())
13139 {
13140 size_t size;
13141 if (vals == NULL)
13142 size = 0;
13143 else if (indexes != NULL)
13144 size = indexes->back() + 1;
13145 else
13146 {
13147 size = vals->size();
13148 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13149 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13150 && size >> (it->bits() - 1) != 0)
13151 {
13152 error_at(location, "too many elements in composite literal");
13153 return Expression::make_error(location);
13154 }
13155 }
13156
13157 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13158 at = Type::make_array_type(at->element_type(), elen);
13159 type = at;
13160 }
13161 else if (at->length() != NULL
13162 && !at->length()->is_error_expression()
13163 && this->vals_ != NULL)
13164 {
13165 Numeric_constant nc;
13166 unsigned long val;
13167 if (at->length()->numeric_constant_value(&nc)
13168 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13169 {
13170 if (indexes == NULL)
13171 {
13172 if (this->vals_->size() > val)
13173 {
13174 error_at(location, "too many elements in composite literal");
13175 return Expression::make_error(location);
13176 }
13177 }
13178 else
13179 {
13180 unsigned long max = indexes->back();
13181 if (max >= val)
13182 {
13183 error_at(location,
13184 ("some element keys in composite literal "
13185 "are out of range"));
13186 return Expression::make_error(location);
13187 }
13188 }
13189 }
13190 }
13191
13192 if (at->length() != NULL)
13193 return new Fixed_array_construction_expression(type, indexes, vals,
13194 location);
13195 else
13196 return new Slice_construction_expression(type, indexes, vals, location);
13197 }
13198
13199 // Lower a map composite literal.
13200
13201 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)13202 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13203 Statement_inserter* inserter,
13204 Type* type)
13205 {
13206 Location location = this->location();
13207 if (this->vals_ != NULL)
13208 {
13209 if (!this->has_keys_)
13210 {
13211 error_at(location, "map composite literal must have keys");
13212 return Expression::make_error(location);
13213 }
13214
13215 for (Expression_list::iterator p = this->vals_->begin();
13216 p != this->vals_->end();
13217 p += 2)
13218 {
13219 if (*p == NULL)
13220 {
13221 ++p;
13222 error_at((*p)->location(),
13223 "map composite literal must have keys for every value");
13224 return Expression::make_error(location);
13225 }
13226 // Make sure we have lowered the key; it may not have been
13227 // lowered in order to handle keys for struct composite
13228 // literals. Lower it now to get the right error message.
13229 if ((*p)->unknown_expression() != NULL)
13230 {
13231 (*p)->unknown_expression()->clear_is_composite_literal_key();
13232 gogo->lower_expression(function, inserter, &*p);
13233 go_assert((*p)->is_error_expression());
13234 return Expression::make_error(location);
13235 }
13236 }
13237 }
13238
13239 return new Map_construction_expression(type, this->vals_, location);
13240 }
13241
13242 // Dump ast representation for a composite literal expression.
13243
13244 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13245 Composite_literal_expression::do_dump_expression(
13246 Ast_dump_context* ast_dump_context) const
13247 {
13248 ast_dump_context->ostream() << "composite(";
13249 ast_dump_context->dump_type(this->type_);
13250 ast_dump_context->ostream() << ", {";
13251 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13252 ast_dump_context->ostream() << "})";
13253 }
13254
13255 // Make a composite literal expression.
13256
13257 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)13258 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13259 Expression_list* vals, bool all_are_names,
13260 Location location)
13261 {
13262 return new Composite_literal_expression(type, depth, has_keys, vals,
13263 all_are_names, location);
13264 }
13265
13266 // Return whether this expression is a composite literal.
13267
13268 bool
is_composite_literal() const13269 Expression::is_composite_literal() const
13270 {
13271 switch (this->classification_)
13272 {
13273 case EXPRESSION_COMPOSITE_LITERAL:
13274 case EXPRESSION_STRUCT_CONSTRUCTION:
13275 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13276 case EXPRESSION_SLICE_CONSTRUCTION:
13277 case EXPRESSION_MAP_CONSTRUCTION:
13278 return true;
13279 default:
13280 return false;
13281 }
13282 }
13283
13284 // Return whether this expression is a composite literal which is not
13285 // constant.
13286
13287 bool
is_nonconstant_composite_literal() const13288 Expression::is_nonconstant_composite_literal() const
13289 {
13290 switch (this->classification_)
13291 {
13292 case EXPRESSION_STRUCT_CONSTRUCTION:
13293 {
13294 const Struct_construction_expression *psce =
13295 static_cast<const Struct_construction_expression*>(this);
13296 return !psce->is_constant_struct();
13297 }
13298 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13299 {
13300 const Fixed_array_construction_expression *pace =
13301 static_cast<const Fixed_array_construction_expression*>(this);
13302 return !pace->is_constant_array();
13303 }
13304 case EXPRESSION_SLICE_CONSTRUCTION:
13305 {
13306 const Slice_construction_expression *pace =
13307 static_cast<const Slice_construction_expression*>(this);
13308 return !pace->is_constant_array();
13309 }
13310 case EXPRESSION_MAP_CONSTRUCTION:
13311 return true;
13312 default:
13313 return false;
13314 }
13315 }
13316
13317 // Return true if this is a variable or temporary_variable.
13318
13319 bool
is_variable() const13320 Expression::is_variable() const
13321 {
13322 switch (this->classification_)
13323 {
13324 case EXPRESSION_VAR_REFERENCE:
13325 case EXPRESSION_TEMPORARY_REFERENCE:
13326 case EXPRESSION_SET_AND_USE_TEMPORARY:
13327 return true;
13328 default:
13329 return false;
13330 }
13331 }
13332
13333 // Return true if this is a reference to a local variable.
13334
13335 bool
is_local_variable() const13336 Expression::is_local_variable() const
13337 {
13338 const Var_expression* ve = this->var_expression();
13339 if (ve == NULL)
13340 return false;
13341 const Named_object* no = ve->named_object();
13342 return (no->is_result_variable()
13343 || (no->is_variable() && !no->var_value()->is_global()));
13344 }
13345
13346 // Class Type_guard_expression.
13347
13348 // Traversal.
13349
13350 int
do_traverse(Traverse * traverse)13351 Type_guard_expression::do_traverse(Traverse* traverse)
13352 {
13353 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13354 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13355 return TRAVERSE_EXIT;
13356 return TRAVERSE_CONTINUE;
13357 }
13358
13359 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13360 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13361 Statement_inserter* inserter)
13362 {
13363 if (this->expr_->is_error_expression()
13364 || this->expr_->type()->is_error_type())
13365 {
13366 go_assert(saw_errors());
13367 return Expression::make_error(this->location());
13368 }
13369
13370 if (!this->expr_->is_variable())
13371 {
13372 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13373 this->location());
13374 inserter->insert(temp);
13375 this->expr_ =
13376 Expression::make_temporary_reference(temp, this->location());
13377 }
13378 return this;
13379 }
13380
13381 // Check types of a type guard expression. The expression must have
13382 // an interface type, but the actual type conversion is checked at run
13383 // time.
13384
13385 void
do_check_types(Gogo *)13386 Type_guard_expression::do_check_types(Gogo*)
13387 {
13388 Type* expr_type = this->expr_->type();
13389 if (expr_type->interface_type() == NULL)
13390 {
13391 if (!expr_type->is_error() && !this->type_->is_error())
13392 this->report_error(_("type assertion only valid for interface types"));
13393 this->set_is_error();
13394 }
13395 else if (this->type_->interface_type() == NULL)
13396 {
13397 std::string reason;
13398 if (!expr_type->interface_type()->implements_interface(this->type_,
13399 &reason))
13400 {
13401 if (!this->type_->is_error())
13402 {
13403 if (reason.empty())
13404 this->report_error(_("impossible type assertion: "
13405 "type does not implement interface"));
13406 else
13407 error_at(this->location(),
13408 ("impossible type assertion: "
13409 "type does not implement interface (%s)"),
13410 reason.c_str());
13411 }
13412 this->set_is_error();
13413 }
13414 }
13415 }
13416
13417 // Return the backend representation for a type guard expression.
13418
13419 Bexpression*
do_get_backend(Translate_context * context)13420 Type_guard_expression::do_get_backend(Translate_context* context)
13421 {
13422 Expression* conversion;
13423 if (this->type_->interface_type() != NULL)
13424 conversion =
13425 Expression::convert_interface_to_interface(this->type_, this->expr_,
13426 true, this->location());
13427 else
13428 conversion =
13429 Expression::convert_for_assignment(context->gogo(), this->type_,
13430 this->expr_, this->location());
13431
13432 return conversion->get_backend(context);
13433 }
13434
13435 // Dump ast representation for a type guard expression.
13436
13437 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13438 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13439 const
13440 {
13441 this->expr_->dump_expression(ast_dump_context);
13442 ast_dump_context->ostream() << ".";
13443 ast_dump_context->dump_type(this->type_);
13444 }
13445
13446 // Make a type guard expression.
13447
13448 Expression*
make_type_guard(Expression * expr,Type * type,Location location)13449 Expression::make_type_guard(Expression* expr, Type* type,
13450 Location location)
13451 {
13452 return new Type_guard_expression(expr, type, location);
13453 }
13454
13455 // Class Heap_expression.
13456
13457 // Return the type of the expression stored on the heap.
13458
13459 Type*
do_type()13460 Heap_expression::do_type()
13461 { return Type::make_pointer_type(this->expr_->type()); }
13462
13463 // Return the backend representation for allocating an expression on the heap.
13464
13465 Bexpression*
do_get_backend(Translate_context * context)13466 Heap_expression::do_get_backend(Translate_context* context)
13467 {
13468 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13469 return context->backend()->error_expression();
13470
13471 Location loc = this->location();
13472 Gogo* gogo = context->gogo();
13473 Btype* btype = this->type()->get_backend(gogo);
13474 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13475 loc)->get_backend(context);
13476
13477 Bstatement* decl;
13478 Named_object* fn = context->function();
13479 go_assert(fn != NULL);
13480 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13481 Bvariable* space_temp =
13482 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13483 space, true, loc, &decl);
13484 space = gogo->backend()->var_expression(space_temp, loc);
13485 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13486 Bexpression* ref =
13487 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13488
13489 Bexpression* bexpr = this->expr_->get_backend(context);
13490 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13491 decl = gogo->backend()->compound_statement(decl, assn);
13492 space = gogo->backend()->var_expression(space_temp, loc);
13493 return gogo->backend()->compound_expression(decl, space, loc);
13494 }
13495
13496 // Dump ast representation for a heap expression.
13497
13498 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13499 Heap_expression::do_dump_expression(
13500 Ast_dump_context* ast_dump_context) const
13501 {
13502 ast_dump_context->ostream() << "&(";
13503 ast_dump_context->dump_expression(this->expr_);
13504 ast_dump_context->ostream() << ")";
13505 }
13506
13507 // Allocate an expression on the heap.
13508
13509 Expression*
make_heap_expression(Expression * expr,Location location)13510 Expression::make_heap_expression(Expression* expr, Location location)
13511 {
13512 return new Heap_expression(expr, location);
13513 }
13514
13515 // Class Receive_expression.
13516
13517 // Return the type of a receive expression.
13518
13519 Type*
do_type()13520 Receive_expression::do_type()
13521 {
13522 if (this->is_error_expression())
13523 return Type::make_error_type();
13524 Channel_type* channel_type = this->channel_->type()->channel_type();
13525 if (channel_type == NULL)
13526 {
13527 this->report_error(_("expected channel"));
13528 return Type::make_error_type();
13529 }
13530 return channel_type->element_type();
13531 }
13532
13533 // Check types for a receive expression.
13534
13535 void
do_check_types(Gogo *)13536 Receive_expression::do_check_types(Gogo*)
13537 {
13538 Type* type = this->channel_->type();
13539 if (type->is_error())
13540 {
13541 go_assert(saw_errors());
13542 this->set_is_error();
13543 return;
13544 }
13545 if (type->channel_type() == NULL)
13546 {
13547 this->report_error(_("expected channel"));
13548 return;
13549 }
13550 if (!type->channel_type()->may_receive())
13551 {
13552 this->report_error(_("invalid receive on send-only channel"));
13553 return;
13554 }
13555 }
13556
13557 // Flattening for receive expressions creates a temporary variable to store
13558 // received data in for receives.
13559
13560 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13561 Receive_expression::do_flatten(Gogo*, Named_object*,
13562 Statement_inserter* inserter)
13563 {
13564 Channel_type* channel_type = this->channel_->type()->channel_type();
13565 if (channel_type == NULL)
13566 {
13567 go_assert(saw_errors());
13568 return this;
13569 }
13570 else if (this->channel_->is_error_expression())
13571 {
13572 go_assert(saw_errors());
13573 return Expression::make_error(this->location());
13574 }
13575
13576 Type* element_type = channel_type->element_type();
13577 if (this->temp_receiver_ == NULL)
13578 {
13579 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13580 this->location());
13581 this->temp_receiver_->set_is_address_taken();
13582 inserter->insert(this->temp_receiver_);
13583 }
13584
13585 return this;
13586 }
13587
13588 // Get the backend representation for a receive expression.
13589
13590 Bexpression*
do_get_backend(Translate_context * context)13591 Receive_expression::do_get_backend(Translate_context* context)
13592 {
13593 Location loc = this->location();
13594
13595 Channel_type* channel_type = this->channel_->type()->channel_type();
13596 if (channel_type == NULL)
13597 {
13598 go_assert(this->channel_->type()->is_error());
13599 return context->backend()->error_expression();
13600 }
13601 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13602
13603 Expression* recv_ref =
13604 Expression::make_temporary_reference(this->temp_receiver_, loc);
13605 Expression* recv_addr =
13606 Expression::make_temporary_reference(this->temp_receiver_, loc);
13607 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13608 Expression* recv =
13609 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13610 td, this->channel_, recv_addr);
13611 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13612 }
13613
13614 // Dump ast representation for a receive expression.
13615
13616 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13617 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13618 {
13619 ast_dump_context->ostream() << " <- " ;
13620 ast_dump_context->dump_expression(channel_);
13621 }
13622
13623 // Make a receive expression.
13624
13625 Receive_expression*
make_receive(Expression * channel,Location location)13626 Expression::make_receive(Expression* channel, Location location)
13627 {
13628 return new Receive_expression(channel, location);
13629 }
13630
13631 // An expression which evaluates to a pointer to the type descriptor
13632 // of a type.
13633
13634 class Type_descriptor_expression : public Expression
13635 {
13636 public:
Type_descriptor_expression(Type * type,Location location)13637 Type_descriptor_expression(Type* type, Location location)
13638 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13639 type_(type)
13640 { }
13641
13642 protected:
13643 int
13644 do_traverse(Traverse*);
13645
13646 Type*
do_type()13647 do_type()
13648 { return Type::make_type_descriptor_ptr_type(); }
13649
13650 bool
do_is_immutable() const13651 do_is_immutable() const
13652 { return true; }
13653
13654 void
do_determine_type(const Type_context *)13655 do_determine_type(const Type_context*)
13656 { }
13657
13658 Expression*
do_copy()13659 do_copy()
13660 { return this; }
13661
13662 Bexpression*
do_get_backend(Translate_context * context)13663 do_get_backend(Translate_context* context)
13664 {
13665 return this->type_->type_descriptor_pointer(context->gogo(),
13666 this->location());
13667 }
13668
13669 void
13670 do_dump_expression(Ast_dump_context*) const;
13671
13672 private:
13673 // The type for which this is the descriptor.
13674 Type* type_;
13675 };
13676
13677 int
do_traverse(Traverse * traverse)13678 Type_descriptor_expression::do_traverse(Traverse* traverse)
13679 {
13680 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13681 return TRAVERSE_EXIT;
13682 return TRAVERSE_CONTINUE;
13683 }
13684
13685 // Dump ast representation for a type descriptor expression.
13686
13687 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13688 Type_descriptor_expression::do_dump_expression(
13689 Ast_dump_context* ast_dump_context) const
13690 {
13691 ast_dump_context->dump_type(this->type_);
13692 }
13693
13694 // Make a type descriptor expression.
13695
13696 Expression*
make_type_descriptor(Type * type,Location location)13697 Expression::make_type_descriptor(Type* type, Location location)
13698 {
13699 return new Type_descriptor_expression(type, location);
13700 }
13701
13702 // An expression which evaluates to a pointer to the Garbage Collection symbol
13703 // of a type.
13704
13705 class GC_symbol_expression : public Expression
13706 {
13707 public:
GC_symbol_expression(Type * type)13708 GC_symbol_expression(Type* type)
13709 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
13710 type_(type)
13711 {}
13712
13713 protected:
13714 Type*
do_type()13715 do_type()
13716 { return Type::lookup_integer_type("uintptr"); }
13717
13718 bool
do_is_immutable() const13719 do_is_immutable() const
13720 { return true; }
13721
13722 void
do_determine_type(const Type_context *)13723 do_determine_type(const Type_context*)
13724 { }
13725
13726 Expression*
do_copy()13727 do_copy()
13728 { return this; }
13729
13730 Bexpression*
do_get_backend(Translate_context * context)13731 do_get_backend(Translate_context* context)
13732 { return this->type_->gc_symbol_pointer(context->gogo()); }
13733
13734 void
13735 do_dump_expression(Ast_dump_context*) const;
13736
13737 private:
13738 // The type which this gc symbol describes.
13739 Type* type_;
13740 };
13741
13742 // Dump ast representation for a gc symbol expression.
13743
13744 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13745 GC_symbol_expression::do_dump_expression(
13746 Ast_dump_context* ast_dump_context) const
13747 {
13748 ast_dump_context->ostream() << "gcdata(";
13749 ast_dump_context->dump_type(this->type_);
13750 ast_dump_context->ostream() << ")";
13751 }
13752
13753 // Make a gc symbol expression.
13754
13755 Expression*
make_gc_symbol(Type * type)13756 Expression::make_gc_symbol(Type* type)
13757 {
13758 return new GC_symbol_expression(type);
13759 }
13760
13761 // An expression which evaluates to some characteristic of a type.
13762 // This is only used to initialize fields of a type descriptor. Using
13763 // a new expression class is slightly inefficient but gives us a good
13764 // separation between the frontend and the middle-end with regard to
13765 // how types are laid out.
13766
13767 class Type_info_expression : public Expression
13768 {
13769 public:
Type_info_expression(Type * type,Type_info type_info)13770 Type_info_expression(Type* type, Type_info type_info)
13771 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13772 type_(type), type_info_(type_info)
13773 { }
13774
13775 protected:
13776 bool
do_is_immutable() const13777 do_is_immutable() const
13778 { return true; }
13779
13780 Type*
13781 do_type();
13782
13783 void
do_determine_type(const Type_context *)13784 do_determine_type(const Type_context*)
13785 { }
13786
13787 Expression*
do_copy()13788 do_copy()
13789 { return this; }
13790
13791 Bexpression*
13792 do_get_backend(Translate_context* context);
13793
13794 void
13795 do_dump_expression(Ast_dump_context*) const;
13796
13797 private:
13798 // The type for which we are getting information.
13799 Type* type_;
13800 // What information we want.
13801 Type_info type_info_;
13802 };
13803
13804 // The type is chosen to match what the type descriptor struct
13805 // expects.
13806
13807 Type*
do_type()13808 Type_info_expression::do_type()
13809 {
13810 switch (this->type_info_)
13811 {
13812 case TYPE_INFO_SIZE:
13813 return Type::lookup_integer_type("uintptr");
13814 case TYPE_INFO_ALIGNMENT:
13815 case TYPE_INFO_FIELD_ALIGNMENT:
13816 return Type::lookup_integer_type("uint8");
13817 default:
13818 go_unreachable();
13819 }
13820 }
13821
13822 // Return the backend representation for type information.
13823
13824 Bexpression*
do_get_backend(Translate_context * context)13825 Type_info_expression::do_get_backend(Translate_context* context)
13826 {
13827 Gogo* gogo = context->gogo();
13828 bool ok = true;
13829 int64_t val;
13830 switch (this->type_info_)
13831 {
13832 case TYPE_INFO_SIZE:
13833 ok = this->type_->backend_type_size(gogo, &val);
13834 break;
13835 case TYPE_INFO_ALIGNMENT:
13836 ok = this->type_->backend_type_align(gogo, &val);
13837 break;
13838 case TYPE_INFO_FIELD_ALIGNMENT:
13839 ok = this->type_->backend_type_field_align(gogo, &val);
13840 break;
13841 default:
13842 go_unreachable();
13843 }
13844 if (!ok)
13845 {
13846 go_assert(saw_errors());
13847 return gogo->backend()->error_expression();
13848 }
13849 Expression* e = Expression::make_integer_int64(val, this->type(),
13850 this->location());
13851 return e->get_backend(context);
13852 }
13853
13854 // Dump ast representation for a type info expression.
13855
13856 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13857 Type_info_expression::do_dump_expression(
13858 Ast_dump_context* ast_dump_context) const
13859 {
13860 ast_dump_context->ostream() << "typeinfo(";
13861 ast_dump_context->dump_type(this->type_);
13862 ast_dump_context->ostream() << ",";
13863 ast_dump_context->ostream() <<
13864 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13865 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13866 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13867 : "unknown");
13868 ast_dump_context->ostream() << ")";
13869 }
13870
13871 // Make a type info expression.
13872
13873 Expression*
make_type_info(Type * type,Type_info type_info)13874 Expression::make_type_info(Type* type, Type_info type_info)
13875 {
13876 return new Type_info_expression(type, type_info);
13877 }
13878
13879 // An expression that evaluates to some characteristic of a slice.
13880 // This is used when indexing, bound-checking, or nil checking a slice.
13881
13882 class Slice_info_expression : public Expression
13883 {
13884 public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)13885 Slice_info_expression(Expression* slice, Slice_info slice_info,
13886 Location location)
13887 : Expression(EXPRESSION_SLICE_INFO, location),
13888 slice_(slice), slice_info_(slice_info)
13889 { }
13890
13891 protected:
13892 Type*
13893 do_type();
13894
13895 void
do_determine_type(const Type_context *)13896 do_determine_type(const Type_context*)
13897 { }
13898
13899 Expression*
do_copy()13900 do_copy()
13901 {
13902 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
13903 this->location());
13904 }
13905
13906 Bexpression*
13907 do_get_backend(Translate_context* context);
13908
13909 void
13910 do_dump_expression(Ast_dump_context*) const;
13911
13912 void
do_issue_nil_check()13913 do_issue_nil_check()
13914 { this->slice_->issue_nil_check(); }
13915
13916 private:
13917 // The slice for which we are getting information.
13918 Expression* slice_;
13919 // What information we want.
13920 Slice_info slice_info_;
13921 };
13922
13923 // Return the type of the slice info.
13924
13925 Type*
do_type()13926 Slice_info_expression::do_type()
13927 {
13928 switch (this->slice_info_)
13929 {
13930 case SLICE_INFO_VALUE_POINTER:
13931 return Type::make_pointer_type(
13932 this->slice_->type()->array_type()->element_type());
13933 case SLICE_INFO_LENGTH:
13934 case SLICE_INFO_CAPACITY:
13935 return Type::lookup_integer_type("int");
13936 default:
13937 go_unreachable();
13938 }
13939 }
13940
13941 // Return the backend information for slice information.
13942
13943 Bexpression*
do_get_backend(Translate_context * context)13944 Slice_info_expression::do_get_backend(Translate_context* context)
13945 {
13946 Gogo* gogo = context->gogo();
13947 Bexpression* bslice = this->slice_->get_backend(context);
13948 switch (this->slice_info_)
13949 {
13950 case SLICE_INFO_VALUE_POINTER:
13951 case SLICE_INFO_LENGTH:
13952 case SLICE_INFO_CAPACITY:
13953 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
13954 this->location());
13955 break;
13956 default:
13957 go_unreachable();
13958 }
13959 }
13960
13961 // Dump ast representation for a type info expression.
13962
13963 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13964 Slice_info_expression::do_dump_expression(
13965 Ast_dump_context* ast_dump_context) const
13966 {
13967 ast_dump_context->ostream() << "sliceinfo(";
13968 this->slice_->dump_expression(ast_dump_context);
13969 ast_dump_context->ostream() << ",";
13970 ast_dump_context->ostream() <<
13971 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
13972 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
13973 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
13974 : "unknown");
13975 ast_dump_context->ostream() << ")";
13976 }
13977
13978 // Make a slice info expression.
13979
13980 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)13981 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
13982 Location location)
13983 {
13984 return new Slice_info_expression(slice, slice_info, location);
13985 }
13986
13987 // An expression that represents a slice value: a struct with value pointer,
13988 // length, and capacity fields.
13989
13990 class Slice_value_expression : public Expression
13991 {
13992 public:
Slice_value_expression(Type * type,Expression * valptr,Expression * len,Expression * cap,Location location)13993 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
13994 Expression* cap, Location location)
13995 : Expression(EXPRESSION_SLICE_VALUE, location),
13996 type_(type), valptr_(valptr), len_(len), cap_(cap)
13997 { }
13998
13999 protected:
14000 int
14001 do_traverse(Traverse*);
14002
14003 Type*
do_type()14004 do_type()
14005 { return this->type_; }
14006
14007 void
do_determine_type(const Type_context *)14008 do_determine_type(const Type_context*)
14009 { go_unreachable(); }
14010
14011 Expression*
do_copy()14012 do_copy()
14013 {
14014 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14015 this->len_->copy(), this->cap_->copy(),
14016 this->location());
14017 }
14018
14019 Bexpression*
14020 do_get_backend(Translate_context* context);
14021
14022 void
14023 do_dump_expression(Ast_dump_context*) const;
14024
14025 private:
14026 // The type of the slice value.
14027 Type* type_;
14028 // The pointer to the values in the slice.
14029 Expression* valptr_;
14030 // The length of the slice.
14031 Expression* len_;
14032 // The capacity of the slice.
14033 Expression* cap_;
14034 };
14035
14036 int
do_traverse(Traverse * traverse)14037 Slice_value_expression::do_traverse(Traverse* traverse)
14038 {
14039 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14040 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14041 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14042 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14043 return TRAVERSE_EXIT;
14044 return TRAVERSE_CONTINUE;
14045 }
14046
14047 Bexpression*
do_get_backend(Translate_context * context)14048 Slice_value_expression::do_get_backend(Translate_context* context)
14049 {
14050 std::vector<Bexpression*> vals(3);
14051 vals[0] = this->valptr_->get_backend(context);
14052 vals[1] = this->len_->get_backend(context);
14053 vals[2] = this->cap_->get_backend(context);
14054
14055 Gogo* gogo = context->gogo();
14056 Btype* btype = this->type_->get_backend(gogo);
14057 return gogo->backend()->constructor_expression(btype, vals, this->location());
14058 }
14059
14060 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14061 Slice_value_expression::do_dump_expression(
14062 Ast_dump_context* ast_dump_context) const
14063 {
14064 ast_dump_context->ostream() << "slicevalue(";
14065 ast_dump_context->ostream() << "values: ";
14066 this->valptr_->dump_expression(ast_dump_context);
14067 ast_dump_context->ostream() << ", length: ";
14068 this->len_->dump_expression(ast_dump_context);
14069 ast_dump_context->ostream() << ", capacity: ";
14070 this->cap_->dump_expression(ast_dump_context);
14071 ast_dump_context->ostream() << ")";
14072 }
14073
14074 Expression*
make_slice_value(Type * at,Expression * valptr,Expression * len,Expression * cap,Location location)14075 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14076 Expression* cap, Location location)
14077 {
14078 go_assert(at->is_slice_type());
14079 return new Slice_value_expression(at, valptr, len, cap, location);
14080 }
14081
14082 // An expression that evaluates to some characteristic of a non-empty interface.
14083 // This is used to access the method table or underlying object of an interface.
14084
14085 class Interface_info_expression : public Expression
14086 {
14087 public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)14088 Interface_info_expression(Expression* iface, Interface_info iface_info,
14089 Location location)
14090 : Expression(EXPRESSION_INTERFACE_INFO, location),
14091 iface_(iface), iface_info_(iface_info)
14092 { }
14093
14094 protected:
14095 Type*
14096 do_type();
14097
14098 void
do_determine_type(const Type_context *)14099 do_determine_type(const Type_context*)
14100 { }
14101
14102 Expression*
do_copy()14103 do_copy()
14104 {
14105 return new Interface_info_expression(this->iface_->copy(),
14106 this->iface_info_, this->location());
14107 }
14108
14109 Bexpression*
14110 do_get_backend(Translate_context* context);
14111
14112 void
14113 do_dump_expression(Ast_dump_context*) const;
14114
14115 void
do_issue_nil_check()14116 do_issue_nil_check()
14117 { this->iface_->issue_nil_check(); }
14118
14119 private:
14120 // The interface for which we are getting information.
14121 Expression* iface_;
14122 // What information we want.
14123 Interface_info iface_info_;
14124 };
14125
14126 // Return the type of the interface info.
14127
14128 Type*
do_type()14129 Interface_info_expression::do_type()
14130 {
14131 switch (this->iface_info_)
14132 {
14133 case INTERFACE_INFO_METHODS:
14134 {
14135 Type* pdt = Type::make_type_descriptor_ptr_type();
14136 if (this->iface_->type()->interface_type()->is_empty())
14137 return pdt;
14138
14139 Location loc = this->location();
14140 Struct_field_list* sfl = new Struct_field_list();
14141 sfl->push_back(
14142 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14143
14144 Interface_type* itype = this->iface_->type()->interface_type();
14145 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14146 p != itype->methods()->end();
14147 ++p)
14148 {
14149 Function_type* ft = p->type()->function_type();
14150 go_assert(ft->receiver() == NULL);
14151
14152 const Typed_identifier_list* params = ft->parameters();
14153 Typed_identifier_list* mparams = new Typed_identifier_list();
14154 if (params != NULL)
14155 mparams->reserve(params->size() + 1);
14156 Type* vt = Type::make_pointer_type(Type::make_void_type());
14157 mparams->push_back(Typed_identifier("", vt, ft->location()));
14158 if (params != NULL)
14159 {
14160 for (Typed_identifier_list::const_iterator pp = params->begin();
14161 pp != params->end();
14162 ++pp)
14163 mparams->push_back(*pp);
14164 }
14165
14166 Typed_identifier_list* mresults = (ft->results() == NULL
14167 ? NULL
14168 : ft->results()->copy());
14169 Backend_function_type* mft =
14170 Type::make_backend_function_type(NULL, mparams, mresults,
14171 ft->location());
14172
14173 std::string fname = Gogo::unpack_hidden_name(p->name());
14174 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14175 }
14176
14177 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14178 }
14179 case INTERFACE_INFO_OBJECT:
14180 return Type::make_pointer_type(Type::make_void_type());
14181 default:
14182 go_unreachable();
14183 }
14184 }
14185
14186 // Return the backend representation for interface information.
14187
14188 Bexpression*
do_get_backend(Translate_context * context)14189 Interface_info_expression::do_get_backend(Translate_context* context)
14190 {
14191 Gogo* gogo = context->gogo();
14192 Bexpression* biface = this->iface_->get_backend(context);
14193 switch (this->iface_info_)
14194 {
14195 case INTERFACE_INFO_METHODS:
14196 case INTERFACE_INFO_OBJECT:
14197 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14198 this->location());
14199 break;
14200 default:
14201 go_unreachable();
14202 }
14203 }
14204
14205 // Dump ast representation for an interface info expression.
14206
14207 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14208 Interface_info_expression::do_dump_expression(
14209 Ast_dump_context* ast_dump_context) const
14210 {
14211 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14212 ast_dump_context->ostream() << "interfaceinfo(";
14213 this->iface_->dump_expression(ast_dump_context);
14214 ast_dump_context->ostream() << ",";
14215 ast_dump_context->ostream() <<
14216 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14217 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14218 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14219 : "unknown");
14220 ast_dump_context->ostream() << ")";
14221 }
14222
14223 // Make an interface info expression.
14224
14225 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)14226 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14227 Location location)
14228 {
14229 return new Interface_info_expression(iface, iface_info, location);
14230 }
14231
14232 // An expression that represents an interface value. The first field is either
14233 // a type descriptor for an empty interface or a pointer to the interface method
14234 // table for a non-empty interface. The second field is always the object.
14235
14236 class Interface_value_expression : public Expression
14237 {
14238 public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)14239 Interface_value_expression(Type* type, Expression* first_field,
14240 Expression* obj, Location location)
14241 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14242 type_(type), first_field_(first_field), obj_(obj)
14243 { }
14244
14245 protected:
14246 int
14247 do_traverse(Traverse*);
14248
14249 Type*
do_type()14250 do_type()
14251 { return this->type_; }
14252
14253 void
do_determine_type(const Type_context *)14254 do_determine_type(const Type_context*)
14255 { go_unreachable(); }
14256
14257 Expression*
do_copy()14258 do_copy()
14259 {
14260 return new Interface_value_expression(this->type_,
14261 this->first_field_->copy(),
14262 this->obj_->copy(), this->location());
14263 }
14264
14265 Bexpression*
14266 do_get_backend(Translate_context* context);
14267
14268 void
14269 do_dump_expression(Ast_dump_context*) const;
14270
14271 private:
14272 // The type of the interface value.
14273 Type* type_;
14274 // The first field of the interface (either a type descriptor or a pointer
14275 // to the method table.
14276 Expression* first_field_;
14277 // The underlying object of the interface.
14278 Expression* obj_;
14279 };
14280
14281 int
do_traverse(Traverse * traverse)14282 Interface_value_expression::do_traverse(Traverse* traverse)
14283 {
14284 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14285 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14286 return TRAVERSE_EXIT;
14287 return TRAVERSE_CONTINUE;
14288 }
14289
14290 Bexpression*
do_get_backend(Translate_context * context)14291 Interface_value_expression::do_get_backend(Translate_context* context)
14292 {
14293 std::vector<Bexpression*> vals(2);
14294 vals[0] = this->first_field_->get_backend(context);
14295 vals[1] = this->obj_->get_backend(context);
14296
14297 Gogo* gogo = context->gogo();
14298 Btype* btype = this->type_->get_backend(gogo);
14299 return gogo->backend()->constructor_expression(btype, vals, this->location());
14300 }
14301
14302 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14303 Interface_value_expression::do_dump_expression(
14304 Ast_dump_context* ast_dump_context) const
14305 {
14306 ast_dump_context->ostream() << "interfacevalue(";
14307 ast_dump_context->ostream() <<
14308 (this->type_->interface_type()->is_empty()
14309 ? "type_descriptor: "
14310 : "methods: ");
14311 this->first_field_->dump_expression(ast_dump_context);
14312 ast_dump_context->ostream() << ", object: ";
14313 this->obj_->dump_expression(ast_dump_context);
14314 ast_dump_context->ostream() << ")";
14315 }
14316
14317 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)14318 Expression::make_interface_value(Type* type, Expression* first_value,
14319 Expression* object, Location location)
14320 {
14321 return new Interface_value_expression(type, first_value, object, location);
14322 }
14323
14324 // An interface method table for a pair of types: an interface type and a type
14325 // that implements that interface.
14326
14327 class Interface_mtable_expression : public Expression
14328 {
14329 public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)14330 Interface_mtable_expression(Interface_type* itype, Type* type,
14331 bool is_pointer, Location location)
14332 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14333 itype_(itype), type_(type), is_pointer_(is_pointer),
14334 method_table_type_(NULL), bvar_(NULL)
14335 { }
14336
14337 protected:
14338 int
14339 do_traverse(Traverse*);
14340
14341 Type*
14342 do_type();
14343
14344 bool
is_immutable() const14345 is_immutable() const
14346 { return true; }
14347
14348 void
do_determine_type(const Type_context *)14349 do_determine_type(const Type_context*)
14350 { go_unreachable(); }
14351
14352 Expression*
do_copy()14353 do_copy()
14354 {
14355 return new Interface_mtable_expression(this->itype_, this->type_,
14356 this->is_pointer_, this->location());
14357 }
14358
14359 bool
do_is_addressable() const14360 do_is_addressable() const
14361 { return true; }
14362
14363 Bexpression*
14364 do_get_backend(Translate_context* context);
14365
14366 void
14367 do_dump_expression(Ast_dump_context*) const;
14368
14369 private:
14370 // The interface type for which the methods are defined.
14371 Interface_type* itype_;
14372 // The type to construct the interface method table for.
14373 Type* type_;
14374 // Whether this table contains the method set for the receiver type or the
14375 // pointer receiver type.
14376 bool is_pointer_;
14377 // The type of the method table.
14378 Type* method_table_type_;
14379 // The backend variable that refers to the interface method table.
14380 Bvariable* bvar_;
14381 };
14382
14383 int
do_traverse(Traverse * traverse)14384 Interface_mtable_expression::do_traverse(Traverse* traverse)
14385 {
14386 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14387 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14388 return TRAVERSE_EXIT;
14389 return TRAVERSE_CONTINUE;
14390 }
14391
14392 Type*
do_type()14393 Interface_mtable_expression::do_type()
14394 {
14395 if (this->method_table_type_ != NULL)
14396 return this->method_table_type_;
14397
14398 const Typed_identifier_list* interface_methods = this->itype_->methods();
14399 go_assert(!interface_methods->empty());
14400
14401 Struct_field_list* sfl = new Struct_field_list;
14402 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14403 this->location());
14404 sfl->push_back(Struct_field(tid));
14405 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14406 p != interface_methods->end();
14407 ++p)
14408 sfl->push_back(Struct_field(*p));
14409 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14410 return this->method_table_type_;
14411 }
14412
14413 Bexpression*
do_get_backend(Translate_context * context)14414 Interface_mtable_expression::do_get_backend(Translate_context* context)
14415 {
14416 Gogo* gogo = context->gogo();
14417 Location loc = Linemap::predeclared_location();
14418 if (this->bvar_ != NULL)
14419 return gogo->backend()->var_expression(this->bvar_, this->location());
14420
14421 const Typed_identifier_list* interface_methods = this->itype_->methods();
14422 go_assert(!interface_methods->empty());
14423
14424 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14425 + this->itype_->mangled_name(gogo)
14426 + "__"
14427 + this->type_->mangled_name(gogo));
14428
14429 // See whether this interface has any hidden methods.
14430 bool has_hidden_methods = false;
14431 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14432 p != interface_methods->end();
14433 ++p)
14434 {
14435 if (Gogo::is_hidden_name(p->name()))
14436 {
14437 has_hidden_methods = true;
14438 break;
14439 }
14440 }
14441
14442 // We already know that the named type is convertible to the
14443 // interface. If the interface has hidden methods, and the named
14444 // type is defined in a different package, then the interface
14445 // conversion table will be defined by that other package.
14446 if (has_hidden_methods
14447 && this->type_->named_type() != NULL
14448 && this->type_->named_type()->named_object()->package() != NULL)
14449 {
14450 Btype* btype = this->type()->get_backend(gogo);
14451 this->bvar_ =
14452 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14453 return gogo->backend()->var_expression(this->bvar_, this->location());
14454 }
14455
14456 // The first element is the type descriptor.
14457 Type* td_type;
14458 if (!this->is_pointer_)
14459 td_type = this->type_;
14460 else
14461 td_type = Type::make_pointer_type(this->type_);
14462
14463 // Build an interface method table for a type: a type descriptor followed by a
14464 // list of function pointers, one for each interface method. This is used for
14465 // interfaces.
14466 Expression_list* svals = new Expression_list();
14467 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14468
14469 Named_type* nt = this->type_->named_type();
14470 Struct_type* st = this->type_->struct_type();
14471 go_assert(nt != NULL || st != NULL);
14472
14473 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14474 p != interface_methods->end();
14475 ++p)
14476 {
14477 bool is_ambiguous;
14478 Method* m;
14479 if (nt != NULL)
14480 m = nt->method_function(p->name(), &is_ambiguous);
14481 else
14482 m = st->method_function(p->name(), &is_ambiguous);
14483 go_assert(m != NULL);
14484 Named_object* no = m->named_object();
14485
14486 go_assert(no->is_function() || no->is_function_declaration());
14487 svals->push_back(Expression::make_func_code_reference(no, loc));
14488 }
14489
14490 Btype* btype = this->type()->get_backend(gogo);
14491 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14492 svals, loc);
14493 Bexpression* ctor = mtable->get_backend(context);
14494
14495 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14496 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14497 !is_public, btype, loc);
14498 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14499 !is_public, btype, loc, ctor);
14500 return gogo->backend()->var_expression(this->bvar_, loc);
14501 }
14502
14503 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14504 Interface_mtable_expression::do_dump_expression(
14505 Ast_dump_context* ast_dump_context) const
14506 {
14507 ast_dump_context->ostream() << "__go_"
14508 << (this->is_pointer_ ? "pimt__" : "imt_");
14509 ast_dump_context->dump_type(this->itype_);
14510 ast_dump_context->ostream() << "__";
14511 ast_dump_context->dump_type(this->type_);
14512 }
14513
14514 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)14515 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14516 bool is_pointer, Location location)
14517 {
14518 return new Interface_mtable_expression(itype, type, is_pointer, location);
14519 }
14520
14521 // An expression which evaluates to the offset of a field within a
14522 // struct. This, like Type_info_expression, q.v., is only used to
14523 // initialize fields of a type descriptor.
14524
14525 class Struct_field_offset_expression : public Expression
14526 {
14527 public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)14528 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14529 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14530 Linemap::predeclared_location()),
14531 type_(type), field_(field)
14532 { }
14533
14534 protected:
14535 bool
do_is_immutable() const14536 do_is_immutable() const
14537 { return true; }
14538
14539 Type*
do_type()14540 do_type()
14541 { return Type::lookup_integer_type("uintptr"); }
14542
14543 void
do_determine_type(const Type_context *)14544 do_determine_type(const Type_context*)
14545 { }
14546
14547 Expression*
do_copy()14548 do_copy()
14549 { return this; }
14550
14551 Bexpression*
14552 do_get_backend(Translate_context* context);
14553
14554 void
14555 do_dump_expression(Ast_dump_context*) const;
14556
14557 private:
14558 // The type of the struct.
14559 Struct_type* type_;
14560 // The field.
14561 const Struct_field* field_;
14562 };
14563
14564 // Return the backend representation for a struct field offset.
14565
14566 Bexpression*
do_get_backend(Translate_context * context)14567 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14568 {
14569 const Struct_field_list* fields = this->type_->fields();
14570 Struct_field_list::const_iterator p;
14571 unsigned i = 0;
14572 for (p = fields->begin();
14573 p != fields->end();
14574 ++p, ++i)
14575 if (&*p == this->field_)
14576 break;
14577 go_assert(&*p == this->field_);
14578
14579 Gogo* gogo = context->gogo();
14580 Btype* btype = this->type_->get_backend(gogo);
14581
14582 int64_t offset = gogo->backend()->type_field_offset(btype, i);
14583 Type* uptr_type = Type::lookup_integer_type("uintptr");
14584 Expression* ret =
14585 Expression::make_integer_int64(offset, uptr_type,
14586 Linemap::predeclared_location());
14587 return ret->get_backend(context);
14588 }
14589
14590 // Dump ast representation for a struct field offset expression.
14591
14592 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14593 Struct_field_offset_expression::do_dump_expression(
14594 Ast_dump_context* ast_dump_context) const
14595 {
14596 ast_dump_context->ostream() << "unsafe.Offsetof(";
14597 ast_dump_context->dump_type(this->type_);
14598 ast_dump_context->ostream() << '.';
14599 ast_dump_context->ostream() <<
14600 Gogo::message_name(this->field_->field_name());
14601 ast_dump_context->ostream() << ")";
14602 }
14603
14604 // Make an expression for a struct field offset.
14605
14606 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)14607 Expression::make_struct_field_offset(Struct_type* type,
14608 const Struct_field* field)
14609 {
14610 return new Struct_field_offset_expression(type, field);
14611 }
14612
14613 // An expression which evaluates to a pointer to the map descriptor of
14614 // a map type.
14615
14616 class Map_descriptor_expression : public Expression
14617 {
14618 public:
Map_descriptor_expression(Map_type * type,Location location)14619 Map_descriptor_expression(Map_type* type, Location location)
14620 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14621 type_(type)
14622 { }
14623
14624 protected:
14625 Type*
do_type()14626 do_type()
14627 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14628
14629 void
do_determine_type(const Type_context *)14630 do_determine_type(const Type_context*)
14631 { }
14632
14633 Expression*
do_copy()14634 do_copy()
14635 { return this; }
14636
14637 Bexpression*
do_get_backend(Translate_context * context)14638 do_get_backend(Translate_context* context)
14639 {
14640 return this->type_->map_descriptor_pointer(context->gogo(),
14641 this->location());
14642 }
14643
14644 void
14645 do_dump_expression(Ast_dump_context*) const;
14646
14647 private:
14648 // The type for which this is the descriptor.
14649 Map_type* type_;
14650 };
14651
14652 // Dump ast representation for a map descriptor expression.
14653
14654 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14655 Map_descriptor_expression::do_dump_expression(
14656 Ast_dump_context* ast_dump_context) const
14657 {
14658 ast_dump_context->ostream() << "map_descriptor(";
14659 ast_dump_context->dump_type(this->type_);
14660 ast_dump_context->ostream() << ")";
14661 }
14662
14663 // Make a map descriptor expression.
14664
14665 Expression*
make_map_descriptor(Map_type * type,Location location)14666 Expression::make_map_descriptor(Map_type* type, Location location)
14667 {
14668 return new Map_descriptor_expression(type, location);
14669 }
14670
14671 // An expression which evaluates to the address of an unnamed label.
14672
14673 class Label_addr_expression : public Expression
14674 {
14675 public:
Label_addr_expression(Label * label,Location location)14676 Label_addr_expression(Label* label, Location location)
14677 : Expression(EXPRESSION_LABEL_ADDR, location),
14678 label_(label)
14679 { }
14680
14681 protected:
14682 Type*
do_type()14683 do_type()
14684 { return Type::make_pointer_type(Type::make_void_type()); }
14685
14686 void
do_determine_type(const Type_context *)14687 do_determine_type(const Type_context*)
14688 { }
14689
14690 Expression*
do_copy()14691 do_copy()
14692 { return new Label_addr_expression(this->label_, this->location()); }
14693
14694 Bexpression*
do_get_backend(Translate_context * context)14695 do_get_backend(Translate_context* context)
14696 { return this->label_->get_addr(context, this->location()); }
14697
14698 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14699 do_dump_expression(Ast_dump_context* ast_dump_context) const
14700 { ast_dump_context->ostream() << this->label_->name(); }
14701
14702 private:
14703 // The label whose address we are taking.
14704 Label* label_;
14705 };
14706
14707 // Make an expression for the address of an unnamed label.
14708
14709 Expression*
make_label_addr(Label * label,Location location)14710 Expression::make_label_addr(Label* label, Location location)
14711 {
14712 return new Label_addr_expression(label, location);
14713 }
14714
14715 // Class Conditional_expression.
14716
14717 // Traversal.
14718
14719 int
do_traverse(Traverse * traverse)14720 Conditional_expression::do_traverse(Traverse* traverse)
14721 {
14722 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14723 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14724 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14725 return TRAVERSE_EXIT;
14726 return TRAVERSE_CONTINUE;
14727 }
14728
14729 // Return the type of the conditional expression.
14730
14731 Type*
do_type()14732 Conditional_expression::do_type()
14733 {
14734 Type* result_type = Type::make_void_type();
14735 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14736 NULL))
14737 result_type = this->then_->type();
14738 else if (this->then_->is_nil_expression()
14739 || this->else_->is_nil_expression())
14740 result_type = (!this->then_->is_nil_expression()
14741 ? this->then_->type()
14742 : this->else_->type());
14743 return result_type;
14744 }
14745
14746 // Determine type for a conditional expression.
14747
14748 void
do_determine_type(const Type_context * context)14749 Conditional_expression::do_determine_type(const Type_context* context)
14750 {
14751 this->cond_->determine_type_no_context();
14752 this->then_->determine_type(context);
14753 this->else_->determine_type(context);
14754 }
14755
14756 // Get the backend representation of a conditional expression.
14757
14758 Bexpression*
do_get_backend(Translate_context * context)14759 Conditional_expression::do_get_backend(Translate_context* context)
14760 {
14761 Gogo* gogo = context->gogo();
14762 Btype* result_btype = this->type()->get_backend(gogo);
14763 Bexpression* cond = this->cond_->get_backend(context);
14764 Bexpression* then = this->then_->get_backend(context);
14765 Bexpression* belse = this->else_->get_backend(context);
14766 return gogo->backend()->conditional_expression(result_btype, cond, then,
14767 belse, this->location());
14768 }
14769
14770 // Dump ast representation of a conditional expression.
14771
14772 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14773 Conditional_expression::do_dump_expression(
14774 Ast_dump_context* ast_dump_context) const
14775 {
14776 ast_dump_context->ostream() << "(";
14777 ast_dump_context->dump_expression(this->cond_);
14778 ast_dump_context->ostream() << " ? ";
14779 ast_dump_context->dump_expression(this->then_);
14780 ast_dump_context->ostream() << " : ";
14781 ast_dump_context->dump_expression(this->else_);
14782 ast_dump_context->ostream() << ") ";
14783 }
14784
14785 // Make a conditional expression.
14786
14787 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)14788 Expression::make_conditional(Expression* cond, Expression* then,
14789 Expression* else_expr, Location location)
14790 {
14791 return new Conditional_expression(cond, then, else_expr, location);
14792 }
14793
14794 // Class Compound_expression.
14795
14796 // Traversal.
14797
14798 int
do_traverse(Traverse * traverse)14799 Compound_expression::do_traverse(Traverse* traverse)
14800 {
14801 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
14802 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
14803 return TRAVERSE_EXIT;
14804 return TRAVERSE_CONTINUE;
14805 }
14806
14807 // Return the type of the compound expression.
14808
14809 Type*
do_type()14810 Compound_expression::do_type()
14811 {
14812 return this->expr_->type();
14813 }
14814
14815 // Determine type for a compound expression.
14816
14817 void
do_determine_type(const Type_context * context)14818 Compound_expression::do_determine_type(const Type_context* context)
14819 {
14820 this->init_->determine_type_no_context();
14821 this->expr_->determine_type(context);
14822 }
14823
14824 // Get the backend representation of a compound expression.
14825
14826 Bexpression*
do_get_backend(Translate_context * context)14827 Compound_expression::do_get_backend(Translate_context* context)
14828 {
14829 Gogo* gogo = context->gogo();
14830 Bexpression* binit = this->init_->get_backend(context);
14831 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
14832 Bexpression* bexpr = this->expr_->get_backend(context);
14833 return gogo->backend()->compound_expression(init_stmt, bexpr,
14834 this->location());
14835 }
14836
14837 // Dump ast representation of a conditional expression.
14838
14839 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14840 Compound_expression::do_dump_expression(
14841 Ast_dump_context* ast_dump_context) const
14842 {
14843 ast_dump_context->ostream() << "(";
14844 ast_dump_context->dump_expression(this->init_);
14845 ast_dump_context->ostream() << ",";
14846 ast_dump_context->dump_expression(this->expr_);
14847 ast_dump_context->ostream() << ") ";
14848 }
14849
14850 // Make a compound expression.
14851
14852 Expression*
make_compound(Expression * init,Expression * expr,Location location)14853 Expression::make_compound(Expression* init, Expression* expr, Location location)
14854 {
14855 return new Compound_expression(init, expr, location);
14856 }
14857
14858 // Import an expression. This comes at the end in order to see the
14859 // various class definitions.
14860
14861 Expression*
import_expression(Import * imp)14862 Expression::import_expression(Import* imp)
14863 {
14864 int c = imp->peek_char();
14865 if (imp->match_c_string("- ")
14866 || imp->match_c_string("! ")
14867 || imp->match_c_string("^ "))
14868 return Unary_expression::do_import(imp);
14869 else if (c == '(')
14870 return Binary_expression::do_import(imp);
14871 else if (imp->match_c_string("true")
14872 || imp->match_c_string("false"))
14873 return Boolean_expression::do_import(imp);
14874 else if (c == '"')
14875 return String_expression::do_import(imp);
14876 else if (c == '-' || (c >= '0' && c <= '9'))
14877 {
14878 // This handles integers, floats and complex constants.
14879 return Integer_expression::do_import(imp);
14880 }
14881 else if (imp->match_c_string("nil"))
14882 return Nil_expression::do_import(imp);
14883 else if (imp->match_c_string("convert"))
14884 return Type_conversion_expression::do_import(imp);
14885 else
14886 {
14887 error_at(imp->location(), "import error: expected expression");
14888 return Expression::make_error(imp->location());
14889 }
14890 }
14891
14892 // Class Expression_list.
14893
14894 // Traverse the list.
14895
14896 int
traverse(Traverse * traverse)14897 Expression_list::traverse(Traverse* traverse)
14898 {
14899 for (Expression_list::iterator p = this->begin();
14900 p != this->end();
14901 ++p)
14902 {
14903 if (*p != NULL)
14904 {
14905 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14906 return TRAVERSE_EXIT;
14907 }
14908 }
14909 return TRAVERSE_CONTINUE;
14910 }
14911
14912 // Copy the list.
14913
14914 Expression_list*
copy()14915 Expression_list::copy()
14916 {
14917 Expression_list* ret = new Expression_list();
14918 for (Expression_list::iterator p = this->begin();
14919 p != this->end();
14920 ++p)
14921 {
14922 if (*p == NULL)
14923 ret->push_back(NULL);
14924 else
14925 ret->push_back((*p)->copy());
14926 }
14927 return ret;
14928 }
14929
14930 // Return whether an expression list has an error expression.
14931
14932 bool
contains_error() const14933 Expression_list::contains_error() const
14934 {
14935 for (Expression_list::const_iterator p = this->begin();
14936 p != this->end();
14937 ++p)
14938 if (*p != NULL && (*p)->is_error_expression())
14939 return true;
14940 return false;
14941 }
14942
14943 // Class Numeric_constant.
14944
14945 // Destructor.
14946
~Numeric_constant()14947 Numeric_constant::~Numeric_constant()
14948 {
14949 this->clear();
14950 }
14951
14952 // Copy constructor.
14953
Numeric_constant(const Numeric_constant & a)14954 Numeric_constant::Numeric_constant(const Numeric_constant& a)
14955 : classification_(a.classification_), type_(a.type_)
14956 {
14957 switch (a.classification_)
14958 {
14959 case NC_INVALID:
14960 break;
14961 case NC_INT:
14962 case NC_RUNE:
14963 mpz_init_set(this->u_.int_val, a.u_.int_val);
14964 break;
14965 case NC_FLOAT:
14966 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14967 break;
14968 case NC_COMPLEX:
14969 mpc_init2(this->u_.complex_val, mpc_precision);
14970 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14971 break;
14972 default:
14973 go_unreachable();
14974 }
14975 }
14976
14977 // Assignment operator.
14978
14979 Numeric_constant&
operator =(const Numeric_constant & a)14980 Numeric_constant::operator=(const Numeric_constant& a)
14981 {
14982 this->clear();
14983 this->classification_ = a.classification_;
14984 this->type_ = a.type_;
14985 switch (a.classification_)
14986 {
14987 case NC_INVALID:
14988 break;
14989 case NC_INT:
14990 case NC_RUNE:
14991 mpz_init_set(this->u_.int_val, a.u_.int_val);
14992 break;
14993 case NC_FLOAT:
14994 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14995 break;
14996 case NC_COMPLEX:
14997 mpc_init2(this->u_.complex_val, mpc_precision);
14998 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14999 break;
15000 default:
15001 go_unreachable();
15002 }
15003 return *this;
15004 }
15005
15006 // Clear the contents.
15007
15008 void
clear()15009 Numeric_constant::clear()
15010 {
15011 switch (this->classification_)
15012 {
15013 case NC_INVALID:
15014 break;
15015 case NC_INT:
15016 case NC_RUNE:
15017 mpz_clear(this->u_.int_val);
15018 break;
15019 case NC_FLOAT:
15020 mpfr_clear(this->u_.float_val);
15021 break;
15022 case NC_COMPLEX:
15023 mpc_clear(this->u_.complex_val);
15024 break;
15025 default:
15026 go_unreachable();
15027 }
15028 this->classification_ = NC_INVALID;
15029 }
15030
15031 // Set to an unsigned long value.
15032
15033 void
set_unsigned_long(Type * type,unsigned long val)15034 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15035 {
15036 this->clear();
15037 this->classification_ = NC_INT;
15038 this->type_ = type;
15039 mpz_init_set_ui(this->u_.int_val, val);
15040 }
15041
15042 // Set to an integer value.
15043
15044 void
set_int(Type * type,const mpz_t val)15045 Numeric_constant::set_int(Type* type, const mpz_t val)
15046 {
15047 this->clear();
15048 this->classification_ = NC_INT;
15049 this->type_ = type;
15050 mpz_init_set(this->u_.int_val, val);
15051 }
15052
15053 // Set to a rune value.
15054
15055 void
set_rune(Type * type,const mpz_t val)15056 Numeric_constant::set_rune(Type* type, const mpz_t val)
15057 {
15058 this->clear();
15059 this->classification_ = NC_RUNE;
15060 this->type_ = type;
15061 mpz_init_set(this->u_.int_val, val);
15062 }
15063
15064 // Set to a floating point value.
15065
15066 void
set_float(Type * type,const mpfr_t val)15067 Numeric_constant::set_float(Type* type, const mpfr_t val)
15068 {
15069 this->clear();
15070 this->classification_ = NC_FLOAT;
15071 this->type_ = type;
15072 // Numeric constants do not have negative zero values, so remove
15073 // them here. They also don't have infinity or NaN values, but we
15074 // should never see them here.
15075 if (mpfr_zero_p(val))
15076 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15077 else
15078 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15079 }
15080
15081 // Set to a complex value.
15082
15083 void
set_complex(Type * type,const mpc_t val)15084 Numeric_constant::set_complex(Type* type, const mpc_t val)
15085 {
15086 this->clear();
15087 this->classification_ = NC_COMPLEX;
15088 this->type_ = type;
15089 mpc_init2(this->u_.complex_val, mpc_precision);
15090 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
15091 }
15092
15093 // Get an int value.
15094
15095 void
get_int(mpz_t * val) const15096 Numeric_constant::get_int(mpz_t* val) const
15097 {
15098 go_assert(this->is_int());
15099 mpz_init_set(*val, this->u_.int_val);
15100 }
15101
15102 // Get a rune value.
15103
15104 void
get_rune(mpz_t * val) const15105 Numeric_constant::get_rune(mpz_t* val) const
15106 {
15107 go_assert(this->is_rune());
15108 mpz_init_set(*val, this->u_.int_val);
15109 }
15110
15111 // Get a floating point value.
15112
15113 void
get_float(mpfr_t * val) const15114 Numeric_constant::get_float(mpfr_t* val) const
15115 {
15116 go_assert(this->is_float());
15117 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15118 }
15119
15120 // Get a complex value.
15121
15122 void
get_complex(mpc_t * val) const15123 Numeric_constant::get_complex(mpc_t* val) const
15124 {
15125 go_assert(this->is_complex());
15126 mpc_init2(*val, mpc_precision);
15127 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15128 }
15129
15130 // Express value as unsigned long if possible.
15131
15132 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const15133 Numeric_constant::to_unsigned_long(unsigned long* val) const
15134 {
15135 switch (this->classification_)
15136 {
15137 case NC_INT:
15138 case NC_RUNE:
15139 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15140 case NC_FLOAT:
15141 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15142 case NC_COMPLEX:
15143 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15144 return NC_UL_NOTINT;
15145 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15146 val);
15147 default:
15148 go_unreachable();
15149 }
15150 }
15151
15152 // Express integer value as unsigned long if possible.
15153
15154 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const15155 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15156 unsigned long *val) const
15157 {
15158 if (mpz_sgn(ival) < 0)
15159 return NC_UL_NEGATIVE;
15160 unsigned long ui = mpz_get_ui(ival);
15161 if (mpz_cmp_ui(ival, ui) != 0)
15162 return NC_UL_BIG;
15163 *val = ui;
15164 return NC_UL_VALID;
15165 }
15166
15167 // Express floating point value as unsigned long if possible.
15168
15169 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const15170 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15171 unsigned long *val) const
15172 {
15173 if (!mpfr_integer_p(fval))
15174 return NC_UL_NOTINT;
15175 mpz_t ival;
15176 mpz_init(ival);
15177 mpfr_get_z(ival, fval, GMP_RNDN);
15178 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15179 mpz_clear(ival);
15180 return ret;
15181 }
15182
15183 // Convert value to integer if possible.
15184
15185 bool
to_int(mpz_t * val) const15186 Numeric_constant::to_int(mpz_t* val) const
15187 {
15188 switch (this->classification_)
15189 {
15190 case NC_INT:
15191 case NC_RUNE:
15192 mpz_init_set(*val, this->u_.int_val);
15193 return true;
15194 case NC_FLOAT:
15195 if (!mpfr_integer_p(this->u_.float_val))
15196 return false;
15197 mpz_init(*val);
15198 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15199 return true;
15200 case NC_COMPLEX:
15201 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15202 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
15203 return false;
15204 mpz_init(*val);
15205 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15206 return true;
15207 default:
15208 go_unreachable();
15209 }
15210 }
15211
15212 // Convert value to floating point if possible.
15213
15214 bool
to_float(mpfr_t * val) const15215 Numeric_constant::to_float(mpfr_t* val) const
15216 {
15217 switch (this->classification_)
15218 {
15219 case NC_INT:
15220 case NC_RUNE:
15221 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15222 return true;
15223 case NC_FLOAT:
15224 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15225 return true;
15226 case NC_COMPLEX:
15227 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15228 return false;
15229 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15230 return true;
15231 default:
15232 go_unreachable();
15233 }
15234 }
15235
15236 // Convert value to complex.
15237
15238 bool
to_complex(mpc_t * val) const15239 Numeric_constant::to_complex(mpc_t* val) const
15240 {
15241 mpc_init2(*val, mpc_precision);
15242 switch (this->classification_)
15243 {
15244 case NC_INT:
15245 case NC_RUNE:
15246 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
15247 return true;
15248 case NC_FLOAT:
15249 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
15250 return true;
15251 case NC_COMPLEX:
15252 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15253 return true;
15254 default:
15255 go_unreachable();
15256 }
15257 }
15258
15259 // Get the type.
15260
15261 Type*
type() const15262 Numeric_constant::type() const
15263 {
15264 if (this->type_ != NULL)
15265 return this->type_;
15266 switch (this->classification_)
15267 {
15268 case NC_INT:
15269 return Type::make_abstract_integer_type();
15270 case NC_RUNE:
15271 return Type::make_abstract_character_type();
15272 case NC_FLOAT:
15273 return Type::make_abstract_float_type();
15274 case NC_COMPLEX:
15275 return Type::make_abstract_complex_type();
15276 default:
15277 go_unreachable();
15278 }
15279 }
15280
15281 // If the constant can be expressed in TYPE, then set the type of the
15282 // constant to TYPE and return true. Otherwise return false, and, if
15283 // ISSUE_ERROR is true, report an appropriate error message.
15284
15285 bool
set_type(Type * type,bool issue_error,Location loc)15286 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15287 {
15288 bool ret;
15289 if (type == NULL || type->is_error())
15290 ret = true;
15291 else if (type->integer_type() != NULL)
15292 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15293 else if (type->float_type() != NULL)
15294 ret = this->check_float_type(type->float_type(), issue_error, loc);
15295 else if (type->complex_type() != NULL)
15296 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15297 else
15298 {
15299 ret = false;
15300 if (issue_error)
15301 go_assert(saw_errors());
15302 }
15303 if (ret)
15304 this->type_ = type;
15305 return ret;
15306 }
15307
15308 // Check whether the constant can be expressed in an integer type.
15309
15310 bool
check_int_type(Integer_type * type,bool issue_error,Location location)15311 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15312 Location location)
15313 {
15314 mpz_t val;
15315 switch (this->classification_)
15316 {
15317 case NC_INT:
15318 case NC_RUNE:
15319 mpz_init_set(val, this->u_.int_val);
15320 break;
15321
15322 case NC_FLOAT:
15323 if (!mpfr_integer_p(this->u_.float_val))
15324 {
15325 if (issue_error)
15326 {
15327 error_at(location,
15328 "floating point constant truncated to integer");
15329 this->set_invalid();
15330 }
15331 return false;
15332 }
15333 mpz_init(val);
15334 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15335 break;
15336
15337 case NC_COMPLEX:
15338 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15339 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15340 {
15341 if (issue_error)
15342 {
15343 error_at(location, "complex constant truncated to integer");
15344 this->set_invalid();
15345 }
15346 return false;
15347 }
15348 mpz_init(val);
15349 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15350 break;
15351
15352 default:
15353 go_unreachable();
15354 }
15355
15356 bool ret;
15357 if (type->is_abstract())
15358 ret = true;
15359 else
15360 {
15361 int bits = mpz_sizeinbase(val, 2);
15362 if (type->is_unsigned())
15363 {
15364 // For an unsigned type we can only accept a nonnegative
15365 // number, and we must be able to represents at least BITS.
15366 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15367 }
15368 else
15369 {
15370 // For a signed type we need an extra bit to indicate the
15371 // sign. We have to handle the most negative integer
15372 // specially.
15373 ret = (bits + 1 <= type->bits()
15374 || (bits <= type->bits()
15375 && mpz_sgn(val) < 0
15376 && (mpz_scan1(val, 0)
15377 == static_cast<unsigned long>(type->bits() - 1))
15378 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15379 }
15380 }
15381
15382 if (!ret && issue_error)
15383 {
15384 error_at(location, "integer constant overflow");
15385 this->set_invalid();
15386 }
15387
15388 return ret;
15389 }
15390
15391 // Check whether the constant can be expressed in a floating point
15392 // type.
15393
15394 bool
check_float_type(Float_type * type,bool issue_error,Location location)15395 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15396 Location location)
15397 {
15398 mpfr_t val;
15399 switch (this->classification_)
15400 {
15401 case NC_INT:
15402 case NC_RUNE:
15403 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15404 break;
15405
15406 case NC_FLOAT:
15407 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15408 break;
15409
15410 case NC_COMPLEX:
15411 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15412 {
15413 if (issue_error)
15414 {
15415 this->set_invalid();
15416 error_at(location, "complex constant truncated to float");
15417 }
15418 return false;
15419 }
15420 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15421 break;
15422
15423 default:
15424 go_unreachable();
15425 }
15426
15427 bool ret;
15428 if (type->is_abstract())
15429 ret = true;
15430 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15431 {
15432 // A NaN or Infinity always fits in the range of the type.
15433 ret = true;
15434 }
15435 else
15436 {
15437 mp_exp_t exp = mpfr_get_exp(val);
15438 mp_exp_t max_exp;
15439 switch (type->bits())
15440 {
15441 case 32:
15442 max_exp = 128;
15443 break;
15444 case 64:
15445 max_exp = 1024;
15446 break;
15447 default:
15448 go_unreachable();
15449 }
15450
15451 ret = exp <= max_exp;
15452
15453 if (ret)
15454 {
15455 // Round the constant to the desired type.
15456 mpfr_t t;
15457 mpfr_init(t);
15458 switch (type->bits())
15459 {
15460 case 32:
15461 mpfr_set_prec(t, 24);
15462 break;
15463 case 64:
15464 mpfr_set_prec(t, 53);
15465 break;
15466 default:
15467 go_unreachable();
15468 }
15469 mpfr_set(t, val, GMP_RNDN);
15470 mpfr_set(val, t, GMP_RNDN);
15471 mpfr_clear(t);
15472
15473 this->set_float(type, val);
15474 }
15475 }
15476
15477 mpfr_clear(val);
15478
15479 if (!ret && issue_error)
15480 {
15481 error_at(location, "floating point constant overflow");
15482 this->set_invalid();
15483 }
15484
15485 return ret;
15486 }
15487
15488 // Check whether the constant can be expressed in a complex type.
15489
15490 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)15491 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15492 Location location)
15493 {
15494 if (type->is_abstract())
15495 return true;
15496
15497 mp_exp_t max_exp;
15498 switch (type->bits())
15499 {
15500 case 64:
15501 max_exp = 128;
15502 break;
15503 case 128:
15504 max_exp = 1024;
15505 break;
15506 default:
15507 go_unreachable();
15508 }
15509
15510 mpc_t val;
15511 mpc_init2(val, mpc_precision);
15512 switch (this->classification_)
15513 {
15514 case NC_INT:
15515 case NC_RUNE:
15516 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
15517 break;
15518
15519 case NC_FLOAT:
15520 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
15521 break;
15522
15523 case NC_COMPLEX:
15524 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
15525 break;
15526
15527 default:
15528 go_unreachable();
15529 }
15530
15531 bool ret = true;
15532 if (!mpfr_nan_p(mpc_realref(val))
15533 && !mpfr_inf_p(mpc_realref(val))
15534 && !mpfr_zero_p(mpc_realref(val))
15535 && mpfr_get_exp(mpc_realref(val)) > max_exp)
15536 {
15537 if (issue_error)
15538 {
15539 error_at(location, "complex real part overflow");
15540 this->set_invalid();
15541 }
15542 ret = false;
15543 }
15544
15545 if (!mpfr_nan_p(mpc_imagref(val))
15546 && !mpfr_inf_p(mpc_imagref(val))
15547 && !mpfr_zero_p(mpc_imagref(val))
15548 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
15549 {
15550 if (issue_error)
15551 {
15552 error_at(location, "complex imaginary part overflow");
15553 this->set_invalid();
15554 }
15555 ret = false;
15556 }
15557
15558 if (ret)
15559 {
15560 // Round the constant to the desired type.
15561 mpc_t t;
15562 switch (type->bits())
15563 {
15564 case 64:
15565 mpc_init2(t, 24);
15566 break;
15567 case 128:
15568 mpc_init2(t, 53);
15569 break;
15570 default:
15571 go_unreachable();
15572 }
15573 mpc_set(t, val, MPC_RNDNN);
15574 mpc_set(val, t, MPC_RNDNN);
15575 mpc_clear(t);
15576
15577 this->set_complex(type, val);
15578 }
15579
15580 mpc_clear(val);
15581
15582 return ret;
15583 }
15584
15585 // Return an Expression for this value.
15586
15587 Expression*
expression(Location loc) const15588 Numeric_constant::expression(Location loc) const
15589 {
15590 switch (this->classification_)
15591 {
15592 case NC_INT:
15593 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
15594 case NC_RUNE:
15595 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15596 case NC_FLOAT:
15597 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15598 case NC_COMPLEX:
15599 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
15600 case NC_INVALID:
15601 go_assert(saw_errors());
15602 return Expression::make_error(loc);
15603 default:
15604 go_unreachable();
15605 }
15606 }
15607