]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
2017-06-08 Alexander Ivchenko <alexander.ivchenko@intel.com>
[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"
438b4bec 14#include "go-encode-id.h"
e440a328 15#include "types.h"
16#include "export.h"
17#include "import.h"
18#include "statements.h"
19#include "lex.h"
a9182619 20#include "runtime.h"
6e193e6f 21#include "backend.h"
e440a328 22#include "expressions.h"
d751bb78 23#include "ast-dump.h"
e440a328 24
25// Class Expression.
26
27Expression::Expression(Expression_classification classification,
b13c66cd 28 Location location)
e440a328 29 : classification_(classification), location_(location)
30{
31}
32
33Expression::~Expression()
34{
35}
36
e440a328 37// Traverse the expressions.
38
39int
40Expression::traverse(Expression** pexpr, Traverse* traverse)
41{
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
44 {
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
50 }
51 return expr->do_traverse(traverse);
52}
53
54// Traverse subexpressions of this expression.
55
56int
57Expression::traverse_subexpressions(Traverse* traverse)
58{
59 return this->do_traverse(traverse);
60}
61
62// Default implementation for do_traverse for child classes.
63
64int
65Expression::do_traverse(Traverse*)
66{
67 return TRAVERSE_CONTINUE;
68}
69
70// This virtual function is called by the parser if the value of this
a7549a6a 71// expression is being discarded. By default, we give an error.
72// Expressions with side effects override.
e440a328 73
4f2138d7 74bool
e440a328 75Expression::do_discarding_value()
76{
a7549a6a 77 this->unused_value_error();
4f2138d7 78 return false;
e440a328 79}
80
81// This virtual function is called to export expressions. This will
82// only be used by expressions which may be constant.
83
84void
85Expression::do_export(Export*) const
86{
c3e6f413 87 go_unreachable();
e440a328 88}
89
a7549a6a 90// Give an error saying that the value of the expression is not used.
e440a328 91
92void
a7549a6a 93Expression::unused_value_error()
e440a328 94{
4f2138d7 95 this->report_error(_("value computed is not used"));
e440a328 96}
97
98// Note that this expression is an error. This is called by children
99// when they discover an error.
100
101void
102Expression::set_is_error()
103{
104 this->classification_ = EXPRESSION_ERROR;
105}
106
107// For children to call to report an error conveniently.
108
109void
110Expression::report_error(const char* msg)
111{
631d5788 112 go_error_at(this->location_, "%s", msg);
e440a328 113 this->set_is_error();
114}
115
116// Set types of variables and constants. This is implemented by the
117// child class.
118
119void
120Expression::determine_type(const Type_context* context)
121{
122 this->do_determine_type(context);
123}
124
125// Set types when there is no context.
126
127void
128Expression::determine_type_no_context()
129{
130 Type_context context;
131 this->do_determine_type(&context);
132}
133
2c809f8f 134// Return an expression handling any conversions which must be done during
e440a328 135// assignment.
136
2c809f8f 137Expression*
b4a33049 138Expression::convert_for_assignment(Gogo*, Type* lhs_type,
2c809f8f 139 Expression* rhs, Location location)
e440a328 140{
2c809f8f 141 Type* rhs_type = rhs->type();
142 if (lhs_type->is_error()
143 || rhs_type->is_error()
144 || rhs->is_error_expression())
145 return Expression::make_error(location);
e440a328 146
54211955 147 if (lhs_type->forwarded() != rhs_type->forwarded()
148 && lhs_type->interface_type() != NULL)
e440a328 149 {
150 if (rhs_type->interface_type() == NULL)
2c809f8f 151 return Expression::convert_type_to_interface(lhs_type, rhs, location);
e440a328 152 else
2c809f8f 153 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154 location);
e440a328 155 }
54211955 156 else if (lhs_type->forwarded() != rhs_type->forwarded()
157 && rhs_type->interface_type() != NULL)
2c809f8f 158 return Expression::convert_interface_to_type(lhs_type, rhs, location);
411eb89e 159 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 160 {
2c809f8f 161 // Assigning nil to a slice.
2c809f8f 162 Expression* nil = Expression::make_nil(location);
e67508fa 163 Expression* zero = Expression::make_integer_ul(0, NULL, location);
2c809f8f 164 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
e440a328 165 }
166 else if (rhs_type->is_nil_type())
2c809f8f 167 return Expression::make_nil(location);
168 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
e440a328 169 {
170 // No conversion is needed.
2c809f8f 171 return rhs;
172 }
173 else if (lhs_type->points_to() != NULL)
174 return Expression::make_unsafe_cast(lhs_type, rhs, location);
175 else if (lhs_type->is_numeric_type())
176 return Expression::make_cast(lhs_type, rhs, location);
177 else if ((lhs_type->struct_type() != NULL
178 && rhs_type->struct_type() != NULL)
179 || (lhs_type->array_type() != NULL
180 && rhs_type->array_type() != NULL))
e440a328 181 {
182 // This conversion must be permitted by Go, or we wouldn't have
183 // gotten here.
2c809f8f 184 return Expression::make_unsafe_cast(lhs_type, rhs, location);
e440a328 185 }
186 else
2c809f8f 187 return rhs;
e440a328 188}
189
2c809f8f 190// Return an expression for a conversion from a non-interface type to an
e440a328 191// interface type.
192
2c809f8f 193Expression*
194Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
195 Location location)
e440a328 196{
e440a328 197 Interface_type* lhs_interface_type = lhs_type->interface_type();
198 bool lhs_is_empty = lhs_interface_type->is_empty();
199
200 // Since RHS_TYPE is a static type, we can create the interface
201 // method table at compile time.
202
203 // When setting an interface to nil, we just set both fields to
204 // NULL.
2c809f8f 205 Type* rhs_type = rhs->type();
e440a328 206 if (rhs_type->is_nil_type())
63697958 207 {
2c809f8f 208 Expression* nil = Expression::make_nil(location);
209 return Expression::make_interface_value(lhs_type, nil, nil, location);
63697958 210 }
e440a328 211
212 // This should have been checked already.
c484d925 213 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 214
e440a328 215 // An interface is a tuple. If LHS_TYPE is an empty interface type,
216 // then the first field is the type descriptor for RHS_TYPE.
217 // Otherwise it is the interface method table for RHS_TYPE.
2c809f8f 218 Expression* first_field;
e440a328 219 if (lhs_is_empty)
2c809f8f 220 first_field = Expression::make_type_descriptor(rhs_type, location);
e440a328 221 else
222 {
223 // Build the interface method table for this interface and this
224 // object type: a list of function pointers for each interface
225 // method.
226 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 227 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 228 bool is_pointer = false;
c0cab2ec 229 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 230 {
231 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 232 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 233 is_pointer = true;
234 }
c0cab2ec 235 if (rhs_named_type != NULL)
2c809f8f 236 first_field =
237 rhs_named_type->interface_method_table(lhs_interface_type,
238 is_pointer);
c0cab2ec 239 else if (rhs_struct_type != NULL)
2c809f8f 240 first_field =
241 rhs_struct_type->interface_method_table(lhs_interface_type,
242 is_pointer);
c0cab2ec 243 else
2c809f8f 244 first_field = Expression::make_nil(location);
e440a328 245 }
e440a328 246
2c809f8f 247 Expression* obj;
e440a328 248 if (rhs_type->points_to() != NULL)
249 {
2c809f8f 250 // We are assigning a pointer to the interface; the interface
e440a328 251 // holds the pointer itself.
2c809f8f 252 obj = rhs;
253 }
254 else
255 {
256 // We are assigning a non-pointer value to the interface; the
45ff893b 257 // interface gets a copy of the value in the heap if it escapes.
258 // TODO(cmang): Associate escape state state of RHS with newly
259 // created OBJ.
2c809f8f 260 obj = Expression::make_heap_expression(rhs, location);
e440a328 261 }
262
2c809f8f 263 return Expression::make_interface_value(lhs_type, first_field, obj, location);
264}
e440a328 265
2c809f8f 266// Return an expression for the type descriptor of RHS.
e440a328 267
2c809f8f 268Expression*
269Expression::get_interface_type_descriptor(Expression* rhs)
270{
271 go_assert(rhs->type()->interface_type() != NULL);
272 Location location = rhs->location();
e440a328 273
2c809f8f 274 // The type descriptor is the first field of an empty interface.
275 if (rhs->type()->interface_type()->is_empty())
276 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
277 location);
278
279 Expression* mtable =
280 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
e440a328 281
2c809f8f 282 Expression* descriptor =
283 Expression::make_unary(OPERATOR_MULT, mtable, location);
284 descriptor = Expression::make_field_reference(descriptor, 0, location);
285 Expression* nil = Expression::make_nil(location);
e440a328 286
2c809f8f 287 Expression* eq =
288 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
289 return Expression::make_conditional(eq, nil, descriptor, location);
e440a328 290}
291
2c809f8f 292// Return an expression for the conversion of an interface type to an
e440a328 293// interface type.
294
2c809f8f 295Expression*
296Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
297 bool for_type_guard,
298 Location location)
e440a328 299{
8ba8cc87 300 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
301 return rhs;
302
e440a328 303 Interface_type* lhs_interface_type = lhs_type->interface_type();
304 bool lhs_is_empty = lhs_interface_type->is_empty();
305
e440a328 306 // In the general case this requires runtime examination of the type
307 // method table to match it up with the interface methods.
308
309 // FIXME: If all of the methods in the right hand side interface
310 // also appear in the left hand side interface, then we don't need
311 // to do a runtime check, although we still need to build a new
312 // method table.
313
8ba8cc87 314 // We are going to evaluate RHS multiple times.
315 go_assert(rhs->is_variable());
316
e440a328 317 // Get the type descriptor for the right hand side. This will be
318 // NULL for a nil interface.
2c809f8f 319 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
320 Expression* lhs_type_expr =
321 Expression::make_type_descriptor(lhs_type, location);
e440a328 322
2c809f8f 323 Expression* first_field;
e440a328 324 if (for_type_guard)
325 {
326 // A type assertion fails when converting a nil interface.
6098d6cb 327 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
328 lhs_type_expr, rhs_type_expr);
e440a328 329 }
330 else if (lhs_is_empty)
331 {
2c809f8f 332 // A conversion to an empty interface always succeeds, and the
e440a328 333 // first field is just the type descriptor of the object.
2c809f8f 334 first_field = rhs_type_expr;
e440a328 335 }
336 else
337 {
338 // A conversion to a non-empty interface may fail, but unlike a
339 // type assertion converting nil will always succeed.
6098d6cb 340 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
341 lhs_type_expr, rhs_type_expr);
e440a328 342 }
343
344 // The second field is simply the object pointer.
2c809f8f 345 Expression* obj =
346 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
347 return Expression::make_interface_value(lhs_type, first_field, obj, location);
e440a328 348}
349
2c809f8f 350// Return an expression for the conversion of an interface type to a
e440a328 351// non-interface type.
352
2c809f8f 353Expression*
354Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
355 Location location)
e440a328 356{
8ba8cc87 357 // We are going to evaluate RHS multiple times.
358 go_assert(rhs->is_variable());
359
e440a328 360 // Call a function to check that the type is valid. The function
361 // will panic with an appropriate runtime type error if the type is
362 // not valid.
2c809f8f 363 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
364 location);
365 Expression* rhs_descriptor =
366 Expression::get_interface_type_descriptor(rhs);
367
368 Type* rhs_type = rhs->type();
369 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
370 location);
371
6098d6cb 372 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
2c809f8f 373 location, 3, lhs_type_expr,
374 rhs_descriptor, rhs_inter_expr);
e440a328 375
376 // If the call succeeds, pull out the value.
2c809f8f 377 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
378 location);
e440a328 379
380 // If the value is a pointer, then it is the value we want.
381 // Otherwise it points to the value.
382 if (lhs_type->points_to() == NULL)
383 {
2c809f8f 384 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
385 location);
386 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
e440a328 387 }
2c809f8f 388 return Expression::make_compound(check_iface, obj, location);
e440a328 389}
390
ea664253 391// Convert an expression to its backend representation. This is implemented by
392// the child class. Not that it is not in general safe to call this multiple
e440a328 393// times for a single expression, but that we don't catch such errors.
394
ea664253 395Bexpression*
396Expression::get_backend(Translate_context* context)
e440a328 397{
398 // The child may have marked this expression as having an error.
399 if (this->classification_ == EXPRESSION_ERROR)
ea664253 400 return context->backend()->error_expression();
e440a328 401
ea664253 402 return this->do_get_backend(context);
e440a328 403}
404
48c2a53a 405// Return a backend expression for VAL.
406Bexpression*
407Expression::backend_numeric_constant_expression(Translate_context* context,
408 Numeric_constant* val)
e440a328 409{
48c2a53a 410 Gogo* gogo = context->gogo();
411 Type* type = val->type();
412 if (type == NULL)
413 return gogo->backend()->error_expression();
e440a328 414
48c2a53a 415 Btype* btype = type->get_backend(gogo);
416 Bexpression* ret;
417 if (type->integer_type() != NULL)
e440a328 418 {
419 mpz_t ival;
48c2a53a 420 if (!val->to_int(&ival))
421 {
422 go_assert(saw_errors());
423 return gogo->backend()->error_expression();
424 }
425 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 426 mpz_clear(ival);
e440a328 427 }
48c2a53a 428 else if (type->float_type() != NULL)
e440a328 429 {
48c2a53a 430 mpfr_t fval;
431 if (!val->to_float(&fval))
432 {
433 go_assert(saw_errors());
434 return gogo->backend()->error_expression();
435 }
436 ret = gogo->backend()->float_constant_expression(btype, fval);
437 mpfr_clear(fval);
e440a328 438 }
48c2a53a 439 else if (type->complex_type() != NULL)
e440a328 440 {
fcbea5e4 441 mpc_t cval;
442 if (!val->to_complex(&cval))
48c2a53a 443 {
444 go_assert(saw_errors());
445 return gogo->backend()->error_expression();
446 }
fcbea5e4 447 ret = gogo->backend()->complex_constant_expression(btype, cval);
448 mpc_clear(cval);
e440a328 449 }
450 else
c3e6f413 451 go_unreachable();
e440a328 452
48c2a53a 453 return ret;
e440a328 454}
455
2c809f8f 456// Return an expression which evaluates to true if VAL, of arbitrary integer
457// type, is negative or is more than the maximum value of the Go type "int".
e440a328 458
2c809f8f 459Expression*
460Expression::check_bounds(Expression* val, Location loc)
e440a328 461{
2c809f8f 462 Type* val_type = val->type();
463 Type* bound_type = Type::lookup_integer_type("int");
464
465 int val_type_size;
466 bool val_is_unsigned = false;
467 if (val_type->integer_type() != NULL)
468 {
469 val_type_size = val_type->integer_type()->bits();
470 val_is_unsigned = val_type->integer_type()->is_unsigned();
471 }
472 else
473 {
474 if (!val_type->is_numeric_type()
475 || !Type::are_convertible(bound_type, val_type, NULL))
476 {
477 go_assert(saw_errors());
478 return Expression::make_boolean(true, loc);
479 }
e440a328 480
2c809f8f 481 if (val_type->complex_type() != NULL)
482 val_type_size = val_type->complex_type()->bits();
483 else
484 val_type_size = val_type->float_type()->bits();
485 }
486
487 Expression* negative_index = Expression::make_boolean(false, loc);
488 Expression* index_overflows = Expression::make_boolean(false, loc);
489 if (!val_is_unsigned)
e440a328 490 {
e67508fa 491 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
2c809f8f 492 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
e440a328 493 }
494
2c809f8f 495 int bound_type_size = bound_type->integer_type()->bits();
c3068ac0 496 if (val_type_size > bound_type_size
497 || (val_type_size == bound_type_size
2c809f8f 498 && val_is_unsigned))
499 {
500 mpz_t one;
501 mpz_init_set_ui(one, 1UL);
502
503 // maxval = 2^(bound_type_size - 1) - 1
504 mpz_t maxval;
505 mpz_init(maxval);
506 mpz_mul_2exp(maxval, one, bound_type_size - 1);
507 mpz_sub_ui(maxval, maxval, 1);
e67508fa 508 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
2c809f8f 509 mpz_clear(one);
510 mpz_clear(maxval);
511
512 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
e440a328 513 }
514
2c809f8f 515 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
516 loc);
e440a328 517}
518
d751bb78 519void
520Expression::dump_expression(Ast_dump_context* ast_dump_context) const
521{
522 this->do_dump_expression(ast_dump_context);
523}
524
e440a328 525// Error expressions. This are used to avoid cascading errors.
526
527class Error_expression : public Expression
528{
529 public:
b13c66cd 530 Error_expression(Location location)
e440a328 531 : Expression(EXPRESSION_ERROR, location)
532 { }
533
534 protected:
535 bool
536 do_is_constant() const
537 { return true; }
538
539 bool
0c77715b 540 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 541 {
0c77715b 542 nc->set_unsigned_long(NULL, 0);
e440a328 543 return true;
544 }
545
4f2138d7 546 bool
e440a328 547 do_discarding_value()
4f2138d7 548 { return true; }
e440a328 549
550 Type*
551 do_type()
552 { return Type::make_error_type(); }
553
554 void
555 do_determine_type(const Type_context*)
556 { }
557
558 Expression*
559 do_copy()
560 { return this; }
561
562 bool
563 do_is_addressable() const
564 { return true; }
565
ea664253 566 Bexpression*
567 do_get_backend(Translate_context* context)
568 { return context->backend()->error_expression(); }
d751bb78 569
570 void
571 do_dump_expression(Ast_dump_context*) const;
e440a328 572};
573
d751bb78 574// Dump the ast representation for an error expression to a dump context.
575
576void
577Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
578{
579 ast_dump_context->ostream() << "_Error_" ;
580}
581
e440a328 582Expression*
b13c66cd 583Expression::make_error(Location location)
e440a328 584{
585 return new Error_expression(location);
586}
587
588// An expression which is really a type. This is used during parsing.
589// It is an error if these survive after lowering.
590
591class
592Type_expression : public Expression
593{
594 public:
b13c66cd 595 Type_expression(Type* type, Location location)
e440a328 596 : Expression(EXPRESSION_TYPE, location),
597 type_(type)
598 { }
599
600 protected:
601 int
602 do_traverse(Traverse* traverse)
603 { return Type::traverse(this->type_, traverse); }
604
605 Type*
606 do_type()
607 { return this->type_; }
608
609 void
610 do_determine_type(const Type_context*)
611 { }
612
613 void
614 do_check_types(Gogo*)
615 { this->report_error(_("invalid use of type")); }
616
617 Expression*
618 do_copy()
619 { return this; }
620
ea664253 621 Bexpression*
622 do_get_backend(Translate_context*)
c3e6f413 623 { go_unreachable(); }
e440a328 624
d751bb78 625 void do_dump_expression(Ast_dump_context*) const;
626
e440a328 627 private:
628 // The type which we are representing as an expression.
629 Type* type_;
630};
631
d751bb78 632void
633Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
634{
635 ast_dump_context->dump_type(this->type_);
636}
637
e440a328 638Expression*
b13c66cd 639Expression::make_type(Type* type, Location location)
e440a328 640{
641 return new Type_expression(type, location);
642}
643
e03bdf36 644// Class Parser_expression.
645
646Type*
647Parser_expression::do_type()
648{
649 // We should never really ask for the type of a Parser_expression.
650 // However, it can happen, at least when we have an invalid const
651 // whose initializer refers to the const itself. In that case we
652 // may ask for the type when lowering the const itself.
c484d925 653 go_assert(saw_errors());
e03bdf36 654 return Type::make_error_type();
655}
656
e440a328 657// Class Var_expression.
658
659// Lower a variable expression. Here we just make sure that the
660// initialization expression of the variable has been lowered. This
661// ensures that we will be able to determine the type of the variable
662// if necessary.
663
664Expression*
ceeb4318 665Var_expression::do_lower(Gogo* gogo, Named_object* function,
666 Statement_inserter* inserter, int)
e440a328 667{
668 if (this->variable_->is_variable())
669 {
670 Variable* var = this->variable_->var_value();
671 // This is either a local variable or a global variable. A
672 // reference to a variable which is local to an enclosing
673 // function will be a reference to a field in a closure.
674 if (var->is_global())
ceeb4318 675 {
676 function = NULL;
677 inserter = NULL;
678 }
679 var->lower_init_expression(gogo, function, inserter);
e440a328 680 }
681 return this;
682}
683
e440a328 684// Return the type of a reference to a variable.
685
686Type*
687Var_expression::do_type()
688{
689 if (this->variable_->is_variable())
690 return this->variable_->var_value()->type();
691 else if (this->variable_->is_result_variable())
692 return this->variable_->result_var_value()->type();
693 else
c3e6f413 694 go_unreachable();
e440a328 695}
696
0ab09e06 697// Determine the type of a reference to a variable.
698
699void
700Var_expression::do_determine_type(const Type_context*)
701{
702 if (this->variable_->is_variable())
703 this->variable_->var_value()->determine_type();
704}
705
e440a328 706// Something takes the address of this variable. This means that we
707// may want to move the variable onto the heap.
708
709void
710Var_expression::do_address_taken(bool escapes)
711{
712 if (!escapes)
f325319b 713 {
714 if (this->variable_->is_variable())
715 this->variable_->var_value()->set_non_escaping_address_taken();
716 else if (this->variable_->is_result_variable())
717 this->variable_->result_var_value()->set_non_escaping_address_taken();
718 else
719 go_unreachable();
720 }
e440a328 721 else
f325319b 722 {
723 if (this->variable_->is_variable())
724 this->variable_->var_value()->set_address_taken();
725 else if (this->variable_->is_result_variable())
726 this->variable_->result_var_value()->set_address_taken();
727 else
728 go_unreachable();
729 }
45ff893b 730
731 if (this->variable_->is_variable()
732 && this->variable_->var_value()->is_in_heap())
733 {
734 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
735 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
736 }
e440a328 737}
738
ea664253 739// Get the backend representation for a reference to a variable.
e440a328 740
ea664253 741Bexpression*
742Var_expression::do_get_backend(Translate_context* context)
e440a328 743{
fe2f84cf 744 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
745 context->function());
fe2f84cf 746 bool is_in_heap;
c6777780 747 Location loc = this->location();
9b27b43c 748 Btype* btype;
749 Gogo* gogo = context->gogo();
fe2f84cf 750 if (this->variable_->is_variable())
9b27b43c 751 {
752 is_in_heap = this->variable_->var_value()->is_in_heap();
753 btype = this->variable_->var_value()->type()->get_backend(gogo);
754 }
fe2f84cf 755 else if (this->variable_->is_result_variable())
9b27b43c 756 {
757 is_in_heap = this->variable_->result_var_value()->is_in_heap();
758 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
759 }
fe2f84cf 760 else
c3e6f413 761 go_unreachable();
c6777780 762
d4e6573e 763 Bexpression* ret =
764 context->backend()->var_expression(bvar, this->in_lvalue_pos_, loc);
fe2f84cf 765 if (is_in_heap)
9b27b43c 766 ret = context->backend()->indirect_expression(btype, ret, true, loc);
ea664253 767 return ret;
e440a328 768}
769
d751bb78 770// Ast dump for variable expression.
771
772void
773Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
774{
775 ast_dump_context->ostream() << this->variable_->name() ;
776}
777
e440a328 778// Make a reference to a variable in an expression.
779
780Expression*
b13c66cd 781Expression::make_var_reference(Named_object* var, Location location)
e440a328 782{
783 if (var->is_sink())
784 return Expression::make_sink(location);
785
786 // FIXME: Creating a new object for each reference to a variable is
787 // wasteful.
788 return new Var_expression(var, location);
789}
790
b0c09712 791// Class Enclosed_var_expression.
792
793int
794Enclosed_var_expression::do_traverse(Traverse*)
795{
796 return TRAVERSE_CONTINUE;
797}
798
799// Lower the reference to the enclosed variable.
800
801Expression*
802Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
803 Statement_inserter* inserter, int)
804{
805 gogo->lower_expression(function, inserter, &this->reference_);
806 return this;
807}
808
809// Flatten the reference to the enclosed variable.
810
811Expression*
812Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
813 Statement_inserter* inserter)
814{
815 gogo->flatten_expression(function, inserter, &this->reference_);
816 return this;
817}
818
819void
820Enclosed_var_expression::do_address_taken(bool escapes)
821{
822 if (!escapes)
823 {
824 if (this->variable_->is_variable())
825 this->variable_->var_value()->set_non_escaping_address_taken();
826 else if (this->variable_->is_result_variable())
827 this->variable_->result_var_value()->set_non_escaping_address_taken();
828 else
829 go_unreachable();
830 }
831 else
832 {
833 if (this->variable_->is_variable())
834 this->variable_->var_value()->set_address_taken();
835 else if (this->variable_->is_result_variable())
836 this->variable_->result_var_value()->set_address_taken();
837 else
838 go_unreachable();
839 }
45ff893b 840
841 if (this->variable_->is_variable()
842 && this->variable_->var_value()->is_in_heap())
843 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
b0c09712 844}
845
846// Ast dump for enclosed variable expression.
847
848void
849Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
850{
851 adc->ostream() << this->variable_->name();
852}
853
854// Make a reference to a variable within an enclosing function.
855
856Expression*
857Expression::make_enclosing_var_reference(Expression* reference,
858 Named_object* var, Location location)
859{
860 return new Enclosed_var_expression(reference, var, location);
861}
862
e440a328 863// Class Temporary_reference_expression.
864
865// The type.
866
867Type*
868Temporary_reference_expression::do_type()
869{
870 return this->statement_->type();
871}
872
873// Called if something takes the address of this temporary variable.
874// We never have to move temporary variables to the heap, but we do
875// need to know that they must live in the stack rather than in a
876// register.
877
878void
879Temporary_reference_expression::do_address_taken(bool)
880{
881 this->statement_->set_is_address_taken();
882}
883
ea664253 884// Get a backend expression referring to the variable.
e440a328 885
ea664253 886Bexpression*
887Temporary_reference_expression::do_get_backend(Translate_context* context)
e440a328 888{
cd440cff 889 Gogo* gogo = context->gogo();
eefc1ed3 890 Bvariable* bvar = this->statement_->get_backend_variable(context);
d4e6573e 891 Varexpr_context ve_ctxt = (this->is_lvalue_ ? VE_lvalue : VE_rvalue);
892
893 Bexpression* ret = gogo->backend()->var_expression(bvar, ve_ctxt,
894 this->location());
eefc1ed3 895
cd440cff 896 // The backend can't always represent the same set of recursive types
eefc1ed3 897 // that the Go frontend can. In some cases this means that a
898 // temporary variable won't have the right backend type. Correct
899 // that here by adding a type cast. We need to use base() to push
900 // the circularity down one level.
cd440cff 901 Type* stype = this->statement_->type();
ceeb4318 902 if (!this->is_lvalue_
03118c21 903 && stype->points_to() != NULL
904 && stype->points_to()->is_void_type())
eefc1ed3 905 {
cd440cff 906 Btype* btype = this->type()->base()->get_backend(gogo);
907 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 908 }
ea664253 909 return ret;
e440a328 910}
911
d751bb78 912// Ast dump for temporary reference.
913
914void
915Temporary_reference_expression::do_dump_expression(
916 Ast_dump_context* ast_dump_context) const
917{
918 ast_dump_context->dump_temp_variable_name(this->statement_);
919}
920
e440a328 921// Make a reference to a temporary variable.
922
ceeb4318 923Temporary_reference_expression*
e440a328 924Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 925 Location location)
e440a328 926{
927 return new Temporary_reference_expression(statement, location);
928}
929
e9d3367e 930// Class Set_and_use_temporary_expression.
931
932// Return the type.
933
934Type*
935Set_and_use_temporary_expression::do_type()
936{
937 return this->statement_->type();
938}
939
0afbb937 940// Determine the type of the expression.
941
942void
943Set_and_use_temporary_expression::do_determine_type(
944 const Type_context* context)
945{
946 this->expr_->determine_type(context);
947}
948
e9d3367e 949// Take the address.
950
951void
952Set_and_use_temporary_expression::do_address_taken(bool)
953{
954 this->statement_->set_is_address_taken();
955}
956
957// Return the backend representation.
958
ea664253 959Bexpression*
960Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
e9d3367e 961{
e9d3367e 962 Location loc = this->location();
a302c105 963 Gogo* gogo = context->gogo();
964 Bvariable* bvar = this->statement_->get_backend_variable(context);
d4e6573e 965 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, VE_rvalue, loc);
a302c105 966
0ab48656 967 Named_object* fn = context->function();
968 go_assert(fn != NULL);
969 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
ea664253 970 Bexpression* bexpr = this->expr_->get_backend(context);
0ab48656 971 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
972 bexpr, loc);
d4e6573e 973 Bexpression* var_ref = gogo->backend()->var_expression(bvar, VE_lvalue, loc);
a302c105 974 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
ea664253 975 return ret;
e9d3367e 976}
977
978// Dump.
979
980void
981Set_and_use_temporary_expression::do_dump_expression(
982 Ast_dump_context* ast_dump_context) const
983{
984 ast_dump_context->ostream() << '(';
985 ast_dump_context->dump_temp_variable_name(this->statement_);
986 ast_dump_context->ostream() << " = ";
987 this->expr_->dump_expression(ast_dump_context);
988 ast_dump_context->ostream() << ')';
989}
990
991// Make a set-and-use temporary.
992
993Set_and_use_temporary_expression*
994Expression::make_set_and_use_temporary(Temporary_statement* statement,
995 Expression* expr, Location location)
996{
997 return new Set_and_use_temporary_expression(statement, expr, location);
998}
999
e440a328 1000// A sink expression--a use of the blank identifier _.
1001
1002class Sink_expression : public Expression
1003{
1004 public:
b13c66cd 1005 Sink_expression(Location location)
e440a328 1006 : Expression(EXPRESSION_SINK, location),
aa93217a 1007 type_(NULL), bvar_(NULL)
e440a328 1008 { }
1009
1010 protected:
4f2138d7 1011 bool
e440a328 1012 do_discarding_value()
4f2138d7 1013 { return true; }
e440a328 1014
1015 Type*
1016 do_type();
1017
1018 void
1019 do_determine_type(const Type_context*);
1020
1021 Expression*
1022 do_copy()
1023 { return new Sink_expression(this->location()); }
1024
ea664253 1025 Bexpression*
1026 do_get_backend(Translate_context*);
e440a328 1027
d751bb78 1028 void
1029 do_dump_expression(Ast_dump_context*) const;
1030
e440a328 1031 private:
1032 // The type of this sink variable.
1033 Type* type_;
1034 // The temporary variable we generate.
aa93217a 1035 Bvariable* bvar_;
e440a328 1036};
1037
1038// Return the type of a sink expression.
1039
1040Type*
1041Sink_expression::do_type()
1042{
1043 if (this->type_ == NULL)
1044 return Type::make_sink_type();
1045 return this->type_;
1046}
1047
1048// Determine the type of a sink expression.
1049
1050void
1051Sink_expression::do_determine_type(const Type_context* context)
1052{
1053 if (context->type != NULL)
1054 this->type_ = context->type;
1055}
1056
1057// Return a temporary variable for a sink expression. This will
1058// presumably be a write-only variable which the middle-end will drop.
1059
ea664253 1060Bexpression*
1061Sink_expression::do_get_backend(Translate_context* context)
e440a328 1062{
aa93217a 1063 Location loc = this->location();
1064 Gogo* gogo = context->gogo();
1065 if (this->bvar_ == NULL)
e440a328 1066 {
c484d925 1067 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
aa93217a 1068 Named_object* fn = context->function();
1069 go_assert(fn != NULL);
1070 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
9f0e0513 1071 Btype* bt = this->type_->get_backend(context->gogo());
aa93217a 1072 Bstatement* decl;
1073 this->bvar_ =
1074 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1075 false, loc, &decl);
d4e6573e 1076 Bexpression* var_ref =
1077 gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
aa93217a 1078 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
ea664253 1079 return var_ref;
e440a328 1080 }
d4e6573e 1081 return gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
e440a328 1082}
1083
d751bb78 1084// Ast dump for sink expression.
1085
1086void
1087Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1088{
1089 ast_dump_context->ostream() << "_" ;
1090}
1091
e440a328 1092// Make a sink expression.
1093
1094Expression*
b13c66cd 1095Expression::make_sink(Location location)
e440a328 1096{
1097 return new Sink_expression(location);
1098}
1099
1100// Class Func_expression.
1101
1102// FIXME: Can a function expression appear in a constant expression?
1103// The value is unchanging. Initializing a constant to the address of
1104// a function seems like it could work, though there might be little
1105// point to it.
1106
e440a328 1107// Traversal.
1108
1109int
1110Func_expression::do_traverse(Traverse* traverse)
1111{
1112 return (this->closure_ == NULL
1113 ? TRAVERSE_CONTINUE
1114 : Expression::traverse(&this->closure_, traverse));
1115}
1116
1117// Return the type of a function expression.
1118
1119Type*
1120Func_expression::do_type()
1121{
1122 if (this->function_->is_function())
1123 return this->function_->func_value()->type();
1124 else if (this->function_->is_function_declaration())
1125 return this->function_->func_declaration_value()->type();
1126 else
c3e6f413 1127 go_unreachable();
e440a328 1128}
1129
ea664253 1130// Get the backend representation for the code of a function expression.
e440a328 1131
97267c39 1132Bexpression*
8381eda7 1133Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1134{
1135 Function_type* fntype;
8381eda7 1136 if (no->is_function())
1137 fntype = no->func_value()->type();
1138 else if (no->is_function_declaration())
1139 fntype = no->func_declaration_value()->type();
e440a328 1140 else
c3e6f413 1141 go_unreachable();
e440a328 1142
1143 // Builtin functions are handled specially by Call_expression. We
1144 // can't take their address.
1145 if (fntype->is_builtin())
1146 {
631d5788 1147 go_error_at(loc,
1148 "invalid use of special builtin function %qs; must be called",
1149 no->message_name().c_str());
97267c39 1150 return gogo->backend()->error_expression();
e440a328 1151 }
1152
97267c39 1153 Bfunction* fndecl;
e440a328 1154 if (no->is_function())
cf3cae55 1155 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1156 else if (no->is_function_declaration())
cf3cae55 1157 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1158 else
c3e6f413 1159 go_unreachable();
e440a328 1160
97267c39 1161 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1162}
1163
ea664253 1164// Get the backend representation for a function expression. This is used when
1165// we take the address of a function rather than simply calling it. A func
8381eda7 1166// value is represented as a pointer to a block of memory. The first
1167// word of that memory is a pointer to the function code. The
1168// remaining parts of that memory are the addresses of variables that
1169// the function closes over.
e440a328 1170
ea664253 1171Bexpression*
1172Func_expression::do_get_backend(Translate_context* context)
e440a328 1173{
8381eda7 1174 // If there is no closure, just use the function descriptor.
2010c17a 1175 if (this->closure_ == NULL)
8381eda7 1176 {
1177 Gogo* gogo = context->gogo();
1178 Named_object* no = this->function_;
1179 Expression* descriptor;
1180 if (no->is_function())
1181 descriptor = no->func_value()->descriptor(gogo, no);
1182 else if (no->is_function_declaration())
1183 {
1184 if (no->func_declaration_value()->type()->is_builtin())
1185 {
631d5788 1186 go_error_at(this->location(),
1187 ("invalid use of special builtin function %qs; "
1188 "must be called"),
1189 no->message_name().c_str());
ea664253 1190 return gogo->backend()->error_expression();
8381eda7 1191 }
1192 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1193 }
1194 else
1195 go_unreachable();
2010c17a 1196
ea664253 1197 Bexpression* bdesc = descriptor->get_backend(context);
1198 return gogo->backend()->address_expression(bdesc, this->location());
8381eda7 1199 }
e440a328 1200
8381eda7 1201 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1202
8381eda7 1203 // If there is a closure, then the closure is itself the function
1204 // expression. It is a pointer to a struct whose first field points
1205 // to the function code and whose remaining fields are the addresses
1206 // of the closed-over variables.
ea664253 1207 return this->closure_->get_backend(context);
e440a328 1208}
1209
d751bb78 1210// Ast dump for function.
1211
1212void
1213Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1214{
8b1c301d 1215 ast_dump_context->ostream() << this->function_->name();
1216 if (this->closure_ != NULL)
1217 {
1218 ast_dump_context->ostream() << " {closure = ";
1219 this->closure_->dump_expression(ast_dump_context);
1220 ast_dump_context->ostream() << "}";
1221 }
d751bb78 1222}
1223
e440a328 1224// Make a reference to a function in an expression.
1225
1226Expression*
1227Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1228 Location location)
e440a328 1229{
b1d7ecfa 1230 Func_expression* fe = new Func_expression(function, closure, location);
1231
1232 // Detect references to builtin functions and set the runtime code if
1233 // appropriate.
1234 if (function->is_function_declaration())
1235 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1236 return fe;
e440a328 1237}
1238
c6837989 1239// Class Func_descriptor_expression.
8381eda7 1240
c6837989 1241// Constructor.
8381eda7 1242
c6837989 1243Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1244 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1245 fn_(fn), dvar_(NULL)
c6837989 1246{
1247 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1248}
8381eda7 1249
c6837989 1250// Traversal.
8381eda7 1251
c6837989 1252int
1253Func_descriptor_expression::do_traverse(Traverse*)
1254{
1255 return TRAVERSE_CONTINUE;
1256}
8381eda7 1257
1258// All function descriptors have the same type.
1259
1260Type* Func_descriptor_expression::descriptor_type;
1261
1262void
1263Func_descriptor_expression::make_func_descriptor_type()
1264{
1265 if (Func_descriptor_expression::descriptor_type != NULL)
1266 return;
1267 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1268 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1269 Func_descriptor_expression::descriptor_type =
1270 Type::make_builtin_named_type("functionDescriptor", struct_type);
1271}
1272
1273Type*
1274Func_descriptor_expression::do_type()
1275{
1276 Func_descriptor_expression::make_func_descriptor_type();
1277 return Func_descriptor_expression::descriptor_type;
1278}
1279
ea664253 1280// The backend representation for a function descriptor.
8381eda7 1281
ea664253 1282Bexpression*
1283Func_descriptor_expression::do_get_backend(Translate_context* context)
8381eda7 1284{
8381eda7 1285 Named_object* no = this->fn_;
1286 Location loc = no->location();
ea664253 1287 if (this->dvar_ != NULL)
d4e6573e 1288 return context->backend()->var_expression(this->dvar_, VE_rvalue, loc);
8381eda7 1289
ea664253 1290 Gogo* gogo = context->gogo();
8381eda7 1291 std::string var_name;
09e57698 1292 bool is_descriptor = false;
1293 if (no->is_function_declaration()
1294 && !no->func_declaration_value()->asm_name().empty()
1295 && Linemap::is_predeclared_location(no->location()))
1296 {
6098d6cb 1297 if (no->func_declaration_value()->asm_name().substr(0, 8) != "runtime.")
1298 var_name = no->func_declaration_value()->asm_name() + "_descriptor";
1299 else
1300 var_name = no->func_declaration_value()->asm_name() + "$descriptor";
09e57698 1301 is_descriptor = true;
1302 }
8381eda7 1303 else
09e57698 1304 {
1305 if (no->package() == NULL)
1306 var_name = gogo->pkgpath_symbol();
1307 else
1308 var_name = no->package()->pkgpath_symbol();
1309 var_name.push_back('.');
1310 var_name.append(Gogo::unpack_hidden_name(no->name()));
1311 var_name.append("$descriptor");
1312 }
8381eda7 1313
1314 Btype* btype = this->type()->get_backend(gogo);
1315
1316 Bvariable* bvar;
438b4bec 1317 std::string asm_name(go_selectively_encode_id(var_name));
09e57698 1318 if (no->package() != NULL || is_descriptor)
438b4bec 1319 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1320 btype, loc);
8381eda7 1321 else
1322 {
1323 Location bloc = Linemap::predeclared_location();
1324 bool is_hidden = ((no->is_function()
1325 && no->func_value()->enclosing() != NULL)
1326 || Gogo::is_thunk(no));
438b4bec 1327 bvar = context->backend()->immutable_struct(var_name, asm_name,
1328 is_hidden, false,
8381eda7 1329 btype, bloc);
1330 Expression_list* vals = new Expression_list();
f8bdf81a 1331 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1332 Expression* init =
1333 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1334 Translate_context bcontext(gogo, NULL, NULL, NULL);
1335 bcontext.set_is_const();
ea664253 1336 Bexpression* binit = init->get_backend(&bcontext);
8381eda7 1337 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1338 false, btype, bloc, binit);
1339 }
1340
1341 this->dvar_ = bvar;
d4e6573e 1342 return gogo->backend()->var_expression(bvar, VE_rvalue, loc);
8381eda7 1343}
1344
c6837989 1345// Print a function descriptor expression.
1346
1347void
1348Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1349{
1350 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1351}
1352
8381eda7 1353// Make a function descriptor expression.
1354
c6837989 1355Func_descriptor_expression*
1356Expression::make_func_descriptor(Named_object* fn)
8381eda7 1357{
c6837989 1358 return new Func_descriptor_expression(fn);
8381eda7 1359}
1360
1361// Make the function descriptor type, so that it can be converted.
1362
1363void
1364Expression::make_func_descriptor_type()
1365{
1366 Func_descriptor_expression::make_func_descriptor_type();
1367}
1368
1369// A reference to just the code of a function.
1370
1371class Func_code_reference_expression : public Expression
1372{
1373 public:
1374 Func_code_reference_expression(Named_object* function, Location location)
1375 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1376 function_(function)
1377 { }
1378
1379 protected:
1380 int
1381 do_traverse(Traverse*)
1382 { return TRAVERSE_CONTINUE; }
1383
f9ca30f9 1384 bool
3ae06f68 1385 do_is_static_initializer() const
f9ca30f9 1386 { return true; }
1387
8381eda7 1388 Type*
1389 do_type()
1390 { return Type::make_pointer_type(Type::make_void_type()); }
1391
1392 void
1393 do_determine_type(const Type_context*)
1394 { }
1395
1396 Expression*
1397 do_copy()
1398 {
1399 return Expression::make_func_code_reference(this->function_,
1400 this->location());
1401 }
1402
ea664253 1403 Bexpression*
1404 do_get_backend(Translate_context*);
8381eda7 1405
1406 void
1407 do_dump_expression(Ast_dump_context* context) const
1408 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1409
1410 private:
1411 // The function.
1412 Named_object* function_;
1413};
1414
ea664253 1415// Get the backend representation for a reference to function code.
8381eda7 1416
ea664253 1417Bexpression*
1418Func_code_reference_expression::do_get_backend(Translate_context* context)
8381eda7 1419{
ea664253 1420 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1421 this->location());
8381eda7 1422}
1423
1424// Make a reference to the code of a function.
1425
1426Expression*
1427Expression::make_func_code_reference(Named_object* function, Location location)
1428{
1429 return new Func_code_reference_expression(function, location);
1430}
1431
e440a328 1432// Class Unknown_expression.
1433
1434// Return the name of an unknown expression.
1435
1436const std::string&
1437Unknown_expression::name() const
1438{
1439 return this->named_object_->name();
1440}
1441
1442// Lower a reference to an unknown name.
1443
1444Expression*
ceeb4318 1445Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1446{
b13c66cd 1447 Location location = this->location();
e440a328 1448 Named_object* no = this->named_object_;
deded542 1449 Named_object* real;
1450 if (!no->is_unknown())
1451 real = no;
1452 else
e440a328 1453 {
deded542 1454 real = no->unknown_value()->real_named_object();
1455 if (real == NULL)
1456 {
1457 if (this->is_composite_literal_key_)
1458 return this;
acf8e158 1459 if (!this->no_error_message_)
631d5788 1460 go_error_at(location, "reference to undefined name %qs",
1461 this->named_object_->message_name().c_str());
deded542 1462 return Expression::make_error(location);
1463 }
e440a328 1464 }
1465 switch (real->classification())
1466 {
1467 case Named_object::NAMED_OBJECT_CONST:
1468 return Expression::make_const_reference(real, location);
1469 case Named_object::NAMED_OBJECT_TYPE:
1470 return Expression::make_type(real->type_value(), location);
1471 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1472 if (this->is_composite_literal_key_)
1473 return this;
acf8e158 1474 if (!this->no_error_message_)
631d5788 1475 go_error_at(location, "reference to undefined type %qs",
1476 real->message_name().c_str());
e440a328 1477 return Expression::make_error(location);
1478 case Named_object::NAMED_OBJECT_VAR:
7d834090 1479 real->var_value()->set_is_used();
e440a328 1480 return Expression::make_var_reference(real, location);
1481 case Named_object::NAMED_OBJECT_FUNC:
1482 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1483 return Expression::make_func_reference(real, NULL, location);
1484 case Named_object::NAMED_OBJECT_PACKAGE:
1485 if (this->is_composite_literal_key_)
1486 return this;
acf8e158 1487 if (!this->no_error_message_)
631d5788 1488 go_error_at(location, "unexpected reference to package");
e440a328 1489 return Expression::make_error(location);
1490 default:
c3e6f413 1491 go_unreachable();
e440a328 1492 }
1493}
1494
d751bb78 1495// Dump the ast representation for an unknown expression to a dump context.
1496
1497void
1498Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1499{
1500 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1501 << ")";
d751bb78 1502}
1503
e440a328 1504// Make a reference to an unknown name.
1505
acf8e158 1506Unknown_expression*
b13c66cd 1507Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1508{
e440a328 1509 return new Unknown_expression(no, location);
1510}
1511
1512// A boolean expression.
1513
1514class Boolean_expression : public Expression
1515{
1516 public:
b13c66cd 1517 Boolean_expression(bool val, Location location)
e440a328 1518 : Expression(EXPRESSION_BOOLEAN, location),
1519 val_(val), type_(NULL)
1520 { }
1521
1522 static Expression*
1523 do_import(Import*);
1524
1525 protected:
1526 bool
1527 do_is_constant() const
1528 { return true; }
1529
0e168074 1530 bool
3ae06f68 1531 do_is_static_initializer() const
0e168074 1532 { return true; }
1533
e440a328 1534 Type*
1535 do_type();
1536
1537 void
1538 do_determine_type(const Type_context*);
1539
1540 Expression*
1541 do_copy()
1542 { return this; }
1543
ea664253 1544 Bexpression*
1545 do_get_backend(Translate_context* context)
1546 { return context->backend()->boolean_constant_expression(this->val_); }
e440a328 1547
1548 void
1549 do_export(Export* exp) const
1550 { exp->write_c_string(this->val_ ? "true" : "false"); }
1551
d751bb78 1552 void
1553 do_dump_expression(Ast_dump_context* ast_dump_context) const
1554 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1555
e440a328 1556 private:
1557 // The constant.
1558 bool val_;
1559 // The type as determined by context.
1560 Type* type_;
1561};
1562
1563// Get the type.
1564
1565Type*
1566Boolean_expression::do_type()
1567{
1568 if (this->type_ == NULL)
1569 this->type_ = Type::make_boolean_type();
1570 return this->type_;
1571}
1572
1573// Set the type from the context.
1574
1575void
1576Boolean_expression::do_determine_type(const Type_context* context)
1577{
1578 if (this->type_ != NULL && !this->type_->is_abstract())
1579 ;
1580 else if (context->type != NULL && context->type->is_boolean_type())
1581 this->type_ = context->type;
1582 else if (!context->may_be_abstract)
1583 this->type_ = Type::lookup_bool_type();
1584}
1585
1586// Import a boolean constant.
1587
1588Expression*
1589Boolean_expression::do_import(Import* imp)
1590{
1591 if (imp->peek_char() == 't')
1592 {
1593 imp->require_c_string("true");
1594 return Expression::make_boolean(true, imp->location());
1595 }
1596 else
1597 {
1598 imp->require_c_string("false");
1599 return Expression::make_boolean(false, imp->location());
1600 }
1601}
1602
1603// Make a boolean expression.
1604
1605Expression*
b13c66cd 1606Expression::make_boolean(bool val, Location location)
e440a328 1607{
1608 return new Boolean_expression(val, location);
1609}
1610
1611// Class String_expression.
1612
1613// Get the type.
1614
1615Type*
1616String_expression::do_type()
1617{
1618 if (this->type_ == NULL)
1619 this->type_ = Type::make_string_type();
1620 return this->type_;
1621}
1622
1623// Set the type from the context.
1624
1625void
1626String_expression::do_determine_type(const Type_context* context)
1627{
1628 if (this->type_ != NULL && !this->type_->is_abstract())
1629 ;
1630 else if (context->type != NULL && context->type->is_string_type())
1631 this->type_ = context->type;
1632 else if (!context->may_be_abstract)
1633 this->type_ = Type::lookup_string_type();
1634}
1635
1636// Build a string constant.
1637
ea664253 1638Bexpression*
1639String_expression::do_get_backend(Translate_context* context)
e440a328 1640{
2c809f8f 1641 Gogo* gogo = context->gogo();
1642 Btype* btype = Type::make_string_type()->get_backend(gogo);
1643
1644 Location loc = this->location();
1645 std::vector<Bexpression*> init(2);
1646 Bexpression* str_cst =
1647 gogo->backend()->string_constant_expression(this->val_);
1648 init[0] = gogo->backend()->address_expression(str_cst, loc);
1649
1650 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1651 mpz_t lenval;
1652 mpz_init_set_ui(lenval, this->val_.length());
1653 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1654 mpz_clear(lenval);
1655
ea664253 1656 return gogo->backend()->constructor_expression(btype, init, loc);
e440a328 1657}
1658
8b1c301d 1659 // Write string literal to string dump.
e440a328 1660
1661void
8b1c301d 1662String_expression::export_string(String_dump* exp,
1663 const String_expression* str)
e440a328 1664{
1665 std::string s;
8b1c301d 1666 s.reserve(str->val_.length() * 4 + 2);
e440a328 1667 s += '"';
8b1c301d 1668 for (std::string::const_iterator p = str->val_.begin();
1669 p != str->val_.end();
e440a328 1670 ++p)
1671 {
1672 if (*p == '\\' || *p == '"')
1673 {
1674 s += '\\';
1675 s += *p;
1676 }
1677 else if (*p >= 0x20 && *p < 0x7f)
1678 s += *p;
1679 else if (*p == '\n')
1680 s += "\\n";
1681 else if (*p == '\t')
1682 s += "\\t";
1683 else
1684 {
1685 s += "\\x";
1686 unsigned char c = *p;
1687 unsigned int dig = c >> 4;
1688 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1689 dig = c & 0xf;
1690 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1691 }
1692 }
1693 s += '"';
1694 exp->write_string(s);
1695}
1696
8b1c301d 1697// Export a string expression.
1698
1699void
1700String_expression::do_export(Export* exp) const
1701{
1702 String_expression::export_string(exp, this);
1703}
1704
e440a328 1705// Import a string expression.
1706
1707Expression*
1708String_expression::do_import(Import* imp)
1709{
1710 imp->require_c_string("\"");
1711 std::string val;
1712 while (true)
1713 {
1714 int c = imp->get_char();
1715 if (c == '"' || c == -1)
1716 break;
1717 if (c != '\\')
1718 val += static_cast<char>(c);
1719 else
1720 {
1721 c = imp->get_char();
1722 if (c == '\\' || c == '"')
1723 val += static_cast<char>(c);
1724 else if (c == 'n')
1725 val += '\n';
1726 else if (c == 't')
1727 val += '\t';
1728 else if (c == 'x')
1729 {
1730 c = imp->get_char();
1731 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1732 c = imp->get_char();
1733 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1734 char v = (vh << 4) | vl;
1735 val += v;
1736 }
1737 else
1738 {
631d5788 1739 go_error_at(imp->location(), "bad string constant");
e440a328 1740 return Expression::make_error(imp->location());
1741 }
1742 }
1743 }
1744 return Expression::make_string(val, imp->location());
1745}
1746
d751bb78 1747// Ast dump for string expression.
1748
1749void
1750String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1751{
8b1c301d 1752 String_expression::export_string(ast_dump_context, this);
d751bb78 1753}
1754
e440a328 1755// Make a string expression.
1756
1757Expression*
b13c66cd 1758Expression::make_string(const std::string& val, Location location)
e440a328 1759{
1760 return new String_expression(val, location);
1761}
1762
2c809f8f 1763// An expression that evaluates to some characteristic of a string.
1764// This is used when indexing, bound-checking, or nil checking a string.
1765
1766class String_info_expression : public Expression
1767{
1768 public:
1769 String_info_expression(Expression* string, String_info string_info,
1770 Location location)
1771 : Expression(EXPRESSION_STRING_INFO, location),
1772 string_(string), string_info_(string_info)
1773 { }
1774
1775 protected:
1776 Type*
1777 do_type();
1778
1779 void
1780 do_determine_type(const Type_context*)
1781 { go_unreachable(); }
1782
1783 Expression*
1784 do_copy()
1785 {
1786 return new String_info_expression(this->string_->copy(), this->string_info_,
1787 this->location());
1788 }
1789
ea664253 1790 Bexpression*
1791 do_get_backend(Translate_context* context);
2c809f8f 1792
1793 void
1794 do_dump_expression(Ast_dump_context*) const;
1795
1796 void
1797 do_issue_nil_check()
1798 { this->string_->issue_nil_check(); }
1799
1800 private:
1801 // The string for which we are getting information.
1802 Expression* string_;
1803 // What information we want.
1804 String_info string_info_;
1805};
1806
1807// Return the type of the string info.
1808
1809Type*
1810String_info_expression::do_type()
1811{
1812 switch (this->string_info_)
1813 {
1814 case STRING_INFO_DATA:
1815 {
1816 Type* byte_type = Type::lookup_integer_type("uint8");
1817 return Type::make_pointer_type(byte_type);
1818 }
1819 case STRING_INFO_LENGTH:
1820 return Type::lookup_integer_type("int");
1821 default:
1822 go_unreachable();
1823 }
1824}
1825
1826// Return string information in GENERIC.
1827
ea664253 1828Bexpression*
1829String_info_expression::do_get_backend(Translate_context* context)
2c809f8f 1830{
1831 Gogo* gogo = context->gogo();
1832
ea664253 1833 Bexpression* bstring = this->string_->get_backend(context);
2c809f8f 1834 switch (this->string_info_)
1835 {
1836 case STRING_INFO_DATA:
1837 case STRING_INFO_LENGTH:
ea664253 1838 return gogo->backend()->struct_field_expression(bstring,
1839 this->string_info_,
1840 this->location());
2c809f8f 1841 break;
1842 default:
1843 go_unreachable();
1844 }
2c809f8f 1845}
1846
1847// Dump ast representation for a type info expression.
1848
1849void
1850String_info_expression::do_dump_expression(
1851 Ast_dump_context* ast_dump_context) const
1852{
1853 ast_dump_context->ostream() << "stringinfo(";
1854 this->string_->dump_expression(ast_dump_context);
1855 ast_dump_context->ostream() << ",";
1856 ast_dump_context->ostream() <<
1857 (this->string_info_ == STRING_INFO_DATA ? "data"
1858 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1859 : "unknown");
1860 ast_dump_context->ostream() << ")";
1861}
1862
1863// Make a string info expression.
1864
1865Expression*
1866Expression::make_string_info(Expression* string, String_info string_info,
1867 Location location)
1868{
1869 return new String_info_expression(string, string_info, location);
1870}
1871
e440a328 1872// Make an integer expression.
1873
1874class Integer_expression : public Expression
1875{
1876 public:
5d4b8566 1877 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1878 Location location)
e440a328 1879 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1880 type_(type), is_character_constant_(is_character_constant)
e440a328 1881 { mpz_init_set(this->val_, *val); }
1882
1883 static Expression*
1884 do_import(Import*);
1885
8b1c301d 1886 // Write VAL to string dump.
e440a328 1887 static void
8b1c301d 1888 export_integer(String_dump* exp, const mpz_t val);
e440a328 1889
d751bb78 1890 // Write VAL to dump context.
1891 static void
1892 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1893
e440a328 1894 protected:
1895 bool
1896 do_is_constant() const
1897 { return true; }
1898
0e168074 1899 bool
3ae06f68 1900 do_is_static_initializer() const
0e168074 1901 { return true; }
1902
e440a328 1903 bool
0c77715b 1904 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1905
1906 Type*
1907 do_type();
1908
1909 void
1910 do_determine_type(const Type_context* context);
1911
1912 void
1913 do_check_types(Gogo*);
1914
ea664253 1915 Bexpression*
1916 do_get_backend(Translate_context*);
e440a328 1917
1918 Expression*
1919 do_copy()
5d4b8566 1920 {
1921 if (this->is_character_constant_)
1922 return Expression::make_character(&this->val_, this->type_,
1923 this->location());
1924 else
e67508fa 1925 return Expression::make_integer_z(&this->val_, this->type_,
1926 this->location());
5d4b8566 1927 }
e440a328 1928
1929 void
1930 do_export(Export*) const;
1931
d751bb78 1932 void
1933 do_dump_expression(Ast_dump_context*) const;
1934
e440a328 1935 private:
1936 // The integer value.
1937 mpz_t val_;
1938 // The type so far.
1939 Type* type_;
5d4b8566 1940 // Whether this is a character constant.
1941 bool is_character_constant_;
e440a328 1942};
1943
0c77715b 1944// Return a numeric constant for this expression. We have to mark
1945// this as a character when appropriate.
e440a328 1946
1947bool
0c77715b 1948Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1949{
0c77715b 1950 if (this->is_character_constant_)
1951 nc->set_rune(this->type_, this->val_);
1952 else
1953 nc->set_int(this->type_, this->val_);
e440a328 1954 return true;
1955}
1956
1957// Return the current type. If we haven't set the type yet, we return
1958// an abstract integer type.
1959
1960Type*
1961Integer_expression::do_type()
1962{
1963 if (this->type_ == NULL)
5d4b8566 1964 {
1965 if (this->is_character_constant_)
1966 this->type_ = Type::make_abstract_character_type();
1967 else
1968 this->type_ = Type::make_abstract_integer_type();
1969 }
e440a328 1970 return this->type_;
1971}
1972
1973// Set the type of the integer value. Here we may switch from an
1974// abstract type to a real type.
1975
1976void
1977Integer_expression::do_determine_type(const Type_context* context)
1978{
1979 if (this->type_ != NULL && !this->type_->is_abstract())
1980 ;
0c77715b 1981 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1982 this->type_ = context->type;
1983 else if (!context->may_be_abstract)
5d4b8566 1984 {
1985 if (this->is_character_constant_)
1986 this->type_ = Type::lookup_integer_type("int32");
1987 else
1988 this->type_ = Type::lookup_integer_type("int");
1989 }
e440a328 1990}
1991
e440a328 1992// Check the type of an integer constant.
1993
1994void
1995Integer_expression::do_check_types(Gogo*)
1996{
0c77715b 1997 Type* type = this->type_;
1998 if (type == NULL)
e440a328 1999 return;
0c77715b 2000 Numeric_constant nc;
2001 if (this->is_character_constant_)
2002 nc.set_rune(NULL, this->val_);
2003 else
2004 nc.set_int(NULL, this->val_);
2005 if (!nc.set_type(type, true, this->location()))
e440a328 2006 this->set_is_error();
2007}
2008
ea664253 2009// Get the backend representation for an integer constant.
e440a328 2010
ea664253 2011Bexpression*
2012Integer_expression::do_get_backend(Translate_context* context)
e440a328 2013{
12373dd5 2014 if (this->is_error_expression()
2015 || (this->type_ != NULL && this->type_->is_error_type()))
2016 {
2017 go_assert(saw_errors());
2018 return context->gogo()->backend()->error_expression();
2019 }
2020
48c2a53a 2021 Type* resolved_type = NULL;
e440a328 2022 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2023 resolved_type = this->type_;
e440a328 2024 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2025 {
2026 // We are converting to an abstract floating point type.
48c2a53a 2027 resolved_type = Type::lookup_float_type("float64");
e440a328 2028 }
2029 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2030 {
2031 // We are converting to an abstract complex type.
48c2a53a 2032 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2033 }
2034 else
2035 {
2036 // If we still have an abstract type here, then this is being
2037 // used in a constant expression which didn't get reduced for
2038 // some reason. Use a type which will fit the value. We use <,
2039 // not <=, because we need an extra bit for the sign bit.
2040 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 2041 Type* int_type = Type::lookup_integer_type("int");
2042 if (bits < int_type->integer_type()->bits())
48c2a53a 2043 resolved_type = int_type;
e440a328 2044 else if (bits < 64)
48c2a53a 2045 resolved_type = Type::lookup_integer_type("int64");
e440a328 2046 else
48c2a53a 2047 {
2048 if (!saw_errors())
631d5788 2049 go_error_at(this->location(),
2050 "unknown type for large integer constant");
ea664253 2051 return context->gogo()->backend()->error_expression();
48c2a53a 2052 }
e440a328 2053 }
48c2a53a 2054 Numeric_constant nc;
2055 nc.set_int(resolved_type, this->val_);
ea664253 2056 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2057}
2058
2059// Write VAL to export data.
2060
2061void
8b1c301d 2062Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 2063{
2064 char* s = mpz_get_str(NULL, 10, val);
2065 exp->write_c_string(s);
2066 free(s);
2067}
2068
2069// Export an integer in a constant expression.
2070
2071void
2072Integer_expression::do_export(Export* exp) const
2073{
2074 Integer_expression::export_integer(exp, this->val_);
5d4b8566 2075 if (this->is_character_constant_)
2076 exp->write_c_string("'");
e440a328 2077 // A trailing space lets us reliably identify the end of the number.
2078 exp->write_c_string(" ");
2079}
2080
2081// Import an integer, floating point, or complex value. This handles
2082// all these types because they all start with digits.
2083
2084Expression*
2085Integer_expression::do_import(Import* imp)
2086{
2087 std::string num = imp->read_identifier();
2088 imp->require_c_string(" ");
2089 if (!num.empty() && num[num.length() - 1] == 'i')
2090 {
2091 mpfr_t real;
2092 size_t plus_pos = num.find('+', 1);
2093 size_t minus_pos = num.find('-', 1);
2094 size_t pos;
2095 if (plus_pos == std::string::npos)
2096 pos = minus_pos;
2097 else if (minus_pos == std::string::npos)
2098 pos = plus_pos;
2099 else
2100 {
631d5788 2101 go_error_at(imp->location(), "bad number in import data: %qs",
2102 num.c_str());
e440a328 2103 return Expression::make_error(imp->location());
2104 }
2105 if (pos == std::string::npos)
2106 mpfr_set_ui(real, 0, GMP_RNDN);
2107 else
2108 {
2109 std::string real_str = num.substr(0, pos);
2110 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2111 {
631d5788 2112 go_error_at(imp->location(), "bad number in import data: %qs",
2113 real_str.c_str());
e440a328 2114 return Expression::make_error(imp->location());
2115 }
2116 }
2117
2118 std::string imag_str;
2119 if (pos == std::string::npos)
2120 imag_str = num;
2121 else
2122 imag_str = num.substr(pos);
2123 imag_str = imag_str.substr(0, imag_str.size() - 1);
2124 mpfr_t imag;
2125 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2126 {
631d5788 2127 go_error_at(imp->location(), "bad number in import data: %qs",
2128 imag_str.c_str());
e440a328 2129 return Expression::make_error(imp->location());
2130 }
fcbea5e4 2131 mpc_t cval;
2132 mpc_init2(cval, mpc_precision);
2133 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
e440a328 2134 mpfr_clear(real);
2135 mpfr_clear(imag);
fcbea5e4 2136 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2137 mpc_clear(cval);
e440a328 2138 return ret;
2139 }
2140 else if (num.find('.') == std::string::npos
2141 && num.find('E') == std::string::npos)
2142 {
5d4b8566 2143 bool is_character_constant = (!num.empty()
2144 && num[num.length() - 1] == '\'');
2145 if (is_character_constant)
2146 num = num.substr(0, num.length() - 1);
e440a328 2147 mpz_t val;
2148 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2149 {
631d5788 2150 go_error_at(imp->location(), "bad number in import data: %qs",
2151 num.c_str());
e440a328 2152 return Expression::make_error(imp->location());
2153 }
5d4b8566 2154 Expression* ret;
2155 if (is_character_constant)
2156 ret = Expression::make_character(&val, NULL, imp->location());
2157 else
e67508fa 2158 ret = Expression::make_integer_z(&val, NULL, imp->location());
e440a328 2159 mpz_clear(val);
2160 return ret;
2161 }
2162 else
2163 {
2164 mpfr_t val;
2165 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2166 {
631d5788 2167 go_error_at(imp->location(), "bad number in import data: %qs",
2168 num.c_str());
e440a328 2169 return Expression::make_error(imp->location());
2170 }
2171 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2172 mpfr_clear(val);
2173 return ret;
2174 }
2175}
d751bb78 2176// Ast dump for integer expression.
2177
2178void
2179Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2180{
5d4b8566 2181 if (this->is_character_constant_)
2182 ast_dump_context->ostream() << '\'';
8b1c301d 2183 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2184 if (this->is_character_constant_)
2185 ast_dump_context->ostream() << '\'';
d751bb78 2186}
2187
e67508fa 2188// Build a new integer value from a multi-precision integer.
e440a328 2189
2190Expression*
e67508fa 2191Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
5d4b8566 2192{
2193 return new Integer_expression(val, type, false, location);
2194}
2195
e67508fa 2196// Build a new integer value from an unsigned long.
2197
2198Expression*
2199Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2200{
2201 mpz_t zval;
2202 mpz_init_set_ui(zval, val);
2203 Expression* ret = Expression::make_integer_z(&zval, type, location);
2204 mpz_clear(zval);
2205 return ret;
2206}
2207
2208// Build a new integer value from a signed long.
2209
2210Expression*
2211Expression::make_integer_sl(long val, Type *type, Location location)
2212{
2213 mpz_t zval;
2214 mpz_init_set_si(zval, val);
2215 Expression* ret = Expression::make_integer_z(&zval, type, location);
2216 mpz_clear(zval);
2217 return ret;
2218}
2219
3f378015 2220// Store an int64_t in an uninitialized mpz_t.
2221
2222static void
2223set_mpz_from_int64(mpz_t* zval, int64_t val)
2224{
2225 if (val >= 0)
2226 {
2227 unsigned long ul = static_cast<unsigned long>(val);
2228 if (static_cast<int64_t>(ul) == val)
2229 {
2230 mpz_init_set_ui(*zval, ul);
2231 return;
2232 }
2233 }
2234 uint64_t uv;
2235 if (val >= 0)
2236 uv = static_cast<uint64_t>(val);
2237 else
2238 uv = static_cast<uint64_t>(- val);
2239 unsigned long ul = uv & 0xffffffffUL;
2240 mpz_init_set_ui(*zval, ul);
2241 mpz_t hval;
2242 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2243 mpz_mul_2exp(hval, hval, 32);
2244 mpz_add(*zval, *zval, hval);
2245 mpz_clear(hval);
2246 if (val < 0)
2247 mpz_neg(*zval, *zval);
2248}
2249
2250// Build a new integer value from an int64_t.
2251
2252Expression*
2253Expression::make_integer_int64(int64_t val, Type* type, Location location)
2254{
2255 mpz_t zval;
2256 set_mpz_from_int64(&zval, val);
2257 Expression* ret = Expression::make_integer_z(&zval, type, location);
2258 mpz_clear(zval);
2259 return ret;
2260}
2261
5d4b8566 2262// Build a new character constant value.
2263
2264Expression*
2265Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2266{
5d4b8566 2267 return new Integer_expression(val, type, true, location);
e440a328 2268}
2269
2270// Floats.
2271
2272class Float_expression : public Expression
2273{
2274 public:
b13c66cd 2275 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2276 : Expression(EXPRESSION_FLOAT, location),
2277 type_(type)
2278 {
2279 mpfr_init_set(this->val_, *val, GMP_RNDN);
2280 }
2281
e440a328 2282 // Write VAL to export data.
2283 static void
8b1c301d 2284 export_float(String_dump* exp, const mpfr_t val);
2285
d751bb78 2286 // Write VAL to dump file.
2287 static void
2288 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2289
2290 protected:
2291 bool
2292 do_is_constant() const
2293 { return true; }
2294
0e168074 2295 bool
3ae06f68 2296 do_is_static_initializer() const
0e168074 2297 { return true; }
2298
e440a328 2299 bool
0c77715b 2300 do_numeric_constant_value(Numeric_constant* nc) const
2301 {
2302 nc->set_float(this->type_, this->val_);
2303 return true;
2304 }
e440a328 2305
2306 Type*
2307 do_type();
2308
2309 void
2310 do_determine_type(const Type_context*);
2311
2312 void
2313 do_check_types(Gogo*);
2314
2315 Expression*
2316 do_copy()
2317 { return Expression::make_float(&this->val_, this->type_,
2318 this->location()); }
2319
ea664253 2320 Bexpression*
2321 do_get_backend(Translate_context*);
e440a328 2322
2323 void
2324 do_export(Export*) const;
2325
d751bb78 2326 void
2327 do_dump_expression(Ast_dump_context*) const;
2328
e440a328 2329 private:
2330 // The floating point value.
2331 mpfr_t val_;
2332 // The type so far.
2333 Type* type_;
2334};
2335
e440a328 2336// Return the current type. If we haven't set the type yet, we return
2337// an abstract float type.
2338
2339Type*
2340Float_expression::do_type()
2341{
2342 if (this->type_ == NULL)
2343 this->type_ = Type::make_abstract_float_type();
2344 return this->type_;
2345}
2346
2347// Set the type of the float value. Here we may switch from an
2348// abstract type to a real type.
2349
2350void
2351Float_expression::do_determine_type(const Type_context* context)
2352{
2353 if (this->type_ != NULL && !this->type_->is_abstract())
2354 ;
2355 else if (context->type != NULL
2356 && (context->type->integer_type() != NULL
2357 || context->type->float_type() != NULL
2358 || context->type->complex_type() != NULL))
2359 this->type_ = context->type;
2360 else if (!context->may_be_abstract)
48080209 2361 this->type_ = Type::lookup_float_type("float64");
e440a328 2362}
2363
e440a328 2364// Check the type of a float value.
2365
2366void
2367Float_expression::do_check_types(Gogo*)
2368{
0c77715b 2369 Type* type = this->type_;
2370 if (type == NULL)
e440a328 2371 return;
0c77715b 2372 Numeric_constant nc;
2373 nc.set_float(NULL, this->val_);
2374 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2375 this->set_is_error();
e440a328 2376}
2377
ea664253 2378// Get the backend representation for a float constant.
e440a328 2379
ea664253 2380Bexpression*
2381Float_expression::do_get_backend(Translate_context* context)
e440a328 2382{
12373dd5 2383 if (this->is_error_expression()
2384 || (this->type_ != NULL && this->type_->is_error_type()))
2385 {
2386 go_assert(saw_errors());
2387 return context->gogo()->backend()->error_expression();
2388 }
2389
48c2a53a 2390 Type* resolved_type;
e440a328 2391 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2392 resolved_type = this->type_;
e440a328 2393 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2394 {
2395 // We have an abstract integer type. We just hope for the best.
48c2a53a 2396 resolved_type = Type::lookup_integer_type("int");
2397 }
2398 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2399 {
2400 // We are converting to an abstract complex type.
2401 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2402 }
2403 else
2404 {
2405 // If we still have an abstract type here, then this is being
2406 // used in a constant expression which didn't get reduced. We
2407 // just use float64 and hope for the best.
48c2a53a 2408 resolved_type = Type::lookup_float_type("float64");
e440a328 2409 }
48c2a53a 2410
2411 Numeric_constant nc;
2412 nc.set_float(resolved_type, this->val_);
ea664253 2413 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2414}
2415
8b1c301d 2416// Write a floating point number to a string dump.
e440a328 2417
2418void
8b1c301d 2419Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2420{
2421 mp_exp_t exponent;
2422 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2423 if (*s == '-')
2424 exp->write_c_string("-");
2425 exp->write_c_string("0.");
2426 exp->write_c_string(*s == '-' ? s + 1 : s);
2427 mpfr_free_str(s);
2428 char buf[30];
2429 snprintf(buf, sizeof buf, "E%ld", exponent);
2430 exp->write_c_string(buf);
2431}
2432
2433// Export a floating point number in a constant expression.
2434
2435void
2436Float_expression::do_export(Export* exp) const
2437{
2438 Float_expression::export_float(exp, this->val_);
2439 // A trailing space lets us reliably identify the end of the number.
2440 exp->write_c_string(" ");
2441}
2442
d751bb78 2443// Dump a floating point number to the dump file.
2444
2445void
2446Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2447{
8b1c301d 2448 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2449}
2450
e440a328 2451// Make a float expression.
2452
2453Expression*
b13c66cd 2454Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2455{
2456 return new Float_expression(val, type, location);
2457}
2458
2459// Complex numbers.
2460
2461class Complex_expression : public Expression
2462{
2463 public:
fcbea5e4 2464 Complex_expression(const mpc_t* val, Type* type, Location location)
e440a328 2465 : Expression(EXPRESSION_COMPLEX, location),
2466 type_(type)
2467 {
fcbea5e4 2468 mpc_init2(this->val_, mpc_precision);
2469 mpc_set(this->val_, *val, MPC_RNDNN);
e440a328 2470 }
2471
fcbea5e4 2472 // Write VAL to string dump.
e440a328 2473 static void
fcbea5e4 2474 export_complex(String_dump* exp, const mpc_t val);
e440a328 2475
d751bb78 2476 // Write REAL/IMAG to dump context.
2477 static void
fcbea5e4 2478 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
d751bb78 2479
e440a328 2480 protected:
2481 bool
2482 do_is_constant() const
2483 { return true; }
2484
0e168074 2485 bool
3ae06f68 2486 do_is_static_initializer() const
0e168074 2487 { return true; }
2488
e440a328 2489 bool
0c77715b 2490 do_numeric_constant_value(Numeric_constant* nc) const
2491 {
fcbea5e4 2492 nc->set_complex(this->type_, this->val_);
0c77715b 2493 return true;
2494 }
e440a328 2495
2496 Type*
2497 do_type();
2498
2499 void
2500 do_determine_type(const Type_context*);
2501
2502 void
2503 do_check_types(Gogo*);
2504
2505 Expression*
2506 do_copy()
2507 {
fcbea5e4 2508 return Expression::make_complex(&this->val_, this->type_,
e440a328 2509 this->location());
2510 }
2511
ea664253 2512 Bexpression*
2513 do_get_backend(Translate_context*);
e440a328 2514
2515 void
2516 do_export(Export*) const;
2517
d751bb78 2518 void
2519 do_dump_expression(Ast_dump_context*) const;
abd26de0 2520
e440a328 2521 private:
fcbea5e4 2522 // The complex value.
2523 mpc_t val_;
e440a328 2524 // The type if known.
2525 Type* type_;
2526};
2527
e440a328 2528// Return the current type. If we haven't set the type yet, we return
2529// an abstract complex type.
2530
2531Type*
2532Complex_expression::do_type()
2533{
2534 if (this->type_ == NULL)
2535 this->type_ = Type::make_abstract_complex_type();
2536 return this->type_;
2537}
2538
2539// Set the type of the complex value. Here we may switch from an
2540// abstract type to a real type.
2541
2542void
2543Complex_expression::do_determine_type(const Type_context* context)
2544{
2545 if (this->type_ != NULL && !this->type_->is_abstract())
2546 ;
abd26de0 2547 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 2548 this->type_ = context->type;
2549 else if (!context->may_be_abstract)
48080209 2550 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2551}
2552
e440a328 2553// Check the type of a complex value.
2554
2555void
2556Complex_expression::do_check_types(Gogo*)
2557{
0c77715b 2558 Type* type = this->type_;
2559 if (type == NULL)
e440a328 2560 return;
0c77715b 2561 Numeric_constant nc;
fcbea5e4 2562 nc.set_complex(NULL, this->val_);
0c77715b 2563 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2564 this->set_is_error();
2565}
2566
ea664253 2567// Get the backend representation for a complex constant.
e440a328 2568
ea664253 2569Bexpression*
2570Complex_expression::do_get_backend(Translate_context* context)
e440a328 2571{
12373dd5 2572 if (this->is_error_expression()
2573 || (this->type_ != NULL && this->type_->is_error_type()))
2574 {
2575 go_assert(saw_errors());
2576 return context->gogo()->backend()->error_expression();
2577 }
2578
48c2a53a 2579 Type* resolved_type;
e440a328 2580 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2581 resolved_type = this->type_;
2582 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2583 {
2584 // We are converting to an abstract integer type.
2585 resolved_type = Type::lookup_integer_type("int");
2586 }
2587 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2588 {
2589 // We are converting to an abstract float type.
2590 resolved_type = Type::lookup_float_type("float64");
2591 }
e440a328 2592 else
2593 {
47ae02b7 2594 // If we still have an abstract type here, this is being
e440a328 2595 // used in a constant expression which didn't get reduced. We
2596 // just use complex128 and hope for the best.
48c2a53a 2597 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2598 }
48c2a53a 2599
2600 Numeric_constant nc;
fcbea5e4 2601 nc.set_complex(resolved_type, this->val_);
ea664253 2602 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2603}
2604
2605// Write REAL/IMAG to export data.
2606
2607void
fcbea5e4 2608Complex_expression::export_complex(String_dump* exp, const mpc_t val)
e440a328 2609{
fcbea5e4 2610 if (!mpfr_zero_p(mpc_realref(val)))
e440a328 2611 {
fcbea5e4 2612 Float_expression::export_float(exp, mpc_realref(val));
d1db782d 2613 if (mpfr_sgn(mpc_imagref(val)) >= 0)
e440a328 2614 exp->write_c_string("+");
2615 }
fcbea5e4 2616 Float_expression::export_float(exp, mpc_imagref(val));
e440a328 2617 exp->write_c_string("i");
2618}
2619
2620// Export a complex number in a constant expression.
2621
2622void
2623Complex_expression::do_export(Export* exp) const
2624{
fcbea5e4 2625 Complex_expression::export_complex(exp, this->val_);
e440a328 2626 // A trailing space lets us reliably identify the end of the number.
2627 exp->write_c_string(" ");
2628}
2629
d751bb78 2630// Dump a complex expression to the dump file.
2631
2632void
2633Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2634{
fcbea5e4 2635 Complex_expression::export_complex(ast_dump_context, this->val_);
d751bb78 2636}
2637
e440a328 2638// Make a complex expression.
2639
2640Expression*
fcbea5e4 2641Expression::make_complex(const mpc_t* val, Type* type, Location location)
e440a328 2642{
fcbea5e4 2643 return new Complex_expression(val, type, location);
e440a328 2644}
2645
d5b605df 2646// Find a named object in an expression.
2647
2648class Find_named_object : public Traverse
2649{
2650 public:
2651 Find_named_object(Named_object* no)
2652 : Traverse(traverse_expressions),
2653 no_(no), found_(false)
2654 { }
2655
2656 // Whether we found the object.
2657 bool
2658 found() const
2659 { return this->found_; }
2660
2661 protected:
2662 int
2663 expression(Expression**);
2664
2665 private:
2666 // The object we are looking for.
2667 Named_object* no_;
2668 // Whether we found it.
2669 bool found_;
2670};
2671
e440a328 2672// A reference to a const in an expression.
2673
2674class Const_expression : public Expression
2675{
2676 public:
b13c66cd 2677 Const_expression(Named_object* constant, Location location)
e440a328 2678 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2679 constant_(constant), type_(NULL), seen_(false)
e440a328 2680 { }
2681
d5b605df 2682 Named_object*
2683 named_object()
2684 { return this->constant_; }
2685
a7f064d5 2686 // Check that the initializer does not refer to the constant itself.
2687 void
2688 check_for_init_loop();
2689
e440a328 2690 protected:
ba4aedd4 2691 int
2692 do_traverse(Traverse*);
2693
e440a328 2694 Expression*
ceeb4318 2695 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2696
2697 bool
2698 do_is_constant() const
2699 { return true; }
2700
0e168074 2701 bool
3ae06f68 2702 do_is_static_initializer() const
0e168074 2703 { return true; }
2704
e440a328 2705 bool
0c77715b 2706 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2707
2708 bool
af6b489a 2709 do_string_constant_value(std::string* val) const;
e440a328 2710
2711 Type*
2712 do_type();
2713
2714 // The type of a const is set by the declaration, not the use.
2715 void
2716 do_determine_type(const Type_context*);
2717
2718 void
2719 do_check_types(Gogo*);
2720
2721 Expression*
2722 do_copy()
2723 { return this; }
2724
ea664253 2725 Bexpression*
2726 do_get_backend(Translate_context* context);
e440a328 2727
2728 // When exporting a reference to a const as part of a const
2729 // expression, we export the value. We ignore the fact that it has
2730 // a name.
2731 void
2732 do_export(Export* exp) const
2733 { this->constant_->const_value()->expr()->export_expression(exp); }
2734
d751bb78 2735 void
2736 do_dump_expression(Ast_dump_context*) const;
2737
e440a328 2738 private:
2739 // The constant.
2740 Named_object* constant_;
2741 // The type of this reference. This is used if the constant has an
2742 // abstract type.
2743 Type* type_;
13e818f5 2744 // Used to prevent infinite recursion when a constant incorrectly
2745 // refers to itself.
2746 mutable bool seen_;
e440a328 2747};
2748
ba4aedd4 2749// Traversal.
2750
2751int
2752Const_expression::do_traverse(Traverse* traverse)
2753{
2754 if (this->type_ != NULL)
2755 return Type::traverse(this->type_, traverse);
2756 return TRAVERSE_CONTINUE;
2757}
2758
e440a328 2759// Lower a constant expression. This is where we convert the
2760// predeclared constant iota into an integer value.
2761
2762Expression*
ceeb4318 2763Const_expression::do_lower(Gogo* gogo, Named_object*,
2764 Statement_inserter*, int iota_value)
e440a328 2765{
2766 if (this->constant_->const_value()->expr()->classification()
2767 == EXPRESSION_IOTA)
2768 {
2769 if (iota_value == -1)
2770 {
631d5788 2771 go_error_at(this->location(),
2772 "iota is only defined in const declarations");
e440a328 2773 iota_value = 0;
2774 }
e67508fa 2775 return Expression::make_integer_ul(iota_value, NULL, this->location());
e440a328 2776 }
2777
2778 // Make sure that the constant itself has been lowered.
2779 gogo->lower_constant(this->constant_);
2780
2781 return this;
2782}
2783
0c77715b 2784// Return a numeric constant value.
e440a328 2785
2786bool
0c77715b 2787Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2788{
13e818f5 2789 if (this->seen_)
2790 return false;
2791
e440a328 2792 Expression* e = this->constant_->const_value()->expr();
0c77715b 2793
13e818f5 2794 this->seen_ = true;
2795
0c77715b 2796 bool r = e->numeric_constant_value(nc);
e440a328 2797
13e818f5 2798 this->seen_ = false;
2799
e440a328 2800 Type* ctype;
2801 if (this->type_ != NULL)
2802 ctype = this->type_;
2803 else
2804 ctype = this->constant_->const_value()->type();
e440a328 2805 if (r && ctype != NULL)
2806 {
0c77715b 2807 if (!nc->set_type(ctype, false, this->location()))
e440a328 2808 return false;
e440a328 2809 }
e440a328 2810
e440a328 2811 return r;
2812}
2813
af6b489a 2814bool
2815Const_expression::do_string_constant_value(std::string* val) const
2816{
2817 if (this->seen_)
2818 return false;
2819
2820 Expression* e = this->constant_->const_value()->expr();
2821
2822 this->seen_ = true;
2823 bool ok = e->string_constant_value(val);
2824 this->seen_ = false;
2825
2826 return ok;
2827}
2828
e440a328 2829// Return the type of the const reference.
2830
2831Type*
2832Const_expression::do_type()
2833{
2834 if (this->type_ != NULL)
2835 return this->type_;
13e818f5 2836
2f78f012 2837 Named_constant* nc = this->constant_->const_value();
2838
2839 if (this->seen_ || nc->lowering())
13e818f5 2840 {
2841 this->report_error(_("constant refers to itself"));
2842 this->type_ = Type::make_error_type();
2843 return this->type_;
2844 }
2845
2846 this->seen_ = true;
2847
e440a328 2848 Type* ret = nc->type();
13e818f5 2849
e440a328 2850 if (ret != NULL)
13e818f5 2851 {
2852 this->seen_ = false;
2853 return ret;
2854 }
2855
e440a328 2856 // During parsing, a named constant may have a NULL type, but we
2857 // must not return a NULL type here.
13e818f5 2858 ret = nc->expr()->type();
2859
2860 this->seen_ = false;
2861
2862 return ret;
e440a328 2863}
2864
2865// Set the type of the const reference.
2866
2867void
2868Const_expression::do_determine_type(const Type_context* context)
2869{
2870 Type* ctype = this->constant_->const_value()->type();
2871 Type* cetype = (ctype != NULL
2872 ? ctype
2873 : this->constant_->const_value()->expr()->type());
2874 if (ctype != NULL && !ctype->is_abstract())
2875 ;
2876 else if (context->type != NULL
0c77715b 2877 && context->type->is_numeric_type()
2878 && cetype->is_numeric_type())
e440a328 2879 this->type_ = context->type;
2880 else if (context->type != NULL
2881 && context->type->is_string_type()
2882 && cetype->is_string_type())
2883 this->type_ = context->type;
2884 else if (context->type != NULL
2885 && context->type->is_boolean_type()
2886 && cetype->is_boolean_type())
2887 this->type_ = context->type;
2888 else if (!context->may_be_abstract)
2889 {
2890 if (cetype->is_abstract())
2891 cetype = cetype->make_non_abstract_type();
2892 this->type_ = cetype;
2893 }
2894}
2895
a7f064d5 2896// Check for a loop in which the initializer of a constant refers to
2897// the constant itself.
e440a328 2898
2899void
a7f064d5 2900Const_expression::check_for_init_loop()
e440a328 2901{
5c13bd80 2902 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2903 return;
2904
a7f064d5 2905 if (this->seen_)
2906 {
2907 this->report_error(_("constant refers to itself"));
2908 this->type_ = Type::make_error_type();
2909 return;
2910 }
2911
d5b605df 2912 Expression* init = this->constant_->const_value()->expr();
2913 Find_named_object find_named_object(this->constant_);
a7f064d5 2914
2915 this->seen_ = true;
d5b605df 2916 Expression::traverse(&init, &find_named_object);
a7f064d5 2917 this->seen_ = false;
2918
d5b605df 2919 if (find_named_object.found())
2920 {
5c13bd80 2921 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2922 {
2923 this->report_error(_("constant refers to itself"));
2924 this->type_ = Type::make_error_type();
2925 }
d5b605df 2926 return;
2927 }
a7f064d5 2928}
2929
2930// Check types of a const reference.
2931
2932void
2933Const_expression::do_check_types(Gogo*)
2934{
5c13bd80 2935 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2936 return;
2937
2938 this->check_for_init_loop();
d5b605df 2939
0c77715b 2940 // Check that numeric constant fits in type.
2941 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2942 {
0c77715b 2943 Numeric_constant nc;
2944 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2945 {
0c77715b 2946 if (!nc.set_type(this->type_, true, this->location()))
2947 this->set_is_error();
e440a328 2948 }
e440a328 2949 }
2950}
2951
ea664253 2952// Return the backend representation for a const reference.
e440a328 2953
ea664253 2954Bexpression*
2955Const_expression::do_get_backend(Translate_context* context)
e440a328 2956{
12373dd5 2957 if (this->is_error_expression()
2958 || (this->type_ != NULL && this->type_->is_error()))
2959 {
2960 go_assert(saw_errors());
2961 return context->backend()->error_expression();
2962 }
e440a328 2963
2964 // If the type has been set for this expression, but the underlying
2965 // object is an abstract int or float, we try to get the abstract
2966 // value. Otherwise we may lose something in the conversion.
f2de4532 2967 Expression* expr = this->constant_->const_value()->expr();
e440a328 2968 if (this->type_ != NULL
0c77715b 2969 && this->type_->is_numeric_type()
a68492b4 2970 && (this->constant_->const_value()->type() == NULL
2971 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2972 {
0c77715b 2973 Numeric_constant nc;
2974 if (expr->numeric_constant_value(&nc)
2975 && nc.set_type(this->type_, false, this->location()))
e440a328 2976 {
0c77715b 2977 Expression* e = nc.expression(this->location());
ea664253 2978 return e->get_backend(context);
e440a328 2979 }
e440a328 2980 }
2981
2c809f8f 2982 if (this->type_ != NULL)
f2de4532 2983 expr = Expression::make_cast(this->type_, expr, this->location());
ea664253 2984 return expr->get_backend(context);
e440a328 2985}
2986
d751bb78 2987// Dump ast representation for constant expression.
2988
2989void
2990Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2991{
2992 ast_dump_context->ostream() << this->constant_->name();
2993}
2994
e440a328 2995// Make a reference to a constant in an expression.
2996
2997Expression*
2998Expression::make_const_reference(Named_object* constant,
b13c66cd 2999 Location location)
e440a328 3000{
3001 return new Const_expression(constant, location);
3002}
3003
d5b605df 3004// Find a named object in an expression.
3005
3006int
3007Find_named_object::expression(Expression** pexpr)
3008{
3009 switch ((*pexpr)->classification())
3010 {
3011 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 3012 {
3013 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3014 if (ce->named_object() == this->no_)
3015 break;
3016
3017 // We need to check a constant initializer explicitly, as
3018 // loops here will not be caught by the loop checking for
3019 // variable initializers.
3020 ce->check_for_init_loop();
3021
3022 return TRAVERSE_CONTINUE;
3023 }
3024
d5b605df 3025 case Expression::EXPRESSION_VAR_REFERENCE:
3026 if ((*pexpr)->var_expression()->named_object() == this->no_)
3027 break;
3028 return TRAVERSE_CONTINUE;
3029 case Expression::EXPRESSION_FUNC_REFERENCE:
3030 if ((*pexpr)->func_expression()->named_object() == this->no_)
3031 break;
3032 return TRAVERSE_CONTINUE;
3033 default:
3034 return TRAVERSE_CONTINUE;
3035 }
3036 this->found_ = true;
3037 return TRAVERSE_EXIT;
3038}
3039
e440a328 3040// The nil value.
3041
3042class Nil_expression : public Expression
3043{
3044 public:
b13c66cd 3045 Nil_expression(Location location)
e440a328 3046 : Expression(EXPRESSION_NIL, location)
3047 { }
3048
3049 static Expression*
3050 do_import(Import*);
3051
3052 protected:
3053 bool
3054 do_is_constant() const
3055 { return true; }
3056
f9ca30f9 3057 bool
3ae06f68 3058 do_is_static_initializer() const
f9ca30f9 3059 { return true; }
3060
e440a328 3061 Type*
3062 do_type()
3063 { return Type::make_nil_type(); }
3064
3065 void
3066 do_determine_type(const Type_context*)
3067 { }
3068
3069 Expression*
3070 do_copy()
3071 { return this; }
3072
ea664253 3073 Bexpression*
3074 do_get_backend(Translate_context* context)
3075 { return context->backend()->nil_pointer_expression(); }
e440a328 3076
3077 void
3078 do_export(Export* exp) const
3079 { exp->write_c_string("nil"); }
d751bb78 3080
3081 void
3082 do_dump_expression(Ast_dump_context* ast_dump_context) const
3083 { ast_dump_context->ostream() << "nil"; }
e440a328 3084};
3085
3086// Import a nil expression.
3087
3088Expression*
3089Nil_expression::do_import(Import* imp)
3090{
3091 imp->require_c_string("nil");
3092 return Expression::make_nil(imp->location());
3093}
3094
3095// Make a nil expression.
3096
3097Expression*
b13c66cd 3098Expression::make_nil(Location location)
e440a328 3099{
3100 return new Nil_expression(location);
3101}
3102
3103// The value of the predeclared constant iota. This is little more
3104// than a marker. This will be lowered to an integer in
3105// Const_expression::do_lower, which is where we know the value that
3106// it should have.
3107
3108class Iota_expression : public Parser_expression
3109{
3110 public:
b13c66cd 3111 Iota_expression(Location location)
e440a328 3112 : Parser_expression(EXPRESSION_IOTA, location)
3113 { }
3114
3115 protected:
3116 Expression*
ceeb4318 3117 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 3118 { go_unreachable(); }
e440a328 3119
3120 // There should only ever be one of these.
3121 Expression*
3122 do_copy()
c3e6f413 3123 { go_unreachable(); }
d751bb78 3124
3125 void
3126 do_dump_expression(Ast_dump_context* ast_dump_context) const
3127 { ast_dump_context->ostream() << "iota"; }
e440a328 3128};
3129
3130// Make an iota expression. This is only called for one case: the
3131// value of the predeclared constant iota.
3132
3133Expression*
3134Expression::make_iota()
3135{
b13c66cd 3136 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 3137 return &iota_expression;
3138}
3139
da244e59 3140// Class Type_conversion_expression.
e440a328 3141
3142// Traversal.
3143
3144int
3145Type_conversion_expression::do_traverse(Traverse* traverse)
3146{
3147 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3148 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3149 return TRAVERSE_EXIT;
3150 return TRAVERSE_CONTINUE;
3151}
3152
3153// Convert to a constant at lowering time.
3154
3155Expression*
ceeb4318 3156Type_conversion_expression::do_lower(Gogo*, Named_object*,
3157 Statement_inserter*, int)
e440a328 3158{
3159 Type* type = this->type_;
3160 Expression* val = this->expr_;
b13c66cd 3161 Location location = this->location();
e440a328 3162
0c77715b 3163 if (type->is_numeric_type())
e440a328 3164 {
0c77715b 3165 Numeric_constant nc;
3166 if (val->numeric_constant_value(&nc))
e440a328 3167 {
0c77715b 3168 if (!nc.set_type(type, true, location))
3169 return Expression::make_error(location);
3170 return nc.expression(location);
e440a328 3171 }
e440a328 3172 }
3173
d7739c9a 3174 // According to the language specification on string conversions
3175 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3176 // When converting an integer into a string, the string will be a UTF-8
3177 // representation of the integer and integers "outside the range of valid
3178 // Unicode code points are converted to '\uFFFD'."
3179 if (type->is_string_type())
3180 {
3181 Numeric_constant nc;
3182 if (val->numeric_constant_value(&nc) && nc.is_int())
3183 {
3184 // An integer value doesn't fit in the Unicode code point range if it
3185 // overflows the Go "int" type or is negative.
3186 unsigned long ul;
3187 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3188 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3189 return Expression::make_string("\ufffd", location);
3190 }
3191 }
3192
55072f2b 3193 if (type->is_slice_type())
e440a328 3194 {
3195 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3196 bool is_byte = (element_type->integer_type() != NULL
3197 && element_type->integer_type()->is_byte());
3198 bool is_rune = (element_type->integer_type() != NULL
3199 && element_type->integer_type()->is_rune());
3200 if (is_byte || is_rune)
e440a328 3201 {
3202 std::string s;
3203 if (val->string_constant_value(&s))
3204 {
3205 Expression_list* vals = new Expression_list();
3206 if (is_byte)
3207 {
3208 for (std::string::const_iterator p = s.begin();
3209 p != s.end();
3210 p++)
3211 {
e67508fa 3212 unsigned char c = static_cast<unsigned char>(*p);
3213 vals->push_back(Expression::make_integer_ul(c,
3214 element_type,
3215 location));
e440a328 3216 }
3217 }
3218 else
3219 {
3220 const char *p = s.data();
3221 const char *pend = s.data() + s.length();
3222 while (p < pend)
3223 {
3224 unsigned int c;
3225 int adv = Lex::fetch_char(p, &c);
3226 if (adv == 0)
3227 {
631d5788 3228 go_warning_at(this->location(), 0,
e440a328 3229 "invalid UTF-8 encoding");
3230 adv = 1;
3231 }
3232 p += adv;
e67508fa 3233 vals->push_back(Expression::make_integer_ul(c,
3234 element_type,
3235 location));
e440a328 3236 }
3237 }
3238
3239 return Expression::make_slice_composite_literal(type, vals,
3240 location);
3241 }
3242 }
3243 }
3244
3245 return this;
3246}
3247
35a54f17 3248// Flatten a type conversion by using a temporary variable for the slice
3249// in slice to string conversions.
3250
3251Expression*
3252Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3253 Statement_inserter* inserter)
3254{
5bf8be8b 3255 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3256 {
3257 go_assert(saw_errors());
3258 return Expression::make_error(this->location());
3259 }
3260
2c809f8f 3261 if (((this->type()->is_string_type()
3262 && this->expr_->type()->is_slice_type())
8ba8cc87 3263 || this->expr_->type()->interface_type() != NULL)
35a54f17 3264 && !this->expr_->is_variable())
3265 {
3266 Temporary_statement* temp =
3267 Statement::make_temporary(NULL, this->expr_, this->location());
3268 inserter->insert(temp);
3269 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3270 }
3271 return this;
3272}
3273
1ca01a59 3274// Return whether a type conversion is a constant.
3275
3276bool
3277Type_conversion_expression::do_is_constant() const
3278{
3279 if (!this->expr_->is_constant())
3280 return false;
3281
3282 // A conversion to a type that may not be used as a constant is not
3283 // a constant. For example, []byte(nil).
3284 Type* type = this->type_;
3285 if (type->integer_type() == NULL
3286 && type->float_type() == NULL
3287 && type->complex_type() == NULL
3288 && !type->is_boolean_type()
3289 && !type->is_string_type())
3290 return false;
3291
3292 return true;
3293}
3294
3ae06f68 3295// Return whether a type conversion can be used in a constant
3296// initializer.
0e168074 3297
3298bool
3ae06f68 3299Type_conversion_expression::do_is_static_initializer() const
0e168074 3300{
3301 Type* type = this->type_;
3302 Type* expr_type = this->expr_->type();
3303
3304 if (type->interface_type() != NULL
3305 || expr_type->interface_type() != NULL)
3306 return false;
3307
3ae06f68 3308 if (!this->expr_->is_static_initializer())
0e168074 3309 return false;
3310
3311 if (Type::are_identical(type, expr_type, false, NULL))
3312 return true;
3313
03118c21 3314 if (type->is_string_type() && expr_type->is_string_type())
3315 return true;
3316
3317 if ((type->is_numeric_type()
3318 || type->is_boolean_type()
3319 || type->points_to() != NULL)
3320 && (expr_type->is_numeric_type()
3321 || expr_type->is_boolean_type()
3322 || expr_type->points_to() != NULL))
3323 return true;
3324
3325 return false;
0e168074 3326}
3327
0c77715b 3328// Return the constant numeric value if there is one.
e440a328 3329
3330bool
0c77715b 3331Type_conversion_expression::do_numeric_constant_value(
3332 Numeric_constant* nc) const
e440a328 3333{
0c77715b 3334 if (!this->type_->is_numeric_type())
e440a328 3335 return false;
0c77715b 3336 if (!this->expr_->numeric_constant_value(nc))
e440a328 3337 return false;
0c77715b 3338 return nc->set_type(this->type_, false, this->location());
e440a328 3339}
3340
3341// Return the constant string value if there is one.
3342
3343bool
3344Type_conversion_expression::do_string_constant_value(std::string* val) const
3345{
3346 if (this->type_->is_string_type()
3347 && this->expr_->type()->integer_type() != NULL)
3348 {
0c77715b 3349 Numeric_constant nc;
3350 if (this->expr_->numeric_constant_value(&nc))
e440a328 3351 {
0c77715b 3352 unsigned long ival;
3353 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3354 {
0c77715b 3355 val->clear();
3356 Lex::append_char(ival, true, val, this->location());
e440a328 3357 return true;
3358 }
3359 }
e440a328 3360 }
3361
3362 // FIXME: Could handle conversion from const []int here.
3363
3364 return false;
3365}
3366
da244e59 3367// Determine the resulting type of the conversion.
3368
3369void
3370Type_conversion_expression::do_determine_type(const Type_context*)
3371{
3372 Type_context subcontext(this->type_, false);
3373 this->expr_->determine_type(&subcontext);
3374}
3375
e440a328 3376// Check that types are convertible.
3377
3378void
3379Type_conversion_expression::do_check_types(Gogo*)
3380{
3381 Type* type = this->type_;
3382 Type* expr_type = this->expr_->type();
3383 std::string reason;
3384
5c13bd80 3385 if (type->is_error() || expr_type->is_error())
842f6425 3386 {
842f6425 3387 this->set_is_error();
3388 return;
3389 }
3390
e440a328 3391 if (this->may_convert_function_types_
3392 && type->function_type() != NULL
3393 && expr_type->function_type() != NULL)
3394 return;
3395
3396 if (Type::are_convertible(type, expr_type, &reason))
3397 return;
3398
631d5788 3399 go_error_at(this->location(), "%s", reason.c_str());
e440a328 3400 this->set_is_error();
3401}
3402
ea664253 3403// Get the backend representation for a type conversion.
e440a328 3404
ea664253 3405Bexpression*
3406Type_conversion_expression::do_get_backend(Translate_context* context)
e440a328 3407{
e440a328 3408 Type* type = this->type_;
3409 Type* expr_type = this->expr_->type();
2c809f8f 3410
3411 Gogo* gogo = context->gogo();
3412 Btype* btype = type->get_backend(gogo);
ea664253 3413 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3414 Location loc = this->location();
3415
3416 if (Type::are_identical(type, expr_type, false, NULL))
ea664253 3417 return gogo->backend()->convert_expression(btype, bexpr, loc);
2c809f8f 3418 else if (type->interface_type() != NULL
3419 || expr_type->interface_type() != NULL)
e440a328 3420 {
2c809f8f 3421 Expression* conversion =
3422 Expression::convert_for_assignment(gogo, type, this->expr_,
3423 this->location());
ea664253 3424 return conversion->get_backend(context);
e440a328 3425 }
3426 else if (type->is_string_type()
3427 && expr_type->integer_type() != NULL)
3428 {
2c809f8f 3429 mpz_t intval;
3430 Numeric_constant nc;
3431 if (this->expr_->numeric_constant_value(&nc)
3432 && nc.to_int(&intval)
3433 && mpz_fits_ushort_p(intval))
e440a328 3434 {
e440a328 3435 std::string s;
2c809f8f 3436 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3437 mpz_clear(intval);
3438 Expression* se = Expression::make_string(s, loc);
ea664253 3439 return se->get_backend(context);
e440a328 3440 }
3441
f16ab008 3442 Expression* i2s_expr =
736a16ba 3443 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3444 Expression::make_nil(loc), this->expr_);
ea664253 3445 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
e440a328 3446 }
55072f2b 3447 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3448 {
55072f2b 3449 Array_type* a = expr_type->array_type();
e440a328 3450 Type* e = a->element_type()->forwarded();
c484d925 3451 go_assert(e->integer_type() != NULL);
35a54f17 3452 go_assert(this->expr_->is_variable());
3453
3454 Runtime::Function code;
60963afd 3455 if (e->integer_type()->is_byte())
736a16ba 3456 code = Runtime::SLICEBYTETOSTRING;
e440a328 3457 else
35a54f17 3458 {
3459 go_assert(e->integer_type()->is_rune());
736a16ba 3460 code = Runtime::SLICERUNETOSTRING;
35a54f17 3461 }
736a16ba 3462 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3463 this->expr_)->get_backend(context);
e440a328 3464 }
411eb89e 3465 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3466 {
3467 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3468 go_assert(e->integer_type() != NULL);
6c252e42 3469
2c809f8f 3470 Runtime::Function code;
60963afd 3471 if (e->integer_type()->is_byte())
736a16ba 3472 code = Runtime::STRINGTOSLICEBYTE;
e440a328 3473 else
3474 {
60963afd 3475 go_assert(e->integer_type()->is_rune());
736a16ba 3476 code = Runtime::STRINGTOSLICERUNE;
e440a328 3477 }
736a16ba 3478 Expression* s2a = Runtime::make_call(code, loc, 2,
3479 Expression::make_nil(loc),
3480 this->expr_);
ea664253 3481 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
2c809f8f 3482 }
3483 else if (type->is_numeric_type())
3484 {
3485 go_assert(Type::are_convertible(type, expr_type, NULL));
ea664253 3486 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3487 }
3488 else if ((type->is_unsafe_pointer_type()
2c809f8f 3489 && (expr_type->points_to() != NULL
3490 || expr_type->integer_type()))
3491 || (expr_type->is_unsafe_pointer_type()
3492 && type->points_to() != NULL)
3493 || (this->may_convert_function_types_
3494 && type->function_type() != NULL
3495 && expr_type->function_type() != NULL))
ea664253 3496 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3497 else
2c809f8f 3498 {
3499 Expression* conversion =
3500 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
ea664253 3501 return conversion->get_backend(context);
2c809f8f 3502 }
e440a328 3503}
3504
3505// Output a type conversion in a constant expression.
3506
3507void
3508Type_conversion_expression::do_export(Export* exp) const
3509{
3510 exp->write_c_string("convert(");
3511 exp->write_type(this->type_);
3512 exp->write_c_string(", ");
3513 this->expr_->export_expression(exp);
3514 exp->write_c_string(")");
3515}
3516
3517// Import a type conversion or a struct construction.
3518
3519Expression*
3520Type_conversion_expression::do_import(Import* imp)
3521{
3522 imp->require_c_string("convert(");
3523 Type* type = imp->read_type();
3524 imp->require_c_string(", ");
3525 Expression* val = Expression::import_expression(imp);
3526 imp->require_c_string(")");
3527 return Expression::make_cast(type, val, imp->location());
3528}
3529
d751bb78 3530// Dump ast representation for a type conversion expression.
3531
3532void
3533Type_conversion_expression::do_dump_expression(
3534 Ast_dump_context* ast_dump_context) const
3535{
3536 ast_dump_context->dump_type(this->type_);
3537 ast_dump_context->ostream() << "(";
3538 ast_dump_context->dump_expression(this->expr_);
3539 ast_dump_context->ostream() << ") ";
3540}
3541
e440a328 3542// Make a type cast expression.
3543
3544Expression*
b13c66cd 3545Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3546{
3547 if (type->is_error_type() || val->is_error_expression())
3548 return Expression::make_error(location);
3549 return new Type_conversion_expression(type, val, location);
3550}
3551
98f62f7a 3552// Class Unsafe_type_conversion_expression.
9581e91d 3553
3554// Traversal.
3555
3556int
3557Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3558{
3559 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3560 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3561 return TRAVERSE_EXIT;
3562 return TRAVERSE_CONTINUE;
3563}
3564
3ae06f68 3565// Return whether an unsafe type conversion can be used as a constant
3566// initializer.
aa5ae575 3567
3568bool
3ae06f68 3569Unsafe_type_conversion_expression::do_is_static_initializer() const
aa5ae575 3570{
3571 Type* type = this->type_;
3572 Type* expr_type = this->expr_->type();
3573
3574 if (type->interface_type() != NULL
3575 || expr_type->interface_type() != NULL)
3576 return false;
3577
3ae06f68 3578 if (!this->expr_->is_static_initializer())
aa5ae575 3579 return false;
3580
3581 if (Type::are_convertible(type, expr_type, NULL))
3582 return true;
3583
03118c21 3584 if (type->is_string_type() && expr_type->is_string_type())
3585 return true;
3586
3587 if ((type->is_numeric_type()
3588 || type->is_boolean_type()
3589 || type->points_to() != NULL)
3590 && (expr_type->is_numeric_type()
3591 || expr_type->is_boolean_type()
3592 || expr_type->points_to() != NULL))
3593 return true;
3594
3595 return false;
aa5ae575 3596}
3597
9581e91d 3598// Convert to backend representation.
3599
ea664253 3600Bexpression*
3601Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
9581e91d 3602{
3603 // We are only called for a limited number of cases.
3604
3605 Type* t = this->type_;
3606 Type* et = this->expr_->type();
5c4802f1 3607
3608 if (t->is_error_type()
3609 || this->expr_->is_error_expression()
3610 || et->is_error_type())
3611 {
3612 go_assert(saw_errors());
3613 return context->backend()->error_expression();
3614 }
3615
2c809f8f 3616 if (t->array_type() != NULL)
3617 go_assert(et->array_type() != NULL
3618 && t->is_slice_type() == et->is_slice_type());
3619 else if (t->struct_type() != NULL)
9581e91d 3620 {
2c809f8f 3621 if (t->named_type() != NULL
3622 && et->named_type() != NULL
3623 && !Type::are_convertible(t, et, NULL))
3624 {
3625 go_assert(saw_errors());
ea664253 3626 return context->backend()->error_expression();
2c809f8f 3627 }
3628
3629 go_assert(et->struct_type() != NULL
3630 && Type::are_convertible(t, et, NULL));
3631 }
3632 else if (t->map_type() != NULL)
c484d925 3633 go_assert(et->map_type() != NULL);
9581e91d 3634 else if (t->channel_type() != NULL)
c484d925 3635 go_assert(et->channel_type() != NULL);
09ea332d 3636 else if (t->points_to() != NULL)
2c809f8f 3637 go_assert(et->points_to() != NULL
3638 || et->channel_type() != NULL
3639 || et->map_type() != NULL
3640 || et->function_type() != NULL
132ed071 3641 || et->integer_type() != NULL
2c809f8f 3642 || et->is_nil_type());
9581e91d 3643 else if (et->is_unsafe_pointer_type())
c484d925 3644 go_assert(t->points_to() != NULL);
2c809f8f 3645 else if (t->interface_type() != NULL)
9581e91d 3646 {
2c809f8f 3647 bool empty_iface = t->interface_type()->is_empty();
c484d925 3648 go_assert(et->interface_type() != NULL
2c809f8f 3649 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3650 }
588e3cf9 3651 else if (t->integer_type() != NULL)
2c809f8f 3652 go_assert(et->is_boolean_type()
3653 || et->integer_type() != NULL
3654 || et->function_type() != NULL
3655 || et->points_to() != NULL
3656 || et->map_type() != NULL
8ba8cc87 3657 || et->channel_type() != NULL
3658 || et->is_nil_type());
cd39797e 3659 else if (t->function_type() != NULL)
3660 go_assert(et->points_to() != NULL);
9581e91d 3661 else
c3e6f413 3662 go_unreachable();
9581e91d 3663
2c809f8f 3664 Gogo* gogo = context->gogo();
3665 Btype* btype = t->get_backend(gogo);
ea664253 3666 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3667 Location loc = this->location();
ea664253 3668 return gogo->backend()->convert_expression(btype, bexpr, loc);
9581e91d 3669}
3670
d751bb78 3671// Dump ast representation for an unsafe type conversion expression.
3672
3673void
3674Unsafe_type_conversion_expression::do_dump_expression(
3675 Ast_dump_context* ast_dump_context) const
3676{
3677 ast_dump_context->dump_type(this->type_);
3678 ast_dump_context->ostream() << "(";
3679 ast_dump_context->dump_expression(this->expr_);
3680 ast_dump_context->ostream() << ") ";
3681}
3682
9581e91d 3683// Make an unsafe type conversion expression.
3684
3685Expression*
3686Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3687 Location location)
9581e91d 3688{
3689 return new Unsafe_type_conversion_expression(type, expr, location);
3690}
3691
76f85fd6 3692// Class Unary_expression.
e440a328 3693
03118c21 3694// Call the address_taken method of the operand if needed. This is
3695// called after escape analysis but before inserting write barriers.
3696
3697void
3698Unary_expression::check_operand_address_taken(Gogo* gogo)
3699{
3700 if (this->op_ != OPERATOR_AND)
3701 return;
3702
3703 // If this->escapes_ is false at this point, then it was set to
3704 // false by an explicit call to set_does_not_escape, and the value
3705 // does not escape. If this->escapes_ is true, we may be able to
3706 // set it to false if taking the address of a variable that does not
3707 // escape.
3708 Node* n = Node::make_node(this);
3709 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3710 this->escapes_ = false;
3711
3712 // When compiling the runtime, the address operator does not cause
3713 // local variables to escape. When escape analysis becomes the
3714 // default, this should be changed to make it an error if we have an
3715 // address operator that escapes.
3716 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3717 this->escapes_ = false;
3718
3719 Named_object* var = NULL;
3720 if (this->expr_->var_expression() != NULL)
3721 var = this->expr_->var_expression()->named_object();
3722 else if (this->expr_->enclosed_var_expression() != NULL)
3723 var = this->expr_->enclosed_var_expression()->variable();
3724
3725 if (this->escapes_ && var != NULL)
3726 {
3727 if (var->is_variable())
3728 this->escapes_ = var->var_value()->escapes();
3729 if (var->is_result_variable())
3730 this->escapes_ = var->result_var_value()->escapes();
3731 }
3732
3733 this->expr_->address_taken(this->escapes_);
3734}
3735
e440a328 3736// If we are taking the address of a composite literal, and the
2c809f8f 3737// contents are not constant, then we want to make a heap expression
e440a328 3738// instead.
3739
3740Expression*
ceeb4318 3741Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3742{
b13c66cd 3743 Location loc = this->location();
e440a328 3744 Operator op = this->op_;
3745 Expression* expr = this->expr_;
3746
3747 if (op == OPERATOR_MULT && expr->is_type_expression())
3748 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3749
3750 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3751 // moving x to the heap. FIXME: Is it worth doing a real escape
3752 // analysis here? This case is found in math/unsafe.go and is
3753 // therefore worth special casing.
3754 if (op == OPERATOR_MULT)
3755 {
3756 Expression* e = expr;
3757 while (e->classification() == EXPRESSION_CONVERSION)
3758 {
3759 Type_conversion_expression* te
3760 = static_cast<Type_conversion_expression*>(e);
3761 e = te->expr();
3762 }
3763
3764 if (e->classification() == EXPRESSION_UNARY)
3765 {
3766 Unary_expression* ue = static_cast<Unary_expression*>(e);
3767 if (ue->op_ == OPERATOR_AND)
3768 {
3769 if (e == expr)
3770 {
3771 // *&x == x.
f4dea966 3772 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3773 {
631d5788 3774 go_error_at(ue->location(),
3775 "invalid operand for unary %<&%>");
f4dea966 3776 this->set_is_error();
3777 }
e440a328 3778 return ue->expr_;
3779 }
3780 ue->set_does_not_escape();
3781 }
3782 }
3783 }
3784
55661ce9 3785 // Catching an invalid indirection of unsafe.Pointer here avoid
3786 // having to deal with TYPE_VOID in other places.
3787 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3788 {
631d5788 3789 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
55661ce9 3790 return Expression::make_error(this->location());
3791 }
3792
d9f3743a 3793 // Check for an invalid pointer dereference. We need to do this
3794 // here because Unary_expression::do_type will return an error type
3795 // in this case. That can cause code to appear erroneous, and
3796 // therefore disappear at lowering time, without any error message.
3797 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3798 {
3799 this->report_error(_("expected pointer"));
3800 return Expression::make_error(this->location());
3801 }
3802
59a401fe 3803 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3804 {
0c77715b 3805 Numeric_constant nc;
3806 if (expr->numeric_constant_value(&nc))
e440a328 3807 {
0c77715b 3808 Numeric_constant result;
af7a5274 3809 bool issued_error;
3810 if (Unary_expression::eval_constant(op, &nc, loc, &result,
3811 &issued_error))
0c77715b 3812 return result.expression(loc);
af7a5274 3813 else if (issued_error)
3814 return Expression::make_error(this->location());
e440a328 3815 }
3816 }
3817
3818 return this;
3819}
3820
f9ca30f9 3821// Flatten expression if a nil check must be performed and create temporary
3822// variables if necessary.
3823
3824Expression*
3825Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3826 Statement_inserter* inserter)
3827{
5bf8be8b 3828 if (this->is_error_expression()
3829 || this->expr_->is_error_expression()
3830 || this->expr_->type()->is_error_type())
3831 {
3832 go_assert(saw_errors());
3833 return Expression::make_error(this->location());
3834 }
f4dea966 3835
f9ca30f9 3836 Location location = this->location();
3837 if (this->op_ == OPERATOR_MULT
3838 && !this->expr_->is_variable())
3839 {
3840 go_assert(this->expr_->type()->points_to() != NULL);
3841 Type* ptype = this->expr_->type()->points_to();
3842 if (!ptype->is_void_type())
3843 {
2a305b85 3844 int64_t s;
3845 bool ok = ptype->backend_type_size(gogo, &s);
3846 if (!ok)
3847 {
3848 go_assert(saw_errors());
3849 return Expression::make_error(this->location());
3850 }
f9ca30f9 3851 if (s >= 4096 || this->issue_nil_check_)
3852 {
3853 Temporary_statement* temp =
3854 Statement::make_temporary(NULL, this->expr_, location);
3855 inserter->insert(temp);
3856 this->expr_ =
3857 Expression::make_temporary_reference(temp, location);
3858 }
3859 }
3860 }
3861
3862 if (this->create_temp_ && !this->expr_->is_variable())
3863 {
3864 Temporary_statement* temp =
3865 Statement::make_temporary(NULL, this->expr_, location);
3866 inserter->insert(temp);
3867 this->expr_ = Expression::make_temporary_reference(temp, location);
3868 }
3869
3870 return this;
3871}
3872
e440a328 3873// Return whether a unary expression is a constant.
3874
3875bool
3876Unary_expression::do_is_constant() const
3877{
3878 if (this->op_ == OPERATOR_MULT)
3879 {
3880 // Indirecting through a pointer is only constant if the object
3881 // to which the expression points is constant, but we currently
3882 // have no way to determine that.
3883 return false;
3884 }
3885 else if (this->op_ == OPERATOR_AND)
3886 {
3887 // Taking the address of a variable is constant if it is a
f9ca30f9 3888 // global variable, not constant otherwise. In other cases taking the
3889 // address is probably not a constant.
e440a328 3890 Var_expression* ve = this->expr_->var_expression();
3891 if (ve != NULL)
3892 {
3893 Named_object* no = ve->named_object();
3894 return no->is_variable() && no->var_value()->is_global();
3895 }
3896 return false;
3897 }
3898 else
3899 return this->expr_->is_constant();
3900}
3901
3ae06f68 3902// Return whether a unary expression can be used as a constant
3903// initializer.
3904
3905bool
3906Unary_expression::do_is_static_initializer() const
3907{
3908 if (this->op_ == OPERATOR_MULT)
3909 return false;
3910 else if (this->op_ == OPERATOR_AND)
de048538 3911 return Unary_expression::base_is_static_initializer(this->expr_);
3912 else
3913 return this->expr_->is_static_initializer();
3914}
3ae06f68 3915
de048538 3916// Return whether the address of EXPR can be used as a static
3917// initializer.
3ae06f68 3918
de048538 3919bool
3920Unary_expression::base_is_static_initializer(Expression* expr)
3921{
3922 // The address of a field reference can be a static initializer if
3923 // the base can be a static initializer.
3924 Field_reference_expression* fre = expr->field_reference_expression();
3925 if (fre != NULL)
3926 return Unary_expression::base_is_static_initializer(fre->expr());
3927
3928 // The address of an index expression can be a static initializer if
3929 // the base can be a static initializer and the index is constant.
3930 Array_index_expression* aind = expr->array_index_expression();
3931 if (aind != NULL)
3932 return (aind->end() == NULL
3933 && aind->start()->is_constant()
3934 && Unary_expression::base_is_static_initializer(aind->array()));
3935
3936 // The address of a global variable can be a static initializer.
3937 Var_expression* ve = expr->var_expression();
3938 if (ve != NULL)
3939 {
3940 Named_object* no = ve->named_object();
3941 return no->is_variable() && no->var_value()->is_global();
3942 }
3943
3944 // The address of a composite literal can be used as a static
3945 // initializer if the composite literal is itself usable as a
3946 // static initializer.
3947 if (expr->is_composite_literal() && expr->is_static_initializer())
3948 return true;
3ae06f68 3949
de048538 3950 // The address of a string constant can be used as a static
3951 // initializer. This can not be written in Go itself but this is
3952 // used when building a type descriptor.
3953 if (expr->string_expression() != NULL)
3954 return true;
3955
3956 return false;
3ae06f68 3957}
3958
0c77715b 3959// Apply unary opcode OP to UNC, setting NC. Return true if this
af7a5274 3960// could be done, false if not. On overflow, issues an error and sets
3961// *ISSUED_ERROR.
e440a328 3962
3963bool
0c77715b 3964Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
af7a5274 3965 Location location, Numeric_constant* nc,
3966 bool* issued_error)
e440a328 3967{
af7a5274 3968 *issued_error = false;
e440a328 3969 switch (op)
3970 {
3971 case OPERATOR_PLUS:
0c77715b 3972 *nc = *unc;
e440a328 3973 return true;
0c77715b 3974
e440a328 3975 case OPERATOR_MINUS:
0c77715b 3976 if (unc->is_int() || unc->is_rune())
3977 break;
3978 else if (unc->is_float())
3979 {
3980 mpfr_t uval;
3981 unc->get_float(&uval);
3982 mpfr_t val;
3983 mpfr_init(val);
3984 mpfr_neg(val, uval, GMP_RNDN);
3985 nc->set_float(unc->type(), val);
3986 mpfr_clear(uval);
3987 mpfr_clear(val);
3988 return true;
3989 }
3990 else if (unc->is_complex())
3991 {
fcbea5e4 3992 mpc_t uval;
3993 unc->get_complex(&uval);
3994 mpc_t val;
3995 mpc_init2(val, mpc_precision);
3996 mpc_neg(val, uval, MPC_RNDNN);
3997 nc->set_complex(unc->type(), val);
3998 mpc_clear(uval);
3999 mpc_clear(val);
0c77715b 4000 return true;
4001 }
e440a328 4002 else
0c77715b 4003 go_unreachable();
e440a328 4004
0c77715b 4005 case OPERATOR_XOR:
4006 break;
68448d53 4007
59a401fe 4008 case OPERATOR_NOT:
e440a328 4009 case OPERATOR_AND:
4010 case OPERATOR_MULT:
4011 return false;
0c77715b 4012
e440a328 4013 default:
c3e6f413 4014 go_unreachable();
e440a328 4015 }
e440a328 4016
0c77715b 4017 if (!unc->is_int() && !unc->is_rune())
4018 return false;
4019
4020 mpz_t uval;
8387e1df 4021 if (unc->is_rune())
4022 unc->get_rune(&uval);
4023 else
4024 unc->get_int(&uval);
0c77715b 4025 mpz_t val;
4026 mpz_init(val);
e440a328 4027
e440a328 4028 switch (op)
4029 {
e440a328 4030 case OPERATOR_MINUS:
0c77715b 4031 mpz_neg(val, uval);
4032 break;
4033
e440a328 4034 case OPERATOR_NOT:
0c77715b 4035 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4036 break;
4037
e440a328 4038 case OPERATOR_XOR:
0c77715b 4039 {
4040 Type* utype = unc->type();
4041 if (utype->integer_type() == NULL
4042 || utype->integer_type()->is_abstract())
4043 mpz_com(val, uval);
4044 else
4045 {
4046 // The number of HOST_WIDE_INTs that it takes to represent
4047 // UVAL.
4048 size_t count = ((mpz_sizeinbase(uval, 2)
4049 + HOST_BITS_PER_WIDE_INT
4050 - 1)
4051 / HOST_BITS_PER_WIDE_INT);
e440a328 4052
0c77715b 4053 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4054 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4055
4056 size_t obits = utype->integer_type()->bits();
4057
4058 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4059 {
4060 mpz_t adj;
4061 mpz_init_set_ui(adj, 1);
4062 mpz_mul_2exp(adj, adj, obits);
4063 mpz_add(uval, uval, adj);
4064 mpz_clear(adj);
4065 }
4066
4067 size_t ecount;
4068 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4069 go_assert(ecount <= count);
4070
4071 // Trim down to the number of words required by the type.
4072 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4073 / HOST_BITS_PER_WIDE_INT);
4074 go_assert(ocount <= count);
4075
4076 for (size_t i = 0; i < ocount; ++i)
4077 phwi[i] = ~phwi[i];
4078
4079 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4080 if (clearbits != 0)
4081 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4082 >> clearbits);
4083
4084 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4085
4086 if (!utype->integer_type()->is_unsigned()
4087 && mpz_tstbit(val, obits - 1))
4088 {
4089 mpz_t adj;
4090 mpz_init_set_ui(adj, 1);
4091 mpz_mul_2exp(adj, adj, obits);
4092 mpz_sub(val, val, adj);
4093 mpz_clear(adj);
4094 }
4095
4096 delete[] phwi;
4097 }
4098 }
4099 break;
e440a328 4100
e440a328 4101 default:
c3e6f413 4102 go_unreachable();
e440a328 4103 }
e440a328 4104
0c77715b 4105 if (unc->is_rune())
4106 nc->set_rune(NULL, val);
e440a328 4107 else
0c77715b 4108 nc->set_int(NULL, val);
e440a328 4109
0c77715b 4110 mpz_clear(uval);
4111 mpz_clear(val);
e440a328 4112
af7a5274 4113 if (!nc->set_type(unc->type(), true, location))
4114 {
4115 *issued_error = true;
4116 return false;
4117 }
4118 return true;
e440a328 4119}
4120
0c77715b 4121// Return the integral constant value of a unary expression, if it has one.
e440a328 4122
4123bool
0c77715b 4124Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 4125{
0c77715b 4126 Numeric_constant unc;
4127 if (!this->expr_->numeric_constant_value(&unc))
4128 return false;
af7a5274 4129 bool issued_error;
0c77715b 4130 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
af7a5274 4131 nc, &issued_error);
e440a328 4132}
4133
4134// Return the type of a unary expression.
4135
4136Type*
4137Unary_expression::do_type()
4138{
4139 switch (this->op_)
4140 {
4141 case OPERATOR_PLUS:
4142 case OPERATOR_MINUS:
4143 case OPERATOR_NOT:
4144 case OPERATOR_XOR:
4145 return this->expr_->type();
4146
4147 case OPERATOR_AND:
4148 return Type::make_pointer_type(this->expr_->type());
4149
4150 case OPERATOR_MULT:
4151 {
4152 Type* subtype = this->expr_->type();
4153 Type* points_to = subtype->points_to();
4154 if (points_to == NULL)
4155 return Type::make_error_type();
4156 return points_to;
4157 }
4158
4159 default:
c3e6f413 4160 go_unreachable();
e440a328 4161 }
4162}
4163
4164// Determine abstract types for a unary expression.
4165
4166void
4167Unary_expression::do_determine_type(const Type_context* context)
4168{
4169 switch (this->op_)
4170 {
4171 case OPERATOR_PLUS:
4172 case OPERATOR_MINUS:
4173 case OPERATOR_NOT:
4174 case OPERATOR_XOR:
4175 this->expr_->determine_type(context);
4176 break;
4177
4178 case OPERATOR_AND:
4179 // Taking the address of something.
4180 {
4181 Type* subtype = (context->type == NULL
4182 ? NULL
4183 : context->type->points_to());
4184 Type_context subcontext(subtype, false);
4185 this->expr_->determine_type(&subcontext);
4186 }
4187 break;
4188
4189 case OPERATOR_MULT:
4190 // Indirecting through a pointer.
4191 {
4192 Type* subtype = (context->type == NULL
4193 ? NULL
4194 : Type::make_pointer_type(context->type));
4195 Type_context subcontext(subtype, false);
4196 this->expr_->determine_type(&subcontext);
4197 }
4198 break;
4199
4200 default:
c3e6f413 4201 go_unreachable();
e440a328 4202 }
4203}
4204
4205// Check types for a unary expression.
4206
4207void
4208Unary_expression::do_check_types(Gogo*)
4209{
9fe897ef 4210 Type* type = this->expr_->type();
5c13bd80 4211 if (type->is_error())
9fe897ef 4212 {
4213 this->set_is_error();
4214 return;
4215 }
4216
e440a328 4217 switch (this->op_)
4218 {
4219 case OPERATOR_PLUS:
4220 case OPERATOR_MINUS:
9fe897ef 4221 if (type->integer_type() == NULL
4222 && type->float_type() == NULL
4223 && type->complex_type() == NULL)
4224 this->report_error(_("expected numeric type"));
e440a328 4225 break;
4226
4227 case OPERATOR_NOT:
59a401fe 4228 if (!type->is_boolean_type())
4229 this->report_error(_("expected boolean type"));
4230 break;
4231
e440a328 4232 case OPERATOR_XOR:
b3b1474e 4233 if (type->integer_type() == NULL)
4234 this->report_error(_("expected integer"));
e440a328 4235 break;
4236
4237 case OPERATOR_AND:
4238 if (!this->expr_->is_addressable())
09ea332d 4239 {
4240 if (!this->create_temp_)
f4dea966 4241 {
631d5788 4242 go_error_at(this->location(), "invalid operand for unary %<&%>");
f4dea966 4243 this->set_is_error();
4244 }
09ea332d 4245 }
e440a328 4246 else
da244e59 4247 this->expr_->issue_nil_check();
e440a328 4248 break;
4249
4250 case OPERATOR_MULT:
4251 // Indirecting through a pointer.
9fe897ef 4252 if (type->points_to() == NULL)
4253 this->report_error(_("expected pointer"));
7661d702 4254 if (type->points_to()->is_error())
4255 this->set_is_error();
e440a328 4256 break;
4257
4258 default:
c3e6f413 4259 go_unreachable();
e440a328 4260 }
4261}
4262
ea664253 4263// Get the backend representation for a unary expression.
e440a328 4264
ea664253 4265Bexpression*
4266Unary_expression::do_get_backend(Translate_context* context)
e440a328 4267{
1b1f2abf 4268 Gogo* gogo = context->gogo();
e9d3367e 4269 Location loc = this->location();
4270
4271 // Taking the address of a set-and-use-temporary expression requires
4272 // setting the temporary and then taking the address.
4273 if (this->op_ == OPERATOR_AND)
4274 {
4275 Set_and_use_temporary_expression* sut =
4276 this->expr_->set_and_use_temporary_expression();
4277 if (sut != NULL)
4278 {
4279 Temporary_statement* temp = sut->temporary();
4280 Bvariable* bvar = temp->get_backend_variable(context);
d4e6573e 4281 Bexpression* bvar_expr =
4282 gogo->backend()->var_expression(bvar, VE_lvalue, loc);
ea664253 4283 Bexpression* bval = sut->expression()->get_backend(context);
f9ca30f9 4284
0ab48656 4285 Named_object* fn = context->function();
4286 go_assert(fn != NULL);
4287 Bfunction* bfn =
4288 fn->func_value()->get_or_make_decl(gogo, fn);
f9ca30f9 4289 Bstatement* bassign =
0ab48656 4290 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
f9ca30f9 4291 Bexpression* bvar_addr =
4292 gogo->backend()->address_expression(bvar_expr, loc);
ea664253 4293 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
e9d3367e 4294 }
4295 }
4296
f9ca30f9 4297 Bexpression* ret;
ea664253 4298 Bexpression* bexpr = this->expr_->get_backend(context);
f9ca30f9 4299 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4300 switch (this->op_)
4301 {
4302 case OPERATOR_PLUS:
f9ca30f9 4303 ret = bexpr;
4304 break;
e440a328 4305
4306 case OPERATOR_MINUS:
f9ca30f9 4307 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4308 ret = gogo->backend()->convert_expression(btype, ret, loc);
4309 break;
e440a328 4310
4311 case OPERATOR_NOT:
e440a328 4312 case OPERATOR_XOR:
f9ca30f9 4313 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4314 break;
e440a328 4315
4316 case OPERATOR_AND:
09ea332d 4317 if (!this->create_temp_)
4318 {
4319 // We should not see a non-constant constructor here; cases
4320 // where we would see one should have been moved onto the
4321 // heap at parse time. Taking the address of a nonconstant
4322 // constructor will not do what the programmer expects.
f9ca30f9 4323
4324 go_assert(!this->expr_->is_composite_literal()
3ae06f68 4325 || this->expr_->is_static_initializer());
24060bf9 4326 if (this->expr_->classification() == EXPRESSION_UNARY)
4327 {
4328 Unary_expression* ue =
4329 static_cast<Unary_expression*>(this->expr_);
4330 go_assert(ue->op() != OPERATOR_AND);
4331 }
09ea332d 4332 }
e440a328 4333
f23d7786 4334 static unsigned int counter;
4335 char buf[100];
4336 if (this->is_gc_root_ || this->is_slice_init_)
76f85fd6 4337 {
f23d7786 4338 bool copy_to_heap = false;
4339 if (this->is_gc_root_)
4340 {
4341 // Build a decl for a GC root variable. GC roots are mutable, so
4342 // they cannot be represented as an immutable_struct in the
4343 // backend.
4344 static unsigned int root_counter;
4345 snprintf(buf, sizeof buf, "gc%u", root_counter);
4346 ++root_counter;
4347 }
4348 else
4349 {
4350 // Build a decl for a slice value initializer. An immutable slice
4351 // value initializer may have to be copied to the heap if it
4352 // contains pointers in a non-constant context.
4353 snprintf(buf, sizeof buf, "C%u", counter);
4354 ++counter;
4355
4356 Array_type* at = this->expr_->type()->array_type();
4357 go_assert(at != NULL);
4358
4359 // If we are not copying the value to the heap, we will only
4360 // initialize the value once, so we can use this directly
4361 // rather than copying it. In that case we can't make it
4362 // read-only, because the program is permitted to change it.
3ae06f68 4363 copy_to_heap = context->function() != NULL;
f23d7786 4364 }
438b4bec 4365 std::string asm_name(go_selectively_encode_id(buf));
f23d7786 4366 Bvariable* implicit =
438b4bec 4367 gogo->backend()->implicit_variable(buf, asm_name,
4368 btype, true, copy_to_heap,
4369 false, 0);
aa5ae575 4370 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4371 true, copy_to_heap, false,
4372 bexpr);
d4e6573e 4373 bexpr = gogo->backend()->var_expression(implicit, VE_lvalue, loc);
1b4fb1e0 4374
4375 // If we are not copying a slice initializer to the heap,
4376 // then it can be changed by the program, so if it can
4377 // contain pointers we must register it as a GC root.
4378 if (this->is_slice_init_
4379 && !copy_to_heap
4380 && this->expr_->type()->has_pointer())
4381 {
4382 Bexpression* root =
d4e6573e 4383 gogo->backend()->var_expression(implicit, VE_lvalue, loc);
1b4fb1e0 4384 root = gogo->backend()->address_expression(root, loc);
4385 Type* type = Type::make_pointer_type(this->expr_->type());
4386 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4387 }
76f85fd6 4388 }
4389 else if ((this->expr_->is_composite_literal()
3ae06f68 4390 || this->expr_->string_expression() != NULL)
4391 && this->expr_->is_static_initializer())
f9ca30f9 4392 {
76f85fd6 4393 // Build a decl for a constant constructor.
f9ca30f9 4394 snprintf(buf, sizeof buf, "C%u", counter);
4395 ++counter;
4396
438b4bec 4397 std::string asm_name(go_selectively_encode_id(buf));
f9ca30f9 4398 Bvariable* decl =
438b4bec 4399 gogo->backend()->immutable_struct(buf, asm_name,
4400 true, false, btype, loc);
f9ca30f9 4401 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4402 btype, loc, bexpr);
d4e6573e 4403 bexpr = gogo->backend()->var_expression(decl, VE_lvalue, loc);
f9ca30f9 4404 }
09ea332d 4405
f9ca30f9 4406 go_assert(!this->create_temp_ || this->expr_->is_variable());
4407 ret = gogo->backend()->address_expression(bexpr, loc);
4408 break;
e440a328 4409
4410 case OPERATOR_MULT:
4411 {
f9ca30f9 4412 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4413
4414 // If we are dereferencing the pointer to a large struct, we
4415 // need to check for nil. We don't bother to check for small
4416 // structs because we expect the system to crash on a nil
56080003 4417 // pointer dereference. However, if we know the address of this
4418 // expression is being taken, we must always check for nil.
f9ca30f9 4419
4420 Type* ptype = this->expr_->type()->points_to();
4421 Btype* pbtype = ptype->get_backend(gogo);
4422 if (!ptype->is_void_type())
e440a328 4423 {
2a305b85 4424 int64_t s;
4425 bool ok = ptype->backend_type_size(gogo, &s);
4426 if (!ok)
4427 {
4428 go_assert(saw_errors());
4429 return gogo->backend()->error_expression();
4430 }
f9ca30f9 4431 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4432 {
f9ca30f9 4433 go_assert(this->expr_->is_variable());
ea664253 4434 Bexpression* nil =
4435 Expression::make_nil(loc)->get_backend(context);
f9ca30f9 4436 Bexpression* compare =
4437 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4438 nil, loc);
f9ca30f9 4439 Bexpression* crash =
ea664253 4440 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4441 loc)->get_backend(context);
93715b75 4442 Bfunction* bfn = context->function()->func_value()->get_decl();
4443 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4444 compare,
f9ca30f9 4445 crash, bexpr,
4446 loc);
4447
19b4f09b 4448 }
e440a328 4449 }
9b27b43c 4450 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
e440a328 4451 }
f9ca30f9 4452 break;
e440a328 4453
4454 default:
c3e6f413 4455 go_unreachable();
e440a328 4456 }
f9ca30f9 4457
ea664253 4458 return ret;
e440a328 4459}
4460
4461// Export a unary expression.
4462
4463void
4464Unary_expression::do_export(Export* exp) const
4465{
4466 switch (this->op_)
4467 {
4468 case OPERATOR_PLUS:
4469 exp->write_c_string("+ ");
4470 break;
4471 case OPERATOR_MINUS:
4472 exp->write_c_string("- ");
4473 break;
4474 case OPERATOR_NOT:
4475 exp->write_c_string("! ");
4476 break;
4477 case OPERATOR_XOR:
4478 exp->write_c_string("^ ");
4479 break;
4480 case OPERATOR_AND:
4481 case OPERATOR_MULT:
4482 default:
c3e6f413 4483 go_unreachable();
e440a328 4484 }
4485 this->expr_->export_expression(exp);
4486}
4487
4488// Import a unary expression.
4489
4490Expression*
4491Unary_expression::do_import(Import* imp)
4492{
4493 Operator op;
4494 switch (imp->get_char())
4495 {
4496 case '+':
4497 op = OPERATOR_PLUS;
4498 break;
4499 case '-':
4500 op = OPERATOR_MINUS;
4501 break;
4502 case '!':
4503 op = OPERATOR_NOT;
4504 break;
4505 case '^':
4506 op = OPERATOR_XOR;
4507 break;
4508 default:
c3e6f413 4509 go_unreachable();
e440a328 4510 }
4511 imp->require_c_string(" ");
4512 Expression* expr = Expression::import_expression(imp);
4513 return Expression::make_unary(op, expr, imp->location());
4514}
4515
d751bb78 4516// Dump ast representation of an unary expression.
4517
4518void
4519Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4520{
4521 ast_dump_context->dump_operator(this->op_);
4522 ast_dump_context->ostream() << "(";
4523 ast_dump_context->dump_expression(this->expr_);
4524 ast_dump_context->ostream() << ") ";
4525}
4526
e440a328 4527// Make a unary expression.
4528
4529Expression*
b13c66cd 4530Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4531{
4532 return new Unary_expression(op, expr, location);
4533}
4534
4535// If this is an indirection through a pointer, return the expression
4536// being pointed through. Otherwise return this.
4537
4538Expression*
4539Expression::deref()
4540{
4541 if (this->classification_ == EXPRESSION_UNARY)
4542 {
4543 Unary_expression* ue = static_cast<Unary_expression*>(this);
4544 if (ue->op() == OPERATOR_MULT)
4545 return ue->operand();
4546 }
4547 return this;
4548}
4549
4550// Class Binary_expression.
4551
4552// Traversal.
4553
4554int
4555Binary_expression::do_traverse(Traverse* traverse)
4556{
4557 int t = Expression::traverse(&this->left_, traverse);
4558 if (t == TRAVERSE_EXIT)
4559 return TRAVERSE_EXIT;
4560 return Expression::traverse(&this->right_, traverse);
4561}
4562
3ae06f68 4563// Return whether this expression may be used as a static initializer.
4564
4565bool
4566Binary_expression::do_is_static_initializer() const
4567{
4568 if (!this->left_->is_static_initializer()
4569 || !this->right_->is_static_initializer())
4570 return false;
4571
4572 // Addresses can be static initializers, but we can't implement
4573 // arbitray binary expressions of them.
4574 Unary_expression* lu = this->left_->unary_expression();
4575 Unary_expression* ru = this->right_->unary_expression();
4576 if (lu != NULL && lu->op() == OPERATOR_AND)
4577 {
4578 if (ru != NULL && ru->op() == OPERATOR_AND)
4579 return this->op_ == OPERATOR_MINUS;
4580 else
4581 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4582 }
4583 else if (ru != NULL && ru->op() == OPERATOR_AND)
4584 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4585
4586 // Other cases should resolve in the backend.
4587 return true;
4588}
4589
0c77715b 4590// Return the type to use for a binary operation on operands of
4591// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4592// such may be NULL or abstract.
4593
4594bool
4595Binary_expression::operation_type(Operator op, Type* left_type,
4596 Type* right_type, Type** result_type)
4597{
4598 if (left_type != right_type
4599 && !left_type->is_abstract()
4600 && !right_type->is_abstract()
4601 && left_type->base() != right_type->base()
4602 && op != OPERATOR_LSHIFT
4603 && op != OPERATOR_RSHIFT)
4604 {
4605 // May be a type error--let it be diagnosed elsewhere.
4606 return false;
4607 }
4608
4609 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4610 {
4611 if (left_type->integer_type() != NULL)
4612 *result_type = left_type;
4613 else
4614 *result_type = Type::make_abstract_integer_type();
4615 }
4616 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4617 *result_type = left_type;
4618 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4619 *result_type = right_type;
4620 else if (!left_type->is_abstract())
4621 *result_type = left_type;
4622 else if (!right_type->is_abstract())
4623 *result_type = right_type;
4624 else if (left_type->complex_type() != NULL)
4625 *result_type = left_type;
4626 else if (right_type->complex_type() != NULL)
4627 *result_type = right_type;
4628 else if (left_type->float_type() != NULL)
4629 *result_type = left_type;
4630 else if (right_type->float_type() != NULL)
4631 *result_type = right_type;
4632 else if (left_type->integer_type() != NULL
4633 && left_type->integer_type()->is_rune())
4634 *result_type = left_type;
4635 else if (right_type->integer_type() != NULL
4636 && right_type->integer_type()->is_rune())
4637 *result_type = right_type;
4638 else
4639 *result_type = left_type;
4640
4641 return true;
4642}
4643
4644// Convert an integer comparison code and an operator to a boolean
4645// value.
e440a328 4646
4647bool
0c77715b 4648Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4649{
e440a328 4650 switch (op)
4651 {
4652 case OPERATOR_EQEQ:
0c77715b 4653 return cmp == 0;
4654 break;
e440a328 4655 case OPERATOR_NOTEQ:
0c77715b 4656 return cmp != 0;
4657 break;
e440a328 4658 case OPERATOR_LT:
0c77715b 4659 return cmp < 0;
4660 break;
e440a328 4661 case OPERATOR_LE:
0c77715b 4662 return cmp <= 0;
e440a328 4663 case OPERATOR_GT:
0c77715b 4664 return cmp > 0;
e440a328 4665 case OPERATOR_GE:
0c77715b 4666 return cmp >= 0;
e440a328 4667 default:
c3e6f413 4668 go_unreachable();
e440a328 4669 }
4670}
4671
0c77715b 4672// Compare constants according to OP.
e440a328 4673
4674bool
0c77715b 4675Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4676 Numeric_constant* right_nc,
4677 Location location, bool* result)
e440a328 4678{
0c77715b 4679 Type* left_type = left_nc->type();
4680 Type* right_type = right_nc->type();
4681
4682 Type* type;
4683 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4684 return false;
4685
4686 // When comparing an untyped operand to a typed operand, we are
4687 // effectively coercing the untyped operand to the other operand's
4688 // type, so make sure that is valid.
4689 if (!left_nc->set_type(type, true, location)
4690 || !right_nc->set_type(type, true, location))
4691 return false;
4692
4693 bool ret;
4694 int cmp;
4695 if (type->complex_type() != NULL)
4696 {
4697 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4698 return false;
4699 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4700 }
4701 else if (type->float_type() != NULL)
4702 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4703 else
0c77715b 4704 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4705
4706 if (ret)
4707 *result = Binary_expression::cmp_to_bool(op, cmp);
4708
4709 return ret;
4710}
4711
4712// Compare integer constants.
4713
4714bool
4715Binary_expression::compare_integer(const Numeric_constant* left_nc,
4716 const Numeric_constant* right_nc,
4717 int* cmp)
4718{
4719 mpz_t left_val;
4720 if (!left_nc->to_int(&left_val))
4721 return false;
4722 mpz_t right_val;
4723 if (!right_nc->to_int(&right_val))
e440a328 4724 {
0c77715b 4725 mpz_clear(left_val);
4726 return false;
e440a328 4727 }
0c77715b 4728
4729 *cmp = mpz_cmp(left_val, right_val);
4730
4731 mpz_clear(left_val);
4732 mpz_clear(right_val);
4733
4734 return true;
4735}
4736
4737// Compare floating point constants.
4738
4739bool
4740Binary_expression::compare_float(const Numeric_constant* left_nc,
4741 const Numeric_constant* right_nc,
4742 int* cmp)
4743{
4744 mpfr_t left_val;
4745 if (!left_nc->to_float(&left_val))
4746 return false;
4747 mpfr_t right_val;
4748 if (!right_nc->to_float(&right_val))
e440a328 4749 {
0c77715b 4750 mpfr_clear(left_val);
4751 return false;
4752 }
4753
4754 // We already coerced both operands to the same type. If that type
4755 // is not an abstract type, we need to round the values accordingly.
4756 Type* type = left_nc->type();
4757 if (!type->is_abstract() && type->float_type() != NULL)
4758 {
4759 int bits = type->float_type()->bits();
4760 mpfr_prec_round(left_val, bits, GMP_RNDN);
4761 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4762 }
0c77715b 4763
4764 *cmp = mpfr_cmp(left_val, right_val);
4765
4766 mpfr_clear(left_val);
4767 mpfr_clear(right_val);
4768
4769 return true;
e440a328 4770}
4771
0c77715b 4772// Compare complex constants. Complex numbers may only be compared
4773// for equality.
e440a328 4774
4775bool
0c77715b 4776Binary_expression::compare_complex(const Numeric_constant* left_nc,
4777 const Numeric_constant* right_nc,
4778 int* cmp)
e440a328 4779{
fcbea5e4 4780 mpc_t left_val;
4781 if (!left_nc->to_complex(&left_val))
0c77715b 4782 return false;
fcbea5e4 4783 mpc_t right_val;
4784 if (!right_nc->to_complex(&right_val))
e440a328 4785 {
fcbea5e4 4786 mpc_clear(left_val);
0c77715b 4787 return false;
e440a328 4788 }
0c77715b 4789
4790 // We already coerced both operands to the same type. If that type
4791 // is not an abstract type, we need to round the values accordingly.
4792 Type* type = left_nc->type();
4793 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4794 {
0c77715b 4795 int bits = type->complex_type()->bits();
fcbea5e4 4796 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4797 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4798 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4799 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
e440a328 4800 }
0c77715b 4801
fcbea5e4 4802 *cmp = mpc_cmp(left_val, right_val) != 0;
0c77715b 4803
fcbea5e4 4804 mpc_clear(left_val);
4805 mpc_clear(right_val);
0c77715b 4806
4807 return true;
e440a328 4808}
4809
0c77715b 4810// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4811// true if this could be done, false if not. Issue errors at LOCATION
af7a5274 4812// as appropriate, and sets *ISSUED_ERROR if it did.
e440a328 4813
4814bool
0c77715b 4815Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4816 Numeric_constant* right_nc,
af7a5274 4817 Location location, Numeric_constant* nc,
4818 bool* issued_error)
e440a328 4819{
af7a5274 4820 *issued_error = false;
e440a328 4821 switch (op)
4822 {
4823 case OPERATOR_OROR:
4824 case OPERATOR_ANDAND:
4825 case OPERATOR_EQEQ:
4826 case OPERATOR_NOTEQ:
4827 case OPERATOR_LT:
4828 case OPERATOR_LE:
4829 case OPERATOR_GT:
4830 case OPERATOR_GE:
9767e2d3 4831 // These return boolean values, not numeric.
4832 return false;
0c77715b 4833 default:
4834 break;
4835 }
4836
4837 Type* left_type = left_nc->type();
4838 Type* right_type = right_nc->type();
4839
4840 Type* type;
4841 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4842 return false;
4843
4844 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4845
4846 // When combining an untyped operand with a typed operand, we are
4847 // effectively coercing the untyped operand to the other operand's
4848 // type, so make sure that is valid.
4849 if (!left_nc->set_type(type, true, location))
4850 return false;
4851 if (!is_shift && !right_nc->set_type(type, true, location))
4852 return false;
85334a21 4853 if (is_shift
4854 && ((left_type->integer_type() == NULL
4855 && !left_type->is_abstract())
4856 || (right_type->integer_type() == NULL
4857 && !right_type->is_abstract())))
4858 return false;
0c77715b 4859
4860 bool r;
4861 if (type->complex_type() != NULL)
4862 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4863 else if (type->float_type() != NULL)
4864 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4865 else
4866 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4867
4868 if (r)
af7a5274 4869 {
4870 r = nc->set_type(type, true, location);
4871 if (!r)
4872 *issued_error = true;
4873 }
0c77715b 4874
4875 return r;
4876}
4877
4878// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4879// integer operations. Return true if this could be done, false if
4880// not.
4881
4882bool
4883Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4884 const Numeric_constant* right_nc,
4885 Location location, Numeric_constant* nc)
4886{
4887 mpz_t left_val;
4888 if (!left_nc->to_int(&left_val))
4889 return false;
4890 mpz_t right_val;
4891 if (!right_nc->to_int(&right_val))
4892 {
4893 mpz_clear(left_val);
e440a328 4894 return false;
0c77715b 4895 }
4896
4897 mpz_t val;
4898 mpz_init(val);
4899
4900 switch (op)
4901 {
e440a328 4902 case OPERATOR_PLUS:
4903 mpz_add(val, left_val, right_val);
2c809f8f 4904 if (mpz_sizeinbase(val, 2) > 0x100000)
4905 {
631d5788 4906 go_error_at(location, "constant addition overflow");
71a45216 4907 nc->set_invalid();
2c809f8f 4908 mpz_set_ui(val, 1);
4909 }
e440a328 4910 break;
4911 case OPERATOR_MINUS:
4912 mpz_sub(val, left_val, right_val);
2c809f8f 4913 if (mpz_sizeinbase(val, 2) > 0x100000)
4914 {
631d5788 4915 go_error_at(location, "constant subtraction overflow");
71a45216 4916 nc->set_invalid();
2c809f8f 4917 mpz_set_ui(val, 1);
4918 }
e440a328 4919 break;
4920 case OPERATOR_OR:
4921 mpz_ior(val, left_val, right_val);
4922 break;
4923 case OPERATOR_XOR:
4924 mpz_xor(val, left_val, right_val);
4925 break;
4926 case OPERATOR_MULT:
4927 mpz_mul(val, left_val, right_val);
2c809f8f 4928 if (mpz_sizeinbase(val, 2) > 0x100000)
4929 {
631d5788 4930 go_error_at(location, "constant multiplication overflow");
71a45216 4931 nc->set_invalid();
2c809f8f 4932 mpz_set_ui(val, 1);
4933 }
e440a328 4934 break;
4935 case OPERATOR_DIV:
4936 if (mpz_sgn(right_val) != 0)
4937 mpz_tdiv_q(val, left_val, right_val);
4938 else
4939 {
631d5788 4940 go_error_at(location, "division by zero");
71a45216 4941 nc->set_invalid();
e440a328 4942 mpz_set_ui(val, 0);
e440a328 4943 }
4944 break;
4945 case OPERATOR_MOD:
4946 if (mpz_sgn(right_val) != 0)
4947 mpz_tdiv_r(val, left_val, right_val);
4948 else
4949 {
631d5788 4950 go_error_at(location, "division by zero");
71a45216 4951 nc->set_invalid();
e440a328 4952 mpz_set_ui(val, 0);
e440a328 4953 }
4954 break;
4955 case OPERATOR_LSHIFT:
4956 {
4957 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4958 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4959 mpz_mul_2exp(val, left_val, shift);
4960 else
e440a328 4961 {
631d5788 4962 go_error_at(location, "shift count overflow");
71a45216 4963 nc->set_invalid();
2c809f8f 4964 mpz_set_ui(val, 1);
e440a328 4965 }
e440a328 4966 break;
4967 }
4968 break;
4969 case OPERATOR_RSHIFT:
4970 {
4971 unsigned long shift = mpz_get_ui(right_val);
4972 if (mpz_cmp_ui(right_val, shift) != 0)
4973 {
631d5788 4974 go_error_at(location, "shift count overflow");
71a45216 4975 nc->set_invalid();
2c809f8f 4976 mpz_set_ui(val, 1);
e440a328 4977 }
e440a328 4978 else
0c77715b 4979 {
4980 if (mpz_cmp_ui(left_val, 0) >= 0)
4981 mpz_tdiv_q_2exp(val, left_val, shift);
4982 else
4983 mpz_fdiv_q_2exp(val, left_val, shift);
4984 }
e440a328 4985 break;
4986 }
4987 break;
4988 case OPERATOR_AND:
4989 mpz_and(val, left_val, right_val);
4990 break;
4991 case OPERATOR_BITCLEAR:
4992 {
4993 mpz_t tval;
4994 mpz_init(tval);
4995 mpz_com(tval, right_val);
4996 mpz_and(val, left_val, tval);
4997 mpz_clear(tval);
4998 }
4999 break;
5000 default:
c3e6f413 5001 go_unreachable();
e440a328 5002 }
5003
0c77715b 5004 mpz_clear(left_val);
5005 mpz_clear(right_val);
e440a328 5006
0c77715b 5007 if (left_nc->is_rune()
5008 || (op != OPERATOR_LSHIFT
5009 && op != OPERATOR_RSHIFT
5010 && right_nc->is_rune()))
5011 nc->set_rune(NULL, val);
5012 else
5013 nc->set_int(NULL, val);
5014
5015 mpz_clear(val);
e440a328 5016
5017 return true;
5018}
5019
0c77715b 5020// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5021// floating point operations. Return true if this could be done,
5022// false if not.
e440a328 5023
5024bool
0c77715b 5025Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5026 const Numeric_constant* right_nc,
5027 Location location, Numeric_constant* nc)
e440a328 5028{
0c77715b 5029 mpfr_t left_val;
5030 if (!left_nc->to_float(&left_val))
5031 return false;
5032 mpfr_t right_val;
5033 if (!right_nc->to_float(&right_val))
e440a328 5034 {
0c77715b 5035 mpfr_clear(left_val);
e440a328 5036 return false;
0c77715b 5037 }
5038
5039 mpfr_t val;
5040 mpfr_init(val);
5041
5042 bool ret = true;
5043 switch (op)
5044 {
e440a328 5045 case OPERATOR_PLUS:
5046 mpfr_add(val, left_val, right_val, GMP_RNDN);
5047 break;
5048 case OPERATOR_MINUS:
5049 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5050 break;
5051 case OPERATOR_OR:
5052 case OPERATOR_XOR:
5053 case OPERATOR_AND:
5054 case OPERATOR_BITCLEAR:
0c77715b 5055 case OPERATOR_MOD:
5056 case OPERATOR_LSHIFT:
5057 case OPERATOR_RSHIFT:
5058 mpfr_set_ui(val, 0, GMP_RNDN);
5059 ret = false;
5060 break;
e440a328 5061 case OPERATOR_MULT:
5062 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5063 break;
5064 case OPERATOR_DIV:
0c77715b 5065 if (!mpfr_zero_p(right_val))
5066 mpfr_div(val, left_val, right_val, GMP_RNDN);
5067 else
5068 {
631d5788 5069 go_error_at(location, "division by zero");
71a45216 5070 nc->set_invalid();
0c77715b 5071 mpfr_set_ui(val, 0, GMP_RNDN);
5072 }
e440a328 5073 break;
e440a328 5074 default:
c3e6f413 5075 go_unreachable();
e440a328 5076 }
5077
0c77715b 5078 mpfr_clear(left_val);
5079 mpfr_clear(right_val);
e440a328 5080
0c77715b 5081 nc->set_float(NULL, val);
5082 mpfr_clear(val);
e440a328 5083
0c77715b 5084 return ret;
e440a328 5085}
5086
0c77715b 5087// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5088// complex operations. Return true if this could be done, false if
5089// not.
e440a328 5090
5091bool
0c77715b 5092Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5093 const Numeric_constant* right_nc,
5094 Location location, Numeric_constant* nc)
e440a328 5095{
fcbea5e4 5096 mpc_t left_val;
5097 if (!left_nc->to_complex(&left_val))
0c77715b 5098 return false;
fcbea5e4 5099 mpc_t right_val;
5100 if (!right_nc->to_complex(&right_val))
e440a328 5101 {
fcbea5e4 5102 mpc_clear(left_val);
e440a328 5103 return false;
0c77715b 5104 }
5105
fcbea5e4 5106 mpc_t val;
5107 mpc_init2(val, mpc_precision);
0c77715b 5108
5109 bool ret = true;
5110 switch (op)
5111 {
e440a328 5112 case OPERATOR_PLUS:
fcbea5e4 5113 mpc_add(val, left_val, right_val, MPC_RNDNN);
e440a328 5114 break;
5115 case OPERATOR_MINUS:
fcbea5e4 5116 mpc_sub(val, left_val, right_val, MPC_RNDNN);
e440a328 5117 break;
5118 case OPERATOR_OR:
5119 case OPERATOR_XOR:
5120 case OPERATOR_AND:
5121 case OPERATOR_BITCLEAR:
0c77715b 5122 case OPERATOR_MOD:
5123 case OPERATOR_LSHIFT:
5124 case OPERATOR_RSHIFT:
fcbea5e4 5125 mpc_set_ui(val, 0, MPC_RNDNN);
0c77715b 5126 ret = false;
5127 break;
e440a328 5128 case OPERATOR_MULT:
fcbea5e4 5129 mpc_mul(val, left_val, right_val, MPC_RNDNN);
e440a328 5130 break;
5131 case OPERATOR_DIV:
fcbea5e4 5132 if (mpc_cmp_si(right_val, 0) == 0)
5133 {
631d5788 5134 go_error_at(location, "division by zero");
71a45216 5135 nc->set_invalid();
fcbea5e4 5136 mpc_set_ui(val, 0, MPC_RNDNN);
5137 break;
5138 }
5139 mpc_div(val, left_val, right_val, MPC_RNDNN);
e440a328 5140 break;
e440a328 5141 default:
c3e6f413 5142 go_unreachable();
e440a328 5143 }
5144
fcbea5e4 5145 mpc_clear(left_val);
5146 mpc_clear(right_val);
e440a328 5147
fcbea5e4 5148 nc->set_complex(NULL, val);
5149 mpc_clear(val);
e440a328 5150
0c77715b 5151 return ret;
e440a328 5152}
5153
5154// Lower a binary expression. We have to evaluate constant
5155// expressions now, in order to implement Go's unlimited precision
5156// constants.
5157
5158Expression*
e9d3367e 5159Binary_expression::do_lower(Gogo* gogo, Named_object*,
5160 Statement_inserter* inserter, int)
e440a328 5161{
b13c66cd 5162 Location location = this->location();
e440a328 5163 Operator op = this->op_;
5164 Expression* left = this->left_;
5165 Expression* right = this->right_;
5166
5167 const bool is_comparison = (op == OPERATOR_EQEQ
5168 || op == OPERATOR_NOTEQ
5169 || op == OPERATOR_LT
5170 || op == OPERATOR_LE
5171 || op == OPERATOR_GT
5172 || op == OPERATOR_GE);
5173
0c77715b 5174 // Numeric constant expressions.
e440a328 5175 {
0c77715b 5176 Numeric_constant left_nc;
5177 Numeric_constant right_nc;
5178 if (left->numeric_constant_value(&left_nc)
5179 && right->numeric_constant_value(&right_nc))
e440a328 5180 {
0c77715b 5181 if (is_comparison)
e440a328 5182 {
0c77715b 5183 bool result;
5184 if (!Binary_expression::compare_constant(op, &left_nc,
5185 &right_nc, location,
5186 &result))
5187 return this;
e90c9dfc 5188 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5189 Expression::make_boolean(result,
5190 location),
5191 location);
e440a328 5192 }
5193 else
5194 {
0c77715b 5195 Numeric_constant nc;
af7a5274 5196 bool issued_error;
0c77715b 5197 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
af7a5274 5198 location, &nc,
5199 &issued_error))
5200 {
5201 if (issued_error)
5202 return Expression::make_error(location);
71a45216 5203 return this;
af7a5274 5204 }
0c77715b 5205 return nc.expression(location);
e440a328 5206 }
5207 }
e440a328 5208 }
5209
5210 // String constant expressions.
315fa98d 5211 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5212 {
5213 std::string left_string;
5214 std::string right_string;
5215 if (left->string_constant_value(&left_string)
5216 && right->string_constant_value(&right_string))
315fa98d 5217 {
5218 if (op == OPERATOR_PLUS)
5219 return Expression::make_string(left_string + right_string,
5220 location);
5221 else if (is_comparison)
5222 {
5223 int cmp = left_string.compare(right_string);
0c77715b 5224 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5225 return Expression::make_boolean(r, location);
b40dc774 5226 }
5227 }
b40dc774 5228 }
5229
ceeb12d7 5230 // Lower struct, array, and some interface comparisons.
e9d3367e 5231 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5232 {
b79832ca 5233 if (left->type()->struct_type() != NULL
5234 && right->type()->struct_type() != NULL)
e9d3367e 5235 return this->lower_struct_comparison(gogo, inserter);
5236 else if (left->type()->array_type() != NULL
b79832ca 5237 && !left->type()->is_slice_type()
5238 && right->type()->array_type() != NULL
5239 && !right->type()->is_slice_type())
e9d3367e 5240 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5241 else if ((left->type()->interface_type() != NULL
5242 && right->type()->interface_type() == NULL)
5243 || (left->type()->interface_type() == NULL
5244 && right->type()->interface_type() != NULL))
5245 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5246 }
5247
736a16ba 5248 // Lower string concatenation to String_concat_expression, so that
5249 // we can group sequences of string additions.
5250 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5251 {
5252 Expression_list* exprs;
5253 String_concat_expression* left_sce =
5254 this->left_->string_concat_expression();
5255 if (left_sce != NULL)
5256 exprs = left_sce->exprs();
5257 else
5258 {
5259 exprs = new Expression_list();
5260 exprs->push_back(this->left_);
5261 }
5262
5263 String_concat_expression* right_sce =
5264 this->right_->string_concat_expression();
5265 if (right_sce != NULL)
5266 exprs->append(right_sce->exprs());
5267 else
5268 exprs->push_back(this->right_);
5269
5270 return Expression::make_string_concat(exprs);
5271 }
5272
e440a328 5273 return this;
5274}
5275
e9d3367e 5276// Lower a struct comparison.
5277
5278Expression*
5279Binary_expression::lower_struct_comparison(Gogo* gogo,
5280 Statement_inserter* inserter)
5281{
5282 Struct_type* st = this->left_->type()->struct_type();
5283 Struct_type* st2 = this->right_->type()->struct_type();
5284 if (st2 == NULL)
5285 return this;
5286 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5287 return this;
5288 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5289 this->right_->type(), NULL))
5290 return this;
5291
5292 // See if we can compare using memcmp. As a heuristic, we use
5293 // memcmp rather than field references and comparisons if there are
5294 // more than two fields.
113ef6a5 5295 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5296 return this->lower_compare_to_memcmp(gogo, inserter);
5297
5298 Location loc = this->location();
5299
5300 Expression* left = this->left_;
5301 Temporary_statement* left_temp = NULL;
5302 if (left->var_expression() == NULL
5303 && left->temporary_reference_expression() == NULL)
5304 {
5305 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5306 inserter->insert(left_temp);
5307 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5308 }
5309
5310 Expression* right = this->right_;
5311 Temporary_statement* right_temp = NULL;
5312 if (right->var_expression() == NULL
5313 && right->temporary_reference_expression() == NULL)
5314 {
5315 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5316 inserter->insert(right_temp);
5317 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5318 }
5319
5320 Expression* ret = Expression::make_boolean(true, loc);
5321 const Struct_field_list* fields = st->fields();
5322 unsigned int field_index = 0;
5323 for (Struct_field_list::const_iterator pf = fields->begin();
5324 pf != fields->end();
5325 ++pf, ++field_index)
5326 {
f5165c05 5327 if (Gogo::is_sink_name(pf->field_name()))
5328 continue;
5329
e9d3367e 5330 if (field_index > 0)
5331 {
5332 if (left_temp == NULL)
5333 left = left->copy();
5334 else
5335 left = Expression::make_temporary_reference(left_temp, loc);
5336 if (right_temp == NULL)
5337 right = right->copy();
5338 else
5339 right = Expression::make_temporary_reference(right_temp, loc);
5340 }
5341 Expression* f1 = Expression::make_field_reference(left, field_index,
5342 loc);
5343 Expression* f2 = Expression::make_field_reference(right, field_index,
5344 loc);
5345 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5346 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5347 }
5348
5349 if (this->op_ == OPERATOR_NOTEQ)
5350 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5351
5352 return ret;
5353}
5354
5355// Lower an array comparison.
5356
5357Expression*
5358Binary_expression::lower_array_comparison(Gogo* gogo,
5359 Statement_inserter* inserter)
5360{
5361 Array_type* at = this->left_->type()->array_type();
5362 Array_type* at2 = this->right_->type()->array_type();
5363 if (at2 == NULL)
5364 return this;
5365 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5366 return this;
5367 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5368 this->right_->type(), NULL))
5369 return this;
5370
5371 // Call memcmp directly if possible. This may let the middle-end
5372 // optimize the call.
113ef6a5 5373 if (at->compare_is_identity(gogo))
e9d3367e 5374 return this->lower_compare_to_memcmp(gogo, inserter);
5375
5376 // Call the array comparison function.
5377 Named_object* hash_fn;
5378 Named_object* equal_fn;
5379 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5380 &hash_fn, &equal_fn);
5381
5382 Location loc = this->location();
5383
5384 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5385
5386 Expression_list* args = new Expression_list();
5387 args->push_back(this->operand_address(inserter, this->left_));
5388 args->push_back(this->operand_address(inserter, this->right_));
e9d3367e 5389
5390 Expression* ret = Expression::make_call(func, args, false, loc);
5391
5392 if (this->op_ == OPERATOR_NOTEQ)
5393 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5394
5395 return ret;
5396}
5397
ceeb12d7 5398// Lower an interface to value comparison.
5399
5400Expression*
5401Binary_expression::lower_interface_value_comparison(Gogo*,
5402 Statement_inserter* inserter)
5403{
5404 Type* left_type = this->left_->type();
5405 Type* right_type = this->right_->type();
5406 Interface_type* ift;
5407 if (left_type->interface_type() != NULL)
5408 {
5409 ift = left_type->interface_type();
5410 if (!ift->implements_interface(right_type, NULL))
5411 return this;
5412 }
5413 else
5414 {
5415 ift = right_type->interface_type();
5416 if (!ift->implements_interface(left_type, NULL))
5417 return this;
5418 }
5419 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5420 return this;
5421
5422 Location loc = this->location();
5423
5424 if (left_type->interface_type() == NULL
5425 && left_type->points_to() == NULL
5426 && !this->left_->is_addressable())
5427 {
5428 Temporary_statement* temp =
5429 Statement::make_temporary(left_type, NULL, loc);
5430 inserter->insert(temp);
5431 this->left_ =
5432 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5433 }
5434
5435 if (right_type->interface_type() == NULL
5436 && right_type->points_to() == NULL
5437 && !this->right_->is_addressable())
5438 {
5439 Temporary_statement* temp =
5440 Statement::make_temporary(right_type, NULL, loc);
5441 inserter->insert(temp);
5442 this->right_ =
5443 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5444 }
5445
5446 return this;
5447}
5448
e9d3367e 5449// Lower a struct or array comparison to a call to memcmp.
5450
5451Expression*
5452Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5453{
5454 Location loc = this->location();
5455
5456 Expression* a1 = this->operand_address(inserter, this->left_);
5457 Expression* a2 = this->operand_address(inserter, this->right_);
5458 Expression* len = Expression::make_type_info(this->left_->type(),
5459 TYPE_INFO_SIZE);
5460
5461 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
e67508fa 5462 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
e9d3367e 5463 return Expression::make_binary(this->op_, call, zero, loc);
5464}
5465
a32698ee 5466Expression*
5c3f3470 5467Binary_expression::do_flatten(Gogo* gogo, Named_object*,
a32698ee 5468 Statement_inserter* inserter)
5469{
5470 Location loc = this->location();
5bf8be8b 5471 if (this->left_->type()->is_error_type()
5472 || this->right_->type()->is_error_type()
5473 || this->left_->is_error_expression()
5474 || this->right_->is_error_expression())
5475 {
5476 go_assert(saw_errors());
5477 return Expression::make_error(loc);
5478 }
5479
a32698ee 5480 Temporary_statement* temp;
a32698ee 5481
5482 Type* left_type = this->left_->type();
5483 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5484 || this->op_ == OPERATOR_RSHIFT);
5485 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5486 left_type->integer_type() != NULL)
5487 || this->op_ == OPERATOR_MOD);
5488
a32698ee 5489 if (is_shift_op
5c3f3470 5490 || (is_idiv_op
5491 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
a32698ee 5492 {
545ab43b 5493 if (!this->left_->is_variable() && !this->left_->is_constant())
a32698ee 5494 {
5495 temp = Statement::make_temporary(NULL, this->left_, loc);
5496 inserter->insert(temp);
5497 this->left_ = Expression::make_temporary_reference(temp, loc);
5498 }
545ab43b 5499 if (!this->right_->is_variable() && !this->right_->is_constant())
a32698ee 5500 {
5501 temp =
5502 Statement::make_temporary(NULL, this->right_, loc);
5503 this->right_ = Expression::make_temporary_reference(temp, loc);
5504 inserter->insert(temp);
5505 }
5506 }
5507 return this;
5508}
5509
5510
e9d3367e 5511// Return the address of EXPR, cast to unsafe.Pointer.
5512
5513Expression*
5514Binary_expression::operand_address(Statement_inserter* inserter,
5515 Expression* expr)
5516{
5517 Location loc = this->location();
5518
5519 if (!expr->is_addressable())
5520 {
5521 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5522 loc);
5523 inserter->insert(temp);
5524 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5525 }
5526 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5527 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5528 Type* void_type = Type::make_void_type();
5529 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5530 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5531}
5532
0c77715b 5533// Return the numeric constant value, if it has one.
e440a328 5534
5535bool
0c77715b 5536Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5537{
0c77715b 5538 Numeric_constant left_nc;
5539 if (!this->left_->numeric_constant_value(&left_nc))
5540 return false;
5541 Numeric_constant right_nc;
5542 if (!this->right_->numeric_constant_value(&right_nc))
5543 return false;
af7a5274 5544 bool issued_error;
9767e2d3 5545 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
af7a5274 5546 this->location(), nc, &issued_error);
e440a328 5547}
5548
5549// Note that the value is being discarded.
5550
4f2138d7 5551bool
e440a328 5552Binary_expression::do_discarding_value()
5553{
5554 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5555 return this->right_->discarding_value();
e440a328 5556 else
4f2138d7 5557 {
5558 this->unused_value_error();
5559 return false;
5560 }
e440a328 5561}
5562
5563// Get type.
5564
5565Type*
5566Binary_expression::do_type()
5567{
5f5fea79 5568 if (this->classification() == EXPRESSION_ERROR)
5569 return Type::make_error_type();
5570
e440a328 5571 switch (this->op_)
5572 {
e440a328 5573 case OPERATOR_EQEQ:
5574 case OPERATOR_NOTEQ:
5575 case OPERATOR_LT:
5576 case OPERATOR_LE:
5577 case OPERATOR_GT:
5578 case OPERATOR_GE:
e90c9dfc 5579 if (this->type_ == NULL)
5580 this->type_ = Type::make_boolean_type();
5581 return this->type_;
e440a328 5582
5583 case OPERATOR_PLUS:
5584 case OPERATOR_MINUS:
5585 case OPERATOR_OR:
5586 case OPERATOR_XOR:
5587 case OPERATOR_MULT:
5588 case OPERATOR_DIV:
5589 case OPERATOR_MOD:
5590 case OPERATOR_AND:
5591 case OPERATOR_BITCLEAR:
e90c9dfc 5592 case OPERATOR_OROR:
5593 case OPERATOR_ANDAND:
e440a328 5594 {
0c77715b 5595 Type* type;
5596 if (!Binary_expression::operation_type(this->op_,
5597 this->left_->type(),
5598 this->right_->type(),
5599 &type))
5600 return Type::make_error_type();
5601 return type;
e440a328 5602 }
5603
5604 case OPERATOR_LSHIFT:
5605 case OPERATOR_RSHIFT:
5606 return this->left_->type();
5607
5608 default:
c3e6f413 5609 go_unreachable();
e440a328 5610 }
5611}
5612
5613// Set type for a binary expression.
5614
5615void
5616Binary_expression::do_determine_type(const Type_context* context)
5617{
5618 Type* tleft = this->left_->type();
5619 Type* tright = this->right_->type();
5620
5621 // Both sides should have the same type, except for the shift
5622 // operations. For a comparison, we should ignore the incoming
5623 // type.
5624
5625 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5626 || this->op_ == OPERATOR_RSHIFT);
5627
5628 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5629 || this->op_ == OPERATOR_NOTEQ
5630 || this->op_ == OPERATOR_LT
5631 || this->op_ == OPERATOR_LE
5632 || this->op_ == OPERATOR_GT
5633 || this->op_ == OPERATOR_GE);
5634
c999c2a7 5635 // For constant expressions, the context of the result is not useful in
5636 // determining the types of the operands. It is only legal to use abstract
5637 // boolean, numeric, and string constants as operands where it is legal to
5638 // use non-abstract boolean, numeric, and string constants, respectively.
5639 // Any issues with the operation will be resolved in the check_types pass.
5640 bool is_constant_expr = (this->left_->is_constant()
5641 && this->right_->is_constant());
5642
e440a328 5643 Type_context subcontext(*context);
5644
af7a5274 5645 if (is_constant_expr)
5646 {
5647 subcontext.type = NULL;
5648 subcontext.may_be_abstract = true;
5649 }
5650 else if (is_comparison)
e440a328 5651 {
5652 // In a comparison, the context does not determine the types of
5653 // the operands.
5654 subcontext.type = NULL;
5655 }
5656
5657 // Set the context for the left hand operand.
5658 if (is_shift_op)
5659 {
b40dc774 5660 // The right hand operand of a shift plays no role in
5661 // determining the type of the left hand operand.
e440a328 5662 }
5663 else if (!tleft->is_abstract())
5664 subcontext.type = tleft;
5665 else if (!tright->is_abstract())
5666 subcontext.type = tright;
5667 else if (subcontext.type == NULL)
5668 {
5669 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5670 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5671 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5672 {
5673 // Both sides have an abstract integer, abstract float, or
5674 // abstract complex type. Just let CONTEXT determine
5675 // whether they may remain abstract or not.
5676 }
5677 else if (tleft->complex_type() != NULL)
5678 subcontext.type = tleft;
5679 else if (tright->complex_type() != NULL)
5680 subcontext.type = tright;
5681 else if (tleft->float_type() != NULL)
5682 subcontext.type = tleft;
5683 else if (tright->float_type() != NULL)
5684 subcontext.type = tright;
5685 else
5686 subcontext.type = tleft;
f58a23ae 5687
5688 if (subcontext.type != NULL && !context->may_be_abstract)
5689 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5690 }
5691
af7a5274 5692 this->left_->determine_type(&subcontext);
e440a328 5693
e440a328 5694 if (is_shift_op)
5695 {
b40dc774 5696 // We may have inherited an unusable type for the shift operand.
5697 // Give a useful error if that happened.
5698 if (tleft->is_abstract()
5699 && subcontext.type != NULL
8ab6effb 5700 && !subcontext.may_be_abstract
f6bc81e6 5701 && subcontext.type->interface_type() == NULL
8ab6effb 5702 && subcontext.type->integer_type() == NULL)
b40dc774 5703 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5704 "for left operand of shift"));
b40dc774 5705
5706 // The context for the right hand operand is the same as for the
5707 // left hand operand, except for a shift operator.
e440a328 5708 subcontext.type = Type::lookup_integer_type("uint");
5709 subcontext.may_be_abstract = false;
5710 }
5711
af7a5274 5712 this->right_->determine_type(&subcontext);
e90c9dfc 5713
5714 if (is_comparison)
5715 {
5716 if (this->type_ != NULL && !this->type_->is_abstract())
5717 ;
5718 else if (context->type != NULL && context->type->is_boolean_type())
5719 this->type_ = context->type;
5720 else if (!context->may_be_abstract)
5721 this->type_ = Type::lookup_bool_type();
5722 }
e440a328 5723}
5724
5725// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5726// OTYPE is the type of the other operand. Return whether the
5727// operation is OK. This should not be used for shift.
e440a328 5728
5729bool
be8b5eee 5730Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5731 Location location)
e440a328 5732{
5733 switch (op)
5734 {
5735 case OPERATOR_OROR:
5736 case OPERATOR_ANDAND:
c999c2a7 5737 if (!type->is_boolean_type()
5738 || !otype->is_boolean_type())
e440a328 5739 {
631d5788 5740 go_error_at(location, "expected boolean type");
e440a328 5741 return false;
5742 }
5743 break;
5744
5745 case OPERATOR_EQEQ:
5746 case OPERATOR_NOTEQ:
e9d3367e 5747 {
5748 std::string reason;
5749 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5750 {
631d5788 5751 go_error_at(location, "%s", reason.c_str());
e9d3367e 5752 return false;
5753 }
5754 }
e440a328 5755 break;
5756
5757 case OPERATOR_LT:
5758 case OPERATOR_LE:
5759 case OPERATOR_GT:
5760 case OPERATOR_GE:
e9d3367e 5761 {
5762 std::string reason;
5763 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5764 {
631d5788 5765 go_error_at(location, "%s", reason.c_str());
e9d3367e 5766 return false;
5767 }
5768 }
e440a328 5769 break;
5770
5771 case OPERATOR_PLUS:
5772 case OPERATOR_PLUSEQ:
c999c2a7 5773 if ((!type->is_numeric_type() && !type->is_string_type())
5774 || (!otype->is_numeric_type() && !otype->is_string_type()))
e440a328 5775 {
631d5788 5776 go_error_at(location,
e440a328 5777 "expected integer, floating, complex, or string type");
5778 return false;
5779 }
5780 break;
5781
5782 case OPERATOR_MINUS:
5783 case OPERATOR_MINUSEQ:
5784 case OPERATOR_MULT:
5785 case OPERATOR_MULTEQ:
5786 case OPERATOR_DIV:
5787 case OPERATOR_DIVEQ:
c999c2a7 5788 if (!type->is_numeric_type() || !otype->is_numeric_type())
e440a328 5789 {
631d5788 5790 go_error_at(location, "expected integer, floating, or complex type");
e440a328 5791 return false;
5792 }
5793 break;
5794
5795 case OPERATOR_MOD:
5796 case OPERATOR_MODEQ:
5797 case OPERATOR_OR:
5798 case OPERATOR_OREQ:
5799 case OPERATOR_AND:
5800 case OPERATOR_ANDEQ:
5801 case OPERATOR_XOR:
5802 case OPERATOR_XOREQ:
5803 case OPERATOR_BITCLEAR:
5804 case OPERATOR_BITCLEAREQ:
c999c2a7 5805 if (type->integer_type() == NULL || otype->integer_type() == NULL)
e440a328 5806 {
631d5788 5807 go_error_at(location, "expected integer type");
e440a328 5808 return false;
5809 }
5810 break;
5811
5812 default:
c3e6f413 5813 go_unreachable();
e440a328 5814 }
5815
5816 return true;
5817}
5818
5819// Check types.
5820
5821void
5822Binary_expression::do_check_types(Gogo*)
5823{
5f5fea79 5824 if (this->classification() == EXPRESSION_ERROR)
5825 return;
5826
e440a328 5827 Type* left_type = this->left_->type();
5828 Type* right_type = this->right_->type();
5c13bd80 5829 if (left_type->is_error() || right_type->is_error())
9fe897ef 5830 {
5831 this->set_is_error();
5832 return;
5833 }
e440a328 5834
5835 if (this->op_ == OPERATOR_EQEQ
5836 || this->op_ == OPERATOR_NOTEQ
5837 || this->op_ == OPERATOR_LT
5838 || this->op_ == OPERATOR_LE
5839 || this->op_ == OPERATOR_GT
5840 || this->op_ == OPERATOR_GE)
5841 {
907c5ecd 5842 if (left_type->is_nil_type() && right_type->is_nil_type())
5843 {
5844 this->report_error(_("invalid comparison of nil with nil"));
5845 return;
5846 }
e440a328 5847 if (!Type::are_assignable(left_type, right_type, NULL)
5848 && !Type::are_assignable(right_type, left_type, NULL))
5849 {
5850 this->report_error(_("incompatible types in binary expression"));
5851 return;
5852 }
5853 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5854 right_type,
e440a328 5855 this->location())
5856 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5857 left_type,
e440a328 5858 this->location()))
5859 {
5860 this->set_is_error();
5861 return;
5862 }
5863 }
5864 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5865 {
5866 if (!Type::are_compatible_for_binop(left_type, right_type))
5867 {
5868 this->report_error(_("incompatible types in binary expression"));
5869 return;
5870 }
5871 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5872 right_type,
e440a328 5873 this->location()))
5874 {
5875 this->set_is_error();
5876 return;
5877 }
5c65b19d 5878 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5879 {
5880 // Division by a zero integer constant is an error.
5881 Numeric_constant rconst;
5882 unsigned long rval;
5883 if (left_type->integer_type() != NULL
5884 && this->right_->numeric_constant_value(&rconst)
5885 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5886 && rval == 0)
5887 {
5888 this->report_error(_("integer division by zero"));
5889 return;
5890 }
5891 }
e440a328 5892 }
5893 else
5894 {
5895 if (left_type->integer_type() == NULL)
5896 this->report_error(_("shift of non-integer operand"));
5897
6b5e0fac 5898 if (right_type->is_string_type())
5899 this->report_error(_("shift count not unsigned integer"));
5900 else if (!right_type->is_abstract()
e440a328 5901 && (right_type->integer_type() == NULL
5902 || !right_type->integer_type()->is_unsigned()))
5903 this->report_error(_("shift count not unsigned integer"));
5904 else
5905 {
0c77715b 5906 Numeric_constant nc;
5907 if (this->right_->numeric_constant_value(&nc))
e440a328 5908 {
0c77715b 5909 mpz_t val;
5910 if (!nc.to_int(&val))
5911 this->report_error(_("shift count not unsigned integer"));
5912 else
a4eba91b 5913 {
0c77715b 5914 if (mpz_sgn(val) < 0)
5915 {
5916 this->report_error(_("negative shift count"));
0c77715b 5917 Location rloc = this->right_->location();
e67508fa 5918 this->right_ = Expression::make_integer_ul(0, right_type,
5919 rloc);
0c77715b 5920 }
5921 mpz_clear(val);
a4eba91b 5922 }
e440a328 5923 }
e440a328 5924 }
5925 }
5926}
5927
ea664253 5928// Get the backend representation for a binary expression.
e440a328 5929
ea664253 5930Bexpression*
5931Binary_expression::do_get_backend(Translate_context* context)
e440a328 5932{
1b1f2abf 5933 Gogo* gogo = context->gogo();
a32698ee 5934 Location loc = this->location();
5935 Type* left_type = this->left_->type();
5936 Type* right_type = this->right_->type();
1b1f2abf 5937
e440a328 5938 bool use_left_type = true;
5939 bool is_shift_op = false;
29a2d1d8 5940 bool is_idiv_op = false;
e440a328 5941 switch (this->op_)
5942 {
5943 case OPERATOR_EQEQ:
5944 case OPERATOR_NOTEQ:
5945 case OPERATOR_LT:
5946 case OPERATOR_LE:
5947 case OPERATOR_GT:
5948 case OPERATOR_GE:
ea664253 5949 return Expression::comparison(context, this->type_, this->op_,
5950 this->left_, this->right_, loc);
e440a328 5951
5952 case OPERATOR_OROR:
e440a328 5953 case OPERATOR_ANDAND:
e440a328 5954 use_left_type = false;
5955 break;
5956 case OPERATOR_PLUS:
e440a328 5957 case OPERATOR_MINUS:
e440a328 5958 case OPERATOR_OR:
e440a328 5959 case OPERATOR_XOR:
e440a328 5960 case OPERATOR_MULT:
e440a328 5961 break;
5962 case OPERATOR_DIV:
a32698ee 5963 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5964 break;
729f8831 5965 // Fall through.
e440a328 5966 case OPERATOR_MOD:
29a2d1d8 5967 is_idiv_op = true;
e440a328 5968 break;
5969 case OPERATOR_LSHIFT:
e440a328 5970 case OPERATOR_RSHIFT:
e440a328 5971 is_shift_op = true;
5972 break;
e440a328 5973 case OPERATOR_BITCLEAR:
a32698ee 5974 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5975 case OPERATOR_AND:
e440a328 5976 break;
5977 default:
c3e6f413 5978 go_unreachable();
e440a328 5979 }
5980
736a16ba 5981 // The only binary operation for string is +, and that should have
5982 // been converted to a String_concat_expression in do_lower.
5983 go_assert(!left_type->is_string_type());
a32698ee 5984
5985 // For complex division Go might want slightly different results than the
5986 // backend implementation provides, so we have our own runtime routine.
1850e20c 5987 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5988 {
a32698ee 5989 Runtime::Function complex_code;
1850e20c 5990 switch (this->left_->type()->complex_type()->bits())
5991 {
5992 case 64:
a32698ee 5993 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5994 break;
5995 case 128:
a32698ee 5996 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5997 break;
5998 default:
5999 go_unreachable();
6000 }
a32698ee 6001 Expression* complex_div =
6002 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
ea664253 6003 return complex_div->get_backend(context);
1850e20c 6004 }
6005
ea664253 6006 Bexpression* left = this->left_->get_backend(context);
6007 Bexpression* right = this->right_->get_backend(context);
e440a328 6008
a32698ee 6009 Type* type = use_left_type ? left_type : right_type;
6010 Btype* btype = type->get_backend(gogo);
6011
6012 Bexpression* ret =
6013 gogo->backend()->binary_expression(this->op_, left, right, loc);
6014 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 6015
a32698ee 6016 // Initialize overflow constants.
6017 Bexpression* overflow;
6018 mpz_t zero;
6019 mpz_init_set_ui(zero, 0UL);
6020 mpz_t one;
6021 mpz_init_set_ui(one, 1UL);
6022 mpz_t neg_one;
6023 mpz_init_set_si(neg_one, -1);
e440a328 6024
a32698ee 6025 Btype* left_btype = left_type->get_backend(gogo);
6026 Btype* right_btype = right_type->get_backend(gogo);
e440a328 6027
6028 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 6029 // This is not true in C, so we need to insert a conditional.
e440a328 6030 if (is_shift_op)
6031 {
a32698ee 6032 go_assert(left_type->integer_type() != NULL);
e440a328 6033
a32698ee 6034 mpz_t bitsval;
6035 int bits = left_type->integer_type()->bits();
6036 mpz_init_set_ui(bitsval, bits);
6037 Bexpression* bits_expr =
6038 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6039 Bexpression* compare =
6040 gogo->backend()->binary_expression(OPERATOR_LT,
6041 right, bits_expr, loc);
e440a328 6042
a32698ee 6043 Bexpression* zero_expr =
6044 gogo->backend()->integer_constant_expression(left_btype, zero);
6045 overflow = zero_expr;
93715b75 6046 Bfunction* bfn = context->function()->func_value()->get_decl();
e440a328 6047 if (this->op_ == OPERATOR_RSHIFT
a32698ee 6048 && !left_type->integer_type()->is_unsigned())
e440a328 6049 {
a32698ee 6050 Bexpression* neg_expr =
6051 gogo->backend()->binary_expression(OPERATOR_LT, left,
6052 zero_expr, loc);
6053 Bexpression* neg_one_expr =
6054 gogo->backend()->integer_constant_expression(left_btype, neg_one);
93715b75 6055 overflow = gogo->backend()->conditional_expression(bfn,
6056 btype, neg_expr,
a32698ee 6057 neg_one_expr,
6058 zero_expr, loc);
29a2d1d8 6059 }
93715b75 6060 ret = gogo->backend()->conditional_expression(bfn, btype, compare, ret,
a32698ee 6061 overflow, loc);
6062 mpz_clear(bitsval);
29a2d1d8 6063 }
6064
6065 // Add checks for division by zero and division overflow as needed.
6066 if (is_idiv_op)
6067 {
5c3f3470 6068 if (gogo->check_divide_by_zero())
29a2d1d8 6069 {
6070 // right == 0
a32698ee 6071 Bexpression* zero_expr =
6072 gogo->backend()->integer_constant_expression(right_btype, zero);
6073 Bexpression* check =
6074 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6075 right, zero_expr, loc);
29a2d1d8 6076
a32698ee 6077 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 6078 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
ea664253 6079 Bexpression* crash = gogo->runtime_error(errcode,
6080 loc)->get_backend(context);
29a2d1d8 6081
6082 // right == 0 ? (__go_runtime_error(...), 0) : ret
93715b75 6083 Bfunction* bfn = context->function()->func_value()->get_decl();
6084 ret = gogo->backend()->conditional_expression(bfn, btype,
6085 check, crash,
ea664253 6086 ret, loc);
b13c66cd 6087 }
6088
5c3f3470 6089 if (gogo->check_divide_overflow())
29a2d1d8 6090 {
6091 // right == -1
6092 // FIXME: It would be nice to say that this test is expected
6093 // to return false.
a32698ee 6094
6095 Bexpression* neg_one_expr =
6096 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6097 Bexpression* check =
6098 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6099 right, neg_one_expr, loc);
6100
6101 Bexpression* zero_expr =
6102 gogo->backend()->integer_constant_expression(btype, zero);
6103 Bexpression* one_expr =
6104 gogo->backend()->integer_constant_expression(btype, one);
93715b75 6105 Bfunction* bfn = context->function()->func_value()->get_decl();
a32698ee 6106
6107 if (type->integer_type()->is_unsigned())
29a2d1d8 6108 {
6109 // An unsigned -1 is the largest possible number, so
6110 // dividing is always 1 or 0.
a32698ee 6111
6112 Bexpression* cmp =
6113 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6114 left, right, loc);
29a2d1d8 6115 if (this->op_ == OPERATOR_DIV)
a32698ee 6116 overflow =
93715b75 6117 gogo->backend()->conditional_expression(bfn, btype, cmp,
a32698ee 6118 one_expr, zero_expr,
6119 loc);
29a2d1d8 6120 else
a32698ee 6121 overflow =
93715b75 6122 gogo->backend()->conditional_expression(bfn, btype, cmp,
a32698ee 6123 zero_expr, left,
6124 loc);
29a2d1d8 6125 }
6126 else
6127 {
6128 // Computing left / -1 is the same as computing - left,
6129 // which does not overflow since Go sets -fwrapv.
6130 if (this->op_ == OPERATOR_DIV)
a32698ee 6131 {
6132 Expression* negate_expr =
6133 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
ea664253 6134 overflow = negate_expr->get_backend(context);
a32698ee 6135 }
29a2d1d8 6136 else
a32698ee 6137 overflow = zero_expr;
29a2d1d8 6138 }
a32698ee 6139 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6140
6141 // right == -1 ? - left : ret
93715b75 6142 ret = gogo->backend()->conditional_expression(bfn, btype,
6143 check, overflow,
a32698ee 6144 ret, loc);
29a2d1d8 6145 }
e440a328 6146 }
6147
a32698ee 6148 mpz_clear(zero);
6149 mpz_clear(one);
6150 mpz_clear(neg_one);
ea664253 6151 return ret;
e440a328 6152}
6153
6154// Export a binary expression.
6155
6156void
6157Binary_expression::do_export(Export* exp) const
6158{
6159 exp->write_c_string("(");
6160 this->left_->export_expression(exp);
6161 switch (this->op_)
6162 {
6163 case OPERATOR_OROR:
6164 exp->write_c_string(" || ");
6165 break;
6166 case OPERATOR_ANDAND:
6167 exp->write_c_string(" && ");
6168 break;
6169 case OPERATOR_EQEQ:
6170 exp->write_c_string(" == ");
6171 break;
6172 case OPERATOR_NOTEQ:
6173 exp->write_c_string(" != ");
6174 break;
6175 case OPERATOR_LT:
6176 exp->write_c_string(" < ");
6177 break;
6178 case OPERATOR_LE:
6179 exp->write_c_string(" <= ");
6180 break;
6181 case OPERATOR_GT:
6182 exp->write_c_string(" > ");
6183 break;
6184 case OPERATOR_GE:
6185 exp->write_c_string(" >= ");
6186 break;
6187 case OPERATOR_PLUS:
6188 exp->write_c_string(" + ");
6189 break;
6190 case OPERATOR_MINUS:
6191 exp->write_c_string(" - ");
6192 break;
6193 case OPERATOR_OR:
6194 exp->write_c_string(" | ");
6195 break;
6196 case OPERATOR_XOR:
6197 exp->write_c_string(" ^ ");
6198 break;
6199 case OPERATOR_MULT:
6200 exp->write_c_string(" * ");
6201 break;
6202 case OPERATOR_DIV:
6203 exp->write_c_string(" / ");
6204 break;
6205 case OPERATOR_MOD:
6206 exp->write_c_string(" % ");
6207 break;
6208 case OPERATOR_LSHIFT:
6209 exp->write_c_string(" << ");
6210 break;
6211 case OPERATOR_RSHIFT:
6212 exp->write_c_string(" >> ");
6213 break;
6214 case OPERATOR_AND:
6215 exp->write_c_string(" & ");
6216 break;
6217 case OPERATOR_BITCLEAR:
6218 exp->write_c_string(" &^ ");
6219 break;
6220 default:
c3e6f413 6221 go_unreachable();
e440a328 6222 }
6223 this->right_->export_expression(exp);
6224 exp->write_c_string(")");
6225}
6226
6227// Import a binary expression.
6228
6229Expression*
6230Binary_expression::do_import(Import* imp)
6231{
6232 imp->require_c_string("(");
6233
6234 Expression* left = Expression::import_expression(imp);
6235
6236 Operator op;
6237 if (imp->match_c_string(" || "))
6238 {
6239 op = OPERATOR_OROR;
6240 imp->advance(4);
6241 }
6242 else if (imp->match_c_string(" && "))
6243 {
6244 op = OPERATOR_ANDAND;
6245 imp->advance(4);
6246 }
6247 else if (imp->match_c_string(" == "))
6248 {
6249 op = OPERATOR_EQEQ;
6250 imp->advance(4);
6251 }
6252 else if (imp->match_c_string(" != "))
6253 {
6254 op = OPERATOR_NOTEQ;
6255 imp->advance(4);
6256 }
6257 else if (imp->match_c_string(" < "))
6258 {
6259 op = OPERATOR_LT;
6260 imp->advance(3);
6261 }
6262 else if (imp->match_c_string(" <= "))
6263 {
6264 op = OPERATOR_LE;
6265 imp->advance(4);
6266 }
6267 else if (imp->match_c_string(" > "))
6268 {
6269 op = OPERATOR_GT;
6270 imp->advance(3);
6271 }
6272 else if (imp->match_c_string(" >= "))
6273 {
6274 op = OPERATOR_GE;
6275 imp->advance(4);
6276 }
6277 else if (imp->match_c_string(" + "))
6278 {
6279 op = OPERATOR_PLUS;
6280 imp->advance(3);
6281 }
6282 else if (imp->match_c_string(" - "))
6283 {
6284 op = OPERATOR_MINUS;
6285 imp->advance(3);
6286 }
6287 else if (imp->match_c_string(" | "))
6288 {
6289 op = OPERATOR_OR;
6290 imp->advance(3);
6291 }
6292 else if (imp->match_c_string(" ^ "))
6293 {
6294 op = OPERATOR_XOR;
6295 imp->advance(3);
6296 }
6297 else if (imp->match_c_string(" * "))
6298 {
6299 op = OPERATOR_MULT;
6300 imp->advance(3);
6301 }
6302 else if (imp->match_c_string(" / "))
6303 {
6304 op = OPERATOR_DIV;
6305 imp->advance(3);
6306 }
6307 else if (imp->match_c_string(" % "))
6308 {
6309 op = OPERATOR_MOD;
6310 imp->advance(3);
6311 }
6312 else if (imp->match_c_string(" << "))
6313 {
6314 op = OPERATOR_LSHIFT;
6315 imp->advance(4);
6316 }
6317 else if (imp->match_c_string(" >> "))
6318 {
6319 op = OPERATOR_RSHIFT;
6320 imp->advance(4);
6321 }
6322 else if (imp->match_c_string(" & "))
6323 {
6324 op = OPERATOR_AND;
6325 imp->advance(3);
6326 }
6327 else if (imp->match_c_string(" &^ "))
6328 {
6329 op = OPERATOR_BITCLEAR;
6330 imp->advance(4);
6331 }
6332 else
6333 {
631d5788 6334 go_error_at(imp->location(), "unrecognized binary operator");
e440a328 6335 return Expression::make_error(imp->location());
6336 }
6337
6338 Expression* right = Expression::import_expression(imp);
6339
6340 imp->require_c_string(")");
6341
6342 return Expression::make_binary(op, left, right, imp->location());
6343}
6344
d751bb78 6345// Dump ast representation of a binary expression.
6346
6347void
6348Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6349{
6350 ast_dump_context->ostream() << "(";
6351 ast_dump_context->dump_expression(this->left_);
6352 ast_dump_context->ostream() << " ";
6353 ast_dump_context->dump_operator(this->op_);
6354 ast_dump_context->ostream() << " ";
6355 ast_dump_context->dump_expression(this->right_);
6356 ast_dump_context->ostream() << ") ";
6357}
6358
e440a328 6359// Make a binary expression.
6360
6361Expression*
6362Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6363 Location location)
e440a328 6364{
6365 return new Binary_expression(op, left, right, location);
6366}
6367
6368// Implement a comparison.
6369
a32698ee 6370Bexpression*
6371Expression::comparison(Translate_context* context, Type* result_type,
6372 Operator op, Expression* left, Expression* right,
6373 Location location)
e440a328 6374{
2387f644 6375 Type* left_type = left->type();
6376 Type* right_type = right->type();
ceeb12d7 6377
e67508fa 6378 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
1b1f2abf 6379
15c67ee2 6380 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6381 {
6098d6cb 6382 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6383 {
6384 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6385 left, right);
6386 right = Expression::make_boolean(true, location);
6387 }
6388 else
6389 {
6390 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6391 left, right);
6392 right = zexpr;
6393 }
e440a328 6394 }
15c67ee2 6395 else if ((left_type->interface_type() != NULL
6396 && right_type->interface_type() == NULL
6397 && !right_type->is_nil_type())
6398 || (left_type->interface_type() == NULL
6399 && !left_type->is_nil_type()
6400 && right_type->interface_type() != NULL))
e440a328 6401 {
6402 // Comparing an interface value to a non-interface value.
6403 if (left_type->interface_type() == NULL)
6404 {
6405 std::swap(left_type, right_type);
2387f644 6406 std::swap(left, right);
e440a328 6407 }
6408
6409 // The right operand is not an interface. We need to take its
6410 // address if it is not a pointer.
ceeb12d7 6411 Expression* pointer_arg = NULL;
e440a328 6412 if (right_type->points_to() != NULL)
2387f644 6413 pointer_arg = right;
e440a328 6414 else
6415 {
2387f644 6416 go_assert(right->is_addressable());
6417 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6418 location);
e440a328 6419 }
e440a328 6420
2387f644 6421 Expression* descriptor =
6422 Expression::make_type_descriptor(right_type, location);
6423 left =
ceeb12d7 6424 Runtime::make_call((left_type->interface_type()->is_empty()
6098d6cb 6425 ? Runtime::EFACEVALEQ
6426 : Runtime::IFACEVALEQ),
2387f644 6427 location, 3, left, descriptor,
ceeb12d7 6428 pointer_arg);
6098d6cb 6429 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6430 right = Expression::make_boolean(true, location);
e440a328 6431 }
6432 else if (left_type->interface_type() != NULL
6433 && right_type->interface_type() != NULL)
6434 {
ceeb12d7 6435 Runtime::Function compare_function;
739bad04 6436 if (left_type->interface_type()->is_empty()
6437 && right_type->interface_type()->is_empty())
6098d6cb 6438 compare_function = Runtime::EFACEEQ;
739bad04 6439 else if (!left_type->interface_type()->is_empty()
6440 && !right_type->interface_type()->is_empty())
6098d6cb 6441 compare_function = Runtime::IFACEEQ;
739bad04 6442 else
6443 {
6444 if (left_type->interface_type()->is_empty())
6445 {
739bad04 6446 std::swap(left_type, right_type);
2387f644 6447 std::swap(left, right);
739bad04 6448 }
c484d925 6449 go_assert(!left_type->interface_type()->is_empty());
6450 go_assert(right_type->interface_type()->is_empty());
6098d6cb 6451 compare_function = Runtime::IFACEEFACEEQ;
739bad04 6452 }
6453
2387f644 6454 left = Runtime::make_call(compare_function, location, 2, left, right);
6098d6cb 6455 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6456 right = Expression::make_boolean(true, location);
e440a328 6457 }
6458
6459 if (left_type->is_nil_type()
6460 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6461 {
6462 std::swap(left_type, right_type);
2387f644 6463 std::swap(left, right);
e440a328 6464 }
6465
6466 if (right_type->is_nil_type())
6467 {
2387f644 6468 right = Expression::make_nil(location);
e440a328 6469 if (left_type->array_type() != NULL
6470 && left_type->array_type()->length() == NULL)
6471 {
6472 Array_type* at = left_type->array_type();
44dbe1d7 6473 bool is_lvalue = false;
6474 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
e440a328 6475 }
6476 else if (left_type->interface_type() != NULL)
6477 {
6478 // An interface is nil if the first field is nil.
2387f644 6479 left = Expression::make_field_reference(left, 0, location);
e440a328 6480 }
6481 }
6482
ea664253 6483 Bexpression* left_bexpr = left->get_backend(context);
6484 Bexpression* right_bexpr = right->get_backend(context);
e90c9dfc 6485
a32698ee 6486 Gogo* gogo = context->gogo();
6487 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6488 right_bexpr, location);
6489 if (result_type != NULL)
6490 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6491 ret, location);
e440a328 6492 return ret;
6493}
6494
736a16ba 6495// Class String_concat_expression.
6496
6497bool
6498String_concat_expression::do_is_constant() const
6499{
6500 for (Expression_list::const_iterator pe = this->exprs_->begin();
6501 pe != this->exprs_->end();
6502 ++pe)
6503 {
6504 if (!(*pe)->is_constant())
6505 return false;
6506 }
6507 return true;
6508}
6509
6510bool
3ae06f68 6511String_concat_expression::do_is_static_initializer() const
736a16ba 6512{
6513 for (Expression_list::const_iterator pe = this->exprs_->begin();
6514 pe != this->exprs_->end();
6515 ++pe)
6516 {
3ae06f68 6517 if (!(*pe)->is_static_initializer())
736a16ba 6518 return false;
6519 }
6520 return true;
6521}
6522
6523Type*
6524String_concat_expression::do_type()
6525{
6526 Type* t = this->exprs_->front()->type();
6527 Expression_list::iterator pe = this->exprs_->begin();
6528 ++pe;
6529 for (; pe != this->exprs_->end(); ++pe)
6530 {
6531 Type* t1;
6532 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6533 (*pe)->type(),
6534 &t1))
6535 return Type::make_error_type();
6536 t = t1;
6537 }
6538 return t;
6539}
6540
6541void
6542String_concat_expression::do_determine_type(const Type_context* context)
6543{
6544 Type_context subcontext(*context);
6545 for (Expression_list::iterator pe = this->exprs_->begin();
6546 pe != this->exprs_->end();
6547 ++pe)
6548 {
6549 Type* t = (*pe)->type();
6550 if (!t->is_abstract())
6551 {
6552 subcontext.type = t;
6553 break;
6554 }
6555 }
6556 if (subcontext.type == NULL)
6557 subcontext.type = this->exprs_->front()->type();
6558 for (Expression_list::iterator pe = this->exprs_->begin();
6559 pe != this->exprs_->end();
6560 ++pe)
6561 (*pe)->determine_type(&subcontext);
6562}
6563
6564void
6565String_concat_expression::do_check_types(Gogo*)
6566{
6567 if (this->is_error_expression())
6568 return;
6569 Type* t = this->exprs_->front()->type();
6570 if (t->is_error())
6571 {
6572 this->set_is_error();
6573 return;
6574 }
6575 Expression_list::iterator pe = this->exprs_->begin();
6576 ++pe;
6577 for (; pe != this->exprs_->end(); ++pe)
6578 {
6579 Type* t1 = (*pe)->type();
6580 if (!Type::are_compatible_for_binop(t, t1))
6581 {
6582 this->report_error("incompatible types in binary expression");
6583 return;
6584 }
6585 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6586 this->location()))
6587 {
6588 this->set_is_error();
6589 return;
6590 }
6591 }
6592}
6593
6594Expression*
6595String_concat_expression::do_flatten(Gogo*, Named_object*,
6596 Statement_inserter*)
6597{
6598 if (this->is_error_expression())
6599 return this;
6600 Location loc = this->location();
6601 Type* type = this->type();
6602 Expression* nil_arg = Expression::make_nil(loc);
6603 Expression* call;
6604 switch (this->exprs_->size())
6605 {
6606 case 0: case 1:
6607 go_unreachable();
6608
6609 case 2: case 3: case 4: case 5:
6610 {
6611 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6612 NULL, loc);
6613 Array_type* arg_type = Type::make_array_type(type, len);
6614 arg_type->set_is_array_incomparable();
6615 Expression* arg =
6616 Expression::make_array_composite_literal(arg_type, this->exprs_,
6617 loc);
6618 Runtime::Function code;
6619 switch (this->exprs_->size())
6620 {
6621 default:
6622 go_unreachable();
6623 case 2:
6624 code = Runtime::CONCATSTRING2;
6625 break;
6626 case 3:
6627 code = Runtime::CONCATSTRING3;
6628 break;
6629 case 4:
6630 code = Runtime::CONCATSTRING4;
6631 break;
6632 case 5:
6633 code = Runtime::CONCATSTRING5;
6634 break;
6635 }
6636 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6637 }
6638 break;
6639
6640 default:
6641 {
6642 Type* arg_type = Type::make_array_type(type, NULL);
6643 Slice_construction_expression* sce =
6644 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6645 loc);
6646 sce->set_storage_does_not_escape();
6647 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6648 sce);
6649 }
6650 break;
6651 }
6652
6653 return Expression::make_cast(type, call, loc);
6654}
6655
6656void
6657String_concat_expression::do_dump_expression(
6658 Ast_dump_context* ast_dump_context) const
6659{
6660 ast_dump_context->ostream() << "concat(";
6661 ast_dump_context->dump_expression_list(this->exprs_, false);
6662 ast_dump_context->ostream() << ")";
6663}
6664
6665Expression*
6666Expression::make_string_concat(Expression_list* exprs)
6667{
6668 return new String_concat_expression(exprs);
6669}
6670
e440a328 6671// Class Bound_method_expression.
6672
6673// Traversal.
6674
6675int
6676Bound_method_expression::do_traverse(Traverse* traverse)
6677{
e0659c9e 6678 return Expression::traverse(&this->expr_, traverse);
e440a328 6679}
6680
6681// Return the type of a bound method expression. The type of this
0afbb937 6682// object is simply the type of the method with no receiver.
e440a328 6683
6684Type*
6685Bound_method_expression::do_type()
6686{
0afbb937 6687 Named_object* fn = this->method_->named_object();
6688 Function_type* fntype;
6689 if (fn->is_function())
6690 fntype = fn->func_value()->type();
6691 else if (fn->is_function_declaration())
6692 fntype = fn->func_declaration_value()->type();
e0659c9e 6693 else
6694 return Type::make_error_type();
0afbb937 6695 return fntype->copy_without_receiver();
e440a328 6696}
6697
6698// Determine the types of a method expression.
6699
6700void
6701Bound_method_expression::do_determine_type(const Type_context*)
6702{
0afbb937 6703 Named_object* fn = this->method_->named_object();
6704 Function_type* fntype;
6705 if (fn->is_function())
6706 fntype = fn->func_value()->type();
6707 else if (fn->is_function_declaration())
6708 fntype = fn->func_declaration_value()->type();
6709 else
6710 fntype = NULL;
e440a328 6711 if (fntype == NULL || !fntype->is_method())
6712 this->expr_->determine_type_no_context();
6713 else
6714 {
6715 Type_context subcontext(fntype->receiver()->type(), false);
6716 this->expr_->determine_type(&subcontext);
6717 }
6718}
6719
6720// Check the types of a method expression.
6721
6722void
6723Bound_method_expression::do_check_types(Gogo*)
6724{
0afbb937 6725 Named_object* fn = this->method_->named_object();
6726 if (!fn->is_function() && !fn->is_function_declaration())
6727 {
6728 this->report_error(_("object is not a method"));
6729 return;
6730 }
6731
6732 Function_type* fntype;
6733 if (fn->is_function())
6734 fntype = fn->func_value()->type();
6735 else if (fn->is_function_declaration())
6736 fntype = fn->func_declaration_value()->type();
e440a328 6737 else
0afbb937 6738 go_unreachable();
6739 Type* rtype = fntype->receiver()->type()->deref();
6740 Type* etype = (this->expr_type_ != NULL
6741 ? this->expr_type_
6742 : this->expr_->type());
6743 etype = etype->deref();
6744 if (!Type::are_identical(rtype, etype, true, NULL))
6745 this->report_error(_("method type does not match object type"));
6746}
6747
6748// If a bound method expression is not simply called, then it is
6749// represented as a closure. The closure will hold a single variable,
6750// the receiver to pass to the method. The function will be a simple
6751// thunk that pulls that value from the closure and calls the method
6752// with the remaining arguments.
6753//
6754// Because method values are not common, we don't build all thunks for
6755// every methods, but instead only build them as we need them. In
6756// particular, we even build them on demand for methods defined in
6757// other packages.
6758
6759Bound_method_expression::Method_value_thunks
6760 Bound_method_expression::method_value_thunks;
6761
6762// Find or create the thunk for METHOD.
6763
6764Named_object*
6765Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6766 Named_object* fn)
6767{
6768 std::pair<Named_object*, Named_object*> val(fn, NULL);
6769 std::pair<Method_value_thunks::iterator, bool> ins =
6770 Bound_method_expression::method_value_thunks.insert(val);
6771 if (!ins.second)
6772 {
6773 // We have seen this method before.
6774 go_assert(ins.first->second != NULL);
6775 return ins.first->second;
6776 }
6777
6778 Location loc = fn->location();
6779
6780 Function_type* orig_fntype;
6781 if (fn->is_function())
6782 orig_fntype = fn->func_value()->type();
6783 else if (fn->is_function_declaration())
6784 orig_fntype = fn->func_declaration_value()->type();
6785 else
6786 orig_fntype = NULL;
6787
6788 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6789 {
0afbb937 6790 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6791 return ins.first->second;
e440a328 6792 }
0afbb937 6793
6794 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6795 // The type here is wrong--it should be the C function type. But it
6796 // doesn't really matter.
0afbb937 6797 Type* vt = Type::make_pointer_type(Type::make_void_type());
6798 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6799 sfl->push_back(Struct_field(Typed_identifier("val.1",
6800 orig_fntype->receiver()->type(),
6801 loc)));
6bf4793c 6802 Struct_type* st = Type::make_struct_type(sfl, loc);
6803 st->set_is_struct_incomparable();
6804 Type* closure_type = Type::make_pointer_type(st);
0afbb937 6805
f8bdf81a 6806 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6807
da244e59 6808 std::string thunk_name = Gogo::thunk_name();
6809 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 6810 false, loc);
6811
f8bdf81a 6812 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6813 cvar->set_is_used();
1ecc6157 6814 cvar->set_is_closure();
da244e59 6815 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6816 NULL, cvar);
f8bdf81a 6817 new_no->func_value()->set_closure_var(cp);
0afbb937 6818
f8bdf81a 6819 gogo->start_block(loc);
0afbb937 6820
6821 // Field 0 of the closure is the function code pointer, field 1 is
6822 // the value on which to invoke the method.
6823 Expression* arg = Expression::make_var_reference(cp, loc);
6824 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6825 arg = Expression::make_field_reference(arg, 1, loc);
6826
6827 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6828
6829 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6830 Expression_list* args;
6831 if (orig_params == NULL || orig_params->empty())
6832 args = NULL;
6833 else
6834 {
6835 const Typed_identifier_list* new_params = new_fntype->parameters();
6836 args = new Expression_list();
6837 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6838 p != new_params->end();
0afbb937 6839 ++p)
6840 {
6841 Named_object* p_no = gogo->lookup(p->name(), NULL);
6842 go_assert(p_no != NULL
6843 && p_no->is_variable()
6844 && p_no->var_value()->is_parameter());
6845 args->push_back(Expression::make_var_reference(p_no, loc));
6846 }
6847 }
6848
6849 Call_expression* call = Expression::make_call(bme, args,
6850 orig_fntype->is_varargs(),
6851 loc);
6852 call->set_varargs_are_lowered();
6853
6854 Statement* s = Statement::make_return_from_call(call, loc);
6855 gogo->add_statement(s);
6856 Block* b = gogo->finish_block(loc);
6857 gogo->add_block(b, loc);
6858 gogo->lower_block(new_no, b);
a32698ee 6859 gogo->flatten_block(new_no, b);
0afbb937 6860 gogo->finish_function(loc);
6861
6862 ins.first->second = new_no;
6863 return new_no;
6864}
6865
6866// Return an expression to check *REF for nil while dereferencing
6867// according to FIELD_INDEXES. Update *REF to build up the field
6868// reference. This is a static function so that we don't have to
6869// worry about declaring Field_indexes in expressions.h.
6870
6871static Expression*
6872bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6873 Expression** ref)
6874{
6875 if (field_indexes == NULL)
6876 return Expression::make_boolean(false, loc);
6877 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6878 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6879 go_assert(stype != NULL
6880 && field_indexes->field_index < stype->field_count());
6881 if ((*ref)->type()->struct_type() == NULL)
6882 {
6883 go_assert((*ref)->type()->points_to() != NULL);
6884 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6885 Expression::make_nil(loc),
6886 loc);
6887 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6888 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6889 go_assert((*ref)->type()->struct_type() == stype);
6890 }
6891 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6892 loc);
6893 return cond;
e440a328 6894}
6895
cd39797e 6896// Flatten a method value into a struct with nil checks. We can't do
6897// this in the lowering phase, because if the method value is called
6898// directly we don't need a thunk. That case will have been handled
6899// by Call_expression::do_lower, so if we get here then we do need a
6900// thunk.
e440a328 6901
cd39797e 6902Expression*
6903Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6904 Statement_inserter* inserter)
e440a328 6905{
cd39797e 6906 Location loc = this->location();
6907
6908 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
0afbb937 6909 this->method_,
6910 this->function_);
6911 if (thunk->is_erroneous())
6912 {
6913 go_assert(saw_errors());
cd39797e 6914 return Expression::make_error(loc);
0afbb937 6915 }
6916
cd39797e 6917 // Force the expression into a variable. This is only necessary if
6918 // we are going to do nil checks below, but it's easy enough to
6919 // always do it.
6920 Expression* expr = this->expr_;
6921 if (!expr->is_variable())
6922 {
6923 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6924 inserter->insert(etemp);
6925 expr = Expression::make_temporary_reference(etemp, loc);
6926 }
0afbb937 6927
6928 // If the method expects a value, and we have a pointer, we need to
6929 // dereference the pointer.
6930
6931 Named_object* fn = this->method_->named_object();
cd39797e 6932 Function_type *fntype;
0afbb937 6933 if (fn->is_function())
6934 fntype = fn->func_value()->type();
6935 else if (fn->is_function_declaration())
6936 fntype = fn->func_declaration_value()->type();
6937 else
6938 go_unreachable();
6939
cd39797e 6940 Expression* val = expr;
0afbb937 6941 if (fntype->receiver()->type()->points_to() == NULL
6942 && val->type()->points_to() != NULL)
6943 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6944
6945 // Note that we are ignoring this->expr_type_ here. The thunk will
6946 // expect a closure whose second field has type this->expr_type_ (if
6947 // that is not NULL). We are going to pass it a closure whose
6948 // second field has type this->expr_->type(). Since
6949 // this->expr_type_ is only not-NULL for pointer types, we can get
6950 // away with this.
6951
6952 Struct_field_list* fields = new Struct_field_list();
6953 fields->push_back(Struct_field(Typed_identifier("fn.0",
6954 thunk->func_value()->type(),
6955 loc)));
6956 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6957 Struct_type* st = Type::make_struct_type(fields, loc);
6bf4793c 6958 st->set_is_struct_incomparable();
0afbb937 6959
6960 Expression_list* vals = new Expression_list();
6961 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6962 vals->push_back(val);
6963
6964 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
0afbb937 6965
cd39797e 6966 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
6967 ret = Expression::make_heap_expression(ret, loc);
6968 else
6969 {
6970 // When compiling the runtime, method closures do not escape.
6971 // When escape analysis becomes the default, and applies to
6972 // method closures, this should be changed to make it an error
6973 // if a method closure escapes.
6974 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
6975 inserter->insert(ctemp);
6976 ret = Expression::make_temporary_reference(ctemp, loc);
6977 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
6978 ret->unary_expression()->set_does_not_escape();
6979 }
6980
6981 // If necessary, check whether the expression or any embedded
6982 // pointers are nil.
0afbb937 6983
df7ef1fd 6984 Expression* nil_check = NULL;
0afbb937 6985 if (this->method_->field_indexes() != NULL)
6986 {
0afbb937 6987 Expression* ref = expr;
6988 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6989 expr = ref;
6990 }
6991
6992 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6993 {
6994 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6995 Expression::make_nil(loc),
6996 loc);
6997 if (nil_check == NULL)
6998 nil_check = n;
6999 else
7000 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7001 }
7002
7003 if (nil_check != NULL)
7004 {
cd39797e 7005 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7006 loc);
7007 // Fix the type of the conditional expression by pretending to
7008 // evaluate to RET either way through the conditional.
7009 crash = Expression::make_compound(crash, ret, loc);
7010 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7011 }
7012
7013 // RET is a pointer to a struct, but we want a function type.
7014 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7015
7016 return ret;
e440a328 7017}
7018
d751bb78 7019// Dump ast representation of a bound method expression.
7020
7021void
7022Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7023 const
7024{
7025 if (this->expr_type_ != NULL)
7026 ast_dump_context->ostream() << "(";
7027 ast_dump_context->dump_expression(this->expr_);
7028 if (this->expr_type_ != NULL)
7029 {
7030 ast_dump_context->ostream() << ":";
7031 ast_dump_context->dump_type(this->expr_type_);
7032 ast_dump_context->ostream() << ")";
7033 }
7034
0afbb937 7035 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 7036}
7037
e440a328 7038// Make a method expression.
7039
7040Bound_method_expression*
0afbb937 7041Expression::make_bound_method(Expression* expr, const Method* method,
7042 Named_object* function, Location location)
e440a328 7043{
0afbb937 7044 return new Bound_method_expression(expr, method, function, location);
e440a328 7045}
7046
7047// Class Builtin_call_expression. This is used for a call to a
7048// builtin function.
7049
7050class Builtin_call_expression : public Call_expression
7051{
7052 public:
7053 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 7054 bool is_varargs, Location location);
e440a328 7055
7056 protected:
7057 // This overrides Call_expression::do_lower.
7058 Expression*
ceeb4318 7059 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 7060
35a54f17 7061 Expression*
7062 do_flatten(Gogo*, Named_object*, Statement_inserter*);
7063
e440a328 7064 bool
7065 do_is_constant() const;
7066
7067 bool
0c77715b 7068 do_numeric_constant_value(Numeric_constant*) const;
e440a328 7069
4f2138d7 7070 bool
a7549a6a 7071 do_discarding_value();
7072
e440a328 7073 Type*
7074 do_type();
7075
7076 void
7077 do_determine_type(const Type_context*);
7078
7079 void
7080 do_check_types(Gogo*);
7081
7082 Expression*
72666aed 7083 do_copy();
e440a328 7084
ea664253 7085 Bexpression*
7086 do_get_backend(Translate_context*);
e440a328 7087
7088 void
7089 do_export(Export*) const;
7090
7091 virtual bool
7092 do_is_recover_call() const;
7093
7094 virtual void
7095 do_set_recover_arg(Expression*);
7096
7097 private:
7098 // The builtin functions.
7099 enum Builtin_function_code
7100 {
7101 BUILTIN_INVALID,
7102
7103 // Predeclared builtin functions.
7104 BUILTIN_APPEND,
7105 BUILTIN_CAP,
7106 BUILTIN_CLOSE,
48080209 7107 BUILTIN_COMPLEX,
e440a328 7108 BUILTIN_COPY,
1cce762f 7109 BUILTIN_DELETE,
e440a328 7110 BUILTIN_IMAG,
7111 BUILTIN_LEN,
7112 BUILTIN_MAKE,
7113 BUILTIN_NEW,
7114 BUILTIN_PANIC,
7115 BUILTIN_PRINT,
7116 BUILTIN_PRINTLN,
7117 BUILTIN_REAL,
7118 BUILTIN_RECOVER,
7119
7120 // Builtin functions from the unsafe package.
7121 BUILTIN_ALIGNOF,
7122 BUILTIN_OFFSETOF,
7123 BUILTIN_SIZEOF
7124 };
7125
7126 Expression*
7127 one_arg() const;
7128
7129 bool
7130 check_one_arg();
7131
7132 static Type*
7133 real_imag_type(Type*);
7134
7135 static Type*
48080209 7136 complex_type(Type*);
e440a328 7137
a9182619 7138 Expression*
321e5ad2 7139 lower_make(Statement_inserter*);
7140
7141 Expression* flatten_append(Gogo*, Named_object*, Statement_inserter*);
a9182619 7142
7143 bool
ccea2b36 7144 check_int_value(Expression*, bool is_length, bool* small);
a9182619 7145
e440a328 7146 // A pointer back to the general IR structure. This avoids a global
7147 // variable, or passing it around everywhere.
7148 Gogo* gogo_;
7149 // The builtin function being called.
7150 Builtin_function_code code_;
0f914071 7151 // Used to stop endless loops when the length of an array uses len
7152 // or cap of the array itself.
7153 mutable bool seen_;
6334270b 7154 // Whether the argument is set for calls to BUILTIN_RECOVER.
7155 bool recover_arg_is_set_;
e440a328 7156};
7157
7158Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7159 Expression* fn,
7160 Expression_list* args,
7161 bool is_varargs,
b13c66cd 7162 Location location)
e440a328 7163 : Call_expression(fn, args, is_varargs, location),
6334270b 7164 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7165 recover_arg_is_set_(false)
e440a328 7166{
7167 Func_expression* fnexp = this->fn()->func_expression();
79651b1f 7168 if (fnexp == NULL)
7169 {
7170 this->code_ = BUILTIN_INVALID;
7171 return;
7172 }
e440a328 7173 const std::string& name(fnexp->named_object()->name());
7174 if (name == "append")
7175 this->code_ = BUILTIN_APPEND;
7176 else if (name == "cap")
7177 this->code_ = BUILTIN_CAP;
7178 else if (name == "close")
7179 this->code_ = BUILTIN_CLOSE;
48080209 7180 else if (name == "complex")
7181 this->code_ = BUILTIN_COMPLEX;
e440a328 7182 else if (name == "copy")
7183 this->code_ = BUILTIN_COPY;
1cce762f 7184 else if (name == "delete")
7185 this->code_ = BUILTIN_DELETE;
e440a328 7186 else if (name == "imag")
7187 this->code_ = BUILTIN_IMAG;
7188 else if (name == "len")
7189 this->code_ = BUILTIN_LEN;
7190 else if (name == "make")
7191 this->code_ = BUILTIN_MAKE;
7192 else if (name == "new")
7193 this->code_ = BUILTIN_NEW;
7194 else if (name == "panic")
7195 this->code_ = BUILTIN_PANIC;
7196 else if (name == "print")
7197 this->code_ = BUILTIN_PRINT;
7198 else if (name == "println")
7199 this->code_ = BUILTIN_PRINTLN;
7200 else if (name == "real")
7201 this->code_ = BUILTIN_REAL;
7202 else if (name == "recover")
7203 this->code_ = BUILTIN_RECOVER;
7204 else if (name == "Alignof")
7205 this->code_ = BUILTIN_ALIGNOF;
7206 else if (name == "Offsetof")
7207 this->code_ = BUILTIN_OFFSETOF;
7208 else if (name == "Sizeof")
7209 this->code_ = BUILTIN_SIZEOF;
7210 else
c3e6f413 7211 go_unreachable();
e440a328 7212}
7213
7214// Return whether this is a call to recover. This is a virtual
7215// function called from the parent class.
7216
7217bool
7218Builtin_call_expression::do_is_recover_call() const
7219{
7220 if (this->classification() == EXPRESSION_ERROR)
7221 return false;
7222 return this->code_ == BUILTIN_RECOVER;
7223}
7224
7225// Set the argument for a call to recover.
7226
7227void
7228Builtin_call_expression::do_set_recover_arg(Expression* arg)
7229{
7230 const Expression_list* args = this->args();
c484d925 7231 go_assert(args == NULL || args->empty());
e440a328 7232 Expression_list* new_args = new Expression_list();
7233 new_args->push_back(arg);
7234 this->set_args(new_args);
6334270b 7235 this->recover_arg_is_set_ = true;
e440a328 7236}
7237
e440a328 7238// Lower a builtin call expression. This turns new and make into
7239// specific expressions. We also convert to a constant if we can.
7240
7241Expression*
321e5ad2 7242Builtin_call_expression::do_lower(Gogo*, Named_object* function,
ceeb4318 7243 Statement_inserter* inserter, int)
e440a328 7244{
79651b1f 7245 if (this->is_error_expression())
a9182619 7246 return this;
7247
b13c66cd 7248 Location loc = this->location();
1cce762f 7249
a8725655 7250 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7251 {
7252 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7253 return Expression::make_error(loc);
a8725655 7254 }
7255
393ba00b 7256 if (this->code_ == BUILTIN_OFFSETOF)
7257 {
7258 Expression* arg = this->one_arg();
12e69faa 7259
7260 if (arg->bound_method_expression() != NULL
7261 || arg->interface_field_reference_expression() != NULL)
7262 {
7263 this->report_error(_("invalid use of method value as argument "
7264 "of Offsetof"));
7265 return this;
7266 }
7267
393ba00b 7268 Field_reference_expression* farg = arg->field_reference_expression();
7269 while (farg != NULL)
7270 {
7271 if (!farg->implicit())
7272 break;
7273 // When the selector refers to an embedded field,
7274 // it must not be reached through pointer indirections.
7275 if (farg->expr()->deref() != farg->expr())
7276 {
12e69faa 7277 this->report_error(_("argument of Offsetof implies "
7278 "indirection of an embedded field"));
393ba00b 7279 return this;
7280 }
7281 // Go up until we reach the original base.
7282 farg = farg->expr()->field_reference_expression();
7283 }
7284 }
7285
1cce762f 7286 if (this->is_constant())
e440a328 7287 {
0c77715b 7288 Numeric_constant nc;
7289 if (this->numeric_constant_value(&nc))
7290 return nc.expression(loc);
e440a328 7291 }
1cce762f 7292
7293 switch (this->code_)
e440a328 7294 {
1cce762f 7295 default:
7296 break;
7297
7298 case BUILTIN_NEW:
7299 {
7300 const Expression_list* args = this->args();
7301 if (args == NULL || args->size() < 1)
7302 this->report_error(_("not enough arguments"));
7303 else if (args->size() > 1)
7304 this->report_error(_("too many arguments"));
7305 else
7306 {
7307 Expression* arg = args->front();
7308 if (!arg->is_type_expression())
7309 {
631d5788 7310 go_error_at(arg->location(), "expected type");
1cce762f 7311 this->set_is_error();
7312 }
7313 else
7314 return Expression::make_allocation(arg->type(), loc);
7315 }
7316 }
7317 break;
7318
7319 case BUILTIN_MAKE:
321e5ad2 7320 return this->lower_make(inserter);
1cce762f 7321
7322 case BUILTIN_RECOVER:
e440a328 7323 if (function != NULL)
7324 function->func_value()->set_calls_recover();
7325 else
7326 {
7327 // Calling recover outside of a function always returns the
7328 // nil empty interface.
823c7e3d 7329 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7330 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7331 }
1cce762f 7332 break;
7333
1cce762f 7334 case BUILTIN_DELETE:
7335 {
7336 // Lower to a runtime function call.
7337 const Expression_list* args = this->args();
7338 if (args == NULL || args->size() < 2)
7339 this->report_error(_("not enough arguments"));
7340 else if (args->size() > 2)
7341 this->report_error(_("too many arguments"));
7342 else if (args->front()->type()->map_type() == NULL)
7343 this->report_error(_("argument 1 must be a map"));
7344 else
7345 {
7346 // Since this function returns no value it must appear in
7347 // a statement by itself, so we don't have to worry about
7348 // order of evaluation of values around it. Evaluate the
7349 // map first to get order of evaluation right.
7350 Map_type* mt = args->front()->type()->map_type();
7351 Temporary_statement* map_temp =
7352 Statement::make_temporary(mt, args->front(), loc);
7353 inserter->insert(map_temp);
7354
7355 Temporary_statement* key_temp =
7356 Statement::make_temporary(mt->key_type(), args->back(), loc);
7357 inserter->insert(key_temp);
7358
0d5530d9 7359 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7360 Expression* e2 = Expression::make_temporary_reference(map_temp,
1cce762f 7361 loc);
0d5530d9 7362 Expression* e3 = Expression::make_temporary_reference(key_temp,
1cce762f 7363 loc);
0d5530d9 7364 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
1cce762f 7365 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
0d5530d9 7366 3, e1, e2, e3);
1cce762f 7367 }
7368 }
7369 break;
88b03a70 7370
7371 case BUILTIN_PRINT:
7372 case BUILTIN_PRINTLN:
7373 // Force all the arguments into temporary variables, so that we
7374 // don't try to evaluate something while holding the print lock.
7375 if (this->args() == NULL)
7376 break;
7377 for (Expression_list::iterator pa = this->args()->begin();
7378 pa != this->args()->end();
7379 ++pa)
7380 {
493ce3ee 7381 if (!(*pa)->is_variable() && !(*pa)->is_constant())
88b03a70 7382 {
7383 Temporary_statement* temp =
7384 Statement::make_temporary(NULL, *pa, loc);
7385 inserter->insert(temp);
7386 *pa = Expression::make_temporary_reference(temp, loc);
7387 }
7388 }
7389 break;
e440a328 7390 }
7391
7392 return this;
7393}
7394
35a54f17 7395// Flatten a builtin call expression. This turns the arguments of copy and
7396// append into temporary expressions.
7397
7398Expression*
321e5ad2 7399Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
35a54f17 7400 Statement_inserter* inserter)
7401{
16cb7fec 7402 Location loc = this->location();
7403
7404 switch (this->code_)
35a54f17 7405 {
16cb7fec 7406 default:
7407 break;
7408
7409 case BUILTIN_APPEND:
321e5ad2 7410 return this->flatten_append(gogo, function, inserter);
7411
16cb7fec 7412 case BUILTIN_COPY:
7413 {
7414 Type* at = this->args()->front()->type();
7415 for (Expression_list::iterator pa = this->args()->begin();
7416 pa != this->args()->end();
7417 ++pa)
7418 {
7419 if ((*pa)->is_nil_expression())
7420 {
7421 Expression* nil = Expression::make_nil(loc);
7422 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7423 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7424 }
7425 if (!(*pa)->is_variable())
7426 {
7427 Temporary_statement* temp =
7428 Statement::make_temporary(NULL, *pa, loc);
7429 inserter->insert(temp);
7430 *pa = Expression::make_temporary_reference(temp, loc);
7431 }
7432 }
7433 }
7434 break;
7435
7436 case BUILTIN_PANIC:
35a54f17 7437 for (Expression_list::iterator pa = this->args()->begin();
16cb7fec 7438 pa != this->args()->end();
7439 ++pa)
7440 {
7441 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
55e8ba6a 7442 {
16cb7fec 7443 Temporary_statement* temp =
7444 Statement::make_temporary(NULL, *pa, loc);
7445 inserter->insert(temp);
7446 *pa = Expression::make_temporary_reference(temp, loc);
55e8ba6a 7447 }
16cb7fec 7448 }
7739537f 7449 break;
0d5530d9 7450
7451 case BUILTIN_LEN:
132ed071 7452 case BUILTIN_CAP:
321e5ad2 7453 {
7454 Expression_list::iterator pa = this->args()->begin();
7455 if (!(*pa)->is_variable()
7456 && ((*pa)->type()->map_type() != NULL
7457 || (*pa)->type()->channel_type() != NULL))
7458 {
7459 Temporary_statement* temp =
7460 Statement::make_temporary(NULL, *pa, loc);
7461 inserter->insert(temp);
7462 *pa = Expression::make_temporary_reference(temp, loc);
7463 }
7464 }
7465 break;
35a54f17 7466 }
16cb7fec 7467
35a54f17 7468 return this;
7469}
7470
a9182619 7471// Lower a make expression.
7472
7473Expression*
321e5ad2 7474Builtin_call_expression::lower_make(Statement_inserter* inserter)
a9182619 7475{
b13c66cd 7476 Location loc = this->location();
a9182619 7477
7478 const Expression_list* args = this->args();
7479 if (args == NULL || args->size() < 1)
7480 {
7481 this->report_error(_("not enough arguments"));
7482 return Expression::make_error(this->location());
7483 }
7484
7485 Expression_list::const_iterator parg = args->begin();
7486
7487 Expression* first_arg = *parg;
7488 if (!first_arg->is_type_expression())
7489 {
631d5788 7490 go_error_at(first_arg->location(), "expected type");
a9182619 7491 this->set_is_error();
7492 return Expression::make_error(this->location());
7493 }
7494 Type* type = first_arg->type();
7495
7496 bool is_slice = false;
7497 bool is_map = false;
7498 bool is_chan = false;
411eb89e 7499 if (type->is_slice_type())
a9182619 7500 is_slice = true;
7501 else if (type->map_type() != NULL)
7502 is_map = true;
7503 else if (type->channel_type() != NULL)
7504 is_chan = true;
7505 else
7506 {
7507 this->report_error(_("invalid type for make function"));
7508 return Expression::make_error(this->location());
7509 }
7510
f6bc81e6 7511 Type_context int_context(Type::lookup_integer_type("int"), false);
7512
a9182619 7513 ++parg;
7514 Expression* len_arg;
ccea2b36 7515 bool len_small = false;
a9182619 7516 if (parg == args->end())
7517 {
7518 if (is_slice)
7519 {
7520 this->report_error(_("length required when allocating a slice"));
7521 return Expression::make_error(this->location());
7522 }
e67508fa 7523 len_arg = Expression::make_integer_ul(0, NULL, loc);
a9182619 7524 }
7525 else
7526 {
7527 len_arg = *parg;
f6bc81e6 7528 len_arg->determine_type(&int_context);
ccea2b36 7529 if (!this->check_int_value(len_arg, true, &len_small))
1ad00fd4 7530 return Expression::make_error(this->location());
a9182619 7531 ++parg;
7532 }
7533
7534 Expression* cap_arg = NULL;
ccea2b36 7535 bool cap_small = false;
a9182619 7536 if (is_slice && parg != args->end())
7537 {
7538 cap_arg = *parg;
f6bc81e6 7539 cap_arg->determine_type(&int_context);
ccea2b36 7540 if (!this->check_int_value(cap_arg, false, &cap_small))
1ad00fd4 7541 return Expression::make_error(this->location());
7542
7543 Numeric_constant nclen;
7544 Numeric_constant nccap;
7545 unsigned long vlen;
7546 unsigned long vcap;
7547 if (len_arg->numeric_constant_value(&nclen)
7548 && cap_arg->numeric_constant_value(&nccap)
7549 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7550 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7551 && vlen > vcap)
a9182619 7552 {
1ad00fd4 7553 this->report_error(_("len larger than cap"));
a9182619 7554 return Expression::make_error(this->location());
7555 }
1ad00fd4 7556
a9182619 7557 ++parg;
7558 }
7559
7560 if (parg != args->end())
7561 {
7562 this->report_error(_("too many arguments to make"));
7563 return Expression::make_error(this->location());
7564 }
7565
b13c66cd 7566 Location type_loc = first_arg->location();
a9182619 7567
7568 Expression* call;
7569 if (is_slice)
7570 {
321e5ad2 7571 Type* et = type->array_type()->element_type();
7572 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
a9182619 7573 if (cap_arg == NULL)
321e5ad2 7574 {
7575 Temporary_statement* temp = Statement::make_temporary(NULL,
7576 len_arg,
7577 loc);
7578 inserter->insert(temp);
7579 len_arg = Expression::make_temporary_reference(temp, loc);
7580 cap_arg = Expression::make_temporary_reference(temp, loc);
ccea2b36 7581 cap_small = len_small;
321e5ad2 7582 }
ccea2b36 7583
7584 Runtime::Function code = Runtime::MAKESLICE;
7585 if (!len_small || !cap_small)
7586 code = Runtime::MAKESLICE64;
7587 call = Runtime::make_call(code, loc, 3, type_arg, len_arg, cap_arg);
a9182619 7588 }
7589 else if (is_map)
321e5ad2 7590 {
7591 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7592 call = Runtime::make_call(Runtime::MAKEMAP, loc, 4, type_arg, len_arg,
7593 Expression::make_nil(loc),
7594 Expression::make_nil(loc));
7595 }
a9182619 7596 else if (is_chan)
321e5ad2 7597 {
7598 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7599 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7600 }
a9182619 7601 else
7602 go_unreachable();
7603
7604 return Expression::make_unsafe_cast(type, call, loc);
7605}
7606
321e5ad2 7607// Flatten a call to the predeclared append function. We do this in
7608// the flatten phase, not the lowering phase, so that we run after
7609// type checking and after order_evaluations.
7610
7611Expression*
7612Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7613 Statement_inserter* inserter)
7614{
7615 if (this->is_error_expression())
7616 return this;
7617
7618 Location loc = this->location();
7619
7620 const Expression_list* args = this->args();
7621 go_assert(args != NULL && !args->empty());
7622
7623 Type* slice_type = args->front()->type();
7624 go_assert(slice_type->is_slice_type());
7625 Type* element_type = slice_type->array_type()->element_type();
7626
7627 if (args->size() == 1)
7628 {
7629 // append(s) evaluates to s.
7630 return args->front();
7631 }
7632
7633 Type* int_type = Type::lookup_integer_type("int");
7634 Type* uint_type = Type::lookup_integer_type("uint");
7635
7636 // Implementing
7637 // append(s1, s2...)
7638 // or
7639 // append(s1, a1, a2, a3, ...)
7640
7641 // s1tmp := s1
7642 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7643 loc);
7644 inserter->insert(s1tmp);
7645
7646 // l1tmp := len(s1tmp)
7647 Named_object* lenfn = gogo->lookup_global("len");
7648 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7649 Expression_list* call_args = new Expression_list();
7650 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7651 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7652 gogo->lower_expression(function, inserter, &len);
7653 gogo->flatten_expression(function, inserter, &len);
7654 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7655 inserter->insert(l1tmp);
7656
7657 Temporary_statement* s2tmp = NULL;
7658 Temporary_statement* l2tmp = NULL;
7659 Expression_list* add = NULL;
7660 Expression* len2;
7661 if (this->is_varargs())
7662 {
7663 go_assert(args->size() == 2);
7664
7665 // s2tmp := s2
7666 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7667 inserter->insert(s2tmp);
7668
7669 // l2tmp := len(s2tmp)
7670 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7671 call_args = new Expression_list();
7672 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7673 len = Expression::make_call(lenref, call_args, false, loc);
7674 gogo->lower_expression(function, inserter, &len);
7675 gogo->flatten_expression(function, inserter, &len);
7676 l2tmp = Statement::make_temporary(int_type, len, loc);
7677 inserter->insert(l2tmp);
7678
7679 // len2 = l2tmp
7680 len2 = Expression::make_temporary_reference(l2tmp, loc);
7681 }
7682 else
7683 {
7684 // We have to ensure that all the arguments are in variables
7685 // now, because otherwise if one of them is an index expression
7686 // into the current slice we could overwrite it before we fetch
7687 // it.
7688 add = new Expression_list();
7689 Expression_list::const_iterator pa = args->begin();
7690 for (++pa; pa != args->end(); ++pa)
7691 {
7692 if ((*pa)->is_variable())
7693 add->push_back(*pa);
7694 else
7695 {
7696 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7697 loc);
7698 inserter->insert(tmp);
7699 add->push_back(Expression::make_temporary_reference(tmp, loc));
7700 }
7701 }
7702
7703 // len2 = len(add)
7704 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7705 }
7706
7707 // ntmp := l1tmp + len2
7708 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7709 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7710 gogo->lower_expression(function, inserter, &sum);
7711 gogo->flatten_expression(function, inserter, &sum);
7712 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7713 inserter->insert(ntmp);
7714
7715 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7716 // growslice(type, s1tmp, ntmp) :
7717 // s1tmp[:ntmp]
7718 // Using uint here means that if the computation of ntmp overflowed,
7719 // we will call growslice which will panic.
7720
7721 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7722 left = Expression::make_cast(uint_type, left, loc);
7723
7724 Named_object* capfn = gogo->lookup_global("cap");
7725 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7726 call_args = new Expression_list();
7727 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7728 Expression* right = Expression::make_call(capref, call_args, false, loc);
7729 right = Expression::make_cast(uint_type, right, loc);
7730
7731 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7732
7733 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7734 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7735 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7736 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7737 a1, a2, a3);
7738 call = Expression::make_unsafe_cast(slice_type, call, loc);
7739
7740 ref = Expression::make_temporary_reference(s1tmp, loc);
7741 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7742 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7743 // FIXME: Mark this index as not requiring bounds checks.
7744 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7745
7746 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7747
7748 gogo->lower_expression(function, inserter, &rhs);
7749 gogo->flatten_expression(function, inserter, &rhs);
7750
7751 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7752 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7753 inserter->insert(assign);
7754
7755 if (this->is_varargs())
7756 {
7757 // copy(s1tmp[l1tmp:], s2tmp)
7758 a1 = Expression::make_temporary_reference(s1tmp, loc);
7759 ref = Expression::make_temporary_reference(l1tmp, loc);
7760 Expression* nil = Expression::make_nil(loc);
7761 // FIXME: Mark this index as not requiring bounds checks.
7762 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7763
7764 a2 = Expression::make_temporary_reference(s2tmp, loc);
7765
7766 Named_object* copyfn = gogo->lookup_global("copy");
7767 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7768 call_args = new Expression_list();
7769 call_args->push_back(a1);
7770 call_args->push_back(a2);
7771 call = Expression::make_call(copyref, call_args, false, loc);
7772 gogo->lower_expression(function, inserter, &call);
7773 gogo->flatten_expression(function, inserter, &call);
7774 inserter->insert(Statement::make_statement(call, false));
7775 }
7776 else
7777 {
7778 // For each argument:
7779 // s1tmp[l1tmp+i] = a
7780 unsigned long i = 0;
7781 for (Expression_list::const_iterator pa = add->begin();
7782 pa != add->end();
7783 ++pa, ++i)
7784 {
7785 ref = Expression::make_temporary_reference(s1tmp, loc);
7786 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7787 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7788 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7789 // FIXME: Mark this index as not requiring bounds checks.
7790 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7791 gogo->lower_expression(function, inserter, &lhs);
7792 gogo->flatten_expression(function, inserter, &lhs);
03118c21 7793 // The flatten pass runs after the write barrier pass, so we
7794 // need to insert a write barrier here if necessary.
7795 if (!gogo->assign_needs_write_barrier(lhs))
7796 assign = Statement::make_assignment(lhs, *pa, loc);
7797 else
7798 {
7799 Function* f = function == NULL ? NULL : function->func_value();
7800 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
7801 lhs, *pa, loc);
7802 }
321e5ad2 7803 inserter->insert(assign);
7804 }
7805 }
7806
7807 return Expression::make_temporary_reference(s1tmp, loc);
7808}
7809
a9182619 7810// Return whether an expression has an integer value. Report an error
7811// if not. This is used when handling calls to the predeclared make
ccea2b36 7812// function. Set *SMALL if the value is known to fit in type "int".
a9182619 7813
7814bool
ccea2b36 7815Builtin_call_expression::check_int_value(Expression* e, bool is_length,
7816 bool *small)
a9182619 7817{
ccea2b36 7818 *small = false;
7819
0c77715b 7820 Numeric_constant nc;
1ad00fd4 7821 if (e->numeric_constant_value(&nc))
a9182619 7822 {
1ad00fd4 7823 unsigned long v;
7824 switch (nc.to_unsigned_long(&v))
7825 {
7826 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7827 break;
1ad00fd4 7828 case Numeric_constant::NC_UL_NOTINT:
631d5788 7829 go_error_at(e->location(), "non-integer %s argument to make",
7830 is_length ? "len" : "cap");
1ad00fd4 7831 return false;
7832 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 7833 go_error_at(e->location(), "negative %s argument to make",
7834 is_length ? "len" : "cap");
1ad00fd4 7835 return false;
7836 case Numeric_constant::NC_UL_BIG:
7837 // We don't want to give a compile-time error for a 64-bit
7838 // value on a 32-bit target.
1b10c5e7 7839 break;
1ad00fd4 7840 }
1b10c5e7 7841
7842 mpz_t val;
7843 if (!nc.to_int(&val))
7844 go_unreachable();
7845 int bits = mpz_sizeinbase(val, 2);
7846 mpz_clear(val);
7847 Type* int_type = Type::lookup_integer_type("int");
7848 if (bits >= int_type->integer_type()->bits())
7849 {
631d5788 7850 go_error_at(e->location(), "%s argument too large for make",
7851 is_length ? "len" : "cap");
1b10c5e7 7852 return false;
7853 }
7854
ccea2b36 7855 *small = true;
1b10c5e7 7856 return true;
a9182619 7857 }
7858
1ad00fd4 7859 if (e->type()->integer_type() != NULL)
ccea2b36 7860 {
7861 int ebits = e->type()->integer_type()->bits();
7862 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
7863
7864 // We can treat ebits == intbits as small even for an unsigned
7865 // integer type, because we will convert the value to int and
7866 // then reject it in the runtime if it is negative.
7867 *small = ebits <= intbits;
7868
7869 return true;
7870 }
1ad00fd4 7871
631d5788 7872 go_error_at(e->location(), "non-integer %s argument to make",
7873 is_length ? "len" : "cap");
a9182619 7874 return false;
7875}
7876
e440a328 7877// Return the type of the real or imag functions, given the type of
fcbea5e4 7878// the argument. We need to map complex64 to float32 and complex128
7879// to float64, so it has to be done by name. This returns NULL if it
7880// can't figure out the type.
e440a328 7881
7882Type*
7883Builtin_call_expression::real_imag_type(Type* arg_type)
7884{
7885 if (arg_type == NULL || arg_type->is_abstract())
7886 return NULL;
7887 Named_type* nt = arg_type->named_type();
7888 if (nt == NULL)
7889 return NULL;
7890 while (nt->real_type()->named_type() != NULL)
7891 nt = nt->real_type()->named_type();
48080209 7892 if (nt->name() == "complex64")
e440a328 7893 return Type::lookup_float_type("float32");
7894 else if (nt->name() == "complex128")
7895 return Type::lookup_float_type("float64");
7896 else
7897 return NULL;
7898}
7899
48080209 7900// Return the type of the complex function, given the type of one of the
e440a328 7901// argments. Like real_imag_type, we have to map by name.
7902
7903Type*
48080209 7904Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7905{
7906 if (arg_type == NULL || arg_type->is_abstract())
7907 return NULL;
7908 Named_type* nt = arg_type->named_type();
7909 if (nt == NULL)
7910 return NULL;
7911 while (nt->real_type()->named_type() != NULL)
7912 nt = nt->real_type()->named_type();
48080209 7913 if (nt->name() == "float32")
e440a328 7914 return Type::lookup_complex_type("complex64");
7915 else if (nt->name() == "float64")
7916 return Type::lookup_complex_type("complex128");
7917 else
7918 return NULL;
7919}
7920
7921// Return a single argument, or NULL if there isn't one.
7922
7923Expression*
7924Builtin_call_expression::one_arg() const
7925{
7926 const Expression_list* args = this->args();
aa615cb3 7927 if (args == NULL || args->size() != 1)
e440a328 7928 return NULL;
7929 return args->front();
7930}
7931
83921647 7932// A traversal class which looks for a call or receive expression.
7933
7934class Find_call_expression : public Traverse
7935{
7936 public:
7937 Find_call_expression()
7938 : Traverse(traverse_expressions),
7939 found_(false)
7940 { }
7941
7942 int
7943 expression(Expression**);
7944
7945 bool
7946 found()
7947 { return this->found_; }
7948
7949 private:
7950 bool found_;
7951};
7952
7953int
7954Find_call_expression::expression(Expression** pexpr)
7955{
7956 if ((*pexpr)->call_expression() != NULL
7957 || (*pexpr)->receive_expression() != NULL)
7958 {
7959 this->found_ = true;
7960 return TRAVERSE_EXIT;
7961 }
7962 return TRAVERSE_CONTINUE;
7963}
7964
7965// Return whether this is constant: len of a string constant, or len
7966// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7967// unsafe.Alignof.
e440a328 7968
7969bool
7970Builtin_call_expression::do_is_constant() const
7971{
12e69faa 7972 if (this->is_error_expression())
7973 return true;
e440a328 7974 switch (this->code_)
7975 {
7976 case BUILTIN_LEN:
7977 case BUILTIN_CAP:
7978 {
0f914071 7979 if (this->seen_)
7980 return false;
7981
e440a328 7982 Expression* arg = this->one_arg();
7983 if (arg == NULL)
7984 return false;
7985 Type* arg_type = arg->type();
7986
7987 if (arg_type->points_to() != NULL
7988 && arg_type->points_to()->array_type() != NULL
411eb89e 7989 && !arg_type->points_to()->is_slice_type())
e440a328 7990 arg_type = arg_type->points_to();
7991
83921647 7992 // The len and cap functions are only constant if there are no
7993 // function calls or channel operations in the arguments.
7994 // Otherwise we have to make the call.
7995 if (!arg->is_constant())
7996 {
7997 Find_call_expression find_call;
7998 Expression::traverse(&arg, &find_call);
7999 if (find_call.found())
8000 return false;
8001 }
8002
e440a328 8003 if (arg_type->array_type() != NULL
8004 && arg_type->array_type()->length() != NULL)
0f914071 8005 return true;
e440a328 8006
8007 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 8008 {
8009 this->seen_ = true;
8010 bool ret = arg->is_constant();
8011 this->seen_ = false;
8012 return ret;
8013 }
e440a328 8014 }
8015 break;
8016
8017 case BUILTIN_SIZEOF:
8018 case BUILTIN_ALIGNOF:
8019 return this->one_arg() != NULL;
8020
8021 case BUILTIN_OFFSETOF:
8022 {
8023 Expression* arg = this->one_arg();
8024 if (arg == NULL)
8025 return false;
8026 return arg->field_reference_expression() != NULL;
8027 }
8028
48080209 8029 case BUILTIN_COMPLEX:
e440a328 8030 {
8031 const Expression_list* args = this->args();
8032 if (args != NULL && args->size() == 2)
8033 return args->front()->is_constant() && args->back()->is_constant();
8034 }
8035 break;
8036
8037 case BUILTIN_REAL:
8038 case BUILTIN_IMAG:
8039 {
8040 Expression* arg = this->one_arg();
8041 return arg != NULL && arg->is_constant();
8042 }
8043
8044 default:
8045 break;
8046 }
8047
8048 return false;
8049}
8050
0c77715b 8051// Return a numeric constant if possible.
e440a328 8052
8053bool
0c77715b 8054Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 8055{
8056 if (this->code_ == BUILTIN_LEN
8057 || this->code_ == BUILTIN_CAP)
8058 {
8059 Expression* arg = this->one_arg();
8060 if (arg == NULL)
8061 return false;
8062 Type* arg_type = arg->type();
8063
8064 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8065 {
8066 std::string sval;
8067 if (arg->string_constant_value(&sval))
8068 {
0c77715b 8069 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8070 sval.length());
e440a328 8071 return true;
8072 }
8073 }
8074
8075 if (arg_type->points_to() != NULL
8076 && arg_type->points_to()->array_type() != NULL
411eb89e 8077 && !arg_type->points_to()->is_slice_type())
e440a328 8078 arg_type = arg_type->points_to();
8079
8080 if (arg_type->array_type() != NULL
8081 && arg_type->array_type()->length() != NULL)
8082 {
0f914071 8083 if (this->seen_)
8084 return false;
e440a328 8085 Expression* e = arg_type->array_type()->length();
0f914071 8086 this->seen_ = true;
0c77715b 8087 bool r = e->numeric_constant_value(nc);
0f914071 8088 this->seen_ = false;
8089 if (r)
e440a328 8090 {
0c77715b 8091 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8092 this->location()))
8093 r = false;
e440a328 8094 }
0c77715b 8095 return r;
e440a328 8096 }
8097 }
8098 else if (this->code_ == BUILTIN_SIZEOF
8099 || this->code_ == BUILTIN_ALIGNOF)
8100 {
8101 Expression* arg = this->one_arg();
8102 if (arg == NULL)
8103 return false;
8104 Type* arg_type = arg->type();
5c13bd80 8105 if (arg_type->is_error())
e440a328 8106 return false;
8107 if (arg_type->is_abstract())
8108 return false;
2c809f8f 8109 if (this->seen_)
8110 return false;
927a01eb 8111
3f378015 8112 int64_t ret;
e440a328 8113 if (this->code_ == BUILTIN_SIZEOF)
8114 {
2c809f8f 8115 this->seen_ = true;
8116 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8117 this->seen_ = false;
8118 if (!ok)
e440a328 8119 return false;
8120 }
8121 else if (this->code_ == BUILTIN_ALIGNOF)
8122 {
2c809f8f 8123 bool ok;
8124 this->seen_ = true;
637bd3af 8125 if (arg->field_reference_expression() == NULL)
2c809f8f 8126 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 8127 else
e440a328 8128 {
8129 // Calling unsafe.Alignof(s.f) returns the alignment of
8130 // the type of f when it is used as a field in a struct.
2c809f8f 8131 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 8132 }
2c809f8f 8133 this->seen_ = false;
8134 if (!ok)
8135 return false;
e440a328 8136 }
8137 else
c3e6f413 8138 go_unreachable();
927a01eb 8139
3f378015 8140 mpz_t zval;
8141 set_mpz_from_int64(&zval, ret);
8142 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8143 mpz_clear(zval);
e440a328 8144 return true;
8145 }
8146 else if (this->code_ == BUILTIN_OFFSETOF)
8147 {
8148 Expression* arg = this->one_arg();
8149 if (arg == NULL)
8150 return false;
8151 Field_reference_expression* farg = arg->field_reference_expression();
8152 if (farg == NULL)
8153 return false;
2c809f8f 8154 if (this->seen_)
8155 return false;
8156
3f378015 8157 int64_t total_offset = 0;
9a4bd570 8158 while (true)
8159 {
8160 Expression* struct_expr = farg->expr();
8161 Type* st = struct_expr->type();
8162 if (st->struct_type() == NULL)
8163 return false;
8164 if (st->named_type() != NULL)
8165 st->named_type()->convert(this->gogo_);
3f378015 8166 int64_t offset;
2c809f8f 8167 this->seen_ = true;
8168 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8169 farg->field_index(),
8170 &offset);
8171 this->seen_ = false;
8172 if (!ok)
8173 return false;
9a4bd570 8174 total_offset += offset;
8175 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8176 {
8177 // Go up until we reach the original base.
8178 farg = struct_expr->field_reference_expression();
8179 continue;
8180 }
8181 break;
8182 }
3f378015 8183 mpz_t zval;
8184 set_mpz_from_int64(&zval, total_offset);
8185 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8186 mpz_clear(zval);
e440a328 8187 return true;
8188 }
0c77715b 8189 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 8190 {
8191 Expression* arg = this->one_arg();
8192 if (arg == NULL)
8193 return false;
8194
0c77715b 8195 Numeric_constant argnc;
8196 if (!arg->numeric_constant_value(&argnc))
8197 return false;
8198
fcbea5e4 8199 mpc_t val;
8200 if (!argnc.to_complex(&val))
0c77715b 8201 return false;
e440a328 8202
0c77715b 8203 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8204 if (this->code_ == BUILTIN_REAL)
fcbea5e4 8205 nc->set_float(type, mpc_realref(val));
0c77715b 8206 else
fcbea5e4 8207 nc->set_float(type, mpc_imagref(val));
8208 mpc_clear(val);
0c77715b 8209 return true;
e440a328 8210 }
0c77715b 8211 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 8212 {
8213 const Expression_list* args = this->args();
8214 if (args == NULL || args->size() != 2)
8215 return false;
8216
0c77715b 8217 Numeric_constant rnc;
8218 if (!args->front()->numeric_constant_value(&rnc))
8219 return false;
8220 Numeric_constant inc;
8221 if (!args->back()->numeric_constant_value(&inc))
8222 return false;
8223
8224 if (rnc.type() != NULL
8225 && !rnc.type()->is_abstract()
8226 && inc.type() != NULL
8227 && !inc.type()->is_abstract()
8228 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8229 return false;
8230
e440a328 8231 mpfr_t r;
0c77715b 8232 if (!rnc.to_float(&r))
8233 return false;
8234 mpfr_t i;
8235 if (!inc.to_float(&i))
e440a328 8236 {
8237 mpfr_clear(r);
8238 return false;
8239 }
8240
0c77715b 8241 Type* arg_type = rnc.type();
8242 if (arg_type == NULL || arg_type->is_abstract())
8243 arg_type = inc.type();
e440a328 8244
fcbea5e4 8245 mpc_t val;
8246 mpc_init2(val, mpc_precision);
8247 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
e440a328 8248 mpfr_clear(r);
8249 mpfr_clear(i);
8250
fcbea5e4 8251 Type* type = Builtin_call_expression::complex_type(arg_type);
8252 nc->set_complex(type, val);
8253
8254 mpc_clear(val);
8255
0c77715b 8256 return true;
e440a328 8257 }
8258
8259 return false;
8260}
8261
a7549a6a 8262// Give an error if we are discarding the value of an expression which
8263// should not normally be discarded. We don't give an error for
8264// discarding the value of an ordinary function call, but we do for
8265// builtin functions, purely for consistency with the gc compiler.
8266
4f2138d7 8267bool
a7549a6a 8268Builtin_call_expression::do_discarding_value()
8269{
8270 switch (this->code_)
8271 {
8272 case BUILTIN_INVALID:
8273 default:
8274 go_unreachable();
8275
8276 case BUILTIN_APPEND:
8277 case BUILTIN_CAP:
8278 case BUILTIN_COMPLEX:
8279 case BUILTIN_IMAG:
8280 case BUILTIN_LEN:
8281 case BUILTIN_MAKE:
8282 case BUILTIN_NEW:
8283 case BUILTIN_REAL:
8284 case BUILTIN_ALIGNOF:
8285 case BUILTIN_OFFSETOF:
8286 case BUILTIN_SIZEOF:
8287 this->unused_value_error();
4f2138d7 8288 return false;
a7549a6a 8289
8290 case BUILTIN_CLOSE:
8291 case BUILTIN_COPY:
1cce762f 8292 case BUILTIN_DELETE:
a7549a6a 8293 case BUILTIN_PANIC:
8294 case BUILTIN_PRINT:
8295 case BUILTIN_PRINTLN:
8296 case BUILTIN_RECOVER:
4f2138d7 8297 return true;
a7549a6a 8298 }
8299}
8300
e440a328 8301// Return the type.
8302
8303Type*
8304Builtin_call_expression::do_type()
8305{
79651b1f 8306 if (this->is_error_expression())
8307 return Type::make_error_type();
e440a328 8308 switch (this->code_)
8309 {
8310 case BUILTIN_INVALID:
8311 default:
79651b1f 8312 return Type::make_error_type();
e440a328 8313
8314 case BUILTIN_NEW:
8315 case BUILTIN_MAKE:
8316 {
8317 const Expression_list* args = this->args();
8318 if (args == NULL || args->empty())
8319 return Type::make_error_type();
8320 return Type::make_pointer_type(args->front()->type());
8321 }
8322
8323 case BUILTIN_CAP:
8324 case BUILTIN_COPY:
8325 case BUILTIN_LEN:
7ba86326 8326 return Type::lookup_integer_type("int");
8327
e440a328 8328 case BUILTIN_ALIGNOF:
8329 case BUILTIN_OFFSETOF:
8330 case BUILTIN_SIZEOF:
7ba86326 8331 return Type::lookup_integer_type("uintptr");
e440a328 8332
8333 case BUILTIN_CLOSE:
1cce762f 8334 case BUILTIN_DELETE:
e440a328 8335 case BUILTIN_PANIC:
8336 case BUILTIN_PRINT:
8337 case BUILTIN_PRINTLN:
8338 return Type::make_void_type();
8339
e440a328 8340 case BUILTIN_RECOVER:
823c7e3d 8341 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8342
8343 case BUILTIN_APPEND:
8344 {
8345 const Expression_list* args = this->args();
8346 if (args == NULL || args->empty())
8347 return Type::make_error_type();
3ff4863b 8348 Type *ret = args->front()->type();
8349 if (!ret->is_slice_type())
8350 return Type::make_error_type();
8351 return ret;
e440a328 8352 }
8353
8354 case BUILTIN_REAL:
8355 case BUILTIN_IMAG:
8356 {
8357 Expression* arg = this->one_arg();
8358 if (arg == NULL)
8359 return Type::make_error_type();
8360 Type* t = arg->type();
8361 if (t->is_abstract())
8362 t = t->make_non_abstract_type();
8363 t = Builtin_call_expression::real_imag_type(t);
8364 if (t == NULL)
8365 t = Type::make_error_type();
8366 return t;
8367 }
8368
48080209 8369 case BUILTIN_COMPLEX:
e440a328 8370 {
8371 const Expression_list* args = this->args();
8372 if (args == NULL || args->size() != 2)
8373 return Type::make_error_type();
8374 Type* t = args->front()->type();
8375 if (t->is_abstract())
8376 {
8377 t = args->back()->type();
8378 if (t->is_abstract())
8379 t = t->make_non_abstract_type();
8380 }
48080209 8381 t = Builtin_call_expression::complex_type(t);
e440a328 8382 if (t == NULL)
8383 t = Type::make_error_type();
8384 return t;
8385 }
8386 }
8387}
8388
8389// Determine the type.
8390
8391void
8392Builtin_call_expression::do_determine_type(const Type_context* context)
8393{
fb94b0ca 8394 if (!this->determining_types())
8395 return;
8396
e440a328 8397 this->fn()->determine_type_no_context();
8398
8399 const Expression_list* args = this->args();
8400
8401 bool is_print;
8402 Type* arg_type = NULL;
321e5ad2 8403 Type* trailing_arg_types = NULL;
e440a328 8404 switch (this->code_)
8405 {
8406 case BUILTIN_PRINT:
8407 case BUILTIN_PRINTLN:
8408 // Do not force a large integer constant to "int".
8409 is_print = true;
8410 break;
8411
8412 case BUILTIN_REAL:
8413 case BUILTIN_IMAG:
48080209 8414 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 8415 if (arg_type == NULL)
8416 arg_type = Type::lookup_complex_type("complex128");
e440a328 8417 is_print = false;
8418 break;
8419
48080209 8420 case BUILTIN_COMPLEX:
e440a328 8421 {
48080209 8422 // For the complex function the type of one operand can
e440a328 8423 // determine the type of the other, as in a binary expression.
8424 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 8425 if (arg_type == NULL)
8426 arg_type = Type::lookup_float_type("float64");
e440a328 8427 if (args != NULL && args->size() == 2)
8428 {
8429 Type* t1 = args->front()->type();
c849bb59 8430 Type* t2 = args->back()->type();
e440a328 8431 if (!t1->is_abstract())
8432 arg_type = t1;
8433 else if (!t2->is_abstract())
8434 arg_type = t2;
8435 }
8436 is_print = false;
8437 }
8438 break;
8439
321e5ad2 8440 case BUILTIN_APPEND:
8441 if (!this->is_varargs()
8442 && args != NULL
8443 && !args->empty()
8444 && args->front()->type()->is_slice_type())
8445 trailing_arg_types =
8446 args->front()->type()->array_type()->element_type();
8447 is_print = false;
8448 break;
8449
e440a328 8450 default:
8451 is_print = false;
8452 break;
8453 }
8454
8455 if (args != NULL)
8456 {
8457 for (Expression_list::const_iterator pa = args->begin();
8458 pa != args->end();
8459 ++pa)
8460 {
8461 Type_context subcontext;
8462 subcontext.type = arg_type;
8463
8464 if (is_print)
8465 {
8466 // We want to print large constants, we so can't just
8467 // use the appropriate nonabstract type. Use uint64 for
8468 // an integer if we know it is nonnegative, otherwise
8469 // use int64 for a integer, otherwise use float64 for a
8470 // float or complex128 for a complex.
8471 Type* want_type = NULL;
8472 Type* atype = (*pa)->type();
8473 if (atype->is_abstract())
8474 {
8475 if (atype->integer_type() != NULL)
8476 {
0c77715b 8477 Numeric_constant nc;
8478 if (this->numeric_constant_value(&nc))
8479 {
8480 mpz_t val;
8481 if (nc.to_int(&val))
8482 {
8483 if (mpz_sgn(val) >= 0)
8484 want_type = Type::lookup_integer_type("uint64");
8485 mpz_clear(val);
8486 }
8487 }
8488 if (want_type == NULL)
e440a328 8489 want_type = Type::lookup_integer_type("int64");
e440a328 8490 }
8491 else if (atype->float_type() != NULL)
8492 want_type = Type::lookup_float_type("float64");
8493 else if (atype->complex_type() != NULL)
8494 want_type = Type::lookup_complex_type("complex128");
8495 else if (atype->is_abstract_string_type())
8496 want_type = Type::lookup_string_type();
8497 else if (atype->is_abstract_boolean_type())
8498 want_type = Type::lookup_bool_type();
8499 else
c3e6f413 8500 go_unreachable();
e440a328 8501 subcontext.type = want_type;
8502 }
8503 }
8504
8505 (*pa)->determine_type(&subcontext);
321e5ad2 8506
8507 if (trailing_arg_types != NULL)
8508 {
8509 arg_type = trailing_arg_types;
8510 trailing_arg_types = NULL;
8511 }
e440a328 8512 }
8513 }
8514}
8515
8516// If there is exactly one argument, return true. Otherwise give an
8517// error message and return false.
8518
8519bool
8520Builtin_call_expression::check_one_arg()
8521{
8522 const Expression_list* args = this->args();
8523 if (args == NULL || args->size() < 1)
8524 {
8525 this->report_error(_("not enough arguments"));
8526 return false;
8527 }
8528 else if (args->size() > 1)
8529 {
8530 this->report_error(_("too many arguments"));
8531 return false;
8532 }
8533 if (args->front()->is_error_expression()
5c13bd80 8534 || args->front()->type()->is_error())
e440a328 8535 {
8536 this->set_is_error();
8537 return false;
8538 }
8539 return true;
8540}
8541
8542// Check argument types for a builtin function.
8543
8544void
8545Builtin_call_expression::do_check_types(Gogo*)
8546{
375646ea 8547 if (this->is_error_expression())
8548 return;
e440a328 8549 switch (this->code_)
8550 {
8551 case BUILTIN_INVALID:
8552 case BUILTIN_NEW:
8553 case BUILTIN_MAKE:
cd238b8d 8554 case BUILTIN_DELETE:
e440a328 8555 return;
8556
8557 case BUILTIN_LEN:
8558 case BUILTIN_CAP:
8559 {
8560 // The single argument may be either a string or an array or a
8561 // map or a channel, or a pointer to a closed array.
8562 if (this->check_one_arg())
8563 {
8564 Type* arg_type = this->one_arg()->type();
8565 if (arg_type->points_to() != NULL
8566 && arg_type->points_to()->array_type() != NULL
411eb89e 8567 && !arg_type->points_to()->is_slice_type())
e440a328 8568 arg_type = arg_type->points_to();
8569 if (this->code_ == BUILTIN_CAP)
8570 {
5c13bd80 8571 if (!arg_type->is_error()
e440a328 8572 && arg_type->array_type() == NULL
8573 && arg_type->channel_type() == NULL)
8574 this->report_error(_("argument must be array or slice "
8575 "or channel"));
8576 }
8577 else
8578 {
5c13bd80 8579 if (!arg_type->is_error()
e440a328 8580 && !arg_type->is_string_type()
8581 && arg_type->array_type() == NULL
8582 && arg_type->map_type() == NULL
8583 && arg_type->channel_type() == NULL)
8584 this->report_error(_("argument must be string or "
8585 "array or slice or map or channel"));
8586 }
8587 }
8588 }
8589 break;
8590
8591 case BUILTIN_PRINT:
8592 case BUILTIN_PRINTLN:
8593 {
8594 const Expression_list* args = this->args();
8595 if (args == NULL)
8596 {
8597 if (this->code_ == BUILTIN_PRINT)
631d5788 8598 go_warning_at(this->location(), 0,
e440a328 8599 "no arguments for builtin function %<%s%>",
8600 (this->code_ == BUILTIN_PRINT
8601 ? "print"
8602 : "println"));
8603 }
8604 else
8605 {
8606 for (Expression_list::const_iterator p = args->begin();
8607 p != args->end();
8608 ++p)
8609 {
8610 Type* type = (*p)->type();
5c13bd80 8611 if (type->is_error()
e440a328 8612 || type->is_string_type()
8613 || type->integer_type() != NULL
8614 || type->float_type() != NULL
8615 || type->complex_type() != NULL
8616 || type->is_boolean_type()
8617 || type->points_to() != NULL
8618 || type->interface_type() != NULL
8619 || type->channel_type() != NULL
8620 || type->map_type() != NULL
8621 || type->function_type() != NULL
411eb89e 8622 || type->is_slice_type())
e440a328 8623 ;
acf8e158 8624 else if ((*p)->is_type_expression())
8625 {
8626 // If this is a type expression it's going to give
8627 // an error anyhow, so we don't need one here.
8628 }
e440a328 8629 else
8630 this->report_error(_("unsupported argument type to "
8631 "builtin function"));
8632 }
8633 }
8634 }
8635 break;
8636
8637 case BUILTIN_CLOSE:
e440a328 8638 if (this->check_one_arg())
8639 {
8640 if (this->one_arg()->type()->channel_type() == NULL)
8641 this->report_error(_("argument must be channel"));
5202d986 8642 else if (!this->one_arg()->type()->channel_type()->may_send())
8643 this->report_error(_("cannot close receive-only channel"));
e440a328 8644 }
8645 break;
8646
8647 case BUILTIN_PANIC:
8648 case BUILTIN_SIZEOF:
8649 case BUILTIN_ALIGNOF:
8650 this->check_one_arg();
8651 break;
8652
8653 case BUILTIN_RECOVER:
6334270b 8654 if (this->args() != NULL
8655 && !this->args()->empty()
8656 && !this->recover_arg_is_set_)
e440a328 8657 this->report_error(_("too many arguments"));
8658 break;
8659
8660 case BUILTIN_OFFSETOF:
8661 if (this->check_one_arg())
8662 {
8663 Expression* arg = this->one_arg();
8664 if (arg->field_reference_expression() == NULL)
8665 this->report_error(_("argument must be a field reference"));
8666 }
8667 break;
8668
8669 case BUILTIN_COPY:
8670 {
8671 const Expression_list* args = this->args();
8672 if (args == NULL || args->size() < 2)
8673 {
8674 this->report_error(_("not enough arguments"));
8675 break;
8676 }
8677 else if (args->size() > 2)
8678 {
8679 this->report_error(_("too many arguments"));
8680 break;
8681 }
8682 Type* arg1_type = args->front()->type();
8683 Type* arg2_type = args->back()->type();
5c13bd80 8684 if (arg1_type->is_error() || arg2_type->is_error())
6bebb39d 8685 {
8686 this->set_is_error();
8687 break;
8688 }
e440a328 8689
8690 Type* e1;
411eb89e 8691 if (arg1_type->is_slice_type())
e440a328 8692 e1 = arg1_type->array_type()->element_type();
8693 else
8694 {
8695 this->report_error(_("left argument must be a slice"));
8696 break;
8697 }
8698
411eb89e 8699 if (arg2_type->is_slice_type())
60963afd 8700 {
8701 Type* e2 = arg2_type->array_type()->element_type();
8702 if (!Type::are_identical(e1, e2, true, NULL))
8703 this->report_error(_("element types must be the same"));
8704 }
e440a328 8705 else if (arg2_type->is_string_type())
e440a328 8706 {
60963afd 8707 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8708 this->report_error(_("first argument must be []byte"));
e440a328 8709 }
60963afd 8710 else
8711 this->report_error(_("second argument must be slice or string"));
e440a328 8712 }
8713 break;
8714
8715 case BUILTIN_APPEND:
8716 {
8717 const Expression_list* args = this->args();
321e5ad2 8718 if (args == NULL || args->empty())
e440a328 8719 {
8720 this->report_error(_("not enough arguments"));
8721 break;
8722 }
321e5ad2 8723
8724 Type* slice_type = args->front()->type();
8725 if (!slice_type->is_slice_type())
6bebb39d 8726 {
321e5ad2 8727 if (slice_type->is_error_type())
8728 break;
8729 if (slice_type->is_nil_type())
8730 go_error_at(args->front()->location(), "use of untyped nil");
8731 else
8732 go_error_at(args->front()->location(),
8733 "argument 1 must be a slice");
6bebb39d 8734 this->set_is_error();
8735 break;
8736 }
cd238b8d 8737
321e5ad2 8738 Type* element_type = slice_type->array_type()->element_type();
8739 if (this->is_varargs())
4fd4fcf4 8740 {
321e5ad2 8741 if (!args->back()->type()->is_slice_type()
8742 && !args->back()->type()->is_string_type())
8743 {
8744 go_error_at(args->back()->location(),
8745 "invalid use of %<...%> with non-slice/non-string");
8746 this->set_is_error();
8747 break;
8748 }
4fd4fcf4 8749
321e5ad2 8750 if (args->size() < 2)
8751 {
8752 this->report_error(_("not enough arguments"));
8753 break;
8754 }
8755 if (args->size() > 2)
8756 {
8757 this->report_error(_("too many arguments"));
8758 break;
8759 }
8760
8761 if (args->back()->type()->is_string_type()
8762 && element_type->integer_type() != NULL
8763 && element_type->integer_type()->is_byte())
8764 {
8765 // Permit append(s1, s2...) when s1 is a slice of
8766 // bytes and s2 is a string type.
8767 }
e440a328 8768 else
8769 {
321e5ad2 8770 // We have to test for assignment compatibility to a
8771 // slice of the element type, which is not necessarily
8772 // the same as the type of the first argument: the
8773 // first argument might have a named type.
8774 Type* check_type = Type::make_array_type(element_type, NULL);
8775 std::string reason;
8776 if (!Type::are_assignable(check_type, args->back()->type(),
8777 &reason))
8778 {
8779 if (reason.empty())
8780 go_error_at(args->back()->location(),
8781 "argument 2 has invalid type");
8782 else
8783 go_error_at(args->back()->location(),
8784 "argument 2 has invalid type (%s)",
8785 reason.c_str());
8786 this->set_is_error();
8787 break;
8788 }
8789 }
8790 }
8791 else
8792 {
8793 Expression_list::const_iterator pa = args->begin();
8794 int i = 2;
8795 for (++pa; pa != args->end(); ++pa, ++i)
8796 {
8797 std::string reason;
8798 if (!Type::are_assignable(element_type, (*pa)->type(),
8799 &reason))
8800 {
8801 if (reason.empty())
8802 go_error_at((*pa)->location(),
8803 "argument %d has incompatible type", i);
8804 else
8805 go_error_at((*pa)->location(),
8806 "argument %d has incompatible type (%s)",
8807 i, reason.c_str());
8808 this->set_is_error();
8809 }
e440a328 8810 }
8811 }
e440a328 8812 }
321e5ad2 8813 break;
e440a328 8814
8815 case BUILTIN_REAL:
8816 case BUILTIN_IMAG:
8817 if (this->check_one_arg())
8818 {
8819 if (this->one_arg()->type()->complex_type() == NULL)
8820 this->report_error(_("argument must have complex type"));
8821 }
8822 break;
8823
48080209 8824 case BUILTIN_COMPLEX:
e440a328 8825 {
8826 const Expression_list* args = this->args();
8827 if (args == NULL || args->size() < 2)
8828 this->report_error(_("not enough arguments"));
8829 else if (args->size() > 2)
8830 this->report_error(_("too many arguments"));
8831 else if (args->front()->is_error_expression()
5c13bd80 8832 || args->front()->type()->is_error()
e440a328 8833 || args->back()->is_error_expression()
5c13bd80 8834 || args->back()->type()->is_error())
e440a328 8835 this->set_is_error();
8836 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8837 args->back()->type(), true, NULL))
48080209 8838 this->report_error(_("complex arguments must have identical types"));
e440a328 8839 else if (args->front()->type()->float_type() == NULL)
48080209 8840 this->report_error(_("complex arguments must have "
e440a328 8841 "floating-point type"));
8842 }
8843 break;
8844
8845 default:
c3e6f413 8846 go_unreachable();
e440a328 8847 }
8848}
8849
72666aed 8850Expression*
8851Builtin_call_expression::do_copy()
8852{
8853 Call_expression* bce =
8854 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
da244e59 8855 (this->args() == NULL
8856 ? NULL
8857 : this->args()->copy()),
72666aed 8858 this->is_varargs(),
8859 this->location());
8860
8861 if (this->varargs_are_lowered())
8862 bce->set_varargs_are_lowered();
8863 return bce;
8864}
8865
ea664253 8866// Return the backend representation for a builtin function.
e440a328 8867
ea664253 8868Bexpression*
8869Builtin_call_expression::do_get_backend(Translate_context* context)
e440a328 8870{
8871 Gogo* gogo = context->gogo();
b13c66cd 8872 Location location = this->location();
a0d8874e 8873
8874 if (this->is_erroneous_call())
8875 {
8876 go_assert(saw_errors());
8877 return gogo->backend()->error_expression();
8878 }
8879
e440a328 8880 switch (this->code_)
8881 {
8882 case BUILTIN_INVALID:
8883 case BUILTIN_NEW:
8884 case BUILTIN_MAKE:
c3e6f413 8885 go_unreachable();
e440a328 8886
8887 case BUILTIN_LEN:
8888 case BUILTIN_CAP:
8889 {
8890 const Expression_list* args = this->args();
c484d925 8891 go_assert(args != NULL && args->size() == 1);
2c809f8f 8892 Expression* arg = args->front();
e440a328 8893 Type* arg_type = arg->type();
0f914071 8894
8895 if (this->seen_)
8896 {
c484d925 8897 go_assert(saw_errors());
ea664253 8898 return context->backend()->error_expression();
0f914071 8899 }
8900 this->seen_ = true;
0f914071 8901 this->seen_ = false;
e440a328 8902 if (arg_type->points_to() != NULL)
8903 {
8904 arg_type = arg_type->points_to();
c484d925 8905 go_assert(arg_type->array_type() != NULL
411eb89e 8906 && !arg_type->is_slice_type());
2c809f8f 8907 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8908 }
8909
1b1f2abf 8910 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8911 Expression* val;
e440a328 8912 if (this->code_ == BUILTIN_LEN)
8913 {
8914 if (arg_type->is_string_type())
2c809f8f 8915 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8916 location);
e440a328 8917 else if (arg_type->array_type() != NULL)
0f914071 8918 {
8919 if (this->seen_)
8920 {
c484d925 8921 go_assert(saw_errors());
ea664253 8922 return context->backend()->error_expression();
0f914071 8923 }
8924 this->seen_ = true;
2c809f8f 8925 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8926 this->seen_ = false;
8927 }
0d5530d9 8928 else if (arg_type->map_type() != NULL
8929 || arg_type->channel_type() != NULL)
8930 {
8931 // The first field is the length. If the pointer is
8932 // nil, the length is zero.
8933 Type* pint_type = Type::make_pointer_type(int_type);
8934 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8935 Expression* nil = Expression::make_nil(location);
8936 nil = Expression::make_cast(pint_type, nil, location);
8937 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8938 arg, nil, location);
8939 Expression* zero = Expression::make_integer_ul(0, int_type,
8940 location);
8941 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8942 arg, location);
8943 val = Expression::make_conditional(cmp, zero, indir, location);
8944 }
e440a328 8945 else
c3e6f413 8946 go_unreachable();
e440a328 8947 }
8948 else
8949 {
8950 if (arg_type->array_type() != NULL)
0f914071 8951 {
8952 if (this->seen_)
8953 {
c484d925 8954 go_assert(saw_errors());
ea664253 8955 return context->backend()->error_expression();
0f914071 8956 }
8957 this->seen_ = true;
2c809f8f 8958 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8959 this->seen_ = false;
8960 }
e440a328 8961 else if (arg_type->channel_type() != NULL)
132ed071 8962 {
8963 // The second field is the capacity. If the pointer
8964 // is nil, the capacity is zero.
8965 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8966 Type* pint_type = Type::make_pointer_type(int_type);
8967 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8968 arg,
8969 location);
8970 int off = int_type->integer_type()->bits() / 8;
8971 Expression* eoff = Expression::make_integer_ul(off,
8972 uintptr_type,
8973 location);
8974 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8975 location);
8976 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8977 Expression* nil = Expression::make_nil(location);
8978 nil = Expression::make_cast(pint_type, nil, location);
8979 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8980 arg, nil, location);
8981 Expression* zero = Expression::make_integer_ul(0, int_type,
8982 location);
8983 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8984 parg, location);
8985 val = Expression::make_conditional(cmp, zero, indir, location);
8986 }
e440a328 8987 else
c3e6f413 8988 go_unreachable();
e440a328 8989 }
8990
2c809f8f 8991 return Expression::make_cast(int_type, val,
ea664253 8992 location)->get_backend(context);
e440a328 8993 }
8994
8995 case BUILTIN_PRINT:
8996 case BUILTIN_PRINTLN:
8997 {
8998 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
88b03a70 8999
9000 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9001 location, 0);
e440a328 9002
9003 const Expression_list* call_args = this->args();
9004 if (call_args != NULL)
9005 {
9006 for (Expression_list::const_iterator p = call_args->begin();
9007 p != call_args->end();
9008 ++p)
9009 {
9010 if (is_ln && p != call_args->begin())
9011 {
2c809f8f 9012 Expression* print_space =
88b03a70 9013 Runtime::make_call(Runtime::PRINTSP, location, 0);
e440a328 9014
2c809f8f 9015 print_stmts =
9016 Expression::make_compound(print_stmts, print_space,
9017 location);
9018 }
e440a328 9019
2c809f8f 9020 Expression* arg = *p;
9021 Type* type = arg->type();
9022 Runtime::Function code;
e440a328 9023 if (type->is_string_type())
88b03a70 9024 code = Runtime::PRINTSTRING;
e440a328 9025 else if (type->integer_type() != NULL
9026 && type->integer_type()->is_unsigned())
9027 {
e440a328 9028 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 9029 arg = Expression::make_cast(itype, arg, location);
88b03a70 9030 code = Runtime::PRINTUINT;
e440a328 9031 }
9032 else if (type->integer_type() != NULL)
9033 {
e440a328 9034 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 9035 arg = Expression::make_cast(itype, arg, location);
88b03a70 9036 code = Runtime::PRINTINT;
e440a328 9037 }
9038 else if (type->float_type() != NULL)
9039 {
2c809f8f 9040 Type* dtype = Type::lookup_float_type("float64");
9041 arg = Expression::make_cast(dtype, arg, location);
88b03a70 9042 code = Runtime::PRINTFLOAT;
e440a328 9043 }
9044 else if (type->complex_type() != NULL)
9045 {
2c809f8f 9046 Type* ctype = Type::lookup_complex_type("complex128");
9047 arg = Expression::make_cast(ctype, arg, location);
88b03a70 9048 code = Runtime::PRINTCOMPLEX;
e440a328 9049 }
9050 else if (type->is_boolean_type())
88b03a70 9051 code = Runtime::PRINTBOOL;
e440a328 9052 else if (type->points_to() != NULL
9053 || type->channel_type() != NULL
9054 || type->map_type() != NULL
9055 || type->function_type() != NULL)
9056 {
2c809f8f 9057 arg = Expression::make_cast(type, arg, location);
88b03a70 9058 code = Runtime::PRINTPOINTER;
e440a328 9059 }
9060 else if (type->interface_type() != NULL)
9061 {
9062 if (type->interface_type()->is_empty())
88b03a70 9063 code = Runtime::PRINTEFACE;
e440a328 9064 else
88b03a70 9065 code = Runtime::PRINTIFACE;
e440a328 9066 }
411eb89e 9067 else if (type->is_slice_type())
88b03a70 9068 code = Runtime::PRINTSLICE;
e440a328 9069 else
cd238b8d 9070 {
9071 go_assert(saw_errors());
ea664253 9072 return context->backend()->error_expression();
cd238b8d 9073 }
e440a328 9074
2c809f8f 9075 Expression* call = Runtime::make_call(code, location, 1, arg);
88b03a70 9076 print_stmts = Expression::make_compound(print_stmts, call,
9077 location);
e440a328 9078 }
9079 }
9080
9081 if (is_ln)
9082 {
2c809f8f 9083 Expression* print_nl =
88b03a70 9084 Runtime::make_call(Runtime::PRINTNL, location, 0);
9085 print_stmts = Expression::make_compound(print_stmts, print_nl,
9086 location);
e440a328 9087 }
9088
88b03a70 9089 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9090 location, 0);
9091 print_stmts = Expression::make_compound(print_stmts, unlock, location);
32e3ff69 9092
ea664253 9093 return print_stmts->get_backend(context);
e440a328 9094 }
9095
9096 case BUILTIN_PANIC:
9097 {
9098 const Expression_list* args = this->args();
c484d925 9099 go_assert(args != NULL && args->size() == 1);
e440a328 9100 Expression* arg = args->front();
b13c66cd 9101 Type *empty =
823c7e3d 9102 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 9103 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9104
9105 Expression* panic =
03ac9de4 9106 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
ea664253 9107 return panic->get_backend(context);
e440a328 9108 }
9109
9110 case BUILTIN_RECOVER:
9111 {
9112 // The argument is set when building recover thunks. It's a
9113 // boolean value which is true if we can recover a value now.
9114 const Expression_list* args = this->args();
c484d925 9115 go_assert(args != NULL && args->size() == 1);
e440a328 9116 Expression* arg = args->front();
b13c66cd 9117 Type *empty =
823c7e3d 9118 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 9119
e440a328 9120 Expression* nil = Expression::make_nil(location);
2c809f8f 9121 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 9122
9123 // We need to handle a deferred call to recover specially,
9124 // because it changes whether it can recover a panic or not.
9125 // See test7 in test/recover1.go.
2c809f8f 9126 Expression* recover = Runtime::make_call((this->is_deferred()
03ac9de4 9127 ? Runtime::DEFERREDRECOVER
9128 : Runtime::GORECOVER),
2c809f8f 9129 location, 0);
9130 Expression* cond =
9131 Expression::make_conditional(arg, recover, nil, location);
ea664253 9132 return cond->get_backend(context);
e440a328 9133 }
9134
9135 case BUILTIN_CLOSE:
e440a328 9136 {
9137 const Expression_list* args = this->args();
c484d925 9138 go_assert(args != NULL && args->size() == 1);
e440a328 9139 Expression* arg = args->front();
2c809f8f 9140 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9141 1, arg);
ea664253 9142 return close->get_backend(context);
e440a328 9143 }
9144
9145 case BUILTIN_SIZEOF:
9146 case BUILTIN_OFFSETOF:
9147 case BUILTIN_ALIGNOF:
9148 {
0c77715b 9149 Numeric_constant nc;
9150 unsigned long val;
9151 if (!this->numeric_constant_value(&nc)
9152 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 9153 {
c484d925 9154 go_assert(saw_errors());
ea664253 9155 return context->backend()->error_expression();
7f1d9abd 9156 }
7ba86326 9157 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 9158 mpz_t ival;
9159 nc.get_int(&ival);
9160 Expression* int_cst =
e67508fa 9161 Expression::make_integer_z(&ival, uintptr_type, location);
2c809f8f 9162 mpz_clear(ival);
ea664253 9163 return int_cst->get_backend(context);
e440a328 9164 }
9165
9166 case BUILTIN_COPY:
9167 {
9168 const Expression_list* args = this->args();
c484d925 9169 go_assert(args != NULL && args->size() == 2);
e440a328 9170 Expression* arg1 = args->front();
9171 Expression* arg2 = args->back();
9172
e440a328 9173 Type* arg1_type = arg1->type();
9174 Array_type* at = arg1_type->array_type();
35a54f17 9175 go_assert(arg1->is_variable());
321e5ad2 9176
9177 Expression* call;
e440a328 9178
9179 Type* arg2_type = arg2->type();
2c809f8f 9180 go_assert(arg2->is_variable());
321e5ad2 9181 if (arg2_type->is_string_type())
9182 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9183 2, arg1, arg2);
e440a328 9184 else
9185 {
321e5ad2 9186 Type* et = at->element_type();
9187 if (et->has_pointer())
9188 {
9189 Expression* td = Expression::make_type_descriptor(et,
9190 location);
9191 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9192 3, td, arg1, arg2);
9193 }
9194 else
9195 {
9196 Expression* sz = Expression::make_type_info(et,
9197 TYPE_INFO_SIZE);
9198 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9199 arg1, arg2, sz);
9200 }
e440a328 9201 }
2c809f8f 9202
321e5ad2 9203 return call->get_backend(context);
e440a328 9204 }
9205
9206 case BUILTIN_APPEND:
321e5ad2 9207 // Handled in Builtin_call_expression::flatten_append.
9208 go_unreachable();
e440a328 9209
9210 case BUILTIN_REAL:
9211 case BUILTIN_IMAG:
9212 {
9213 const Expression_list* args = this->args();
c484d925 9214 go_assert(args != NULL && args->size() == 1);
2c809f8f 9215
9216 Bexpression* ret;
ea664253 9217 Bexpression* bcomplex = args->front()->get_backend(context);
2c809f8f 9218 if (this->code_ == BUILTIN_REAL)
9219 ret = gogo->backend()->real_part_expression(bcomplex, location);
9220 else
9221 ret = gogo->backend()->imag_part_expression(bcomplex, location);
ea664253 9222 return ret;
e440a328 9223 }
9224
48080209 9225 case BUILTIN_COMPLEX:
e440a328 9226 {
9227 const Expression_list* args = this->args();
c484d925 9228 go_assert(args != NULL && args->size() == 2);
ea664253 9229 Bexpression* breal = args->front()->get_backend(context);
9230 Bexpression* bimag = args->back()->get_backend(context);
9231 return gogo->backend()->complex_expression(breal, bimag, location);
e440a328 9232 }
9233
9234 default:
c3e6f413 9235 go_unreachable();
e440a328 9236 }
9237}
9238
9239// We have to support exporting a builtin call expression, because
9240// code can set a constant to the result of a builtin expression.
9241
9242void
9243Builtin_call_expression::do_export(Export* exp) const
9244{
0c77715b 9245 Numeric_constant nc;
9246 if (!this->numeric_constant_value(&nc))
9247 {
631d5788 9248 go_error_at(this->location(), "value is not constant");
0c77715b 9249 return;
9250 }
e440a328 9251
0c77715b 9252 if (nc.is_int())
e440a328 9253 {
0c77715b 9254 mpz_t val;
9255 nc.get_int(&val);
e440a328 9256 Integer_expression::export_integer(exp, val);
0c77715b 9257 mpz_clear(val);
e440a328 9258 }
0c77715b 9259 else if (nc.is_float())
e440a328 9260 {
9261 mpfr_t fval;
0c77715b 9262 nc.get_float(&fval);
9263 Float_expression::export_float(exp, fval);
e440a328 9264 mpfr_clear(fval);
9265 }
0c77715b 9266 else if (nc.is_complex())
e440a328 9267 {
fcbea5e4 9268 mpc_t cval;
9269 nc.get_complex(&cval);
9270 Complex_expression::export_complex(exp, cval);
9271 mpc_clear(cval);
e440a328 9272 }
0c77715b 9273 else
9274 go_unreachable();
e440a328 9275
9276 // A trailing space lets us reliably identify the end of the number.
9277 exp->write_c_string(" ");
9278}
9279
9280// Class Call_expression.
9281
8381eda7 9282// A Go function can be viewed in a couple of different ways. The
9283// code of a Go function becomes a backend function with parameters
9284// whose types are simply the backend representation of the Go types.
9285// If there are multiple results, they are returned as a backend
9286// struct.
9287
9288// However, when Go code refers to a function other than simply
9289// calling it, the backend type of that function is actually a struct.
9290// The first field of the struct points to the Go function code
9291// (sometimes a wrapper as described below). The remaining fields
9292// hold addresses of closed-over variables. This struct is called a
9293// closure.
9294
9295// There are a few cases to consider.
9296
9297// A direct function call of a known function in package scope. In
9298// this case there are no closed-over variables, and we know the name
9299// of the function code. We can simply produce a backend call to the
9300// function directly, and not worry about the closure.
9301
9302// A direct function call of a known function literal. In this case
9303// we know the function code and we know the closure. We generate the
9304// function code such that it expects an additional final argument of
9305// the closure type. We pass the closure as the last argument, after
9306// the other arguments.
9307
9308// An indirect function call. In this case we have a closure. We
9309// load the pointer to the function code from the first field of the
9310// closure. We pass the address of the closure as the last argument.
9311
9312// A call to a method of an interface. Type methods are always at
9313// package scope, so we call the function directly, and don't worry
9314// about the closure.
9315
9316// This means that for a function at package scope we have two cases.
9317// One is the direct call, which has no closure. The other is the
9318// indirect call, which does have a closure. We can't simply ignore
9319// the closure, even though it is the last argument, because that will
9320// fail on targets where the function pops its arguments. So when
9321// generating a closure for a package-scope function we set the
9322// function code pointer in the closure to point to a wrapper
9323// function. This wrapper function accepts a final argument that
9324// points to the closure, ignores it, and calls the real function as a
9325// direct function call. This wrapper will normally be efficient, and
9326// can often simply be a tail call to the real function.
9327
9328// We don't use GCC's static chain pointer because 1) we don't need
9329// it; 2) GCC only permits using a static chain to call a known
9330// function, so we can't use it for an indirect call anyhow. Since we
9331// can't use it for an indirect call, we may as well not worry about
9332// using it for a direct call either.
9333
9334// We pass the closure last rather than first because it means that
9335// the function wrapper we put into a closure for a package-scope
9336// function can normally just be a tail call to the real function.
9337
9338// For method expressions we generate a wrapper that loads the
9339// receiver from the closure and then calls the method. This
9340// unfortunately forces reshuffling the arguments, since there is a
9341// new first argument, but we can't avoid reshuffling either for
9342// method expressions or for indirect calls of package-scope
9343// functions, and since the latter are more common we reshuffle for
9344// method expressions.
9345
9346// Note that the Go code retains the Go types. The extra final
9347// argument only appears when we convert to the backend
9348// representation.
9349
e440a328 9350// Traversal.
9351
9352int
9353Call_expression::do_traverse(Traverse* traverse)
9354{
0c0dacab 9355 // If we are calling a function in a different package that returns
9356 // an unnamed type, this may be the only chance we get to traverse
9357 // that type. We don't traverse this->type_ because it may be a
9358 // Call_multiple_result_type that will just lead back here.
9359 if (this->type_ != NULL && !this->type_->is_error_type())
9360 {
9361 Function_type *fntype = this->get_function_type();
9362 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9363 return TRAVERSE_EXIT;
9364 }
e440a328 9365 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9366 return TRAVERSE_EXIT;
9367 if (this->args_ != NULL)
9368 {
9369 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9370 return TRAVERSE_EXIT;
9371 }
9372 return TRAVERSE_CONTINUE;
9373}
9374
9375// Lower a call statement.
9376
9377Expression*
ceeb4318 9378Call_expression::do_lower(Gogo* gogo, Named_object* function,
9379 Statement_inserter* inserter, int)
e440a328 9380{
b13c66cd 9381 Location loc = this->location();
09ea332d 9382
ceeb4318 9383 // A type cast can look like a function call.
e440a328 9384 if (this->fn_->is_type_expression()
9385 && this->args_ != NULL
9386 && this->args_->size() == 1)
9387 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 9388 loc);
e440a328 9389
88f06749 9390 // Because do_type will return an error type and thus prevent future
9391 // errors, check for that case now to ensure that the error gets
9392 // reported.
37448b10 9393 Function_type* fntype = this->get_function_type();
9394 if (fntype == NULL)
88f06749 9395 {
9396 if (!this->fn_->type()->is_error())
9397 this->report_error(_("expected function"));
5f1045b5 9398 this->set_is_error();
9399 return this;
88f06749 9400 }
9401
e440a328 9402 // Handle an argument which is a call to a function which returns
9403 // multiple results.
9404 if (this->args_ != NULL
9405 && this->args_->size() == 1
37448b10 9406 && this->args_->front()->call_expression() != NULL)
e440a328 9407 {
e440a328 9408 size_t rc = this->args_->front()->call_expression()->result_count();
9409 if (rc > 1
37448b10 9410 && ((fntype->parameters() != NULL
9411 && (fntype->parameters()->size() == rc
9412 || (fntype->is_varargs()
9413 && fntype->parameters()->size() - 1 <= rc)))
9414 || fntype->is_builtin()))
e440a328 9415 {
9416 Call_expression* call = this->args_->front()->call_expression();
e90ecd2d 9417 call->set_is_multi_value_arg();
c33af8e4 9418 if (this->is_varargs_)
9419 {
9420 // It is not clear which result of a multiple result call
9421 // the ellipsis operator should be applied to. If we unpack the
9422 // the call into its individual results here, the ellipsis will be
9423 // applied to the last result.
631d5788 9424 go_error_at(call->location(),
9425 _("multiple-value argument in single-value context"));
c33af8e4 9426 return Expression::make_error(call->location());
9427 }
9428
e440a328 9429 Expression_list* args = new Expression_list;
9430 for (size_t i = 0; i < rc; ++i)
9431 args->push_back(Expression::make_call_result(call, i));
9432 // We can't return a new call expression here, because this
42535814 9433 // one may be referenced by Call_result expressions. We
9434 // also can't delete the old arguments, because we may still
9435 // traverse them somewhere up the call stack. FIXME.
e440a328 9436 this->args_ = args;
9437 }
9438 }
9439
37448b10 9440 // Recognize a call to a builtin function.
9441 if (fntype->is_builtin())
9442 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9443 this->is_varargs_, loc);
9444
ceeb4318 9445 // If this call returns multiple results, create a temporary
9446 // variable for each result.
9447 size_t rc = this->result_count();
9448 if (rc > 1 && this->results_ == NULL)
9449 {
9450 std::vector<Temporary_statement*>* temps =
9451 new std::vector<Temporary_statement*>;
9452 temps->reserve(rc);
37448b10 9453 const Typed_identifier_list* results = fntype->results();
ceeb4318 9454 for (Typed_identifier_list::const_iterator p = results->begin();
9455 p != results->end();
9456 ++p)
9457 {
9458 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 9459 NULL, loc);
ceeb4318 9460 inserter->insert(temp);
9461 temps->push_back(temp);
9462 }
9463 this->results_ = temps;
9464 }
9465
e440a328 9466 // Handle a call to a varargs function by packaging up the extra
9467 // parameters.
37448b10 9468 if (fntype->is_varargs())
e440a328 9469 {
e440a328 9470 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 9471 go_assert(parameters != NULL && !parameters->empty());
e440a328 9472 Type* varargs_type = parameters->back().type();
09ea332d 9473 this->lower_varargs(gogo, function, inserter, varargs_type,
0e9a2e72 9474 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
09ea332d 9475 }
9476
9477 // If this is call to a method, call the method directly passing the
9478 // object as the first parameter.
9479 Bound_method_expression* bme = this->fn_->bound_method_expression();
9480 if (bme != NULL)
9481 {
0afbb937 9482 Named_object* methodfn = bme->function();
09ea332d 9483 Expression* first_arg = bme->first_argument();
9484
9485 // We always pass a pointer when calling a method.
9486 if (first_arg->type()->points_to() == NULL
9487 && !first_arg->type()->is_error())
9488 {
9489 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9490 // We may need to create a temporary variable so that we can
9491 // take the address. We can't do that here because it will
9492 // mess up the order of evaluation.
9493 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9494 ue->set_create_temp();
9495 }
9496
9497 // If we are calling a method which was inherited from an
9498 // embedded struct, and the method did not get a stub, then the
9499 // first type may be wrong.
9500 Type* fatype = bme->first_argument_type();
9501 if (fatype != NULL)
9502 {
9503 if (fatype->points_to() == NULL)
9504 fatype = Type::make_pointer_type(fatype);
9505 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9506 }
9507
9508 Expression_list* new_args = new Expression_list();
9509 new_args->push_back(first_arg);
9510 if (this->args_ != NULL)
9511 {
9512 for (Expression_list::const_iterator p = this->args_->begin();
9513 p != this->args_->end();
9514 ++p)
9515 new_args->push_back(*p);
9516 }
9517
9518 // We have to change in place because this structure may be
9519 // referenced by Call_result_expressions. We can't delete the
9520 // old arguments, because we may be traversing them up in some
9521 // caller. FIXME.
9522 this->args_ = new_args;
0afbb937 9523 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 9524 bme->location());
e440a328 9525 }
9526
105f9a24 9527 // Handle a couple of special runtime functions. In the runtime
9528 // package, getcallerpc returns the PC of the caller, and
9529 // getcallersp returns the frame pointer of the caller. Implement
9530 // these by turning them into calls to GCC builtin functions. We
9531 // could implement them in normal code, but then we would have to
9532 // explicitly unwind the stack. These functions are intended to be
9533 // efficient. Note that this technique obviously only works for
9534 // direct calls, but that is the only way they are used. The actual
9535 // argument to these functions is always the address of a parameter;
9536 // we don't need that for the GCC builtin functions, so we just
9537 // ignore it.
9538 if (gogo->compiling_runtime()
9539 && this->args_ != NULL
9540 && this->args_->size() == 1
9541 && gogo->package_name() == "runtime")
9542 {
9543 Func_expression* fe = this->fn_->func_expression();
9544 if (fe != NULL
9545 && fe->named_object()->is_function_declaration()
9546 && fe->named_object()->package() == NULL)
9547 {
9548 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9549 if (n == "getcallerpc")
9550 {
9551 static Named_object* builtin_return_address;
9552 return this->lower_to_builtin(&builtin_return_address,
9553 "__builtin_return_address",
9554 0);
9555 }
9556 else if (n == "getcallersp")
9557 {
9558 static Named_object* builtin_frame_address;
9559 return this->lower_to_builtin(&builtin_frame_address,
9560 "__builtin_frame_address",
9561 1);
9562 }
9563 }
9564 }
9565
e440a328 9566 return this;
9567}
9568
9569// Lower a call to a varargs function. FUNCTION is the function in
9570// which the call occurs--it's not the function we are calling.
9571// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9572// PARAM_COUNT is the number of parameters of the function we are
9573// calling; the last of these parameters will be the varargs
9574// parameter.
9575
09ea332d 9576void
e440a328 9577Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 9578 Statement_inserter* inserter,
0e9a2e72 9579 Type* varargs_type, size_t param_count,
9580 Slice_storage_escape_disp escape_disp)
e440a328 9581{
03118c21 9582 // When compiling the runtime, varargs slices do not escape. When
9583 // escape analysis becomes the default, this should be changed to
9584 // make it an error if we have a varargs slice that escapes.
9585 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9586 escape_disp = SLICE_STORAGE_DOES_NOT_ESCAPE;
9587
e440a328 9588 if (this->varargs_are_lowered_)
09ea332d 9589 return;
e440a328 9590
b13c66cd 9591 Location loc = this->location();
e440a328 9592
c484d925 9593 go_assert(param_count > 0);
411eb89e 9594 go_assert(varargs_type->is_slice_type());
e440a328 9595
9596 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9597 if (arg_count < param_count - 1)
9598 {
9599 // Not enough arguments; will be caught in check_types.
09ea332d 9600 return;
e440a328 9601 }
9602
9603 Expression_list* old_args = this->args_;
9604 Expression_list* new_args = new Expression_list();
9605 bool push_empty_arg = false;
9606 if (old_args == NULL || old_args->empty())
9607 {
c484d925 9608 go_assert(param_count == 1);
e440a328 9609 push_empty_arg = true;
9610 }
9611 else
9612 {
9613 Expression_list::const_iterator pa;
9614 int i = 1;
9615 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9616 {
9617 if (static_cast<size_t>(i) == param_count)
9618 break;
9619 new_args->push_back(*pa);
9620 }
9621
9622 // We have reached the varargs parameter.
9623
9624 bool issued_error = false;
9625 if (pa == old_args->end())
9626 push_empty_arg = true;
9627 else if (pa + 1 == old_args->end() && this->is_varargs_)
9628 new_args->push_back(*pa);
9629 else if (this->is_varargs_)
9630 {
a6645f74 9631 if ((*pa)->type()->is_slice_type())
9632 this->report_error(_("too many arguments"));
9633 else
9634 {
631d5788 9635 go_error_at(this->location(),
9636 _("invalid use of %<...%> with non-slice"));
a6645f74 9637 this->set_is_error();
9638 }
09ea332d 9639 return;
e440a328 9640 }
e440a328 9641 else
9642 {
9643 Type* element_type = varargs_type->array_type()->element_type();
9644 Expression_list* vals = new Expression_list;
9645 for (; pa != old_args->end(); ++pa, ++i)
9646 {
9647 // Check types here so that we get a better message.
9648 Type* patype = (*pa)->type();
b13c66cd 9649 Location paloc = (*pa)->location();
e440a328 9650 if (!this->check_argument_type(i, element_type, patype,
9651 paloc, issued_error))
9652 continue;
9653 vals->push_back(*pa);
9654 }
0e9a2e72 9655 Slice_construction_expression* sce =
e440a328 9656 Expression::make_slice_composite_literal(varargs_type, vals, loc);
0e9a2e72 9657 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9658 sce->set_storage_does_not_escape();
9659 Expression* val = sce;
09ea332d 9660 gogo->lower_expression(function, inserter, &val);
e440a328 9661 new_args->push_back(val);
9662 }
9663 }
9664
9665 if (push_empty_arg)
9666 new_args->push_back(Expression::make_nil(loc));
9667
9668 // We can't return a new call expression here, because this one may
6d4c2432 9669 // be referenced by Call_result expressions. FIXME. We can't
9670 // delete OLD_ARGS because we may have both a Call_expression and a
9671 // Builtin_call_expression which refer to them. FIXME.
e440a328 9672 this->args_ = new_args;
9673 this->varargs_are_lowered_ = true;
e440a328 9674}
9675
105f9a24 9676// Return a call to __builtin_return_address or __builtin_frame_address.
9677
9678Expression*
9679Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9680 int arg)
9681{
9682 if (*pno == NULL)
9683 *pno = Gogo::declare_builtin_rf_address(name);
9684
9685 Location loc = this->location();
9686
9687 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9688 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9689 Expression_list *args = new Expression_list();
9690 args->push_back(a);
9691 Expression* call = Expression::make_call(fn, args, false, loc);
9692
9693 // The builtin functions return void*, but the Go functions return uintptr.
9694 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9695 return Expression::make_cast(uintptr_type, call, loc);
9696}
9697
2c809f8f 9698// Flatten a call with multiple results into a temporary.
9699
9700Expression*
b8e86a51 9701Call_expression::do_flatten(Gogo* gogo, Named_object*,
9702 Statement_inserter* inserter)
2c809f8f 9703{
5bf8be8b 9704 if (this->is_erroneous_call())
9705 {
9706 go_assert(saw_errors());
9707 return Expression::make_error(this->location());
9708 }
b8e86a51 9709
91c0fd76 9710 if (this->is_flattened_)
9711 return this;
9712 this->is_flattened_ = true;
9713
b8e86a51 9714 // Add temporary variables for all arguments that require type
9715 // conversion.
9716 Function_type* fntype = this->get_function_type();
9782d556 9717 if (fntype == NULL)
9718 {
9719 go_assert(saw_errors());
9720 return this;
9721 }
b8e86a51 9722 if (this->args_ != NULL && !this->args_->empty()
9723 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9724 {
9725 bool is_interface_method =
9726 this->fn_->interface_field_reference_expression() != NULL;
9727
9728 Expression_list *args = new Expression_list();
9729 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9730 Expression_list::const_iterator pa = this->args_->begin();
9731 if (!is_interface_method && fntype->is_method())
9732 {
9733 // The receiver argument.
9734 args->push_back(*pa);
9735 ++pa;
9736 }
9737 for (; pa != this->args_->end(); ++pa, ++pp)
9738 {
9739 go_assert(pp != fntype->parameters()->end());
9740 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9741 args->push_back(*pa);
9742 else
9743 {
9744 Location loc = (*pa)->location();
8ba8cc87 9745 Expression* arg = *pa;
9746 if (!arg->is_variable())
9747 {
9748 Temporary_statement *temp =
9749 Statement::make_temporary(NULL, arg, loc);
9750 inserter->insert(temp);
9751 arg = Expression::make_temporary_reference(temp, loc);
9752 }
9753 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9754 loc);
9755 args->push_back(arg);
b8e86a51 9756 }
9757 }
9758 delete this->args_;
9759 this->args_ = args;
9760 }
9761
2c809f8f 9762 size_t rc = this->result_count();
9763 if (rc > 1 && this->call_temp_ == NULL)
9764 {
9765 Struct_field_list* sfl = new Struct_field_list();
9766 Function_type* fntype = this->get_function_type();
9767 const Typed_identifier_list* results = fntype->results();
9768 Location loc = this->location();
9769
9770 int i = 0;
61575e0f 9771 char buf[20];
2c809f8f 9772 for (Typed_identifier_list::const_iterator p = results->begin();
9773 p != results->end();
9774 ++p, ++i)
9775 {
9776 snprintf(buf, sizeof buf, "res%d", i);
9777 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9778 }
9779
9780 Struct_type* st = Type::make_struct_type(sfl, loc);
6bf4793c 9781 st->set_is_struct_incomparable();
2c809f8f 9782 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9783 inserter->insert(this->call_temp_);
9784 }
9785
9786 return this;
9787}
9788
ceeb4318 9789// Get the function type. This can return NULL in error cases.
e440a328 9790
9791Function_type*
9792Call_expression::get_function_type() const
9793{
9794 return this->fn_->type()->function_type();
9795}
9796
9797// Return the number of values which this call will return.
9798
9799size_t
9800Call_expression::result_count() const
9801{
9802 const Function_type* fntype = this->get_function_type();
9803 if (fntype == NULL)
9804 return 0;
9805 if (fntype->results() == NULL)
9806 return 0;
9807 return fntype->results()->size();
9808}
9809
ceeb4318 9810// Return the temporary which holds a result.
9811
9812Temporary_statement*
9813Call_expression::result(size_t i) const
9814{
cd238b8d 9815 if (this->results_ == NULL || this->results_->size() <= i)
9816 {
9817 go_assert(saw_errors());
9818 return NULL;
9819 }
ceeb4318 9820 return (*this->results_)[i];
9821}
9822
1373401e 9823// Set the number of results expected from a call expression.
9824
9825void
9826Call_expression::set_expected_result_count(size_t count)
9827{
9828 go_assert(this->expected_result_count_ == 0);
9829 this->expected_result_count_ = count;
9830}
9831
e440a328 9832// Return whether this is a call to the predeclared function recover.
9833
9834bool
9835Call_expression::is_recover_call() const
9836{
9837 return this->do_is_recover_call();
9838}
9839
9840// Set the argument to the recover function.
9841
9842void
9843Call_expression::set_recover_arg(Expression* arg)
9844{
9845 this->do_set_recover_arg(arg);
9846}
9847
9848// Virtual functions also implemented by Builtin_call_expression.
9849
9850bool
9851Call_expression::do_is_recover_call() const
9852{
9853 return false;
9854}
9855
9856void
9857Call_expression::do_set_recover_arg(Expression*)
9858{
c3e6f413 9859 go_unreachable();
e440a328 9860}
9861
ceeb4318 9862// We have found an error with this call expression; return true if
9863// we should report it.
9864
9865bool
9866Call_expression::issue_error()
9867{
9868 if (this->issued_error_)
9869 return false;
9870 else
9871 {
9872 this->issued_error_ = true;
9873 return true;
9874 }
9875}
9876
5bf8be8b 9877// Whether or not this call contains errors, either in the call or the
9878// arguments to the call.
9879
9880bool
9881Call_expression::is_erroneous_call()
9882{
9883 if (this->is_error_expression() || this->fn()->is_error_expression())
9884 return true;
9885
9886 if (this->args() == NULL)
9887 return false;
9888 for (Expression_list::iterator pa = this->args()->begin();
9889 pa != this->args()->end();
9890 ++pa)
9891 {
9892 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9893 return true;
9894 }
9895 return false;
9896}
9897
e440a328 9898// Get the type.
9899
9900Type*
9901Call_expression::do_type()
9902{
9903 if (this->type_ != NULL)
9904 return this->type_;
9905
9906 Type* ret;
9907 Function_type* fntype = this->get_function_type();
9908 if (fntype == NULL)
9909 return Type::make_error_type();
9910
9911 const Typed_identifier_list* results = fntype->results();
9912 if (results == NULL)
9913 ret = Type::make_void_type();
9914 else if (results->size() == 1)
9915 ret = results->begin()->type();
9916 else
9917 ret = Type::make_call_multiple_result_type(this);
9918
9919 this->type_ = ret;
9920
9921 return this->type_;
9922}
9923
9924// Determine types for a call expression. We can use the function
9925// parameter types to set the types of the arguments.
9926
9927void
9928Call_expression::do_determine_type(const Type_context*)
9929{
fb94b0ca 9930 if (!this->determining_types())
9931 return;
9932
e440a328 9933 this->fn_->determine_type_no_context();
9934 Function_type* fntype = this->get_function_type();
9935 const Typed_identifier_list* parameters = NULL;
9936 if (fntype != NULL)
9937 parameters = fntype->parameters();
9938 if (this->args_ != NULL)
9939 {
9940 Typed_identifier_list::const_iterator pt;
9941 if (parameters != NULL)
9942 pt = parameters->begin();
09ea332d 9943 bool first = true;
e440a328 9944 for (Expression_list::const_iterator pa = this->args_->begin();
9945 pa != this->args_->end();
9946 ++pa)
9947 {
09ea332d 9948 if (first)
9949 {
9950 first = false;
9951 // If this is a method, the first argument is the
9952 // receiver.
9953 if (fntype != NULL && fntype->is_method())
9954 {
9955 Type* rtype = fntype->receiver()->type();
9956 // The receiver is always passed as a pointer.
9957 if (rtype->points_to() == NULL)
9958 rtype = Type::make_pointer_type(rtype);
9959 Type_context subcontext(rtype, false);
9960 (*pa)->determine_type(&subcontext);
9961 continue;
9962 }
9963 }
9964
e440a328 9965 if (parameters != NULL && pt != parameters->end())
9966 {
9967 Type_context subcontext(pt->type(), false);
9968 (*pa)->determine_type(&subcontext);
9969 ++pt;
9970 }
9971 else
9972 (*pa)->determine_type_no_context();
9973 }
9974 }
9975}
9976
fb94b0ca 9977// Called when determining types for a Call_expression. Return true
9978// if we should go ahead, false if they have already been determined.
9979
9980bool
9981Call_expression::determining_types()
9982{
9983 if (this->types_are_determined_)
9984 return false;
9985 else
9986 {
9987 this->types_are_determined_ = true;
9988 return true;
9989 }
9990}
9991
e440a328 9992// Check types for parameter I.
9993
9994bool
9995Call_expression::check_argument_type(int i, const Type* parameter_type,
9996 const Type* argument_type,
b13c66cd 9997 Location argument_location,
e440a328 9998 bool issued_error)
9999{
10000 std::string reason;
1eae365b 10001 if (!Type::are_assignable(parameter_type, argument_type, &reason))
e440a328 10002 {
10003 if (!issued_error)
10004 {
10005 if (reason.empty())
631d5788 10006 go_error_at(argument_location, "argument %d has incompatible type", i);
e440a328 10007 else
631d5788 10008 go_error_at(argument_location,
10009 "argument %d has incompatible type (%s)",
10010 i, reason.c_str());
e440a328 10011 }
10012 this->set_is_error();
10013 return false;
10014 }
10015 return true;
10016}
10017
10018// Check types.
10019
10020void
10021Call_expression::do_check_types(Gogo*)
10022{
a6645f74 10023 if (this->classification() == EXPRESSION_ERROR)
10024 return;
10025
e440a328 10026 Function_type* fntype = this->get_function_type();
10027 if (fntype == NULL)
10028 {
5c13bd80 10029 if (!this->fn_->type()->is_error())
e440a328 10030 this->report_error(_("expected function"));
10031 return;
10032 }
10033
1373401e 10034 if (this->expected_result_count_ != 0
10035 && this->expected_result_count_ != this->result_count())
10036 {
10037 if (this->issue_error())
10038 this->report_error(_("function result count mismatch"));
10039 this->set_is_error();
10040 return;
10041 }
10042
09ea332d 10043 bool is_method = fntype->is_method();
10044 if (is_method)
e440a328 10045 {
09ea332d 10046 go_assert(this->args_ != NULL && !this->args_->empty());
10047 Type* rtype = fntype->receiver()->type();
10048 Expression* first_arg = this->args_->front();
1eae365b 10049 // We dereference the values since receivers are always passed
10050 // as pointers.
09ea332d 10051 std::string reason;
1eae365b 10052 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10053 &reason))
e440a328 10054 {
09ea332d 10055 if (reason.empty())
10056 this->report_error(_("incompatible type for receiver"));
10057 else
e440a328 10058 {
631d5788 10059 go_error_at(this->location(),
10060 "incompatible type for receiver (%s)",
10061 reason.c_str());
09ea332d 10062 this->set_is_error();
e440a328 10063 }
10064 }
10065 }
10066
10067 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 10068 // we don't have to worry about it here unless something is wrong.
10069 if (this->is_varargs_ && !this->varargs_are_lowered_)
10070 {
10071 if (!fntype->is_varargs())
10072 {
631d5788 10073 go_error_at(this->location(),
10074 _("invalid use of %<...%> calling non-variadic function"));
a6645f74 10075 this->set_is_error();
10076 return;
10077 }
10078 }
e440a328 10079
10080 const Typed_identifier_list* parameters = fntype->parameters();
10081 if (this->args_ == NULL)
10082 {
10083 if (parameters != NULL && !parameters->empty())
10084 this->report_error(_("not enough arguments"));
10085 }
10086 else if (parameters == NULL)
09ea332d 10087 {
10088 if (!is_method || this->args_->size() > 1)
10089 this->report_error(_("too many arguments"));
10090 }
1373401e 10091 else if (this->args_->size() == 1
10092 && this->args_->front()->call_expression() != NULL
10093 && this->args_->front()->call_expression()->result_count() > 1)
10094 {
10095 // This is F(G()) when G returns more than one result. If the
10096 // results can be matched to parameters, it would have been
10097 // lowered in do_lower. If we get here we know there is a
10098 // mismatch.
10099 if (this->args_->front()->call_expression()->result_count()
10100 < parameters->size())
10101 this->report_error(_("not enough arguments"));
10102 else
10103 this->report_error(_("too many arguments"));
10104 }
e440a328 10105 else
10106 {
10107 int i = 0;
09ea332d 10108 Expression_list::const_iterator pa = this->args_->begin();
10109 if (is_method)
10110 ++pa;
10111 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10112 pt != parameters->end();
10113 ++pt, ++pa, ++i)
e440a328 10114 {
09ea332d 10115 if (pa == this->args_->end())
e440a328 10116 {
09ea332d 10117 this->report_error(_("not enough arguments"));
e440a328 10118 return;
10119 }
10120 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10121 (*pa)->location(), false);
10122 }
09ea332d 10123 if (pa != this->args_->end())
10124 this->report_error(_("too many arguments"));
e440a328 10125 }
10126}
10127
72666aed 10128Expression*
10129Call_expression::do_copy()
10130{
10131 Call_expression* call =
10132 Expression::make_call(this->fn_->copy(),
10133 (this->args_ == NULL
10134 ? NULL
10135 : this->args_->copy()),
10136 this->is_varargs_, this->location());
10137
10138 if (this->varargs_are_lowered_)
10139 call->set_varargs_are_lowered();
10140 return call;
10141}
10142
e440a328 10143// Return whether we have to use a temporary variable to ensure that
10144// we evaluate this call expression in order. If the call returns no
ceeb4318 10145// results then it will inevitably be executed last.
e440a328 10146
10147bool
10148Call_expression::do_must_eval_in_order() const
10149{
ceeb4318 10150 return this->result_count() > 0;
e440a328 10151}
10152
e440a328 10153// Get the function and the first argument to use when calling an
10154// interface method.
10155
2387f644 10156Expression*
e440a328 10157Call_expression::interface_method_function(
e440a328 10158 Interface_field_reference_expression* interface_method,
db122cb9 10159 Expression** first_arg_ptr,
10160 Location location)
e440a328 10161{
db122cb9 10162 Expression* object = interface_method->get_underlying_object();
10163 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10164 *first_arg_ptr =
10165 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
2387f644 10166 return interface_method->get_function();
e440a328 10167}
10168
10169// Build the call expression.
10170
ea664253 10171Bexpression*
10172Call_expression::do_get_backend(Translate_context* context)
e440a328 10173{
2c809f8f 10174 if (this->call_ != NULL)
ea664253 10175 return this->call_;
e440a328 10176
10177 Function_type* fntype = this->get_function_type();
10178 if (fntype == NULL)
ea664253 10179 return context->backend()->error_expression();
e440a328 10180
10181 if (this->fn_->is_error_expression())
ea664253 10182 return context->backend()->error_expression();
e440a328 10183
10184 Gogo* gogo = context->gogo();
b13c66cd 10185 Location location = this->location();
e440a328 10186
10187 Func_expression* func = this->fn_->func_expression();
e440a328 10188 Interface_field_reference_expression* interface_method =
10189 this->fn_->interface_field_reference_expression();
10190 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 10191 const bool is_interface_method = interface_method != NULL;
e440a328 10192
f8bdf81a 10193 bool has_closure_arg;
8381eda7 10194 if (has_closure)
f8bdf81a 10195 has_closure_arg = true;
8381eda7 10196 else if (func != NULL)
f8bdf81a 10197 has_closure_arg = false;
8381eda7 10198 else if (is_interface_method)
f8bdf81a 10199 has_closure_arg = false;
8381eda7 10200 else
f8bdf81a 10201 has_closure_arg = true;
8381eda7 10202
e440a328 10203 int nargs;
2c809f8f 10204 std::vector<Bexpression*> fn_args;
e440a328 10205 if (this->args_ == NULL || this->args_->empty())
10206 {
f8bdf81a 10207 nargs = is_interface_method ? 1 : 0;
2c809f8f 10208 if (nargs > 0)
10209 fn_args.resize(1);
e440a328 10210 }
09ea332d 10211 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10212 {
10213 // Passing a receiver parameter.
10214 go_assert(!is_interface_method
10215 && fntype->is_method()
10216 && this->args_->size() == 1);
f8bdf81a 10217 nargs = 1;
2c809f8f 10218 fn_args.resize(1);
ea664253 10219 fn_args[0] = this->args_->front()->get_backend(context);
09ea332d 10220 }
e440a328 10221 else
10222 {
10223 const Typed_identifier_list* params = fntype->parameters();
e440a328 10224
10225 nargs = this->args_->size();
09ea332d 10226 int i = is_interface_method ? 1 : 0;
e440a328 10227 nargs += i;
2c809f8f 10228 fn_args.resize(nargs);
e440a328 10229
10230 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 10231 Expression_list::const_iterator pe = this->args_->begin();
10232 if (!is_interface_method && fntype->is_method())
10233 {
ea664253 10234 fn_args[i] = (*pe)->get_backend(context);
09ea332d 10235 ++pe;
10236 ++i;
10237 }
10238 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 10239 {
c484d925 10240 go_assert(pp != params->end());
2c809f8f 10241 Expression* arg =
10242 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10243 location);
ea664253 10244 fn_args[i] = arg->get_backend(context);
e440a328 10245 }
c484d925 10246 go_assert(pp == params->end());
f8bdf81a 10247 go_assert(i == nargs);
e440a328 10248 }
10249
2c809f8f 10250 Expression* fn;
10251 Expression* closure = NULL;
8381eda7 10252 if (func != NULL)
10253 {
10254 Named_object* no = func->named_object();
2c809f8f 10255 fn = Expression::make_func_code_reference(no, location);
10256 if (has_closure)
10257 closure = func->closure();
8381eda7 10258 }
09ea332d 10259 else if (!is_interface_method)
8381eda7 10260 {
2c809f8f 10261 closure = this->fn_;
10262
10263 // The backend representation of this function type is a pointer
10264 // to a struct whose first field is the actual function to call.
10265 Type* pfntype =
10266 Type::make_pointer_type(
10267 Type::make_pointer_type(Type::make_void_type()));
10268 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10269 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
10270 }
e440a328 10271 else
cf609de4 10272 {
2387f644 10273 Expression* first_arg;
db122cb9 10274 fn = this->interface_method_function(interface_method, &first_arg,
10275 location);
ea664253 10276 fn_args[0] = first_arg->get_backend(context);
e440a328 10277 }
10278
1ecc6157 10279 Bexpression* bclosure = NULL;
10280 if (has_closure_arg)
10281 bclosure = closure->get_backend(context);
f8bdf81a 10282 else
1ecc6157 10283 go_assert(closure == NULL);
f8bdf81a 10284
ea664253 10285 Bexpression* bfn = fn->get_backend(context);
80d1e1a8 10286
10287 // When not calling a named function directly, use a type conversion
10288 // in case the type of the function is a recursive type which refers
10289 // to itself. We don't do this for an interface method because 1)
10290 // an interface method never refers to itself, so we always have a
10291 // function type here; 2) we pass an extra first argument to an
10292 // interface method, so fntype is not correct.
10293 if (func == NULL && !is_interface_method)
10294 {
10295 Btype* bft = fntype->get_backend_fntype(gogo);
10296 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10297 }
10298
4ced7af9 10299 Bfunction* bfunction = NULL;
10300 if (context->function())
10301 bfunction = context->function()->func_value()->get_decl();
10302 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10303 fn_args, bclosure,
10304 location);
e440a328 10305
2c809f8f 10306 if (this->results_ != NULL)
e440a328 10307 {
03118c21 10308 Bexpression* bcall_ref = this->call_result_ref(context);
2c809f8f 10309 Bstatement* assn_stmt =
0ab48656 10310 gogo->backend()->assignment_statement(bfunction,
10311 bcall_ref, call, location);
e440a328 10312
03118c21 10313 this->call_ = this->set_results(context);
e440a328 10314
2c809f8f 10315 Bexpression* set_and_call =
10316 gogo->backend()->compound_expression(assn_stmt, this->call_,
10317 location);
ea664253 10318 return set_and_call;
2c809f8f 10319 }
e440a328 10320
2c809f8f 10321 this->call_ = call;
ea664253 10322 return this->call_;
e440a328 10323}
10324
03118c21 10325// Return the backend representation of a reference to the struct used
10326// to capture the result of a multiple-output call.
10327
10328Bexpression*
10329Call_expression::call_result_ref(Translate_context* context)
10330{
10331 go_assert(this->call_temp_ != NULL);
10332 Location location = this->location();
10333 Expression* call_ref =
10334 Expression::make_temporary_reference(this->call_temp_, location);
10335 Bexpression* bcall_ref = call_ref->get_backend(context);
10336 return bcall_ref;
10337}
10338
ceeb4318 10339// Set the result variables if this call returns multiple results.
10340
2c809f8f 10341Bexpression*
03118c21 10342Call_expression::set_results(Translate_context* context)
ceeb4318 10343{
2c809f8f 10344 Gogo* gogo = context->gogo();
ceeb4318 10345
2c809f8f 10346 Bexpression* results = NULL;
b13c66cd 10347 Location loc = this->location();
2c809f8f 10348
03118c21 10349 go_assert(this->call_temp_ != NULL);
10350
ceeb4318 10351 size_t rc = this->result_count();
2c809f8f 10352 for (size_t i = 0; i < rc; ++i)
ceeb4318 10353 {
ceeb4318 10354 Temporary_statement* temp = this->result(i);
cd238b8d 10355 if (temp == NULL)
10356 {
10357 go_assert(saw_errors());
2c809f8f 10358 return gogo->backend()->error_expression();
cd238b8d 10359 }
ceeb4318 10360 Temporary_reference_expression* ref =
10361 Expression::make_temporary_reference(temp, loc);
10362 ref->set_is_lvalue();
ceeb4318 10363
0ab48656 10364 Bfunction* bfunction = context->function()->func_value()->get_decl();
ea664253 10365 Bexpression* result_ref = ref->get_backend(context);
03118c21 10366 Bexpression* bcall_ref = this->call_result_ref(context);
2c809f8f 10367 Bexpression* call_result =
03118c21 10368 gogo->backend()->struct_field_expression(bcall_ref, i, loc);
2c809f8f 10369 Bstatement* assn_stmt =
0ab48656 10370 gogo->backend()->assignment_statement(bfunction,
10371 result_ref, call_result, loc);
ceeb4318 10372
03118c21 10373 bcall_ref = this->call_result_ref(context);
10374 call_result = gogo->backend()->struct_field_expression(bcall_ref, i, loc);
2c809f8f 10375 Bexpression* result =
10376 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 10377
2c809f8f 10378 if (results == NULL)
10379 results = result;
10380 else
10381 {
0ab48656 10382 Bstatement* expr_stmt =
10383 gogo->backend()->expression_statement(bfunction, result);
2c809f8f 10384 results =
10385 gogo->backend()->compound_expression(expr_stmt, results, loc);
10386 }
10387 }
10388 return results;
ceeb4318 10389}
10390
d751bb78 10391// Dump ast representation for a call expressin.
10392
10393void
10394Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10395{
10396 this->fn_->dump_expression(ast_dump_context);
10397 ast_dump_context->ostream() << "(";
10398 if (args_ != NULL)
10399 ast_dump_context->dump_expression_list(this->args_);
10400
10401 ast_dump_context->ostream() << ") ";
10402}
10403
e440a328 10404// Make a call expression.
10405
10406Call_expression*
10407Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 10408 Location location)
e440a328 10409{
10410 return new Call_expression(fn, args, is_varargs, location);
10411}
10412
da244e59 10413// Class Call_result_expression.
e440a328 10414
10415// Traverse a call result.
10416
10417int
10418Call_result_expression::do_traverse(Traverse* traverse)
10419{
10420 if (traverse->remember_expression(this->call_))
10421 {
10422 // We have already traversed the call expression.
10423 return TRAVERSE_CONTINUE;
10424 }
10425 return Expression::traverse(&this->call_, traverse);
10426}
10427
10428// Get the type.
10429
10430Type*
10431Call_result_expression::do_type()
10432{
425dd051 10433 if (this->classification() == EXPRESSION_ERROR)
10434 return Type::make_error_type();
10435
e440a328 10436 // THIS->CALL_ can be replaced with a temporary reference due to
10437 // Call_expression::do_must_eval_in_order when there is an error.
10438 Call_expression* ce = this->call_->call_expression();
10439 if (ce == NULL)
5e85f268 10440 {
10441 this->set_is_error();
10442 return Type::make_error_type();
10443 }
e440a328 10444 Function_type* fntype = ce->get_function_type();
10445 if (fntype == NULL)
5e85f268 10446 {
e37658e2 10447 if (ce->issue_error())
99b3f06f 10448 {
10449 if (!ce->fn()->type()->is_error())
10450 this->report_error(_("expected function"));
10451 }
5e85f268 10452 this->set_is_error();
10453 return Type::make_error_type();
10454 }
e440a328 10455 const Typed_identifier_list* results = fntype->results();
ceeb4318 10456 if (results == NULL || results->size() < 2)
7b8d861f 10457 {
ceeb4318 10458 if (ce->issue_error())
10459 this->report_error(_("number of results does not match "
10460 "number of values"));
7b8d861f 10461 return Type::make_error_type();
10462 }
e440a328 10463 Typed_identifier_list::const_iterator pr = results->begin();
10464 for (unsigned int i = 0; i < this->index_; ++i)
10465 {
10466 if (pr == results->end())
425dd051 10467 break;
e440a328 10468 ++pr;
10469 }
10470 if (pr == results->end())
425dd051 10471 {
ceeb4318 10472 if (ce->issue_error())
10473 this->report_error(_("number of results does not match "
10474 "number of values"));
425dd051 10475 return Type::make_error_type();
10476 }
e440a328 10477 return pr->type();
10478}
10479
425dd051 10480// Check the type. Just make sure that we trigger the warning in
10481// do_type.
e440a328 10482
10483void
10484Call_result_expression::do_check_types(Gogo*)
10485{
425dd051 10486 this->type();
e440a328 10487}
10488
10489// Determine the type. We have nothing to do here, but the 0 result
10490// needs to pass down to the caller.
10491
10492void
10493Call_result_expression::do_determine_type(const Type_context*)
10494{
fb94b0ca 10495 this->call_->determine_type_no_context();
e440a328 10496}
10497
ea664253 10498// Return the backend representation. We just refer to the temporary set by the
10499// call expression. We don't do this at lowering time because it makes it
ceeb4318 10500// hard to evaluate the call at the right time.
e440a328 10501
ea664253 10502Bexpression*
10503Call_result_expression::do_get_backend(Translate_context* context)
e440a328 10504{
ceeb4318 10505 Call_expression* ce = this->call_->call_expression();
cd238b8d 10506 if (ce == NULL)
10507 {
10508 go_assert(this->call_->is_error_expression());
ea664253 10509 return context->backend()->error_expression();
cd238b8d 10510 }
ceeb4318 10511 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 10512 if (ts == NULL)
10513 {
10514 go_assert(saw_errors());
ea664253 10515 return context->backend()->error_expression();
cd238b8d 10516 }
ceeb4318 10517 Expression* ref = Expression::make_temporary_reference(ts, this->location());
ea664253 10518 return ref->get_backend(context);
e440a328 10519}
10520
d751bb78 10521// Dump ast representation for a call result expression.
10522
10523void
10524Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10525 const
10526{
10527 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10528 // (struct) and the fields are referenced instead.
10529 ast_dump_context->ostream() << this->index_ << "@(";
10530 ast_dump_context->dump_expression(this->call_);
10531 ast_dump_context->ostream() << ")";
10532}
10533
e440a328 10534// Make a reference to a single result of a call which returns
10535// multiple results.
10536
10537Expression*
10538Expression::make_call_result(Call_expression* call, unsigned int index)
10539{
10540 return new Call_result_expression(call, index);
10541}
10542
10543// Class Index_expression.
10544
10545// Traversal.
10546
10547int
10548Index_expression::do_traverse(Traverse* traverse)
10549{
10550 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10551 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10552 || (this->end_ != NULL
acf2b673 10553 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10554 || (this->cap_ != NULL
10555 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 10556 return TRAVERSE_EXIT;
10557 return TRAVERSE_CONTINUE;
10558}
10559
10560// Lower an index expression. This converts the generic index
10561// expression into an array index, a string index, or a map index.
10562
10563Expression*
ceeb4318 10564Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 10565{
b13c66cd 10566 Location location = this->location();
e440a328 10567 Expression* left = this->left_;
10568 Expression* start = this->start_;
10569 Expression* end = this->end_;
acf2b673 10570 Expression* cap = this->cap_;
e440a328 10571
10572 Type* type = left->type();
5c13bd80 10573 if (type->is_error())
d9f3743a 10574 {
10575 go_assert(saw_errors());
10576 return Expression::make_error(location);
10577 }
b0cf7ddd 10578 else if (left->is_type_expression())
10579 {
631d5788 10580 go_error_at(location, "attempt to index type expression");
b0cf7ddd 10581 return Expression::make_error(location);
10582 }
e440a328 10583 else if (type->array_type() != NULL)
acf2b673 10584 return Expression::make_array_index(left, start, end, cap, location);
e440a328 10585 else if (type->points_to() != NULL
10586 && type->points_to()->array_type() != NULL
411eb89e 10587 && !type->points_to()->is_slice_type())
e440a328 10588 {
10589 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10590 location);
38092374 10591
10592 // For an ordinary index into the array, the pointer will be
10593 // dereferenced. For a slice it will not--the resulting slice
10594 // will simply reuse the pointer, which is incorrect if that
10595 // pointer is nil.
10596 if (end != NULL || cap != NULL)
10597 deref->issue_nil_check();
10598
acf2b673 10599 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 10600 }
10601 else if (type->is_string_type())
acf2b673 10602 {
10603 if (cap != NULL)
10604 {
631d5788 10605 go_error_at(location, "invalid 3-index slice of string");
acf2b673 10606 return Expression::make_error(location);
10607 }
10608 return Expression::make_string_index(left, start, end, location);
10609 }
e440a328 10610 else if (type->map_type() != NULL)
10611 {
acf2b673 10612 if (end != NULL || cap != NULL)
e440a328 10613 {
631d5788 10614 go_error_at(location, "invalid slice of map");
e440a328 10615 return Expression::make_error(location);
10616 }
0d5530d9 10617 return Expression::make_map_index(left, start, location);
e440a328 10618 }
b1aba207 10619 else if (cap != NULL)
10620 {
10621 go_error_at(location,
10622 "invalid 3-index slice of object that is not a slice");
10623 return Expression::make_error(location);
10624 }
10625 else if (end != NULL)
10626 {
10627 go_error_at(location,
10628 ("attempt to slice object that is not "
10629 "array, slice, or string"));
10630 return Expression::make_error(location);
10631 }
e440a328 10632 else
10633 {
631d5788 10634 go_error_at(location,
b1aba207 10635 ("attempt to index object that is not "
10636 "array, slice, string, or map"));
e440a328 10637 return Expression::make_error(location);
10638 }
10639}
10640
acf2b673 10641// Write an indexed expression
10642// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 10643
10644void
10645Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10646 const Expression* expr,
10647 const Expression* start,
acf2b673 10648 const Expression* end,
10649 const Expression* cap)
d751bb78 10650{
10651 expr->dump_expression(ast_dump_context);
10652 ast_dump_context->ostream() << "[";
10653 start->dump_expression(ast_dump_context);
10654 if (end != NULL)
10655 {
10656 ast_dump_context->ostream() << ":";
10657 end->dump_expression(ast_dump_context);
10658 }
acf2b673 10659 if (cap != NULL)
10660 {
10661 ast_dump_context->ostream() << ":";
10662 cap->dump_expression(ast_dump_context);
10663 }
d751bb78 10664 ast_dump_context->ostream() << "]";
10665}
10666
10667// Dump ast representation for an index expression.
10668
10669void
10670Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10671 const
10672{
10673 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 10674 this->start_, this->end_, this->cap_);
d751bb78 10675}
10676
e440a328 10677// Make an index expression.
10678
10679Expression*
10680Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 10681 Expression* cap, Location location)
e440a328 10682{
acf2b673 10683 return new Index_expression(left, start, end, cap, location);
e440a328 10684}
10685
da244e59 10686// Class Array_index_expression.
e440a328 10687
10688// Array index traversal.
10689
10690int
10691Array_index_expression::do_traverse(Traverse* traverse)
10692{
10693 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10694 return TRAVERSE_EXIT;
10695 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10696 return TRAVERSE_EXIT;
10697 if (this->end_ != NULL)
10698 {
10699 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10700 return TRAVERSE_EXIT;
10701 }
acf2b673 10702 if (this->cap_ != NULL)
10703 {
10704 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10705 return TRAVERSE_EXIT;
10706 }
e440a328 10707 return TRAVERSE_CONTINUE;
10708}
10709
10710// Return the type of an array index.
10711
10712Type*
10713Array_index_expression::do_type()
10714{
10715 if (this->type_ == NULL)
10716 {
10717 Array_type* type = this->array_->type()->array_type();
10718 if (type == NULL)
10719 this->type_ = Type::make_error_type();
10720 else if (this->end_ == NULL)
10721 this->type_ = type->element_type();
411eb89e 10722 else if (type->is_slice_type())
e440a328 10723 {
10724 // A slice of a slice has the same type as the original
10725 // slice.
10726 this->type_ = this->array_->type()->deref();
10727 }
10728 else
10729 {
10730 // A slice of an array is a slice.
10731 this->type_ = Type::make_array_type(type->element_type(), NULL);
10732 }
10733 }
10734 return this->type_;
10735}
10736
10737// Set the type of an array index.
10738
10739void
10740Array_index_expression::do_determine_type(const Type_context*)
10741{
10742 this->array_->determine_type_no_context();
f77aa642 10743
10744 Type_context index_context(Type::lookup_integer_type("int"), false);
10745 if (this->start_->is_constant())
10746 this->start_->determine_type(&index_context);
10747 else
10748 this->start_->determine_type_no_context();
e440a328 10749 if (this->end_ != NULL)
f77aa642 10750 {
10751 if (this->end_->is_constant())
10752 this->end_->determine_type(&index_context);
10753 else
10754 this->end_->determine_type_no_context();
10755 }
acf2b673 10756 if (this->cap_ != NULL)
f77aa642 10757 {
10758 if (this->cap_->is_constant())
10759 this->cap_->determine_type(&index_context);
10760 else
10761 this->cap_->determine_type_no_context();
10762 }
e440a328 10763}
10764
10765// Check types of an array index.
10766
10767void
d0a50ed8 10768Array_index_expression::do_check_types(Gogo* gogo)
e440a328 10769{
f6bc81e6 10770 Numeric_constant nc;
10771 unsigned long v;
10772 if (this->start_->type()->integer_type() == NULL
10773 && !this->start_->type()->is_error()
10774 && (!this->start_->numeric_constant_value(&nc)
10775 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10776 this->report_error(_("index must be integer"));
10777 if (this->end_ != NULL
10778 && this->end_->type()->integer_type() == NULL
99b3f06f 10779 && !this->end_->type()->is_error()
10780 && !this->end_->is_nil_expression()
f6bc81e6 10781 && !this->end_->is_error_expression()
10782 && (!this->end_->numeric_constant_value(&nc)
10783 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10784 this->report_error(_("slice end must be integer"));
acf2b673 10785 if (this->cap_ != NULL
10786 && this->cap_->type()->integer_type() == NULL
10787 && !this->cap_->type()->is_error()
10788 && !this->cap_->is_nil_expression()
10789 && !this->cap_->is_error_expression()
10790 && (!this->cap_->numeric_constant_value(&nc)
10791 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10792 this->report_error(_("slice capacity must be integer"));
e440a328 10793
10794 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10795 if (array_type == NULL)
10796 {
c484d925 10797 go_assert(this->array_->type()->is_error());
f9c68f17 10798 return;
10799 }
e440a328 10800
10801 unsigned int int_bits =
10802 Type::lookup_integer_type("int")->integer_type()->bits();
10803
0c77715b 10804 Numeric_constant lvalnc;
e440a328 10805 mpz_t lval;
e440a328 10806 bool lval_valid = (array_type->length() != NULL
0c77715b 10807 && array_type->length()->numeric_constant_value(&lvalnc)
10808 && lvalnc.to_int(&lval));
10809 Numeric_constant inc;
e440a328 10810 mpz_t ival;
0bd5d859 10811 bool ival_valid = false;
0c77715b 10812 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10813 {
0bd5d859 10814 ival_valid = true;
e440a328 10815 if (mpz_sgn(ival) < 0
10816 || mpz_sizeinbase(ival, 2) >= int_bits
10817 || (lval_valid
10818 && (this->end_ == NULL
10819 ? mpz_cmp(ival, lval) >= 0
10820 : mpz_cmp(ival, lval) > 0)))
10821 {
631d5788 10822 go_error_at(this->start_->location(), "array index out of bounds");
e440a328 10823 this->set_is_error();
10824 }
10825 }
10826 if (this->end_ != NULL && !this->end_->is_nil_expression())
10827 {
0c77715b 10828 Numeric_constant enc;
10829 mpz_t eval;
acf2b673 10830 bool eval_valid = false;
0c77715b 10831 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10832 {
acf2b673 10833 eval_valid = true;
0c77715b 10834 if (mpz_sgn(eval) < 0
10835 || mpz_sizeinbase(eval, 2) >= int_bits
10836 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10837 {
631d5788 10838 go_error_at(this->end_->location(), "array index out of bounds");
e440a328 10839 this->set_is_error();
10840 }
0bd5d859 10841 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10842 this->report_error(_("inverted slice range"));
e440a328 10843 }
acf2b673 10844
10845 Numeric_constant cnc;
10846 mpz_t cval;
10847 if (this->cap_ != NULL
10848 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10849 {
10850 if (mpz_sgn(cval) < 0
10851 || mpz_sizeinbase(cval, 2) >= int_bits
10852 || (lval_valid && mpz_cmp(cval, lval) > 0))
10853 {
631d5788 10854 go_error_at(this->cap_->location(), "array index out of bounds");
acf2b673 10855 this->set_is_error();
10856 }
10857 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10858 {
631d5788 10859 go_error_at(this->cap_->location(),
10860 "invalid slice index: capacity less than start");
acf2b673 10861 this->set_is_error();
10862 }
10863 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10864 {
631d5788 10865 go_error_at(this->cap_->location(),
10866 "invalid slice index: capacity less than length");
acf2b673 10867 this->set_is_error();
10868 }
10869 mpz_clear(cval);
10870 }
10871
10872 if (eval_valid)
10873 mpz_clear(eval);
e440a328 10874 }
0bd5d859 10875 if (ival_valid)
10876 mpz_clear(ival);
0c77715b 10877 if (lval_valid)
10878 mpz_clear(lval);
e440a328 10879
10880 // A slice of an array requires an addressable array. A slice of a
10881 // slice is always possible.
411eb89e 10882 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10883 {
10884 if (!this->array_->is_addressable())
8da39c3b 10885 this->report_error(_("slice of unaddressable value"));
88ec30c8 10886 else
d0a50ed8 10887 {
10888 bool escapes = true;
10889
10890 // When compiling the runtime, a slice operation does not
10891 // cause local variables to escape. When escape analysis
10892 // becomes the default, this should be changed to make it an
10893 // error if we have a slice operation that escapes.
10894 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
10895 escapes = false;
10896
10897 this->array_->address_taken(escapes);
10898 }
88ec30c8 10899 }
e440a328 10900}
10901
2c809f8f 10902// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10903
10904Expression*
10905Array_index_expression::do_flatten(Gogo*, Named_object*,
10906 Statement_inserter* inserter)
10907{
10908 Location loc = this->location();
5bf8be8b 10909 Expression* array = this->array_;
10910 Expression* start = this->start_;
10911 Expression* end = this->end_;
10912 Expression* cap = this->cap_;
10913 if (array->is_error_expression()
10914 || array->type()->is_error_type()
10915 || start->is_error_expression()
10916 || start->type()->is_error_type()
10917 || (end != NULL
10918 && (end->is_error_expression() || end->type()->is_error_type()))
10919 || (cap != NULL
10920 && (cap->is_error_expression() || cap->type()->is_error_type())))
10921 {
10922 go_assert(saw_errors());
10923 return Expression::make_error(loc);
10924 }
10925
2c809f8f 10926 Temporary_statement* temp;
5bf8be8b 10927 if (array->type()->is_slice_type() && !array->is_variable())
35a54f17 10928 {
5bf8be8b 10929 temp = Statement::make_temporary(NULL, array, loc);
35a54f17 10930 inserter->insert(temp);
10931 this->array_ = Expression::make_temporary_reference(temp, loc);
10932 }
5bf8be8b 10933 if (!start->is_variable())
2c809f8f 10934 {
5bf8be8b 10935 temp = Statement::make_temporary(NULL, start, loc);
2c809f8f 10936 inserter->insert(temp);
10937 this->start_ = Expression::make_temporary_reference(temp, loc);
10938 }
5bf8be8b 10939 if (end != NULL
10940 && !end->is_nil_expression()
10941 && !end->is_variable())
2c809f8f 10942 {
5bf8be8b 10943 temp = Statement::make_temporary(NULL, end, loc);
2c809f8f 10944 inserter->insert(temp);
10945 this->end_ = Expression::make_temporary_reference(temp, loc);
10946 }
03118c21 10947 if (cap != NULL && !cap->is_variable())
2c809f8f 10948 {
5bf8be8b 10949 temp = Statement::make_temporary(NULL, cap, loc);
2c809f8f 10950 inserter->insert(temp);
10951 this->cap_ = Expression::make_temporary_reference(temp, loc);
10952 }
10953
35a54f17 10954 return this;
10955}
10956
e440a328 10957// Return whether this expression is addressable.
10958
10959bool
10960Array_index_expression::do_is_addressable() const
10961{
10962 // A slice expression is not addressable.
10963 if (this->end_ != NULL)
10964 return false;
10965
10966 // An index into a slice is addressable.
411eb89e 10967 if (this->array_->type()->is_slice_type())
e440a328 10968 return true;
10969
10970 // An index into an array is addressable if the array is
10971 // addressable.
10972 return this->array_->is_addressable();
10973}
10974
ea664253 10975// Get the backend representation for an array index.
e440a328 10976
ea664253 10977Bexpression*
10978Array_index_expression::do_get_backend(Translate_context* context)
e440a328 10979{
e440a328 10980 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10981 if (array_type == NULL)
10982 {
c484d925 10983 go_assert(this->array_->type()->is_error());
ea664253 10984 return context->backend()->error_expression();
d8cd8e2d 10985 }
35a54f17 10986 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10987
2c809f8f 10988 Location loc = this->location();
10989 Gogo* gogo = context->gogo();
10990
6dfedc16 10991 Type* int_type = Type::lookup_integer_type("int");
10992 Btype* int_btype = int_type->get_backend(gogo);
e440a328 10993
2c809f8f 10994 // We need to convert the length and capacity to the Go "int" type here
10995 // because the length of a fixed-length array could be of type "uintptr"
10996 // and gimple disallows binary operations between "uintptr" and other
10997 // integer types. FIXME.
10998 Bexpression* length = NULL;
a04bfdfc 10999 if (this->end_ == NULL || this->end_->is_nil_expression())
11000 {
35a54f17 11001 Expression* len = array_type->get_length(gogo, this->array_);
ea664253 11002 length = len->get_backend(context);
2c809f8f 11003 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 11004 }
11005
2c809f8f 11006 Bexpression* capacity = NULL;
a04bfdfc 11007 if (this->end_ != NULL)
11008 {
35a54f17 11009 Expression* cap = array_type->get_capacity(gogo, this->array_);
ea664253 11010 capacity = cap->get_backend(context);
2c809f8f 11011 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 11012 }
11013
2c809f8f 11014 Bexpression* cap_arg = capacity;
acf2b673 11015 if (this->cap_ != NULL)
11016 {
ea664253 11017 cap_arg = this->cap_->get_backend(context);
2c809f8f 11018 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 11019 }
11020
2c809f8f 11021 if (length == NULL)
11022 length = cap_arg;
e440a328 11023
11024 int code = (array_type->length() != NULL
11025 ? (this->end_ == NULL
11026 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
11027 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
11028 : (this->end_ == NULL
11029 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
11030 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
ea664253 11031 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
2c809f8f 11032
6dfedc16 11033 if (this->start_->type()->integer_type() == NULL
11034 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11035 {
11036 go_assert(saw_errors());
11037 return context->backend()->error_expression();
11038 }
d9f3743a 11039
ea664253 11040 Bexpression* bad_index =
d9f3743a 11041 Expression::check_bounds(this->start_, loc)->get_backend(context);
2c809f8f 11042
ea664253 11043 Bexpression* start = this->start_->get_backend(context);
2c809f8f 11044 start = gogo->backend()->convert_expression(int_btype, start, loc);
11045 Bexpression* start_too_large =
11046 gogo->backend()->binary_expression((this->end_ == NULL
11047 ? OPERATOR_GE
11048 : OPERATOR_GT),
11049 start,
11050 (this->end_ == NULL
11051 ? length
11052 : capacity),
11053 loc);
11054 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
11055 bad_index, loc);
e440a328 11056
93715b75 11057 Bfunction* bfn = context->function()->func_value()->get_decl();
e440a328 11058 if (this->end_ == NULL)
11059 {
11060 // Simple array indexing. This has to return an l-value, so
2c809f8f 11061 // wrap the index check into START.
11062 start =
93715b75 11063 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
2c809f8f 11064 crash, start, loc);
e440a328 11065
2c809f8f 11066 Bexpression* ret;
e440a328 11067 if (array_type->length() != NULL)
11068 {
ea664253 11069 Bexpression* array = this->array_->get_backend(context);
2c809f8f 11070 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 11071 }
11072 else
11073 {
2c809f8f 11074 // Slice.
11075 Expression* valptr =
44dbe1d7 11076 array_type->get_value_pointer(gogo, this->array_,
11077 this->is_lvalue_);
ea664253 11078 Bexpression* ptr = valptr->get_backend(context);
2c809f8f 11079 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 11080
11081 Type* ele_type = this->array_->type()->array_type()->element_type();
11082 Btype* ele_btype = ele_type->get_backend(gogo);
11083 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 11084 }
ea664253 11085 return ret;
e440a328 11086 }
11087
11088 // Array slice.
11089
acf2b673 11090 if (this->cap_ != NULL)
11091 {
2c809f8f 11092 Bexpression* bounds_bcheck =
ea664253 11093 Expression::check_bounds(this->cap_, loc)->get_backend(context);
2c809f8f 11094 bad_index =
11095 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11096 bad_index, loc);
11097 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11098
11099 Bexpression* cap_too_small =
11100 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11101 Bexpression* cap_too_large =
11102 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11103 Bexpression* bad_cap =
11104 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11105 cap_too_large, loc);
11106 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11107 bad_index, loc);
11108 }
11109
11110 Bexpression* end;
e440a328 11111 if (this->end_->is_nil_expression())
2c809f8f 11112 end = length;
e440a328 11113 else
11114 {
2c809f8f 11115 Bexpression* bounds_bcheck =
ea664253 11116 Expression::check_bounds(this->end_, loc)->get_backend(context);
e440a328 11117
2c809f8f 11118 bad_index =
11119 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11120 bad_index, loc);
e440a328 11121
ea664253 11122 end = this->end_->get_backend(context);
2c809f8f 11123 end = gogo->backend()->convert_expression(int_btype, end, loc);
11124 Bexpression* end_too_small =
11125 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11126 Bexpression* end_too_large =
11127 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11128 Bexpression* bad_end =
11129 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11130 end_too_large, loc);
11131 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11132 bad_index, loc);
e440a328 11133 }
11134
2c809f8f 11135 Bexpression* result_length =
11136 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 11137
2c809f8f 11138 Bexpression* result_capacity =
11139 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 11140
03118c21 11141 // If the new capacity is zero, don't change val. Otherwise we can
11142 // get a pointer to the next object in memory, keeping it live
11143 // unnecessarily. When the capacity is zero, the actual pointer
11144 // value doesn't matter.
11145 Bexpression* zero =
11146 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11147 Bexpression* cond =
11148 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11149 loc);
11150 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11151 cond, zero,
11152 start, loc);
44dbe1d7 11153 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11154 this->is_lvalue_);
03118c21 11155 Bexpression* val = valptr->get_backend(context);
11156 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11157
2c809f8f 11158 Btype* struct_btype = this->type()->get_backend(gogo);
11159 std::vector<Bexpression*> init;
11160 init.push_back(val);
11161 init.push_back(result_length);
11162 init.push_back(result_capacity);
e440a328 11163
2c809f8f 11164 Bexpression* ctor =
11165 gogo->backend()->constructor_expression(struct_btype, init, loc);
93715b75 11166 return gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
ea664253 11167 crash, ctor, loc);
e440a328 11168}
11169
d751bb78 11170// Dump ast representation for an array index expression.
11171
11172void
11173Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11174 const
11175{
11176 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 11177 this->start_, this->end_, this->cap_);
d751bb78 11178}
11179
acf2b673 11180// Make an array index expression. END and CAP may be NULL.
e440a328 11181
11182Expression*
11183Expression::make_array_index(Expression* array, Expression* start,
acf2b673 11184 Expression* end, Expression* cap,
11185 Location location)
e440a328 11186{
acf2b673 11187 return new Array_index_expression(array, start, end, cap, location);
e440a328 11188}
11189
50075d74 11190// Class String_index_expression.
e440a328 11191
11192// String index traversal.
11193
11194int
11195String_index_expression::do_traverse(Traverse* traverse)
11196{
11197 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11198 return TRAVERSE_EXIT;
11199 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11200 return TRAVERSE_EXIT;
11201 if (this->end_ != NULL)
11202 {
11203 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11204 return TRAVERSE_EXIT;
11205 }
11206 return TRAVERSE_CONTINUE;
11207}
11208
2c809f8f 11209Expression*
11210String_index_expression::do_flatten(Gogo*, Named_object*,
11211 Statement_inserter* inserter)
e440a328 11212{
2c809f8f 11213 Location loc = this->location();
5bf8be8b 11214 Expression* string = this->string_;
11215 Expression* start = this->start_;
11216 Expression* end = this->end_;
11217 if (string->is_error_expression()
11218 || string->type()->is_error_type()
11219 || start->is_error_expression()
11220 || start->type()->is_error_type()
11221 || (end != NULL
11222 && (end->is_error_expression() || end->type()->is_error_type())))
11223 {
11224 go_assert(saw_errors());
11225 return Expression::make_error(loc);
11226 }
11227
11228 Temporary_statement* temp;
2c809f8f 11229 if (!this->string_->is_variable())
11230 {
11231 temp = Statement::make_temporary(NULL, this->string_, loc);
11232 inserter->insert(temp);
11233 this->string_ = Expression::make_temporary_reference(temp, loc);
11234 }
11235 if (!this->start_->is_variable())
11236 {
11237 temp = Statement::make_temporary(NULL, this->start_, loc);
11238 inserter->insert(temp);
11239 this->start_ = Expression::make_temporary_reference(temp, loc);
11240 }
11241 if (this->end_ != NULL
11242 && !this->end_->is_nil_expression()
11243 && !this->end_->is_variable())
11244 {
11245 temp = Statement::make_temporary(NULL, this->end_, loc);
11246 inserter->insert(temp);
11247 this->end_ = Expression::make_temporary_reference(temp, loc);
11248 }
11249
11250 return this;
11251}
11252
11253// Return the type of a string index.
11254
11255Type*
11256String_index_expression::do_type()
11257{
11258 if (this->end_ == NULL)
11259 return Type::lookup_integer_type("uint8");
11260 else
11261 return this->string_->type();
11262}
11263
11264// Determine the type of a string index.
11265
11266void
11267String_index_expression::do_determine_type(const Type_context*)
11268{
11269 this->string_->determine_type_no_context();
f77aa642 11270
11271 Type_context index_context(Type::lookup_integer_type("int"), false);
11272 if (this->start_->is_constant())
11273 this->start_->determine_type(&index_context);
11274 else
11275 this->start_->determine_type_no_context();
e440a328 11276 if (this->end_ != NULL)
f77aa642 11277 {
11278 if (this->end_->is_constant())
11279 this->end_->determine_type(&index_context);
11280 else
11281 this->end_->determine_type_no_context();
11282 }
e440a328 11283}
11284
11285// Check types of a string index.
11286
11287void
11288String_index_expression::do_check_types(Gogo*)
11289{
acdc230d 11290 Numeric_constant nc;
11291 unsigned long v;
11292 if (this->start_->type()->integer_type() == NULL
11293 && !this->start_->type()->is_error()
11294 && (!this->start_->numeric_constant_value(&nc)
11295 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11296 this->report_error(_("index must be integer"));
11297 if (this->end_ != NULL
11298 && this->end_->type()->integer_type() == NULL
acdc230d 11299 && !this->end_->type()->is_error()
11300 && !this->end_->is_nil_expression()
11301 && !this->end_->is_error_expression()
11302 && (!this->end_->numeric_constant_value(&nc)
11303 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11304 this->report_error(_("slice end must be integer"));
11305
11306 std::string sval;
11307 bool sval_valid = this->string_->string_constant_value(&sval);
11308
0c77715b 11309 Numeric_constant inc;
e440a328 11310 mpz_t ival;
0bd5d859 11311 bool ival_valid = false;
0c77715b 11312 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 11313 {
0bd5d859 11314 ival_valid = true;
e440a328 11315 if (mpz_sgn(ival) < 0
b10f32fb 11316 || (sval_valid
11317 && (this->end_ == NULL
11318 ? mpz_cmp_ui(ival, sval.length()) >= 0
11319 : mpz_cmp_ui(ival, sval.length()) > 0)))
e440a328 11320 {
631d5788 11321 go_error_at(this->start_->location(), "string index out of bounds");
e440a328 11322 this->set_is_error();
11323 }
11324 }
11325 if (this->end_ != NULL && !this->end_->is_nil_expression())
11326 {
0c77715b 11327 Numeric_constant enc;
11328 mpz_t eval;
11329 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 11330 {
0c77715b 11331 if (mpz_sgn(eval) < 0
11332 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 11333 {
631d5788 11334 go_error_at(this->end_->location(), "string index out of bounds");
e440a328 11335 this->set_is_error();
11336 }
0bd5d859 11337 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11338 this->report_error(_("inverted slice range"));
0c77715b 11339 mpz_clear(eval);
e440a328 11340 }
11341 }
0bd5d859 11342 if (ival_valid)
11343 mpz_clear(ival);
e440a328 11344}
11345
ea664253 11346// Get the backend representation for a string index.
e440a328 11347
ea664253 11348Bexpression*
11349String_index_expression::do_get_backend(Translate_context* context)
e440a328 11350{
b13c66cd 11351 Location loc = this->location();
2c809f8f 11352 Expression* string_arg = this->string_;
11353 if (this->string_->type()->points_to() != NULL)
11354 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 11355
2c809f8f 11356 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 11357
2c809f8f 11358 int code = (this->end_ == NULL
11359 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11360 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 11361
2c809f8f 11362 Gogo* gogo = context->gogo();
ea664253 11363 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
1b1f2abf 11364
11365 Type* int_type = Type::lookup_integer_type("int");
e440a328 11366
2c809f8f 11367 // It is possible that an error occurred earlier because the start index
11368 // cannot be represented as an integer type. In this case, we shouldn't
11369 // try casting the starting index into an integer since
11370 // Type_conversion_expression will fail to get the backend representation.
11371 // FIXME.
11372 if (this->start_->type()->integer_type() == NULL
11373 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11374 {
11375 go_assert(saw_errors());
ea664253 11376 return context->backend()->error_expression();
2c809f8f 11377 }
e440a328 11378
2c809f8f 11379 Expression* start = Expression::make_cast(int_type, this->start_, loc);
93715b75 11380 Bfunction* bfn = context->function()->func_value()->get_decl();
e440a328 11381
2c809f8f 11382 if (this->end_ == NULL)
11383 {
11384 Expression* length =
11385 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 11386
2c809f8f 11387 Expression* start_too_large =
11388 Expression::make_binary(OPERATOR_GE, start, length, loc);
11389 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11390 bad_index, loc);
11391 Expression* bytes =
11392 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 11393
ea664253 11394 Bexpression* bstart = start->get_backend(context);
11395 Bexpression* ptr = bytes->get_backend(context);
2c809f8f 11396 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 11397 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11398 Bexpression* index =
11399 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 11400
2c809f8f 11401 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
ea664253 11402 Bexpression* index_error = bad_index->get_backend(context);
93715b75 11403 return gogo->backend()->conditional_expression(bfn, byte_btype,
11404 index_error, crash,
11405 index, loc);
2c809f8f 11406 }
11407
11408 Expression* end = NULL;
11409 if (this->end_->is_nil_expression())
e67508fa 11410 end = Expression::make_integer_sl(-1, int_type, loc);
e440a328 11411 else
11412 {
2c809f8f 11413 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11414 bad_index =
11415 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11416 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 11417 }
2c809f8f 11418
11419 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11420 string_arg, start, end);
ea664253 11421 Bexpression* bstrslice = strslice->get_backend(context);
2c809f8f 11422
11423 Btype* str_btype = strslice->type()->get_backend(gogo);
ea664253 11424 Bexpression* index_error = bad_index->get_backend(context);
93715b75 11425 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
ea664253 11426 crash, bstrslice, loc);
e440a328 11427}
11428
d751bb78 11429// Dump ast representation for a string index expression.
11430
11431void
11432String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11433 const
11434{
acf2b673 11435 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11436 this->start_, this->end_, NULL);
d751bb78 11437}
11438
e440a328 11439// Make a string index expression. END may be NULL.
11440
11441Expression*
11442Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 11443 Expression* end, Location location)
e440a328 11444{
11445 return new String_index_expression(string, start, end, location);
11446}
11447
11448// Class Map_index.
11449
11450// Get the type of the map.
11451
11452Map_type*
11453Map_index_expression::get_map_type() const
11454{
0d5530d9 11455 Map_type* mt = this->map_->type()->map_type();
c7524fae 11456 if (mt == NULL)
c484d925 11457 go_assert(saw_errors());
e440a328 11458 return mt;
11459}
11460
11461// Map index traversal.
11462
11463int
11464Map_index_expression::do_traverse(Traverse* traverse)
11465{
11466 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11467 return TRAVERSE_EXIT;
11468 return Expression::traverse(&this->index_, traverse);
11469}
11470
2c809f8f 11471// We need to pass in a pointer to the key, so flatten the index into a
11472// temporary variable if it isn't already. The value pointer will be
11473// dereferenced and checked for nil, so flatten into a temporary to avoid
11474// recomputation.
11475
11476Expression*
91c0fd76 11477Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
2c809f8f 11478 Statement_inserter* inserter)
11479{
91c0fd76 11480 Location loc = this->location();
2c809f8f 11481 Map_type* mt = this->get_map_type();
5bf8be8b 11482 if (this->index()->is_error_expression()
11483 || this->index()->type()->is_error_type()
11484 || mt->is_error_type())
11485 {
11486 go_assert(saw_errors());
11487 return Expression::make_error(loc);
11488 }
11489
91c0fd76 11490 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11491 {
11492 if (this->index_->type()->interface_type() != NULL
11493 && !this->index_->is_variable())
11494 {
11495 Temporary_statement* temp =
11496 Statement::make_temporary(NULL, this->index_, loc);
11497 inserter->insert(temp);
11498 this->index_ = Expression::make_temporary_reference(temp, loc);
11499 }
11500 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11501 this->index_, loc);
11502 }
2c809f8f 11503
11504 if (!this->index_->is_variable())
11505 {
11506 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
91c0fd76 11507 loc);
2c809f8f 11508 inserter->insert(temp);
91c0fd76 11509 this->index_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11510 }
11511
11512 if (this->value_pointer_ == NULL)
0d5530d9 11513 this->get_value_pointer(gogo);
5bf8be8b 11514 if (this->value_pointer_->is_error_expression()
11515 || this->value_pointer_->type()->is_error_type())
11516 return Expression::make_error(loc);
2c809f8f 11517 if (!this->value_pointer_->is_variable())
11518 {
11519 Temporary_statement* temp =
91c0fd76 11520 Statement::make_temporary(NULL, this->value_pointer_, loc);
2c809f8f 11521 inserter->insert(temp);
91c0fd76 11522 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11523 }
11524
11525 return this;
11526}
11527
e440a328 11528// Return the type of a map index.
11529
11530Type*
11531Map_index_expression::do_type()
11532{
c7524fae 11533 Map_type* mt = this->get_map_type();
11534 if (mt == NULL)
11535 return Type::make_error_type();
0d5530d9 11536 return mt->val_type();
e440a328 11537}
11538
11539// Fix the type of a map index.
11540
11541void
11542Map_index_expression::do_determine_type(const Type_context*)
11543{
11544 this->map_->determine_type_no_context();
c7524fae 11545 Map_type* mt = this->get_map_type();
11546 Type* key_type = mt == NULL ? NULL : mt->key_type();
11547 Type_context subcontext(key_type, false);
e440a328 11548 this->index_->determine_type(&subcontext);
11549}
11550
11551// Check types of a map index.
11552
11553void
11554Map_index_expression::do_check_types(Gogo*)
11555{
11556 std::string reason;
c7524fae 11557 Map_type* mt = this->get_map_type();
11558 if (mt == NULL)
11559 return;
11560 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 11561 {
11562 if (reason.empty())
11563 this->report_error(_("incompatible type for map index"));
11564 else
11565 {
631d5788 11566 go_error_at(this->location(), "incompatible type for map index (%s)",
11567 reason.c_str());
e440a328 11568 this->set_is_error();
11569 }
11570 }
11571}
11572
ea664253 11573// Get the backend representation for a map index.
e440a328 11574
ea664253 11575Bexpression*
11576Map_index_expression::do_get_backend(Translate_context* context)
e440a328 11577{
11578 Map_type* type = this->get_map_type();
c7524fae 11579 if (type == NULL)
2c809f8f 11580 {
11581 go_assert(saw_errors());
ea664253 11582 return context->backend()->error_expression();
2c809f8f 11583 }
e440a328 11584
2c809f8f 11585 go_assert(this->value_pointer_ != NULL
11586 && this->value_pointer_->is_variable());
e440a328 11587
0d5530d9 11588 Expression* val = Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
11589 this->location());
11590 return val->get_backend(context);
e440a328 11591}
11592
0d5530d9 11593// Get an expression for the map index. This returns an expression
11594// that evaluates to a pointer to a value. If the key is not in the
11595// map, the pointer will point to a zero value.
e440a328 11596
2c809f8f 11597Expression*
0d5530d9 11598Map_index_expression::get_value_pointer(Gogo* gogo)
e440a328 11599{
2c809f8f 11600 if (this->value_pointer_ == NULL)
746d2e73 11601 {
2c809f8f 11602 Map_type* type = this->get_map_type();
11603 if (type == NULL)
746d2e73 11604 {
2c809f8f 11605 go_assert(saw_errors());
11606 return Expression::make_error(this->location());
746d2e73 11607 }
e440a328 11608
2c809f8f 11609 Location loc = this->location();
11610 Expression* map_ref = this->map_;
e440a328 11611
0d5530d9 11612 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11613 this->index_,
2c809f8f 11614 loc);
0d5530d9 11615
11616 Expression* zero = type->fat_zero_value(gogo);
11617
11618 Expression* map_index;
11619
11620 if (zero == NULL)
11621 map_index =
11622 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11623 Expression::make_type_descriptor(type, loc),
11624 map_ref, index_ptr);
11625 else
11626 map_index =
11627 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11628 Expression::make_type_descriptor(type, loc),
11629 map_ref, index_ptr, zero);
2c809f8f 11630
11631 Type* val_type = type->val_type();
11632 this->value_pointer_ =
11633 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11634 map_index, this->location());
11635 }
0d5530d9 11636
2c809f8f 11637 return this->value_pointer_;
e440a328 11638}
11639
d751bb78 11640// Dump ast representation for a map index expression
11641
11642void
11643Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11644 const
11645{
acf2b673 11646 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11647 this->index_, NULL, NULL);
d751bb78 11648}
11649
e440a328 11650// Make a map index expression.
11651
11652Map_index_expression*
11653Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 11654 Location location)
e440a328 11655{
11656 return new Map_index_expression(map, index, location);
11657}
11658
11659// Class Field_reference_expression.
11660
149eabc5 11661// Lower a field reference expression. There is nothing to lower, but
11662// this is where we generate the tracking information for fields with
11663// the magic go:"track" tag.
11664
11665Expression*
11666Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11667 Statement_inserter* inserter, int)
11668{
11669 Struct_type* struct_type = this->expr_->type()->struct_type();
11670 if (struct_type == NULL)
11671 {
11672 // Error will be reported elsewhere.
11673 return this;
11674 }
11675 const Struct_field* field = struct_type->field(this->field_index_);
11676 if (field == NULL)
11677 return this;
11678 if (!field->has_tag())
11679 return this;
11680 if (field->tag().find("go:\"track\"") == std::string::npos)
11681 return this;
11682
604e278d 11683 // References from functions generated by the compiler don't count.
c6292d1d 11684 if (function != NULL && function->func_value()->is_type_specific_function())
604e278d 11685 return this;
11686
149eabc5 11687 // We have found a reference to a tracked field. Build a call to
11688 // the runtime function __go_fieldtrack with a string that describes
11689 // the field. FIXME: We should only call this once per referenced
11690 // field per function, not once for each reference to the field.
11691
11692 if (this->called_fieldtrack_)
11693 return this;
11694 this->called_fieldtrack_ = true;
11695
11696 Location loc = this->location();
11697
11698 std::string s = "fieldtrack \"";
11699 Named_type* nt = this->expr_->type()->named_type();
11700 if (nt == NULL || nt->named_object()->package() == NULL)
11701 s.append(gogo->pkgpath());
11702 else
11703 s.append(nt->named_object()->package()->pkgpath());
11704 s.push_back('.');
11705 if (nt != NULL)
5c29ad36 11706 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11707 s.push_back('.');
11708 s.append(field->field_name());
11709 s.push_back('"');
11710
11711 // We can't use a string here, because internally a string holds a
11712 // pointer to the actual bytes; when the linker garbage collects the
11713 // string, it won't garbage collect the bytes. So we use a
11714 // [...]byte.
11715
e67508fa 11716 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
149eabc5 11717
11718 Type* byte_type = gogo->lookup_global("byte")->type_value();
6bf4793c 11719 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
11720 array_type->set_is_array_incomparable();
149eabc5 11721
11722 Expression_list* bytes = new Expression_list();
11723 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11724 {
e67508fa 11725 unsigned char c = static_cast<unsigned char>(*p);
11726 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
149eabc5 11727 }
11728
11729 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11730 bytes, false, loc);
149eabc5 11731
11732 Variable* var = new Variable(array_type, e, true, false, false, loc);
11733
11734 static int count;
11735 char buf[50];
11736 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11737 ++count;
11738
11739 Named_object* no = gogo->add_variable(buf, var);
11740 e = Expression::make_var_reference(no, loc);
11741 e = Expression::make_unary(OPERATOR_AND, e, loc);
11742
11743 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
604e278d 11744 gogo->lower_expression(function, inserter, &call);
149eabc5 11745 inserter->insert(Statement::make_statement(call, false));
11746
11747 // Put this function, and the global variable we just created, into
11748 // unique sections. This will permit the linker to garbage collect
11749 // them if they are not referenced. The effect is that the only
11750 // strings, indicating field references, that will wind up in the
11751 // executable will be those for functions that are actually needed.
66a6be58 11752 if (function != NULL)
11753 function->func_value()->set_in_unique_section();
149eabc5 11754 var->set_in_unique_section();
11755
11756 return this;
11757}
11758
e440a328 11759// Return the type of a field reference.
11760
11761Type*
11762Field_reference_expression::do_type()
11763{
b0e628fb 11764 Type* type = this->expr_->type();
5c13bd80 11765 if (type->is_error())
b0e628fb 11766 return type;
11767 Struct_type* struct_type = type->struct_type();
c484d925 11768 go_assert(struct_type != NULL);
e440a328 11769 return struct_type->field(this->field_index_)->type();
11770}
11771
11772// Check the types for a field reference.
11773
11774void
11775Field_reference_expression::do_check_types(Gogo*)
11776{
b0e628fb 11777 Type* type = this->expr_->type();
5c13bd80 11778 if (type->is_error())
b0e628fb 11779 return;
11780 Struct_type* struct_type = type->struct_type();
c484d925 11781 go_assert(struct_type != NULL);
11782 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11783}
11784
ea664253 11785// Get the backend representation for a field reference.
e440a328 11786
ea664253 11787Bexpression*
11788Field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11789{
ea664253 11790 Bexpression* bstruct = this->expr_->get_backend(context);
11791 return context->gogo()->backend()->struct_field_expression(bstruct,
11792 this->field_index_,
11793 this->location());
e440a328 11794}
11795
d751bb78 11796// Dump ast representation for a field reference expression.
11797
11798void
11799Field_reference_expression::do_dump_expression(
11800 Ast_dump_context* ast_dump_context) const
11801{
11802 this->expr_->dump_expression(ast_dump_context);
11803 ast_dump_context->ostream() << "." << this->field_index_;
11804}
11805
e440a328 11806// Make a reference to a qualified identifier in an expression.
11807
11808Field_reference_expression*
11809Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11810 Location location)
e440a328 11811{
11812 return new Field_reference_expression(expr, field_index, location);
11813}
11814
11815// Class Interface_field_reference_expression.
11816
2387f644 11817// Return an expression for the pointer to the function to call.
e440a328 11818
2387f644 11819Expression*
11820Interface_field_reference_expression::get_function()
e440a328 11821{
2387f644 11822 Expression* ref = this->expr_;
11823 Location loc = this->location();
11824 if (ref->type()->points_to() != NULL)
11825 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11826
2387f644 11827 Expression* mtable =
11828 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11829 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11830
11831 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11832 unsigned int index;
11833 const Struct_field* field = mtable_type->find_local_field(name, &index);
11834 go_assert(field != NULL);
11835 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11836 return Expression::make_field_reference(mtable, index, loc);
e440a328 11837}
11838
2387f644 11839// Return an expression for the first argument to pass to the interface
e440a328 11840// function.
11841
2387f644 11842Expression*
11843Interface_field_reference_expression::get_underlying_object()
e440a328 11844{
2387f644 11845 Expression* expr = this->expr_;
11846 if (expr->type()->points_to() != NULL)
11847 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11848 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11849 this->location());
e440a328 11850}
11851
11852// Traversal.
11853
11854int
11855Interface_field_reference_expression::do_traverse(Traverse* traverse)
11856{
11857 return Expression::traverse(&this->expr_, traverse);
11858}
11859
0afbb937 11860// Lower the expression. If this expression is not called, we need to
11861// evaluate the expression twice when converting to the backend
11862// interface. So introduce a temporary variable if necessary.
11863
11864Expression*
9782d556 11865Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11866 Statement_inserter* inserter)
0afbb937 11867{
5bf8be8b 11868 if (this->expr_->is_error_expression()
11869 || this->expr_->type()->is_error_type())
11870 {
11871 go_assert(saw_errors());
11872 return Expression::make_error(this->location());
11873 }
11874
2387f644 11875 if (!this->expr_->is_variable())
0afbb937 11876 {
11877 Temporary_statement* temp =
11878 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11879 inserter->insert(temp);
11880 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11881 this->location());
11882 }
11883 return this;
11884}
11885
e440a328 11886// Return the type of an interface field reference.
11887
11888Type*
11889Interface_field_reference_expression::do_type()
11890{
11891 Type* expr_type = this->expr_->type();
11892
11893 Type* points_to = expr_type->points_to();
11894 if (points_to != NULL)
11895 expr_type = points_to;
11896
11897 Interface_type* interface_type = expr_type->interface_type();
11898 if (interface_type == NULL)
11899 return Type::make_error_type();
11900
11901 const Typed_identifier* method = interface_type->find_method(this->name_);
11902 if (method == NULL)
11903 return Type::make_error_type();
11904
11905 return method->type();
11906}
11907
11908// Determine types.
11909
11910void
11911Interface_field_reference_expression::do_determine_type(const Type_context*)
11912{
11913 this->expr_->determine_type_no_context();
11914}
11915
11916// Check the types for an interface field reference.
11917
11918void
11919Interface_field_reference_expression::do_check_types(Gogo*)
11920{
11921 Type* type = this->expr_->type();
11922
11923 Type* points_to = type->points_to();
11924 if (points_to != NULL)
11925 type = points_to;
11926
11927 Interface_type* interface_type = type->interface_type();
11928 if (interface_type == NULL)
5c491127 11929 {
11930 if (!type->is_error_type())
11931 this->report_error(_("expected interface or pointer to interface"));
11932 }
e440a328 11933 else
11934 {
11935 const Typed_identifier* method =
11936 interface_type->find_method(this->name_);
11937 if (method == NULL)
11938 {
631d5788 11939 go_error_at(this->location(), "method %qs not in interface",
11940 Gogo::message_name(this->name_).c_str());
e440a328 11941 this->set_is_error();
11942 }
11943 }
11944}
11945
0afbb937 11946// If an interface field reference is not simply called, then it is
11947// represented as a closure. The closure will hold a single variable,
11948// the value of the interface on which the method should be called.
11949// The function will be a simple thunk that pulls the value from the
11950// closure and calls the method with the remaining arguments.
11951
11952// Because method values are not common, we don't build all thunks for
11953// all possible interface methods, but instead only build them as we
11954// need them. In particular, we even build them on demand for
11955// interface methods defined in other packages.
11956
11957Interface_field_reference_expression::Interface_method_thunks
11958 Interface_field_reference_expression::interface_method_thunks;
11959
11960// Find or create the thunk to call method NAME on TYPE.
11961
11962Named_object*
11963Interface_field_reference_expression::create_thunk(Gogo* gogo,
11964 Interface_type* type,
11965 const std::string& name)
11966{
11967 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11968 std::pair<Interface_method_thunks::iterator, bool> ins =
11969 Interface_field_reference_expression::interface_method_thunks.insert(val);
11970 if (ins.second)
11971 {
11972 // This is the first time we have seen this interface.
11973 ins.first->second = new Method_thunks();
11974 }
11975
11976 for (Method_thunks::const_iterator p = ins.first->second->begin();
11977 p != ins.first->second->end();
11978 p++)
11979 if (p->first == name)
11980 return p->second;
11981
11982 Location loc = type->location();
11983
11984 const Typed_identifier* method_id = type->find_method(name);
11985 if (method_id == NULL)
11986 return Named_object::make_erroneous_name(Gogo::thunk_name());
11987
11988 Function_type* orig_fntype = method_id->type()->function_type();
11989 if (orig_fntype == NULL)
11990 return Named_object::make_erroneous_name(Gogo::thunk_name());
11991
11992 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11993 // The type here is wrong--it should be the C function type. But it
11994 // doesn't really matter.
0afbb937 11995 Type* vt = Type::make_pointer_type(Type::make_void_type());
11996 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11997 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
6bf4793c 11998 Struct_type* st = Type::make_struct_type(sfl, loc);
11999 st->set_is_struct_incomparable();
12000 Type* closure_type = Type::make_pointer_type(st);
0afbb937 12001
f8bdf81a 12002 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 12003
da244e59 12004 std::string thunk_name = Gogo::thunk_name();
12005 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 12006 false, loc);
12007
f8bdf81a 12008 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
12009 cvar->set_is_used();
1ecc6157 12010 cvar->set_is_closure();
da244e59 12011 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
12012 NULL, cvar);
f8bdf81a 12013 new_no->func_value()->set_closure_var(cp);
0afbb937 12014
f8bdf81a 12015 gogo->start_block(loc);
0afbb937 12016
12017 // Field 0 of the closure is the function code pointer, field 1 is
12018 // the value on which to invoke the method.
12019 Expression* arg = Expression::make_var_reference(cp, loc);
12020 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
12021 arg = Expression::make_field_reference(arg, 1, loc);
12022
12023 Expression *ifre = Expression::make_interface_field_reference(arg, name,
12024 loc);
12025
12026 const Typed_identifier_list* orig_params = orig_fntype->parameters();
12027 Expression_list* args;
12028 if (orig_params == NULL || orig_params->empty())
12029 args = NULL;
12030 else
12031 {
12032 const Typed_identifier_list* new_params = new_fntype->parameters();
12033 args = new Expression_list();
12034 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 12035 p != new_params->end();
0afbb937 12036 ++p)
12037 {
12038 Named_object* p_no = gogo->lookup(p->name(), NULL);
12039 go_assert(p_no != NULL
12040 && p_no->is_variable()
12041 && p_no->var_value()->is_parameter());
12042 args->push_back(Expression::make_var_reference(p_no, loc));
12043 }
12044 }
12045
12046 Call_expression* call = Expression::make_call(ifre, args,
12047 orig_fntype->is_varargs(),
12048 loc);
12049 call->set_varargs_are_lowered();
12050
12051 Statement* s = Statement::make_return_from_call(call, loc);
12052 gogo->add_statement(s);
12053 Block* b = gogo->finish_block(loc);
12054 gogo->add_block(b, loc);
12055 gogo->lower_block(new_no, b);
a32698ee 12056 gogo->flatten_block(new_no, b);
0afbb937 12057 gogo->finish_function(loc);
12058
12059 ins.first->second->push_back(std::make_pair(name, new_no));
12060 return new_no;
12061}
12062
ea664253 12063// Get the backend representation for a method value.
e440a328 12064
ea664253 12065Bexpression*
12066Interface_field_reference_expression::do_get_backend(Translate_context* context)
e440a328 12067{
0afbb937 12068 Interface_type* type = this->expr_->type()->interface_type();
12069 if (type == NULL)
12070 {
12071 go_assert(saw_errors());
ea664253 12072 return context->backend()->error_expression();
0afbb937 12073 }
12074
12075 Named_object* thunk =
12076 Interface_field_reference_expression::create_thunk(context->gogo(),
12077 type, this->name_);
12078 if (thunk->is_erroneous())
12079 {
12080 go_assert(saw_errors());
ea664253 12081 return context->backend()->error_expression();
0afbb937 12082 }
12083
12084 // FIXME: We should lower this earlier, but we can't it lower it in
12085 // the lowering pass because at that point we don't know whether we
12086 // need to create the thunk or not. If the expression is called, we
12087 // don't need the thunk.
12088
12089 Location loc = this->location();
12090
12091 Struct_field_list* fields = new Struct_field_list();
12092 fields->push_back(Struct_field(Typed_identifier("fn.0",
12093 thunk->func_value()->type(),
12094 loc)));
12095 fields->push_back(Struct_field(Typed_identifier("val.1",
12096 this->expr_->type(),
12097 loc)));
12098 Struct_type* st = Type::make_struct_type(fields, loc);
6bf4793c 12099 st->set_is_struct_incomparable();
0afbb937 12100
12101 Expression_list* vals = new Expression_list();
12102 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12103 vals->push_back(this->expr_);
12104
12105 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
ea664253 12106 Bexpression* bclosure =
12107 Expression::make_heap_expression(expr, loc)->get_backend(context);
0afbb937 12108
2387f644 12109 Expression* nil_check =
12110 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12111 Expression::make_nil(loc), loc);
ea664253 12112 Bexpression* bnil_check = nil_check->get_backend(context);
0afbb937 12113
2387f644 12114 Gogo* gogo = context->gogo();
ea664253 12115 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12116 loc)->get_backend(context);
2387f644 12117
93715b75 12118 Bfunction* bfn = context->function()->func_value()->get_decl();
2387f644 12119 Bexpression* bcond =
93715b75 12120 gogo->backend()->conditional_expression(bfn, NULL,
12121 bnil_check, bcrash, NULL, loc);
0ab48656 12122 Bfunction* bfunction = context->function()->func_value()->get_decl();
12123 Bstatement* cond_statement =
12124 gogo->backend()->expression_statement(bfunction, bcond);
ea664253 12125 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
e440a328 12126}
12127
d751bb78 12128// Dump ast representation for an interface field reference.
12129
12130void
12131Interface_field_reference_expression::do_dump_expression(
12132 Ast_dump_context* ast_dump_context) const
12133{
12134 this->expr_->dump_expression(ast_dump_context);
12135 ast_dump_context->ostream() << "." << this->name_;
12136}
12137
e440a328 12138// Make a reference to a field in an interface.
12139
12140Expression*
12141Expression::make_interface_field_reference(Expression* expr,
12142 const std::string& field,
b13c66cd 12143 Location location)
e440a328 12144{
12145 return new Interface_field_reference_expression(expr, field, location);
12146}
12147
12148// A general selector. This is a Parser_expression for LEFT.NAME. It
12149// is lowered after we know the type of the left hand side.
12150
12151class Selector_expression : public Parser_expression
12152{
12153 public:
12154 Selector_expression(Expression* left, const std::string& name,
b13c66cd 12155 Location location)
e440a328 12156 : Parser_expression(EXPRESSION_SELECTOR, location),
12157 left_(left), name_(name)
12158 { }
12159
12160 protected:
12161 int
12162 do_traverse(Traverse* traverse)
12163 { return Expression::traverse(&this->left_, traverse); }
12164
12165 Expression*
ceeb4318 12166 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 12167
12168 Expression*
12169 do_copy()
12170 {
12171 return new Selector_expression(this->left_->copy(), this->name_,
12172 this->location());
12173 }
12174
d751bb78 12175 void
12176 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12177
e440a328 12178 private:
12179 Expression*
12180 lower_method_expression(Gogo*);
12181
12182 // The expression on the left hand side.
12183 Expression* left_;
12184 // The name on the right hand side.
12185 std::string name_;
12186};
12187
12188// Lower a selector expression once we know the real type of the left
12189// hand side.
12190
12191Expression*
ceeb4318 12192Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12193 int)
e440a328 12194{
12195 Expression* left = this->left_;
12196 if (left->is_type_expression())
12197 return this->lower_method_expression(gogo);
12198 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12199 this->location());
12200}
12201
12202// Lower a method expression T.M or (*T).M. We turn this into a
12203// function literal.
12204
12205Expression*
12206Selector_expression::lower_method_expression(Gogo* gogo)
12207{
b13c66cd 12208 Location location = this->location();
868b439e 12209 Type* left_type = this->left_->type();
12210 Type* type = left_type;
e440a328 12211 const std::string& name(this->name_);
12212
12213 bool is_pointer;
12214 if (type->points_to() == NULL)
12215 is_pointer = false;
12216 else
12217 {
12218 is_pointer = true;
12219 type = type->points_to();
12220 }
12221 Named_type* nt = type->named_type();
12222 if (nt == NULL)
12223 {
631d5788 12224 go_error_at(location,
12225 ("method expression requires named type or "
12226 "pointer to named type"));
e440a328 12227 return Expression::make_error(location);
12228 }
12229
12230 bool is_ambiguous;
12231 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 12232 const Typed_identifier* imethod = NULL;
dcc8506b 12233 if (method == NULL && !is_pointer)
ab1468c3 12234 {
12235 Interface_type* it = nt->interface_type();
12236 if (it != NULL)
12237 imethod = it->find_method(name);
12238 }
12239
868b439e 12240 if ((method == NULL && imethod == NULL)
12241 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
e440a328 12242 {
12243 if (!is_ambiguous)
631d5788 12244 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12245 is_pointer ? "*" : "",
12246 nt->message_name().c_str(),
12247 Gogo::message_name(name).c_str());
e440a328 12248 else
631d5788 12249 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12250 Gogo::message_name(name).c_str(),
12251 is_pointer ? "*" : "",
12252 nt->message_name().c_str());
e440a328 12253 return Expression::make_error(location);
12254 }
12255
ab1468c3 12256 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 12257 {
631d5788 12258 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12259 nt->message_name().c_str(),
12260 Gogo::message_name(name).c_str());
e440a328 12261 return Expression::make_error(location);
12262 }
12263
12264 // Build a new function type in which the receiver becomes the first
12265 // argument.
ab1468c3 12266 Function_type* method_type;
12267 if (method != NULL)
12268 {
12269 method_type = method->type();
c484d925 12270 go_assert(method_type->is_method());
ab1468c3 12271 }
12272 else
12273 {
12274 method_type = imethod->type()->function_type();
c484d925 12275 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 12276 }
e440a328 12277
12278 const char* const receiver_name = "$this";
12279 Typed_identifier_list* parameters = new Typed_identifier_list();
12280 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12281 location));
12282
12283 const Typed_identifier_list* method_parameters = method_type->parameters();
12284 if (method_parameters != NULL)
12285 {
f470da59 12286 int i = 0;
e440a328 12287 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12288 p != method_parameters->end();
f470da59 12289 ++p, ++i)
12290 {
68883531 12291 if (!p->name().empty())
f470da59 12292 parameters->push_back(*p);
12293 else
12294 {
12295 char buf[20];
12296 snprintf(buf, sizeof buf, "$param%d", i);
12297 parameters->push_back(Typed_identifier(buf, p->type(),
12298 p->location()));
12299 }
12300 }
e440a328 12301 }
12302
12303 const Typed_identifier_list* method_results = method_type->results();
12304 Typed_identifier_list* results;
12305 if (method_results == NULL)
12306 results = NULL;
12307 else
12308 {
12309 results = new Typed_identifier_list();
12310 for (Typed_identifier_list::const_iterator p = method_results->begin();
12311 p != method_results->end();
12312 ++p)
12313 results->push_back(*p);
12314 }
12315
12316 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12317 location);
12318 if (method_type->is_varargs())
12319 fntype->set_is_varargs();
12320
12321 // We generate methods which always takes a pointer to the receiver
12322 // as their first argument. If this is for a pointer type, we can
12323 // simply reuse the existing function. We use an internal hack to
12324 // get the right type.
8381eda7 12325 // FIXME: This optimization is disabled because it doesn't yet work
12326 // with function descriptors when the method expression is not
12327 // directly called.
12328 if (method != NULL && is_pointer && false)
e440a328 12329 {
12330 Named_object* mno = (method->needs_stub_method()
12331 ? method->stub_object()
12332 : method->named_object());
12333 Expression* f = Expression::make_func_reference(mno, NULL, location);
12334 f = Expression::make_cast(fntype, f, location);
12335 Type_conversion_expression* tce =
12336 static_cast<Type_conversion_expression*>(f);
12337 tce->set_may_convert_function_types();
12338 return f;
12339 }
12340
12341 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12342 location);
12343
12344 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 12345 go_assert(vno != NULL);
e440a328 12346 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 12347 Expression* bm;
12348 if (method != NULL)
12349 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12350 else
12351 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 12352
12353 // Even though we found the method above, if it has an error type we
12354 // may see an error here.
12355 if (bm->is_error_expression())
463fe805 12356 {
12357 gogo->finish_function(location);
12358 return bm;
12359 }
e440a328 12360
12361 Expression_list* args;
f470da59 12362 if (parameters->size() <= 1)
e440a328 12363 args = NULL;
12364 else
12365 {
12366 args = new Expression_list();
f470da59 12367 Typed_identifier_list::const_iterator p = parameters->begin();
12368 ++p;
12369 for (; p != parameters->end(); ++p)
e440a328 12370 {
12371 vno = gogo->lookup(p->name(), NULL);
c484d925 12372 go_assert(vno != NULL);
e440a328 12373 args->push_back(Expression::make_var_reference(vno, location));
12374 }
12375 }
12376
ceeb4318 12377 gogo->start_block(location);
12378
e440a328 12379 Call_expression* call = Expression::make_call(bm, args,
12380 method_type->is_varargs(),
12381 location);
12382
0afbb937 12383 Statement* s = Statement::make_return_from_call(call, location);
e440a328 12384 gogo->add_statement(s);
12385
ceeb4318 12386 Block* b = gogo->finish_block(location);
12387
12388 gogo->add_block(b, location);
12389
12390 // Lower the call in case there are multiple results.
12391 gogo->lower_block(no, b);
a32698ee 12392 gogo->flatten_block(no, b);
ceeb4318 12393
e440a328 12394 gogo->finish_function(location);
12395
12396 return Expression::make_func_reference(no, NULL, location);
12397}
12398
d751bb78 12399// Dump the ast for a selector expression.
12400
12401void
12402Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12403 const
12404{
12405 ast_dump_context->dump_expression(this->left_);
12406 ast_dump_context->ostream() << ".";
12407 ast_dump_context->ostream() << this->name_;
12408}
12409
e440a328 12410// Make a selector expression.
12411
12412Expression*
12413Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 12414 Location location)
e440a328 12415{
12416 return new Selector_expression(left, name, location);
12417}
12418
da244e59 12419// Class Allocation_expression.
e440a328 12420
da244e59 12421int
12422Allocation_expression::do_traverse(Traverse* traverse)
e440a328 12423{
da244e59 12424 return Type::traverse(this->type_, traverse);
12425}
e440a328 12426
da244e59 12427Type*
12428Allocation_expression::do_type()
12429{
12430 return Type::make_pointer_type(this->type_);
12431}
e440a328 12432
da244e59 12433// Make a copy of an allocation expression.
e440a328 12434
da244e59 12435Expression*
12436Allocation_expression::do_copy()
12437{
12438 Allocation_expression* alloc =
12439 new Allocation_expression(this->type_, this->location());
12440 if (this->allocate_on_stack_)
12441 alloc->set_allocate_on_stack();
12442 return alloc;
12443}
e440a328 12444
ea664253 12445// Return the backend representation for an allocation expression.
e440a328 12446
ea664253 12447Bexpression*
12448Allocation_expression::do_get_backend(Translate_context* context)
e440a328 12449{
2c809f8f 12450 Gogo* gogo = context->gogo();
12451 Location loc = this->location();
da244e59 12452
45ff893b 12453 Node* n = Node::make_node(this);
12454 if (this->allocate_on_stack_
12455 || (n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
da244e59 12456 {
2a305b85 12457 int64_t size;
12458 bool ok = this->type_->backend_type_size(gogo, &size);
12459 if (!ok)
12460 {
12461 go_assert(saw_errors());
12462 return gogo->backend()->error_expression();
12463 }
d5d1c295 12464 return gogo->backend()->stack_allocation_expression(size, loc);
da244e59 12465 }
12466
2a305b85 12467 Btype* btype = this->type_->get_backend(gogo);
12468 Bexpression* space =
ea664253 12469 gogo->allocate_memory(this->type_, loc)->get_backend(context);
d5d1c295 12470 Btype* pbtype = gogo->backend()->pointer_type(btype);
ea664253 12471 return gogo->backend()->convert_expression(pbtype, space, loc);
e440a328 12472}
12473
d751bb78 12474// Dump ast representation for an allocation expression.
12475
12476void
12477Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12478 const
12479{
12480 ast_dump_context->ostream() << "new(";
12481 ast_dump_context->dump_type(this->type_);
12482 ast_dump_context->ostream() << ")";
12483}
12484
e440a328 12485// Make an allocation expression.
12486
12487Expression*
b13c66cd 12488Expression::make_allocation(Type* type, Location location)
e440a328 12489{
12490 return new Allocation_expression(type, location);
12491}
12492
e32de7ba 12493// Class Ordered_value_list.
e440a328 12494
12495int
e32de7ba 12496Ordered_value_list::traverse_vals(Traverse* traverse)
e440a328 12497{
0c4f5a19 12498 if (this->vals_ != NULL)
12499 {
12500 if (this->traverse_order_ == NULL)
12501 {
12502 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12503 return TRAVERSE_EXIT;
12504 }
12505 else
12506 {
e32de7ba 12507 for (std::vector<unsigned long>::const_iterator p =
12508 this->traverse_order_->begin();
0c4f5a19 12509 p != this->traverse_order_->end();
12510 ++p)
12511 {
12512 if (Expression::traverse(&this->vals_->at(*p), traverse)
12513 == TRAVERSE_EXIT)
12514 return TRAVERSE_EXIT;
12515 }
12516 }
12517 }
e32de7ba 12518 return TRAVERSE_CONTINUE;
12519}
12520
12521// Class Struct_construction_expression.
12522
12523// Traversal.
12524
12525int
12526Struct_construction_expression::do_traverse(Traverse* traverse)
12527{
12528 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12529 return TRAVERSE_EXIT;
e440a328 12530 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12531 return TRAVERSE_EXIT;
12532 return TRAVERSE_CONTINUE;
12533}
12534
12535// Return whether this is a constant initializer.
12536
12537bool
12538Struct_construction_expression::is_constant_struct() const
12539{
e32de7ba 12540 if (this->vals() == NULL)
e440a328 12541 return true;
e32de7ba 12542 for (Expression_list::const_iterator pv = this->vals()->begin();
12543 pv != this->vals()->end();
e440a328 12544 ++pv)
12545 {
12546 if (*pv != NULL
12547 && !(*pv)->is_constant()
12548 && (!(*pv)->is_composite_literal()
12549 || (*pv)->is_nonconstant_composite_literal()))
12550 return false;
12551 }
12552
12553 const Struct_field_list* fields = this->type_->struct_type()->fields();
12554 for (Struct_field_list::const_iterator pf = fields->begin();
12555 pf != fields->end();
12556 ++pf)
12557 {
12558 // There are no constant constructors for interfaces.
12559 if (pf->type()->interface_type() != NULL)
12560 return false;
12561 }
12562
12563 return true;
12564}
12565
3ae06f68 12566// Return whether this struct can be used as a constant initializer.
f9ca30f9 12567
12568bool
3ae06f68 12569Struct_construction_expression::do_is_static_initializer() const
f9ca30f9 12570{
e32de7ba 12571 if (this->vals() == NULL)
f9ca30f9 12572 return true;
e32de7ba 12573 for (Expression_list::const_iterator pv = this->vals()->begin();
12574 pv != this->vals()->end();
f9ca30f9 12575 ++pv)
12576 {
3ae06f68 12577 if (*pv != NULL && !(*pv)->is_static_initializer())
f9ca30f9 12578 return false;
12579 }
de048538 12580
12581 const Struct_field_list* fields = this->type_->struct_type()->fields();
12582 for (Struct_field_list::const_iterator pf = fields->begin();
12583 pf != fields->end();
12584 ++pf)
12585 {
12586 // There are no constant constructors for interfaces.
12587 if (pf->type()->interface_type() != NULL)
12588 return false;
12589 }
12590
f9ca30f9 12591 return true;
12592}
12593
e440a328 12594// Final type determination.
12595
12596void
12597Struct_construction_expression::do_determine_type(const Type_context*)
12598{
e32de7ba 12599 if (this->vals() == NULL)
e440a328 12600 return;
12601 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12602 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12603 for (Struct_field_list::const_iterator pf = fields->begin();
12604 pf != fields->end();
12605 ++pf, ++pv)
12606 {
e32de7ba 12607 if (pv == this->vals()->end())
e440a328 12608 return;
12609 if (*pv != NULL)
12610 {
12611 Type_context subcontext(pf->type(), false);
12612 (*pv)->determine_type(&subcontext);
12613 }
12614 }
a6cb4c0e 12615 // Extra values are an error we will report elsewhere; we still want
12616 // to determine the type to avoid knockon errors.
e32de7ba 12617 for (; pv != this->vals()->end(); ++pv)
a6cb4c0e 12618 (*pv)->determine_type_no_context();
e440a328 12619}
12620
12621// Check types.
12622
12623void
12624Struct_construction_expression::do_check_types(Gogo*)
12625{
e32de7ba 12626 if (this->vals() == NULL)
e440a328 12627 return;
12628
12629 Struct_type* st = this->type_->struct_type();
e32de7ba 12630 if (this->vals()->size() > st->field_count())
e440a328 12631 {
12632 this->report_error(_("too many expressions for struct"));
12633 return;
12634 }
12635
12636 const Struct_field_list* fields = st->fields();
e32de7ba 12637 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12638 int i = 0;
12639 for (Struct_field_list::const_iterator pf = fields->begin();
12640 pf != fields->end();
12641 ++pf, ++pv, ++i)
12642 {
e32de7ba 12643 if (pv == this->vals()->end())
e440a328 12644 {
12645 this->report_error(_("too few expressions for struct"));
12646 break;
12647 }
12648
12649 if (*pv == NULL)
12650 continue;
12651
12652 std::string reason;
12653 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12654 {
12655 if (reason.empty())
631d5788 12656 go_error_at((*pv)->location(),
12657 "incompatible type for field %d in struct construction",
12658 i + 1);
e440a328 12659 else
631d5788 12660 go_error_at((*pv)->location(),
12661 ("incompatible type for field %d in "
12662 "struct construction (%s)"),
12663 i + 1, reason.c_str());
e440a328 12664 this->set_is_error();
12665 }
12666 }
e32de7ba 12667 go_assert(pv == this->vals()->end());
e440a328 12668}
12669
8ba8cc87 12670// Flatten a struct construction expression. Store the values into
12671// temporaries in case they need interface conversion.
12672
12673Expression*
12674Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12675 Statement_inserter* inserter)
12676{
e32de7ba 12677 if (this->vals() == NULL)
8ba8cc87 12678 return this;
12679
12680 // If this is a constant struct, we don't need temporaries.
de048538 12681 if (this->is_constant_struct() || this->is_static_initializer())
8ba8cc87 12682 return this;
12683
12684 Location loc = this->location();
e32de7ba 12685 for (Expression_list::iterator pv = this->vals()->begin();
12686 pv != this->vals()->end();
8ba8cc87 12687 ++pv)
12688 {
12689 if (*pv != NULL)
12690 {
5bf8be8b 12691 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12692 {
12693 go_assert(saw_errors());
12694 return Expression::make_error(loc);
12695 }
8ba8cc87 12696 if (!(*pv)->is_variable())
12697 {
12698 Temporary_statement* temp =
12699 Statement::make_temporary(NULL, *pv, loc);
12700 inserter->insert(temp);
12701 *pv = Expression::make_temporary_reference(temp, loc);
12702 }
12703 }
12704 }
12705 return this;
12706}
12707
ea664253 12708// Return the backend representation for constructing a struct.
e440a328 12709
ea664253 12710Bexpression*
12711Struct_construction_expression::do_get_backend(Translate_context* context)
e440a328 12712{
12713 Gogo* gogo = context->gogo();
12714
2c809f8f 12715 Btype* btype = this->type_->get_backend(gogo);
e32de7ba 12716 if (this->vals() == NULL)
ea664253 12717 return gogo->backend()->zero_expression(btype);
e440a328 12718
e440a328 12719 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12720 Expression_list::const_iterator pv = this->vals()->begin();
2c809f8f 12721 std::vector<Bexpression*> init;
12722 for (Struct_field_list::const_iterator pf = fields->begin();
12723 pf != fields->end();
12724 ++pf)
e440a328 12725 {
63697958 12726 Btype* fbtype = pf->type()->get_backend(gogo);
e32de7ba 12727 if (pv == this->vals()->end())
2c809f8f 12728 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12729 else if (*pv == NULL)
12730 {
2c809f8f 12731 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12732 ++pv;
12733 }
12734 else
12735 {
2c809f8f 12736 Expression* val =
12737 Expression::convert_for_assignment(gogo, pf->type(),
12738 *pv, this->location());
ea664253 12739 init.push_back(val->get_backend(context));
e440a328 12740 ++pv;
12741 }
e440a328 12742 }
ea664253 12743 return gogo->backend()->constructor_expression(btype, init, this->location());
e440a328 12744}
12745
12746// Export a struct construction.
12747
12748void
12749Struct_construction_expression::do_export(Export* exp) const
12750{
12751 exp->write_c_string("convert(");
12752 exp->write_type(this->type_);
e32de7ba 12753 for (Expression_list::const_iterator pv = this->vals()->begin();
12754 pv != this->vals()->end();
e440a328 12755 ++pv)
12756 {
12757 exp->write_c_string(", ");
12758 if (*pv != NULL)
12759 (*pv)->export_expression(exp);
12760 }
12761 exp->write_c_string(")");
12762}
12763
d751bb78 12764// Dump ast representation of a struct construction expression.
12765
12766void
12767Struct_construction_expression::do_dump_expression(
12768 Ast_dump_context* ast_dump_context) const
12769{
d751bb78 12770 ast_dump_context->dump_type(this->type_);
12771 ast_dump_context->ostream() << "{";
e32de7ba 12772 ast_dump_context->dump_expression_list(this->vals());
d751bb78 12773 ast_dump_context->ostream() << "}";
12774}
12775
e440a328 12776// Make a struct composite literal. This used by the thunk code.
12777
12778Expression*
12779Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12780 Location location)
e440a328 12781{
c484d925 12782 go_assert(type->struct_type() != NULL);
e440a328 12783 return new Struct_construction_expression(type, vals, location);
12784}
12785
da244e59 12786// Class Array_construction_expression.
e440a328 12787
12788// Traversal.
12789
12790int
12791Array_construction_expression::do_traverse(Traverse* traverse)
12792{
e32de7ba 12793 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
e440a328 12794 return TRAVERSE_EXIT;
12795 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12796 return TRAVERSE_EXIT;
12797 return TRAVERSE_CONTINUE;
12798}
12799
12800// Return whether this is a constant initializer.
12801
12802bool
12803Array_construction_expression::is_constant_array() const
12804{
e32de7ba 12805 if (this->vals() == NULL)
e440a328 12806 return true;
12807
12808 // There are no constant constructors for interfaces.
12809 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12810 return false;
12811
e32de7ba 12812 for (Expression_list::const_iterator pv = this->vals()->begin();
12813 pv != this->vals()->end();
e440a328 12814 ++pv)
12815 {
12816 if (*pv != NULL
12817 && !(*pv)->is_constant()
12818 && (!(*pv)->is_composite_literal()
12819 || (*pv)->is_nonconstant_composite_literal()))
12820 return false;
12821 }
12822 return true;
12823}
12824
3ae06f68 12825// Return whether this can be used a constant initializer.
f9ca30f9 12826
12827bool
3ae06f68 12828Array_construction_expression::do_is_static_initializer() const
f9ca30f9 12829{
e32de7ba 12830 if (this->vals() == NULL)
f9ca30f9 12831 return true;
de048538 12832
12833 // There are no constant constructors for interfaces.
12834 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12835 return false;
12836
e32de7ba 12837 for (Expression_list::const_iterator pv = this->vals()->begin();
12838 pv != this->vals()->end();
f9ca30f9 12839 ++pv)
12840 {
3ae06f68 12841 if (*pv != NULL && !(*pv)->is_static_initializer())
f9ca30f9 12842 return false;
12843 }
12844 return true;
12845}
12846
e440a328 12847// Final type determination.
12848
12849void
12850Array_construction_expression::do_determine_type(const Type_context*)
12851{
e32de7ba 12852 if (this->vals() == NULL)
e440a328 12853 return;
12854 Type_context subcontext(this->type_->array_type()->element_type(), false);
e32de7ba 12855 for (Expression_list::const_iterator pv = this->vals()->begin();
12856 pv != this->vals()->end();
e440a328 12857 ++pv)
12858 {
12859 if (*pv != NULL)
12860 (*pv)->determine_type(&subcontext);
12861 }
12862}
12863
12864// Check types.
12865
12866void
12867Array_construction_expression::do_check_types(Gogo*)
12868{
e32de7ba 12869 if (this->vals() == NULL)
e440a328 12870 return;
12871
12872 Array_type* at = this->type_->array_type();
12873 int i = 0;
12874 Type* element_type = at->element_type();
e32de7ba 12875 for (Expression_list::const_iterator pv = this->vals()->begin();
12876 pv != this->vals()->end();
e440a328 12877 ++pv, ++i)
12878 {
12879 if (*pv != NULL
12880 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12881 {
631d5788 12882 go_error_at((*pv)->location(),
12883 "incompatible type for element %d in composite literal",
12884 i + 1);
e440a328 12885 this->set_is_error();
12886 }
12887 }
e440a328 12888}
12889
8ba8cc87 12890// Flatten an array construction expression. Store the values into
12891// temporaries in case they need interface conversion.
12892
12893Expression*
12894Array_construction_expression::do_flatten(Gogo*, Named_object*,
12895 Statement_inserter* inserter)
12896{
e32de7ba 12897 if (this->vals() == NULL)
8ba8cc87 12898 return this;
12899
12900 // If this is a constant array, we don't need temporaries.
de048538 12901 if (this->is_constant_array() || this->is_static_initializer())
8ba8cc87 12902 return this;
12903
12904 Location loc = this->location();
e32de7ba 12905 for (Expression_list::iterator pv = this->vals()->begin();
12906 pv != this->vals()->end();
8ba8cc87 12907 ++pv)
12908 {
12909 if (*pv != NULL)
12910 {
5bf8be8b 12911 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12912 {
12913 go_assert(saw_errors());
12914 return Expression::make_error(loc);
12915 }
8ba8cc87 12916 if (!(*pv)->is_variable())
12917 {
12918 Temporary_statement* temp =
12919 Statement::make_temporary(NULL, *pv, loc);
12920 inserter->insert(temp);
12921 *pv = Expression::make_temporary_reference(temp, loc);
12922 }
12923 }
12924 }
12925 return this;
12926}
12927
2c809f8f 12928// Get a constructor expression for the array values.
e440a328 12929
2c809f8f 12930Bexpression*
12931Array_construction_expression::get_constructor(Translate_context* context,
12932 Btype* array_btype)
e440a328 12933{
e440a328 12934 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12935
12936 std::vector<unsigned long> indexes;
12937 std::vector<Bexpression*> vals;
12938 Gogo* gogo = context->gogo();
e32de7ba 12939 if (this->vals() != NULL)
e440a328 12940 {
12941 size_t i = 0;
ffe743ca 12942 std::vector<unsigned long>::const_iterator pi;
12943 if (this->indexes_ != NULL)
12944 pi = this->indexes_->begin();
e32de7ba 12945 for (Expression_list::const_iterator pv = this->vals()->begin();
12946 pv != this->vals()->end();
e440a328 12947 ++pv, ++i)
12948 {
ffe743ca 12949 if (this->indexes_ != NULL)
12950 go_assert(pi != this->indexes_->end());
ffe743ca 12951
12952 if (this->indexes_ == NULL)
2c809f8f 12953 indexes.push_back(i);
ffe743ca 12954 else
2c809f8f 12955 indexes.push_back(*pi);
e440a328 12956 if (*pv == NULL)
63697958 12957 {
63697958 12958 Btype* ebtype = element_type->get_backend(gogo);
12959 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12960 vals.push_back(zv);
63697958 12961 }
e440a328 12962 else
12963 {
2c809f8f 12964 Expression* val_expr =
12965 Expression::convert_for_assignment(gogo, element_type, *pv,
12966 this->location());
ea664253 12967 vals.push_back(val_expr->get_backend(context));
e440a328 12968 }
ffe743ca 12969 if (this->indexes_ != NULL)
12970 ++pi;
e440a328 12971 }
ffe743ca 12972 if (this->indexes_ != NULL)
12973 go_assert(pi == this->indexes_->end());
e440a328 12974 }
2c809f8f 12975 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12976 vals, this->location());
e440a328 12977}
12978
12979// Export an array construction.
12980
12981void
12982Array_construction_expression::do_export(Export* exp) const
12983{
12984 exp->write_c_string("convert(");
12985 exp->write_type(this->type_);
e32de7ba 12986 if (this->vals() != NULL)
e440a328 12987 {
ffe743ca 12988 std::vector<unsigned long>::const_iterator pi;
12989 if (this->indexes_ != NULL)
12990 pi = this->indexes_->begin();
e32de7ba 12991 for (Expression_list::const_iterator pv = this->vals()->begin();
12992 pv != this->vals()->end();
e440a328 12993 ++pv)
12994 {
12995 exp->write_c_string(", ");
ffe743ca 12996
12997 if (this->indexes_ != NULL)
12998 {
12999 char buf[100];
13000 snprintf(buf, sizeof buf, "%lu", *pi);
13001 exp->write_c_string(buf);
13002 exp->write_c_string(":");
13003 }
13004
e440a328 13005 if (*pv != NULL)
13006 (*pv)->export_expression(exp);
ffe743ca 13007
13008 if (this->indexes_ != NULL)
13009 ++pi;
e440a328 13010 }
13011 }
13012 exp->write_c_string(")");
13013}
13014
0e9a2e72 13015// Dump ast representation of an array construction expression.
d751bb78 13016
13017void
13018Array_construction_expression::do_dump_expression(
13019 Ast_dump_context* ast_dump_context) const
13020{
ffe743ca 13021 Expression* length = this->type_->array_type()->length();
8b1c301d 13022
13023 ast_dump_context->ostream() << "[" ;
13024 if (length != NULL)
13025 {
13026 ast_dump_context->dump_expression(length);
13027 }
13028 ast_dump_context->ostream() << "]" ;
d751bb78 13029 ast_dump_context->dump_type(this->type_);
0e9a2e72 13030 this->dump_slice_storage_expression(ast_dump_context);
d751bb78 13031 ast_dump_context->ostream() << "{" ;
ffe743ca 13032 if (this->indexes_ == NULL)
e32de7ba 13033 ast_dump_context->dump_expression_list(this->vals());
ffe743ca 13034 else
13035 {
e32de7ba 13036 Expression_list::const_iterator pv = this->vals()->begin();
ffe743ca 13037 for (std::vector<unsigned long>::const_iterator pi =
13038 this->indexes_->begin();
13039 pi != this->indexes_->end();
13040 ++pi, ++pv)
13041 {
13042 if (pi != this->indexes_->begin())
13043 ast_dump_context->ostream() << ", ";
13044 ast_dump_context->ostream() << *pi << ':';
13045 ast_dump_context->dump_expression(*pv);
13046 }
13047 }
d751bb78 13048 ast_dump_context->ostream() << "}" ;
13049
13050}
13051
da244e59 13052// Class Fixed_array_construction_expression.
e440a328 13053
da244e59 13054Fixed_array_construction_expression::Fixed_array_construction_expression(
13055 Type* type, const std::vector<unsigned long>* indexes,
13056 Expression_list* vals, Location location)
13057 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13058 type, indexes, vals, location)
13059{ go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 13060
ea664253 13061// Return the backend representation for constructing a fixed array.
e440a328 13062
ea664253 13063Bexpression*
13064Fixed_array_construction_expression::do_get_backend(Translate_context* context)
e440a328 13065{
9f0e0513 13066 Type* type = this->type();
13067 Btype* btype = type->get_backend(context->gogo());
ea664253 13068 return this->get_constructor(context, btype);
e440a328 13069}
13070
76f85fd6 13071Expression*
13072Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13073 Location location)
13074{
13075 go_assert(type->array_type() != NULL && !type->is_slice_type());
13076 return new Fixed_array_construction_expression(type, NULL, vals, location);
13077}
13078
da244e59 13079// Class Slice_construction_expression.
e440a328 13080
da244e59 13081Slice_construction_expression::Slice_construction_expression(
13082 Type* type, const std::vector<unsigned long>* indexes,
13083 Expression_list* vals, Location location)
13084 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13085 type, indexes, vals, location),
0e9a2e72 13086 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13087 storage_escapes_(true)
e440a328 13088{
da244e59 13089 go_assert(type->is_slice_type());
23d77f91 13090
da244e59 13091 unsigned long lenval;
13092 Expression* length;
13093 if (vals == NULL || vals->empty())
13094 lenval = 0;
13095 else
13096 {
13097 if (this->indexes() == NULL)
13098 lenval = vals->size();
13099 else
13100 lenval = indexes->back() + 1;
13101 }
13102 Type* int_type = Type::lookup_integer_type("int");
13103 length = Expression::make_integer_ul(lenval, int_type, location);
13104 Type* element_type = type->array_type()->element_type();
6bf4793c 13105 Array_type* array_type = Type::make_array_type(element_type, length);
13106 array_type->set_is_array_incomparable();
13107 this->valtype_ = array_type;
da244e59 13108}
e440a328 13109
23d77f91 13110// Traversal.
13111
13112int
13113Slice_construction_expression::do_traverse(Traverse* traverse)
13114{
13115 if (this->Array_construction_expression::do_traverse(traverse)
13116 == TRAVERSE_EXIT)
13117 return TRAVERSE_EXIT;
13118 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13119 return TRAVERSE_EXIT;
0e9a2e72 13120 if (this->array_val_ != NULL
13121 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13122 return TRAVERSE_EXIT;
13123 if (this->slice_storage_ != NULL
13124 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13125 return TRAVERSE_EXIT;
23d77f91 13126 return TRAVERSE_CONTINUE;
13127}
13128
0e9a2e72 13129// Helper routine to create fixed array value underlying the slice literal.
13130// May be called during flattening, or later during do_get_backend().
e440a328 13131
0e9a2e72 13132Expression*
13133Slice_construction_expression::create_array_val()
e440a328 13134{
f9c68f17 13135 Array_type* array_type = this->type()->array_type();
13136 if (array_type == NULL)
13137 {
c484d925 13138 go_assert(this->type()->is_error());
0e9a2e72 13139 return NULL;
f9c68f17 13140 }
13141
f23d7786 13142 Location loc = this->location();
23d77f91 13143 go_assert(this->valtype_ != NULL);
3d60812e 13144
f23d7786 13145 Expression_list* vals = this->vals();
0e9a2e72 13146 return new Fixed_array_construction_expression(
13147 this->valtype_, this->indexes(), vals, loc);
13148}
13149
13150// If we're previous established that the slice storage does not
13151// escape, then create a separate array temp val here for it. We
13152// need to do this as part of flattening so as to be able to insert
13153// the new temp statement.
13154
13155Expression*
13156Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13157 Statement_inserter* inserter)
13158{
13159 if (this->type()->array_type() == NULL)
13160 return NULL;
13161
13162 // Base class flattening first
13163 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13164
a1bbc2c3 13165 // Create a stack-allocated storage temp if storage won't escape
03118c21 13166 if (!this->storage_escapes_
13167 && this->slice_storage_ == NULL
13168 && this->element_count() > 0)
0e9a2e72 13169 {
13170 Location loc = this->location();
03118c21 13171 this->array_val_ = this->create_array_val();
0e9a2e72 13172 go_assert(this->array_val_);
13173 Temporary_statement* temp =
13174 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13175 inserter->insert(temp);
13176 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13177 }
13178 return this;
13179}
13180
13181// When dumping a slice construction expression that has an explicit
13182// storeage temp, emit the temp here (if we don't do this the storage
13183// temp appears unused in the AST dump).
13184
13185void
13186Slice_construction_expression::
13187dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13188{
13189 if (this->slice_storage_ == NULL)
13190 return;
13191 ast_dump_context->ostream() << "storage=" ;
13192 ast_dump_context->dump_expression(this->slice_storage_);
13193}
13194
13195// Return the backend representation for constructing a slice.
13196
13197Bexpression*
13198Slice_construction_expression::do_get_backend(Translate_context* context)
13199{
13200 if (this->array_val_ == NULL)
03118c21 13201 this->array_val_ = this->create_array_val();
0e9a2e72 13202 if (this->array_val_ == NULL)
13203 {
13204 go_assert(this->type()->is_error());
13205 return context->backend()->error_expression();
13206 }
13207
13208 Location loc = this->location();
e440a328 13209
3ae06f68 13210 bool is_static_initializer = this->array_val_->is_static_initializer();
d8829beb 13211
13212 // We have to copy the initial values into heap memory if we are in
3ae06f68 13213 // a function or if the values are not constants.
13214 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
e440a328 13215
f23d7786 13216 Expression* space;
0e9a2e72 13217
13218 if (this->slice_storage_ != NULL)
13219 {
13220 go_assert(!this->storage_escapes_);
13221 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13222 }
13223 else if (!copy_to_heap)
e440a328 13224 {
f23d7786 13225 // The initializer will only run once.
0e9a2e72 13226 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
f23d7786 13227 space->unary_expression()->set_is_slice_init();
e440a328 13228 }
13229 else
45ff893b 13230 {
0e9a2e72 13231 space = Expression::make_heap_expression(this->array_val_, loc);
45ff893b 13232 Node* n = Node::make_node(this);
13233 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
13234 {
13235 n = Node::make_node(space);
13236 n->set_encoding(Node::ESCAPE_NONE);
13237 }
13238 }
e440a328 13239
2c809f8f 13240 // Build a constructor for the slice.
f23d7786 13241 Expression* len = this->valtype_->array_type()->length();
13242 Expression* slice_val =
13243 Expression::make_slice_value(this->type(), space, len, len, loc);
ea664253 13244 return slice_val->get_backend(context);
e440a328 13245}
13246
13247// Make a slice composite literal. This is used by the type
13248// descriptor code.
13249
0e9a2e72 13250Slice_construction_expression*
e440a328 13251Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 13252 Location location)
e440a328 13253{
411eb89e 13254 go_assert(type->is_slice_type());
2c809f8f 13255 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 13256}
13257
da244e59 13258// Class Map_construction_expression.
e440a328 13259
13260// Traversal.
13261
13262int
13263Map_construction_expression::do_traverse(Traverse* traverse)
13264{
13265 if (this->vals_ != NULL
13266 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13267 return TRAVERSE_EXIT;
13268 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13269 return TRAVERSE_EXIT;
13270 return TRAVERSE_CONTINUE;
13271}
13272
2c809f8f 13273// Flatten constructor initializer into a temporary variable since
13274// we need to take its address for __go_construct_map.
13275
13276Expression*
13277Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13278 Statement_inserter* inserter)
13279{
13280 if (!this->is_error_expression()
13281 && this->vals_ != NULL
13282 && !this->vals_->empty()
13283 && this->constructor_temp_ == NULL)
13284 {
13285 Map_type* mt = this->type_->map_type();
13286 Type* key_type = mt->key_type();
13287 Type* val_type = mt->val_type();
13288 this->element_type_ = Type::make_builtin_struct_type(2,
13289 "__key", key_type,
13290 "__val", val_type);
13291
13292 Expression_list* value_pairs = new Expression_list();
13293 Location loc = this->location();
13294
13295 size_t i = 0;
13296 for (Expression_list::const_iterator pv = this->vals_->begin();
13297 pv != this->vals_->end();
13298 ++pv, ++i)
13299 {
13300 Expression_list* key_value_pair = new Expression_list();
91c0fd76 13301 Expression* key = *pv;
5bf8be8b 13302 if (key->is_error_expression() || key->type()->is_error_type())
13303 {
13304 go_assert(saw_errors());
13305 return Expression::make_error(loc);
13306 }
91c0fd76 13307 if (key->type()->interface_type() != NULL && !key->is_variable())
13308 {
13309 Temporary_statement* temp =
13310 Statement::make_temporary(NULL, key, loc);
13311 inserter->insert(temp);
13312 key = Expression::make_temporary_reference(temp, loc);
13313 }
13314 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
2c809f8f 13315
13316 ++pv;
91c0fd76 13317 Expression* val = *pv;
5bf8be8b 13318 if (val->is_error_expression() || val->type()->is_error_type())
13319 {
13320 go_assert(saw_errors());
13321 return Expression::make_error(loc);
13322 }
91c0fd76 13323 if (val->type()->interface_type() != NULL && !val->is_variable())
13324 {
13325 Temporary_statement* temp =
13326 Statement::make_temporary(NULL, val, loc);
13327 inserter->insert(temp);
13328 val = Expression::make_temporary_reference(temp, loc);
13329 }
13330 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
2c809f8f 13331
13332 key_value_pair->push_back(key);
13333 key_value_pair->push_back(val);
13334 value_pairs->push_back(
13335 Expression::make_struct_composite_literal(this->element_type_,
13336 key_value_pair, loc));
13337 }
13338
e67508fa 13339 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
6bf4793c 13340 Array_type* ctor_type =
2c809f8f 13341 Type::make_array_type(this->element_type_, element_count);
6bf4793c 13342 ctor_type->set_is_array_incomparable();
2c809f8f 13343 Expression* constructor =
13344 new Fixed_array_construction_expression(ctor_type, NULL,
13345 value_pairs, loc);
13346
13347 this->constructor_temp_ =
13348 Statement::make_temporary(NULL, constructor, loc);
13349 constructor->issue_nil_check();
13350 this->constructor_temp_->set_is_address_taken();
13351 inserter->insert(this->constructor_temp_);
13352 }
13353
13354 return this;
13355}
13356
e440a328 13357// Final type determination.
13358
13359void
13360Map_construction_expression::do_determine_type(const Type_context*)
13361{
13362 if (this->vals_ == NULL)
13363 return;
13364
13365 Map_type* mt = this->type_->map_type();
13366 Type_context key_context(mt->key_type(), false);
13367 Type_context val_context(mt->val_type(), false);
13368 for (Expression_list::const_iterator pv = this->vals_->begin();
13369 pv != this->vals_->end();
13370 ++pv)
13371 {
13372 (*pv)->determine_type(&key_context);
13373 ++pv;
13374 (*pv)->determine_type(&val_context);
13375 }
13376}
13377
13378// Check types.
13379
13380void
13381Map_construction_expression::do_check_types(Gogo*)
13382{
13383 if (this->vals_ == NULL)
13384 return;
13385
13386 Map_type* mt = this->type_->map_type();
13387 int i = 0;
13388 Type* key_type = mt->key_type();
13389 Type* val_type = mt->val_type();
13390 for (Expression_list::const_iterator pv = this->vals_->begin();
13391 pv != this->vals_->end();
13392 ++pv, ++i)
13393 {
13394 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13395 {
631d5788 13396 go_error_at((*pv)->location(),
13397 "incompatible type for element %d key in map construction",
13398 i + 1);
e440a328 13399 this->set_is_error();
13400 }
13401 ++pv;
13402 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13403 {
631d5788 13404 go_error_at((*pv)->location(),
13405 ("incompatible type for element %d value "
13406 "in map construction"),
e440a328 13407 i + 1);
13408 this->set_is_error();
13409 }
13410 }
13411}
13412
ea664253 13413// Return the backend representation for constructing a map.
e440a328 13414
ea664253 13415Bexpression*
13416Map_construction_expression::do_get_backend(Translate_context* context)
e440a328 13417{
2c809f8f 13418 if (this->is_error_expression())
ea664253 13419 return context->backend()->error_expression();
2c809f8f 13420 Location loc = this->location();
e440a328 13421
e440a328 13422 size_t i = 0;
2c809f8f 13423 Expression* ventries;
e440a328 13424 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 13425 ventries = Expression::make_nil(loc);
e440a328 13426 else
13427 {
2c809f8f 13428 go_assert(this->constructor_temp_ != NULL);
13429 i = this->vals_->size() / 2;
e440a328 13430
2c809f8f 13431 Expression* ctor_ref =
13432 Expression::make_temporary_reference(this->constructor_temp_, loc);
13433 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13434 }
e440a328 13435
2c809f8f 13436 Map_type* mt = this->type_->map_type();
13437 if (this->element_type_ == NULL)
13438 this->element_type_ =
13439 Type::make_builtin_struct_type(2,
13440 "__key", mt->key_type(),
13441 "__val", mt->val_type());
0d5530d9 13442 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
2c809f8f 13443
13444 Type* uintptr_t = Type::lookup_integer_type("uintptr");
e67508fa 13445 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
2c809f8f 13446
13447 Expression* entry_size =
13448 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13449
13450 unsigned int field_index;
13451 const Struct_field* valfield =
13452 this->element_type_->find_local_field("__val", &field_index);
13453 Expression* val_offset =
13454 Expression::make_struct_field_offset(this->element_type_, valfield);
2c809f8f 13455
13456 Expression* map_ctor =
0d5530d9 13457 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13458 entry_size, val_offset, ventries);
ea664253 13459 return map_ctor->get_backend(context);
2c809f8f 13460}
e440a328 13461
2c809f8f 13462// Export an array construction.
e440a328 13463
2c809f8f 13464void
13465Map_construction_expression::do_export(Export* exp) const
13466{
13467 exp->write_c_string("convert(");
13468 exp->write_type(this->type_);
13469 for (Expression_list::const_iterator pv = this->vals_->begin();
13470 pv != this->vals_->end();
13471 ++pv)
13472 {
13473 exp->write_c_string(", ");
13474 (*pv)->export_expression(exp);
13475 }
13476 exp->write_c_string(")");
13477}
e440a328 13478
2c809f8f 13479// Dump ast representation for a map construction expression.
d751bb78 13480
13481void
13482Map_construction_expression::do_dump_expression(
13483 Ast_dump_context* ast_dump_context) const
13484{
d751bb78 13485 ast_dump_context->ostream() << "{" ;
8b1c301d 13486 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 13487 ast_dump_context->ostream() << "}";
13488}
13489
7795ac51 13490// Class Composite_literal_expression.
e440a328 13491
13492// Traversal.
13493
13494int
13495Composite_literal_expression::do_traverse(Traverse* traverse)
13496{
dbffccfc 13497 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 13498 return TRAVERSE_EXIT;
dbffccfc 13499
13500 // If this is a struct composite literal with keys, then the keys
13501 // are field names, not expressions. We don't want to traverse them
13502 // in that case. If we do, we can give an erroneous error "variable
13503 // initializer refers to itself." See bug482.go in the testsuite.
13504 if (this->has_keys_ && this->vals_ != NULL)
13505 {
13506 // The type may not be resolvable at this point.
13507 Type* type = this->type_;
a01f2481 13508
7795ac51 13509 for (int depth = 0; depth < this->depth_; ++depth)
a01f2481 13510 {
13511 if (type->array_type() != NULL)
13512 type = type->array_type()->element_type();
13513 else if (type->map_type() != NULL)
7795ac51 13514 {
13515 if (this->key_path_[depth])
13516 type = type->map_type()->key_type();
13517 else
13518 type = type->map_type()->val_type();
13519 }
a01f2481 13520 else
13521 {
13522 // This error will be reported during lowering.
13523 return TRAVERSE_CONTINUE;
13524 }
13525 }
13526
dbffccfc 13527 while (true)
13528 {
13529 if (type->classification() == Type::TYPE_NAMED)
13530 type = type->named_type()->real_type();
13531 else if (type->classification() == Type::TYPE_FORWARD)
13532 {
13533 Type* t = type->forwarded();
13534 if (t == type)
13535 break;
13536 type = t;
13537 }
13538 else
13539 break;
13540 }
13541
13542 if (type->classification() == Type::TYPE_STRUCT)
13543 {
13544 Expression_list::iterator p = this->vals_->begin();
13545 while (p != this->vals_->end())
13546 {
13547 // Skip key.
13548 ++p;
13549 go_assert(p != this->vals_->end());
13550 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13551 return TRAVERSE_EXIT;
13552 ++p;
13553 }
13554 return TRAVERSE_CONTINUE;
13555 }
13556 }
13557
13558 if (this->vals_ != NULL)
13559 return this->vals_->traverse(traverse);
13560
13561 return TRAVERSE_CONTINUE;
e440a328 13562}
13563
13564// Lower a generic composite literal into a specific version based on
13565// the type.
13566
13567Expression*
ceeb4318 13568Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13569 Statement_inserter* inserter, int)
e440a328 13570{
13571 Type* type = this->type_;
13572
7795ac51 13573 for (int depth = 0; depth < this->depth_; ++depth)
e440a328 13574 {
13575 if (type->array_type() != NULL)
13576 type = type->array_type()->element_type();
13577 else if (type->map_type() != NULL)
7795ac51 13578 {
13579 if (this->key_path_[depth])
13580 type = type->map_type()->key_type();
13581 else
13582 type = type->map_type()->val_type();
13583 }
e440a328 13584 else
13585 {
5c13bd80 13586 if (!type->is_error())
631d5788 13587 go_error_at(this->location(),
13588 ("may only omit types within composite literals "
13589 "of slice, array, or map type"));
e440a328 13590 return Expression::make_error(this->location());
13591 }
13592 }
13593
e00772b3 13594 Type *pt = type->points_to();
13595 bool is_pointer = false;
13596 if (pt != NULL)
13597 {
13598 is_pointer = true;
13599 type = pt;
13600 }
13601
13602 Expression* ret;
5c13bd80 13603 if (type->is_error())
e440a328 13604 return Expression::make_error(this->location());
13605 else if (type->struct_type() != NULL)
e00772b3 13606 ret = this->lower_struct(gogo, type);
e440a328 13607 else if (type->array_type() != NULL)
113ef6a5 13608 ret = this->lower_array(type);
e440a328 13609 else if (type->map_type() != NULL)
e00772b3 13610 ret = this->lower_map(gogo, function, inserter, type);
e440a328 13611 else
13612 {
631d5788 13613 go_error_at(this->location(),
13614 ("expected struct, slice, array, or map type "
13615 "for composite literal"));
e440a328 13616 return Expression::make_error(this->location());
13617 }
e00772b3 13618
13619 if (is_pointer)
2c809f8f 13620 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13621
13622 return ret;
e440a328 13623}
13624
13625// Lower a struct composite literal.
13626
13627Expression*
81c4b26b 13628Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13629{
b13c66cd 13630 Location location = this->location();
e440a328 13631 Struct_type* st = type->struct_type();
13632 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13633 {
e6013c28 13634 if (this->vals_ != NULL
13635 && !this->vals_->empty()
13636 && type->named_type() != NULL
13637 && type->named_type()->named_object()->package() != NULL)
13638 {
13639 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13640 pf != st->fields()->end();
13641 ++pf)
07daa4e7 13642 {
07ba7f26 13643 if (Gogo::is_hidden_name(pf->field_name())
13644 || pf->is_embedded_builtin(gogo))
631d5788 13645 go_error_at(this->location(),
13646 "assignment of unexported field %qs in %qs literal",
13647 Gogo::message_name(pf->field_name()).c_str(),
13648 type->named_type()->message_name().c_str());
07daa4e7 13649 }
13650 }
13651
13652 return new Struct_construction_expression(type, this->vals_, location);
13653 }
e440a328 13654
13655 size_t field_count = st->field_count();
13656 std::vector<Expression*> vals(field_count);
e32de7ba 13657 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
e440a328 13658 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13659 Expression* external_expr = NULL;
13660 const Named_object* external_no = NULL;
e440a328 13661 while (p != this->vals_->end())
13662 {
13663 Expression* name_expr = *p;
13664
13665 ++p;
c484d925 13666 go_assert(p != this->vals_->end());
e440a328 13667 Expression* val = *p;
13668
13669 ++p;
13670
13671 if (name_expr == NULL)
13672 {
631d5788 13673 go_error_at(val->location(),
13674 "mixture of field and value initializers");
e440a328 13675 return Expression::make_error(location);
13676 }
13677
13678 bool bad_key = false;
13679 std::string name;
81c4b26b 13680 const Named_object* no = NULL;
e440a328 13681 switch (name_expr->classification())
13682 {
13683 case EXPRESSION_UNKNOWN_REFERENCE:
13684 name = name_expr->unknown_expression()->name();
7f7ce694 13685 if (type->named_type() != NULL)
13686 {
13687 // If the named object found for this field name comes from a
13688 // different package than the struct it is a part of, do not count
13689 // this incorrect lookup as a usage of the object's package.
13690 no = name_expr->unknown_expression()->named_object();
13691 if (no->package() != NULL
13692 && no->package() != type->named_type()->named_object()->package())
13693 no->package()->forget_usage(name_expr);
13694 }
e440a328 13695 break;
13696
13697 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13698 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13699 break;
13700
13701 case EXPRESSION_TYPE:
13702 {
13703 Type* t = name_expr->type();
13704 Named_type* nt = t->named_type();
13705 if (nt == NULL)
13706 bad_key = true;
13707 else
81c4b26b 13708 no = nt->named_object();
e440a328 13709 }
13710 break;
13711
13712 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13713 no = name_expr->var_expression()->named_object();
e440a328 13714 break;
13715
b0c09712 13716 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13717 no = name_expr->enclosed_var_expression()->variable();
e440a328 13718 break;
13719
b0c09712 13720 case EXPRESSION_FUNC_REFERENCE:
13721 no = name_expr->func_expression()->named_object();
e440a328 13722 break;
13723
13724 default:
13725 bad_key = true;
13726 break;
13727 }
13728 if (bad_key)
13729 {
631d5788 13730 go_error_at(name_expr->location(), "expected struct field name");
e440a328 13731 return Expression::make_error(location);
13732 }
13733
81c4b26b 13734 if (no != NULL)
13735 {
62750cd5 13736 if (no->package() != NULL && external_expr == NULL)
13737 {
13738 external_expr = name_expr;
13739 external_no = no;
13740 }
13741
81c4b26b 13742 name = no->name();
13743
13744 // A predefined name won't be packed. If it starts with a
13745 // lower case letter we need to check for that case, because
2d29d278 13746 // the field name will be packed. FIXME.
81c4b26b 13747 if (!Gogo::is_hidden_name(name)
13748 && name[0] >= 'a'
13749 && name[0] <= 'z')
13750 {
13751 Named_object* gno = gogo->lookup_global(name.c_str());
13752 if (gno == no)
13753 name = gogo->pack_hidden_name(name, false);
13754 }
13755 }
13756
e440a328 13757 unsigned int index;
13758 const Struct_field* sf = st->find_local_field(name, &index);
13759 if (sf == NULL)
13760 {
631d5788 13761 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13762 Gogo::message_name(name).c_str(),
13763 (type->named_type() != NULL
13764 ? type->named_type()->message_name().c_str()
13765 : "unnamed struct"));
e440a328 13766 return Expression::make_error(location);
13767 }
13768 if (vals[index] != NULL)
13769 {
631d5788 13770 go_error_at(name_expr->location(),
13771 "duplicate value for field %qs in %qs",
13772 Gogo::message_name(name).c_str(),
13773 (type->named_type() != NULL
13774 ? type->named_type()->message_name().c_str()
13775 : "unnamed struct"));
e440a328 13776 return Expression::make_error(location);
13777 }
13778
07daa4e7 13779 if (type->named_type() != NULL
13780 && type->named_type()->named_object()->package() != NULL
07ba7f26 13781 && (Gogo::is_hidden_name(sf->field_name())
13782 || sf->is_embedded_builtin(gogo)))
631d5788 13783 go_error_at(name_expr->location(),
13784 "assignment of unexported field %qs in %qs literal",
13785 Gogo::message_name(sf->field_name()).c_str(),
13786 type->named_type()->message_name().c_str());
07daa4e7 13787
e440a328 13788 vals[index] = val;
e32de7ba 13789 traverse_order->push_back(static_cast<unsigned long>(index));
e440a328 13790 }
13791
62750cd5 13792 if (!this->all_are_names_)
13793 {
13794 // This is a weird case like bug462 in the testsuite.
13795 if (external_expr == NULL)
631d5788 13796 go_error_at(this->location(), "unknown field in %qs literal",
13797 (type->named_type() != NULL
13798 ? type->named_type()->message_name().c_str()
13799 : "unnamed struct"));
62750cd5 13800 else
631d5788 13801 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13802 external_no->message_name().c_str(),
13803 (type->named_type() != NULL
13804 ? type->named_type()->message_name().c_str()
13805 : "unnamed struct"));
62750cd5 13806 return Expression::make_error(location);
13807 }
13808
e440a328 13809 Expression_list* list = new Expression_list;
13810 list->reserve(field_count);
13811 for (size_t i = 0; i < field_count; ++i)
13812 list->push_back(vals[i]);
13813
0c4f5a19 13814 Struct_construction_expression* ret =
13815 new Struct_construction_expression(type, list, location);
13816 ret->set_traverse_order(traverse_order);
13817 return ret;
e440a328 13818}
13819
e32de7ba 13820// Index/value/traversal-order triple.
00773463 13821
e32de7ba 13822struct IVT_triple {
13823 unsigned long index;
13824 unsigned long traversal_order;
13825 Expression* expr;
13826 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13827 : index(i), traversal_order(to), expr(e) { }
13828 bool operator<(const IVT_triple& other) const
13829 { return this->index < other.index; }
00773463 13830};
13831
e440a328 13832// Lower an array composite literal.
13833
13834Expression*
113ef6a5 13835Composite_literal_expression::lower_array(Type* type)
e440a328 13836{
b13c66cd 13837 Location location = this->location();
e440a328 13838 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13839 return this->make_array(type, NULL, this->vals_);
e440a328 13840
ffe743ca 13841 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13842 indexes->reserve(this->vals_->size());
00773463 13843 bool indexes_out_of_order = false;
ffe743ca 13844 Expression_list* vals = new Expression_list();
13845 vals->reserve(this->vals_->size());
e440a328 13846 unsigned long index = 0;
13847 Expression_list::const_iterator p = this->vals_->begin();
13848 while (p != this->vals_->end())
13849 {
13850 Expression* index_expr = *p;
13851
13852 ++p;
c484d925 13853 go_assert(p != this->vals_->end());
e440a328 13854 Expression* val = *p;
13855
13856 ++p;
13857
ffe743ca 13858 if (index_expr == NULL)
13859 {
13860 if (!indexes->empty())
13861 indexes->push_back(index);
13862 }
13863 else
e440a328 13864 {
ffe743ca 13865 if (indexes->empty() && !vals->empty())
13866 {
13867 for (size_t i = 0; i < vals->size(); ++i)
13868 indexes->push_back(i);
13869 }
13870
0c77715b 13871 Numeric_constant nc;
13872 if (!index_expr->numeric_constant_value(&nc))
e440a328 13873 {
631d5788 13874 go_error_at(index_expr->location(),
13875 "index expression is not integer constant");
e440a328 13876 return Expression::make_error(location);
13877 }
6f6d9955 13878
0c77715b 13879 switch (nc.to_unsigned_long(&index))
e440a328 13880 {
0c77715b 13881 case Numeric_constant::NC_UL_VALID:
13882 break;
13883 case Numeric_constant::NC_UL_NOTINT:
631d5788 13884 go_error_at(index_expr->location(),
13885 "index expression is not integer constant");
0c77715b 13886 return Expression::make_error(location);
13887 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 13888 go_error_at(index_expr->location(),
13889 "index expression is negative");
e440a328 13890 return Expression::make_error(location);
0c77715b 13891 case Numeric_constant::NC_UL_BIG:
631d5788 13892 go_error_at(index_expr->location(), "index value overflow");
e440a328 13893 return Expression::make_error(location);
0c77715b 13894 default:
13895 go_unreachable();
e440a328 13896 }
6f6d9955 13897
13898 Named_type* ntype = Type::lookup_integer_type("int");
13899 Integer_type* inttype = ntype->integer_type();
0c77715b 13900 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13901 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13902 {
631d5788 13903 go_error_at(index_expr->location(), "index value overflow");
6f6d9955 13904 return Expression::make_error(location);
13905 }
13906
ffe743ca 13907 if (std::find(indexes->begin(), indexes->end(), index)
13908 != indexes->end())
e440a328 13909 {
631d5788 13910 go_error_at(index_expr->location(),
13911 "duplicate value for index %lu",
13912 index);
e440a328 13913 return Expression::make_error(location);
13914 }
ffe743ca 13915
00773463 13916 if (!indexes->empty() && index < indexes->back())
13917 indexes_out_of_order = true;
13918
ffe743ca 13919 indexes->push_back(index);
e440a328 13920 }
13921
ffe743ca 13922 vals->push_back(val);
13923
e440a328 13924 ++index;
13925 }
13926
ffe743ca 13927 if (indexes->empty())
13928 {
13929 delete indexes;
13930 indexes = NULL;
13931 }
e440a328 13932
e32de7ba 13933 std::vector<unsigned long>* traverse_order = NULL;
00773463 13934 if (indexes_out_of_order)
13935 {
e32de7ba 13936 typedef std::vector<IVT_triple> V;
00773463 13937
13938 V v;
13939 v.reserve(indexes->size());
13940 std::vector<unsigned long>::const_iterator pi = indexes->begin();
e32de7ba 13941 unsigned long torder = 0;
00773463 13942 for (Expression_list::const_iterator pe = vals->begin();
13943 pe != vals->end();
e32de7ba 13944 ++pe, ++pi, ++torder)
13945 v.push_back(IVT_triple(*pi, torder, *pe));
00773463 13946
e32de7ba 13947 std::sort(v.begin(), v.end());
00773463 13948
13949 delete indexes;
13950 delete vals;
e32de7ba 13951
00773463 13952 indexes = new std::vector<unsigned long>();
13953 indexes->reserve(v.size());
13954 vals = new Expression_list();
13955 vals->reserve(v.size());
e32de7ba 13956 traverse_order = new std::vector<unsigned long>();
13957 traverse_order->reserve(v.size());
00773463 13958
13959 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13960 {
e32de7ba 13961 indexes->push_back(p->index);
13962 vals->push_back(p->expr);
13963 traverse_order->push_back(p->traversal_order);
00773463 13964 }
13965 }
13966
e32de7ba 13967 Expression* ret = this->make_array(type, indexes, vals);
13968 Array_construction_expression* ace = ret->array_literal();
13969 if (ace != NULL && traverse_order != NULL)
13970 ace->set_traverse_order(traverse_order);
13971 return ret;
e440a328 13972}
13973
13974// Actually build the array composite literal. This handles
13975// [...]{...}.
13976
13977Expression*
ffe743ca 13978Composite_literal_expression::make_array(
13979 Type* type,
13980 const std::vector<unsigned long>* indexes,
13981 Expression_list* vals)
e440a328 13982{
b13c66cd 13983 Location location = this->location();
e440a328 13984 Array_type* at = type->array_type();
ffe743ca 13985
e440a328 13986 if (at->length() != NULL && at->length()->is_nil_expression())
13987 {
ffe743ca 13988 size_t size;
13989 if (vals == NULL)
13990 size = 0;
00773463 13991 else if (indexes != NULL)
13992 size = indexes->back() + 1;
13993 else
ffe743ca 13994 {
13995 size = vals->size();
13996 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13997 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13998 && size >> (it->bits() - 1) != 0)
13999 {
631d5788 14000 go_error_at(location, "too many elements in composite literal");
ffe743ca 14001 return Expression::make_error(location);
14002 }
14003 }
ffe743ca 14004
e67508fa 14005 Expression* elen = Expression::make_integer_ul(size, NULL, location);
e440a328 14006 at = Type::make_array_type(at->element_type(), elen);
14007 type = at;
14008 }
ffe743ca 14009 else if (at->length() != NULL
14010 && !at->length()->is_error_expression()
14011 && this->vals_ != NULL)
14012 {
14013 Numeric_constant nc;
14014 unsigned long val;
14015 if (at->length()->numeric_constant_value(&nc)
14016 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
14017 {
14018 if (indexes == NULL)
14019 {
14020 if (this->vals_->size() > val)
14021 {
631d5788 14022 go_error_at(location,
14023 "too many elements in composite literal");
ffe743ca 14024 return Expression::make_error(location);
14025 }
14026 }
14027 else
14028 {
00773463 14029 unsigned long max = indexes->back();
ffe743ca 14030 if (max >= val)
14031 {
631d5788 14032 go_error_at(location,
14033 ("some element keys in composite literal "
14034 "are out of range"));
ffe743ca 14035 return Expression::make_error(location);
14036 }
14037 }
14038 }
14039 }
14040
e440a328 14041 if (at->length() != NULL)
ffe743ca 14042 return new Fixed_array_construction_expression(type, indexes, vals,
14043 location);
e440a328 14044 else
2c809f8f 14045 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 14046}
14047
14048// Lower a map composite literal.
14049
14050Expression*
a287720d 14051Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 14052 Statement_inserter* inserter,
a287720d 14053 Type* type)
e440a328 14054{
b13c66cd 14055 Location location = this->location();
e440a328 14056 if (this->vals_ != NULL)
14057 {
14058 if (!this->has_keys_)
14059 {
631d5788 14060 go_error_at(location, "map composite literal must have keys");
e440a328 14061 return Expression::make_error(location);
14062 }
14063
a287720d 14064 for (Expression_list::iterator p = this->vals_->begin();
e440a328 14065 p != this->vals_->end();
14066 p += 2)
14067 {
14068 if (*p == NULL)
14069 {
14070 ++p;
631d5788 14071 go_error_at((*p)->location(),
14072 ("map composite literal must "
14073 "have keys for every value"));
e440a328 14074 return Expression::make_error(location);
14075 }
a287720d 14076 // Make sure we have lowered the key; it may not have been
14077 // lowered in order to handle keys for struct composite
14078 // literals. Lower it now to get the right error message.
14079 if ((*p)->unknown_expression() != NULL)
14080 {
14081 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 14082 gogo->lower_expression(function, inserter, &*p);
c484d925 14083 go_assert((*p)->is_error_expression());
a287720d 14084 return Expression::make_error(location);
14085 }
e440a328 14086 }
14087 }
14088
14089 return new Map_construction_expression(type, this->vals_, location);
14090}
14091
d751bb78 14092// Dump ast representation for a composite literal expression.
14093
14094void
14095Composite_literal_expression::do_dump_expression(
14096 Ast_dump_context* ast_dump_context) const
14097{
8b1c301d 14098 ast_dump_context->ostream() << "composite(";
d751bb78 14099 ast_dump_context->dump_type(this->type_);
14100 ast_dump_context->ostream() << ", {";
8b1c301d 14101 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 14102 ast_dump_context->ostream() << "})";
14103}
14104
e440a328 14105// Make a composite literal expression.
14106
14107Expression*
14108Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 14109 Expression_list* vals, bool all_are_names,
b13c66cd 14110 Location location)
e440a328 14111{
14112 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 14113 all_are_names, location);
e440a328 14114}
14115
14116// Return whether this expression is a composite literal.
14117
14118bool
14119Expression::is_composite_literal() const
14120{
14121 switch (this->classification_)
14122 {
14123 case EXPRESSION_COMPOSITE_LITERAL:
14124 case EXPRESSION_STRUCT_CONSTRUCTION:
14125 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 14126 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 14127 case EXPRESSION_MAP_CONSTRUCTION:
14128 return true;
14129 default:
14130 return false;
14131 }
14132}
14133
14134// Return whether this expression is a composite literal which is not
14135// constant.
14136
14137bool
14138Expression::is_nonconstant_composite_literal() const
14139{
14140 switch (this->classification_)
14141 {
14142 case EXPRESSION_STRUCT_CONSTRUCTION:
14143 {
14144 const Struct_construction_expression *psce =
14145 static_cast<const Struct_construction_expression*>(this);
14146 return !psce->is_constant_struct();
14147 }
14148 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14149 {
14150 const Fixed_array_construction_expression *pace =
14151 static_cast<const Fixed_array_construction_expression*>(this);
14152 return !pace->is_constant_array();
14153 }
2c809f8f 14154 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 14155 {
2c809f8f 14156 const Slice_construction_expression *pace =
14157 static_cast<const Slice_construction_expression*>(this);
e440a328 14158 return !pace->is_constant_array();
14159 }
14160 case EXPRESSION_MAP_CONSTRUCTION:
14161 return true;
14162 default:
14163 return false;
14164 }
14165}
14166
35a54f17 14167// Return true if this is a variable or temporary_variable.
14168
14169bool
14170Expression::is_variable() const
14171{
14172 switch (this->classification_)
14173 {
14174 case EXPRESSION_VAR_REFERENCE:
14175 case EXPRESSION_TEMPORARY_REFERENCE:
14176 case EXPRESSION_SET_AND_USE_TEMPORARY:
b0c09712 14177 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
35a54f17 14178 return true;
14179 default:
14180 return false;
14181 }
14182}
14183
e440a328 14184// Return true if this is a reference to a local variable.
14185
14186bool
14187Expression::is_local_variable() const
14188{
14189 const Var_expression* ve = this->var_expression();
14190 if (ve == NULL)
14191 return false;
14192 const Named_object* no = ve->named_object();
14193 return (no->is_result_variable()
14194 || (no->is_variable() && !no->var_value()->is_global()));
14195}
14196
14197// Class Type_guard_expression.
14198
14199// Traversal.
14200
14201int
14202Type_guard_expression::do_traverse(Traverse* traverse)
14203{
14204 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14205 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14206 return TRAVERSE_EXIT;
14207 return TRAVERSE_CONTINUE;
14208}
14209
2c809f8f 14210Expression*
14211Type_guard_expression::do_flatten(Gogo*, Named_object*,
14212 Statement_inserter* inserter)
14213{
5bf8be8b 14214 if (this->expr_->is_error_expression()
14215 || this->expr_->type()->is_error_type())
14216 {
14217 go_assert(saw_errors());
14218 return Expression::make_error(this->location());
14219 }
14220
2c809f8f 14221 if (!this->expr_->is_variable())
14222 {
14223 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14224 this->location());
14225 inserter->insert(temp);
14226 this->expr_ =
14227 Expression::make_temporary_reference(temp, this->location());
14228 }
14229 return this;
14230}
14231
e440a328 14232// Check types of a type guard expression. The expression must have
14233// an interface type, but the actual type conversion is checked at run
14234// time.
14235
14236void
14237Type_guard_expression::do_check_types(Gogo*)
14238{
e440a328 14239 Type* expr_type = this->expr_->type();
7e9da23f 14240 if (expr_type->interface_type() == NULL)
f725ade8 14241 {
5c13bd80 14242 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 14243 this->report_error(_("type assertion only valid for interface types"));
14244 this->set_is_error();
14245 }
e440a328 14246 else if (this->type_->interface_type() == NULL)
14247 {
14248 std::string reason;
14249 if (!expr_type->interface_type()->implements_interface(this->type_,
14250 &reason))
14251 {
5c13bd80 14252 if (!this->type_->is_error())
e440a328 14253 {
f725ade8 14254 if (reason.empty())
14255 this->report_error(_("impossible type assertion: "
14256 "type does not implement interface"));
14257 else
631d5788 14258 go_error_at(this->location(),
14259 ("impossible type assertion: "
14260 "type does not implement interface (%s)"),
14261 reason.c_str());
e440a328 14262 }
f725ade8 14263 this->set_is_error();
e440a328 14264 }
14265 }
14266}
14267
ea664253 14268// Return the backend representation for a type guard expression.
e440a328 14269
ea664253 14270Bexpression*
14271Type_guard_expression::do_get_backend(Translate_context* context)
e440a328 14272{
2c809f8f 14273 Expression* conversion;
7e9da23f 14274 if (this->type_->interface_type() != NULL)
2c809f8f 14275 conversion =
14276 Expression::convert_interface_to_interface(this->type_, this->expr_,
14277 true, this->location());
e440a328 14278 else
2c809f8f 14279 conversion =
14280 Expression::convert_for_assignment(context->gogo(), this->type_,
14281 this->expr_, this->location());
14282
ea664253 14283 return conversion->get_backend(context);
e440a328 14284}
14285
d751bb78 14286// Dump ast representation for a type guard expression.
14287
14288void
2c809f8f 14289Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 14290 const
14291{
14292 this->expr_->dump_expression(ast_dump_context);
14293 ast_dump_context->ostream() << ".";
14294 ast_dump_context->dump_type(this->type_);
14295}
14296
e440a328 14297// Make a type guard expression.
14298
14299Expression*
14300Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 14301 Location location)
e440a328 14302{
14303 return new Type_guard_expression(expr, type, location);
14304}
14305
2c809f8f 14306// Class Heap_expression.
e440a328 14307
da244e59 14308// Return the type of the expression stored on the heap.
e440a328 14309
da244e59 14310Type*
14311Heap_expression::do_type()
14312{ return Type::make_pointer_type(this->expr_->type()); }
e440a328 14313
ea664253 14314// Return the backend representation for allocating an expression on the heap.
e440a328 14315
ea664253 14316Bexpression*
14317Heap_expression::do_get_backend(Translate_context* context)
e440a328 14318{
03118c21 14319 Type* etype = this->expr_->type();
14320 if (this->expr_->is_error_expression() || etype->is_error())
ea664253 14321 return context->backend()->error_expression();
2c809f8f 14322
02c19a1a 14323 Location loc = this->location();
2c809f8f 14324 Gogo* gogo = context->gogo();
02c19a1a 14325 Btype* btype = this->type()->get_backend(gogo);
45ff893b 14326
03118c21 14327 Expression* alloc = Expression::make_allocation(etype, loc);
45ff893b 14328 Node* n = Node::make_node(this);
14329 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
14330 alloc->allocation_expression()->set_allocate_on_stack();
14331 Bexpression* space = alloc->get_backend(context);
02c19a1a 14332
14333 Bstatement* decl;
14334 Named_object* fn = context->function();
14335 go_assert(fn != NULL);
14336 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14337 Bvariable* space_temp =
14338 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14339 space, true, loc, &decl);
03118c21 14340 Btype* expr_btype = etype->get_backend(gogo);
02c19a1a 14341
ea664253 14342 Bexpression* bexpr = this->expr_->get_backend(context);
03118c21 14343
14344 // If this assignment needs a write barrier, call typedmemmove. We
14345 // don't do this in the write barrier pass because in some cases
14346 // backend conversion can introduce new Heap_expression values.
14347 Bstatement* assn;
14348 if (!etype->has_pointer())
14349 {
14350 space = gogo->backend()->var_expression(space_temp, VE_lvalue, loc);
14351 Bexpression* ref =
14352 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14353 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14354 }
14355 else
14356 {
14357 Bstatement* edecl;
14358 Bvariable* btemp =
14359 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14360 expr_btype, bexpr, true, loc,
14361 &edecl);
14362 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14363 VE_lvalue, loc);
14364 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14365
14366 Expression* td = Expression::make_type_descriptor(etype, loc);
14367 Type* etype_ptr = Type::make_pointer_type(etype);
14368 space = gogo->backend()->var_expression(space_temp, VE_rvalue, loc);
14369 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14370 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14371 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14372 td, elhs, erhs);
14373 Bexpression* bcall = call->get_backend(context);
14374 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14375 assn = gogo->backend()->compound_statement(edecl, s);
14376 }
02c19a1a 14377 decl = gogo->backend()->compound_statement(decl, assn);
d4e6573e 14378 space = gogo->backend()->var_expression(space_temp, VE_rvalue, loc);
ea664253 14379 return gogo->backend()->compound_expression(decl, space, loc);
e440a328 14380}
14381
2c809f8f 14382// Dump ast representation for a heap expression.
d751bb78 14383
14384void
2c809f8f 14385Heap_expression::do_dump_expression(
d751bb78 14386 Ast_dump_context* ast_dump_context) const
14387{
14388 ast_dump_context->ostream() << "&(";
14389 ast_dump_context->dump_expression(this->expr_);
14390 ast_dump_context->ostream() << ")";
14391}
14392
2c809f8f 14393// Allocate an expression on the heap.
e440a328 14394
14395Expression*
2c809f8f 14396Expression::make_heap_expression(Expression* expr, Location location)
e440a328 14397{
2c809f8f 14398 return new Heap_expression(expr, location);
e440a328 14399}
14400
14401// Class Receive_expression.
14402
14403// Return the type of a receive expression.
14404
14405Type*
14406Receive_expression::do_type()
14407{
e429e3bd 14408 if (this->is_error_expression())
14409 return Type::make_error_type();
e440a328 14410 Channel_type* channel_type = this->channel_->type()->channel_type();
14411 if (channel_type == NULL)
e429e3bd 14412 {
14413 this->report_error(_("expected channel"));
14414 return Type::make_error_type();
14415 }
e440a328 14416 return channel_type->element_type();
14417}
14418
14419// Check types for a receive expression.
14420
14421void
14422Receive_expression::do_check_types(Gogo*)
14423{
14424 Type* type = this->channel_->type();
5c13bd80 14425 if (type->is_error())
e440a328 14426 {
e429e3bd 14427 go_assert(saw_errors());
e440a328 14428 this->set_is_error();
14429 return;
14430 }
14431 if (type->channel_type() == NULL)
14432 {
14433 this->report_error(_("expected channel"));
14434 return;
14435 }
14436 if (!type->channel_type()->may_receive())
14437 {
14438 this->report_error(_("invalid receive on send-only channel"));
14439 return;
14440 }
14441}
14442
2c809f8f 14443// Flattening for receive expressions creates a temporary variable to store
14444// received data in for receives.
14445
14446Expression*
14447Receive_expression::do_flatten(Gogo*, Named_object*,
14448 Statement_inserter* inserter)
14449{
14450 Channel_type* channel_type = this->channel_->type()->channel_type();
14451 if (channel_type == NULL)
14452 {
14453 go_assert(saw_errors());
14454 return this;
14455 }
5bf8be8b 14456 else if (this->channel_->is_error_expression())
14457 {
14458 go_assert(saw_errors());
14459 return Expression::make_error(this->location());
14460 }
2c809f8f 14461
14462 Type* element_type = channel_type->element_type();
14463 if (this->temp_receiver_ == NULL)
14464 {
14465 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14466 this->location());
14467 this->temp_receiver_->set_is_address_taken();
14468 inserter->insert(this->temp_receiver_);
14469 }
14470
14471 return this;
14472}
14473
ea664253 14474// Get the backend representation for a receive expression.
e440a328 14475
ea664253 14476Bexpression*
14477Receive_expression::do_get_backend(Translate_context* context)
e440a328 14478{
f24f10bb 14479 Location loc = this->location();
14480
e440a328 14481 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 14482 if (channel_type == NULL)
14483 {
c484d925 14484 go_assert(this->channel_->type()->is_error());
ea664253 14485 return context->backend()->error_expression();
5b8368f4 14486 }
f24f10bb 14487 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 14488
2c809f8f 14489 Expression* recv_ref =
14490 Expression::make_temporary_reference(this->temp_receiver_, loc);
14491 Expression* recv_addr =
14492 Expression::make_temporary_reference(this->temp_receiver_, loc);
14493 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
132ed071 14494 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 3,
14495 td, this->channel_, recv_addr);
ea664253 14496 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
e440a328 14497}
14498
d751bb78 14499// Dump ast representation for a receive expression.
14500
14501void
14502Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14503{
14504 ast_dump_context->ostream() << " <- " ;
14505 ast_dump_context->dump_expression(channel_);
14506}
14507
e440a328 14508// Make a receive expression.
14509
14510Receive_expression*
b13c66cd 14511Expression::make_receive(Expression* channel, Location location)
e440a328 14512{
14513 return new Receive_expression(channel, location);
14514}
14515
e440a328 14516// An expression which evaluates to a pointer to the type descriptor
14517// of a type.
14518
14519class Type_descriptor_expression : public Expression
14520{
14521 public:
b13c66cd 14522 Type_descriptor_expression(Type* type, Location location)
e440a328 14523 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14524 type_(type)
14525 { }
14526
14527 protected:
4b686186 14528 int
14529 do_traverse(Traverse*);
14530
e440a328 14531 Type*
14532 do_type()
14533 { return Type::make_type_descriptor_ptr_type(); }
14534
f9ca30f9 14535 bool
3ae06f68 14536 do_is_static_initializer() const
f9ca30f9 14537 { return true; }
14538
e440a328 14539 void
14540 do_determine_type(const Type_context*)
14541 { }
14542
14543 Expression*
14544 do_copy()
14545 { return this; }
14546
ea664253 14547 Bexpression*
14548 do_get_backend(Translate_context* context)
a1d23b41 14549 {
ea664253 14550 return this->type_->type_descriptor_pointer(context->gogo(),
14551 this->location());
a1d23b41 14552 }
e440a328 14553
d751bb78 14554 void
14555 do_dump_expression(Ast_dump_context*) const;
14556
e440a328 14557 private:
14558 // The type for which this is the descriptor.
14559 Type* type_;
14560};
14561
4b686186 14562int
14563Type_descriptor_expression::do_traverse(Traverse* traverse)
14564{
14565 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14566 return TRAVERSE_EXIT;
14567 return TRAVERSE_CONTINUE;
14568}
14569
d751bb78 14570// Dump ast representation for a type descriptor expression.
14571
14572void
14573Type_descriptor_expression::do_dump_expression(
14574 Ast_dump_context* ast_dump_context) const
14575{
14576 ast_dump_context->dump_type(this->type_);
14577}
14578
e440a328 14579// Make a type descriptor expression.
14580
14581Expression*
b13c66cd 14582Expression::make_type_descriptor(Type* type, Location location)
e440a328 14583{
14584 return new Type_descriptor_expression(type, location);
14585}
14586
aa5ae575 14587// An expression which evaluates to a pointer to the Garbage Collection symbol
14588// of a type.
14589
14590class GC_symbol_expression : public Expression
14591{
14592 public:
14593 GC_symbol_expression(Type* type)
14594 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14595 type_(type)
14596 {}
14597
14598 protected:
14599 Type*
14600 do_type()
03118c21 14601 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
aa5ae575 14602
14603 bool
3ae06f68 14604 do_is_static_initializer() const
aa5ae575 14605 { return true; }
14606
14607 void
14608 do_determine_type(const Type_context*)
14609 { }
14610
14611 Expression*
14612 do_copy()
14613 { return this; }
14614
14615 Bexpression*
14616 do_get_backend(Translate_context* context)
14617 { return this->type_->gc_symbol_pointer(context->gogo()); }
14618
14619 void
14620 do_dump_expression(Ast_dump_context*) const;
14621
14622 private:
14623 // The type which this gc symbol describes.
14624 Type* type_;
14625};
14626
14627// Dump ast representation for a gc symbol expression.
14628
14629void
14630GC_symbol_expression::do_dump_expression(
14631 Ast_dump_context* ast_dump_context) const
14632{
14633 ast_dump_context->ostream() << "gcdata(";
14634 ast_dump_context->dump_type(this->type_);
14635 ast_dump_context->ostream() << ")";
14636}
14637
14638// Make a gc symbol expression.
14639
14640Expression*
14641Expression::make_gc_symbol(Type* type)
14642{
14643 return new GC_symbol_expression(type);
14644}
14645
03118c21 14646// An expression that evaluates to a pointer to a symbol holding the
14647// ptrmask data of a type.
14648
14649class Ptrmask_symbol_expression : public Expression
14650{
14651 public:
14652 Ptrmask_symbol_expression(Type* type)
14653 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
14654 type_(type)
14655 {}
14656
14657 protected:
14658 Type*
14659 do_type()
14660 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
14661
14662 bool
14663 do_is_static_initializer() const
14664 { return true; }
14665
14666 void
14667 do_determine_type(const Type_context*)
14668 { }
14669
14670 Expression*
14671 do_copy()
14672 { return this; }
14673
14674 Bexpression*
14675 do_get_backend(Translate_context*);
14676
14677 void
14678 do_dump_expression(Ast_dump_context*) const;
14679
14680 private:
14681 // The type that this ptrmask symbol describes.
14682 Type* type_;
14683};
14684
14685// Return the ptrmask variable.
14686
14687Bexpression*
14688Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
14689{
14690 Gogo* gogo = context->gogo();
14691
14692 // If this type does not need a gcprog, then we can use the standard
14693 // GC symbol.
14694 int64_t ptrsize, ptrdata;
14695 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
14696 return this->type_->gc_symbol_pointer(gogo);
14697
14698 // Otherwise we have to build a ptrmask variable, and return a
14699 // pointer to it.
14700
14701 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
14702 Location bloc = Linemap::predeclared_location();
14703 Bexpression* bref = gogo->backend()->var_expression(bvar, VE_rvalue, bloc);
14704 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
14705
14706 Type* uint8_type = Type::lookup_integer_type("uint8");
14707 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
14708 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
14709 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
14710}
14711
14712// Dump AST for a ptrmask symbol expression.
14713
14714void
14715Ptrmask_symbol_expression::do_dump_expression(
14716 Ast_dump_context* ast_dump_context) const
14717{
14718 ast_dump_context->ostream() << "ptrmask(";
14719 ast_dump_context->dump_type(this->type_);
14720 ast_dump_context->ostream() << ")";
14721}
14722
14723// Make a ptrmask symbol expression.
14724
14725Expression*
14726Expression::make_ptrmask_symbol(Type* type)
14727{
14728 return new Ptrmask_symbol_expression(type);
14729}
14730
e440a328 14731// An expression which evaluates to some characteristic of a type.
14732// This is only used to initialize fields of a type descriptor. Using
14733// a new expression class is slightly inefficient but gives us a good
14734// separation between the frontend and the middle-end with regard to
14735// how types are laid out.
14736
14737class Type_info_expression : public Expression
14738{
14739 public:
14740 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 14741 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 14742 type_(type), type_info_(type_info)
14743 { }
14744
14745 protected:
0e168074 14746 bool
3ae06f68 14747 do_is_static_initializer() const
0e168074 14748 { return true; }
14749
e440a328 14750 Type*
14751 do_type();
14752
14753 void
14754 do_determine_type(const Type_context*)
14755 { }
14756
14757 Expression*
14758 do_copy()
14759 { return this; }
14760
ea664253 14761 Bexpression*
14762 do_get_backend(Translate_context* context);
e440a328 14763
d751bb78 14764 void
14765 do_dump_expression(Ast_dump_context*) const;
14766
e440a328 14767 private:
14768 // The type for which we are getting information.
14769 Type* type_;
14770 // What information we want.
14771 Type_info type_info_;
14772};
14773
14774// The type is chosen to match what the type descriptor struct
14775// expects.
14776
14777Type*
14778Type_info_expression::do_type()
14779{
14780 switch (this->type_info_)
14781 {
14782 case TYPE_INFO_SIZE:
03118c21 14783 case TYPE_INFO_BACKEND_PTRDATA:
14784 case TYPE_INFO_DESCRIPTOR_PTRDATA:
e440a328 14785 return Type::lookup_integer_type("uintptr");
14786 case TYPE_INFO_ALIGNMENT:
14787 case TYPE_INFO_FIELD_ALIGNMENT:
14788 return Type::lookup_integer_type("uint8");
14789 default:
c3e6f413 14790 go_unreachable();
e440a328 14791 }
14792}
14793
ea664253 14794// Return the backend representation for type information.
e440a328 14795
ea664253 14796Bexpression*
14797Type_info_expression::do_get_backend(Translate_context* context)
e440a328 14798{
927a01eb 14799 Gogo* gogo = context->gogo();
2a305b85 14800 bool ok = true;
3f378015 14801 int64_t val;
927a01eb 14802 switch (this->type_info_)
e440a328 14803 {
927a01eb 14804 case TYPE_INFO_SIZE:
2a305b85 14805 ok = this->type_->backend_type_size(gogo, &val);
927a01eb 14806 break;
14807 case TYPE_INFO_ALIGNMENT:
2a305b85 14808 ok = this->type_->backend_type_align(gogo, &val);
927a01eb 14809 break;
14810 case TYPE_INFO_FIELD_ALIGNMENT:
2a305b85 14811 ok = this->type_->backend_type_field_align(gogo, &val);
927a01eb 14812 break;
03118c21 14813 case TYPE_INFO_BACKEND_PTRDATA:
14814 ok = this->type_->backend_type_ptrdata(gogo, &val);
14815 break;
14816 case TYPE_INFO_DESCRIPTOR_PTRDATA:
14817 ok = this->type_->descriptor_ptrdata(gogo, &val);
14818 break;
927a01eb 14819 default:
14820 go_unreachable();
e440a328 14821 }
2a305b85 14822 if (!ok)
14823 {
14824 go_assert(saw_errors());
14825 return gogo->backend()->error_expression();
14826 }
3f378015 14827 Expression* e = Expression::make_integer_int64(val, this->type(),
14828 this->location());
14829 return e->get_backend(context);
e440a328 14830}
14831
d751bb78 14832// Dump ast representation for a type info expression.
14833
14834void
14835Type_info_expression::do_dump_expression(
14836 Ast_dump_context* ast_dump_context) const
14837{
14838 ast_dump_context->ostream() << "typeinfo(";
14839 ast_dump_context->dump_type(this->type_);
14840 ast_dump_context->ostream() << ",";
14841 ast_dump_context->ostream() <<
14842 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14843 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
03118c21 14844 : this->type_info_ == TYPE_INFO_SIZE ? "size"
14845 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
14846 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
d751bb78 14847 : "unknown");
14848 ast_dump_context->ostream() << ")";
14849}
14850
e440a328 14851// Make a type info expression.
14852
14853Expression*
14854Expression::make_type_info(Type* type, Type_info type_info)
14855{
14856 return new Type_info_expression(type, type_info);
14857}
14858
35a54f17 14859// An expression that evaluates to some characteristic of a slice.
14860// This is used when indexing, bound-checking, or nil checking a slice.
14861
14862class Slice_info_expression : public Expression
14863{
14864 public:
14865 Slice_info_expression(Expression* slice, Slice_info slice_info,
14866 Location location)
14867 : Expression(EXPRESSION_SLICE_INFO, location),
14868 slice_(slice), slice_info_(slice_info)
14869 { }
14870
14871 protected:
14872 Type*
14873 do_type();
14874
14875 void
14876 do_determine_type(const Type_context*)
14877 { }
14878
14879 Expression*
14880 do_copy()
14881 {
14882 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14883 this->location());
14884 }
14885
ea664253 14886 Bexpression*
14887 do_get_backend(Translate_context* context);
35a54f17 14888
14889 void
14890 do_dump_expression(Ast_dump_context*) const;
14891
14892 void
14893 do_issue_nil_check()
14894 { this->slice_->issue_nil_check(); }
14895
14896 private:
14897 // The slice for which we are getting information.
14898 Expression* slice_;
14899 // What information we want.
14900 Slice_info slice_info_;
14901};
14902
14903// Return the type of the slice info.
14904
14905Type*
14906Slice_info_expression::do_type()
14907{
14908 switch (this->slice_info_)
14909 {
14910 case SLICE_INFO_VALUE_POINTER:
14911 return Type::make_pointer_type(
14912 this->slice_->type()->array_type()->element_type());
14913 case SLICE_INFO_LENGTH:
14914 case SLICE_INFO_CAPACITY:
14915 return Type::lookup_integer_type("int");
14916 default:
14917 go_unreachable();
14918 }
14919}
14920
ea664253 14921// Return the backend information for slice information.
35a54f17 14922
ea664253 14923Bexpression*
14924Slice_info_expression::do_get_backend(Translate_context* context)
35a54f17 14925{
14926 Gogo* gogo = context->gogo();
ea664253 14927 Bexpression* bslice = this->slice_->get_backend(context);
35a54f17 14928 switch (this->slice_info_)
14929 {
14930 case SLICE_INFO_VALUE_POINTER:
14931 case SLICE_INFO_LENGTH:
14932 case SLICE_INFO_CAPACITY:
ea664253 14933 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14934 this->location());
35a54f17 14935 break;
14936 default:
14937 go_unreachable();
14938 }
35a54f17 14939}
14940
14941// Dump ast representation for a type info expression.
14942
14943void
14944Slice_info_expression::do_dump_expression(
14945 Ast_dump_context* ast_dump_context) const
14946{
14947 ast_dump_context->ostream() << "sliceinfo(";
14948 this->slice_->dump_expression(ast_dump_context);
14949 ast_dump_context->ostream() << ",";
14950 ast_dump_context->ostream() <<
14951 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14952 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14953 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14954 : "unknown");
14955 ast_dump_context->ostream() << ")";
14956}
14957
14958// Make a slice info expression.
14959
14960Expression*
14961Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14962 Location location)
14963{
14964 return new Slice_info_expression(slice, slice_info, location);
14965}
14966
2c809f8f 14967// An expression that represents a slice value: a struct with value pointer,
14968// length, and capacity fields.
14969
14970class Slice_value_expression : public Expression
14971{
14972 public:
14973 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14974 Expression* cap, Location location)
14975 : Expression(EXPRESSION_SLICE_VALUE, location),
14976 type_(type), valptr_(valptr), len_(len), cap_(cap)
14977 { }
14978
14979 protected:
14980 int
14981 do_traverse(Traverse*);
14982
14983 Type*
14984 do_type()
14985 { return this->type_; }
14986
14987 void
14988 do_determine_type(const Type_context*)
14989 { go_unreachable(); }
14990
14991 Expression*
14992 do_copy()
14993 {
14994 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14995 this->len_->copy(), this->cap_->copy(),
14996 this->location());
14997 }
14998
ea664253 14999 Bexpression*
15000 do_get_backend(Translate_context* context);
2c809f8f 15001
15002 void
15003 do_dump_expression(Ast_dump_context*) const;
15004
15005 private:
15006 // The type of the slice value.
15007 Type* type_;
15008 // The pointer to the values in the slice.
15009 Expression* valptr_;
15010 // The length of the slice.
15011 Expression* len_;
15012 // The capacity of the slice.
15013 Expression* cap_;
15014};
15015
15016int
15017Slice_value_expression::do_traverse(Traverse* traverse)
15018{
55e8ba6a 15019 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
15020 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2c809f8f 15021 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
15022 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
15023 return TRAVERSE_EXIT;
15024 return TRAVERSE_CONTINUE;
15025}
15026
ea664253 15027Bexpression*
15028Slice_value_expression::do_get_backend(Translate_context* context)
2c809f8f 15029{
15030 std::vector<Bexpression*> vals(3);
ea664253 15031 vals[0] = this->valptr_->get_backend(context);
15032 vals[1] = this->len_->get_backend(context);
15033 vals[2] = this->cap_->get_backend(context);
2c809f8f 15034
15035 Gogo* gogo = context->gogo();
15036 Btype* btype = this->type_->get_backend(gogo);
ea664253 15037 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 15038}
15039
15040void
15041Slice_value_expression::do_dump_expression(
15042 Ast_dump_context* ast_dump_context) const
15043{
15044 ast_dump_context->ostream() << "slicevalue(";
15045 ast_dump_context->ostream() << "values: ";
15046 this->valptr_->dump_expression(ast_dump_context);
15047 ast_dump_context->ostream() << ", length: ";
15048 this->len_->dump_expression(ast_dump_context);
15049 ast_dump_context->ostream() << ", capacity: ";
15050 this->cap_->dump_expression(ast_dump_context);
15051 ast_dump_context->ostream() << ")";
15052}
15053
15054Expression*
15055Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
15056 Expression* cap, Location location)
15057{
15058 go_assert(at->is_slice_type());
15059 return new Slice_value_expression(at, valptr, len, cap, location);
15060}
2387f644 15061
15062// An expression that evaluates to some characteristic of a non-empty interface.
15063// This is used to access the method table or underlying object of an interface.
15064
15065class Interface_info_expression : public Expression
15066{
15067 public:
15068 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 15069 Location location)
2387f644 15070 : Expression(EXPRESSION_INTERFACE_INFO, location),
15071 iface_(iface), iface_info_(iface_info)
15072 { }
15073
15074 protected:
15075 Type*
15076 do_type();
15077
15078 void
15079 do_determine_type(const Type_context*)
15080 { }
15081
15082 Expression*
15083 do_copy()
15084 {
15085 return new Interface_info_expression(this->iface_->copy(),
15086 this->iface_info_, this->location());
15087 }
15088
ea664253 15089 Bexpression*
15090 do_get_backend(Translate_context* context);
2387f644 15091
15092 void
15093 do_dump_expression(Ast_dump_context*) const;
15094
15095 void
15096 do_issue_nil_check()
15097 { this->iface_->issue_nil_check(); }
15098
15099 private:
15100 // The interface for which we are getting information.
15101 Expression* iface_;
15102 // What information we want.
15103 Interface_info iface_info_;
15104};
15105
15106// Return the type of the interface info.
15107
15108Type*
15109Interface_info_expression::do_type()
15110{
15111 switch (this->iface_info_)
15112 {
15113 case INTERFACE_INFO_METHODS:
15114 {
625d3118 15115 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15116 static Hashtable result_types;
15117
15118 Interface_type* itype = this->iface_->type()->interface_type();
15119
15120 Hashtable::const_iterator p = result_types.find(itype);
15121 if (p != result_types.end())
15122 return p->second;
15123
2c809f8f 15124 Type* pdt = Type::make_type_descriptor_ptr_type();
625d3118 15125 if (itype->is_empty())
15126 {
15127 result_types[itype] = pdt;
15128 return pdt;
15129 }
2c809f8f 15130
2387f644 15131 Location loc = this->location();
15132 Struct_field_list* sfl = new Struct_field_list();
2387f644 15133 sfl->push_back(
15134 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15135
2387f644 15136 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15137 p != itype->methods()->end();
15138 ++p)
15139 {
15140 Function_type* ft = p->type()->function_type();
15141 go_assert(ft->receiver() == NULL);
15142
15143 const Typed_identifier_list* params = ft->parameters();
15144 Typed_identifier_list* mparams = new Typed_identifier_list();
15145 if (params != NULL)
15146 mparams->reserve(params->size() + 1);
15147 Type* vt = Type::make_pointer_type(Type::make_void_type());
15148 mparams->push_back(Typed_identifier("", vt, ft->location()));
15149 if (params != NULL)
15150 {
15151 for (Typed_identifier_list::const_iterator pp = params->begin();
15152 pp != params->end();
15153 ++pp)
15154 mparams->push_back(*pp);
15155 }
15156
15157 Typed_identifier_list* mresults = (ft->results() == NULL
15158 ? NULL
15159 : ft->results()->copy());
15160 Backend_function_type* mft =
15161 Type::make_backend_function_type(NULL, mparams, mresults,
15162 ft->location());
15163
15164 std::string fname = Gogo::unpack_hidden_name(p->name());
15165 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15166 }
15167
6bf4793c 15168 Struct_type* st = Type::make_struct_type(sfl, loc);
15169 st->set_is_struct_incomparable();
15170 Pointer_type *pt = Type::make_pointer_type(st);
625d3118 15171 result_types[itype] = pt;
15172 return pt;
2387f644 15173 }
15174 case INTERFACE_INFO_OBJECT:
15175 return Type::make_pointer_type(Type::make_void_type());
15176 default:
15177 go_unreachable();
15178 }
15179}
15180
ea664253 15181// Return the backend representation for interface information.
2387f644 15182
ea664253 15183Bexpression*
15184Interface_info_expression::do_get_backend(Translate_context* context)
2387f644 15185{
15186 Gogo* gogo = context->gogo();
ea664253 15187 Bexpression* biface = this->iface_->get_backend(context);
2387f644 15188 switch (this->iface_info_)
15189 {
15190 case INTERFACE_INFO_METHODS:
15191 case INTERFACE_INFO_OBJECT:
ea664253 15192 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15193 this->location());
2387f644 15194 break;
15195 default:
15196 go_unreachable();
15197 }
2387f644 15198}
15199
15200// Dump ast representation for an interface info expression.
15201
15202void
15203Interface_info_expression::do_dump_expression(
15204 Ast_dump_context* ast_dump_context) const
15205{
2c809f8f 15206 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 15207 ast_dump_context->ostream() << "interfaceinfo(";
15208 this->iface_->dump_expression(ast_dump_context);
15209 ast_dump_context->ostream() << ",";
15210 ast_dump_context->ostream() <<
2c809f8f 15211 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15212 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 15213 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15214 : "unknown");
15215 ast_dump_context->ostream() << ")";
15216}
15217
15218// Make an interface info expression.
15219
15220Expression*
15221Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15222 Location location)
15223{
15224 return new Interface_info_expression(iface, iface_info, location);
15225}
15226
2c809f8f 15227// An expression that represents an interface value. The first field is either
15228// a type descriptor for an empty interface or a pointer to the interface method
15229// table for a non-empty interface. The second field is always the object.
15230
15231class Interface_value_expression : public Expression
15232{
15233 public:
15234 Interface_value_expression(Type* type, Expression* first_field,
15235 Expression* obj, Location location)
15236 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15237 type_(type), first_field_(first_field), obj_(obj)
15238 { }
15239
15240 protected:
15241 int
15242 do_traverse(Traverse*);
15243
15244 Type*
15245 do_type()
15246 { return this->type_; }
15247
15248 void
15249 do_determine_type(const Type_context*)
15250 { go_unreachable(); }
15251
15252 Expression*
15253 do_copy()
15254 {
15255 return new Interface_value_expression(this->type_,
15256 this->first_field_->copy(),
15257 this->obj_->copy(), this->location());
15258 }
15259
ea664253 15260 Bexpression*
15261 do_get_backend(Translate_context* context);
2c809f8f 15262
15263 void
15264 do_dump_expression(Ast_dump_context*) const;
15265
15266 private:
15267 // The type of the interface value.
15268 Type* type_;
15269 // The first field of the interface (either a type descriptor or a pointer
15270 // to the method table.
15271 Expression* first_field_;
15272 // The underlying object of the interface.
15273 Expression* obj_;
15274};
15275
15276int
15277Interface_value_expression::do_traverse(Traverse* traverse)
15278{
15279 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15280 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15281 return TRAVERSE_EXIT;
15282 return TRAVERSE_CONTINUE;
15283}
15284
ea664253 15285Bexpression*
15286Interface_value_expression::do_get_backend(Translate_context* context)
2c809f8f 15287{
15288 std::vector<Bexpression*> vals(2);
ea664253 15289 vals[0] = this->first_field_->get_backend(context);
15290 vals[1] = this->obj_->get_backend(context);
2c809f8f 15291
15292 Gogo* gogo = context->gogo();
15293 Btype* btype = this->type_->get_backend(gogo);
ea664253 15294 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 15295}
15296
15297void
15298Interface_value_expression::do_dump_expression(
15299 Ast_dump_context* ast_dump_context) const
15300{
15301 ast_dump_context->ostream() << "interfacevalue(";
15302 ast_dump_context->ostream() <<
15303 (this->type_->interface_type()->is_empty()
15304 ? "type_descriptor: "
15305 : "methods: ");
15306 this->first_field_->dump_expression(ast_dump_context);
15307 ast_dump_context->ostream() << ", object: ";
15308 this->obj_->dump_expression(ast_dump_context);
15309 ast_dump_context->ostream() << ")";
15310}
15311
15312Expression*
15313Expression::make_interface_value(Type* type, Expression* first_value,
15314 Expression* object, Location location)
15315{
15316 return new Interface_value_expression(type, first_value, object, location);
15317}
15318
15319// An interface method table for a pair of types: an interface type and a type
15320// that implements that interface.
15321
15322class Interface_mtable_expression : public Expression
15323{
15324 public:
15325 Interface_mtable_expression(Interface_type* itype, Type* type,
15326 bool is_pointer, Location location)
15327 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15328 itype_(itype), type_(type), is_pointer_(is_pointer),
15329 method_table_type_(NULL), bvar_(NULL)
15330 { }
15331
15332 protected:
15333 int
15334 do_traverse(Traverse*);
15335
15336 Type*
15337 do_type();
15338
15339 bool
3ae06f68 15340 do_is_static_initializer() const
2c809f8f 15341 { return true; }
15342
15343 void
15344 do_determine_type(const Type_context*)
15345 { go_unreachable(); }
15346
15347 Expression*
15348 do_copy()
15349 {
15350 return new Interface_mtable_expression(this->itype_, this->type_,
15351 this->is_pointer_, this->location());
15352 }
15353
15354 bool
15355 do_is_addressable() const
15356 { return true; }
15357
ea664253 15358 Bexpression*
15359 do_get_backend(Translate_context* context);
2c809f8f 15360
15361 void
15362 do_dump_expression(Ast_dump_context*) const;
15363
15364 private:
15365 // The interface type for which the methods are defined.
15366 Interface_type* itype_;
15367 // The type to construct the interface method table for.
15368 Type* type_;
15369 // Whether this table contains the method set for the receiver type or the
15370 // pointer receiver type.
15371 bool is_pointer_;
15372 // The type of the method table.
15373 Type* method_table_type_;
15374 // The backend variable that refers to the interface method table.
15375 Bvariable* bvar_;
15376};
15377
15378int
15379Interface_mtable_expression::do_traverse(Traverse* traverse)
15380{
15381 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15382 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15383 return TRAVERSE_EXIT;
15384 return TRAVERSE_CONTINUE;
15385}
15386
15387Type*
15388Interface_mtable_expression::do_type()
15389{
15390 if (this->method_table_type_ != NULL)
15391 return this->method_table_type_;
15392
15393 const Typed_identifier_list* interface_methods = this->itype_->methods();
15394 go_assert(!interface_methods->empty());
15395
15396 Struct_field_list* sfl = new Struct_field_list;
15397 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15398 this->location());
15399 sfl->push_back(Struct_field(tid));
db122cb9 15400 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
2c809f8f 15401 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15402 p != interface_methods->end();
15403 ++p)
db122cb9 15404 {
15405 // We want C function pointers here, not func descriptors; model
15406 // using void* pointers.
15407 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15408 sfl->push_back(Struct_field(method));
15409 }
6bf4793c 15410 Struct_type* st = Type::make_struct_type(sfl, this->location());
15411 st->set_is_struct_incomparable();
15412 this->method_table_type_ = st;
2c809f8f 15413 return this->method_table_type_;
15414}
15415
ea664253 15416Bexpression*
15417Interface_mtable_expression::do_get_backend(Translate_context* context)
2c809f8f 15418{
15419 Gogo* gogo = context->gogo();
2c809f8f 15420 Location loc = Linemap::predeclared_location();
15421 if (this->bvar_ != NULL)
d4e6573e 15422 return gogo->backend()->var_expression(this->bvar_, VE_rvalue,
15423 this->location());
2c809f8f 15424
15425 const Typed_identifier_list* interface_methods = this->itype_->methods();
15426 go_assert(!interface_methods->empty());
15427
15428 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
15429 + this->itype_->mangled_name(gogo)
15430 + "__"
15431 + this->type_->mangled_name(gogo));
15432
15433 // See whether this interface has any hidden methods.
15434 bool has_hidden_methods = false;
15435 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15436 p != interface_methods->end();
15437 ++p)
15438 {
15439 if (Gogo::is_hidden_name(p->name()))
15440 {
15441 has_hidden_methods = true;
15442 break;
15443 }
15444 }
15445
15446 // We already know that the named type is convertible to the
15447 // interface. If the interface has hidden methods, and the named
15448 // type is defined in a different package, then the interface
15449 // conversion table will be defined by that other package.
15450 if (has_hidden_methods
15451 && this->type_->named_type() != NULL
15452 && this->type_->named_type()->named_object()->package() != NULL)
15453 {
15454 Btype* btype = this->type()->get_backend(gogo);
438b4bec 15455 std::string asm_name(go_selectively_encode_id(mangled_name));
2c809f8f 15456 this->bvar_ =
438b4bec 15457 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15458 btype, loc);
d4e6573e 15459 return gogo->backend()->var_expression(this->bvar_, VE_rvalue,
15460 this->location());
2c809f8f 15461 }
15462
15463 // The first element is the type descriptor.
15464 Type* td_type;
15465 if (!this->is_pointer_)
15466 td_type = this->type_;
15467 else
15468 td_type = Type::make_pointer_type(this->type_);
15469
db122cb9 15470 std::vector<Backend::Btyped_identifier> bstructfields;
15471
2c809f8f 15472 // Build an interface method table for a type: a type descriptor followed by a
15473 // list of function pointers, one for each interface method. This is used for
15474 // interfaces.
15475 Expression_list* svals = new Expression_list();
db122cb9 15476 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
15477 svals->push_back(tdescriptor);
15478
15479 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
15480 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
15481 bstructfields.push_back(btd);
2c809f8f 15482
15483 Named_type* nt = this->type_->named_type();
15484 Struct_type* st = this->type_->struct_type();
15485 go_assert(nt != NULL || st != NULL);
15486
15487 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15488 p != interface_methods->end();
15489 ++p)
15490 {
15491 bool is_ambiguous;
15492 Method* m;
15493 if (nt != NULL)
15494 m = nt->method_function(p->name(), &is_ambiguous);
15495 else
15496 m = st->method_function(p->name(), &is_ambiguous);
15497 go_assert(m != NULL);
15498 Named_object* no = m->named_object();
15499
15500 go_assert(no->is_function() || no->is_function_declaration());
db122cb9 15501
15502 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
15503 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
15504 bstructfields.push_back(bmtype);
15505
2c809f8f 15506 svals->push_back(Expression::make_func_code_reference(no, loc));
15507 }
15508
db122cb9 15509 Btype *btype = gogo->backend()->struct_type(bstructfields);
15510 std::vector<Bexpression*> ctor_bexprs;
15511 for (Expression_list::const_iterator pe = svals->begin();
15512 pe != svals->end();
15513 ++pe)
15514 {
15515 ctor_bexprs.push_back((*pe)->get_backend(context));
15516 }
15517 Bexpression* ctor =
15518 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
2c809f8f 15519
15520 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
438b4bec 15521 std::string asm_name(go_selectively_encode_id(mangled_name));
15522 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
2c809f8f 15523 !is_public, btype, loc);
15524 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15525 !is_public, btype, loc, ctor);
d4e6573e 15526 return gogo->backend()->var_expression(this->bvar_, VE_lvalue, loc);
2c809f8f 15527}
15528
15529void
15530Interface_mtable_expression::do_dump_expression(
15531 Ast_dump_context* ast_dump_context) const
15532{
15533 ast_dump_context->ostream() << "__go_"
15534 << (this->is_pointer_ ? "pimt__" : "imt_");
15535 ast_dump_context->dump_type(this->itype_);
15536 ast_dump_context->ostream() << "__";
15537 ast_dump_context->dump_type(this->type_);
15538}
15539
15540Expression*
15541Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15542 bool is_pointer, Location location)
15543{
15544 return new Interface_mtable_expression(itype, type, is_pointer, location);
15545}
15546
e440a328 15547// An expression which evaluates to the offset of a field within a
15548// struct. This, like Type_info_expression, q.v., is only used to
15549// initialize fields of a type descriptor.
15550
15551class Struct_field_offset_expression : public Expression
15552{
15553 public:
15554 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 15555 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15556 Linemap::predeclared_location()),
e440a328 15557 type_(type), field_(field)
15558 { }
15559
15560 protected:
f23d7786 15561 bool
3ae06f68 15562 do_is_static_initializer() const
f23d7786 15563 { return true; }
15564
e440a328 15565 Type*
15566 do_type()
15567 { return Type::lookup_integer_type("uintptr"); }
15568
15569 void
15570 do_determine_type(const Type_context*)
15571 { }
15572
15573 Expression*
15574 do_copy()
15575 { return this; }
15576
ea664253 15577 Bexpression*
15578 do_get_backend(Translate_context* context);
e440a328 15579
d751bb78 15580 void
15581 do_dump_expression(Ast_dump_context*) const;
15582
e440a328 15583 private:
15584 // The type of the struct.
15585 Struct_type* type_;
15586 // The field.
15587 const Struct_field* field_;
15588};
15589
ea664253 15590// Return the backend representation for a struct field offset.
e440a328 15591
ea664253 15592Bexpression*
15593Struct_field_offset_expression::do_get_backend(Translate_context* context)
e440a328 15594{
e440a328 15595 const Struct_field_list* fields = this->type_->fields();
e440a328 15596 Struct_field_list::const_iterator p;
2c8bda43 15597 unsigned i = 0;
e440a328 15598 for (p = fields->begin();
15599 p != fields->end();
2c8bda43 15600 ++p, ++i)
15601 if (&*p == this->field_)
15602 break;
c484d925 15603 go_assert(&*p == this->field_);
e440a328 15604
2c8bda43 15605 Gogo* gogo = context->gogo();
15606 Btype* btype = this->type_->get_backend(gogo);
15607
3f378015 15608 int64_t offset = gogo->backend()->type_field_offset(btype, i);
2c8bda43 15609 Type* uptr_type = Type::lookup_integer_type("uintptr");
e67508fa 15610 Expression* ret =
3f378015 15611 Expression::make_integer_int64(offset, uptr_type,
15612 Linemap::predeclared_location());
ea664253 15613 return ret->get_backend(context);
e440a328 15614}
15615
d751bb78 15616// Dump ast representation for a struct field offset expression.
15617
15618void
15619Struct_field_offset_expression::do_dump_expression(
15620 Ast_dump_context* ast_dump_context) const
15621{
15622 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 15623 ast_dump_context->dump_type(this->type_);
15624 ast_dump_context->ostream() << '.';
15625 ast_dump_context->ostream() <<
15626 Gogo::message_name(this->field_->field_name());
d751bb78 15627 ast_dump_context->ostream() << ")";
15628}
15629
e440a328 15630// Make an expression for a struct field offset.
15631
15632Expression*
15633Expression::make_struct_field_offset(Struct_type* type,
15634 const Struct_field* field)
15635{
15636 return new Struct_field_offset_expression(type, field);
15637}
15638
15639// An expression which evaluates to the address of an unnamed label.
15640
15641class Label_addr_expression : public Expression
15642{
15643 public:
b13c66cd 15644 Label_addr_expression(Label* label, Location location)
e440a328 15645 : Expression(EXPRESSION_LABEL_ADDR, location),
15646 label_(label)
15647 { }
15648
15649 protected:
15650 Type*
15651 do_type()
15652 { return Type::make_pointer_type(Type::make_void_type()); }
15653
15654 void
15655 do_determine_type(const Type_context*)
15656 { }
15657
15658 Expression*
15659 do_copy()
15660 { return new Label_addr_expression(this->label_, this->location()); }
15661
ea664253 15662 Bexpression*
15663 do_get_backend(Translate_context* context)
15664 { return this->label_->get_addr(context, this->location()); }
e440a328 15665
d751bb78 15666 void
15667 do_dump_expression(Ast_dump_context* ast_dump_context) const
15668 { ast_dump_context->ostream() << this->label_->name(); }
15669
e440a328 15670 private:
15671 // The label whose address we are taking.
15672 Label* label_;
15673};
15674
15675// Make an expression for the address of an unnamed label.
15676
15677Expression*
b13c66cd 15678Expression::make_label_addr(Label* label, Location location)
e440a328 15679{
15680 return new Label_addr_expression(label, location);
15681}
15682
da244e59 15683// Class Conditional_expression.
283a177b 15684
2c809f8f 15685// Traversal.
15686
15687int
15688Conditional_expression::do_traverse(Traverse* traverse)
15689{
15690 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15691 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15692 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15693 return TRAVERSE_EXIT;
15694 return TRAVERSE_CONTINUE;
15695}
15696
283a177b 15697// Return the type of the conditional expression.
15698
15699Type*
15700Conditional_expression::do_type()
15701{
15702 Type* result_type = Type::make_void_type();
2c809f8f 15703 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15704 NULL))
283a177b 15705 result_type = this->then_->type();
15706 else if (this->then_->is_nil_expression()
15707 || this->else_->is_nil_expression())
15708 result_type = (!this->then_->is_nil_expression()
15709 ? this->then_->type()
15710 : this->else_->type());
15711 return result_type;
15712}
15713
2c809f8f 15714// Determine type for a conditional expression.
15715
15716void
15717Conditional_expression::do_determine_type(const Type_context* context)
15718{
15719 this->cond_->determine_type_no_context();
15720 this->then_->determine_type(context);
15721 this->else_->determine_type(context);
15722}
15723
283a177b 15724// Get the backend representation of a conditional expression.
15725
ea664253 15726Bexpression*
15727Conditional_expression::do_get_backend(Translate_context* context)
283a177b 15728{
15729 Gogo* gogo = context->gogo();
15730 Btype* result_btype = this->type()->get_backend(gogo);
ea664253 15731 Bexpression* cond = this->cond_->get_backend(context);
15732 Bexpression* then = this->then_->get_backend(context);
15733 Bexpression* belse = this->else_->get_backend(context);
93715b75 15734 Bfunction* bfn = context->function()->func_value()->get_decl();
15735 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
ea664253 15736 belse, this->location());
283a177b 15737}
15738
15739// Dump ast representation of a conditional expression.
15740
15741void
15742Conditional_expression::do_dump_expression(
15743 Ast_dump_context* ast_dump_context) const
15744{
15745 ast_dump_context->ostream() << "(";
15746 ast_dump_context->dump_expression(this->cond_);
15747 ast_dump_context->ostream() << " ? ";
15748 ast_dump_context->dump_expression(this->then_);
15749 ast_dump_context->ostream() << " : ";
15750 ast_dump_context->dump_expression(this->else_);
15751 ast_dump_context->ostream() << ") ";
15752}
15753
15754// Make a conditional expression.
15755
15756Expression*
15757Expression::make_conditional(Expression* cond, Expression* then,
15758 Expression* else_expr, Location location)
15759{
15760 return new Conditional_expression(cond, then, else_expr, location);
15761}
15762
da244e59 15763// Class Compound_expression.
2c809f8f 15764
15765// Traversal.
15766
15767int
15768Compound_expression::do_traverse(Traverse* traverse)
15769{
15770 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15771 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15772 return TRAVERSE_EXIT;
15773 return TRAVERSE_CONTINUE;
15774}
15775
15776// Return the type of the compound expression.
15777
15778Type*
15779Compound_expression::do_type()
15780{
15781 return this->expr_->type();
15782}
15783
15784// Determine type for a compound expression.
15785
15786void
15787Compound_expression::do_determine_type(const Type_context* context)
15788{
15789 this->init_->determine_type_no_context();
15790 this->expr_->determine_type(context);
15791}
15792
15793// Get the backend representation of a compound expression.
15794
ea664253 15795Bexpression*
15796Compound_expression::do_get_backend(Translate_context* context)
2c809f8f 15797{
15798 Gogo* gogo = context->gogo();
ea664253 15799 Bexpression* binit = this->init_->get_backend(context);
0ab48656 15800 Bfunction* bfunction = context->function()->func_value()->get_decl();
15801 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
15802 binit);
ea664253 15803 Bexpression* bexpr = this->expr_->get_backend(context);
15804 return gogo->backend()->compound_expression(init_stmt, bexpr,
15805 this->location());
2c809f8f 15806}
15807
15808// Dump ast representation of a conditional expression.
15809
15810void
15811Compound_expression::do_dump_expression(
15812 Ast_dump_context* ast_dump_context) const
15813{
15814 ast_dump_context->ostream() << "(";
15815 ast_dump_context->dump_expression(this->init_);
15816 ast_dump_context->ostream() << ",";
15817 ast_dump_context->dump_expression(this->expr_);
15818 ast_dump_context->ostream() << ") ";
15819}
15820
15821// Make a compound expression.
15822
15823Expression*
15824Expression::make_compound(Expression* init, Expression* expr, Location location)
15825{
15826 return new Compound_expression(init, expr, location);
15827}
15828
1b4fb1e0 15829// Class Backend_expression.
15830
15831int
15832Backend_expression::do_traverse(Traverse*)
15833{
15834 return TRAVERSE_CONTINUE;
15835}
15836
15837void
15838Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15839{
15840 ast_dump_context->ostream() << "backend_expression<";
15841 ast_dump_context->dump_type(this->type_);
15842 ast_dump_context->ostream() << ">";
15843}
15844
15845Expression*
15846Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
15847{
15848 return new Backend_expression(bexpr, type, location);
15849}
15850
e440a328 15851// Import an expression. This comes at the end in order to see the
15852// various class definitions.
15853
15854Expression*
15855Expression::import_expression(Import* imp)
15856{
15857 int c = imp->peek_char();
15858 if (imp->match_c_string("- ")
15859 || imp->match_c_string("! ")
15860 || imp->match_c_string("^ "))
15861 return Unary_expression::do_import(imp);
15862 else if (c == '(')
15863 return Binary_expression::do_import(imp);
15864 else if (imp->match_c_string("true")
15865 || imp->match_c_string("false"))
15866 return Boolean_expression::do_import(imp);
15867 else if (c == '"')
15868 return String_expression::do_import(imp);
15869 else if (c == '-' || (c >= '0' && c <= '9'))
15870 {
15871 // This handles integers, floats and complex constants.
15872 return Integer_expression::do_import(imp);
15873 }
15874 else if (imp->match_c_string("nil"))
15875 return Nil_expression::do_import(imp);
15876 else if (imp->match_c_string("convert"))
15877 return Type_conversion_expression::do_import(imp);
15878 else
15879 {
631d5788 15880 go_error_at(imp->location(), "import error: expected expression");
e440a328 15881 return Expression::make_error(imp->location());
15882 }
15883}
15884
15885// Class Expression_list.
15886
15887// Traverse the list.
15888
15889int
15890Expression_list::traverse(Traverse* traverse)
15891{
15892 for (Expression_list::iterator p = this->begin();
15893 p != this->end();
15894 ++p)
15895 {
15896 if (*p != NULL)
15897 {
15898 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15899 return TRAVERSE_EXIT;
15900 }
15901 }
15902 return TRAVERSE_CONTINUE;
15903}
15904
15905// Copy the list.
15906
15907Expression_list*
15908Expression_list::copy()
15909{
15910 Expression_list* ret = new Expression_list();
15911 for (Expression_list::iterator p = this->begin();
15912 p != this->end();
15913 ++p)
15914 {
15915 if (*p == NULL)
15916 ret->push_back(NULL);
15917 else
15918 ret->push_back((*p)->copy());
15919 }
15920 return ret;
15921}
15922
15923// Return whether an expression list has an error expression.
15924
15925bool
15926Expression_list::contains_error() const
15927{
15928 for (Expression_list::const_iterator p = this->begin();
15929 p != this->end();
15930 ++p)
15931 if (*p != NULL && (*p)->is_error_expression())
15932 return true;
15933 return false;
15934}
0c77715b 15935
15936// Class Numeric_constant.
15937
15938// Destructor.
15939
15940Numeric_constant::~Numeric_constant()
15941{
15942 this->clear();
15943}
15944
15945// Copy constructor.
15946
15947Numeric_constant::Numeric_constant(const Numeric_constant& a)
15948 : classification_(a.classification_), type_(a.type_)
15949{
15950 switch (a.classification_)
15951 {
15952 case NC_INVALID:
15953 break;
15954 case NC_INT:
15955 case NC_RUNE:
15956 mpz_init_set(this->u_.int_val, a.u_.int_val);
15957 break;
15958 case NC_FLOAT:
15959 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15960 break;
15961 case NC_COMPLEX:
fcbea5e4 15962 mpc_init2(this->u_.complex_val, mpc_precision);
15963 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15964 break;
15965 default:
15966 go_unreachable();
15967 }
15968}
15969
15970// Assignment operator.
15971
15972Numeric_constant&
15973Numeric_constant::operator=(const Numeric_constant& a)
15974{
15975 this->clear();
15976 this->classification_ = a.classification_;
15977 this->type_ = a.type_;
15978 switch (a.classification_)
15979 {
15980 case NC_INVALID:
15981 break;
15982 case NC_INT:
15983 case NC_RUNE:
15984 mpz_init_set(this->u_.int_val, a.u_.int_val);
15985 break;
15986 case NC_FLOAT:
15987 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15988 break;
15989 case NC_COMPLEX:
fcbea5e4 15990 mpc_init2(this->u_.complex_val, mpc_precision);
15991 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15992 break;
15993 default:
15994 go_unreachable();
15995 }
15996 return *this;
15997}
15998
15999// Clear the contents.
16000
16001void
16002Numeric_constant::clear()
16003{
16004 switch (this->classification_)
16005 {
16006 case NC_INVALID:
16007 break;
16008 case NC_INT:
16009 case NC_RUNE:
16010 mpz_clear(this->u_.int_val);
16011 break;
16012 case NC_FLOAT:
16013 mpfr_clear(this->u_.float_val);
16014 break;
16015 case NC_COMPLEX:
fcbea5e4 16016 mpc_clear(this->u_.complex_val);
0c77715b 16017 break;
16018 default:
16019 go_unreachable();
16020 }
16021 this->classification_ = NC_INVALID;
16022}
16023
16024// Set to an unsigned long value.
16025
16026void
16027Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
16028{
16029 this->clear();
16030 this->classification_ = NC_INT;
16031 this->type_ = type;
16032 mpz_init_set_ui(this->u_.int_val, val);
16033}
16034
16035// Set to an integer value.
16036
16037void
16038Numeric_constant::set_int(Type* type, const mpz_t val)
16039{
16040 this->clear();
16041 this->classification_ = NC_INT;
16042 this->type_ = type;
16043 mpz_init_set(this->u_.int_val, val);
16044}
16045
16046// Set to a rune value.
16047
16048void
16049Numeric_constant::set_rune(Type* type, const mpz_t val)
16050{
16051 this->clear();
16052 this->classification_ = NC_RUNE;
16053 this->type_ = type;
16054 mpz_init_set(this->u_.int_val, val);
16055}
16056
16057// Set to a floating point value.
16058
16059void
16060Numeric_constant::set_float(Type* type, const mpfr_t val)
16061{
16062 this->clear();
16063 this->classification_ = NC_FLOAT;
16064 this->type_ = type;
833b523c 16065 // Numeric constants do not have negative zero values, so remove
16066 // them here. They also don't have infinity or NaN values, but we
16067 // should never see them here.
16068 if (mpfr_zero_p(val))
16069 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16070 else
16071 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 16072}
16073
16074// Set to a complex value.
16075
16076void
fcbea5e4 16077Numeric_constant::set_complex(Type* type, const mpc_t val)
0c77715b 16078{
16079 this->clear();
16080 this->classification_ = NC_COMPLEX;
16081 this->type_ = type;
fcbea5e4 16082 mpc_init2(this->u_.complex_val, mpc_precision);
16083 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
0c77715b 16084}
16085
16086// Get an int value.
16087
16088void
16089Numeric_constant::get_int(mpz_t* val) const
16090{
16091 go_assert(this->is_int());
16092 mpz_init_set(*val, this->u_.int_val);
16093}
16094
16095// Get a rune value.
16096
16097void
16098Numeric_constant::get_rune(mpz_t* val) const
16099{
16100 go_assert(this->is_rune());
16101 mpz_init_set(*val, this->u_.int_val);
16102}
16103
16104// Get a floating point value.
16105
16106void
16107Numeric_constant::get_float(mpfr_t* val) const
16108{
16109 go_assert(this->is_float());
16110 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16111}
16112
16113// Get a complex value.
16114
16115void
fcbea5e4 16116Numeric_constant::get_complex(mpc_t* val) const
0c77715b 16117{
16118 go_assert(this->is_complex());
fcbea5e4 16119 mpc_init2(*val, mpc_precision);
16120 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 16121}
16122
16123// Express value as unsigned long if possible.
16124
16125Numeric_constant::To_unsigned_long
16126Numeric_constant::to_unsigned_long(unsigned long* val) const
16127{
16128 switch (this->classification_)
16129 {
16130 case NC_INT:
16131 case NC_RUNE:
16132 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16133 case NC_FLOAT:
16134 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16135 case NC_COMPLEX:
fcbea5e4 16136 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 16137 return NC_UL_NOTINT;
fcbea5e4 16138 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16139 val);
0c77715b 16140 default:
16141 go_unreachable();
16142 }
16143}
16144
16145// Express integer value as unsigned long if possible.
16146
16147Numeric_constant::To_unsigned_long
16148Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16149 unsigned long *val) const
16150{
16151 if (mpz_sgn(ival) < 0)
16152 return NC_UL_NEGATIVE;
16153 unsigned long ui = mpz_get_ui(ival);
16154 if (mpz_cmp_ui(ival, ui) != 0)
16155 return NC_UL_BIG;
16156 *val = ui;
16157 return NC_UL_VALID;
16158}
16159
16160// Express floating point value as unsigned long if possible.
16161
16162Numeric_constant::To_unsigned_long
16163Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16164 unsigned long *val) const
16165{
16166 if (!mpfr_integer_p(fval))
16167 return NC_UL_NOTINT;
16168 mpz_t ival;
16169 mpz_init(ival);
16170 mpfr_get_z(ival, fval, GMP_RNDN);
16171 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16172 mpz_clear(ival);
16173 return ret;
16174}
16175
03118c21 16176// Express value as memory size if possible.
16177
16178bool
16179Numeric_constant::to_memory_size(int64_t* val) const
16180{
16181 switch (this->classification_)
16182 {
16183 case NC_INT:
16184 case NC_RUNE:
16185 return this->mpz_to_memory_size(this->u_.int_val, val);
16186 case NC_FLOAT:
16187 return this->mpfr_to_memory_size(this->u_.float_val, val);
16188 case NC_COMPLEX:
16189 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16190 return false;
16191 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16192 default:
16193 go_unreachable();
16194 }
16195}
16196
16197// Express integer as memory size if possible.
16198
16199bool
16200Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16201{
16202 if (mpz_sgn(ival) < 0)
16203 return false;
16204 if (mpz_fits_slong_p(ival))
16205 {
16206 *val = static_cast<int64_t>(mpz_get_si(ival));
16207 return true;
16208 }
16209
16210 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16211 // positive value.
16212 if (mpz_sizeinbase(ival, 2) >= 64)
16213 return false;
16214
16215 mpz_t q, r;
16216 mpz_init(q);
16217 mpz_init(r);
16218 mpz_tdiv_q_2exp(q, ival, 32);
16219 mpz_tdiv_r_2exp(r, ival, 32);
16220 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16221 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16222 + static_cast<int64_t>(mpz_get_ui(r)));
16223 mpz_clear(r);
16224 mpz_clear(q);
16225 return true;
16226}
16227
16228// Express floating point value as memory size if possible.
16229
16230bool
16231Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16232{
16233 if (!mpfr_integer_p(fval))
16234 return false;
16235 mpz_t ival;
16236 mpz_init(ival);
16237 mpfr_get_z(ival, fval, GMP_RNDN);
16238 bool ret = this->mpz_to_memory_size(ival, val);
16239 mpz_clear(ival);
16240 return ret;
16241}
16242
0c77715b 16243// Convert value to integer if possible.
16244
16245bool
16246Numeric_constant::to_int(mpz_t* val) const
16247{
16248 switch (this->classification_)
16249 {
16250 case NC_INT:
16251 case NC_RUNE:
16252 mpz_init_set(*val, this->u_.int_val);
16253 return true;
16254 case NC_FLOAT:
16255 if (!mpfr_integer_p(this->u_.float_val))
16256 return false;
16257 mpz_init(*val);
16258 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16259 return true;
16260 case NC_COMPLEX:
fcbea5e4 16261 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16262 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
0c77715b 16263 return false;
16264 mpz_init(*val);
fcbea5e4 16265 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 16266 return true;
16267 default:
16268 go_unreachable();
16269 }
16270}
16271
16272// Convert value to floating point if possible.
16273
16274bool
16275Numeric_constant::to_float(mpfr_t* val) const
16276{
16277 switch (this->classification_)
16278 {
16279 case NC_INT:
16280 case NC_RUNE:
16281 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16282 return true;
16283 case NC_FLOAT:
16284 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16285 return true;
16286 case NC_COMPLEX:
fcbea5e4 16287 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 16288 return false;
fcbea5e4 16289 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 16290 return true;
16291 default:
16292 go_unreachable();
16293 }
16294}
16295
16296// Convert value to complex.
16297
16298bool
fcbea5e4 16299Numeric_constant::to_complex(mpc_t* val) const
0c77715b 16300{
fcbea5e4 16301 mpc_init2(*val, mpc_precision);
0c77715b 16302 switch (this->classification_)
16303 {
16304 case NC_INT:
16305 case NC_RUNE:
fcbea5e4 16306 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
0c77715b 16307 return true;
16308 case NC_FLOAT:
fcbea5e4 16309 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
0c77715b 16310 return true;
16311 case NC_COMPLEX:
fcbea5e4 16312 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 16313 return true;
16314 default:
16315 go_unreachable();
16316 }
16317}
16318
16319// Get the type.
16320
16321Type*
16322Numeric_constant::type() const
16323{
16324 if (this->type_ != NULL)
16325 return this->type_;
16326 switch (this->classification_)
16327 {
16328 case NC_INT:
16329 return Type::make_abstract_integer_type();
16330 case NC_RUNE:
16331 return Type::make_abstract_character_type();
16332 case NC_FLOAT:
16333 return Type::make_abstract_float_type();
16334 case NC_COMPLEX:
16335 return Type::make_abstract_complex_type();
16336 default:
16337 go_unreachable();
16338 }
16339}
16340
16341// If the constant can be expressed in TYPE, then set the type of the
16342// constant to TYPE and return true. Otherwise return false, and, if
16343// ISSUE_ERROR is true, report an appropriate error message.
16344
16345bool
16346Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
16347{
16348 bool ret;
f11c2155 16349 if (type == NULL || type->is_error())
0c77715b 16350 ret = true;
16351 else if (type->integer_type() != NULL)
16352 ret = this->check_int_type(type->integer_type(), issue_error, loc);
16353 else if (type->float_type() != NULL)
16354 ret = this->check_float_type(type->float_type(), issue_error, loc);
16355 else if (type->complex_type() != NULL)
16356 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
16357 else
5706ab68 16358 {
16359 ret = false;
16360 if (issue_error)
16361 go_assert(saw_errors());
16362 }
0c77715b 16363 if (ret)
16364 this->type_ = type;
16365 return ret;
16366}
16367
16368// Check whether the constant can be expressed in an integer type.
16369
16370bool
16371Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
71a45216 16372 Location location)
0c77715b 16373{
16374 mpz_t val;
16375 switch (this->classification_)
16376 {
16377 case NC_INT:
16378 case NC_RUNE:
16379 mpz_init_set(val, this->u_.int_val);
16380 break;
16381
16382 case NC_FLOAT:
16383 if (!mpfr_integer_p(this->u_.float_val))
16384 {
16385 if (issue_error)
71a45216 16386 {
631d5788 16387 go_error_at(location,
16388 "floating point constant truncated to integer");
71a45216 16389 this->set_invalid();
16390 }
0c77715b 16391 return false;
16392 }
16393 mpz_init(val);
16394 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
16395 break;
16396
16397 case NC_COMPLEX:
fcbea5e4 16398 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
16399 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 16400 {
16401 if (issue_error)
71a45216 16402 {
631d5788 16403 go_error_at(location, "complex constant truncated to integer");
71a45216 16404 this->set_invalid();
16405 }
0c77715b 16406 return false;
16407 }
16408 mpz_init(val);
fcbea5e4 16409 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 16410 break;
16411
16412 default:
16413 go_unreachable();
16414 }
16415
16416 bool ret;
16417 if (type->is_abstract())
16418 ret = true;
16419 else
16420 {
16421 int bits = mpz_sizeinbase(val, 2);
16422 if (type->is_unsigned())
16423 {
16424 // For an unsigned type we can only accept a nonnegative
16425 // number, and we must be able to represents at least BITS.
16426 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
16427 }
16428 else
16429 {
16430 // For a signed type we need an extra bit to indicate the
16431 // sign. We have to handle the most negative integer
16432 // specially.
16433 ret = (bits + 1 <= type->bits()
16434 || (bits <= type->bits()
16435 && mpz_sgn(val) < 0
16436 && (mpz_scan1(val, 0)
16437 == static_cast<unsigned long>(type->bits() - 1))
16438 && mpz_scan0(val, type->bits()) == ULONG_MAX));
16439 }
16440 }
16441
16442 if (!ret && issue_error)
71a45216 16443 {
631d5788 16444 go_error_at(location, "integer constant overflow");
71a45216 16445 this->set_invalid();
16446 }
0c77715b 16447
16448 return ret;
16449}
16450
16451// Check whether the constant can be expressed in a floating point
16452// type.
16453
16454bool
16455Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 16456 Location location)
0c77715b 16457{
16458 mpfr_t val;
16459 switch (this->classification_)
16460 {
16461 case NC_INT:
16462 case NC_RUNE:
16463 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
16464 break;
16465
16466 case NC_FLOAT:
16467 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
16468 break;
16469
16470 case NC_COMPLEX:
fcbea5e4 16471 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 16472 {
16473 if (issue_error)
71a45216 16474 {
16475 this->set_invalid();
631d5788 16476 go_error_at(location, "complex constant truncated to float");
71a45216 16477 }
0c77715b 16478 return false;
16479 }
fcbea5e4 16480 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 16481 break;
16482
16483 default:
16484 go_unreachable();
16485 }
16486
16487 bool ret;
16488 if (type->is_abstract())
16489 ret = true;
16490 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16491 {
16492 // A NaN or Infinity always fits in the range of the type.
16493 ret = true;
16494 }
16495 else
16496 {
16497 mp_exp_t exp = mpfr_get_exp(val);
16498 mp_exp_t max_exp;
16499 switch (type->bits())
16500 {
16501 case 32:
16502 max_exp = 128;
16503 break;
16504 case 64:
16505 max_exp = 1024;
16506 break;
16507 default:
16508 go_unreachable();
16509 }
16510
16511 ret = exp <= max_exp;
d0bcce51 16512
16513 if (ret)
16514 {
16515 // Round the constant to the desired type.
16516 mpfr_t t;
16517 mpfr_init(t);
16518 switch (type->bits())
16519 {
16520 case 32:
16521 mpfr_set_prec(t, 24);
16522 break;
16523 case 64:
16524 mpfr_set_prec(t, 53);
16525 break;
16526 default:
16527 go_unreachable();
16528 }
16529 mpfr_set(t, val, GMP_RNDN);
16530 mpfr_set(val, t, GMP_RNDN);
16531 mpfr_clear(t);
16532
16533 this->set_float(type, val);
16534 }
0c77715b 16535 }
16536
16537 mpfr_clear(val);
16538
16539 if (!ret && issue_error)
71a45216 16540 {
631d5788 16541 go_error_at(location, "floating point constant overflow");
71a45216 16542 this->set_invalid();
16543 }
0c77715b 16544
16545 return ret;
16546}
16547
16548// Check whether the constant can be expressed in a complex type.
16549
16550bool
16551Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 16552 Location location)
0c77715b 16553{
16554 if (type->is_abstract())
16555 return true;
16556
16557 mp_exp_t max_exp;
16558 switch (type->bits())
16559 {
16560 case 64:
16561 max_exp = 128;
16562 break;
16563 case 128:
16564 max_exp = 1024;
16565 break;
16566 default:
16567 go_unreachable();
16568 }
16569
fcbea5e4 16570 mpc_t val;
16571 mpc_init2(val, mpc_precision);
0c77715b 16572 switch (this->classification_)
16573 {
16574 case NC_INT:
16575 case NC_RUNE:
fcbea5e4 16576 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
0c77715b 16577 break;
16578
16579 case NC_FLOAT:
fcbea5e4 16580 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
0c77715b 16581 break;
16582
16583 case NC_COMPLEX:
fcbea5e4 16584 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
0c77715b 16585 break;
16586
16587 default:
16588 go_unreachable();
16589 }
16590
d0bcce51 16591 bool ret = true;
fcbea5e4 16592 if (!mpfr_nan_p(mpc_realref(val))
16593 && !mpfr_inf_p(mpc_realref(val))
16594 && !mpfr_zero_p(mpc_realref(val))
16595 && mpfr_get_exp(mpc_realref(val)) > max_exp)
d0bcce51 16596 {
16597 if (issue_error)
71a45216 16598 {
631d5788 16599 go_error_at(location, "complex real part overflow");
71a45216 16600 this->set_invalid();
16601 }
d0bcce51 16602 ret = false;
16603 }
0c77715b 16604
fcbea5e4 16605 if (!mpfr_nan_p(mpc_imagref(val))
16606 && !mpfr_inf_p(mpc_imagref(val))
16607 && !mpfr_zero_p(mpc_imagref(val))
16608 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
d0bcce51 16609 {
16610 if (issue_error)
71a45216 16611 {
631d5788 16612 go_error_at(location, "complex imaginary part overflow");
71a45216 16613 this->set_invalid();
16614 }
d0bcce51 16615 ret = false;
16616 }
0c77715b 16617
d0bcce51 16618 if (ret)
16619 {
16620 // Round the constant to the desired type.
fcbea5e4 16621 mpc_t t;
d0bcce51 16622 switch (type->bits())
16623 {
16624 case 64:
fcbea5e4 16625 mpc_init2(t, 24);
d0bcce51 16626 break;
16627 case 128:
fcbea5e4 16628 mpc_init2(t, 53);
d0bcce51 16629 break;
16630 default:
16631 go_unreachable();
16632 }
fcbea5e4 16633 mpc_set(t, val, MPC_RNDNN);
16634 mpc_set(val, t, MPC_RNDNN);
16635 mpc_clear(t);
d0bcce51 16636
fcbea5e4 16637 this->set_complex(type, val);
d0bcce51 16638 }
16639
fcbea5e4 16640 mpc_clear(val);
0c77715b 16641
16642 return ret;
16643}
16644
16645// Return an Expression for this value.
16646
16647Expression*
16648Numeric_constant::expression(Location loc) const
16649{
16650 switch (this->classification_)
16651 {
16652 case NC_INT:
e67508fa 16653 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
0c77715b 16654 case NC_RUNE:
16655 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16656 case NC_FLOAT:
16657 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16658 case NC_COMPLEX:
fcbea5e4 16659 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
71a45216 16660 case NC_INVALID:
16661 go_assert(saw_errors());
16662 return Expression::make_error(loc);
0c77715b 16663 default:
16664 go_unreachable();
16665 }
16666}