]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
OpenMP loop cloning for SIMT execution
[thirdparty/gcc.git] / gcc / go / gofrontend / expressions.cc
CommitLineData
e440a328 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
ffe743ca 9#include <algorithm>
10
e440a328 11#include "go-c.h"
12#include "gogo.h"
631d5788 13#include "go-diagnostics.h"
e440a328 14#include "types.h"
15#include "export.h"
16#include "import.h"
17#include "statements.h"
18#include "lex.h"
a9182619 19#include "runtime.h"
6e193e6f 20#include "backend.h"
e440a328 21#include "expressions.h"
d751bb78 22#include "ast-dump.h"
e440a328 23
24// Class Expression.
25
26Expression::Expression(Expression_classification classification,
b13c66cd 27 Location location)
e440a328 28 : classification_(classification), location_(location)
29{
30}
31
32Expression::~Expression()
33{
34}
35
e440a328 36// Traverse the expressions.
37
38int
39Expression::traverse(Expression** pexpr, Traverse* traverse)
40{
41 Expression* expr = *pexpr;
42 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
43 {
44 int t = traverse->expression(pexpr);
45 if (t == TRAVERSE_EXIT)
46 return TRAVERSE_EXIT;
47 else if (t == TRAVERSE_SKIP_COMPONENTS)
48 return TRAVERSE_CONTINUE;
49 }
50 return expr->do_traverse(traverse);
51}
52
53// Traverse subexpressions of this expression.
54
55int
56Expression::traverse_subexpressions(Traverse* traverse)
57{
58 return this->do_traverse(traverse);
59}
60
61// Default implementation for do_traverse for child classes.
62
63int
64Expression::do_traverse(Traverse*)
65{
66 return TRAVERSE_CONTINUE;
67}
68
69// This virtual function is called by the parser if the value of this
a7549a6a 70// expression is being discarded. By default, we give an error.
71// Expressions with side effects override.
e440a328 72
4f2138d7 73bool
e440a328 74Expression::do_discarding_value()
75{
a7549a6a 76 this->unused_value_error();
4f2138d7 77 return false;
e440a328 78}
79
80// This virtual function is called to export expressions. This will
81// only be used by expressions which may be constant.
82
83void
84Expression::do_export(Export*) const
85{
c3e6f413 86 go_unreachable();
e440a328 87}
88
a7549a6a 89// Give an error saying that the value of the expression is not used.
e440a328 90
91void
a7549a6a 92Expression::unused_value_error()
e440a328 93{
4f2138d7 94 this->report_error(_("value computed is not used"));
e440a328 95}
96
97// Note that this expression is an error. This is called by children
98// when they discover an error.
99
100void
101Expression::set_is_error()
102{
103 this->classification_ = EXPRESSION_ERROR;
104}
105
106// For children to call to report an error conveniently.
107
108void
109Expression::report_error(const char* msg)
110{
631d5788 111 go_error_at(this->location_, "%s", msg);
e440a328 112 this->set_is_error();
113}
114
115// Set types of variables and constants. This is implemented by the
116// child class.
117
118void
119Expression::determine_type(const Type_context* context)
120{
121 this->do_determine_type(context);
122}
123
124// Set types when there is no context.
125
126void
127Expression::determine_type_no_context()
128{
129 Type_context context;
130 this->do_determine_type(&context);
131}
132
2c809f8f 133// Return an expression handling any conversions which must be done during
e440a328 134// assignment.
135
2c809f8f 136Expression*
b4a33049 137Expression::convert_for_assignment(Gogo*, Type* lhs_type,
2c809f8f 138 Expression* rhs, Location location)
e440a328 139{
2c809f8f 140 Type* rhs_type = rhs->type();
141 if (lhs_type->is_error()
142 || rhs_type->is_error()
143 || rhs->is_error_expression())
144 return Expression::make_error(location);
e440a328 145
54211955 146 if (lhs_type->forwarded() != rhs_type->forwarded()
147 && lhs_type->interface_type() != NULL)
e440a328 148 {
149 if (rhs_type->interface_type() == NULL)
2c809f8f 150 return Expression::convert_type_to_interface(lhs_type, rhs, location);
e440a328 151 else
2c809f8f 152 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
153 location);
e440a328 154 }
54211955 155 else if (lhs_type->forwarded() != rhs_type->forwarded()
156 && rhs_type->interface_type() != NULL)
2c809f8f 157 return Expression::convert_interface_to_type(lhs_type, rhs, location);
411eb89e 158 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 159 {
2c809f8f 160 // Assigning nil to a slice.
2c809f8f 161 Expression* nil = Expression::make_nil(location);
e67508fa 162 Expression* zero = Expression::make_integer_ul(0, NULL, location);
2c809f8f 163 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
e440a328 164 }
165 else if (rhs_type->is_nil_type())
2c809f8f 166 return Expression::make_nil(location);
167 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
e440a328 168 {
169 // No conversion is needed.
2c809f8f 170 return rhs;
171 }
172 else if (lhs_type->points_to() != NULL)
173 return Expression::make_unsafe_cast(lhs_type, rhs, location);
174 else if (lhs_type->is_numeric_type())
175 return Expression::make_cast(lhs_type, rhs, location);
176 else if ((lhs_type->struct_type() != NULL
177 && rhs_type->struct_type() != NULL)
178 || (lhs_type->array_type() != NULL
179 && rhs_type->array_type() != NULL))
e440a328 180 {
181 // This conversion must be permitted by Go, or we wouldn't have
182 // gotten here.
2c809f8f 183 return Expression::make_unsafe_cast(lhs_type, rhs, location);
e440a328 184 }
185 else
2c809f8f 186 return rhs;
e440a328 187}
188
2c809f8f 189// Return an expression for a conversion from a non-interface type to an
e440a328 190// interface type.
191
2c809f8f 192Expression*
193Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
194 Location location)
e440a328 195{
e440a328 196 Interface_type* lhs_interface_type = lhs_type->interface_type();
197 bool lhs_is_empty = lhs_interface_type->is_empty();
198
199 // Since RHS_TYPE is a static type, we can create the interface
200 // method table at compile time.
201
202 // When setting an interface to nil, we just set both fields to
203 // NULL.
2c809f8f 204 Type* rhs_type = rhs->type();
e440a328 205 if (rhs_type->is_nil_type())
63697958 206 {
2c809f8f 207 Expression* nil = Expression::make_nil(location);
208 return Expression::make_interface_value(lhs_type, nil, nil, location);
63697958 209 }
e440a328 210
211 // This should have been checked already.
c484d925 212 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 213
e440a328 214 // An interface is a tuple. If LHS_TYPE is an empty interface type,
215 // then the first field is the type descriptor for RHS_TYPE.
216 // Otherwise it is the interface method table for RHS_TYPE.
2c809f8f 217 Expression* first_field;
e440a328 218 if (lhs_is_empty)
2c809f8f 219 first_field = Expression::make_type_descriptor(rhs_type, location);
e440a328 220 else
221 {
222 // Build the interface method table for this interface and this
223 // object type: a list of function pointers for each interface
224 // method.
225 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 226 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 227 bool is_pointer = false;
c0cab2ec 228 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 229 {
230 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 231 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 232 is_pointer = true;
233 }
c0cab2ec 234 if (rhs_named_type != NULL)
2c809f8f 235 first_field =
236 rhs_named_type->interface_method_table(lhs_interface_type,
237 is_pointer);
c0cab2ec 238 else if (rhs_struct_type != NULL)
2c809f8f 239 first_field =
240 rhs_struct_type->interface_method_table(lhs_interface_type,
241 is_pointer);
c0cab2ec 242 else
2c809f8f 243 first_field = Expression::make_nil(location);
e440a328 244 }
e440a328 245
2c809f8f 246 Expression* obj;
e440a328 247 if (rhs_type->points_to() != NULL)
248 {
2c809f8f 249 // We are assigning a pointer to the interface; the interface
e440a328 250 // holds the pointer itself.
2c809f8f 251 obj = rhs;
252 }
253 else
254 {
255 // We are assigning a non-pointer value to the interface; the
45ff893b 256 // interface gets a copy of the value in the heap if it escapes.
257 // TODO(cmang): Associate escape state state of RHS with newly
258 // created OBJ.
2c809f8f 259 obj = Expression::make_heap_expression(rhs, location);
e440a328 260 }
261
2c809f8f 262 return Expression::make_interface_value(lhs_type, first_field, obj, location);
263}
e440a328 264
2c809f8f 265// Return an expression for the type descriptor of RHS.
e440a328 266
2c809f8f 267Expression*
268Expression::get_interface_type_descriptor(Expression* rhs)
269{
270 go_assert(rhs->type()->interface_type() != NULL);
271 Location location = rhs->location();
e440a328 272
2c809f8f 273 // The type descriptor is the first field of an empty interface.
274 if (rhs->type()->interface_type()->is_empty())
275 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
276 location);
277
278 Expression* mtable =
279 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
e440a328 280
2c809f8f 281 Expression* descriptor =
282 Expression::make_unary(OPERATOR_MULT, mtable, location);
283 descriptor = Expression::make_field_reference(descriptor, 0, location);
284 Expression* nil = Expression::make_nil(location);
e440a328 285
2c809f8f 286 Expression* eq =
287 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
288 return Expression::make_conditional(eq, nil, descriptor, location);
e440a328 289}
290
2c809f8f 291// Return an expression for the conversion of an interface type to an
e440a328 292// interface type.
293
2c809f8f 294Expression*
295Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
296 bool for_type_guard,
297 Location location)
e440a328 298{
8ba8cc87 299 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
300 return rhs;
301
e440a328 302 Interface_type* lhs_interface_type = lhs_type->interface_type();
303 bool lhs_is_empty = lhs_interface_type->is_empty();
304
e440a328 305 // In the general case this requires runtime examination of the type
306 // method table to match it up with the interface methods.
307
308 // FIXME: If all of the methods in the right hand side interface
309 // also appear in the left hand side interface, then we don't need
310 // to do a runtime check, although we still need to build a new
311 // method table.
312
8ba8cc87 313 // We are going to evaluate RHS multiple times.
314 go_assert(rhs->is_variable());
315
e440a328 316 // Get the type descriptor for the right hand side. This will be
317 // NULL for a nil interface.
2c809f8f 318 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
319 Expression* lhs_type_expr =
320 Expression::make_type_descriptor(lhs_type, location);
e440a328 321
2c809f8f 322 Expression* first_field;
e440a328 323 if (for_type_guard)
324 {
325 // A type assertion fails when converting a nil interface.
6098d6cb 326 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
327 lhs_type_expr, rhs_type_expr);
e440a328 328 }
329 else if (lhs_is_empty)
330 {
2c809f8f 331 // A conversion to an empty interface always succeeds, and the
e440a328 332 // first field is just the type descriptor of the object.
2c809f8f 333 first_field = rhs_type_expr;
e440a328 334 }
335 else
336 {
337 // A conversion to a non-empty interface may fail, but unlike a
338 // type assertion converting nil will always succeed.
6098d6cb 339 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
340 lhs_type_expr, rhs_type_expr);
e440a328 341 }
342
343 // The second field is simply the object pointer.
2c809f8f 344 Expression* obj =
345 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
346 return Expression::make_interface_value(lhs_type, first_field, obj, location);
e440a328 347}
348
2c809f8f 349// Return an expression for the conversion of an interface type to a
e440a328 350// non-interface type.
351
2c809f8f 352Expression*
353Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
354 Location location)
e440a328 355{
8ba8cc87 356 // We are going to evaluate RHS multiple times.
357 go_assert(rhs->is_variable());
358
e440a328 359 // Call a function to check that the type is valid. The function
360 // will panic with an appropriate runtime type error if the type is
361 // not valid.
2c809f8f 362 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
363 location);
364 Expression* rhs_descriptor =
365 Expression::get_interface_type_descriptor(rhs);
366
367 Type* rhs_type = rhs->type();
368 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
369 location);
370
6098d6cb 371 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
2c809f8f 372 location, 3, lhs_type_expr,
373 rhs_descriptor, rhs_inter_expr);
e440a328 374
375 // If the call succeeds, pull out the value.
2c809f8f 376 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
377 location);
e440a328 378
379 // If the value is a pointer, then it is the value we want.
380 // Otherwise it points to the value.
381 if (lhs_type->points_to() == NULL)
382 {
2c809f8f 383 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
384 location);
385 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
e440a328 386 }
2c809f8f 387 return Expression::make_compound(check_iface, obj, location);
e440a328 388}
389
ea664253 390// Convert an expression to its backend representation. This is implemented by
391// the child class. Not that it is not in general safe to call this multiple
e440a328 392// times for a single expression, but that we don't catch such errors.
393
ea664253 394Bexpression*
395Expression::get_backend(Translate_context* context)
e440a328 396{
397 // The child may have marked this expression as having an error.
398 if (this->classification_ == EXPRESSION_ERROR)
ea664253 399 return context->backend()->error_expression();
e440a328 400
ea664253 401 return this->do_get_backend(context);
e440a328 402}
403
48c2a53a 404// Return a backend expression for VAL.
405Bexpression*
406Expression::backend_numeric_constant_expression(Translate_context* context,
407 Numeric_constant* val)
e440a328 408{
48c2a53a 409 Gogo* gogo = context->gogo();
410 Type* type = val->type();
411 if (type == NULL)
412 return gogo->backend()->error_expression();
e440a328 413
48c2a53a 414 Btype* btype = type->get_backend(gogo);
415 Bexpression* ret;
416 if (type->integer_type() != NULL)
e440a328 417 {
418 mpz_t ival;
48c2a53a 419 if (!val->to_int(&ival))
420 {
421 go_assert(saw_errors());
422 return gogo->backend()->error_expression();
423 }
424 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 425 mpz_clear(ival);
e440a328 426 }
48c2a53a 427 else if (type->float_type() != NULL)
e440a328 428 {
48c2a53a 429 mpfr_t fval;
430 if (!val->to_float(&fval))
431 {
432 go_assert(saw_errors());
433 return gogo->backend()->error_expression();
434 }
435 ret = gogo->backend()->float_constant_expression(btype, fval);
436 mpfr_clear(fval);
e440a328 437 }
48c2a53a 438 else if (type->complex_type() != NULL)
e440a328 439 {
fcbea5e4 440 mpc_t cval;
441 if (!val->to_complex(&cval))
48c2a53a 442 {
443 go_assert(saw_errors());
444 return gogo->backend()->error_expression();
445 }
fcbea5e4 446 ret = gogo->backend()->complex_constant_expression(btype, cval);
447 mpc_clear(cval);
e440a328 448 }
449 else
c3e6f413 450 go_unreachable();
e440a328 451
48c2a53a 452 return ret;
e440a328 453}
454
2c809f8f 455// Return an expression which evaluates to true if VAL, of arbitrary integer
456// type, is negative or is more than the maximum value of the Go type "int".
e440a328 457
2c809f8f 458Expression*
459Expression::check_bounds(Expression* val, Location loc)
e440a328 460{
2c809f8f 461 Type* val_type = val->type();
462 Type* bound_type = Type::lookup_integer_type("int");
463
464 int val_type_size;
465 bool val_is_unsigned = false;
466 if (val_type->integer_type() != NULL)
467 {
468 val_type_size = val_type->integer_type()->bits();
469 val_is_unsigned = val_type->integer_type()->is_unsigned();
470 }
471 else
472 {
473 if (!val_type->is_numeric_type()
474 || !Type::are_convertible(bound_type, val_type, NULL))
475 {
476 go_assert(saw_errors());
477 return Expression::make_boolean(true, loc);
478 }
e440a328 479
2c809f8f 480 if (val_type->complex_type() != NULL)
481 val_type_size = val_type->complex_type()->bits();
482 else
483 val_type_size = val_type->float_type()->bits();
484 }
485
486 Expression* negative_index = Expression::make_boolean(false, loc);
487 Expression* index_overflows = Expression::make_boolean(false, loc);
488 if (!val_is_unsigned)
e440a328 489 {
e67508fa 490 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
2c809f8f 491 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
e440a328 492 }
493
2c809f8f 494 int bound_type_size = bound_type->integer_type()->bits();
c3068ac0 495 if (val_type_size > bound_type_size
496 || (val_type_size == bound_type_size
2c809f8f 497 && val_is_unsigned))
498 {
499 mpz_t one;
500 mpz_init_set_ui(one, 1UL);
501
502 // maxval = 2^(bound_type_size - 1) - 1
503 mpz_t maxval;
504 mpz_init(maxval);
505 mpz_mul_2exp(maxval, one, bound_type_size - 1);
506 mpz_sub_ui(maxval, maxval, 1);
e67508fa 507 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
2c809f8f 508 mpz_clear(one);
509 mpz_clear(maxval);
510
511 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
e440a328 512 }
513
2c809f8f 514 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
515 loc);
e440a328 516}
517
d751bb78 518void
519Expression::dump_expression(Ast_dump_context* ast_dump_context) const
520{
521 this->do_dump_expression(ast_dump_context);
522}
523
e440a328 524// Error expressions. This are used to avoid cascading errors.
525
526class Error_expression : public Expression
527{
528 public:
b13c66cd 529 Error_expression(Location location)
e440a328 530 : Expression(EXPRESSION_ERROR, location)
531 { }
532
533 protected:
534 bool
535 do_is_constant() const
536 { return true; }
537
538 bool
0c77715b 539 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 540 {
0c77715b 541 nc->set_unsigned_long(NULL, 0);
e440a328 542 return true;
543 }
544
4f2138d7 545 bool
e440a328 546 do_discarding_value()
4f2138d7 547 { return true; }
e440a328 548
549 Type*
550 do_type()
551 { return Type::make_error_type(); }
552
553 void
554 do_determine_type(const Type_context*)
555 { }
556
557 Expression*
558 do_copy()
559 { return this; }
560
561 bool
562 do_is_addressable() const
563 { return true; }
564
ea664253 565 Bexpression*
566 do_get_backend(Translate_context* context)
567 { return context->backend()->error_expression(); }
d751bb78 568
569 void
570 do_dump_expression(Ast_dump_context*) const;
e440a328 571};
572
d751bb78 573// Dump the ast representation for an error expression to a dump context.
574
575void
576Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
577{
578 ast_dump_context->ostream() << "_Error_" ;
579}
580
e440a328 581Expression*
b13c66cd 582Expression::make_error(Location location)
e440a328 583{
584 return new Error_expression(location);
585}
586
587// An expression which is really a type. This is used during parsing.
588// It is an error if these survive after lowering.
589
590class
591Type_expression : public Expression
592{
593 public:
b13c66cd 594 Type_expression(Type* type, Location location)
e440a328 595 : Expression(EXPRESSION_TYPE, location),
596 type_(type)
597 { }
598
599 protected:
600 int
601 do_traverse(Traverse* traverse)
602 { return Type::traverse(this->type_, traverse); }
603
604 Type*
605 do_type()
606 { return this->type_; }
607
608 void
609 do_determine_type(const Type_context*)
610 { }
611
612 void
613 do_check_types(Gogo*)
614 { this->report_error(_("invalid use of type")); }
615
616 Expression*
617 do_copy()
618 { return this; }
619
ea664253 620 Bexpression*
621 do_get_backend(Translate_context*)
c3e6f413 622 { go_unreachable(); }
e440a328 623
d751bb78 624 void do_dump_expression(Ast_dump_context*) const;
625
e440a328 626 private:
627 // The type which we are representing as an expression.
628 Type* type_;
629};
630
d751bb78 631void
632Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
633{
634 ast_dump_context->dump_type(this->type_);
635}
636
e440a328 637Expression*
b13c66cd 638Expression::make_type(Type* type, Location location)
e440a328 639{
640 return new Type_expression(type, location);
641}
642
e03bdf36 643// Class Parser_expression.
644
645Type*
646Parser_expression::do_type()
647{
648 // We should never really ask for the type of a Parser_expression.
649 // However, it can happen, at least when we have an invalid const
650 // whose initializer refers to the const itself. In that case we
651 // may ask for the type when lowering the const itself.
c484d925 652 go_assert(saw_errors());
e03bdf36 653 return Type::make_error_type();
654}
655
e440a328 656// Class Var_expression.
657
658// Lower a variable expression. Here we just make sure that the
659// initialization expression of the variable has been lowered. This
660// ensures that we will be able to determine the type of the variable
661// if necessary.
662
663Expression*
ceeb4318 664Var_expression::do_lower(Gogo* gogo, Named_object* function,
665 Statement_inserter* inserter, int)
e440a328 666{
667 if (this->variable_->is_variable())
668 {
669 Variable* var = this->variable_->var_value();
670 // This is either a local variable or a global variable. A
671 // reference to a variable which is local to an enclosing
672 // function will be a reference to a field in a closure.
673 if (var->is_global())
ceeb4318 674 {
675 function = NULL;
676 inserter = NULL;
677 }
678 var->lower_init_expression(gogo, function, inserter);
e440a328 679 }
680 return this;
681}
682
e440a328 683// Return the type of a reference to a variable.
684
685Type*
686Var_expression::do_type()
687{
688 if (this->variable_->is_variable())
689 return this->variable_->var_value()->type();
690 else if (this->variable_->is_result_variable())
691 return this->variable_->result_var_value()->type();
692 else
c3e6f413 693 go_unreachable();
e440a328 694}
695
0ab09e06 696// Determine the type of a reference to a variable.
697
698void
699Var_expression::do_determine_type(const Type_context*)
700{
701 if (this->variable_->is_variable())
702 this->variable_->var_value()->determine_type();
703}
704
e440a328 705// Something takes the address of this variable. This means that we
706// may want to move the variable onto the heap.
707
708void
709Var_expression::do_address_taken(bool escapes)
710{
711 if (!escapes)
f325319b 712 {
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->set_non_escaping_address_taken();
715 else if (this->variable_->is_result_variable())
716 this->variable_->result_var_value()->set_non_escaping_address_taken();
717 else
718 go_unreachable();
719 }
e440a328 720 else
f325319b 721 {
722 if (this->variable_->is_variable())
723 this->variable_->var_value()->set_address_taken();
724 else if (this->variable_->is_result_variable())
725 this->variable_->result_var_value()->set_address_taken();
726 else
727 go_unreachable();
728 }
45ff893b 729
730 if (this->variable_->is_variable()
731 && this->variable_->var_value()->is_in_heap())
732 {
733 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
734 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
735 }
e440a328 736}
737
ea664253 738// Get the backend representation for a reference to a variable.
e440a328 739
ea664253 740Bexpression*
741Var_expression::do_get_backend(Translate_context* context)
e440a328 742{
fe2f84cf 743 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
744 context->function());
fe2f84cf 745 bool is_in_heap;
c6777780 746 Location loc = this->location();
9b27b43c 747 Btype* btype;
748 Gogo* gogo = context->gogo();
fe2f84cf 749 if (this->variable_->is_variable())
9b27b43c 750 {
751 is_in_heap = this->variable_->var_value()->is_in_heap();
752 btype = this->variable_->var_value()->type()->get_backend(gogo);
753 }
fe2f84cf 754 else if (this->variable_->is_result_variable())
9b27b43c 755 {
756 is_in_heap = this->variable_->result_var_value()->is_in_heap();
757 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
758 }
fe2f84cf 759 else
c3e6f413 760 go_unreachable();
c6777780 761
762 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 763 if (is_in_heap)
9b27b43c 764 ret = context->backend()->indirect_expression(btype, ret, true, loc);
ea664253 765 return ret;
e440a328 766}
767
d751bb78 768// Ast dump for variable expression.
769
770void
771Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
772{
773 ast_dump_context->ostream() << this->variable_->name() ;
774}
775
e440a328 776// Make a reference to a variable in an expression.
777
778Expression*
b13c66cd 779Expression::make_var_reference(Named_object* var, Location location)
e440a328 780{
781 if (var->is_sink())
782 return Expression::make_sink(location);
783
784 // FIXME: Creating a new object for each reference to a variable is
785 // wasteful.
786 return new Var_expression(var, location);
787}
788
b0c09712 789// Class Enclosed_var_expression.
790
791int
792Enclosed_var_expression::do_traverse(Traverse*)
793{
794 return TRAVERSE_CONTINUE;
795}
796
797// Lower the reference to the enclosed variable.
798
799Expression*
800Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
801 Statement_inserter* inserter, int)
802{
803 gogo->lower_expression(function, inserter, &this->reference_);
804 return this;
805}
806
807// Flatten the reference to the enclosed variable.
808
809Expression*
810Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
811 Statement_inserter* inserter)
812{
813 gogo->flatten_expression(function, inserter, &this->reference_);
814 return this;
815}
816
817void
818Enclosed_var_expression::do_address_taken(bool escapes)
819{
820 if (!escapes)
821 {
822 if (this->variable_->is_variable())
823 this->variable_->var_value()->set_non_escaping_address_taken();
824 else if (this->variable_->is_result_variable())
825 this->variable_->result_var_value()->set_non_escaping_address_taken();
826 else
827 go_unreachable();
828 }
829 else
830 {
831 if (this->variable_->is_variable())
832 this->variable_->var_value()->set_address_taken();
833 else if (this->variable_->is_result_variable())
834 this->variable_->result_var_value()->set_address_taken();
835 else
836 go_unreachable();
837 }
45ff893b 838
839 if (this->variable_->is_variable()
840 && this->variable_->var_value()->is_in_heap())
841 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
b0c09712 842}
843
844// Ast dump for enclosed variable expression.
845
846void
847Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
848{
849 adc->ostream() << this->variable_->name();
850}
851
852// Make a reference to a variable within an enclosing function.
853
854Expression*
855Expression::make_enclosing_var_reference(Expression* reference,
856 Named_object* var, Location location)
857{
858 return new Enclosed_var_expression(reference, var, location);
859}
860
e440a328 861// Class Temporary_reference_expression.
862
863// The type.
864
865Type*
866Temporary_reference_expression::do_type()
867{
868 return this->statement_->type();
869}
870
871// Called if something takes the address of this temporary variable.
872// We never have to move temporary variables to the heap, but we do
873// need to know that they must live in the stack rather than in a
874// register.
875
876void
877Temporary_reference_expression::do_address_taken(bool)
878{
879 this->statement_->set_is_address_taken();
880}
881
ea664253 882// Get a backend expression referring to the variable.
e440a328 883
ea664253 884Bexpression*
885Temporary_reference_expression::do_get_backend(Translate_context* context)
e440a328 886{
cd440cff 887 Gogo* gogo = context->gogo();
eefc1ed3 888 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 889 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 890
cd440cff 891 // The backend can't always represent the same set of recursive types
eefc1ed3 892 // that the Go frontend can. In some cases this means that a
893 // temporary variable won't have the right backend type. Correct
894 // that here by adding a type cast. We need to use base() to push
895 // the circularity down one level.
cd440cff 896 Type* stype = this->statement_->type();
ceeb4318 897 if (!this->is_lvalue_
cd440cff 898 && stype->has_pointer()
899 && stype->deref()->is_void_type())
eefc1ed3 900 {
cd440cff 901 Btype* btype = this->type()->base()->get_backend(gogo);
902 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 903 }
ea664253 904 return ret;
e440a328 905}
906
d751bb78 907// Ast dump for temporary reference.
908
909void
910Temporary_reference_expression::do_dump_expression(
911 Ast_dump_context* ast_dump_context) const
912{
913 ast_dump_context->dump_temp_variable_name(this->statement_);
914}
915
e440a328 916// Make a reference to a temporary variable.
917
ceeb4318 918Temporary_reference_expression*
e440a328 919Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 920 Location location)
e440a328 921{
922 return new Temporary_reference_expression(statement, location);
923}
924
e9d3367e 925// Class Set_and_use_temporary_expression.
926
927// Return the type.
928
929Type*
930Set_and_use_temporary_expression::do_type()
931{
932 return this->statement_->type();
933}
934
0afbb937 935// Determine the type of the expression.
936
937void
938Set_and_use_temporary_expression::do_determine_type(
939 const Type_context* context)
940{
941 this->expr_->determine_type(context);
942}
943
e9d3367e 944// Take the address.
945
946void
947Set_and_use_temporary_expression::do_address_taken(bool)
948{
949 this->statement_->set_is_address_taken();
950}
951
952// Return the backend representation.
953
ea664253 954Bexpression*
955Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
e9d3367e 956{
e9d3367e 957 Location loc = this->location();
a302c105 958 Gogo* gogo = context->gogo();
959 Bvariable* bvar = this->statement_->get_backend_variable(context);
960 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
961
ea664253 962 Bexpression* bexpr = this->expr_->get_backend(context);
a302c105 963 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
964 var_ref = gogo->backend()->var_expression(bvar, loc);
965 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
ea664253 966 return ret;
e9d3367e 967}
968
969// Dump.
970
971void
972Set_and_use_temporary_expression::do_dump_expression(
973 Ast_dump_context* ast_dump_context) const
974{
975 ast_dump_context->ostream() << '(';
976 ast_dump_context->dump_temp_variable_name(this->statement_);
977 ast_dump_context->ostream() << " = ";
978 this->expr_->dump_expression(ast_dump_context);
979 ast_dump_context->ostream() << ')';
980}
981
982// Make a set-and-use temporary.
983
984Set_and_use_temporary_expression*
985Expression::make_set_and_use_temporary(Temporary_statement* statement,
986 Expression* expr, Location location)
987{
988 return new Set_and_use_temporary_expression(statement, expr, location);
989}
990
e440a328 991// A sink expression--a use of the blank identifier _.
992
993class Sink_expression : public Expression
994{
995 public:
b13c66cd 996 Sink_expression(Location location)
e440a328 997 : Expression(EXPRESSION_SINK, location),
aa93217a 998 type_(NULL), bvar_(NULL)
e440a328 999 { }
1000
1001 protected:
4f2138d7 1002 bool
e440a328 1003 do_discarding_value()
4f2138d7 1004 { return true; }
e440a328 1005
1006 Type*
1007 do_type();
1008
1009 void
1010 do_determine_type(const Type_context*);
1011
1012 Expression*
1013 do_copy()
1014 { return new Sink_expression(this->location()); }
1015
ea664253 1016 Bexpression*
1017 do_get_backend(Translate_context*);
e440a328 1018
d751bb78 1019 void
1020 do_dump_expression(Ast_dump_context*) const;
1021
e440a328 1022 private:
1023 // The type of this sink variable.
1024 Type* type_;
1025 // The temporary variable we generate.
aa93217a 1026 Bvariable* bvar_;
e440a328 1027};
1028
1029// Return the type of a sink expression.
1030
1031Type*
1032Sink_expression::do_type()
1033{
1034 if (this->type_ == NULL)
1035 return Type::make_sink_type();
1036 return this->type_;
1037}
1038
1039// Determine the type of a sink expression.
1040
1041void
1042Sink_expression::do_determine_type(const Type_context* context)
1043{
1044 if (context->type != NULL)
1045 this->type_ = context->type;
1046}
1047
1048// Return a temporary variable for a sink expression. This will
1049// presumably be a write-only variable which the middle-end will drop.
1050
ea664253 1051Bexpression*
1052Sink_expression::do_get_backend(Translate_context* context)
e440a328 1053{
aa93217a 1054 Location loc = this->location();
1055 Gogo* gogo = context->gogo();
1056 if (this->bvar_ == NULL)
e440a328 1057 {
c484d925 1058 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
aa93217a 1059 Named_object* fn = context->function();
1060 go_assert(fn != NULL);
1061 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
9f0e0513 1062 Btype* bt = this->type_->get_backend(context->gogo());
aa93217a 1063 Bstatement* decl;
1064 this->bvar_ =
1065 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1066 false, loc, &decl);
1067 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1068 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
ea664253 1069 return var_ref;
e440a328 1070 }
ea664253 1071 return gogo->backend()->var_expression(this->bvar_, loc);
e440a328 1072}
1073
d751bb78 1074// Ast dump for sink expression.
1075
1076void
1077Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1078{
1079 ast_dump_context->ostream() << "_" ;
1080}
1081
e440a328 1082// Make a sink expression.
1083
1084Expression*
b13c66cd 1085Expression::make_sink(Location location)
e440a328 1086{
1087 return new Sink_expression(location);
1088}
1089
1090// Class Func_expression.
1091
1092// FIXME: Can a function expression appear in a constant expression?
1093// The value is unchanging. Initializing a constant to the address of
1094// a function seems like it could work, though there might be little
1095// point to it.
1096
e440a328 1097// Traversal.
1098
1099int
1100Func_expression::do_traverse(Traverse* traverse)
1101{
1102 return (this->closure_ == NULL
1103 ? TRAVERSE_CONTINUE
1104 : Expression::traverse(&this->closure_, traverse));
1105}
1106
1107// Return the type of a function expression.
1108
1109Type*
1110Func_expression::do_type()
1111{
1112 if (this->function_->is_function())
1113 return this->function_->func_value()->type();
1114 else if (this->function_->is_function_declaration())
1115 return this->function_->func_declaration_value()->type();
1116 else
c3e6f413 1117 go_unreachable();
e440a328 1118}
1119
ea664253 1120// Get the backend representation for the code of a function expression.
e440a328 1121
97267c39 1122Bexpression*
8381eda7 1123Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1124{
1125 Function_type* fntype;
8381eda7 1126 if (no->is_function())
1127 fntype = no->func_value()->type();
1128 else if (no->is_function_declaration())
1129 fntype = no->func_declaration_value()->type();
e440a328 1130 else
c3e6f413 1131 go_unreachable();
e440a328 1132
1133 // Builtin functions are handled specially by Call_expression. We
1134 // can't take their address.
1135 if (fntype->is_builtin())
1136 {
631d5788 1137 go_error_at(loc,
1138 "invalid use of special builtin function %qs; must be called",
1139 no->message_name().c_str());
97267c39 1140 return gogo->backend()->error_expression();
e440a328 1141 }
1142
97267c39 1143 Bfunction* fndecl;
e440a328 1144 if (no->is_function())
cf3cae55 1145 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1146 else if (no->is_function_declaration())
cf3cae55 1147 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1148 else
c3e6f413 1149 go_unreachable();
e440a328 1150
97267c39 1151 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1152}
1153
ea664253 1154// Get the backend representation for a function expression. This is used when
1155// we take the address of a function rather than simply calling it. A func
8381eda7 1156// value is represented as a pointer to a block of memory. The first
1157// word of that memory is a pointer to the function code. The
1158// remaining parts of that memory are the addresses of variables that
1159// the function closes over.
e440a328 1160
ea664253 1161Bexpression*
1162Func_expression::do_get_backend(Translate_context* context)
e440a328 1163{
8381eda7 1164 // If there is no closure, just use the function descriptor.
2010c17a 1165 if (this->closure_ == NULL)
8381eda7 1166 {
1167 Gogo* gogo = context->gogo();
1168 Named_object* no = this->function_;
1169 Expression* descriptor;
1170 if (no->is_function())
1171 descriptor = no->func_value()->descriptor(gogo, no);
1172 else if (no->is_function_declaration())
1173 {
1174 if (no->func_declaration_value()->type()->is_builtin())
1175 {
631d5788 1176 go_error_at(this->location(),
1177 ("invalid use of special builtin function %qs; "
1178 "must be called"),
1179 no->message_name().c_str());
ea664253 1180 return gogo->backend()->error_expression();
8381eda7 1181 }
1182 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1183 }
1184 else
1185 go_unreachable();
2010c17a 1186
ea664253 1187 Bexpression* bdesc = descriptor->get_backend(context);
1188 return gogo->backend()->address_expression(bdesc, this->location());
8381eda7 1189 }
e440a328 1190
8381eda7 1191 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1192
8381eda7 1193 // If there is a closure, then the closure is itself the function
1194 // expression. It is a pointer to a struct whose first field points
1195 // to the function code and whose remaining fields are the addresses
1196 // of the closed-over variables.
ea664253 1197 return this->closure_->get_backend(context);
e440a328 1198}
1199
d751bb78 1200// Ast dump for function.
1201
1202void
1203Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1204{
8b1c301d 1205 ast_dump_context->ostream() << this->function_->name();
1206 if (this->closure_ != NULL)
1207 {
1208 ast_dump_context->ostream() << " {closure = ";
1209 this->closure_->dump_expression(ast_dump_context);
1210 ast_dump_context->ostream() << "}";
1211 }
d751bb78 1212}
1213
e440a328 1214// Make a reference to a function in an expression.
1215
1216Expression*
1217Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1218 Location location)
e440a328 1219{
b1d7ecfa 1220 Func_expression* fe = new Func_expression(function, closure, location);
1221
1222 // Detect references to builtin functions and set the runtime code if
1223 // appropriate.
1224 if (function->is_function_declaration())
1225 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1226 return fe;
e440a328 1227}
1228
c6837989 1229// Class Func_descriptor_expression.
8381eda7 1230
c6837989 1231// Constructor.
8381eda7 1232
c6837989 1233Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1234 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1235 fn_(fn), dvar_(NULL)
c6837989 1236{
1237 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1238}
8381eda7 1239
c6837989 1240// Traversal.
8381eda7 1241
c6837989 1242int
1243Func_descriptor_expression::do_traverse(Traverse*)
1244{
1245 return TRAVERSE_CONTINUE;
1246}
8381eda7 1247
1248// All function descriptors have the same type.
1249
1250Type* Func_descriptor_expression::descriptor_type;
1251
1252void
1253Func_descriptor_expression::make_func_descriptor_type()
1254{
1255 if (Func_descriptor_expression::descriptor_type != NULL)
1256 return;
1257 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1258 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1259 Func_descriptor_expression::descriptor_type =
1260 Type::make_builtin_named_type("functionDescriptor", struct_type);
1261}
1262
1263Type*
1264Func_descriptor_expression::do_type()
1265{
1266 Func_descriptor_expression::make_func_descriptor_type();
1267 return Func_descriptor_expression::descriptor_type;
1268}
1269
ea664253 1270// The backend representation for a function descriptor.
8381eda7 1271
ea664253 1272Bexpression*
1273Func_descriptor_expression::do_get_backend(Translate_context* context)
8381eda7 1274{
8381eda7 1275 Named_object* no = this->fn_;
1276 Location loc = no->location();
ea664253 1277 if (this->dvar_ != NULL)
1278 return context->backend()->var_expression(this->dvar_, loc);
8381eda7 1279
ea664253 1280 Gogo* gogo = context->gogo();
8381eda7 1281 std::string var_name;
09e57698 1282 bool is_descriptor = false;
1283 if (no->is_function_declaration()
1284 && !no->func_declaration_value()->asm_name().empty()
1285 && Linemap::is_predeclared_location(no->location()))
1286 {
6098d6cb 1287 if (no->func_declaration_value()->asm_name().substr(0, 8) != "runtime.")
1288 var_name = no->func_declaration_value()->asm_name() + "_descriptor";
1289 else
1290 var_name = no->func_declaration_value()->asm_name() + "$descriptor";
09e57698 1291 is_descriptor = true;
1292 }
8381eda7 1293 else
09e57698 1294 {
1295 if (no->package() == NULL)
1296 var_name = gogo->pkgpath_symbol();
1297 else
1298 var_name = no->package()->pkgpath_symbol();
1299 var_name.push_back('.');
1300 var_name.append(Gogo::unpack_hidden_name(no->name()));
1301 var_name.append("$descriptor");
1302 }
8381eda7 1303
1304 Btype* btype = this->type()->get_backend(gogo);
1305
1306 Bvariable* bvar;
09e57698 1307 if (no->package() != NULL || is_descriptor)
f8bdf81a 1308 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1309 loc);
8381eda7 1310 else
1311 {
1312 Location bloc = Linemap::predeclared_location();
1313 bool is_hidden = ((no->is_function()
1314 && no->func_value()->enclosing() != NULL)
1315 || Gogo::is_thunk(no));
1316 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1317 btype, bloc);
1318 Expression_list* vals = new Expression_list();
f8bdf81a 1319 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1320 Expression* init =
1321 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1322 Translate_context bcontext(gogo, NULL, NULL, NULL);
1323 bcontext.set_is_const();
ea664253 1324 Bexpression* binit = init->get_backend(&bcontext);
8381eda7 1325 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1326 false, btype, bloc, binit);
1327 }
1328
1329 this->dvar_ = bvar;
ea664253 1330 return gogo->backend()->var_expression(bvar, loc);
8381eda7 1331}
1332
c6837989 1333// Print a function descriptor expression.
1334
1335void
1336Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1337{
1338 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1339}
1340
8381eda7 1341// Make a function descriptor expression.
1342
c6837989 1343Func_descriptor_expression*
1344Expression::make_func_descriptor(Named_object* fn)
8381eda7 1345{
c6837989 1346 return new Func_descriptor_expression(fn);
8381eda7 1347}
1348
1349// Make the function descriptor type, so that it can be converted.
1350
1351void
1352Expression::make_func_descriptor_type()
1353{
1354 Func_descriptor_expression::make_func_descriptor_type();
1355}
1356
1357// A reference to just the code of a function.
1358
1359class Func_code_reference_expression : public Expression
1360{
1361 public:
1362 Func_code_reference_expression(Named_object* function, Location location)
1363 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1364 function_(function)
1365 { }
1366
1367 protected:
1368 int
1369 do_traverse(Traverse*)
1370 { return TRAVERSE_CONTINUE; }
1371
f9ca30f9 1372 bool
3ae06f68 1373 do_is_static_initializer() const
f9ca30f9 1374 { return true; }
1375
8381eda7 1376 Type*
1377 do_type()
1378 { return Type::make_pointer_type(Type::make_void_type()); }
1379
1380 void
1381 do_determine_type(const Type_context*)
1382 { }
1383
1384 Expression*
1385 do_copy()
1386 {
1387 return Expression::make_func_code_reference(this->function_,
1388 this->location());
1389 }
1390
ea664253 1391 Bexpression*
1392 do_get_backend(Translate_context*);
8381eda7 1393
1394 void
1395 do_dump_expression(Ast_dump_context* context) const
1396 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1397
1398 private:
1399 // The function.
1400 Named_object* function_;
1401};
1402
ea664253 1403// Get the backend representation for a reference to function code.
8381eda7 1404
ea664253 1405Bexpression*
1406Func_code_reference_expression::do_get_backend(Translate_context* context)
8381eda7 1407{
ea664253 1408 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1409 this->location());
8381eda7 1410}
1411
1412// Make a reference to the code of a function.
1413
1414Expression*
1415Expression::make_func_code_reference(Named_object* function, Location location)
1416{
1417 return new Func_code_reference_expression(function, location);
1418}
1419
e440a328 1420// Class Unknown_expression.
1421
1422// Return the name of an unknown expression.
1423
1424const std::string&
1425Unknown_expression::name() const
1426{
1427 return this->named_object_->name();
1428}
1429
1430// Lower a reference to an unknown name.
1431
1432Expression*
ceeb4318 1433Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1434{
b13c66cd 1435 Location location = this->location();
e440a328 1436 Named_object* no = this->named_object_;
deded542 1437 Named_object* real;
1438 if (!no->is_unknown())
1439 real = no;
1440 else
e440a328 1441 {
deded542 1442 real = no->unknown_value()->real_named_object();
1443 if (real == NULL)
1444 {
1445 if (this->is_composite_literal_key_)
1446 return this;
acf8e158 1447 if (!this->no_error_message_)
631d5788 1448 go_error_at(location, "reference to undefined name %qs",
1449 this->named_object_->message_name().c_str());
deded542 1450 return Expression::make_error(location);
1451 }
e440a328 1452 }
1453 switch (real->classification())
1454 {
1455 case Named_object::NAMED_OBJECT_CONST:
1456 return Expression::make_const_reference(real, location);
1457 case Named_object::NAMED_OBJECT_TYPE:
1458 return Expression::make_type(real->type_value(), location);
1459 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1460 if (this->is_composite_literal_key_)
1461 return this;
acf8e158 1462 if (!this->no_error_message_)
631d5788 1463 go_error_at(location, "reference to undefined type %qs",
1464 real->message_name().c_str());
e440a328 1465 return Expression::make_error(location);
1466 case Named_object::NAMED_OBJECT_VAR:
7d834090 1467 real->var_value()->set_is_used();
e440a328 1468 return Expression::make_var_reference(real, location);
1469 case Named_object::NAMED_OBJECT_FUNC:
1470 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1471 return Expression::make_func_reference(real, NULL, location);
1472 case Named_object::NAMED_OBJECT_PACKAGE:
1473 if (this->is_composite_literal_key_)
1474 return this;
acf8e158 1475 if (!this->no_error_message_)
631d5788 1476 go_error_at(location, "unexpected reference to package");
e440a328 1477 return Expression::make_error(location);
1478 default:
c3e6f413 1479 go_unreachable();
e440a328 1480 }
1481}
1482
d751bb78 1483// Dump the ast representation for an unknown expression to a dump context.
1484
1485void
1486Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1487{
1488 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1489 << ")";
d751bb78 1490}
1491
e440a328 1492// Make a reference to an unknown name.
1493
acf8e158 1494Unknown_expression*
b13c66cd 1495Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1496{
e440a328 1497 return new Unknown_expression(no, location);
1498}
1499
1500// A boolean expression.
1501
1502class Boolean_expression : public Expression
1503{
1504 public:
b13c66cd 1505 Boolean_expression(bool val, Location location)
e440a328 1506 : Expression(EXPRESSION_BOOLEAN, location),
1507 val_(val), type_(NULL)
1508 { }
1509
1510 static Expression*
1511 do_import(Import*);
1512
1513 protected:
1514 bool
1515 do_is_constant() const
1516 { return true; }
1517
0e168074 1518 bool
3ae06f68 1519 do_is_static_initializer() const
0e168074 1520 { return true; }
1521
e440a328 1522 Type*
1523 do_type();
1524
1525 void
1526 do_determine_type(const Type_context*);
1527
1528 Expression*
1529 do_copy()
1530 { return this; }
1531
ea664253 1532 Bexpression*
1533 do_get_backend(Translate_context* context)
1534 { return context->backend()->boolean_constant_expression(this->val_); }
e440a328 1535
1536 void
1537 do_export(Export* exp) const
1538 { exp->write_c_string(this->val_ ? "true" : "false"); }
1539
d751bb78 1540 void
1541 do_dump_expression(Ast_dump_context* ast_dump_context) const
1542 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1543
e440a328 1544 private:
1545 // The constant.
1546 bool val_;
1547 // The type as determined by context.
1548 Type* type_;
1549};
1550
1551// Get the type.
1552
1553Type*
1554Boolean_expression::do_type()
1555{
1556 if (this->type_ == NULL)
1557 this->type_ = Type::make_boolean_type();
1558 return this->type_;
1559}
1560
1561// Set the type from the context.
1562
1563void
1564Boolean_expression::do_determine_type(const Type_context* context)
1565{
1566 if (this->type_ != NULL && !this->type_->is_abstract())
1567 ;
1568 else if (context->type != NULL && context->type->is_boolean_type())
1569 this->type_ = context->type;
1570 else if (!context->may_be_abstract)
1571 this->type_ = Type::lookup_bool_type();
1572}
1573
1574// Import a boolean constant.
1575
1576Expression*
1577Boolean_expression::do_import(Import* imp)
1578{
1579 if (imp->peek_char() == 't')
1580 {
1581 imp->require_c_string("true");
1582 return Expression::make_boolean(true, imp->location());
1583 }
1584 else
1585 {
1586 imp->require_c_string("false");
1587 return Expression::make_boolean(false, imp->location());
1588 }
1589}
1590
1591// Make a boolean expression.
1592
1593Expression*
b13c66cd 1594Expression::make_boolean(bool val, Location location)
e440a328 1595{
1596 return new Boolean_expression(val, location);
1597}
1598
1599// Class String_expression.
1600
1601// Get the type.
1602
1603Type*
1604String_expression::do_type()
1605{
1606 if (this->type_ == NULL)
1607 this->type_ = Type::make_string_type();
1608 return this->type_;
1609}
1610
1611// Set the type from the context.
1612
1613void
1614String_expression::do_determine_type(const Type_context* context)
1615{
1616 if (this->type_ != NULL && !this->type_->is_abstract())
1617 ;
1618 else if (context->type != NULL && context->type->is_string_type())
1619 this->type_ = context->type;
1620 else if (!context->may_be_abstract)
1621 this->type_ = Type::lookup_string_type();
1622}
1623
1624// Build a string constant.
1625
ea664253 1626Bexpression*
1627String_expression::do_get_backend(Translate_context* context)
e440a328 1628{
2c809f8f 1629 Gogo* gogo = context->gogo();
1630 Btype* btype = Type::make_string_type()->get_backend(gogo);
1631
1632 Location loc = this->location();
1633 std::vector<Bexpression*> init(2);
1634 Bexpression* str_cst =
1635 gogo->backend()->string_constant_expression(this->val_);
1636 init[0] = gogo->backend()->address_expression(str_cst, loc);
1637
1638 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1639 mpz_t lenval;
1640 mpz_init_set_ui(lenval, this->val_.length());
1641 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1642 mpz_clear(lenval);
1643
ea664253 1644 return gogo->backend()->constructor_expression(btype, init, loc);
e440a328 1645}
1646
8b1c301d 1647 // Write string literal to string dump.
e440a328 1648
1649void
8b1c301d 1650String_expression::export_string(String_dump* exp,
1651 const String_expression* str)
e440a328 1652{
1653 std::string s;
8b1c301d 1654 s.reserve(str->val_.length() * 4 + 2);
e440a328 1655 s += '"';
8b1c301d 1656 for (std::string::const_iterator p = str->val_.begin();
1657 p != str->val_.end();
e440a328 1658 ++p)
1659 {
1660 if (*p == '\\' || *p == '"')
1661 {
1662 s += '\\';
1663 s += *p;
1664 }
1665 else if (*p >= 0x20 && *p < 0x7f)
1666 s += *p;
1667 else if (*p == '\n')
1668 s += "\\n";
1669 else if (*p == '\t')
1670 s += "\\t";
1671 else
1672 {
1673 s += "\\x";
1674 unsigned char c = *p;
1675 unsigned int dig = c >> 4;
1676 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1677 dig = c & 0xf;
1678 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1679 }
1680 }
1681 s += '"';
1682 exp->write_string(s);
1683}
1684
8b1c301d 1685// Export a string expression.
1686
1687void
1688String_expression::do_export(Export* exp) const
1689{
1690 String_expression::export_string(exp, this);
1691}
1692
e440a328 1693// Import a string expression.
1694
1695Expression*
1696String_expression::do_import(Import* imp)
1697{
1698 imp->require_c_string("\"");
1699 std::string val;
1700 while (true)
1701 {
1702 int c = imp->get_char();
1703 if (c == '"' || c == -1)
1704 break;
1705 if (c != '\\')
1706 val += static_cast<char>(c);
1707 else
1708 {
1709 c = imp->get_char();
1710 if (c == '\\' || c == '"')
1711 val += static_cast<char>(c);
1712 else if (c == 'n')
1713 val += '\n';
1714 else if (c == 't')
1715 val += '\t';
1716 else if (c == 'x')
1717 {
1718 c = imp->get_char();
1719 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1720 c = imp->get_char();
1721 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1722 char v = (vh << 4) | vl;
1723 val += v;
1724 }
1725 else
1726 {
631d5788 1727 go_error_at(imp->location(), "bad string constant");
e440a328 1728 return Expression::make_error(imp->location());
1729 }
1730 }
1731 }
1732 return Expression::make_string(val, imp->location());
1733}
1734
d751bb78 1735// Ast dump for string expression.
1736
1737void
1738String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1739{
8b1c301d 1740 String_expression::export_string(ast_dump_context, this);
d751bb78 1741}
1742
e440a328 1743// Make a string expression.
1744
1745Expression*
b13c66cd 1746Expression::make_string(const std::string& val, Location location)
e440a328 1747{
1748 return new String_expression(val, location);
1749}
1750
2c809f8f 1751// An expression that evaluates to some characteristic of a string.
1752// This is used when indexing, bound-checking, or nil checking a string.
1753
1754class String_info_expression : public Expression
1755{
1756 public:
1757 String_info_expression(Expression* string, String_info string_info,
1758 Location location)
1759 : Expression(EXPRESSION_STRING_INFO, location),
1760 string_(string), string_info_(string_info)
1761 { }
1762
1763 protected:
1764 Type*
1765 do_type();
1766
1767 void
1768 do_determine_type(const Type_context*)
1769 { go_unreachable(); }
1770
1771 Expression*
1772 do_copy()
1773 {
1774 return new String_info_expression(this->string_->copy(), this->string_info_,
1775 this->location());
1776 }
1777
ea664253 1778 Bexpression*
1779 do_get_backend(Translate_context* context);
2c809f8f 1780
1781 void
1782 do_dump_expression(Ast_dump_context*) const;
1783
1784 void
1785 do_issue_nil_check()
1786 { this->string_->issue_nil_check(); }
1787
1788 private:
1789 // The string for which we are getting information.
1790 Expression* string_;
1791 // What information we want.
1792 String_info string_info_;
1793};
1794
1795// Return the type of the string info.
1796
1797Type*
1798String_info_expression::do_type()
1799{
1800 switch (this->string_info_)
1801 {
1802 case STRING_INFO_DATA:
1803 {
1804 Type* byte_type = Type::lookup_integer_type("uint8");
1805 return Type::make_pointer_type(byte_type);
1806 }
1807 case STRING_INFO_LENGTH:
1808 return Type::lookup_integer_type("int");
1809 default:
1810 go_unreachable();
1811 }
1812}
1813
1814// Return string information in GENERIC.
1815
ea664253 1816Bexpression*
1817String_info_expression::do_get_backend(Translate_context* context)
2c809f8f 1818{
1819 Gogo* gogo = context->gogo();
1820
ea664253 1821 Bexpression* bstring = this->string_->get_backend(context);
2c809f8f 1822 switch (this->string_info_)
1823 {
1824 case STRING_INFO_DATA:
1825 case STRING_INFO_LENGTH:
ea664253 1826 return gogo->backend()->struct_field_expression(bstring,
1827 this->string_info_,
1828 this->location());
2c809f8f 1829 break;
1830 default:
1831 go_unreachable();
1832 }
2c809f8f 1833}
1834
1835// Dump ast representation for a type info expression.
1836
1837void
1838String_info_expression::do_dump_expression(
1839 Ast_dump_context* ast_dump_context) const
1840{
1841 ast_dump_context->ostream() << "stringinfo(";
1842 this->string_->dump_expression(ast_dump_context);
1843 ast_dump_context->ostream() << ",";
1844 ast_dump_context->ostream() <<
1845 (this->string_info_ == STRING_INFO_DATA ? "data"
1846 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1847 : "unknown");
1848 ast_dump_context->ostream() << ")";
1849}
1850
1851// Make a string info expression.
1852
1853Expression*
1854Expression::make_string_info(Expression* string, String_info string_info,
1855 Location location)
1856{
1857 return new String_info_expression(string, string_info, location);
1858}
1859
e440a328 1860// Make an integer expression.
1861
1862class Integer_expression : public Expression
1863{
1864 public:
5d4b8566 1865 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1866 Location location)
e440a328 1867 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1868 type_(type), is_character_constant_(is_character_constant)
e440a328 1869 { mpz_init_set(this->val_, *val); }
1870
1871 static Expression*
1872 do_import(Import*);
1873
8b1c301d 1874 // Write VAL to string dump.
e440a328 1875 static void
8b1c301d 1876 export_integer(String_dump* exp, const mpz_t val);
e440a328 1877
d751bb78 1878 // Write VAL to dump context.
1879 static void
1880 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1881
e440a328 1882 protected:
1883 bool
1884 do_is_constant() const
1885 { return true; }
1886
0e168074 1887 bool
3ae06f68 1888 do_is_static_initializer() const
0e168074 1889 { return true; }
1890
e440a328 1891 bool
0c77715b 1892 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1893
1894 Type*
1895 do_type();
1896
1897 void
1898 do_determine_type(const Type_context* context);
1899
1900 void
1901 do_check_types(Gogo*);
1902
ea664253 1903 Bexpression*
1904 do_get_backend(Translate_context*);
e440a328 1905
1906 Expression*
1907 do_copy()
5d4b8566 1908 {
1909 if (this->is_character_constant_)
1910 return Expression::make_character(&this->val_, this->type_,
1911 this->location());
1912 else
e67508fa 1913 return Expression::make_integer_z(&this->val_, this->type_,
1914 this->location());
5d4b8566 1915 }
e440a328 1916
1917 void
1918 do_export(Export*) const;
1919
d751bb78 1920 void
1921 do_dump_expression(Ast_dump_context*) const;
1922
e440a328 1923 private:
1924 // The integer value.
1925 mpz_t val_;
1926 // The type so far.
1927 Type* type_;
5d4b8566 1928 // Whether this is a character constant.
1929 bool is_character_constant_;
e440a328 1930};
1931
0c77715b 1932// Return a numeric constant for this expression. We have to mark
1933// this as a character when appropriate.
e440a328 1934
1935bool
0c77715b 1936Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1937{
0c77715b 1938 if (this->is_character_constant_)
1939 nc->set_rune(this->type_, this->val_);
1940 else
1941 nc->set_int(this->type_, this->val_);
e440a328 1942 return true;
1943}
1944
1945// Return the current type. If we haven't set the type yet, we return
1946// an abstract integer type.
1947
1948Type*
1949Integer_expression::do_type()
1950{
1951 if (this->type_ == NULL)
5d4b8566 1952 {
1953 if (this->is_character_constant_)
1954 this->type_ = Type::make_abstract_character_type();
1955 else
1956 this->type_ = Type::make_abstract_integer_type();
1957 }
e440a328 1958 return this->type_;
1959}
1960
1961// Set the type of the integer value. Here we may switch from an
1962// abstract type to a real type.
1963
1964void
1965Integer_expression::do_determine_type(const Type_context* context)
1966{
1967 if (this->type_ != NULL && !this->type_->is_abstract())
1968 ;
0c77715b 1969 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1970 this->type_ = context->type;
1971 else if (!context->may_be_abstract)
5d4b8566 1972 {
1973 if (this->is_character_constant_)
1974 this->type_ = Type::lookup_integer_type("int32");
1975 else
1976 this->type_ = Type::lookup_integer_type("int");
1977 }
e440a328 1978}
1979
e440a328 1980// Check the type of an integer constant.
1981
1982void
1983Integer_expression::do_check_types(Gogo*)
1984{
0c77715b 1985 Type* type = this->type_;
1986 if (type == NULL)
e440a328 1987 return;
0c77715b 1988 Numeric_constant nc;
1989 if (this->is_character_constant_)
1990 nc.set_rune(NULL, this->val_);
1991 else
1992 nc.set_int(NULL, this->val_);
1993 if (!nc.set_type(type, true, this->location()))
e440a328 1994 this->set_is_error();
1995}
1996
ea664253 1997// Get the backend representation for an integer constant.
e440a328 1998
ea664253 1999Bexpression*
2000Integer_expression::do_get_backend(Translate_context* context)
e440a328 2001{
12373dd5 2002 if (this->is_error_expression()
2003 || (this->type_ != NULL && this->type_->is_error_type()))
2004 {
2005 go_assert(saw_errors());
2006 return context->gogo()->backend()->error_expression();
2007 }
2008
48c2a53a 2009 Type* resolved_type = NULL;
e440a328 2010 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2011 resolved_type = this->type_;
e440a328 2012 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2013 {
2014 // We are converting to an abstract floating point type.
48c2a53a 2015 resolved_type = Type::lookup_float_type("float64");
e440a328 2016 }
2017 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2018 {
2019 // We are converting to an abstract complex type.
48c2a53a 2020 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2021 }
2022 else
2023 {
2024 // If we still have an abstract type here, then this is being
2025 // used in a constant expression which didn't get reduced for
2026 // some reason. Use a type which will fit the value. We use <,
2027 // not <=, because we need an extra bit for the sign bit.
2028 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 2029 Type* int_type = Type::lookup_integer_type("int");
2030 if (bits < int_type->integer_type()->bits())
48c2a53a 2031 resolved_type = int_type;
e440a328 2032 else if (bits < 64)
48c2a53a 2033 resolved_type = Type::lookup_integer_type("int64");
e440a328 2034 else
48c2a53a 2035 {
2036 if (!saw_errors())
631d5788 2037 go_error_at(this->location(),
2038 "unknown type for large integer constant");
ea664253 2039 return context->gogo()->backend()->error_expression();
48c2a53a 2040 }
e440a328 2041 }
48c2a53a 2042 Numeric_constant nc;
2043 nc.set_int(resolved_type, this->val_);
ea664253 2044 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2045}
2046
2047// Write VAL to export data.
2048
2049void
8b1c301d 2050Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 2051{
2052 char* s = mpz_get_str(NULL, 10, val);
2053 exp->write_c_string(s);
2054 free(s);
2055}
2056
2057// Export an integer in a constant expression.
2058
2059void
2060Integer_expression::do_export(Export* exp) const
2061{
2062 Integer_expression::export_integer(exp, this->val_);
5d4b8566 2063 if (this->is_character_constant_)
2064 exp->write_c_string("'");
e440a328 2065 // A trailing space lets us reliably identify the end of the number.
2066 exp->write_c_string(" ");
2067}
2068
2069// Import an integer, floating point, or complex value. This handles
2070// all these types because they all start with digits.
2071
2072Expression*
2073Integer_expression::do_import(Import* imp)
2074{
2075 std::string num = imp->read_identifier();
2076 imp->require_c_string(" ");
2077 if (!num.empty() && num[num.length() - 1] == 'i')
2078 {
2079 mpfr_t real;
2080 size_t plus_pos = num.find('+', 1);
2081 size_t minus_pos = num.find('-', 1);
2082 size_t pos;
2083 if (plus_pos == std::string::npos)
2084 pos = minus_pos;
2085 else if (minus_pos == std::string::npos)
2086 pos = plus_pos;
2087 else
2088 {
631d5788 2089 go_error_at(imp->location(), "bad number in import data: %qs",
2090 num.c_str());
e440a328 2091 return Expression::make_error(imp->location());
2092 }
2093 if (pos == std::string::npos)
2094 mpfr_set_ui(real, 0, GMP_RNDN);
2095 else
2096 {
2097 std::string real_str = num.substr(0, pos);
2098 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2099 {
631d5788 2100 go_error_at(imp->location(), "bad number in import data: %qs",
2101 real_str.c_str());
e440a328 2102 return Expression::make_error(imp->location());
2103 }
2104 }
2105
2106 std::string imag_str;
2107 if (pos == std::string::npos)
2108 imag_str = num;
2109 else
2110 imag_str = num.substr(pos);
2111 imag_str = imag_str.substr(0, imag_str.size() - 1);
2112 mpfr_t imag;
2113 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2114 {
631d5788 2115 go_error_at(imp->location(), "bad number in import data: %qs",
2116 imag_str.c_str());
e440a328 2117 return Expression::make_error(imp->location());
2118 }
fcbea5e4 2119 mpc_t cval;
2120 mpc_init2(cval, mpc_precision);
2121 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
e440a328 2122 mpfr_clear(real);
2123 mpfr_clear(imag);
fcbea5e4 2124 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2125 mpc_clear(cval);
e440a328 2126 return ret;
2127 }
2128 else if (num.find('.') == std::string::npos
2129 && num.find('E') == std::string::npos)
2130 {
5d4b8566 2131 bool is_character_constant = (!num.empty()
2132 && num[num.length() - 1] == '\'');
2133 if (is_character_constant)
2134 num = num.substr(0, num.length() - 1);
e440a328 2135 mpz_t val;
2136 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2137 {
631d5788 2138 go_error_at(imp->location(), "bad number in import data: %qs",
2139 num.c_str());
e440a328 2140 return Expression::make_error(imp->location());
2141 }
5d4b8566 2142 Expression* ret;
2143 if (is_character_constant)
2144 ret = Expression::make_character(&val, NULL, imp->location());
2145 else
e67508fa 2146 ret = Expression::make_integer_z(&val, NULL, imp->location());
e440a328 2147 mpz_clear(val);
2148 return ret;
2149 }
2150 else
2151 {
2152 mpfr_t val;
2153 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2154 {
631d5788 2155 go_error_at(imp->location(), "bad number in import data: %qs",
2156 num.c_str());
e440a328 2157 return Expression::make_error(imp->location());
2158 }
2159 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2160 mpfr_clear(val);
2161 return ret;
2162 }
2163}
d751bb78 2164// Ast dump for integer expression.
2165
2166void
2167Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2168{
5d4b8566 2169 if (this->is_character_constant_)
2170 ast_dump_context->ostream() << '\'';
8b1c301d 2171 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2172 if (this->is_character_constant_)
2173 ast_dump_context->ostream() << '\'';
d751bb78 2174}
2175
e67508fa 2176// Build a new integer value from a multi-precision integer.
e440a328 2177
2178Expression*
e67508fa 2179Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
5d4b8566 2180{
2181 return new Integer_expression(val, type, false, location);
2182}
2183
e67508fa 2184// Build a new integer value from an unsigned long.
2185
2186Expression*
2187Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2188{
2189 mpz_t zval;
2190 mpz_init_set_ui(zval, val);
2191 Expression* ret = Expression::make_integer_z(&zval, type, location);
2192 mpz_clear(zval);
2193 return ret;
2194}
2195
2196// Build a new integer value from a signed long.
2197
2198Expression*
2199Expression::make_integer_sl(long val, Type *type, Location location)
2200{
2201 mpz_t zval;
2202 mpz_init_set_si(zval, val);
2203 Expression* ret = Expression::make_integer_z(&zval, type, location);
2204 mpz_clear(zval);
2205 return ret;
2206}
2207
3f378015 2208// Store an int64_t in an uninitialized mpz_t.
2209
2210static void
2211set_mpz_from_int64(mpz_t* zval, int64_t val)
2212{
2213 if (val >= 0)
2214 {
2215 unsigned long ul = static_cast<unsigned long>(val);
2216 if (static_cast<int64_t>(ul) == val)
2217 {
2218 mpz_init_set_ui(*zval, ul);
2219 return;
2220 }
2221 }
2222 uint64_t uv;
2223 if (val >= 0)
2224 uv = static_cast<uint64_t>(val);
2225 else
2226 uv = static_cast<uint64_t>(- val);
2227 unsigned long ul = uv & 0xffffffffUL;
2228 mpz_init_set_ui(*zval, ul);
2229 mpz_t hval;
2230 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2231 mpz_mul_2exp(hval, hval, 32);
2232 mpz_add(*zval, *zval, hval);
2233 mpz_clear(hval);
2234 if (val < 0)
2235 mpz_neg(*zval, *zval);
2236}
2237
2238// Build a new integer value from an int64_t.
2239
2240Expression*
2241Expression::make_integer_int64(int64_t val, Type* type, Location location)
2242{
2243 mpz_t zval;
2244 set_mpz_from_int64(&zval, val);
2245 Expression* ret = Expression::make_integer_z(&zval, type, location);
2246 mpz_clear(zval);
2247 return ret;
2248}
2249
5d4b8566 2250// Build a new character constant value.
2251
2252Expression*
2253Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2254{
5d4b8566 2255 return new Integer_expression(val, type, true, location);
e440a328 2256}
2257
2258// Floats.
2259
2260class Float_expression : public Expression
2261{
2262 public:
b13c66cd 2263 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2264 : Expression(EXPRESSION_FLOAT, location),
2265 type_(type)
2266 {
2267 mpfr_init_set(this->val_, *val, GMP_RNDN);
2268 }
2269
e440a328 2270 // Write VAL to export data.
2271 static void
8b1c301d 2272 export_float(String_dump* exp, const mpfr_t val);
2273
d751bb78 2274 // Write VAL to dump file.
2275 static void
2276 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2277
2278 protected:
2279 bool
2280 do_is_constant() const
2281 { return true; }
2282
0e168074 2283 bool
3ae06f68 2284 do_is_static_initializer() const
0e168074 2285 { return true; }
2286
e440a328 2287 bool
0c77715b 2288 do_numeric_constant_value(Numeric_constant* nc) const
2289 {
2290 nc->set_float(this->type_, this->val_);
2291 return true;
2292 }
e440a328 2293
2294 Type*
2295 do_type();
2296
2297 void
2298 do_determine_type(const Type_context*);
2299
2300 void
2301 do_check_types(Gogo*);
2302
2303 Expression*
2304 do_copy()
2305 { return Expression::make_float(&this->val_, this->type_,
2306 this->location()); }
2307
ea664253 2308 Bexpression*
2309 do_get_backend(Translate_context*);
e440a328 2310
2311 void
2312 do_export(Export*) const;
2313
d751bb78 2314 void
2315 do_dump_expression(Ast_dump_context*) const;
2316
e440a328 2317 private:
2318 // The floating point value.
2319 mpfr_t val_;
2320 // The type so far.
2321 Type* type_;
2322};
2323
e440a328 2324// Return the current type. If we haven't set the type yet, we return
2325// an abstract float type.
2326
2327Type*
2328Float_expression::do_type()
2329{
2330 if (this->type_ == NULL)
2331 this->type_ = Type::make_abstract_float_type();
2332 return this->type_;
2333}
2334
2335// Set the type of the float value. Here we may switch from an
2336// abstract type to a real type.
2337
2338void
2339Float_expression::do_determine_type(const Type_context* context)
2340{
2341 if (this->type_ != NULL && !this->type_->is_abstract())
2342 ;
2343 else if (context->type != NULL
2344 && (context->type->integer_type() != NULL
2345 || context->type->float_type() != NULL
2346 || context->type->complex_type() != NULL))
2347 this->type_ = context->type;
2348 else if (!context->may_be_abstract)
48080209 2349 this->type_ = Type::lookup_float_type("float64");
e440a328 2350}
2351
e440a328 2352// Check the type of a float value.
2353
2354void
2355Float_expression::do_check_types(Gogo*)
2356{
0c77715b 2357 Type* type = this->type_;
2358 if (type == NULL)
e440a328 2359 return;
0c77715b 2360 Numeric_constant nc;
2361 nc.set_float(NULL, this->val_);
2362 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2363 this->set_is_error();
e440a328 2364}
2365
ea664253 2366// Get the backend representation for a float constant.
e440a328 2367
ea664253 2368Bexpression*
2369Float_expression::do_get_backend(Translate_context* context)
e440a328 2370{
12373dd5 2371 if (this->is_error_expression()
2372 || (this->type_ != NULL && this->type_->is_error_type()))
2373 {
2374 go_assert(saw_errors());
2375 return context->gogo()->backend()->error_expression();
2376 }
2377
48c2a53a 2378 Type* resolved_type;
e440a328 2379 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2380 resolved_type = this->type_;
e440a328 2381 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2382 {
2383 // We have an abstract integer type. We just hope for the best.
48c2a53a 2384 resolved_type = Type::lookup_integer_type("int");
2385 }
2386 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2387 {
2388 // We are converting to an abstract complex type.
2389 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2390 }
2391 else
2392 {
2393 // If we still have an abstract type here, then this is being
2394 // used in a constant expression which didn't get reduced. We
2395 // just use float64 and hope for the best.
48c2a53a 2396 resolved_type = Type::lookup_float_type("float64");
e440a328 2397 }
48c2a53a 2398
2399 Numeric_constant nc;
2400 nc.set_float(resolved_type, this->val_);
ea664253 2401 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2402}
2403
8b1c301d 2404// Write a floating point number to a string dump.
e440a328 2405
2406void
8b1c301d 2407Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2408{
2409 mp_exp_t exponent;
2410 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2411 if (*s == '-')
2412 exp->write_c_string("-");
2413 exp->write_c_string("0.");
2414 exp->write_c_string(*s == '-' ? s + 1 : s);
2415 mpfr_free_str(s);
2416 char buf[30];
2417 snprintf(buf, sizeof buf, "E%ld", exponent);
2418 exp->write_c_string(buf);
2419}
2420
2421// Export a floating point number in a constant expression.
2422
2423void
2424Float_expression::do_export(Export* exp) const
2425{
2426 Float_expression::export_float(exp, this->val_);
2427 // A trailing space lets us reliably identify the end of the number.
2428 exp->write_c_string(" ");
2429}
2430
d751bb78 2431// Dump a floating point number to the dump file.
2432
2433void
2434Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2435{
8b1c301d 2436 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2437}
2438
e440a328 2439// Make a float expression.
2440
2441Expression*
b13c66cd 2442Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2443{
2444 return new Float_expression(val, type, location);
2445}
2446
2447// Complex numbers.
2448
2449class Complex_expression : public Expression
2450{
2451 public:
fcbea5e4 2452 Complex_expression(const mpc_t* val, Type* type, Location location)
e440a328 2453 : Expression(EXPRESSION_COMPLEX, location),
2454 type_(type)
2455 {
fcbea5e4 2456 mpc_init2(this->val_, mpc_precision);
2457 mpc_set(this->val_, *val, MPC_RNDNN);
e440a328 2458 }
2459
fcbea5e4 2460 // Write VAL to string dump.
e440a328 2461 static void
fcbea5e4 2462 export_complex(String_dump* exp, const mpc_t val);
e440a328 2463
d751bb78 2464 // Write REAL/IMAG to dump context.
2465 static void
fcbea5e4 2466 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
d751bb78 2467
e440a328 2468 protected:
2469 bool
2470 do_is_constant() const
2471 { return true; }
2472
0e168074 2473 bool
3ae06f68 2474 do_is_static_initializer() const
0e168074 2475 { return true; }
2476
e440a328 2477 bool
0c77715b 2478 do_numeric_constant_value(Numeric_constant* nc) const
2479 {
fcbea5e4 2480 nc->set_complex(this->type_, this->val_);
0c77715b 2481 return true;
2482 }
e440a328 2483
2484 Type*
2485 do_type();
2486
2487 void
2488 do_determine_type(const Type_context*);
2489
2490 void
2491 do_check_types(Gogo*);
2492
2493 Expression*
2494 do_copy()
2495 {
fcbea5e4 2496 return Expression::make_complex(&this->val_, this->type_,
e440a328 2497 this->location());
2498 }
2499
ea664253 2500 Bexpression*
2501 do_get_backend(Translate_context*);
e440a328 2502
2503 void
2504 do_export(Export*) const;
2505
d751bb78 2506 void
2507 do_dump_expression(Ast_dump_context*) const;
abd26de0 2508
e440a328 2509 private:
fcbea5e4 2510 // The complex value.
2511 mpc_t val_;
e440a328 2512 // The type if known.
2513 Type* type_;
2514};
2515
e440a328 2516// Return the current type. If we haven't set the type yet, we return
2517// an abstract complex type.
2518
2519Type*
2520Complex_expression::do_type()
2521{
2522 if (this->type_ == NULL)
2523 this->type_ = Type::make_abstract_complex_type();
2524 return this->type_;
2525}
2526
2527// Set the type of the complex value. Here we may switch from an
2528// abstract type to a real type.
2529
2530void
2531Complex_expression::do_determine_type(const Type_context* context)
2532{
2533 if (this->type_ != NULL && !this->type_->is_abstract())
2534 ;
abd26de0 2535 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 2536 this->type_ = context->type;
2537 else if (!context->may_be_abstract)
48080209 2538 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2539}
2540
e440a328 2541// Check the type of a complex value.
2542
2543void
2544Complex_expression::do_check_types(Gogo*)
2545{
0c77715b 2546 Type* type = this->type_;
2547 if (type == NULL)
e440a328 2548 return;
0c77715b 2549 Numeric_constant nc;
fcbea5e4 2550 nc.set_complex(NULL, this->val_);
0c77715b 2551 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2552 this->set_is_error();
2553}
2554
ea664253 2555// Get the backend representation for a complex constant.
e440a328 2556
ea664253 2557Bexpression*
2558Complex_expression::do_get_backend(Translate_context* context)
e440a328 2559{
12373dd5 2560 if (this->is_error_expression()
2561 || (this->type_ != NULL && this->type_->is_error_type()))
2562 {
2563 go_assert(saw_errors());
2564 return context->gogo()->backend()->error_expression();
2565 }
2566
48c2a53a 2567 Type* resolved_type;
e440a328 2568 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2569 resolved_type = this->type_;
2570 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2571 {
2572 // We are converting to an abstract integer type.
2573 resolved_type = Type::lookup_integer_type("int");
2574 }
2575 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2576 {
2577 // We are converting to an abstract float type.
2578 resolved_type = Type::lookup_float_type("float64");
2579 }
e440a328 2580 else
2581 {
47ae02b7 2582 // If we still have an abstract type here, this is being
e440a328 2583 // used in a constant expression which didn't get reduced. We
2584 // just use complex128 and hope for the best.
48c2a53a 2585 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2586 }
48c2a53a 2587
2588 Numeric_constant nc;
fcbea5e4 2589 nc.set_complex(resolved_type, this->val_);
ea664253 2590 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2591}
2592
2593// Write REAL/IMAG to export data.
2594
2595void
fcbea5e4 2596Complex_expression::export_complex(String_dump* exp, const mpc_t val)
e440a328 2597{
fcbea5e4 2598 if (!mpfr_zero_p(mpc_realref(val)))
e440a328 2599 {
fcbea5e4 2600 Float_expression::export_float(exp, mpc_realref(val));
d1db782d 2601 if (mpfr_sgn(mpc_imagref(val)) >= 0)
e440a328 2602 exp->write_c_string("+");
2603 }
fcbea5e4 2604 Float_expression::export_float(exp, mpc_imagref(val));
e440a328 2605 exp->write_c_string("i");
2606}
2607
2608// Export a complex number in a constant expression.
2609
2610void
2611Complex_expression::do_export(Export* exp) const
2612{
fcbea5e4 2613 Complex_expression::export_complex(exp, this->val_);
e440a328 2614 // A trailing space lets us reliably identify the end of the number.
2615 exp->write_c_string(" ");
2616}
2617
d751bb78 2618// Dump a complex expression to the dump file.
2619
2620void
2621Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2622{
fcbea5e4 2623 Complex_expression::export_complex(ast_dump_context, this->val_);
d751bb78 2624}
2625
e440a328 2626// Make a complex expression.
2627
2628Expression*
fcbea5e4 2629Expression::make_complex(const mpc_t* val, Type* type, Location location)
e440a328 2630{
fcbea5e4 2631 return new Complex_expression(val, type, location);
e440a328 2632}
2633
d5b605df 2634// Find a named object in an expression.
2635
2636class Find_named_object : public Traverse
2637{
2638 public:
2639 Find_named_object(Named_object* no)
2640 : Traverse(traverse_expressions),
2641 no_(no), found_(false)
2642 { }
2643
2644 // Whether we found the object.
2645 bool
2646 found() const
2647 { return this->found_; }
2648
2649 protected:
2650 int
2651 expression(Expression**);
2652
2653 private:
2654 // The object we are looking for.
2655 Named_object* no_;
2656 // Whether we found it.
2657 bool found_;
2658};
2659
e440a328 2660// A reference to a const in an expression.
2661
2662class Const_expression : public Expression
2663{
2664 public:
b13c66cd 2665 Const_expression(Named_object* constant, Location location)
e440a328 2666 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2667 constant_(constant), type_(NULL), seen_(false)
e440a328 2668 { }
2669
d5b605df 2670 Named_object*
2671 named_object()
2672 { return this->constant_; }
2673
a7f064d5 2674 // Check that the initializer does not refer to the constant itself.
2675 void
2676 check_for_init_loop();
2677
e440a328 2678 protected:
ba4aedd4 2679 int
2680 do_traverse(Traverse*);
2681
e440a328 2682 Expression*
ceeb4318 2683 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2684
2685 bool
2686 do_is_constant() const
2687 { return true; }
2688
0e168074 2689 bool
3ae06f68 2690 do_is_static_initializer() const
0e168074 2691 { return true; }
2692
e440a328 2693 bool
0c77715b 2694 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2695
2696 bool
af6b489a 2697 do_string_constant_value(std::string* val) const;
e440a328 2698
2699 Type*
2700 do_type();
2701
2702 // The type of a const is set by the declaration, not the use.
2703 void
2704 do_determine_type(const Type_context*);
2705
2706 void
2707 do_check_types(Gogo*);
2708
2709 Expression*
2710 do_copy()
2711 { return this; }
2712
ea664253 2713 Bexpression*
2714 do_get_backend(Translate_context* context);
e440a328 2715
2716 // When exporting a reference to a const as part of a const
2717 // expression, we export the value. We ignore the fact that it has
2718 // a name.
2719 void
2720 do_export(Export* exp) const
2721 { this->constant_->const_value()->expr()->export_expression(exp); }
2722
d751bb78 2723 void
2724 do_dump_expression(Ast_dump_context*) const;
2725
e440a328 2726 private:
2727 // The constant.
2728 Named_object* constant_;
2729 // The type of this reference. This is used if the constant has an
2730 // abstract type.
2731 Type* type_;
13e818f5 2732 // Used to prevent infinite recursion when a constant incorrectly
2733 // refers to itself.
2734 mutable bool seen_;
e440a328 2735};
2736
ba4aedd4 2737// Traversal.
2738
2739int
2740Const_expression::do_traverse(Traverse* traverse)
2741{
2742 if (this->type_ != NULL)
2743 return Type::traverse(this->type_, traverse);
2744 return TRAVERSE_CONTINUE;
2745}
2746
e440a328 2747// Lower a constant expression. This is where we convert the
2748// predeclared constant iota into an integer value.
2749
2750Expression*
ceeb4318 2751Const_expression::do_lower(Gogo* gogo, Named_object*,
2752 Statement_inserter*, int iota_value)
e440a328 2753{
2754 if (this->constant_->const_value()->expr()->classification()
2755 == EXPRESSION_IOTA)
2756 {
2757 if (iota_value == -1)
2758 {
631d5788 2759 go_error_at(this->location(),
2760 "iota is only defined in const declarations");
e440a328 2761 iota_value = 0;
2762 }
e67508fa 2763 return Expression::make_integer_ul(iota_value, NULL, this->location());
e440a328 2764 }
2765
2766 // Make sure that the constant itself has been lowered.
2767 gogo->lower_constant(this->constant_);
2768
2769 return this;
2770}
2771
0c77715b 2772// Return a numeric constant value.
e440a328 2773
2774bool
0c77715b 2775Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2776{
13e818f5 2777 if (this->seen_)
2778 return false;
2779
e440a328 2780 Expression* e = this->constant_->const_value()->expr();
0c77715b 2781
13e818f5 2782 this->seen_ = true;
2783
0c77715b 2784 bool r = e->numeric_constant_value(nc);
e440a328 2785
13e818f5 2786 this->seen_ = false;
2787
e440a328 2788 Type* ctype;
2789 if (this->type_ != NULL)
2790 ctype = this->type_;
2791 else
2792 ctype = this->constant_->const_value()->type();
e440a328 2793 if (r && ctype != NULL)
2794 {
0c77715b 2795 if (!nc->set_type(ctype, false, this->location()))
e440a328 2796 return false;
e440a328 2797 }
e440a328 2798
e440a328 2799 return r;
2800}
2801
af6b489a 2802bool
2803Const_expression::do_string_constant_value(std::string* val) const
2804{
2805 if (this->seen_)
2806 return false;
2807
2808 Expression* e = this->constant_->const_value()->expr();
2809
2810 this->seen_ = true;
2811 bool ok = e->string_constant_value(val);
2812 this->seen_ = false;
2813
2814 return ok;
2815}
2816
e440a328 2817// Return the type of the const reference.
2818
2819Type*
2820Const_expression::do_type()
2821{
2822 if (this->type_ != NULL)
2823 return this->type_;
13e818f5 2824
2f78f012 2825 Named_constant* nc = this->constant_->const_value();
2826
2827 if (this->seen_ || nc->lowering())
13e818f5 2828 {
2829 this->report_error(_("constant refers to itself"));
2830 this->type_ = Type::make_error_type();
2831 return this->type_;
2832 }
2833
2834 this->seen_ = true;
2835
e440a328 2836 Type* ret = nc->type();
13e818f5 2837
e440a328 2838 if (ret != NULL)
13e818f5 2839 {
2840 this->seen_ = false;
2841 return ret;
2842 }
2843
e440a328 2844 // During parsing, a named constant may have a NULL type, but we
2845 // must not return a NULL type here.
13e818f5 2846 ret = nc->expr()->type();
2847
2848 this->seen_ = false;
2849
2850 return ret;
e440a328 2851}
2852
2853// Set the type of the const reference.
2854
2855void
2856Const_expression::do_determine_type(const Type_context* context)
2857{
2858 Type* ctype = this->constant_->const_value()->type();
2859 Type* cetype = (ctype != NULL
2860 ? ctype
2861 : this->constant_->const_value()->expr()->type());
2862 if (ctype != NULL && !ctype->is_abstract())
2863 ;
2864 else if (context->type != NULL
0c77715b 2865 && context->type->is_numeric_type()
2866 && cetype->is_numeric_type())
e440a328 2867 this->type_ = context->type;
2868 else if (context->type != NULL
2869 && context->type->is_string_type()
2870 && cetype->is_string_type())
2871 this->type_ = context->type;
2872 else if (context->type != NULL
2873 && context->type->is_boolean_type()
2874 && cetype->is_boolean_type())
2875 this->type_ = context->type;
2876 else if (!context->may_be_abstract)
2877 {
2878 if (cetype->is_abstract())
2879 cetype = cetype->make_non_abstract_type();
2880 this->type_ = cetype;
2881 }
2882}
2883
a7f064d5 2884// Check for a loop in which the initializer of a constant refers to
2885// the constant itself.
e440a328 2886
2887void
a7f064d5 2888Const_expression::check_for_init_loop()
e440a328 2889{
5c13bd80 2890 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2891 return;
2892
a7f064d5 2893 if (this->seen_)
2894 {
2895 this->report_error(_("constant refers to itself"));
2896 this->type_ = Type::make_error_type();
2897 return;
2898 }
2899
d5b605df 2900 Expression* init = this->constant_->const_value()->expr();
2901 Find_named_object find_named_object(this->constant_);
a7f064d5 2902
2903 this->seen_ = true;
d5b605df 2904 Expression::traverse(&init, &find_named_object);
a7f064d5 2905 this->seen_ = false;
2906
d5b605df 2907 if (find_named_object.found())
2908 {
5c13bd80 2909 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2910 {
2911 this->report_error(_("constant refers to itself"));
2912 this->type_ = Type::make_error_type();
2913 }
d5b605df 2914 return;
2915 }
a7f064d5 2916}
2917
2918// Check types of a const reference.
2919
2920void
2921Const_expression::do_check_types(Gogo*)
2922{
5c13bd80 2923 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2924 return;
2925
2926 this->check_for_init_loop();
d5b605df 2927
0c77715b 2928 // Check that numeric constant fits in type.
2929 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2930 {
0c77715b 2931 Numeric_constant nc;
2932 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2933 {
0c77715b 2934 if (!nc.set_type(this->type_, true, this->location()))
2935 this->set_is_error();
e440a328 2936 }
e440a328 2937 }
2938}
2939
ea664253 2940// Return the backend representation for a const reference.
e440a328 2941
ea664253 2942Bexpression*
2943Const_expression::do_get_backend(Translate_context* context)
e440a328 2944{
12373dd5 2945 if (this->is_error_expression()
2946 || (this->type_ != NULL && this->type_->is_error()))
2947 {
2948 go_assert(saw_errors());
2949 return context->backend()->error_expression();
2950 }
e440a328 2951
2952 // If the type has been set for this expression, but the underlying
2953 // object is an abstract int or float, we try to get the abstract
2954 // value. Otherwise we may lose something in the conversion.
f2de4532 2955 Expression* expr = this->constant_->const_value()->expr();
e440a328 2956 if (this->type_ != NULL
0c77715b 2957 && this->type_->is_numeric_type()
a68492b4 2958 && (this->constant_->const_value()->type() == NULL
2959 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2960 {
0c77715b 2961 Numeric_constant nc;
2962 if (expr->numeric_constant_value(&nc)
2963 && nc.set_type(this->type_, false, this->location()))
e440a328 2964 {
0c77715b 2965 Expression* e = nc.expression(this->location());
ea664253 2966 return e->get_backend(context);
e440a328 2967 }
e440a328 2968 }
2969
2c809f8f 2970 if (this->type_ != NULL)
f2de4532 2971 expr = Expression::make_cast(this->type_, expr, this->location());
ea664253 2972 return expr->get_backend(context);
e440a328 2973}
2974
d751bb78 2975// Dump ast representation for constant expression.
2976
2977void
2978Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2979{
2980 ast_dump_context->ostream() << this->constant_->name();
2981}
2982
e440a328 2983// Make a reference to a constant in an expression.
2984
2985Expression*
2986Expression::make_const_reference(Named_object* constant,
b13c66cd 2987 Location location)
e440a328 2988{
2989 return new Const_expression(constant, location);
2990}
2991
d5b605df 2992// Find a named object in an expression.
2993
2994int
2995Find_named_object::expression(Expression** pexpr)
2996{
2997 switch ((*pexpr)->classification())
2998 {
2999 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 3000 {
3001 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3002 if (ce->named_object() == this->no_)
3003 break;
3004
3005 // We need to check a constant initializer explicitly, as
3006 // loops here will not be caught by the loop checking for
3007 // variable initializers.
3008 ce->check_for_init_loop();
3009
3010 return TRAVERSE_CONTINUE;
3011 }
3012
d5b605df 3013 case Expression::EXPRESSION_VAR_REFERENCE:
3014 if ((*pexpr)->var_expression()->named_object() == this->no_)
3015 break;
3016 return TRAVERSE_CONTINUE;
3017 case Expression::EXPRESSION_FUNC_REFERENCE:
3018 if ((*pexpr)->func_expression()->named_object() == this->no_)
3019 break;
3020 return TRAVERSE_CONTINUE;
3021 default:
3022 return TRAVERSE_CONTINUE;
3023 }
3024 this->found_ = true;
3025 return TRAVERSE_EXIT;
3026}
3027
e440a328 3028// The nil value.
3029
3030class Nil_expression : public Expression
3031{
3032 public:
b13c66cd 3033 Nil_expression(Location location)
e440a328 3034 : Expression(EXPRESSION_NIL, location)
3035 { }
3036
3037 static Expression*
3038 do_import(Import*);
3039
3040 protected:
3041 bool
3042 do_is_constant() const
3043 { return true; }
3044
f9ca30f9 3045 bool
3ae06f68 3046 do_is_static_initializer() const
f9ca30f9 3047 { return true; }
3048
e440a328 3049 Type*
3050 do_type()
3051 { return Type::make_nil_type(); }
3052
3053 void
3054 do_determine_type(const Type_context*)
3055 { }
3056
3057 Expression*
3058 do_copy()
3059 { return this; }
3060
ea664253 3061 Bexpression*
3062 do_get_backend(Translate_context* context)
3063 { return context->backend()->nil_pointer_expression(); }
e440a328 3064
3065 void
3066 do_export(Export* exp) const
3067 { exp->write_c_string("nil"); }
d751bb78 3068
3069 void
3070 do_dump_expression(Ast_dump_context* ast_dump_context) const
3071 { ast_dump_context->ostream() << "nil"; }
e440a328 3072};
3073
3074// Import a nil expression.
3075
3076Expression*
3077Nil_expression::do_import(Import* imp)
3078{
3079 imp->require_c_string("nil");
3080 return Expression::make_nil(imp->location());
3081}
3082
3083// Make a nil expression.
3084
3085Expression*
b13c66cd 3086Expression::make_nil(Location location)
e440a328 3087{
3088 return new Nil_expression(location);
3089}
3090
3091// The value of the predeclared constant iota. This is little more
3092// than a marker. This will be lowered to an integer in
3093// Const_expression::do_lower, which is where we know the value that
3094// it should have.
3095
3096class Iota_expression : public Parser_expression
3097{
3098 public:
b13c66cd 3099 Iota_expression(Location location)
e440a328 3100 : Parser_expression(EXPRESSION_IOTA, location)
3101 { }
3102
3103 protected:
3104 Expression*
ceeb4318 3105 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 3106 { go_unreachable(); }
e440a328 3107
3108 // There should only ever be one of these.
3109 Expression*
3110 do_copy()
c3e6f413 3111 { go_unreachable(); }
d751bb78 3112
3113 void
3114 do_dump_expression(Ast_dump_context* ast_dump_context) const
3115 { ast_dump_context->ostream() << "iota"; }
e440a328 3116};
3117
3118// Make an iota expression. This is only called for one case: the
3119// value of the predeclared constant iota.
3120
3121Expression*
3122Expression::make_iota()
3123{
b13c66cd 3124 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 3125 return &iota_expression;
3126}
3127
da244e59 3128// Class Type_conversion_expression.
e440a328 3129
3130// Traversal.
3131
3132int
3133Type_conversion_expression::do_traverse(Traverse* traverse)
3134{
3135 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3136 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3137 return TRAVERSE_EXIT;
3138 return TRAVERSE_CONTINUE;
3139}
3140
3141// Convert to a constant at lowering time.
3142
3143Expression*
ceeb4318 3144Type_conversion_expression::do_lower(Gogo*, Named_object*,
3145 Statement_inserter*, int)
e440a328 3146{
3147 Type* type = this->type_;
3148 Expression* val = this->expr_;
b13c66cd 3149 Location location = this->location();
e440a328 3150
0c77715b 3151 if (type->is_numeric_type())
e440a328 3152 {
0c77715b 3153 Numeric_constant nc;
3154 if (val->numeric_constant_value(&nc))
e440a328 3155 {
0c77715b 3156 if (!nc.set_type(type, true, location))
3157 return Expression::make_error(location);
3158 return nc.expression(location);
e440a328 3159 }
e440a328 3160 }
3161
d7739c9a 3162 // According to the language specification on string conversions
3163 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3164 // When converting an integer into a string, the string will be a UTF-8
3165 // representation of the integer and integers "outside the range of valid
3166 // Unicode code points are converted to '\uFFFD'."
3167 if (type->is_string_type())
3168 {
3169 Numeric_constant nc;
3170 if (val->numeric_constant_value(&nc) && nc.is_int())
3171 {
3172 // An integer value doesn't fit in the Unicode code point range if it
3173 // overflows the Go "int" type or is negative.
3174 unsigned long ul;
3175 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3176 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3177 return Expression::make_string("\ufffd", location);
3178 }
3179 }
3180
55072f2b 3181 if (type->is_slice_type())
e440a328 3182 {
3183 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3184 bool is_byte = (element_type->integer_type() != NULL
3185 && element_type->integer_type()->is_byte());
3186 bool is_rune = (element_type->integer_type() != NULL
3187 && element_type->integer_type()->is_rune());
3188 if (is_byte || is_rune)
e440a328 3189 {
3190 std::string s;
3191 if (val->string_constant_value(&s))
3192 {
3193 Expression_list* vals = new Expression_list();
3194 if (is_byte)
3195 {
3196 for (std::string::const_iterator p = s.begin();
3197 p != s.end();
3198 p++)
3199 {
e67508fa 3200 unsigned char c = static_cast<unsigned char>(*p);
3201 vals->push_back(Expression::make_integer_ul(c,
3202 element_type,
3203 location));
e440a328 3204 }
3205 }
3206 else
3207 {
3208 const char *p = s.data();
3209 const char *pend = s.data() + s.length();
3210 while (p < pend)
3211 {
3212 unsigned int c;
3213 int adv = Lex::fetch_char(p, &c);
3214 if (adv == 0)
3215 {
631d5788 3216 go_warning_at(this->location(), 0,
e440a328 3217 "invalid UTF-8 encoding");
3218 adv = 1;
3219 }
3220 p += adv;
e67508fa 3221 vals->push_back(Expression::make_integer_ul(c,
3222 element_type,
3223 location));
e440a328 3224 }
3225 }
3226
3227 return Expression::make_slice_composite_literal(type, vals,
3228 location);
3229 }
3230 }
3231 }
3232
3233 return this;
3234}
3235
35a54f17 3236// Flatten a type conversion by using a temporary variable for the slice
3237// in slice to string conversions.
3238
3239Expression*
3240Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3241 Statement_inserter* inserter)
3242{
5bf8be8b 3243 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3244 {
3245 go_assert(saw_errors());
3246 return Expression::make_error(this->location());
3247 }
3248
2c809f8f 3249 if (((this->type()->is_string_type()
3250 && this->expr_->type()->is_slice_type())
8ba8cc87 3251 || this->expr_->type()->interface_type() != NULL)
35a54f17 3252 && !this->expr_->is_variable())
3253 {
3254 Temporary_statement* temp =
3255 Statement::make_temporary(NULL, this->expr_, this->location());
3256 inserter->insert(temp);
3257 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3258 }
3259 return this;
3260}
3261
1ca01a59 3262// Return whether a type conversion is a constant.
3263
3264bool
3265Type_conversion_expression::do_is_constant() const
3266{
3267 if (!this->expr_->is_constant())
3268 return false;
3269
3270 // A conversion to a type that may not be used as a constant is not
3271 // a constant. For example, []byte(nil).
3272 Type* type = this->type_;
3273 if (type->integer_type() == NULL
3274 && type->float_type() == NULL
3275 && type->complex_type() == NULL
3276 && !type->is_boolean_type()
3277 && !type->is_string_type())
3278 return false;
3279
3280 return true;
3281}
3282
3ae06f68 3283// Return whether a type conversion can be used in a constant
3284// initializer.
0e168074 3285
3286bool
3ae06f68 3287Type_conversion_expression::do_is_static_initializer() const
0e168074 3288{
3289 Type* type = this->type_;
3290 Type* expr_type = this->expr_->type();
3291
3292 if (type->interface_type() != NULL
3293 || expr_type->interface_type() != NULL)
3294 return false;
3295
3ae06f68 3296 if (!this->expr_->is_static_initializer())
0e168074 3297 return false;
3298
3299 if (Type::are_identical(type, expr_type, false, NULL))
3300 return true;
3301
3302 return type->is_basic_type() && expr_type->is_basic_type();
3303}
3304
0c77715b 3305// Return the constant numeric value if there is one.
e440a328 3306
3307bool
0c77715b 3308Type_conversion_expression::do_numeric_constant_value(
3309 Numeric_constant* nc) const
e440a328 3310{
0c77715b 3311 if (!this->type_->is_numeric_type())
e440a328 3312 return false;
0c77715b 3313 if (!this->expr_->numeric_constant_value(nc))
e440a328 3314 return false;
0c77715b 3315 return nc->set_type(this->type_, false, this->location());
e440a328 3316}
3317
3318// Return the constant string value if there is one.
3319
3320bool
3321Type_conversion_expression::do_string_constant_value(std::string* val) const
3322{
3323 if (this->type_->is_string_type()
3324 && this->expr_->type()->integer_type() != NULL)
3325 {
0c77715b 3326 Numeric_constant nc;
3327 if (this->expr_->numeric_constant_value(&nc))
e440a328 3328 {
0c77715b 3329 unsigned long ival;
3330 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3331 {
0c77715b 3332 val->clear();
3333 Lex::append_char(ival, true, val, this->location());
e440a328 3334 return true;
3335 }
3336 }
e440a328 3337 }
3338
3339 // FIXME: Could handle conversion from const []int here.
3340
3341 return false;
3342}
3343
da244e59 3344// Determine the resulting type of the conversion.
3345
3346void
3347Type_conversion_expression::do_determine_type(const Type_context*)
3348{
3349 Type_context subcontext(this->type_, false);
3350 this->expr_->determine_type(&subcontext);
3351}
3352
e440a328 3353// Check that types are convertible.
3354
3355void
3356Type_conversion_expression::do_check_types(Gogo*)
3357{
3358 Type* type = this->type_;
3359 Type* expr_type = this->expr_->type();
3360 std::string reason;
3361
5c13bd80 3362 if (type->is_error() || expr_type->is_error())
842f6425 3363 {
842f6425 3364 this->set_is_error();
3365 return;
3366 }
3367
e440a328 3368 if (this->may_convert_function_types_
3369 && type->function_type() != NULL
3370 && expr_type->function_type() != NULL)
3371 return;
3372
3373 if (Type::are_convertible(type, expr_type, &reason))
3374 return;
3375
631d5788 3376 go_error_at(this->location(), "%s", reason.c_str());
e440a328 3377 this->set_is_error();
3378}
3379
ea664253 3380// Get the backend representation for a type conversion.
e440a328 3381
ea664253 3382Bexpression*
3383Type_conversion_expression::do_get_backend(Translate_context* context)
e440a328 3384{
e440a328 3385 Type* type = this->type_;
3386 Type* expr_type = this->expr_->type();
2c809f8f 3387
3388 Gogo* gogo = context->gogo();
3389 Btype* btype = type->get_backend(gogo);
ea664253 3390 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3391 Location loc = this->location();
3392
3393 if (Type::are_identical(type, expr_type, false, NULL))
ea664253 3394 return gogo->backend()->convert_expression(btype, bexpr, loc);
2c809f8f 3395 else if (type->interface_type() != NULL
3396 || expr_type->interface_type() != NULL)
e440a328 3397 {
2c809f8f 3398 Expression* conversion =
3399 Expression::convert_for_assignment(gogo, type, this->expr_,
3400 this->location());
ea664253 3401 return conversion->get_backend(context);
e440a328 3402 }
3403 else if (type->is_string_type()
3404 && expr_type->integer_type() != NULL)
3405 {
2c809f8f 3406 mpz_t intval;
3407 Numeric_constant nc;
3408 if (this->expr_->numeric_constant_value(&nc)
3409 && nc.to_int(&intval)
3410 && mpz_fits_ushort_p(intval))
e440a328 3411 {
e440a328 3412 std::string s;
2c809f8f 3413 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3414 mpz_clear(intval);
3415 Expression* se = Expression::make_string(s, loc);
ea664253 3416 return se->get_backend(context);
e440a328 3417 }
3418
f16ab008 3419 Expression* i2s_expr =
736a16ba 3420 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3421 Expression::make_nil(loc), this->expr_);
ea664253 3422 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
e440a328 3423 }
55072f2b 3424 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3425 {
55072f2b 3426 Array_type* a = expr_type->array_type();
e440a328 3427 Type* e = a->element_type()->forwarded();
c484d925 3428 go_assert(e->integer_type() != NULL);
35a54f17 3429 go_assert(this->expr_->is_variable());
3430
3431 Runtime::Function code;
60963afd 3432 if (e->integer_type()->is_byte())
736a16ba 3433 code = Runtime::SLICEBYTETOSTRING;
e440a328 3434 else
35a54f17 3435 {
3436 go_assert(e->integer_type()->is_rune());
736a16ba 3437 code = Runtime::SLICERUNETOSTRING;
35a54f17 3438 }
736a16ba 3439 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3440 this->expr_)->get_backend(context);
e440a328 3441 }
411eb89e 3442 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3443 {
3444 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3445 go_assert(e->integer_type() != NULL);
6c252e42 3446
2c809f8f 3447 Runtime::Function code;
60963afd 3448 if (e->integer_type()->is_byte())
736a16ba 3449 code = Runtime::STRINGTOSLICEBYTE;
e440a328 3450 else
3451 {
60963afd 3452 go_assert(e->integer_type()->is_rune());
736a16ba 3453 code = Runtime::STRINGTOSLICERUNE;
e440a328 3454 }
736a16ba 3455 Expression* s2a = Runtime::make_call(code, loc, 2,
3456 Expression::make_nil(loc),
3457 this->expr_);
ea664253 3458 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
2c809f8f 3459 }
3460 else if (type->is_numeric_type())
3461 {
3462 go_assert(Type::are_convertible(type, expr_type, NULL));
ea664253 3463 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3464 }
3465 else if ((type->is_unsafe_pointer_type()
2c809f8f 3466 && (expr_type->points_to() != NULL
3467 || expr_type->integer_type()))
3468 || (expr_type->is_unsafe_pointer_type()
3469 && type->points_to() != NULL)
3470 || (this->may_convert_function_types_
3471 && type->function_type() != NULL
3472 && expr_type->function_type() != NULL))
ea664253 3473 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3474 else
2c809f8f 3475 {
3476 Expression* conversion =
3477 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
ea664253 3478 return conversion->get_backend(context);
2c809f8f 3479 }
e440a328 3480}
3481
3482// Output a type conversion in a constant expression.
3483
3484void
3485Type_conversion_expression::do_export(Export* exp) const
3486{
3487 exp->write_c_string("convert(");
3488 exp->write_type(this->type_);
3489 exp->write_c_string(", ");
3490 this->expr_->export_expression(exp);
3491 exp->write_c_string(")");
3492}
3493
3494// Import a type conversion or a struct construction.
3495
3496Expression*
3497Type_conversion_expression::do_import(Import* imp)
3498{
3499 imp->require_c_string("convert(");
3500 Type* type = imp->read_type();
3501 imp->require_c_string(", ");
3502 Expression* val = Expression::import_expression(imp);
3503 imp->require_c_string(")");
3504 return Expression::make_cast(type, val, imp->location());
3505}
3506
d751bb78 3507// Dump ast representation for a type conversion expression.
3508
3509void
3510Type_conversion_expression::do_dump_expression(
3511 Ast_dump_context* ast_dump_context) const
3512{
3513 ast_dump_context->dump_type(this->type_);
3514 ast_dump_context->ostream() << "(";
3515 ast_dump_context->dump_expression(this->expr_);
3516 ast_dump_context->ostream() << ") ";
3517}
3518
e440a328 3519// Make a type cast expression.
3520
3521Expression*
b13c66cd 3522Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3523{
3524 if (type->is_error_type() || val->is_error_expression())
3525 return Expression::make_error(location);
3526 return new Type_conversion_expression(type, val, location);
3527}
3528
98f62f7a 3529// Class Unsafe_type_conversion_expression.
9581e91d 3530
3531// Traversal.
3532
3533int
3534Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3535{
3536 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3537 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3538 return TRAVERSE_EXIT;
3539 return TRAVERSE_CONTINUE;
3540}
3541
3ae06f68 3542// Return whether an unsafe type conversion can be used as a constant
3543// initializer.
aa5ae575 3544
3545bool
3ae06f68 3546Unsafe_type_conversion_expression::do_is_static_initializer() const
aa5ae575 3547{
3548 Type* type = this->type_;
3549 Type* expr_type = this->expr_->type();
3550
3551 if (type->interface_type() != NULL
3552 || expr_type->interface_type() != NULL)
3553 return false;
3554
3ae06f68 3555 if (!this->expr_->is_static_initializer())
aa5ae575 3556 return false;
3557
3558 if (Type::are_convertible(type, expr_type, NULL))
3559 return true;
3560
3561 return type->is_basic_type() && expr_type->is_basic_type();
3562}
3563
9581e91d 3564// Convert to backend representation.
3565
ea664253 3566Bexpression*
3567Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
9581e91d 3568{
3569 // We are only called for a limited number of cases.
3570
3571 Type* t = this->type_;
3572 Type* et = this->expr_->type();
5c4802f1 3573
3574 if (t->is_error_type()
3575 || this->expr_->is_error_expression()
3576 || et->is_error_type())
3577 {
3578 go_assert(saw_errors());
3579 return context->backend()->error_expression();
3580 }
3581
2c809f8f 3582 if (t->array_type() != NULL)
3583 go_assert(et->array_type() != NULL
3584 && t->is_slice_type() == et->is_slice_type());
3585 else if (t->struct_type() != NULL)
9581e91d 3586 {
2c809f8f 3587 if (t->named_type() != NULL
3588 && et->named_type() != NULL
3589 && !Type::are_convertible(t, et, NULL))
3590 {
3591 go_assert(saw_errors());
ea664253 3592 return context->backend()->error_expression();
2c809f8f 3593 }
3594
3595 go_assert(et->struct_type() != NULL
3596 && Type::are_convertible(t, et, NULL));
3597 }
3598 else if (t->map_type() != NULL)
c484d925 3599 go_assert(et->map_type() != NULL);
9581e91d 3600 else if (t->channel_type() != NULL)
c484d925 3601 go_assert(et->channel_type() != NULL);
09ea332d 3602 else if (t->points_to() != NULL)
2c809f8f 3603 go_assert(et->points_to() != NULL
3604 || et->channel_type() != NULL
3605 || et->map_type() != NULL
3606 || et->function_type() != NULL
132ed071 3607 || et->integer_type() != NULL
2c809f8f 3608 || et->is_nil_type());
9581e91d 3609 else if (et->is_unsafe_pointer_type())
c484d925 3610 go_assert(t->points_to() != NULL);
2c809f8f 3611 else if (t->interface_type() != NULL)
9581e91d 3612 {
2c809f8f 3613 bool empty_iface = t->interface_type()->is_empty();
c484d925 3614 go_assert(et->interface_type() != NULL
2c809f8f 3615 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3616 }
588e3cf9 3617 else if (t->integer_type() != NULL)
2c809f8f 3618 go_assert(et->is_boolean_type()
3619 || et->integer_type() != NULL
3620 || et->function_type() != NULL
3621 || et->points_to() != NULL
3622 || et->map_type() != NULL
8ba8cc87 3623 || et->channel_type() != NULL
3624 || et->is_nil_type());
cd39797e 3625 else if (t->function_type() != NULL)
3626 go_assert(et->points_to() != NULL);
9581e91d 3627 else
c3e6f413 3628 go_unreachable();
9581e91d 3629
2c809f8f 3630 Gogo* gogo = context->gogo();
3631 Btype* btype = t->get_backend(gogo);
ea664253 3632 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3633 Location loc = this->location();
ea664253 3634 return gogo->backend()->convert_expression(btype, bexpr, loc);
9581e91d 3635}
3636
d751bb78 3637// Dump ast representation for an unsafe type conversion expression.
3638
3639void
3640Unsafe_type_conversion_expression::do_dump_expression(
3641 Ast_dump_context* ast_dump_context) const
3642{
3643 ast_dump_context->dump_type(this->type_);
3644 ast_dump_context->ostream() << "(";
3645 ast_dump_context->dump_expression(this->expr_);
3646 ast_dump_context->ostream() << ") ";
3647}
3648
9581e91d 3649// Make an unsafe type conversion expression.
3650
3651Expression*
3652Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3653 Location location)
9581e91d 3654{
3655 return new Unsafe_type_conversion_expression(type, expr, location);
3656}
3657
76f85fd6 3658// Class Unary_expression.
e440a328 3659
3660// If we are taking the address of a composite literal, and the
2c809f8f 3661// contents are not constant, then we want to make a heap expression
e440a328 3662// instead.
3663
3664Expression*
ceeb4318 3665Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3666{
b13c66cd 3667 Location loc = this->location();
e440a328 3668 Operator op = this->op_;
3669 Expression* expr = this->expr_;
3670
3671 if (op == OPERATOR_MULT && expr->is_type_expression())
3672 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3673
3674 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3675 // moving x to the heap. FIXME: Is it worth doing a real escape
3676 // analysis here? This case is found in math/unsafe.go and is
3677 // therefore worth special casing.
3678 if (op == OPERATOR_MULT)
3679 {
3680 Expression* e = expr;
3681 while (e->classification() == EXPRESSION_CONVERSION)
3682 {
3683 Type_conversion_expression* te
3684 = static_cast<Type_conversion_expression*>(e);
3685 e = te->expr();
3686 }
3687
3688 if (e->classification() == EXPRESSION_UNARY)
3689 {
3690 Unary_expression* ue = static_cast<Unary_expression*>(e);
3691 if (ue->op_ == OPERATOR_AND)
3692 {
3693 if (e == expr)
3694 {
3695 // *&x == x.
f4dea966 3696 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3697 {
631d5788 3698 go_error_at(ue->location(),
3699 "invalid operand for unary %<&%>");
f4dea966 3700 this->set_is_error();
3701 }
e440a328 3702 return ue->expr_;
3703 }
3704 ue->set_does_not_escape();
3705 }
3706 }
3707 }
3708
55661ce9 3709 // Catching an invalid indirection of unsafe.Pointer here avoid
3710 // having to deal with TYPE_VOID in other places.
3711 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3712 {
631d5788 3713 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
55661ce9 3714 return Expression::make_error(this->location());
3715 }
3716
d9f3743a 3717 // Check for an invalid pointer dereference. We need to do this
3718 // here because Unary_expression::do_type will return an error type
3719 // in this case. That can cause code to appear erroneous, and
3720 // therefore disappear at lowering time, without any error message.
3721 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3722 {
3723 this->report_error(_("expected pointer"));
3724 return Expression::make_error(this->location());
3725 }
3726
59a401fe 3727 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3728 {
0c77715b 3729 Numeric_constant nc;
3730 if (expr->numeric_constant_value(&nc))
e440a328 3731 {
0c77715b 3732 Numeric_constant result;
3733 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3734 return result.expression(loc);
e440a328 3735 }
3736 }
3737
3738 return this;
3739}
3740
f9ca30f9 3741// Flatten expression if a nil check must be performed and create temporary
3742// variables if necessary.
3743
3744Expression*
3745Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3746 Statement_inserter* inserter)
3747{
5bf8be8b 3748 if (this->is_error_expression()
3749 || this->expr_->is_error_expression()
3750 || this->expr_->type()->is_error_type())
3751 {
3752 go_assert(saw_errors());
3753 return Expression::make_error(this->location());
3754 }
f4dea966 3755
f9ca30f9 3756 Location location = this->location();
3757 if (this->op_ == OPERATOR_MULT
3758 && !this->expr_->is_variable())
3759 {
3760 go_assert(this->expr_->type()->points_to() != NULL);
3761 Type* ptype = this->expr_->type()->points_to();
3762 if (!ptype->is_void_type())
3763 {
2a305b85 3764 int64_t s;
3765 bool ok = ptype->backend_type_size(gogo, &s);
3766 if (!ok)
3767 {
3768 go_assert(saw_errors());
3769 return Expression::make_error(this->location());
3770 }
f9ca30f9 3771 if (s >= 4096 || this->issue_nil_check_)
3772 {
3773 Temporary_statement* temp =
3774 Statement::make_temporary(NULL, this->expr_, location);
3775 inserter->insert(temp);
3776 this->expr_ =
3777 Expression::make_temporary_reference(temp, location);
3778 }
3779 }
3780 }
3781
da244e59 3782 if (this->op_ == OPERATOR_AND)
3783 {
8ff995b5 3784 // If this->escapes_ is false at this point, then it was set to
3785 // false by an explicit call to set_does_not_escape, and the
3786 // value does not escape. If this->escapes_ is true, we may be
3787 // able to set it to false if taking the address of a variable
3788 // that does not escape.
45ff893b 3789 Node* n = Node::make_node(this);
3790 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3791 this->escapes_ = false;
3792
0dad6de4 3793 // When compiling the runtime, the address operator does not
87211034 3794 // cause local variables to escape. When escape analysis
0dad6de4 3795 // becomes the default, this should be changed to make it an
3796 // error if we have an address operator that escapes.
3797 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3798 this->escapes_ = false;
3799
45ff893b 3800 Named_object* var = NULL;
3801 if (this->expr_->var_expression() != NULL)
3802 var = this->expr_->var_expression()->named_object();
3803 else if (this->expr_->enclosed_var_expression() != NULL)
3804 var = this->expr_->enclosed_var_expression()->variable();
3805
3806 if (this->escapes_ && var != NULL)
da244e59 3807 {
da244e59 3808 if (var->is_variable())
3809 this->escapes_ = var->var_value()->escapes();
3810 if (var->is_result_variable())
3811 this->escapes_ = var->result_var_value()->escapes();
3812 }
3813 this->expr_->address_taken(this->escapes_);
3814 }
3815
f9ca30f9 3816 if (this->create_temp_ && !this->expr_->is_variable())
3817 {
3818 Temporary_statement* temp =
3819 Statement::make_temporary(NULL, this->expr_, location);
3820 inserter->insert(temp);
3821 this->expr_ = Expression::make_temporary_reference(temp, location);
3822 }
3823
3824 return this;
3825}
3826
e440a328 3827// Return whether a unary expression is a constant.
3828
3829bool
3830Unary_expression::do_is_constant() const
3831{
3832 if (this->op_ == OPERATOR_MULT)
3833 {
3834 // Indirecting through a pointer is only constant if the object
3835 // to which the expression points is constant, but we currently
3836 // have no way to determine that.
3837 return false;
3838 }
3839 else if (this->op_ == OPERATOR_AND)
3840 {
3841 // Taking the address of a variable is constant if it is a
f9ca30f9 3842 // global variable, not constant otherwise. In other cases taking the
3843 // address is probably not a constant.
e440a328 3844 Var_expression* ve = this->expr_->var_expression();
3845 if (ve != NULL)
3846 {
3847 Named_object* no = ve->named_object();
3848 return no->is_variable() && no->var_value()->is_global();
3849 }
3850 return false;
3851 }
3852 else
3853 return this->expr_->is_constant();
3854}
3855
3ae06f68 3856// Return whether a unary expression can be used as a constant
3857// initializer.
3858
3859bool
3860Unary_expression::do_is_static_initializer() const
3861{
3862 if (this->op_ == OPERATOR_MULT)
3863 return false;
3864 else if (this->op_ == OPERATOR_AND)
3865 {
3866 // The address of a global variable can used as a static
3867 // initializer.
3868 Var_expression* ve = this->expr_->var_expression();
3869 if (ve != NULL)
3870 {
3871 Named_object* no = ve->named_object();
3872 return no->is_variable() && no->var_value()->is_global();
3873 }
3874
3875 // The address of a composite literal can be used as a static
3876 // initializer if the composite literal is itself usable as a
3877 // static initializer.
3878 if (this->expr_->is_composite_literal()
3879 && this->expr_->is_static_initializer())
3880 return true;
3881
3882 // The address of a string constant can be used as a static
3883 // initializer. This can not be written in Go itself but this
3884 // is used when building a type descriptor.
3885 if (this->expr_->string_expression() != NULL)
3886 return true;
3887
3888 return false;
3889 }
3890 else
3891 return this->expr_->is_static_initializer();
3892}
3893
0c77715b 3894// Apply unary opcode OP to UNC, setting NC. Return true if this
3895// could be done, false if not. Issue errors for overflow.
e440a328 3896
3897bool
0c77715b 3898Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3899 Location location, Numeric_constant* nc)
e440a328 3900{
3901 switch (op)
3902 {
3903 case OPERATOR_PLUS:
0c77715b 3904 *nc = *unc;
e440a328 3905 return true;
0c77715b 3906
e440a328 3907 case OPERATOR_MINUS:
0c77715b 3908 if (unc->is_int() || unc->is_rune())
3909 break;
3910 else if (unc->is_float())
3911 {
3912 mpfr_t uval;
3913 unc->get_float(&uval);
3914 mpfr_t val;
3915 mpfr_init(val);
3916 mpfr_neg(val, uval, GMP_RNDN);
3917 nc->set_float(unc->type(), val);
3918 mpfr_clear(uval);
3919 mpfr_clear(val);
3920 return true;
3921 }
3922 else if (unc->is_complex())
3923 {
fcbea5e4 3924 mpc_t uval;
3925 unc->get_complex(&uval);
3926 mpc_t val;
3927 mpc_init2(val, mpc_precision);
3928 mpc_neg(val, uval, MPC_RNDNN);
3929 nc->set_complex(unc->type(), val);
3930 mpc_clear(uval);
3931 mpc_clear(val);
0c77715b 3932 return true;
3933 }
e440a328 3934 else
0c77715b 3935 go_unreachable();
e440a328 3936
0c77715b 3937 case OPERATOR_XOR:
3938 break;
68448d53 3939
59a401fe 3940 case OPERATOR_NOT:
e440a328 3941 case OPERATOR_AND:
3942 case OPERATOR_MULT:
3943 return false;
0c77715b 3944
e440a328 3945 default:
c3e6f413 3946 go_unreachable();
e440a328 3947 }
e440a328 3948
0c77715b 3949 if (!unc->is_int() && !unc->is_rune())
3950 return false;
3951
3952 mpz_t uval;
8387e1df 3953 if (unc->is_rune())
3954 unc->get_rune(&uval);
3955 else
3956 unc->get_int(&uval);
0c77715b 3957 mpz_t val;
3958 mpz_init(val);
e440a328 3959
e440a328 3960 switch (op)
3961 {
e440a328 3962 case OPERATOR_MINUS:
0c77715b 3963 mpz_neg(val, uval);
3964 break;
3965
e440a328 3966 case OPERATOR_NOT:
0c77715b 3967 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3968 break;
3969
e440a328 3970 case OPERATOR_XOR:
0c77715b 3971 {
3972 Type* utype = unc->type();
3973 if (utype->integer_type() == NULL
3974 || utype->integer_type()->is_abstract())
3975 mpz_com(val, uval);
3976 else
3977 {
3978 // The number of HOST_WIDE_INTs that it takes to represent
3979 // UVAL.
3980 size_t count = ((mpz_sizeinbase(uval, 2)
3981 + HOST_BITS_PER_WIDE_INT
3982 - 1)
3983 / HOST_BITS_PER_WIDE_INT);
e440a328 3984
0c77715b 3985 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3986 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3987
3988 size_t obits = utype->integer_type()->bits();
3989
3990 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3991 {
3992 mpz_t adj;
3993 mpz_init_set_ui(adj, 1);
3994 mpz_mul_2exp(adj, adj, obits);
3995 mpz_add(uval, uval, adj);
3996 mpz_clear(adj);
3997 }
3998
3999 size_t ecount;
4000 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4001 go_assert(ecount <= count);
4002
4003 // Trim down to the number of words required by the type.
4004 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4005 / HOST_BITS_PER_WIDE_INT);
4006 go_assert(ocount <= count);
4007
4008 for (size_t i = 0; i < ocount; ++i)
4009 phwi[i] = ~phwi[i];
4010
4011 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4012 if (clearbits != 0)
4013 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4014 >> clearbits);
4015
4016 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4017
4018 if (!utype->integer_type()->is_unsigned()
4019 && mpz_tstbit(val, obits - 1))
4020 {
4021 mpz_t adj;
4022 mpz_init_set_ui(adj, 1);
4023 mpz_mul_2exp(adj, adj, obits);
4024 mpz_sub(val, val, adj);
4025 mpz_clear(adj);
4026 }
4027
4028 delete[] phwi;
4029 }
4030 }
4031 break;
e440a328 4032
e440a328 4033 default:
c3e6f413 4034 go_unreachable();
e440a328 4035 }
e440a328 4036
0c77715b 4037 if (unc->is_rune())
4038 nc->set_rune(NULL, val);
e440a328 4039 else
0c77715b 4040 nc->set_int(NULL, val);
e440a328 4041
0c77715b 4042 mpz_clear(uval);
4043 mpz_clear(val);
e440a328 4044
0c77715b 4045 return nc->set_type(unc->type(), true, location);
e440a328 4046}
4047
0c77715b 4048// Return the integral constant value of a unary expression, if it has one.
e440a328 4049
4050bool
0c77715b 4051Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 4052{
0c77715b 4053 Numeric_constant unc;
4054 if (!this->expr_->numeric_constant_value(&unc))
4055 return false;
4056 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4057 nc);
e440a328 4058}
4059
4060// Return the type of a unary expression.
4061
4062Type*
4063Unary_expression::do_type()
4064{
4065 switch (this->op_)
4066 {
4067 case OPERATOR_PLUS:
4068 case OPERATOR_MINUS:
4069 case OPERATOR_NOT:
4070 case OPERATOR_XOR:
4071 return this->expr_->type();
4072
4073 case OPERATOR_AND:
4074 return Type::make_pointer_type(this->expr_->type());
4075
4076 case OPERATOR_MULT:
4077 {
4078 Type* subtype = this->expr_->type();
4079 Type* points_to = subtype->points_to();
4080 if (points_to == NULL)
4081 return Type::make_error_type();
4082 return points_to;
4083 }
4084
4085 default:
c3e6f413 4086 go_unreachable();
e440a328 4087 }
4088}
4089
4090// Determine abstract types for a unary expression.
4091
4092void
4093Unary_expression::do_determine_type(const Type_context* context)
4094{
4095 switch (this->op_)
4096 {
4097 case OPERATOR_PLUS:
4098 case OPERATOR_MINUS:
4099 case OPERATOR_NOT:
4100 case OPERATOR_XOR:
4101 this->expr_->determine_type(context);
4102 break;
4103
4104 case OPERATOR_AND:
4105 // Taking the address of something.
4106 {
4107 Type* subtype = (context->type == NULL
4108 ? NULL
4109 : context->type->points_to());
4110 Type_context subcontext(subtype, false);
4111 this->expr_->determine_type(&subcontext);
4112 }
4113 break;
4114
4115 case OPERATOR_MULT:
4116 // Indirecting through a pointer.
4117 {
4118 Type* subtype = (context->type == NULL
4119 ? NULL
4120 : Type::make_pointer_type(context->type));
4121 Type_context subcontext(subtype, false);
4122 this->expr_->determine_type(&subcontext);
4123 }
4124 break;
4125
4126 default:
c3e6f413 4127 go_unreachable();
e440a328 4128 }
4129}
4130
4131// Check types for a unary expression.
4132
4133void
4134Unary_expression::do_check_types(Gogo*)
4135{
9fe897ef 4136 Type* type = this->expr_->type();
5c13bd80 4137 if (type->is_error())
9fe897ef 4138 {
4139 this->set_is_error();
4140 return;
4141 }
4142
e440a328 4143 switch (this->op_)
4144 {
4145 case OPERATOR_PLUS:
4146 case OPERATOR_MINUS:
9fe897ef 4147 if (type->integer_type() == NULL
4148 && type->float_type() == NULL
4149 && type->complex_type() == NULL)
4150 this->report_error(_("expected numeric type"));
e440a328 4151 break;
4152
4153 case OPERATOR_NOT:
59a401fe 4154 if (!type->is_boolean_type())
4155 this->report_error(_("expected boolean type"));
4156 break;
4157
e440a328 4158 case OPERATOR_XOR:
b3b1474e 4159 if (type->integer_type() == NULL)
4160 this->report_error(_("expected integer"));
e440a328 4161 break;
4162
4163 case OPERATOR_AND:
4164 if (!this->expr_->is_addressable())
09ea332d 4165 {
4166 if (!this->create_temp_)
f4dea966 4167 {
631d5788 4168 go_error_at(this->location(), "invalid operand for unary %<&%>");
f4dea966 4169 this->set_is_error();
4170 }
09ea332d 4171 }
e440a328 4172 else
da244e59 4173 this->expr_->issue_nil_check();
e440a328 4174 break;
4175
4176 case OPERATOR_MULT:
4177 // Indirecting through a pointer.
9fe897ef 4178 if (type->points_to() == NULL)
4179 this->report_error(_("expected pointer"));
7661d702 4180 if (type->points_to()->is_error())
4181 this->set_is_error();
e440a328 4182 break;
4183
4184 default:
c3e6f413 4185 go_unreachable();
e440a328 4186 }
4187}
4188
ea664253 4189// Get the backend representation for a unary expression.
e440a328 4190
ea664253 4191Bexpression*
4192Unary_expression::do_get_backend(Translate_context* context)
e440a328 4193{
1b1f2abf 4194 Gogo* gogo = context->gogo();
e9d3367e 4195 Location loc = this->location();
4196
4197 // Taking the address of a set-and-use-temporary expression requires
4198 // setting the temporary and then taking the address.
4199 if (this->op_ == OPERATOR_AND)
4200 {
4201 Set_and_use_temporary_expression* sut =
4202 this->expr_->set_and_use_temporary_expression();
4203 if (sut != NULL)
4204 {
4205 Temporary_statement* temp = sut->temporary();
4206 Bvariable* bvar = temp->get_backend_variable(context);
f9ca30f9 4207 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
ea664253 4208 Bexpression* bval = sut->expression()->get_backend(context);
f9ca30f9 4209
4210 Bstatement* bassign =
4211 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4212 Bexpression* bvar_addr =
4213 gogo->backend()->address_expression(bvar_expr, loc);
ea664253 4214 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
e9d3367e 4215 }
4216 }
4217
f9ca30f9 4218 Bexpression* ret;
ea664253 4219 Bexpression* bexpr = this->expr_->get_backend(context);
f9ca30f9 4220 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4221 switch (this->op_)
4222 {
4223 case OPERATOR_PLUS:
f9ca30f9 4224 ret = bexpr;
4225 break;
e440a328 4226
4227 case OPERATOR_MINUS:
f9ca30f9 4228 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4229 ret = gogo->backend()->convert_expression(btype, ret, loc);
4230 break;
e440a328 4231
4232 case OPERATOR_NOT:
e440a328 4233 case OPERATOR_XOR:
f9ca30f9 4234 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4235 break;
e440a328 4236
4237 case OPERATOR_AND:
09ea332d 4238 if (!this->create_temp_)
4239 {
4240 // We should not see a non-constant constructor here; cases
4241 // where we would see one should have been moved onto the
4242 // heap at parse time. Taking the address of a nonconstant
4243 // constructor will not do what the programmer expects.
f9ca30f9 4244
4245 go_assert(!this->expr_->is_composite_literal()
3ae06f68 4246 || this->expr_->is_static_initializer());
24060bf9 4247 if (this->expr_->classification() == EXPRESSION_UNARY)
4248 {
4249 Unary_expression* ue =
4250 static_cast<Unary_expression*>(this->expr_);
4251 go_assert(ue->op() != OPERATOR_AND);
4252 }
09ea332d 4253 }
e440a328 4254
f23d7786 4255 static unsigned int counter;
4256 char buf[100];
4257 if (this->is_gc_root_ || this->is_slice_init_)
76f85fd6 4258 {
f23d7786 4259 bool copy_to_heap = false;
4260 if (this->is_gc_root_)
4261 {
4262 // Build a decl for a GC root variable. GC roots are mutable, so
4263 // they cannot be represented as an immutable_struct in the
4264 // backend.
4265 static unsigned int root_counter;
4266 snprintf(buf, sizeof buf, "gc%u", root_counter);
4267 ++root_counter;
4268 }
4269 else
4270 {
4271 // Build a decl for a slice value initializer. An immutable slice
4272 // value initializer may have to be copied to the heap if it
4273 // contains pointers in a non-constant context.
4274 snprintf(buf, sizeof buf, "C%u", counter);
4275 ++counter;
4276
4277 Array_type* at = this->expr_->type()->array_type();
4278 go_assert(at != NULL);
4279
4280 // If we are not copying the value to the heap, we will only
4281 // initialize the value once, so we can use this directly
4282 // rather than copying it. In that case we can't make it
4283 // read-only, because the program is permitted to change it.
3ae06f68 4284 copy_to_heap = context->function() != NULL;
f23d7786 4285 }
4286 Bvariable* implicit =
aa5ae575 4287 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
5892f89f 4288 false, 0);
aa5ae575 4289 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4290 true, copy_to_heap, false,
4291 bexpr);
f23d7786 4292 bexpr = gogo->backend()->var_expression(implicit, loc);
76f85fd6 4293 }
4294 else if ((this->expr_->is_composite_literal()
3ae06f68 4295 || this->expr_->string_expression() != NULL)
4296 && this->expr_->is_static_initializer())
f9ca30f9 4297 {
76f85fd6 4298 // Build a decl for a constant constructor.
f9ca30f9 4299 snprintf(buf, sizeof buf, "C%u", counter);
4300 ++counter;
4301
4302 Bvariable* decl =
4303 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4304 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4305 btype, loc, bexpr);
4306 bexpr = gogo->backend()->var_expression(decl, loc);
4307 }
09ea332d 4308
f9ca30f9 4309 go_assert(!this->create_temp_ || this->expr_->is_variable());
4310 ret = gogo->backend()->address_expression(bexpr, loc);
4311 break;
e440a328 4312
4313 case OPERATOR_MULT:
4314 {
f9ca30f9 4315 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4316
4317 // If we are dereferencing the pointer to a large struct, we
4318 // need to check for nil. We don't bother to check for small
4319 // structs because we expect the system to crash on a nil
56080003 4320 // pointer dereference. However, if we know the address of this
4321 // expression is being taken, we must always check for nil.
f9ca30f9 4322
4323 Type* ptype = this->expr_->type()->points_to();
4324 Btype* pbtype = ptype->get_backend(gogo);
4325 if (!ptype->is_void_type())
e440a328 4326 {
2a305b85 4327 int64_t s;
4328 bool ok = ptype->backend_type_size(gogo, &s);
4329 if (!ok)
4330 {
4331 go_assert(saw_errors());
4332 return gogo->backend()->error_expression();
4333 }
f9ca30f9 4334 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4335 {
f9ca30f9 4336 go_assert(this->expr_->is_variable());
ea664253 4337 Bexpression* nil =
4338 Expression::make_nil(loc)->get_backend(context);
f9ca30f9 4339 Bexpression* compare =
4340 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4341 nil, loc);
f9ca30f9 4342 Bexpression* crash =
ea664253 4343 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4344 loc)->get_backend(context);
f9ca30f9 4345 bexpr = gogo->backend()->conditional_expression(btype, compare,
4346 crash, bexpr,
4347 loc);
4348
19b4f09b 4349 }
e440a328 4350 }
9b27b43c 4351 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
e440a328 4352 }
f9ca30f9 4353 break;
e440a328 4354
4355 default:
c3e6f413 4356 go_unreachable();
e440a328 4357 }
f9ca30f9 4358
ea664253 4359 return ret;
e440a328 4360}
4361
4362// Export a unary expression.
4363
4364void
4365Unary_expression::do_export(Export* exp) const
4366{
4367 switch (this->op_)
4368 {
4369 case OPERATOR_PLUS:
4370 exp->write_c_string("+ ");
4371 break;
4372 case OPERATOR_MINUS:
4373 exp->write_c_string("- ");
4374 break;
4375 case OPERATOR_NOT:
4376 exp->write_c_string("! ");
4377 break;
4378 case OPERATOR_XOR:
4379 exp->write_c_string("^ ");
4380 break;
4381 case OPERATOR_AND:
4382 case OPERATOR_MULT:
4383 default:
c3e6f413 4384 go_unreachable();
e440a328 4385 }
4386 this->expr_->export_expression(exp);
4387}
4388
4389// Import a unary expression.
4390
4391Expression*
4392Unary_expression::do_import(Import* imp)
4393{
4394 Operator op;
4395 switch (imp->get_char())
4396 {
4397 case '+':
4398 op = OPERATOR_PLUS;
4399 break;
4400 case '-':
4401 op = OPERATOR_MINUS;
4402 break;
4403 case '!':
4404 op = OPERATOR_NOT;
4405 break;
4406 case '^':
4407 op = OPERATOR_XOR;
4408 break;
4409 default:
c3e6f413 4410 go_unreachable();
e440a328 4411 }
4412 imp->require_c_string(" ");
4413 Expression* expr = Expression::import_expression(imp);
4414 return Expression::make_unary(op, expr, imp->location());
4415}
4416
d751bb78 4417// Dump ast representation of an unary expression.
4418
4419void
4420Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4421{
4422 ast_dump_context->dump_operator(this->op_);
4423 ast_dump_context->ostream() << "(";
4424 ast_dump_context->dump_expression(this->expr_);
4425 ast_dump_context->ostream() << ") ";
4426}
4427
e440a328 4428// Make a unary expression.
4429
4430Expression*
b13c66cd 4431Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4432{
4433 return new Unary_expression(op, expr, location);
4434}
4435
4436// If this is an indirection through a pointer, return the expression
4437// being pointed through. Otherwise return this.
4438
4439Expression*
4440Expression::deref()
4441{
4442 if (this->classification_ == EXPRESSION_UNARY)
4443 {
4444 Unary_expression* ue = static_cast<Unary_expression*>(this);
4445 if (ue->op() == OPERATOR_MULT)
4446 return ue->operand();
4447 }
4448 return this;
4449}
4450
4451// Class Binary_expression.
4452
4453// Traversal.
4454
4455int
4456Binary_expression::do_traverse(Traverse* traverse)
4457{
4458 int t = Expression::traverse(&this->left_, traverse);
4459 if (t == TRAVERSE_EXIT)
4460 return TRAVERSE_EXIT;
4461 return Expression::traverse(&this->right_, traverse);
4462}
4463
3ae06f68 4464// Return whether this expression may be used as a static initializer.
4465
4466bool
4467Binary_expression::do_is_static_initializer() const
4468{
4469 if (!this->left_->is_static_initializer()
4470 || !this->right_->is_static_initializer())
4471 return false;
4472
4473 // Addresses can be static initializers, but we can't implement
4474 // arbitray binary expressions of them.
4475 Unary_expression* lu = this->left_->unary_expression();
4476 Unary_expression* ru = this->right_->unary_expression();
4477 if (lu != NULL && lu->op() == OPERATOR_AND)
4478 {
4479 if (ru != NULL && ru->op() == OPERATOR_AND)
4480 return this->op_ == OPERATOR_MINUS;
4481 else
4482 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4483 }
4484 else if (ru != NULL && ru->op() == OPERATOR_AND)
4485 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4486
4487 // Other cases should resolve in the backend.
4488 return true;
4489}
4490
0c77715b 4491// Return the type to use for a binary operation on operands of
4492// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4493// such may be NULL or abstract.
4494
4495bool
4496Binary_expression::operation_type(Operator op, Type* left_type,
4497 Type* right_type, Type** result_type)
4498{
4499 if (left_type != right_type
4500 && !left_type->is_abstract()
4501 && !right_type->is_abstract()
4502 && left_type->base() != right_type->base()
4503 && op != OPERATOR_LSHIFT
4504 && op != OPERATOR_RSHIFT)
4505 {
4506 // May be a type error--let it be diagnosed elsewhere.
4507 return false;
4508 }
4509
4510 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4511 {
4512 if (left_type->integer_type() != NULL)
4513 *result_type = left_type;
4514 else
4515 *result_type = Type::make_abstract_integer_type();
4516 }
4517 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4518 *result_type = left_type;
4519 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4520 *result_type = right_type;
4521 else if (!left_type->is_abstract())
4522 *result_type = left_type;
4523 else if (!right_type->is_abstract())
4524 *result_type = right_type;
4525 else if (left_type->complex_type() != NULL)
4526 *result_type = left_type;
4527 else if (right_type->complex_type() != NULL)
4528 *result_type = right_type;
4529 else if (left_type->float_type() != NULL)
4530 *result_type = left_type;
4531 else if (right_type->float_type() != NULL)
4532 *result_type = right_type;
4533 else if (left_type->integer_type() != NULL
4534 && left_type->integer_type()->is_rune())
4535 *result_type = left_type;
4536 else if (right_type->integer_type() != NULL
4537 && right_type->integer_type()->is_rune())
4538 *result_type = right_type;
4539 else
4540 *result_type = left_type;
4541
4542 return true;
4543}
4544
4545// Convert an integer comparison code and an operator to a boolean
4546// value.
e440a328 4547
4548bool
0c77715b 4549Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4550{
e440a328 4551 switch (op)
4552 {
4553 case OPERATOR_EQEQ:
0c77715b 4554 return cmp == 0;
4555 break;
e440a328 4556 case OPERATOR_NOTEQ:
0c77715b 4557 return cmp != 0;
4558 break;
e440a328 4559 case OPERATOR_LT:
0c77715b 4560 return cmp < 0;
4561 break;
e440a328 4562 case OPERATOR_LE:
0c77715b 4563 return cmp <= 0;
e440a328 4564 case OPERATOR_GT:
0c77715b 4565 return cmp > 0;
e440a328 4566 case OPERATOR_GE:
0c77715b 4567 return cmp >= 0;
e440a328 4568 default:
c3e6f413 4569 go_unreachable();
e440a328 4570 }
4571}
4572
0c77715b 4573// Compare constants according to OP.
e440a328 4574
4575bool
0c77715b 4576Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4577 Numeric_constant* right_nc,
4578 Location location, bool* result)
e440a328 4579{
0c77715b 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 // When comparing an untyped operand to a typed operand, we are
4588 // effectively coercing the untyped operand to the other operand's
4589 // type, so make sure that is valid.
4590 if (!left_nc->set_type(type, true, location)
4591 || !right_nc->set_type(type, true, location))
4592 return false;
4593
4594 bool ret;
4595 int cmp;
4596 if (type->complex_type() != NULL)
4597 {
4598 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4599 return false;
4600 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4601 }
4602 else if (type->float_type() != NULL)
4603 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4604 else
0c77715b 4605 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4606
4607 if (ret)
4608 *result = Binary_expression::cmp_to_bool(op, cmp);
4609
4610 return ret;
4611}
4612
4613// Compare integer constants.
4614
4615bool
4616Binary_expression::compare_integer(const Numeric_constant* left_nc,
4617 const Numeric_constant* right_nc,
4618 int* cmp)
4619{
4620 mpz_t left_val;
4621 if (!left_nc->to_int(&left_val))
4622 return false;
4623 mpz_t right_val;
4624 if (!right_nc->to_int(&right_val))
e440a328 4625 {
0c77715b 4626 mpz_clear(left_val);
4627 return false;
e440a328 4628 }
0c77715b 4629
4630 *cmp = mpz_cmp(left_val, right_val);
4631
4632 mpz_clear(left_val);
4633 mpz_clear(right_val);
4634
4635 return true;
4636}
4637
4638// Compare floating point constants.
4639
4640bool
4641Binary_expression::compare_float(const Numeric_constant* left_nc,
4642 const Numeric_constant* right_nc,
4643 int* cmp)
4644{
4645 mpfr_t left_val;
4646 if (!left_nc->to_float(&left_val))
4647 return false;
4648 mpfr_t right_val;
4649 if (!right_nc->to_float(&right_val))
e440a328 4650 {
0c77715b 4651 mpfr_clear(left_val);
4652 return false;
4653 }
4654
4655 // We already coerced both operands to the same type. If that type
4656 // is not an abstract type, we need to round the values accordingly.
4657 Type* type = left_nc->type();
4658 if (!type->is_abstract() && type->float_type() != NULL)
4659 {
4660 int bits = type->float_type()->bits();
4661 mpfr_prec_round(left_val, bits, GMP_RNDN);
4662 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4663 }
0c77715b 4664
4665 *cmp = mpfr_cmp(left_val, right_val);
4666
4667 mpfr_clear(left_val);
4668 mpfr_clear(right_val);
4669
4670 return true;
e440a328 4671}
4672
0c77715b 4673// Compare complex constants. Complex numbers may only be compared
4674// for equality.
e440a328 4675
4676bool
0c77715b 4677Binary_expression::compare_complex(const Numeric_constant* left_nc,
4678 const Numeric_constant* right_nc,
4679 int* cmp)
e440a328 4680{
fcbea5e4 4681 mpc_t left_val;
4682 if (!left_nc->to_complex(&left_val))
0c77715b 4683 return false;
fcbea5e4 4684 mpc_t right_val;
4685 if (!right_nc->to_complex(&right_val))
e440a328 4686 {
fcbea5e4 4687 mpc_clear(left_val);
0c77715b 4688 return false;
e440a328 4689 }
0c77715b 4690
4691 // We already coerced both operands to the same type. If that type
4692 // is not an abstract type, we need to round the values accordingly.
4693 Type* type = left_nc->type();
4694 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4695 {
0c77715b 4696 int bits = type->complex_type()->bits();
fcbea5e4 4697 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4698 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4699 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4700 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
e440a328 4701 }
0c77715b 4702
fcbea5e4 4703 *cmp = mpc_cmp(left_val, right_val) != 0;
0c77715b 4704
fcbea5e4 4705 mpc_clear(left_val);
4706 mpc_clear(right_val);
0c77715b 4707
4708 return true;
e440a328 4709}
4710
0c77715b 4711// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4712// true if this could be done, false if not. Issue errors at LOCATION
4713// as appropriate.
e440a328 4714
4715bool
0c77715b 4716Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4717 Numeric_constant* right_nc,
4718 Location location, Numeric_constant* nc)
e440a328 4719{
e440a328 4720 switch (op)
4721 {
4722 case OPERATOR_OROR:
4723 case OPERATOR_ANDAND:
4724 case OPERATOR_EQEQ:
4725 case OPERATOR_NOTEQ:
4726 case OPERATOR_LT:
4727 case OPERATOR_LE:
4728 case OPERATOR_GT:
4729 case OPERATOR_GE:
9767e2d3 4730 // These return boolean values, not numeric.
4731 return false;
0c77715b 4732 default:
4733 break;
4734 }
4735
4736 Type* left_type = left_nc->type();
4737 Type* right_type = right_nc->type();
4738
4739 Type* type;
4740 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4741 return false;
4742
4743 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4744
4745 // When combining an untyped operand with a typed operand, we are
4746 // effectively coercing the untyped operand to the other operand's
4747 // type, so make sure that is valid.
4748 if (!left_nc->set_type(type, true, location))
4749 return false;
4750 if (!is_shift && !right_nc->set_type(type, true, location))
4751 return false;
85334a21 4752 if (is_shift
4753 && ((left_type->integer_type() == NULL
4754 && !left_type->is_abstract())
4755 || (right_type->integer_type() == NULL
4756 && !right_type->is_abstract())))
4757 return false;
0c77715b 4758
4759 bool r;
4760 if (type->complex_type() != NULL)
4761 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4762 else if (type->float_type() != NULL)
4763 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4764 else
4765 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4766
4767 if (r)
4768 r = nc->set_type(type, true, location);
4769
4770 return r;
4771}
4772
4773// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4774// integer operations. Return true if this could be done, false if
4775// not.
4776
4777bool
4778Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4779 const Numeric_constant* right_nc,
4780 Location location, Numeric_constant* nc)
4781{
4782 mpz_t left_val;
4783 if (!left_nc->to_int(&left_val))
4784 return false;
4785 mpz_t right_val;
4786 if (!right_nc->to_int(&right_val))
4787 {
4788 mpz_clear(left_val);
e440a328 4789 return false;
0c77715b 4790 }
4791
4792 mpz_t val;
4793 mpz_init(val);
4794
4795 switch (op)
4796 {
e440a328 4797 case OPERATOR_PLUS:
4798 mpz_add(val, left_val, right_val);
2c809f8f 4799 if (mpz_sizeinbase(val, 2) > 0x100000)
4800 {
631d5788 4801 go_error_at(location, "constant addition overflow");
71a45216 4802 nc->set_invalid();
2c809f8f 4803 mpz_set_ui(val, 1);
4804 }
e440a328 4805 break;
4806 case OPERATOR_MINUS:
4807 mpz_sub(val, left_val, right_val);
2c809f8f 4808 if (mpz_sizeinbase(val, 2) > 0x100000)
4809 {
631d5788 4810 go_error_at(location, "constant subtraction overflow");
71a45216 4811 nc->set_invalid();
2c809f8f 4812 mpz_set_ui(val, 1);
4813 }
e440a328 4814 break;
4815 case OPERATOR_OR:
4816 mpz_ior(val, left_val, right_val);
4817 break;
4818 case OPERATOR_XOR:
4819 mpz_xor(val, left_val, right_val);
4820 break;
4821 case OPERATOR_MULT:
4822 mpz_mul(val, left_val, right_val);
2c809f8f 4823 if (mpz_sizeinbase(val, 2) > 0x100000)
4824 {
631d5788 4825 go_error_at(location, "constant multiplication overflow");
71a45216 4826 nc->set_invalid();
2c809f8f 4827 mpz_set_ui(val, 1);
4828 }
e440a328 4829 break;
4830 case OPERATOR_DIV:
4831 if (mpz_sgn(right_val) != 0)
4832 mpz_tdiv_q(val, left_val, right_val);
4833 else
4834 {
631d5788 4835 go_error_at(location, "division by zero");
71a45216 4836 nc->set_invalid();
e440a328 4837 mpz_set_ui(val, 0);
e440a328 4838 }
4839 break;
4840 case OPERATOR_MOD:
4841 if (mpz_sgn(right_val) != 0)
4842 mpz_tdiv_r(val, left_val, right_val);
4843 else
4844 {
631d5788 4845 go_error_at(location, "division by zero");
71a45216 4846 nc->set_invalid();
e440a328 4847 mpz_set_ui(val, 0);
e440a328 4848 }
4849 break;
4850 case OPERATOR_LSHIFT:
4851 {
4852 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4853 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4854 mpz_mul_2exp(val, left_val, shift);
4855 else
e440a328 4856 {
631d5788 4857 go_error_at(location, "shift count overflow");
71a45216 4858 nc->set_invalid();
2c809f8f 4859 mpz_set_ui(val, 1);
e440a328 4860 }
e440a328 4861 break;
4862 }
4863 break;
4864 case OPERATOR_RSHIFT:
4865 {
4866 unsigned long shift = mpz_get_ui(right_val);
4867 if (mpz_cmp_ui(right_val, shift) != 0)
4868 {
631d5788 4869 go_error_at(location, "shift count overflow");
71a45216 4870 nc->set_invalid();
2c809f8f 4871 mpz_set_ui(val, 1);
e440a328 4872 }
e440a328 4873 else
0c77715b 4874 {
4875 if (mpz_cmp_ui(left_val, 0) >= 0)
4876 mpz_tdiv_q_2exp(val, left_val, shift);
4877 else
4878 mpz_fdiv_q_2exp(val, left_val, shift);
4879 }
e440a328 4880 break;
4881 }
4882 break;
4883 case OPERATOR_AND:
4884 mpz_and(val, left_val, right_val);
4885 break;
4886 case OPERATOR_BITCLEAR:
4887 {
4888 mpz_t tval;
4889 mpz_init(tval);
4890 mpz_com(tval, right_val);
4891 mpz_and(val, left_val, tval);
4892 mpz_clear(tval);
4893 }
4894 break;
4895 default:
c3e6f413 4896 go_unreachable();
e440a328 4897 }
4898
0c77715b 4899 mpz_clear(left_val);
4900 mpz_clear(right_val);
e440a328 4901
0c77715b 4902 if (left_nc->is_rune()
4903 || (op != OPERATOR_LSHIFT
4904 && op != OPERATOR_RSHIFT
4905 && right_nc->is_rune()))
4906 nc->set_rune(NULL, val);
4907 else
4908 nc->set_int(NULL, val);
4909
4910 mpz_clear(val);
e440a328 4911
4912 return true;
4913}
4914
0c77715b 4915// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4916// floating point operations. Return true if this could be done,
4917// false if not.
e440a328 4918
4919bool
0c77715b 4920Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4921 const Numeric_constant* right_nc,
4922 Location location, Numeric_constant* nc)
e440a328 4923{
0c77715b 4924 mpfr_t left_val;
4925 if (!left_nc->to_float(&left_val))
4926 return false;
4927 mpfr_t right_val;
4928 if (!right_nc->to_float(&right_val))
e440a328 4929 {
0c77715b 4930 mpfr_clear(left_val);
e440a328 4931 return false;
0c77715b 4932 }
4933
4934 mpfr_t val;
4935 mpfr_init(val);
4936
4937 bool ret = true;
4938 switch (op)
4939 {
e440a328 4940 case OPERATOR_PLUS:
4941 mpfr_add(val, left_val, right_val, GMP_RNDN);
4942 break;
4943 case OPERATOR_MINUS:
4944 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4945 break;
4946 case OPERATOR_OR:
4947 case OPERATOR_XOR:
4948 case OPERATOR_AND:
4949 case OPERATOR_BITCLEAR:
0c77715b 4950 case OPERATOR_MOD:
4951 case OPERATOR_LSHIFT:
4952 case OPERATOR_RSHIFT:
4953 mpfr_set_ui(val, 0, GMP_RNDN);
4954 ret = false;
4955 break;
e440a328 4956 case OPERATOR_MULT:
4957 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4958 break;
4959 case OPERATOR_DIV:
0c77715b 4960 if (!mpfr_zero_p(right_val))
4961 mpfr_div(val, left_val, right_val, GMP_RNDN);
4962 else
4963 {
631d5788 4964 go_error_at(location, "division by zero");
71a45216 4965 nc->set_invalid();
0c77715b 4966 mpfr_set_ui(val, 0, GMP_RNDN);
4967 }
e440a328 4968 break;
e440a328 4969 default:
c3e6f413 4970 go_unreachable();
e440a328 4971 }
4972
0c77715b 4973 mpfr_clear(left_val);
4974 mpfr_clear(right_val);
e440a328 4975
0c77715b 4976 nc->set_float(NULL, val);
4977 mpfr_clear(val);
e440a328 4978
0c77715b 4979 return ret;
e440a328 4980}
4981
0c77715b 4982// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4983// complex operations. Return true if this could be done, false if
4984// not.
e440a328 4985
4986bool
0c77715b 4987Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4988 const Numeric_constant* right_nc,
4989 Location location, Numeric_constant* nc)
e440a328 4990{
fcbea5e4 4991 mpc_t left_val;
4992 if (!left_nc->to_complex(&left_val))
0c77715b 4993 return false;
fcbea5e4 4994 mpc_t right_val;
4995 if (!right_nc->to_complex(&right_val))
e440a328 4996 {
fcbea5e4 4997 mpc_clear(left_val);
e440a328 4998 return false;
0c77715b 4999 }
5000
fcbea5e4 5001 mpc_t val;
5002 mpc_init2(val, mpc_precision);
0c77715b 5003
5004 bool ret = true;
5005 switch (op)
5006 {
e440a328 5007 case OPERATOR_PLUS:
fcbea5e4 5008 mpc_add(val, left_val, right_val, MPC_RNDNN);
e440a328 5009 break;
5010 case OPERATOR_MINUS:
fcbea5e4 5011 mpc_sub(val, left_val, right_val, MPC_RNDNN);
e440a328 5012 break;
5013 case OPERATOR_OR:
5014 case OPERATOR_XOR:
5015 case OPERATOR_AND:
5016 case OPERATOR_BITCLEAR:
0c77715b 5017 case OPERATOR_MOD:
5018 case OPERATOR_LSHIFT:
5019 case OPERATOR_RSHIFT:
fcbea5e4 5020 mpc_set_ui(val, 0, MPC_RNDNN);
0c77715b 5021 ret = false;
5022 break;
e440a328 5023 case OPERATOR_MULT:
fcbea5e4 5024 mpc_mul(val, left_val, right_val, MPC_RNDNN);
e440a328 5025 break;
5026 case OPERATOR_DIV:
fcbea5e4 5027 if (mpc_cmp_si(right_val, 0) == 0)
5028 {
631d5788 5029 go_error_at(location, "division by zero");
71a45216 5030 nc->set_invalid();
fcbea5e4 5031 mpc_set_ui(val, 0, MPC_RNDNN);
5032 break;
5033 }
5034 mpc_div(val, left_val, right_val, MPC_RNDNN);
e440a328 5035 break;
e440a328 5036 default:
c3e6f413 5037 go_unreachable();
e440a328 5038 }
5039
fcbea5e4 5040 mpc_clear(left_val);
5041 mpc_clear(right_val);
e440a328 5042
fcbea5e4 5043 nc->set_complex(NULL, val);
5044 mpc_clear(val);
e440a328 5045
0c77715b 5046 return ret;
e440a328 5047}
5048
5049// Lower a binary expression. We have to evaluate constant
5050// expressions now, in order to implement Go's unlimited precision
5051// constants.
5052
5053Expression*
e9d3367e 5054Binary_expression::do_lower(Gogo* gogo, Named_object*,
5055 Statement_inserter* inserter, int)
e440a328 5056{
b13c66cd 5057 Location location = this->location();
e440a328 5058 Operator op = this->op_;
5059 Expression* left = this->left_;
5060 Expression* right = this->right_;
5061
5062 const bool is_comparison = (op == OPERATOR_EQEQ
5063 || op == OPERATOR_NOTEQ
5064 || op == OPERATOR_LT
5065 || op == OPERATOR_LE
5066 || op == OPERATOR_GT
5067 || op == OPERATOR_GE);
5068
0c77715b 5069 // Numeric constant expressions.
e440a328 5070 {
0c77715b 5071 Numeric_constant left_nc;
5072 Numeric_constant right_nc;
5073 if (left->numeric_constant_value(&left_nc)
5074 && right->numeric_constant_value(&right_nc))
e440a328 5075 {
0c77715b 5076 if (is_comparison)
e440a328 5077 {
0c77715b 5078 bool result;
5079 if (!Binary_expression::compare_constant(op, &left_nc,
5080 &right_nc, location,
5081 &result))
5082 return this;
e90c9dfc 5083 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5084 Expression::make_boolean(result,
5085 location),
5086 location);
e440a328 5087 }
5088 else
5089 {
0c77715b 5090 Numeric_constant nc;
5091 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5092 location, &nc))
71a45216 5093 return this;
0c77715b 5094 return nc.expression(location);
e440a328 5095 }
5096 }
e440a328 5097 }
5098
5099 // String constant expressions.
315fa98d 5100 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5101 {
5102 std::string left_string;
5103 std::string right_string;
5104 if (left->string_constant_value(&left_string)
5105 && right->string_constant_value(&right_string))
315fa98d 5106 {
5107 if (op == OPERATOR_PLUS)
5108 return Expression::make_string(left_string + right_string,
5109 location);
5110 else if (is_comparison)
5111 {
5112 int cmp = left_string.compare(right_string);
0c77715b 5113 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5114 return Expression::make_boolean(r, location);
b40dc774 5115 }
5116 }
b40dc774 5117 }
5118
ceeb12d7 5119 // Lower struct, array, and some interface comparisons.
e9d3367e 5120 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5121 {
b79832ca 5122 if (left->type()->struct_type() != NULL
5123 && right->type()->struct_type() != NULL)
e9d3367e 5124 return this->lower_struct_comparison(gogo, inserter);
5125 else if (left->type()->array_type() != NULL
b79832ca 5126 && !left->type()->is_slice_type()
5127 && right->type()->array_type() != NULL
5128 && !right->type()->is_slice_type())
e9d3367e 5129 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5130 else if ((left->type()->interface_type() != NULL
5131 && right->type()->interface_type() == NULL)
5132 || (left->type()->interface_type() == NULL
5133 && right->type()->interface_type() != NULL))
5134 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5135 }
5136
736a16ba 5137 // Lower string concatenation to String_concat_expression, so that
5138 // we can group sequences of string additions.
5139 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5140 {
5141 Expression_list* exprs;
5142 String_concat_expression* left_sce =
5143 this->left_->string_concat_expression();
5144 if (left_sce != NULL)
5145 exprs = left_sce->exprs();
5146 else
5147 {
5148 exprs = new Expression_list();
5149 exprs->push_back(this->left_);
5150 }
5151
5152 String_concat_expression* right_sce =
5153 this->right_->string_concat_expression();
5154 if (right_sce != NULL)
5155 exprs->append(right_sce->exprs());
5156 else
5157 exprs->push_back(this->right_);
5158
5159 return Expression::make_string_concat(exprs);
5160 }
5161
e440a328 5162 return this;
5163}
5164
e9d3367e 5165// Lower a struct comparison.
5166
5167Expression*
5168Binary_expression::lower_struct_comparison(Gogo* gogo,
5169 Statement_inserter* inserter)
5170{
5171 Struct_type* st = this->left_->type()->struct_type();
5172 Struct_type* st2 = this->right_->type()->struct_type();
5173 if (st2 == NULL)
5174 return this;
5175 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5176 return this;
5177 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5178 this->right_->type(), NULL))
5179 return this;
5180
5181 // See if we can compare using memcmp. As a heuristic, we use
5182 // memcmp rather than field references and comparisons if there are
5183 // more than two fields.
113ef6a5 5184 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5185 return this->lower_compare_to_memcmp(gogo, inserter);
5186
5187 Location loc = this->location();
5188
5189 Expression* left = this->left_;
5190 Temporary_statement* left_temp = NULL;
5191 if (left->var_expression() == NULL
5192 && left->temporary_reference_expression() == NULL)
5193 {
5194 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5195 inserter->insert(left_temp);
5196 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5197 }
5198
5199 Expression* right = this->right_;
5200 Temporary_statement* right_temp = NULL;
5201 if (right->var_expression() == NULL
5202 && right->temporary_reference_expression() == NULL)
5203 {
5204 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5205 inserter->insert(right_temp);
5206 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5207 }
5208
5209 Expression* ret = Expression::make_boolean(true, loc);
5210 const Struct_field_list* fields = st->fields();
5211 unsigned int field_index = 0;
5212 for (Struct_field_list::const_iterator pf = fields->begin();
5213 pf != fields->end();
5214 ++pf, ++field_index)
5215 {
f5165c05 5216 if (Gogo::is_sink_name(pf->field_name()))
5217 continue;
5218
e9d3367e 5219 if (field_index > 0)
5220 {
5221 if (left_temp == NULL)
5222 left = left->copy();
5223 else
5224 left = Expression::make_temporary_reference(left_temp, loc);
5225 if (right_temp == NULL)
5226 right = right->copy();
5227 else
5228 right = Expression::make_temporary_reference(right_temp, loc);
5229 }
5230 Expression* f1 = Expression::make_field_reference(left, field_index,
5231 loc);
5232 Expression* f2 = Expression::make_field_reference(right, field_index,
5233 loc);
5234 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5235 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5236 }
5237
5238 if (this->op_ == OPERATOR_NOTEQ)
5239 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5240
5241 return ret;
5242}
5243
5244// Lower an array comparison.
5245
5246Expression*
5247Binary_expression::lower_array_comparison(Gogo* gogo,
5248 Statement_inserter* inserter)
5249{
5250 Array_type* at = this->left_->type()->array_type();
5251 Array_type* at2 = this->right_->type()->array_type();
5252 if (at2 == NULL)
5253 return this;
5254 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5255 return this;
5256 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5257 this->right_->type(), NULL))
5258 return this;
5259
5260 // Call memcmp directly if possible. This may let the middle-end
5261 // optimize the call.
113ef6a5 5262 if (at->compare_is_identity(gogo))
e9d3367e 5263 return this->lower_compare_to_memcmp(gogo, inserter);
5264
5265 // Call the array comparison function.
5266 Named_object* hash_fn;
5267 Named_object* equal_fn;
5268 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5269 &hash_fn, &equal_fn);
5270
5271 Location loc = this->location();
5272
5273 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5274
5275 Expression_list* args = new Expression_list();
5276 args->push_back(this->operand_address(inserter, this->left_));
5277 args->push_back(this->operand_address(inserter, this->right_));
5278 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5279
5280 Expression* ret = Expression::make_call(func, args, false, loc);
5281
5282 if (this->op_ == OPERATOR_NOTEQ)
5283 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5284
5285 return ret;
5286}
5287
ceeb12d7 5288// Lower an interface to value comparison.
5289
5290Expression*
5291Binary_expression::lower_interface_value_comparison(Gogo*,
5292 Statement_inserter* inserter)
5293{
5294 Type* left_type = this->left_->type();
5295 Type* right_type = this->right_->type();
5296 Interface_type* ift;
5297 if (left_type->interface_type() != NULL)
5298 {
5299 ift = left_type->interface_type();
5300 if (!ift->implements_interface(right_type, NULL))
5301 return this;
5302 }
5303 else
5304 {
5305 ift = right_type->interface_type();
5306 if (!ift->implements_interface(left_type, NULL))
5307 return this;
5308 }
5309 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5310 return this;
5311
5312 Location loc = this->location();
5313
5314 if (left_type->interface_type() == NULL
5315 && left_type->points_to() == NULL
5316 && !this->left_->is_addressable())
5317 {
5318 Temporary_statement* temp =
5319 Statement::make_temporary(left_type, NULL, loc);
5320 inserter->insert(temp);
5321 this->left_ =
5322 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5323 }
5324
5325 if (right_type->interface_type() == NULL
5326 && right_type->points_to() == NULL
5327 && !this->right_->is_addressable())
5328 {
5329 Temporary_statement* temp =
5330 Statement::make_temporary(right_type, NULL, loc);
5331 inserter->insert(temp);
5332 this->right_ =
5333 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5334 }
5335
5336 return this;
5337}
5338
e9d3367e 5339// Lower a struct or array comparison to a call to memcmp.
5340
5341Expression*
5342Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5343{
5344 Location loc = this->location();
5345
5346 Expression* a1 = this->operand_address(inserter, this->left_);
5347 Expression* a2 = this->operand_address(inserter, this->right_);
5348 Expression* len = Expression::make_type_info(this->left_->type(),
5349 TYPE_INFO_SIZE);
5350
5351 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
e67508fa 5352 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
e9d3367e 5353 return Expression::make_binary(this->op_, call, zero, loc);
5354}
5355
a32698ee 5356Expression*
5c3f3470 5357Binary_expression::do_flatten(Gogo* gogo, Named_object*,
a32698ee 5358 Statement_inserter* inserter)
5359{
5360 Location loc = this->location();
5bf8be8b 5361 if (this->left_->type()->is_error_type()
5362 || this->right_->type()->is_error_type()
5363 || this->left_->is_error_expression()
5364 || this->right_->is_error_expression())
5365 {
5366 go_assert(saw_errors());
5367 return Expression::make_error(loc);
5368 }
5369
a32698ee 5370 Temporary_statement* temp;
a32698ee 5371
5372 Type* left_type = this->left_->type();
5373 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5374 || this->op_ == OPERATOR_RSHIFT);
5375 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5376 left_type->integer_type() != NULL)
5377 || this->op_ == OPERATOR_MOD);
5378
a32698ee 5379 if (is_shift_op
5c3f3470 5380 || (is_idiv_op
5381 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
a32698ee 5382 {
545ab43b 5383 if (!this->left_->is_variable() && !this->left_->is_constant())
a32698ee 5384 {
5385 temp = Statement::make_temporary(NULL, this->left_, loc);
5386 inserter->insert(temp);
5387 this->left_ = Expression::make_temporary_reference(temp, loc);
5388 }
545ab43b 5389 if (!this->right_->is_variable() && !this->right_->is_constant())
a32698ee 5390 {
5391 temp =
5392 Statement::make_temporary(NULL, this->right_, loc);
5393 this->right_ = Expression::make_temporary_reference(temp, loc);
5394 inserter->insert(temp);
5395 }
5396 }
5397 return this;
5398}
5399
5400
e9d3367e 5401// Return the address of EXPR, cast to unsafe.Pointer.
5402
5403Expression*
5404Binary_expression::operand_address(Statement_inserter* inserter,
5405 Expression* expr)
5406{
5407 Location loc = this->location();
5408
5409 if (!expr->is_addressable())
5410 {
5411 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5412 loc);
5413 inserter->insert(temp);
5414 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5415 }
5416 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5417 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5418 Type* void_type = Type::make_void_type();
5419 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5420 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5421}
5422
0c77715b 5423// Return the numeric constant value, if it has one.
e440a328 5424
5425bool
0c77715b 5426Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5427{
0c77715b 5428 Numeric_constant left_nc;
5429 if (!this->left_->numeric_constant_value(&left_nc))
5430 return false;
5431 Numeric_constant right_nc;
5432 if (!this->right_->numeric_constant_value(&right_nc))
5433 return false;
9767e2d3 5434 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5435 this->location(), nc);
e440a328 5436}
5437
5438// Note that the value is being discarded.
5439
4f2138d7 5440bool
e440a328 5441Binary_expression::do_discarding_value()
5442{
5443 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5444 return this->right_->discarding_value();
e440a328 5445 else
4f2138d7 5446 {
5447 this->unused_value_error();
5448 return false;
5449 }
e440a328 5450}
5451
5452// Get type.
5453
5454Type*
5455Binary_expression::do_type()
5456{
5f5fea79 5457 if (this->classification() == EXPRESSION_ERROR)
5458 return Type::make_error_type();
5459
e440a328 5460 switch (this->op_)
5461 {
e440a328 5462 case OPERATOR_EQEQ:
5463 case OPERATOR_NOTEQ:
5464 case OPERATOR_LT:
5465 case OPERATOR_LE:
5466 case OPERATOR_GT:
5467 case OPERATOR_GE:
e90c9dfc 5468 if (this->type_ == NULL)
5469 this->type_ = Type::make_boolean_type();
5470 return this->type_;
e440a328 5471
5472 case OPERATOR_PLUS:
5473 case OPERATOR_MINUS:
5474 case OPERATOR_OR:
5475 case OPERATOR_XOR:
5476 case OPERATOR_MULT:
5477 case OPERATOR_DIV:
5478 case OPERATOR_MOD:
5479 case OPERATOR_AND:
5480 case OPERATOR_BITCLEAR:
e90c9dfc 5481 case OPERATOR_OROR:
5482 case OPERATOR_ANDAND:
e440a328 5483 {
0c77715b 5484 Type* type;
5485 if (!Binary_expression::operation_type(this->op_,
5486 this->left_->type(),
5487 this->right_->type(),
5488 &type))
5489 return Type::make_error_type();
5490 return type;
e440a328 5491 }
5492
5493 case OPERATOR_LSHIFT:
5494 case OPERATOR_RSHIFT:
5495 return this->left_->type();
5496
5497 default:
c3e6f413 5498 go_unreachable();
e440a328 5499 }
5500}
5501
5502// Set type for a binary expression.
5503
5504void
5505Binary_expression::do_determine_type(const Type_context* context)
5506{
5507 Type* tleft = this->left_->type();
5508 Type* tright = this->right_->type();
5509
5510 // Both sides should have the same type, except for the shift
5511 // operations. For a comparison, we should ignore the incoming
5512 // type.
5513
5514 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5515 || this->op_ == OPERATOR_RSHIFT);
5516
5517 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5518 || this->op_ == OPERATOR_NOTEQ
5519 || this->op_ == OPERATOR_LT
5520 || this->op_ == OPERATOR_LE
5521 || this->op_ == OPERATOR_GT
5522 || this->op_ == OPERATOR_GE);
5523
c999c2a7 5524 // For constant expressions, the context of the result is not useful in
5525 // determining the types of the operands. It is only legal to use abstract
5526 // boolean, numeric, and string constants as operands where it is legal to
5527 // use non-abstract boolean, numeric, and string constants, respectively.
5528 // Any issues with the operation will be resolved in the check_types pass.
5529 bool is_constant_expr = (this->left_->is_constant()
5530 && this->right_->is_constant());
5531
e440a328 5532 Type_context subcontext(*context);
5533
5534 if (is_comparison)
5535 {
5536 // In a comparison, the context does not determine the types of
5537 // the operands.
5538 subcontext.type = NULL;
5539 }
5540
5541 // Set the context for the left hand operand.
5542 if (is_shift_op)
5543 {
b40dc774 5544 // The right hand operand of a shift plays no role in
5545 // determining the type of the left hand operand.
e440a328 5546 }
5547 else if (!tleft->is_abstract())
5548 subcontext.type = tleft;
5549 else if (!tright->is_abstract())
5550 subcontext.type = tright;
5551 else if (subcontext.type == NULL)
5552 {
5553 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5554 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5555 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5556 {
5557 // Both sides have an abstract integer, abstract float, or
5558 // abstract complex type. Just let CONTEXT determine
5559 // whether they may remain abstract or not.
5560 }
5561 else if (tleft->complex_type() != NULL)
5562 subcontext.type = tleft;
5563 else if (tright->complex_type() != NULL)
5564 subcontext.type = tright;
5565 else if (tleft->float_type() != NULL)
5566 subcontext.type = tleft;
5567 else if (tright->float_type() != NULL)
5568 subcontext.type = tright;
5569 else
5570 subcontext.type = tleft;
f58a23ae 5571
5572 if (subcontext.type != NULL && !context->may_be_abstract)
5573 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5574 }
5575
c999c2a7 5576 if (!is_constant_expr)
5577 this->left_->determine_type(&subcontext);
e440a328 5578
e440a328 5579 if (is_shift_op)
5580 {
b40dc774 5581 // We may have inherited an unusable type for the shift operand.
5582 // Give a useful error if that happened.
5583 if (tleft->is_abstract()
5584 && subcontext.type != NULL
8ab6effb 5585 && !subcontext.may_be_abstract
f6bc81e6 5586 && subcontext.type->interface_type() == NULL
8ab6effb 5587 && subcontext.type->integer_type() == NULL)
b40dc774 5588 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5589 "for left operand of shift"));
b40dc774 5590
5591 // The context for the right hand operand is the same as for the
5592 // left hand operand, except for a shift operator.
e440a328 5593 subcontext.type = Type::lookup_integer_type("uint");
5594 subcontext.may_be_abstract = false;
5595 }
5596
c999c2a7 5597 if (!is_constant_expr)
5598 this->right_->determine_type(&subcontext);
e90c9dfc 5599
5600 if (is_comparison)
5601 {
5602 if (this->type_ != NULL && !this->type_->is_abstract())
5603 ;
5604 else if (context->type != NULL && context->type->is_boolean_type())
5605 this->type_ = context->type;
5606 else if (!context->may_be_abstract)
5607 this->type_ = Type::lookup_bool_type();
5608 }
e440a328 5609}
5610
5611// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5612// OTYPE is the type of the other operand. Return whether the
5613// operation is OK. This should not be used for shift.
e440a328 5614
5615bool
be8b5eee 5616Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5617 Location location)
e440a328 5618{
5619 switch (op)
5620 {
5621 case OPERATOR_OROR:
5622 case OPERATOR_ANDAND:
c999c2a7 5623 if (!type->is_boolean_type()
5624 || !otype->is_boolean_type())
e440a328 5625 {
631d5788 5626 go_error_at(location, "expected boolean type");
e440a328 5627 return false;
5628 }
5629 break;
5630
5631 case OPERATOR_EQEQ:
5632 case OPERATOR_NOTEQ:
e9d3367e 5633 {
5634 std::string reason;
5635 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5636 {
631d5788 5637 go_error_at(location, "%s", reason.c_str());
e9d3367e 5638 return false;
5639 }
5640 }
e440a328 5641 break;
5642
5643 case OPERATOR_LT:
5644 case OPERATOR_LE:
5645 case OPERATOR_GT:
5646 case OPERATOR_GE:
e9d3367e 5647 {
5648 std::string reason;
5649 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5650 {
631d5788 5651 go_error_at(location, "%s", reason.c_str());
e9d3367e 5652 return false;
5653 }
5654 }
e440a328 5655 break;
5656
5657 case OPERATOR_PLUS:
5658 case OPERATOR_PLUSEQ:
c999c2a7 5659 if ((!type->is_numeric_type() && !type->is_string_type())
5660 || (!otype->is_numeric_type() && !otype->is_string_type()))
e440a328 5661 {
631d5788 5662 go_error_at(location,
e440a328 5663 "expected integer, floating, complex, or string type");
5664 return false;
5665 }
5666 break;
5667
5668 case OPERATOR_MINUS:
5669 case OPERATOR_MINUSEQ:
5670 case OPERATOR_MULT:
5671 case OPERATOR_MULTEQ:
5672 case OPERATOR_DIV:
5673 case OPERATOR_DIVEQ:
c999c2a7 5674 if (!type->is_numeric_type() || !otype->is_numeric_type())
e440a328 5675 {
631d5788 5676 go_error_at(location, "expected integer, floating, or complex type");
e440a328 5677 return false;
5678 }
5679 break;
5680
5681 case OPERATOR_MOD:
5682 case OPERATOR_MODEQ:
5683 case OPERATOR_OR:
5684 case OPERATOR_OREQ:
5685 case OPERATOR_AND:
5686 case OPERATOR_ANDEQ:
5687 case OPERATOR_XOR:
5688 case OPERATOR_XOREQ:
5689 case OPERATOR_BITCLEAR:
5690 case OPERATOR_BITCLEAREQ:
c999c2a7 5691 if (type->integer_type() == NULL || otype->integer_type() == NULL)
e440a328 5692 {
631d5788 5693 go_error_at(location, "expected integer type");
e440a328 5694 return false;
5695 }
5696 break;
5697
5698 default:
c3e6f413 5699 go_unreachable();
e440a328 5700 }
5701
5702 return true;
5703}
5704
5705// Check types.
5706
5707void
5708Binary_expression::do_check_types(Gogo*)
5709{
5f5fea79 5710 if (this->classification() == EXPRESSION_ERROR)
5711 return;
5712
e440a328 5713 Type* left_type = this->left_->type();
5714 Type* right_type = this->right_->type();
5c13bd80 5715 if (left_type->is_error() || right_type->is_error())
9fe897ef 5716 {
5717 this->set_is_error();
5718 return;
5719 }
e440a328 5720
5721 if (this->op_ == OPERATOR_EQEQ
5722 || this->op_ == OPERATOR_NOTEQ
5723 || this->op_ == OPERATOR_LT
5724 || this->op_ == OPERATOR_LE
5725 || this->op_ == OPERATOR_GT
5726 || this->op_ == OPERATOR_GE)
5727 {
907c5ecd 5728 if (left_type->is_nil_type() && right_type->is_nil_type())
5729 {
5730 this->report_error(_("invalid comparison of nil with nil"));
5731 return;
5732 }
e440a328 5733 if (!Type::are_assignable(left_type, right_type, NULL)
5734 && !Type::are_assignable(right_type, left_type, NULL))
5735 {
5736 this->report_error(_("incompatible types in binary expression"));
5737 return;
5738 }
5739 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5740 right_type,
e440a328 5741 this->location())
5742 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5743 left_type,
e440a328 5744 this->location()))
5745 {
5746 this->set_is_error();
5747 return;
5748 }
5749 }
5750 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5751 {
5752 if (!Type::are_compatible_for_binop(left_type, right_type))
5753 {
5754 this->report_error(_("incompatible types in binary expression"));
5755 return;
5756 }
5757 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5758 right_type,
e440a328 5759 this->location()))
5760 {
5761 this->set_is_error();
5762 return;
5763 }
5c65b19d 5764 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5765 {
5766 // Division by a zero integer constant is an error.
5767 Numeric_constant rconst;
5768 unsigned long rval;
5769 if (left_type->integer_type() != NULL
5770 && this->right_->numeric_constant_value(&rconst)
5771 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5772 && rval == 0)
5773 {
5774 this->report_error(_("integer division by zero"));
5775 return;
5776 }
5777 }
e440a328 5778 }
5779 else
5780 {
5781 if (left_type->integer_type() == NULL)
5782 this->report_error(_("shift of non-integer operand"));
5783
6b5e0fac 5784 if (right_type->is_string_type())
5785 this->report_error(_("shift count not unsigned integer"));
5786 else if (!right_type->is_abstract()
e440a328 5787 && (right_type->integer_type() == NULL
5788 || !right_type->integer_type()->is_unsigned()))
5789 this->report_error(_("shift count not unsigned integer"));
5790 else
5791 {
0c77715b 5792 Numeric_constant nc;
5793 if (this->right_->numeric_constant_value(&nc))
e440a328 5794 {
0c77715b 5795 mpz_t val;
5796 if (!nc.to_int(&val))
5797 this->report_error(_("shift count not unsigned integer"));
5798 else
a4eba91b 5799 {
0c77715b 5800 if (mpz_sgn(val) < 0)
5801 {
5802 this->report_error(_("negative shift count"));
0c77715b 5803 Location rloc = this->right_->location();
e67508fa 5804 this->right_ = Expression::make_integer_ul(0, right_type,
5805 rloc);
0c77715b 5806 }
5807 mpz_clear(val);
a4eba91b 5808 }
e440a328 5809 }
e440a328 5810 }
5811 }
5812}
5813
ea664253 5814// Get the backend representation for a binary expression.
e440a328 5815
ea664253 5816Bexpression*
5817Binary_expression::do_get_backend(Translate_context* context)
e440a328 5818{
1b1f2abf 5819 Gogo* gogo = context->gogo();
a32698ee 5820 Location loc = this->location();
5821 Type* left_type = this->left_->type();
5822 Type* right_type = this->right_->type();
1b1f2abf 5823
e440a328 5824 bool use_left_type = true;
5825 bool is_shift_op = false;
29a2d1d8 5826 bool is_idiv_op = false;
e440a328 5827 switch (this->op_)
5828 {
5829 case OPERATOR_EQEQ:
5830 case OPERATOR_NOTEQ:
5831 case OPERATOR_LT:
5832 case OPERATOR_LE:
5833 case OPERATOR_GT:
5834 case OPERATOR_GE:
ea664253 5835 return Expression::comparison(context, this->type_, this->op_,
5836 this->left_, this->right_, loc);
e440a328 5837
5838 case OPERATOR_OROR:
e440a328 5839 case OPERATOR_ANDAND:
e440a328 5840 use_left_type = false;
5841 break;
5842 case OPERATOR_PLUS:
e440a328 5843 case OPERATOR_MINUS:
e440a328 5844 case OPERATOR_OR:
e440a328 5845 case OPERATOR_XOR:
e440a328 5846 case OPERATOR_MULT:
e440a328 5847 break;
5848 case OPERATOR_DIV:
a32698ee 5849 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5850 break;
729f8831 5851 // Fall through.
e440a328 5852 case OPERATOR_MOD:
29a2d1d8 5853 is_idiv_op = true;
e440a328 5854 break;
5855 case OPERATOR_LSHIFT:
e440a328 5856 case OPERATOR_RSHIFT:
e440a328 5857 is_shift_op = true;
5858 break;
e440a328 5859 case OPERATOR_BITCLEAR:
a32698ee 5860 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5861 case OPERATOR_AND:
e440a328 5862 break;
5863 default:
c3e6f413 5864 go_unreachable();
e440a328 5865 }
5866
736a16ba 5867 // The only binary operation for string is +, and that should have
5868 // been converted to a String_concat_expression in do_lower.
5869 go_assert(!left_type->is_string_type());
a32698ee 5870
5871 // For complex division Go might want slightly different results than the
5872 // backend implementation provides, so we have our own runtime routine.
1850e20c 5873 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5874 {
a32698ee 5875 Runtime::Function complex_code;
1850e20c 5876 switch (this->left_->type()->complex_type()->bits())
5877 {
5878 case 64:
a32698ee 5879 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5880 break;
5881 case 128:
a32698ee 5882 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5883 break;
5884 default:
5885 go_unreachable();
5886 }
a32698ee 5887 Expression* complex_div =
5888 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
ea664253 5889 return complex_div->get_backend(context);
1850e20c 5890 }
5891
ea664253 5892 Bexpression* left = this->left_->get_backend(context);
5893 Bexpression* right = this->right_->get_backend(context);
e440a328 5894
a32698ee 5895 Type* type = use_left_type ? left_type : right_type;
5896 Btype* btype = type->get_backend(gogo);
5897
5898 Bexpression* ret =
5899 gogo->backend()->binary_expression(this->op_, left, right, loc);
5900 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 5901
a32698ee 5902 // Initialize overflow constants.
5903 Bexpression* overflow;
5904 mpz_t zero;
5905 mpz_init_set_ui(zero, 0UL);
5906 mpz_t one;
5907 mpz_init_set_ui(one, 1UL);
5908 mpz_t neg_one;
5909 mpz_init_set_si(neg_one, -1);
e440a328 5910
a32698ee 5911 Btype* left_btype = left_type->get_backend(gogo);
5912 Btype* right_btype = right_type->get_backend(gogo);
e440a328 5913
5914 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 5915 // This is not true in C, so we need to insert a conditional.
e440a328 5916 if (is_shift_op)
5917 {
a32698ee 5918 go_assert(left_type->integer_type() != NULL);
e440a328 5919
a32698ee 5920 mpz_t bitsval;
5921 int bits = left_type->integer_type()->bits();
5922 mpz_init_set_ui(bitsval, bits);
5923 Bexpression* bits_expr =
5924 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5925 Bexpression* compare =
5926 gogo->backend()->binary_expression(OPERATOR_LT,
5927 right, bits_expr, loc);
e440a328 5928
a32698ee 5929 Bexpression* zero_expr =
5930 gogo->backend()->integer_constant_expression(left_btype, zero);
5931 overflow = zero_expr;
e440a328 5932 if (this->op_ == OPERATOR_RSHIFT
a32698ee 5933 && !left_type->integer_type()->is_unsigned())
e440a328 5934 {
a32698ee 5935 Bexpression* neg_expr =
5936 gogo->backend()->binary_expression(OPERATOR_LT, left,
5937 zero_expr, loc);
5938 Bexpression* neg_one_expr =
5939 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5940 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5941 neg_one_expr,
5942 zero_expr, loc);
29a2d1d8 5943 }
a32698ee 5944 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5945 overflow, loc);
5946 mpz_clear(bitsval);
29a2d1d8 5947 }
5948
5949 // Add checks for division by zero and division overflow as needed.
5950 if (is_idiv_op)
5951 {
5c3f3470 5952 if (gogo->check_divide_by_zero())
29a2d1d8 5953 {
5954 // right == 0
a32698ee 5955 Bexpression* zero_expr =
5956 gogo->backend()->integer_constant_expression(right_btype, zero);
5957 Bexpression* check =
5958 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5959 right, zero_expr, loc);
29a2d1d8 5960
a32698ee 5961 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 5962 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
ea664253 5963 Bexpression* crash = gogo->runtime_error(errcode,
5964 loc)->get_backend(context);
29a2d1d8 5965
5966 // right == 0 ? (__go_runtime_error(...), 0) : ret
ea664253 5967 ret = gogo->backend()->conditional_expression(btype, check, crash,
5968 ret, loc);
b13c66cd 5969 }
5970
5c3f3470 5971 if (gogo->check_divide_overflow())
29a2d1d8 5972 {
5973 // right == -1
5974 // FIXME: It would be nice to say that this test is expected
5975 // to return false.
a32698ee 5976
5977 Bexpression* neg_one_expr =
5978 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5979 Bexpression* check =
5980 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5981 right, neg_one_expr, loc);
5982
5983 Bexpression* zero_expr =
5984 gogo->backend()->integer_constant_expression(btype, zero);
5985 Bexpression* one_expr =
5986 gogo->backend()->integer_constant_expression(btype, one);
5987
5988 if (type->integer_type()->is_unsigned())
29a2d1d8 5989 {
5990 // An unsigned -1 is the largest possible number, so
5991 // dividing is always 1 or 0.
a32698ee 5992
5993 Bexpression* cmp =
5994 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5995 left, right, loc);
29a2d1d8 5996 if (this->op_ == OPERATOR_DIV)
a32698ee 5997 overflow =
5998 gogo->backend()->conditional_expression(btype, cmp,
5999 one_expr, zero_expr,
6000 loc);
29a2d1d8 6001 else
a32698ee 6002 overflow =
6003 gogo->backend()->conditional_expression(btype, cmp,
6004 zero_expr, left,
6005 loc);
29a2d1d8 6006 }
6007 else
6008 {
6009 // Computing left / -1 is the same as computing - left,
6010 // which does not overflow since Go sets -fwrapv.
6011 if (this->op_ == OPERATOR_DIV)
a32698ee 6012 {
6013 Expression* negate_expr =
6014 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
ea664253 6015 overflow = negate_expr->get_backend(context);
a32698ee 6016 }
29a2d1d8 6017 else
a32698ee 6018 overflow = zero_expr;
29a2d1d8 6019 }
a32698ee 6020 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6021
6022 // right == -1 ? - left : ret
a32698ee 6023 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6024 ret, loc);
29a2d1d8 6025 }
e440a328 6026 }
6027
a32698ee 6028 mpz_clear(zero);
6029 mpz_clear(one);
6030 mpz_clear(neg_one);
ea664253 6031 return ret;
e440a328 6032}
6033
6034// Export a binary expression.
6035
6036void
6037Binary_expression::do_export(Export* exp) const
6038{
6039 exp->write_c_string("(");
6040 this->left_->export_expression(exp);
6041 switch (this->op_)
6042 {
6043 case OPERATOR_OROR:
6044 exp->write_c_string(" || ");
6045 break;
6046 case OPERATOR_ANDAND:
6047 exp->write_c_string(" && ");
6048 break;
6049 case OPERATOR_EQEQ:
6050 exp->write_c_string(" == ");
6051 break;
6052 case OPERATOR_NOTEQ:
6053 exp->write_c_string(" != ");
6054 break;
6055 case OPERATOR_LT:
6056 exp->write_c_string(" < ");
6057 break;
6058 case OPERATOR_LE:
6059 exp->write_c_string(" <= ");
6060 break;
6061 case OPERATOR_GT:
6062 exp->write_c_string(" > ");
6063 break;
6064 case OPERATOR_GE:
6065 exp->write_c_string(" >= ");
6066 break;
6067 case OPERATOR_PLUS:
6068 exp->write_c_string(" + ");
6069 break;
6070 case OPERATOR_MINUS:
6071 exp->write_c_string(" - ");
6072 break;
6073 case OPERATOR_OR:
6074 exp->write_c_string(" | ");
6075 break;
6076 case OPERATOR_XOR:
6077 exp->write_c_string(" ^ ");
6078 break;
6079 case OPERATOR_MULT:
6080 exp->write_c_string(" * ");
6081 break;
6082 case OPERATOR_DIV:
6083 exp->write_c_string(" / ");
6084 break;
6085 case OPERATOR_MOD:
6086 exp->write_c_string(" % ");
6087 break;
6088 case OPERATOR_LSHIFT:
6089 exp->write_c_string(" << ");
6090 break;
6091 case OPERATOR_RSHIFT:
6092 exp->write_c_string(" >> ");
6093 break;
6094 case OPERATOR_AND:
6095 exp->write_c_string(" & ");
6096 break;
6097 case OPERATOR_BITCLEAR:
6098 exp->write_c_string(" &^ ");
6099 break;
6100 default:
c3e6f413 6101 go_unreachable();
e440a328 6102 }
6103 this->right_->export_expression(exp);
6104 exp->write_c_string(")");
6105}
6106
6107// Import a binary expression.
6108
6109Expression*
6110Binary_expression::do_import(Import* imp)
6111{
6112 imp->require_c_string("(");
6113
6114 Expression* left = Expression::import_expression(imp);
6115
6116 Operator op;
6117 if (imp->match_c_string(" || "))
6118 {
6119 op = OPERATOR_OROR;
6120 imp->advance(4);
6121 }
6122 else if (imp->match_c_string(" && "))
6123 {
6124 op = OPERATOR_ANDAND;
6125 imp->advance(4);
6126 }
6127 else if (imp->match_c_string(" == "))
6128 {
6129 op = OPERATOR_EQEQ;
6130 imp->advance(4);
6131 }
6132 else if (imp->match_c_string(" != "))
6133 {
6134 op = OPERATOR_NOTEQ;
6135 imp->advance(4);
6136 }
6137 else if (imp->match_c_string(" < "))
6138 {
6139 op = OPERATOR_LT;
6140 imp->advance(3);
6141 }
6142 else if (imp->match_c_string(" <= "))
6143 {
6144 op = OPERATOR_LE;
6145 imp->advance(4);
6146 }
6147 else if (imp->match_c_string(" > "))
6148 {
6149 op = OPERATOR_GT;
6150 imp->advance(3);
6151 }
6152 else if (imp->match_c_string(" >= "))
6153 {
6154 op = OPERATOR_GE;
6155 imp->advance(4);
6156 }
6157 else if (imp->match_c_string(" + "))
6158 {
6159 op = OPERATOR_PLUS;
6160 imp->advance(3);
6161 }
6162 else if (imp->match_c_string(" - "))
6163 {
6164 op = OPERATOR_MINUS;
6165 imp->advance(3);
6166 }
6167 else if (imp->match_c_string(" | "))
6168 {
6169 op = OPERATOR_OR;
6170 imp->advance(3);
6171 }
6172 else if (imp->match_c_string(" ^ "))
6173 {
6174 op = OPERATOR_XOR;
6175 imp->advance(3);
6176 }
6177 else if (imp->match_c_string(" * "))
6178 {
6179 op = OPERATOR_MULT;
6180 imp->advance(3);
6181 }
6182 else if (imp->match_c_string(" / "))
6183 {
6184 op = OPERATOR_DIV;
6185 imp->advance(3);
6186 }
6187 else if (imp->match_c_string(" % "))
6188 {
6189 op = OPERATOR_MOD;
6190 imp->advance(3);
6191 }
6192 else if (imp->match_c_string(" << "))
6193 {
6194 op = OPERATOR_LSHIFT;
6195 imp->advance(4);
6196 }
6197 else if (imp->match_c_string(" >> "))
6198 {
6199 op = OPERATOR_RSHIFT;
6200 imp->advance(4);
6201 }
6202 else if (imp->match_c_string(" & "))
6203 {
6204 op = OPERATOR_AND;
6205 imp->advance(3);
6206 }
6207 else if (imp->match_c_string(" &^ "))
6208 {
6209 op = OPERATOR_BITCLEAR;
6210 imp->advance(4);
6211 }
6212 else
6213 {
631d5788 6214 go_error_at(imp->location(), "unrecognized binary operator");
e440a328 6215 return Expression::make_error(imp->location());
6216 }
6217
6218 Expression* right = Expression::import_expression(imp);
6219
6220 imp->require_c_string(")");
6221
6222 return Expression::make_binary(op, left, right, imp->location());
6223}
6224
d751bb78 6225// Dump ast representation of a binary expression.
6226
6227void
6228Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6229{
6230 ast_dump_context->ostream() << "(";
6231 ast_dump_context->dump_expression(this->left_);
6232 ast_dump_context->ostream() << " ";
6233 ast_dump_context->dump_operator(this->op_);
6234 ast_dump_context->ostream() << " ";
6235 ast_dump_context->dump_expression(this->right_);
6236 ast_dump_context->ostream() << ") ";
6237}
6238
e440a328 6239// Make a binary expression.
6240
6241Expression*
6242Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6243 Location location)
e440a328 6244{
6245 return new Binary_expression(op, left, right, location);
6246}
6247
6248// Implement a comparison.
6249
a32698ee 6250Bexpression*
6251Expression::comparison(Translate_context* context, Type* result_type,
6252 Operator op, Expression* left, Expression* right,
6253 Location location)
e440a328 6254{
2387f644 6255 Type* left_type = left->type();
6256 Type* right_type = right->type();
ceeb12d7 6257
e67508fa 6258 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
1b1f2abf 6259
15c67ee2 6260 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6261 {
6098d6cb 6262 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6263 {
6264 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6265 left, right);
6266 right = Expression::make_boolean(true, location);
6267 }
6268 else
6269 {
6270 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6271 left, right);
6272 right = zexpr;
6273 }
e440a328 6274 }
15c67ee2 6275 else if ((left_type->interface_type() != NULL
6276 && right_type->interface_type() == NULL
6277 && !right_type->is_nil_type())
6278 || (left_type->interface_type() == NULL
6279 && !left_type->is_nil_type()
6280 && right_type->interface_type() != NULL))
e440a328 6281 {
6282 // Comparing an interface value to a non-interface value.
6283 if (left_type->interface_type() == NULL)
6284 {
6285 std::swap(left_type, right_type);
2387f644 6286 std::swap(left, right);
e440a328 6287 }
6288
6289 // The right operand is not an interface. We need to take its
6290 // address if it is not a pointer.
ceeb12d7 6291 Expression* pointer_arg = NULL;
e440a328 6292 if (right_type->points_to() != NULL)
2387f644 6293 pointer_arg = right;
e440a328 6294 else
6295 {
2387f644 6296 go_assert(right->is_addressable());
6297 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6298 location);
e440a328 6299 }
e440a328 6300
2387f644 6301 Expression* descriptor =
6302 Expression::make_type_descriptor(right_type, location);
6303 left =
ceeb12d7 6304 Runtime::make_call((left_type->interface_type()->is_empty()
6098d6cb 6305 ? Runtime::EFACEVALEQ
6306 : Runtime::IFACEVALEQ),
2387f644 6307 location, 3, left, descriptor,
ceeb12d7 6308 pointer_arg);
6098d6cb 6309 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6310 right = Expression::make_boolean(true, location);
e440a328 6311 }
6312 else if (left_type->interface_type() != NULL
6313 && right_type->interface_type() != NULL)
6314 {
ceeb12d7 6315 Runtime::Function compare_function;
739bad04 6316 if (left_type->interface_type()->is_empty()
6317 && right_type->interface_type()->is_empty())
6098d6cb 6318 compare_function = Runtime::EFACEEQ;
739bad04 6319 else if (!left_type->interface_type()->is_empty()
6320 && !right_type->interface_type()->is_empty())
6098d6cb 6321 compare_function = Runtime::IFACEEQ;
739bad04 6322 else
6323 {
6324 if (left_type->interface_type()->is_empty())
6325 {
739bad04 6326 std::swap(left_type, right_type);
2387f644 6327 std::swap(left, right);
739bad04 6328 }
c484d925 6329 go_assert(!left_type->interface_type()->is_empty());
6330 go_assert(right_type->interface_type()->is_empty());
6098d6cb 6331 compare_function = Runtime::IFACEEFACEEQ;
739bad04 6332 }
6333
2387f644 6334 left = Runtime::make_call(compare_function, location, 2, left, right);
6098d6cb 6335 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6336 right = Expression::make_boolean(true, location);
e440a328 6337 }
6338
6339 if (left_type->is_nil_type()
6340 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6341 {
6342 std::swap(left_type, right_type);
2387f644 6343 std::swap(left, right);
e440a328 6344 }
6345
6346 if (right_type->is_nil_type())
6347 {
2387f644 6348 right = Expression::make_nil(location);
e440a328 6349 if (left_type->array_type() != NULL
6350 && left_type->array_type()->length() == NULL)
6351 {
6352 Array_type* at = left_type->array_type();
2387f644 6353 left = at->get_value_pointer(context->gogo(), left);
e440a328 6354 }
6355 else if (left_type->interface_type() != NULL)
6356 {
6357 // An interface is nil if the first field is nil.
2387f644 6358 left = Expression::make_field_reference(left, 0, location);
e440a328 6359 }
6360 }
6361
ea664253 6362 Bexpression* left_bexpr = left->get_backend(context);
6363 Bexpression* right_bexpr = right->get_backend(context);
e90c9dfc 6364
a32698ee 6365 Gogo* gogo = context->gogo();
6366 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6367 right_bexpr, location);
6368 if (result_type != NULL)
6369 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6370 ret, location);
e440a328 6371 return ret;
6372}
6373
736a16ba 6374// Class String_concat_expression.
6375
6376bool
6377String_concat_expression::do_is_constant() const
6378{
6379 for (Expression_list::const_iterator pe = this->exprs_->begin();
6380 pe != this->exprs_->end();
6381 ++pe)
6382 {
6383 if (!(*pe)->is_constant())
6384 return false;
6385 }
6386 return true;
6387}
6388
6389bool
3ae06f68 6390String_concat_expression::do_is_static_initializer() const
736a16ba 6391{
6392 for (Expression_list::const_iterator pe = this->exprs_->begin();
6393 pe != this->exprs_->end();
6394 ++pe)
6395 {
3ae06f68 6396 if (!(*pe)->is_static_initializer())
736a16ba 6397 return false;
6398 }
6399 return true;
6400}
6401
6402Type*
6403String_concat_expression::do_type()
6404{
6405 Type* t = this->exprs_->front()->type();
6406 Expression_list::iterator pe = this->exprs_->begin();
6407 ++pe;
6408 for (; pe != this->exprs_->end(); ++pe)
6409 {
6410 Type* t1;
6411 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6412 (*pe)->type(),
6413 &t1))
6414 return Type::make_error_type();
6415 t = t1;
6416 }
6417 return t;
6418}
6419
6420void
6421String_concat_expression::do_determine_type(const Type_context* context)
6422{
6423 Type_context subcontext(*context);
6424 for (Expression_list::iterator pe = this->exprs_->begin();
6425 pe != this->exprs_->end();
6426 ++pe)
6427 {
6428 Type* t = (*pe)->type();
6429 if (!t->is_abstract())
6430 {
6431 subcontext.type = t;
6432 break;
6433 }
6434 }
6435 if (subcontext.type == NULL)
6436 subcontext.type = this->exprs_->front()->type();
6437 for (Expression_list::iterator pe = this->exprs_->begin();
6438 pe != this->exprs_->end();
6439 ++pe)
6440 (*pe)->determine_type(&subcontext);
6441}
6442
6443void
6444String_concat_expression::do_check_types(Gogo*)
6445{
6446 if (this->is_error_expression())
6447 return;
6448 Type* t = this->exprs_->front()->type();
6449 if (t->is_error())
6450 {
6451 this->set_is_error();
6452 return;
6453 }
6454 Expression_list::iterator pe = this->exprs_->begin();
6455 ++pe;
6456 for (; pe != this->exprs_->end(); ++pe)
6457 {
6458 Type* t1 = (*pe)->type();
6459 if (!Type::are_compatible_for_binop(t, t1))
6460 {
6461 this->report_error("incompatible types in binary expression");
6462 return;
6463 }
6464 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6465 this->location()))
6466 {
6467 this->set_is_error();
6468 return;
6469 }
6470 }
6471}
6472
6473Expression*
6474String_concat_expression::do_flatten(Gogo*, Named_object*,
6475 Statement_inserter*)
6476{
6477 if (this->is_error_expression())
6478 return this;
6479 Location loc = this->location();
6480 Type* type = this->type();
6481 Expression* nil_arg = Expression::make_nil(loc);
6482 Expression* call;
6483 switch (this->exprs_->size())
6484 {
6485 case 0: case 1:
6486 go_unreachable();
6487
6488 case 2: case 3: case 4: case 5:
6489 {
6490 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6491 NULL, loc);
6492 Array_type* arg_type = Type::make_array_type(type, len);
6493 arg_type->set_is_array_incomparable();
6494 Expression* arg =
6495 Expression::make_array_composite_literal(arg_type, this->exprs_,
6496 loc);
6497 Runtime::Function code;
6498 switch (this->exprs_->size())
6499 {
6500 default:
6501 go_unreachable();
6502 case 2:
6503 code = Runtime::CONCATSTRING2;
6504 break;
6505 case 3:
6506 code = Runtime::CONCATSTRING3;
6507 break;
6508 case 4:
6509 code = Runtime::CONCATSTRING4;
6510 break;
6511 case 5:
6512 code = Runtime::CONCATSTRING5;
6513 break;
6514 }
6515 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6516 }
6517 break;
6518
6519 default:
6520 {
6521 Type* arg_type = Type::make_array_type(type, NULL);
6522 Slice_construction_expression* sce =
6523 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6524 loc);
6525 sce->set_storage_does_not_escape();
6526 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6527 sce);
6528 }
6529 break;
6530 }
6531
6532 return Expression::make_cast(type, call, loc);
6533}
6534
6535void
6536String_concat_expression::do_dump_expression(
6537 Ast_dump_context* ast_dump_context) const
6538{
6539 ast_dump_context->ostream() << "concat(";
6540 ast_dump_context->dump_expression_list(this->exprs_, false);
6541 ast_dump_context->ostream() << ")";
6542}
6543
6544Expression*
6545Expression::make_string_concat(Expression_list* exprs)
6546{
6547 return new String_concat_expression(exprs);
6548}
6549
e440a328 6550// Class Bound_method_expression.
6551
6552// Traversal.
6553
6554int
6555Bound_method_expression::do_traverse(Traverse* traverse)
6556{
e0659c9e 6557 return Expression::traverse(&this->expr_, traverse);
e440a328 6558}
6559
6560// Return the type of a bound method expression. The type of this
0afbb937 6561// object is simply the type of the method with no receiver.
e440a328 6562
6563Type*
6564Bound_method_expression::do_type()
6565{
0afbb937 6566 Named_object* fn = this->method_->named_object();
6567 Function_type* fntype;
6568 if (fn->is_function())
6569 fntype = fn->func_value()->type();
6570 else if (fn->is_function_declaration())
6571 fntype = fn->func_declaration_value()->type();
e0659c9e 6572 else
6573 return Type::make_error_type();
0afbb937 6574 return fntype->copy_without_receiver();
e440a328 6575}
6576
6577// Determine the types of a method expression.
6578
6579void
6580Bound_method_expression::do_determine_type(const Type_context*)
6581{
0afbb937 6582 Named_object* fn = this->method_->named_object();
6583 Function_type* fntype;
6584 if (fn->is_function())
6585 fntype = fn->func_value()->type();
6586 else if (fn->is_function_declaration())
6587 fntype = fn->func_declaration_value()->type();
6588 else
6589 fntype = NULL;
e440a328 6590 if (fntype == NULL || !fntype->is_method())
6591 this->expr_->determine_type_no_context();
6592 else
6593 {
6594 Type_context subcontext(fntype->receiver()->type(), false);
6595 this->expr_->determine_type(&subcontext);
6596 }
6597}
6598
6599// Check the types of a method expression.
6600
6601void
6602Bound_method_expression::do_check_types(Gogo*)
6603{
0afbb937 6604 Named_object* fn = this->method_->named_object();
6605 if (!fn->is_function() && !fn->is_function_declaration())
6606 {
6607 this->report_error(_("object is not a method"));
6608 return;
6609 }
6610
6611 Function_type* fntype;
6612 if (fn->is_function())
6613 fntype = fn->func_value()->type();
6614 else if (fn->is_function_declaration())
6615 fntype = fn->func_declaration_value()->type();
e440a328 6616 else
0afbb937 6617 go_unreachable();
6618 Type* rtype = fntype->receiver()->type()->deref();
6619 Type* etype = (this->expr_type_ != NULL
6620 ? this->expr_type_
6621 : this->expr_->type());
6622 etype = etype->deref();
6623 if (!Type::are_identical(rtype, etype, true, NULL))
6624 this->report_error(_("method type does not match object type"));
6625}
6626
6627// If a bound method expression is not simply called, then it is
6628// represented as a closure. The closure will hold a single variable,
6629// the receiver to pass to the method. The function will be a simple
6630// thunk that pulls that value from the closure and calls the method
6631// with the remaining arguments.
6632//
6633// Because method values are not common, we don't build all thunks for
6634// every methods, but instead only build them as we need them. In
6635// particular, we even build them on demand for methods defined in
6636// other packages.
6637
6638Bound_method_expression::Method_value_thunks
6639 Bound_method_expression::method_value_thunks;
6640
6641// Find or create the thunk for METHOD.
6642
6643Named_object*
6644Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6645 Named_object* fn)
6646{
6647 std::pair<Named_object*, Named_object*> val(fn, NULL);
6648 std::pair<Method_value_thunks::iterator, bool> ins =
6649 Bound_method_expression::method_value_thunks.insert(val);
6650 if (!ins.second)
6651 {
6652 // We have seen this method before.
6653 go_assert(ins.first->second != NULL);
6654 return ins.first->second;
6655 }
6656
6657 Location loc = fn->location();
6658
6659 Function_type* orig_fntype;
6660 if (fn->is_function())
6661 orig_fntype = fn->func_value()->type();
6662 else if (fn->is_function_declaration())
6663 orig_fntype = fn->func_declaration_value()->type();
6664 else
6665 orig_fntype = NULL;
6666
6667 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6668 {
0afbb937 6669 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6670 return ins.first->second;
e440a328 6671 }
0afbb937 6672
6673 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6674 // The type here is wrong--it should be the C function type. But it
6675 // doesn't really matter.
0afbb937 6676 Type* vt = Type::make_pointer_type(Type::make_void_type());
6677 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6678 sfl->push_back(Struct_field(Typed_identifier("val.1",
6679 orig_fntype->receiver()->type(),
6680 loc)));
6681 Type* closure_type = Type::make_struct_type(sfl, loc);
6682 closure_type = Type::make_pointer_type(closure_type);
6683
f8bdf81a 6684 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6685
da244e59 6686 std::string thunk_name = Gogo::thunk_name();
6687 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 6688 false, loc);
6689
f8bdf81a 6690 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6691 cvar->set_is_used();
1ecc6157 6692 cvar->set_is_closure();
da244e59 6693 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6694 NULL, cvar);
f8bdf81a 6695 new_no->func_value()->set_closure_var(cp);
0afbb937 6696
f8bdf81a 6697 gogo->start_block(loc);
0afbb937 6698
6699 // Field 0 of the closure is the function code pointer, field 1 is
6700 // the value on which to invoke the method.
6701 Expression* arg = Expression::make_var_reference(cp, loc);
6702 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6703 arg = Expression::make_field_reference(arg, 1, loc);
6704
6705 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6706
6707 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6708 Expression_list* args;
6709 if (orig_params == NULL || orig_params->empty())
6710 args = NULL;
6711 else
6712 {
6713 const Typed_identifier_list* new_params = new_fntype->parameters();
6714 args = new Expression_list();
6715 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6716 p != new_params->end();
0afbb937 6717 ++p)
6718 {
6719 Named_object* p_no = gogo->lookup(p->name(), NULL);
6720 go_assert(p_no != NULL
6721 && p_no->is_variable()
6722 && p_no->var_value()->is_parameter());
6723 args->push_back(Expression::make_var_reference(p_no, loc));
6724 }
6725 }
6726
6727 Call_expression* call = Expression::make_call(bme, args,
6728 orig_fntype->is_varargs(),
6729 loc);
6730 call->set_varargs_are_lowered();
6731
6732 Statement* s = Statement::make_return_from_call(call, loc);
6733 gogo->add_statement(s);
6734 Block* b = gogo->finish_block(loc);
6735 gogo->add_block(b, loc);
6736 gogo->lower_block(new_no, b);
a32698ee 6737 gogo->flatten_block(new_no, b);
0afbb937 6738 gogo->finish_function(loc);
6739
6740 ins.first->second = new_no;
6741 return new_no;
6742}
6743
6744// Return an expression to check *REF for nil while dereferencing
6745// according to FIELD_INDEXES. Update *REF to build up the field
6746// reference. This is a static function so that we don't have to
6747// worry about declaring Field_indexes in expressions.h.
6748
6749static Expression*
6750bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6751 Expression** ref)
6752{
6753 if (field_indexes == NULL)
6754 return Expression::make_boolean(false, loc);
6755 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6756 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6757 go_assert(stype != NULL
6758 && field_indexes->field_index < stype->field_count());
6759 if ((*ref)->type()->struct_type() == NULL)
6760 {
6761 go_assert((*ref)->type()->points_to() != NULL);
6762 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6763 Expression::make_nil(loc),
6764 loc);
6765 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6766 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6767 go_assert((*ref)->type()->struct_type() == stype);
6768 }
6769 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6770 loc);
6771 return cond;
e440a328 6772}
6773
cd39797e 6774// Flatten a method value into a struct with nil checks. We can't do
6775// this in the lowering phase, because if the method value is called
6776// directly we don't need a thunk. That case will have been handled
6777// by Call_expression::do_lower, so if we get here then we do need a
6778// thunk.
e440a328 6779
cd39797e 6780Expression*
6781Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6782 Statement_inserter* inserter)
e440a328 6783{
cd39797e 6784 Location loc = this->location();
6785
6786 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
0afbb937 6787 this->method_,
6788 this->function_);
6789 if (thunk->is_erroneous())
6790 {
6791 go_assert(saw_errors());
cd39797e 6792 return Expression::make_error(loc);
0afbb937 6793 }
6794
cd39797e 6795 // Force the expression into a variable. This is only necessary if
6796 // we are going to do nil checks below, but it's easy enough to
6797 // always do it.
6798 Expression* expr = this->expr_;
6799 if (!expr->is_variable())
6800 {
6801 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6802 inserter->insert(etemp);
6803 expr = Expression::make_temporary_reference(etemp, loc);
6804 }
0afbb937 6805
6806 // If the method expects a value, and we have a pointer, we need to
6807 // dereference the pointer.
6808
6809 Named_object* fn = this->method_->named_object();
cd39797e 6810 Function_type *fntype;
0afbb937 6811 if (fn->is_function())
6812 fntype = fn->func_value()->type();
6813 else if (fn->is_function_declaration())
6814 fntype = fn->func_declaration_value()->type();
6815 else
6816 go_unreachable();
6817
cd39797e 6818 Expression* val = expr;
0afbb937 6819 if (fntype->receiver()->type()->points_to() == NULL
6820 && val->type()->points_to() != NULL)
6821 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6822
6823 // Note that we are ignoring this->expr_type_ here. The thunk will
6824 // expect a closure whose second field has type this->expr_type_ (if
6825 // that is not NULL). We are going to pass it a closure whose
6826 // second field has type this->expr_->type(). Since
6827 // this->expr_type_ is only not-NULL for pointer types, we can get
6828 // away with this.
6829
6830 Struct_field_list* fields = new Struct_field_list();
6831 fields->push_back(Struct_field(Typed_identifier("fn.0",
6832 thunk->func_value()->type(),
6833 loc)));
6834 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6835 Struct_type* st = Type::make_struct_type(fields, loc);
6836
6837 Expression_list* vals = new Expression_list();
6838 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6839 vals->push_back(val);
6840
6841 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
0afbb937 6842
cd39797e 6843 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
6844 ret = Expression::make_heap_expression(ret, loc);
6845 else
6846 {
6847 // When compiling the runtime, method closures do not escape.
6848 // When escape analysis becomes the default, and applies to
6849 // method closures, this should be changed to make it an error
6850 // if a method closure escapes.
6851 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
6852 inserter->insert(ctemp);
6853 ret = Expression::make_temporary_reference(ctemp, loc);
6854 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
6855 ret->unary_expression()->set_does_not_escape();
6856 }
6857
6858 // If necessary, check whether the expression or any embedded
6859 // pointers are nil.
0afbb937 6860
df7ef1fd 6861 Expression* nil_check = NULL;
0afbb937 6862 if (this->method_->field_indexes() != NULL)
6863 {
0afbb937 6864 Expression* ref = expr;
6865 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6866 expr = ref;
6867 }
6868
6869 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6870 {
6871 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6872 Expression::make_nil(loc),
6873 loc);
6874 if (nil_check == NULL)
6875 nil_check = n;
6876 else
6877 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6878 }
6879
6880 if (nil_check != NULL)
6881 {
cd39797e 6882 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6883 loc);
6884 // Fix the type of the conditional expression by pretending to
6885 // evaluate to RET either way through the conditional.
6886 crash = Expression::make_compound(crash, ret, loc);
6887 ret = Expression::make_conditional(nil_check, crash, ret, loc);
6888 }
6889
6890 // RET is a pointer to a struct, but we want a function type.
6891 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
6892
6893 return ret;
e440a328 6894}
6895
d751bb78 6896// Dump ast representation of a bound method expression.
6897
6898void
6899Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6900 const
6901{
6902 if (this->expr_type_ != NULL)
6903 ast_dump_context->ostream() << "(";
6904 ast_dump_context->dump_expression(this->expr_);
6905 if (this->expr_type_ != NULL)
6906 {
6907 ast_dump_context->ostream() << ":";
6908 ast_dump_context->dump_type(this->expr_type_);
6909 ast_dump_context->ostream() << ")";
6910 }
6911
0afbb937 6912 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6913}
6914
e440a328 6915// Make a method expression.
6916
6917Bound_method_expression*
0afbb937 6918Expression::make_bound_method(Expression* expr, const Method* method,
6919 Named_object* function, Location location)
e440a328 6920{
0afbb937 6921 return new Bound_method_expression(expr, method, function, location);
e440a328 6922}
6923
6924// Class Builtin_call_expression. This is used for a call to a
6925// builtin function.
6926
6927class Builtin_call_expression : public Call_expression
6928{
6929 public:
6930 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6931 bool is_varargs, Location location);
e440a328 6932
6933 protected:
6934 // This overrides Call_expression::do_lower.
6935 Expression*
ceeb4318 6936 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6937
35a54f17 6938 Expression*
6939 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6940
e440a328 6941 bool
6942 do_is_constant() const;
6943
6944 bool
0c77715b 6945 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6946
4f2138d7 6947 bool
a7549a6a 6948 do_discarding_value();
6949
e440a328 6950 Type*
6951 do_type();
6952
6953 void
6954 do_determine_type(const Type_context*);
6955
6956 void
6957 do_check_types(Gogo*);
6958
6959 Expression*
72666aed 6960 do_copy();
e440a328 6961
ea664253 6962 Bexpression*
6963 do_get_backend(Translate_context*);
e440a328 6964
6965 void
6966 do_export(Export*) const;
6967
6968 virtual bool
6969 do_is_recover_call() const;
6970
6971 virtual void
6972 do_set_recover_arg(Expression*);
6973
6974 private:
6975 // The builtin functions.
6976 enum Builtin_function_code
6977 {
6978 BUILTIN_INVALID,
6979
6980 // Predeclared builtin functions.
6981 BUILTIN_APPEND,
6982 BUILTIN_CAP,
6983 BUILTIN_CLOSE,
48080209 6984 BUILTIN_COMPLEX,
e440a328 6985 BUILTIN_COPY,
1cce762f 6986 BUILTIN_DELETE,
e440a328 6987 BUILTIN_IMAG,
6988 BUILTIN_LEN,
6989 BUILTIN_MAKE,
6990 BUILTIN_NEW,
6991 BUILTIN_PANIC,
6992 BUILTIN_PRINT,
6993 BUILTIN_PRINTLN,
6994 BUILTIN_REAL,
6995 BUILTIN_RECOVER,
6996
6997 // Builtin functions from the unsafe package.
6998 BUILTIN_ALIGNOF,
6999 BUILTIN_OFFSETOF,
7000 BUILTIN_SIZEOF
7001 };
7002
7003 Expression*
7004 one_arg() const;
7005
7006 bool
7007 check_one_arg();
7008
7009 static Type*
7010 real_imag_type(Type*);
7011
7012 static Type*
48080209 7013 complex_type(Type*);
e440a328 7014
a9182619 7015 Expression*
321e5ad2 7016 lower_make(Statement_inserter*);
7017
7018 Expression* flatten_append(Gogo*, Named_object*, Statement_inserter*);
a9182619 7019
7020 bool
1ad00fd4 7021 check_int_value(Expression*, bool is_length);
a9182619 7022
e440a328 7023 // A pointer back to the general IR structure. This avoids a global
7024 // variable, or passing it around everywhere.
7025 Gogo* gogo_;
7026 // The builtin function being called.
7027 Builtin_function_code code_;
0f914071 7028 // Used to stop endless loops when the length of an array uses len
7029 // or cap of the array itself.
7030 mutable bool seen_;
6334270b 7031 // Whether the argument is set for calls to BUILTIN_RECOVER.
7032 bool recover_arg_is_set_;
e440a328 7033};
7034
7035Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7036 Expression* fn,
7037 Expression_list* args,
7038 bool is_varargs,
b13c66cd 7039 Location location)
e440a328 7040 : Call_expression(fn, args, is_varargs, location),
6334270b 7041 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7042 recover_arg_is_set_(false)
e440a328 7043{
7044 Func_expression* fnexp = this->fn()->func_expression();
79651b1f 7045 if (fnexp == NULL)
7046 {
7047 this->code_ = BUILTIN_INVALID;
7048 return;
7049 }
e440a328 7050 const std::string& name(fnexp->named_object()->name());
7051 if (name == "append")
7052 this->code_ = BUILTIN_APPEND;
7053 else if (name == "cap")
7054 this->code_ = BUILTIN_CAP;
7055 else if (name == "close")
7056 this->code_ = BUILTIN_CLOSE;
48080209 7057 else if (name == "complex")
7058 this->code_ = BUILTIN_COMPLEX;
e440a328 7059 else if (name == "copy")
7060 this->code_ = BUILTIN_COPY;
1cce762f 7061 else if (name == "delete")
7062 this->code_ = BUILTIN_DELETE;
e440a328 7063 else if (name == "imag")
7064 this->code_ = BUILTIN_IMAG;
7065 else if (name == "len")
7066 this->code_ = BUILTIN_LEN;
7067 else if (name == "make")
7068 this->code_ = BUILTIN_MAKE;
7069 else if (name == "new")
7070 this->code_ = BUILTIN_NEW;
7071 else if (name == "panic")
7072 this->code_ = BUILTIN_PANIC;
7073 else if (name == "print")
7074 this->code_ = BUILTIN_PRINT;
7075 else if (name == "println")
7076 this->code_ = BUILTIN_PRINTLN;
7077 else if (name == "real")
7078 this->code_ = BUILTIN_REAL;
7079 else if (name == "recover")
7080 this->code_ = BUILTIN_RECOVER;
7081 else if (name == "Alignof")
7082 this->code_ = BUILTIN_ALIGNOF;
7083 else if (name == "Offsetof")
7084 this->code_ = BUILTIN_OFFSETOF;
7085 else if (name == "Sizeof")
7086 this->code_ = BUILTIN_SIZEOF;
7087 else
c3e6f413 7088 go_unreachable();
e440a328 7089}
7090
7091// Return whether this is a call to recover. This is a virtual
7092// function called from the parent class.
7093
7094bool
7095Builtin_call_expression::do_is_recover_call() const
7096{
7097 if (this->classification() == EXPRESSION_ERROR)
7098 return false;
7099 return this->code_ == BUILTIN_RECOVER;
7100}
7101
7102// Set the argument for a call to recover.
7103
7104void
7105Builtin_call_expression::do_set_recover_arg(Expression* arg)
7106{
7107 const Expression_list* args = this->args();
c484d925 7108 go_assert(args == NULL || args->empty());
e440a328 7109 Expression_list* new_args = new Expression_list();
7110 new_args->push_back(arg);
7111 this->set_args(new_args);
6334270b 7112 this->recover_arg_is_set_ = true;
e440a328 7113}
7114
e440a328 7115// Lower a builtin call expression. This turns new and make into
7116// specific expressions. We also convert to a constant if we can.
7117
7118Expression*
321e5ad2 7119Builtin_call_expression::do_lower(Gogo*, Named_object* function,
ceeb4318 7120 Statement_inserter* inserter, int)
e440a328 7121{
79651b1f 7122 if (this->is_error_expression())
a9182619 7123 return this;
7124
b13c66cd 7125 Location loc = this->location();
1cce762f 7126
a8725655 7127 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7128 {
7129 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7130 return Expression::make_error(loc);
a8725655 7131 }
7132
393ba00b 7133 if (this->code_ == BUILTIN_OFFSETOF)
7134 {
7135 Expression* arg = this->one_arg();
12e69faa 7136
7137 if (arg->bound_method_expression() != NULL
7138 || arg->interface_field_reference_expression() != NULL)
7139 {
7140 this->report_error(_("invalid use of method value as argument "
7141 "of Offsetof"));
7142 return this;
7143 }
7144
393ba00b 7145 Field_reference_expression* farg = arg->field_reference_expression();
7146 while (farg != NULL)
7147 {
7148 if (!farg->implicit())
7149 break;
7150 // When the selector refers to an embedded field,
7151 // it must not be reached through pointer indirections.
7152 if (farg->expr()->deref() != farg->expr())
7153 {
12e69faa 7154 this->report_error(_("argument of Offsetof implies "
7155 "indirection of an embedded field"));
393ba00b 7156 return this;
7157 }
7158 // Go up until we reach the original base.
7159 farg = farg->expr()->field_reference_expression();
7160 }
7161 }
7162
1cce762f 7163 if (this->is_constant())
e440a328 7164 {
0c77715b 7165 Numeric_constant nc;
7166 if (this->numeric_constant_value(&nc))
7167 return nc.expression(loc);
e440a328 7168 }
1cce762f 7169
7170 switch (this->code_)
e440a328 7171 {
1cce762f 7172 default:
7173 break;
7174
7175 case BUILTIN_NEW:
7176 {
7177 const Expression_list* args = this->args();
7178 if (args == NULL || args->size() < 1)
7179 this->report_error(_("not enough arguments"));
7180 else if (args->size() > 1)
7181 this->report_error(_("too many arguments"));
7182 else
7183 {
7184 Expression* arg = args->front();
7185 if (!arg->is_type_expression())
7186 {
631d5788 7187 go_error_at(arg->location(), "expected type");
1cce762f 7188 this->set_is_error();
7189 }
7190 else
7191 return Expression::make_allocation(arg->type(), loc);
7192 }
7193 }
7194 break;
7195
7196 case BUILTIN_MAKE:
321e5ad2 7197 return this->lower_make(inserter);
1cce762f 7198
7199 case BUILTIN_RECOVER:
e440a328 7200 if (function != NULL)
7201 function->func_value()->set_calls_recover();
7202 else
7203 {
7204 // Calling recover outside of a function always returns the
7205 // nil empty interface.
823c7e3d 7206 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7207 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7208 }
1cce762f 7209 break;
7210
1cce762f 7211 case BUILTIN_DELETE:
7212 {
7213 // Lower to a runtime function call.
7214 const Expression_list* args = this->args();
7215 if (args == NULL || args->size() < 2)
7216 this->report_error(_("not enough arguments"));
7217 else if (args->size() > 2)
7218 this->report_error(_("too many arguments"));
7219 else if (args->front()->type()->map_type() == NULL)
7220 this->report_error(_("argument 1 must be a map"));
7221 else
7222 {
7223 // Since this function returns no value it must appear in
7224 // a statement by itself, so we don't have to worry about
7225 // order of evaluation of values around it. Evaluate the
7226 // map first to get order of evaluation right.
7227 Map_type* mt = args->front()->type()->map_type();
7228 Temporary_statement* map_temp =
7229 Statement::make_temporary(mt, args->front(), loc);
7230 inserter->insert(map_temp);
7231
7232 Temporary_statement* key_temp =
7233 Statement::make_temporary(mt->key_type(), args->back(), loc);
7234 inserter->insert(key_temp);
7235
0d5530d9 7236 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7237 Expression* e2 = Expression::make_temporary_reference(map_temp,
1cce762f 7238 loc);
0d5530d9 7239 Expression* e3 = Expression::make_temporary_reference(key_temp,
1cce762f 7240 loc);
0d5530d9 7241 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
1cce762f 7242 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
0d5530d9 7243 3, e1, e2, e3);
1cce762f 7244 }
7245 }
7246 break;
88b03a70 7247
7248 case BUILTIN_PRINT:
7249 case BUILTIN_PRINTLN:
7250 // Force all the arguments into temporary variables, so that we
7251 // don't try to evaluate something while holding the print lock.
7252 if (this->args() == NULL)
7253 break;
7254 for (Expression_list::iterator pa = this->args()->begin();
7255 pa != this->args()->end();
7256 ++pa)
7257 {
493ce3ee 7258 if (!(*pa)->is_variable() && !(*pa)->is_constant())
88b03a70 7259 {
7260 Temporary_statement* temp =
7261 Statement::make_temporary(NULL, *pa, loc);
7262 inserter->insert(temp);
7263 *pa = Expression::make_temporary_reference(temp, loc);
7264 }
7265 }
7266 break;
e440a328 7267 }
7268
7269 return this;
7270}
7271
35a54f17 7272// Flatten a builtin call expression. This turns the arguments of copy and
7273// append into temporary expressions.
7274
7275Expression*
321e5ad2 7276Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
35a54f17 7277 Statement_inserter* inserter)
7278{
16cb7fec 7279 Location loc = this->location();
7280
7281 switch (this->code_)
35a54f17 7282 {
16cb7fec 7283 default:
7284 break;
7285
7286 case BUILTIN_APPEND:
321e5ad2 7287 return this->flatten_append(gogo, function, inserter);
7288
16cb7fec 7289 case BUILTIN_COPY:
7290 {
7291 Type* at = this->args()->front()->type();
7292 for (Expression_list::iterator pa = this->args()->begin();
7293 pa != this->args()->end();
7294 ++pa)
7295 {
7296 if ((*pa)->is_nil_expression())
7297 {
7298 Expression* nil = Expression::make_nil(loc);
7299 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7300 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7301 }
7302 if (!(*pa)->is_variable())
7303 {
7304 Temporary_statement* temp =
7305 Statement::make_temporary(NULL, *pa, loc);
7306 inserter->insert(temp);
7307 *pa = Expression::make_temporary_reference(temp, loc);
7308 }
7309 }
7310 }
7311 break;
7312
7313 case BUILTIN_PANIC:
35a54f17 7314 for (Expression_list::iterator pa = this->args()->begin();
16cb7fec 7315 pa != this->args()->end();
7316 ++pa)
7317 {
7318 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
55e8ba6a 7319 {
16cb7fec 7320 Temporary_statement* temp =
7321 Statement::make_temporary(NULL, *pa, loc);
7322 inserter->insert(temp);
7323 *pa = Expression::make_temporary_reference(temp, loc);
55e8ba6a 7324 }
16cb7fec 7325 }
7739537f 7326 break;
0d5530d9 7327
7328 case BUILTIN_LEN:
132ed071 7329 case BUILTIN_CAP:
321e5ad2 7330 {
7331 Expression_list::iterator pa = this->args()->begin();
7332 if (!(*pa)->is_variable()
7333 && ((*pa)->type()->map_type() != NULL
7334 || (*pa)->type()->channel_type() != NULL))
7335 {
7336 Temporary_statement* temp =
7337 Statement::make_temporary(NULL, *pa, loc);
7338 inserter->insert(temp);
7339 *pa = Expression::make_temporary_reference(temp, loc);
7340 }
7341 }
7342 break;
35a54f17 7343 }
16cb7fec 7344
35a54f17 7345 return this;
7346}
7347
a9182619 7348// Lower a make expression.
7349
7350Expression*
321e5ad2 7351Builtin_call_expression::lower_make(Statement_inserter* inserter)
a9182619 7352{
b13c66cd 7353 Location loc = this->location();
a9182619 7354
7355 const Expression_list* args = this->args();
7356 if (args == NULL || args->size() < 1)
7357 {
7358 this->report_error(_("not enough arguments"));
7359 return Expression::make_error(this->location());
7360 }
7361
7362 Expression_list::const_iterator parg = args->begin();
7363
7364 Expression* first_arg = *parg;
7365 if (!first_arg->is_type_expression())
7366 {
631d5788 7367 go_error_at(first_arg->location(), "expected type");
a9182619 7368 this->set_is_error();
7369 return Expression::make_error(this->location());
7370 }
7371 Type* type = first_arg->type();
7372
7373 bool is_slice = false;
7374 bool is_map = false;
7375 bool is_chan = false;
411eb89e 7376 if (type->is_slice_type())
a9182619 7377 is_slice = true;
7378 else if (type->map_type() != NULL)
7379 is_map = true;
7380 else if (type->channel_type() != NULL)
7381 is_chan = true;
7382 else
7383 {
7384 this->report_error(_("invalid type for make function"));
7385 return Expression::make_error(this->location());
7386 }
7387
f6bc81e6 7388 Type_context int_context(Type::lookup_integer_type("int"), false);
7389
a9182619 7390 ++parg;
7391 Expression* len_arg;
7392 if (parg == args->end())
7393 {
7394 if (is_slice)
7395 {
7396 this->report_error(_("length required when allocating a slice"));
7397 return Expression::make_error(this->location());
7398 }
e67508fa 7399 len_arg = Expression::make_integer_ul(0, NULL, loc);
a9182619 7400 }
7401 else
7402 {
7403 len_arg = *parg;
f6bc81e6 7404 len_arg->determine_type(&int_context);
1ad00fd4 7405 if (!this->check_int_value(len_arg, true))
7406 return Expression::make_error(this->location());
a9182619 7407 ++parg;
7408 }
7409
7410 Expression* cap_arg = NULL;
7411 if (is_slice && parg != args->end())
7412 {
7413 cap_arg = *parg;
f6bc81e6 7414 cap_arg->determine_type(&int_context);
1ad00fd4 7415 if (!this->check_int_value(cap_arg, false))
7416 return Expression::make_error(this->location());
7417
7418 Numeric_constant nclen;
7419 Numeric_constant nccap;
7420 unsigned long vlen;
7421 unsigned long vcap;
7422 if (len_arg->numeric_constant_value(&nclen)
7423 && cap_arg->numeric_constant_value(&nccap)
7424 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7425 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7426 && vlen > vcap)
a9182619 7427 {
1ad00fd4 7428 this->report_error(_("len larger than cap"));
a9182619 7429 return Expression::make_error(this->location());
7430 }
1ad00fd4 7431
a9182619 7432 ++parg;
7433 }
7434
7435 if (parg != args->end())
7436 {
7437 this->report_error(_("too many arguments to make"));
7438 return Expression::make_error(this->location());
7439 }
7440
b13c66cd 7441 Location type_loc = first_arg->location();
a9182619 7442
7443 Expression* call;
7444 if (is_slice)
7445 {
321e5ad2 7446 Type* et = type->array_type()->element_type();
7447 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
a9182619 7448 if (cap_arg == NULL)
321e5ad2 7449 {
7450 Temporary_statement* temp = Statement::make_temporary(NULL,
7451 len_arg,
7452 loc);
7453 inserter->insert(temp);
7454 len_arg = Expression::make_temporary_reference(temp, loc);
7455 cap_arg = Expression::make_temporary_reference(temp, loc);
7456 }
7457 call = Runtime::make_call(Runtime::MAKESLICE, loc, 3, type_arg,
7458 len_arg, cap_arg);
a9182619 7459 }
7460 else if (is_map)
321e5ad2 7461 {
7462 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7463 call = Runtime::make_call(Runtime::MAKEMAP, loc, 4, type_arg, len_arg,
7464 Expression::make_nil(loc),
7465 Expression::make_nil(loc));
7466 }
a9182619 7467 else if (is_chan)
321e5ad2 7468 {
7469 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7470 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7471 }
a9182619 7472 else
7473 go_unreachable();
7474
7475 return Expression::make_unsafe_cast(type, call, loc);
7476}
7477
321e5ad2 7478// Flatten a call to the predeclared append function. We do this in
7479// the flatten phase, not the lowering phase, so that we run after
7480// type checking and after order_evaluations.
7481
7482Expression*
7483Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7484 Statement_inserter* inserter)
7485{
7486 if (this->is_error_expression())
7487 return this;
7488
7489 Location loc = this->location();
7490
7491 const Expression_list* args = this->args();
7492 go_assert(args != NULL && !args->empty());
7493
7494 Type* slice_type = args->front()->type();
7495 go_assert(slice_type->is_slice_type());
7496 Type* element_type = slice_type->array_type()->element_type();
7497
7498 if (args->size() == 1)
7499 {
7500 // append(s) evaluates to s.
7501 return args->front();
7502 }
7503
7504 Type* int_type = Type::lookup_integer_type("int");
7505 Type* uint_type = Type::lookup_integer_type("uint");
7506
7507 // Implementing
7508 // append(s1, s2...)
7509 // or
7510 // append(s1, a1, a2, a3, ...)
7511
7512 // s1tmp := s1
7513 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7514 loc);
7515 inserter->insert(s1tmp);
7516
7517 // l1tmp := len(s1tmp)
7518 Named_object* lenfn = gogo->lookup_global("len");
7519 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7520 Expression_list* call_args = new Expression_list();
7521 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7522 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7523 gogo->lower_expression(function, inserter, &len);
7524 gogo->flatten_expression(function, inserter, &len);
7525 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7526 inserter->insert(l1tmp);
7527
7528 Temporary_statement* s2tmp = NULL;
7529 Temporary_statement* l2tmp = NULL;
7530 Expression_list* add = NULL;
7531 Expression* len2;
7532 if (this->is_varargs())
7533 {
7534 go_assert(args->size() == 2);
7535
7536 // s2tmp := s2
7537 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7538 inserter->insert(s2tmp);
7539
7540 // l2tmp := len(s2tmp)
7541 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7542 call_args = new Expression_list();
7543 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7544 len = Expression::make_call(lenref, call_args, false, loc);
7545 gogo->lower_expression(function, inserter, &len);
7546 gogo->flatten_expression(function, inserter, &len);
7547 l2tmp = Statement::make_temporary(int_type, len, loc);
7548 inserter->insert(l2tmp);
7549
7550 // len2 = l2tmp
7551 len2 = Expression::make_temporary_reference(l2tmp, loc);
7552 }
7553 else
7554 {
7555 // We have to ensure that all the arguments are in variables
7556 // now, because otherwise if one of them is an index expression
7557 // into the current slice we could overwrite it before we fetch
7558 // it.
7559 add = new Expression_list();
7560 Expression_list::const_iterator pa = args->begin();
7561 for (++pa; pa != args->end(); ++pa)
7562 {
7563 if ((*pa)->is_variable())
7564 add->push_back(*pa);
7565 else
7566 {
7567 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7568 loc);
7569 inserter->insert(tmp);
7570 add->push_back(Expression::make_temporary_reference(tmp, loc));
7571 }
7572 }
7573
7574 // len2 = len(add)
7575 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7576 }
7577
7578 // ntmp := l1tmp + len2
7579 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7580 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7581 gogo->lower_expression(function, inserter, &sum);
7582 gogo->flatten_expression(function, inserter, &sum);
7583 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7584 inserter->insert(ntmp);
7585
7586 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7587 // growslice(type, s1tmp, ntmp) :
7588 // s1tmp[:ntmp]
7589 // Using uint here means that if the computation of ntmp overflowed,
7590 // we will call growslice which will panic.
7591
7592 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7593 left = Expression::make_cast(uint_type, left, loc);
7594
7595 Named_object* capfn = gogo->lookup_global("cap");
7596 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7597 call_args = new Expression_list();
7598 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7599 Expression* right = Expression::make_call(capref, call_args, false, loc);
7600 right = Expression::make_cast(uint_type, right, loc);
7601
7602 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7603
7604 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7605 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7606 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7607 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7608 a1, a2, a3);
7609 call = Expression::make_unsafe_cast(slice_type, call, loc);
7610
7611 ref = Expression::make_temporary_reference(s1tmp, loc);
7612 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7613 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7614 // FIXME: Mark this index as not requiring bounds checks.
7615 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7616
7617 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7618
7619 gogo->lower_expression(function, inserter, &rhs);
7620 gogo->flatten_expression(function, inserter, &rhs);
7621
7622 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7623 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7624 inserter->insert(assign);
7625
7626 if (this->is_varargs())
7627 {
7628 // copy(s1tmp[l1tmp:], s2tmp)
7629 a1 = Expression::make_temporary_reference(s1tmp, loc);
7630 ref = Expression::make_temporary_reference(l1tmp, loc);
7631 Expression* nil = Expression::make_nil(loc);
7632 // FIXME: Mark this index as not requiring bounds checks.
7633 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7634
7635 a2 = Expression::make_temporary_reference(s2tmp, loc);
7636
7637 Named_object* copyfn = gogo->lookup_global("copy");
7638 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7639 call_args = new Expression_list();
7640 call_args->push_back(a1);
7641 call_args->push_back(a2);
7642 call = Expression::make_call(copyref, call_args, false, loc);
7643 gogo->lower_expression(function, inserter, &call);
7644 gogo->flatten_expression(function, inserter, &call);
7645 inserter->insert(Statement::make_statement(call, false));
7646 }
7647 else
7648 {
7649 // For each argument:
7650 // s1tmp[l1tmp+i] = a
7651 unsigned long i = 0;
7652 for (Expression_list::const_iterator pa = add->begin();
7653 pa != add->end();
7654 ++pa, ++i)
7655 {
7656 ref = Expression::make_temporary_reference(s1tmp, loc);
7657 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7658 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7659 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7660 // FIXME: Mark this index as not requiring bounds checks.
7661 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7662 gogo->lower_expression(function, inserter, &lhs);
7663 gogo->flatten_expression(function, inserter, &lhs);
7664 assign = Statement::make_assignment(lhs, *pa, loc);
7665 inserter->insert(assign);
7666 }
7667 }
7668
7669 return Expression::make_temporary_reference(s1tmp, loc);
7670}
7671
a9182619 7672// Return whether an expression has an integer value. Report an error
7673// if not. This is used when handling calls to the predeclared make
7674// function.
7675
7676bool
1ad00fd4 7677Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7678{
0c77715b 7679 Numeric_constant nc;
1ad00fd4 7680 if (e->numeric_constant_value(&nc))
a9182619 7681 {
1ad00fd4 7682 unsigned long v;
7683 switch (nc.to_unsigned_long(&v))
7684 {
7685 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7686 break;
1ad00fd4 7687 case Numeric_constant::NC_UL_NOTINT:
631d5788 7688 go_error_at(e->location(), "non-integer %s argument to make",
7689 is_length ? "len" : "cap");
1ad00fd4 7690 return false;
7691 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 7692 go_error_at(e->location(), "negative %s argument to make",
7693 is_length ? "len" : "cap");
1ad00fd4 7694 return false;
7695 case Numeric_constant::NC_UL_BIG:
7696 // We don't want to give a compile-time error for a 64-bit
7697 // value on a 32-bit target.
1b10c5e7 7698 break;
1ad00fd4 7699 }
1b10c5e7 7700
7701 mpz_t val;
7702 if (!nc.to_int(&val))
7703 go_unreachable();
7704 int bits = mpz_sizeinbase(val, 2);
7705 mpz_clear(val);
7706 Type* int_type = Type::lookup_integer_type("int");
7707 if (bits >= int_type->integer_type()->bits())
7708 {
631d5788 7709 go_error_at(e->location(), "%s argument too large for make",
7710 is_length ? "len" : "cap");
1b10c5e7 7711 return false;
7712 }
7713
7714 return true;
a9182619 7715 }
7716
1ad00fd4 7717 if (e->type()->integer_type() != NULL)
7718 return true;
7719
631d5788 7720 go_error_at(e->location(), "non-integer %s argument to make",
7721 is_length ? "len" : "cap");
a9182619 7722 return false;
7723}
7724
e440a328 7725// Return the type of the real or imag functions, given the type of
fcbea5e4 7726// the argument. We need to map complex64 to float32 and complex128
7727// to float64, so it has to be done by name. This returns NULL if it
7728// can't figure out the type.
e440a328 7729
7730Type*
7731Builtin_call_expression::real_imag_type(Type* arg_type)
7732{
7733 if (arg_type == NULL || arg_type->is_abstract())
7734 return NULL;
7735 Named_type* nt = arg_type->named_type();
7736 if (nt == NULL)
7737 return NULL;
7738 while (nt->real_type()->named_type() != NULL)
7739 nt = nt->real_type()->named_type();
48080209 7740 if (nt->name() == "complex64")
e440a328 7741 return Type::lookup_float_type("float32");
7742 else if (nt->name() == "complex128")
7743 return Type::lookup_float_type("float64");
7744 else
7745 return NULL;
7746}
7747
48080209 7748// Return the type of the complex function, given the type of one of the
e440a328 7749// argments. Like real_imag_type, we have to map by name.
7750
7751Type*
48080209 7752Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7753{
7754 if (arg_type == NULL || arg_type->is_abstract())
7755 return NULL;
7756 Named_type* nt = arg_type->named_type();
7757 if (nt == NULL)
7758 return NULL;
7759 while (nt->real_type()->named_type() != NULL)
7760 nt = nt->real_type()->named_type();
48080209 7761 if (nt->name() == "float32")
e440a328 7762 return Type::lookup_complex_type("complex64");
7763 else if (nt->name() == "float64")
7764 return Type::lookup_complex_type("complex128");
7765 else
7766 return NULL;
7767}
7768
7769// Return a single argument, or NULL if there isn't one.
7770
7771Expression*
7772Builtin_call_expression::one_arg() const
7773{
7774 const Expression_list* args = this->args();
aa615cb3 7775 if (args == NULL || args->size() != 1)
e440a328 7776 return NULL;
7777 return args->front();
7778}
7779
83921647 7780// A traversal class which looks for a call or receive expression.
7781
7782class Find_call_expression : public Traverse
7783{
7784 public:
7785 Find_call_expression()
7786 : Traverse(traverse_expressions),
7787 found_(false)
7788 { }
7789
7790 int
7791 expression(Expression**);
7792
7793 bool
7794 found()
7795 { return this->found_; }
7796
7797 private:
7798 bool found_;
7799};
7800
7801int
7802Find_call_expression::expression(Expression** pexpr)
7803{
7804 if ((*pexpr)->call_expression() != NULL
7805 || (*pexpr)->receive_expression() != NULL)
7806 {
7807 this->found_ = true;
7808 return TRAVERSE_EXIT;
7809 }
7810 return TRAVERSE_CONTINUE;
7811}
7812
7813// Return whether this is constant: len of a string constant, or len
7814// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7815// unsafe.Alignof.
e440a328 7816
7817bool
7818Builtin_call_expression::do_is_constant() const
7819{
12e69faa 7820 if (this->is_error_expression())
7821 return true;
e440a328 7822 switch (this->code_)
7823 {
7824 case BUILTIN_LEN:
7825 case BUILTIN_CAP:
7826 {
0f914071 7827 if (this->seen_)
7828 return false;
7829
e440a328 7830 Expression* arg = this->one_arg();
7831 if (arg == NULL)
7832 return false;
7833 Type* arg_type = arg->type();
7834
7835 if (arg_type->points_to() != NULL
7836 && arg_type->points_to()->array_type() != NULL
411eb89e 7837 && !arg_type->points_to()->is_slice_type())
e440a328 7838 arg_type = arg_type->points_to();
7839
83921647 7840 // The len and cap functions are only constant if there are no
7841 // function calls or channel operations in the arguments.
7842 // Otherwise we have to make the call.
7843 if (!arg->is_constant())
7844 {
7845 Find_call_expression find_call;
7846 Expression::traverse(&arg, &find_call);
7847 if (find_call.found())
7848 return false;
7849 }
7850
e440a328 7851 if (arg_type->array_type() != NULL
7852 && arg_type->array_type()->length() != NULL)
0f914071 7853 return true;
e440a328 7854
7855 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7856 {
7857 this->seen_ = true;
7858 bool ret = arg->is_constant();
7859 this->seen_ = false;
7860 return ret;
7861 }
e440a328 7862 }
7863 break;
7864
7865 case BUILTIN_SIZEOF:
7866 case BUILTIN_ALIGNOF:
7867 return this->one_arg() != NULL;
7868
7869 case BUILTIN_OFFSETOF:
7870 {
7871 Expression* arg = this->one_arg();
7872 if (arg == NULL)
7873 return false;
7874 return arg->field_reference_expression() != NULL;
7875 }
7876
48080209 7877 case BUILTIN_COMPLEX:
e440a328 7878 {
7879 const Expression_list* args = this->args();
7880 if (args != NULL && args->size() == 2)
7881 return args->front()->is_constant() && args->back()->is_constant();
7882 }
7883 break;
7884
7885 case BUILTIN_REAL:
7886 case BUILTIN_IMAG:
7887 {
7888 Expression* arg = this->one_arg();
7889 return arg != NULL && arg->is_constant();
7890 }
7891
7892 default:
7893 break;
7894 }
7895
7896 return false;
7897}
7898
0c77715b 7899// Return a numeric constant if possible.
e440a328 7900
7901bool
0c77715b 7902Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7903{
7904 if (this->code_ == BUILTIN_LEN
7905 || this->code_ == BUILTIN_CAP)
7906 {
7907 Expression* arg = this->one_arg();
7908 if (arg == NULL)
7909 return false;
7910 Type* arg_type = arg->type();
7911
7912 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7913 {
7914 std::string sval;
7915 if (arg->string_constant_value(&sval))
7916 {
0c77715b 7917 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7918 sval.length());
e440a328 7919 return true;
7920 }
7921 }
7922
7923 if (arg_type->points_to() != NULL
7924 && arg_type->points_to()->array_type() != NULL
411eb89e 7925 && !arg_type->points_to()->is_slice_type())
e440a328 7926 arg_type = arg_type->points_to();
7927
7928 if (arg_type->array_type() != NULL
7929 && arg_type->array_type()->length() != NULL)
7930 {
0f914071 7931 if (this->seen_)
7932 return false;
e440a328 7933 Expression* e = arg_type->array_type()->length();
0f914071 7934 this->seen_ = true;
0c77715b 7935 bool r = e->numeric_constant_value(nc);
0f914071 7936 this->seen_ = false;
7937 if (r)
e440a328 7938 {
0c77715b 7939 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7940 this->location()))
7941 r = false;
e440a328 7942 }
0c77715b 7943 return r;
e440a328 7944 }
7945 }
7946 else if (this->code_ == BUILTIN_SIZEOF
7947 || this->code_ == BUILTIN_ALIGNOF)
7948 {
7949 Expression* arg = this->one_arg();
7950 if (arg == NULL)
7951 return false;
7952 Type* arg_type = arg->type();
5c13bd80 7953 if (arg_type->is_error())
e440a328 7954 return false;
7955 if (arg_type->is_abstract())
7956 return false;
2c809f8f 7957 if (this->seen_)
7958 return false;
927a01eb 7959
3f378015 7960 int64_t ret;
e440a328 7961 if (this->code_ == BUILTIN_SIZEOF)
7962 {
2c809f8f 7963 this->seen_ = true;
7964 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7965 this->seen_ = false;
7966 if (!ok)
e440a328 7967 return false;
7968 }
7969 else if (this->code_ == BUILTIN_ALIGNOF)
7970 {
2c809f8f 7971 bool ok;
7972 this->seen_ = true;
637bd3af 7973 if (arg->field_reference_expression() == NULL)
2c809f8f 7974 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7975 else
e440a328 7976 {
7977 // Calling unsafe.Alignof(s.f) returns the alignment of
7978 // the type of f when it is used as a field in a struct.
2c809f8f 7979 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7980 }
2c809f8f 7981 this->seen_ = false;
7982 if (!ok)
7983 return false;
e440a328 7984 }
7985 else
c3e6f413 7986 go_unreachable();
927a01eb 7987
3f378015 7988 mpz_t zval;
7989 set_mpz_from_int64(&zval, ret);
7990 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7991 mpz_clear(zval);
e440a328 7992 return true;
7993 }
7994 else if (this->code_ == BUILTIN_OFFSETOF)
7995 {
7996 Expression* arg = this->one_arg();
7997 if (arg == NULL)
7998 return false;
7999 Field_reference_expression* farg = arg->field_reference_expression();
8000 if (farg == NULL)
8001 return false;
2c809f8f 8002 if (this->seen_)
8003 return false;
8004
3f378015 8005 int64_t total_offset = 0;
9a4bd570 8006 while (true)
8007 {
8008 Expression* struct_expr = farg->expr();
8009 Type* st = struct_expr->type();
8010 if (st->struct_type() == NULL)
8011 return false;
8012 if (st->named_type() != NULL)
8013 st->named_type()->convert(this->gogo_);
3f378015 8014 int64_t offset;
2c809f8f 8015 this->seen_ = true;
8016 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8017 farg->field_index(),
8018 &offset);
8019 this->seen_ = false;
8020 if (!ok)
8021 return false;
9a4bd570 8022 total_offset += offset;
8023 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8024 {
8025 // Go up until we reach the original base.
8026 farg = struct_expr->field_reference_expression();
8027 continue;
8028 }
8029 break;
8030 }
3f378015 8031 mpz_t zval;
8032 set_mpz_from_int64(&zval, total_offset);
8033 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8034 mpz_clear(zval);
e440a328 8035 return true;
8036 }
0c77715b 8037 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 8038 {
8039 Expression* arg = this->one_arg();
8040 if (arg == NULL)
8041 return false;
8042
0c77715b 8043 Numeric_constant argnc;
8044 if (!arg->numeric_constant_value(&argnc))
8045 return false;
8046
fcbea5e4 8047 mpc_t val;
8048 if (!argnc.to_complex(&val))
0c77715b 8049 return false;
e440a328 8050
0c77715b 8051 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8052 if (this->code_ == BUILTIN_REAL)
fcbea5e4 8053 nc->set_float(type, mpc_realref(val));
0c77715b 8054 else
fcbea5e4 8055 nc->set_float(type, mpc_imagref(val));
8056 mpc_clear(val);
0c77715b 8057 return true;
e440a328 8058 }
0c77715b 8059 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 8060 {
8061 const Expression_list* args = this->args();
8062 if (args == NULL || args->size() != 2)
8063 return false;
8064
0c77715b 8065 Numeric_constant rnc;
8066 if (!args->front()->numeric_constant_value(&rnc))
8067 return false;
8068 Numeric_constant inc;
8069 if (!args->back()->numeric_constant_value(&inc))
8070 return false;
8071
8072 if (rnc.type() != NULL
8073 && !rnc.type()->is_abstract()
8074 && inc.type() != NULL
8075 && !inc.type()->is_abstract()
8076 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8077 return false;
8078
e440a328 8079 mpfr_t r;
0c77715b 8080 if (!rnc.to_float(&r))
8081 return false;
8082 mpfr_t i;
8083 if (!inc.to_float(&i))
e440a328 8084 {
8085 mpfr_clear(r);
8086 return false;
8087 }
8088
0c77715b 8089 Type* arg_type = rnc.type();
8090 if (arg_type == NULL || arg_type->is_abstract())
8091 arg_type = inc.type();
e440a328 8092
fcbea5e4 8093 mpc_t val;
8094 mpc_init2(val, mpc_precision);
8095 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
e440a328 8096 mpfr_clear(r);
8097 mpfr_clear(i);
8098
fcbea5e4 8099 Type* type = Builtin_call_expression::complex_type(arg_type);
8100 nc->set_complex(type, val);
8101
8102 mpc_clear(val);
8103
0c77715b 8104 return true;
e440a328 8105 }
8106
8107 return false;
8108}
8109
a7549a6a 8110// Give an error if we are discarding the value of an expression which
8111// should not normally be discarded. We don't give an error for
8112// discarding the value of an ordinary function call, but we do for
8113// builtin functions, purely for consistency with the gc compiler.
8114
4f2138d7 8115bool
a7549a6a 8116Builtin_call_expression::do_discarding_value()
8117{
8118 switch (this->code_)
8119 {
8120 case BUILTIN_INVALID:
8121 default:
8122 go_unreachable();
8123
8124 case BUILTIN_APPEND:
8125 case BUILTIN_CAP:
8126 case BUILTIN_COMPLEX:
8127 case BUILTIN_IMAG:
8128 case BUILTIN_LEN:
8129 case BUILTIN_MAKE:
8130 case BUILTIN_NEW:
8131 case BUILTIN_REAL:
8132 case BUILTIN_ALIGNOF:
8133 case BUILTIN_OFFSETOF:
8134 case BUILTIN_SIZEOF:
8135 this->unused_value_error();
4f2138d7 8136 return false;
a7549a6a 8137
8138 case BUILTIN_CLOSE:
8139 case BUILTIN_COPY:
1cce762f 8140 case BUILTIN_DELETE:
a7549a6a 8141 case BUILTIN_PANIC:
8142 case BUILTIN_PRINT:
8143 case BUILTIN_PRINTLN:
8144 case BUILTIN_RECOVER:
4f2138d7 8145 return true;
a7549a6a 8146 }
8147}
8148
e440a328 8149// Return the type.
8150
8151Type*
8152Builtin_call_expression::do_type()
8153{
79651b1f 8154 if (this->is_error_expression())
8155 return Type::make_error_type();
e440a328 8156 switch (this->code_)
8157 {
8158 case BUILTIN_INVALID:
8159 default:
79651b1f 8160 return Type::make_error_type();
e440a328 8161
8162 case BUILTIN_NEW:
8163 case BUILTIN_MAKE:
8164 {
8165 const Expression_list* args = this->args();
8166 if (args == NULL || args->empty())
8167 return Type::make_error_type();
8168 return Type::make_pointer_type(args->front()->type());
8169 }
8170
8171 case BUILTIN_CAP:
8172 case BUILTIN_COPY:
8173 case BUILTIN_LEN:
7ba86326 8174 return Type::lookup_integer_type("int");
8175
e440a328 8176 case BUILTIN_ALIGNOF:
8177 case BUILTIN_OFFSETOF:
8178 case BUILTIN_SIZEOF:
7ba86326 8179 return Type::lookup_integer_type("uintptr");
e440a328 8180
8181 case BUILTIN_CLOSE:
1cce762f 8182 case BUILTIN_DELETE:
e440a328 8183 case BUILTIN_PANIC:
8184 case BUILTIN_PRINT:
8185 case BUILTIN_PRINTLN:
8186 return Type::make_void_type();
8187
e440a328 8188 case BUILTIN_RECOVER:
823c7e3d 8189 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8190
8191 case BUILTIN_APPEND:
8192 {
8193 const Expression_list* args = this->args();
8194 if (args == NULL || args->empty())
8195 return Type::make_error_type();
3ff4863b 8196 Type *ret = args->front()->type();
8197 if (!ret->is_slice_type())
8198 return Type::make_error_type();
8199 return ret;
e440a328 8200 }
8201
8202 case BUILTIN_REAL:
8203 case BUILTIN_IMAG:
8204 {
8205 Expression* arg = this->one_arg();
8206 if (arg == NULL)
8207 return Type::make_error_type();
8208 Type* t = arg->type();
8209 if (t->is_abstract())
8210 t = t->make_non_abstract_type();
8211 t = Builtin_call_expression::real_imag_type(t);
8212 if (t == NULL)
8213 t = Type::make_error_type();
8214 return t;
8215 }
8216
48080209 8217 case BUILTIN_COMPLEX:
e440a328 8218 {
8219 const Expression_list* args = this->args();
8220 if (args == NULL || args->size() != 2)
8221 return Type::make_error_type();
8222 Type* t = args->front()->type();
8223 if (t->is_abstract())
8224 {
8225 t = args->back()->type();
8226 if (t->is_abstract())
8227 t = t->make_non_abstract_type();
8228 }
48080209 8229 t = Builtin_call_expression::complex_type(t);
e440a328 8230 if (t == NULL)
8231 t = Type::make_error_type();
8232 return t;
8233 }
8234 }
8235}
8236
8237// Determine the type.
8238
8239void
8240Builtin_call_expression::do_determine_type(const Type_context* context)
8241{
fb94b0ca 8242 if (!this->determining_types())
8243 return;
8244
e440a328 8245 this->fn()->determine_type_no_context();
8246
8247 const Expression_list* args = this->args();
8248
8249 bool is_print;
8250 Type* arg_type = NULL;
321e5ad2 8251 Type* trailing_arg_types = NULL;
e440a328 8252 switch (this->code_)
8253 {
8254 case BUILTIN_PRINT:
8255 case BUILTIN_PRINTLN:
8256 // Do not force a large integer constant to "int".
8257 is_print = true;
8258 break;
8259
8260 case BUILTIN_REAL:
8261 case BUILTIN_IMAG:
48080209 8262 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 8263 if (arg_type == NULL)
8264 arg_type = Type::lookup_complex_type("complex128");
e440a328 8265 is_print = false;
8266 break;
8267
48080209 8268 case BUILTIN_COMPLEX:
e440a328 8269 {
48080209 8270 // For the complex function the type of one operand can
e440a328 8271 // determine the type of the other, as in a binary expression.
8272 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 8273 if (arg_type == NULL)
8274 arg_type = Type::lookup_float_type("float64");
e440a328 8275 if (args != NULL && args->size() == 2)
8276 {
8277 Type* t1 = args->front()->type();
c849bb59 8278 Type* t2 = args->back()->type();
e440a328 8279 if (!t1->is_abstract())
8280 arg_type = t1;
8281 else if (!t2->is_abstract())
8282 arg_type = t2;
8283 }
8284 is_print = false;
8285 }
8286 break;
8287
321e5ad2 8288 case BUILTIN_APPEND:
8289 if (!this->is_varargs()
8290 && args != NULL
8291 && !args->empty()
8292 && args->front()->type()->is_slice_type())
8293 trailing_arg_types =
8294 args->front()->type()->array_type()->element_type();
8295 is_print = false;
8296 break;
8297
e440a328 8298 default:
8299 is_print = false;
8300 break;
8301 }
8302
8303 if (args != NULL)
8304 {
8305 for (Expression_list::const_iterator pa = args->begin();
8306 pa != args->end();
8307 ++pa)
8308 {
8309 Type_context subcontext;
8310 subcontext.type = arg_type;
8311
8312 if (is_print)
8313 {
8314 // We want to print large constants, we so can't just
8315 // use the appropriate nonabstract type. Use uint64 for
8316 // an integer if we know it is nonnegative, otherwise
8317 // use int64 for a integer, otherwise use float64 for a
8318 // float or complex128 for a complex.
8319 Type* want_type = NULL;
8320 Type* atype = (*pa)->type();
8321 if (atype->is_abstract())
8322 {
8323 if (atype->integer_type() != NULL)
8324 {
0c77715b 8325 Numeric_constant nc;
8326 if (this->numeric_constant_value(&nc))
8327 {
8328 mpz_t val;
8329 if (nc.to_int(&val))
8330 {
8331 if (mpz_sgn(val) >= 0)
8332 want_type = Type::lookup_integer_type("uint64");
8333 mpz_clear(val);
8334 }
8335 }
8336 if (want_type == NULL)
e440a328 8337 want_type = Type::lookup_integer_type("int64");
e440a328 8338 }
8339 else if (atype->float_type() != NULL)
8340 want_type = Type::lookup_float_type("float64");
8341 else if (atype->complex_type() != NULL)
8342 want_type = Type::lookup_complex_type("complex128");
8343 else if (atype->is_abstract_string_type())
8344 want_type = Type::lookup_string_type();
8345 else if (atype->is_abstract_boolean_type())
8346 want_type = Type::lookup_bool_type();
8347 else
c3e6f413 8348 go_unreachable();
e440a328 8349 subcontext.type = want_type;
8350 }
8351 }
8352
8353 (*pa)->determine_type(&subcontext);
321e5ad2 8354
8355 if (trailing_arg_types != NULL)
8356 {
8357 arg_type = trailing_arg_types;
8358 trailing_arg_types = NULL;
8359 }
e440a328 8360 }
8361 }
8362}
8363
8364// If there is exactly one argument, return true. Otherwise give an
8365// error message and return false.
8366
8367bool
8368Builtin_call_expression::check_one_arg()
8369{
8370 const Expression_list* args = this->args();
8371 if (args == NULL || args->size() < 1)
8372 {
8373 this->report_error(_("not enough arguments"));
8374 return false;
8375 }
8376 else if (args->size() > 1)
8377 {
8378 this->report_error(_("too many arguments"));
8379 return false;
8380 }
8381 if (args->front()->is_error_expression()
5c13bd80 8382 || args->front()->type()->is_error())
e440a328 8383 {
8384 this->set_is_error();
8385 return false;
8386 }
8387 return true;
8388}
8389
8390// Check argument types for a builtin function.
8391
8392void
8393Builtin_call_expression::do_check_types(Gogo*)
8394{
375646ea 8395 if (this->is_error_expression())
8396 return;
e440a328 8397 switch (this->code_)
8398 {
8399 case BUILTIN_INVALID:
8400 case BUILTIN_NEW:
8401 case BUILTIN_MAKE:
cd238b8d 8402 case BUILTIN_DELETE:
e440a328 8403 return;
8404
8405 case BUILTIN_LEN:
8406 case BUILTIN_CAP:
8407 {
8408 // The single argument may be either a string or an array or a
8409 // map or a channel, or a pointer to a closed array.
8410 if (this->check_one_arg())
8411 {
8412 Type* arg_type = this->one_arg()->type();
8413 if (arg_type->points_to() != NULL
8414 && arg_type->points_to()->array_type() != NULL
411eb89e 8415 && !arg_type->points_to()->is_slice_type())
e440a328 8416 arg_type = arg_type->points_to();
8417 if (this->code_ == BUILTIN_CAP)
8418 {
5c13bd80 8419 if (!arg_type->is_error()
e440a328 8420 && arg_type->array_type() == NULL
8421 && arg_type->channel_type() == NULL)
8422 this->report_error(_("argument must be array or slice "
8423 "or channel"));
8424 }
8425 else
8426 {
5c13bd80 8427 if (!arg_type->is_error()
e440a328 8428 && !arg_type->is_string_type()
8429 && arg_type->array_type() == NULL
8430 && arg_type->map_type() == NULL
8431 && arg_type->channel_type() == NULL)
8432 this->report_error(_("argument must be string or "
8433 "array or slice or map or channel"));
8434 }
8435 }
8436 }
8437 break;
8438
8439 case BUILTIN_PRINT:
8440 case BUILTIN_PRINTLN:
8441 {
8442 const Expression_list* args = this->args();
8443 if (args == NULL)
8444 {
8445 if (this->code_ == BUILTIN_PRINT)
631d5788 8446 go_warning_at(this->location(), 0,
e440a328 8447 "no arguments for builtin function %<%s%>",
8448 (this->code_ == BUILTIN_PRINT
8449 ? "print"
8450 : "println"));
8451 }
8452 else
8453 {
8454 for (Expression_list::const_iterator p = args->begin();
8455 p != args->end();
8456 ++p)
8457 {
8458 Type* type = (*p)->type();
5c13bd80 8459 if (type->is_error()
e440a328 8460 || type->is_string_type()
8461 || type->integer_type() != NULL
8462 || type->float_type() != NULL
8463 || type->complex_type() != NULL
8464 || type->is_boolean_type()
8465 || type->points_to() != NULL
8466 || type->interface_type() != NULL
8467 || type->channel_type() != NULL
8468 || type->map_type() != NULL
8469 || type->function_type() != NULL
411eb89e 8470 || type->is_slice_type())
e440a328 8471 ;
acf8e158 8472 else if ((*p)->is_type_expression())
8473 {
8474 // If this is a type expression it's going to give
8475 // an error anyhow, so we don't need one here.
8476 }
e440a328 8477 else
8478 this->report_error(_("unsupported argument type to "
8479 "builtin function"));
8480 }
8481 }
8482 }
8483 break;
8484
8485 case BUILTIN_CLOSE:
e440a328 8486 if (this->check_one_arg())
8487 {
8488 if (this->one_arg()->type()->channel_type() == NULL)
8489 this->report_error(_("argument must be channel"));
5202d986 8490 else if (!this->one_arg()->type()->channel_type()->may_send())
8491 this->report_error(_("cannot close receive-only channel"));
e440a328 8492 }
8493 break;
8494
8495 case BUILTIN_PANIC:
8496 case BUILTIN_SIZEOF:
8497 case BUILTIN_ALIGNOF:
8498 this->check_one_arg();
8499 break;
8500
8501 case BUILTIN_RECOVER:
6334270b 8502 if (this->args() != NULL
8503 && !this->args()->empty()
8504 && !this->recover_arg_is_set_)
e440a328 8505 this->report_error(_("too many arguments"));
8506 break;
8507
8508 case BUILTIN_OFFSETOF:
8509 if (this->check_one_arg())
8510 {
8511 Expression* arg = this->one_arg();
8512 if (arg->field_reference_expression() == NULL)
8513 this->report_error(_("argument must be a field reference"));
8514 }
8515 break;
8516
8517 case BUILTIN_COPY:
8518 {
8519 const Expression_list* args = this->args();
8520 if (args == NULL || args->size() < 2)
8521 {
8522 this->report_error(_("not enough arguments"));
8523 break;
8524 }
8525 else if (args->size() > 2)
8526 {
8527 this->report_error(_("too many arguments"));
8528 break;
8529 }
8530 Type* arg1_type = args->front()->type();
8531 Type* arg2_type = args->back()->type();
5c13bd80 8532 if (arg1_type->is_error() || arg2_type->is_error())
6bebb39d 8533 {
8534 this->set_is_error();
8535 break;
8536 }
e440a328 8537
8538 Type* e1;
411eb89e 8539 if (arg1_type->is_slice_type())
e440a328 8540 e1 = arg1_type->array_type()->element_type();
8541 else
8542 {
8543 this->report_error(_("left argument must be a slice"));
8544 break;
8545 }
8546
411eb89e 8547 if (arg2_type->is_slice_type())
60963afd 8548 {
8549 Type* e2 = arg2_type->array_type()->element_type();
8550 if (!Type::are_identical(e1, e2, true, NULL))
8551 this->report_error(_("element types must be the same"));
8552 }
e440a328 8553 else if (arg2_type->is_string_type())
e440a328 8554 {
60963afd 8555 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8556 this->report_error(_("first argument must be []byte"));
e440a328 8557 }
60963afd 8558 else
8559 this->report_error(_("second argument must be slice or string"));
e440a328 8560 }
8561 break;
8562
8563 case BUILTIN_APPEND:
8564 {
8565 const Expression_list* args = this->args();
321e5ad2 8566 if (args == NULL || args->empty())
e440a328 8567 {
8568 this->report_error(_("not enough arguments"));
8569 break;
8570 }
321e5ad2 8571
8572 Type* slice_type = args->front()->type();
8573 if (!slice_type->is_slice_type())
6bebb39d 8574 {
321e5ad2 8575 if (slice_type->is_error_type())
8576 break;
8577 if (slice_type->is_nil_type())
8578 go_error_at(args->front()->location(), "use of untyped nil");
8579 else
8580 go_error_at(args->front()->location(),
8581 "argument 1 must be a slice");
6bebb39d 8582 this->set_is_error();
8583 break;
8584 }
cd238b8d 8585
321e5ad2 8586 Type* element_type = slice_type->array_type()->element_type();
8587 if (this->is_varargs())
4fd4fcf4 8588 {
321e5ad2 8589 if (!args->back()->type()->is_slice_type()
8590 && !args->back()->type()->is_string_type())
8591 {
8592 go_error_at(args->back()->location(),
8593 "invalid use of %<...%> with non-slice/non-string");
8594 this->set_is_error();
8595 break;
8596 }
4fd4fcf4 8597
321e5ad2 8598 if (args->size() < 2)
8599 {
8600 this->report_error(_("not enough arguments"));
8601 break;
8602 }
8603 if (args->size() > 2)
8604 {
8605 this->report_error(_("too many arguments"));
8606 break;
8607 }
8608
8609 if (args->back()->type()->is_string_type()
8610 && element_type->integer_type() != NULL
8611 && element_type->integer_type()->is_byte())
8612 {
8613 // Permit append(s1, s2...) when s1 is a slice of
8614 // bytes and s2 is a string type.
8615 }
e440a328 8616 else
8617 {
321e5ad2 8618 // We have to test for assignment compatibility to a
8619 // slice of the element type, which is not necessarily
8620 // the same as the type of the first argument: the
8621 // first argument might have a named type.
8622 Type* check_type = Type::make_array_type(element_type, NULL);
8623 std::string reason;
8624 if (!Type::are_assignable(check_type, args->back()->type(),
8625 &reason))
8626 {
8627 if (reason.empty())
8628 go_error_at(args->back()->location(),
8629 "argument 2 has invalid type");
8630 else
8631 go_error_at(args->back()->location(),
8632 "argument 2 has invalid type (%s)",
8633 reason.c_str());
8634 this->set_is_error();
8635 break;
8636 }
8637 }
8638 }
8639 else
8640 {
8641 Expression_list::const_iterator pa = args->begin();
8642 int i = 2;
8643 for (++pa; pa != args->end(); ++pa, ++i)
8644 {
8645 std::string reason;
8646 if (!Type::are_assignable(element_type, (*pa)->type(),
8647 &reason))
8648 {
8649 if (reason.empty())
8650 go_error_at((*pa)->location(),
8651 "argument %d has incompatible type", i);
8652 else
8653 go_error_at((*pa)->location(),
8654 "argument %d has incompatible type (%s)",
8655 i, reason.c_str());
8656 this->set_is_error();
8657 }
e440a328 8658 }
8659 }
e440a328 8660 }
321e5ad2 8661 break;
e440a328 8662
8663 case BUILTIN_REAL:
8664 case BUILTIN_IMAG:
8665 if (this->check_one_arg())
8666 {
8667 if (this->one_arg()->type()->complex_type() == NULL)
8668 this->report_error(_("argument must have complex type"));
8669 }
8670 break;
8671
48080209 8672 case BUILTIN_COMPLEX:
e440a328 8673 {
8674 const Expression_list* args = this->args();
8675 if (args == NULL || args->size() < 2)
8676 this->report_error(_("not enough arguments"));
8677 else if (args->size() > 2)
8678 this->report_error(_("too many arguments"));
8679 else if (args->front()->is_error_expression()
5c13bd80 8680 || args->front()->type()->is_error()
e440a328 8681 || args->back()->is_error_expression()
5c13bd80 8682 || args->back()->type()->is_error())
e440a328 8683 this->set_is_error();
8684 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8685 args->back()->type(), true, NULL))
48080209 8686 this->report_error(_("complex arguments must have identical types"));
e440a328 8687 else if (args->front()->type()->float_type() == NULL)
48080209 8688 this->report_error(_("complex arguments must have "
e440a328 8689 "floating-point type"));
8690 }
8691 break;
8692
8693 default:
c3e6f413 8694 go_unreachable();
e440a328 8695 }
8696}
8697
72666aed 8698Expression*
8699Builtin_call_expression::do_copy()
8700{
8701 Call_expression* bce =
8702 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
da244e59 8703 (this->args() == NULL
8704 ? NULL
8705 : this->args()->copy()),
72666aed 8706 this->is_varargs(),
8707 this->location());
8708
8709 if (this->varargs_are_lowered())
8710 bce->set_varargs_are_lowered();
8711 return bce;
8712}
8713
ea664253 8714// Return the backend representation for a builtin function.
e440a328 8715
ea664253 8716Bexpression*
8717Builtin_call_expression::do_get_backend(Translate_context* context)
e440a328 8718{
8719 Gogo* gogo = context->gogo();
b13c66cd 8720 Location location = this->location();
a0d8874e 8721
8722 if (this->is_erroneous_call())
8723 {
8724 go_assert(saw_errors());
8725 return gogo->backend()->error_expression();
8726 }
8727
e440a328 8728 switch (this->code_)
8729 {
8730 case BUILTIN_INVALID:
8731 case BUILTIN_NEW:
8732 case BUILTIN_MAKE:
c3e6f413 8733 go_unreachable();
e440a328 8734
8735 case BUILTIN_LEN:
8736 case BUILTIN_CAP:
8737 {
8738 const Expression_list* args = this->args();
c484d925 8739 go_assert(args != NULL && args->size() == 1);
2c809f8f 8740 Expression* arg = args->front();
e440a328 8741 Type* arg_type = arg->type();
0f914071 8742
8743 if (this->seen_)
8744 {
c484d925 8745 go_assert(saw_errors());
ea664253 8746 return context->backend()->error_expression();
0f914071 8747 }
8748 this->seen_ = true;
0f914071 8749 this->seen_ = false;
e440a328 8750 if (arg_type->points_to() != NULL)
8751 {
8752 arg_type = arg_type->points_to();
c484d925 8753 go_assert(arg_type->array_type() != NULL
411eb89e 8754 && !arg_type->is_slice_type());
2c809f8f 8755 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8756 }
8757
1b1f2abf 8758 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8759 Expression* val;
e440a328 8760 if (this->code_ == BUILTIN_LEN)
8761 {
8762 if (arg_type->is_string_type())
2c809f8f 8763 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8764 location);
e440a328 8765 else if (arg_type->array_type() != NULL)
0f914071 8766 {
8767 if (this->seen_)
8768 {
c484d925 8769 go_assert(saw_errors());
ea664253 8770 return context->backend()->error_expression();
0f914071 8771 }
8772 this->seen_ = true;
2c809f8f 8773 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8774 this->seen_ = false;
8775 }
0d5530d9 8776 else if (arg_type->map_type() != NULL
8777 || arg_type->channel_type() != NULL)
8778 {
8779 // The first field is the length. If the pointer is
8780 // nil, the length is zero.
8781 Type* pint_type = Type::make_pointer_type(int_type);
8782 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8783 Expression* nil = Expression::make_nil(location);
8784 nil = Expression::make_cast(pint_type, nil, location);
8785 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8786 arg, nil, location);
8787 Expression* zero = Expression::make_integer_ul(0, int_type,
8788 location);
8789 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8790 arg, location);
8791 val = Expression::make_conditional(cmp, zero, indir, location);
8792 }
e440a328 8793 else
c3e6f413 8794 go_unreachable();
e440a328 8795 }
8796 else
8797 {
8798 if (arg_type->array_type() != NULL)
0f914071 8799 {
8800 if (this->seen_)
8801 {
c484d925 8802 go_assert(saw_errors());
ea664253 8803 return context->backend()->error_expression();
0f914071 8804 }
8805 this->seen_ = true;
2c809f8f 8806 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8807 this->seen_ = false;
8808 }
e440a328 8809 else if (arg_type->channel_type() != NULL)
132ed071 8810 {
8811 // The second field is the capacity. If the pointer
8812 // is nil, the capacity is zero.
8813 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8814 Type* pint_type = Type::make_pointer_type(int_type);
8815 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8816 arg,
8817 location);
8818 int off = int_type->integer_type()->bits() / 8;
8819 Expression* eoff = Expression::make_integer_ul(off,
8820 uintptr_type,
8821 location);
8822 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8823 location);
8824 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8825 Expression* nil = Expression::make_nil(location);
8826 nil = Expression::make_cast(pint_type, nil, location);
8827 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8828 arg, nil, location);
8829 Expression* zero = Expression::make_integer_ul(0, int_type,
8830 location);
8831 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8832 parg, location);
8833 val = Expression::make_conditional(cmp, zero, indir, location);
8834 }
e440a328 8835 else
c3e6f413 8836 go_unreachable();
e440a328 8837 }
8838
2c809f8f 8839 return Expression::make_cast(int_type, val,
ea664253 8840 location)->get_backend(context);
e440a328 8841 }
8842
8843 case BUILTIN_PRINT:
8844 case BUILTIN_PRINTLN:
8845 {
8846 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
88b03a70 8847
8848 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
8849 location, 0);
e440a328 8850
8851 const Expression_list* call_args = this->args();
8852 if (call_args != NULL)
8853 {
8854 for (Expression_list::const_iterator p = call_args->begin();
8855 p != call_args->end();
8856 ++p)
8857 {
8858 if (is_ln && p != call_args->begin())
8859 {
2c809f8f 8860 Expression* print_space =
88b03a70 8861 Runtime::make_call(Runtime::PRINTSP, location, 0);
e440a328 8862
2c809f8f 8863 print_stmts =
8864 Expression::make_compound(print_stmts, print_space,
8865 location);
8866 }
e440a328 8867
2c809f8f 8868 Expression* arg = *p;
8869 Type* type = arg->type();
8870 Runtime::Function code;
e440a328 8871 if (type->is_string_type())
88b03a70 8872 code = Runtime::PRINTSTRING;
e440a328 8873 else if (type->integer_type() != NULL
8874 && type->integer_type()->is_unsigned())
8875 {
e440a328 8876 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8877 arg = Expression::make_cast(itype, arg, location);
88b03a70 8878 code = Runtime::PRINTUINT;
e440a328 8879 }
8880 else if (type->integer_type() != NULL)
8881 {
e440a328 8882 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8883 arg = Expression::make_cast(itype, arg, location);
88b03a70 8884 code = Runtime::PRINTINT;
e440a328 8885 }
8886 else if (type->float_type() != NULL)
8887 {
2c809f8f 8888 Type* dtype = Type::lookup_float_type("float64");
8889 arg = Expression::make_cast(dtype, arg, location);
88b03a70 8890 code = Runtime::PRINTFLOAT;
e440a328 8891 }
8892 else if (type->complex_type() != NULL)
8893 {
2c809f8f 8894 Type* ctype = Type::lookup_complex_type("complex128");
8895 arg = Expression::make_cast(ctype, arg, location);
88b03a70 8896 code = Runtime::PRINTCOMPLEX;
e440a328 8897 }
8898 else if (type->is_boolean_type())
88b03a70 8899 code = Runtime::PRINTBOOL;
e440a328 8900 else if (type->points_to() != NULL
8901 || type->channel_type() != NULL
8902 || type->map_type() != NULL
8903 || type->function_type() != NULL)
8904 {
2c809f8f 8905 arg = Expression::make_cast(type, arg, location);
88b03a70 8906 code = Runtime::PRINTPOINTER;
e440a328 8907 }
8908 else if (type->interface_type() != NULL)
8909 {
8910 if (type->interface_type()->is_empty())
88b03a70 8911 code = Runtime::PRINTEFACE;
e440a328 8912 else
88b03a70 8913 code = Runtime::PRINTIFACE;
e440a328 8914 }
411eb89e 8915 else if (type->is_slice_type())
88b03a70 8916 code = Runtime::PRINTSLICE;
e440a328 8917 else
cd238b8d 8918 {
8919 go_assert(saw_errors());
ea664253 8920 return context->backend()->error_expression();
cd238b8d 8921 }
e440a328 8922
2c809f8f 8923 Expression* call = Runtime::make_call(code, location, 1, arg);
88b03a70 8924 print_stmts = Expression::make_compound(print_stmts, call,
8925 location);
e440a328 8926 }
8927 }
8928
8929 if (is_ln)
8930 {
2c809f8f 8931 Expression* print_nl =
88b03a70 8932 Runtime::make_call(Runtime::PRINTNL, location, 0);
8933 print_stmts = Expression::make_compound(print_stmts, print_nl,
8934 location);
e440a328 8935 }
8936
88b03a70 8937 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
8938 location, 0);
8939 print_stmts = Expression::make_compound(print_stmts, unlock, location);
32e3ff69 8940
ea664253 8941 return print_stmts->get_backend(context);
e440a328 8942 }
8943
8944 case BUILTIN_PANIC:
8945 {
8946 const Expression_list* args = this->args();
c484d925 8947 go_assert(args != NULL && args->size() == 1);
e440a328 8948 Expression* arg = args->front();
b13c66cd 8949 Type *empty =
823c7e3d 8950 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8951 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8952
8953 Expression* panic =
8954 Runtime::make_call(Runtime::PANIC, location, 1, arg);
ea664253 8955 return panic->get_backend(context);
e440a328 8956 }
8957
8958 case BUILTIN_RECOVER:
8959 {
8960 // The argument is set when building recover thunks. It's a
8961 // boolean value which is true if we can recover a value now.
8962 const Expression_list* args = this->args();
c484d925 8963 go_assert(args != NULL && args->size() == 1);
e440a328 8964 Expression* arg = args->front();
b13c66cd 8965 Type *empty =
823c7e3d 8966 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8967
e440a328 8968 Expression* nil = Expression::make_nil(location);
2c809f8f 8969 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8970
8971 // We need to handle a deferred call to recover specially,
8972 // because it changes whether it can recover a panic or not.
8973 // See test7 in test/recover1.go.
2c809f8f 8974 Expression* recover = Runtime::make_call((this->is_deferred()
8975 ? Runtime::DEFERRED_RECOVER
8976 : Runtime::RECOVER),
8977 location, 0);
8978 Expression* cond =
8979 Expression::make_conditional(arg, recover, nil, location);
ea664253 8980 return cond->get_backend(context);
e440a328 8981 }
8982
8983 case BUILTIN_CLOSE:
e440a328 8984 {
8985 const Expression_list* args = this->args();
c484d925 8986 go_assert(args != NULL && args->size() == 1);
e440a328 8987 Expression* arg = args->front();
2c809f8f 8988 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8989 1, arg);
ea664253 8990 return close->get_backend(context);
e440a328 8991 }
8992
8993 case BUILTIN_SIZEOF:
8994 case BUILTIN_OFFSETOF:
8995 case BUILTIN_ALIGNOF:
8996 {
0c77715b 8997 Numeric_constant nc;
8998 unsigned long val;
8999 if (!this->numeric_constant_value(&nc)
9000 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 9001 {
c484d925 9002 go_assert(saw_errors());
ea664253 9003 return context->backend()->error_expression();
7f1d9abd 9004 }
7ba86326 9005 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 9006 mpz_t ival;
9007 nc.get_int(&ival);
9008 Expression* int_cst =
e67508fa 9009 Expression::make_integer_z(&ival, uintptr_type, location);
2c809f8f 9010 mpz_clear(ival);
ea664253 9011 return int_cst->get_backend(context);
e440a328 9012 }
9013
9014 case BUILTIN_COPY:
9015 {
9016 const Expression_list* args = this->args();
c484d925 9017 go_assert(args != NULL && args->size() == 2);
e440a328 9018 Expression* arg1 = args->front();
9019 Expression* arg2 = args->back();
9020
e440a328 9021 Type* arg1_type = arg1->type();
9022 Array_type* at = arg1_type->array_type();
35a54f17 9023 go_assert(arg1->is_variable());
321e5ad2 9024
9025 Expression* call;
e440a328 9026
9027 Type* arg2_type = arg2->type();
2c809f8f 9028 go_assert(arg2->is_variable());
321e5ad2 9029 if (arg2_type->is_string_type())
9030 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9031 2, arg1, arg2);
e440a328 9032 else
9033 {
321e5ad2 9034 Type* et = at->element_type();
9035 if (et->has_pointer())
9036 {
9037 Expression* td = Expression::make_type_descriptor(et,
9038 location);
9039 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9040 3, td, arg1, arg2);
9041 }
9042 else
9043 {
9044 Expression* sz = Expression::make_type_info(et,
9045 TYPE_INFO_SIZE);
9046 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9047 arg1, arg2, sz);
9048 }
e440a328 9049 }
2c809f8f 9050
321e5ad2 9051 return call->get_backend(context);
e440a328 9052 }
9053
9054 case BUILTIN_APPEND:
321e5ad2 9055 // Handled in Builtin_call_expression::flatten_append.
9056 go_unreachable();
e440a328 9057
9058 case BUILTIN_REAL:
9059 case BUILTIN_IMAG:
9060 {
9061 const Expression_list* args = this->args();
c484d925 9062 go_assert(args != NULL && args->size() == 1);
2c809f8f 9063
9064 Bexpression* ret;
ea664253 9065 Bexpression* bcomplex = args->front()->get_backend(context);
2c809f8f 9066 if (this->code_ == BUILTIN_REAL)
9067 ret = gogo->backend()->real_part_expression(bcomplex, location);
9068 else
9069 ret = gogo->backend()->imag_part_expression(bcomplex, location);
ea664253 9070 return ret;
e440a328 9071 }
9072
48080209 9073 case BUILTIN_COMPLEX:
e440a328 9074 {
9075 const Expression_list* args = this->args();
c484d925 9076 go_assert(args != NULL && args->size() == 2);
ea664253 9077 Bexpression* breal = args->front()->get_backend(context);
9078 Bexpression* bimag = args->back()->get_backend(context);
9079 return gogo->backend()->complex_expression(breal, bimag, location);
e440a328 9080 }
9081
9082 default:
c3e6f413 9083 go_unreachable();
e440a328 9084 }
9085}
9086
9087// We have to support exporting a builtin call expression, because
9088// code can set a constant to the result of a builtin expression.
9089
9090void
9091Builtin_call_expression::do_export(Export* exp) const
9092{
0c77715b 9093 Numeric_constant nc;
9094 if (!this->numeric_constant_value(&nc))
9095 {
631d5788 9096 go_error_at(this->location(), "value is not constant");
0c77715b 9097 return;
9098 }
e440a328 9099
0c77715b 9100 if (nc.is_int())
e440a328 9101 {
0c77715b 9102 mpz_t val;
9103 nc.get_int(&val);
e440a328 9104 Integer_expression::export_integer(exp, val);
0c77715b 9105 mpz_clear(val);
e440a328 9106 }
0c77715b 9107 else if (nc.is_float())
e440a328 9108 {
9109 mpfr_t fval;
0c77715b 9110 nc.get_float(&fval);
9111 Float_expression::export_float(exp, fval);
e440a328 9112 mpfr_clear(fval);
9113 }
0c77715b 9114 else if (nc.is_complex())
e440a328 9115 {
fcbea5e4 9116 mpc_t cval;
9117 nc.get_complex(&cval);
9118 Complex_expression::export_complex(exp, cval);
9119 mpc_clear(cval);
e440a328 9120 }
0c77715b 9121 else
9122 go_unreachable();
e440a328 9123
9124 // A trailing space lets us reliably identify the end of the number.
9125 exp->write_c_string(" ");
9126}
9127
9128// Class Call_expression.
9129
8381eda7 9130// A Go function can be viewed in a couple of different ways. The
9131// code of a Go function becomes a backend function with parameters
9132// whose types are simply the backend representation of the Go types.
9133// If there are multiple results, they are returned as a backend
9134// struct.
9135
9136// However, when Go code refers to a function other than simply
9137// calling it, the backend type of that function is actually a struct.
9138// The first field of the struct points to the Go function code
9139// (sometimes a wrapper as described below). The remaining fields
9140// hold addresses of closed-over variables. This struct is called a
9141// closure.
9142
9143// There are a few cases to consider.
9144
9145// A direct function call of a known function in package scope. In
9146// this case there are no closed-over variables, and we know the name
9147// of the function code. We can simply produce a backend call to the
9148// function directly, and not worry about the closure.
9149
9150// A direct function call of a known function literal. In this case
9151// we know the function code and we know the closure. We generate the
9152// function code such that it expects an additional final argument of
9153// the closure type. We pass the closure as the last argument, after
9154// the other arguments.
9155
9156// An indirect function call. In this case we have a closure. We
9157// load the pointer to the function code from the first field of the
9158// closure. We pass the address of the closure as the last argument.
9159
9160// A call to a method of an interface. Type methods are always at
9161// package scope, so we call the function directly, and don't worry
9162// about the closure.
9163
9164// This means that for a function at package scope we have two cases.
9165// One is the direct call, which has no closure. The other is the
9166// indirect call, which does have a closure. We can't simply ignore
9167// the closure, even though it is the last argument, because that will
9168// fail on targets where the function pops its arguments. So when
9169// generating a closure for a package-scope function we set the
9170// function code pointer in the closure to point to a wrapper
9171// function. This wrapper function accepts a final argument that
9172// points to the closure, ignores it, and calls the real function as a
9173// direct function call. This wrapper will normally be efficient, and
9174// can often simply be a tail call to the real function.
9175
9176// We don't use GCC's static chain pointer because 1) we don't need
9177// it; 2) GCC only permits using a static chain to call a known
9178// function, so we can't use it for an indirect call anyhow. Since we
9179// can't use it for an indirect call, we may as well not worry about
9180// using it for a direct call either.
9181
9182// We pass the closure last rather than first because it means that
9183// the function wrapper we put into a closure for a package-scope
9184// function can normally just be a tail call to the real function.
9185
9186// For method expressions we generate a wrapper that loads the
9187// receiver from the closure and then calls the method. This
9188// unfortunately forces reshuffling the arguments, since there is a
9189// new first argument, but we can't avoid reshuffling either for
9190// method expressions or for indirect calls of package-scope
9191// functions, and since the latter are more common we reshuffle for
9192// method expressions.
9193
9194// Note that the Go code retains the Go types. The extra final
9195// argument only appears when we convert to the backend
9196// representation.
9197
e440a328 9198// Traversal.
9199
9200int
9201Call_expression::do_traverse(Traverse* traverse)
9202{
0c0dacab 9203 // If we are calling a function in a different package that returns
9204 // an unnamed type, this may be the only chance we get to traverse
9205 // that type. We don't traverse this->type_ because it may be a
9206 // Call_multiple_result_type that will just lead back here.
9207 if (this->type_ != NULL && !this->type_->is_error_type())
9208 {
9209 Function_type *fntype = this->get_function_type();
9210 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9211 return TRAVERSE_EXIT;
9212 }
e440a328 9213 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9214 return TRAVERSE_EXIT;
9215 if (this->args_ != NULL)
9216 {
9217 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9218 return TRAVERSE_EXIT;
9219 }
9220 return TRAVERSE_CONTINUE;
9221}
9222
9223// Lower a call statement.
9224
9225Expression*
ceeb4318 9226Call_expression::do_lower(Gogo* gogo, Named_object* function,
9227 Statement_inserter* inserter, int)
e440a328 9228{
b13c66cd 9229 Location loc = this->location();
09ea332d 9230
ceeb4318 9231 // A type cast can look like a function call.
e440a328 9232 if (this->fn_->is_type_expression()
9233 && this->args_ != NULL
9234 && this->args_->size() == 1)
9235 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 9236 loc);
e440a328 9237
88f06749 9238 // Because do_type will return an error type and thus prevent future
9239 // errors, check for that case now to ensure that the error gets
9240 // reported.
37448b10 9241 Function_type* fntype = this->get_function_type();
9242 if (fntype == NULL)
88f06749 9243 {
9244 if (!this->fn_->type()->is_error())
9245 this->report_error(_("expected function"));
5f1045b5 9246 this->set_is_error();
9247 return this;
88f06749 9248 }
9249
e440a328 9250 // Handle an argument which is a call to a function which returns
9251 // multiple results.
9252 if (this->args_ != NULL
9253 && this->args_->size() == 1
37448b10 9254 && this->args_->front()->call_expression() != NULL)
e440a328 9255 {
e440a328 9256 size_t rc = this->args_->front()->call_expression()->result_count();
9257 if (rc > 1
37448b10 9258 && ((fntype->parameters() != NULL
9259 && (fntype->parameters()->size() == rc
9260 || (fntype->is_varargs()
9261 && fntype->parameters()->size() - 1 <= rc)))
9262 || fntype->is_builtin()))
e440a328 9263 {
9264 Call_expression* call = this->args_->front()->call_expression();
e90ecd2d 9265 call->set_is_multi_value_arg();
c33af8e4 9266 if (this->is_varargs_)
9267 {
9268 // It is not clear which result of a multiple result call
9269 // the ellipsis operator should be applied to. If we unpack the
9270 // the call into its individual results here, the ellipsis will be
9271 // applied to the last result.
631d5788 9272 go_error_at(call->location(),
9273 _("multiple-value argument in single-value context"));
c33af8e4 9274 return Expression::make_error(call->location());
9275 }
9276
e440a328 9277 Expression_list* args = new Expression_list;
9278 for (size_t i = 0; i < rc; ++i)
9279 args->push_back(Expression::make_call_result(call, i));
9280 // We can't return a new call expression here, because this
42535814 9281 // one may be referenced by Call_result expressions. We
9282 // also can't delete the old arguments, because we may still
9283 // traverse them somewhere up the call stack. FIXME.
e440a328 9284 this->args_ = args;
9285 }
9286 }
9287
37448b10 9288 // Recognize a call to a builtin function.
9289 if (fntype->is_builtin())
9290 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9291 this->is_varargs_, loc);
9292
ceeb4318 9293 // If this call returns multiple results, create a temporary
9294 // variable for each result.
9295 size_t rc = this->result_count();
9296 if (rc > 1 && this->results_ == NULL)
9297 {
9298 std::vector<Temporary_statement*>* temps =
9299 new std::vector<Temporary_statement*>;
9300 temps->reserve(rc);
37448b10 9301 const Typed_identifier_list* results = fntype->results();
ceeb4318 9302 for (Typed_identifier_list::const_iterator p = results->begin();
9303 p != results->end();
9304 ++p)
9305 {
9306 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 9307 NULL, loc);
ceeb4318 9308 inserter->insert(temp);
9309 temps->push_back(temp);
9310 }
9311 this->results_ = temps;
9312 }
9313
e440a328 9314 // Handle a call to a varargs function by packaging up the extra
9315 // parameters.
37448b10 9316 if (fntype->is_varargs())
e440a328 9317 {
e440a328 9318 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 9319 go_assert(parameters != NULL && !parameters->empty());
e440a328 9320 Type* varargs_type = parameters->back().type();
09ea332d 9321 this->lower_varargs(gogo, function, inserter, varargs_type,
0e9a2e72 9322 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
09ea332d 9323 }
9324
9325 // If this is call to a method, call the method directly passing the
9326 // object as the first parameter.
9327 Bound_method_expression* bme = this->fn_->bound_method_expression();
9328 if (bme != NULL)
9329 {
0afbb937 9330 Named_object* methodfn = bme->function();
09ea332d 9331 Expression* first_arg = bme->first_argument();
9332
9333 // We always pass a pointer when calling a method.
9334 if (first_arg->type()->points_to() == NULL
9335 && !first_arg->type()->is_error())
9336 {
9337 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9338 // We may need to create a temporary variable so that we can
9339 // take the address. We can't do that here because it will
9340 // mess up the order of evaluation.
9341 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9342 ue->set_create_temp();
9343 }
9344
9345 // If we are calling a method which was inherited from an
9346 // embedded struct, and the method did not get a stub, then the
9347 // first type may be wrong.
9348 Type* fatype = bme->first_argument_type();
9349 if (fatype != NULL)
9350 {
9351 if (fatype->points_to() == NULL)
9352 fatype = Type::make_pointer_type(fatype);
9353 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9354 }
9355
9356 Expression_list* new_args = new Expression_list();
9357 new_args->push_back(first_arg);
9358 if (this->args_ != NULL)
9359 {
9360 for (Expression_list::const_iterator p = this->args_->begin();
9361 p != this->args_->end();
9362 ++p)
9363 new_args->push_back(*p);
9364 }
9365
9366 // We have to change in place because this structure may be
9367 // referenced by Call_result_expressions. We can't delete the
9368 // old arguments, because we may be traversing them up in some
9369 // caller. FIXME.
9370 this->args_ = new_args;
0afbb937 9371 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 9372 bme->location());
e440a328 9373 }
9374
105f9a24 9375 // Handle a couple of special runtime functions. In the runtime
9376 // package, getcallerpc returns the PC of the caller, and
9377 // getcallersp returns the frame pointer of the caller. Implement
9378 // these by turning them into calls to GCC builtin functions. We
9379 // could implement them in normal code, but then we would have to
9380 // explicitly unwind the stack. These functions are intended to be
9381 // efficient. Note that this technique obviously only works for
9382 // direct calls, but that is the only way they are used. The actual
9383 // argument to these functions is always the address of a parameter;
9384 // we don't need that for the GCC builtin functions, so we just
9385 // ignore it.
9386 if (gogo->compiling_runtime()
9387 && this->args_ != NULL
9388 && this->args_->size() == 1
9389 && gogo->package_name() == "runtime")
9390 {
9391 Func_expression* fe = this->fn_->func_expression();
9392 if (fe != NULL
9393 && fe->named_object()->is_function_declaration()
9394 && fe->named_object()->package() == NULL)
9395 {
9396 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9397 if (n == "getcallerpc")
9398 {
9399 static Named_object* builtin_return_address;
9400 return this->lower_to_builtin(&builtin_return_address,
9401 "__builtin_return_address",
9402 0);
9403 }
9404 else if (n == "getcallersp")
9405 {
9406 static Named_object* builtin_frame_address;
9407 return this->lower_to_builtin(&builtin_frame_address,
9408 "__builtin_frame_address",
9409 1);
9410 }
9411 }
9412 }
9413
e440a328 9414 return this;
9415}
9416
9417// Lower a call to a varargs function. FUNCTION is the function in
9418// which the call occurs--it's not the function we are calling.
9419// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9420// PARAM_COUNT is the number of parameters of the function we are
9421// calling; the last of these parameters will be the varargs
9422// parameter.
9423
09ea332d 9424void
e440a328 9425Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 9426 Statement_inserter* inserter,
0e9a2e72 9427 Type* varargs_type, size_t param_count,
9428 Slice_storage_escape_disp escape_disp)
e440a328 9429{
9430 if (this->varargs_are_lowered_)
09ea332d 9431 return;
e440a328 9432
b13c66cd 9433 Location loc = this->location();
e440a328 9434
c484d925 9435 go_assert(param_count > 0);
411eb89e 9436 go_assert(varargs_type->is_slice_type());
e440a328 9437
9438 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9439 if (arg_count < param_count - 1)
9440 {
9441 // Not enough arguments; will be caught in check_types.
09ea332d 9442 return;
e440a328 9443 }
9444
9445 Expression_list* old_args = this->args_;
9446 Expression_list* new_args = new Expression_list();
9447 bool push_empty_arg = false;
9448 if (old_args == NULL || old_args->empty())
9449 {
c484d925 9450 go_assert(param_count == 1);
e440a328 9451 push_empty_arg = true;
9452 }
9453 else
9454 {
9455 Expression_list::const_iterator pa;
9456 int i = 1;
9457 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9458 {
9459 if (static_cast<size_t>(i) == param_count)
9460 break;
9461 new_args->push_back(*pa);
9462 }
9463
9464 // We have reached the varargs parameter.
9465
9466 bool issued_error = false;
9467 if (pa == old_args->end())
9468 push_empty_arg = true;
9469 else if (pa + 1 == old_args->end() && this->is_varargs_)
9470 new_args->push_back(*pa);
9471 else if (this->is_varargs_)
9472 {
a6645f74 9473 if ((*pa)->type()->is_slice_type())
9474 this->report_error(_("too many arguments"));
9475 else
9476 {
631d5788 9477 go_error_at(this->location(),
9478 _("invalid use of %<...%> with non-slice"));
a6645f74 9479 this->set_is_error();
9480 }
09ea332d 9481 return;
e440a328 9482 }
e440a328 9483 else
9484 {
9485 Type* element_type = varargs_type->array_type()->element_type();
9486 Expression_list* vals = new Expression_list;
9487 for (; pa != old_args->end(); ++pa, ++i)
9488 {
9489 // Check types here so that we get a better message.
9490 Type* patype = (*pa)->type();
b13c66cd 9491 Location paloc = (*pa)->location();
e440a328 9492 if (!this->check_argument_type(i, element_type, patype,
9493 paloc, issued_error))
9494 continue;
9495 vals->push_back(*pa);
9496 }
0e9a2e72 9497 Slice_construction_expression* sce =
e440a328 9498 Expression::make_slice_composite_literal(varargs_type, vals, loc);
0e9a2e72 9499 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9500 sce->set_storage_does_not_escape();
9501 Expression* val = sce;
09ea332d 9502 gogo->lower_expression(function, inserter, &val);
e440a328 9503 new_args->push_back(val);
9504 }
9505 }
9506
9507 if (push_empty_arg)
9508 new_args->push_back(Expression::make_nil(loc));
9509
9510 // We can't return a new call expression here, because this one may
6d4c2432 9511 // be referenced by Call_result expressions. FIXME. We can't
9512 // delete OLD_ARGS because we may have both a Call_expression and a
9513 // Builtin_call_expression which refer to them. FIXME.
e440a328 9514 this->args_ = new_args;
9515 this->varargs_are_lowered_ = true;
e440a328 9516}
9517
105f9a24 9518// Return a call to __builtin_return_address or __builtin_frame_address.
9519
9520Expression*
9521Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9522 int arg)
9523{
9524 if (*pno == NULL)
9525 *pno = Gogo::declare_builtin_rf_address(name);
9526
9527 Location loc = this->location();
9528
9529 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9530 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9531 Expression_list *args = new Expression_list();
9532 args->push_back(a);
9533 Expression* call = Expression::make_call(fn, args, false, loc);
9534
9535 // The builtin functions return void*, but the Go functions return uintptr.
9536 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9537 return Expression::make_cast(uintptr_type, call, loc);
9538}
9539
2c809f8f 9540// Flatten a call with multiple results into a temporary.
9541
9542Expression*
b8e86a51 9543Call_expression::do_flatten(Gogo* gogo, Named_object*,
9544 Statement_inserter* inserter)
2c809f8f 9545{
5bf8be8b 9546 if (this->is_erroneous_call())
9547 {
9548 go_assert(saw_errors());
9549 return Expression::make_error(this->location());
9550 }
b8e86a51 9551
91c0fd76 9552 if (this->is_flattened_)
9553 return this;
9554 this->is_flattened_ = true;
9555
b8e86a51 9556 // Add temporary variables for all arguments that require type
9557 // conversion.
9558 Function_type* fntype = this->get_function_type();
9782d556 9559 if (fntype == NULL)
9560 {
9561 go_assert(saw_errors());
9562 return this;
9563 }
b8e86a51 9564 if (this->args_ != NULL && !this->args_->empty()
9565 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9566 {
9567 bool is_interface_method =
9568 this->fn_->interface_field_reference_expression() != NULL;
9569
9570 Expression_list *args = new Expression_list();
9571 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9572 Expression_list::const_iterator pa = this->args_->begin();
9573 if (!is_interface_method && fntype->is_method())
9574 {
9575 // The receiver argument.
9576 args->push_back(*pa);
9577 ++pa;
9578 }
9579 for (; pa != this->args_->end(); ++pa, ++pp)
9580 {
9581 go_assert(pp != fntype->parameters()->end());
9582 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9583 args->push_back(*pa);
9584 else
9585 {
9586 Location loc = (*pa)->location();
8ba8cc87 9587 Expression* arg = *pa;
9588 if (!arg->is_variable())
9589 {
9590 Temporary_statement *temp =
9591 Statement::make_temporary(NULL, arg, loc);
9592 inserter->insert(temp);
9593 arg = Expression::make_temporary_reference(temp, loc);
9594 }
9595 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9596 loc);
9597 args->push_back(arg);
b8e86a51 9598 }
9599 }
9600 delete this->args_;
9601 this->args_ = args;
9602 }
9603
2c809f8f 9604 size_t rc = this->result_count();
9605 if (rc > 1 && this->call_temp_ == NULL)
9606 {
9607 Struct_field_list* sfl = new Struct_field_list();
9608 Function_type* fntype = this->get_function_type();
9609 const Typed_identifier_list* results = fntype->results();
9610 Location loc = this->location();
9611
9612 int i = 0;
61575e0f 9613 char buf[20];
2c809f8f 9614 for (Typed_identifier_list::const_iterator p = results->begin();
9615 p != results->end();
9616 ++p, ++i)
9617 {
9618 snprintf(buf, sizeof buf, "res%d", i);
9619 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9620 }
9621
9622 Struct_type* st = Type::make_struct_type(sfl, loc);
9623 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9624 inserter->insert(this->call_temp_);
9625 }
9626
9627 return this;
9628}
9629
ceeb4318 9630// Get the function type. This can return NULL in error cases.
e440a328 9631
9632Function_type*
9633Call_expression::get_function_type() const
9634{
9635 return this->fn_->type()->function_type();
9636}
9637
9638// Return the number of values which this call will return.
9639
9640size_t
9641Call_expression::result_count() const
9642{
9643 const Function_type* fntype = this->get_function_type();
9644 if (fntype == NULL)
9645 return 0;
9646 if (fntype->results() == NULL)
9647 return 0;
9648 return fntype->results()->size();
9649}
9650
ceeb4318 9651// Return the temporary which holds a result.
9652
9653Temporary_statement*
9654Call_expression::result(size_t i) const
9655{
cd238b8d 9656 if (this->results_ == NULL || this->results_->size() <= i)
9657 {
9658 go_assert(saw_errors());
9659 return NULL;
9660 }
ceeb4318 9661 return (*this->results_)[i];
9662}
9663
1373401e 9664// Set the number of results expected from a call expression.
9665
9666void
9667Call_expression::set_expected_result_count(size_t count)
9668{
9669 go_assert(this->expected_result_count_ == 0);
9670 this->expected_result_count_ = count;
9671}
9672
e440a328 9673// Return whether this is a call to the predeclared function recover.
9674
9675bool
9676Call_expression::is_recover_call() const
9677{
9678 return this->do_is_recover_call();
9679}
9680
9681// Set the argument to the recover function.
9682
9683void
9684Call_expression::set_recover_arg(Expression* arg)
9685{
9686 this->do_set_recover_arg(arg);
9687}
9688
9689// Virtual functions also implemented by Builtin_call_expression.
9690
9691bool
9692Call_expression::do_is_recover_call() const
9693{
9694 return false;
9695}
9696
9697void
9698Call_expression::do_set_recover_arg(Expression*)
9699{
c3e6f413 9700 go_unreachable();
e440a328 9701}
9702
ceeb4318 9703// We have found an error with this call expression; return true if
9704// we should report it.
9705
9706bool
9707Call_expression::issue_error()
9708{
9709 if (this->issued_error_)
9710 return false;
9711 else
9712 {
9713 this->issued_error_ = true;
9714 return true;
9715 }
9716}
9717
5bf8be8b 9718// Whether or not this call contains errors, either in the call or the
9719// arguments to the call.
9720
9721bool
9722Call_expression::is_erroneous_call()
9723{
9724 if (this->is_error_expression() || this->fn()->is_error_expression())
9725 return true;
9726
9727 if (this->args() == NULL)
9728 return false;
9729 for (Expression_list::iterator pa = this->args()->begin();
9730 pa != this->args()->end();
9731 ++pa)
9732 {
9733 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9734 return true;
9735 }
9736 return false;
9737}
9738
e440a328 9739// Get the type.
9740
9741Type*
9742Call_expression::do_type()
9743{
9744 if (this->type_ != NULL)
9745 return this->type_;
9746
9747 Type* ret;
9748 Function_type* fntype = this->get_function_type();
9749 if (fntype == NULL)
9750 return Type::make_error_type();
9751
9752 const Typed_identifier_list* results = fntype->results();
9753 if (results == NULL)
9754 ret = Type::make_void_type();
9755 else if (results->size() == 1)
9756 ret = results->begin()->type();
9757 else
9758 ret = Type::make_call_multiple_result_type(this);
9759
9760 this->type_ = ret;
9761
9762 return this->type_;
9763}
9764
9765// Determine types for a call expression. We can use the function
9766// parameter types to set the types of the arguments.
9767
9768void
9769Call_expression::do_determine_type(const Type_context*)
9770{
fb94b0ca 9771 if (!this->determining_types())
9772 return;
9773
e440a328 9774 this->fn_->determine_type_no_context();
9775 Function_type* fntype = this->get_function_type();
9776 const Typed_identifier_list* parameters = NULL;
9777 if (fntype != NULL)
9778 parameters = fntype->parameters();
9779 if (this->args_ != NULL)
9780 {
9781 Typed_identifier_list::const_iterator pt;
9782 if (parameters != NULL)
9783 pt = parameters->begin();
09ea332d 9784 bool first = true;
e440a328 9785 for (Expression_list::const_iterator pa = this->args_->begin();
9786 pa != this->args_->end();
9787 ++pa)
9788 {
09ea332d 9789 if (first)
9790 {
9791 first = false;
9792 // If this is a method, the first argument is the
9793 // receiver.
9794 if (fntype != NULL && fntype->is_method())
9795 {
9796 Type* rtype = fntype->receiver()->type();
9797 // The receiver is always passed as a pointer.
9798 if (rtype->points_to() == NULL)
9799 rtype = Type::make_pointer_type(rtype);
9800 Type_context subcontext(rtype, false);
9801 (*pa)->determine_type(&subcontext);
9802 continue;
9803 }
9804 }
9805
e440a328 9806 if (parameters != NULL && pt != parameters->end())
9807 {
9808 Type_context subcontext(pt->type(), false);
9809 (*pa)->determine_type(&subcontext);
9810 ++pt;
9811 }
9812 else
9813 (*pa)->determine_type_no_context();
9814 }
9815 }
9816}
9817
fb94b0ca 9818// Called when determining types for a Call_expression. Return true
9819// if we should go ahead, false if they have already been determined.
9820
9821bool
9822Call_expression::determining_types()
9823{
9824 if (this->types_are_determined_)
9825 return false;
9826 else
9827 {
9828 this->types_are_determined_ = true;
9829 return true;
9830 }
9831}
9832
e440a328 9833// Check types for parameter I.
9834
9835bool
9836Call_expression::check_argument_type(int i, const Type* parameter_type,
9837 const Type* argument_type,
b13c66cd 9838 Location argument_location,
e440a328 9839 bool issued_error)
9840{
9841 std::string reason;
1eae365b 9842 if (!Type::are_assignable(parameter_type, argument_type, &reason))
e440a328 9843 {
9844 if (!issued_error)
9845 {
9846 if (reason.empty())
631d5788 9847 go_error_at(argument_location, "argument %d has incompatible type", i);
e440a328 9848 else
631d5788 9849 go_error_at(argument_location,
9850 "argument %d has incompatible type (%s)",
9851 i, reason.c_str());
e440a328 9852 }
9853 this->set_is_error();
9854 return false;
9855 }
9856 return true;
9857}
9858
9859// Check types.
9860
9861void
9862Call_expression::do_check_types(Gogo*)
9863{
a6645f74 9864 if (this->classification() == EXPRESSION_ERROR)
9865 return;
9866
e440a328 9867 Function_type* fntype = this->get_function_type();
9868 if (fntype == NULL)
9869 {
5c13bd80 9870 if (!this->fn_->type()->is_error())
e440a328 9871 this->report_error(_("expected function"));
9872 return;
9873 }
9874
1373401e 9875 if (this->expected_result_count_ != 0
9876 && this->expected_result_count_ != this->result_count())
9877 {
9878 if (this->issue_error())
9879 this->report_error(_("function result count mismatch"));
9880 this->set_is_error();
9881 return;
9882 }
9883
09ea332d 9884 bool is_method = fntype->is_method();
9885 if (is_method)
e440a328 9886 {
09ea332d 9887 go_assert(this->args_ != NULL && !this->args_->empty());
9888 Type* rtype = fntype->receiver()->type();
9889 Expression* first_arg = this->args_->front();
1eae365b 9890 // We dereference the values since receivers are always passed
9891 // as pointers.
09ea332d 9892 std::string reason;
1eae365b 9893 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9894 &reason))
e440a328 9895 {
09ea332d 9896 if (reason.empty())
9897 this->report_error(_("incompatible type for receiver"));
9898 else
e440a328 9899 {
631d5788 9900 go_error_at(this->location(),
9901 "incompatible type for receiver (%s)",
9902 reason.c_str());
09ea332d 9903 this->set_is_error();
e440a328 9904 }
9905 }
9906 }
9907
9908 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9909 // we don't have to worry about it here unless something is wrong.
9910 if (this->is_varargs_ && !this->varargs_are_lowered_)
9911 {
9912 if (!fntype->is_varargs())
9913 {
631d5788 9914 go_error_at(this->location(),
9915 _("invalid use of %<...%> calling non-variadic function"));
a6645f74 9916 this->set_is_error();
9917 return;
9918 }
9919 }
e440a328 9920
9921 const Typed_identifier_list* parameters = fntype->parameters();
9922 if (this->args_ == NULL)
9923 {
9924 if (parameters != NULL && !parameters->empty())
9925 this->report_error(_("not enough arguments"));
9926 }
9927 else if (parameters == NULL)
09ea332d 9928 {
9929 if (!is_method || this->args_->size() > 1)
9930 this->report_error(_("too many arguments"));
9931 }
1373401e 9932 else if (this->args_->size() == 1
9933 && this->args_->front()->call_expression() != NULL
9934 && this->args_->front()->call_expression()->result_count() > 1)
9935 {
9936 // This is F(G()) when G returns more than one result. If the
9937 // results can be matched to parameters, it would have been
9938 // lowered in do_lower. If we get here we know there is a
9939 // mismatch.
9940 if (this->args_->front()->call_expression()->result_count()
9941 < parameters->size())
9942 this->report_error(_("not enough arguments"));
9943 else
9944 this->report_error(_("too many arguments"));
9945 }
e440a328 9946 else
9947 {
9948 int i = 0;
09ea332d 9949 Expression_list::const_iterator pa = this->args_->begin();
9950 if (is_method)
9951 ++pa;
9952 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9953 pt != parameters->end();
9954 ++pt, ++pa, ++i)
e440a328 9955 {
09ea332d 9956 if (pa == this->args_->end())
e440a328 9957 {
09ea332d 9958 this->report_error(_("not enough arguments"));
e440a328 9959 return;
9960 }
9961 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9962 (*pa)->location(), false);
9963 }
09ea332d 9964 if (pa != this->args_->end())
9965 this->report_error(_("too many arguments"));
e440a328 9966 }
9967}
9968
72666aed 9969Expression*
9970Call_expression::do_copy()
9971{
9972 Call_expression* call =
9973 Expression::make_call(this->fn_->copy(),
9974 (this->args_ == NULL
9975 ? NULL
9976 : this->args_->copy()),
9977 this->is_varargs_, this->location());
9978
9979 if (this->varargs_are_lowered_)
9980 call->set_varargs_are_lowered();
9981 return call;
9982}
9983
e440a328 9984// Return whether we have to use a temporary variable to ensure that
9985// we evaluate this call expression in order. If the call returns no
ceeb4318 9986// results then it will inevitably be executed last.
e440a328 9987
9988bool
9989Call_expression::do_must_eval_in_order() const
9990{
ceeb4318 9991 return this->result_count() > 0;
e440a328 9992}
9993
e440a328 9994// Get the function and the first argument to use when calling an
9995// interface method.
9996
2387f644 9997Expression*
e440a328 9998Call_expression::interface_method_function(
e440a328 9999 Interface_field_reference_expression* interface_method,
2387f644 10000 Expression** first_arg_ptr)
e440a328 10001{
2387f644 10002 *first_arg_ptr = interface_method->get_underlying_object();
10003 return interface_method->get_function();
e440a328 10004}
10005
10006// Build the call expression.
10007
ea664253 10008Bexpression*
10009Call_expression::do_get_backend(Translate_context* context)
e440a328 10010{
2c809f8f 10011 if (this->call_ != NULL)
ea664253 10012 return this->call_;
e440a328 10013
10014 Function_type* fntype = this->get_function_type();
10015 if (fntype == NULL)
ea664253 10016 return context->backend()->error_expression();
e440a328 10017
10018 if (this->fn_->is_error_expression())
ea664253 10019 return context->backend()->error_expression();
e440a328 10020
10021 Gogo* gogo = context->gogo();
b13c66cd 10022 Location location = this->location();
e440a328 10023
10024 Func_expression* func = this->fn_->func_expression();
e440a328 10025 Interface_field_reference_expression* interface_method =
10026 this->fn_->interface_field_reference_expression();
10027 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 10028 const bool is_interface_method = interface_method != NULL;
e440a328 10029
f8bdf81a 10030 bool has_closure_arg;
8381eda7 10031 if (has_closure)
f8bdf81a 10032 has_closure_arg = true;
8381eda7 10033 else if (func != NULL)
f8bdf81a 10034 has_closure_arg = false;
8381eda7 10035 else if (is_interface_method)
f8bdf81a 10036 has_closure_arg = false;
8381eda7 10037 else
f8bdf81a 10038 has_closure_arg = true;
8381eda7 10039
e440a328 10040 int nargs;
2c809f8f 10041 std::vector<Bexpression*> fn_args;
e440a328 10042 if (this->args_ == NULL || this->args_->empty())
10043 {
f8bdf81a 10044 nargs = is_interface_method ? 1 : 0;
2c809f8f 10045 if (nargs > 0)
10046 fn_args.resize(1);
e440a328 10047 }
09ea332d 10048 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10049 {
10050 // Passing a receiver parameter.
10051 go_assert(!is_interface_method
10052 && fntype->is_method()
10053 && this->args_->size() == 1);
f8bdf81a 10054 nargs = 1;
2c809f8f 10055 fn_args.resize(1);
ea664253 10056 fn_args[0] = this->args_->front()->get_backend(context);
09ea332d 10057 }
e440a328 10058 else
10059 {
10060 const Typed_identifier_list* params = fntype->parameters();
e440a328 10061
10062 nargs = this->args_->size();
09ea332d 10063 int i = is_interface_method ? 1 : 0;
e440a328 10064 nargs += i;
2c809f8f 10065 fn_args.resize(nargs);
e440a328 10066
10067 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 10068 Expression_list::const_iterator pe = this->args_->begin();
10069 if (!is_interface_method && fntype->is_method())
10070 {
ea664253 10071 fn_args[i] = (*pe)->get_backend(context);
09ea332d 10072 ++pe;
10073 ++i;
10074 }
10075 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 10076 {
c484d925 10077 go_assert(pp != params->end());
2c809f8f 10078 Expression* arg =
10079 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10080 location);
ea664253 10081 fn_args[i] = arg->get_backend(context);
e440a328 10082 }
c484d925 10083 go_assert(pp == params->end());
f8bdf81a 10084 go_assert(i == nargs);
e440a328 10085 }
10086
2c809f8f 10087 Expression* fn;
10088 Expression* closure = NULL;
8381eda7 10089 if (func != NULL)
10090 {
10091 Named_object* no = func->named_object();
2c809f8f 10092 fn = Expression::make_func_code_reference(no, location);
10093 if (has_closure)
10094 closure = func->closure();
8381eda7 10095 }
09ea332d 10096 else if (!is_interface_method)
8381eda7 10097 {
2c809f8f 10098 closure = this->fn_;
10099
10100 // The backend representation of this function type is a pointer
10101 // to a struct whose first field is the actual function to call.
10102 Type* pfntype =
10103 Type::make_pointer_type(
10104 Type::make_pointer_type(Type::make_void_type()));
10105 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10106 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
10107 }
e440a328 10108 else
cf609de4 10109 {
2387f644 10110 Expression* first_arg;
2c809f8f 10111 fn = this->interface_method_function(interface_method, &first_arg);
ea664253 10112 fn_args[0] = first_arg->get_backend(context);
e440a328 10113 }
10114
1ecc6157 10115 Bexpression* bclosure = NULL;
10116 if (has_closure_arg)
10117 bclosure = closure->get_backend(context);
f8bdf81a 10118 else
1ecc6157 10119 go_assert(closure == NULL);
f8bdf81a 10120
ea664253 10121 Bexpression* bfn = fn->get_backend(context);
80d1e1a8 10122
10123 // When not calling a named function directly, use a type conversion
10124 // in case the type of the function is a recursive type which refers
10125 // to itself. We don't do this for an interface method because 1)
10126 // an interface method never refers to itself, so we always have a
10127 // function type here; 2) we pass an extra first argument to an
10128 // interface method, so fntype is not correct.
10129 if (func == NULL && !is_interface_method)
10130 {
10131 Btype* bft = fntype->get_backend_fntype(gogo);
10132 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10133 }
10134
1ecc6157 10135 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
10136 bclosure, location);
e440a328 10137
2c809f8f 10138 if (this->results_ != NULL)
e440a328 10139 {
2c809f8f 10140 go_assert(this->call_temp_ != NULL);
10141 Expression* call_ref =
10142 Expression::make_temporary_reference(this->call_temp_, location);
ea664253 10143 Bexpression* bcall_ref = call_ref->get_backend(context);
2c809f8f 10144 Bstatement* assn_stmt =
10145 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 10146
2c809f8f 10147 this->call_ = this->set_results(context, bcall_ref);
e440a328 10148
2c809f8f 10149 Bexpression* set_and_call =
10150 gogo->backend()->compound_expression(assn_stmt, this->call_,
10151 location);
ea664253 10152 return set_and_call;
2c809f8f 10153 }
e440a328 10154
2c809f8f 10155 this->call_ = call;
ea664253 10156 return this->call_;
e440a328 10157}
10158
ceeb4318 10159// Set the result variables if this call returns multiple results.
10160
2c809f8f 10161Bexpression*
10162Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 10163{
2c809f8f 10164 Gogo* gogo = context->gogo();
ceeb4318 10165
2c809f8f 10166 Bexpression* results = NULL;
b13c66cd 10167 Location loc = this->location();
2c809f8f 10168
ceeb4318 10169 size_t rc = this->result_count();
2c809f8f 10170 for (size_t i = 0; i < rc; ++i)
ceeb4318 10171 {
ceeb4318 10172 Temporary_statement* temp = this->result(i);
cd238b8d 10173 if (temp == NULL)
10174 {
10175 go_assert(saw_errors());
2c809f8f 10176 return gogo->backend()->error_expression();
cd238b8d 10177 }
ceeb4318 10178 Temporary_reference_expression* ref =
10179 Expression::make_temporary_reference(temp, loc);
10180 ref->set_is_lvalue();
ceeb4318 10181
ea664253 10182 Bexpression* result_ref = ref->get_backend(context);
2c809f8f 10183 Bexpression* call_result =
10184 gogo->backend()->struct_field_expression(call, i, loc);
10185 Bstatement* assn_stmt =
10186 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 10187
2c809f8f 10188 Bexpression* result =
10189 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 10190
2c809f8f 10191 if (results == NULL)
10192 results = result;
10193 else
10194 {
10195 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
10196 results =
10197 gogo->backend()->compound_expression(expr_stmt, results, loc);
10198 }
10199 }
10200 return results;
ceeb4318 10201}
10202
d751bb78 10203// Dump ast representation for a call expressin.
10204
10205void
10206Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10207{
10208 this->fn_->dump_expression(ast_dump_context);
10209 ast_dump_context->ostream() << "(";
10210 if (args_ != NULL)
10211 ast_dump_context->dump_expression_list(this->args_);
10212
10213 ast_dump_context->ostream() << ") ";
10214}
10215
e440a328 10216// Make a call expression.
10217
10218Call_expression*
10219Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 10220 Location location)
e440a328 10221{
10222 return new Call_expression(fn, args, is_varargs, location);
10223}
10224
da244e59 10225// Class Call_result_expression.
e440a328 10226
10227// Traverse a call result.
10228
10229int
10230Call_result_expression::do_traverse(Traverse* traverse)
10231{
10232 if (traverse->remember_expression(this->call_))
10233 {
10234 // We have already traversed the call expression.
10235 return TRAVERSE_CONTINUE;
10236 }
10237 return Expression::traverse(&this->call_, traverse);
10238}
10239
10240// Get the type.
10241
10242Type*
10243Call_result_expression::do_type()
10244{
425dd051 10245 if (this->classification() == EXPRESSION_ERROR)
10246 return Type::make_error_type();
10247
e440a328 10248 // THIS->CALL_ can be replaced with a temporary reference due to
10249 // Call_expression::do_must_eval_in_order when there is an error.
10250 Call_expression* ce = this->call_->call_expression();
10251 if (ce == NULL)
5e85f268 10252 {
10253 this->set_is_error();
10254 return Type::make_error_type();
10255 }
e440a328 10256 Function_type* fntype = ce->get_function_type();
10257 if (fntype == NULL)
5e85f268 10258 {
e37658e2 10259 if (ce->issue_error())
99b3f06f 10260 {
10261 if (!ce->fn()->type()->is_error())
10262 this->report_error(_("expected function"));
10263 }
5e85f268 10264 this->set_is_error();
10265 return Type::make_error_type();
10266 }
e440a328 10267 const Typed_identifier_list* results = fntype->results();
ceeb4318 10268 if (results == NULL || results->size() < 2)
7b8d861f 10269 {
ceeb4318 10270 if (ce->issue_error())
10271 this->report_error(_("number of results does not match "
10272 "number of values"));
7b8d861f 10273 return Type::make_error_type();
10274 }
e440a328 10275 Typed_identifier_list::const_iterator pr = results->begin();
10276 for (unsigned int i = 0; i < this->index_; ++i)
10277 {
10278 if (pr == results->end())
425dd051 10279 break;
e440a328 10280 ++pr;
10281 }
10282 if (pr == results->end())
425dd051 10283 {
ceeb4318 10284 if (ce->issue_error())
10285 this->report_error(_("number of results does not match "
10286 "number of values"));
425dd051 10287 return Type::make_error_type();
10288 }
e440a328 10289 return pr->type();
10290}
10291
425dd051 10292// Check the type. Just make sure that we trigger the warning in
10293// do_type.
e440a328 10294
10295void
10296Call_result_expression::do_check_types(Gogo*)
10297{
425dd051 10298 this->type();
e440a328 10299}
10300
10301// Determine the type. We have nothing to do here, but the 0 result
10302// needs to pass down to the caller.
10303
10304void
10305Call_result_expression::do_determine_type(const Type_context*)
10306{
fb94b0ca 10307 this->call_->determine_type_no_context();
e440a328 10308}
10309
ea664253 10310// Return the backend representation. We just refer to the temporary set by the
10311// call expression. We don't do this at lowering time because it makes it
ceeb4318 10312// hard to evaluate the call at the right time.
e440a328 10313
ea664253 10314Bexpression*
10315Call_result_expression::do_get_backend(Translate_context* context)
e440a328 10316{
ceeb4318 10317 Call_expression* ce = this->call_->call_expression();
cd238b8d 10318 if (ce == NULL)
10319 {
10320 go_assert(this->call_->is_error_expression());
ea664253 10321 return context->backend()->error_expression();
cd238b8d 10322 }
ceeb4318 10323 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 10324 if (ts == NULL)
10325 {
10326 go_assert(saw_errors());
ea664253 10327 return context->backend()->error_expression();
cd238b8d 10328 }
ceeb4318 10329 Expression* ref = Expression::make_temporary_reference(ts, this->location());
ea664253 10330 return ref->get_backend(context);
e440a328 10331}
10332
d751bb78 10333// Dump ast representation for a call result expression.
10334
10335void
10336Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10337 const
10338{
10339 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10340 // (struct) and the fields are referenced instead.
10341 ast_dump_context->ostream() << this->index_ << "@(";
10342 ast_dump_context->dump_expression(this->call_);
10343 ast_dump_context->ostream() << ")";
10344}
10345
e440a328 10346// Make a reference to a single result of a call which returns
10347// multiple results.
10348
10349Expression*
10350Expression::make_call_result(Call_expression* call, unsigned int index)
10351{
10352 return new Call_result_expression(call, index);
10353}
10354
10355// Class Index_expression.
10356
10357// Traversal.
10358
10359int
10360Index_expression::do_traverse(Traverse* traverse)
10361{
10362 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10363 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10364 || (this->end_ != NULL
acf2b673 10365 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10366 || (this->cap_ != NULL
10367 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 10368 return TRAVERSE_EXIT;
10369 return TRAVERSE_CONTINUE;
10370}
10371
10372// Lower an index expression. This converts the generic index
10373// expression into an array index, a string index, or a map index.
10374
10375Expression*
ceeb4318 10376Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 10377{
b13c66cd 10378 Location location = this->location();
e440a328 10379 Expression* left = this->left_;
10380 Expression* start = this->start_;
10381 Expression* end = this->end_;
acf2b673 10382 Expression* cap = this->cap_;
e440a328 10383
10384 Type* type = left->type();
5c13bd80 10385 if (type->is_error())
d9f3743a 10386 {
10387 go_assert(saw_errors());
10388 return Expression::make_error(location);
10389 }
b0cf7ddd 10390 else if (left->is_type_expression())
10391 {
631d5788 10392 go_error_at(location, "attempt to index type expression");
b0cf7ddd 10393 return Expression::make_error(location);
10394 }
e440a328 10395 else if (type->array_type() != NULL)
acf2b673 10396 return Expression::make_array_index(left, start, end, cap, location);
e440a328 10397 else if (type->points_to() != NULL
10398 && type->points_to()->array_type() != NULL
411eb89e 10399 && !type->points_to()->is_slice_type())
e440a328 10400 {
10401 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10402 location);
38092374 10403
10404 // For an ordinary index into the array, the pointer will be
10405 // dereferenced. For a slice it will not--the resulting slice
10406 // will simply reuse the pointer, which is incorrect if that
10407 // pointer is nil.
10408 if (end != NULL || cap != NULL)
10409 deref->issue_nil_check();
10410
acf2b673 10411 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 10412 }
10413 else if (type->is_string_type())
acf2b673 10414 {
10415 if (cap != NULL)
10416 {
631d5788 10417 go_error_at(location, "invalid 3-index slice of string");
acf2b673 10418 return Expression::make_error(location);
10419 }
10420 return Expression::make_string_index(left, start, end, location);
10421 }
e440a328 10422 else if (type->map_type() != NULL)
10423 {
acf2b673 10424 if (end != NULL || cap != NULL)
e440a328 10425 {
631d5788 10426 go_error_at(location, "invalid slice of map");
e440a328 10427 return Expression::make_error(location);
10428 }
0d5530d9 10429 return Expression::make_map_index(left, start, location);
e440a328 10430 }
10431 else
10432 {
631d5788 10433 go_error_at(location,
10434 "attempt to index object which is not array, string, or map");
e440a328 10435 return Expression::make_error(location);
10436 }
10437}
10438
acf2b673 10439// Write an indexed expression
10440// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 10441
10442void
10443Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10444 const Expression* expr,
10445 const Expression* start,
acf2b673 10446 const Expression* end,
10447 const Expression* cap)
d751bb78 10448{
10449 expr->dump_expression(ast_dump_context);
10450 ast_dump_context->ostream() << "[";
10451 start->dump_expression(ast_dump_context);
10452 if (end != NULL)
10453 {
10454 ast_dump_context->ostream() << ":";
10455 end->dump_expression(ast_dump_context);
10456 }
acf2b673 10457 if (cap != NULL)
10458 {
10459 ast_dump_context->ostream() << ":";
10460 cap->dump_expression(ast_dump_context);
10461 }
d751bb78 10462 ast_dump_context->ostream() << "]";
10463}
10464
10465// Dump ast representation for an index expression.
10466
10467void
10468Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10469 const
10470{
10471 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 10472 this->start_, this->end_, this->cap_);
d751bb78 10473}
10474
e440a328 10475// Make an index expression.
10476
10477Expression*
10478Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 10479 Expression* cap, Location location)
e440a328 10480{
acf2b673 10481 return new Index_expression(left, start, end, cap, location);
e440a328 10482}
10483
da244e59 10484// Class Array_index_expression.
e440a328 10485
10486// Array index traversal.
10487
10488int
10489Array_index_expression::do_traverse(Traverse* traverse)
10490{
10491 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10492 return TRAVERSE_EXIT;
10493 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10494 return TRAVERSE_EXIT;
10495 if (this->end_ != NULL)
10496 {
10497 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10498 return TRAVERSE_EXIT;
10499 }
acf2b673 10500 if (this->cap_ != NULL)
10501 {
10502 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10503 return TRAVERSE_EXIT;
10504 }
e440a328 10505 return TRAVERSE_CONTINUE;
10506}
10507
10508// Return the type of an array index.
10509
10510Type*
10511Array_index_expression::do_type()
10512{
10513 if (this->type_ == NULL)
10514 {
10515 Array_type* type = this->array_->type()->array_type();
10516 if (type == NULL)
10517 this->type_ = Type::make_error_type();
10518 else if (this->end_ == NULL)
10519 this->type_ = type->element_type();
411eb89e 10520 else if (type->is_slice_type())
e440a328 10521 {
10522 // A slice of a slice has the same type as the original
10523 // slice.
10524 this->type_ = this->array_->type()->deref();
10525 }
10526 else
10527 {
10528 // A slice of an array is a slice.
10529 this->type_ = Type::make_array_type(type->element_type(), NULL);
10530 }
10531 }
10532 return this->type_;
10533}
10534
10535// Set the type of an array index.
10536
10537void
10538Array_index_expression::do_determine_type(const Type_context*)
10539{
10540 this->array_->determine_type_no_context();
f77aa642 10541
10542 Type_context index_context(Type::lookup_integer_type("int"), false);
10543 if (this->start_->is_constant())
10544 this->start_->determine_type(&index_context);
10545 else
10546 this->start_->determine_type_no_context();
e440a328 10547 if (this->end_ != NULL)
f77aa642 10548 {
10549 if (this->end_->is_constant())
10550 this->end_->determine_type(&index_context);
10551 else
10552 this->end_->determine_type_no_context();
10553 }
acf2b673 10554 if (this->cap_ != NULL)
f77aa642 10555 {
10556 if (this->cap_->is_constant())
10557 this->cap_->determine_type(&index_context);
10558 else
10559 this->cap_->determine_type_no_context();
10560 }
e440a328 10561}
10562
10563// Check types of an array index.
10564
10565void
d0a50ed8 10566Array_index_expression::do_check_types(Gogo* gogo)
e440a328 10567{
f6bc81e6 10568 Numeric_constant nc;
10569 unsigned long v;
10570 if (this->start_->type()->integer_type() == NULL
10571 && !this->start_->type()->is_error()
10572 && (!this->start_->numeric_constant_value(&nc)
10573 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10574 this->report_error(_("index must be integer"));
10575 if (this->end_ != NULL
10576 && this->end_->type()->integer_type() == NULL
99b3f06f 10577 && !this->end_->type()->is_error()
10578 && !this->end_->is_nil_expression()
f6bc81e6 10579 && !this->end_->is_error_expression()
10580 && (!this->end_->numeric_constant_value(&nc)
10581 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10582 this->report_error(_("slice end must be integer"));
acf2b673 10583 if (this->cap_ != NULL
10584 && this->cap_->type()->integer_type() == NULL
10585 && !this->cap_->type()->is_error()
10586 && !this->cap_->is_nil_expression()
10587 && !this->cap_->is_error_expression()
10588 && (!this->cap_->numeric_constant_value(&nc)
10589 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10590 this->report_error(_("slice capacity must be integer"));
e440a328 10591
10592 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10593 if (array_type == NULL)
10594 {
c484d925 10595 go_assert(this->array_->type()->is_error());
f9c68f17 10596 return;
10597 }
e440a328 10598
10599 unsigned int int_bits =
10600 Type::lookup_integer_type("int")->integer_type()->bits();
10601
0c77715b 10602 Numeric_constant lvalnc;
e440a328 10603 mpz_t lval;
e440a328 10604 bool lval_valid = (array_type->length() != NULL
0c77715b 10605 && array_type->length()->numeric_constant_value(&lvalnc)
10606 && lvalnc.to_int(&lval));
10607 Numeric_constant inc;
e440a328 10608 mpz_t ival;
0bd5d859 10609 bool ival_valid = false;
0c77715b 10610 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10611 {
0bd5d859 10612 ival_valid = true;
e440a328 10613 if (mpz_sgn(ival) < 0
10614 || mpz_sizeinbase(ival, 2) >= int_bits
10615 || (lval_valid
10616 && (this->end_ == NULL
10617 ? mpz_cmp(ival, lval) >= 0
10618 : mpz_cmp(ival, lval) > 0)))
10619 {
631d5788 10620 go_error_at(this->start_->location(), "array index out of bounds");
e440a328 10621 this->set_is_error();
10622 }
10623 }
10624 if (this->end_ != NULL && !this->end_->is_nil_expression())
10625 {
0c77715b 10626 Numeric_constant enc;
10627 mpz_t eval;
acf2b673 10628 bool eval_valid = false;
0c77715b 10629 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10630 {
acf2b673 10631 eval_valid = true;
0c77715b 10632 if (mpz_sgn(eval) < 0
10633 || mpz_sizeinbase(eval, 2) >= int_bits
10634 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10635 {
631d5788 10636 go_error_at(this->end_->location(), "array index out of bounds");
e440a328 10637 this->set_is_error();
10638 }
0bd5d859 10639 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10640 this->report_error(_("inverted slice range"));
e440a328 10641 }
acf2b673 10642
10643 Numeric_constant cnc;
10644 mpz_t cval;
10645 if (this->cap_ != NULL
10646 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10647 {
10648 if (mpz_sgn(cval) < 0
10649 || mpz_sizeinbase(cval, 2) >= int_bits
10650 || (lval_valid && mpz_cmp(cval, lval) > 0))
10651 {
631d5788 10652 go_error_at(this->cap_->location(), "array index out of bounds");
acf2b673 10653 this->set_is_error();
10654 }
10655 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10656 {
631d5788 10657 go_error_at(this->cap_->location(),
10658 "invalid slice index: capacity less than start");
acf2b673 10659 this->set_is_error();
10660 }
10661 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10662 {
631d5788 10663 go_error_at(this->cap_->location(),
10664 "invalid slice index: capacity less than length");
acf2b673 10665 this->set_is_error();
10666 }
10667 mpz_clear(cval);
10668 }
10669
10670 if (eval_valid)
10671 mpz_clear(eval);
e440a328 10672 }
0bd5d859 10673 if (ival_valid)
10674 mpz_clear(ival);
0c77715b 10675 if (lval_valid)
10676 mpz_clear(lval);
e440a328 10677
10678 // A slice of an array requires an addressable array. A slice of a
10679 // slice is always possible.
411eb89e 10680 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10681 {
10682 if (!this->array_->is_addressable())
8da39c3b 10683 this->report_error(_("slice of unaddressable value"));
88ec30c8 10684 else
d0a50ed8 10685 {
10686 bool escapes = true;
10687
10688 // When compiling the runtime, a slice operation does not
10689 // cause local variables to escape. When escape analysis
10690 // becomes the default, this should be changed to make it an
10691 // error if we have a slice operation that escapes.
10692 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
10693 escapes = false;
10694
10695 this->array_->address_taken(escapes);
10696 }
88ec30c8 10697 }
e440a328 10698}
10699
2c809f8f 10700// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10701
10702Expression*
10703Array_index_expression::do_flatten(Gogo*, Named_object*,
10704 Statement_inserter* inserter)
10705{
10706 Location loc = this->location();
5bf8be8b 10707 Expression* array = this->array_;
10708 Expression* start = this->start_;
10709 Expression* end = this->end_;
10710 Expression* cap = this->cap_;
10711 if (array->is_error_expression()
10712 || array->type()->is_error_type()
10713 || start->is_error_expression()
10714 || start->type()->is_error_type()
10715 || (end != NULL
10716 && (end->is_error_expression() || end->type()->is_error_type()))
10717 || (cap != NULL
10718 && (cap->is_error_expression() || cap->type()->is_error_type())))
10719 {
10720 go_assert(saw_errors());
10721 return Expression::make_error(loc);
10722 }
10723
2c809f8f 10724 Temporary_statement* temp;
5bf8be8b 10725 if (array->type()->is_slice_type() && !array->is_variable())
35a54f17 10726 {
5bf8be8b 10727 temp = Statement::make_temporary(NULL, array, loc);
35a54f17 10728 inserter->insert(temp);
10729 this->array_ = Expression::make_temporary_reference(temp, loc);
10730 }
5bf8be8b 10731 if (!start->is_variable())
2c809f8f 10732 {
5bf8be8b 10733 temp = Statement::make_temporary(NULL, start, loc);
2c809f8f 10734 inserter->insert(temp);
10735 this->start_ = Expression::make_temporary_reference(temp, loc);
10736 }
5bf8be8b 10737 if (end != NULL
10738 && !end->is_nil_expression()
10739 && !end->is_variable())
2c809f8f 10740 {
5bf8be8b 10741 temp = Statement::make_temporary(NULL, end, loc);
2c809f8f 10742 inserter->insert(temp);
10743 this->end_ = Expression::make_temporary_reference(temp, loc);
10744 }
5bf8be8b 10745 if (cap!= NULL && !cap->is_variable())
2c809f8f 10746 {
5bf8be8b 10747 temp = Statement::make_temporary(NULL, cap, loc);
2c809f8f 10748 inserter->insert(temp);
10749 this->cap_ = Expression::make_temporary_reference(temp, loc);
10750 }
10751
35a54f17 10752 return this;
10753}
10754
e440a328 10755// Return whether this expression is addressable.
10756
10757bool
10758Array_index_expression::do_is_addressable() const
10759{
10760 // A slice expression is not addressable.
10761 if (this->end_ != NULL)
10762 return false;
10763
10764 // An index into a slice is addressable.
411eb89e 10765 if (this->array_->type()->is_slice_type())
e440a328 10766 return true;
10767
10768 // An index into an array is addressable if the array is
10769 // addressable.
10770 return this->array_->is_addressable();
10771}
10772
ea664253 10773// Get the backend representation for an array index.
e440a328 10774
ea664253 10775Bexpression*
10776Array_index_expression::do_get_backend(Translate_context* context)
e440a328 10777{
e440a328 10778 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10779 if (array_type == NULL)
10780 {
c484d925 10781 go_assert(this->array_->type()->is_error());
ea664253 10782 return context->backend()->error_expression();
d8cd8e2d 10783 }
35a54f17 10784 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10785
2c809f8f 10786 Location loc = this->location();
10787 Gogo* gogo = context->gogo();
10788
6dfedc16 10789 Type* int_type = Type::lookup_integer_type("int");
10790 Btype* int_btype = int_type->get_backend(gogo);
e440a328 10791
2c809f8f 10792 // We need to convert the length and capacity to the Go "int" type here
10793 // because the length of a fixed-length array could be of type "uintptr"
10794 // and gimple disallows binary operations between "uintptr" and other
10795 // integer types. FIXME.
10796 Bexpression* length = NULL;
a04bfdfc 10797 if (this->end_ == NULL || this->end_->is_nil_expression())
10798 {
35a54f17 10799 Expression* len = array_type->get_length(gogo, this->array_);
ea664253 10800 length = len->get_backend(context);
2c809f8f 10801 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10802 }
10803
2c809f8f 10804 Bexpression* capacity = NULL;
a04bfdfc 10805 if (this->end_ != NULL)
10806 {
35a54f17 10807 Expression* cap = array_type->get_capacity(gogo, this->array_);
ea664253 10808 capacity = cap->get_backend(context);
2c809f8f 10809 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10810 }
10811
2c809f8f 10812 Bexpression* cap_arg = capacity;
acf2b673 10813 if (this->cap_ != NULL)
10814 {
ea664253 10815 cap_arg = this->cap_->get_backend(context);
2c809f8f 10816 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10817 }
10818
2c809f8f 10819 if (length == NULL)
10820 length = cap_arg;
e440a328 10821
10822 int code = (array_type->length() != NULL
10823 ? (this->end_ == NULL
10824 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10825 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10826 : (this->end_ == NULL
10827 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10828 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
ea664253 10829 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
2c809f8f 10830
6dfedc16 10831 if (this->start_->type()->integer_type() == NULL
10832 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10833 {
10834 go_assert(saw_errors());
10835 return context->backend()->error_expression();
10836 }
d9f3743a 10837
ea664253 10838 Bexpression* bad_index =
d9f3743a 10839 Expression::check_bounds(this->start_, loc)->get_backend(context);
2c809f8f 10840
ea664253 10841 Bexpression* start = this->start_->get_backend(context);
2c809f8f 10842 start = gogo->backend()->convert_expression(int_btype, start, loc);
10843 Bexpression* start_too_large =
10844 gogo->backend()->binary_expression((this->end_ == NULL
10845 ? OPERATOR_GE
10846 : OPERATOR_GT),
10847 start,
10848 (this->end_ == NULL
10849 ? length
10850 : capacity),
10851 loc);
10852 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10853 bad_index, loc);
e440a328 10854
10855 if (this->end_ == NULL)
10856 {
10857 // Simple array indexing. This has to return an l-value, so
2c809f8f 10858 // wrap the index check into START.
10859 start =
10860 gogo->backend()->conditional_expression(int_btype, bad_index,
10861 crash, start, loc);
e440a328 10862
2c809f8f 10863 Bexpression* ret;
e440a328 10864 if (array_type->length() != NULL)
10865 {
ea664253 10866 Bexpression* array = this->array_->get_backend(context);
2c809f8f 10867 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10868 }
10869 else
10870 {
2c809f8f 10871 // Slice.
10872 Expression* valptr =
35a54f17 10873 array_type->get_value_pointer(gogo, this->array_);
ea664253 10874 Bexpression* ptr = valptr->get_backend(context);
2c809f8f 10875 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 10876
10877 Type* ele_type = this->array_->type()->array_type()->element_type();
10878 Btype* ele_btype = ele_type->get_backend(gogo);
10879 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 10880 }
ea664253 10881 return ret;
e440a328 10882 }
10883
10884 // Array slice.
10885
acf2b673 10886 if (this->cap_ != NULL)
10887 {
2c809f8f 10888 Bexpression* bounds_bcheck =
ea664253 10889 Expression::check_bounds(this->cap_, loc)->get_backend(context);
2c809f8f 10890 bad_index =
10891 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10892 bad_index, loc);
10893 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10894
10895 Bexpression* cap_too_small =
10896 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10897 Bexpression* cap_too_large =
10898 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10899 Bexpression* bad_cap =
10900 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10901 cap_too_large, loc);
10902 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10903 bad_index, loc);
10904 }
10905
10906 Bexpression* end;
e440a328 10907 if (this->end_->is_nil_expression())
2c809f8f 10908 end = length;
e440a328 10909 else
10910 {
2c809f8f 10911 Bexpression* bounds_bcheck =
ea664253 10912 Expression::check_bounds(this->end_, loc)->get_backend(context);
e440a328 10913
2c809f8f 10914 bad_index =
10915 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10916 bad_index, loc);
e440a328 10917
ea664253 10918 end = this->end_->get_backend(context);
2c809f8f 10919 end = gogo->backend()->convert_expression(int_btype, end, loc);
10920 Bexpression* end_too_small =
10921 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10922 Bexpression* end_too_large =
10923 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10924 Bexpression* bad_end =
10925 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10926 end_too_large, loc);
10927 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10928 bad_index, loc);
e440a328 10929 }
10930
35a54f17 10931 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
ea664253 10932 Bexpression* val = valptr->get_backend(context);
2c809f8f 10933 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10934
2c809f8f 10935 Bexpression* result_length =
10936 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10937
2c809f8f 10938 Bexpression* result_capacity =
10939 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10940
2c809f8f 10941 Btype* struct_btype = this->type()->get_backend(gogo);
10942 std::vector<Bexpression*> init;
10943 init.push_back(val);
10944 init.push_back(result_length);
10945 init.push_back(result_capacity);
e440a328 10946
2c809f8f 10947 Bexpression* ctor =
10948 gogo->backend()->constructor_expression(struct_btype, init, loc);
ea664253 10949 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10950 crash, ctor, loc);
e440a328 10951}
10952
d751bb78 10953// Dump ast representation for an array index expression.
10954
10955void
10956Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10957 const
10958{
10959 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10960 this->start_, this->end_, this->cap_);
d751bb78 10961}
10962
acf2b673 10963// Make an array index expression. END and CAP may be NULL.
e440a328 10964
10965Expression*
10966Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10967 Expression* end, Expression* cap,
10968 Location location)
e440a328 10969{
acf2b673 10970 return new Array_index_expression(array, start, end, cap, location);
e440a328 10971}
10972
50075d74 10973// Class String_index_expression.
e440a328 10974
10975// String index traversal.
10976
10977int
10978String_index_expression::do_traverse(Traverse* traverse)
10979{
10980 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10981 return TRAVERSE_EXIT;
10982 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10983 return TRAVERSE_EXIT;
10984 if (this->end_ != NULL)
10985 {
10986 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10987 return TRAVERSE_EXIT;
10988 }
10989 return TRAVERSE_CONTINUE;
10990}
10991
2c809f8f 10992Expression*
10993String_index_expression::do_flatten(Gogo*, Named_object*,
10994 Statement_inserter* inserter)
e440a328 10995{
2c809f8f 10996 Location loc = this->location();
5bf8be8b 10997 Expression* string = this->string_;
10998 Expression* start = this->start_;
10999 Expression* end = this->end_;
11000 if (string->is_error_expression()
11001 || string->type()->is_error_type()
11002 || start->is_error_expression()
11003 || start->type()->is_error_type()
11004 || (end != NULL
11005 && (end->is_error_expression() || end->type()->is_error_type())))
11006 {
11007 go_assert(saw_errors());
11008 return Expression::make_error(loc);
11009 }
11010
11011 Temporary_statement* temp;
2c809f8f 11012 if (!this->string_->is_variable())
11013 {
11014 temp = Statement::make_temporary(NULL, this->string_, loc);
11015 inserter->insert(temp);
11016 this->string_ = Expression::make_temporary_reference(temp, loc);
11017 }
11018 if (!this->start_->is_variable())
11019 {
11020 temp = Statement::make_temporary(NULL, this->start_, loc);
11021 inserter->insert(temp);
11022 this->start_ = Expression::make_temporary_reference(temp, loc);
11023 }
11024 if (this->end_ != NULL
11025 && !this->end_->is_nil_expression()
11026 && !this->end_->is_variable())
11027 {
11028 temp = Statement::make_temporary(NULL, this->end_, loc);
11029 inserter->insert(temp);
11030 this->end_ = Expression::make_temporary_reference(temp, loc);
11031 }
11032
11033 return this;
11034}
11035
11036// Return the type of a string index.
11037
11038Type*
11039String_index_expression::do_type()
11040{
11041 if (this->end_ == NULL)
11042 return Type::lookup_integer_type("uint8");
11043 else
11044 return this->string_->type();
11045}
11046
11047// Determine the type of a string index.
11048
11049void
11050String_index_expression::do_determine_type(const Type_context*)
11051{
11052 this->string_->determine_type_no_context();
f77aa642 11053
11054 Type_context index_context(Type::lookup_integer_type("int"), false);
11055 if (this->start_->is_constant())
11056 this->start_->determine_type(&index_context);
11057 else
11058 this->start_->determine_type_no_context();
e440a328 11059 if (this->end_ != NULL)
f77aa642 11060 {
11061 if (this->end_->is_constant())
11062 this->end_->determine_type(&index_context);
11063 else
11064 this->end_->determine_type_no_context();
11065 }
e440a328 11066}
11067
11068// Check types of a string index.
11069
11070void
11071String_index_expression::do_check_types(Gogo*)
11072{
acdc230d 11073 Numeric_constant nc;
11074 unsigned long v;
11075 if (this->start_->type()->integer_type() == NULL
11076 && !this->start_->type()->is_error()
11077 && (!this->start_->numeric_constant_value(&nc)
11078 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11079 this->report_error(_("index must be integer"));
11080 if (this->end_ != NULL
11081 && this->end_->type()->integer_type() == NULL
acdc230d 11082 && !this->end_->type()->is_error()
11083 && !this->end_->is_nil_expression()
11084 && !this->end_->is_error_expression()
11085 && (!this->end_->numeric_constant_value(&nc)
11086 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11087 this->report_error(_("slice end must be integer"));
11088
11089 std::string sval;
11090 bool sval_valid = this->string_->string_constant_value(&sval);
11091
0c77715b 11092 Numeric_constant inc;
e440a328 11093 mpz_t ival;
0bd5d859 11094 bool ival_valid = false;
0c77715b 11095 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 11096 {
0bd5d859 11097 ival_valid = true;
e440a328 11098 if (mpz_sgn(ival) < 0
b10f32fb 11099 || (sval_valid
11100 && (this->end_ == NULL
11101 ? mpz_cmp_ui(ival, sval.length()) >= 0
11102 : mpz_cmp_ui(ival, sval.length()) > 0)))
e440a328 11103 {
631d5788 11104 go_error_at(this->start_->location(), "string index out of bounds");
e440a328 11105 this->set_is_error();
11106 }
11107 }
11108 if (this->end_ != NULL && !this->end_->is_nil_expression())
11109 {
0c77715b 11110 Numeric_constant enc;
11111 mpz_t eval;
11112 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 11113 {
0c77715b 11114 if (mpz_sgn(eval) < 0
11115 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 11116 {
631d5788 11117 go_error_at(this->end_->location(), "string index out of bounds");
e440a328 11118 this->set_is_error();
11119 }
0bd5d859 11120 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11121 this->report_error(_("inverted slice range"));
0c77715b 11122 mpz_clear(eval);
e440a328 11123 }
11124 }
0bd5d859 11125 if (ival_valid)
11126 mpz_clear(ival);
e440a328 11127}
11128
ea664253 11129// Get the backend representation for a string index.
e440a328 11130
ea664253 11131Bexpression*
11132String_index_expression::do_get_backend(Translate_context* context)
e440a328 11133{
b13c66cd 11134 Location loc = this->location();
2c809f8f 11135 Expression* string_arg = this->string_;
11136 if (this->string_->type()->points_to() != NULL)
11137 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 11138
2c809f8f 11139 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 11140
2c809f8f 11141 int code = (this->end_ == NULL
11142 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11143 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 11144
2c809f8f 11145 Gogo* gogo = context->gogo();
ea664253 11146 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
1b1f2abf 11147
11148 Type* int_type = Type::lookup_integer_type("int");
e440a328 11149
2c809f8f 11150 // It is possible that an error occurred earlier because the start index
11151 // cannot be represented as an integer type. In this case, we shouldn't
11152 // try casting the starting index into an integer since
11153 // Type_conversion_expression will fail to get the backend representation.
11154 // FIXME.
11155 if (this->start_->type()->integer_type() == NULL
11156 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11157 {
11158 go_assert(saw_errors());
ea664253 11159 return context->backend()->error_expression();
2c809f8f 11160 }
e440a328 11161
2c809f8f 11162 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 11163
2c809f8f 11164 if (this->end_ == NULL)
11165 {
11166 Expression* length =
11167 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 11168
2c809f8f 11169 Expression* start_too_large =
11170 Expression::make_binary(OPERATOR_GE, start, length, loc);
11171 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11172 bad_index, loc);
11173 Expression* bytes =
11174 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 11175
ea664253 11176 Bexpression* bstart = start->get_backend(context);
11177 Bexpression* ptr = bytes->get_backend(context);
2c809f8f 11178 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 11179 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11180 Bexpression* index =
11181 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 11182
2c809f8f 11183 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
ea664253 11184 Bexpression* index_error = bad_index->get_backend(context);
11185 return gogo->backend()->conditional_expression(byte_btype, index_error,
11186 crash, index, loc);
2c809f8f 11187 }
11188
11189 Expression* end = NULL;
11190 if (this->end_->is_nil_expression())
e67508fa 11191 end = Expression::make_integer_sl(-1, int_type, loc);
e440a328 11192 else
11193 {
2c809f8f 11194 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11195 bad_index =
11196 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11197 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 11198 }
2c809f8f 11199
11200 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11201 string_arg, start, end);
ea664253 11202 Bexpression* bstrslice = strslice->get_backend(context);
2c809f8f 11203
11204 Btype* str_btype = strslice->type()->get_backend(gogo);
ea664253 11205 Bexpression* index_error = bad_index->get_backend(context);
11206 return gogo->backend()->conditional_expression(str_btype, index_error,
11207 crash, bstrslice, loc);
e440a328 11208}
11209
d751bb78 11210// Dump ast representation for a string index expression.
11211
11212void
11213String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11214 const
11215{
acf2b673 11216 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11217 this->start_, this->end_, NULL);
d751bb78 11218}
11219
e440a328 11220// Make a string index expression. END may be NULL.
11221
11222Expression*
11223Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 11224 Expression* end, Location location)
e440a328 11225{
11226 return new String_index_expression(string, start, end, location);
11227}
11228
11229// Class Map_index.
11230
11231// Get the type of the map.
11232
11233Map_type*
11234Map_index_expression::get_map_type() const
11235{
0d5530d9 11236 Map_type* mt = this->map_->type()->map_type();
c7524fae 11237 if (mt == NULL)
c484d925 11238 go_assert(saw_errors());
e440a328 11239 return mt;
11240}
11241
11242// Map index traversal.
11243
11244int
11245Map_index_expression::do_traverse(Traverse* traverse)
11246{
11247 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11248 return TRAVERSE_EXIT;
11249 return Expression::traverse(&this->index_, traverse);
11250}
11251
2c809f8f 11252// We need to pass in a pointer to the key, so flatten the index into a
11253// temporary variable if it isn't already. The value pointer will be
11254// dereferenced and checked for nil, so flatten into a temporary to avoid
11255// recomputation.
11256
11257Expression*
91c0fd76 11258Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
2c809f8f 11259 Statement_inserter* inserter)
11260{
91c0fd76 11261 Location loc = this->location();
2c809f8f 11262 Map_type* mt = this->get_map_type();
5bf8be8b 11263 if (this->index()->is_error_expression()
11264 || this->index()->type()->is_error_type()
11265 || mt->is_error_type())
11266 {
11267 go_assert(saw_errors());
11268 return Expression::make_error(loc);
11269 }
11270
91c0fd76 11271 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11272 {
11273 if (this->index_->type()->interface_type() != NULL
11274 && !this->index_->is_variable())
11275 {
11276 Temporary_statement* temp =
11277 Statement::make_temporary(NULL, this->index_, loc);
11278 inserter->insert(temp);
11279 this->index_ = Expression::make_temporary_reference(temp, loc);
11280 }
11281 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11282 this->index_, loc);
11283 }
2c809f8f 11284
11285 if (!this->index_->is_variable())
11286 {
11287 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
91c0fd76 11288 loc);
2c809f8f 11289 inserter->insert(temp);
91c0fd76 11290 this->index_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11291 }
11292
11293 if (this->value_pointer_ == NULL)
0d5530d9 11294 this->get_value_pointer(gogo);
5bf8be8b 11295 if (this->value_pointer_->is_error_expression()
11296 || this->value_pointer_->type()->is_error_type())
11297 return Expression::make_error(loc);
2c809f8f 11298 if (!this->value_pointer_->is_variable())
11299 {
11300 Temporary_statement* temp =
91c0fd76 11301 Statement::make_temporary(NULL, this->value_pointer_, loc);
2c809f8f 11302 inserter->insert(temp);
91c0fd76 11303 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11304 }
11305
11306 return this;
11307}
11308
e440a328 11309// Return the type of a map index.
11310
11311Type*
11312Map_index_expression::do_type()
11313{
c7524fae 11314 Map_type* mt = this->get_map_type();
11315 if (mt == NULL)
11316 return Type::make_error_type();
0d5530d9 11317 return mt->val_type();
e440a328 11318}
11319
11320// Fix the type of a map index.
11321
11322void
11323Map_index_expression::do_determine_type(const Type_context*)
11324{
11325 this->map_->determine_type_no_context();
c7524fae 11326 Map_type* mt = this->get_map_type();
11327 Type* key_type = mt == NULL ? NULL : mt->key_type();
11328 Type_context subcontext(key_type, false);
e440a328 11329 this->index_->determine_type(&subcontext);
11330}
11331
11332// Check types of a map index.
11333
11334void
11335Map_index_expression::do_check_types(Gogo*)
11336{
11337 std::string reason;
c7524fae 11338 Map_type* mt = this->get_map_type();
11339 if (mt == NULL)
11340 return;
11341 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 11342 {
11343 if (reason.empty())
11344 this->report_error(_("incompatible type for map index"));
11345 else
11346 {
631d5788 11347 go_error_at(this->location(), "incompatible type for map index (%s)",
11348 reason.c_str());
e440a328 11349 this->set_is_error();
11350 }
11351 }
11352}
11353
ea664253 11354// Get the backend representation for a map index.
e440a328 11355
ea664253 11356Bexpression*
11357Map_index_expression::do_get_backend(Translate_context* context)
e440a328 11358{
11359 Map_type* type = this->get_map_type();
c7524fae 11360 if (type == NULL)
2c809f8f 11361 {
11362 go_assert(saw_errors());
ea664253 11363 return context->backend()->error_expression();
2c809f8f 11364 }
e440a328 11365
2c809f8f 11366 go_assert(this->value_pointer_ != NULL
11367 && this->value_pointer_->is_variable());
e440a328 11368
0d5530d9 11369 Expression* val = Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
11370 this->location());
11371 return val->get_backend(context);
e440a328 11372}
11373
0d5530d9 11374// Get an expression for the map index. This returns an expression
11375// that evaluates to a pointer to a value. If the key is not in the
11376// map, the pointer will point to a zero value.
e440a328 11377
2c809f8f 11378Expression*
0d5530d9 11379Map_index_expression::get_value_pointer(Gogo* gogo)
e440a328 11380{
2c809f8f 11381 if (this->value_pointer_ == NULL)
746d2e73 11382 {
2c809f8f 11383 Map_type* type = this->get_map_type();
11384 if (type == NULL)
746d2e73 11385 {
2c809f8f 11386 go_assert(saw_errors());
11387 return Expression::make_error(this->location());
746d2e73 11388 }
e440a328 11389
2c809f8f 11390 Location loc = this->location();
11391 Expression* map_ref = this->map_;
e440a328 11392
0d5530d9 11393 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11394 this->index_,
2c809f8f 11395 loc);
0d5530d9 11396
11397 Expression* zero = type->fat_zero_value(gogo);
11398
11399 Expression* map_index;
11400
11401 if (zero == NULL)
11402 map_index =
11403 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11404 Expression::make_type_descriptor(type, loc),
11405 map_ref, index_ptr);
11406 else
11407 map_index =
11408 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11409 Expression::make_type_descriptor(type, loc),
11410 map_ref, index_ptr, zero);
2c809f8f 11411
11412 Type* val_type = type->val_type();
11413 this->value_pointer_ =
11414 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11415 map_index, this->location());
11416 }
0d5530d9 11417
2c809f8f 11418 return this->value_pointer_;
e440a328 11419}
11420
d751bb78 11421// Dump ast representation for a map index expression
11422
11423void
11424Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11425 const
11426{
acf2b673 11427 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11428 this->index_, NULL, NULL);
d751bb78 11429}
11430
e440a328 11431// Make a map index expression.
11432
11433Map_index_expression*
11434Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 11435 Location location)
e440a328 11436{
11437 return new Map_index_expression(map, index, location);
11438}
11439
11440// Class Field_reference_expression.
11441
149eabc5 11442// Lower a field reference expression. There is nothing to lower, but
11443// this is where we generate the tracking information for fields with
11444// the magic go:"track" tag.
11445
11446Expression*
11447Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11448 Statement_inserter* inserter, int)
11449{
11450 Struct_type* struct_type = this->expr_->type()->struct_type();
11451 if (struct_type == NULL)
11452 {
11453 // Error will be reported elsewhere.
11454 return this;
11455 }
11456 const Struct_field* field = struct_type->field(this->field_index_);
11457 if (field == NULL)
11458 return this;
11459 if (!field->has_tag())
11460 return this;
11461 if (field->tag().find("go:\"track\"") == std::string::npos)
11462 return this;
11463
604e278d 11464 // References from functions generated by the compiler don't count.
c6292d1d 11465 if (function != NULL && function->func_value()->is_type_specific_function())
604e278d 11466 return this;
11467
149eabc5 11468 // We have found a reference to a tracked field. Build a call to
11469 // the runtime function __go_fieldtrack with a string that describes
11470 // the field. FIXME: We should only call this once per referenced
11471 // field per function, not once for each reference to the field.
11472
11473 if (this->called_fieldtrack_)
11474 return this;
11475 this->called_fieldtrack_ = true;
11476
11477 Location loc = this->location();
11478
11479 std::string s = "fieldtrack \"";
11480 Named_type* nt = this->expr_->type()->named_type();
11481 if (nt == NULL || nt->named_object()->package() == NULL)
11482 s.append(gogo->pkgpath());
11483 else
11484 s.append(nt->named_object()->package()->pkgpath());
11485 s.push_back('.');
11486 if (nt != NULL)
5c29ad36 11487 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11488 s.push_back('.');
11489 s.append(field->field_name());
11490 s.push_back('"');
11491
11492 // We can't use a string here, because internally a string holds a
11493 // pointer to the actual bytes; when the linker garbage collects the
11494 // string, it won't garbage collect the bytes. So we use a
11495 // [...]byte.
11496
e67508fa 11497 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
149eabc5 11498
11499 Type* byte_type = gogo->lookup_global("byte")->type_value();
11500 Type* array_type = Type::make_array_type(byte_type, length_expr);
11501
11502 Expression_list* bytes = new Expression_list();
11503 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11504 {
e67508fa 11505 unsigned char c = static_cast<unsigned char>(*p);
11506 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
149eabc5 11507 }
11508
11509 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11510 bytes, false, loc);
149eabc5 11511
11512 Variable* var = new Variable(array_type, e, true, false, false, loc);
11513
11514 static int count;
11515 char buf[50];
11516 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11517 ++count;
11518
11519 Named_object* no = gogo->add_variable(buf, var);
11520 e = Expression::make_var_reference(no, loc);
11521 e = Expression::make_unary(OPERATOR_AND, e, loc);
11522
11523 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
604e278d 11524 gogo->lower_expression(function, inserter, &call);
149eabc5 11525 inserter->insert(Statement::make_statement(call, false));
11526
11527 // Put this function, and the global variable we just created, into
11528 // unique sections. This will permit the linker to garbage collect
11529 // them if they are not referenced. The effect is that the only
11530 // strings, indicating field references, that will wind up in the
11531 // executable will be those for functions that are actually needed.
66a6be58 11532 if (function != NULL)
11533 function->func_value()->set_in_unique_section();
149eabc5 11534 var->set_in_unique_section();
11535
11536 return this;
11537}
11538
e440a328 11539// Return the type of a field reference.
11540
11541Type*
11542Field_reference_expression::do_type()
11543{
b0e628fb 11544 Type* type = this->expr_->type();
5c13bd80 11545 if (type->is_error())
b0e628fb 11546 return type;
11547 Struct_type* struct_type = type->struct_type();
c484d925 11548 go_assert(struct_type != NULL);
e440a328 11549 return struct_type->field(this->field_index_)->type();
11550}
11551
11552// Check the types for a field reference.
11553
11554void
11555Field_reference_expression::do_check_types(Gogo*)
11556{
b0e628fb 11557 Type* type = this->expr_->type();
5c13bd80 11558 if (type->is_error())
b0e628fb 11559 return;
11560 Struct_type* struct_type = type->struct_type();
c484d925 11561 go_assert(struct_type != NULL);
11562 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11563}
11564
ea664253 11565// Get the backend representation for a field reference.
e440a328 11566
ea664253 11567Bexpression*
11568Field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11569{
ea664253 11570 Bexpression* bstruct = this->expr_->get_backend(context);
11571 return context->gogo()->backend()->struct_field_expression(bstruct,
11572 this->field_index_,
11573 this->location());
e440a328 11574}
11575
d751bb78 11576// Dump ast representation for a field reference expression.
11577
11578void
11579Field_reference_expression::do_dump_expression(
11580 Ast_dump_context* ast_dump_context) const
11581{
11582 this->expr_->dump_expression(ast_dump_context);
11583 ast_dump_context->ostream() << "." << this->field_index_;
11584}
11585
e440a328 11586// Make a reference to a qualified identifier in an expression.
11587
11588Field_reference_expression*
11589Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11590 Location location)
e440a328 11591{
11592 return new Field_reference_expression(expr, field_index, location);
11593}
11594
11595// Class Interface_field_reference_expression.
11596
2387f644 11597// Return an expression for the pointer to the function to call.
e440a328 11598
2387f644 11599Expression*
11600Interface_field_reference_expression::get_function()
e440a328 11601{
2387f644 11602 Expression* ref = this->expr_;
11603 Location loc = this->location();
11604 if (ref->type()->points_to() != NULL)
11605 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11606
2387f644 11607 Expression* mtable =
11608 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11609 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11610
11611 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11612 unsigned int index;
11613 const Struct_field* field = mtable_type->find_local_field(name, &index);
11614 go_assert(field != NULL);
11615 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11616 return Expression::make_field_reference(mtable, index, loc);
e440a328 11617}
11618
2387f644 11619// Return an expression for the first argument to pass to the interface
e440a328 11620// function.
11621
2387f644 11622Expression*
11623Interface_field_reference_expression::get_underlying_object()
e440a328 11624{
2387f644 11625 Expression* expr = this->expr_;
11626 if (expr->type()->points_to() != NULL)
11627 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11628 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11629 this->location());
e440a328 11630}
11631
11632// Traversal.
11633
11634int
11635Interface_field_reference_expression::do_traverse(Traverse* traverse)
11636{
11637 return Expression::traverse(&this->expr_, traverse);
11638}
11639
0afbb937 11640// Lower the expression. If this expression is not called, we need to
11641// evaluate the expression twice when converting to the backend
11642// interface. So introduce a temporary variable if necessary.
11643
11644Expression*
9782d556 11645Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11646 Statement_inserter* inserter)
0afbb937 11647{
5bf8be8b 11648 if (this->expr_->is_error_expression()
11649 || this->expr_->type()->is_error_type())
11650 {
11651 go_assert(saw_errors());
11652 return Expression::make_error(this->location());
11653 }
11654
2387f644 11655 if (!this->expr_->is_variable())
0afbb937 11656 {
11657 Temporary_statement* temp =
11658 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11659 inserter->insert(temp);
11660 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11661 this->location());
11662 }
11663 return this;
11664}
11665
e440a328 11666// Return the type of an interface field reference.
11667
11668Type*
11669Interface_field_reference_expression::do_type()
11670{
11671 Type* expr_type = this->expr_->type();
11672
11673 Type* points_to = expr_type->points_to();
11674 if (points_to != NULL)
11675 expr_type = points_to;
11676
11677 Interface_type* interface_type = expr_type->interface_type();
11678 if (interface_type == NULL)
11679 return Type::make_error_type();
11680
11681 const Typed_identifier* method = interface_type->find_method(this->name_);
11682 if (method == NULL)
11683 return Type::make_error_type();
11684
11685 return method->type();
11686}
11687
11688// Determine types.
11689
11690void
11691Interface_field_reference_expression::do_determine_type(const Type_context*)
11692{
11693 this->expr_->determine_type_no_context();
11694}
11695
11696// Check the types for an interface field reference.
11697
11698void
11699Interface_field_reference_expression::do_check_types(Gogo*)
11700{
11701 Type* type = this->expr_->type();
11702
11703 Type* points_to = type->points_to();
11704 if (points_to != NULL)
11705 type = points_to;
11706
11707 Interface_type* interface_type = type->interface_type();
11708 if (interface_type == NULL)
5c491127 11709 {
11710 if (!type->is_error_type())
11711 this->report_error(_("expected interface or pointer to interface"));
11712 }
e440a328 11713 else
11714 {
11715 const Typed_identifier* method =
11716 interface_type->find_method(this->name_);
11717 if (method == NULL)
11718 {
631d5788 11719 go_error_at(this->location(), "method %qs not in interface",
11720 Gogo::message_name(this->name_).c_str());
e440a328 11721 this->set_is_error();
11722 }
11723 }
11724}
11725
0afbb937 11726// If an interface field reference is not simply called, then it is
11727// represented as a closure. The closure will hold a single variable,
11728// the value of the interface on which the method should be called.
11729// The function will be a simple thunk that pulls the value from the
11730// closure and calls the method with the remaining arguments.
11731
11732// Because method values are not common, we don't build all thunks for
11733// all possible interface methods, but instead only build them as we
11734// need them. In particular, we even build them on demand for
11735// interface methods defined in other packages.
11736
11737Interface_field_reference_expression::Interface_method_thunks
11738 Interface_field_reference_expression::interface_method_thunks;
11739
11740// Find or create the thunk to call method NAME on TYPE.
11741
11742Named_object*
11743Interface_field_reference_expression::create_thunk(Gogo* gogo,
11744 Interface_type* type,
11745 const std::string& name)
11746{
11747 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11748 std::pair<Interface_method_thunks::iterator, bool> ins =
11749 Interface_field_reference_expression::interface_method_thunks.insert(val);
11750 if (ins.second)
11751 {
11752 // This is the first time we have seen this interface.
11753 ins.first->second = new Method_thunks();
11754 }
11755
11756 for (Method_thunks::const_iterator p = ins.first->second->begin();
11757 p != ins.first->second->end();
11758 p++)
11759 if (p->first == name)
11760 return p->second;
11761
11762 Location loc = type->location();
11763
11764 const Typed_identifier* method_id = type->find_method(name);
11765 if (method_id == NULL)
11766 return Named_object::make_erroneous_name(Gogo::thunk_name());
11767
11768 Function_type* orig_fntype = method_id->type()->function_type();
11769 if (orig_fntype == NULL)
11770 return Named_object::make_erroneous_name(Gogo::thunk_name());
11771
11772 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11773 // The type here is wrong--it should be the C function type. But it
11774 // doesn't really matter.
0afbb937 11775 Type* vt = Type::make_pointer_type(Type::make_void_type());
11776 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11777 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11778 Type* closure_type = Type::make_struct_type(sfl, loc);
11779 closure_type = Type::make_pointer_type(closure_type);
11780
f8bdf81a 11781 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11782
da244e59 11783 std::string thunk_name = Gogo::thunk_name();
11784 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 11785 false, loc);
11786
f8bdf81a 11787 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11788 cvar->set_is_used();
1ecc6157 11789 cvar->set_is_closure();
da244e59 11790 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11791 NULL, cvar);
f8bdf81a 11792 new_no->func_value()->set_closure_var(cp);
0afbb937 11793
f8bdf81a 11794 gogo->start_block(loc);
0afbb937 11795
11796 // Field 0 of the closure is the function code pointer, field 1 is
11797 // the value on which to invoke the method.
11798 Expression* arg = Expression::make_var_reference(cp, loc);
11799 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11800 arg = Expression::make_field_reference(arg, 1, loc);
11801
11802 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11803 loc);
11804
11805 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11806 Expression_list* args;
11807 if (orig_params == NULL || orig_params->empty())
11808 args = NULL;
11809 else
11810 {
11811 const Typed_identifier_list* new_params = new_fntype->parameters();
11812 args = new Expression_list();
11813 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11814 p != new_params->end();
0afbb937 11815 ++p)
11816 {
11817 Named_object* p_no = gogo->lookup(p->name(), NULL);
11818 go_assert(p_no != NULL
11819 && p_no->is_variable()
11820 && p_no->var_value()->is_parameter());
11821 args->push_back(Expression::make_var_reference(p_no, loc));
11822 }
11823 }
11824
11825 Call_expression* call = Expression::make_call(ifre, args,
11826 orig_fntype->is_varargs(),
11827 loc);
11828 call->set_varargs_are_lowered();
11829
11830 Statement* s = Statement::make_return_from_call(call, loc);
11831 gogo->add_statement(s);
11832 Block* b = gogo->finish_block(loc);
11833 gogo->add_block(b, loc);
11834 gogo->lower_block(new_no, b);
a32698ee 11835 gogo->flatten_block(new_no, b);
0afbb937 11836 gogo->finish_function(loc);
11837
11838 ins.first->second->push_back(std::make_pair(name, new_no));
11839 return new_no;
11840}
11841
ea664253 11842// Get the backend representation for a method value.
e440a328 11843
ea664253 11844Bexpression*
11845Interface_field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11846{
0afbb937 11847 Interface_type* type = this->expr_->type()->interface_type();
11848 if (type == NULL)
11849 {
11850 go_assert(saw_errors());
ea664253 11851 return context->backend()->error_expression();
0afbb937 11852 }
11853
11854 Named_object* thunk =
11855 Interface_field_reference_expression::create_thunk(context->gogo(),
11856 type, this->name_);
11857 if (thunk->is_erroneous())
11858 {
11859 go_assert(saw_errors());
ea664253 11860 return context->backend()->error_expression();
0afbb937 11861 }
11862
11863 // FIXME: We should lower this earlier, but we can't it lower it in
11864 // the lowering pass because at that point we don't know whether we
11865 // need to create the thunk or not. If the expression is called, we
11866 // don't need the thunk.
11867
11868 Location loc = this->location();
11869
11870 Struct_field_list* fields = new Struct_field_list();
11871 fields->push_back(Struct_field(Typed_identifier("fn.0",
11872 thunk->func_value()->type(),
11873 loc)));
11874 fields->push_back(Struct_field(Typed_identifier("val.1",
11875 this->expr_->type(),
11876 loc)));
11877 Struct_type* st = Type::make_struct_type(fields, loc);
11878
11879 Expression_list* vals = new Expression_list();
11880 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11881 vals->push_back(this->expr_);
11882
11883 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
ea664253 11884 Bexpression* bclosure =
11885 Expression::make_heap_expression(expr, loc)->get_backend(context);
0afbb937 11886
2387f644 11887 Expression* nil_check =
11888 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11889 Expression::make_nil(loc), loc);
ea664253 11890 Bexpression* bnil_check = nil_check->get_backend(context);
0afbb937 11891
2387f644 11892 Gogo* gogo = context->gogo();
ea664253 11893 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11894 loc)->get_backend(context);
2387f644 11895
11896 Bexpression* bcond =
a32698ee 11897 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11898 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
ea664253 11899 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
e440a328 11900}
11901
d751bb78 11902// Dump ast representation for an interface field reference.
11903
11904void
11905Interface_field_reference_expression::do_dump_expression(
11906 Ast_dump_context* ast_dump_context) const
11907{
11908 this->expr_->dump_expression(ast_dump_context);
11909 ast_dump_context->ostream() << "." << this->name_;
11910}
11911
e440a328 11912// Make a reference to a field in an interface.
11913
11914Expression*
11915Expression::make_interface_field_reference(Expression* expr,
11916 const std::string& field,
b13c66cd 11917 Location location)
e440a328 11918{
11919 return new Interface_field_reference_expression(expr, field, location);
11920}
11921
11922// A general selector. This is a Parser_expression for LEFT.NAME. It
11923// is lowered after we know the type of the left hand side.
11924
11925class Selector_expression : public Parser_expression
11926{
11927 public:
11928 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11929 Location location)
e440a328 11930 : Parser_expression(EXPRESSION_SELECTOR, location),
11931 left_(left), name_(name)
11932 { }
11933
11934 protected:
11935 int
11936 do_traverse(Traverse* traverse)
11937 { return Expression::traverse(&this->left_, traverse); }
11938
11939 Expression*
ceeb4318 11940 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11941
11942 Expression*
11943 do_copy()
11944 {
11945 return new Selector_expression(this->left_->copy(), this->name_,
11946 this->location());
11947 }
11948
d751bb78 11949 void
11950 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11951
e440a328 11952 private:
11953 Expression*
11954 lower_method_expression(Gogo*);
11955
11956 // The expression on the left hand side.
11957 Expression* left_;
11958 // The name on the right hand side.
11959 std::string name_;
11960};
11961
11962// Lower a selector expression once we know the real type of the left
11963// hand side.
11964
11965Expression*
ceeb4318 11966Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11967 int)
e440a328 11968{
11969 Expression* left = this->left_;
11970 if (left->is_type_expression())
11971 return this->lower_method_expression(gogo);
11972 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11973 this->location());
11974}
11975
11976// Lower a method expression T.M or (*T).M. We turn this into a
11977// function literal.
11978
11979Expression*
11980Selector_expression::lower_method_expression(Gogo* gogo)
11981{
b13c66cd 11982 Location location = this->location();
868b439e 11983 Type* left_type = this->left_->type();
11984 Type* type = left_type;
e440a328 11985 const std::string& name(this->name_);
11986
11987 bool is_pointer;
11988 if (type->points_to() == NULL)
11989 is_pointer = false;
11990 else
11991 {
11992 is_pointer = true;
11993 type = type->points_to();
11994 }
11995 Named_type* nt = type->named_type();
11996 if (nt == NULL)
11997 {
631d5788 11998 go_error_at(location,
11999 ("method expression requires named type or "
12000 "pointer to named type"));
e440a328 12001 return Expression::make_error(location);
12002 }
12003
12004 bool is_ambiguous;
12005 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 12006 const Typed_identifier* imethod = NULL;
dcc8506b 12007 if (method == NULL && !is_pointer)
ab1468c3 12008 {
12009 Interface_type* it = nt->interface_type();
12010 if (it != NULL)
12011 imethod = it->find_method(name);
12012 }
12013
868b439e 12014 if ((method == NULL && imethod == NULL)
12015 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
e440a328 12016 {
12017 if (!is_ambiguous)
631d5788 12018 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12019 is_pointer ? "*" : "",
12020 nt->message_name().c_str(),
12021 Gogo::message_name(name).c_str());
e440a328 12022 else
631d5788 12023 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12024 Gogo::message_name(name).c_str(),
12025 is_pointer ? "*" : "",
12026 nt->message_name().c_str());
e440a328 12027 return Expression::make_error(location);
12028 }
12029
ab1468c3 12030 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 12031 {
631d5788 12032 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12033 nt->message_name().c_str(),
12034 Gogo::message_name(name).c_str());
e440a328 12035 return Expression::make_error(location);
12036 }
12037
12038 // Build a new function type in which the receiver becomes the first
12039 // argument.
ab1468c3 12040 Function_type* method_type;
12041 if (method != NULL)
12042 {
12043 method_type = method->type();
c484d925 12044 go_assert(method_type->is_method());
ab1468c3 12045 }
12046 else
12047 {
12048 method_type = imethod->type()->function_type();
c484d925 12049 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 12050 }
e440a328 12051
12052 const char* const receiver_name = "$this";
12053 Typed_identifier_list* parameters = new Typed_identifier_list();
12054 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12055 location));
12056
12057 const Typed_identifier_list* method_parameters = method_type->parameters();
12058 if (method_parameters != NULL)
12059 {
f470da59 12060 int i = 0;
e440a328 12061 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12062 p != method_parameters->end();
f470da59 12063 ++p, ++i)
12064 {
68883531 12065 if (!p->name().empty())
f470da59 12066 parameters->push_back(*p);
12067 else
12068 {
12069 char buf[20];
12070 snprintf(buf, sizeof buf, "$param%d", i);
12071 parameters->push_back(Typed_identifier(buf, p->type(),
12072 p->location()));
12073 }
12074 }
e440a328 12075 }
12076
12077 const Typed_identifier_list* method_results = method_type->results();
12078 Typed_identifier_list* results;
12079 if (method_results == NULL)
12080 results = NULL;
12081 else
12082 {
12083 results = new Typed_identifier_list();
12084 for (Typed_identifier_list::const_iterator p = method_results->begin();
12085 p != method_results->end();
12086 ++p)
12087 results->push_back(*p);
12088 }
12089
12090 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12091 location);
12092 if (method_type->is_varargs())
12093 fntype->set_is_varargs();
12094
12095 // We generate methods which always takes a pointer to the receiver
12096 // as their first argument. If this is for a pointer type, we can
12097 // simply reuse the existing function. We use an internal hack to
12098 // get the right type.
8381eda7 12099 // FIXME: This optimization is disabled because it doesn't yet work
12100 // with function descriptors when the method expression is not
12101 // directly called.
12102 if (method != NULL && is_pointer && false)
e440a328 12103 {
12104 Named_object* mno = (method->needs_stub_method()
12105 ? method->stub_object()
12106 : method->named_object());
12107 Expression* f = Expression::make_func_reference(mno, NULL, location);
12108 f = Expression::make_cast(fntype, f, location);
12109 Type_conversion_expression* tce =
12110 static_cast<Type_conversion_expression*>(f);
12111 tce->set_may_convert_function_types();
12112 return f;
12113 }
12114
12115 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12116 location);
12117
12118 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 12119 go_assert(vno != NULL);
e440a328 12120 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 12121 Expression* bm;
12122 if (method != NULL)
12123 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12124 else
12125 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 12126
12127 // Even though we found the method above, if it has an error type we
12128 // may see an error here.
12129 if (bm->is_error_expression())
463fe805 12130 {
12131 gogo->finish_function(location);
12132 return bm;
12133 }
e440a328 12134
12135 Expression_list* args;
f470da59 12136 if (parameters->size() <= 1)
e440a328 12137 args = NULL;
12138 else
12139 {
12140 args = new Expression_list();
f470da59 12141 Typed_identifier_list::const_iterator p = parameters->begin();
12142 ++p;
12143 for (; p != parameters->end(); ++p)
e440a328 12144 {
12145 vno = gogo->lookup(p->name(), NULL);
c484d925 12146 go_assert(vno != NULL);
e440a328 12147 args->push_back(Expression::make_var_reference(vno, location));
12148 }
12149 }
12150
ceeb4318 12151 gogo->start_block(location);
12152
e440a328 12153 Call_expression* call = Expression::make_call(bm, args,
12154 method_type->is_varargs(),
12155 location);
12156
0afbb937 12157 Statement* s = Statement::make_return_from_call(call, location);
e440a328 12158 gogo->add_statement(s);
12159
ceeb4318 12160 Block* b = gogo->finish_block(location);
12161
12162 gogo->add_block(b, location);
12163
12164 // Lower the call in case there are multiple results.
12165 gogo->lower_block(no, b);
a32698ee 12166 gogo->flatten_block(no, b);
ceeb4318 12167
e440a328 12168 gogo->finish_function(location);
12169
12170 return Expression::make_func_reference(no, NULL, location);
12171}
12172
d751bb78 12173// Dump the ast for a selector expression.
12174
12175void
12176Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12177 const
12178{
12179 ast_dump_context->dump_expression(this->left_);
12180 ast_dump_context->ostream() << ".";
12181 ast_dump_context->ostream() << this->name_;
12182}
12183
e440a328 12184// Make a selector expression.
12185
12186Expression*
12187Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 12188 Location location)
e440a328 12189{
12190 return new Selector_expression(left, name, location);
12191}
12192
da244e59 12193// Class Allocation_expression.
e440a328 12194
da244e59 12195int
12196Allocation_expression::do_traverse(Traverse* traverse)
e440a328 12197{
da244e59 12198 return Type::traverse(this->type_, traverse);
12199}
e440a328 12200
da244e59 12201Type*
12202Allocation_expression::do_type()
12203{
12204 return Type::make_pointer_type(this->type_);
12205}
e440a328 12206
da244e59 12207// Make a copy of an allocation expression.
e440a328 12208
da244e59 12209Expression*
12210Allocation_expression::do_copy()
12211{
12212 Allocation_expression* alloc =
12213 new Allocation_expression(this->type_, this->location());
12214 if (this->allocate_on_stack_)
12215 alloc->set_allocate_on_stack();
12216 return alloc;
12217}
e440a328 12218
ea664253 12219// Return the backend representation for an allocation expression.
e440a328 12220
ea664253 12221Bexpression*
12222Allocation_expression::do_get_backend(Translate_context* context)
e440a328 12223{
2c809f8f 12224 Gogo* gogo = context->gogo();
12225 Location loc = this->location();
da244e59 12226
45ff893b 12227 Node* n = Node::make_node(this);
12228 if (this->allocate_on_stack_
12229 || (n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
da244e59 12230 {
2a305b85 12231 int64_t size;
12232 bool ok = this->type_->backend_type_size(gogo, &size);
12233 if (!ok)
12234 {
12235 go_assert(saw_errors());
12236 return gogo->backend()->error_expression();
12237 }
d5d1c295 12238 return gogo->backend()->stack_allocation_expression(size, loc);
da244e59 12239 }
12240
2a305b85 12241 Btype* btype = this->type_->get_backend(gogo);
12242 Bexpression* space =
ea664253 12243 gogo->allocate_memory(this->type_, loc)->get_backend(context);
d5d1c295 12244 Btype* pbtype = gogo->backend()->pointer_type(btype);
ea664253 12245 return gogo->backend()->convert_expression(pbtype, space, loc);
e440a328 12246}
12247
d751bb78 12248// Dump ast representation for an allocation expression.
12249
12250void
12251Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12252 const
12253{
12254 ast_dump_context->ostream() << "new(";
12255 ast_dump_context->dump_type(this->type_);
12256 ast_dump_context->ostream() << ")";
12257}
12258
e440a328 12259// Make an allocation expression.
12260
12261Expression*
b13c66cd 12262Expression::make_allocation(Type* type, Location location)
e440a328 12263{
12264 return new Allocation_expression(type, location);
12265}
12266
e32de7ba 12267// Class Ordered_value_list.
e440a328 12268
12269int
e32de7ba 12270Ordered_value_list::traverse_vals(Traverse* traverse)
e440a328 12271{
0c4f5a19 12272 if (this->vals_ != NULL)
12273 {
12274 if (this->traverse_order_ == NULL)
12275 {
12276 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12277 return TRAVERSE_EXIT;
12278 }
12279 else
12280 {
e32de7ba 12281 for (std::vector<unsigned long>::const_iterator p =
12282 this->traverse_order_->begin();
0c4f5a19 12283 p != this->traverse_order_->end();
12284 ++p)
12285 {
12286 if (Expression::traverse(&this->vals_->at(*p), traverse)
12287 == TRAVERSE_EXIT)
12288 return TRAVERSE_EXIT;
12289 }
12290 }
12291 }
e32de7ba 12292 return TRAVERSE_CONTINUE;
12293}
12294
12295// Class Struct_construction_expression.
12296
12297// Traversal.
12298
12299int
12300Struct_construction_expression::do_traverse(Traverse* traverse)
12301{
12302 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12303 return TRAVERSE_EXIT;
e440a328 12304 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12305 return TRAVERSE_EXIT;
12306 return TRAVERSE_CONTINUE;
12307}
12308
12309// Return whether this is a constant initializer.
12310
12311bool
12312Struct_construction_expression::is_constant_struct() const
12313{
e32de7ba 12314 if (this->vals() == NULL)
e440a328 12315 return true;
e32de7ba 12316 for (Expression_list::const_iterator pv = this->vals()->begin();
12317 pv != this->vals()->end();
e440a328 12318 ++pv)
12319 {
12320 if (*pv != NULL
12321 && !(*pv)->is_constant()
12322 && (!(*pv)->is_composite_literal()
12323 || (*pv)->is_nonconstant_composite_literal()))
12324 return false;
12325 }
12326
12327 const Struct_field_list* fields = this->type_->struct_type()->fields();
12328 for (Struct_field_list::const_iterator pf = fields->begin();
12329 pf != fields->end();
12330 ++pf)
12331 {
12332 // There are no constant constructors for interfaces.
12333 if (pf->type()->interface_type() != NULL)
12334 return false;
12335 }
12336
12337 return true;
12338}
12339
3ae06f68 12340// Return whether this struct can be used as a constant initializer.
f9ca30f9 12341
12342bool
3ae06f68 12343Struct_construction_expression::do_is_static_initializer() const
f9ca30f9 12344{
e32de7ba 12345 if (this->vals() == NULL)
f9ca30f9 12346 return true;
e32de7ba 12347 for (Expression_list::const_iterator pv = this->vals()->begin();
12348 pv != this->vals()->end();
f9ca30f9 12349 ++pv)
12350 {
3ae06f68 12351 if (*pv != NULL && !(*pv)->is_static_initializer())
f9ca30f9 12352 return false;
12353 }
12354 return true;
12355}
12356
e440a328 12357// Final type determination.
12358
12359void
12360Struct_construction_expression::do_determine_type(const Type_context*)
12361{
e32de7ba 12362 if (this->vals() == NULL)
e440a328 12363 return;
12364 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12365 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12366 for (Struct_field_list::const_iterator pf = fields->begin();
12367 pf != fields->end();
12368 ++pf, ++pv)
12369 {
e32de7ba 12370 if (pv == this->vals()->end())
e440a328 12371 return;
12372 if (*pv != NULL)
12373 {
12374 Type_context subcontext(pf->type(), false);
12375 (*pv)->determine_type(&subcontext);
12376 }
12377 }
a6cb4c0e 12378 // Extra values are an error we will report elsewhere; we still want
12379 // to determine the type to avoid knockon errors.
e32de7ba 12380 for (; pv != this->vals()->end(); ++pv)
a6cb4c0e 12381 (*pv)->determine_type_no_context();
e440a328 12382}
12383
12384// Check types.
12385
12386void
12387Struct_construction_expression::do_check_types(Gogo*)
12388{
e32de7ba 12389 if (this->vals() == NULL)
e440a328 12390 return;
12391
12392 Struct_type* st = this->type_->struct_type();
e32de7ba 12393 if (this->vals()->size() > st->field_count())
e440a328 12394 {
12395 this->report_error(_("too many expressions for struct"));
12396 return;
12397 }
12398
12399 const Struct_field_list* fields = st->fields();
e32de7ba 12400 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12401 int i = 0;
12402 for (Struct_field_list::const_iterator pf = fields->begin();
12403 pf != fields->end();
12404 ++pf, ++pv, ++i)
12405 {
e32de7ba 12406 if (pv == this->vals()->end())
e440a328 12407 {
12408 this->report_error(_("too few expressions for struct"));
12409 break;
12410 }
12411
12412 if (*pv == NULL)
12413 continue;
12414
12415 std::string reason;
12416 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12417 {
12418 if (reason.empty())
631d5788 12419 go_error_at((*pv)->location(),
12420 "incompatible type for field %d in struct construction",
12421 i + 1);
e440a328 12422 else
631d5788 12423 go_error_at((*pv)->location(),
12424 ("incompatible type for field %d in "
12425 "struct construction (%s)"),
12426 i + 1, reason.c_str());
e440a328 12427 this->set_is_error();
12428 }
12429 }
e32de7ba 12430 go_assert(pv == this->vals()->end());
e440a328 12431}
12432
8ba8cc87 12433// Flatten a struct construction expression. Store the values into
12434// temporaries in case they need interface conversion.
12435
12436Expression*
12437Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12438 Statement_inserter* inserter)
12439{
e32de7ba 12440 if (this->vals() == NULL)
8ba8cc87 12441 return this;
12442
12443 // If this is a constant struct, we don't need temporaries.
12444 if (this->is_constant_struct())
12445 return this;
12446
12447 Location loc = this->location();
e32de7ba 12448 for (Expression_list::iterator pv = this->vals()->begin();
12449 pv != this->vals()->end();
8ba8cc87 12450 ++pv)
12451 {
12452 if (*pv != NULL)
12453 {
5bf8be8b 12454 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12455 {
12456 go_assert(saw_errors());
12457 return Expression::make_error(loc);
12458 }
8ba8cc87 12459 if (!(*pv)->is_variable())
12460 {
12461 Temporary_statement* temp =
12462 Statement::make_temporary(NULL, *pv, loc);
12463 inserter->insert(temp);
12464 *pv = Expression::make_temporary_reference(temp, loc);
12465 }
12466 }
12467 }
12468 return this;
12469}
12470
ea664253 12471// Return the backend representation for constructing a struct.
e440a328 12472
ea664253 12473Bexpression*
12474Struct_construction_expression::do_get_backend(Translate_context* context)
e440a328 12475{
12476 Gogo* gogo = context->gogo();
12477
2c809f8f 12478 Btype* btype = this->type_->get_backend(gogo);
e32de7ba 12479 if (this->vals() == NULL)
ea664253 12480 return gogo->backend()->zero_expression(btype);
e440a328 12481
e440a328 12482 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12483 Expression_list::const_iterator pv = this->vals()->begin();
2c809f8f 12484 std::vector<Bexpression*> init;
12485 for (Struct_field_list::const_iterator pf = fields->begin();
12486 pf != fields->end();
12487 ++pf)
e440a328 12488 {
63697958 12489 Btype* fbtype = pf->type()->get_backend(gogo);
e32de7ba 12490 if (pv == this->vals()->end())
2c809f8f 12491 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12492 else if (*pv == NULL)
12493 {
2c809f8f 12494 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12495 ++pv;
12496 }
12497 else
12498 {
2c809f8f 12499 Expression* val =
12500 Expression::convert_for_assignment(gogo, pf->type(),
12501 *pv, this->location());
ea664253 12502 init.push_back(val->get_backend(context));
e440a328 12503 ++pv;
12504 }
e440a328 12505 }
ea664253 12506 return gogo->backend()->constructor_expression(btype, init, this->location());
e440a328 12507}
12508
12509// Export a struct construction.
12510
12511void
12512Struct_construction_expression::do_export(Export* exp) const
12513{
12514 exp->write_c_string("convert(");
12515 exp->write_type(this->type_);
e32de7ba 12516 for (Expression_list::const_iterator pv = this->vals()->begin();
12517 pv != this->vals()->end();
e440a328 12518 ++pv)
12519 {
12520 exp->write_c_string(", ");
12521 if (*pv != NULL)
12522 (*pv)->export_expression(exp);
12523 }
12524 exp->write_c_string(")");
12525}
12526
d751bb78 12527// Dump ast representation of a struct construction expression.
12528
12529void
12530Struct_construction_expression::do_dump_expression(
12531 Ast_dump_context* ast_dump_context) const
12532{
d751bb78 12533 ast_dump_context->dump_type(this->type_);
12534 ast_dump_context->ostream() << "{";
e32de7ba 12535 ast_dump_context->dump_expression_list(this->vals());
d751bb78 12536 ast_dump_context->ostream() << "}";
12537}
12538
e440a328 12539// Make a struct composite literal. This used by the thunk code.
12540
12541Expression*
12542Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12543 Location location)
e440a328 12544{
c484d925 12545 go_assert(type->struct_type() != NULL);
e440a328 12546 return new Struct_construction_expression(type, vals, location);
12547}
12548
da244e59 12549// Class Array_construction_expression.
e440a328 12550
12551// Traversal.
12552
12553int
12554Array_construction_expression::do_traverse(Traverse* traverse)
12555{
e32de7ba 12556 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
e440a328 12557 return TRAVERSE_EXIT;
12558 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12559 return TRAVERSE_EXIT;
12560 return TRAVERSE_CONTINUE;
12561}
12562
12563// Return whether this is a constant initializer.
12564
12565bool
12566Array_construction_expression::is_constant_array() const
12567{
e32de7ba 12568 if (this->vals() == NULL)
e440a328 12569 return true;
12570
12571 // There are no constant constructors for interfaces.
12572 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12573 return false;
12574
e32de7ba 12575 for (Expression_list::const_iterator pv = this->vals()->begin();
12576 pv != this->vals()->end();
e440a328 12577 ++pv)
12578 {
12579 if (*pv != NULL
12580 && !(*pv)->is_constant()
12581 && (!(*pv)->is_composite_literal()
12582 || (*pv)->is_nonconstant_composite_literal()))
12583 return false;
12584 }
12585 return true;
12586}
12587
3ae06f68 12588// Return whether this can be used a constant initializer.
f9ca30f9 12589
12590bool
3ae06f68 12591Array_construction_expression::do_is_static_initializer() const
f9ca30f9 12592{
e32de7ba 12593 if (this->vals() == NULL)
f9ca30f9 12594 return true;
e32de7ba 12595 for (Expression_list::const_iterator pv = this->vals()->begin();
12596 pv != this->vals()->end();
f9ca30f9 12597 ++pv)
12598 {
3ae06f68 12599 if (*pv != NULL && !(*pv)->is_static_initializer())
f9ca30f9 12600 return false;
12601 }
12602 return true;
12603}
12604
e440a328 12605// Final type determination.
12606
12607void
12608Array_construction_expression::do_determine_type(const Type_context*)
12609{
e32de7ba 12610 if (this->vals() == NULL)
e440a328 12611 return;
12612 Type_context subcontext(this->type_->array_type()->element_type(), false);
e32de7ba 12613 for (Expression_list::const_iterator pv = this->vals()->begin();
12614 pv != this->vals()->end();
e440a328 12615 ++pv)
12616 {
12617 if (*pv != NULL)
12618 (*pv)->determine_type(&subcontext);
12619 }
12620}
12621
12622// Check types.
12623
12624void
12625Array_construction_expression::do_check_types(Gogo*)
12626{
e32de7ba 12627 if (this->vals() == NULL)
e440a328 12628 return;
12629
12630 Array_type* at = this->type_->array_type();
12631 int i = 0;
12632 Type* element_type = at->element_type();
e32de7ba 12633 for (Expression_list::const_iterator pv = this->vals()->begin();
12634 pv != this->vals()->end();
e440a328 12635 ++pv, ++i)
12636 {
12637 if (*pv != NULL
12638 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12639 {
631d5788 12640 go_error_at((*pv)->location(),
12641 "incompatible type for element %d in composite literal",
12642 i + 1);
e440a328 12643 this->set_is_error();
12644 }
12645 }
e440a328 12646}
12647
8ba8cc87 12648// Flatten an array construction expression. Store the values into
12649// temporaries in case they need interface conversion.
12650
12651Expression*
12652Array_construction_expression::do_flatten(Gogo*, Named_object*,
12653 Statement_inserter* inserter)
12654{
e32de7ba 12655 if (this->vals() == NULL)
8ba8cc87 12656 return this;
12657
12658 // If this is a constant array, we don't need temporaries.
12659 if (this->is_constant_array())
12660 return this;
12661
12662 Location loc = this->location();
e32de7ba 12663 for (Expression_list::iterator pv = this->vals()->begin();
12664 pv != this->vals()->end();
8ba8cc87 12665 ++pv)
12666 {
12667 if (*pv != NULL)
12668 {
5bf8be8b 12669 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12670 {
12671 go_assert(saw_errors());
12672 return Expression::make_error(loc);
12673 }
8ba8cc87 12674 if (!(*pv)->is_variable())
12675 {
12676 Temporary_statement* temp =
12677 Statement::make_temporary(NULL, *pv, loc);
12678 inserter->insert(temp);
12679 *pv = Expression::make_temporary_reference(temp, loc);
12680 }
12681 }
12682 }
12683 return this;
12684}
12685
2c809f8f 12686// Get a constructor expression for the array values.
e440a328 12687
2c809f8f 12688Bexpression*
12689Array_construction_expression::get_constructor(Translate_context* context,
12690 Btype* array_btype)
e440a328 12691{
e440a328 12692 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12693
12694 std::vector<unsigned long> indexes;
12695 std::vector<Bexpression*> vals;
12696 Gogo* gogo = context->gogo();
e32de7ba 12697 if (this->vals() != NULL)
e440a328 12698 {
12699 size_t i = 0;
ffe743ca 12700 std::vector<unsigned long>::const_iterator pi;
12701 if (this->indexes_ != NULL)
12702 pi = this->indexes_->begin();
e32de7ba 12703 for (Expression_list::const_iterator pv = this->vals()->begin();
12704 pv != this->vals()->end();
e440a328 12705 ++pv, ++i)
12706 {
ffe743ca 12707 if (this->indexes_ != NULL)
12708 go_assert(pi != this->indexes_->end());
ffe743ca 12709
12710 if (this->indexes_ == NULL)
2c809f8f 12711 indexes.push_back(i);
ffe743ca 12712 else
2c809f8f 12713 indexes.push_back(*pi);
e440a328 12714 if (*pv == NULL)
63697958 12715 {
63697958 12716 Btype* ebtype = element_type->get_backend(gogo);
12717 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12718 vals.push_back(zv);
63697958 12719 }
e440a328 12720 else
12721 {
2c809f8f 12722 Expression* val_expr =
12723 Expression::convert_for_assignment(gogo, element_type, *pv,
12724 this->location());
ea664253 12725 vals.push_back(val_expr->get_backend(context));
e440a328 12726 }
ffe743ca 12727 if (this->indexes_ != NULL)
12728 ++pi;
e440a328 12729 }
ffe743ca 12730 if (this->indexes_ != NULL)
12731 go_assert(pi == this->indexes_->end());
e440a328 12732 }
2c809f8f 12733 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12734 vals, this->location());
e440a328 12735}
12736
12737// Export an array construction.
12738
12739void
12740Array_construction_expression::do_export(Export* exp) const
12741{
12742 exp->write_c_string("convert(");
12743 exp->write_type(this->type_);
e32de7ba 12744 if (this->vals() != NULL)
e440a328 12745 {
ffe743ca 12746 std::vector<unsigned long>::const_iterator pi;
12747 if (this->indexes_ != NULL)
12748 pi = this->indexes_->begin();
e32de7ba 12749 for (Expression_list::const_iterator pv = this->vals()->begin();
12750 pv != this->vals()->end();
e440a328 12751 ++pv)
12752 {
12753 exp->write_c_string(", ");
ffe743ca 12754
12755 if (this->indexes_ != NULL)
12756 {
12757 char buf[100];
12758 snprintf(buf, sizeof buf, "%lu", *pi);
12759 exp->write_c_string(buf);
12760 exp->write_c_string(":");
12761 }
12762
e440a328 12763 if (*pv != NULL)
12764 (*pv)->export_expression(exp);
ffe743ca 12765
12766 if (this->indexes_ != NULL)
12767 ++pi;
e440a328 12768 }
12769 }
12770 exp->write_c_string(")");
12771}
12772
0e9a2e72 12773// Dump ast representation of an array construction expression.
d751bb78 12774
12775void
12776Array_construction_expression::do_dump_expression(
12777 Ast_dump_context* ast_dump_context) const
12778{
ffe743ca 12779 Expression* length = this->type_->array_type()->length();
8b1c301d 12780
12781 ast_dump_context->ostream() << "[" ;
12782 if (length != NULL)
12783 {
12784 ast_dump_context->dump_expression(length);
12785 }
12786 ast_dump_context->ostream() << "]" ;
d751bb78 12787 ast_dump_context->dump_type(this->type_);
0e9a2e72 12788 this->dump_slice_storage_expression(ast_dump_context);
d751bb78 12789 ast_dump_context->ostream() << "{" ;
ffe743ca 12790 if (this->indexes_ == NULL)
e32de7ba 12791 ast_dump_context->dump_expression_list(this->vals());
ffe743ca 12792 else
12793 {
e32de7ba 12794 Expression_list::const_iterator pv = this->vals()->begin();
ffe743ca 12795 for (std::vector<unsigned long>::const_iterator pi =
12796 this->indexes_->begin();
12797 pi != this->indexes_->end();
12798 ++pi, ++pv)
12799 {
12800 if (pi != this->indexes_->begin())
12801 ast_dump_context->ostream() << ", ";
12802 ast_dump_context->ostream() << *pi << ':';
12803 ast_dump_context->dump_expression(*pv);
12804 }
12805 }
d751bb78 12806 ast_dump_context->ostream() << "}" ;
12807
12808}
12809
da244e59 12810// Class Fixed_array_construction_expression.
e440a328 12811
da244e59 12812Fixed_array_construction_expression::Fixed_array_construction_expression(
12813 Type* type, const std::vector<unsigned long>* indexes,
12814 Expression_list* vals, Location location)
12815 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12816 type, indexes, vals, location)
12817{ go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12818
ea664253 12819// Return the backend representation for constructing a fixed array.
e440a328 12820
ea664253 12821Bexpression*
12822Fixed_array_construction_expression::do_get_backend(Translate_context* context)
e440a328 12823{
9f0e0513 12824 Type* type = this->type();
12825 Btype* btype = type->get_backend(context->gogo());
ea664253 12826 return this->get_constructor(context, btype);
e440a328 12827}
12828
76f85fd6 12829Expression*
12830Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12831 Location location)
12832{
12833 go_assert(type->array_type() != NULL && !type->is_slice_type());
12834 return new Fixed_array_construction_expression(type, NULL, vals, location);
12835}
12836
da244e59 12837// Class Slice_construction_expression.
e440a328 12838
da244e59 12839Slice_construction_expression::Slice_construction_expression(
12840 Type* type, const std::vector<unsigned long>* indexes,
12841 Expression_list* vals, Location location)
12842 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12843 type, indexes, vals, location),
0e9a2e72 12844 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
12845 storage_escapes_(true)
e440a328 12846{
da244e59 12847 go_assert(type->is_slice_type());
23d77f91 12848
da244e59 12849 unsigned long lenval;
12850 Expression* length;
12851 if (vals == NULL || vals->empty())
12852 lenval = 0;
12853 else
12854 {
12855 if (this->indexes() == NULL)
12856 lenval = vals->size();
12857 else
12858 lenval = indexes->back() + 1;
12859 }
12860 Type* int_type = Type::lookup_integer_type("int");
12861 length = Expression::make_integer_ul(lenval, int_type, location);
12862 Type* element_type = type->array_type()->element_type();
12863 this->valtype_ = Type::make_array_type(element_type, length);
12864}
e440a328 12865
23d77f91 12866// Traversal.
12867
12868int
12869Slice_construction_expression::do_traverse(Traverse* traverse)
12870{
12871 if (this->Array_construction_expression::do_traverse(traverse)
12872 == TRAVERSE_EXIT)
12873 return TRAVERSE_EXIT;
12874 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12875 return TRAVERSE_EXIT;
0e9a2e72 12876 if (this->array_val_ != NULL
12877 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
12878 return TRAVERSE_EXIT;
12879 if (this->slice_storage_ != NULL
12880 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
12881 return TRAVERSE_EXIT;
23d77f91 12882 return TRAVERSE_CONTINUE;
12883}
12884
0e9a2e72 12885// Helper routine to create fixed array value underlying the slice literal.
12886// May be called during flattening, or later during do_get_backend().
e440a328 12887
0e9a2e72 12888Expression*
12889Slice_construction_expression::create_array_val()
e440a328 12890{
f9c68f17 12891 Array_type* array_type = this->type()->array_type();
12892 if (array_type == NULL)
12893 {
c484d925 12894 go_assert(this->type()->is_error());
0e9a2e72 12895 return NULL;
f9c68f17 12896 }
12897
f23d7786 12898 Location loc = this->location();
23d77f91 12899 go_assert(this->valtype_ != NULL);
3d60812e 12900
f23d7786 12901 Expression_list* vals = this->vals();
e440a328 12902 if (this->vals() == NULL || this->vals()->empty())
12903 {
f23d7786 12904 // We need to create a unique value for the empty array literal.
12905 vals = new Expression_list;
12906 vals->push_back(NULL);
e440a328 12907 }
0e9a2e72 12908 return new Fixed_array_construction_expression(
12909 this->valtype_, this->indexes(), vals, loc);
12910}
12911
12912// If we're previous established that the slice storage does not
12913// escape, then create a separate array temp val here for it. We
12914// need to do this as part of flattening so as to be able to insert
12915// the new temp statement.
12916
12917Expression*
12918Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
12919 Statement_inserter* inserter)
12920{
12921 if (this->type()->array_type() == NULL)
12922 return NULL;
12923
12924 // Base class flattening first
12925 this->Array_construction_expression::do_flatten(gogo, no, inserter);
12926
12927 // Create an stack-allocated storage temp if storage won't escape
12928 if (!this->storage_escapes_)
12929 {
12930 Location loc = this->location();
12931 this->array_val_ = create_array_val();
12932 go_assert(this->array_val_);
12933 Temporary_statement* temp =
12934 Statement::make_temporary(this->valtype_, this->array_val_, loc);
12935 inserter->insert(temp);
12936 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
12937 }
12938 return this;
12939}
12940
12941// When dumping a slice construction expression that has an explicit
12942// storeage temp, emit the temp here (if we don't do this the storage
12943// temp appears unused in the AST dump).
12944
12945void
12946Slice_construction_expression::
12947dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
12948{
12949 if (this->slice_storage_ == NULL)
12950 return;
12951 ast_dump_context->ostream() << "storage=" ;
12952 ast_dump_context->dump_expression(this->slice_storage_);
12953}
12954
12955// Return the backend representation for constructing a slice.
12956
12957Bexpression*
12958Slice_construction_expression::do_get_backend(Translate_context* context)
12959{
12960 if (this->array_val_ == NULL)
12961 this->array_val_ = create_array_val();
12962 if (this->array_val_ == NULL)
12963 {
12964 go_assert(this->type()->is_error());
12965 return context->backend()->error_expression();
12966 }
12967
12968 Location loc = this->location();
e440a328 12969
3ae06f68 12970 bool is_static_initializer = this->array_val_->is_static_initializer();
d8829beb 12971
12972 // We have to copy the initial values into heap memory if we are in
3ae06f68 12973 // a function or if the values are not constants.
12974 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
e440a328 12975
f23d7786 12976 Expression* space;
0e9a2e72 12977
12978 if (this->slice_storage_ != NULL)
12979 {
12980 go_assert(!this->storage_escapes_);
12981 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
12982 }
12983 else if (!copy_to_heap)
e440a328 12984 {
f23d7786 12985 // The initializer will only run once.
0e9a2e72 12986 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
f23d7786 12987 space->unary_expression()->set_is_slice_init();
e440a328 12988 }
12989 else
45ff893b 12990 {
0e9a2e72 12991 space = Expression::make_heap_expression(this->array_val_, loc);
45ff893b 12992 Node* n = Node::make_node(this);
12993 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
12994 {
12995 n = Node::make_node(space);
12996 n->set_encoding(Node::ESCAPE_NONE);
12997 }
12998 }
e440a328 12999
2c809f8f 13000 // Build a constructor for the slice.
f23d7786 13001 Expression* len = this->valtype_->array_type()->length();
13002 Expression* slice_val =
13003 Expression::make_slice_value(this->type(), space, len, len, loc);
ea664253 13004 return slice_val->get_backend(context);
e440a328 13005}
13006
13007// Make a slice composite literal. This is used by the type
13008// descriptor code.
13009
0e9a2e72 13010Slice_construction_expression*
e440a328 13011Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 13012 Location location)
e440a328 13013{
411eb89e 13014 go_assert(type->is_slice_type());
2c809f8f 13015 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 13016}
13017
da244e59 13018// Class Map_construction_expression.
e440a328 13019
13020// Traversal.
13021
13022int
13023Map_construction_expression::do_traverse(Traverse* traverse)
13024{
13025 if (this->vals_ != NULL
13026 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13027 return TRAVERSE_EXIT;
13028 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13029 return TRAVERSE_EXIT;
13030 return TRAVERSE_CONTINUE;
13031}
13032
2c809f8f 13033// Flatten constructor initializer into a temporary variable since
13034// we need to take its address for __go_construct_map.
13035
13036Expression*
13037Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13038 Statement_inserter* inserter)
13039{
13040 if (!this->is_error_expression()
13041 && this->vals_ != NULL
13042 && !this->vals_->empty()
13043 && this->constructor_temp_ == NULL)
13044 {
13045 Map_type* mt = this->type_->map_type();
13046 Type* key_type = mt->key_type();
13047 Type* val_type = mt->val_type();
13048 this->element_type_ = Type::make_builtin_struct_type(2,
13049 "__key", key_type,
13050 "__val", val_type);
13051
13052 Expression_list* value_pairs = new Expression_list();
13053 Location loc = this->location();
13054
13055 size_t i = 0;
13056 for (Expression_list::const_iterator pv = this->vals_->begin();
13057 pv != this->vals_->end();
13058 ++pv, ++i)
13059 {
13060 Expression_list* key_value_pair = new Expression_list();
91c0fd76 13061 Expression* key = *pv;
5bf8be8b 13062 if (key->is_error_expression() || key->type()->is_error_type())
13063 {
13064 go_assert(saw_errors());
13065 return Expression::make_error(loc);
13066 }
91c0fd76 13067 if (key->type()->interface_type() != NULL && !key->is_variable())
13068 {
13069 Temporary_statement* temp =
13070 Statement::make_temporary(NULL, key, loc);
13071 inserter->insert(temp);
13072 key = Expression::make_temporary_reference(temp, loc);
13073 }
13074 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
2c809f8f 13075
13076 ++pv;
91c0fd76 13077 Expression* val = *pv;
5bf8be8b 13078 if (val->is_error_expression() || val->type()->is_error_type())
13079 {
13080 go_assert(saw_errors());
13081 return Expression::make_error(loc);
13082 }
91c0fd76 13083 if (val->type()->interface_type() != NULL && !val->is_variable())
13084 {
13085 Temporary_statement* temp =
13086 Statement::make_temporary(NULL, val, loc);
13087 inserter->insert(temp);
13088 val = Expression::make_temporary_reference(temp, loc);
13089 }
13090 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
2c809f8f 13091
13092 key_value_pair->push_back(key);
13093 key_value_pair->push_back(val);
13094 value_pairs->push_back(
13095 Expression::make_struct_composite_literal(this->element_type_,
13096 key_value_pair, loc));
13097 }
13098
e67508fa 13099 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
2c809f8f 13100 Type* ctor_type =
13101 Type::make_array_type(this->element_type_, element_count);
13102 Expression* constructor =
13103 new Fixed_array_construction_expression(ctor_type, NULL,
13104 value_pairs, loc);
13105
13106 this->constructor_temp_ =
13107 Statement::make_temporary(NULL, constructor, loc);
13108 constructor->issue_nil_check();
13109 this->constructor_temp_->set_is_address_taken();
13110 inserter->insert(this->constructor_temp_);
13111 }
13112
13113 return this;
13114}
13115
e440a328 13116// Final type determination.
13117
13118void
13119Map_construction_expression::do_determine_type(const Type_context*)
13120{
13121 if (this->vals_ == NULL)
13122 return;
13123
13124 Map_type* mt = this->type_->map_type();
13125 Type_context key_context(mt->key_type(), false);
13126 Type_context val_context(mt->val_type(), false);
13127 for (Expression_list::const_iterator pv = this->vals_->begin();
13128 pv != this->vals_->end();
13129 ++pv)
13130 {
13131 (*pv)->determine_type(&key_context);
13132 ++pv;
13133 (*pv)->determine_type(&val_context);
13134 }
13135}
13136
13137// Check types.
13138
13139void
13140Map_construction_expression::do_check_types(Gogo*)
13141{
13142 if (this->vals_ == NULL)
13143 return;
13144
13145 Map_type* mt = this->type_->map_type();
13146 int i = 0;
13147 Type* key_type = mt->key_type();
13148 Type* val_type = mt->val_type();
13149 for (Expression_list::const_iterator pv = this->vals_->begin();
13150 pv != this->vals_->end();
13151 ++pv, ++i)
13152 {
13153 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13154 {
631d5788 13155 go_error_at((*pv)->location(),
13156 "incompatible type for element %d key in map construction",
13157 i + 1);
e440a328 13158 this->set_is_error();
13159 }
13160 ++pv;
13161 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13162 {
631d5788 13163 go_error_at((*pv)->location(),
13164 ("incompatible type for element %d value "
13165 "in map construction"),
e440a328 13166 i + 1);
13167 this->set_is_error();
13168 }
13169 }
13170}
13171
ea664253 13172// Return the backend representation for constructing a map.
e440a328 13173
ea664253 13174Bexpression*
13175Map_construction_expression::do_get_backend(Translate_context* context)
e440a328 13176{
2c809f8f 13177 if (this->is_error_expression())
ea664253 13178 return context->backend()->error_expression();
2c809f8f 13179 Location loc = this->location();
e440a328 13180
e440a328 13181 size_t i = 0;
2c809f8f 13182 Expression* ventries;
e440a328 13183 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 13184 ventries = Expression::make_nil(loc);
e440a328 13185 else
13186 {
2c809f8f 13187 go_assert(this->constructor_temp_ != NULL);
13188 i = this->vals_->size() / 2;
e440a328 13189
2c809f8f 13190 Expression* ctor_ref =
13191 Expression::make_temporary_reference(this->constructor_temp_, loc);
13192 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13193 }
e440a328 13194
2c809f8f 13195 Map_type* mt = this->type_->map_type();
13196 if (this->element_type_ == NULL)
13197 this->element_type_ =
13198 Type::make_builtin_struct_type(2,
13199 "__key", mt->key_type(),
13200 "__val", mt->val_type());
0d5530d9 13201 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
2c809f8f 13202
13203 Type* uintptr_t = Type::lookup_integer_type("uintptr");
e67508fa 13204 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
2c809f8f 13205
13206 Expression* entry_size =
13207 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13208
13209 unsigned int field_index;
13210 const Struct_field* valfield =
13211 this->element_type_->find_local_field("__val", &field_index);
13212 Expression* val_offset =
13213 Expression::make_struct_field_offset(this->element_type_, valfield);
2c809f8f 13214
13215 Expression* map_ctor =
0d5530d9 13216 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13217 entry_size, val_offset, ventries);
ea664253 13218 return map_ctor->get_backend(context);
2c809f8f 13219}
e440a328 13220
2c809f8f 13221// Export an array construction.
e440a328 13222
2c809f8f 13223void
13224Map_construction_expression::do_export(Export* exp) const
13225{
13226 exp->write_c_string("convert(");
13227 exp->write_type(this->type_);
13228 for (Expression_list::const_iterator pv = this->vals_->begin();
13229 pv != this->vals_->end();
13230 ++pv)
13231 {
13232 exp->write_c_string(", ");
13233 (*pv)->export_expression(exp);
13234 }
13235 exp->write_c_string(")");
13236}
e440a328 13237
2c809f8f 13238// Dump ast representation for a map construction expression.
d751bb78 13239
13240void
13241Map_construction_expression::do_dump_expression(
13242 Ast_dump_context* ast_dump_context) const
13243{
d751bb78 13244 ast_dump_context->ostream() << "{" ;
8b1c301d 13245 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 13246 ast_dump_context->ostream() << "}";
13247}
13248
7795ac51 13249// Class Composite_literal_expression.
e440a328 13250
13251// Traversal.
13252
13253int
13254Composite_literal_expression::do_traverse(Traverse* traverse)
13255{
dbffccfc 13256 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 13257 return TRAVERSE_EXIT;
dbffccfc 13258
13259 // If this is a struct composite literal with keys, then the keys
13260 // are field names, not expressions. We don't want to traverse them
13261 // in that case. If we do, we can give an erroneous error "variable
13262 // initializer refers to itself." See bug482.go in the testsuite.
13263 if (this->has_keys_ && this->vals_ != NULL)
13264 {
13265 // The type may not be resolvable at this point.
13266 Type* type = this->type_;
a01f2481 13267
7795ac51 13268 for (int depth = 0; depth < this->depth_; ++depth)
a01f2481 13269 {
13270 if (type->array_type() != NULL)
13271 type = type->array_type()->element_type();
13272 else if (type->map_type() != NULL)
7795ac51 13273 {
13274 if (this->key_path_[depth])
13275 type = type->map_type()->key_type();
13276 else
13277 type = type->map_type()->val_type();
13278 }
a01f2481 13279 else
13280 {
13281 // This error will be reported during lowering.
13282 return TRAVERSE_CONTINUE;
13283 }
13284 }
13285
dbffccfc 13286 while (true)
13287 {
13288 if (type->classification() == Type::TYPE_NAMED)
13289 type = type->named_type()->real_type();
13290 else if (type->classification() == Type::TYPE_FORWARD)
13291 {
13292 Type* t = type->forwarded();
13293 if (t == type)
13294 break;
13295 type = t;
13296 }
13297 else
13298 break;
13299 }
13300
13301 if (type->classification() == Type::TYPE_STRUCT)
13302 {
13303 Expression_list::iterator p = this->vals_->begin();
13304 while (p != this->vals_->end())
13305 {
13306 // Skip key.
13307 ++p;
13308 go_assert(p != this->vals_->end());
13309 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13310 return TRAVERSE_EXIT;
13311 ++p;
13312 }
13313 return TRAVERSE_CONTINUE;
13314 }
13315 }
13316
13317 if (this->vals_ != NULL)
13318 return this->vals_->traverse(traverse);
13319
13320 return TRAVERSE_CONTINUE;
e440a328 13321}
13322
13323// Lower a generic composite literal into a specific version based on
13324// the type.
13325
13326Expression*
ceeb4318 13327Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13328 Statement_inserter* inserter, int)
e440a328 13329{
13330 Type* type = this->type_;
13331
7795ac51 13332 for (int depth = 0; depth < this->depth_; ++depth)
e440a328 13333 {
13334 if (type->array_type() != NULL)
13335 type = type->array_type()->element_type();
13336 else if (type->map_type() != NULL)
7795ac51 13337 {
13338 if (this->key_path_[depth])
13339 type = type->map_type()->key_type();
13340 else
13341 type = type->map_type()->val_type();
13342 }
e440a328 13343 else
13344 {
5c13bd80 13345 if (!type->is_error())
631d5788 13346 go_error_at(this->location(),
13347 ("may only omit types within composite literals "
13348 "of slice, array, or map type"));
e440a328 13349 return Expression::make_error(this->location());
13350 }
13351 }
13352
e00772b3 13353 Type *pt = type->points_to();
13354 bool is_pointer = false;
13355 if (pt != NULL)
13356 {
13357 is_pointer = true;
13358 type = pt;
13359 }
13360
13361 Expression* ret;
5c13bd80 13362 if (type->is_error())
e440a328 13363 return Expression::make_error(this->location());
13364 else if (type->struct_type() != NULL)
e00772b3 13365 ret = this->lower_struct(gogo, type);
e440a328 13366 else if (type->array_type() != NULL)
113ef6a5 13367 ret = this->lower_array(type);
e440a328 13368 else if (type->map_type() != NULL)
e00772b3 13369 ret = this->lower_map(gogo, function, inserter, type);
e440a328 13370 else
13371 {
631d5788 13372 go_error_at(this->location(),
13373 ("expected struct, slice, array, or map type "
13374 "for composite literal"));
e440a328 13375 return Expression::make_error(this->location());
13376 }
e00772b3 13377
13378 if (is_pointer)
2c809f8f 13379 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13380
13381 return ret;
e440a328 13382}
13383
13384// Lower a struct composite literal.
13385
13386Expression*
81c4b26b 13387Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13388{
b13c66cd 13389 Location location = this->location();
e440a328 13390 Struct_type* st = type->struct_type();
13391 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13392 {
e6013c28 13393 if (this->vals_ != NULL
13394 && !this->vals_->empty()
13395 && type->named_type() != NULL
13396 && type->named_type()->named_object()->package() != NULL)
13397 {
13398 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13399 pf != st->fields()->end();
13400 ++pf)
07daa4e7 13401 {
07ba7f26 13402 if (Gogo::is_hidden_name(pf->field_name())
13403 || pf->is_embedded_builtin(gogo))
631d5788 13404 go_error_at(this->location(),
13405 "assignment of unexported field %qs in %qs literal",
13406 Gogo::message_name(pf->field_name()).c_str(),
13407 type->named_type()->message_name().c_str());
07daa4e7 13408 }
13409 }
13410
13411 return new Struct_construction_expression(type, this->vals_, location);
13412 }
e440a328 13413
13414 size_t field_count = st->field_count();
13415 std::vector<Expression*> vals(field_count);
e32de7ba 13416 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
e440a328 13417 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13418 Expression* external_expr = NULL;
13419 const Named_object* external_no = NULL;
e440a328 13420 while (p != this->vals_->end())
13421 {
13422 Expression* name_expr = *p;
13423
13424 ++p;
c484d925 13425 go_assert(p != this->vals_->end());
e440a328 13426 Expression* val = *p;
13427
13428 ++p;
13429
13430 if (name_expr == NULL)
13431 {
631d5788 13432 go_error_at(val->location(),
13433 "mixture of field and value initializers");
e440a328 13434 return Expression::make_error(location);
13435 }
13436
13437 bool bad_key = false;
13438 std::string name;
81c4b26b 13439 const Named_object* no = NULL;
e440a328 13440 switch (name_expr->classification())
13441 {
13442 case EXPRESSION_UNKNOWN_REFERENCE:
13443 name = name_expr->unknown_expression()->name();
7f7ce694 13444 if (type->named_type() != NULL)
13445 {
13446 // If the named object found for this field name comes from a
13447 // different package than the struct it is a part of, do not count
13448 // this incorrect lookup as a usage of the object's package.
13449 no = name_expr->unknown_expression()->named_object();
13450 if (no->package() != NULL
13451 && no->package() != type->named_type()->named_object()->package())
13452 no->package()->forget_usage(name_expr);
13453 }
e440a328 13454 break;
13455
13456 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13457 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13458 break;
13459
13460 case EXPRESSION_TYPE:
13461 {
13462 Type* t = name_expr->type();
13463 Named_type* nt = t->named_type();
13464 if (nt == NULL)
13465 bad_key = true;
13466 else
81c4b26b 13467 no = nt->named_object();
e440a328 13468 }
13469 break;
13470
13471 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13472 no = name_expr->var_expression()->named_object();
e440a328 13473 break;
13474
b0c09712 13475 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13476 no = name_expr->enclosed_var_expression()->variable();
e440a328 13477 break;
13478
b0c09712 13479 case EXPRESSION_FUNC_REFERENCE:
13480 no = name_expr->func_expression()->named_object();
e440a328 13481 break;
13482
13483 default:
13484 bad_key = true;
13485 break;
13486 }
13487 if (bad_key)
13488 {
631d5788 13489 go_error_at(name_expr->location(), "expected struct field name");
e440a328 13490 return Expression::make_error(location);
13491 }
13492
81c4b26b 13493 if (no != NULL)
13494 {
62750cd5 13495 if (no->package() != NULL && external_expr == NULL)
13496 {
13497 external_expr = name_expr;
13498 external_no = no;
13499 }
13500
81c4b26b 13501 name = no->name();
13502
13503 // A predefined name won't be packed. If it starts with a
13504 // lower case letter we need to check for that case, because
2d29d278 13505 // the field name will be packed. FIXME.
81c4b26b 13506 if (!Gogo::is_hidden_name(name)
13507 && name[0] >= 'a'
13508 && name[0] <= 'z')
13509 {
13510 Named_object* gno = gogo->lookup_global(name.c_str());
13511 if (gno == no)
13512 name = gogo->pack_hidden_name(name, false);
13513 }
13514 }
13515
e440a328 13516 unsigned int index;
13517 const Struct_field* sf = st->find_local_field(name, &index);
13518 if (sf == NULL)
13519 {
631d5788 13520 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13521 Gogo::message_name(name).c_str(),
13522 (type->named_type() != NULL
13523 ? type->named_type()->message_name().c_str()
13524 : "unnamed struct"));
e440a328 13525 return Expression::make_error(location);
13526 }
13527 if (vals[index] != NULL)
13528 {
631d5788 13529 go_error_at(name_expr->location(),
13530 "duplicate value for field %qs in %qs",
13531 Gogo::message_name(name).c_str(),
13532 (type->named_type() != NULL
13533 ? type->named_type()->message_name().c_str()
13534 : "unnamed struct"));
e440a328 13535 return Expression::make_error(location);
13536 }
13537
07daa4e7 13538 if (type->named_type() != NULL
13539 && type->named_type()->named_object()->package() != NULL
07ba7f26 13540 && (Gogo::is_hidden_name(sf->field_name())
13541 || sf->is_embedded_builtin(gogo)))
631d5788 13542 go_error_at(name_expr->location(),
13543 "assignment of unexported field %qs in %qs literal",
13544 Gogo::message_name(sf->field_name()).c_str(),
13545 type->named_type()->message_name().c_str());
07daa4e7 13546
e440a328 13547 vals[index] = val;
e32de7ba 13548 traverse_order->push_back(static_cast<unsigned long>(index));
e440a328 13549 }
13550
62750cd5 13551 if (!this->all_are_names_)
13552 {
13553 // This is a weird case like bug462 in the testsuite.
13554 if (external_expr == NULL)
631d5788 13555 go_error_at(this->location(), "unknown field in %qs literal",
13556 (type->named_type() != NULL
13557 ? type->named_type()->message_name().c_str()
13558 : "unnamed struct"));
62750cd5 13559 else
631d5788 13560 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13561 external_no->message_name().c_str(),
13562 (type->named_type() != NULL
13563 ? type->named_type()->message_name().c_str()
13564 : "unnamed struct"));
62750cd5 13565 return Expression::make_error(location);
13566 }
13567
e440a328 13568 Expression_list* list = new Expression_list;
13569 list->reserve(field_count);
13570 for (size_t i = 0; i < field_count; ++i)
13571 list->push_back(vals[i]);
13572
0c4f5a19 13573 Struct_construction_expression* ret =
13574 new Struct_construction_expression(type, list, location);
13575 ret->set_traverse_order(traverse_order);
13576 return ret;
e440a328 13577}
13578
e32de7ba 13579// Index/value/traversal-order triple.
00773463 13580
e32de7ba 13581struct IVT_triple {
13582 unsigned long index;
13583 unsigned long traversal_order;
13584 Expression* expr;
13585 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13586 : index(i), traversal_order(to), expr(e) { }
13587 bool operator<(const IVT_triple& other) const
13588 { return this->index < other.index; }
00773463 13589};
13590
e440a328 13591// Lower an array composite literal.
13592
13593Expression*
113ef6a5 13594Composite_literal_expression::lower_array(Type* type)
e440a328 13595{
b13c66cd 13596 Location location = this->location();
e440a328 13597 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13598 return this->make_array(type, NULL, this->vals_);
e440a328 13599
ffe743ca 13600 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13601 indexes->reserve(this->vals_->size());
00773463 13602 bool indexes_out_of_order = false;
ffe743ca 13603 Expression_list* vals = new Expression_list();
13604 vals->reserve(this->vals_->size());
e440a328 13605 unsigned long index = 0;
13606 Expression_list::const_iterator p = this->vals_->begin();
13607 while (p != this->vals_->end())
13608 {
13609 Expression* index_expr = *p;
13610
13611 ++p;
c484d925 13612 go_assert(p != this->vals_->end());
e440a328 13613 Expression* val = *p;
13614
13615 ++p;
13616
ffe743ca 13617 if (index_expr == NULL)
13618 {
13619 if (!indexes->empty())
13620 indexes->push_back(index);
13621 }
13622 else
e440a328 13623 {
ffe743ca 13624 if (indexes->empty() && !vals->empty())
13625 {
13626 for (size_t i = 0; i < vals->size(); ++i)
13627 indexes->push_back(i);
13628 }
13629
0c77715b 13630 Numeric_constant nc;
13631 if (!index_expr->numeric_constant_value(&nc))
e440a328 13632 {
631d5788 13633 go_error_at(index_expr->location(),
13634 "index expression is not integer constant");
e440a328 13635 return Expression::make_error(location);
13636 }
6f6d9955 13637
0c77715b 13638 switch (nc.to_unsigned_long(&index))
e440a328 13639 {
0c77715b 13640 case Numeric_constant::NC_UL_VALID:
13641 break;
13642 case Numeric_constant::NC_UL_NOTINT:
631d5788 13643 go_error_at(index_expr->location(),
13644 "index expression is not integer constant");
0c77715b 13645 return Expression::make_error(location);
13646 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 13647 go_error_at(index_expr->location(),
13648 "index expression is negative");
e440a328 13649 return Expression::make_error(location);
0c77715b 13650 case Numeric_constant::NC_UL_BIG:
631d5788 13651 go_error_at(index_expr->location(), "index value overflow");
e440a328 13652 return Expression::make_error(location);
0c77715b 13653 default:
13654 go_unreachable();
e440a328 13655 }
6f6d9955 13656
13657 Named_type* ntype = Type::lookup_integer_type("int");
13658 Integer_type* inttype = ntype->integer_type();
0c77715b 13659 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13660 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13661 {
631d5788 13662 go_error_at(index_expr->location(), "index value overflow");
6f6d9955 13663 return Expression::make_error(location);
13664 }
13665
ffe743ca 13666 if (std::find(indexes->begin(), indexes->end(), index)
13667 != indexes->end())
e440a328 13668 {
631d5788 13669 go_error_at(index_expr->location(),
13670 "duplicate value for index %lu",
13671 index);
e440a328 13672 return Expression::make_error(location);
13673 }
ffe743ca 13674
00773463 13675 if (!indexes->empty() && index < indexes->back())
13676 indexes_out_of_order = true;
13677
ffe743ca 13678 indexes->push_back(index);
e440a328 13679 }
13680
ffe743ca 13681 vals->push_back(val);
13682
e440a328 13683 ++index;
13684 }
13685
ffe743ca 13686 if (indexes->empty())
13687 {
13688 delete indexes;
13689 indexes = NULL;
13690 }
e440a328 13691
e32de7ba 13692 std::vector<unsigned long>* traverse_order = NULL;
00773463 13693 if (indexes_out_of_order)
13694 {
e32de7ba 13695 typedef std::vector<IVT_triple> V;
00773463 13696
13697 V v;
13698 v.reserve(indexes->size());
13699 std::vector<unsigned long>::const_iterator pi = indexes->begin();
e32de7ba 13700 unsigned long torder = 0;
00773463 13701 for (Expression_list::const_iterator pe = vals->begin();
13702 pe != vals->end();
e32de7ba 13703 ++pe, ++pi, ++torder)
13704 v.push_back(IVT_triple(*pi, torder, *pe));
00773463 13705
e32de7ba 13706 std::sort(v.begin(), v.end());
00773463 13707
13708 delete indexes;
13709 delete vals;
e32de7ba 13710
00773463 13711 indexes = new std::vector<unsigned long>();
13712 indexes->reserve(v.size());
13713 vals = new Expression_list();
13714 vals->reserve(v.size());
e32de7ba 13715 traverse_order = new std::vector<unsigned long>();
13716 traverse_order->reserve(v.size());
00773463 13717
13718 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13719 {
e32de7ba 13720 indexes->push_back(p->index);
13721 vals->push_back(p->expr);
13722 traverse_order->push_back(p->traversal_order);
00773463 13723 }
13724 }
13725
e32de7ba 13726 Expression* ret = this->make_array(type, indexes, vals);
13727 Array_construction_expression* ace = ret->array_literal();
13728 if (ace != NULL && traverse_order != NULL)
13729 ace->set_traverse_order(traverse_order);
13730 return ret;
e440a328 13731}
13732
13733// Actually build the array composite literal. This handles
13734// [...]{...}.
13735
13736Expression*
ffe743ca 13737Composite_literal_expression::make_array(
13738 Type* type,
13739 const std::vector<unsigned long>* indexes,
13740 Expression_list* vals)
e440a328 13741{
b13c66cd 13742 Location location = this->location();
e440a328 13743 Array_type* at = type->array_type();
ffe743ca 13744
e440a328 13745 if (at->length() != NULL && at->length()->is_nil_expression())
13746 {
ffe743ca 13747 size_t size;
13748 if (vals == NULL)
13749 size = 0;
00773463 13750 else if (indexes != NULL)
13751 size = indexes->back() + 1;
13752 else
ffe743ca 13753 {
13754 size = vals->size();
13755 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13756 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13757 && size >> (it->bits() - 1) != 0)
13758 {
631d5788 13759 go_error_at(location, "too many elements in composite literal");
ffe743ca 13760 return Expression::make_error(location);
13761 }
13762 }
ffe743ca 13763
e67508fa 13764 Expression* elen = Expression::make_integer_ul(size, NULL, location);
e440a328 13765 at = Type::make_array_type(at->element_type(), elen);
13766 type = at;
13767 }
ffe743ca 13768 else if (at->length() != NULL
13769 && !at->length()->is_error_expression()
13770 && this->vals_ != NULL)
13771 {
13772 Numeric_constant nc;
13773 unsigned long val;
13774 if (at->length()->numeric_constant_value(&nc)
13775 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13776 {
13777 if (indexes == NULL)
13778 {
13779 if (this->vals_->size() > val)
13780 {
631d5788 13781 go_error_at(location,
13782 "too many elements in composite literal");
ffe743ca 13783 return Expression::make_error(location);
13784 }
13785 }
13786 else
13787 {
00773463 13788 unsigned long max = indexes->back();
ffe743ca 13789 if (max >= val)
13790 {
631d5788 13791 go_error_at(location,
13792 ("some element keys in composite literal "
13793 "are out of range"));
ffe743ca 13794 return Expression::make_error(location);
13795 }
13796 }
13797 }
13798 }
13799
e440a328 13800 if (at->length() != NULL)
ffe743ca 13801 return new Fixed_array_construction_expression(type, indexes, vals,
13802 location);
e440a328 13803 else
2c809f8f 13804 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13805}
13806
13807// Lower a map composite literal.
13808
13809Expression*
a287720d 13810Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13811 Statement_inserter* inserter,
a287720d 13812 Type* type)
e440a328 13813{
b13c66cd 13814 Location location = this->location();
e440a328 13815 if (this->vals_ != NULL)
13816 {
13817 if (!this->has_keys_)
13818 {
631d5788 13819 go_error_at(location, "map composite literal must have keys");
e440a328 13820 return Expression::make_error(location);
13821 }
13822
a287720d 13823 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13824 p != this->vals_->end();
13825 p += 2)
13826 {
13827 if (*p == NULL)
13828 {
13829 ++p;
631d5788 13830 go_error_at((*p)->location(),
13831 ("map composite literal must "
13832 "have keys for every value"));
e440a328 13833 return Expression::make_error(location);
13834 }
a287720d 13835 // Make sure we have lowered the key; it may not have been
13836 // lowered in order to handle keys for struct composite
13837 // literals. Lower it now to get the right error message.
13838 if ((*p)->unknown_expression() != NULL)
13839 {
13840 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13841 gogo->lower_expression(function, inserter, &*p);
c484d925 13842 go_assert((*p)->is_error_expression());
a287720d 13843 return Expression::make_error(location);
13844 }
e440a328 13845 }
13846 }
13847
13848 return new Map_construction_expression(type, this->vals_, location);
13849}
13850
d751bb78 13851// Dump ast representation for a composite literal expression.
13852
13853void
13854Composite_literal_expression::do_dump_expression(
13855 Ast_dump_context* ast_dump_context) const
13856{
8b1c301d 13857 ast_dump_context->ostream() << "composite(";
d751bb78 13858 ast_dump_context->dump_type(this->type_);
13859 ast_dump_context->ostream() << ", {";
8b1c301d 13860 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13861 ast_dump_context->ostream() << "})";
13862}
13863
e440a328 13864// Make a composite literal expression.
13865
13866Expression*
13867Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13868 Expression_list* vals, bool all_are_names,
b13c66cd 13869 Location location)
e440a328 13870{
13871 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13872 all_are_names, location);
e440a328 13873}
13874
13875// Return whether this expression is a composite literal.
13876
13877bool
13878Expression::is_composite_literal() const
13879{
13880 switch (this->classification_)
13881 {
13882 case EXPRESSION_COMPOSITE_LITERAL:
13883 case EXPRESSION_STRUCT_CONSTRUCTION:
13884 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13885 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13886 case EXPRESSION_MAP_CONSTRUCTION:
13887 return true;
13888 default:
13889 return false;
13890 }
13891}
13892
13893// Return whether this expression is a composite literal which is not
13894// constant.
13895
13896bool
13897Expression::is_nonconstant_composite_literal() const
13898{
13899 switch (this->classification_)
13900 {
13901 case EXPRESSION_STRUCT_CONSTRUCTION:
13902 {
13903 const Struct_construction_expression *psce =
13904 static_cast<const Struct_construction_expression*>(this);
13905 return !psce->is_constant_struct();
13906 }
13907 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13908 {
13909 const Fixed_array_construction_expression *pace =
13910 static_cast<const Fixed_array_construction_expression*>(this);
13911 return !pace->is_constant_array();
13912 }
2c809f8f 13913 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13914 {
2c809f8f 13915 const Slice_construction_expression *pace =
13916 static_cast<const Slice_construction_expression*>(this);
e440a328 13917 return !pace->is_constant_array();
13918 }
13919 case EXPRESSION_MAP_CONSTRUCTION:
13920 return true;
13921 default:
13922 return false;
13923 }
13924}
13925
35a54f17 13926// Return true if this is a variable or temporary_variable.
13927
13928bool
13929Expression::is_variable() const
13930{
13931 switch (this->classification_)
13932 {
13933 case EXPRESSION_VAR_REFERENCE:
13934 case EXPRESSION_TEMPORARY_REFERENCE:
13935 case EXPRESSION_SET_AND_USE_TEMPORARY:
b0c09712 13936 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
35a54f17 13937 return true;
13938 default:
13939 return false;
13940 }
13941}
13942
e440a328 13943// Return true if this is a reference to a local variable.
13944
13945bool
13946Expression::is_local_variable() const
13947{
13948 const Var_expression* ve = this->var_expression();
13949 if (ve == NULL)
13950 return false;
13951 const Named_object* no = ve->named_object();
13952 return (no->is_result_variable()
13953 || (no->is_variable() && !no->var_value()->is_global()));
13954}
13955
13956// Class Type_guard_expression.
13957
13958// Traversal.
13959
13960int
13961Type_guard_expression::do_traverse(Traverse* traverse)
13962{
13963 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13964 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13965 return TRAVERSE_EXIT;
13966 return TRAVERSE_CONTINUE;
13967}
13968
2c809f8f 13969Expression*
13970Type_guard_expression::do_flatten(Gogo*, Named_object*,
13971 Statement_inserter* inserter)
13972{
5bf8be8b 13973 if (this->expr_->is_error_expression()
13974 || this->expr_->type()->is_error_type())
13975 {
13976 go_assert(saw_errors());
13977 return Expression::make_error(this->location());
13978 }
13979
2c809f8f 13980 if (!this->expr_->is_variable())
13981 {
13982 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13983 this->location());
13984 inserter->insert(temp);
13985 this->expr_ =
13986 Expression::make_temporary_reference(temp, this->location());
13987 }
13988 return this;
13989}
13990
e440a328 13991// Check types of a type guard expression. The expression must have
13992// an interface type, but the actual type conversion is checked at run
13993// time.
13994
13995void
13996Type_guard_expression::do_check_types(Gogo*)
13997{
e440a328 13998 Type* expr_type = this->expr_->type();
7e9da23f 13999 if (expr_type->interface_type() == NULL)
f725ade8 14000 {
5c13bd80 14001 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 14002 this->report_error(_("type assertion only valid for interface types"));
14003 this->set_is_error();
14004 }
e440a328 14005 else if (this->type_->interface_type() == NULL)
14006 {
14007 std::string reason;
14008 if (!expr_type->interface_type()->implements_interface(this->type_,
14009 &reason))
14010 {
5c13bd80 14011 if (!this->type_->is_error())
e440a328 14012 {
f725ade8 14013 if (reason.empty())
14014 this->report_error(_("impossible type assertion: "
14015 "type does not implement interface"));
14016 else
631d5788 14017 go_error_at(this->location(),
14018 ("impossible type assertion: "
14019 "type does not implement interface (%s)"),
14020 reason.c_str());
e440a328 14021 }
f725ade8 14022 this->set_is_error();
e440a328 14023 }
14024 }
14025}
14026
ea664253 14027// Return the backend representation for a type guard expression.
e440a328 14028
ea664253 14029Bexpression*
14030Type_guard_expression::do_get_backend(Translate_context* context)
e440a328 14031{
2c809f8f 14032 Expression* conversion;
7e9da23f 14033 if (this->type_->interface_type() != NULL)
2c809f8f 14034 conversion =
14035 Expression::convert_interface_to_interface(this->type_, this->expr_,
14036 true, this->location());
e440a328 14037 else
2c809f8f 14038 conversion =
14039 Expression::convert_for_assignment(context->gogo(), this->type_,
14040 this->expr_, this->location());
14041
ea664253 14042 return conversion->get_backend(context);
e440a328 14043}
14044
d751bb78 14045// Dump ast representation for a type guard expression.
14046
14047void
2c809f8f 14048Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 14049 const
14050{
14051 this->expr_->dump_expression(ast_dump_context);
14052 ast_dump_context->ostream() << ".";
14053 ast_dump_context->dump_type(this->type_);
14054}
14055
e440a328 14056// Make a type guard expression.
14057
14058Expression*
14059Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 14060 Location location)
e440a328 14061{
14062 return new Type_guard_expression(expr, type, location);
14063}
14064
2c809f8f 14065// Class Heap_expression.
e440a328 14066
da244e59 14067// Return the type of the expression stored on the heap.
e440a328 14068
da244e59 14069Type*
14070Heap_expression::do_type()
14071{ return Type::make_pointer_type(this->expr_->type()); }
e440a328 14072
ea664253 14073// Return the backend representation for allocating an expression on the heap.
e440a328 14074
ea664253 14075Bexpression*
14076Heap_expression::do_get_backend(Translate_context* context)
e440a328 14077{
02c19a1a 14078 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
ea664253 14079 return context->backend()->error_expression();
2c809f8f 14080
02c19a1a 14081 Location loc = this->location();
2c809f8f 14082 Gogo* gogo = context->gogo();
02c19a1a 14083 Btype* btype = this->type()->get_backend(gogo);
45ff893b 14084
14085 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
14086 Node* n = Node::make_node(this);
14087 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
14088 alloc->allocation_expression()->set_allocate_on_stack();
14089 Bexpression* space = alloc->get_backend(context);
02c19a1a 14090
14091 Bstatement* decl;
14092 Named_object* fn = context->function();
14093 go_assert(fn != NULL);
14094 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14095 Bvariable* space_temp =
14096 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14097 space, true, loc, &decl);
14098 space = gogo->backend()->var_expression(space_temp, loc);
9b27b43c 14099 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
14100 Bexpression* ref =
14101 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
02c19a1a 14102
ea664253 14103 Bexpression* bexpr = this->expr_->get_backend(context);
02c19a1a 14104 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
14105 decl = gogo->backend()->compound_statement(decl, assn);
14106 space = gogo->backend()->var_expression(space_temp, loc);
ea664253 14107 return gogo->backend()->compound_expression(decl, space, loc);
e440a328 14108}
14109
2c809f8f 14110// Dump ast representation for a heap expression.
d751bb78 14111
14112void
2c809f8f 14113Heap_expression::do_dump_expression(
d751bb78 14114 Ast_dump_context* ast_dump_context) const
14115{
14116 ast_dump_context->ostream() << "&(";
14117 ast_dump_context->dump_expression(this->expr_);
14118 ast_dump_context->ostream() << ")";
14119}
14120
2c809f8f 14121// Allocate an expression on the heap.
e440a328 14122
14123Expression*
2c809f8f 14124Expression::make_heap_expression(Expression* expr, Location location)
e440a328 14125{
2c809f8f 14126 return new Heap_expression(expr, location);
e440a328 14127}
14128
14129// Class Receive_expression.
14130
14131// Return the type of a receive expression.
14132
14133Type*
14134Receive_expression::do_type()
14135{
e429e3bd 14136 if (this->is_error_expression())
14137 return Type::make_error_type();
e440a328 14138 Channel_type* channel_type = this->channel_->type()->channel_type();
14139 if (channel_type == NULL)
e429e3bd 14140 {
14141 this->report_error(_("expected channel"));
14142 return Type::make_error_type();
14143 }
e440a328 14144 return channel_type->element_type();
14145}
14146
14147// Check types for a receive expression.
14148
14149void
14150Receive_expression::do_check_types(Gogo*)
14151{
14152 Type* type = this->channel_->type();
5c13bd80 14153 if (type->is_error())
e440a328 14154 {
e429e3bd 14155 go_assert(saw_errors());
e440a328 14156 this->set_is_error();
14157 return;
14158 }
14159 if (type->channel_type() == NULL)
14160 {
14161 this->report_error(_("expected channel"));
14162 return;
14163 }
14164 if (!type->channel_type()->may_receive())
14165 {
14166 this->report_error(_("invalid receive on send-only channel"));
14167 return;
14168 }
14169}
14170
2c809f8f 14171// Flattening for receive expressions creates a temporary variable to store
14172// received data in for receives.
14173
14174Expression*
14175Receive_expression::do_flatten(Gogo*, Named_object*,
14176 Statement_inserter* inserter)
14177{
14178 Channel_type* channel_type = this->channel_->type()->channel_type();
14179 if (channel_type == NULL)
14180 {
14181 go_assert(saw_errors());
14182 return this;
14183 }
5bf8be8b 14184 else if (this->channel_->is_error_expression())
14185 {
14186 go_assert(saw_errors());
14187 return Expression::make_error(this->location());
14188 }
2c809f8f 14189
14190 Type* element_type = channel_type->element_type();
14191 if (this->temp_receiver_ == NULL)
14192 {
14193 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14194 this->location());
14195 this->temp_receiver_->set_is_address_taken();
14196 inserter->insert(this->temp_receiver_);
14197 }
14198
14199 return this;
14200}
14201
ea664253 14202// Get the backend representation for a receive expression.
e440a328 14203
ea664253 14204Bexpression*
14205Receive_expression::do_get_backend(Translate_context* context)
e440a328 14206{
f24f10bb 14207 Location loc = this->location();
14208
e440a328 14209 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 14210 if (channel_type == NULL)
14211 {
c484d925 14212 go_assert(this->channel_->type()->is_error());
ea664253 14213 return context->backend()->error_expression();
5b8368f4 14214 }
f24f10bb 14215 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 14216
2c809f8f 14217 Expression* recv_ref =
14218 Expression::make_temporary_reference(this->temp_receiver_, loc);
14219 Expression* recv_addr =
14220 Expression::make_temporary_reference(this->temp_receiver_, loc);
14221 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
132ed071 14222 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 3,
14223 td, this->channel_, recv_addr);
ea664253 14224 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
e440a328 14225}
14226
d751bb78 14227// Dump ast representation for a receive expression.
14228
14229void
14230Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14231{
14232 ast_dump_context->ostream() << " <- " ;
14233 ast_dump_context->dump_expression(channel_);
14234}
14235
e440a328 14236// Make a receive expression.
14237
14238Receive_expression*
b13c66cd 14239Expression::make_receive(Expression* channel, Location location)
e440a328 14240{
14241 return new Receive_expression(channel, location);
14242}
14243
e440a328 14244// An expression which evaluates to a pointer to the type descriptor
14245// of a type.
14246
14247class Type_descriptor_expression : public Expression
14248{
14249 public:
b13c66cd 14250 Type_descriptor_expression(Type* type, Location location)
e440a328 14251 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14252 type_(type)
14253 { }
14254
14255 protected:
4b686186 14256 int
14257 do_traverse(Traverse*);
14258
e440a328 14259 Type*
14260 do_type()
14261 { return Type::make_type_descriptor_ptr_type(); }
14262
f9ca30f9 14263 bool
3ae06f68 14264 do_is_static_initializer() const
f9ca30f9 14265 { return true; }
14266
e440a328 14267 void
14268 do_determine_type(const Type_context*)
14269 { }
14270
14271 Expression*
14272 do_copy()
14273 { return this; }
14274
ea664253 14275 Bexpression*
14276 do_get_backend(Translate_context* context)
a1d23b41 14277 {
ea664253 14278 return this->type_->type_descriptor_pointer(context->gogo(),
14279 this->location());
a1d23b41 14280 }
e440a328 14281
d751bb78 14282 void
14283 do_dump_expression(Ast_dump_context*) const;
14284
e440a328 14285 private:
14286 // The type for which this is the descriptor.
14287 Type* type_;
14288};
14289
4b686186 14290int
14291Type_descriptor_expression::do_traverse(Traverse* traverse)
14292{
14293 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14294 return TRAVERSE_EXIT;
14295 return TRAVERSE_CONTINUE;
14296}
14297
d751bb78 14298// Dump ast representation for a type descriptor expression.
14299
14300void
14301Type_descriptor_expression::do_dump_expression(
14302 Ast_dump_context* ast_dump_context) const
14303{
14304 ast_dump_context->dump_type(this->type_);
14305}
14306
e440a328 14307// Make a type descriptor expression.
14308
14309Expression*
b13c66cd 14310Expression::make_type_descriptor(Type* type, Location location)
e440a328 14311{
14312 return new Type_descriptor_expression(type, location);
14313}
14314
aa5ae575 14315// An expression which evaluates to a pointer to the Garbage Collection symbol
14316// of a type.
14317
14318class GC_symbol_expression : public Expression
14319{
14320 public:
14321 GC_symbol_expression(Type* type)
14322 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14323 type_(type)
14324 {}
14325
14326 protected:
14327 Type*
14328 do_type()
23d77f91 14329 { return Type::lookup_integer_type("uintptr"); }
aa5ae575 14330
14331 bool
3ae06f68 14332 do_is_static_initializer() const
aa5ae575 14333 { return true; }
14334
14335 void
14336 do_determine_type(const Type_context*)
14337 { }
14338
14339 Expression*
14340 do_copy()
14341 { return this; }
14342
14343 Bexpression*
14344 do_get_backend(Translate_context* context)
14345 { return this->type_->gc_symbol_pointer(context->gogo()); }
14346
14347 void
14348 do_dump_expression(Ast_dump_context*) const;
14349
14350 private:
14351 // The type which this gc symbol describes.
14352 Type* type_;
14353};
14354
14355// Dump ast representation for a gc symbol expression.
14356
14357void
14358GC_symbol_expression::do_dump_expression(
14359 Ast_dump_context* ast_dump_context) const
14360{
14361 ast_dump_context->ostream() << "gcdata(";
14362 ast_dump_context->dump_type(this->type_);
14363 ast_dump_context->ostream() << ")";
14364}
14365
14366// Make a gc symbol expression.
14367
14368Expression*
14369Expression::make_gc_symbol(Type* type)
14370{
14371 return new GC_symbol_expression(type);
14372}
14373
e440a328 14374// An expression which evaluates to some characteristic of a type.
14375// This is only used to initialize fields of a type descriptor. Using
14376// a new expression class is slightly inefficient but gives us a good
14377// separation between the frontend and the middle-end with regard to
14378// how types are laid out.
14379
14380class Type_info_expression : public Expression
14381{
14382 public:
14383 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 14384 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 14385 type_(type), type_info_(type_info)
14386 { }
14387
14388 protected:
0e168074 14389 bool
3ae06f68 14390 do_is_static_initializer() const
0e168074 14391 { return true; }
14392
e440a328 14393 Type*
14394 do_type();
14395
14396 void
14397 do_determine_type(const Type_context*)
14398 { }
14399
14400 Expression*
14401 do_copy()
14402 { return this; }
14403
ea664253 14404 Bexpression*
14405 do_get_backend(Translate_context* context);
e440a328 14406
d751bb78 14407 void
14408 do_dump_expression(Ast_dump_context*) const;
14409
e440a328 14410 private:
14411 // The type for which we are getting information.
14412 Type* type_;
14413 // What information we want.
14414 Type_info type_info_;
14415};
14416
14417// The type is chosen to match what the type descriptor struct
14418// expects.
14419
14420Type*
14421Type_info_expression::do_type()
14422{
14423 switch (this->type_info_)
14424 {
14425 case TYPE_INFO_SIZE:
14426 return Type::lookup_integer_type("uintptr");
14427 case TYPE_INFO_ALIGNMENT:
14428 case TYPE_INFO_FIELD_ALIGNMENT:
14429 return Type::lookup_integer_type("uint8");
14430 default:
c3e6f413 14431 go_unreachable();
e440a328 14432 }
14433}
14434
ea664253 14435// Return the backend representation for type information.
e440a328 14436
ea664253 14437Bexpression*
14438Type_info_expression::do_get_backend(Translate_context* context)
e440a328 14439{
927a01eb 14440 Gogo* gogo = context->gogo();
2a305b85 14441 bool ok = true;
3f378015 14442 int64_t val;
927a01eb 14443 switch (this->type_info_)
e440a328 14444 {
927a01eb 14445 case TYPE_INFO_SIZE:
2a305b85 14446 ok = this->type_->backend_type_size(gogo, &val);
927a01eb 14447 break;
14448 case TYPE_INFO_ALIGNMENT:
2a305b85 14449 ok = this->type_->backend_type_align(gogo, &val);
927a01eb 14450 break;
14451 case TYPE_INFO_FIELD_ALIGNMENT:
2a305b85 14452 ok = this->type_->backend_type_field_align(gogo, &val);
927a01eb 14453 break;
14454 default:
14455 go_unreachable();
e440a328 14456 }
2a305b85 14457 if (!ok)
14458 {
14459 go_assert(saw_errors());
14460 return gogo->backend()->error_expression();
14461 }
3f378015 14462 Expression* e = Expression::make_integer_int64(val, this->type(),
14463 this->location());
14464 return e->get_backend(context);
e440a328 14465}
14466
d751bb78 14467// Dump ast representation for a type info expression.
14468
14469void
14470Type_info_expression::do_dump_expression(
14471 Ast_dump_context* ast_dump_context) const
14472{
14473 ast_dump_context->ostream() << "typeinfo(";
14474 ast_dump_context->dump_type(this->type_);
14475 ast_dump_context->ostream() << ",";
14476 ast_dump_context->ostream() <<
14477 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14478 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14479 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14480 : "unknown");
14481 ast_dump_context->ostream() << ")";
14482}
14483
e440a328 14484// Make a type info expression.
14485
14486Expression*
14487Expression::make_type_info(Type* type, Type_info type_info)
14488{
14489 return new Type_info_expression(type, type_info);
14490}
14491
35a54f17 14492// An expression that evaluates to some characteristic of a slice.
14493// This is used when indexing, bound-checking, or nil checking a slice.
14494
14495class Slice_info_expression : public Expression
14496{
14497 public:
14498 Slice_info_expression(Expression* slice, Slice_info slice_info,
14499 Location location)
14500 : Expression(EXPRESSION_SLICE_INFO, location),
14501 slice_(slice), slice_info_(slice_info)
14502 { }
14503
14504 protected:
14505 Type*
14506 do_type();
14507
14508 void
14509 do_determine_type(const Type_context*)
14510 { }
14511
14512 Expression*
14513 do_copy()
14514 {
14515 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14516 this->location());
14517 }
14518
ea664253 14519 Bexpression*
14520 do_get_backend(Translate_context* context);
35a54f17 14521
14522 void
14523 do_dump_expression(Ast_dump_context*) const;
14524
14525 void
14526 do_issue_nil_check()
14527 { this->slice_->issue_nil_check(); }
14528
14529 private:
14530 // The slice for which we are getting information.
14531 Expression* slice_;
14532 // What information we want.
14533 Slice_info slice_info_;
14534};
14535
14536// Return the type of the slice info.
14537
14538Type*
14539Slice_info_expression::do_type()
14540{
14541 switch (this->slice_info_)
14542 {
14543 case SLICE_INFO_VALUE_POINTER:
14544 return Type::make_pointer_type(
14545 this->slice_->type()->array_type()->element_type());
14546 case SLICE_INFO_LENGTH:
14547 case SLICE_INFO_CAPACITY:
14548 return Type::lookup_integer_type("int");
14549 default:
14550 go_unreachable();
14551 }
14552}
14553
ea664253 14554// Return the backend information for slice information.
35a54f17 14555
ea664253 14556Bexpression*
14557Slice_info_expression::do_get_backend(Translate_context* context)
35a54f17 14558{
14559 Gogo* gogo = context->gogo();
ea664253 14560 Bexpression* bslice = this->slice_->get_backend(context);
35a54f17 14561 switch (this->slice_info_)
14562 {
14563 case SLICE_INFO_VALUE_POINTER:
14564 case SLICE_INFO_LENGTH:
14565 case SLICE_INFO_CAPACITY:
ea664253 14566 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14567 this->location());
35a54f17 14568 break;
14569 default:
14570 go_unreachable();
14571 }
35a54f17 14572}
14573
14574// Dump ast representation for a type info expression.
14575
14576void
14577Slice_info_expression::do_dump_expression(
14578 Ast_dump_context* ast_dump_context) const
14579{
14580 ast_dump_context->ostream() << "sliceinfo(";
14581 this->slice_->dump_expression(ast_dump_context);
14582 ast_dump_context->ostream() << ",";
14583 ast_dump_context->ostream() <<
14584 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14585 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14586 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14587 : "unknown");
14588 ast_dump_context->ostream() << ")";
14589}
14590
14591// Make a slice info expression.
14592
14593Expression*
14594Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14595 Location location)
14596{
14597 return new Slice_info_expression(slice, slice_info, location);
14598}
14599
2c809f8f 14600// An expression that represents a slice value: a struct with value pointer,
14601// length, and capacity fields.
14602
14603class Slice_value_expression : public Expression
14604{
14605 public:
14606 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14607 Expression* cap, Location location)
14608 : Expression(EXPRESSION_SLICE_VALUE, location),
14609 type_(type), valptr_(valptr), len_(len), cap_(cap)
14610 { }
14611
14612 protected:
14613 int
14614 do_traverse(Traverse*);
14615
14616 Type*
14617 do_type()
14618 { return this->type_; }
14619
14620 void
14621 do_determine_type(const Type_context*)
14622 { go_unreachable(); }
14623
14624 Expression*
14625 do_copy()
14626 {
14627 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14628 this->len_->copy(), this->cap_->copy(),
14629 this->location());
14630 }
14631
ea664253 14632 Bexpression*
14633 do_get_backend(Translate_context* context);
2c809f8f 14634
14635 void
14636 do_dump_expression(Ast_dump_context*) const;
14637
14638 private:
14639 // The type of the slice value.
14640 Type* type_;
14641 // The pointer to the values in the slice.
14642 Expression* valptr_;
14643 // The length of the slice.
14644 Expression* len_;
14645 // The capacity of the slice.
14646 Expression* cap_;
14647};
14648
14649int
14650Slice_value_expression::do_traverse(Traverse* traverse)
14651{
55e8ba6a 14652 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14653 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2c809f8f 14654 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14655 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14656 return TRAVERSE_EXIT;
14657 return TRAVERSE_CONTINUE;
14658}
14659
ea664253 14660Bexpression*
14661Slice_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14662{
14663 std::vector<Bexpression*> vals(3);
ea664253 14664 vals[0] = this->valptr_->get_backend(context);
14665 vals[1] = this->len_->get_backend(context);
14666 vals[2] = this->cap_->get_backend(context);
2c809f8f 14667
14668 Gogo* gogo = context->gogo();
14669 Btype* btype = this->type_->get_backend(gogo);
ea664253 14670 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14671}
14672
14673void
14674Slice_value_expression::do_dump_expression(
14675 Ast_dump_context* ast_dump_context) const
14676{
14677 ast_dump_context->ostream() << "slicevalue(";
14678 ast_dump_context->ostream() << "values: ";
14679 this->valptr_->dump_expression(ast_dump_context);
14680 ast_dump_context->ostream() << ", length: ";
14681 this->len_->dump_expression(ast_dump_context);
14682 ast_dump_context->ostream() << ", capacity: ";
14683 this->cap_->dump_expression(ast_dump_context);
14684 ast_dump_context->ostream() << ")";
14685}
14686
14687Expression*
14688Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14689 Expression* cap, Location location)
14690{
14691 go_assert(at->is_slice_type());
14692 return new Slice_value_expression(at, valptr, len, cap, location);
14693}
2387f644 14694
14695// An expression that evaluates to some characteristic of a non-empty interface.
14696// This is used to access the method table or underlying object of an interface.
14697
14698class Interface_info_expression : public Expression
14699{
14700 public:
14701 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14702 Location location)
2387f644 14703 : Expression(EXPRESSION_INTERFACE_INFO, location),
14704 iface_(iface), iface_info_(iface_info)
14705 { }
14706
14707 protected:
14708 Type*
14709 do_type();
14710
14711 void
14712 do_determine_type(const Type_context*)
14713 { }
14714
14715 Expression*
14716 do_copy()
14717 {
14718 return new Interface_info_expression(this->iface_->copy(),
14719 this->iface_info_, this->location());
14720 }
14721
ea664253 14722 Bexpression*
14723 do_get_backend(Translate_context* context);
2387f644 14724
14725 void
14726 do_dump_expression(Ast_dump_context*) const;
14727
14728 void
14729 do_issue_nil_check()
14730 { this->iface_->issue_nil_check(); }
14731
14732 private:
14733 // The interface for which we are getting information.
14734 Expression* iface_;
14735 // What information we want.
14736 Interface_info iface_info_;
14737};
14738
14739// Return the type of the interface info.
14740
14741Type*
14742Interface_info_expression::do_type()
14743{
14744 switch (this->iface_info_)
14745 {
14746 case INTERFACE_INFO_METHODS:
14747 {
625d3118 14748 typedef Unordered_map(Interface_type*, Type*) Hashtable;
14749 static Hashtable result_types;
14750
14751 Interface_type* itype = this->iface_->type()->interface_type();
14752
14753 Hashtable::const_iterator p = result_types.find(itype);
14754 if (p != result_types.end())
14755 return p->second;
14756
2c809f8f 14757 Type* pdt = Type::make_type_descriptor_ptr_type();
625d3118 14758 if (itype->is_empty())
14759 {
14760 result_types[itype] = pdt;
14761 return pdt;
14762 }
2c809f8f 14763
2387f644 14764 Location loc = this->location();
14765 Struct_field_list* sfl = new Struct_field_list();
2387f644 14766 sfl->push_back(
14767 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14768
2387f644 14769 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14770 p != itype->methods()->end();
14771 ++p)
14772 {
14773 Function_type* ft = p->type()->function_type();
14774 go_assert(ft->receiver() == NULL);
14775
14776 const Typed_identifier_list* params = ft->parameters();
14777 Typed_identifier_list* mparams = new Typed_identifier_list();
14778 if (params != NULL)
14779 mparams->reserve(params->size() + 1);
14780 Type* vt = Type::make_pointer_type(Type::make_void_type());
14781 mparams->push_back(Typed_identifier("", vt, ft->location()));
14782 if (params != NULL)
14783 {
14784 for (Typed_identifier_list::const_iterator pp = params->begin();
14785 pp != params->end();
14786 ++pp)
14787 mparams->push_back(*pp);
14788 }
14789
14790 Typed_identifier_list* mresults = (ft->results() == NULL
14791 ? NULL
14792 : ft->results()->copy());
14793 Backend_function_type* mft =
14794 Type::make_backend_function_type(NULL, mparams, mresults,
14795 ft->location());
14796
14797 std::string fname = Gogo::unpack_hidden_name(p->name());
14798 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14799 }
14800
625d3118 14801 Pointer_type *pt = Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14802 result_types[itype] = pt;
14803 return pt;
2387f644 14804 }
14805 case INTERFACE_INFO_OBJECT:
14806 return Type::make_pointer_type(Type::make_void_type());
14807 default:
14808 go_unreachable();
14809 }
14810}
14811
ea664253 14812// Return the backend representation for interface information.
2387f644 14813
ea664253 14814Bexpression*
14815Interface_info_expression::do_get_backend(Translate_context* context)
2387f644 14816{
14817 Gogo* gogo = context->gogo();
ea664253 14818 Bexpression* biface = this->iface_->get_backend(context);
2387f644 14819 switch (this->iface_info_)
14820 {
14821 case INTERFACE_INFO_METHODS:
14822 case INTERFACE_INFO_OBJECT:
ea664253 14823 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14824 this->location());
2387f644 14825 break;
14826 default:
14827 go_unreachable();
14828 }
2387f644 14829}
14830
14831// Dump ast representation for an interface info expression.
14832
14833void
14834Interface_info_expression::do_dump_expression(
14835 Ast_dump_context* ast_dump_context) const
14836{
2c809f8f 14837 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14838 ast_dump_context->ostream() << "interfaceinfo(";
14839 this->iface_->dump_expression(ast_dump_context);
14840 ast_dump_context->ostream() << ",";
14841 ast_dump_context->ostream() <<
2c809f8f 14842 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14843 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14844 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14845 : "unknown");
14846 ast_dump_context->ostream() << ")";
14847}
14848
14849// Make an interface info expression.
14850
14851Expression*
14852Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14853 Location location)
14854{
14855 return new Interface_info_expression(iface, iface_info, location);
14856}
14857
2c809f8f 14858// An expression that represents an interface value. The first field is either
14859// a type descriptor for an empty interface or a pointer to the interface method
14860// table for a non-empty interface. The second field is always the object.
14861
14862class Interface_value_expression : public Expression
14863{
14864 public:
14865 Interface_value_expression(Type* type, Expression* first_field,
14866 Expression* obj, Location location)
14867 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14868 type_(type), first_field_(first_field), obj_(obj)
14869 { }
14870
14871 protected:
14872 int
14873 do_traverse(Traverse*);
14874
14875 Type*
14876 do_type()
14877 { return this->type_; }
14878
14879 void
14880 do_determine_type(const Type_context*)
14881 { go_unreachable(); }
14882
14883 Expression*
14884 do_copy()
14885 {
14886 return new Interface_value_expression(this->type_,
14887 this->first_field_->copy(),
14888 this->obj_->copy(), this->location());
14889 }
14890
ea664253 14891 Bexpression*
14892 do_get_backend(Translate_context* context);
2c809f8f 14893
14894 void
14895 do_dump_expression(Ast_dump_context*) const;
14896
14897 private:
14898 // The type of the interface value.
14899 Type* type_;
14900 // The first field of the interface (either a type descriptor or a pointer
14901 // to the method table.
14902 Expression* first_field_;
14903 // The underlying object of the interface.
14904 Expression* obj_;
14905};
14906
14907int
14908Interface_value_expression::do_traverse(Traverse* traverse)
14909{
14910 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14911 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14912 return TRAVERSE_EXIT;
14913 return TRAVERSE_CONTINUE;
14914}
14915
ea664253 14916Bexpression*
14917Interface_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14918{
14919 std::vector<Bexpression*> vals(2);
ea664253 14920 vals[0] = this->first_field_->get_backend(context);
14921 vals[1] = this->obj_->get_backend(context);
2c809f8f 14922
14923 Gogo* gogo = context->gogo();
14924 Btype* btype = this->type_->get_backend(gogo);
ea664253 14925 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14926}
14927
14928void
14929Interface_value_expression::do_dump_expression(
14930 Ast_dump_context* ast_dump_context) const
14931{
14932 ast_dump_context->ostream() << "interfacevalue(";
14933 ast_dump_context->ostream() <<
14934 (this->type_->interface_type()->is_empty()
14935 ? "type_descriptor: "
14936 : "methods: ");
14937 this->first_field_->dump_expression(ast_dump_context);
14938 ast_dump_context->ostream() << ", object: ";
14939 this->obj_->dump_expression(ast_dump_context);
14940 ast_dump_context->ostream() << ")";
14941}
14942
14943Expression*
14944Expression::make_interface_value(Type* type, Expression* first_value,
14945 Expression* object, Location location)
14946{
14947 return new Interface_value_expression(type, first_value, object, location);
14948}
14949
14950// An interface method table for a pair of types: an interface type and a type
14951// that implements that interface.
14952
14953class Interface_mtable_expression : public Expression
14954{
14955 public:
14956 Interface_mtable_expression(Interface_type* itype, Type* type,
14957 bool is_pointer, Location location)
14958 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14959 itype_(itype), type_(type), is_pointer_(is_pointer),
14960 method_table_type_(NULL), bvar_(NULL)
14961 { }
14962
14963 protected:
14964 int
14965 do_traverse(Traverse*);
14966
14967 Type*
14968 do_type();
14969
14970 bool
3ae06f68 14971 do_is_static_initializer() const
2c809f8f 14972 { return true; }
14973
14974 void
14975 do_determine_type(const Type_context*)
14976 { go_unreachable(); }
14977
14978 Expression*
14979 do_copy()
14980 {
14981 return new Interface_mtable_expression(this->itype_, this->type_,
14982 this->is_pointer_, this->location());
14983 }
14984
14985 bool
14986 do_is_addressable() const
14987 { return true; }
14988
ea664253 14989 Bexpression*
14990 do_get_backend(Translate_context* context);
2c809f8f 14991
14992 void
14993 do_dump_expression(Ast_dump_context*) const;
14994
14995 private:
14996 // The interface type for which the methods are defined.
14997 Interface_type* itype_;
14998 // The type to construct the interface method table for.
14999 Type* type_;
15000 // Whether this table contains the method set for the receiver type or the
15001 // pointer receiver type.
15002 bool is_pointer_;
15003 // The type of the method table.
15004 Type* method_table_type_;
15005 // The backend variable that refers to the interface method table.
15006 Bvariable* bvar_;
15007};
15008
15009int
15010Interface_mtable_expression::do_traverse(Traverse* traverse)
15011{
15012 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15013 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15014 return TRAVERSE_EXIT;
15015 return TRAVERSE_CONTINUE;
15016}
15017
15018Type*
15019Interface_mtable_expression::do_type()
15020{
15021 if (this->method_table_type_ != NULL)
15022 return this->method_table_type_;
15023
15024 const Typed_identifier_list* interface_methods = this->itype_->methods();
15025 go_assert(!interface_methods->empty());
15026
15027 Struct_field_list* sfl = new Struct_field_list;
15028 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15029 this->location());
15030 sfl->push_back(Struct_field(tid));
15031 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15032 p != interface_methods->end();
15033 ++p)
15034 sfl->push_back(Struct_field(*p));
15035 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
15036 return this->method_table_type_;
15037}
15038
ea664253 15039Bexpression*
15040Interface_mtable_expression::do_get_backend(Translate_context* context)
2c809f8f 15041{
15042 Gogo* gogo = context->gogo();
2c809f8f 15043 Location loc = Linemap::predeclared_location();
15044 if (this->bvar_ != NULL)
ea664253 15045 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 15046
15047 const Typed_identifier_list* interface_methods = this->itype_->methods();
15048 go_assert(!interface_methods->empty());
15049
15050 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
15051 + this->itype_->mangled_name(gogo)
15052 + "__"
15053 + this->type_->mangled_name(gogo));
15054
15055 // See whether this interface has any hidden methods.
15056 bool has_hidden_methods = false;
15057 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15058 p != interface_methods->end();
15059 ++p)
15060 {
15061 if (Gogo::is_hidden_name(p->name()))
15062 {
15063 has_hidden_methods = true;
15064 break;
15065 }
15066 }
15067
15068 // We already know that the named type is convertible to the
15069 // interface. If the interface has hidden methods, and the named
15070 // type is defined in a different package, then the interface
15071 // conversion table will be defined by that other package.
15072 if (has_hidden_methods
15073 && this->type_->named_type() != NULL
15074 && this->type_->named_type()->named_object()->package() != NULL)
15075 {
15076 Btype* btype = this->type()->get_backend(gogo);
15077 this->bvar_ =
15078 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
ea664253 15079 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 15080 }
15081
15082 // The first element is the type descriptor.
15083 Type* td_type;
15084 if (!this->is_pointer_)
15085 td_type = this->type_;
15086 else
15087 td_type = Type::make_pointer_type(this->type_);
15088
15089 // Build an interface method table for a type: a type descriptor followed by a
15090 // list of function pointers, one for each interface method. This is used for
15091 // interfaces.
15092 Expression_list* svals = new Expression_list();
15093 svals->push_back(Expression::make_type_descriptor(td_type, loc));
15094
15095 Named_type* nt = this->type_->named_type();
15096 Struct_type* st = this->type_->struct_type();
15097 go_assert(nt != NULL || st != NULL);
15098
15099 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15100 p != interface_methods->end();
15101 ++p)
15102 {
15103 bool is_ambiguous;
15104 Method* m;
15105 if (nt != NULL)
15106 m = nt->method_function(p->name(), &is_ambiguous);
15107 else
15108 m = st->method_function(p->name(), &is_ambiguous);
15109 go_assert(m != NULL);
15110 Named_object* no = m->named_object();
15111
15112 go_assert(no->is_function() || no->is_function_declaration());
15113 svals->push_back(Expression::make_func_code_reference(no, loc));
15114 }
15115
15116 Btype* btype = this->type()->get_backend(gogo);
15117 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
15118 svals, loc);
ea664253 15119 Bexpression* ctor = mtable->get_backend(context);
2c809f8f 15120
15121 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
15122 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
15123 !is_public, btype, loc);
15124 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15125 !is_public, btype, loc, ctor);
ea664253 15126 return gogo->backend()->var_expression(this->bvar_, loc);
2c809f8f 15127}
15128
15129void
15130Interface_mtable_expression::do_dump_expression(
15131 Ast_dump_context* ast_dump_context) const
15132{
15133 ast_dump_context->ostream() << "__go_"
15134 << (this->is_pointer_ ? "pimt__" : "imt_");
15135 ast_dump_context->dump_type(this->itype_);
15136 ast_dump_context->ostream() << "__";
15137 ast_dump_context->dump_type(this->type_);
15138}
15139
15140Expression*
15141Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15142 bool is_pointer, Location location)
15143{
15144 return new Interface_mtable_expression(itype, type, is_pointer, location);
15145}
15146
e440a328 15147// An expression which evaluates to the offset of a field within a
15148// struct. This, like Type_info_expression, q.v., is only used to
15149// initialize fields of a type descriptor.
15150
15151class Struct_field_offset_expression : public Expression
15152{
15153 public:
15154 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 15155 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15156 Linemap::predeclared_location()),
e440a328 15157 type_(type), field_(field)
15158 { }
15159
15160 protected:
f23d7786 15161 bool
3ae06f68 15162 do_is_static_initializer() const
f23d7786 15163 { return true; }
15164
e440a328 15165 Type*
15166 do_type()
15167 { return Type::lookup_integer_type("uintptr"); }
15168
15169 void
15170 do_determine_type(const Type_context*)
15171 { }
15172
15173 Expression*
15174 do_copy()
15175 { return this; }
15176
ea664253 15177 Bexpression*
15178 do_get_backend(Translate_context* context);
e440a328 15179
d751bb78 15180 void
15181 do_dump_expression(Ast_dump_context*) const;
15182
e440a328 15183 private:
15184 // The type of the struct.
15185 Struct_type* type_;
15186 // The field.
15187 const Struct_field* field_;
15188};
15189
ea664253 15190// Return the backend representation for a struct field offset.
e440a328 15191
ea664253 15192Bexpression*
15193Struct_field_offset_expression::do_get_backend(Translate_context* context)
e440a328 15194{
e440a328 15195 const Struct_field_list* fields = this->type_->fields();
e440a328 15196 Struct_field_list::const_iterator p;
2c8bda43 15197 unsigned i = 0;
e440a328 15198 for (p = fields->begin();
15199 p != fields->end();
2c8bda43 15200 ++p, ++i)
15201 if (&*p == this->field_)
15202 break;
c484d925 15203 go_assert(&*p == this->field_);
e440a328 15204
2c8bda43 15205 Gogo* gogo = context->gogo();
15206 Btype* btype = this->type_->get_backend(gogo);
15207
3f378015 15208 int64_t offset = gogo->backend()->type_field_offset(btype, i);
2c8bda43 15209 Type* uptr_type = Type::lookup_integer_type("uintptr");
e67508fa 15210 Expression* ret =
3f378015 15211 Expression::make_integer_int64(offset, uptr_type,
15212 Linemap::predeclared_location());
ea664253 15213 return ret->get_backend(context);
e440a328 15214}
15215
d751bb78 15216// Dump ast representation for a struct field offset expression.
15217
15218void
15219Struct_field_offset_expression::do_dump_expression(
15220 Ast_dump_context* ast_dump_context) const
15221{
15222 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 15223 ast_dump_context->dump_type(this->type_);
15224 ast_dump_context->ostream() << '.';
15225 ast_dump_context->ostream() <<
15226 Gogo::message_name(this->field_->field_name());
d751bb78 15227 ast_dump_context->ostream() << ")";
15228}
15229
e440a328 15230// Make an expression for a struct field offset.
15231
15232Expression*
15233Expression::make_struct_field_offset(Struct_type* type,
15234 const Struct_field* field)
15235{
15236 return new Struct_field_offset_expression(type, field);
15237}
15238
15239// An expression which evaluates to the address of an unnamed label.
15240
15241class Label_addr_expression : public Expression
15242{
15243 public:
b13c66cd 15244 Label_addr_expression(Label* label, Location location)
e440a328 15245 : Expression(EXPRESSION_LABEL_ADDR, location),
15246 label_(label)
15247 { }
15248
15249 protected:
15250 Type*
15251 do_type()
15252 { return Type::make_pointer_type(Type::make_void_type()); }
15253
15254 void
15255 do_determine_type(const Type_context*)
15256 { }
15257
15258 Expression*
15259 do_copy()
15260 { return new Label_addr_expression(this->label_, this->location()); }
15261
ea664253 15262 Bexpression*
15263 do_get_backend(Translate_context* context)
15264 { return this->label_->get_addr(context, this->location()); }
e440a328 15265
d751bb78 15266 void
15267 do_dump_expression(Ast_dump_context* ast_dump_context) const
15268 { ast_dump_context->ostream() << this->label_->name(); }
15269
e440a328 15270 private:
15271 // The label whose address we are taking.
15272 Label* label_;
15273};
15274
15275// Make an expression for the address of an unnamed label.
15276
15277Expression*
b13c66cd 15278Expression::make_label_addr(Label* label, Location location)
e440a328 15279{
15280 return new Label_addr_expression(label, location);
15281}
15282
da244e59 15283// Class Conditional_expression.
283a177b 15284
2c809f8f 15285// Traversal.
15286
15287int
15288Conditional_expression::do_traverse(Traverse* traverse)
15289{
15290 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15291 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15292 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15293 return TRAVERSE_EXIT;
15294 return TRAVERSE_CONTINUE;
15295}
15296
283a177b 15297// Return the type of the conditional expression.
15298
15299Type*
15300Conditional_expression::do_type()
15301{
15302 Type* result_type = Type::make_void_type();
2c809f8f 15303 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15304 NULL))
283a177b 15305 result_type = this->then_->type();
15306 else if (this->then_->is_nil_expression()
15307 || this->else_->is_nil_expression())
15308 result_type = (!this->then_->is_nil_expression()
15309 ? this->then_->type()
15310 : this->else_->type());
15311 return result_type;
15312}
15313
2c809f8f 15314// Determine type for a conditional expression.
15315
15316void
15317Conditional_expression::do_determine_type(const Type_context* context)
15318{
15319 this->cond_->determine_type_no_context();
15320 this->then_->determine_type(context);
15321 this->else_->determine_type(context);
15322}
15323
283a177b 15324// Get the backend representation of a conditional expression.
15325
ea664253 15326Bexpression*
15327Conditional_expression::do_get_backend(Translate_context* context)
283a177b 15328{
15329 Gogo* gogo = context->gogo();
15330 Btype* result_btype = this->type()->get_backend(gogo);
ea664253 15331 Bexpression* cond = this->cond_->get_backend(context);
15332 Bexpression* then = this->then_->get_backend(context);
15333 Bexpression* belse = this->else_->get_backend(context);
15334 return gogo->backend()->conditional_expression(result_btype, cond, then,
15335 belse, this->location());
283a177b 15336}
15337
15338// Dump ast representation of a conditional expression.
15339
15340void
15341Conditional_expression::do_dump_expression(
15342 Ast_dump_context* ast_dump_context) const
15343{
15344 ast_dump_context->ostream() << "(";
15345 ast_dump_context->dump_expression(this->cond_);
15346 ast_dump_context->ostream() << " ? ";
15347 ast_dump_context->dump_expression(this->then_);
15348 ast_dump_context->ostream() << " : ";
15349 ast_dump_context->dump_expression(this->else_);
15350 ast_dump_context->ostream() << ") ";
15351}
15352
15353// Make a conditional expression.
15354
15355Expression*
15356Expression::make_conditional(Expression* cond, Expression* then,
15357 Expression* else_expr, Location location)
15358{
15359 return new Conditional_expression(cond, then, else_expr, location);
15360}
15361
da244e59 15362// Class Compound_expression.
2c809f8f 15363
15364// Traversal.
15365
15366int
15367Compound_expression::do_traverse(Traverse* traverse)
15368{
15369 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15370 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15371 return TRAVERSE_EXIT;
15372 return TRAVERSE_CONTINUE;
15373}
15374
15375// Return the type of the compound expression.
15376
15377Type*
15378Compound_expression::do_type()
15379{
15380 return this->expr_->type();
15381}
15382
15383// Determine type for a compound expression.
15384
15385void
15386Compound_expression::do_determine_type(const Type_context* context)
15387{
15388 this->init_->determine_type_no_context();
15389 this->expr_->determine_type(context);
15390}
15391
15392// Get the backend representation of a compound expression.
15393
ea664253 15394Bexpression*
15395Compound_expression::do_get_backend(Translate_context* context)
2c809f8f 15396{
15397 Gogo* gogo = context->gogo();
ea664253 15398 Bexpression* binit = this->init_->get_backend(context);
2c809f8f 15399 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
ea664253 15400 Bexpression* bexpr = this->expr_->get_backend(context);
15401 return gogo->backend()->compound_expression(init_stmt, bexpr,
15402 this->location());
2c809f8f 15403}
15404
15405// Dump ast representation of a conditional expression.
15406
15407void
15408Compound_expression::do_dump_expression(
15409 Ast_dump_context* ast_dump_context) const
15410{
15411 ast_dump_context->ostream() << "(";
15412 ast_dump_context->dump_expression(this->init_);
15413 ast_dump_context->ostream() << ",";
15414 ast_dump_context->dump_expression(this->expr_);
15415 ast_dump_context->ostream() << ") ";
15416}
15417
15418// Make a compound expression.
15419
15420Expression*
15421Expression::make_compound(Expression* init, Expression* expr, Location location)
15422{
15423 return new Compound_expression(init, expr, location);
15424}
15425
e440a328 15426// Import an expression. This comes at the end in order to see the
15427// various class definitions.
15428
15429Expression*
15430Expression::import_expression(Import* imp)
15431{
15432 int c = imp->peek_char();
15433 if (imp->match_c_string("- ")
15434 || imp->match_c_string("! ")
15435 || imp->match_c_string("^ "))
15436 return Unary_expression::do_import(imp);
15437 else if (c == '(')
15438 return Binary_expression::do_import(imp);
15439 else if (imp->match_c_string("true")
15440 || imp->match_c_string("false"))
15441 return Boolean_expression::do_import(imp);
15442 else if (c == '"')
15443 return String_expression::do_import(imp);
15444 else if (c == '-' || (c >= '0' && c <= '9'))
15445 {
15446 // This handles integers, floats and complex constants.
15447 return Integer_expression::do_import(imp);
15448 }
15449 else if (imp->match_c_string("nil"))
15450 return Nil_expression::do_import(imp);
15451 else if (imp->match_c_string("convert"))
15452 return Type_conversion_expression::do_import(imp);
15453 else
15454 {
631d5788 15455 go_error_at(imp->location(), "import error: expected expression");
e440a328 15456 return Expression::make_error(imp->location());
15457 }
15458}
15459
15460// Class Expression_list.
15461
15462// Traverse the list.
15463
15464int
15465Expression_list::traverse(Traverse* traverse)
15466{
15467 for (Expression_list::iterator p = this->begin();
15468 p != this->end();
15469 ++p)
15470 {
15471 if (*p != NULL)
15472 {
15473 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15474 return TRAVERSE_EXIT;
15475 }
15476 }
15477 return TRAVERSE_CONTINUE;
15478}
15479
15480// Copy the list.
15481
15482Expression_list*
15483Expression_list::copy()
15484{
15485 Expression_list* ret = new Expression_list();
15486 for (Expression_list::iterator p = this->begin();
15487 p != this->end();
15488 ++p)
15489 {
15490 if (*p == NULL)
15491 ret->push_back(NULL);
15492 else
15493 ret->push_back((*p)->copy());
15494 }
15495 return ret;
15496}
15497
15498// Return whether an expression list has an error expression.
15499
15500bool
15501Expression_list::contains_error() const
15502{
15503 for (Expression_list::const_iterator p = this->begin();
15504 p != this->end();
15505 ++p)
15506 if (*p != NULL && (*p)->is_error_expression())
15507 return true;
15508 return false;
15509}
0c77715b 15510
15511// Class Numeric_constant.
15512
15513// Destructor.
15514
15515Numeric_constant::~Numeric_constant()
15516{
15517 this->clear();
15518}
15519
15520// Copy constructor.
15521
15522Numeric_constant::Numeric_constant(const Numeric_constant& a)
15523 : classification_(a.classification_), type_(a.type_)
15524{
15525 switch (a.classification_)
15526 {
15527 case NC_INVALID:
15528 break;
15529 case NC_INT:
15530 case NC_RUNE:
15531 mpz_init_set(this->u_.int_val, a.u_.int_val);
15532 break;
15533 case NC_FLOAT:
15534 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15535 break;
15536 case NC_COMPLEX:
fcbea5e4 15537 mpc_init2(this->u_.complex_val, mpc_precision);
15538 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15539 break;
15540 default:
15541 go_unreachable();
15542 }
15543}
15544
15545// Assignment operator.
15546
15547Numeric_constant&
15548Numeric_constant::operator=(const Numeric_constant& a)
15549{
15550 this->clear();
15551 this->classification_ = a.classification_;
15552 this->type_ = a.type_;
15553 switch (a.classification_)
15554 {
15555 case NC_INVALID:
15556 break;
15557 case NC_INT:
15558 case NC_RUNE:
15559 mpz_init_set(this->u_.int_val, a.u_.int_val);
15560 break;
15561 case NC_FLOAT:
15562 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15563 break;
15564 case NC_COMPLEX:
fcbea5e4 15565 mpc_init2(this->u_.complex_val, mpc_precision);
15566 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15567 break;
15568 default:
15569 go_unreachable();
15570 }
15571 return *this;
15572}
15573
15574// Clear the contents.
15575
15576void
15577Numeric_constant::clear()
15578{
15579 switch (this->classification_)
15580 {
15581 case NC_INVALID:
15582 break;
15583 case NC_INT:
15584 case NC_RUNE:
15585 mpz_clear(this->u_.int_val);
15586 break;
15587 case NC_FLOAT:
15588 mpfr_clear(this->u_.float_val);
15589 break;
15590 case NC_COMPLEX:
fcbea5e4 15591 mpc_clear(this->u_.complex_val);
0c77715b 15592 break;
15593 default:
15594 go_unreachable();
15595 }
15596 this->classification_ = NC_INVALID;
15597}
15598
15599// Set to an unsigned long value.
15600
15601void
15602Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15603{
15604 this->clear();
15605 this->classification_ = NC_INT;
15606 this->type_ = type;
15607 mpz_init_set_ui(this->u_.int_val, val);
15608}
15609
15610// Set to an integer value.
15611
15612void
15613Numeric_constant::set_int(Type* type, const mpz_t val)
15614{
15615 this->clear();
15616 this->classification_ = NC_INT;
15617 this->type_ = type;
15618 mpz_init_set(this->u_.int_val, val);
15619}
15620
15621// Set to a rune value.
15622
15623void
15624Numeric_constant::set_rune(Type* type, const mpz_t val)
15625{
15626 this->clear();
15627 this->classification_ = NC_RUNE;
15628 this->type_ = type;
15629 mpz_init_set(this->u_.int_val, val);
15630}
15631
15632// Set to a floating point value.
15633
15634void
15635Numeric_constant::set_float(Type* type, const mpfr_t val)
15636{
15637 this->clear();
15638 this->classification_ = NC_FLOAT;
15639 this->type_ = type;
833b523c 15640 // Numeric constants do not have negative zero values, so remove
15641 // them here. They also don't have infinity or NaN values, but we
15642 // should never see them here.
15643 if (mpfr_zero_p(val))
15644 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15645 else
15646 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15647}
15648
15649// Set to a complex value.
15650
15651void
fcbea5e4 15652Numeric_constant::set_complex(Type* type, const mpc_t val)
0c77715b 15653{
15654 this->clear();
15655 this->classification_ = NC_COMPLEX;
15656 this->type_ = type;
fcbea5e4 15657 mpc_init2(this->u_.complex_val, mpc_precision);
15658 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
0c77715b 15659}
15660
15661// Get an int value.
15662
15663void
15664Numeric_constant::get_int(mpz_t* val) const
15665{
15666 go_assert(this->is_int());
15667 mpz_init_set(*val, this->u_.int_val);
15668}
15669
15670// Get a rune value.
15671
15672void
15673Numeric_constant::get_rune(mpz_t* val) const
15674{
15675 go_assert(this->is_rune());
15676 mpz_init_set(*val, this->u_.int_val);
15677}
15678
15679// Get a floating point value.
15680
15681void
15682Numeric_constant::get_float(mpfr_t* val) const
15683{
15684 go_assert(this->is_float());
15685 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15686}
15687
15688// Get a complex value.
15689
15690void
fcbea5e4 15691Numeric_constant::get_complex(mpc_t* val) const
0c77715b 15692{
15693 go_assert(this->is_complex());
fcbea5e4 15694 mpc_init2(*val, mpc_precision);
15695 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15696}
15697
15698// Express value as unsigned long if possible.
15699
15700Numeric_constant::To_unsigned_long
15701Numeric_constant::to_unsigned_long(unsigned long* val) const
15702{
15703 switch (this->classification_)
15704 {
15705 case NC_INT:
15706 case NC_RUNE:
15707 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15708 case NC_FLOAT:
15709 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15710 case NC_COMPLEX:
fcbea5e4 15711 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15712 return NC_UL_NOTINT;
fcbea5e4 15713 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15714 val);
0c77715b 15715 default:
15716 go_unreachable();
15717 }
15718}
15719
15720// Express integer value as unsigned long if possible.
15721
15722Numeric_constant::To_unsigned_long
15723Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15724 unsigned long *val) const
15725{
15726 if (mpz_sgn(ival) < 0)
15727 return NC_UL_NEGATIVE;
15728 unsigned long ui = mpz_get_ui(ival);
15729 if (mpz_cmp_ui(ival, ui) != 0)
15730 return NC_UL_BIG;
15731 *val = ui;
15732 return NC_UL_VALID;
15733}
15734
15735// Express floating point value as unsigned long if possible.
15736
15737Numeric_constant::To_unsigned_long
15738Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15739 unsigned long *val) const
15740{
15741 if (!mpfr_integer_p(fval))
15742 return NC_UL_NOTINT;
15743 mpz_t ival;
15744 mpz_init(ival);
15745 mpfr_get_z(ival, fval, GMP_RNDN);
15746 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15747 mpz_clear(ival);
15748 return ret;
15749}
15750
15751// Convert value to integer if possible.
15752
15753bool
15754Numeric_constant::to_int(mpz_t* val) const
15755{
15756 switch (this->classification_)
15757 {
15758 case NC_INT:
15759 case NC_RUNE:
15760 mpz_init_set(*val, this->u_.int_val);
15761 return true;
15762 case NC_FLOAT:
15763 if (!mpfr_integer_p(this->u_.float_val))
15764 return false;
15765 mpz_init(*val);
15766 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15767 return true;
15768 case NC_COMPLEX:
fcbea5e4 15769 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15770 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
0c77715b 15771 return false;
15772 mpz_init(*val);
fcbea5e4 15773 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15774 return true;
15775 default:
15776 go_unreachable();
15777 }
15778}
15779
15780// Convert value to floating point if possible.
15781
15782bool
15783Numeric_constant::to_float(mpfr_t* val) const
15784{
15785 switch (this->classification_)
15786 {
15787 case NC_INT:
15788 case NC_RUNE:
15789 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15790 return true;
15791 case NC_FLOAT:
15792 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15793 return true;
15794 case NC_COMPLEX:
fcbea5e4 15795 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15796 return false;
fcbea5e4 15797 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15798 return true;
15799 default:
15800 go_unreachable();
15801 }
15802}
15803
15804// Convert value to complex.
15805
15806bool
fcbea5e4 15807Numeric_constant::to_complex(mpc_t* val) const
0c77715b 15808{
fcbea5e4 15809 mpc_init2(*val, mpc_precision);
0c77715b 15810 switch (this->classification_)
15811 {
15812 case NC_INT:
15813 case NC_RUNE:
fcbea5e4 15814 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
0c77715b 15815 return true;
15816 case NC_FLOAT:
fcbea5e4 15817 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
0c77715b 15818 return true;
15819 case NC_COMPLEX:
fcbea5e4 15820 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15821 return true;
15822 default:
15823 go_unreachable();
15824 }
15825}
15826
15827// Get the type.
15828
15829Type*
15830Numeric_constant::type() const
15831{
15832 if (this->type_ != NULL)
15833 return this->type_;
15834 switch (this->classification_)
15835 {
15836 case NC_INT:
15837 return Type::make_abstract_integer_type();
15838 case NC_RUNE:
15839 return Type::make_abstract_character_type();
15840 case NC_FLOAT:
15841 return Type::make_abstract_float_type();
15842 case NC_COMPLEX:
15843 return Type::make_abstract_complex_type();
15844 default:
15845 go_unreachable();
15846 }
15847}
15848
15849// If the constant can be expressed in TYPE, then set the type of the
15850// constant to TYPE and return true. Otherwise return false, and, if
15851// ISSUE_ERROR is true, report an appropriate error message.
15852
15853bool
15854Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15855{
15856 bool ret;
f11c2155 15857 if (type == NULL || type->is_error())
0c77715b 15858 ret = true;
15859 else if (type->integer_type() != NULL)
15860 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15861 else if (type->float_type() != NULL)
15862 ret = this->check_float_type(type->float_type(), issue_error, loc);
15863 else if (type->complex_type() != NULL)
15864 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15865 else
5706ab68 15866 {
15867 ret = false;
15868 if (issue_error)
15869 go_assert(saw_errors());
15870 }
0c77715b 15871 if (ret)
15872 this->type_ = type;
15873 return ret;
15874}
15875
15876// Check whether the constant can be expressed in an integer type.
15877
15878bool
15879Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
71a45216 15880 Location location)
0c77715b 15881{
15882 mpz_t val;
15883 switch (this->classification_)
15884 {
15885 case NC_INT:
15886 case NC_RUNE:
15887 mpz_init_set(val, this->u_.int_val);
15888 break;
15889
15890 case NC_FLOAT:
15891 if (!mpfr_integer_p(this->u_.float_val))
15892 {
15893 if (issue_error)
71a45216 15894 {
631d5788 15895 go_error_at(location,
15896 "floating point constant truncated to integer");
71a45216 15897 this->set_invalid();
15898 }
0c77715b 15899 return false;
15900 }
15901 mpz_init(val);
15902 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15903 break;
15904
15905 case NC_COMPLEX:
fcbea5e4 15906 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15907 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15908 {
15909 if (issue_error)
71a45216 15910 {
631d5788 15911 go_error_at(location, "complex constant truncated to integer");
71a45216 15912 this->set_invalid();
15913 }
0c77715b 15914 return false;
15915 }
15916 mpz_init(val);
fcbea5e4 15917 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15918 break;
15919
15920 default:
15921 go_unreachable();
15922 }
15923
15924 bool ret;
15925 if (type->is_abstract())
15926 ret = true;
15927 else
15928 {
15929 int bits = mpz_sizeinbase(val, 2);
15930 if (type->is_unsigned())
15931 {
15932 // For an unsigned type we can only accept a nonnegative
15933 // number, and we must be able to represents at least BITS.
15934 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15935 }
15936 else
15937 {
15938 // For a signed type we need an extra bit to indicate the
15939 // sign. We have to handle the most negative integer
15940 // specially.
15941 ret = (bits + 1 <= type->bits()
15942 || (bits <= type->bits()
15943 && mpz_sgn(val) < 0
15944 && (mpz_scan1(val, 0)
15945 == static_cast<unsigned long>(type->bits() - 1))
15946 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15947 }
15948 }
15949
15950 if (!ret && issue_error)
71a45216 15951 {
631d5788 15952 go_error_at(location, "integer constant overflow");
71a45216 15953 this->set_invalid();
15954 }
0c77715b 15955
15956 return ret;
15957}
15958
15959// Check whether the constant can be expressed in a floating point
15960// type.
15961
15962bool
15963Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15964 Location location)
0c77715b 15965{
15966 mpfr_t val;
15967 switch (this->classification_)
15968 {
15969 case NC_INT:
15970 case NC_RUNE:
15971 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15972 break;
15973
15974 case NC_FLOAT:
15975 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15976 break;
15977
15978 case NC_COMPLEX:
fcbea5e4 15979 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15980 {
15981 if (issue_error)
71a45216 15982 {
15983 this->set_invalid();
631d5788 15984 go_error_at(location, "complex constant truncated to float");
71a45216 15985 }
0c77715b 15986 return false;
15987 }
fcbea5e4 15988 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15989 break;
15990
15991 default:
15992 go_unreachable();
15993 }
15994
15995 bool ret;
15996 if (type->is_abstract())
15997 ret = true;
15998 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15999 {
16000 // A NaN or Infinity always fits in the range of the type.
16001 ret = true;
16002 }
16003 else
16004 {
16005 mp_exp_t exp = mpfr_get_exp(val);
16006 mp_exp_t max_exp;
16007 switch (type->bits())
16008 {
16009 case 32:
16010 max_exp = 128;
16011 break;
16012 case 64:
16013 max_exp = 1024;
16014 break;
16015 default:
16016 go_unreachable();
16017 }
16018
16019 ret = exp <= max_exp;
d0bcce51 16020
16021 if (ret)
16022 {
16023 // Round the constant to the desired type.
16024 mpfr_t t;
16025 mpfr_init(t);
16026 switch (type->bits())
16027 {
16028 case 32:
16029 mpfr_set_prec(t, 24);
16030 break;
16031 case 64:
16032 mpfr_set_prec(t, 53);
16033 break;
16034 default:
16035 go_unreachable();
16036 }
16037 mpfr_set(t, val, GMP_RNDN);
16038 mpfr_set(val, t, GMP_RNDN);
16039 mpfr_clear(t);
16040
16041 this->set_float(type, val);
16042 }
0c77715b 16043 }
16044
16045 mpfr_clear(val);
16046
16047 if (!ret && issue_error)
71a45216 16048 {
631d5788 16049 go_error_at(location, "floating point constant overflow");
71a45216 16050 this->set_invalid();
16051 }
0c77715b 16052
16053 return ret;
16054}
16055
16056// Check whether the constant can be expressed in a complex type.
16057
16058bool
16059Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 16060 Location location)
0c77715b 16061{
16062 if (type->is_abstract())
16063 return true;
16064
16065 mp_exp_t max_exp;
16066 switch (type->bits())
16067 {
16068 case 64:
16069 max_exp = 128;
16070 break;
16071 case 128:
16072 max_exp = 1024;
16073 break;
16074 default:
16075 go_unreachable();
16076 }
16077
fcbea5e4 16078 mpc_t val;
16079 mpc_init2(val, mpc_precision);
0c77715b 16080 switch (this->classification_)
16081 {
16082 case NC_INT:
16083 case NC_RUNE:
fcbea5e4 16084 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
0c77715b 16085 break;
16086
16087 case NC_FLOAT:
fcbea5e4 16088 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
0c77715b 16089 break;
16090
16091 case NC_COMPLEX:
fcbea5e4 16092 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
0c77715b 16093 break;
16094
16095 default:
16096 go_unreachable();
16097 }
16098
d0bcce51 16099 bool ret = true;
fcbea5e4 16100 if (!mpfr_nan_p(mpc_realref(val))
16101 && !mpfr_inf_p(mpc_realref(val))
16102 && !mpfr_zero_p(mpc_realref(val))
16103 && mpfr_get_exp(mpc_realref(val)) > max_exp)
d0bcce51 16104 {
16105 if (issue_error)
71a45216 16106 {
631d5788 16107 go_error_at(location, "complex real part overflow");
71a45216 16108 this->set_invalid();
16109 }
d0bcce51 16110 ret = false;
16111 }
0c77715b 16112
fcbea5e4 16113 if (!mpfr_nan_p(mpc_imagref(val))
16114 && !mpfr_inf_p(mpc_imagref(val))
16115 && !mpfr_zero_p(mpc_imagref(val))
16116 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
d0bcce51 16117 {
16118 if (issue_error)
71a45216 16119 {
631d5788 16120 go_error_at(location, "complex imaginary part overflow");
71a45216 16121 this->set_invalid();
16122 }
d0bcce51 16123 ret = false;
16124 }
0c77715b 16125
d0bcce51 16126 if (ret)
16127 {
16128 // Round the constant to the desired type.
fcbea5e4 16129 mpc_t t;
d0bcce51 16130 switch (type->bits())
16131 {
16132 case 64:
fcbea5e4 16133 mpc_init2(t, 24);
d0bcce51 16134 break;
16135 case 128:
fcbea5e4 16136 mpc_init2(t, 53);
d0bcce51 16137 break;
16138 default:
16139 go_unreachable();
16140 }
fcbea5e4 16141 mpc_set(t, val, MPC_RNDNN);
16142 mpc_set(val, t, MPC_RNDNN);
16143 mpc_clear(t);
d0bcce51 16144
fcbea5e4 16145 this->set_complex(type, val);
d0bcce51 16146 }
16147
fcbea5e4 16148 mpc_clear(val);
0c77715b 16149
16150 return ret;
16151}
16152
16153// Return an Expression for this value.
16154
16155Expression*
16156Numeric_constant::expression(Location loc) const
16157{
16158 switch (this->classification_)
16159 {
16160 case NC_INT:
e67508fa 16161 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
0c77715b 16162 case NC_RUNE:
16163 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16164 case NC_FLOAT:
16165 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16166 case NC_COMPLEX:
fcbea5e4 16167 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
71a45216 16168 case NC_INVALID:
16169 go_assert(saw_errors());
16170 return Expression::make_error(loc);
0c77715b 16171 default:
16172 go_unreachable();
16173 }
16174}