]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
2014-05-06 Jan-Benedict Glaw <jbglaw@lug-owl.de>
[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 "toplev.h"
12#include "intl.h"
13#include "tree.h"
9ed99284 14#include "stringpool.h"
15#include "stor-layout.h"
764505e6 16#include "gimple-expr.h"
e440a328 17#include "tree-iterator.h"
18#include "convert.h"
19#include "real.h"
20#include "realmpfr.h"
e440a328 21
e440a328 22#include "go-c.h"
23#include "gogo.h"
24#include "types.h"
25#include "export.h"
26#include "import.h"
27#include "statements.h"
28#include "lex.h"
a9182619 29#include "runtime.h"
6e193e6f 30#include "backend.h"
e440a328 31#include "expressions.h"
d751bb78 32#include "ast-dump.h"
e440a328 33
34// Class Expression.
35
36Expression::Expression(Expression_classification classification,
b13c66cd 37 Location location)
e440a328 38 : classification_(classification), location_(location)
39{
40}
41
42Expression::~Expression()
43{
44}
45
e440a328 46// Traverse the expressions.
47
48int
49Expression::traverse(Expression** pexpr, Traverse* traverse)
50{
51 Expression* expr = *pexpr;
52 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
53 {
54 int t = traverse->expression(pexpr);
55 if (t == TRAVERSE_EXIT)
56 return TRAVERSE_EXIT;
57 else if (t == TRAVERSE_SKIP_COMPONENTS)
58 return TRAVERSE_CONTINUE;
59 }
60 return expr->do_traverse(traverse);
61}
62
63// Traverse subexpressions of this expression.
64
65int
66Expression::traverse_subexpressions(Traverse* traverse)
67{
68 return this->do_traverse(traverse);
69}
70
71// Default implementation for do_traverse for child classes.
72
73int
74Expression::do_traverse(Traverse*)
75{
76 return TRAVERSE_CONTINUE;
77}
78
79// This virtual function is called by the parser if the value of this
a7549a6a 80// expression is being discarded. By default, we give an error.
81// Expressions with side effects override.
e440a328 82
4f2138d7 83bool
e440a328 84Expression::do_discarding_value()
85{
a7549a6a 86 this->unused_value_error();
4f2138d7 87 return false;
e440a328 88}
89
90// This virtual function is called to export expressions. This will
91// only be used by expressions which may be constant.
92
93void
94Expression::do_export(Export*) const
95{
c3e6f413 96 go_unreachable();
e440a328 97}
98
a7549a6a 99// Give an error saying that the value of the expression is not used.
e440a328 100
101void
a7549a6a 102Expression::unused_value_error()
e440a328 103{
4f2138d7 104 this->report_error(_("value computed is not used"));
e440a328 105}
106
107// Note that this expression is an error. This is called by children
108// when they discover an error.
109
110void
111Expression::set_is_error()
112{
113 this->classification_ = EXPRESSION_ERROR;
114}
115
116// For children to call to report an error conveniently.
117
118void
119Expression::report_error(const char* msg)
120{
121 error_at(this->location_, "%s", msg);
122 this->set_is_error();
123}
124
125// Set types of variables and constants. This is implemented by the
126// child class.
127
128void
129Expression::determine_type(const Type_context* context)
130{
131 this->do_determine_type(context);
132}
133
134// Set types when there is no context.
135
136void
137Expression::determine_type_no_context()
138{
139 Type_context context;
140 this->do_determine_type(&context);
141}
142
2c809f8f 143// Return an expression handling any conversions which must be done during
e440a328 144// assignment.
145
2c809f8f 146Expression*
147Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
148 Expression* rhs, Location location)
e440a328 149{
2c809f8f 150 Type* rhs_type = rhs->type();
151 if (lhs_type->is_error()
152 || rhs_type->is_error()
153 || rhs->is_error_expression())
154 return Expression::make_error(location);
e440a328 155
54211955 156 if (lhs_type->forwarded() != rhs_type->forwarded()
157 && lhs_type->interface_type() != NULL)
e440a328 158 {
159 if (rhs_type->interface_type() == NULL)
2c809f8f 160 return Expression::convert_type_to_interface(lhs_type, rhs, location);
e440a328 161 else
2c809f8f 162 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
163 location);
e440a328 164 }
54211955 165 else if (lhs_type->forwarded() != rhs_type->forwarded()
166 && rhs_type->interface_type() != NULL)
2c809f8f 167 return Expression::convert_interface_to_type(lhs_type, rhs, location);
411eb89e 168 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 169 {
2c809f8f 170 // Assigning nil to a slice.
171 mpz_t zval;
172 mpz_init_set_ui(zval, 0UL);
173 Expression* zero = Expression::make_integer(&zval, NULL, location);
174 mpz_clear(zval);
175 Expression* nil = Expression::make_nil(location);
176 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
e440a328 177 }
178 else if (rhs_type->is_nil_type())
2c809f8f 179 return Expression::make_nil(location);
180 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
e440a328 181 {
182 // No conversion is needed.
2c809f8f 183 return rhs;
184 }
185 else if (lhs_type->points_to() != NULL)
186 return Expression::make_unsafe_cast(lhs_type, rhs, location);
187 else if (lhs_type->is_numeric_type())
188 return Expression::make_cast(lhs_type, rhs, location);
189 else if ((lhs_type->struct_type() != NULL
190 && rhs_type->struct_type() != NULL)
191 || (lhs_type->array_type() != NULL
192 && rhs_type->array_type() != NULL))
e440a328 193 {
bb92f513 194 // Avoid confusion from zero sized variables which may be
195 // represented as non-zero-sized.
2c809f8f 196 // TODO(cmang): This check is for a GCC-specific issue, and should be
197 // removed from the frontend. FIXME.
198 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
199 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
200 if (rhs_size == 0 || lhs_size == 0)
201 return rhs;
bb92f513 202
e440a328 203 // This conversion must be permitted by Go, or we wouldn't have
204 // gotten here.
2c809f8f 205 return Expression::make_unsafe_cast(lhs_type, rhs, location);
e440a328 206 }
207 else
2c809f8f 208 return rhs;
e440a328 209}
210
2c809f8f 211// Return an expression for a conversion from a non-interface type to an
e440a328 212// interface type.
213
2c809f8f 214Expression*
215Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
216 Location location)
e440a328 217{
e440a328 218 Interface_type* lhs_interface_type = lhs_type->interface_type();
219 bool lhs_is_empty = lhs_interface_type->is_empty();
220
221 // Since RHS_TYPE is a static type, we can create the interface
222 // method table at compile time.
223
224 // When setting an interface to nil, we just set both fields to
225 // NULL.
2c809f8f 226 Type* rhs_type = rhs->type();
e440a328 227 if (rhs_type->is_nil_type())
63697958 228 {
2c809f8f 229 Expression* nil = Expression::make_nil(location);
230 return Expression::make_interface_value(lhs_type, nil, nil, location);
63697958 231 }
e440a328 232
233 // This should have been checked already.
c484d925 234 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 235
e440a328 236 // An interface is a tuple. If LHS_TYPE is an empty interface type,
237 // then the first field is the type descriptor for RHS_TYPE.
238 // Otherwise it is the interface method table for RHS_TYPE.
2c809f8f 239 Expression* first_field;
e440a328 240 if (lhs_is_empty)
2c809f8f 241 first_field = Expression::make_type_descriptor(rhs_type, location);
e440a328 242 else
243 {
244 // Build the interface method table for this interface and this
245 // object type: a list of function pointers for each interface
246 // method.
247 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 248 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 249 bool is_pointer = false;
c0cab2ec 250 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 251 {
252 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 253 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 254 is_pointer = true;
255 }
c0cab2ec 256 if (rhs_named_type != NULL)
2c809f8f 257 first_field =
258 rhs_named_type->interface_method_table(lhs_interface_type,
259 is_pointer);
c0cab2ec 260 else if (rhs_struct_type != NULL)
2c809f8f 261 first_field =
262 rhs_struct_type->interface_method_table(lhs_interface_type,
263 is_pointer);
c0cab2ec 264 else
2c809f8f 265 first_field = Expression::make_nil(location);
e440a328 266 }
e440a328 267
2c809f8f 268 Expression* obj;
e440a328 269 if (rhs_type->points_to() != NULL)
270 {
2c809f8f 271 // We are assigning a pointer to the interface; the interface
e440a328 272 // holds the pointer itself.
2c809f8f 273 obj = rhs;
274 }
275 else
276 {
277 // We are assigning a non-pointer value to the interface; the
278 // interface gets a copy of the value in the heap.
279 obj = Expression::make_heap_expression(rhs, location);
e440a328 280 }
281
2c809f8f 282 return Expression::make_interface_value(lhs_type, first_field, obj, location);
283}
e440a328 284
2c809f8f 285// Return an expression for the type descriptor of RHS.
e440a328 286
2c809f8f 287Expression*
288Expression::get_interface_type_descriptor(Expression* rhs)
289{
290 go_assert(rhs->type()->interface_type() != NULL);
291 Location location = rhs->location();
e440a328 292
2c809f8f 293 // The type descriptor is the first field of an empty interface.
294 if (rhs->type()->interface_type()->is_empty())
295 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
296 location);
297
298 Expression* mtable =
299 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
e440a328 300
2c809f8f 301 Expression* descriptor =
302 Expression::make_unary(OPERATOR_MULT, mtable, location);
303 descriptor = Expression::make_field_reference(descriptor, 0, location);
304 Expression* nil = Expression::make_nil(location);
e440a328 305
2c809f8f 306 Expression* eq =
307 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
308 return Expression::make_conditional(eq, nil, descriptor, location);
e440a328 309}
310
2c809f8f 311// Return an expression for the conversion of an interface type to an
e440a328 312// interface type.
313
2c809f8f 314Expression*
315Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
316 bool for_type_guard,
317 Location location)
e440a328 318{
e440a328 319 Interface_type* lhs_interface_type = lhs_type->interface_type();
320 bool lhs_is_empty = lhs_interface_type->is_empty();
321
e440a328 322 // In the general case this requires runtime examination of the type
323 // method table to match it up with the interface methods.
324
325 // FIXME: If all of the methods in the right hand side interface
326 // also appear in the left hand side interface, then we don't need
327 // to do a runtime check, although we still need to build a new
328 // method table.
329
330 // Get the type descriptor for the right hand side. This will be
331 // NULL for a nil interface.
2c809f8f 332 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
333 Expression* lhs_type_expr =
334 Expression::make_type_descriptor(lhs_type, location);
e440a328 335
2c809f8f 336 Expression* first_field;
e440a328 337 if (for_type_guard)
338 {
339 // A type assertion fails when converting a nil interface.
2c809f8f 340 first_field =
341 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
e440a328 343 }
344 else if (lhs_is_empty)
345 {
2c809f8f 346 // A conversion to an empty interface always succeeds, and the
e440a328 347 // first field is just the type descriptor of the object.
2c809f8f 348 first_field = rhs_type_expr;
e440a328 349 }
350 else
351 {
352 // A conversion to a non-empty interface may fail, but unlike a
353 // type assertion converting nil will always succeed.
2c809f8f 354 first_field =
355 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
356 lhs_type_expr, rhs_type_expr);
e440a328 357 }
358
359 // The second field is simply the object pointer.
2c809f8f 360 Expression* obj =
361 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
362 return Expression::make_interface_value(lhs_type, first_field, obj, location);
e440a328 363}
364
2c809f8f 365// Return an expression for the conversion of an interface type to a
e440a328 366// non-interface type.
367
2c809f8f 368Expression*
369Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
370 Location location)
e440a328 371{
e440a328 372 // Call a function to check that the type is valid. The function
373 // will panic with an appropriate runtime type error if the type is
374 // not valid.
2c809f8f 375 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
376 location);
377 Expression* rhs_descriptor =
378 Expression::get_interface_type_descriptor(rhs);
379
380 Type* rhs_type = rhs->type();
381 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
382 location);
383
384 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
385 location, 3, lhs_type_expr,
386 rhs_descriptor, rhs_inter_expr);
e440a328 387
388 // If the call succeeds, pull out the value.
2c809f8f 389 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
390 location);
e440a328 391
392 // If the value is a pointer, then it is the value we want.
393 // Otherwise it points to the value.
394 if (lhs_type->points_to() == NULL)
395 {
2c809f8f 396 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
397 location);
398 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
e440a328 399 }
2c809f8f 400 return Expression::make_compound(check_iface, obj, location);
e440a328 401}
402
403// Convert an expression to a tree. This is implemented by the child
404// class. Not that it is not in general safe to call this multiple
405// times for a single expression, but that we don't catch such errors.
406
407tree
408Expression::get_tree(Translate_context* context)
409{
410 // The child may have marked this expression as having an error.
411 if (this->classification_ == EXPRESSION_ERROR)
412 return error_mark_node;
413
414 return this->do_get_tree(context);
415}
416
48c2a53a 417// Return a backend expression for VAL.
418Bexpression*
419Expression::backend_numeric_constant_expression(Translate_context* context,
420 Numeric_constant* val)
e440a328 421{
48c2a53a 422 Gogo* gogo = context->gogo();
423 Type* type = val->type();
424 if (type == NULL)
425 return gogo->backend()->error_expression();
e440a328 426
48c2a53a 427 Btype* btype = type->get_backend(gogo);
428 Bexpression* ret;
429 if (type->integer_type() != NULL)
e440a328 430 {
431 mpz_t ival;
48c2a53a 432 if (!val->to_int(&ival))
433 {
434 go_assert(saw_errors());
435 return gogo->backend()->error_expression();
436 }
437 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 438 mpz_clear(ival);
e440a328 439 }
48c2a53a 440 else if (type->float_type() != NULL)
e440a328 441 {
48c2a53a 442 mpfr_t fval;
443 if (!val->to_float(&fval))
444 {
445 go_assert(saw_errors());
446 return gogo->backend()->error_expression();
447 }
448 ret = gogo->backend()->float_constant_expression(btype, fval);
449 mpfr_clear(fval);
e440a328 450 }
48c2a53a 451 else if (type->complex_type() != NULL)
e440a328 452 {
48c2a53a 453 mpfr_t real;
454 mpfr_t imag;
455 if (!val->to_complex(&real, &imag))
456 {
457 go_assert(saw_errors());
458 return gogo->backend()->error_expression();
459 }
460 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
461 mpfr_clear(real);
462 mpfr_clear(imag);
e440a328 463 }
464 else
c3e6f413 465 go_unreachable();
e440a328 466
48c2a53a 467 return ret;
e440a328 468}
469
2c809f8f 470// Return an expression which evaluates to true if VAL, of arbitrary integer
471// type, is negative or is more than the maximum value of the Go type "int".
e440a328 472
2c809f8f 473Expression*
474Expression::check_bounds(Expression* val, Location loc)
e440a328 475{
2c809f8f 476 Type* val_type = val->type();
477 Type* bound_type = Type::lookup_integer_type("int");
478
479 int val_type_size;
480 bool val_is_unsigned = false;
481 if (val_type->integer_type() != NULL)
482 {
483 val_type_size = val_type->integer_type()->bits();
484 val_is_unsigned = val_type->integer_type()->is_unsigned();
485 }
486 else
487 {
488 if (!val_type->is_numeric_type()
489 || !Type::are_convertible(bound_type, val_type, NULL))
490 {
491 go_assert(saw_errors());
492 return Expression::make_boolean(true, loc);
493 }
e440a328 494
2c809f8f 495 if (val_type->complex_type() != NULL)
496 val_type_size = val_type->complex_type()->bits();
497 else
498 val_type_size = val_type->float_type()->bits();
499 }
500
501 Expression* negative_index = Expression::make_boolean(false, loc);
502 Expression* index_overflows = Expression::make_boolean(false, loc);
503 if (!val_is_unsigned)
e440a328 504 {
2c809f8f 505 mpz_t zval;
506 mpz_init_set_ui(zval, 0UL);
507 Expression* zero = Expression::make_integer(&zval, val_type, loc);
508 mpz_clear(zval);
509
510 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
e440a328 511 }
512
2c809f8f 513 int bound_type_size = bound_type->integer_type()->bits();
c3068ac0 514 if (val_type_size > bound_type_size
515 || (val_type_size == bound_type_size
2c809f8f 516 && val_is_unsigned))
517 {
518 mpz_t one;
519 mpz_init_set_ui(one, 1UL);
520
521 // maxval = 2^(bound_type_size - 1) - 1
522 mpz_t maxval;
523 mpz_init(maxval);
524 mpz_mul_2exp(maxval, one, bound_type_size - 1);
525 mpz_sub_ui(maxval, maxval, 1);
526 Expression* max = Expression::make_integer(&maxval, val_type, loc);
527 mpz_clear(one);
528 mpz_clear(maxval);
529
530 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
e440a328 531 }
532
2c809f8f 533 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
534 loc);
e440a328 535}
536
d751bb78 537void
538Expression::dump_expression(Ast_dump_context* ast_dump_context) const
539{
540 this->do_dump_expression(ast_dump_context);
541}
542
e440a328 543// Error expressions. This are used to avoid cascading errors.
544
545class Error_expression : public Expression
546{
547 public:
b13c66cd 548 Error_expression(Location location)
e440a328 549 : Expression(EXPRESSION_ERROR, location)
550 { }
551
552 protected:
553 bool
554 do_is_constant() const
555 { return true; }
556
0e168074 557 bool
558 do_is_immutable() const
559 { return true; }
560
e440a328 561 bool
0c77715b 562 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 563 {
0c77715b 564 nc->set_unsigned_long(NULL, 0);
e440a328 565 return true;
566 }
567
4f2138d7 568 bool
e440a328 569 do_discarding_value()
4f2138d7 570 { return true; }
e440a328 571
572 Type*
573 do_type()
574 { return Type::make_error_type(); }
575
576 void
577 do_determine_type(const Type_context*)
578 { }
579
580 Expression*
581 do_copy()
582 { return this; }
583
584 bool
585 do_is_addressable() const
586 { return true; }
587
588 tree
589 do_get_tree(Translate_context*)
590 { return error_mark_node; }
d751bb78 591
592 void
593 do_dump_expression(Ast_dump_context*) const;
e440a328 594};
595
d751bb78 596// Dump the ast representation for an error expression to a dump context.
597
598void
599Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
600{
601 ast_dump_context->ostream() << "_Error_" ;
602}
603
e440a328 604Expression*
b13c66cd 605Expression::make_error(Location location)
e440a328 606{
607 return new Error_expression(location);
608}
609
610// An expression which is really a type. This is used during parsing.
611// It is an error if these survive after lowering.
612
613class
614Type_expression : public Expression
615{
616 public:
b13c66cd 617 Type_expression(Type* type, Location location)
e440a328 618 : Expression(EXPRESSION_TYPE, location),
619 type_(type)
620 { }
621
622 protected:
623 int
624 do_traverse(Traverse* traverse)
625 { return Type::traverse(this->type_, traverse); }
626
627 Type*
628 do_type()
629 { return this->type_; }
630
631 void
632 do_determine_type(const Type_context*)
633 { }
634
635 void
636 do_check_types(Gogo*)
637 { this->report_error(_("invalid use of type")); }
638
639 Expression*
640 do_copy()
641 { return this; }
642
643 tree
644 do_get_tree(Translate_context*)
c3e6f413 645 { go_unreachable(); }
e440a328 646
d751bb78 647 void do_dump_expression(Ast_dump_context*) const;
648
e440a328 649 private:
650 // The type which we are representing as an expression.
651 Type* type_;
652};
653
d751bb78 654void
655Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
656{
657 ast_dump_context->dump_type(this->type_);
658}
659
e440a328 660Expression*
b13c66cd 661Expression::make_type(Type* type, Location location)
e440a328 662{
663 return new Type_expression(type, location);
664}
665
e03bdf36 666// Class Parser_expression.
667
668Type*
669Parser_expression::do_type()
670{
671 // We should never really ask for the type of a Parser_expression.
672 // However, it can happen, at least when we have an invalid const
673 // whose initializer refers to the const itself. In that case we
674 // may ask for the type when lowering the const itself.
c484d925 675 go_assert(saw_errors());
e03bdf36 676 return Type::make_error_type();
677}
678
e440a328 679// Class Var_expression.
680
681// Lower a variable expression. Here we just make sure that the
682// initialization expression of the variable has been lowered. This
683// ensures that we will be able to determine the type of the variable
684// if necessary.
685
686Expression*
ceeb4318 687Var_expression::do_lower(Gogo* gogo, Named_object* function,
688 Statement_inserter* inserter, int)
e440a328 689{
690 if (this->variable_->is_variable())
691 {
692 Variable* var = this->variable_->var_value();
693 // This is either a local variable or a global variable. A
694 // reference to a variable which is local to an enclosing
695 // function will be a reference to a field in a closure.
696 if (var->is_global())
ceeb4318 697 {
698 function = NULL;
699 inserter = NULL;
700 }
701 var->lower_init_expression(gogo, function, inserter);
e440a328 702 }
703 return this;
704}
705
e440a328 706// Return the type of a reference to a variable.
707
708Type*
709Var_expression::do_type()
710{
711 if (this->variable_->is_variable())
712 return this->variable_->var_value()->type();
713 else if (this->variable_->is_result_variable())
714 return this->variable_->result_var_value()->type();
715 else
c3e6f413 716 go_unreachable();
e440a328 717}
718
0ab09e06 719// Determine the type of a reference to a variable.
720
721void
722Var_expression::do_determine_type(const Type_context*)
723{
724 if (this->variable_->is_variable())
725 this->variable_->var_value()->determine_type();
726}
727
e440a328 728// Something takes the address of this variable. This means that we
729// may want to move the variable onto the heap.
730
731void
732Var_expression::do_address_taken(bool escapes)
733{
734 if (!escapes)
f325319b 735 {
736 if (this->variable_->is_variable())
737 this->variable_->var_value()->set_non_escaping_address_taken();
738 else if (this->variable_->is_result_variable())
739 this->variable_->result_var_value()->set_non_escaping_address_taken();
740 else
741 go_unreachable();
742 }
e440a328 743 else
f325319b 744 {
745 if (this->variable_->is_variable())
746 this->variable_->var_value()->set_address_taken();
747 else if (this->variable_->is_result_variable())
748 this->variable_->result_var_value()->set_address_taken();
749 else
750 go_unreachable();
751 }
e440a328 752}
753
754// Get the tree for a reference to a variable.
755
756tree
757Var_expression::do_get_tree(Translate_context* context)
758{
fe2f84cf 759 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
760 context->function());
fe2f84cf 761 bool is_in_heap;
c6777780 762 Location loc = this->location();
9b27b43c 763 Btype* btype;
764 Gogo* gogo = context->gogo();
fe2f84cf 765 if (this->variable_->is_variable())
9b27b43c 766 {
767 is_in_heap = this->variable_->var_value()->is_in_heap();
768 btype = this->variable_->var_value()->type()->get_backend(gogo);
769 }
fe2f84cf 770 else if (this->variable_->is_result_variable())
9b27b43c 771 {
772 is_in_heap = this->variable_->result_var_value()->is_in_heap();
773 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
774 }
fe2f84cf 775 else
c3e6f413 776 go_unreachable();
c6777780 777
778 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 779 if (is_in_heap)
9b27b43c 780 ret = context->backend()->indirect_expression(btype, ret, true, loc);
c6777780 781 return expr_to_tree(ret);
e440a328 782}
783
d751bb78 784// Ast dump for variable expression.
785
786void
787Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
788{
789 ast_dump_context->ostream() << this->variable_->name() ;
790}
791
e440a328 792// Make a reference to a variable in an expression.
793
794Expression*
b13c66cd 795Expression::make_var_reference(Named_object* var, Location location)
e440a328 796{
797 if (var->is_sink())
798 return Expression::make_sink(location);
799
800 // FIXME: Creating a new object for each reference to a variable is
801 // wasteful.
802 return new Var_expression(var, location);
803}
804
805// Class Temporary_reference_expression.
806
807// The type.
808
809Type*
810Temporary_reference_expression::do_type()
811{
812 return this->statement_->type();
813}
814
815// Called if something takes the address of this temporary variable.
816// We never have to move temporary variables to the heap, but we do
817// need to know that they must live in the stack rather than in a
818// register.
819
820void
821Temporary_reference_expression::do_address_taken(bool)
822{
823 this->statement_->set_is_address_taken();
824}
825
826// Get a tree referring to the variable.
827
828tree
eefc1ed3 829Temporary_reference_expression::do_get_tree(Translate_context* context)
e440a328 830{
cd440cff 831 Gogo* gogo = context->gogo();
eefc1ed3 832 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 833 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 834
cd440cff 835 // The backend can't always represent the same set of recursive types
eefc1ed3 836 // that the Go frontend can. In some cases this means that a
837 // temporary variable won't have the right backend type. Correct
838 // that here by adding a type cast. We need to use base() to push
839 // the circularity down one level.
cd440cff 840 Type* stype = this->statement_->type();
ceeb4318 841 if (!this->is_lvalue_
cd440cff 842 && stype->has_pointer()
843 && stype->deref()->is_void_type())
eefc1ed3 844 {
cd440cff 845 Btype* btype = this->type()->base()->get_backend(gogo);
846 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 847 }
cd440cff 848 return expr_to_tree(ret);
e440a328 849}
850
d751bb78 851// Ast dump for temporary reference.
852
853void
854Temporary_reference_expression::do_dump_expression(
855 Ast_dump_context* ast_dump_context) const
856{
857 ast_dump_context->dump_temp_variable_name(this->statement_);
858}
859
e440a328 860// Make a reference to a temporary variable.
861
ceeb4318 862Temporary_reference_expression*
e440a328 863Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 864 Location location)
e440a328 865{
866 return new Temporary_reference_expression(statement, location);
867}
868
e9d3367e 869// Class Set_and_use_temporary_expression.
870
871// Return the type.
872
873Type*
874Set_and_use_temporary_expression::do_type()
875{
876 return this->statement_->type();
877}
878
0afbb937 879// Determine the type of the expression.
880
881void
882Set_and_use_temporary_expression::do_determine_type(
883 const Type_context* context)
884{
885 this->expr_->determine_type(context);
886}
887
e9d3367e 888// Take the address.
889
890void
891Set_and_use_temporary_expression::do_address_taken(bool)
892{
893 this->statement_->set_is_address_taken();
894}
895
896// Return the backend representation.
897
898tree
899Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
900{
e9d3367e 901 Location loc = this->location();
a302c105 902 Gogo* gogo = context->gogo();
903 Bvariable* bvar = this->statement_->get_backend_variable(context);
904 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
905
906 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
907 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
908 var_ref = gogo->backend()->var_expression(bvar, loc);
909 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
910 return expr_to_tree(ret);
e9d3367e 911}
912
913// Dump.
914
915void
916Set_and_use_temporary_expression::do_dump_expression(
917 Ast_dump_context* ast_dump_context) const
918{
919 ast_dump_context->ostream() << '(';
920 ast_dump_context->dump_temp_variable_name(this->statement_);
921 ast_dump_context->ostream() << " = ";
922 this->expr_->dump_expression(ast_dump_context);
923 ast_dump_context->ostream() << ')';
924}
925
926// Make a set-and-use temporary.
927
928Set_and_use_temporary_expression*
929Expression::make_set_and_use_temporary(Temporary_statement* statement,
930 Expression* expr, Location location)
931{
932 return new Set_and_use_temporary_expression(statement, expr, location);
933}
934
e440a328 935// A sink expression--a use of the blank identifier _.
936
937class Sink_expression : public Expression
938{
939 public:
b13c66cd 940 Sink_expression(Location location)
e440a328 941 : Expression(EXPRESSION_SINK, location),
aa93217a 942 type_(NULL), bvar_(NULL)
e440a328 943 { }
944
945 protected:
4f2138d7 946 bool
e440a328 947 do_discarding_value()
4f2138d7 948 { return true; }
e440a328 949
950 Type*
951 do_type();
952
953 void
954 do_determine_type(const Type_context*);
955
956 Expression*
957 do_copy()
958 { return new Sink_expression(this->location()); }
959
960 tree
961 do_get_tree(Translate_context*);
962
d751bb78 963 void
964 do_dump_expression(Ast_dump_context*) const;
965
e440a328 966 private:
967 // The type of this sink variable.
968 Type* type_;
969 // The temporary variable we generate.
aa93217a 970 Bvariable* bvar_;
e440a328 971};
972
973// Return the type of a sink expression.
974
975Type*
976Sink_expression::do_type()
977{
978 if (this->type_ == NULL)
979 return Type::make_sink_type();
980 return this->type_;
981}
982
983// Determine the type of a sink expression.
984
985void
986Sink_expression::do_determine_type(const Type_context* context)
987{
988 if (context->type != NULL)
989 this->type_ = context->type;
990}
991
992// Return a temporary variable for a sink expression. This will
993// presumably be a write-only variable which the middle-end will drop.
994
995tree
996Sink_expression::do_get_tree(Translate_context* context)
997{
aa93217a 998 Location loc = this->location();
999 Gogo* gogo = context->gogo();
1000 if (this->bvar_ == NULL)
e440a328 1001 {
c484d925 1002 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
aa93217a 1003 Named_object* fn = context->function();
1004 go_assert(fn != NULL);
1005 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
9f0e0513 1006 Btype* bt = this->type_->get_backend(context->gogo());
aa93217a 1007 Bstatement* decl;
1008 this->bvar_ =
1009 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1010 false, loc, &decl);
1011 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1012 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1013 return expr_to_tree(var_ref);
e440a328 1014 }
aa93217a 1015 return expr_to_tree(gogo->backend()->var_expression(this->bvar_, loc));
e440a328 1016}
1017
d751bb78 1018// Ast dump for sink expression.
1019
1020void
1021Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1022{
1023 ast_dump_context->ostream() << "_" ;
1024}
1025
e440a328 1026// Make a sink expression.
1027
1028Expression*
b13c66cd 1029Expression::make_sink(Location location)
e440a328 1030{
1031 return new Sink_expression(location);
1032}
1033
1034// Class Func_expression.
1035
1036// FIXME: Can a function expression appear in a constant expression?
1037// The value is unchanging. Initializing a constant to the address of
1038// a function seems like it could work, though there might be little
1039// point to it.
1040
e440a328 1041// Traversal.
1042
1043int
1044Func_expression::do_traverse(Traverse* traverse)
1045{
1046 return (this->closure_ == NULL
1047 ? TRAVERSE_CONTINUE
1048 : Expression::traverse(&this->closure_, traverse));
1049}
1050
1051// Return the type of a function expression.
1052
1053Type*
1054Func_expression::do_type()
1055{
1056 if (this->function_->is_function())
1057 return this->function_->func_value()->type();
1058 else if (this->function_->is_function_declaration())
1059 return this->function_->func_declaration_value()->type();
1060 else
c3e6f413 1061 go_unreachable();
e440a328 1062}
1063
8381eda7 1064// Get the tree for the code of a function expression.
e440a328 1065
97267c39 1066Bexpression*
8381eda7 1067Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1068{
1069 Function_type* fntype;
8381eda7 1070 if (no->is_function())
1071 fntype = no->func_value()->type();
1072 else if (no->is_function_declaration())
1073 fntype = no->func_declaration_value()->type();
e440a328 1074 else
c3e6f413 1075 go_unreachable();
e440a328 1076
1077 // Builtin functions are handled specially by Call_expression. We
1078 // can't take their address.
1079 if (fntype->is_builtin())
1080 {
8381eda7 1081 error_at(loc,
cb0e02f3 1082 "invalid use of special builtin function %qs; must be called",
8381eda7 1083 no->message_name().c_str());
97267c39 1084 return gogo->backend()->error_expression();
e440a328 1085 }
1086
97267c39 1087 Bfunction* fndecl;
e440a328 1088 if (no->is_function())
cf3cae55 1089 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1090 else if (no->is_function_declaration())
cf3cae55 1091 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1092 else
c3e6f413 1093 go_unreachable();
e440a328 1094
97267c39 1095 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1096}
1097
1098// Get the tree for a function expression. This is used when we take
8381eda7 1099// the address of a function rather than simply calling it. A func
1100// value is represented as a pointer to a block of memory. The first
1101// word of that memory is a pointer to the function code. The
1102// remaining parts of that memory are the addresses of variables that
1103// the function closes over.
e440a328 1104
1105tree
1106Func_expression::do_get_tree(Translate_context* context)
1107{
8381eda7 1108 // If there is no closure, just use the function descriptor.
2010c17a 1109 if (this->closure_ == NULL)
8381eda7 1110 {
1111 Gogo* gogo = context->gogo();
1112 Named_object* no = this->function_;
1113 Expression* descriptor;
1114 if (no->is_function())
1115 descriptor = no->func_value()->descriptor(gogo, no);
1116 else if (no->is_function_declaration())
1117 {
1118 if (no->func_declaration_value()->type()->is_builtin())
1119 {
1120 error_at(this->location(),
1121 ("invalid use of special builtin function %qs; "
1122 "must be called"),
1123 no->message_name().c_str());
1124 return error_mark_node;
1125 }
1126 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1127 }
1128 else
1129 go_unreachable();
2010c17a 1130
8381eda7 1131 tree dtree = descriptor->get_tree(context);
1132 if (dtree == error_mark_node)
1133 return error_mark_node;
1134 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1135 }
e440a328 1136
8381eda7 1137 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1138
8381eda7 1139 // If there is a closure, then the closure is itself the function
1140 // expression. It is a pointer to a struct whose first field points
1141 // to the function code and whose remaining fields are the addresses
1142 // of the closed-over variables.
1143 return this->closure_->get_tree(context);
e440a328 1144}
1145
d751bb78 1146// Ast dump for function.
1147
1148void
1149Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1150{
8b1c301d 1151 ast_dump_context->ostream() << this->function_->name();
1152 if (this->closure_ != NULL)
1153 {
1154 ast_dump_context->ostream() << " {closure = ";
1155 this->closure_->dump_expression(ast_dump_context);
1156 ast_dump_context->ostream() << "}";
1157 }
d751bb78 1158}
1159
e440a328 1160// Make a reference to a function in an expression.
1161
1162Expression*
1163Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1164 Location location)
e440a328 1165{
1166 return new Func_expression(function, closure, location);
1167}
1168
c6837989 1169// Class Func_descriptor_expression.
8381eda7 1170
c6837989 1171// Constructor.
8381eda7 1172
c6837989 1173Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1174 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1175 fn_(fn), dvar_(NULL)
c6837989 1176{
1177 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1178}
8381eda7 1179
c6837989 1180// Traversal.
8381eda7 1181
c6837989 1182int
1183Func_descriptor_expression::do_traverse(Traverse*)
1184{
1185 return TRAVERSE_CONTINUE;
1186}
8381eda7 1187
1188// All function descriptors have the same type.
1189
1190Type* Func_descriptor_expression::descriptor_type;
1191
1192void
1193Func_descriptor_expression::make_func_descriptor_type()
1194{
1195 if (Func_descriptor_expression::descriptor_type != NULL)
1196 return;
1197 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1198 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1199 Func_descriptor_expression::descriptor_type =
1200 Type::make_builtin_named_type("functionDescriptor", struct_type);
1201}
1202
1203Type*
1204Func_descriptor_expression::do_type()
1205{
1206 Func_descriptor_expression::make_func_descriptor_type();
1207 return Func_descriptor_expression::descriptor_type;
1208}
1209
1210// The tree for a function descriptor.
1211
1212tree
1213Func_descriptor_expression::do_get_tree(Translate_context* context)
1214{
1215 if (this->dvar_ != NULL)
1216 return var_to_tree(this->dvar_);
1217
1218 Gogo* gogo = context->gogo();
1219 Named_object* no = this->fn_;
1220 Location loc = no->location();
1221
1222 std::string var_name;
1223 if (no->package() == NULL)
1224 var_name = gogo->pkgpath_symbol();
1225 else
1226 var_name = no->package()->pkgpath_symbol();
1227 var_name.push_back('.');
1228 var_name.append(Gogo::unpack_hidden_name(no->name()));
1229 var_name.append("$descriptor");
1230
1231 Btype* btype = this->type()->get_backend(gogo);
1232
1233 Bvariable* bvar;
1234 if (no->package() != NULL
1235 || Linemap::is_predeclared_location(no->location()))
f8bdf81a 1236 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1237 loc);
8381eda7 1238 else
1239 {
1240 Location bloc = Linemap::predeclared_location();
1241 bool is_hidden = ((no->is_function()
1242 && no->func_value()->enclosing() != NULL)
1243 || Gogo::is_thunk(no));
1244 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1245 btype, bloc);
1246 Expression_list* vals = new Expression_list();
f8bdf81a 1247 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1248 Expression* init =
1249 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1250 Translate_context bcontext(gogo, NULL, NULL, NULL);
1251 bcontext.set_is_const();
1252 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1253 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1254 false, btype, bloc, binit);
1255 }
1256
1257 this->dvar_ = bvar;
1258 return var_to_tree(bvar);
1259}
1260
c6837989 1261// Print a function descriptor expression.
1262
1263void
1264Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1265{
1266 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1267}
1268
8381eda7 1269// Make a function descriptor expression.
1270
c6837989 1271Func_descriptor_expression*
1272Expression::make_func_descriptor(Named_object* fn)
8381eda7 1273{
c6837989 1274 return new Func_descriptor_expression(fn);
8381eda7 1275}
1276
1277// Make the function descriptor type, so that it can be converted.
1278
1279void
1280Expression::make_func_descriptor_type()
1281{
1282 Func_descriptor_expression::make_func_descriptor_type();
1283}
1284
1285// A reference to just the code of a function.
1286
1287class Func_code_reference_expression : public Expression
1288{
1289 public:
1290 Func_code_reference_expression(Named_object* function, Location location)
1291 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1292 function_(function)
1293 { }
1294
1295 protected:
1296 int
1297 do_traverse(Traverse*)
1298 { return TRAVERSE_CONTINUE; }
1299
f9ca30f9 1300 bool
1301 do_is_immutable() const
1302 { return true; }
1303
8381eda7 1304 Type*
1305 do_type()
1306 { return Type::make_pointer_type(Type::make_void_type()); }
1307
1308 void
1309 do_determine_type(const Type_context*)
1310 { }
1311
1312 Expression*
1313 do_copy()
1314 {
1315 return Expression::make_func_code_reference(this->function_,
1316 this->location());
1317 }
1318
1319 tree
1320 do_get_tree(Translate_context*);
1321
1322 void
1323 do_dump_expression(Ast_dump_context* context) const
1324 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1325
1326 private:
1327 // The function.
1328 Named_object* function_;
1329};
1330
1331// Get the tree for a reference to function code.
1332
1333tree
1334Func_code_reference_expression::do_get_tree(Translate_context* context)
1335{
97267c39 1336 Bexpression* ret =
1337 Func_expression::get_code_pointer(context->gogo(), this->function_,
1338 this->location());
1339 return expr_to_tree(ret);
8381eda7 1340}
1341
1342// Make a reference to the code of a function.
1343
1344Expression*
1345Expression::make_func_code_reference(Named_object* function, Location location)
1346{
1347 return new Func_code_reference_expression(function, location);
1348}
1349
e440a328 1350// Class Unknown_expression.
1351
1352// Return the name of an unknown expression.
1353
1354const std::string&
1355Unknown_expression::name() const
1356{
1357 return this->named_object_->name();
1358}
1359
1360// Lower a reference to an unknown name.
1361
1362Expression*
ceeb4318 1363Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1364{
b13c66cd 1365 Location location = this->location();
e440a328 1366 Named_object* no = this->named_object_;
deded542 1367 Named_object* real;
1368 if (!no->is_unknown())
1369 real = no;
1370 else
e440a328 1371 {
deded542 1372 real = no->unknown_value()->real_named_object();
1373 if (real == NULL)
1374 {
1375 if (this->is_composite_literal_key_)
1376 return this;
acf8e158 1377 if (!this->no_error_message_)
1378 error_at(location, "reference to undefined name %qs",
1379 this->named_object_->message_name().c_str());
deded542 1380 return Expression::make_error(location);
1381 }
e440a328 1382 }
1383 switch (real->classification())
1384 {
1385 case Named_object::NAMED_OBJECT_CONST:
1386 return Expression::make_const_reference(real, location);
1387 case Named_object::NAMED_OBJECT_TYPE:
1388 return Expression::make_type(real->type_value(), location);
1389 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1390 if (this->is_composite_literal_key_)
1391 return this;
acf8e158 1392 if (!this->no_error_message_)
1393 error_at(location, "reference to undefined type %qs",
1394 real->message_name().c_str());
e440a328 1395 return Expression::make_error(location);
1396 case Named_object::NAMED_OBJECT_VAR:
7d834090 1397 real->var_value()->set_is_used();
e440a328 1398 return Expression::make_var_reference(real, location);
1399 case Named_object::NAMED_OBJECT_FUNC:
1400 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1401 return Expression::make_func_reference(real, NULL, location);
1402 case Named_object::NAMED_OBJECT_PACKAGE:
1403 if (this->is_composite_literal_key_)
1404 return this;
acf8e158 1405 if (!this->no_error_message_)
1406 error_at(location, "unexpected reference to package");
e440a328 1407 return Expression::make_error(location);
1408 default:
c3e6f413 1409 go_unreachable();
e440a328 1410 }
1411}
1412
d751bb78 1413// Dump the ast representation for an unknown expression to a dump context.
1414
1415void
1416Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1417{
1418 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1419 << ")";
d751bb78 1420}
1421
e440a328 1422// Make a reference to an unknown name.
1423
acf8e158 1424Unknown_expression*
b13c66cd 1425Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1426{
e440a328 1427 return new Unknown_expression(no, location);
1428}
1429
1430// A boolean expression.
1431
1432class Boolean_expression : public Expression
1433{
1434 public:
b13c66cd 1435 Boolean_expression(bool val, Location location)
e440a328 1436 : Expression(EXPRESSION_BOOLEAN, location),
1437 val_(val), type_(NULL)
1438 { }
1439
1440 static Expression*
1441 do_import(Import*);
1442
1443 protected:
1444 bool
1445 do_is_constant() const
1446 { return true; }
1447
0e168074 1448 bool
1449 do_is_immutable() const
1450 { return true; }
1451
e440a328 1452 Type*
1453 do_type();
1454
1455 void
1456 do_determine_type(const Type_context*);
1457
1458 Expression*
1459 do_copy()
1460 { return this; }
1461
1462 tree
1463 do_get_tree(Translate_context*)
1464 { return this->val_ ? boolean_true_node : boolean_false_node; }
1465
1466 void
1467 do_export(Export* exp) const
1468 { exp->write_c_string(this->val_ ? "true" : "false"); }
1469
d751bb78 1470 void
1471 do_dump_expression(Ast_dump_context* ast_dump_context) const
1472 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1473
e440a328 1474 private:
1475 // The constant.
1476 bool val_;
1477 // The type as determined by context.
1478 Type* type_;
1479};
1480
1481// Get the type.
1482
1483Type*
1484Boolean_expression::do_type()
1485{
1486 if (this->type_ == NULL)
1487 this->type_ = Type::make_boolean_type();
1488 return this->type_;
1489}
1490
1491// Set the type from the context.
1492
1493void
1494Boolean_expression::do_determine_type(const Type_context* context)
1495{
1496 if (this->type_ != NULL && !this->type_->is_abstract())
1497 ;
1498 else if (context->type != NULL && context->type->is_boolean_type())
1499 this->type_ = context->type;
1500 else if (!context->may_be_abstract)
1501 this->type_ = Type::lookup_bool_type();
1502}
1503
1504// Import a boolean constant.
1505
1506Expression*
1507Boolean_expression::do_import(Import* imp)
1508{
1509 if (imp->peek_char() == 't')
1510 {
1511 imp->require_c_string("true");
1512 return Expression::make_boolean(true, imp->location());
1513 }
1514 else
1515 {
1516 imp->require_c_string("false");
1517 return Expression::make_boolean(false, imp->location());
1518 }
1519}
1520
1521// Make a boolean expression.
1522
1523Expression*
b13c66cd 1524Expression::make_boolean(bool val, Location location)
e440a328 1525{
1526 return new Boolean_expression(val, location);
1527}
1528
1529// Class String_expression.
1530
1531// Get the type.
1532
1533Type*
1534String_expression::do_type()
1535{
1536 if (this->type_ == NULL)
1537 this->type_ = Type::make_string_type();
1538 return this->type_;
1539}
1540
1541// Set the type from the context.
1542
1543void
1544String_expression::do_determine_type(const Type_context* context)
1545{
1546 if (this->type_ != NULL && !this->type_->is_abstract())
1547 ;
1548 else if (context->type != NULL && context->type->is_string_type())
1549 this->type_ = context->type;
1550 else if (!context->may_be_abstract)
1551 this->type_ = Type::lookup_string_type();
1552}
1553
1554// Build a string constant.
1555
1556tree
1557String_expression::do_get_tree(Translate_context* context)
1558{
2c809f8f 1559 Gogo* gogo = context->gogo();
1560 Btype* btype = Type::make_string_type()->get_backend(gogo);
1561
1562 Location loc = this->location();
1563 std::vector<Bexpression*> init(2);
1564 Bexpression* str_cst =
1565 gogo->backend()->string_constant_expression(this->val_);
1566 init[0] = gogo->backend()->address_expression(str_cst, loc);
1567
1568 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1569 mpz_t lenval;
1570 mpz_init_set_ui(lenval, this->val_.length());
1571 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1572 mpz_clear(lenval);
1573
1574 Bexpression* ret = gogo->backend()->constructor_expression(btype, init, loc);
1575 return expr_to_tree(ret);
e440a328 1576}
1577
8b1c301d 1578 // Write string literal to string dump.
e440a328 1579
1580void
8b1c301d 1581String_expression::export_string(String_dump* exp,
1582 const String_expression* str)
e440a328 1583{
1584 std::string s;
8b1c301d 1585 s.reserve(str->val_.length() * 4 + 2);
e440a328 1586 s += '"';
8b1c301d 1587 for (std::string::const_iterator p = str->val_.begin();
1588 p != str->val_.end();
e440a328 1589 ++p)
1590 {
1591 if (*p == '\\' || *p == '"')
1592 {
1593 s += '\\';
1594 s += *p;
1595 }
1596 else if (*p >= 0x20 && *p < 0x7f)
1597 s += *p;
1598 else if (*p == '\n')
1599 s += "\\n";
1600 else if (*p == '\t')
1601 s += "\\t";
1602 else
1603 {
1604 s += "\\x";
1605 unsigned char c = *p;
1606 unsigned int dig = c >> 4;
1607 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1608 dig = c & 0xf;
1609 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1610 }
1611 }
1612 s += '"';
1613 exp->write_string(s);
1614}
1615
8b1c301d 1616// Export a string expression.
1617
1618void
1619String_expression::do_export(Export* exp) const
1620{
1621 String_expression::export_string(exp, this);
1622}
1623
e440a328 1624// Import a string expression.
1625
1626Expression*
1627String_expression::do_import(Import* imp)
1628{
1629 imp->require_c_string("\"");
1630 std::string val;
1631 while (true)
1632 {
1633 int c = imp->get_char();
1634 if (c == '"' || c == -1)
1635 break;
1636 if (c != '\\')
1637 val += static_cast<char>(c);
1638 else
1639 {
1640 c = imp->get_char();
1641 if (c == '\\' || c == '"')
1642 val += static_cast<char>(c);
1643 else if (c == 'n')
1644 val += '\n';
1645 else if (c == 't')
1646 val += '\t';
1647 else if (c == 'x')
1648 {
1649 c = imp->get_char();
1650 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1651 c = imp->get_char();
1652 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653 char v = (vh << 4) | vl;
1654 val += v;
1655 }
1656 else
1657 {
1658 error_at(imp->location(), "bad string constant");
1659 return Expression::make_error(imp->location());
1660 }
1661 }
1662 }
1663 return Expression::make_string(val, imp->location());
1664}
1665
d751bb78 1666// Ast dump for string expression.
1667
1668void
1669String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1670{
8b1c301d 1671 String_expression::export_string(ast_dump_context, this);
d751bb78 1672}
1673
e440a328 1674// Make a string expression.
1675
1676Expression*
b13c66cd 1677Expression::make_string(const std::string& val, Location location)
e440a328 1678{
1679 return new String_expression(val, location);
1680}
1681
2c809f8f 1682// An expression that evaluates to some characteristic of a string.
1683// This is used when indexing, bound-checking, or nil checking a string.
1684
1685class String_info_expression : public Expression
1686{
1687 public:
1688 String_info_expression(Expression* string, String_info string_info,
1689 Location location)
1690 : Expression(EXPRESSION_STRING_INFO, location),
1691 string_(string), string_info_(string_info)
1692 { }
1693
1694 protected:
1695 Type*
1696 do_type();
1697
1698 void
1699 do_determine_type(const Type_context*)
1700 { go_unreachable(); }
1701
1702 Expression*
1703 do_copy()
1704 {
1705 return new String_info_expression(this->string_->copy(), this->string_info_,
1706 this->location());
1707 }
1708
1709 tree
1710 do_get_tree(Translate_context* context);
1711
1712 void
1713 do_dump_expression(Ast_dump_context*) const;
1714
1715 void
1716 do_issue_nil_check()
1717 { this->string_->issue_nil_check(); }
1718
1719 private:
1720 // The string for which we are getting information.
1721 Expression* string_;
1722 // What information we want.
1723 String_info string_info_;
1724};
1725
1726// Return the type of the string info.
1727
1728Type*
1729String_info_expression::do_type()
1730{
1731 switch (this->string_info_)
1732 {
1733 case STRING_INFO_DATA:
1734 {
1735 Type* byte_type = Type::lookup_integer_type("uint8");
1736 return Type::make_pointer_type(byte_type);
1737 }
1738 case STRING_INFO_LENGTH:
1739 return Type::lookup_integer_type("int");
1740 default:
1741 go_unreachable();
1742 }
1743}
1744
1745// Return string information in GENERIC.
1746
1747tree
1748String_info_expression::do_get_tree(Translate_context* context)
1749{
1750 Gogo* gogo = context->gogo();
1751
1752 Bexpression* bstring = tree_to_expr(this->string_->get_tree(context));
1753 Bexpression* ret;
1754 switch (this->string_info_)
1755 {
1756 case STRING_INFO_DATA:
1757 case STRING_INFO_LENGTH:
1758 ret = gogo->backend()->struct_field_expression(bstring, this->string_info_,
1759 this->location());
1760 break;
1761 default:
1762 go_unreachable();
1763 }
1764 return expr_to_tree(ret);
1765}
1766
1767// Dump ast representation for a type info expression.
1768
1769void
1770String_info_expression::do_dump_expression(
1771 Ast_dump_context* ast_dump_context) const
1772{
1773 ast_dump_context->ostream() << "stringinfo(";
1774 this->string_->dump_expression(ast_dump_context);
1775 ast_dump_context->ostream() << ",";
1776 ast_dump_context->ostream() <<
1777 (this->string_info_ == STRING_INFO_DATA ? "data"
1778 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1779 : "unknown");
1780 ast_dump_context->ostream() << ")";
1781}
1782
1783// Make a string info expression.
1784
1785Expression*
1786Expression::make_string_info(Expression* string, String_info string_info,
1787 Location location)
1788{
1789 return new String_info_expression(string, string_info, location);
1790}
1791
e440a328 1792// Make an integer expression.
1793
1794class Integer_expression : public Expression
1795{
1796 public:
5d4b8566 1797 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1798 Location location)
e440a328 1799 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1800 type_(type), is_character_constant_(is_character_constant)
e440a328 1801 { mpz_init_set(this->val_, *val); }
1802
1803 static Expression*
1804 do_import(Import*);
1805
8b1c301d 1806 // Write VAL to string dump.
e440a328 1807 static void
8b1c301d 1808 export_integer(String_dump* exp, const mpz_t val);
e440a328 1809
d751bb78 1810 // Write VAL to dump context.
1811 static void
1812 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1813
e440a328 1814 protected:
1815 bool
1816 do_is_constant() const
1817 { return true; }
1818
0e168074 1819 bool
1820 do_is_immutable() const
1821 { return true; }
1822
e440a328 1823 bool
0c77715b 1824 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1825
1826 Type*
1827 do_type();
1828
1829 void
1830 do_determine_type(const Type_context* context);
1831
1832 void
1833 do_check_types(Gogo*);
1834
1835 tree
1836 do_get_tree(Translate_context*);
1837
1838 Expression*
1839 do_copy()
5d4b8566 1840 {
1841 if (this->is_character_constant_)
1842 return Expression::make_character(&this->val_, this->type_,
1843 this->location());
1844 else
1845 return Expression::make_integer(&this->val_, this->type_,
1846 this->location());
1847 }
e440a328 1848
1849 void
1850 do_export(Export*) const;
1851
d751bb78 1852 void
1853 do_dump_expression(Ast_dump_context*) const;
1854
e440a328 1855 private:
1856 // The integer value.
1857 mpz_t val_;
1858 // The type so far.
1859 Type* type_;
5d4b8566 1860 // Whether this is a character constant.
1861 bool is_character_constant_;
e440a328 1862};
1863
0c77715b 1864// Return a numeric constant for this expression. We have to mark
1865// this as a character when appropriate.
e440a328 1866
1867bool
0c77715b 1868Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1869{
0c77715b 1870 if (this->is_character_constant_)
1871 nc->set_rune(this->type_, this->val_);
1872 else
1873 nc->set_int(this->type_, this->val_);
e440a328 1874 return true;
1875}
1876
1877// Return the current type. If we haven't set the type yet, we return
1878// an abstract integer type.
1879
1880Type*
1881Integer_expression::do_type()
1882{
1883 if (this->type_ == NULL)
5d4b8566 1884 {
1885 if (this->is_character_constant_)
1886 this->type_ = Type::make_abstract_character_type();
1887 else
1888 this->type_ = Type::make_abstract_integer_type();
1889 }
e440a328 1890 return this->type_;
1891}
1892
1893// Set the type of the integer value. Here we may switch from an
1894// abstract type to a real type.
1895
1896void
1897Integer_expression::do_determine_type(const Type_context* context)
1898{
1899 if (this->type_ != NULL && !this->type_->is_abstract())
1900 ;
0c77715b 1901 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1902 this->type_ = context->type;
1903 else if (!context->may_be_abstract)
5d4b8566 1904 {
1905 if (this->is_character_constant_)
1906 this->type_ = Type::lookup_integer_type("int32");
1907 else
1908 this->type_ = Type::lookup_integer_type("int");
1909 }
e440a328 1910}
1911
e440a328 1912// Check the type of an integer constant.
1913
1914void
1915Integer_expression::do_check_types(Gogo*)
1916{
0c77715b 1917 Type* type = this->type_;
1918 if (type == NULL)
e440a328 1919 return;
0c77715b 1920 Numeric_constant nc;
1921 if (this->is_character_constant_)
1922 nc.set_rune(NULL, this->val_);
1923 else
1924 nc.set_int(NULL, this->val_);
1925 if (!nc.set_type(type, true, this->location()))
e440a328 1926 this->set_is_error();
1927}
1928
1929// Get a tree for an integer constant.
1930
1931tree
1932Integer_expression::do_get_tree(Translate_context* context)
1933{
48c2a53a 1934 Type* resolved_type = NULL;
e440a328 1935 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 1936 resolved_type = this->type_;
e440a328 1937 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1938 {
1939 // We are converting to an abstract floating point type.
48c2a53a 1940 resolved_type = Type::lookup_float_type("float64");
e440a328 1941 }
1942 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1943 {
1944 // We are converting to an abstract complex type.
48c2a53a 1945 resolved_type = Type::lookup_complex_type("complex128");
e440a328 1946 }
1947 else
1948 {
1949 // If we still have an abstract type here, then this is being
1950 // used in a constant expression which didn't get reduced for
1951 // some reason. Use a type which will fit the value. We use <,
1952 // not <=, because we need an extra bit for the sign bit.
1953 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 1954 Type* int_type = Type::lookup_integer_type("int");
1955 if (bits < int_type->integer_type()->bits())
48c2a53a 1956 resolved_type = int_type;
e440a328 1957 else if (bits < 64)
48c2a53a 1958 resolved_type = Type::lookup_integer_type("int64");
e440a328 1959 else
48c2a53a 1960 {
1961 if (!saw_errors())
1962 error_at(this->location(),
1963 "unknown type for large integer constant");
1964 Bexpression* ret = context->gogo()->backend()->error_expression();
1965 return expr_to_tree(ret);
1966 }
e440a328 1967 }
48c2a53a 1968 Numeric_constant nc;
1969 nc.set_int(resolved_type, this->val_);
1970 Bexpression* ret =
1971 Expression::backend_numeric_constant_expression(context, &nc);
1972 return expr_to_tree(ret);
e440a328 1973}
1974
1975// Write VAL to export data.
1976
1977void
8b1c301d 1978Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 1979{
1980 char* s = mpz_get_str(NULL, 10, val);
1981 exp->write_c_string(s);
1982 free(s);
1983}
1984
1985// Export an integer in a constant expression.
1986
1987void
1988Integer_expression::do_export(Export* exp) const
1989{
1990 Integer_expression::export_integer(exp, this->val_);
5d4b8566 1991 if (this->is_character_constant_)
1992 exp->write_c_string("'");
e440a328 1993 // A trailing space lets us reliably identify the end of the number.
1994 exp->write_c_string(" ");
1995}
1996
1997// Import an integer, floating point, or complex value. This handles
1998// all these types because they all start with digits.
1999
2000Expression*
2001Integer_expression::do_import(Import* imp)
2002{
2003 std::string num = imp->read_identifier();
2004 imp->require_c_string(" ");
2005 if (!num.empty() && num[num.length() - 1] == 'i')
2006 {
2007 mpfr_t real;
2008 size_t plus_pos = num.find('+', 1);
2009 size_t minus_pos = num.find('-', 1);
2010 size_t pos;
2011 if (plus_pos == std::string::npos)
2012 pos = minus_pos;
2013 else if (minus_pos == std::string::npos)
2014 pos = plus_pos;
2015 else
2016 {
2017 error_at(imp->location(), "bad number in import data: %qs",
2018 num.c_str());
2019 return Expression::make_error(imp->location());
2020 }
2021 if (pos == std::string::npos)
2022 mpfr_set_ui(real, 0, GMP_RNDN);
2023 else
2024 {
2025 std::string real_str = num.substr(0, pos);
2026 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2027 {
2028 error_at(imp->location(), "bad number in import data: %qs",
2029 real_str.c_str());
2030 return Expression::make_error(imp->location());
2031 }
2032 }
2033
2034 std::string imag_str;
2035 if (pos == std::string::npos)
2036 imag_str = num;
2037 else
2038 imag_str = num.substr(pos);
2039 imag_str = imag_str.substr(0, imag_str.size() - 1);
2040 mpfr_t imag;
2041 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2042 {
2043 error_at(imp->location(), "bad number in import data: %qs",
2044 imag_str.c_str());
2045 return Expression::make_error(imp->location());
2046 }
2047 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2048 imp->location());
2049 mpfr_clear(real);
2050 mpfr_clear(imag);
2051 return ret;
2052 }
2053 else if (num.find('.') == std::string::npos
2054 && num.find('E') == std::string::npos)
2055 {
5d4b8566 2056 bool is_character_constant = (!num.empty()
2057 && num[num.length() - 1] == '\'');
2058 if (is_character_constant)
2059 num = num.substr(0, num.length() - 1);
e440a328 2060 mpz_t val;
2061 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2062 {
2063 error_at(imp->location(), "bad number in import data: %qs",
2064 num.c_str());
2065 return Expression::make_error(imp->location());
2066 }
5d4b8566 2067 Expression* ret;
2068 if (is_character_constant)
2069 ret = Expression::make_character(&val, NULL, imp->location());
2070 else
2071 ret = Expression::make_integer(&val, NULL, imp->location());
e440a328 2072 mpz_clear(val);
2073 return ret;
2074 }
2075 else
2076 {
2077 mpfr_t val;
2078 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2079 {
2080 error_at(imp->location(), "bad number in import data: %qs",
2081 num.c_str());
2082 return Expression::make_error(imp->location());
2083 }
2084 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2085 mpfr_clear(val);
2086 return ret;
2087 }
2088}
d751bb78 2089// Ast dump for integer expression.
2090
2091void
2092Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2093{
5d4b8566 2094 if (this->is_character_constant_)
2095 ast_dump_context->ostream() << '\'';
8b1c301d 2096 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2097 if (this->is_character_constant_)
2098 ast_dump_context->ostream() << '\'';
d751bb78 2099}
2100
e440a328 2101// Build a new integer value.
2102
2103Expression*
5d4b8566 2104Expression::make_integer(const mpz_t* val, Type* type, Location location)
2105{
2106 return new Integer_expression(val, type, false, location);
2107}
2108
2109// Build a new character constant value.
2110
2111Expression*
2112Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2113{
5d4b8566 2114 return new Integer_expression(val, type, true, location);
e440a328 2115}
2116
2117// Floats.
2118
2119class Float_expression : public Expression
2120{
2121 public:
b13c66cd 2122 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2123 : Expression(EXPRESSION_FLOAT, location),
2124 type_(type)
2125 {
2126 mpfr_init_set(this->val_, *val, GMP_RNDN);
2127 }
2128
e440a328 2129 // Write VAL to export data.
2130 static void
8b1c301d 2131 export_float(String_dump* exp, const mpfr_t val);
2132
d751bb78 2133 // Write VAL to dump file.
2134 static void
2135 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2136
2137 protected:
2138 bool
2139 do_is_constant() const
2140 { return true; }
2141
0e168074 2142 bool
2143 do_is_immutable() const
2144 { return true; }
2145
e440a328 2146 bool
0c77715b 2147 do_numeric_constant_value(Numeric_constant* nc) const
2148 {
2149 nc->set_float(this->type_, this->val_);
2150 return true;
2151 }
e440a328 2152
2153 Type*
2154 do_type();
2155
2156 void
2157 do_determine_type(const Type_context*);
2158
2159 void
2160 do_check_types(Gogo*);
2161
2162 Expression*
2163 do_copy()
2164 { return Expression::make_float(&this->val_, this->type_,
2165 this->location()); }
2166
2167 tree
2168 do_get_tree(Translate_context*);
2169
2170 void
2171 do_export(Export*) const;
2172
d751bb78 2173 void
2174 do_dump_expression(Ast_dump_context*) const;
2175
e440a328 2176 private:
2177 // The floating point value.
2178 mpfr_t val_;
2179 // The type so far.
2180 Type* type_;
2181};
2182
e440a328 2183// Return the current type. If we haven't set the type yet, we return
2184// an abstract float type.
2185
2186Type*
2187Float_expression::do_type()
2188{
2189 if (this->type_ == NULL)
2190 this->type_ = Type::make_abstract_float_type();
2191 return this->type_;
2192}
2193
2194// Set the type of the float value. Here we may switch from an
2195// abstract type to a real type.
2196
2197void
2198Float_expression::do_determine_type(const Type_context* context)
2199{
2200 if (this->type_ != NULL && !this->type_->is_abstract())
2201 ;
2202 else if (context->type != NULL
2203 && (context->type->integer_type() != NULL
2204 || context->type->float_type() != NULL
2205 || context->type->complex_type() != NULL))
2206 this->type_ = context->type;
2207 else if (!context->may_be_abstract)
48080209 2208 this->type_ = Type::lookup_float_type("float64");
e440a328 2209}
2210
e440a328 2211// Check the type of a float value.
2212
2213void
2214Float_expression::do_check_types(Gogo*)
2215{
0c77715b 2216 Type* type = this->type_;
2217 if (type == NULL)
e440a328 2218 return;
0c77715b 2219 Numeric_constant nc;
2220 nc.set_float(NULL, this->val_);
2221 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2222 this->set_is_error();
e440a328 2223}
2224
2225// Get a tree for a float constant.
2226
2227tree
2228Float_expression::do_get_tree(Translate_context* context)
2229{
48c2a53a 2230 Type* resolved_type;
e440a328 2231 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2232 resolved_type = this->type_;
e440a328 2233 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2234 {
2235 // We have an abstract integer type. We just hope for the best.
48c2a53a 2236 resolved_type = Type::lookup_integer_type("int");
2237 }
2238 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2239 {
2240 // We are converting to an abstract complex type.
2241 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2242 }
2243 else
2244 {
2245 // If we still have an abstract type here, then this is being
2246 // used in a constant expression which didn't get reduced. We
2247 // just use float64 and hope for the best.
48c2a53a 2248 resolved_type = Type::lookup_float_type("float64");
e440a328 2249 }
48c2a53a 2250
2251 Numeric_constant nc;
2252 nc.set_float(resolved_type, this->val_);
2253 Bexpression* ret =
2254 Expression::backend_numeric_constant_expression(context, &nc);
2255 return expr_to_tree(ret);
e440a328 2256}
2257
8b1c301d 2258// Write a floating point number to a string dump.
e440a328 2259
2260void
8b1c301d 2261Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2262{
2263 mp_exp_t exponent;
2264 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2265 if (*s == '-')
2266 exp->write_c_string("-");
2267 exp->write_c_string("0.");
2268 exp->write_c_string(*s == '-' ? s + 1 : s);
2269 mpfr_free_str(s);
2270 char buf[30];
2271 snprintf(buf, sizeof buf, "E%ld", exponent);
2272 exp->write_c_string(buf);
2273}
2274
2275// Export a floating point number in a constant expression.
2276
2277void
2278Float_expression::do_export(Export* exp) const
2279{
2280 Float_expression::export_float(exp, this->val_);
2281 // A trailing space lets us reliably identify the end of the number.
2282 exp->write_c_string(" ");
2283}
2284
d751bb78 2285// Dump a floating point number to the dump file.
2286
2287void
2288Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2289{
8b1c301d 2290 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2291}
2292
e440a328 2293// Make a float expression.
2294
2295Expression*
b13c66cd 2296Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2297{
2298 return new Float_expression(val, type, location);
2299}
2300
2301// Complex numbers.
2302
2303class Complex_expression : public Expression
2304{
2305 public:
2306 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2307 Location location)
e440a328 2308 : Expression(EXPRESSION_COMPLEX, location),
2309 type_(type)
2310 {
2311 mpfr_init_set(this->real_, *real, GMP_RNDN);
2312 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2313 }
2314
8b1c301d 2315 // Write REAL/IMAG to string dump.
e440a328 2316 static void
8b1c301d 2317 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
e440a328 2318
d751bb78 2319 // Write REAL/IMAG to dump context.
2320 static void
2321 dump_complex(Ast_dump_context* ast_dump_context,
2322 const mpfr_t real, const mpfr_t val);
2323
e440a328 2324 protected:
2325 bool
2326 do_is_constant() const
2327 { return true; }
2328
0e168074 2329 bool
2330 do_is_immutable() const
2331 { return true; }
2332
e440a328 2333 bool
0c77715b 2334 do_numeric_constant_value(Numeric_constant* nc) const
2335 {
2336 nc->set_complex(this->type_, this->real_, this->imag_);
2337 return true;
2338 }
e440a328 2339
2340 Type*
2341 do_type();
2342
2343 void
2344 do_determine_type(const Type_context*);
2345
2346 void
2347 do_check_types(Gogo*);
2348
2349 Expression*
2350 do_copy()
2351 {
2352 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2353 this->location());
2354 }
2355
2356 tree
2357 do_get_tree(Translate_context*);
2358
2359 void
2360 do_export(Export*) const;
2361
d751bb78 2362 void
2363 do_dump_expression(Ast_dump_context*) const;
2364
e440a328 2365 private:
2366 // The real part.
2367 mpfr_t real_;
2368 // The imaginary part;
2369 mpfr_t imag_;
2370 // The type if known.
2371 Type* type_;
2372};
2373
e440a328 2374// Return the current type. If we haven't set the type yet, we return
2375// an abstract complex type.
2376
2377Type*
2378Complex_expression::do_type()
2379{
2380 if (this->type_ == NULL)
2381 this->type_ = Type::make_abstract_complex_type();
2382 return this->type_;
2383}
2384
2385// Set the type of the complex value. Here we may switch from an
2386// abstract type to a real type.
2387
2388void
2389Complex_expression::do_determine_type(const Type_context* context)
2390{
2391 if (this->type_ != NULL && !this->type_->is_abstract())
2392 ;
2393 else if (context->type != NULL
2394 && context->type->complex_type() != NULL)
2395 this->type_ = context->type;
2396 else if (!context->may_be_abstract)
48080209 2397 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2398}
2399
e440a328 2400// Check the type of a complex value.
2401
2402void
2403Complex_expression::do_check_types(Gogo*)
2404{
0c77715b 2405 Type* type = this->type_;
2406 if (type == NULL)
e440a328 2407 return;
0c77715b 2408 Numeric_constant nc;
2409 nc.set_complex(NULL, this->real_, this->imag_);
2410 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2411 this->set_is_error();
2412}
2413
2414// Get a tree for a complex constant.
2415
2416tree
2417Complex_expression::do_get_tree(Translate_context* context)
2418{
48c2a53a 2419 Type* resolved_type;
e440a328 2420 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2421 resolved_type = this->type_;
2422 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2423 {
2424 // We are converting to an abstract integer type.
2425 resolved_type = Type::lookup_integer_type("int");
2426 }
2427 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2428 {
2429 // We are converting to an abstract float type.
2430 resolved_type = Type::lookup_float_type("float64");
2431 }
e440a328 2432 else
2433 {
2434 // If we still have an abstract type here, this this is being
2435 // used in a constant expression which didn't get reduced. We
2436 // just use complex128 and hope for the best.
48c2a53a 2437 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2438 }
48c2a53a 2439
2440 Numeric_constant nc;
2441 nc.set_complex(resolved_type, this->real_, this->imag_);
2442 Bexpression* ret =
2443 Expression::backend_numeric_constant_expression(context, &nc);
2444 return expr_to_tree(ret);
e440a328 2445}
2446
2447// Write REAL/IMAG to export data.
2448
2449void
8b1c301d 2450Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
e440a328 2451 const mpfr_t imag)
2452{
2453 if (!mpfr_zero_p(real))
2454 {
2455 Float_expression::export_float(exp, real);
2456 if (mpfr_sgn(imag) > 0)
2457 exp->write_c_string("+");
2458 }
2459 Float_expression::export_float(exp, imag);
2460 exp->write_c_string("i");
2461}
2462
2463// Export a complex number in a constant expression.
2464
2465void
2466Complex_expression::do_export(Export* exp) const
2467{
2468 Complex_expression::export_complex(exp, this->real_, this->imag_);
2469 // A trailing space lets us reliably identify the end of the number.
2470 exp->write_c_string(" ");
2471}
2472
d751bb78 2473// Dump a complex expression to the dump file.
2474
2475void
2476Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2477{
8b1c301d 2478 Complex_expression::export_complex(ast_dump_context,
d751bb78 2479 this->real_,
2480 this->imag_);
2481}
2482
e440a328 2483// Make a complex expression.
2484
2485Expression*
2486Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2487 Location location)
e440a328 2488{
2489 return new Complex_expression(real, imag, type, location);
2490}
2491
d5b605df 2492// Find a named object in an expression.
2493
2494class Find_named_object : public Traverse
2495{
2496 public:
2497 Find_named_object(Named_object* no)
2498 : Traverse(traverse_expressions),
2499 no_(no), found_(false)
2500 { }
2501
2502 // Whether we found the object.
2503 bool
2504 found() const
2505 { return this->found_; }
2506
2507 protected:
2508 int
2509 expression(Expression**);
2510
2511 private:
2512 // The object we are looking for.
2513 Named_object* no_;
2514 // Whether we found it.
2515 bool found_;
2516};
2517
e440a328 2518// A reference to a const in an expression.
2519
2520class Const_expression : public Expression
2521{
2522 public:
b13c66cd 2523 Const_expression(Named_object* constant, Location location)
e440a328 2524 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2525 constant_(constant), type_(NULL), seen_(false)
e440a328 2526 { }
2527
d5b605df 2528 Named_object*
2529 named_object()
2530 { return this->constant_; }
2531
a7f064d5 2532 // Check that the initializer does not refer to the constant itself.
2533 void
2534 check_for_init_loop();
2535
e440a328 2536 protected:
ba4aedd4 2537 int
2538 do_traverse(Traverse*);
2539
e440a328 2540 Expression*
ceeb4318 2541 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2542
2543 bool
2544 do_is_constant() const
2545 { return true; }
2546
0e168074 2547 bool
2548 do_is_immutable() const
2549 { return true; }
2550
e440a328 2551 bool
0c77715b 2552 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2553
2554 bool
af6b489a 2555 do_string_constant_value(std::string* val) const;
e440a328 2556
2557 Type*
2558 do_type();
2559
2560 // The type of a const is set by the declaration, not the use.
2561 void
2562 do_determine_type(const Type_context*);
2563
2564 void
2565 do_check_types(Gogo*);
2566
2567 Expression*
2568 do_copy()
2569 { return this; }
2570
2571 tree
2572 do_get_tree(Translate_context* context);
2573
2574 // When exporting a reference to a const as part of a const
2575 // expression, we export the value. We ignore the fact that it has
2576 // a name.
2577 void
2578 do_export(Export* exp) const
2579 { this->constant_->const_value()->expr()->export_expression(exp); }
2580
d751bb78 2581 void
2582 do_dump_expression(Ast_dump_context*) const;
2583
e440a328 2584 private:
2585 // The constant.
2586 Named_object* constant_;
2587 // The type of this reference. This is used if the constant has an
2588 // abstract type.
2589 Type* type_;
13e818f5 2590 // Used to prevent infinite recursion when a constant incorrectly
2591 // refers to itself.
2592 mutable bool seen_;
e440a328 2593};
2594
ba4aedd4 2595// Traversal.
2596
2597int
2598Const_expression::do_traverse(Traverse* traverse)
2599{
2600 if (this->type_ != NULL)
2601 return Type::traverse(this->type_, traverse);
2602 return TRAVERSE_CONTINUE;
2603}
2604
e440a328 2605// Lower a constant expression. This is where we convert the
2606// predeclared constant iota into an integer value.
2607
2608Expression*
ceeb4318 2609Const_expression::do_lower(Gogo* gogo, Named_object*,
2610 Statement_inserter*, int iota_value)
e440a328 2611{
2612 if (this->constant_->const_value()->expr()->classification()
2613 == EXPRESSION_IOTA)
2614 {
2615 if (iota_value == -1)
2616 {
2617 error_at(this->location(),
2618 "iota is only defined in const declarations");
2619 iota_value = 0;
2620 }
2621 mpz_t val;
2622 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2623 Expression* ret = Expression::make_integer(&val, NULL,
2624 this->location());
2625 mpz_clear(val);
2626 return ret;
2627 }
2628
2629 // Make sure that the constant itself has been lowered.
2630 gogo->lower_constant(this->constant_);
2631
2632 return this;
2633}
2634
0c77715b 2635// Return a numeric constant value.
e440a328 2636
2637bool
0c77715b 2638Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2639{
13e818f5 2640 if (this->seen_)
2641 return false;
2642
e440a328 2643 Expression* e = this->constant_->const_value()->expr();
0c77715b 2644
13e818f5 2645 this->seen_ = true;
2646
0c77715b 2647 bool r = e->numeric_constant_value(nc);
e440a328 2648
13e818f5 2649 this->seen_ = false;
2650
e440a328 2651 Type* ctype;
2652 if (this->type_ != NULL)
2653 ctype = this->type_;
2654 else
2655 ctype = this->constant_->const_value()->type();
e440a328 2656 if (r && ctype != NULL)
2657 {
0c77715b 2658 if (!nc->set_type(ctype, false, this->location()))
e440a328 2659 return false;
e440a328 2660 }
e440a328 2661
e440a328 2662 return r;
2663}
2664
af6b489a 2665bool
2666Const_expression::do_string_constant_value(std::string* val) const
2667{
2668 if (this->seen_)
2669 return false;
2670
2671 Expression* e = this->constant_->const_value()->expr();
2672
2673 this->seen_ = true;
2674 bool ok = e->string_constant_value(val);
2675 this->seen_ = false;
2676
2677 return ok;
2678}
2679
e440a328 2680// Return the type of the const reference.
2681
2682Type*
2683Const_expression::do_type()
2684{
2685 if (this->type_ != NULL)
2686 return this->type_;
13e818f5 2687
2f78f012 2688 Named_constant* nc = this->constant_->const_value();
2689
2690 if (this->seen_ || nc->lowering())
13e818f5 2691 {
2692 this->report_error(_("constant refers to itself"));
2693 this->type_ = Type::make_error_type();
2694 return this->type_;
2695 }
2696
2697 this->seen_ = true;
2698
e440a328 2699 Type* ret = nc->type();
13e818f5 2700
e440a328 2701 if (ret != NULL)
13e818f5 2702 {
2703 this->seen_ = false;
2704 return ret;
2705 }
2706
e440a328 2707 // During parsing, a named constant may have a NULL type, but we
2708 // must not return a NULL type here.
13e818f5 2709 ret = nc->expr()->type();
2710
2711 this->seen_ = false;
2712
2713 return ret;
e440a328 2714}
2715
2716// Set the type of the const reference.
2717
2718void
2719Const_expression::do_determine_type(const Type_context* context)
2720{
2721 Type* ctype = this->constant_->const_value()->type();
2722 Type* cetype = (ctype != NULL
2723 ? ctype
2724 : this->constant_->const_value()->expr()->type());
2725 if (ctype != NULL && !ctype->is_abstract())
2726 ;
2727 else if (context->type != NULL
0c77715b 2728 && context->type->is_numeric_type()
2729 && cetype->is_numeric_type())
e440a328 2730 this->type_ = context->type;
2731 else if (context->type != NULL
2732 && context->type->is_string_type()
2733 && cetype->is_string_type())
2734 this->type_ = context->type;
2735 else if (context->type != NULL
2736 && context->type->is_boolean_type()
2737 && cetype->is_boolean_type())
2738 this->type_ = context->type;
2739 else if (!context->may_be_abstract)
2740 {
2741 if (cetype->is_abstract())
2742 cetype = cetype->make_non_abstract_type();
2743 this->type_ = cetype;
2744 }
2745}
2746
a7f064d5 2747// Check for a loop in which the initializer of a constant refers to
2748// the constant itself.
e440a328 2749
2750void
a7f064d5 2751Const_expression::check_for_init_loop()
e440a328 2752{
5c13bd80 2753 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2754 return;
2755
a7f064d5 2756 if (this->seen_)
2757 {
2758 this->report_error(_("constant refers to itself"));
2759 this->type_ = Type::make_error_type();
2760 return;
2761 }
2762
d5b605df 2763 Expression* init = this->constant_->const_value()->expr();
2764 Find_named_object find_named_object(this->constant_);
a7f064d5 2765
2766 this->seen_ = true;
d5b605df 2767 Expression::traverse(&init, &find_named_object);
a7f064d5 2768 this->seen_ = false;
2769
d5b605df 2770 if (find_named_object.found())
2771 {
5c13bd80 2772 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2773 {
2774 this->report_error(_("constant refers to itself"));
2775 this->type_ = Type::make_error_type();
2776 }
d5b605df 2777 return;
2778 }
a7f064d5 2779}
2780
2781// Check types of a const reference.
2782
2783void
2784Const_expression::do_check_types(Gogo*)
2785{
5c13bd80 2786 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2787 return;
2788
2789 this->check_for_init_loop();
d5b605df 2790
0c77715b 2791 // Check that numeric constant fits in type.
2792 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2793 {
0c77715b 2794 Numeric_constant nc;
2795 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2796 {
0c77715b 2797 if (!nc.set_type(this->type_, true, this->location()))
2798 this->set_is_error();
e440a328 2799 }
e440a328 2800 }
2801}
2802
2803// Return a tree for the const reference.
2804
2805tree
2806Const_expression::do_get_tree(Translate_context* context)
2807{
2c809f8f 2808 if (this->type_ != NULL && this->type_->is_error())
2809 return error_mark_node;
e440a328 2810
2811 // If the type has been set for this expression, but the underlying
2812 // object is an abstract int or float, we try to get the abstract
2813 // value. Otherwise we may lose something in the conversion.
f2de4532 2814 Expression* expr = this->constant_->const_value()->expr();
e440a328 2815 if (this->type_ != NULL
0c77715b 2816 && this->type_->is_numeric_type()
a68492b4 2817 && (this->constant_->const_value()->type() == NULL
2818 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2819 {
0c77715b 2820 Numeric_constant nc;
2821 if (expr->numeric_constant_value(&nc)
2822 && nc.set_type(this->type_, false, this->location()))
e440a328 2823 {
0c77715b 2824 Expression* e = nc.expression(this->location());
2825 return e->get_tree(context);
e440a328 2826 }
e440a328 2827 }
2828
2c809f8f 2829 if (this->type_ != NULL)
f2de4532 2830 expr = Expression::make_cast(this->type_, expr, this->location());
2831 return expr->get_tree(context);
e440a328 2832}
2833
d751bb78 2834// Dump ast representation for constant expression.
2835
2836void
2837Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2838{
2839 ast_dump_context->ostream() << this->constant_->name();
2840}
2841
e440a328 2842// Make a reference to a constant in an expression.
2843
2844Expression*
2845Expression::make_const_reference(Named_object* constant,
b13c66cd 2846 Location location)
e440a328 2847{
2848 return new Const_expression(constant, location);
2849}
2850
d5b605df 2851// Find a named object in an expression.
2852
2853int
2854Find_named_object::expression(Expression** pexpr)
2855{
2856 switch ((*pexpr)->classification())
2857 {
2858 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 2859 {
2860 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2861 if (ce->named_object() == this->no_)
2862 break;
2863
2864 // We need to check a constant initializer explicitly, as
2865 // loops here will not be caught by the loop checking for
2866 // variable initializers.
2867 ce->check_for_init_loop();
2868
2869 return TRAVERSE_CONTINUE;
2870 }
2871
d5b605df 2872 case Expression::EXPRESSION_VAR_REFERENCE:
2873 if ((*pexpr)->var_expression()->named_object() == this->no_)
2874 break;
2875 return TRAVERSE_CONTINUE;
2876 case Expression::EXPRESSION_FUNC_REFERENCE:
2877 if ((*pexpr)->func_expression()->named_object() == this->no_)
2878 break;
2879 return TRAVERSE_CONTINUE;
2880 default:
2881 return TRAVERSE_CONTINUE;
2882 }
2883 this->found_ = true;
2884 return TRAVERSE_EXIT;
2885}
2886
e440a328 2887// The nil value.
2888
2889class Nil_expression : public Expression
2890{
2891 public:
b13c66cd 2892 Nil_expression(Location location)
e440a328 2893 : Expression(EXPRESSION_NIL, location)
2894 { }
2895
2896 static Expression*
2897 do_import(Import*);
2898
2899 protected:
2900 bool
2901 do_is_constant() const
2902 { return true; }
2903
f9ca30f9 2904 bool
2905 do_is_immutable() const
2906 { return true; }
2907
e440a328 2908 Type*
2909 do_type()
2910 { return Type::make_nil_type(); }
2911
2912 void
2913 do_determine_type(const Type_context*)
2914 { }
2915
2916 Expression*
2917 do_copy()
2918 { return this; }
2919
2920 tree
2921 do_get_tree(Translate_context*)
2922 { return null_pointer_node; }
2923
2924 void
2925 do_export(Export* exp) const
2926 { exp->write_c_string("nil"); }
d751bb78 2927
2928 void
2929 do_dump_expression(Ast_dump_context* ast_dump_context) const
2930 { ast_dump_context->ostream() << "nil"; }
e440a328 2931};
2932
2933// Import a nil expression.
2934
2935Expression*
2936Nil_expression::do_import(Import* imp)
2937{
2938 imp->require_c_string("nil");
2939 return Expression::make_nil(imp->location());
2940}
2941
2942// Make a nil expression.
2943
2944Expression*
b13c66cd 2945Expression::make_nil(Location location)
e440a328 2946{
2947 return new Nil_expression(location);
2948}
2949
2950// The value of the predeclared constant iota. This is little more
2951// than a marker. This will be lowered to an integer in
2952// Const_expression::do_lower, which is where we know the value that
2953// it should have.
2954
2955class Iota_expression : public Parser_expression
2956{
2957 public:
b13c66cd 2958 Iota_expression(Location location)
e440a328 2959 : Parser_expression(EXPRESSION_IOTA, location)
2960 { }
2961
2962 protected:
2963 Expression*
ceeb4318 2964 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 2965 { go_unreachable(); }
e440a328 2966
2967 // There should only ever be one of these.
2968 Expression*
2969 do_copy()
c3e6f413 2970 { go_unreachable(); }
d751bb78 2971
2972 void
2973 do_dump_expression(Ast_dump_context* ast_dump_context) const
2974 { ast_dump_context->ostream() << "iota"; }
e440a328 2975};
2976
2977// Make an iota expression. This is only called for one case: the
2978// value of the predeclared constant iota.
2979
2980Expression*
2981Expression::make_iota()
2982{
b13c66cd 2983 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 2984 return &iota_expression;
2985}
2986
2987// A type conversion expression.
2988
2989class Type_conversion_expression : public Expression
2990{
2991 public:
2992 Type_conversion_expression(Type* type, Expression* expr,
b13c66cd 2993 Location location)
e440a328 2994 : Expression(EXPRESSION_CONVERSION, location),
2995 type_(type), expr_(expr), may_convert_function_types_(false)
2996 { }
2997
2998 // Return the type to which we are converting.
2999 Type*
3000 type() const
3001 { return this->type_; }
3002
3003 // Return the expression which we are converting.
3004 Expression*
3005 expr() const
3006 { return this->expr_; }
3007
3008 // Permit converting from one function type to another. This is
3009 // used internally for method expressions.
3010 void
3011 set_may_convert_function_types()
3012 {
3013 this->may_convert_function_types_ = true;
3014 }
3015
3016 // Import a type conversion expression.
3017 static Expression*
3018 do_import(Import*);
3019
3020 protected:
3021 int
3022 do_traverse(Traverse* traverse);
3023
3024 Expression*
ceeb4318 3025 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3026
35a54f17 3027 Expression*
3028 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3029
e440a328 3030 bool
1ca01a59 3031 do_is_constant() const;
e440a328 3032
0e168074 3033 bool
3034 do_is_immutable() const;
3035
e440a328 3036 bool
0c77715b 3037 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3038
3039 bool
3040 do_string_constant_value(std::string*) const;
3041
3042 Type*
3043 do_type()
3044 { return this->type_; }
3045
3046 void
3047 do_determine_type(const Type_context*)
3048 {
3049 Type_context subcontext(this->type_, false);
3050 this->expr_->determine_type(&subcontext);
3051 }
3052
3053 void
3054 do_check_types(Gogo*);
3055
3056 Expression*
3057 do_copy()
3058 {
3059 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3060 this->location());
3061 }
3062
3063 tree
3064 do_get_tree(Translate_context* context);
3065
3066 void
3067 do_export(Export*) const;
3068
d751bb78 3069 void
3070 do_dump_expression(Ast_dump_context*) const;
3071
e440a328 3072 private:
3073 // The type to convert to.
3074 Type* type_;
3075 // The expression to convert.
3076 Expression* expr_;
3077 // True if this is permitted to convert function types. This is
3078 // used internally for method expressions.
3079 bool may_convert_function_types_;
3080};
3081
3082// Traversal.
3083
3084int
3085Type_conversion_expression::do_traverse(Traverse* traverse)
3086{
3087 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3088 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3089 return TRAVERSE_EXIT;
3090 return TRAVERSE_CONTINUE;
3091}
3092
3093// Convert to a constant at lowering time.
3094
3095Expression*
ceeb4318 3096Type_conversion_expression::do_lower(Gogo*, Named_object*,
3097 Statement_inserter*, int)
e440a328 3098{
3099 Type* type = this->type_;
3100 Expression* val = this->expr_;
b13c66cd 3101 Location location = this->location();
e440a328 3102
0c77715b 3103 if (type->is_numeric_type())
e440a328 3104 {
0c77715b 3105 Numeric_constant nc;
3106 if (val->numeric_constant_value(&nc))
e440a328 3107 {
0c77715b 3108 if (!nc.set_type(type, true, location))
3109 return Expression::make_error(location);
3110 return nc.expression(location);
e440a328 3111 }
e440a328 3112 }
3113
55072f2b 3114 if (type->is_slice_type())
e440a328 3115 {
3116 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3117 bool is_byte = (element_type->integer_type() != NULL
3118 && element_type->integer_type()->is_byte());
3119 bool is_rune = (element_type->integer_type() != NULL
3120 && element_type->integer_type()->is_rune());
3121 if (is_byte || is_rune)
e440a328 3122 {
3123 std::string s;
3124 if (val->string_constant_value(&s))
3125 {
3126 Expression_list* vals = new Expression_list();
3127 if (is_byte)
3128 {
3129 for (std::string::const_iterator p = s.begin();
3130 p != s.end();
3131 p++)
3132 {
3133 mpz_t val;
3134 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3135 Expression* v = Expression::make_integer(&val,
3136 element_type,
3137 location);
3138 vals->push_back(v);
3139 mpz_clear(val);
3140 }
3141 }
3142 else
3143 {
3144 const char *p = s.data();
3145 const char *pend = s.data() + s.length();
3146 while (p < pend)
3147 {
3148 unsigned int c;
3149 int adv = Lex::fetch_char(p, &c);
3150 if (adv == 0)
3151 {
3152 warning_at(this->location(), 0,
3153 "invalid UTF-8 encoding");
3154 adv = 1;
3155 }
3156 p += adv;
3157 mpz_t val;
3158 mpz_init_set_ui(val, c);
3159 Expression* v = Expression::make_integer(&val,
3160 element_type,
3161 location);
3162 vals->push_back(v);
3163 mpz_clear(val);
3164 }
3165 }
3166
3167 return Expression::make_slice_composite_literal(type, vals,
3168 location);
3169 }
3170 }
3171 }
3172
3173 return this;
3174}
3175
35a54f17 3176// Flatten a type conversion by using a temporary variable for the slice
3177// in slice to string conversions.
3178
3179Expression*
3180Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3181 Statement_inserter* inserter)
3182{
2c809f8f 3183 if (((this->type()->is_string_type()
3184 && this->expr_->type()->is_slice_type())
3185 || (this->type()->interface_type() != NULL
3186 && this->expr_->type()->interface_type() != NULL))
35a54f17 3187 && !this->expr_->is_variable())
3188 {
3189 Temporary_statement* temp =
3190 Statement::make_temporary(NULL, this->expr_, this->location());
3191 inserter->insert(temp);
3192 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3193 }
3194 return this;
3195}
3196
1ca01a59 3197// Return whether a type conversion is a constant.
3198
3199bool
3200Type_conversion_expression::do_is_constant() const
3201{
3202 if (!this->expr_->is_constant())
3203 return false;
3204
3205 // A conversion to a type that may not be used as a constant is not
3206 // a constant. For example, []byte(nil).
3207 Type* type = this->type_;
3208 if (type->integer_type() == NULL
3209 && type->float_type() == NULL
3210 && type->complex_type() == NULL
3211 && !type->is_boolean_type()
3212 && !type->is_string_type())
3213 return false;
3214
3215 return true;
3216}
3217
0e168074 3218// Return whether a type conversion is immutable.
3219
3220bool
3221Type_conversion_expression::do_is_immutable() const
3222{
3223 Type* type = this->type_;
3224 Type* expr_type = this->expr_->type();
3225
3226 if (type->interface_type() != NULL
3227 || expr_type->interface_type() != NULL)
3228 return false;
3229
3230 if (!this->expr_->is_immutable())
3231 return false;
3232
3233 if (Type::are_identical(type, expr_type, false, NULL))
3234 return true;
3235
3236 return type->is_basic_type() && expr_type->is_basic_type();
3237}
3238
0c77715b 3239// Return the constant numeric value if there is one.
e440a328 3240
3241bool
0c77715b 3242Type_conversion_expression::do_numeric_constant_value(
3243 Numeric_constant* nc) const
e440a328 3244{
0c77715b 3245 if (!this->type_->is_numeric_type())
e440a328 3246 return false;
0c77715b 3247 if (!this->expr_->numeric_constant_value(nc))
e440a328 3248 return false;
0c77715b 3249 return nc->set_type(this->type_, false, this->location());
e440a328 3250}
3251
3252// Return the constant string value if there is one.
3253
3254bool
3255Type_conversion_expression::do_string_constant_value(std::string* val) const
3256{
3257 if (this->type_->is_string_type()
3258 && this->expr_->type()->integer_type() != NULL)
3259 {
0c77715b 3260 Numeric_constant nc;
3261 if (this->expr_->numeric_constant_value(&nc))
e440a328 3262 {
0c77715b 3263 unsigned long ival;
3264 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3265 {
0c77715b 3266 val->clear();
3267 Lex::append_char(ival, true, val, this->location());
e440a328 3268 return true;
3269 }
3270 }
e440a328 3271 }
3272
3273 // FIXME: Could handle conversion from const []int here.
3274
3275 return false;
3276}
3277
3278// Check that types are convertible.
3279
3280void
3281Type_conversion_expression::do_check_types(Gogo*)
3282{
3283 Type* type = this->type_;
3284 Type* expr_type = this->expr_->type();
3285 std::string reason;
3286
5c13bd80 3287 if (type->is_error() || expr_type->is_error())
842f6425 3288 {
842f6425 3289 this->set_is_error();
3290 return;
3291 }
3292
e440a328 3293 if (this->may_convert_function_types_
3294 && type->function_type() != NULL
3295 && expr_type->function_type() != NULL)
3296 return;
3297
3298 if (Type::are_convertible(type, expr_type, &reason))
3299 return;
3300
3301 error_at(this->location(), "%s", reason.c_str());
3302 this->set_is_error();
3303}
3304
3305// Get a tree for a type conversion.
3306
3307tree
3308Type_conversion_expression::do_get_tree(Translate_context* context)
3309{
e440a328 3310 Type* type = this->type_;
3311 Type* expr_type = this->expr_->type();
2c809f8f 3312
3313 Gogo* gogo = context->gogo();
3314 Btype* btype = type->get_backend(gogo);
3315 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3316 Location loc = this->location();
3317
3318 if (Type::are_identical(type, expr_type, false, NULL))
e440a328 3319 {
2c809f8f 3320 Bexpression* bconvert =
3321 gogo->backend()->convert_expression(btype, bexpr, loc);
3322 return expr_to_tree(bconvert);
e440a328 3323 }
2c809f8f 3324 else if (type->interface_type() != NULL
3325 || expr_type->interface_type() != NULL)
e440a328 3326 {
2c809f8f 3327 Expression* conversion =
3328 Expression::convert_for_assignment(gogo, type, this->expr_,
3329 this->location());
3330 return conversion->get_tree(context);
e440a328 3331 }
3332 else if (type->is_string_type()
3333 && expr_type->integer_type() != NULL)
3334 {
2c809f8f 3335 mpz_t intval;
3336 Numeric_constant nc;
3337 if (this->expr_->numeric_constant_value(&nc)
3338 && nc.to_int(&intval)
3339 && mpz_fits_ushort_p(intval))
e440a328 3340 {
e440a328 3341 std::string s;
2c809f8f 3342 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3343 mpz_clear(intval);
3344 Expression* se = Expression::make_string(s, loc);
e440a328 3345 return se->get_tree(context);
3346 }
3347
f16ab008 3348 Expression* i2s_expr =
2c809f8f 3349 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3350 return Expression::make_cast(type, i2s_expr, loc)->get_tree(context);
e440a328 3351 }
55072f2b 3352 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3353 {
55072f2b 3354 Array_type* a = expr_type->array_type();
e440a328 3355 Type* e = a->element_type()->forwarded();
c484d925 3356 go_assert(e->integer_type() != NULL);
35a54f17 3357 go_assert(this->expr_->is_variable());
3358
3359 Runtime::Function code;
60963afd 3360 if (e->integer_type()->is_byte())
35a54f17 3361 code = Runtime::BYTE_ARRAY_TO_STRING;
e440a328 3362 else
35a54f17 3363 {
3364 go_assert(e->integer_type()->is_rune());
3365 code = Runtime::INT_ARRAY_TO_STRING;
3366 }
3367 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3368 Expression* len = a->get_length(gogo, this->expr_);
2c809f8f 3369 return Runtime::make_call(code, loc, 2, valptr, len)->get_tree(context);
e440a328 3370 }
411eb89e 3371 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3372 {
3373 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3374 go_assert(e->integer_type() != NULL);
6c252e42 3375
2c809f8f 3376 Runtime::Function code;
60963afd 3377 if (e->integer_type()->is_byte())
2c809f8f 3378 code = Runtime::STRING_TO_BYTE_ARRAY;
e440a328 3379 else
3380 {
60963afd 3381 go_assert(e->integer_type()->is_rune());
2c809f8f 3382 code = Runtime::STRING_TO_INT_ARRAY;
e440a328 3383 }
2c809f8f 3384 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3385 return Expression::make_unsafe_cast(type, s2a, loc)->get_tree(context);
3386 }
3387 else if (type->is_numeric_type())
3388 {
3389 go_assert(Type::are_convertible(type, expr_type, NULL));
3390 Bexpression* bconvert =
3391 gogo->backend()->convert_expression(btype, bexpr, loc);
3392 return expr_to_tree(bconvert);
e440a328 3393 }
3394 else if ((type->is_unsafe_pointer_type()
2c809f8f 3395 && (expr_type->points_to() != NULL
3396 || expr_type->integer_type()))
3397 || (expr_type->is_unsafe_pointer_type()
3398 && type->points_to() != NULL)
3399 || (this->may_convert_function_types_
3400 && type->function_type() != NULL
3401 && expr_type->function_type() != NULL))
3402 {
3403 Bexpression* bconvert =
3404 gogo->backend()->convert_expression(btype, bexpr, loc);
3405 return expr_to_tree(bconvert);
3406 }
e440a328 3407 else
2c809f8f 3408 {
3409 Expression* conversion =
3410 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3411 return conversion->get_tree(context);
3412 }
e440a328 3413}
3414
3415// Output a type conversion in a constant expression.
3416
3417void
3418Type_conversion_expression::do_export(Export* exp) const
3419{
3420 exp->write_c_string("convert(");
3421 exp->write_type(this->type_);
3422 exp->write_c_string(", ");
3423 this->expr_->export_expression(exp);
3424 exp->write_c_string(")");
3425}
3426
3427// Import a type conversion or a struct construction.
3428
3429Expression*
3430Type_conversion_expression::do_import(Import* imp)
3431{
3432 imp->require_c_string("convert(");
3433 Type* type = imp->read_type();
3434 imp->require_c_string(", ");
3435 Expression* val = Expression::import_expression(imp);
3436 imp->require_c_string(")");
3437 return Expression::make_cast(type, val, imp->location());
3438}
3439
d751bb78 3440// Dump ast representation for a type conversion expression.
3441
3442void
3443Type_conversion_expression::do_dump_expression(
3444 Ast_dump_context* ast_dump_context) const
3445{
3446 ast_dump_context->dump_type(this->type_);
3447 ast_dump_context->ostream() << "(";
3448 ast_dump_context->dump_expression(this->expr_);
3449 ast_dump_context->ostream() << ") ";
3450}
3451
e440a328 3452// Make a type cast expression.
3453
3454Expression*
b13c66cd 3455Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3456{
3457 if (type->is_error_type() || val->is_error_expression())
3458 return Expression::make_error(location);
3459 return new Type_conversion_expression(type, val, location);
3460}
3461
9581e91d 3462// An unsafe type conversion, used to pass values to builtin functions.
3463
3464class Unsafe_type_conversion_expression : public Expression
3465{
3466 public:
3467 Unsafe_type_conversion_expression(Type* type, Expression* expr,
b13c66cd 3468 Location location)
9581e91d 3469 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3470 type_(type), expr_(expr)
3471 { }
3472
3473 protected:
3474 int
3475 do_traverse(Traverse* traverse);
3476
3477 Type*
3478 do_type()
3479 { return this->type_; }
3480
3481 void
3482 do_determine_type(const Type_context*)
a9182619 3483 { this->expr_->determine_type_no_context(); }
9581e91d 3484
3485 Expression*
3486 do_copy()
3487 {
3488 return new Unsafe_type_conversion_expression(this->type_,
3489 this->expr_->copy(),
3490 this->location());
3491 }
3492
3493 tree
3494 do_get_tree(Translate_context*);
3495
d751bb78 3496 void
3497 do_dump_expression(Ast_dump_context*) const;
3498
9581e91d 3499 private:
3500 // The type to convert to.
3501 Type* type_;
3502 // The expression to convert.
3503 Expression* expr_;
3504};
3505
3506// Traversal.
3507
3508int
3509Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3510{
3511 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3512 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3513 return TRAVERSE_EXIT;
3514 return TRAVERSE_CONTINUE;
3515}
3516
3517// Convert to backend representation.
3518
3519tree
3520Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3521{
3522 // We are only called for a limited number of cases.
3523
3524 Type* t = this->type_;
3525 Type* et = this->expr_->type();
2c809f8f 3526 if (t->array_type() != NULL)
3527 go_assert(et->array_type() != NULL
3528 && t->is_slice_type() == et->is_slice_type());
3529 else if (t->struct_type() != NULL)
9581e91d 3530 {
2c809f8f 3531 if (t->named_type() != NULL
3532 && et->named_type() != NULL
3533 && !Type::are_convertible(t, et, NULL))
3534 {
3535 go_assert(saw_errors());
3536 return error_mark_node;
3537 }
3538
3539 go_assert(et->struct_type() != NULL
3540 && Type::are_convertible(t, et, NULL));
3541 }
3542 else if (t->map_type() != NULL)
c484d925 3543 go_assert(et->map_type() != NULL);
9581e91d 3544 else if (t->channel_type() != NULL)
c484d925 3545 go_assert(et->channel_type() != NULL);
09ea332d 3546 else if (t->points_to() != NULL)
2c809f8f 3547 go_assert(et->points_to() != NULL
3548 || et->channel_type() != NULL
3549 || et->map_type() != NULL
3550 || et->function_type() != NULL
3551 || et->is_nil_type());
9581e91d 3552 else if (et->is_unsafe_pointer_type())
c484d925 3553 go_assert(t->points_to() != NULL);
2c809f8f 3554 else if (t->interface_type() != NULL)
9581e91d 3555 {
2c809f8f 3556 bool empty_iface = t->interface_type()->is_empty();
c484d925 3557 go_assert(et->interface_type() != NULL
2c809f8f 3558 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3559 }
588e3cf9 3560 else if (t->integer_type() != NULL)
2c809f8f 3561 go_assert(et->is_boolean_type()
3562 || et->integer_type() != NULL
3563 || et->function_type() != NULL
3564 || et->points_to() != NULL
3565 || et->map_type() != NULL
3566 || et->channel_type() != NULL);
9581e91d 3567 else
c3e6f413 3568 go_unreachable();
9581e91d 3569
2c809f8f 3570 Gogo* gogo = context->gogo();
3571 Btype* btype = t->get_backend(gogo);
3572 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3573 Location loc = this->location();
3574 Bexpression* ret =
3575 gogo->backend()->convert_expression(btype, bexpr, loc);
3576 return expr_to_tree(ret);
9581e91d 3577}
3578
d751bb78 3579// Dump ast representation for an unsafe type conversion expression.
3580
3581void
3582Unsafe_type_conversion_expression::do_dump_expression(
3583 Ast_dump_context* ast_dump_context) const
3584{
3585 ast_dump_context->dump_type(this->type_);
3586 ast_dump_context->ostream() << "(";
3587 ast_dump_context->dump_expression(this->expr_);
3588 ast_dump_context->ostream() << ") ";
3589}
3590
9581e91d 3591// Make an unsafe type conversion expression.
3592
3593Expression*
3594Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3595 Location location)
9581e91d 3596{
3597 return new Unsafe_type_conversion_expression(type, expr, location);
3598}
3599
76f85fd6 3600// Class Unary_expression.
e440a328 3601
3602// If we are taking the address of a composite literal, and the
2c809f8f 3603// contents are not constant, then we want to make a heap expression
e440a328 3604// instead.
3605
3606Expression*
ceeb4318 3607Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3608{
b13c66cd 3609 Location loc = this->location();
e440a328 3610 Operator op = this->op_;
3611 Expression* expr = this->expr_;
3612
3613 if (op == OPERATOR_MULT && expr->is_type_expression())
3614 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3615
3616 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3617 // moving x to the heap. FIXME: Is it worth doing a real escape
3618 // analysis here? This case is found in math/unsafe.go and is
3619 // therefore worth special casing.
3620 if (op == OPERATOR_MULT)
3621 {
3622 Expression* e = expr;
3623 while (e->classification() == EXPRESSION_CONVERSION)
3624 {
3625 Type_conversion_expression* te
3626 = static_cast<Type_conversion_expression*>(e);
3627 e = te->expr();
3628 }
3629
3630 if (e->classification() == EXPRESSION_UNARY)
3631 {
3632 Unary_expression* ue = static_cast<Unary_expression*>(e);
3633 if (ue->op_ == OPERATOR_AND)
3634 {
3635 if (e == expr)
3636 {
3637 // *&x == x.
f4dea966 3638 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3639 {
3640 error_at(ue->location(),
3641 "invalid operand for unary %<&%>");
3642 this->set_is_error();
3643 }
e440a328 3644 return ue->expr_;
3645 }
3646 ue->set_does_not_escape();
3647 }
3648 }
3649 }
3650
55661ce9 3651 // Catching an invalid indirection of unsafe.Pointer here avoid
3652 // having to deal with TYPE_VOID in other places.
3653 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3654 {
3655 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3656 return Expression::make_error(this->location());
3657 }
3658
59a401fe 3659 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3660 {
0c77715b 3661 Numeric_constant nc;
3662 if (expr->numeric_constant_value(&nc))
e440a328 3663 {
0c77715b 3664 Numeric_constant result;
3665 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3666 return result.expression(loc);
e440a328 3667 }
3668 }
3669
3670 return this;
3671}
3672
f9ca30f9 3673// Flatten expression if a nil check must be performed and create temporary
3674// variables if necessary.
3675
3676Expression*
3677Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3678 Statement_inserter* inserter)
3679{
f4dea966 3680 if (this->is_error_expression() || this->expr_->is_error_expression())
3681 return Expression::make_error(this->location());
3682
f9ca30f9 3683 Location location = this->location();
3684 if (this->op_ == OPERATOR_MULT
3685 && !this->expr_->is_variable())
3686 {
3687 go_assert(this->expr_->type()->points_to() != NULL);
3688 Type* ptype = this->expr_->type()->points_to();
3689 if (!ptype->is_void_type())
3690 {
3691 Btype* pbtype = ptype->get_backend(gogo);
3692 size_t s = gogo->backend()->type_size(pbtype);
3693 if (s >= 4096 || this->issue_nil_check_)
3694 {
3695 Temporary_statement* temp =
3696 Statement::make_temporary(NULL, this->expr_, location);
3697 inserter->insert(temp);
3698 this->expr_ =
3699 Expression::make_temporary_reference(temp, location);
3700 }
3701 }
3702 }
3703
3704 if (this->create_temp_ && !this->expr_->is_variable())
3705 {
3706 Temporary_statement* temp =
3707 Statement::make_temporary(NULL, this->expr_, location);
3708 inserter->insert(temp);
3709 this->expr_ = Expression::make_temporary_reference(temp, location);
3710 }
3711
3712 return this;
3713}
3714
e440a328 3715// Return whether a unary expression is a constant.
3716
3717bool
3718Unary_expression::do_is_constant() const
3719{
3720 if (this->op_ == OPERATOR_MULT)
3721 {
3722 // Indirecting through a pointer is only constant if the object
3723 // to which the expression points is constant, but we currently
3724 // have no way to determine that.
3725 return false;
3726 }
3727 else if (this->op_ == OPERATOR_AND)
3728 {
3729 // Taking the address of a variable is constant if it is a
f9ca30f9 3730 // global variable, not constant otherwise. In other cases taking the
3731 // address is probably not a constant.
e440a328 3732 Var_expression* ve = this->expr_->var_expression();
3733 if (ve != NULL)
3734 {
3735 Named_object* no = ve->named_object();
3736 return no->is_variable() && no->var_value()->is_global();
3737 }
3738 return false;
3739 }
3740 else
3741 return this->expr_->is_constant();
3742}
3743
0c77715b 3744// Apply unary opcode OP to UNC, setting NC. Return true if this
3745// could be done, false if not. Issue errors for overflow.
e440a328 3746
3747bool
0c77715b 3748Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3749 Location location, Numeric_constant* nc)
e440a328 3750{
3751 switch (op)
3752 {
3753 case OPERATOR_PLUS:
0c77715b 3754 *nc = *unc;
e440a328 3755 return true;
0c77715b 3756
e440a328 3757 case OPERATOR_MINUS:
0c77715b 3758 if (unc->is_int() || unc->is_rune())
3759 break;
3760 else if (unc->is_float())
3761 {
3762 mpfr_t uval;
3763 unc->get_float(&uval);
3764 mpfr_t val;
3765 mpfr_init(val);
3766 mpfr_neg(val, uval, GMP_RNDN);
3767 nc->set_float(unc->type(), val);
3768 mpfr_clear(uval);
3769 mpfr_clear(val);
3770 return true;
3771 }
3772 else if (unc->is_complex())
3773 {
3774 mpfr_t ureal, uimag;
3775 unc->get_complex(&ureal, &uimag);
3776 mpfr_t real, imag;
3777 mpfr_init(real);
3778 mpfr_init(imag);
3779 mpfr_neg(real, ureal, GMP_RNDN);
3780 mpfr_neg(imag, uimag, GMP_RNDN);
3781 nc->set_complex(unc->type(), real, imag);
3782 mpfr_clear(ureal);
3783 mpfr_clear(uimag);
3784 mpfr_clear(real);
3785 mpfr_clear(imag);
3786 return true;
3787 }
e440a328 3788 else
0c77715b 3789 go_unreachable();
e440a328 3790
0c77715b 3791 case OPERATOR_XOR:
3792 break;
68448d53 3793
59a401fe 3794 case OPERATOR_NOT:
e440a328 3795 case OPERATOR_AND:
3796 case OPERATOR_MULT:
3797 return false;
0c77715b 3798
e440a328 3799 default:
c3e6f413 3800 go_unreachable();
e440a328 3801 }
e440a328 3802
0c77715b 3803 if (!unc->is_int() && !unc->is_rune())
3804 return false;
3805
3806 mpz_t uval;
8387e1df 3807 if (unc->is_rune())
3808 unc->get_rune(&uval);
3809 else
3810 unc->get_int(&uval);
0c77715b 3811 mpz_t val;
3812 mpz_init(val);
e440a328 3813
e440a328 3814 switch (op)
3815 {
e440a328 3816 case OPERATOR_MINUS:
0c77715b 3817 mpz_neg(val, uval);
3818 break;
3819
e440a328 3820 case OPERATOR_NOT:
0c77715b 3821 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3822 break;
3823
e440a328 3824 case OPERATOR_XOR:
0c77715b 3825 {
3826 Type* utype = unc->type();
3827 if (utype->integer_type() == NULL
3828 || utype->integer_type()->is_abstract())
3829 mpz_com(val, uval);
3830 else
3831 {
3832 // The number of HOST_WIDE_INTs that it takes to represent
3833 // UVAL.
3834 size_t count = ((mpz_sizeinbase(uval, 2)
3835 + HOST_BITS_PER_WIDE_INT
3836 - 1)
3837 / HOST_BITS_PER_WIDE_INT);
e440a328 3838
0c77715b 3839 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3840 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3841
3842 size_t obits = utype->integer_type()->bits();
3843
3844 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3845 {
3846 mpz_t adj;
3847 mpz_init_set_ui(adj, 1);
3848 mpz_mul_2exp(adj, adj, obits);
3849 mpz_add(uval, uval, adj);
3850 mpz_clear(adj);
3851 }
3852
3853 size_t ecount;
3854 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3855 go_assert(ecount <= count);
3856
3857 // Trim down to the number of words required by the type.
3858 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3859 / HOST_BITS_PER_WIDE_INT);
3860 go_assert(ocount <= count);
3861
3862 for (size_t i = 0; i < ocount; ++i)
3863 phwi[i] = ~phwi[i];
3864
3865 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3866 if (clearbits != 0)
3867 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3868 >> clearbits);
3869
3870 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3871
3872 if (!utype->integer_type()->is_unsigned()
3873 && mpz_tstbit(val, obits - 1))
3874 {
3875 mpz_t adj;
3876 mpz_init_set_ui(adj, 1);
3877 mpz_mul_2exp(adj, adj, obits);
3878 mpz_sub(val, val, adj);
3879 mpz_clear(adj);
3880 }
3881
3882 delete[] phwi;
3883 }
3884 }
3885 break;
e440a328 3886
e440a328 3887 default:
c3e6f413 3888 go_unreachable();
e440a328 3889 }
e440a328 3890
0c77715b 3891 if (unc->is_rune())
3892 nc->set_rune(NULL, val);
e440a328 3893 else
0c77715b 3894 nc->set_int(NULL, val);
e440a328 3895
0c77715b 3896 mpz_clear(uval);
3897 mpz_clear(val);
e440a328 3898
0c77715b 3899 return nc->set_type(unc->type(), true, location);
e440a328 3900}
3901
0c77715b 3902// Return the integral constant value of a unary expression, if it has one.
e440a328 3903
3904bool
0c77715b 3905Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 3906{
0c77715b 3907 Numeric_constant unc;
3908 if (!this->expr_->numeric_constant_value(&unc))
3909 return false;
3910 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3911 nc);
e440a328 3912}
3913
3914// Return the type of a unary expression.
3915
3916Type*
3917Unary_expression::do_type()
3918{
3919 switch (this->op_)
3920 {
3921 case OPERATOR_PLUS:
3922 case OPERATOR_MINUS:
3923 case OPERATOR_NOT:
3924 case OPERATOR_XOR:
3925 return this->expr_->type();
3926
3927 case OPERATOR_AND:
3928 return Type::make_pointer_type(this->expr_->type());
3929
3930 case OPERATOR_MULT:
3931 {
3932 Type* subtype = this->expr_->type();
3933 Type* points_to = subtype->points_to();
3934 if (points_to == NULL)
3935 return Type::make_error_type();
3936 return points_to;
3937 }
3938
3939 default:
c3e6f413 3940 go_unreachable();
e440a328 3941 }
3942}
3943
3944// Determine abstract types for a unary expression.
3945
3946void
3947Unary_expression::do_determine_type(const Type_context* context)
3948{
3949 switch (this->op_)
3950 {
3951 case OPERATOR_PLUS:
3952 case OPERATOR_MINUS:
3953 case OPERATOR_NOT:
3954 case OPERATOR_XOR:
3955 this->expr_->determine_type(context);
3956 break;
3957
3958 case OPERATOR_AND:
3959 // Taking the address of something.
3960 {
3961 Type* subtype = (context->type == NULL
3962 ? NULL
3963 : context->type->points_to());
3964 Type_context subcontext(subtype, false);
3965 this->expr_->determine_type(&subcontext);
3966 }
3967 break;
3968
3969 case OPERATOR_MULT:
3970 // Indirecting through a pointer.
3971 {
3972 Type* subtype = (context->type == NULL
3973 ? NULL
3974 : Type::make_pointer_type(context->type));
3975 Type_context subcontext(subtype, false);
3976 this->expr_->determine_type(&subcontext);
3977 }
3978 break;
3979
3980 default:
c3e6f413 3981 go_unreachable();
e440a328 3982 }
3983}
3984
3985// Check types for a unary expression.
3986
3987void
3988Unary_expression::do_check_types(Gogo*)
3989{
9fe897ef 3990 Type* type = this->expr_->type();
5c13bd80 3991 if (type->is_error())
9fe897ef 3992 {
3993 this->set_is_error();
3994 return;
3995 }
3996
e440a328 3997 switch (this->op_)
3998 {
3999 case OPERATOR_PLUS:
4000 case OPERATOR_MINUS:
9fe897ef 4001 if (type->integer_type() == NULL
4002 && type->float_type() == NULL
4003 && type->complex_type() == NULL)
4004 this->report_error(_("expected numeric type"));
e440a328 4005 break;
4006
4007 case OPERATOR_NOT:
59a401fe 4008 if (!type->is_boolean_type())
4009 this->report_error(_("expected boolean type"));
4010 break;
4011
e440a328 4012 case OPERATOR_XOR:
9fe897ef 4013 if (type->integer_type() == NULL
4014 && !type->is_boolean_type())
4015 this->report_error(_("expected integer or boolean type"));
e440a328 4016 break;
4017
4018 case OPERATOR_AND:
4019 if (!this->expr_->is_addressable())
09ea332d 4020 {
4021 if (!this->create_temp_)
f4dea966 4022 {
4023 error_at(this->location(), "invalid operand for unary %<&%>");
4024 this->set_is_error();
4025 }
09ea332d 4026 }
e440a328 4027 else
56080003 4028 {
4029 this->expr_->address_taken(this->escapes_);
4030 this->expr_->issue_nil_check();
4031 }
e440a328 4032 break;
4033
4034 case OPERATOR_MULT:
4035 // Indirecting through a pointer.
9fe897ef 4036 if (type->points_to() == NULL)
4037 this->report_error(_("expected pointer"));
e440a328 4038 break;
4039
4040 default:
c3e6f413 4041 go_unreachable();
e440a328 4042 }
4043}
4044
4045// Get a tree for a unary expression.
4046
4047tree
4048Unary_expression::do_get_tree(Translate_context* context)
4049{
1b1f2abf 4050 Gogo* gogo = context->gogo();
e9d3367e 4051 Location loc = this->location();
4052
4053 // Taking the address of a set-and-use-temporary expression requires
4054 // setting the temporary and then taking the address.
4055 if (this->op_ == OPERATOR_AND)
4056 {
4057 Set_and_use_temporary_expression* sut =
4058 this->expr_->set_and_use_temporary_expression();
4059 if (sut != NULL)
4060 {
4061 Temporary_statement* temp = sut->temporary();
4062 Bvariable* bvar = temp->get_backend_variable(context);
f9ca30f9 4063 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4064
4065 Expression* val = sut->expression();
4066 Bexpression* bval = tree_to_expr(val->get_tree(context));
4067
4068 Bstatement* bassign =
4069 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4070 Bexpression* bvar_addr =
4071 gogo->backend()->address_expression(bvar_expr, loc);
4072 Bexpression* ret =
4073 gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4074 return expr_to_tree(ret);
e9d3367e 4075 }
4076 }
4077
f9ca30f9 4078 Bexpression* ret;
e440a328 4079 tree expr = this->expr_->get_tree(context);
f9ca30f9 4080 Bexpression* bexpr = tree_to_expr(expr);
4081 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4082 switch (this->op_)
4083 {
4084 case OPERATOR_PLUS:
f9ca30f9 4085 ret = bexpr;
4086 break;
e440a328 4087
4088 case OPERATOR_MINUS:
f9ca30f9 4089 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4090 ret = gogo->backend()->convert_expression(btype, ret, loc);
4091 break;
e440a328 4092
4093 case OPERATOR_NOT:
e440a328 4094 case OPERATOR_XOR:
f9ca30f9 4095 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4096 break;
e440a328 4097
4098 case OPERATOR_AND:
09ea332d 4099 if (!this->create_temp_)
4100 {
4101 // We should not see a non-constant constructor here; cases
4102 // where we would see one should have been moved onto the
4103 // heap at parse time. Taking the address of a nonconstant
4104 // constructor will not do what the programmer expects.
f9ca30f9 4105
4106 go_assert(!this->expr_->is_composite_literal()
4107 || this->expr_->is_immutable());
24060bf9 4108 if (this->expr_->classification() == EXPRESSION_UNARY)
4109 {
4110 Unary_expression* ue =
4111 static_cast<Unary_expression*>(this->expr_);
4112 go_assert(ue->op() != OPERATOR_AND);
4113 }
09ea332d 4114 }
e440a328 4115
f23d7786 4116 static unsigned int counter;
4117 char buf[100];
4118 if (this->is_gc_root_ || this->is_slice_init_)
76f85fd6 4119 {
f23d7786 4120 bool copy_to_heap = false;
4121 if (this->is_gc_root_)
4122 {
4123 // Build a decl for a GC root variable. GC roots are mutable, so
4124 // they cannot be represented as an immutable_struct in the
4125 // backend.
4126 static unsigned int root_counter;
4127 snprintf(buf, sizeof buf, "gc%u", root_counter);
4128 ++root_counter;
4129 }
4130 else
4131 {
4132 // Build a decl for a slice value initializer. An immutable slice
4133 // value initializer may have to be copied to the heap if it
4134 // contains pointers in a non-constant context.
4135 snprintf(buf, sizeof buf, "C%u", counter);
4136 ++counter;
4137
4138 Array_type* at = this->expr_->type()->array_type();
4139 go_assert(at != NULL);
4140
4141 // If we are not copying the value to the heap, we will only
4142 // initialize the value once, so we can use this directly
4143 // rather than copying it. In that case we can't make it
4144 // read-only, because the program is permitted to change it.
4145 copy_to_heap = (at->element_type()->has_pointer()
4146 && !context->is_const());
4147 }
4148 Bvariable* implicit =
4149 gogo->backend()->implicit_variable(buf, btype, bexpr, copy_to_heap);
4150 bexpr = gogo->backend()->var_expression(implicit, loc);
76f85fd6 4151 }
4152 else if ((this->expr_->is_composite_literal()
f9ca30f9 4153 || this->expr_->string_expression() != NULL)
4154 && this->expr_->is_immutable())
4155 {
76f85fd6 4156 // Build a decl for a constant constructor.
f9ca30f9 4157 snprintf(buf, sizeof buf, "C%u", counter);
4158 ++counter;
4159
4160 Bvariable* decl =
4161 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4162 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4163 btype, loc, bexpr);
4164 bexpr = gogo->backend()->var_expression(decl, loc);
4165 }
09ea332d 4166
f9ca30f9 4167 go_assert(!this->create_temp_ || this->expr_->is_variable());
4168 ret = gogo->backend()->address_expression(bexpr, loc);
4169 break;
e440a328 4170
4171 case OPERATOR_MULT:
4172 {
f9ca30f9 4173 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4174
4175 // If we are dereferencing the pointer to a large struct, we
4176 // need to check for nil. We don't bother to check for small
4177 // structs because we expect the system to crash on a nil
56080003 4178 // pointer dereference. However, if we know the address of this
4179 // expression is being taken, we must always check for nil.
f9ca30f9 4180
4181 Type* ptype = this->expr_->type()->points_to();
4182 Btype* pbtype = ptype->get_backend(gogo);
4183 if (!ptype->is_void_type())
e440a328 4184 {
f9ca30f9 4185 size_t s = gogo->backend()->type_size(pbtype);
4186 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4187 {
f9ca30f9 4188 go_assert(this->expr_->is_variable());
4189
4190 Expression* nil_expr = Expression::make_nil(loc);
4191 Bexpression* nil = tree_to_expr(nil_expr->get_tree(context));
4192 Bexpression* compare =
4193 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4194 nil, loc);
4195
aff1f085 4196 Expression* crash_expr =
4197 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
f9ca30f9 4198 Bexpression* crash =
4199 tree_to_expr(crash_expr->get_tree(context));
4200 bexpr = gogo->backend()->conditional_expression(btype, compare,
4201 crash, bexpr,
4202 loc);
4203
19b4f09b 4204 }
e440a328 4205 }
9b27b43c 4206 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
e440a328 4207 }
f9ca30f9 4208 break;
e440a328 4209
4210 default:
c3e6f413 4211 go_unreachable();
e440a328 4212 }
f9ca30f9 4213
4214 return expr_to_tree(ret);
e440a328 4215}
4216
4217// Export a unary expression.
4218
4219void
4220Unary_expression::do_export(Export* exp) const
4221{
4222 switch (this->op_)
4223 {
4224 case OPERATOR_PLUS:
4225 exp->write_c_string("+ ");
4226 break;
4227 case OPERATOR_MINUS:
4228 exp->write_c_string("- ");
4229 break;
4230 case OPERATOR_NOT:
4231 exp->write_c_string("! ");
4232 break;
4233 case OPERATOR_XOR:
4234 exp->write_c_string("^ ");
4235 break;
4236 case OPERATOR_AND:
4237 case OPERATOR_MULT:
4238 default:
c3e6f413 4239 go_unreachable();
e440a328 4240 }
4241 this->expr_->export_expression(exp);
4242}
4243
4244// Import a unary expression.
4245
4246Expression*
4247Unary_expression::do_import(Import* imp)
4248{
4249 Operator op;
4250 switch (imp->get_char())
4251 {
4252 case '+':
4253 op = OPERATOR_PLUS;
4254 break;
4255 case '-':
4256 op = OPERATOR_MINUS;
4257 break;
4258 case '!':
4259 op = OPERATOR_NOT;
4260 break;
4261 case '^':
4262 op = OPERATOR_XOR;
4263 break;
4264 default:
c3e6f413 4265 go_unreachable();
e440a328 4266 }
4267 imp->require_c_string(" ");
4268 Expression* expr = Expression::import_expression(imp);
4269 return Expression::make_unary(op, expr, imp->location());
4270}
4271
d751bb78 4272// Dump ast representation of an unary expression.
4273
4274void
4275Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4276{
4277 ast_dump_context->dump_operator(this->op_);
4278 ast_dump_context->ostream() << "(";
4279 ast_dump_context->dump_expression(this->expr_);
4280 ast_dump_context->ostream() << ") ";
4281}
4282
e440a328 4283// Make a unary expression.
4284
4285Expression*
b13c66cd 4286Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4287{
4288 return new Unary_expression(op, expr, location);
4289}
4290
4291// If this is an indirection through a pointer, return the expression
4292// being pointed through. Otherwise return this.
4293
4294Expression*
4295Expression::deref()
4296{
4297 if (this->classification_ == EXPRESSION_UNARY)
4298 {
4299 Unary_expression* ue = static_cast<Unary_expression*>(this);
4300 if (ue->op() == OPERATOR_MULT)
4301 return ue->operand();
4302 }
4303 return this;
4304}
4305
4306// Class Binary_expression.
4307
4308// Traversal.
4309
4310int
4311Binary_expression::do_traverse(Traverse* traverse)
4312{
4313 int t = Expression::traverse(&this->left_, traverse);
4314 if (t == TRAVERSE_EXIT)
4315 return TRAVERSE_EXIT;
4316 return Expression::traverse(&this->right_, traverse);
4317}
4318
0c77715b 4319// Return the type to use for a binary operation on operands of
4320// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4321// such may be NULL or abstract.
4322
4323bool
4324Binary_expression::operation_type(Operator op, Type* left_type,
4325 Type* right_type, Type** result_type)
4326{
4327 if (left_type != right_type
4328 && !left_type->is_abstract()
4329 && !right_type->is_abstract()
4330 && left_type->base() != right_type->base()
4331 && op != OPERATOR_LSHIFT
4332 && op != OPERATOR_RSHIFT)
4333 {
4334 // May be a type error--let it be diagnosed elsewhere.
4335 return false;
4336 }
4337
4338 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4339 {
4340 if (left_type->integer_type() != NULL)
4341 *result_type = left_type;
4342 else
4343 *result_type = Type::make_abstract_integer_type();
4344 }
4345 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4346 *result_type = left_type;
4347 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4348 *result_type = right_type;
4349 else if (!left_type->is_abstract())
4350 *result_type = left_type;
4351 else if (!right_type->is_abstract())
4352 *result_type = right_type;
4353 else if (left_type->complex_type() != NULL)
4354 *result_type = left_type;
4355 else if (right_type->complex_type() != NULL)
4356 *result_type = right_type;
4357 else if (left_type->float_type() != NULL)
4358 *result_type = left_type;
4359 else if (right_type->float_type() != NULL)
4360 *result_type = right_type;
4361 else if (left_type->integer_type() != NULL
4362 && left_type->integer_type()->is_rune())
4363 *result_type = left_type;
4364 else if (right_type->integer_type() != NULL
4365 && right_type->integer_type()->is_rune())
4366 *result_type = right_type;
4367 else
4368 *result_type = left_type;
4369
4370 return true;
4371}
4372
4373// Convert an integer comparison code and an operator to a boolean
4374// value.
e440a328 4375
4376bool
0c77715b 4377Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4378{
e440a328 4379 switch (op)
4380 {
4381 case OPERATOR_EQEQ:
0c77715b 4382 return cmp == 0;
4383 break;
e440a328 4384 case OPERATOR_NOTEQ:
0c77715b 4385 return cmp != 0;
4386 break;
e440a328 4387 case OPERATOR_LT:
0c77715b 4388 return cmp < 0;
4389 break;
e440a328 4390 case OPERATOR_LE:
0c77715b 4391 return cmp <= 0;
e440a328 4392 case OPERATOR_GT:
0c77715b 4393 return cmp > 0;
e440a328 4394 case OPERATOR_GE:
0c77715b 4395 return cmp >= 0;
e440a328 4396 default:
c3e6f413 4397 go_unreachable();
e440a328 4398 }
4399}
4400
0c77715b 4401// Compare constants according to OP.
e440a328 4402
4403bool
0c77715b 4404Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4405 Numeric_constant* right_nc,
4406 Location location, bool* result)
e440a328 4407{
0c77715b 4408 Type* left_type = left_nc->type();
4409 Type* right_type = right_nc->type();
4410
4411 Type* type;
4412 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4413 return false;
4414
4415 // When comparing an untyped operand to a typed operand, we are
4416 // effectively coercing the untyped operand to the other operand's
4417 // type, so make sure that is valid.
4418 if (!left_nc->set_type(type, true, location)
4419 || !right_nc->set_type(type, true, location))
4420 return false;
4421
4422 bool ret;
4423 int cmp;
4424 if (type->complex_type() != NULL)
4425 {
4426 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4427 return false;
4428 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4429 }
4430 else if (type->float_type() != NULL)
4431 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4432 else
0c77715b 4433 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4434
4435 if (ret)
4436 *result = Binary_expression::cmp_to_bool(op, cmp);
4437
4438 return ret;
4439}
4440
4441// Compare integer constants.
4442
4443bool
4444Binary_expression::compare_integer(const Numeric_constant* left_nc,
4445 const Numeric_constant* right_nc,
4446 int* cmp)
4447{
4448 mpz_t left_val;
4449 if (!left_nc->to_int(&left_val))
4450 return false;
4451 mpz_t right_val;
4452 if (!right_nc->to_int(&right_val))
e440a328 4453 {
0c77715b 4454 mpz_clear(left_val);
4455 return false;
e440a328 4456 }
0c77715b 4457
4458 *cmp = mpz_cmp(left_val, right_val);
4459
4460 mpz_clear(left_val);
4461 mpz_clear(right_val);
4462
4463 return true;
4464}
4465
4466// Compare floating point constants.
4467
4468bool
4469Binary_expression::compare_float(const Numeric_constant* left_nc,
4470 const Numeric_constant* right_nc,
4471 int* cmp)
4472{
4473 mpfr_t left_val;
4474 if (!left_nc->to_float(&left_val))
4475 return false;
4476 mpfr_t right_val;
4477 if (!right_nc->to_float(&right_val))
e440a328 4478 {
0c77715b 4479 mpfr_clear(left_val);
4480 return false;
4481 }
4482
4483 // We already coerced both operands to the same type. If that type
4484 // is not an abstract type, we need to round the values accordingly.
4485 Type* type = left_nc->type();
4486 if (!type->is_abstract() && type->float_type() != NULL)
4487 {
4488 int bits = type->float_type()->bits();
4489 mpfr_prec_round(left_val, bits, GMP_RNDN);
4490 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4491 }
0c77715b 4492
4493 *cmp = mpfr_cmp(left_val, right_val);
4494
4495 mpfr_clear(left_val);
4496 mpfr_clear(right_val);
4497
4498 return true;
e440a328 4499}
4500
0c77715b 4501// Compare complex constants. Complex numbers may only be compared
4502// for equality.
e440a328 4503
4504bool
0c77715b 4505Binary_expression::compare_complex(const Numeric_constant* left_nc,
4506 const Numeric_constant* right_nc,
4507 int* cmp)
e440a328 4508{
0c77715b 4509 mpfr_t left_real, left_imag;
4510 if (!left_nc->to_complex(&left_real, &left_imag))
4511 return false;
4512 mpfr_t right_real, right_imag;
4513 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4514 {
0c77715b 4515 mpfr_clear(left_real);
4516 mpfr_clear(left_imag);
4517 return false;
e440a328 4518 }
0c77715b 4519
4520 // We already coerced both operands to the same type. If that type
4521 // is not an abstract type, we need to round the values accordingly.
4522 Type* type = left_nc->type();
4523 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4524 {
0c77715b 4525 int bits = type->complex_type()->bits();
4526 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4527 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4528 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4529 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
e440a328 4530 }
0c77715b 4531
4532 *cmp = (mpfr_cmp(left_real, right_real) != 0
4533 || mpfr_cmp(left_imag, right_imag) != 0);
4534
4535 mpfr_clear(left_real);
4536 mpfr_clear(left_imag);
4537 mpfr_clear(right_real);
4538 mpfr_clear(right_imag);
4539
4540 return true;
e440a328 4541}
4542
0c77715b 4543// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4544// true if this could be done, false if not. Issue errors at LOCATION
4545// as appropriate.
e440a328 4546
4547bool
0c77715b 4548Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4549 Numeric_constant* right_nc,
4550 Location location, Numeric_constant* nc)
e440a328 4551{
e440a328 4552 switch (op)
4553 {
4554 case OPERATOR_OROR:
4555 case OPERATOR_ANDAND:
4556 case OPERATOR_EQEQ:
4557 case OPERATOR_NOTEQ:
4558 case OPERATOR_LT:
4559 case OPERATOR_LE:
4560 case OPERATOR_GT:
4561 case OPERATOR_GE:
9767e2d3 4562 // These return boolean values, not numeric.
4563 return false;
0c77715b 4564 default:
4565 break;
4566 }
4567
4568 Type* left_type = left_nc->type();
4569 Type* right_type = right_nc->type();
4570
4571 Type* type;
4572 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4573 return false;
4574
4575 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4576
4577 // When combining an untyped operand with a typed operand, we are
4578 // effectively coercing the untyped operand to the other operand's
4579 // type, so make sure that is valid.
4580 if (!left_nc->set_type(type, true, location))
4581 return false;
4582 if (!is_shift && !right_nc->set_type(type, true, location))
4583 return false;
4584
4585 bool r;
4586 if (type->complex_type() != NULL)
4587 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4588 else if (type->float_type() != NULL)
4589 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4590 else
4591 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4592
4593 if (r)
4594 r = nc->set_type(type, true, location);
4595
4596 return r;
4597}
4598
4599// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4600// integer operations. Return true if this could be done, false if
4601// not.
4602
4603bool
4604Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4605 const Numeric_constant* right_nc,
4606 Location location, Numeric_constant* nc)
4607{
4608 mpz_t left_val;
4609 if (!left_nc->to_int(&left_val))
4610 return false;
4611 mpz_t right_val;
4612 if (!right_nc->to_int(&right_val))
4613 {
4614 mpz_clear(left_val);
e440a328 4615 return false;
0c77715b 4616 }
4617
4618 mpz_t val;
4619 mpz_init(val);
4620
4621 switch (op)
4622 {
e440a328 4623 case OPERATOR_PLUS:
4624 mpz_add(val, left_val, right_val);
2c809f8f 4625 if (mpz_sizeinbase(val, 2) > 0x100000)
4626 {
4627 error_at(location, "constant addition overflow");
4628 mpz_set_ui(val, 1);
4629 }
e440a328 4630 break;
4631 case OPERATOR_MINUS:
4632 mpz_sub(val, left_val, right_val);
2c809f8f 4633 if (mpz_sizeinbase(val, 2) > 0x100000)
4634 {
4635 error_at(location, "constant subtraction overflow");
4636 mpz_set_ui(val, 1);
4637 }
e440a328 4638 break;
4639 case OPERATOR_OR:
4640 mpz_ior(val, left_val, right_val);
4641 break;
4642 case OPERATOR_XOR:
4643 mpz_xor(val, left_val, right_val);
4644 break;
4645 case OPERATOR_MULT:
4646 mpz_mul(val, left_val, right_val);
2c809f8f 4647 if (mpz_sizeinbase(val, 2) > 0x100000)
4648 {
4649 error_at(location, "constant multiplication overflow");
4650 mpz_set_ui(val, 1);
4651 }
e440a328 4652 break;
4653 case OPERATOR_DIV:
4654 if (mpz_sgn(right_val) != 0)
4655 mpz_tdiv_q(val, left_val, right_val);
4656 else
4657 {
4658 error_at(location, "division by zero");
4659 mpz_set_ui(val, 0);
e440a328 4660 }
4661 break;
4662 case OPERATOR_MOD:
4663 if (mpz_sgn(right_val) != 0)
4664 mpz_tdiv_r(val, left_val, right_val);
4665 else
4666 {
4667 error_at(location, "division by zero");
4668 mpz_set_ui(val, 0);
e440a328 4669 }
4670 break;
4671 case OPERATOR_LSHIFT:
4672 {
4673 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4674 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4675 mpz_mul_2exp(val, left_val, shift);
4676 else
e440a328 4677 {
4678 error_at(location, "shift count overflow");
2c809f8f 4679 mpz_set_ui(val, 1);
e440a328 4680 }
e440a328 4681 break;
4682 }
4683 break;
4684 case OPERATOR_RSHIFT:
4685 {
4686 unsigned long shift = mpz_get_ui(right_val);
4687 if (mpz_cmp_ui(right_val, shift) != 0)
4688 {
4689 error_at(location, "shift count overflow");
2c809f8f 4690 mpz_set_ui(val, 1);
e440a328 4691 }
e440a328 4692 else
0c77715b 4693 {
4694 if (mpz_cmp_ui(left_val, 0) >= 0)
4695 mpz_tdiv_q_2exp(val, left_val, shift);
4696 else
4697 mpz_fdiv_q_2exp(val, left_val, shift);
4698 }
e440a328 4699 break;
4700 }
4701 break;
4702 case OPERATOR_AND:
4703 mpz_and(val, left_val, right_val);
4704 break;
4705 case OPERATOR_BITCLEAR:
4706 {
4707 mpz_t tval;
4708 mpz_init(tval);
4709 mpz_com(tval, right_val);
4710 mpz_and(val, left_val, tval);
4711 mpz_clear(tval);
4712 }
4713 break;
4714 default:
c3e6f413 4715 go_unreachable();
e440a328 4716 }
4717
0c77715b 4718 mpz_clear(left_val);
4719 mpz_clear(right_val);
e440a328 4720
0c77715b 4721 if (left_nc->is_rune()
4722 || (op != OPERATOR_LSHIFT
4723 && op != OPERATOR_RSHIFT
4724 && right_nc->is_rune()))
4725 nc->set_rune(NULL, val);
4726 else
4727 nc->set_int(NULL, val);
4728
4729 mpz_clear(val);
e440a328 4730
4731 return true;
4732}
4733
0c77715b 4734// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4735// floating point operations. Return true if this could be done,
4736// false if not.
e440a328 4737
4738bool
0c77715b 4739Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4740 const Numeric_constant* right_nc,
4741 Location location, Numeric_constant* nc)
e440a328 4742{
0c77715b 4743 mpfr_t left_val;
4744 if (!left_nc->to_float(&left_val))
4745 return false;
4746 mpfr_t right_val;
4747 if (!right_nc->to_float(&right_val))
e440a328 4748 {
0c77715b 4749 mpfr_clear(left_val);
e440a328 4750 return false;
0c77715b 4751 }
4752
4753 mpfr_t val;
4754 mpfr_init(val);
4755
4756 bool ret = true;
4757 switch (op)
4758 {
e440a328 4759 case OPERATOR_PLUS:
4760 mpfr_add(val, left_val, right_val, GMP_RNDN);
4761 break;
4762 case OPERATOR_MINUS:
4763 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4764 break;
4765 case OPERATOR_OR:
4766 case OPERATOR_XOR:
4767 case OPERATOR_AND:
4768 case OPERATOR_BITCLEAR:
0c77715b 4769 case OPERATOR_MOD:
4770 case OPERATOR_LSHIFT:
4771 case OPERATOR_RSHIFT:
4772 mpfr_set_ui(val, 0, GMP_RNDN);
4773 ret = false;
4774 break;
e440a328 4775 case OPERATOR_MULT:
4776 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4777 break;
4778 case OPERATOR_DIV:
0c77715b 4779 if (!mpfr_zero_p(right_val))
4780 mpfr_div(val, left_val, right_val, GMP_RNDN);
4781 else
4782 {
4783 error_at(location, "division by zero");
4784 mpfr_set_ui(val, 0, GMP_RNDN);
4785 }
e440a328 4786 break;
e440a328 4787 default:
c3e6f413 4788 go_unreachable();
e440a328 4789 }
4790
0c77715b 4791 mpfr_clear(left_val);
4792 mpfr_clear(right_val);
e440a328 4793
0c77715b 4794 nc->set_float(NULL, val);
4795 mpfr_clear(val);
e440a328 4796
0c77715b 4797 return ret;
e440a328 4798}
4799
0c77715b 4800// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4801// complex operations. Return true if this could be done, false if
4802// not.
e440a328 4803
4804bool
0c77715b 4805Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4806 const Numeric_constant* right_nc,
4807 Location location, Numeric_constant* nc)
e440a328 4808{
0c77715b 4809 mpfr_t left_real, left_imag;
4810 if (!left_nc->to_complex(&left_real, &left_imag))
4811 return false;
4812 mpfr_t right_real, right_imag;
4813 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4814 {
0c77715b 4815 mpfr_clear(left_real);
4816 mpfr_clear(left_imag);
e440a328 4817 return false;
0c77715b 4818 }
4819
4820 mpfr_t real, imag;
4821 mpfr_init(real);
4822 mpfr_init(imag);
4823
4824 bool ret = true;
4825 switch (op)
4826 {
e440a328 4827 case OPERATOR_PLUS:
4828 mpfr_add(real, left_real, right_real, GMP_RNDN);
4829 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4830 break;
4831 case OPERATOR_MINUS:
4832 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4833 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4834 break;
4835 case OPERATOR_OR:
4836 case OPERATOR_XOR:
4837 case OPERATOR_AND:
4838 case OPERATOR_BITCLEAR:
0c77715b 4839 case OPERATOR_MOD:
4840 case OPERATOR_LSHIFT:
4841 case OPERATOR_RSHIFT:
4842 mpfr_set_ui(real, 0, GMP_RNDN);
4843 mpfr_set_ui(imag, 0, GMP_RNDN);
4844 ret = false;
4845 break;
e440a328 4846 case OPERATOR_MULT:
4847 {
4848 // You might think that multiplying two complex numbers would
4849 // be simple, and you would be right, until you start to think
4850 // about getting the right answer for infinity. If one
4851 // operand here is infinity and the other is anything other
4852 // than zero or NaN, then we are going to wind up subtracting
4853 // two infinity values. That will give us a NaN, but the
4854 // correct answer is infinity.
4855
4856 mpfr_t lrrr;
4857 mpfr_init(lrrr);
4858 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4859
4860 mpfr_t lrri;
4861 mpfr_init(lrri);
4862 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4863
4864 mpfr_t lirr;
4865 mpfr_init(lirr);
4866 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4867
4868 mpfr_t liri;
4869 mpfr_init(liri);
4870 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4871
4872 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4873 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4874
4875 // If we get NaN on both sides, check whether it should really
4876 // be infinity. The rule is that if either side of the
4877 // complex number is infinity, then the whole value is
4878 // infinity, even if the other side is NaN. So the only case
4879 // we have to fix is the one in which both sides are NaN.
4880 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4881 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4882 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4883 {
4884 bool is_infinity = false;
4885
4886 mpfr_t lr;
4887 mpfr_t li;
4888 mpfr_init_set(lr, left_real, GMP_RNDN);
4889 mpfr_init_set(li, left_imag, GMP_RNDN);
4890
4891 mpfr_t rr;
4892 mpfr_t ri;
4893 mpfr_init_set(rr, right_real, GMP_RNDN);
4894 mpfr_init_set(ri, right_imag, GMP_RNDN);
4895
4896 // If the left side is infinity, then the result is
4897 // infinity.
4898 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4899 {
4900 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4901 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4902 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4903 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4904 if (mpfr_nan_p(rr))
4905 {
4906 mpfr_set_ui(rr, 0, GMP_RNDN);
4907 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4908 }
4909 if (mpfr_nan_p(ri))
4910 {
4911 mpfr_set_ui(ri, 0, GMP_RNDN);
4912 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4913 }
4914 is_infinity = true;
4915 }
4916
4917 // If the right side is infinity, then the result is
4918 // infinity.
4919 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4920 {
4921 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4922 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4923 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4924 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4925 if (mpfr_nan_p(lr))
4926 {
4927 mpfr_set_ui(lr, 0, GMP_RNDN);
4928 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4929 }
4930 if (mpfr_nan_p(li))
4931 {
4932 mpfr_set_ui(li, 0, GMP_RNDN);
4933 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4934 }
4935 is_infinity = true;
4936 }
4937
4938 // If we got an overflow in the intermediate computations,
4939 // then the result is infinity.
4940 if (!is_infinity
4941 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4942 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4943 {
4944 if (mpfr_nan_p(lr))
4945 {
4946 mpfr_set_ui(lr, 0, GMP_RNDN);
4947 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4948 }
4949 if (mpfr_nan_p(li))
4950 {
4951 mpfr_set_ui(li, 0, GMP_RNDN);
4952 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4953 }
4954 if (mpfr_nan_p(rr))
4955 {
4956 mpfr_set_ui(rr, 0, GMP_RNDN);
4957 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4958 }
4959 if (mpfr_nan_p(ri))
4960 {
4961 mpfr_set_ui(ri, 0, GMP_RNDN);
4962 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4963 }
4964 is_infinity = true;
4965 }
4966
4967 if (is_infinity)
4968 {
4969 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4970 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4971 mpfr_mul(lirr, li, rr, GMP_RNDN);
4972 mpfr_mul(liri, li, ri, GMP_RNDN);
4973 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4974 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4975 mpfr_set_inf(real, mpfr_sgn(real));
4976 mpfr_set_inf(imag, mpfr_sgn(imag));
4977 }
4978
4979 mpfr_clear(lr);
4980 mpfr_clear(li);
4981 mpfr_clear(rr);
4982 mpfr_clear(ri);
4983 }
4984
4985 mpfr_clear(lrrr);
4986 mpfr_clear(lrri);
4987 mpfr_clear(lirr);
4988 mpfr_clear(liri);
4989 }
4990 break;
4991 case OPERATOR_DIV:
4992 {
4993 // For complex division we want to avoid having an
4994 // intermediate overflow turn the whole result in a NaN. We
4995 // scale the values to try to avoid this.
4996
4997 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
0c77715b 4998 {
4999 error_at(location, "division by zero");
5000 mpfr_set_ui(real, 0, GMP_RNDN);
5001 mpfr_set_ui(imag, 0, GMP_RNDN);
5002 break;
5003 }
e440a328 5004
5005 mpfr_t rra;
5006 mpfr_t ria;
5007 mpfr_init(rra);
5008 mpfr_init(ria);
5009 mpfr_abs(rra, right_real, GMP_RNDN);
5010 mpfr_abs(ria, right_imag, GMP_RNDN);
5011 mpfr_t t;
5012 mpfr_init(t);
5013 mpfr_max(t, rra, ria, GMP_RNDN);
5014
5015 mpfr_t rr;
5016 mpfr_t ri;
5017 mpfr_init_set(rr, right_real, GMP_RNDN);
5018 mpfr_init_set(ri, right_imag, GMP_RNDN);
5019 long ilogbw = 0;
5020 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5021 {
5022 ilogbw = mpfr_get_exp(t);
5023 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5024 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5025 }
5026
5027 mpfr_t denom;
5028 mpfr_init(denom);
5029 mpfr_mul(denom, rr, rr, GMP_RNDN);
5030 mpfr_mul(t, ri, ri, GMP_RNDN);
5031 mpfr_add(denom, denom, t, GMP_RNDN);
5032
5033 mpfr_mul(real, left_real, rr, GMP_RNDN);
5034 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5035 mpfr_add(real, real, t, GMP_RNDN);
5036 mpfr_div(real, real, denom, GMP_RNDN);
5037 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5038
5039 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5040 mpfr_mul(t, left_real, ri, GMP_RNDN);
5041 mpfr_sub(imag, imag, t, GMP_RNDN);
5042 mpfr_div(imag, imag, denom, GMP_RNDN);
5043 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5044
5045 // If we wind up with NaN on both sides, check whether we
5046 // should really have infinity. The rule is that if either
5047 // side of the complex number is infinity, then the whole
5048 // value is infinity, even if the other side is NaN. So the
5049 // only case we have to fix is the one in which both sides are
5050 // NaN.
5051 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5052 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5053 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5054 {
5055 if (mpfr_zero_p(denom))
5056 {
5057 mpfr_set_inf(real, mpfr_sgn(rr));
5058 mpfr_mul(real, real, left_real, GMP_RNDN);
5059 mpfr_set_inf(imag, mpfr_sgn(rr));
5060 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5061 }
5062 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5063 && mpfr_number_p(rr) && mpfr_number_p(ri))
5064 {
5065 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5066 mpfr_copysign(t, t, left_real, GMP_RNDN);
5067
5068 mpfr_t t2;
5069 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5070 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5071
5072 mpfr_t t3;
5073 mpfr_init(t3);
5074 mpfr_mul(t3, t, rr, GMP_RNDN);
5075
5076 mpfr_t t4;
5077 mpfr_init(t4);
5078 mpfr_mul(t4, t2, ri, GMP_RNDN);
5079
5080 mpfr_add(t3, t3, t4, GMP_RNDN);
5081 mpfr_set_inf(real, mpfr_sgn(t3));
5082
5083 mpfr_mul(t3, t2, rr, GMP_RNDN);
5084 mpfr_mul(t4, t, ri, GMP_RNDN);
5085 mpfr_sub(t3, t3, t4, GMP_RNDN);
5086 mpfr_set_inf(imag, mpfr_sgn(t3));
5087
5088 mpfr_clear(t2);
5089 mpfr_clear(t3);
5090 mpfr_clear(t4);
5091 }
5092 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5093 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5094 {
5095 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5096 mpfr_copysign(t, t, rr, GMP_RNDN);
5097
5098 mpfr_t t2;
5099 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5100 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5101
5102 mpfr_t t3;
5103 mpfr_init(t3);
5104 mpfr_mul(t3, left_real, t, GMP_RNDN);
5105
5106 mpfr_t t4;
5107 mpfr_init(t4);
5108 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5109
5110 mpfr_add(t3, t3, t4, GMP_RNDN);
5111 mpfr_set_ui(real, 0, GMP_RNDN);
5112 mpfr_mul(real, real, t3, GMP_RNDN);
5113
5114 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5115 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5116 mpfr_sub(t3, t3, t4, GMP_RNDN);
5117 mpfr_set_ui(imag, 0, GMP_RNDN);
5118 mpfr_mul(imag, imag, t3, GMP_RNDN);
5119
5120 mpfr_clear(t2);
5121 mpfr_clear(t3);
5122 mpfr_clear(t4);
5123 }
5124 }
5125
5126 mpfr_clear(denom);
5127 mpfr_clear(rr);
5128 mpfr_clear(ri);
5129 mpfr_clear(t);
5130 mpfr_clear(rra);
5131 mpfr_clear(ria);
5132 }
5133 break;
e440a328 5134 default:
c3e6f413 5135 go_unreachable();
e440a328 5136 }
5137
0c77715b 5138 mpfr_clear(left_real);
5139 mpfr_clear(left_imag);
5140 mpfr_clear(right_real);
5141 mpfr_clear(right_imag);
e440a328 5142
0c77715b 5143 nc->set_complex(NULL, real, imag);
5144 mpfr_clear(real);
5145 mpfr_clear(imag);
e440a328 5146
0c77715b 5147 return ret;
e440a328 5148}
5149
5150// Lower a binary expression. We have to evaluate constant
5151// expressions now, in order to implement Go's unlimited precision
5152// constants.
5153
5154Expression*
e9d3367e 5155Binary_expression::do_lower(Gogo* gogo, Named_object*,
5156 Statement_inserter* inserter, int)
e440a328 5157{
b13c66cd 5158 Location location = this->location();
e440a328 5159 Operator op = this->op_;
5160 Expression* left = this->left_;
5161 Expression* right = this->right_;
5162
5163 const bool is_comparison = (op == OPERATOR_EQEQ
5164 || op == OPERATOR_NOTEQ
5165 || op == OPERATOR_LT
5166 || op == OPERATOR_LE
5167 || op == OPERATOR_GT
5168 || op == OPERATOR_GE);
5169
0c77715b 5170 // Numeric constant expressions.
e440a328 5171 {
0c77715b 5172 Numeric_constant left_nc;
5173 Numeric_constant right_nc;
5174 if (left->numeric_constant_value(&left_nc)
5175 && right->numeric_constant_value(&right_nc))
e440a328 5176 {
0c77715b 5177 if (is_comparison)
e440a328 5178 {
0c77715b 5179 bool result;
5180 if (!Binary_expression::compare_constant(op, &left_nc,
5181 &right_nc, location,
5182 &result))
5183 return this;
e90c9dfc 5184 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5185 Expression::make_boolean(result,
5186 location),
5187 location);
e440a328 5188 }
5189 else
5190 {
0c77715b 5191 Numeric_constant nc;
5192 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5193 location, &nc))
5194 return this;
5195 return nc.expression(location);
e440a328 5196 }
5197 }
e440a328 5198 }
5199
5200 // String constant expressions.
315fa98d 5201 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5202 {
5203 std::string left_string;
5204 std::string right_string;
5205 if (left->string_constant_value(&left_string)
5206 && right->string_constant_value(&right_string))
315fa98d 5207 {
5208 if (op == OPERATOR_PLUS)
5209 return Expression::make_string(left_string + right_string,
5210 location);
5211 else if (is_comparison)
5212 {
5213 int cmp = left_string.compare(right_string);
0c77715b 5214 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5215 return Expression::make_boolean(r, location);
b40dc774 5216 }
5217 }
b40dc774 5218 }
5219
ceeb12d7 5220 // Lower struct, array, and some interface comparisons.
e9d3367e 5221 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5222 {
5223 if (left->type()->struct_type() != NULL)
5224 return this->lower_struct_comparison(gogo, inserter);
5225 else if (left->type()->array_type() != NULL
5226 && !left->type()->is_slice_type())
5227 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5228 else if ((left->type()->interface_type() != NULL
5229 && right->type()->interface_type() == NULL)
5230 || (left->type()->interface_type() == NULL
5231 && right->type()->interface_type() != NULL))
5232 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5233 }
5234
e440a328 5235 return this;
5236}
5237
e9d3367e 5238// Lower a struct comparison.
5239
5240Expression*
5241Binary_expression::lower_struct_comparison(Gogo* gogo,
5242 Statement_inserter* inserter)
5243{
5244 Struct_type* st = this->left_->type()->struct_type();
5245 Struct_type* st2 = this->right_->type()->struct_type();
5246 if (st2 == NULL)
5247 return this;
5248 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5249 return this;
5250 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5251 this->right_->type(), NULL))
5252 return this;
5253
5254 // See if we can compare using memcmp. As a heuristic, we use
5255 // memcmp rather than field references and comparisons if there are
5256 // more than two fields.
113ef6a5 5257 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5258 return this->lower_compare_to_memcmp(gogo, inserter);
5259
5260 Location loc = this->location();
5261
5262 Expression* left = this->left_;
5263 Temporary_statement* left_temp = NULL;
5264 if (left->var_expression() == NULL
5265 && left->temporary_reference_expression() == NULL)
5266 {
5267 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5268 inserter->insert(left_temp);
5269 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5270 }
5271
5272 Expression* right = this->right_;
5273 Temporary_statement* right_temp = NULL;
5274 if (right->var_expression() == NULL
5275 && right->temporary_reference_expression() == NULL)
5276 {
5277 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5278 inserter->insert(right_temp);
5279 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5280 }
5281
5282 Expression* ret = Expression::make_boolean(true, loc);
5283 const Struct_field_list* fields = st->fields();
5284 unsigned int field_index = 0;
5285 for (Struct_field_list::const_iterator pf = fields->begin();
5286 pf != fields->end();
5287 ++pf, ++field_index)
5288 {
f5165c05 5289 if (Gogo::is_sink_name(pf->field_name()))
5290 continue;
5291
e9d3367e 5292 if (field_index > 0)
5293 {
5294 if (left_temp == NULL)
5295 left = left->copy();
5296 else
5297 left = Expression::make_temporary_reference(left_temp, loc);
5298 if (right_temp == NULL)
5299 right = right->copy();
5300 else
5301 right = Expression::make_temporary_reference(right_temp, loc);
5302 }
5303 Expression* f1 = Expression::make_field_reference(left, field_index,
5304 loc);
5305 Expression* f2 = Expression::make_field_reference(right, field_index,
5306 loc);
5307 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5308 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5309 }
5310
5311 if (this->op_ == OPERATOR_NOTEQ)
5312 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5313
5314 return ret;
5315}
5316
5317// Lower an array comparison.
5318
5319Expression*
5320Binary_expression::lower_array_comparison(Gogo* gogo,
5321 Statement_inserter* inserter)
5322{
5323 Array_type* at = this->left_->type()->array_type();
5324 Array_type* at2 = this->right_->type()->array_type();
5325 if (at2 == NULL)
5326 return this;
5327 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5328 return this;
5329 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5330 this->right_->type(), NULL))
5331 return this;
5332
5333 // Call memcmp directly if possible. This may let the middle-end
5334 // optimize the call.
113ef6a5 5335 if (at->compare_is_identity(gogo))
e9d3367e 5336 return this->lower_compare_to_memcmp(gogo, inserter);
5337
5338 // Call the array comparison function.
5339 Named_object* hash_fn;
5340 Named_object* equal_fn;
5341 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5342 &hash_fn, &equal_fn);
5343
5344 Location loc = this->location();
5345
5346 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5347
5348 Expression_list* args = new Expression_list();
5349 args->push_back(this->operand_address(inserter, this->left_));
5350 args->push_back(this->operand_address(inserter, this->right_));
5351 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5352
5353 Expression* ret = Expression::make_call(func, args, false, loc);
5354
5355 if (this->op_ == OPERATOR_NOTEQ)
5356 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5357
5358 return ret;
5359}
5360
ceeb12d7 5361// Lower an interface to value comparison.
5362
5363Expression*
5364Binary_expression::lower_interface_value_comparison(Gogo*,
5365 Statement_inserter* inserter)
5366{
5367 Type* left_type = this->left_->type();
5368 Type* right_type = this->right_->type();
5369 Interface_type* ift;
5370 if (left_type->interface_type() != NULL)
5371 {
5372 ift = left_type->interface_type();
5373 if (!ift->implements_interface(right_type, NULL))
5374 return this;
5375 }
5376 else
5377 {
5378 ift = right_type->interface_type();
5379 if (!ift->implements_interface(left_type, NULL))
5380 return this;
5381 }
5382 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5383 return this;
5384
5385 Location loc = this->location();
5386
5387 if (left_type->interface_type() == NULL
5388 && left_type->points_to() == NULL
5389 && !this->left_->is_addressable())
5390 {
5391 Temporary_statement* temp =
5392 Statement::make_temporary(left_type, NULL, loc);
5393 inserter->insert(temp);
5394 this->left_ =
5395 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5396 }
5397
5398 if (right_type->interface_type() == NULL
5399 && right_type->points_to() == NULL
5400 && !this->right_->is_addressable())
5401 {
5402 Temporary_statement* temp =
5403 Statement::make_temporary(right_type, NULL, loc);
5404 inserter->insert(temp);
5405 this->right_ =
5406 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5407 }
5408
5409 return this;
5410}
5411
e9d3367e 5412// Lower a struct or array comparison to a call to memcmp.
5413
5414Expression*
5415Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5416{
5417 Location loc = this->location();
5418
5419 Expression* a1 = this->operand_address(inserter, this->left_);
5420 Expression* a2 = this->operand_address(inserter, this->right_);
5421 Expression* len = Expression::make_type_info(this->left_->type(),
5422 TYPE_INFO_SIZE);
5423
5424 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5425
5426 mpz_t zval;
5427 mpz_init_set_ui(zval, 0);
5428 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5429 mpz_clear(zval);
5430
5431 return Expression::make_binary(this->op_, call, zero, loc);
5432}
5433
a32698ee 5434Expression*
5435Binary_expression::do_flatten(Gogo*, Named_object*,
5436 Statement_inserter* inserter)
5437{
5438 Location loc = this->location();
5439 Temporary_statement* temp;
5440 if (this->left_->type()->is_string_type()
5441 && this->op_ == OPERATOR_PLUS)
5442 {
5443 if (!this->left_->is_variable())
5444 {
5445 temp = Statement::make_temporary(NULL, this->left_, loc);
5446 inserter->insert(temp);
5447 this->left_ = Expression::make_temporary_reference(temp, loc);
5448 }
5449 if (!this->right_->is_variable())
5450 {
5451 temp =
5452 Statement::make_temporary(this->left_->type(), this->right_, loc);
5453 this->right_ = Expression::make_temporary_reference(temp, loc);
5454 inserter->insert(temp);
5455 }
5456 }
5457
5458 Type* left_type = this->left_->type();
5459 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5460 || this->op_ == OPERATOR_RSHIFT);
5461 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5462 left_type->integer_type() != NULL)
5463 || this->op_ == OPERATOR_MOD);
5464
5465 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5466 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5467 // and accessed from the Gogo* passed to do_flatten.
5468 if (is_shift_op
5469 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5470 {
5471 if (!this->left_->is_variable())
5472 {
5473 temp = Statement::make_temporary(NULL, this->left_, loc);
5474 inserter->insert(temp);
5475 this->left_ = Expression::make_temporary_reference(temp, loc);
5476 }
5477 if (!this->right_->is_variable())
5478 {
5479 temp =
5480 Statement::make_temporary(NULL, this->right_, loc);
5481 this->right_ = Expression::make_temporary_reference(temp, loc);
5482 inserter->insert(temp);
5483 }
5484 }
5485 return this;
5486}
5487
5488
e9d3367e 5489// Return the address of EXPR, cast to unsafe.Pointer.
5490
5491Expression*
5492Binary_expression::operand_address(Statement_inserter* inserter,
5493 Expression* expr)
5494{
5495 Location loc = this->location();
5496
5497 if (!expr->is_addressable())
5498 {
5499 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5500 loc);
5501 inserter->insert(temp);
5502 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5503 }
5504 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5505 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5506 Type* void_type = Type::make_void_type();
5507 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5508 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5509}
5510
0c77715b 5511// Return the numeric constant value, if it has one.
e440a328 5512
5513bool
0c77715b 5514Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5515{
0c77715b 5516 Numeric_constant left_nc;
5517 if (!this->left_->numeric_constant_value(&left_nc))
5518 return false;
5519 Numeric_constant right_nc;
5520 if (!this->right_->numeric_constant_value(&right_nc))
5521 return false;
9767e2d3 5522 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5523 this->location(), nc);
e440a328 5524}
5525
5526// Note that the value is being discarded.
5527
4f2138d7 5528bool
e440a328 5529Binary_expression::do_discarding_value()
5530{
5531 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5532 return this->right_->discarding_value();
e440a328 5533 else
4f2138d7 5534 {
5535 this->unused_value_error();
5536 return false;
5537 }
e440a328 5538}
5539
5540// Get type.
5541
5542Type*
5543Binary_expression::do_type()
5544{
5f5fea79 5545 if (this->classification() == EXPRESSION_ERROR)
5546 return Type::make_error_type();
5547
e440a328 5548 switch (this->op_)
5549 {
e440a328 5550 case OPERATOR_EQEQ:
5551 case OPERATOR_NOTEQ:
5552 case OPERATOR_LT:
5553 case OPERATOR_LE:
5554 case OPERATOR_GT:
5555 case OPERATOR_GE:
e90c9dfc 5556 if (this->type_ == NULL)
5557 this->type_ = Type::make_boolean_type();
5558 return this->type_;
e440a328 5559
5560 case OPERATOR_PLUS:
5561 case OPERATOR_MINUS:
5562 case OPERATOR_OR:
5563 case OPERATOR_XOR:
5564 case OPERATOR_MULT:
5565 case OPERATOR_DIV:
5566 case OPERATOR_MOD:
5567 case OPERATOR_AND:
5568 case OPERATOR_BITCLEAR:
e90c9dfc 5569 case OPERATOR_OROR:
5570 case OPERATOR_ANDAND:
e440a328 5571 {
0c77715b 5572 Type* type;
5573 if (!Binary_expression::operation_type(this->op_,
5574 this->left_->type(),
5575 this->right_->type(),
5576 &type))
5577 return Type::make_error_type();
5578 return type;
e440a328 5579 }
5580
5581 case OPERATOR_LSHIFT:
5582 case OPERATOR_RSHIFT:
5583 return this->left_->type();
5584
5585 default:
c3e6f413 5586 go_unreachable();
e440a328 5587 }
5588}
5589
5590// Set type for a binary expression.
5591
5592void
5593Binary_expression::do_determine_type(const Type_context* context)
5594{
5595 Type* tleft = this->left_->type();
5596 Type* tright = this->right_->type();
5597
5598 // Both sides should have the same type, except for the shift
5599 // operations. For a comparison, we should ignore the incoming
5600 // type.
5601
5602 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5603 || this->op_ == OPERATOR_RSHIFT);
5604
5605 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5606 || this->op_ == OPERATOR_NOTEQ
5607 || this->op_ == OPERATOR_LT
5608 || this->op_ == OPERATOR_LE
5609 || this->op_ == OPERATOR_GT
5610 || this->op_ == OPERATOR_GE);
5611
5612 Type_context subcontext(*context);
5613
5614 if (is_comparison)
5615 {
5616 // In a comparison, the context does not determine the types of
5617 // the operands.
5618 subcontext.type = NULL;
5619 }
5620
02ffd97f 5621 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5622 {
5623 // For a logical operation, the context does not determine the
5624 // types of the operands. The operands must be some boolean
5625 // type but if the context has a boolean type they do not
5626 // inherit it. See http://golang.org/issue/3924.
5627 subcontext.type = NULL;
5628 }
5629
e440a328 5630 // Set the context for the left hand operand.
5631 if (is_shift_op)
5632 {
b40dc774 5633 // The right hand operand of a shift plays no role in
5634 // determining the type of the left hand operand.
e440a328 5635 }
5636 else if (!tleft->is_abstract())
5637 subcontext.type = tleft;
5638 else if (!tright->is_abstract())
5639 subcontext.type = tright;
5640 else if (subcontext.type == NULL)
5641 {
5642 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5643 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5644 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5645 {
5646 // Both sides have an abstract integer, abstract float, or
5647 // abstract complex type. Just let CONTEXT determine
5648 // whether they may remain abstract or not.
5649 }
5650 else if (tleft->complex_type() != NULL)
5651 subcontext.type = tleft;
5652 else if (tright->complex_type() != NULL)
5653 subcontext.type = tright;
5654 else if (tleft->float_type() != NULL)
5655 subcontext.type = tleft;
5656 else if (tright->float_type() != NULL)
5657 subcontext.type = tright;
5658 else
5659 subcontext.type = tleft;
f58a23ae 5660
5661 if (subcontext.type != NULL && !context->may_be_abstract)
5662 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5663 }
5664
5665 this->left_->determine_type(&subcontext);
5666
e440a328 5667 if (is_shift_op)
5668 {
b40dc774 5669 // We may have inherited an unusable type for the shift operand.
5670 // Give a useful error if that happened.
5671 if (tleft->is_abstract()
5672 && subcontext.type != NULL
8ab6effb 5673 && !subcontext.may_be_abstract
f6bc81e6 5674 && subcontext.type->interface_type() == NULL
8ab6effb 5675 && subcontext.type->integer_type() == NULL)
b40dc774 5676 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5677 "for left operand of shift"));
b40dc774 5678
5679 // The context for the right hand operand is the same as for the
5680 // left hand operand, except for a shift operator.
e440a328 5681 subcontext.type = Type::lookup_integer_type("uint");
5682 subcontext.may_be_abstract = false;
5683 }
5684
5685 this->right_->determine_type(&subcontext);
e90c9dfc 5686
5687 if (is_comparison)
5688 {
5689 if (this->type_ != NULL && !this->type_->is_abstract())
5690 ;
5691 else if (context->type != NULL && context->type->is_boolean_type())
5692 this->type_ = context->type;
5693 else if (!context->may_be_abstract)
5694 this->type_ = Type::lookup_bool_type();
5695 }
e440a328 5696}
5697
5698// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5699// OTYPE is the type of the other operand. Return whether the
5700// operation is OK. This should not be used for shift.
e440a328 5701
5702bool
be8b5eee 5703Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5704 Location location)
e440a328 5705{
5706 switch (op)
5707 {
5708 case OPERATOR_OROR:
5709 case OPERATOR_ANDAND:
5710 if (!type->is_boolean_type())
5711 {
5712 error_at(location, "expected boolean type");
5713 return false;
5714 }
5715 break;
5716
5717 case OPERATOR_EQEQ:
5718 case OPERATOR_NOTEQ:
e9d3367e 5719 {
5720 std::string reason;
5721 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5722 {
5723 error_at(location, "%s", reason.c_str());
5724 return false;
5725 }
5726 }
e440a328 5727 break;
5728
5729 case OPERATOR_LT:
5730 case OPERATOR_LE:
5731 case OPERATOR_GT:
5732 case OPERATOR_GE:
e9d3367e 5733 {
5734 std::string reason;
5735 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5736 {
5737 error_at(location, "%s", reason.c_str());
5738 return false;
5739 }
5740 }
e440a328 5741 break;
5742
5743 case OPERATOR_PLUS:
5744 case OPERATOR_PLUSEQ:
5745 if (type->integer_type() == NULL
5746 && type->float_type() == NULL
5747 && type->complex_type() == NULL
5748 && !type->is_string_type())
5749 {
5750 error_at(location,
5751 "expected integer, floating, complex, or string type");
5752 return false;
5753 }
5754 break;
5755
5756 case OPERATOR_MINUS:
5757 case OPERATOR_MINUSEQ:
5758 case OPERATOR_MULT:
5759 case OPERATOR_MULTEQ:
5760 case OPERATOR_DIV:
5761 case OPERATOR_DIVEQ:
5762 if (type->integer_type() == NULL
5763 && type->float_type() == NULL
5764 && type->complex_type() == NULL)
5765 {
5766 error_at(location, "expected integer, floating, or complex type");
5767 return false;
5768 }
5769 break;
5770
5771 case OPERATOR_MOD:
5772 case OPERATOR_MODEQ:
5773 case OPERATOR_OR:
5774 case OPERATOR_OREQ:
5775 case OPERATOR_AND:
5776 case OPERATOR_ANDEQ:
5777 case OPERATOR_XOR:
5778 case OPERATOR_XOREQ:
5779 case OPERATOR_BITCLEAR:
5780 case OPERATOR_BITCLEAREQ:
5781 if (type->integer_type() == NULL)
5782 {
5783 error_at(location, "expected integer type");
5784 return false;
5785 }
5786 break;
5787
5788 default:
c3e6f413 5789 go_unreachable();
e440a328 5790 }
5791
5792 return true;
5793}
5794
5795// Check types.
5796
5797void
5798Binary_expression::do_check_types(Gogo*)
5799{
5f5fea79 5800 if (this->classification() == EXPRESSION_ERROR)
5801 return;
5802
e440a328 5803 Type* left_type = this->left_->type();
5804 Type* right_type = this->right_->type();
5c13bd80 5805 if (left_type->is_error() || right_type->is_error())
9fe897ef 5806 {
5807 this->set_is_error();
5808 return;
5809 }
e440a328 5810
5811 if (this->op_ == OPERATOR_EQEQ
5812 || this->op_ == OPERATOR_NOTEQ
5813 || this->op_ == OPERATOR_LT
5814 || this->op_ == OPERATOR_LE
5815 || this->op_ == OPERATOR_GT
5816 || this->op_ == OPERATOR_GE)
5817 {
907c5ecd 5818 if (left_type->is_nil_type() && right_type->is_nil_type())
5819 {
5820 this->report_error(_("invalid comparison of nil with nil"));
5821 return;
5822 }
e440a328 5823 if (!Type::are_assignable(left_type, right_type, NULL)
5824 && !Type::are_assignable(right_type, left_type, NULL))
5825 {
5826 this->report_error(_("incompatible types in binary expression"));
5827 return;
5828 }
5829 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5830 right_type,
e440a328 5831 this->location())
5832 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5833 left_type,
e440a328 5834 this->location()))
5835 {
5836 this->set_is_error();
5837 return;
5838 }
5839 }
5840 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5841 {
5842 if (!Type::are_compatible_for_binop(left_type, right_type))
5843 {
5844 this->report_error(_("incompatible types in binary expression"));
5845 return;
5846 }
5847 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5848 right_type,
e440a328 5849 this->location()))
5850 {
5851 this->set_is_error();
5852 return;
5853 }
5c65b19d 5854 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5855 {
5856 // Division by a zero integer constant is an error.
5857 Numeric_constant rconst;
5858 unsigned long rval;
5859 if (left_type->integer_type() != NULL
5860 && this->right_->numeric_constant_value(&rconst)
5861 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5862 && rval == 0)
5863 {
5864 this->report_error(_("integer division by zero"));
5865 return;
5866 }
5867 }
e440a328 5868 }
5869 else
5870 {
5871 if (left_type->integer_type() == NULL)
5872 this->report_error(_("shift of non-integer operand"));
5873
5874 if (!right_type->is_abstract()
5875 && (right_type->integer_type() == NULL
5876 || !right_type->integer_type()->is_unsigned()))
5877 this->report_error(_("shift count not unsigned integer"));
5878 else
5879 {
0c77715b 5880 Numeric_constant nc;
5881 if (this->right_->numeric_constant_value(&nc))
e440a328 5882 {
0c77715b 5883 mpz_t val;
5884 if (!nc.to_int(&val))
5885 this->report_error(_("shift count not unsigned integer"));
5886 else
a4eba91b 5887 {
0c77715b 5888 if (mpz_sgn(val) < 0)
5889 {
5890 this->report_error(_("negative shift count"));
5891 mpz_set_ui(val, 0);
5892 Location rloc = this->right_->location();
5893 this->right_ = Expression::make_integer(&val, right_type,
5894 rloc);
5895 }
5896 mpz_clear(val);
a4eba91b 5897 }
e440a328 5898 }
e440a328 5899 }
5900 }
5901}
5902
5903// Get a tree for a binary expression.
5904
5905tree
5906Binary_expression::do_get_tree(Translate_context* context)
5907{
1b1f2abf 5908 Gogo* gogo = context->gogo();
a32698ee 5909 Location loc = this->location();
5910 Type* left_type = this->left_->type();
5911 Type* right_type = this->right_->type();
1b1f2abf 5912
e440a328 5913 bool use_left_type = true;
5914 bool is_shift_op = false;
29a2d1d8 5915 bool is_idiv_op = false;
e440a328 5916 switch (this->op_)
5917 {
5918 case OPERATOR_EQEQ:
5919 case OPERATOR_NOTEQ:
5920 case OPERATOR_LT:
5921 case OPERATOR_LE:
5922 case OPERATOR_GT:
5923 case OPERATOR_GE:
a32698ee 5924 {
5925 Bexpression* ret =
5926 Expression::comparison(context, this->type_, this->op_,
5927 this->left_, this->right_, loc);
5928 return expr_to_tree(ret);
5929 }
e440a328 5930
5931 case OPERATOR_OROR:
e440a328 5932 case OPERATOR_ANDAND:
e440a328 5933 use_left_type = false;
5934 break;
5935 case OPERATOR_PLUS:
e440a328 5936 case OPERATOR_MINUS:
e440a328 5937 case OPERATOR_OR:
e440a328 5938 case OPERATOR_XOR:
e440a328 5939 case OPERATOR_MULT:
e440a328 5940 break;
5941 case OPERATOR_DIV:
a32698ee 5942 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5943 break;
e440a328 5944 case OPERATOR_MOD:
29a2d1d8 5945 is_idiv_op = true;
e440a328 5946 break;
5947 case OPERATOR_LSHIFT:
e440a328 5948 case OPERATOR_RSHIFT:
e440a328 5949 is_shift_op = true;
5950 break;
e440a328 5951 case OPERATOR_BITCLEAR:
a32698ee 5952 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5953 case OPERATOR_AND:
e440a328 5954 break;
5955 default:
c3e6f413 5956 go_unreachable();
e440a328 5957 }
5958
a32698ee 5959 if (left_type->is_string_type())
e440a328 5960 {
c484d925 5961 go_assert(this->op_ == OPERATOR_PLUS);
a32698ee 5962 Expression* string_plus =
5963 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5964 this->left_, this->right_);
5965 return string_plus->get_tree(context);
5966 }
5967
5968 // For complex division Go might want slightly different results than the
5969 // backend implementation provides, so we have our own runtime routine.
1850e20c 5970 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5971 {
a32698ee 5972 Runtime::Function complex_code;
1850e20c 5973 switch (this->left_->type()->complex_type()->bits())
5974 {
5975 case 64:
a32698ee 5976 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5977 break;
5978 case 128:
a32698ee 5979 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5980 break;
5981 default:
5982 go_unreachable();
5983 }
a32698ee 5984 Expression* complex_div =
5985 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5986 return complex_div->get_tree(context);
1850e20c 5987 }
5988
a32698ee 5989 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
5990 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
e440a328 5991
a32698ee 5992 Type* type = use_left_type ? left_type : right_type;
5993 Btype* btype = type->get_backend(gogo);
5994
5995 Bexpression* ret =
5996 gogo->backend()->binary_expression(this->op_, left, right, loc);
5997 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 5998
a32698ee 5999 // Initialize overflow constants.
6000 Bexpression* overflow;
6001 mpz_t zero;
6002 mpz_init_set_ui(zero, 0UL);
6003 mpz_t one;
6004 mpz_init_set_ui(one, 1UL);
6005 mpz_t neg_one;
6006 mpz_init_set_si(neg_one, -1);
e440a328 6007
a32698ee 6008 Btype* left_btype = left_type->get_backend(gogo);
6009 Btype* right_btype = right_type->get_backend(gogo);
e440a328 6010
6011 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 6012 // This is not true in C, so we need to insert a conditional.
e440a328 6013 if (is_shift_op)
6014 {
a32698ee 6015 go_assert(left_type->integer_type() != NULL);
e440a328 6016
a32698ee 6017 mpz_t bitsval;
6018 int bits = left_type->integer_type()->bits();
6019 mpz_init_set_ui(bitsval, bits);
6020 Bexpression* bits_expr =
6021 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6022 Bexpression* compare =
6023 gogo->backend()->binary_expression(OPERATOR_LT,
6024 right, bits_expr, loc);
e440a328 6025
a32698ee 6026 Bexpression* zero_expr =
6027 gogo->backend()->integer_constant_expression(left_btype, zero);
6028 overflow = zero_expr;
e440a328 6029 if (this->op_ == OPERATOR_RSHIFT
a32698ee 6030 && !left_type->integer_type()->is_unsigned())
e440a328 6031 {
a32698ee 6032 Bexpression* neg_expr =
6033 gogo->backend()->binary_expression(OPERATOR_LT, left,
6034 zero_expr, loc);
6035 Bexpression* neg_one_expr =
6036 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6037 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6038 neg_one_expr,
6039 zero_expr, loc);
29a2d1d8 6040 }
a32698ee 6041 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6042 overflow, loc);
6043 mpz_clear(bitsval);
29a2d1d8 6044 }
6045
6046 // Add checks for division by zero and division overflow as needed.
6047 if (is_idiv_op)
6048 {
6049 if (go_check_divide_zero)
6050 {
6051 // right == 0
a32698ee 6052 Bexpression* zero_expr =
6053 gogo->backend()->integer_constant_expression(right_btype, zero);
6054 Bexpression* check =
6055 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6056 right, zero_expr, loc);
29a2d1d8 6057
a32698ee 6058 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 6059 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
a32698ee 6060 Expression* crash = gogo->runtime_error(errcode, loc);
6061 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
29a2d1d8 6062
6063 // right == 0 ? (__go_runtime_error(...), 0) : ret
a32698ee 6064 ret = gogo->backend()->conditional_expression(btype, check,
6065 crash_expr, ret, loc);
b13c66cd 6066 }
6067
29a2d1d8 6068 if (go_check_divide_overflow)
6069 {
6070 // right == -1
6071 // FIXME: It would be nice to say that this test is expected
6072 // to return false.
a32698ee 6073
6074 Bexpression* neg_one_expr =
6075 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6076 Bexpression* check =
6077 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6078 right, neg_one_expr, loc);
6079
6080 Bexpression* zero_expr =
6081 gogo->backend()->integer_constant_expression(btype, zero);
6082 Bexpression* one_expr =
6083 gogo->backend()->integer_constant_expression(btype, one);
6084
6085 if (type->integer_type()->is_unsigned())
29a2d1d8 6086 {
6087 // An unsigned -1 is the largest possible number, so
6088 // dividing is always 1 or 0.
a32698ee 6089
6090 Bexpression* cmp =
6091 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6092 left, right, loc);
29a2d1d8 6093 if (this->op_ == OPERATOR_DIV)
a32698ee 6094 overflow =
6095 gogo->backend()->conditional_expression(btype, cmp,
6096 one_expr, zero_expr,
6097 loc);
29a2d1d8 6098 else
a32698ee 6099 overflow =
6100 gogo->backend()->conditional_expression(btype, cmp,
6101 zero_expr, left,
6102 loc);
29a2d1d8 6103 }
6104 else
6105 {
6106 // Computing left / -1 is the same as computing - left,
6107 // which does not overflow since Go sets -fwrapv.
6108 if (this->op_ == OPERATOR_DIV)
a32698ee 6109 {
6110 Expression* negate_expr =
6111 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6112 overflow = tree_to_expr(negate_expr->get_tree(context));
6113 }
29a2d1d8 6114 else
a32698ee 6115 overflow = zero_expr;
29a2d1d8 6116 }
a32698ee 6117 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6118
6119 // right == -1 ? - left : ret
a32698ee 6120 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6121 ret, loc);
29a2d1d8 6122 }
e440a328 6123 }
6124
a32698ee 6125 mpz_clear(zero);
6126 mpz_clear(one);
6127 mpz_clear(neg_one);
6128 return expr_to_tree(ret);
e440a328 6129}
6130
6131// Export a binary expression.
6132
6133void
6134Binary_expression::do_export(Export* exp) const
6135{
6136 exp->write_c_string("(");
6137 this->left_->export_expression(exp);
6138 switch (this->op_)
6139 {
6140 case OPERATOR_OROR:
6141 exp->write_c_string(" || ");
6142 break;
6143 case OPERATOR_ANDAND:
6144 exp->write_c_string(" && ");
6145 break;
6146 case OPERATOR_EQEQ:
6147 exp->write_c_string(" == ");
6148 break;
6149 case OPERATOR_NOTEQ:
6150 exp->write_c_string(" != ");
6151 break;
6152 case OPERATOR_LT:
6153 exp->write_c_string(" < ");
6154 break;
6155 case OPERATOR_LE:
6156 exp->write_c_string(" <= ");
6157 break;
6158 case OPERATOR_GT:
6159 exp->write_c_string(" > ");
6160 break;
6161 case OPERATOR_GE:
6162 exp->write_c_string(" >= ");
6163 break;
6164 case OPERATOR_PLUS:
6165 exp->write_c_string(" + ");
6166 break;
6167 case OPERATOR_MINUS:
6168 exp->write_c_string(" - ");
6169 break;
6170 case OPERATOR_OR:
6171 exp->write_c_string(" | ");
6172 break;
6173 case OPERATOR_XOR:
6174 exp->write_c_string(" ^ ");
6175 break;
6176 case OPERATOR_MULT:
6177 exp->write_c_string(" * ");
6178 break;
6179 case OPERATOR_DIV:
6180 exp->write_c_string(" / ");
6181 break;
6182 case OPERATOR_MOD:
6183 exp->write_c_string(" % ");
6184 break;
6185 case OPERATOR_LSHIFT:
6186 exp->write_c_string(" << ");
6187 break;
6188 case OPERATOR_RSHIFT:
6189 exp->write_c_string(" >> ");
6190 break;
6191 case OPERATOR_AND:
6192 exp->write_c_string(" & ");
6193 break;
6194 case OPERATOR_BITCLEAR:
6195 exp->write_c_string(" &^ ");
6196 break;
6197 default:
c3e6f413 6198 go_unreachable();
e440a328 6199 }
6200 this->right_->export_expression(exp);
6201 exp->write_c_string(")");
6202}
6203
6204// Import a binary expression.
6205
6206Expression*
6207Binary_expression::do_import(Import* imp)
6208{
6209 imp->require_c_string("(");
6210
6211 Expression* left = Expression::import_expression(imp);
6212
6213 Operator op;
6214 if (imp->match_c_string(" || "))
6215 {
6216 op = OPERATOR_OROR;
6217 imp->advance(4);
6218 }
6219 else if (imp->match_c_string(" && "))
6220 {
6221 op = OPERATOR_ANDAND;
6222 imp->advance(4);
6223 }
6224 else if (imp->match_c_string(" == "))
6225 {
6226 op = OPERATOR_EQEQ;
6227 imp->advance(4);
6228 }
6229 else if (imp->match_c_string(" != "))
6230 {
6231 op = OPERATOR_NOTEQ;
6232 imp->advance(4);
6233 }
6234 else if (imp->match_c_string(" < "))
6235 {
6236 op = OPERATOR_LT;
6237 imp->advance(3);
6238 }
6239 else if (imp->match_c_string(" <= "))
6240 {
6241 op = OPERATOR_LE;
6242 imp->advance(4);
6243 }
6244 else if (imp->match_c_string(" > "))
6245 {
6246 op = OPERATOR_GT;
6247 imp->advance(3);
6248 }
6249 else if (imp->match_c_string(" >= "))
6250 {
6251 op = OPERATOR_GE;
6252 imp->advance(4);
6253 }
6254 else if (imp->match_c_string(" + "))
6255 {
6256 op = OPERATOR_PLUS;
6257 imp->advance(3);
6258 }
6259 else if (imp->match_c_string(" - "))
6260 {
6261 op = OPERATOR_MINUS;
6262 imp->advance(3);
6263 }
6264 else if (imp->match_c_string(" | "))
6265 {
6266 op = OPERATOR_OR;
6267 imp->advance(3);
6268 }
6269 else if (imp->match_c_string(" ^ "))
6270 {
6271 op = OPERATOR_XOR;
6272 imp->advance(3);
6273 }
6274 else if (imp->match_c_string(" * "))
6275 {
6276 op = OPERATOR_MULT;
6277 imp->advance(3);
6278 }
6279 else if (imp->match_c_string(" / "))
6280 {
6281 op = OPERATOR_DIV;
6282 imp->advance(3);
6283 }
6284 else if (imp->match_c_string(" % "))
6285 {
6286 op = OPERATOR_MOD;
6287 imp->advance(3);
6288 }
6289 else if (imp->match_c_string(" << "))
6290 {
6291 op = OPERATOR_LSHIFT;
6292 imp->advance(4);
6293 }
6294 else if (imp->match_c_string(" >> "))
6295 {
6296 op = OPERATOR_RSHIFT;
6297 imp->advance(4);
6298 }
6299 else if (imp->match_c_string(" & "))
6300 {
6301 op = OPERATOR_AND;
6302 imp->advance(3);
6303 }
6304 else if (imp->match_c_string(" &^ "))
6305 {
6306 op = OPERATOR_BITCLEAR;
6307 imp->advance(4);
6308 }
6309 else
6310 {
6311 error_at(imp->location(), "unrecognized binary operator");
6312 return Expression::make_error(imp->location());
6313 }
6314
6315 Expression* right = Expression::import_expression(imp);
6316
6317 imp->require_c_string(")");
6318
6319 return Expression::make_binary(op, left, right, imp->location());
6320}
6321
d751bb78 6322// Dump ast representation of a binary expression.
6323
6324void
6325Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6326{
6327 ast_dump_context->ostream() << "(";
6328 ast_dump_context->dump_expression(this->left_);
6329 ast_dump_context->ostream() << " ";
6330 ast_dump_context->dump_operator(this->op_);
6331 ast_dump_context->ostream() << " ";
6332 ast_dump_context->dump_expression(this->right_);
6333 ast_dump_context->ostream() << ") ";
6334}
6335
e440a328 6336// Make a binary expression.
6337
6338Expression*
6339Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6340 Location location)
e440a328 6341{
6342 return new Binary_expression(op, left, right, location);
6343}
6344
6345// Implement a comparison.
6346
a32698ee 6347Bexpression*
6348Expression::comparison(Translate_context* context, Type* result_type,
6349 Operator op, Expression* left, Expression* right,
6350 Location location)
e440a328 6351{
2387f644 6352 Type* left_type = left->type();
6353 Type* right_type = right->type();
ceeb12d7 6354
6355 mpz_t zval;
6356 mpz_init_set_ui(zval, 0UL);
6357 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6358 mpz_clear(zval);
1b1f2abf 6359
15c67ee2 6360 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6361 {
2387f644 6362 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6363 left, right);
6364 right = zexpr;
e440a328 6365 }
15c67ee2 6366 else if ((left_type->interface_type() != NULL
6367 && right_type->interface_type() == NULL
6368 && !right_type->is_nil_type())
6369 || (left_type->interface_type() == NULL
6370 && !left_type->is_nil_type()
6371 && right_type->interface_type() != NULL))
e440a328 6372 {
6373 // Comparing an interface value to a non-interface value.
6374 if (left_type->interface_type() == NULL)
6375 {
6376 std::swap(left_type, right_type);
2387f644 6377 std::swap(left, right);
e440a328 6378 }
6379
6380 // The right operand is not an interface. We need to take its
6381 // address if it is not a pointer.
ceeb12d7 6382 Expression* pointer_arg = NULL;
e440a328 6383 if (right_type->points_to() != NULL)
2387f644 6384 pointer_arg = right;
e440a328 6385 else
6386 {
2387f644 6387 go_assert(right->is_addressable());
6388 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6389 location);
e440a328 6390 }
e440a328 6391
2387f644 6392 Expression* descriptor =
6393 Expression::make_type_descriptor(right_type, location);
6394 left =
ceeb12d7 6395 Runtime::make_call((left_type->interface_type()->is_empty()
6396 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6397 : Runtime::INTERFACE_VALUE_COMPARE),
2387f644 6398 location, 3, left, descriptor,
ceeb12d7 6399 pointer_arg);
2387f644 6400 right = zexpr;
e440a328 6401 }
6402 else if (left_type->interface_type() != NULL
6403 && right_type->interface_type() != NULL)
6404 {
ceeb12d7 6405 Runtime::Function compare_function;
739bad04 6406 if (left_type->interface_type()->is_empty()
6407 && right_type->interface_type()->is_empty())
ceeb12d7 6408 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
739bad04 6409 else if (!left_type->interface_type()->is_empty()
6410 && !right_type->interface_type()->is_empty())
ceeb12d7 6411 compare_function = Runtime::INTERFACE_COMPARE;
739bad04 6412 else
6413 {
6414 if (left_type->interface_type()->is_empty())
6415 {
c484d925 6416 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
739bad04 6417 std::swap(left_type, right_type);
2387f644 6418 std::swap(left, right);
739bad04 6419 }
c484d925 6420 go_assert(!left_type->interface_type()->is_empty());
6421 go_assert(right_type->interface_type()->is_empty());
ceeb12d7 6422 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
739bad04 6423 }
6424
2387f644 6425 left = Runtime::make_call(compare_function, location, 2, left, right);
6426 right = zexpr;
e440a328 6427 }
6428
6429 if (left_type->is_nil_type()
6430 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6431 {
6432 std::swap(left_type, right_type);
2387f644 6433 std::swap(left, right);
e440a328 6434 }
6435
6436 if (right_type->is_nil_type())
6437 {
2387f644 6438 right = Expression::make_nil(location);
e440a328 6439 if (left_type->array_type() != NULL
6440 && left_type->array_type()->length() == NULL)
6441 {
6442 Array_type* at = left_type->array_type();
2387f644 6443 left = at->get_value_pointer(context->gogo(), left);
e440a328 6444 }
6445 else if (left_type->interface_type() != NULL)
6446 {
6447 // An interface is nil if the first field is nil.
2387f644 6448 left = Expression::make_field_reference(left, 0, location);
e440a328 6449 }
6450 }
6451
a32698ee 6452 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6453 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
e90c9dfc 6454
a32698ee 6455 Gogo* gogo = context->gogo();
6456 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6457 right_bexpr, location);
6458 if (result_type != NULL)
6459 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6460 ret, location);
e440a328 6461 return ret;
6462}
6463
6464// Class Bound_method_expression.
6465
6466// Traversal.
6467
6468int
6469Bound_method_expression::do_traverse(Traverse* traverse)
6470{
e0659c9e 6471 return Expression::traverse(&this->expr_, traverse);
e440a328 6472}
6473
0afbb937 6474// Lower the expression. If this is a method value rather than being
6475// called, and the method is accessed via a pointer, we may need to
6476// add nil checks. Introduce a temporary variable so that those nil
6477// checks do not cause multiple evaluation.
6478
6479Expression*
6480Bound_method_expression::do_lower(Gogo*, Named_object*,
6481 Statement_inserter* inserter, int)
6482{
6483 // For simplicity we use a temporary for every call to an embedded
6484 // method, even though some of them might be pure value methods and
6485 // not require a temporary.
6486 if (this->expr_->var_expression() == NULL
6487 && this->expr_->temporary_reference_expression() == NULL
6488 && this->expr_->set_and_use_temporary_expression() == NULL
6489 && (this->method_->field_indexes() != NULL
6490 || (this->method_->is_value_method()
6491 && this->expr_->type()->points_to() != NULL)))
6492 {
6493 Temporary_statement* temp =
6494 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6495 inserter->insert(temp);
6496 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6497 this->location());
6498 }
6499 return this;
6500}
6501
e440a328 6502// Return the type of a bound method expression. The type of this
0afbb937 6503// object is simply the type of the method with no receiver.
e440a328 6504
6505Type*
6506Bound_method_expression::do_type()
6507{
0afbb937 6508 Named_object* fn = this->method_->named_object();
6509 Function_type* fntype;
6510 if (fn->is_function())
6511 fntype = fn->func_value()->type();
6512 else if (fn->is_function_declaration())
6513 fntype = fn->func_declaration_value()->type();
e0659c9e 6514 else
6515 return Type::make_error_type();
0afbb937 6516 return fntype->copy_without_receiver();
e440a328 6517}
6518
6519// Determine the types of a method expression.
6520
6521void
6522Bound_method_expression::do_determine_type(const Type_context*)
6523{
0afbb937 6524 Named_object* fn = this->method_->named_object();
6525 Function_type* fntype;
6526 if (fn->is_function())
6527 fntype = fn->func_value()->type();
6528 else if (fn->is_function_declaration())
6529 fntype = fn->func_declaration_value()->type();
6530 else
6531 fntype = NULL;
e440a328 6532 if (fntype == NULL || !fntype->is_method())
6533 this->expr_->determine_type_no_context();
6534 else
6535 {
6536 Type_context subcontext(fntype->receiver()->type(), false);
6537 this->expr_->determine_type(&subcontext);
6538 }
6539}
6540
6541// Check the types of a method expression.
6542
6543void
6544Bound_method_expression::do_check_types(Gogo*)
6545{
0afbb937 6546 Named_object* fn = this->method_->named_object();
6547 if (!fn->is_function() && !fn->is_function_declaration())
6548 {
6549 this->report_error(_("object is not a method"));
6550 return;
6551 }
6552
6553 Function_type* fntype;
6554 if (fn->is_function())
6555 fntype = fn->func_value()->type();
6556 else if (fn->is_function_declaration())
6557 fntype = fn->func_declaration_value()->type();
e440a328 6558 else
0afbb937 6559 go_unreachable();
6560 Type* rtype = fntype->receiver()->type()->deref();
6561 Type* etype = (this->expr_type_ != NULL
6562 ? this->expr_type_
6563 : this->expr_->type());
6564 etype = etype->deref();
6565 if (!Type::are_identical(rtype, etype, true, NULL))
6566 this->report_error(_("method type does not match object type"));
6567}
6568
6569// If a bound method expression is not simply called, then it is
6570// represented as a closure. The closure will hold a single variable,
6571// the receiver to pass to the method. The function will be a simple
6572// thunk that pulls that value from the closure and calls the method
6573// with the remaining arguments.
6574//
6575// Because method values are not common, we don't build all thunks for
6576// every methods, but instead only build them as we need them. In
6577// particular, we even build them on demand for methods defined in
6578// other packages.
6579
6580Bound_method_expression::Method_value_thunks
6581 Bound_method_expression::method_value_thunks;
6582
6583// Find or create the thunk for METHOD.
6584
6585Named_object*
6586Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6587 Named_object* fn)
6588{
6589 std::pair<Named_object*, Named_object*> val(fn, NULL);
6590 std::pair<Method_value_thunks::iterator, bool> ins =
6591 Bound_method_expression::method_value_thunks.insert(val);
6592 if (!ins.second)
6593 {
6594 // We have seen this method before.
6595 go_assert(ins.first->second != NULL);
6596 return ins.first->second;
6597 }
6598
6599 Location loc = fn->location();
6600
6601 Function_type* orig_fntype;
6602 if (fn->is_function())
6603 orig_fntype = fn->func_value()->type();
6604 else if (fn->is_function_declaration())
6605 orig_fntype = fn->func_declaration_value()->type();
6606 else
6607 orig_fntype = NULL;
6608
6609 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6610 {
0afbb937 6611 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6612 return ins.first->second;
e440a328 6613 }
0afbb937 6614
6615 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6616 // The type here is wrong--it should be the C function type. But it
6617 // doesn't really matter.
0afbb937 6618 Type* vt = Type::make_pointer_type(Type::make_void_type());
6619 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6620 sfl->push_back(Struct_field(Typed_identifier("val.1",
6621 orig_fntype->receiver()->type(),
6622 loc)));
6623 Type* closure_type = Type::make_struct_type(sfl, loc);
6624 closure_type = Type::make_pointer_type(closure_type);
6625
f8bdf81a 6626 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6627
6628 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6629 false, loc);
6630
f8bdf81a 6631 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6632 cvar->set_is_used();
6633 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6634 new_no->func_value()->set_closure_var(cp);
0afbb937 6635
f8bdf81a 6636 gogo->start_block(loc);
0afbb937 6637
6638 // Field 0 of the closure is the function code pointer, field 1 is
6639 // the value on which to invoke the method.
6640 Expression* arg = Expression::make_var_reference(cp, loc);
6641 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6642 arg = Expression::make_field_reference(arg, 1, loc);
6643
6644 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6645
6646 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6647 Expression_list* args;
6648 if (orig_params == NULL || orig_params->empty())
6649 args = NULL;
6650 else
6651 {
6652 const Typed_identifier_list* new_params = new_fntype->parameters();
6653 args = new Expression_list();
6654 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6655 p != new_params->end();
0afbb937 6656 ++p)
6657 {
6658 Named_object* p_no = gogo->lookup(p->name(), NULL);
6659 go_assert(p_no != NULL
6660 && p_no->is_variable()
6661 && p_no->var_value()->is_parameter());
6662 args->push_back(Expression::make_var_reference(p_no, loc));
6663 }
6664 }
6665
6666 Call_expression* call = Expression::make_call(bme, args,
6667 orig_fntype->is_varargs(),
6668 loc);
6669 call->set_varargs_are_lowered();
6670
6671 Statement* s = Statement::make_return_from_call(call, loc);
6672 gogo->add_statement(s);
6673 Block* b = gogo->finish_block(loc);
6674 gogo->add_block(b, loc);
6675 gogo->lower_block(new_no, b);
a32698ee 6676 gogo->flatten_block(new_no, b);
0afbb937 6677 gogo->finish_function(loc);
6678
6679 ins.first->second = new_no;
6680 return new_no;
6681}
6682
6683// Return an expression to check *REF for nil while dereferencing
6684// according to FIELD_INDEXES. Update *REF to build up the field
6685// reference. This is a static function so that we don't have to
6686// worry about declaring Field_indexes in expressions.h.
6687
6688static Expression*
6689bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6690 Expression** ref)
6691{
6692 if (field_indexes == NULL)
6693 return Expression::make_boolean(false, loc);
6694 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6695 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6696 go_assert(stype != NULL
6697 && field_indexes->field_index < stype->field_count());
6698 if ((*ref)->type()->struct_type() == NULL)
6699 {
6700 go_assert((*ref)->type()->points_to() != NULL);
6701 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6702 Expression::make_nil(loc),
6703 loc);
6704 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6705 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6706 go_assert((*ref)->type()->struct_type() == stype);
6707 }
6708 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6709 loc);
6710 return cond;
e440a328 6711}
6712
0afbb937 6713// Get the tree for a method value.
e440a328 6714
6715tree
0afbb937 6716Bound_method_expression::do_get_tree(Translate_context* context)
e440a328 6717{
0afbb937 6718 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6719 this->method_,
6720 this->function_);
6721 if (thunk->is_erroneous())
6722 {
6723 go_assert(saw_errors());
6724 return error_mark_node;
6725 }
6726
6727 // FIXME: We should lower this earlier, but we can't lower it in the
6728 // lowering pass because at that point we don't know whether we need
6729 // to create the thunk or not. If the expression is called, we
6730 // don't need the thunk.
6731
6732 Location loc = this->location();
6733
6734 // If the method expects a value, and we have a pointer, we need to
6735 // dereference the pointer.
6736
6737 Named_object* fn = this->method_->named_object();
6738 Function_type* fntype;
6739 if (fn->is_function())
6740 fntype = fn->func_value()->type();
6741 else if (fn->is_function_declaration())
6742 fntype = fn->func_declaration_value()->type();
6743 else
6744 go_unreachable();
6745
6746 Expression* val = this->expr_;
6747 if (fntype->receiver()->type()->points_to() == NULL
6748 && val->type()->points_to() != NULL)
6749 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6750
6751 // Note that we are ignoring this->expr_type_ here. The thunk will
6752 // expect a closure whose second field has type this->expr_type_ (if
6753 // that is not NULL). We are going to pass it a closure whose
6754 // second field has type this->expr_->type(). Since
6755 // this->expr_type_ is only not-NULL for pointer types, we can get
6756 // away with this.
6757
6758 Struct_field_list* fields = new Struct_field_list();
6759 fields->push_back(Struct_field(Typed_identifier("fn.0",
6760 thunk->func_value()->type(),
6761 loc)));
6762 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6763 Struct_type* st = Type::make_struct_type(fields, loc);
6764
6765 Expression_list* vals = new Expression_list();
6766 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6767 vals->push_back(val);
6768
6769 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 6770 ret = Expression::make_heap_expression(ret, loc);
0afbb937 6771
0afbb937 6772 // See whether the expression or any embedded pointers are nil.
6773
df7ef1fd 6774 Expression* nil_check = NULL;
0afbb937 6775 Expression* expr = this->expr_;
6776 if (this->method_->field_indexes() != NULL)
6777 {
6778 // Note that we are evaluating this->expr_ twice, but that is OK
6779 // because in the lowering pass we forced it into a temporary
6780 // variable.
6781 Expression* ref = expr;
6782 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6783 expr = ref;
6784 }
6785
6786 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6787 {
6788 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6789 Expression::make_nil(loc),
6790 loc);
6791 if (nil_check == NULL)
6792 nil_check = n;
6793 else
6794 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6795 }
6796
df7ef1fd 6797 Bexpression* bme = tree_to_expr(ret->get_tree(context));
0afbb937 6798 if (nil_check != NULL)
6799 {
df7ef1fd 6800 Gogo* gogo = context->gogo();
6801 Expression* crash =
6802 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
6803 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
6804 Btype* btype = ret->type()->get_backend(gogo);
6805 Bexpression* bcheck = tree_to_expr(nil_check->get_tree(context));
6806 bme = gogo->backend()->conditional_expression(btype, bcheck, bcrash,
6807 bme, loc);
6808 }
6809 return expr_to_tree(bme);
e440a328 6810}
6811
d751bb78 6812// Dump ast representation of a bound method expression.
6813
6814void
6815Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6816 const
6817{
6818 if (this->expr_type_ != NULL)
6819 ast_dump_context->ostream() << "(";
6820 ast_dump_context->dump_expression(this->expr_);
6821 if (this->expr_type_ != NULL)
6822 {
6823 ast_dump_context->ostream() << ":";
6824 ast_dump_context->dump_type(this->expr_type_);
6825 ast_dump_context->ostream() << ")";
6826 }
6827
0afbb937 6828 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6829}
6830
e440a328 6831// Make a method expression.
6832
6833Bound_method_expression*
0afbb937 6834Expression::make_bound_method(Expression* expr, const Method* method,
6835 Named_object* function, Location location)
e440a328 6836{
0afbb937 6837 return new Bound_method_expression(expr, method, function, location);
e440a328 6838}
6839
6840// Class Builtin_call_expression. This is used for a call to a
6841// builtin function.
6842
6843class Builtin_call_expression : public Call_expression
6844{
6845 public:
6846 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6847 bool is_varargs, Location location);
e440a328 6848
6849 protected:
6850 // This overrides Call_expression::do_lower.
6851 Expression*
ceeb4318 6852 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6853
35a54f17 6854 Expression*
6855 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6856
e440a328 6857 bool
6858 do_is_constant() const;
6859
6860 bool
0c77715b 6861 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6862
4f2138d7 6863 bool
a7549a6a 6864 do_discarding_value();
6865
e440a328 6866 Type*
6867 do_type();
6868
6869 void
6870 do_determine_type(const Type_context*);
6871
6872 void
6873 do_check_types(Gogo*);
6874
6875 Expression*
6876 do_copy()
6877 {
6878 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6879 this->args()->copy(),
6880 this->is_varargs(),
6881 this->location());
6882 }
6883
6884 tree
6885 do_get_tree(Translate_context*);
6886
6887 void
6888 do_export(Export*) const;
6889
6890 virtual bool
6891 do_is_recover_call() const;
6892
6893 virtual void
6894 do_set_recover_arg(Expression*);
6895
6896 private:
6897 // The builtin functions.
6898 enum Builtin_function_code
6899 {
6900 BUILTIN_INVALID,
6901
6902 // Predeclared builtin functions.
6903 BUILTIN_APPEND,
6904 BUILTIN_CAP,
6905 BUILTIN_CLOSE,
48080209 6906 BUILTIN_COMPLEX,
e440a328 6907 BUILTIN_COPY,
1cce762f 6908 BUILTIN_DELETE,
e440a328 6909 BUILTIN_IMAG,
6910 BUILTIN_LEN,
6911 BUILTIN_MAKE,
6912 BUILTIN_NEW,
6913 BUILTIN_PANIC,
6914 BUILTIN_PRINT,
6915 BUILTIN_PRINTLN,
6916 BUILTIN_REAL,
6917 BUILTIN_RECOVER,
6918
6919 // Builtin functions from the unsafe package.
6920 BUILTIN_ALIGNOF,
6921 BUILTIN_OFFSETOF,
6922 BUILTIN_SIZEOF
6923 };
6924
6925 Expression*
6926 one_arg() const;
6927
6928 bool
6929 check_one_arg();
6930
6931 static Type*
6932 real_imag_type(Type*);
6933
6934 static Type*
48080209 6935 complex_type(Type*);
e440a328 6936
a9182619 6937 Expression*
6938 lower_make();
6939
6940 bool
1ad00fd4 6941 check_int_value(Expression*, bool is_length);
a9182619 6942
e440a328 6943 // A pointer back to the general IR structure. This avoids a global
6944 // variable, or passing it around everywhere.
6945 Gogo* gogo_;
6946 // The builtin function being called.
6947 Builtin_function_code code_;
0f914071 6948 // Used to stop endless loops when the length of an array uses len
6949 // or cap of the array itself.
6950 mutable bool seen_;
e440a328 6951};
6952
6953Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6954 Expression* fn,
6955 Expression_list* args,
6956 bool is_varargs,
b13c66cd 6957 Location location)
e440a328 6958 : Call_expression(fn, args, is_varargs, location),
0f914071 6959 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
e440a328 6960{
6961 Func_expression* fnexp = this->fn()->func_expression();
c484d925 6962 go_assert(fnexp != NULL);
e440a328 6963 const std::string& name(fnexp->named_object()->name());
6964 if (name == "append")
6965 this->code_ = BUILTIN_APPEND;
6966 else if (name == "cap")
6967 this->code_ = BUILTIN_CAP;
6968 else if (name == "close")
6969 this->code_ = BUILTIN_CLOSE;
48080209 6970 else if (name == "complex")
6971 this->code_ = BUILTIN_COMPLEX;
e440a328 6972 else if (name == "copy")
6973 this->code_ = BUILTIN_COPY;
1cce762f 6974 else if (name == "delete")
6975 this->code_ = BUILTIN_DELETE;
e440a328 6976 else if (name == "imag")
6977 this->code_ = BUILTIN_IMAG;
6978 else if (name == "len")
6979 this->code_ = BUILTIN_LEN;
6980 else if (name == "make")
6981 this->code_ = BUILTIN_MAKE;
6982 else if (name == "new")
6983 this->code_ = BUILTIN_NEW;
6984 else if (name == "panic")
6985 this->code_ = BUILTIN_PANIC;
6986 else if (name == "print")
6987 this->code_ = BUILTIN_PRINT;
6988 else if (name == "println")
6989 this->code_ = BUILTIN_PRINTLN;
6990 else if (name == "real")
6991 this->code_ = BUILTIN_REAL;
6992 else if (name == "recover")
6993 this->code_ = BUILTIN_RECOVER;
6994 else if (name == "Alignof")
6995 this->code_ = BUILTIN_ALIGNOF;
6996 else if (name == "Offsetof")
6997 this->code_ = BUILTIN_OFFSETOF;
6998 else if (name == "Sizeof")
6999 this->code_ = BUILTIN_SIZEOF;
7000 else
c3e6f413 7001 go_unreachable();
e440a328 7002}
7003
7004// Return whether this is a call to recover. This is a virtual
7005// function called from the parent class.
7006
7007bool
7008Builtin_call_expression::do_is_recover_call() const
7009{
7010 if (this->classification() == EXPRESSION_ERROR)
7011 return false;
7012 return this->code_ == BUILTIN_RECOVER;
7013}
7014
7015// Set the argument for a call to recover.
7016
7017void
7018Builtin_call_expression::do_set_recover_arg(Expression* arg)
7019{
7020 const Expression_list* args = this->args();
c484d925 7021 go_assert(args == NULL || args->empty());
e440a328 7022 Expression_list* new_args = new Expression_list();
7023 new_args->push_back(arg);
7024 this->set_args(new_args);
7025}
7026
e440a328 7027// Lower a builtin call expression. This turns new and make into
7028// specific expressions. We also convert to a constant if we can.
7029
7030Expression*
ceeb4318 7031Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7032 Statement_inserter* inserter, int)
e440a328 7033{
a9182619 7034 if (this->classification() == EXPRESSION_ERROR)
7035 return this;
7036
b13c66cd 7037 Location loc = this->location();
1cce762f 7038
a8725655 7039 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7040 {
7041 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7042 return Expression::make_error(loc);
a8725655 7043 }
7044
393ba00b 7045 if (this->code_ == BUILTIN_OFFSETOF)
7046 {
7047 Expression* arg = this->one_arg();
12e69faa 7048
7049 if (arg->bound_method_expression() != NULL
7050 || arg->interface_field_reference_expression() != NULL)
7051 {
7052 this->report_error(_("invalid use of method value as argument "
7053 "of Offsetof"));
7054 return this;
7055 }
7056
393ba00b 7057 Field_reference_expression* farg = arg->field_reference_expression();
7058 while (farg != NULL)
7059 {
7060 if (!farg->implicit())
7061 break;
7062 // When the selector refers to an embedded field,
7063 // it must not be reached through pointer indirections.
7064 if (farg->expr()->deref() != farg->expr())
7065 {
12e69faa 7066 this->report_error(_("argument of Offsetof implies "
7067 "indirection of an embedded field"));
393ba00b 7068 return this;
7069 }
7070 // Go up until we reach the original base.
7071 farg = farg->expr()->field_reference_expression();
7072 }
7073 }
7074
1cce762f 7075 if (this->is_constant())
e440a328 7076 {
0c77715b 7077 Numeric_constant nc;
7078 if (this->numeric_constant_value(&nc))
7079 return nc.expression(loc);
e440a328 7080 }
1cce762f 7081
7082 switch (this->code_)
e440a328 7083 {
1cce762f 7084 default:
7085 break;
7086
7087 case BUILTIN_NEW:
7088 {
7089 const Expression_list* args = this->args();
7090 if (args == NULL || args->size() < 1)
7091 this->report_error(_("not enough arguments"));
7092 else if (args->size() > 1)
7093 this->report_error(_("too many arguments"));
7094 else
7095 {
7096 Expression* arg = args->front();
7097 if (!arg->is_type_expression())
7098 {
7099 error_at(arg->location(), "expected type");
7100 this->set_is_error();
7101 }
7102 else
7103 return Expression::make_allocation(arg->type(), loc);
7104 }
7105 }
7106 break;
7107
7108 case BUILTIN_MAKE:
7109 return this->lower_make();
7110
7111 case BUILTIN_RECOVER:
e440a328 7112 if (function != NULL)
7113 function->func_value()->set_calls_recover();
7114 else
7115 {
7116 // Calling recover outside of a function always returns the
7117 // nil empty interface.
823c7e3d 7118 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7119 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7120 }
1cce762f 7121 break;
7122
7123 case BUILTIN_APPEND:
7124 {
7125 // Lower the varargs.
7126 const Expression_list* args = this->args();
7127 if (args == NULL || args->empty())
e440a328 7128 return this;
1cce762f 7129 Type* slice_type = args->front()->type();
7130 if (!slice_type->is_slice_type())
7131 {
3ff4863b 7132 if (slice_type->is_nil_type())
7133 error_at(args->front()->location(), "use of untyped nil");
7134 else
7135 error_at(args->front()->location(),
7136 "argument 1 must be a slice");
1cce762f 7137 this->set_is_error();
7138 return this;
7139 }
19fd40c3 7140 Type* element_type = slice_type->array_type()->element_type();
7141 this->lower_varargs(gogo, function, inserter,
7142 Type::make_array_type(element_type, NULL),
7143 2);
1cce762f 7144 }
7145 break;
7146
7147 case BUILTIN_DELETE:
7148 {
7149 // Lower to a runtime function call.
7150 const Expression_list* args = this->args();
7151 if (args == NULL || args->size() < 2)
7152 this->report_error(_("not enough arguments"));
7153 else if (args->size() > 2)
7154 this->report_error(_("too many arguments"));
7155 else if (args->front()->type()->map_type() == NULL)
7156 this->report_error(_("argument 1 must be a map"));
7157 else
7158 {
7159 // Since this function returns no value it must appear in
7160 // a statement by itself, so we don't have to worry about
7161 // order of evaluation of values around it. Evaluate the
7162 // map first to get order of evaluation right.
7163 Map_type* mt = args->front()->type()->map_type();
7164 Temporary_statement* map_temp =
7165 Statement::make_temporary(mt, args->front(), loc);
7166 inserter->insert(map_temp);
7167
7168 Temporary_statement* key_temp =
7169 Statement::make_temporary(mt->key_type(), args->back(), loc);
7170 inserter->insert(key_temp);
7171
7172 Expression* e1 = Expression::make_temporary_reference(map_temp,
7173 loc);
7174 Expression* e2 = Expression::make_temporary_reference(key_temp,
7175 loc);
7176 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7177 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7178 2, e1, e2);
7179 }
7180 }
7181 break;
e440a328 7182 }
7183
7184 return this;
7185}
7186
35a54f17 7187// Flatten a builtin call expression. This turns the arguments of copy and
7188// append into temporary expressions.
7189
7190Expression*
7191Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7192 Statement_inserter* inserter)
7193{
7194 if (this->code_ == BUILTIN_APPEND
7195 || this->code_ == BUILTIN_COPY)
7196 {
7197 Location loc = this->location();
7198 Type* at = this->args()->front()->type();
7199 for (Expression_list::iterator pa = this->args()->begin();
7200 pa != this->args()->end();
7201 ++pa)
7202 {
7203 if ((*pa)->is_nil_expression())
7204 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7205 if (!(*pa)->is_variable())
7206 {
7207 Temporary_statement* temp =
7208 Statement::make_temporary(NULL, *pa, loc);
7209 inserter->insert(temp);
7210 *pa = Expression::make_temporary_reference(temp, loc);
7211 }
7212 }
7213 }
7214 return this;
7215}
7216
a9182619 7217// Lower a make expression.
7218
7219Expression*
7220Builtin_call_expression::lower_make()
7221{
b13c66cd 7222 Location loc = this->location();
a9182619 7223
7224 const Expression_list* args = this->args();
7225 if (args == NULL || args->size() < 1)
7226 {
7227 this->report_error(_("not enough arguments"));
7228 return Expression::make_error(this->location());
7229 }
7230
7231 Expression_list::const_iterator parg = args->begin();
7232
7233 Expression* first_arg = *parg;
7234 if (!first_arg->is_type_expression())
7235 {
7236 error_at(first_arg->location(), "expected type");
7237 this->set_is_error();
7238 return Expression::make_error(this->location());
7239 }
7240 Type* type = first_arg->type();
7241
7242 bool is_slice = false;
7243 bool is_map = false;
7244 bool is_chan = false;
411eb89e 7245 if (type->is_slice_type())
a9182619 7246 is_slice = true;
7247 else if (type->map_type() != NULL)
7248 is_map = true;
7249 else if (type->channel_type() != NULL)
7250 is_chan = true;
7251 else
7252 {
7253 this->report_error(_("invalid type for make function"));
7254 return Expression::make_error(this->location());
7255 }
7256
ac84c822 7257 bool have_big_args = false;
7258 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7259 int uintptr_bits = uintptr_type->integer_type()->bits();
7260
f6bc81e6 7261 Type_context int_context(Type::lookup_integer_type("int"), false);
7262
a9182619 7263 ++parg;
7264 Expression* len_arg;
7265 if (parg == args->end())
7266 {
7267 if (is_slice)
7268 {
7269 this->report_error(_("length required when allocating a slice"));
7270 return Expression::make_error(this->location());
7271 }
7272
7273 mpz_t zval;
7274 mpz_init_set_ui(zval, 0);
7275 len_arg = Expression::make_integer(&zval, NULL, loc);
7276 mpz_clear(zval);
7277 }
7278 else
7279 {
7280 len_arg = *parg;
f6bc81e6 7281 len_arg->determine_type(&int_context);
1ad00fd4 7282 if (!this->check_int_value(len_arg, true))
7283 return Expression::make_error(this->location());
ac84c822 7284 if (len_arg->type()->integer_type() != NULL
7285 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7286 have_big_args = true;
a9182619 7287 ++parg;
7288 }
7289
7290 Expression* cap_arg = NULL;
7291 if (is_slice && parg != args->end())
7292 {
7293 cap_arg = *parg;
f6bc81e6 7294 cap_arg->determine_type(&int_context);
1ad00fd4 7295 if (!this->check_int_value(cap_arg, false))
7296 return Expression::make_error(this->location());
7297
7298 Numeric_constant nclen;
7299 Numeric_constant nccap;
7300 unsigned long vlen;
7301 unsigned long vcap;
7302 if (len_arg->numeric_constant_value(&nclen)
7303 && cap_arg->numeric_constant_value(&nccap)
7304 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7305 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7306 && vlen > vcap)
a9182619 7307 {
1ad00fd4 7308 this->report_error(_("len larger than cap"));
a9182619 7309 return Expression::make_error(this->location());
7310 }
1ad00fd4 7311
ac84c822 7312 if (cap_arg->type()->integer_type() != NULL
7313 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7314 have_big_args = true;
a9182619 7315 ++parg;
7316 }
7317
7318 if (parg != args->end())
7319 {
7320 this->report_error(_("too many arguments to make"));
7321 return Expression::make_error(this->location());
7322 }
7323
b13c66cd 7324 Location type_loc = first_arg->location();
a9182619 7325 Expression* type_arg;
7326 if (is_slice || is_chan)
7327 type_arg = Expression::make_type_descriptor(type, type_loc);
7328 else if (is_map)
7329 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7330 else
7331 go_unreachable();
7332
7333 Expression* call;
7334 if (is_slice)
7335 {
7336 if (cap_arg == NULL)
ac84c822 7337 call = Runtime::make_call((have_big_args
7338 ? Runtime::MAKESLICE1BIG
7339 : Runtime::MAKESLICE1),
7340 loc, 2, type_arg, len_arg);
a9182619 7341 else
ac84c822 7342 call = Runtime::make_call((have_big_args
7343 ? Runtime::MAKESLICE2BIG
7344 : Runtime::MAKESLICE2),
7345 loc, 3, type_arg, len_arg, cap_arg);
a9182619 7346 }
7347 else if (is_map)
ac84c822 7348 call = Runtime::make_call((have_big_args
7349 ? Runtime::MAKEMAPBIG
7350 : Runtime::MAKEMAP),
7351 loc, 2, type_arg, len_arg);
a9182619 7352 else if (is_chan)
ac84c822 7353 call = Runtime::make_call((have_big_args
7354 ? Runtime::MAKECHANBIG
7355 : Runtime::MAKECHAN),
7356 loc, 2, type_arg, len_arg);
a9182619 7357 else
7358 go_unreachable();
7359
7360 return Expression::make_unsafe_cast(type, call, loc);
7361}
7362
7363// Return whether an expression has an integer value. Report an error
7364// if not. This is used when handling calls to the predeclared make
7365// function.
7366
7367bool
1ad00fd4 7368Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7369{
0c77715b 7370 Numeric_constant nc;
1ad00fd4 7371 if (e->numeric_constant_value(&nc))
a9182619 7372 {
1ad00fd4 7373 unsigned long v;
7374 switch (nc.to_unsigned_long(&v))
7375 {
7376 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7377 break;
1ad00fd4 7378 case Numeric_constant::NC_UL_NOTINT:
7379 error_at(e->location(), "non-integer %s argument to make",
7380 is_length ? "len" : "cap");
7381 return false;
7382 case Numeric_constant::NC_UL_NEGATIVE:
7383 error_at(e->location(), "negative %s argument to make",
7384 is_length ? "len" : "cap");
7385 return false;
7386 case Numeric_constant::NC_UL_BIG:
7387 // We don't want to give a compile-time error for a 64-bit
7388 // value on a 32-bit target.
1b10c5e7 7389 break;
1ad00fd4 7390 }
1b10c5e7 7391
7392 mpz_t val;
7393 if (!nc.to_int(&val))
7394 go_unreachable();
7395 int bits = mpz_sizeinbase(val, 2);
7396 mpz_clear(val);
7397 Type* int_type = Type::lookup_integer_type("int");
7398 if (bits >= int_type->integer_type()->bits())
7399 {
7400 error_at(e->location(), "%s argument too large for make",
7401 is_length ? "len" : "cap");
7402 return false;
7403 }
7404
7405 return true;
a9182619 7406 }
7407
1ad00fd4 7408 if (e->type()->integer_type() != NULL)
7409 return true;
7410
7411 error_at(e->location(), "non-integer %s argument to make",
7412 is_length ? "len" : "cap");
a9182619 7413 return false;
7414}
7415
e440a328 7416// Return the type of the real or imag functions, given the type of
7417// the argument. We need to map complex to float, complex64 to
7418// float32, and complex128 to float64, so it has to be done by name.
7419// This returns NULL if it can't figure out the type.
7420
7421Type*
7422Builtin_call_expression::real_imag_type(Type* arg_type)
7423{
7424 if (arg_type == NULL || arg_type->is_abstract())
7425 return NULL;
7426 Named_type* nt = arg_type->named_type();
7427 if (nt == NULL)
7428 return NULL;
7429 while (nt->real_type()->named_type() != NULL)
7430 nt = nt->real_type()->named_type();
48080209 7431 if (nt->name() == "complex64")
e440a328 7432 return Type::lookup_float_type("float32");
7433 else if (nt->name() == "complex128")
7434 return Type::lookup_float_type("float64");
7435 else
7436 return NULL;
7437}
7438
48080209 7439// Return the type of the complex function, given the type of one of the
e440a328 7440// argments. Like real_imag_type, we have to map by name.
7441
7442Type*
48080209 7443Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7444{
7445 if (arg_type == NULL || arg_type->is_abstract())
7446 return NULL;
7447 Named_type* nt = arg_type->named_type();
7448 if (nt == NULL)
7449 return NULL;
7450 while (nt->real_type()->named_type() != NULL)
7451 nt = nt->real_type()->named_type();
48080209 7452 if (nt->name() == "float32")
e440a328 7453 return Type::lookup_complex_type("complex64");
7454 else if (nt->name() == "float64")
7455 return Type::lookup_complex_type("complex128");
7456 else
7457 return NULL;
7458}
7459
7460// Return a single argument, or NULL if there isn't one.
7461
7462Expression*
7463Builtin_call_expression::one_arg() const
7464{
7465 const Expression_list* args = this->args();
aa615cb3 7466 if (args == NULL || args->size() != 1)
e440a328 7467 return NULL;
7468 return args->front();
7469}
7470
83921647 7471// A traversal class which looks for a call or receive expression.
7472
7473class Find_call_expression : public Traverse
7474{
7475 public:
7476 Find_call_expression()
7477 : Traverse(traverse_expressions),
7478 found_(false)
7479 { }
7480
7481 int
7482 expression(Expression**);
7483
7484 bool
7485 found()
7486 { return this->found_; }
7487
7488 private:
7489 bool found_;
7490};
7491
7492int
7493Find_call_expression::expression(Expression** pexpr)
7494{
7495 if ((*pexpr)->call_expression() != NULL
7496 || (*pexpr)->receive_expression() != NULL)
7497 {
7498 this->found_ = true;
7499 return TRAVERSE_EXIT;
7500 }
7501 return TRAVERSE_CONTINUE;
7502}
7503
7504// Return whether this is constant: len of a string constant, or len
7505// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7506// unsafe.Alignof.
e440a328 7507
7508bool
7509Builtin_call_expression::do_is_constant() const
7510{
12e69faa 7511 if (this->is_error_expression())
7512 return true;
e440a328 7513 switch (this->code_)
7514 {
7515 case BUILTIN_LEN:
7516 case BUILTIN_CAP:
7517 {
0f914071 7518 if (this->seen_)
7519 return false;
7520
e440a328 7521 Expression* arg = this->one_arg();
7522 if (arg == NULL)
7523 return false;
7524 Type* arg_type = arg->type();
7525
7526 if (arg_type->points_to() != NULL
7527 && arg_type->points_to()->array_type() != NULL
411eb89e 7528 && !arg_type->points_to()->is_slice_type())
e440a328 7529 arg_type = arg_type->points_to();
7530
83921647 7531 // The len and cap functions are only constant if there are no
7532 // function calls or channel operations in the arguments.
7533 // Otherwise we have to make the call.
7534 if (!arg->is_constant())
7535 {
7536 Find_call_expression find_call;
7537 Expression::traverse(&arg, &find_call);
7538 if (find_call.found())
7539 return false;
7540 }
7541
e440a328 7542 if (arg_type->array_type() != NULL
7543 && arg_type->array_type()->length() != NULL)
0f914071 7544 return true;
e440a328 7545
7546 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7547 {
7548 this->seen_ = true;
7549 bool ret = arg->is_constant();
7550 this->seen_ = false;
7551 return ret;
7552 }
e440a328 7553 }
7554 break;
7555
7556 case BUILTIN_SIZEOF:
7557 case BUILTIN_ALIGNOF:
7558 return this->one_arg() != NULL;
7559
7560 case BUILTIN_OFFSETOF:
7561 {
7562 Expression* arg = this->one_arg();
7563 if (arg == NULL)
7564 return false;
7565 return arg->field_reference_expression() != NULL;
7566 }
7567
48080209 7568 case BUILTIN_COMPLEX:
e440a328 7569 {
7570 const Expression_list* args = this->args();
7571 if (args != NULL && args->size() == 2)
7572 return args->front()->is_constant() && args->back()->is_constant();
7573 }
7574 break;
7575
7576 case BUILTIN_REAL:
7577 case BUILTIN_IMAG:
7578 {
7579 Expression* arg = this->one_arg();
7580 return arg != NULL && arg->is_constant();
7581 }
7582
7583 default:
7584 break;
7585 }
7586
7587 return false;
7588}
7589
0c77715b 7590// Return a numeric constant if possible.
e440a328 7591
7592bool
0c77715b 7593Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7594{
7595 if (this->code_ == BUILTIN_LEN
7596 || this->code_ == BUILTIN_CAP)
7597 {
7598 Expression* arg = this->one_arg();
7599 if (arg == NULL)
7600 return false;
7601 Type* arg_type = arg->type();
7602
7603 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7604 {
7605 std::string sval;
7606 if (arg->string_constant_value(&sval))
7607 {
0c77715b 7608 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7609 sval.length());
e440a328 7610 return true;
7611 }
7612 }
7613
7614 if (arg_type->points_to() != NULL
7615 && arg_type->points_to()->array_type() != NULL
411eb89e 7616 && !arg_type->points_to()->is_slice_type())
e440a328 7617 arg_type = arg_type->points_to();
7618
7619 if (arg_type->array_type() != NULL
7620 && arg_type->array_type()->length() != NULL)
7621 {
0f914071 7622 if (this->seen_)
7623 return false;
e440a328 7624 Expression* e = arg_type->array_type()->length();
0f914071 7625 this->seen_ = true;
0c77715b 7626 bool r = e->numeric_constant_value(nc);
0f914071 7627 this->seen_ = false;
7628 if (r)
e440a328 7629 {
0c77715b 7630 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7631 this->location()))
7632 r = false;
e440a328 7633 }
0c77715b 7634 return r;
e440a328 7635 }
7636 }
7637 else if (this->code_ == BUILTIN_SIZEOF
7638 || this->code_ == BUILTIN_ALIGNOF)
7639 {
7640 Expression* arg = this->one_arg();
7641 if (arg == NULL)
7642 return false;
7643 Type* arg_type = arg->type();
5c13bd80 7644 if (arg_type->is_error())
e440a328 7645 return false;
7646 if (arg_type->is_abstract())
7647 return false;
2c809f8f 7648 if (this->seen_)
7649 return false;
927a01eb 7650
7651 unsigned int ret;
e440a328 7652 if (this->code_ == BUILTIN_SIZEOF)
7653 {
2c809f8f 7654 this->seen_ = true;
7655 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7656 this->seen_ = false;
7657 if (!ok)
e440a328 7658 return false;
7659 }
7660 else if (this->code_ == BUILTIN_ALIGNOF)
7661 {
2c809f8f 7662 bool ok;
7663 this->seen_ = true;
637bd3af 7664 if (arg->field_reference_expression() == NULL)
2c809f8f 7665 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7666 else
e440a328 7667 {
7668 // Calling unsafe.Alignof(s.f) returns the alignment of
7669 // the type of f when it is used as a field in a struct.
2c809f8f 7670 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7671 }
2c809f8f 7672 this->seen_ = false;
7673 if (!ok)
7674 return false;
e440a328 7675 }
7676 else
c3e6f413 7677 go_unreachable();
927a01eb 7678
7ba86326 7679 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7680 static_cast<unsigned long>(ret));
e440a328 7681 return true;
7682 }
7683 else if (this->code_ == BUILTIN_OFFSETOF)
7684 {
7685 Expression* arg = this->one_arg();
7686 if (arg == NULL)
7687 return false;
7688 Field_reference_expression* farg = arg->field_reference_expression();
7689 if (farg == NULL)
7690 return false;
2c809f8f 7691 if (this->seen_)
7692 return false;
7693
9a4bd570 7694 unsigned int total_offset = 0;
7695 while (true)
7696 {
7697 Expression* struct_expr = farg->expr();
7698 Type* st = struct_expr->type();
7699 if (st->struct_type() == NULL)
7700 return false;
7701 if (st->named_type() != NULL)
7702 st->named_type()->convert(this->gogo_);
7703 unsigned int offset;
2c809f8f 7704 this->seen_ = true;
7705 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7706 farg->field_index(),
7707 &offset);
7708 this->seen_ = false;
7709 if (!ok)
7710 return false;
9a4bd570 7711 total_offset += offset;
7712 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7713 {
7714 // Go up until we reach the original base.
7715 farg = struct_expr->field_reference_expression();
7716 continue;
7717 }
7718 break;
7719 }
7ba86326 7720 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
9a4bd570 7721 static_cast<unsigned long>(total_offset));
e440a328 7722 return true;
7723 }
0c77715b 7724 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7725 {
7726 Expression* arg = this->one_arg();
7727 if (arg == NULL)
7728 return false;
7729
0c77715b 7730 Numeric_constant argnc;
7731 if (!arg->numeric_constant_value(&argnc))
7732 return false;
7733
e440a328 7734 mpfr_t real;
7735 mpfr_t imag;
0c77715b 7736 if (!argnc.to_complex(&real, &imag))
7737 return false;
e440a328 7738
0c77715b 7739 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7740 if (this->code_ == BUILTIN_REAL)
7741 nc->set_float(type, real);
7742 else
7743 nc->set_float(type, imag);
7744 return true;
e440a328 7745 }
0c77715b 7746 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7747 {
7748 const Expression_list* args = this->args();
7749 if (args == NULL || args->size() != 2)
7750 return false;
7751
0c77715b 7752 Numeric_constant rnc;
7753 if (!args->front()->numeric_constant_value(&rnc))
7754 return false;
7755 Numeric_constant inc;
7756 if (!args->back()->numeric_constant_value(&inc))
7757 return false;
7758
7759 if (rnc.type() != NULL
7760 && !rnc.type()->is_abstract()
7761 && inc.type() != NULL
7762 && !inc.type()->is_abstract()
7763 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7764 return false;
7765
e440a328 7766 mpfr_t r;
0c77715b 7767 if (!rnc.to_float(&r))
7768 return false;
7769 mpfr_t i;
7770 if (!inc.to_float(&i))
e440a328 7771 {
7772 mpfr_clear(r);
7773 return false;
7774 }
7775
0c77715b 7776 Type* arg_type = rnc.type();
7777 if (arg_type == NULL || arg_type->is_abstract())
7778 arg_type = inc.type();
e440a328 7779
0c77715b 7780 Type* type = Builtin_call_expression::complex_type(arg_type);
7781 nc->set_complex(type, r, i);
e440a328 7782
7783 mpfr_clear(r);
7784 mpfr_clear(i);
7785
0c77715b 7786 return true;
e440a328 7787 }
7788
7789 return false;
7790}
7791
a7549a6a 7792// Give an error if we are discarding the value of an expression which
7793// should not normally be discarded. We don't give an error for
7794// discarding the value of an ordinary function call, but we do for
7795// builtin functions, purely for consistency with the gc compiler.
7796
4f2138d7 7797bool
a7549a6a 7798Builtin_call_expression::do_discarding_value()
7799{
7800 switch (this->code_)
7801 {
7802 case BUILTIN_INVALID:
7803 default:
7804 go_unreachable();
7805
7806 case BUILTIN_APPEND:
7807 case BUILTIN_CAP:
7808 case BUILTIN_COMPLEX:
7809 case BUILTIN_IMAG:
7810 case BUILTIN_LEN:
7811 case BUILTIN_MAKE:
7812 case BUILTIN_NEW:
7813 case BUILTIN_REAL:
7814 case BUILTIN_ALIGNOF:
7815 case BUILTIN_OFFSETOF:
7816 case BUILTIN_SIZEOF:
7817 this->unused_value_error();
4f2138d7 7818 return false;
a7549a6a 7819
7820 case BUILTIN_CLOSE:
7821 case BUILTIN_COPY:
1cce762f 7822 case BUILTIN_DELETE:
a7549a6a 7823 case BUILTIN_PANIC:
7824 case BUILTIN_PRINT:
7825 case BUILTIN_PRINTLN:
7826 case BUILTIN_RECOVER:
4f2138d7 7827 return true;
a7549a6a 7828 }
7829}
7830
e440a328 7831// Return the type.
7832
7833Type*
7834Builtin_call_expression::do_type()
7835{
7836 switch (this->code_)
7837 {
7838 case BUILTIN_INVALID:
7839 default:
c3e6f413 7840 go_unreachable();
e440a328 7841
7842 case BUILTIN_NEW:
7843 case BUILTIN_MAKE:
7844 {
7845 const Expression_list* args = this->args();
7846 if (args == NULL || args->empty())
7847 return Type::make_error_type();
7848 return Type::make_pointer_type(args->front()->type());
7849 }
7850
7851 case BUILTIN_CAP:
7852 case BUILTIN_COPY:
7853 case BUILTIN_LEN:
7ba86326 7854 return Type::lookup_integer_type("int");
7855
e440a328 7856 case BUILTIN_ALIGNOF:
7857 case BUILTIN_OFFSETOF:
7858 case BUILTIN_SIZEOF:
7ba86326 7859 return Type::lookup_integer_type("uintptr");
e440a328 7860
7861 case BUILTIN_CLOSE:
1cce762f 7862 case BUILTIN_DELETE:
e440a328 7863 case BUILTIN_PANIC:
7864 case BUILTIN_PRINT:
7865 case BUILTIN_PRINTLN:
7866 return Type::make_void_type();
7867
e440a328 7868 case BUILTIN_RECOVER:
823c7e3d 7869 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 7870
7871 case BUILTIN_APPEND:
7872 {
7873 const Expression_list* args = this->args();
7874 if (args == NULL || args->empty())
7875 return Type::make_error_type();
3ff4863b 7876 Type *ret = args->front()->type();
7877 if (!ret->is_slice_type())
7878 return Type::make_error_type();
7879 return ret;
e440a328 7880 }
7881
7882 case BUILTIN_REAL:
7883 case BUILTIN_IMAG:
7884 {
7885 Expression* arg = this->one_arg();
7886 if (arg == NULL)
7887 return Type::make_error_type();
7888 Type* t = arg->type();
7889 if (t->is_abstract())
7890 t = t->make_non_abstract_type();
7891 t = Builtin_call_expression::real_imag_type(t);
7892 if (t == NULL)
7893 t = Type::make_error_type();
7894 return t;
7895 }
7896
48080209 7897 case BUILTIN_COMPLEX:
e440a328 7898 {
7899 const Expression_list* args = this->args();
7900 if (args == NULL || args->size() != 2)
7901 return Type::make_error_type();
7902 Type* t = args->front()->type();
7903 if (t->is_abstract())
7904 {
7905 t = args->back()->type();
7906 if (t->is_abstract())
7907 t = t->make_non_abstract_type();
7908 }
48080209 7909 t = Builtin_call_expression::complex_type(t);
e440a328 7910 if (t == NULL)
7911 t = Type::make_error_type();
7912 return t;
7913 }
7914 }
7915}
7916
7917// Determine the type.
7918
7919void
7920Builtin_call_expression::do_determine_type(const Type_context* context)
7921{
fb94b0ca 7922 if (!this->determining_types())
7923 return;
7924
e440a328 7925 this->fn()->determine_type_no_context();
7926
7927 const Expression_list* args = this->args();
7928
7929 bool is_print;
7930 Type* arg_type = NULL;
7931 switch (this->code_)
7932 {
7933 case BUILTIN_PRINT:
7934 case BUILTIN_PRINTLN:
7935 // Do not force a large integer constant to "int".
7936 is_print = true;
7937 break;
7938
7939 case BUILTIN_REAL:
7940 case BUILTIN_IMAG:
48080209 7941 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 7942 if (arg_type == NULL)
7943 arg_type = Type::lookup_complex_type("complex128");
e440a328 7944 is_print = false;
7945 break;
7946
48080209 7947 case BUILTIN_COMPLEX:
e440a328 7948 {
48080209 7949 // For the complex function the type of one operand can
e440a328 7950 // determine the type of the other, as in a binary expression.
7951 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 7952 if (arg_type == NULL)
7953 arg_type = Type::lookup_float_type("float64");
e440a328 7954 if (args != NULL && args->size() == 2)
7955 {
7956 Type* t1 = args->front()->type();
c849bb59 7957 Type* t2 = args->back()->type();
e440a328 7958 if (!t1->is_abstract())
7959 arg_type = t1;
7960 else if (!t2->is_abstract())
7961 arg_type = t2;
7962 }
7963 is_print = false;
7964 }
7965 break;
7966
7967 default:
7968 is_print = false;
7969 break;
7970 }
7971
7972 if (args != NULL)
7973 {
7974 for (Expression_list::const_iterator pa = args->begin();
7975 pa != args->end();
7976 ++pa)
7977 {
7978 Type_context subcontext;
7979 subcontext.type = arg_type;
7980
7981 if (is_print)
7982 {
7983 // We want to print large constants, we so can't just
7984 // use the appropriate nonabstract type. Use uint64 for
7985 // an integer if we know it is nonnegative, otherwise
7986 // use int64 for a integer, otherwise use float64 for a
7987 // float or complex128 for a complex.
7988 Type* want_type = NULL;
7989 Type* atype = (*pa)->type();
7990 if (atype->is_abstract())
7991 {
7992 if (atype->integer_type() != NULL)
7993 {
0c77715b 7994 Numeric_constant nc;
7995 if (this->numeric_constant_value(&nc))
7996 {
7997 mpz_t val;
7998 if (nc.to_int(&val))
7999 {
8000 if (mpz_sgn(val) >= 0)
8001 want_type = Type::lookup_integer_type("uint64");
8002 mpz_clear(val);
8003 }
8004 }
8005 if (want_type == NULL)
e440a328 8006 want_type = Type::lookup_integer_type("int64");
e440a328 8007 }
8008 else if (atype->float_type() != NULL)
8009 want_type = Type::lookup_float_type("float64");
8010 else if (atype->complex_type() != NULL)
8011 want_type = Type::lookup_complex_type("complex128");
8012 else if (atype->is_abstract_string_type())
8013 want_type = Type::lookup_string_type();
8014 else if (atype->is_abstract_boolean_type())
8015 want_type = Type::lookup_bool_type();
8016 else
c3e6f413 8017 go_unreachable();
e440a328 8018 subcontext.type = want_type;
8019 }
8020 }
8021
8022 (*pa)->determine_type(&subcontext);
8023 }
8024 }
8025}
8026
8027// If there is exactly one argument, return true. Otherwise give an
8028// error message and return false.
8029
8030bool
8031Builtin_call_expression::check_one_arg()
8032{
8033 const Expression_list* args = this->args();
8034 if (args == NULL || args->size() < 1)
8035 {
8036 this->report_error(_("not enough arguments"));
8037 return false;
8038 }
8039 else if (args->size() > 1)
8040 {
8041 this->report_error(_("too many arguments"));
8042 return false;
8043 }
8044 if (args->front()->is_error_expression()
5c13bd80 8045 || args->front()->type()->is_error())
e440a328 8046 {
8047 this->set_is_error();
8048 return false;
8049 }
8050 return true;
8051}
8052
8053// Check argument types for a builtin function.
8054
8055void
8056Builtin_call_expression::do_check_types(Gogo*)
8057{
375646ea 8058 if (this->is_error_expression())
8059 return;
e440a328 8060 switch (this->code_)
8061 {
8062 case BUILTIN_INVALID:
8063 case BUILTIN_NEW:
8064 case BUILTIN_MAKE:
cd238b8d 8065 case BUILTIN_DELETE:
e440a328 8066 return;
8067
8068 case BUILTIN_LEN:
8069 case BUILTIN_CAP:
8070 {
8071 // The single argument may be either a string or an array or a
8072 // map or a channel, or a pointer to a closed array.
8073 if (this->check_one_arg())
8074 {
8075 Type* arg_type = this->one_arg()->type();
8076 if (arg_type->points_to() != NULL
8077 && arg_type->points_to()->array_type() != NULL
411eb89e 8078 && !arg_type->points_to()->is_slice_type())
e440a328 8079 arg_type = arg_type->points_to();
8080 if (this->code_ == BUILTIN_CAP)
8081 {
5c13bd80 8082 if (!arg_type->is_error()
e440a328 8083 && arg_type->array_type() == NULL
8084 && arg_type->channel_type() == NULL)
8085 this->report_error(_("argument must be array or slice "
8086 "or channel"));
8087 }
8088 else
8089 {
5c13bd80 8090 if (!arg_type->is_error()
e440a328 8091 && !arg_type->is_string_type()
8092 && arg_type->array_type() == NULL
8093 && arg_type->map_type() == NULL
8094 && arg_type->channel_type() == NULL)
8095 this->report_error(_("argument must be string or "
8096 "array or slice or map or channel"));
8097 }
8098 }
8099 }
8100 break;
8101
8102 case BUILTIN_PRINT:
8103 case BUILTIN_PRINTLN:
8104 {
8105 const Expression_list* args = this->args();
8106 if (args == NULL)
8107 {
8108 if (this->code_ == BUILTIN_PRINT)
8109 warning_at(this->location(), 0,
8110 "no arguments for builtin function %<%s%>",
8111 (this->code_ == BUILTIN_PRINT
8112 ? "print"
8113 : "println"));
8114 }
8115 else
8116 {
8117 for (Expression_list::const_iterator p = args->begin();
8118 p != args->end();
8119 ++p)
8120 {
8121 Type* type = (*p)->type();
5c13bd80 8122 if (type->is_error()
e440a328 8123 || type->is_string_type()
8124 || type->integer_type() != NULL
8125 || type->float_type() != NULL
8126 || type->complex_type() != NULL
8127 || type->is_boolean_type()
8128 || type->points_to() != NULL
8129 || type->interface_type() != NULL
8130 || type->channel_type() != NULL
8131 || type->map_type() != NULL
8132 || type->function_type() != NULL
411eb89e 8133 || type->is_slice_type())
e440a328 8134 ;
acf8e158 8135 else if ((*p)->is_type_expression())
8136 {
8137 // If this is a type expression it's going to give
8138 // an error anyhow, so we don't need one here.
8139 }
e440a328 8140 else
8141 this->report_error(_("unsupported argument type to "
8142 "builtin function"));
8143 }
8144 }
8145 }
8146 break;
8147
8148 case BUILTIN_CLOSE:
e440a328 8149 if (this->check_one_arg())
8150 {
8151 if (this->one_arg()->type()->channel_type() == NULL)
8152 this->report_error(_("argument must be channel"));
5202d986 8153 else if (!this->one_arg()->type()->channel_type()->may_send())
8154 this->report_error(_("cannot close receive-only channel"));
e440a328 8155 }
8156 break;
8157
8158 case BUILTIN_PANIC:
8159 case BUILTIN_SIZEOF:
8160 case BUILTIN_ALIGNOF:
8161 this->check_one_arg();
8162 break;
8163
8164 case BUILTIN_RECOVER:
8165 if (this->args() != NULL && !this->args()->empty())
8166 this->report_error(_("too many arguments"));
8167 break;
8168
8169 case BUILTIN_OFFSETOF:
8170 if (this->check_one_arg())
8171 {
8172 Expression* arg = this->one_arg();
8173 if (arg->field_reference_expression() == NULL)
8174 this->report_error(_("argument must be a field reference"));
8175 }
8176 break;
8177
8178 case BUILTIN_COPY:
8179 {
8180 const Expression_list* args = this->args();
8181 if (args == NULL || args->size() < 2)
8182 {
8183 this->report_error(_("not enough arguments"));
8184 break;
8185 }
8186 else if (args->size() > 2)
8187 {
8188 this->report_error(_("too many arguments"));
8189 break;
8190 }
8191 Type* arg1_type = args->front()->type();
8192 Type* arg2_type = args->back()->type();
5c13bd80 8193 if (arg1_type->is_error() || arg2_type->is_error())
e440a328 8194 break;
8195
8196 Type* e1;
411eb89e 8197 if (arg1_type->is_slice_type())
e440a328 8198 e1 = arg1_type->array_type()->element_type();
8199 else
8200 {
8201 this->report_error(_("left argument must be a slice"));
8202 break;
8203 }
8204
411eb89e 8205 if (arg2_type->is_slice_type())
60963afd 8206 {
8207 Type* e2 = arg2_type->array_type()->element_type();
8208 if (!Type::are_identical(e1, e2, true, NULL))
8209 this->report_error(_("element types must be the same"));
8210 }
e440a328 8211 else if (arg2_type->is_string_type())
e440a328 8212 {
60963afd 8213 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8214 this->report_error(_("first argument must be []byte"));
e440a328 8215 }
60963afd 8216 else
8217 this->report_error(_("second argument must be slice or string"));
e440a328 8218 }
8219 break;
8220
8221 case BUILTIN_APPEND:
8222 {
8223 const Expression_list* args = this->args();
b0d311a1 8224 if (args == NULL || args->size() < 2)
e440a328 8225 {
8226 this->report_error(_("not enough arguments"));
8227 break;
8228 }
0b7755ec 8229 if (args->size() > 2)
8230 {
8231 this->report_error(_("too many arguments"));
8232 break;
8233 }
cd238b8d 8234 if (args->front()->type()->is_error()
8235 || args->back()->type()->is_error())
8236 break;
8237
8238 Array_type* at = args->front()->type()->array_type();
8239 Type* e = at->element_type();
4fd4fcf4 8240
8241 // The language permits appending a string to a []byte, as a
8242 // special case.
8243 if (args->back()->type()->is_string_type())
8244 {
60963afd 8245 if (e->integer_type() != NULL && e->integer_type()->is_byte())
4fd4fcf4 8246 break;
8247 }
8248
19fd40c3 8249 // The language says that the second argument must be
8250 // assignable to a slice of the element type of the first
8251 // argument. We already know the first argument is a slice
8252 // type.
cd238b8d 8253 Type* arg2_type = Type::make_array_type(e, NULL);
e440a328 8254 std::string reason;
19fd40c3 8255 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
e440a328 8256 {
8257 if (reason.empty())
19fd40c3 8258 this->report_error(_("argument 2 has invalid type"));
e440a328 8259 else
8260 {
19fd40c3 8261 error_at(this->location(), "argument 2 has invalid type (%s)",
e440a328 8262 reason.c_str());
8263 this->set_is_error();
8264 }
8265 }
8266 break;
8267 }
8268
8269 case BUILTIN_REAL:
8270 case BUILTIN_IMAG:
8271 if (this->check_one_arg())
8272 {
8273 if (this->one_arg()->type()->complex_type() == NULL)
8274 this->report_error(_("argument must have complex type"));
8275 }
8276 break;
8277
48080209 8278 case BUILTIN_COMPLEX:
e440a328 8279 {
8280 const Expression_list* args = this->args();
8281 if (args == NULL || args->size() < 2)
8282 this->report_error(_("not enough arguments"));
8283 else if (args->size() > 2)
8284 this->report_error(_("too many arguments"));
8285 else if (args->front()->is_error_expression()
5c13bd80 8286 || args->front()->type()->is_error()
e440a328 8287 || args->back()->is_error_expression()
5c13bd80 8288 || args->back()->type()->is_error())
e440a328 8289 this->set_is_error();
8290 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8291 args->back()->type(), true, NULL))
48080209 8292 this->report_error(_("complex arguments must have identical types"));
e440a328 8293 else if (args->front()->type()->float_type() == NULL)
48080209 8294 this->report_error(_("complex arguments must have "
e440a328 8295 "floating-point type"));
8296 }
8297 break;
8298
8299 default:
c3e6f413 8300 go_unreachable();
e440a328 8301 }
8302}
8303
8304// Return the tree for a builtin function.
8305
8306tree
8307Builtin_call_expression::do_get_tree(Translate_context* context)
8308{
8309 Gogo* gogo = context->gogo();
b13c66cd 8310 Location location = this->location();
e440a328 8311 switch (this->code_)
8312 {
8313 case BUILTIN_INVALID:
8314 case BUILTIN_NEW:
8315 case BUILTIN_MAKE:
c3e6f413 8316 go_unreachable();
e440a328 8317
8318 case BUILTIN_LEN:
8319 case BUILTIN_CAP:
8320 {
8321 const Expression_list* args = this->args();
c484d925 8322 go_assert(args != NULL && args->size() == 1);
2c809f8f 8323 Expression* arg = args->front();
e440a328 8324 Type* arg_type = arg->type();
0f914071 8325
8326 if (this->seen_)
8327 {
c484d925 8328 go_assert(saw_errors());
0f914071 8329 return error_mark_node;
8330 }
8331 this->seen_ = true;
0f914071 8332 this->seen_ = false;
e440a328 8333 if (arg_type->points_to() != NULL)
8334 {
8335 arg_type = arg_type->points_to();
c484d925 8336 go_assert(arg_type->array_type() != NULL
411eb89e 8337 && !arg_type->is_slice_type());
2c809f8f 8338 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8339 }
8340
1b1f2abf 8341 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8342 Expression* val;
e440a328 8343 if (this->code_ == BUILTIN_LEN)
8344 {
8345 if (arg_type->is_string_type())
2c809f8f 8346 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8347 location);
e440a328 8348 else if (arg_type->array_type() != NULL)
0f914071 8349 {
8350 if (this->seen_)
8351 {
c484d925 8352 go_assert(saw_errors());
0f914071 8353 return error_mark_node;
8354 }
8355 this->seen_ = true;
2c809f8f 8356 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8357 this->seen_ = false;
8358 }
e440a328 8359 else if (arg_type->map_type() != NULL)
2c809f8f 8360 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
e440a328 8361 else if (arg_type->channel_type() != NULL)
2c809f8f 8362 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
e440a328 8363 else
c3e6f413 8364 go_unreachable();
e440a328 8365 }
8366 else
8367 {
8368 if (arg_type->array_type() != NULL)
0f914071 8369 {
8370 if (this->seen_)
8371 {
c484d925 8372 go_assert(saw_errors());
0f914071 8373 return error_mark_node;
8374 }
8375 this->seen_ = true;
2c809f8f 8376 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8377 this->seen_ = false;
8378 }
e440a328 8379 else if (arg_type->channel_type() != NULL)
2c809f8f 8380 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
e440a328 8381 else
c3e6f413 8382 go_unreachable();
e440a328 8383 }
8384
2c809f8f 8385 return Expression::make_cast(int_type, val,
8386 location)->get_tree(context);
e440a328 8387 }
8388
8389 case BUILTIN_PRINT:
8390 case BUILTIN_PRINTLN:
8391 {
8392 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
2c809f8f 8393 Expression* print_stmts = NULL;
e440a328 8394
8395 const Expression_list* call_args = this->args();
8396 if (call_args != NULL)
8397 {
8398 for (Expression_list::const_iterator p = call_args->begin();
8399 p != call_args->end();
8400 ++p)
8401 {
8402 if (is_ln && p != call_args->begin())
8403 {
2c809f8f 8404 Expression* print_space =
8405 Runtime::make_call(Runtime::PRINT_SPACE,
8406 this->location(), 0);
e440a328 8407
2c809f8f 8408 print_stmts =
8409 Expression::make_compound(print_stmts, print_space,
8410 location);
8411 }
e440a328 8412
2c809f8f 8413 Expression* arg = *p;
8414 Type* type = arg->type();
8415 Runtime::Function code;
e440a328 8416 if (type->is_string_type())
2c809f8f 8417 code = Runtime::PRINT_STRING;
e440a328 8418 else if (type->integer_type() != NULL
8419 && type->integer_type()->is_unsigned())
8420 {
e440a328 8421 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8422 arg = Expression::make_cast(itype, arg, location);
8423 code = Runtime::PRINT_UINT64;
e440a328 8424 }
8425 else if (type->integer_type() != NULL)
8426 {
e440a328 8427 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8428 arg = Expression::make_cast(itype, arg, location);
8429 code = Runtime::PRINT_INT64;
e440a328 8430 }
8431 else if (type->float_type() != NULL)
8432 {
2c809f8f 8433 Type* dtype = Type::lookup_float_type("float64");
8434 arg = Expression::make_cast(dtype, arg, location);
8435 code = Runtime::PRINT_DOUBLE;
e440a328 8436 }
8437 else if (type->complex_type() != NULL)
8438 {
2c809f8f 8439 Type* ctype = Type::lookup_complex_type("complex128");
8440 arg = Expression::make_cast(ctype, arg, location);
8441 code = Runtime::PRINT_COMPLEX;
e440a328 8442 }
8443 else if (type->is_boolean_type())
2c809f8f 8444 code = Runtime::PRINT_BOOL;
e440a328 8445 else if (type->points_to() != NULL
8446 || type->channel_type() != NULL
8447 || type->map_type() != NULL
8448 || type->function_type() != NULL)
8449 {
2c809f8f 8450 arg = Expression::make_cast(type, arg, location);
8451 code = Runtime::PRINT_POINTER;
e440a328 8452 }
8453 else if (type->interface_type() != NULL)
8454 {
8455 if (type->interface_type()->is_empty())
2c809f8f 8456 code = Runtime::PRINT_EMPTY_INTERFACE;
e440a328 8457 else
2c809f8f 8458 code = Runtime::PRINT_INTERFACE;
e440a328 8459 }
411eb89e 8460 else if (type->is_slice_type())
2c809f8f 8461 code = Runtime::PRINT_SLICE;
e440a328 8462 else
cd238b8d 8463 {
8464 go_assert(saw_errors());
8465 return error_mark_node;
8466 }
e440a328 8467
2c809f8f 8468 Expression* call = Runtime::make_call(code, location, 1, arg);
8469 if (print_stmts == NULL)
8470 print_stmts = call;
8471 else
8472 print_stmts = Expression::make_compound(print_stmts, call,
8473 location);
e440a328 8474 }
8475 }
8476
8477 if (is_ln)
8478 {
2c809f8f 8479 Expression* print_nl =
8480 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8481 if (print_stmts == NULL)
8482 print_stmts = print_nl;
8483 else
8484 print_stmts = Expression::make_compound(print_stmts, print_nl,
8485 location);
e440a328 8486 }
8487
2c809f8f 8488 return print_stmts->get_tree(context);
e440a328 8489 }
8490
8491 case BUILTIN_PANIC:
8492 {
8493 const Expression_list* args = this->args();
c484d925 8494 go_assert(args != NULL && args->size() == 1);
e440a328 8495 Expression* arg = args->front();
b13c66cd 8496 Type *empty =
823c7e3d 8497 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8498 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8499
8500 Expression* panic =
8501 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8502 return panic->get_tree(context);
e440a328 8503 }
8504
8505 case BUILTIN_RECOVER:
8506 {
8507 // The argument is set when building recover thunks. It's a
8508 // boolean value which is true if we can recover a value now.
8509 const Expression_list* args = this->args();
c484d925 8510 go_assert(args != NULL && args->size() == 1);
e440a328 8511 Expression* arg = args->front();
b13c66cd 8512 Type *empty =
823c7e3d 8513 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8514
e440a328 8515 Expression* nil = Expression::make_nil(location);
2c809f8f 8516 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8517
8518 // We need to handle a deferred call to recover specially,
8519 // because it changes whether it can recover a panic or not.
8520 // See test7 in test/recover1.go.
2c809f8f 8521 Expression* recover = Runtime::make_call((this->is_deferred()
8522 ? Runtime::DEFERRED_RECOVER
8523 : Runtime::RECOVER),
8524 location, 0);
8525 Expression* cond =
8526 Expression::make_conditional(arg, recover, nil, location);
8527 return cond->get_tree(context);
e440a328 8528 }
8529
8530 case BUILTIN_CLOSE:
e440a328 8531 {
8532 const Expression_list* args = this->args();
c484d925 8533 go_assert(args != NULL && args->size() == 1);
e440a328 8534 Expression* arg = args->front();
2c809f8f 8535 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8536 1, arg);
8537 return close->get_tree(context);
e440a328 8538 }
8539
8540 case BUILTIN_SIZEOF:
8541 case BUILTIN_OFFSETOF:
8542 case BUILTIN_ALIGNOF:
8543 {
0c77715b 8544 Numeric_constant nc;
8545 unsigned long val;
8546 if (!this->numeric_constant_value(&nc)
8547 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8548 {
c484d925 8549 go_assert(saw_errors());
7f1d9abd 8550 return error_mark_node;
8551 }
7ba86326 8552 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 8553 mpz_t ival;
8554 nc.get_int(&ival);
8555 Expression* int_cst =
8556 Expression::make_integer(&ival, uintptr_type, location);
8557 mpz_clear(ival);
8558 return int_cst->get_tree(context);
e440a328 8559 }
8560
8561 case BUILTIN_COPY:
8562 {
8563 const Expression_list* args = this->args();
c484d925 8564 go_assert(args != NULL && args->size() == 2);
e440a328 8565 Expression* arg1 = args->front();
8566 Expression* arg2 = args->back();
8567
e440a328 8568 Type* arg1_type = arg1->type();
8569 Array_type* at = arg1_type->array_type();
35a54f17 8570 go_assert(arg1->is_variable());
2c809f8f 8571 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8572 Expression* arg1_len = at->get_length(gogo, arg1);
e440a328 8573
8574 Type* arg2_type = arg2->type();
2c809f8f 8575 go_assert(arg2->is_variable());
8576 Expression* arg2_val;
8577 Expression* arg2_len;
411eb89e 8578 if (arg2_type->is_slice_type())
e440a328 8579 {
8580 at = arg2_type->array_type();
2c809f8f 8581 arg2_val = at->get_value_pointer(gogo, arg2);
8582 arg2_len = at->get_length(gogo, arg2);
e440a328 8583 }
8584 else
8585 {
2c809f8f 8586 go_assert(arg2->is_variable());
8587 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8588 location);
8589 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8590 location);
e440a328 8591 }
2c809f8f 8592 Expression* cond =
8593 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8594 Expression* length =
8595 Expression::make_conditional(cond, arg1_len, arg2_len, location);
e440a328 8596
8597 Type* element_type = at->element_type();
9f0e0513 8598 Btype* element_btype = element_type->get_backend(gogo);
e440a328 8599
2c809f8f 8600 mpz_t size;
8601 size_t element_size = gogo->backend()->type_size(element_btype);
8602 mpz_init_set_ui(size, element_size);
8603 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8604 mpz_clear(size);
8605
8606 Expression* bytecount =
8607 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8608 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8609 arg1_val, arg2_val, bytecount);
8610
8611 Expression* compound = Expression::make_compound(copy, length, location);
8612 return compound->get_tree(context);
e440a328 8613 }
8614
8615 case BUILTIN_APPEND:
8616 {
8617 const Expression_list* args = this->args();
c484d925 8618 go_assert(args != NULL && args->size() == 2);
e440a328 8619 Expression* arg1 = args->front();
8620 Expression* arg2 = args->back();
8621
9d44fbe3 8622 Array_type* at = arg1->type()->array_type();
4fd4fcf4 8623 Type* element_type = at->element_type()->forwarded();
9d44fbe3 8624
2c809f8f 8625 go_assert(arg2->is_variable());
8626 Expression* arg2_val;
8627 Expression* arg2_len;
8628 mpz_t size;
4fd4fcf4 8629 if (arg2->type()->is_string_type()
60963afd 8630 && element_type->integer_type() != NULL
8631 && element_type->integer_type()->is_byte())
4fd4fcf4 8632 {
2c809f8f 8633 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8634 location);
8635 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8636 location);
8637 mpz_init_set_ui(size, 1UL);
4fd4fcf4 8638 }
8639 else
8640 {
2c809f8f 8641 arg2_val = at->get_value_pointer(gogo, arg2);
8642 arg2_len = at->get_length(gogo, arg2);
35a54f17 8643 Btype* element_btype = element_type->get_backend(gogo);
2c809f8f 8644 size_t element_size = gogo->backend()->type_size(element_btype);
8645 mpz_init_set_ui(size, element_size);
4fd4fcf4 8646 }
2c809f8f 8647 Expression* element_size =
8648 Expression::make_integer(&size, NULL, location);
8649 mpz_clear(size);
8650
8651 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8652 arg1, arg2_val, arg2_len,
8653 element_size);
8654 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8655 return append->get_tree(context);
e440a328 8656 }
8657
8658 case BUILTIN_REAL:
8659 case BUILTIN_IMAG:
8660 {
8661 const Expression_list* args = this->args();
c484d925 8662 go_assert(args != NULL && args->size() == 1);
e440a328 8663 Expression* arg = args->front();
2c809f8f 8664
8665 Bexpression* ret;
8666 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8667 if (this->code_ == BUILTIN_REAL)
8668 ret = gogo->backend()->real_part_expression(bcomplex, location);
8669 else
8670 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8671 return expr_to_tree(ret);
e440a328 8672 }
8673
48080209 8674 case BUILTIN_COMPLEX:
e440a328 8675 {
8676 const Expression_list* args = this->args();
c484d925 8677 go_assert(args != NULL && args->size() == 2);
2c809f8f 8678 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8679 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8680 Bexpression* ret =
8681 gogo->backend()->complex_expression(breal, bimag, location);
8682 return expr_to_tree(ret);
e440a328 8683 }
8684
8685 default:
c3e6f413 8686 go_unreachable();
e440a328 8687 }
8688}
8689
8690// We have to support exporting a builtin call expression, because
8691// code can set a constant to the result of a builtin expression.
8692
8693void
8694Builtin_call_expression::do_export(Export* exp) const
8695{
0c77715b 8696 Numeric_constant nc;
8697 if (!this->numeric_constant_value(&nc))
8698 {
8699 error_at(this->location(), "value is not constant");
8700 return;
8701 }
e440a328 8702
0c77715b 8703 if (nc.is_int())
e440a328 8704 {
0c77715b 8705 mpz_t val;
8706 nc.get_int(&val);
e440a328 8707 Integer_expression::export_integer(exp, val);
0c77715b 8708 mpz_clear(val);
e440a328 8709 }
0c77715b 8710 else if (nc.is_float())
e440a328 8711 {
8712 mpfr_t fval;
0c77715b 8713 nc.get_float(&fval);
8714 Float_expression::export_float(exp, fval);
e440a328 8715 mpfr_clear(fval);
8716 }
0c77715b 8717 else if (nc.is_complex())
e440a328 8718 {
8719 mpfr_t real;
8720 mpfr_t imag;
0c77715b 8721 Complex_expression::export_complex(exp, real, imag);
e440a328 8722 mpfr_clear(real);
8723 mpfr_clear(imag);
8724 }
0c77715b 8725 else
8726 go_unreachable();
e440a328 8727
8728 // A trailing space lets us reliably identify the end of the number.
8729 exp->write_c_string(" ");
8730}
8731
8732// Class Call_expression.
8733
8381eda7 8734// A Go function can be viewed in a couple of different ways. The
8735// code of a Go function becomes a backend function with parameters
8736// whose types are simply the backend representation of the Go types.
8737// If there are multiple results, they are returned as a backend
8738// struct.
8739
8740// However, when Go code refers to a function other than simply
8741// calling it, the backend type of that function is actually a struct.
8742// The first field of the struct points to the Go function code
8743// (sometimes a wrapper as described below). The remaining fields
8744// hold addresses of closed-over variables. This struct is called a
8745// closure.
8746
8747// There are a few cases to consider.
8748
8749// A direct function call of a known function in package scope. In
8750// this case there are no closed-over variables, and we know the name
8751// of the function code. We can simply produce a backend call to the
8752// function directly, and not worry about the closure.
8753
8754// A direct function call of a known function literal. In this case
8755// we know the function code and we know the closure. We generate the
8756// function code such that it expects an additional final argument of
8757// the closure type. We pass the closure as the last argument, after
8758// the other arguments.
8759
8760// An indirect function call. In this case we have a closure. We
8761// load the pointer to the function code from the first field of the
8762// closure. We pass the address of the closure as the last argument.
8763
8764// A call to a method of an interface. Type methods are always at
8765// package scope, so we call the function directly, and don't worry
8766// about the closure.
8767
8768// This means that for a function at package scope we have two cases.
8769// One is the direct call, which has no closure. The other is the
8770// indirect call, which does have a closure. We can't simply ignore
8771// the closure, even though it is the last argument, because that will
8772// fail on targets where the function pops its arguments. So when
8773// generating a closure for a package-scope function we set the
8774// function code pointer in the closure to point to a wrapper
8775// function. This wrapper function accepts a final argument that
8776// points to the closure, ignores it, and calls the real function as a
8777// direct function call. This wrapper will normally be efficient, and
8778// can often simply be a tail call to the real function.
8779
8780// We don't use GCC's static chain pointer because 1) we don't need
8781// it; 2) GCC only permits using a static chain to call a known
8782// function, so we can't use it for an indirect call anyhow. Since we
8783// can't use it for an indirect call, we may as well not worry about
8784// using it for a direct call either.
8785
8786// We pass the closure last rather than first because it means that
8787// the function wrapper we put into a closure for a package-scope
8788// function can normally just be a tail call to the real function.
8789
8790// For method expressions we generate a wrapper that loads the
8791// receiver from the closure and then calls the method. This
8792// unfortunately forces reshuffling the arguments, since there is a
8793// new first argument, but we can't avoid reshuffling either for
8794// method expressions or for indirect calls of package-scope
8795// functions, and since the latter are more common we reshuffle for
8796// method expressions.
8797
8798// Note that the Go code retains the Go types. The extra final
8799// argument only appears when we convert to the backend
8800// representation.
8801
e440a328 8802// Traversal.
8803
8804int
8805Call_expression::do_traverse(Traverse* traverse)
8806{
8807 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8808 return TRAVERSE_EXIT;
8809 if (this->args_ != NULL)
8810 {
8811 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8812 return TRAVERSE_EXIT;
8813 }
8814 return TRAVERSE_CONTINUE;
8815}
8816
8817// Lower a call statement.
8818
8819Expression*
ceeb4318 8820Call_expression::do_lower(Gogo* gogo, Named_object* function,
8821 Statement_inserter* inserter, int)
e440a328 8822{
b13c66cd 8823 Location loc = this->location();
09ea332d 8824
ceeb4318 8825 // A type cast can look like a function call.
e440a328 8826 if (this->fn_->is_type_expression()
8827 && this->args_ != NULL
8828 && this->args_->size() == 1)
8829 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 8830 loc);
e440a328 8831
88f06749 8832 // Because do_type will return an error type and thus prevent future
8833 // errors, check for that case now to ensure that the error gets
8834 // reported.
37448b10 8835 Function_type* fntype = this->get_function_type();
8836 if (fntype == NULL)
88f06749 8837 {
8838 if (!this->fn_->type()->is_error())
8839 this->report_error(_("expected function"));
8840 return Expression::make_error(loc);
8841 }
8842
e440a328 8843 // Handle an argument which is a call to a function which returns
8844 // multiple results.
8845 if (this->args_ != NULL
8846 && this->args_->size() == 1
37448b10 8847 && this->args_->front()->call_expression() != NULL)
e440a328 8848 {
e440a328 8849 size_t rc = this->args_->front()->call_expression()->result_count();
8850 if (rc > 1
37448b10 8851 && ((fntype->parameters() != NULL
8852 && (fntype->parameters()->size() == rc
8853 || (fntype->is_varargs()
8854 && fntype->parameters()->size() - 1 <= rc)))
8855 || fntype->is_builtin()))
e440a328 8856 {
8857 Call_expression* call = this->args_->front()->call_expression();
8858 Expression_list* args = new Expression_list;
8859 for (size_t i = 0; i < rc; ++i)
8860 args->push_back(Expression::make_call_result(call, i));
8861 // We can't return a new call expression here, because this
42535814 8862 // one may be referenced by Call_result expressions. We
8863 // also can't delete the old arguments, because we may still
8864 // traverse them somewhere up the call stack. FIXME.
e440a328 8865 this->args_ = args;
8866 }
8867 }
8868
37448b10 8869 // Recognize a call to a builtin function.
8870 if (fntype->is_builtin())
8871 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8872 this->is_varargs_, loc);
8873
ceeb4318 8874 // If this call returns multiple results, create a temporary
8875 // variable for each result.
8876 size_t rc = this->result_count();
8877 if (rc > 1 && this->results_ == NULL)
8878 {
8879 std::vector<Temporary_statement*>* temps =
8880 new std::vector<Temporary_statement*>;
8881 temps->reserve(rc);
37448b10 8882 const Typed_identifier_list* results = fntype->results();
ceeb4318 8883 for (Typed_identifier_list::const_iterator p = results->begin();
8884 p != results->end();
8885 ++p)
8886 {
8887 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 8888 NULL, loc);
ceeb4318 8889 inserter->insert(temp);
8890 temps->push_back(temp);
8891 }
8892 this->results_ = temps;
8893 }
8894
e440a328 8895 // Handle a call to a varargs function by packaging up the extra
8896 // parameters.
37448b10 8897 if (fntype->is_varargs())
e440a328 8898 {
e440a328 8899 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 8900 go_assert(parameters != NULL && !parameters->empty());
e440a328 8901 Type* varargs_type = parameters->back().type();
09ea332d 8902 this->lower_varargs(gogo, function, inserter, varargs_type,
8903 parameters->size());
8904 }
8905
8906 // If this is call to a method, call the method directly passing the
8907 // object as the first parameter.
8908 Bound_method_expression* bme = this->fn_->bound_method_expression();
8909 if (bme != NULL)
8910 {
0afbb937 8911 Named_object* methodfn = bme->function();
09ea332d 8912 Expression* first_arg = bme->first_argument();
8913
8914 // We always pass a pointer when calling a method.
8915 if (first_arg->type()->points_to() == NULL
8916 && !first_arg->type()->is_error())
8917 {
8918 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8919 // We may need to create a temporary variable so that we can
8920 // take the address. We can't do that here because it will
8921 // mess up the order of evaluation.
8922 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8923 ue->set_create_temp();
8924 }
8925
8926 // If we are calling a method which was inherited from an
8927 // embedded struct, and the method did not get a stub, then the
8928 // first type may be wrong.
8929 Type* fatype = bme->first_argument_type();
8930 if (fatype != NULL)
8931 {
8932 if (fatype->points_to() == NULL)
8933 fatype = Type::make_pointer_type(fatype);
8934 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8935 }
8936
8937 Expression_list* new_args = new Expression_list();
8938 new_args->push_back(first_arg);
8939 if (this->args_ != NULL)
8940 {
8941 for (Expression_list::const_iterator p = this->args_->begin();
8942 p != this->args_->end();
8943 ++p)
8944 new_args->push_back(*p);
8945 }
8946
8947 // We have to change in place because this structure may be
8948 // referenced by Call_result_expressions. We can't delete the
8949 // old arguments, because we may be traversing them up in some
8950 // caller. FIXME.
8951 this->args_ = new_args;
0afbb937 8952 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 8953 bme->location());
e440a328 8954 }
8955
8956 return this;
8957}
8958
8959// Lower a call to a varargs function. FUNCTION is the function in
8960// which the call occurs--it's not the function we are calling.
8961// VARARGS_TYPE is the type of the varargs parameter, a slice type.
8962// PARAM_COUNT is the number of parameters of the function we are
8963// calling; the last of these parameters will be the varargs
8964// parameter.
8965
09ea332d 8966void
e440a328 8967Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 8968 Statement_inserter* inserter,
e440a328 8969 Type* varargs_type, size_t param_count)
8970{
8971 if (this->varargs_are_lowered_)
09ea332d 8972 return;
e440a328 8973
b13c66cd 8974 Location loc = this->location();
e440a328 8975
c484d925 8976 go_assert(param_count > 0);
411eb89e 8977 go_assert(varargs_type->is_slice_type());
e440a328 8978
8979 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8980 if (arg_count < param_count - 1)
8981 {
8982 // Not enough arguments; will be caught in check_types.
09ea332d 8983 return;
e440a328 8984 }
8985
8986 Expression_list* old_args = this->args_;
8987 Expression_list* new_args = new Expression_list();
8988 bool push_empty_arg = false;
8989 if (old_args == NULL || old_args->empty())
8990 {
c484d925 8991 go_assert(param_count == 1);
e440a328 8992 push_empty_arg = true;
8993 }
8994 else
8995 {
8996 Expression_list::const_iterator pa;
8997 int i = 1;
8998 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8999 {
9000 if (static_cast<size_t>(i) == param_count)
9001 break;
9002 new_args->push_back(*pa);
9003 }
9004
9005 // We have reached the varargs parameter.
9006
9007 bool issued_error = false;
9008 if (pa == old_args->end())
9009 push_empty_arg = true;
9010 else if (pa + 1 == old_args->end() && this->is_varargs_)
9011 new_args->push_back(*pa);
9012 else if (this->is_varargs_)
9013 {
a6645f74 9014 if ((*pa)->type()->is_slice_type())
9015 this->report_error(_("too many arguments"));
9016 else
9017 {
9018 error_at(this->location(),
9019 _("invalid use of %<...%> with non-slice"));
9020 this->set_is_error();
9021 }
09ea332d 9022 return;
e440a328 9023 }
e440a328 9024 else
9025 {
9026 Type* element_type = varargs_type->array_type()->element_type();
9027 Expression_list* vals = new Expression_list;
9028 for (; pa != old_args->end(); ++pa, ++i)
9029 {
9030 // Check types here so that we get a better message.
9031 Type* patype = (*pa)->type();
b13c66cd 9032 Location paloc = (*pa)->location();
e440a328 9033 if (!this->check_argument_type(i, element_type, patype,
9034 paloc, issued_error))
9035 continue;
9036 vals->push_back(*pa);
9037 }
9038 Expression* val =
9039 Expression::make_slice_composite_literal(varargs_type, vals, loc);
09ea332d 9040 gogo->lower_expression(function, inserter, &val);
e440a328 9041 new_args->push_back(val);
9042 }
9043 }
9044
9045 if (push_empty_arg)
9046 new_args->push_back(Expression::make_nil(loc));
9047
9048 // We can't return a new call expression here, because this one may
6d4c2432 9049 // be referenced by Call_result expressions. FIXME. We can't
9050 // delete OLD_ARGS because we may have both a Call_expression and a
9051 // Builtin_call_expression which refer to them. FIXME.
e440a328 9052 this->args_ = new_args;
9053 this->varargs_are_lowered_ = true;
e440a328 9054}
9055
2c809f8f 9056// Flatten a call with multiple results into a temporary.
9057
9058Expression*
9059Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9060{
9061 size_t rc = this->result_count();
9062 if (rc > 1 && this->call_temp_ == NULL)
9063 {
9064 Struct_field_list* sfl = new Struct_field_list();
9065 Function_type* fntype = this->get_function_type();
9066 const Typed_identifier_list* results = fntype->results();
9067 Location loc = this->location();
9068
9069 int i = 0;
9070 char buf[10];
9071 for (Typed_identifier_list::const_iterator p = results->begin();
9072 p != results->end();
9073 ++p, ++i)
9074 {
9075 snprintf(buf, sizeof buf, "res%d", i);
9076 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9077 }
9078
9079 Struct_type* st = Type::make_struct_type(sfl, loc);
9080 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9081 inserter->insert(this->call_temp_);
9082 }
9083
9084 return this;
9085}
9086
ceeb4318 9087// Get the function type. This can return NULL in error cases.
e440a328 9088
9089Function_type*
9090Call_expression::get_function_type() const
9091{
9092 return this->fn_->type()->function_type();
9093}
9094
9095// Return the number of values which this call will return.
9096
9097size_t
9098Call_expression::result_count() const
9099{
9100 const Function_type* fntype = this->get_function_type();
9101 if (fntype == NULL)
9102 return 0;
9103 if (fntype->results() == NULL)
9104 return 0;
9105 return fntype->results()->size();
9106}
9107
ceeb4318 9108// Return the temporary which holds a result.
9109
9110Temporary_statement*
9111Call_expression::result(size_t i) const
9112{
cd238b8d 9113 if (this->results_ == NULL || this->results_->size() <= i)
9114 {
9115 go_assert(saw_errors());
9116 return NULL;
9117 }
ceeb4318 9118 return (*this->results_)[i];
9119}
9120
e440a328 9121// Return whether this is a call to the predeclared function recover.
9122
9123bool
9124Call_expression::is_recover_call() const
9125{
9126 return this->do_is_recover_call();
9127}
9128
9129// Set the argument to the recover function.
9130
9131void
9132Call_expression::set_recover_arg(Expression* arg)
9133{
9134 this->do_set_recover_arg(arg);
9135}
9136
9137// Virtual functions also implemented by Builtin_call_expression.
9138
9139bool
9140Call_expression::do_is_recover_call() const
9141{
9142 return false;
9143}
9144
9145void
9146Call_expression::do_set_recover_arg(Expression*)
9147{
c3e6f413 9148 go_unreachable();
e440a328 9149}
9150
ceeb4318 9151// We have found an error with this call expression; return true if
9152// we should report it.
9153
9154bool
9155Call_expression::issue_error()
9156{
9157 if (this->issued_error_)
9158 return false;
9159 else
9160 {
9161 this->issued_error_ = true;
9162 return true;
9163 }
9164}
9165
e440a328 9166// Get the type.
9167
9168Type*
9169Call_expression::do_type()
9170{
9171 if (this->type_ != NULL)
9172 return this->type_;
9173
9174 Type* ret;
9175 Function_type* fntype = this->get_function_type();
9176 if (fntype == NULL)
9177 return Type::make_error_type();
9178
9179 const Typed_identifier_list* results = fntype->results();
9180 if (results == NULL)
9181 ret = Type::make_void_type();
9182 else if (results->size() == 1)
9183 ret = results->begin()->type();
9184 else
9185 ret = Type::make_call_multiple_result_type(this);
9186
9187 this->type_ = ret;
9188
9189 return this->type_;
9190}
9191
9192// Determine types for a call expression. We can use the function
9193// parameter types to set the types of the arguments.
9194
9195void
9196Call_expression::do_determine_type(const Type_context*)
9197{
fb94b0ca 9198 if (!this->determining_types())
9199 return;
9200
e440a328 9201 this->fn_->determine_type_no_context();
9202 Function_type* fntype = this->get_function_type();
9203 const Typed_identifier_list* parameters = NULL;
9204 if (fntype != NULL)
9205 parameters = fntype->parameters();
9206 if (this->args_ != NULL)
9207 {
9208 Typed_identifier_list::const_iterator pt;
9209 if (parameters != NULL)
9210 pt = parameters->begin();
09ea332d 9211 bool first = true;
e440a328 9212 for (Expression_list::const_iterator pa = this->args_->begin();
9213 pa != this->args_->end();
9214 ++pa)
9215 {
09ea332d 9216 if (first)
9217 {
9218 first = false;
9219 // If this is a method, the first argument is the
9220 // receiver.
9221 if (fntype != NULL && fntype->is_method())
9222 {
9223 Type* rtype = fntype->receiver()->type();
9224 // The receiver is always passed as a pointer.
9225 if (rtype->points_to() == NULL)
9226 rtype = Type::make_pointer_type(rtype);
9227 Type_context subcontext(rtype, false);
9228 (*pa)->determine_type(&subcontext);
9229 continue;
9230 }
9231 }
9232
e440a328 9233 if (parameters != NULL && pt != parameters->end())
9234 {
9235 Type_context subcontext(pt->type(), false);
9236 (*pa)->determine_type(&subcontext);
9237 ++pt;
9238 }
9239 else
9240 (*pa)->determine_type_no_context();
9241 }
9242 }
9243}
9244
fb94b0ca 9245// Called when determining types for a Call_expression. Return true
9246// if we should go ahead, false if they have already been determined.
9247
9248bool
9249Call_expression::determining_types()
9250{
9251 if (this->types_are_determined_)
9252 return false;
9253 else
9254 {
9255 this->types_are_determined_ = true;
9256 return true;
9257 }
9258}
9259
e440a328 9260// Check types for parameter I.
9261
9262bool
9263Call_expression::check_argument_type(int i, const Type* parameter_type,
9264 const Type* argument_type,
b13c66cd 9265 Location argument_location,
e440a328 9266 bool issued_error)
9267{
9268 std::string reason;
053ee6ca 9269 bool ok;
9270 if (this->are_hidden_fields_ok_)
9271 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9272 &reason);
9273 else
9274 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9275 if (!ok)
e440a328 9276 {
9277 if (!issued_error)
9278 {
9279 if (reason.empty())
9280 error_at(argument_location, "argument %d has incompatible type", i);
9281 else
9282 error_at(argument_location,
9283 "argument %d has incompatible type (%s)",
9284 i, reason.c_str());
9285 }
9286 this->set_is_error();
9287 return false;
9288 }
9289 return true;
9290}
9291
9292// Check types.
9293
9294void
9295Call_expression::do_check_types(Gogo*)
9296{
a6645f74 9297 if (this->classification() == EXPRESSION_ERROR)
9298 return;
9299
e440a328 9300 Function_type* fntype = this->get_function_type();
9301 if (fntype == NULL)
9302 {
5c13bd80 9303 if (!this->fn_->type()->is_error())
e440a328 9304 this->report_error(_("expected function"));
9305 return;
9306 }
9307
09ea332d 9308 bool is_method = fntype->is_method();
9309 if (is_method)
e440a328 9310 {
09ea332d 9311 go_assert(this->args_ != NULL && !this->args_->empty());
9312 Type* rtype = fntype->receiver()->type();
9313 Expression* first_arg = this->args_->front();
9314 // The language permits copying hidden fields for a method
9315 // receiver. We dereference the values since receivers are
9316 // always passed as pointers.
9317 std::string reason;
9318 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9319 first_arg->type()->deref(),
9320 &reason))
e440a328 9321 {
09ea332d 9322 if (reason.empty())
9323 this->report_error(_("incompatible type for receiver"));
9324 else
e440a328 9325 {
09ea332d 9326 error_at(this->location(),
9327 "incompatible type for receiver (%s)",
9328 reason.c_str());
9329 this->set_is_error();
e440a328 9330 }
9331 }
9332 }
9333
9334 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9335 // we don't have to worry about it here unless something is wrong.
9336 if (this->is_varargs_ && !this->varargs_are_lowered_)
9337 {
9338 if (!fntype->is_varargs())
9339 {
9340 error_at(this->location(),
9341 _("invalid use of %<...%> calling non-variadic function"));
9342 this->set_is_error();
9343 return;
9344 }
9345 }
e440a328 9346
9347 const Typed_identifier_list* parameters = fntype->parameters();
9348 if (this->args_ == NULL)
9349 {
9350 if (parameters != NULL && !parameters->empty())
9351 this->report_error(_("not enough arguments"));
9352 }
9353 else if (parameters == NULL)
09ea332d 9354 {
9355 if (!is_method || this->args_->size() > 1)
9356 this->report_error(_("too many arguments"));
9357 }
e440a328 9358 else
9359 {
9360 int i = 0;
09ea332d 9361 Expression_list::const_iterator pa = this->args_->begin();
9362 if (is_method)
9363 ++pa;
9364 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9365 pt != parameters->end();
9366 ++pt, ++pa, ++i)
e440a328 9367 {
09ea332d 9368 if (pa == this->args_->end())
e440a328 9369 {
09ea332d 9370 this->report_error(_("not enough arguments"));
e440a328 9371 return;
9372 }
9373 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9374 (*pa)->location(), false);
9375 }
09ea332d 9376 if (pa != this->args_->end())
9377 this->report_error(_("too many arguments"));
e440a328 9378 }
9379}
9380
9381// Return whether we have to use a temporary variable to ensure that
9382// we evaluate this call expression in order. If the call returns no
ceeb4318 9383// results then it will inevitably be executed last.
e440a328 9384
9385bool
9386Call_expression::do_must_eval_in_order() const
9387{
ceeb4318 9388 return this->result_count() > 0;
e440a328 9389}
9390
e440a328 9391// Get the function and the first argument to use when calling an
9392// interface method.
9393
2387f644 9394Expression*
e440a328 9395Call_expression::interface_method_function(
e440a328 9396 Interface_field_reference_expression* interface_method,
2387f644 9397 Expression** first_arg_ptr)
e440a328 9398{
2387f644 9399 *first_arg_ptr = interface_method->get_underlying_object();
9400 return interface_method->get_function();
e440a328 9401}
9402
9403// Build the call expression.
9404
9405tree
9406Call_expression::do_get_tree(Translate_context* context)
9407{
2c809f8f 9408 if (this->call_ != NULL)
9409 return expr_to_tree(this->call_);
e440a328 9410
9411 Function_type* fntype = this->get_function_type();
9412 if (fntype == NULL)
9413 return error_mark_node;
9414
9415 if (this->fn_->is_error_expression())
9416 return error_mark_node;
9417
9418 Gogo* gogo = context->gogo();
b13c66cd 9419 Location location = this->location();
e440a328 9420
9421 Func_expression* func = this->fn_->func_expression();
e440a328 9422 Interface_field_reference_expression* interface_method =
9423 this->fn_->interface_field_reference_expression();
9424 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9425 const bool is_interface_method = interface_method != NULL;
e440a328 9426
f8bdf81a 9427 bool has_closure_arg;
8381eda7 9428 if (has_closure)
f8bdf81a 9429 has_closure_arg = true;
8381eda7 9430 else if (func != NULL)
f8bdf81a 9431 has_closure_arg = false;
8381eda7 9432 else if (is_interface_method)
f8bdf81a 9433 has_closure_arg = false;
8381eda7 9434 else
f8bdf81a 9435 has_closure_arg = true;
8381eda7 9436
e440a328 9437 int nargs;
2c809f8f 9438 std::vector<Bexpression*> fn_args;
e440a328 9439 if (this->args_ == NULL || this->args_->empty())
9440 {
f8bdf81a 9441 nargs = is_interface_method ? 1 : 0;
2c809f8f 9442 if (nargs > 0)
9443 fn_args.resize(1);
e440a328 9444 }
09ea332d 9445 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9446 {
9447 // Passing a receiver parameter.
9448 go_assert(!is_interface_method
9449 && fntype->is_method()
9450 && this->args_->size() == 1);
f8bdf81a 9451 nargs = 1;
2c809f8f 9452 fn_args.resize(1);
9453 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
09ea332d 9454 }
e440a328 9455 else
9456 {
9457 const Typed_identifier_list* params = fntype->parameters();
e440a328 9458
9459 nargs = this->args_->size();
09ea332d 9460 int i = is_interface_method ? 1 : 0;
e440a328 9461 nargs += i;
2c809f8f 9462 fn_args.resize(nargs);
e440a328 9463
9464 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 9465 Expression_list::const_iterator pe = this->args_->begin();
9466 if (!is_interface_method && fntype->is_method())
9467 {
2c809f8f 9468 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
09ea332d 9469 ++pe;
9470 ++i;
9471 }
9472 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 9473 {
c484d925 9474 go_assert(pp != params->end());
2c809f8f 9475 Expression* arg =
9476 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9477 location);
9478 fn_args[i] = tree_to_expr(arg->get_tree(context));
e440a328 9479 }
c484d925 9480 go_assert(pp == params->end());
f8bdf81a 9481 go_assert(i == nargs);
e440a328 9482 }
9483
2c809f8f 9484 Expression* fn;
9485 Expression* closure = NULL;
8381eda7 9486 if (func != NULL)
9487 {
9488 Named_object* no = func->named_object();
2c809f8f 9489 fn = Expression::make_func_code_reference(no, location);
9490 if (has_closure)
9491 closure = func->closure();
8381eda7 9492 }
09ea332d 9493 else if (!is_interface_method)
8381eda7 9494 {
2c809f8f 9495 closure = this->fn_;
9496
9497 // The backend representation of this function type is a pointer
9498 // to a struct whose first field is the actual function to call.
9499 Type* pfntype =
9500 Type::make_pointer_type(
9501 Type::make_pointer_type(Type::make_void_type()));
9502 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9503 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9504 }
e440a328 9505 else
cf609de4 9506 {
2387f644 9507 Expression* first_arg;
2c809f8f 9508 fn = this->interface_method_function(interface_method, &first_arg);
9509 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
e440a328 9510 }
9511
f8bdf81a 9512 if (!has_closure_arg)
2c809f8f 9513 go_assert(closure == NULL);
f8bdf81a 9514 else
9515 {
9516 // Pass the closure argument by calling the function function
9517 // __go_set_closure. In the order_evaluations pass we have
9518 // ensured that if any parameters contain call expressions, they
9519 // will have been moved out to temporary variables.
2c809f8f 9520 go_assert(closure != NULL);
9521 Expression* set_closure =
9522 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9523 fn = Expression::make_compound(set_closure, fn, location);
f8bdf81a 9524 }
9525
2c809f8f 9526 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
80d1e1a8 9527
9528 // When not calling a named function directly, use a type conversion
9529 // in case the type of the function is a recursive type which refers
9530 // to itself. We don't do this for an interface method because 1)
9531 // an interface method never refers to itself, so we always have a
9532 // function type here; 2) we pass an extra first argument to an
9533 // interface method, so fntype is not correct.
9534 if (func == NULL && !is_interface_method)
9535 {
9536 Btype* bft = fntype->get_backend_fntype(gogo);
9537 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9538 }
9539
2c809f8f 9540 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
e440a328 9541
2c809f8f 9542 if (this->results_ != NULL)
e440a328 9543 {
2c809f8f 9544 go_assert(this->call_temp_ != NULL);
9545 Expression* call_ref =
9546 Expression::make_temporary_reference(this->call_temp_, location);
9547 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9548 Bstatement* assn_stmt =
9549 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 9550
2c809f8f 9551 this->call_ = this->set_results(context, bcall_ref);
e440a328 9552
2c809f8f 9553 Bexpression* set_and_call =
9554 gogo->backend()->compound_expression(assn_stmt, this->call_,
9555 location);
9556 return expr_to_tree(set_and_call);
9557 }
e440a328 9558
2c809f8f 9559 this->call_ = call;
9560 return expr_to_tree(this->call_);
e440a328 9561}
9562
ceeb4318 9563// Set the result variables if this call returns multiple results.
9564
2c809f8f 9565Bexpression*
9566Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 9567{
2c809f8f 9568 Gogo* gogo = context->gogo();
ceeb4318 9569
2c809f8f 9570 Bexpression* results = NULL;
b13c66cd 9571 Location loc = this->location();
2c809f8f 9572
ceeb4318 9573 size_t rc = this->result_count();
2c809f8f 9574 for (size_t i = 0; i < rc; ++i)
ceeb4318 9575 {
ceeb4318 9576 Temporary_statement* temp = this->result(i);
cd238b8d 9577 if (temp == NULL)
9578 {
9579 go_assert(saw_errors());
2c809f8f 9580 return gogo->backend()->error_expression();
cd238b8d 9581 }
ceeb4318 9582 Temporary_reference_expression* ref =
9583 Expression::make_temporary_reference(temp, loc);
9584 ref->set_is_lvalue();
ceeb4318 9585
2c809f8f 9586 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9587 Bexpression* call_result =
9588 gogo->backend()->struct_field_expression(call, i, loc);
9589 Bstatement* assn_stmt =
9590 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 9591
2c809f8f 9592 Bexpression* result =
9593 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 9594
2c809f8f 9595 if (results == NULL)
9596 results = result;
9597 else
9598 {
9599 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9600 results =
9601 gogo->backend()->compound_expression(expr_stmt, results, loc);
9602 }
9603 }
9604 return results;
ceeb4318 9605}
9606
d751bb78 9607// Dump ast representation for a call expressin.
9608
9609void
9610Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9611{
9612 this->fn_->dump_expression(ast_dump_context);
9613 ast_dump_context->ostream() << "(";
9614 if (args_ != NULL)
9615 ast_dump_context->dump_expression_list(this->args_);
9616
9617 ast_dump_context->ostream() << ") ";
9618}
9619
e440a328 9620// Make a call expression.
9621
9622Call_expression*
9623Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 9624 Location location)
e440a328 9625{
9626 return new Call_expression(fn, args, is_varargs, location);
9627}
9628
9629// A single result from a call which returns multiple results.
9630
9631class Call_result_expression : public Expression
9632{
9633 public:
9634 Call_result_expression(Call_expression* call, unsigned int index)
9635 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9636 call_(call), index_(index)
9637 { }
9638
9639 protected:
9640 int
9641 do_traverse(Traverse*);
9642
9643 Type*
9644 do_type();
9645
9646 void
9647 do_determine_type(const Type_context*);
9648
9649 void
9650 do_check_types(Gogo*);
9651
9652 Expression*
9653 do_copy()
9654 {
9655 return new Call_result_expression(this->call_->call_expression(),
9656 this->index_);
9657 }
9658
9659 bool
9660 do_must_eval_in_order() const
9661 { return true; }
9662
9663 tree
9664 do_get_tree(Translate_context*);
9665
d751bb78 9666 void
9667 do_dump_expression(Ast_dump_context*) const;
9668
e440a328 9669 private:
9670 // The underlying call expression.
9671 Expression* call_;
9672 // Which result we want.
9673 unsigned int index_;
9674};
9675
9676// Traverse a call result.
9677
9678int
9679Call_result_expression::do_traverse(Traverse* traverse)
9680{
9681 if (traverse->remember_expression(this->call_))
9682 {
9683 // We have already traversed the call expression.
9684 return TRAVERSE_CONTINUE;
9685 }
9686 return Expression::traverse(&this->call_, traverse);
9687}
9688
9689// Get the type.
9690
9691Type*
9692Call_result_expression::do_type()
9693{
425dd051 9694 if (this->classification() == EXPRESSION_ERROR)
9695 return Type::make_error_type();
9696
e440a328 9697 // THIS->CALL_ can be replaced with a temporary reference due to
9698 // Call_expression::do_must_eval_in_order when there is an error.
9699 Call_expression* ce = this->call_->call_expression();
9700 if (ce == NULL)
5e85f268 9701 {
9702 this->set_is_error();
9703 return Type::make_error_type();
9704 }
e440a328 9705 Function_type* fntype = ce->get_function_type();
9706 if (fntype == NULL)
5e85f268 9707 {
e37658e2 9708 if (ce->issue_error())
99b3f06f 9709 {
9710 if (!ce->fn()->type()->is_error())
9711 this->report_error(_("expected function"));
9712 }
5e85f268 9713 this->set_is_error();
9714 return Type::make_error_type();
9715 }
e440a328 9716 const Typed_identifier_list* results = fntype->results();
ceeb4318 9717 if (results == NULL || results->size() < 2)
7b8d861f 9718 {
ceeb4318 9719 if (ce->issue_error())
9720 this->report_error(_("number of results does not match "
9721 "number of values"));
7b8d861f 9722 return Type::make_error_type();
9723 }
e440a328 9724 Typed_identifier_list::const_iterator pr = results->begin();
9725 for (unsigned int i = 0; i < this->index_; ++i)
9726 {
9727 if (pr == results->end())
425dd051 9728 break;
e440a328 9729 ++pr;
9730 }
9731 if (pr == results->end())
425dd051 9732 {
ceeb4318 9733 if (ce->issue_error())
9734 this->report_error(_("number of results does not match "
9735 "number of values"));
425dd051 9736 return Type::make_error_type();
9737 }
e440a328 9738 return pr->type();
9739}
9740
425dd051 9741// Check the type. Just make sure that we trigger the warning in
9742// do_type.
e440a328 9743
9744void
9745Call_result_expression::do_check_types(Gogo*)
9746{
425dd051 9747 this->type();
e440a328 9748}
9749
9750// Determine the type. We have nothing to do here, but the 0 result
9751// needs to pass down to the caller.
9752
9753void
9754Call_result_expression::do_determine_type(const Type_context*)
9755{
fb94b0ca 9756 this->call_->determine_type_no_context();
e440a328 9757}
9758
ceeb4318 9759// Return the tree. We just refer to the temporary set by the call
9760// expression. We don't do this at lowering time because it makes it
9761// hard to evaluate the call at the right time.
e440a328 9762
9763tree
9764Call_result_expression::do_get_tree(Translate_context* context)
9765{
ceeb4318 9766 Call_expression* ce = this->call_->call_expression();
cd238b8d 9767 if (ce == NULL)
9768 {
9769 go_assert(this->call_->is_error_expression());
9770 return error_mark_node;
9771 }
ceeb4318 9772 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 9773 if (ts == NULL)
9774 {
9775 go_assert(saw_errors());
9776 return error_mark_node;
9777 }
ceeb4318 9778 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9779 return ref->get_tree(context);
e440a328 9780}
9781
d751bb78 9782// Dump ast representation for a call result expression.
9783
9784void
9785Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9786 const
9787{
9788 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9789 // (struct) and the fields are referenced instead.
9790 ast_dump_context->ostream() << this->index_ << "@(";
9791 ast_dump_context->dump_expression(this->call_);
9792 ast_dump_context->ostream() << ")";
9793}
9794
e440a328 9795// Make a reference to a single result of a call which returns
9796// multiple results.
9797
9798Expression*
9799Expression::make_call_result(Call_expression* call, unsigned int index)
9800{
9801 return new Call_result_expression(call, index);
9802}
9803
9804// Class Index_expression.
9805
9806// Traversal.
9807
9808int
9809Index_expression::do_traverse(Traverse* traverse)
9810{
9811 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9812 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9813 || (this->end_ != NULL
acf2b673 9814 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9815 || (this->cap_ != NULL
9816 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 9817 return TRAVERSE_EXIT;
9818 return TRAVERSE_CONTINUE;
9819}
9820
9821// Lower an index expression. This converts the generic index
9822// expression into an array index, a string index, or a map index.
9823
9824Expression*
ceeb4318 9825Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 9826{
b13c66cd 9827 Location location = this->location();
e440a328 9828 Expression* left = this->left_;
9829 Expression* start = this->start_;
9830 Expression* end = this->end_;
acf2b673 9831 Expression* cap = this->cap_;
e440a328 9832
9833 Type* type = left->type();
5c13bd80 9834 if (type->is_error())
e440a328 9835 return Expression::make_error(location);
b0cf7ddd 9836 else if (left->is_type_expression())
9837 {
9838 error_at(location, "attempt to index type expression");
9839 return Expression::make_error(location);
9840 }
e440a328 9841 else if (type->array_type() != NULL)
acf2b673 9842 return Expression::make_array_index(left, start, end, cap, location);
e440a328 9843 else if (type->points_to() != NULL
9844 && type->points_to()->array_type() != NULL
411eb89e 9845 && !type->points_to()->is_slice_type())
e440a328 9846 {
9847 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9848 location);
38092374 9849
9850 // For an ordinary index into the array, the pointer will be
9851 // dereferenced. For a slice it will not--the resulting slice
9852 // will simply reuse the pointer, which is incorrect if that
9853 // pointer is nil.
9854 if (end != NULL || cap != NULL)
9855 deref->issue_nil_check();
9856
acf2b673 9857 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 9858 }
9859 else if (type->is_string_type())
acf2b673 9860 {
9861 if (cap != NULL)
9862 {
9863 error_at(location, "invalid 3-index slice of string");
9864 return Expression::make_error(location);
9865 }
9866 return Expression::make_string_index(left, start, end, location);
9867 }
e440a328 9868 else if (type->map_type() != NULL)
9869 {
acf2b673 9870 if (end != NULL || cap != NULL)
e440a328 9871 {
9872 error_at(location, "invalid slice of map");
9873 return Expression::make_error(location);
9874 }
6d4c2432 9875 Map_index_expression* ret = Expression::make_map_index(left, start,
9876 location);
e440a328 9877 if (this->is_lvalue_)
9878 ret->set_is_lvalue();
9879 return ret;
9880 }
9881 else
9882 {
9883 error_at(location,
9884 "attempt to index object which is not array, string, or map");
9885 return Expression::make_error(location);
9886 }
9887}
9888
acf2b673 9889// Write an indexed expression
9890// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 9891
9892void
9893Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9894 const Expression* expr,
9895 const Expression* start,
acf2b673 9896 const Expression* end,
9897 const Expression* cap)
d751bb78 9898{
9899 expr->dump_expression(ast_dump_context);
9900 ast_dump_context->ostream() << "[";
9901 start->dump_expression(ast_dump_context);
9902 if (end != NULL)
9903 {
9904 ast_dump_context->ostream() << ":";
9905 end->dump_expression(ast_dump_context);
9906 }
acf2b673 9907 if (cap != NULL)
9908 {
9909 ast_dump_context->ostream() << ":";
9910 cap->dump_expression(ast_dump_context);
9911 }
d751bb78 9912 ast_dump_context->ostream() << "]";
9913}
9914
9915// Dump ast representation for an index expression.
9916
9917void
9918Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9919 const
9920{
9921 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 9922 this->start_, this->end_, this->cap_);
d751bb78 9923}
9924
e440a328 9925// Make an index expression.
9926
9927Expression*
9928Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 9929 Expression* cap, Location location)
e440a328 9930{
acf2b673 9931 return new Index_expression(left, start, end, cap, location);
e440a328 9932}
9933
9934// An array index. This is used for both indexing and slicing.
9935
9936class Array_index_expression : public Expression
9937{
9938 public:
9939 Array_index_expression(Expression* array, Expression* start,
acf2b673 9940 Expression* end, Expression* cap, Location location)
e440a328 9941 : Expression(EXPRESSION_ARRAY_INDEX, location),
acf2b673 9942 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
e440a328 9943 { }
9944
9945 protected:
9946 int
9947 do_traverse(Traverse*);
9948
2c809f8f 9949 Expression*
9950 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9951
e440a328 9952 Type*
9953 do_type();
9954
9955 void
9956 do_determine_type(const Type_context*);
9957
9958 void
9959 do_check_types(Gogo*);
9960
9961 Expression*
9962 do_copy()
9963 {
9964 return Expression::make_array_index(this->array_->copy(),
9965 this->start_->copy(),
9966 (this->end_ == NULL
9967 ? NULL
9968 : this->end_->copy()),
acf2b673 9969 (this->cap_ == NULL
9970 ? NULL
9971 : this->cap_->copy()),
e440a328 9972 this->location());
9973 }
9974
baef9f7a 9975 bool
9976 do_must_eval_subexpressions_in_order(int* skip) const
9977 {
9978 *skip = 1;
9979 return true;
9980 }
9981
e440a328 9982 bool
9983 do_is_addressable() const;
9984
9985 void
9986 do_address_taken(bool escapes)
9987 { this->array_->address_taken(escapes); }
9988
56080003 9989 void
9990 do_issue_nil_check()
9991 { this->array_->issue_nil_check(); }
9992
e440a328 9993 tree
9994 do_get_tree(Translate_context*);
9995
d751bb78 9996 void
9997 do_dump_expression(Ast_dump_context*) const;
9998
e440a328 9999 private:
10000 // The array we are getting a value from.
10001 Expression* array_;
10002 // The start or only index.
10003 Expression* start_;
10004 // The end index of a slice. This may be NULL for a simple array
10005 // index, or it may be a nil expression for the length of the array.
10006 Expression* end_;
acf2b673 10007 // The capacity argument of a slice. This may be NULL for an array index or
10008 // slice.
10009 Expression* cap_;
e440a328 10010 // The type of the expression.
10011 Type* type_;
10012};
10013
10014// Array index traversal.
10015
10016int
10017Array_index_expression::do_traverse(Traverse* traverse)
10018{
10019 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10020 return TRAVERSE_EXIT;
10021 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10022 return TRAVERSE_EXIT;
10023 if (this->end_ != NULL)
10024 {
10025 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10026 return TRAVERSE_EXIT;
10027 }
acf2b673 10028 if (this->cap_ != NULL)
10029 {
10030 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10031 return TRAVERSE_EXIT;
10032 }
e440a328 10033 return TRAVERSE_CONTINUE;
10034}
10035
10036// Return the type of an array index.
10037
10038Type*
10039Array_index_expression::do_type()
10040{
10041 if (this->type_ == NULL)
10042 {
10043 Array_type* type = this->array_->type()->array_type();
10044 if (type == NULL)
10045 this->type_ = Type::make_error_type();
10046 else if (this->end_ == NULL)
10047 this->type_ = type->element_type();
411eb89e 10048 else if (type->is_slice_type())
e440a328 10049 {
10050 // A slice of a slice has the same type as the original
10051 // slice.
10052 this->type_ = this->array_->type()->deref();
10053 }
10054 else
10055 {
10056 // A slice of an array is a slice.
10057 this->type_ = Type::make_array_type(type->element_type(), NULL);
10058 }
10059 }
10060 return this->type_;
10061}
10062
10063// Set the type of an array index.
10064
10065void
10066Array_index_expression::do_determine_type(const Type_context*)
10067{
10068 this->array_->determine_type_no_context();
7917ad68 10069 this->start_->determine_type_no_context();
e440a328 10070 if (this->end_ != NULL)
7917ad68 10071 this->end_->determine_type_no_context();
acf2b673 10072 if (this->cap_ != NULL)
10073 this->cap_->determine_type_no_context();
e440a328 10074}
10075
10076// Check types of an array index.
10077
10078void
10079Array_index_expression::do_check_types(Gogo*)
10080{
f6bc81e6 10081 Numeric_constant nc;
10082 unsigned long v;
10083 if (this->start_->type()->integer_type() == NULL
10084 && !this->start_->type()->is_error()
10085 && (!this->start_->numeric_constant_value(&nc)
10086 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10087 this->report_error(_("index must be integer"));
10088 if (this->end_ != NULL
10089 && this->end_->type()->integer_type() == NULL
99b3f06f 10090 && !this->end_->type()->is_error()
10091 && !this->end_->is_nil_expression()
f6bc81e6 10092 && !this->end_->is_error_expression()
10093 && (!this->end_->numeric_constant_value(&nc)
10094 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10095 this->report_error(_("slice end must be integer"));
acf2b673 10096 if (this->cap_ != NULL
10097 && this->cap_->type()->integer_type() == NULL
10098 && !this->cap_->type()->is_error()
10099 && !this->cap_->is_nil_expression()
10100 && !this->cap_->is_error_expression()
10101 && (!this->cap_->numeric_constant_value(&nc)
10102 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10103 this->report_error(_("slice capacity must be integer"));
e440a328 10104
10105 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10106 if (array_type == NULL)
10107 {
c484d925 10108 go_assert(this->array_->type()->is_error());
f9c68f17 10109 return;
10110 }
e440a328 10111
10112 unsigned int int_bits =
10113 Type::lookup_integer_type("int")->integer_type()->bits();
10114
0c77715b 10115 Numeric_constant lvalnc;
e440a328 10116 mpz_t lval;
e440a328 10117 bool lval_valid = (array_type->length() != NULL
0c77715b 10118 && array_type->length()->numeric_constant_value(&lvalnc)
10119 && lvalnc.to_int(&lval));
10120 Numeric_constant inc;
e440a328 10121 mpz_t ival;
0bd5d859 10122 bool ival_valid = false;
0c77715b 10123 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10124 {
0bd5d859 10125 ival_valid = true;
e440a328 10126 if (mpz_sgn(ival) < 0
10127 || mpz_sizeinbase(ival, 2) >= int_bits
10128 || (lval_valid
10129 && (this->end_ == NULL
10130 ? mpz_cmp(ival, lval) >= 0
10131 : mpz_cmp(ival, lval) > 0)))
10132 {
10133 error_at(this->start_->location(), "array index out of bounds");
10134 this->set_is_error();
10135 }
10136 }
10137 if (this->end_ != NULL && !this->end_->is_nil_expression())
10138 {
0c77715b 10139 Numeric_constant enc;
10140 mpz_t eval;
acf2b673 10141 bool eval_valid = false;
0c77715b 10142 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10143 {
acf2b673 10144 eval_valid = true;
0c77715b 10145 if (mpz_sgn(eval) < 0
10146 || mpz_sizeinbase(eval, 2) >= int_bits
10147 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10148 {
10149 error_at(this->end_->location(), "array index out of bounds");
10150 this->set_is_error();
10151 }
0bd5d859 10152 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10153 this->report_error(_("inverted slice range"));
e440a328 10154 }
acf2b673 10155
10156 Numeric_constant cnc;
10157 mpz_t cval;
10158 if (this->cap_ != NULL
10159 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10160 {
10161 if (mpz_sgn(cval) < 0
10162 || mpz_sizeinbase(cval, 2) >= int_bits
10163 || (lval_valid && mpz_cmp(cval, lval) > 0))
10164 {
10165 error_at(this->cap_->location(), "array index out of bounds");
10166 this->set_is_error();
10167 }
10168 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10169 {
10170 error_at(this->cap_->location(),
10171 "invalid slice index: capacity less than start");
10172 this->set_is_error();
10173 }
10174 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10175 {
10176 error_at(this->cap_->location(),
10177 "invalid slice index: capacity less than length");
10178 this->set_is_error();
10179 }
10180 mpz_clear(cval);
10181 }
10182
10183 if (eval_valid)
10184 mpz_clear(eval);
e440a328 10185 }
0bd5d859 10186 if (ival_valid)
10187 mpz_clear(ival);
0c77715b 10188 if (lval_valid)
10189 mpz_clear(lval);
e440a328 10190
10191 // A slice of an array requires an addressable array. A slice of a
10192 // slice is always possible.
411eb89e 10193 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10194 {
10195 if (!this->array_->is_addressable())
8da39c3b 10196 this->report_error(_("slice of unaddressable value"));
88ec30c8 10197 else
10198 this->array_->address_taken(true);
10199 }
e440a328 10200}
10201
2c809f8f 10202// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10203
10204Expression*
10205Array_index_expression::do_flatten(Gogo*, Named_object*,
10206 Statement_inserter* inserter)
10207{
10208 Location loc = this->location();
2c809f8f 10209 Temporary_statement* temp;
35a54f17 10210 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10211 {
2c809f8f 10212 temp = Statement::make_temporary(NULL, this->array_, loc);
35a54f17 10213 inserter->insert(temp);
10214 this->array_ = Expression::make_temporary_reference(temp, loc);
10215 }
2c809f8f 10216 if (!this->start_->is_variable())
10217 {
10218 temp = Statement::make_temporary(NULL, this->start_, loc);
10219 inserter->insert(temp);
10220 this->start_ = Expression::make_temporary_reference(temp, loc);
10221 }
10222 if (this->end_ != NULL
10223 && !this->end_->is_nil_expression()
10224 && !this->end_->is_variable())
10225 {
10226 temp = Statement::make_temporary(NULL, this->end_, loc);
10227 inserter->insert(temp);
10228 this->end_ = Expression::make_temporary_reference(temp, loc);
10229 }
10230 if (this->cap_ != NULL && !this->cap_->is_variable())
10231 {
10232 temp = Statement::make_temporary(NULL, this->cap_, loc);
10233 inserter->insert(temp);
10234 this->cap_ = Expression::make_temporary_reference(temp, loc);
10235 }
10236
35a54f17 10237 return this;
10238}
10239
e440a328 10240// Return whether this expression is addressable.
10241
10242bool
10243Array_index_expression::do_is_addressable() const
10244{
10245 // A slice expression is not addressable.
10246 if (this->end_ != NULL)
10247 return false;
10248
10249 // An index into a slice is addressable.
411eb89e 10250 if (this->array_->type()->is_slice_type())
e440a328 10251 return true;
10252
10253 // An index into an array is addressable if the array is
10254 // addressable.
10255 return this->array_->is_addressable();
10256}
10257
10258// Get a tree for an array index.
10259
10260tree
10261Array_index_expression::do_get_tree(Translate_context* context)
10262{
e440a328 10263 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10264 if (array_type == NULL)
10265 {
c484d925 10266 go_assert(this->array_->type()->is_error());
d8cd8e2d 10267 return error_mark_node;
10268 }
35a54f17 10269 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10270
2c809f8f 10271 Location loc = this->location();
10272 Gogo* gogo = context->gogo();
10273
10274 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
e440a328 10275
2c809f8f 10276 // We need to convert the length and capacity to the Go "int" type here
10277 // because the length of a fixed-length array could be of type "uintptr"
10278 // and gimple disallows binary operations between "uintptr" and other
10279 // integer types. FIXME.
10280 Bexpression* length = NULL;
a04bfdfc 10281 if (this->end_ == NULL || this->end_->is_nil_expression())
10282 {
35a54f17 10283 Expression* len = array_type->get_length(gogo, this->array_);
2c809f8f 10284 length = tree_to_expr(len->get_tree(context));
10285 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10286 }
10287
2c809f8f 10288 Bexpression* capacity = NULL;
a04bfdfc 10289 if (this->end_ != NULL)
10290 {
35a54f17 10291 Expression* cap = array_type->get_capacity(gogo, this->array_);
2c809f8f 10292 capacity = tree_to_expr(cap->get_tree(context));
10293 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10294 }
10295
2c809f8f 10296 Bexpression* cap_arg = capacity;
acf2b673 10297 if (this->cap_ != NULL)
10298 {
2c809f8f 10299 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10300 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10301 }
10302
2c809f8f 10303 if (length == NULL)
10304 length = cap_arg;
e440a328 10305
10306 int code = (array_type->length() != NULL
10307 ? (this->end_ == NULL
10308 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10309 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10310 : (this->end_ == NULL
10311 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10312 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
2c809f8f 10313 Bexpression* crash =
10314 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10315
10316 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10317 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10318
10319 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10320 start = gogo->backend()->convert_expression(int_btype, start, loc);
10321 Bexpression* start_too_large =
10322 gogo->backend()->binary_expression((this->end_ == NULL
10323 ? OPERATOR_GE
10324 : OPERATOR_GT),
10325 start,
10326 (this->end_ == NULL
10327 ? length
10328 : capacity),
10329 loc);
10330 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10331 bad_index, loc);
e440a328 10332
10333 if (this->end_ == NULL)
10334 {
10335 // Simple array indexing. This has to return an l-value, so
2c809f8f 10336 // wrap the index check into START.
10337 start =
10338 gogo->backend()->conditional_expression(int_btype, bad_index,
10339 crash, start, loc);
e440a328 10340
2c809f8f 10341 Bexpression* ret;
e440a328 10342 if (array_type->length() != NULL)
10343 {
2c809f8f 10344 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10345 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10346 }
10347 else
10348 {
2c809f8f 10349 // Slice.
10350 Expression* valptr =
35a54f17 10351 array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10352 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10353 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 10354
10355 Type* ele_type = this->array_->type()->array_type()->element_type();
10356 Btype* ele_btype = ele_type->get_backend(gogo);
10357 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 10358 }
2c809f8f 10359 return expr_to_tree(ret);
e440a328 10360 }
10361
10362 // Array slice.
10363
acf2b673 10364 if (this->cap_ != NULL)
10365 {
2c809f8f 10366 bounds_check = Expression::check_bounds(this->cap_, loc);
10367 Bexpression* bounds_bcheck =
10368 tree_to_expr(bounds_check->get_tree(context));
10369 bad_index =
10370 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10371 bad_index, loc);
10372 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10373
10374 Bexpression* cap_too_small =
10375 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10376 Bexpression* cap_too_large =
10377 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10378 Bexpression* bad_cap =
10379 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10380 cap_too_large, loc);
10381 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10382 bad_index, loc);
10383 }
10384
10385 Bexpression* end;
e440a328 10386 if (this->end_->is_nil_expression())
2c809f8f 10387 end = length;
e440a328 10388 else
10389 {
2c809f8f 10390 bounds_check = Expression::check_bounds(this->end_, loc);
10391 Bexpression* bounds_bcheck =
10392 tree_to_expr(bounds_check->get_tree(context));
e440a328 10393
2c809f8f 10394 bad_index =
10395 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10396 bad_index, loc);
e440a328 10397
2c809f8f 10398 end = tree_to_expr(this->end_->get_tree(context));
10399 end = gogo->backend()->convert_expression(int_btype, end, loc);
10400 Bexpression* end_too_small =
10401 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10402 Bexpression* end_too_large =
10403 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10404 Bexpression* bad_end =
10405 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10406 end_too_large, loc);
10407 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10408 bad_index, loc);
e440a328 10409 }
10410
35a54f17 10411 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10412 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10413 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10414
2c809f8f 10415 Bexpression* result_length =
10416 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10417
2c809f8f 10418 Bexpression* result_capacity =
10419 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10420
2c809f8f 10421 Btype* struct_btype = this->type()->get_backend(gogo);
10422 std::vector<Bexpression*> init;
10423 init.push_back(val);
10424 init.push_back(result_length);
10425 init.push_back(result_capacity);
e440a328 10426
2c809f8f 10427 Bexpression* ctor =
10428 gogo->backend()->constructor_expression(struct_btype, init, loc);
10429 Bexpression* ret =
10430 gogo->backend()->conditional_expression(struct_btype, bad_index,
10431 crash, ctor, loc);
e440a328 10432
2c809f8f 10433 return expr_to_tree(ret);
e440a328 10434}
10435
d751bb78 10436// Dump ast representation for an array index expression.
10437
10438void
10439Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10440 const
10441{
10442 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10443 this->start_, this->end_, this->cap_);
d751bb78 10444}
10445
acf2b673 10446// Make an array index expression. END and CAP may be NULL.
e440a328 10447
10448Expression*
10449Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10450 Expression* end, Expression* cap,
10451 Location location)
e440a328 10452{
acf2b673 10453 return new Array_index_expression(array, start, end, cap, location);
e440a328 10454}
10455
10456// A string index. This is used for both indexing and slicing.
10457
10458class String_index_expression : public Expression
10459{
10460 public:
10461 String_index_expression(Expression* string, Expression* start,
b13c66cd 10462 Expression* end, Location location)
e440a328 10463 : Expression(EXPRESSION_STRING_INDEX, location),
10464 string_(string), start_(start), end_(end)
10465 { }
10466
10467 protected:
10468 int
10469 do_traverse(Traverse*);
10470
2c809f8f 10471 Expression*
10472 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10473
e440a328 10474 Type*
10475 do_type();
10476
10477 void
10478 do_determine_type(const Type_context*);
10479
10480 void
10481 do_check_types(Gogo*);
10482
10483 Expression*
10484 do_copy()
10485 {
10486 return Expression::make_string_index(this->string_->copy(),
10487 this->start_->copy(),
10488 (this->end_ == NULL
10489 ? NULL
10490 : this->end_->copy()),
10491 this->location());
10492 }
10493
baef9f7a 10494 bool
10495 do_must_eval_subexpressions_in_order(int* skip) const
10496 {
10497 *skip = 1;
10498 return true;
10499 }
10500
e440a328 10501 tree
10502 do_get_tree(Translate_context*);
10503
d751bb78 10504 void
10505 do_dump_expression(Ast_dump_context*) const;
10506
e440a328 10507 private:
10508 // The string we are getting a value from.
10509 Expression* string_;
10510 // The start or only index.
10511 Expression* start_;
10512 // The end index of a slice. This may be NULL for a single index,
10513 // or it may be a nil expression for the length of the string.
10514 Expression* end_;
10515};
10516
10517// String index traversal.
10518
10519int
10520String_index_expression::do_traverse(Traverse* traverse)
10521{
10522 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10523 return TRAVERSE_EXIT;
10524 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10525 return TRAVERSE_EXIT;
10526 if (this->end_ != NULL)
10527 {
10528 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10529 return TRAVERSE_EXIT;
10530 }
10531 return TRAVERSE_CONTINUE;
10532}
10533
2c809f8f 10534Expression*
10535String_index_expression::do_flatten(Gogo*, Named_object*,
10536 Statement_inserter* inserter)
e440a328 10537{
2c809f8f 10538 Temporary_statement* temp;
10539 Location loc = this->location();
10540 if (!this->string_->is_variable())
10541 {
10542 temp = Statement::make_temporary(NULL, this->string_, loc);
10543 inserter->insert(temp);
10544 this->string_ = Expression::make_temporary_reference(temp, loc);
10545 }
10546 if (!this->start_->is_variable())
10547 {
10548 temp = Statement::make_temporary(NULL, this->start_, loc);
10549 inserter->insert(temp);
10550 this->start_ = Expression::make_temporary_reference(temp, loc);
10551 }
10552 if (this->end_ != NULL
10553 && !this->end_->is_nil_expression()
10554 && !this->end_->is_variable())
10555 {
10556 temp = Statement::make_temporary(NULL, this->end_, loc);
10557 inserter->insert(temp);
10558 this->end_ = Expression::make_temporary_reference(temp, loc);
10559 }
10560
10561 return this;
10562}
10563
10564// Return the type of a string index.
10565
10566Type*
10567String_index_expression::do_type()
10568{
10569 if (this->end_ == NULL)
10570 return Type::lookup_integer_type("uint8");
10571 else
10572 return this->string_->type();
10573}
10574
10575// Determine the type of a string index.
10576
10577void
10578String_index_expression::do_determine_type(const Type_context*)
10579{
10580 this->string_->determine_type_no_context();
10581 this->start_->determine_type_no_context();
e440a328 10582 if (this->end_ != NULL)
93000773 10583 this->end_->determine_type_no_context();
e440a328 10584}
10585
10586// Check types of a string index.
10587
10588void
10589String_index_expression::do_check_types(Gogo*)
10590{
acdc230d 10591 Numeric_constant nc;
10592 unsigned long v;
10593 if (this->start_->type()->integer_type() == NULL
10594 && !this->start_->type()->is_error()
10595 && (!this->start_->numeric_constant_value(&nc)
10596 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10597 this->report_error(_("index must be integer"));
10598 if (this->end_ != NULL
10599 && this->end_->type()->integer_type() == NULL
acdc230d 10600 && !this->end_->type()->is_error()
10601 && !this->end_->is_nil_expression()
10602 && !this->end_->is_error_expression()
10603 && (!this->end_->numeric_constant_value(&nc)
10604 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10605 this->report_error(_("slice end must be integer"));
10606
10607 std::string sval;
10608 bool sval_valid = this->string_->string_constant_value(&sval);
10609
0c77715b 10610 Numeric_constant inc;
e440a328 10611 mpz_t ival;
0bd5d859 10612 bool ival_valid = false;
0c77715b 10613 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10614 {
0bd5d859 10615 ival_valid = true;
e440a328 10616 if (mpz_sgn(ival) < 0
10617 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10618 {
10619 error_at(this->start_->location(), "string index out of bounds");
10620 this->set_is_error();
10621 }
10622 }
10623 if (this->end_ != NULL && !this->end_->is_nil_expression())
10624 {
0c77715b 10625 Numeric_constant enc;
10626 mpz_t eval;
10627 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10628 {
0c77715b 10629 if (mpz_sgn(eval) < 0
10630 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 10631 {
10632 error_at(this->end_->location(), "string index out of bounds");
10633 this->set_is_error();
10634 }
0bd5d859 10635 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10636 this->report_error(_("inverted slice range"));
0c77715b 10637 mpz_clear(eval);
e440a328 10638 }
10639 }
0bd5d859 10640 if (ival_valid)
10641 mpz_clear(ival);
e440a328 10642}
10643
10644// Get a tree for a string index.
10645
10646tree
10647String_index_expression::do_get_tree(Translate_context* context)
10648{
b13c66cd 10649 Location loc = this->location();
2c809f8f 10650 Expression* string_arg = this->string_;
10651 if (this->string_->type()->points_to() != NULL)
10652 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 10653
2c809f8f 10654 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 10655
2c809f8f 10656 int code = (this->end_ == NULL
10657 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10658 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 10659
2c809f8f 10660 Gogo* gogo = context->gogo();
10661 Bexpression* crash =
10662 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
1b1f2abf 10663
10664 Type* int_type = Type::lookup_integer_type("int");
e440a328 10665
2c809f8f 10666 // It is possible that an error occurred earlier because the start index
10667 // cannot be represented as an integer type. In this case, we shouldn't
10668 // try casting the starting index into an integer since
10669 // Type_conversion_expression will fail to get the backend representation.
10670 // FIXME.
10671 if (this->start_->type()->integer_type() == NULL
10672 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10673 {
10674 go_assert(saw_errors());
10675 return error_mark_node;
10676 }
e440a328 10677
2c809f8f 10678 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 10679
2c809f8f 10680 if (this->end_ == NULL)
10681 {
10682 Expression* length =
10683 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 10684
2c809f8f 10685 Expression* start_too_large =
10686 Expression::make_binary(OPERATOR_GE, start, length, loc);
10687 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10688 bad_index, loc);
10689 Expression* bytes =
10690 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 10691
2c809f8f 10692 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10693 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10694 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 10695 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10696 Bexpression* index =
10697 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 10698
2c809f8f 10699 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10700 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10701 Bexpression* ret =
10702 gogo->backend()->conditional_expression(byte_btype, index_error,
10703 crash, index, loc);
10704 return expr_to_tree(ret);
10705 }
10706
10707 Expression* end = NULL;
10708 if (this->end_->is_nil_expression())
e440a328 10709 {
2c809f8f 10710 mpz_t neg_one;
10711 mpz_init_set_si(neg_one, -1);
10712 end = Expression::make_integer(&neg_one, int_type, loc);
10713 mpz_clear(neg_one);
e440a328 10714 }
10715 else
10716 {
2c809f8f 10717 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10718 bad_index =
10719 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10720 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 10721 }
2c809f8f 10722
10723 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10724 string_arg, start, end);
10725 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10726
10727 Btype* str_btype = strslice->type()->get_backend(gogo);
10728 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10729 Bexpression* ret =
10730 gogo->backend()->conditional_expression(str_btype, index_error,
10731 crash, bstrslice, loc);
10732 return expr_to_tree(ret);
e440a328 10733}
10734
d751bb78 10735// Dump ast representation for a string index expression.
10736
10737void
10738String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10739 const
10740{
acf2b673 10741 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10742 this->start_, this->end_, NULL);
d751bb78 10743}
10744
e440a328 10745// Make a string index expression. END may be NULL.
10746
10747Expression*
10748Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 10749 Expression* end, Location location)
e440a328 10750{
10751 return new String_index_expression(string, start, end, location);
10752}
10753
10754// Class Map_index.
10755
10756// Get the type of the map.
10757
10758Map_type*
10759Map_index_expression::get_map_type() const
10760{
10761 Map_type* mt = this->map_->type()->deref()->map_type();
c7524fae 10762 if (mt == NULL)
c484d925 10763 go_assert(saw_errors());
e440a328 10764 return mt;
10765}
10766
10767// Map index traversal.
10768
10769int
10770Map_index_expression::do_traverse(Traverse* traverse)
10771{
10772 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10773 return TRAVERSE_EXIT;
10774 return Expression::traverse(&this->index_, traverse);
10775}
10776
2c809f8f 10777// We need to pass in a pointer to the key, so flatten the index into a
10778// temporary variable if it isn't already. The value pointer will be
10779// dereferenced and checked for nil, so flatten into a temporary to avoid
10780// recomputation.
10781
10782Expression*
10783Map_index_expression::do_flatten(Gogo*, Named_object*,
10784 Statement_inserter* inserter)
10785{
10786 Map_type* mt = this->get_map_type();
10787 if (this->index_->type() != mt->key_type())
10788 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10789 this->location());
10790
10791 if (!this->index_->is_variable())
10792 {
10793 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10794 this->location());
10795 inserter->insert(temp);
10796 this->index_ = Expression::make_temporary_reference(temp,
10797 this->location());
10798 }
10799
10800 if (this->value_pointer_ == NULL)
10801 this->get_value_pointer(this->is_lvalue_);
10802 if (!this->value_pointer_->is_variable())
10803 {
10804 Temporary_statement* temp =
10805 Statement::make_temporary(NULL, this->value_pointer_,
10806 this->location());
10807 inserter->insert(temp);
10808 this->value_pointer_ =
10809 Expression::make_temporary_reference(temp, this->location());
10810 }
10811
10812 return this;
10813}
10814
e440a328 10815// Return the type of a map index.
10816
10817Type*
10818Map_index_expression::do_type()
10819{
c7524fae 10820 Map_type* mt = this->get_map_type();
10821 if (mt == NULL)
10822 return Type::make_error_type();
10823 Type* type = mt->val_type();
e440a328 10824 // If this map index is in a tuple assignment, we actually return a
10825 // pointer to the value type. Tuple_map_assignment_statement is
10826 // responsible for handling this correctly. We need to get the type
10827 // right in case this gets assigned to a temporary variable.
10828 if (this->is_in_tuple_assignment_)
10829 type = Type::make_pointer_type(type);
10830 return type;
10831}
10832
10833// Fix the type of a map index.
10834
10835void
10836Map_index_expression::do_determine_type(const Type_context*)
10837{
10838 this->map_->determine_type_no_context();
c7524fae 10839 Map_type* mt = this->get_map_type();
10840 Type* key_type = mt == NULL ? NULL : mt->key_type();
10841 Type_context subcontext(key_type, false);
e440a328 10842 this->index_->determine_type(&subcontext);
10843}
10844
10845// Check types of a map index.
10846
10847void
10848Map_index_expression::do_check_types(Gogo*)
10849{
10850 std::string reason;
c7524fae 10851 Map_type* mt = this->get_map_type();
10852 if (mt == NULL)
10853 return;
10854 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 10855 {
10856 if (reason.empty())
10857 this->report_error(_("incompatible type for map index"));
10858 else
10859 {
10860 error_at(this->location(), "incompatible type for map index (%s)",
10861 reason.c_str());
10862 this->set_is_error();
10863 }
10864 }
10865}
10866
10867// Get a tree for a map index.
10868
10869tree
10870Map_index_expression::do_get_tree(Translate_context* context)
10871{
10872 Map_type* type = this->get_map_type();
c7524fae 10873 if (type == NULL)
2c809f8f 10874 {
10875 go_assert(saw_errors());
10876 return error_mark_node;
10877 }
e440a328 10878
2c809f8f 10879 go_assert(this->value_pointer_ != NULL
10880 && this->value_pointer_->is_variable());
e440a328 10881
2c809f8f 10882 Bexpression* ret;
e440a328 10883 if (this->is_lvalue_)
2c809f8f 10884 {
10885 Expression* val =
10886 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10887 this->location());
10888 ret = tree_to_expr(val->get_tree(context));
10889 }
e440a328 10890 else if (this->is_in_tuple_assignment_)
10891 {
10892 // Tuple_map_assignment_statement is responsible for using this
10893 // appropriately.
2c809f8f 10894 ret = tree_to_expr(this->value_pointer_->get_tree(context));
e440a328 10895 }
10896 else
10897 {
2c809f8f 10898 Location loc = this->location();
10899
10900 Expression* nil_check =
10901 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10902 Expression::make_nil(loc), loc);
10903 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10904 Expression* val =
10905 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10906 Bexpression* bval = tree_to_expr(val->get_tree(context));
10907
63697958 10908 Gogo* gogo = context->gogo();
10909 Btype* val_btype = type->val_type()->get_backend(gogo);
10910 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
2c809f8f 10911 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10912 val_zero, bval, loc);
e440a328 10913 }
2c809f8f 10914
10915 return expr_to_tree(ret);
e440a328 10916}
10917
2c809f8f 10918// Get an expression for the map index. This returns an expression which
10919// evaluates to a pointer to a value. The pointer will be NULL if the key is
e440a328 10920// not in the map.
10921
2c809f8f 10922Expression*
10923Map_index_expression::get_value_pointer(bool insert)
e440a328 10924{
2c809f8f 10925 if (this->value_pointer_ == NULL)
746d2e73 10926 {
2c809f8f 10927 Map_type* type = this->get_map_type();
10928 if (type == NULL)
746d2e73 10929 {
2c809f8f 10930 go_assert(saw_errors());
10931 return Expression::make_error(this->location());
746d2e73 10932 }
e440a328 10933
2c809f8f 10934 Location loc = this->location();
10935 Expression* map_ref = this->map_;
10936 if (this->map_->type()->points_to() != NULL)
10937 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
e440a328 10938
2c809f8f 10939 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10940 loc);
10941 Expression* map_index =
10942 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10943 map_ref, index_ptr,
10944 Expression::make_boolean(insert, loc));
10945
10946 Type* val_type = type->val_type();
10947 this->value_pointer_ =
10948 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10949 map_index, this->location());
10950 }
10951 return this->value_pointer_;
e440a328 10952}
10953
d751bb78 10954// Dump ast representation for a map index expression
10955
10956void
10957Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10958 const
10959{
acf2b673 10960 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10961 this->index_, NULL, NULL);
d751bb78 10962}
10963
e440a328 10964// Make a map index expression.
10965
10966Map_index_expression*
10967Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 10968 Location location)
e440a328 10969{
10970 return new Map_index_expression(map, index, location);
10971}
10972
10973// Class Field_reference_expression.
10974
149eabc5 10975// Lower a field reference expression. There is nothing to lower, but
10976// this is where we generate the tracking information for fields with
10977// the magic go:"track" tag.
10978
10979Expression*
10980Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10981 Statement_inserter* inserter, int)
10982{
10983 Struct_type* struct_type = this->expr_->type()->struct_type();
10984 if (struct_type == NULL)
10985 {
10986 // Error will be reported elsewhere.
10987 return this;
10988 }
10989 const Struct_field* field = struct_type->field(this->field_index_);
10990 if (field == NULL)
10991 return this;
10992 if (!field->has_tag())
10993 return this;
10994 if (field->tag().find("go:\"track\"") == std::string::npos)
10995 return this;
10996
10997 // We have found a reference to a tracked field. Build a call to
10998 // the runtime function __go_fieldtrack with a string that describes
10999 // the field. FIXME: We should only call this once per referenced
11000 // field per function, not once for each reference to the field.
11001
11002 if (this->called_fieldtrack_)
11003 return this;
11004 this->called_fieldtrack_ = true;
11005
11006 Location loc = this->location();
11007
11008 std::string s = "fieldtrack \"";
11009 Named_type* nt = this->expr_->type()->named_type();
11010 if (nt == NULL || nt->named_object()->package() == NULL)
11011 s.append(gogo->pkgpath());
11012 else
11013 s.append(nt->named_object()->package()->pkgpath());
11014 s.push_back('.');
11015 if (nt != NULL)
5c29ad36 11016 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11017 s.push_back('.');
11018 s.append(field->field_name());
11019 s.push_back('"');
11020
11021 // We can't use a string here, because internally a string holds a
11022 // pointer to the actual bytes; when the linker garbage collects the
11023 // string, it won't garbage collect the bytes. So we use a
11024 // [...]byte.
11025
11026 mpz_t val;
11027 mpz_init_set_ui(val, s.length());
11028 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11029 mpz_clear(val);
11030
11031 Type* byte_type = gogo->lookup_global("byte")->type_value();
11032 Type* array_type = Type::make_array_type(byte_type, length_expr);
11033
11034 Expression_list* bytes = new Expression_list();
11035 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11036 {
11037 mpz_init_set_ui(val, *p);
11038 Expression* byte = Expression::make_integer(&val, NULL, loc);
11039 mpz_clear(val);
11040 bytes->push_back(byte);
11041 }
11042
11043 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11044 bytes, false, loc);
149eabc5 11045
11046 Variable* var = new Variable(array_type, e, true, false, false, loc);
11047
11048 static int count;
11049 char buf[50];
11050 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11051 ++count;
11052
11053 Named_object* no = gogo->add_variable(buf, var);
11054 e = Expression::make_var_reference(no, loc);
11055 e = Expression::make_unary(OPERATOR_AND, e, loc);
11056
11057 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11058 inserter->insert(Statement::make_statement(call, false));
11059
11060 // Put this function, and the global variable we just created, into
11061 // unique sections. This will permit the linker to garbage collect
11062 // them if they are not referenced. The effect is that the only
11063 // strings, indicating field references, that will wind up in the
11064 // executable will be those for functions that are actually needed.
66a6be58 11065 if (function != NULL)
11066 function->func_value()->set_in_unique_section();
149eabc5 11067 var->set_in_unique_section();
11068
11069 return this;
11070}
11071
e440a328 11072// Return the type of a field reference.
11073
11074Type*
11075Field_reference_expression::do_type()
11076{
b0e628fb 11077 Type* type = this->expr_->type();
5c13bd80 11078 if (type->is_error())
b0e628fb 11079 return type;
11080 Struct_type* struct_type = type->struct_type();
c484d925 11081 go_assert(struct_type != NULL);
e440a328 11082 return struct_type->field(this->field_index_)->type();
11083}
11084
11085// Check the types for a field reference.
11086
11087void
11088Field_reference_expression::do_check_types(Gogo*)
11089{
b0e628fb 11090 Type* type = this->expr_->type();
5c13bd80 11091 if (type->is_error())
b0e628fb 11092 return;
11093 Struct_type* struct_type = type->struct_type();
c484d925 11094 go_assert(struct_type != NULL);
11095 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11096}
11097
11098// Get a tree for a field reference.
11099
11100tree
11101Field_reference_expression::do_get_tree(Translate_context* context)
11102{
fbb851c5 11103 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11104 Bexpression* ret =
11105 context->gogo()->backend()->struct_field_expression(bstruct,
11106 this->field_index_,
11107 this->location());
11108 return expr_to_tree(ret);
e440a328 11109}
11110
d751bb78 11111// Dump ast representation for a field reference expression.
11112
11113void
11114Field_reference_expression::do_dump_expression(
11115 Ast_dump_context* ast_dump_context) const
11116{
11117 this->expr_->dump_expression(ast_dump_context);
11118 ast_dump_context->ostream() << "." << this->field_index_;
11119}
11120
e440a328 11121// Make a reference to a qualified identifier in an expression.
11122
11123Field_reference_expression*
11124Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11125 Location location)
e440a328 11126{
11127 return new Field_reference_expression(expr, field_index, location);
11128}
11129
11130// Class Interface_field_reference_expression.
11131
2387f644 11132// Return an expression for the pointer to the function to call.
e440a328 11133
2387f644 11134Expression*
11135Interface_field_reference_expression::get_function()
e440a328 11136{
2387f644 11137 Expression* ref = this->expr_;
11138 Location loc = this->location();
11139 if (ref->type()->points_to() != NULL)
11140 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11141
2387f644 11142 Expression* mtable =
11143 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11144 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11145
11146 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11147 unsigned int index;
11148 const Struct_field* field = mtable_type->find_local_field(name, &index);
11149 go_assert(field != NULL);
11150 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11151 return Expression::make_field_reference(mtable, index, loc);
e440a328 11152}
11153
2387f644 11154// Return an expression for the first argument to pass to the interface
e440a328 11155// function.
11156
2387f644 11157Expression*
11158Interface_field_reference_expression::get_underlying_object()
e440a328 11159{
2387f644 11160 Expression* expr = this->expr_;
11161 if (expr->type()->points_to() != NULL)
11162 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11163 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11164 this->location());
e440a328 11165}
11166
11167// Traversal.
11168
11169int
11170Interface_field_reference_expression::do_traverse(Traverse* traverse)
11171{
11172 return Expression::traverse(&this->expr_, traverse);
11173}
11174
0afbb937 11175// Lower the expression. If this expression is not called, we need to
11176// evaluate the expression twice when converting to the backend
11177// interface. So introduce a temporary variable if necessary.
11178
11179Expression*
11180Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11181 Statement_inserter* inserter,
11182 int)
11183{
2387f644 11184 if (!this->expr_->is_variable())
0afbb937 11185 {
11186 Temporary_statement* temp =
11187 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11188 inserter->insert(temp);
11189 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11190 this->location());
11191 }
11192 return this;
11193}
11194
e440a328 11195// Return the type of an interface field reference.
11196
11197Type*
11198Interface_field_reference_expression::do_type()
11199{
11200 Type* expr_type = this->expr_->type();
11201
11202 Type* points_to = expr_type->points_to();
11203 if (points_to != NULL)
11204 expr_type = points_to;
11205
11206 Interface_type* interface_type = expr_type->interface_type();
11207 if (interface_type == NULL)
11208 return Type::make_error_type();
11209
11210 const Typed_identifier* method = interface_type->find_method(this->name_);
11211 if (method == NULL)
11212 return Type::make_error_type();
11213
11214 return method->type();
11215}
11216
11217// Determine types.
11218
11219void
11220Interface_field_reference_expression::do_determine_type(const Type_context*)
11221{
11222 this->expr_->determine_type_no_context();
11223}
11224
11225// Check the types for an interface field reference.
11226
11227void
11228Interface_field_reference_expression::do_check_types(Gogo*)
11229{
11230 Type* type = this->expr_->type();
11231
11232 Type* points_to = type->points_to();
11233 if (points_to != NULL)
11234 type = points_to;
11235
11236 Interface_type* interface_type = type->interface_type();
11237 if (interface_type == NULL)
5c491127 11238 {
11239 if (!type->is_error_type())
11240 this->report_error(_("expected interface or pointer to interface"));
11241 }
e440a328 11242 else
11243 {
11244 const Typed_identifier* method =
11245 interface_type->find_method(this->name_);
11246 if (method == NULL)
11247 {
11248 error_at(this->location(), "method %qs not in interface",
11249 Gogo::message_name(this->name_).c_str());
11250 this->set_is_error();
11251 }
11252 }
11253}
11254
0afbb937 11255// If an interface field reference is not simply called, then it is
11256// represented as a closure. The closure will hold a single variable,
11257// the value of the interface on which the method should be called.
11258// The function will be a simple thunk that pulls the value from the
11259// closure and calls the method with the remaining arguments.
11260
11261// Because method values are not common, we don't build all thunks for
11262// all possible interface methods, but instead only build them as we
11263// need them. In particular, we even build them on demand for
11264// interface methods defined in other packages.
11265
11266Interface_field_reference_expression::Interface_method_thunks
11267 Interface_field_reference_expression::interface_method_thunks;
11268
11269// Find or create the thunk to call method NAME on TYPE.
11270
11271Named_object*
11272Interface_field_reference_expression::create_thunk(Gogo* gogo,
11273 Interface_type* type,
11274 const std::string& name)
11275{
11276 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11277 std::pair<Interface_method_thunks::iterator, bool> ins =
11278 Interface_field_reference_expression::interface_method_thunks.insert(val);
11279 if (ins.second)
11280 {
11281 // This is the first time we have seen this interface.
11282 ins.first->second = new Method_thunks();
11283 }
11284
11285 for (Method_thunks::const_iterator p = ins.first->second->begin();
11286 p != ins.first->second->end();
11287 p++)
11288 if (p->first == name)
11289 return p->second;
11290
11291 Location loc = type->location();
11292
11293 const Typed_identifier* method_id = type->find_method(name);
11294 if (method_id == NULL)
11295 return Named_object::make_erroneous_name(Gogo::thunk_name());
11296
11297 Function_type* orig_fntype = method_id->type()->function_type();
11298 if (orig_fntype == NULL)
11299 return Named_object::make_erroneous_name(Gogo::thunk_name());
11300
11301 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11302 // The type here is wrong--it should be the C function type. But it
11303 // doesn't really matter.
0afbb937 11304 Type* vt = Type::make_pointer_type(Type::make_void_type());
11305 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11306 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11307 Type* closure_type = Type::make_struct_type(sfl, loc);
11308 closure_type = Type::make_pointer_type(closure_type);
11309
f8bdf81a 11310 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11311
11312 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11313 false, loc);
11314
f8bdf81a 11315 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11316 cvar->set_is_used();
11317 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11318 new_no->func_value()->set_closure_var(cp);
0afbb937 11319
f8bdf81a 11320 gogo->start_block(loc);
0afbb937 11321
11322 // Field 0 of the closure is the function code pointer, field 1 is
11323 // the value on which to invoke the method.
11324 Expression* arg = Expression::make_var_reference(cp, loc);
11325 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11326 arg = Expression::make_field_reference(arg, 1, loc);
11327
11328 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11329 loc);
11330
11331 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11332 Expression_list* args;
11333 if (orig_params == NULL || orig_params->empty())
11334 args = NULL;
11335 else
11336 {
11337 const Typed_identifier_list* new_params = new_fntype->parameters();
11338 args = new Expression_list();
11339 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11340 p != new_params->end();
0afbb937 11341 ++p)
11342 {
11343 Named_object* p_no = gogo->lookup(p->name(), NULL);
11344 go_assert(p_no != NULL
11345 && p_no->is_variable()
11346 && p_no->var_value()->is_parameter());
11347 args->push_back(Expression::make_var_reference(p_no, loc));
11348 }
11349 }
11350
11351 Call_expression* call = Expression::make_call(ifre, args,
11352 orig_fntype->is_varargs(),
11353 loc);
11354 call->set_varargs_are_lowered();
11355
11356 Statement* s = Statement::make_return_from_call(call, loc);
11357 gogo->add_statement(s);
11358 Block* b = gogo->finish_block(loc);
11359 gogo->add_block(b, loc);
11360 gogo->lower_block(new_no, b);
a32698ee 11361 gogo->flatten_block(new_no, b);
0afbb937 11362 gogo->finish_function(loc);
11363
11364 ins.first->second->push_back(std::make_pair(name, new_no));
11365 return new_no;
11366}
11367
11368// Get a tree for a method value.
e440a328 11369
11370tree
0afbb937 11371Interface_field_reference_expression::do_get_tree(Translate_context* context)
e440a328 11372{
0afbb937 11373 Interface_type* type = this->expr_->type()->interface_type();
11374 if (type == NULL)
11375 {
11376 go_assert(saw_errors());
11377 return error_mark_node;
11378 }
11379
11380 Named_object* thunk =
11381 Interface_field_reference_expression::create_thunk(context->gogo(),
11382 type, this->name_);
11383 if (thunk->is_erroneous())
11384 {
11385 go_assert(saw_errors());
11386 return error_mark_node;
11387 }
11388
11389 // FIXME: We should lower this earlier, but we can't it lower it in
11390 // the lowering pass because at that point we don't know whether we
11391 // need to create the thunk or not. If the expression is called, we
11392 // don't need the thunk.
11393
11394 Location loc = this->location();
11395
11396 Struct_field_list* fields = new Struct_field_list();
11397 fields->push_back(Struct_field(Typed_identifier("fn.0",
11398 thunk->func_value()->type(),
11399 loc)));
11400 fields->push_back(Struct_field(Typed_identifier("val.1",
11401 this->expr_->type(),
11402 loc)));
11403 Struct_type* st = Type::make_struct_type(fields, loc);
11404
11405 Expression_list* vals = new Expression_list();
11406 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11407 vals->push_back(this->expr_);
11408
11409 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 11410 expr = Expression::make_heap_expression(expr, loc);
0afbb937 11411
2387f644 11412 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11413 Expression* nil_check =
11414 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11415 Expression::make_nil(loc), loc);
11416 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
0afbb937 11417
2387f644 11418 Gogo* gogo = context->gogo();
11419 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11420 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11421
11422 Bexpression* bcond =
a32698ee 11423 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11424 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11425 Bexpression* ret =
11426 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11427 return expr_to_tree(ret);
e440a328 11428}
11429
d751bb78 11430// Dump ast representation for an interface field reference.
11431
11432void
11433Interface_field_reference_expression::do_dump_expression(
11434 Ast_dump_context* ast_dump_context) const
11435{
11436 this->expr_->dump_expression(ast_dump_context);
11437 ast_dump_context->ostream() << "." << this->name_;
11438}
11439
e440a328 11440// Make a reference to a field in an interface.
11441
11442Expression*
11443Expression::make_interface_field_reference(Expression* expr,
11444 const std::string& field,
b13c66cd 11445 Location location)
e440a328 11446{
11447 return new Interface_field_reference_expression(expr, field, location);
11448}
11449
11450// A general selector. This is a Parser_expression for LEFT.NAME. It
11451// is lowered after we know the type of the left hand side.
11452
11453class Selector_expression : public Parser_expression
11454{
11455 public:
11456 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11457 Location location)
e440a328 11458 : Parser_expression(EXPRESSION_SELECTOR, location),
11459 left_(left), name_(name)
11460 { }
11461
11462 protected:
11463 int
11464 do_traverse(Traverse* traverse)
11465 { return Expression::traverse(&this->left_, traverse); }
11466
11467 Expression*
ceeb4318 11468 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11469
11470 Expression*
11471 do_copy()
11472 {
11473 return new Selector_expression(this->left_->copy(), this->name_,
11474 this->location());
11475 }
11476
d751bb78 11477 void
11478 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11479
e440a328 11480 private:
11481 Expression*
11482 lower_method_expression(Gogo*);
11483
11484 // The expression on the left hand side.
11485 Expression* left_;
11486 // The name on the right hand side.
11487 std::string name_;
11488};
11489
11490// Lower a selector expression once we know the real type of the left
11491// hand side.
11492
11493Expression*
ceeb4318 11494Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11495 int)
e440a328 11496{
11497 Expression* left = this->left_;
11498 if (left->is_type_expression())
11499 return this->lower_method_expression(gogo);
11500 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11501 this->location());
11502}
11503
11504// Lower a method expression T.M or (*T).M. We turn this into a
11505// function literal.
11506
11507Expression*
11508Selector_expression::lower_method_expression(Gogo* gogo)
11509{
b13c66cd 11510 Location location = this->location();
e440a328 11511 Type* type = this->left_->type();
11512 const std::string& name(this->name_);
11513
11514 bool is_pointer;
11515 if (type->points_to() == NULL)
11516 is_pointer = false;
11517 else
11518 {
11519 is_pointer = true;
11520 type = type->points_to();
11521 }
11522 Named_type* nt = type->named_type();
11523 if (nt == NULL)
11524 {
11525 error_at(location,
11526 ("method expression requires named type or "
11527 "pointer to named type"));
11528 return Expression::make_error(location);
11529 }
11530
11531 bool is_ambiguous;
11532 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11533 const Typed_identifier* imethod = NULL;
dcc8506b 11534 if (method == NULL && !is_pointer)
ab1468c3 11535 {
11536 Interface_type* it = nt->interface_type();
11537 if (it != NULL)
11538 imethod = it->find_method(name);
11539 }
11540
11541 if (method == NULL && imethod == NULL)
e440a328 11542 {
11543 if (!is_ambiguous)
dcc8506b 11544 error_at(location, "type %<%s%s%> has no method %<%s%>",
11545 is_pointer ? "*" : "",
e440a328 11546 nt->message_name().c_str(),
11547 Gogo::message_name(name).c_str());
11548 else
dcc8506b 11549 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
e440a328 11550 Gogo::message_name(name).c_str(),
dcc8506b 11551 is_pointer ? "*" : "",
e440a328 11552 nt->message_name().c_str());
11553 return Expression::make_error(location);
11554 }
11555
ab1468c3 11556 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11557 {
11558 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11559 nt->message_name().c_str(),
11560 Gogo::message_name(name).c_str());
11561 return Expression::make_error(location);
11562 }
11563
11564 // Build a new function type in which the receiver becomes the first
11565 // argument.
ab1468c3 11566 Function_type* method_type;
11567 if (method != NULL)
11568 {
11569 method_type = method->type();
c484d925 11570 go_assert(method_type->is_method());
ab1468c3 11571 }
11572 else
11573 {
11574 method_type = imethod->type()->function_type();
c484d925 11575 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11576 }
e440a328 11577
11578 const char* const receiver_name = "$this";
11579 Typed_identifier_list* parameters = new Typed_identifier_list();
11580 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11581 location));
11582
11583 const Typed_identifier_list* method_parameters = method_type->parameters();
11584 if (method_parameters != NULL)
11585 {
f470da59 11586 int i = 0;
e440a328 11587 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11588 p != method_parameters->end();
f470da59 11589 ++p, ++i)
11590 {
68883531 11591 if (!p->name().empty())
f470da59 11592 parameters->push_back(*p);
11593 else
11594 {
11595 char buf[20];
11596 snprintf(buf, sizeof buf, "$param%d", i);
11597 parameters->push_back(Typed_identifier(buf, p->type(),
11598 p->location()));
11599 }
11600 }
e440a328 11601 }
11602
11603 const Typed_identifier_list* method_results = method_type->results();
11604 Typed_identifier_list* results;
11605 if (method_results == NULL)
11606 results = NULL;
11607 else
11608 {
11609 results = new Typed_identifier_list();
11610 for (Typed_identifier_list::const_iterator p = method_results->begin();
11611 p != method_results->end();
11612 ++p)
11613 results->push_back(*p);
11614 }
11615
11616 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11617 location);
11618 if (method_type->is_varargs())
11619 fntype->set_is_varargs();
11620
11621 // We generate methods which always takes a pointer to the receiver
11622 // as their first argument. If this is for a pointer type, we can
11623 // simply reuse the existing function. We use an internal hack to
11624 // get the right type.
8381eda7 11625 // FIXME: This optimization is disabled because it doesn't yet work
11626 // with function descriptors when the method expression is not
11627 // directly called.
11628 if (method != NULL && is_pointer && false)
e440a328 11629 {
11630 Named_object* mno = (method->needs_stub_method()
11631 ? method->stub_object()
11632 : method->named_object());
11633 Expression* f = Expression::make_func_reference(mno, NULL, location);
11634 f = Expression::make_cast(fntype, f, location);
11635 Type_conversion_expression* tce =
11636 static_cast<Type_conversion_expression*>(f);
11637 tce->set_may_convert_function_types();
11638 return f;
11639 }
11640
11641 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11642 location);
11643
11644 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 11645 go_assert(vno != NULL);
e440a328 11646 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 11647 Expression* bm;
11648 if (method != NULL)
11649 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11650 else
11651 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 11652
11653 // Even though we found the method above, if it has an error type we
11654 // may see an error here.
11655 if (bm->is_error_expression())
463fe805 11656 {
11657 gogo->finish_function(location);
11658 return bm;
11659 }
e440a328 11660
11661 Expression_list* args;
f470da59 11662 if (parameters->size() <= 1)
e440a328 11663 args = NULL;
11664 else
11665 {
11666 args = new Expression_list();
f470da59 11667 Typed_identifier_list::const_iterator p = parameters->begin();
11668 ++p;
11669 for (; p != parameters->end(); ++p)
e440a328 11670 {
11671 vno = gogo->lookup(p->name(), NULL);
c484d925 11672 go_assert(vno != NULL);
e440a328 11673 args->push_back(Expression::make_var_reference(vno, location));
11674 }
11675 }
11676
ceeb4318 11677 gogo->start_block(location);
11678
e440a328 11679 Call_expression* call = Expression::make_call(bm, args,
11680 method_type->is_varargs(),
11681 location);
11682
0afbb937 11683 Statement* s = Statement::make_return_from_call(call, location);
e440a328 11684 gogo->add_statement(s);
11685
ceeb4318 11686 Block* b = gogo->finish_block(location);
11687
11688 gogo->add_block(b, location);
11689
11690 // Lower the call in case there are multiple results.
11691 gogo->lower_block(no, b);
a32698ee 11692 gogo->flatten_block(no, b);
ceeb4318 11693
e440a328 11694 gogo->finish_function(location);
11695
11696 return Expression::make_func_reference(no, NULL, location);
11697}
11698
d751bb78 11699// Dump the ast for a selector expression.
11700
11701void
11702Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11703 const
11704{
11705 ast_dump_context->dump_expression(this->left_);
11706 ast_dump_context->ostream() << ".";
11707 ast_dump_context->ostream() << this->name_;
11708}
11709
e440a328 11710// Make a selector expression.
11711
11712Expression*
11713Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 11714 Location location)
e440a328 11715{
11716 return new Selector_expression(left, name, location);
11717}
11718
11719// Implement the builtin function new.
11720
11721class Allocation_expression : public Expression
11722{
11723 public:
b13c66cd 11724 Allocation_expression(Type* type, Location location)
e440a328 11725 : Expression(EXPRESSION_ALLOCATION, location),
11726 type_(type)
11727 { }
11728
11729 protected:
11730 int
11731 do_traverse(Traverse* traverse)
11732 { return Type::traverse(this->type_, traverse); }
11733
11734 Type*
11735 do_type()
11736 { return Type::make_pointer_type(this->type_); }
11737
11738 void
11739 do_determine_type(const Type_context*)
11740 { }
11741
e440a328 11742 Expression*
11743 do_copy()
11744 { return new Allocation_expression(this->type_, this->location()); }
11745
11746 tree
11747 do_get_tree(Translate_context*);
11748
d751bb78 11749 void
11750 do_dump_expression(Ast_dump_context*) const;
11751
e440a328 11752 private:
11753 // The type we are allocating.
11754 Type* type_;
11755};
11756
e440a328 11757// Return a tree for an allocation expression.
11758
11759tree
11760Allocation_expression::do_get_tree(Translate_context* context)
11761{
2c809f8f 11762 Gogo* gogo = context->gogo();
11763 Location loc = this->location();
11764 Expression* space = gogo->allocate_memory(this->type_, loc);
11765 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11766 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11767 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11768 return expr_to_tree(ret);
e440a328 11769}
11770
d751bb78 11771// Dump ast representation for an allocation expression.
11772
11773void
11774Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11775 const
11776{
11777 ast_dump_context->ostream() << "new(";
11778 ast_dump_context->dump_type(this->type_);
11779 ast_dump_context->ostream() << ")";
11780}
11781
e440a328 11782// Make an allocation expression.
11783
11784Expression*
b13c66cd 11785Expression::make_allocation(Type* type, Location location)
e440a328 11786{
11787 return new Allocation_expression(type, location);
11788}
11789
e440a328 11790// Construct a struct.
11791
11792class Struct_construction_expression : public Expression
11793{
11794 public:
11795 Struct_construction_expression(Type* type, Expression_list* vals,
b13c66cd 11796 Location location)
e440a328 11797 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
0c4f5a19 11798 type_(type), vals_(vals), traverse_order_(NULL)
e440a328 11799 { }
11800
0c4f5a19 11801 // Set the traversal order, used to ensure that we implement the
11802 // order of evaluation rules. Takes ownership of the argument.
11803 void
11804 set_traverse_order(std::vector<int>* traverse_order)
11805 { this->traverse_order_ = traverse_order; }
11806
e440a328 11807 // Return whether this is a constant initializer.
11808 bool
11809 is_constant_struct() const;
11810
11811 protected:
11812 int
11813 do_traverse(Traverse* traverse);
11814
f9ca30f9 11815 bool
11816 do_is_immutable() const;
11817
e440a328 11818 Type*
11819 do_type()
11820 { return this->type_; }
11821
11822 void
11823 do_determine_type(const Type_context*);
11824
11825 void
11826 do_check_types(Gogo*);
11827
11828 Expression*
11829 do_copy()
11830 {
0c4f5a19 11831 Struct_construction_expression* ret =
11832 new Struct_construction_expression(this->type_, this->vals_->copy(),
11833 this->location());
11834 if (this->traverse_order_ != NULL)
11835 ret->set_traverse_order(this->traverse_order_);
11836 return ret;
e440a328 11837 }
11838
e440a328 11839 tree
11840 do_get_tree(Translate_context*);
11841
11842 void
11843 do_export(Export*) const;
11844
d751bb78 11845 void
11846 do_dump_expression(Ast_dump_context*) const;
11847
e440a328 11848 private:
11849 // The type of the struct to construct.
11850 Type* type_;
11851 // The list of values, in order of the fields in the struct. A NULL
11852 // entry means that the field should be zero-initialized.
11853 Expression_list* vals_;
0c4f5a19 11854 // If not NULL, the order in which to traverse vals_. This is used
11855 // so that we implement the order of evaluation rules correctly.
11856 std::vector<int>* traverse_order_;
e440a328 11857};
11858
11859// Traversal.
11860
11861int
11862Struct_construction_expression::do_traverse(Traverse* traverse)
11863{
0c4f5a19 11864 if (this->vals_ != NULL)
11865 {
11866 if (this->traverse_order_ == NULL)
11867 {
11868 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11869 return TRAVERSE_EXIT;
11870 }
11871 else
11872 {
11873 for (std::vector<int>::const_iterator p =
11874 this->traverse_order_->begin();
11875 p != this->traverse_order_->end();
11876 ++p)
11877 {
11878 if (Expression::traverse(&this->vals_->at(*p), traverse)
11879 == TRAVERSE_EXIT)
11880 return TRAVERSE_EXIT;
11881 }
11882 }
11883 }
e440a328 11884 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11885 return TRAVERSE_EXIT;
11886 return TRAVERSE_CONTINUE;
11887}
11888
11889// Return whether this is a constant initializer.
11890
11891bool
11892Struct_construction_expression::is_constant_struct() const
11893{
11894 if (this->vals_ == NULL)
11895 return true;
11896 for (Expression_list::const_iterator pv = this->vals_->begin();
11897 pv != this->vals_->end();
11898 ++pv)
11899 {
11900 if (*pv != NULL
11901 && !(*pv)->is_constant()
11902 && (!(*pv)->is_composite_literal()
11903 || (*pv)->is_nonconstant_composite_literal()))
11904 return false;
11905 }
11906
11907 const Struct_field_list* fields = this->type_->struct_type()->fields();
11908 for (Struct_field_list::const_iterator pf = fields->begin();
11909 pf != fields->end();
11910 ++pf)
11911 {
11912 // There are no constant constructors for interfaces.
11913 if (pf->type()->interface_type() != NULL)
11914 return false;
11915 }
11916
11917 return true;
11918}
11919
f9ca30f9 11920// Return whether this struct is immutable.
11921
11922bool
11923Struct_construction_expression::do_is_immutable() const
11924{
11925 if (this->vals_ == NULL)
11926 return true;
11927 for (Expression_list::const_iterator pv = this->vals_->begin();
11928 pv != this->vals_->end();
11929 ++pv)
11930 {
11931 if (*pv != NULL && !(*pv)->is_immutable())
11932 return false;
11933 }
11934 return true;
11935}
11936
e440a328 11937// Final type determination.
11938
11939void
11940Struct_construction_expression::do_determine_type(const Type_context*)
11941{
11942 if (this->vals_ == NULL)
11943 return;
11944 const Struct_field_list* fields = this->type_->struct_type()->fields();
11945 Expression_list::const_iterator pv = this->vals_->begin();
11946 for (Struct_field_list::const_iterator pf = fields->begin();
11947 pf != fields->end();
11948 ++pf, ++pv)
11949 {
11950 if (pv == this->vals_->end())
11951 return;
11952 if (*pv != NULL)
11953 {
11954 Type_context subcontext(pf->type(), false);
11955 (*pv)->determine_type(&subcontext);
11956 }
11957 }
a6cb4c0e 11958 // Extra values are an error we will report elsewhere; we still want
11959 // to determine the type to avoid knockon errors.
11960 for (; pv != this->vals_->end(); ++pv)
11961 (*pv)->determine_type_no_context();
e440a328 11962}
11963
11964// Check types.
11965
11966void
11967Struct_construction_expression::do_check_types(Gogo*)
11968{
11969 if (this->vals_ == NULL)
11970 return;
11971
11972 Struct_type* st = this->type_->struct_type();
11973 if (this->vals_->size() > st->field_count())
11974 {
11975 this->report_error(_("too many expressions for struct"));
11976 return;
11977 }
11978
11979 const Struct_field_list* fields = st->fields();
11980 Expression_list::const_iterator pv = this->vals_->begin();
11981 int i = 0;
11982 for (Struct_field_list::const_iterator pf = fields->begin();
11983 pf != fields->end();
11984 ++pf, ++pv, ++i)
11985 {
11986 if (pv == this->vals_->end())
11987 {
11988 this->report_error(_("too few expressions for struct"));
11989 break;
11990 }
11991
11992 if (*pv == NULL)
11993 continue;
11994
11995 std::string reason;
11996 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11997 {
11998 if (reason.empty())
11999 error_at((*pv)->location(),
12000 "incompatible type for field %d in struct construction",
12001 i + 1);
12002 else
12003 error_at((*pv)->location(),
12004 ("incompatible type for field %d in "
12005 "struct construction (%s)"),
12006 i + 1, reason.c_str());
12007 this->set_is_error();
12008 }
12009 }
c484d925 12010 go_assert(pv == this->vals_->end());
e440a328 12011}
12012
12013// Return a tree for constructing a struct.
12014
12015tree
12016Struct_construction_expression::do_get_tree(Translate_context* context)
12017{
12018 Gogo* gogo = context->gogo();
12019
2c809f8f 12020 Btype* btype = this->type_->get_backend(gogo);
e440a328 12021 if (this->vals_ == NULL)
2c809f8f 12022 return expr_to_tree(gogo->backend()->zero_expression(btype));
e440a328 12023
e440a328 12024 const Struct_field_list* fields = this->type_->struct_type()->fields();
e440a328 12025 Expression_list::const_iterator pv = this->vals_->begin();
2c809f8f 12026 std::vector<Bexpression*> init;
12027 for (Struct_field_list::const_iterator pf = fields->begin();
12028 pf != fields->end();
12029 ++pf)
e440a328 12030 {
63697958 12031 Btype* fbtype = pf->type()->get_backend(gogo);
e440a328 12032 if (pv == this->vals_->end())
2c809f8f 12033 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12034 else if (*pv == NULL)
12035 {
2c809f8f 12036 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12037 ++pv;
12038 }
12039 else
12040 {
2c809f8f 12041 Expression* val =
12042 Expression::convert_for_assignment(gogo, pf->type(),
12043 *pv, this->location());
12044 init.push_back(tree_to_expr(val->get_tree(context)));
e440a328 12045 ++pv;
12046 }
e440a328 12047 }
e440a328 12048
2c809f8f 12049 Bexpression* ret =
12050 gogo->backend()->constructor_expression(btype, init, this->location());
12051 return expr_to_tree(ret);
e440a328 12052}
12053
12054// Export a struct construction.
12055
12056void
12057Struct_construction_expression::do_export(Export* exp) const
12058{
12059 exp->write_c_string("convert(");
12060 exp->write_type(this->type_);
12061 for (Expression_list::const_iterator pv = this->vals_->begin();
12062 pv != this->vals_->end();
12063 ++pv)
12064 {
12065 exp->write_c_string(", ");
12066 if (*pv != NULL)
12067 (*pv)->export_expression(exp);
12068 }
12069 exp->write_c_string(")");
12070}
12071
d751bb78 12072// Dump ast representation of a struct construction expression.
12073
12074void
12075Struct_construction_expression::do_dump_expression(
12076 Ast_dump_context* ast_dump_context) const
12077{
d751bb78 12078 ast_dump_context->dump_type(this->type_);
12079 ast_dump_context->ostream() << "{";
12080 ast_dump_context->dump_expression_list(this->vals_);
12081 ast_dump_context->ostream() << "}";
12082}
12083
e440a328 12084// Make a struct composite literal. This used by the thunk code.
12085
12086Expression*
12087Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12088 Location location)
e440a328 12089{
c484d925 12090 go_assert(type->struct_type() != NULL);
e440a328 12091 return new Struct_construction_expression(type, vals, location);
12092}
12093
12094// Construct an array. This class is not used directly; instead we
12095// use the child classes, Fixed_array_construction_expression and
2c809f8f 12096// Slice_construction_expression.
e440a328 12097
12098class Array_construction_expression : public Expression
12099{
12100 protected:
12101 Array_construction_expression(Expression_classification classification,
ffe743ca 12102 Type* type,
12103 const std::vector<unsigned long>* indexes,
12104 Expression_list* vals, Location location)
e440a328 12105 : Expression(classification, location),
ffe743ca 12106 type_(type), indexes_(indexes), vals_(vals)
12107 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
e440a328 12108
12109 public:
12110 // Return whether this is a constant initializer.
12111 bool
12112 is_constant_array() const;
12113
12114 // Return the number of elements.
12115 size_t
12116 element_count() const
12117 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12118
12119protected:
12120 int
12121 do_traverse(Traverse* traverse);
12122
f9ca30f9 12123 bool
12124 do_is_immutable() const;
12125
e440a328 12126 Type*
12127 do_type()
12128 { return this->type_; }
12129
12130 void
12131 do_determine_type(const Type_context*);
12132
12133 void
12134 do_check_types(Gogo*);
12135
e440a328 12136 void
12137 do_export(Export*) const;
12138
ffe743ca 12139 // The indexes.
12140 const std::vector<unsigned long>*
12141 indexes()
12142 { return this->indexes_; }
12143
e440a328 12144 // The list of values.
12145 Expression_list*
12146 vals()
12147 { return this->vals_; }
12148
2c809f8f 12149 // Get the backend constructor for the array values.
12150 Bexpression*
12151 get_constructor(Translate_context* context, Btype* btype);
e440a328 12152
d751bb78 12153 void
12154 do_dump_expression(Ast_dump_context*) const;
12155
e440a328 12156 private:
12157 // The type of the array to construct.
12158 Type* type_;
ffe743ca 12159 // The list of indexes into the array, one for each value. This may
12160 // be NULL, in which case the indexes start at zero and increment.
12161 const std::vector<unsigned long>* indexes_;
12162 // The list of values. This may be NULL if there are no values.
e440a328 12163 Expression_list* vals_;
12164};
12165
12166// Traversal.
12167
12168int
12169Array_construction_expression::do_traverse(Traverse* traverse)
12170{
12171 if (this->vals_ != NULL
12172 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12173 return TRAVERSE_EXIT;
12174 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12175 return TRAVERSE_EXIT;
12176 return TRAVERSE_CONTINUE;
12177}
12178
12179// Return whether this is a constant initializer.
12180
12181bool
12182Array_construction_expression::is_constant_array() const
12183{
12184 if (this->vals_ == NULL)
12185 return true;
12186
12187 // There are no constant constructors for interfaces.
12188 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12189 return false;
12190
12191 for (Expression_list::const_iterator pv = this->vals_->begin();
12192 pv != this->vals_->end();
12193 ++pv)
12194 {
12195 if (*pv != NULL
12196 && !(*pv)->is_constant()
12197 && (!(*pv)->is_composite_literal()
12198 || (*pv)->is_nonconstant_composite_literal()))
12199 return false;
12200 }
12201 return true;
12202}
12203
f9ca30f9 12204// Return whether this is an immutable array initializer.
12205
12206bool
12207Array_construction_expression::do_is_immutable() const
12208{
12209 if (this->vals_ == NULL)
12210 return true;
12211 for (Expression_list::const_iterator pv = this->vals_->begin();
12212 pv != this->vals_->end();
12213 ++pv)
12214 {
12215 if (*pv != NULL && !(*pv)->is_immutable())
12216 return false;
12217 }
12218 return true;
12219}
12220
e440a328 12221// Final type determination.
12222
12223void
12224Array_construction_expression::do_determine_type(const Type_context*)
12225{
12226 if (this->vals_ == NULL)
12227 return;
12228 Type_context subcontext(this->type_->array_type()->element_type(), false);
12229 for (Expression_list::const_iterator pv = this->vals_->begin();
12230 pv != this->vals_->end();
12231 ++pv)
12232 {
12233 if (*pv != NULL)
12234 (*pv)->determine_type(&subcontext);
12235 }
12236}
12237
12238// Check types.
12239
12240void
12241Array_construction_expression::do_check_types(Gogo*)
12242{
12243 if (this->vals_ == NULL)
12244 return;
12245
12246 Array_type* at = this->type_->array_type();
12247 int i = 0;
12248 Type* element_type = at->element_type();
12249 for (Expression_list::const_iterator pv = this->vals_->begin();
12250 pv != this->vals_->end();
12251 ++pv, ++i)
12252 {
12253 if (*pv != NULL
12254 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12255 {
12256 error_at((*pv)->location(),
12257 "incompatible type for element %d in composite literal",
12258 i + 1);
12259 this->set_is_error();
12260 }
12261 }
e440a328 12262}
12263
2c809f8f 12264// Get a constructor expression for the array values.
e440a328 12265
2c809f8f 12266Bexpression*
12267Array_construction_expression::get_constructor(Translate_context* context,
12268 Btype* array_btype)
e440a328 12269{
e440a328 12270 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12271
12272 std::vector<unsigned long> indexes;
12273 std::vector<Bexpression*> vals;
12274 Gogo* gogo = context->gogo();
e440a328 12275 if (this->vals_ != NULL)
12276 {
12277 size_t i = 0;
ffe743ca 12278 std::vector<unsigned long>::const_iterator pi;
12279 if (this->indexes_ != NULL)
12280 pi = this->indexes_->begin();
e440a328 12281 for (Expression_list::const_iterator pv = this->vals_->begin();
12282 pv != this->vals_->end();
12283 ++pv, ++i)
12284 {
ffe743ca 12285 if (this->indexes_ != NULL)
12286 go_assert(pi != this->indexes_->end());
ffe743ca 12287
12288 if (this->indexes_ == NULL)
2c809f8f 12289 indexes.push_back(i);
ffe743ca 12290 else
2c809f8f 12291 indexes.push_back(*pi);
e440a328 12292 if (*pv == NULL)
63697958 12293 {
63697958 12294 Btype* ebtype = element_type->get_backend(gogo);
12295 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12296 vals.push_back(zv);
63697958 12297 }
e440a328 12298 else
12299 {
2c809f8f 12300 Expression* val_expr =
12301 Expression::convert_for_assignment(gogo, element_type, *pv,
12302 this->location());
12303 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
e440a328 12304 }
ffe743ca 12305 if (this->indexes_ != NULL)
12306 ++pi;
e440a328 12307 }
ffe743ca 12308 if (this->indexes_ != NULL)
12309 go_assert(pi == this->indexes_->end());
e440a328 12310 }
2c809f8f 12311 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12312 vals, this->location());
e440a328 12313}
12314
12315// Export an array construction.
12316
12317void
12318Array_construction_expression::do_export(Export* exp) const
12319{
12320 exp->write_c_string("convert(");
12321 exp->write_type(this->type_);
12322 if (this->vals_ != NULL)
12323 {
ffe743ca 12324 std::vector<unsigned long>::const_iterator pi;
12325 if (this->indexes_ != NULL)
12326 pi = this->indexes_->begin();
e440a328 12327 for (Expression_list::const_iterator pv = this->vals_->begin();
12328 pv != this->vals_->end();
12329 ++pv)
12330 {
12331 exp->write_c_string(", ");
ffe743ca 12332
12333 if (this->indexes_ != NULL)
12334 {
12335 char buf[100];
12336 snprintf(buf, sizeof buf, "%lu", *pi);
12337 exp->write_c_string(buf);
12338 exp->write_c_string(":");
12339 }
12340
e440a328 12341 if (*pv != NULL)
12342 (*pv)->export_expression(exp);
ffe743ca 12343
12344 if (this->indexes_ != NULL)
12345 ++pi;
e440a328 12346 }
12347 }
12348 exp->write_c_string(")");
12349}
12350
d751bb78 12351// Dump ast representation of an array construction expressin.
12352
12353void
12354Array_construction_expression::do_dump_expression(
12355 Ast_dump_context* ast_dump_context) const
12356{
ffe743ca 12357 Expression* length = this->type_->array_type()->length();
8b1c301d 12358
12359 ast_dump_context->ostream() << "[" ;
12360 if (length != NULL)
12361 {
12362 ast_dump_context->dump_expression(length);
12363 }
12364 ast_dump_context->ostream() << "]" ;
d751bb78 12365 ast_dump_context->dump_type(this->type_);
12366 ast_dump_context->ostream() << "{" ;
ffe743ca 12367 if (this->indexes_ == NULL)
12368 ast_dump_context->dump_expression_list(this->vals_);
12369 else
12370 {
12371 Expression_list::const_iterator pv = this->vals_->begin();
12372 for (std::vector<unsigned long>::const_iterator pi =
12373 this->indexes_->begin();
12374 pi != this->indexes_->end();
12375 ++pi, ++pv)
12376 {
12377 if (pi != this->indexes_->begin())
12378 ast_dump_context->ostream() << ", ";
12379 ast_dump_context->ostream() << *pi << ':';
12380 ast_dump_context->dump_expression(*pv);
12381 }
12382 }
d751bb78 12383 ast_dump_context->ostream() << "}" ;
12384
12385}
12386
e440a328 12387// Construct a fixed array.
12388
12389class Fixed_array_construction_expression :
12390 public Array_construction_expression
12391{
12392 public:
ffe743ca 12393 Fixed_array_construction_expression(Type* type,
12394 const std::vector<unsigned long>* indexes,
12395 Expression_list* vals, Location location)
e440a328 12396 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
ffe743ca 12397 type, indexes, vals, location)
12398 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12399
12400 protected:
12401 Expression*
12402 do_copy()
12403 {
12404 return new Fixed_array_construction_expression(this->type(),
ffe743ca 12405 this->indexes(),
e440a328 12406 (this->vals() == NULL
12407 ? NULL
12408 : this->vals()->copy()),
12409 this->location());
12410 }
12411
12412 tree
12413 do_get_tree(Translate_context*);
12414};
12415
12416// Return a tree for constructing a fixed array.
12417
12418tree
12419Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12420{
9f0e0513 12421 Type* type = this->type();
12422 Btype* btype = type->get_backend(context->gogo());
2c809f8f 12423 return expr_to_tree(this->get_constructor(context, btype));
e440a328 12424}
12425
76f85fd6 12426Expression*
12427Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12428 Location location)
12429{
12430 go_assert(type->array_type() != NULL && !type->is_slice_type());
12431 return new Fixed_array_construction_expression(type, NULL, vals, location);
12432}
12433
2c809f8f 12434// Construct a slice.
e440a328 12435
2c809f8f 12436class Slice_construction_expression : public Array_construction_expression
e440a328 12437{
12438 public:
2c809f8f 12439 Slice_construction_expression(Type* type,
12440 const std::vector<unsigned long>* indexes,
12441 Expression_list* vals, Location location)
12442 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12443 type, indexes, vals, location),
12444 valtype_(NULL)
ffe743ca 12445 { go_assert(type->is_slice_type()); }
e440a328 12446
12447 protected:
2c809f8f 12448 // Note that taking the address of a slice literal is invalid.
e440a328 12449
12450 Expression*
12451 do_copy()
12452 {
2c809f8f 12453 return new Slice_construction_expression(this->type(), this->indexes(),
12454 (this->vals() == NULL
12455 ? NULL
12456 : this->vals()->copy()),
12457 this->location());
e440a328 12458 }
12459
12460 tree
12461 do_get_tree(Translate_context*);
2c809f8f 12462
12463 private:
12464 // The type of the values in this slice.
12465 Type* valtype_;
e440a328 12466};
12467
2c809f8f 12468// Return a tree for constructing a slice.
e440a328 12469
12470tree
2c809f8f 12471Slice_construction_expression::do_get_tree(Translate_context* context)
e440a328 12472{
f9c68f17 12473 Array_type* array_type = this->type()->array_type();
12474 if (array_type == NULL)
12475 {
c484d925 12476 go_assert(this->type()->is_error());
f9c68f17 12477 return error_mark_node;
12478 }
12479
f23d7786 12480 Location loc = this->location();
f9c68f17 12481 Type* element_type = array_type->element_type();
2c809f8f 12482 if (this->valtype_ == NULL)
12483 {
12484 mpz_t lenval;
12485 Expression* length;
12486 if (this->vals() == NULL || this->vals()->empty())
12487 mpz_init_set_ui(lenval, 0);
12488 else
12489 {
12490 if (this->indexes() == NULL)
12491 mpz_init_set_ui(lenval, this->vals()->size());
12492 else
12493 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12494 }
2c809f8f 12495 Type* int_type = Type::lookup_integer_type("int");
12496 length = Expression::make_integer(&lenval, int_type, loc);
12497 mpz_clear(lenval);
12498 this->valtype_ = Type::make_array_type(element_type, length);
12499 }
3d60812e 12500
f23d7786 12501 Expression_list* vals = this->vals();
e440a328 12502 if (this->vals() == NULL || this->vals()->empty())
12503 {
f23d7786 12504 // We need to create a unique value for the empty array literal.
12505 vals = new Expression_list;
12506 vals->push_back(NULL);
e440a328 12507 }
f23d7786 12508 Expression* array_val =
12509 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12510 vals, loc);
e440a328 12511
f23d7786 12512 bool is_constant_initializer = array_val->is_immutable();
d8829beb 12513
12514 // We have to copy the initial values into heap memory if we are in
12515 // a function or if the values are not constants. We also have to
12516 // copy them if they may contain pointers in a non-constant context,
12517 // as otherwise the garbage collector won't see them.
12518 bool copy_to_heap = (context->function() != NULL
12519 || !is_constant_initializer
12520 || (element_type->has_pointer()
12521 && !context->is_const()));
e440a328 12522
f23d7786 12523 Expression* space;
d8829beb 12524 if (!copy_to_heap)
e440a328 12525 {
f23d7786 12526 // The initializer will only run once.
12527 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12528 space->unary_expression()->set_is_slice_init();
e440a328 12529 }
12530 else
f23d7786 12531 space = Expression::make_heap_expression(array_val, loc);
e440a328 12532
2c809f8f 12533 // Build a constructor for the slice.
e440a328 12534
f23d7786 12535 Expression* len = this->valtype_->array_type()->length();
12536 Expression* slice_val =
12537 Expression::make_slice_value(this->type(), space, len, len, loc);
12538 return slice_val->get_tree(context);
e440a328 12539}
12540
12541// Make a slice composite literal. This is used by the type
12542// descriptor code.
12543
12544Expression*
12545Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12546 Location location)
e440a328 12547{
411eb89e 12548 go_assert(type->is_slice_type());
2c809f8f 12549 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 12550}
12551
12552// Construct a map.
12553
12554class Map_construction_expression : public Expression
12555{
12556 public:
12557 Map_construction_expression(Type* type, Expression_list* vals,
b13c66cd 12558 Location location)
e440a328 12559 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
2c809f8f 12560 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
c484d925 12561 { go_assert(vals == NULL || vals->size() % 2 == 0); }
e440a328 12562
12563 protected:
12564 int
12565 do_traverse(Traverse* traverse);
12566
2c809f8f 12567 Expression*
12568 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12569
e440a328 12570 Type*
12571 do_type()
12572 { return this->type_; }
12573
12574 void
12575 do_determine_type(const Type_context*);
12576
12577 void
12578 do_check_types(Gogo*);
12579
12580 Expression*
12581 do_copy()
12582 {
12583 return new Map_construction_expression(this->type_, this->vals_->copy(),
12584 this->location());
12585 }
12586
12587 tree
12588 do_get_tree(Translate_context*);
12589
12590 void
12591 do_export(Export*) const;
12592
d751bb78 12593 void
12594 do_dump_expression(Ast_dump_context*) const;
12595
e440a328 12596 private:
12597 // The type of the map to construct.
12598 Type* type_;
12599 // The list of values.
12600 Expression_list* vals_;
2c809f8f 12601 // The type of the key-value pair struct for each map element.
12602 Struct_type* element_type_;
12603 // A temporary reference to the variable storing the constructor initializer.
12604 Temporary_statement* constructor_temp_;
e440a328 12605};
12606
12607// Traversal.
12608
12609int
12610Map_construction_expression::do_traverse(Traverse* traverse)
12611{
12612 if (this->vals_ != NULL
12613 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12614 return TRAVERSE_EXIT;
12615 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12616 return TRAVERSE_EXIT;
12617 return TRAVERSE_CONTINUE;
12618}
12619
2c809f8f 12620// Flatten constructor initializer into a temporary variable since
12621// we need to take its address for __go_construct_map.
12622
12623Expression*
12624Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12625 Statement_inserter* inserter)
12626{
12627 if (!this->is_error_expression()
12628 && this->vals_ != NULL
12629 && !this->vals_->empty()
12630 && this->constructor_temp_ == NULL)
12631 {
12632 Map_type* mt = this->type_->map_type();
12633 Type* key_type = mt->key_type();
12634 Type* val_type = mt->val_type();
12635 this->element_type_ = Type::make_builtin_struct_type(2,
12636 "__key", key_type,
12637 "__val", val_type);
12638
12639 Expression_list* value_pairs = new Expression_list();
12640 Location loc = this->location();
12641
12642 size_t i = 0;
12643 for (Expression_list::const_iterator pv = this->vals_->begin();
12644 pv != this->vals_->end();
12645 ++pv, ++i)
12646 {
12647 Expression_list* key_value_pair = new Expression_list();
12648 Expression* key =
12649 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12650
12651 ++pv;
12652 Expression* val =
12653 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12654
12655 key_value_pair->push_back(key);
12656 key_value_pair->push_back(val);
12657 value_pairs->push_back(
12658 Expression::make_struct_composite_literal(this->element_type_,
12659 key_value_pair, loc));
12660 }
12661
12662 mpz_t lenval;
12663 mpz_init_set_ui(lenval, i);
12664 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12665 mpz_clear(lenval);
12666
12667 Type* ctor_type =
12668 Type::make_array_type(this->element_type_, element_count);
12669 Expression* constructor =
12670 new Fixed_array_construction_expression(ctor_type, NULL,
12671 value_pairs, loc);
12672
12673 this->constructor_temp_ =
12674 Statement::make_temporary(NULL, constructor, loc);
12675 constructor->issue_nil_check();
12676 this->constructor_temp_->set_is_address_taken();
12677 inserter->insert(this->constructor_temp_);
12678 }
12679
12680 return this;
12681}
12682
e440a328 12683// Final type determination.
12684
12685void
12686Map_construction_expression::do_determine_type(const Type_context*)
12687{
12688 if (this->vals_ == NULL)
12689 return;
12690
12691 Map_type* mt = this->type_->map_type();
12692 Type_context key_context(mt->key_type(), false);
12693 Type_context val_context(mt->val_type(), false);
12694 for (Expression_list::const_iterator pv = this->vals_->begin();
12695 pv != this->vals_->end();
12696 ++pv)
12697 {
12698 (*pv)->determine_type(&key_context);
12699 ++pv;
12700 (*pv)->determine_type(&val_context);
12701 }
12702}
12703
12704// Check types.
12705
12706void
12707Map_construction_expression::do_check_types(Gogo*)
12708{
12709 if (this->vals_ == NULL)
12710 return;
12711
12712 Map_type* mt = this->type_->map_type();
12713 int i = 0;
12714 Type* key_type = mt->key_type();
12715 Type* val_type = mt->val_type();
12716 for (Expression_list::const_iterator pv = this->vals_->begin();
12717 pv != this->vals_->end();
12718 ++pv, ++i)
12719 {
12720 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12721 {
12722 error_at((*pv)->location(),
12723 "incompatible type for element %d key in map construction",
12724 i + 1);
12725 this->set_is_error();
12726 }
12727 ++pv;
12728 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12729 {
12730 error_at((*pv)->location(),
12731 ("incompatible type for element %d value "
12732 "in map construction"),
12733 i + 1);
12734 this->set_is_error();
12735 }
12736 }
12737}
12738
12739// Return a tree for constructing a map.
12740
12741tree
12742Map_construction_expression::do_get_tree(Translate_context* context)
12743{
2c809f8f 12744 if (this->is_error_expression())
5845bde6 12745 return error_mark_node;
2c809f8f 12746 Location loc = this->location();
e440a328 12747
e440a328 12748 size_t i = 0;
2c809f8f 12749 Expression* ventries;
e440a328 12750 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 12751 ventries = Expression::make_nil(loc);
e440a328 12752 else
12753 {
2c809f8f 12754 go_assert(this->constructor_temp_ != NULL);
12755 i = this->vals_->size() / 2;
e440a328 12756
2c809f8f 12757 Expression* ctor_ref =
12758 Expression::make_temporary_reference(this->constructor_temp_, loc);
12759 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12760 }
e440a328 12761
2c809f8f 12762 Map_type* mt = this->type_->map_type();
12763 if (this->element_type_ == NULL)
12764 this->element_type_ =
12765 Type::make_builtin_struct_type(2,
12766 "__key", mt->key_type(),
12767 "__val", mt->val_type());
12768 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12769
12770 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12771 mpz_t countval;
12772 mpz_init_set_ui(countval, i);
12773 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12774 mpz_clear(countval);
12775
12776 Expression* entry_size =
12777 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12778
12779 unsigned int field_index;
12780 const Struct_field* valfield =
12781 this->element_type_->find_local_field("__val", &field_index);
12782 Expression* val_offset =
12783 Expression::make_struct_field_offset(this->element_type_, valfield);
12784 Expression* val_size =
12785 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12786
12787 Expression* map_ctor =
12788 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12789 entry_size, val_offset, val_size, ventries);
12790 return map_ctor->get_tree(context);
12791}
e440a328 12792
2c809f8f 12793// Export an array construction.
e440a328 12794
2c809f8f 12795void
12796Map_construction_expression::do_export(Export* exp) const
12797{
12798 exp->write_c_string("convert(");
12799 exp->write_type(this->type_);
12800 for (Expression_list::const_iterator pv = this->vals_->begin();
12801 pv != this->vals_->end();
12802 ++pv)
12803 {
12804 exp->write_c_string(", ");
12805 (*pv)->export_expression(exp);
12806 }
12807 exp->write_c_string(")");
12808}
e440a328 12809
2c809f8f 12810// Dump ast representation for a map construction expression.
d751bb78 12811
12812void
12813Map_construction_expression::do_dump_expression(
12814 Ast_dump_context* ast_dump_context) const
12815{
d751bb78 12816 ast_dump_context->ostream() << "{" ;
8b1c301d 12817 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 12818 ast_dump_context->ostream() << "}";
12819}
12820
e440a328 12821// A general composite literal. This is lowered to a type specific
12822// version.
12823
12824class Composite_literal_expression : public Parser_expression
12825{
12826 public:
12827 Composite_literal_expression(Type* type, int depth, bool has_keys,
62750cd5 12828 Expression_list* vals, bool all_are_names,
12829 Location location)
e440a328 12830 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
62750cd5 12831 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12832 all_are_names_(all_are_names)
e440a328 12833 { }
12834
12835 protected:
12836 int
12837 do_traverse(Traverse* traverse);
12838
12839 Expression*
ceeb4318 12840 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 12841
12842 Expression*
12843 do_copy()
12844 {
12845 return new Composite_literal_expression(this->type_, this->depth_,
12846 this->has_keys_,
12847 (this->vals_ == NULL
12848 ? NULL
12849 : this->vals_->copy()),
62750cd5 12850 this->all_are_names_,
e440a328 12851 this->location());
12852 }
12853
d751bb78 12854 void
12855 do_dump_expression(Ast_dump_context*) const;
12856
e440a328 12857 private:
12858 Expression*
81c4b26b 12859 lower_struct(Gogo*, Type*);
e440a328 12860
12861 Expression*
113ef6a5 12862 lower_array(Type*);
e440a328 12863
12864 Expression*
ffe743ca 12865 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
e440a328 12866
12867 Expression*
ceeb4318 12868 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
e440a328 12869
12870 // The type of the composite literal.
12871 Type* type_;
12872 // The depth within a list of composite literals within a composite
12873 // literal, when the type is omitted.
12874 int depth_;
12875 // The values to put in the composite literal.
12876 Expression_list* vals_;
12877 // If this is true, then VALS_ is a list of pairs: a key and a
12878 // value. In an array initializer, a missing key will be NULL.
12879 bool has_keys_;
62750cd5 12880 // If this is true, then HAS_KEYS_ is true, and every key is a
12881 // simple identifier.
12882 bool all_are_names_;
e440a328 12883};
12884
12885// Traversal.
12886
12887int
12888Composite_literal_expression::do_traverse(Traverse* traverse)
12889{
dbffccfc 12890 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 12891 return TRAVERSE_EXIT;
dbffccfc 12892
12893 // If this is a struct composite literal with keys, then the keys
12894 // are field names, not expressions. We don't want to traverse them
12895 // in that case. If we do, we can give an erroneous error "variable
12896 // initializer refers to itself." See bug482.go in the testsuite.
12897 if (this->has_keys_ && this->vals_ != NULL)
12898 {
12899 // The type may not be resolvable at this point.
12900 Type* type = this->type_;
a01f2481 12901
12902 for (int depth = this->depth_; depth > 0; --depth)
12903 {
12904 if (type->array_type() != NULL)
12905 type = type->array_type()->element_type();
12906 else if (type->map_type() != NULL)
12907 type = type->map_type()->val_type();
12908 else
12909 {
12910 // This error will be reported during lowering.
12911 return TRAVERSE_CONTINUE;
12912 }
12913 }
12914
dbffccfc 12915 while (true)
12916 {
12917 if (type->classification() == Type::TYPE_NAMED)
12918 type = type->named_type()->real_type();
12919 else if (type->classification() == Type::TYPE_FORWARD)
12920 {
12921 Type* t = type->forwarded();
12922 if (t == type)
12923 break;
12924 type = t;
12925 }
12926 else
12927 break;
12928 }
12929
12930 if (type->classification() == Type::TYPE_STRUCT)
12931 {
12932 Expression_list::iterator p = this->vals_->begin();
12933 while (p != this->vals_->end())
12934 {
12935 // Skip key.
12936 ++p;
12937 go_assert(p != this->vals_->end());
12938 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12939 return TRAVERSE_EXIT;
12940 ++p;
12941 }
12942 return TRAVERSE_CONTINUE;
12943 }
12944 }
12945
12946 if (this->vals_ != NULL)
12947 return this->vals_->traverse(traverse);
12948
12949 return TRAVERSE_CONTINUE;
e440a328 12950}
12951
12952// Lower a generic composite literal into a specific version based on
12953// the type.
12954
12955Expression*
ceeb4318 12956Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12957 Statement_inserter* inserter, int)
e440a328 12958{
12959 Type* type = this->type_;
12960
12961 for (int depth = this->depth_; depth > 0; --depth)
12962 {
12963 if (type->array_type() != NULL)
12964 type = type->array_type()->element_type();
12965 else if (type->map_type() != NULL)
12966 type = type->map_type()->val_type();
12967 else
12968 {
5c13bd80 12969 if (!type->is_error())
e440a328 12970 error_at(this->location(),
12971 ("may only omit types within composite literals "
12972 "of slice, array, or map type"));
12973 return Expression::make_error(this->location());
12974 }
12975 }
12976
e00772b3 12977 Type *pt = type->points_to();
12978 bool is_pointer = false;
12979 if (pt != NULL)
12980 {
12981 is_pointer = true;
12982 type = pt;
12983 }
12984
12985 Expression* ret;
5c13bd80 12986 if (type->is_error())
e440a328 12987 return Expression::make_error(this->location());
12988 else if (type->struct_type() != NULL)
e00772b3 12989 ret = this->lower_struct(gogo, type);
e440a328 12990 else if (type->array_type() != NULL)
113ef6a5 12991 ret = this->lower_array(type);
e440a328 12992 else if (type->map_type() != NULL)
e00772b3 12993 ret = this->lower_map(gogo, function, inserter, type);
e440a328 12994 else
12995 {
12996 error_at(this->location(),
12997 ("expected struct, slice, array, or map type "
12998 "for composite literal"));
12999 return Expression::make_error(this->location());
13000 }
e00772b3 13001
13002 if (is_pointer)
2c809f8f 13003 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13004
13005 return ret;
e440a328 13006}
13007
13008// Lower a struct composite literal.
13009
13010Expression*
81c4b26b 13011Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13012{
b13c66cd 13013 Location location = this->location();
e440a328 13014 Struct_type* st = type->struct_type();
13015 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13016 {
e6013c28 13017 if (this->vals_ != NULL
13018 && !this->vals_->empty()
13019 && type->named_type() != NULL
13020 && type->named_type()->named_object()->package() != NULL)
13021 {
13022 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13023 pf != st->fields()->end();
13024 ++pf)
07daa4e7 13025 {
e6013c28 13026 if (Gogo::is_hidden_name(pf->field_name()))
07daa4e7 13027 error_at(this->location(),
e6013c28 13028 "assignment of unexported field %qs in %qs literal",
13029 Gogo::message_name(pf->field_name()).c_str(),
13030 type->named_type()->message_name().c_str());
07daa4e7 13031 }
13032 }
13033
13034 return new Struct_construction_expression(type, this->vals_, location);
13035 }
e440a328 13036
13037 size_t field_count = st->field_count();
13038 std::vector<Expression*> vals(field_count);
0c4f5a19 13039 std::vector<int>* traverse_order = new(std::vector<int>);
e440a328 13040 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13041 Expression* external_expr = NULL;
13042 const Named_object* external_no = NULL;
e440a328 13043 while (p != this->vals_->end())
13044 {
13045 Expression* name_expr = *p;
13046
13047 ++p;
c484d925 13048 go_assert(p != this->vals_->end());
e440a328 13049 Expression* val = *p;
13050
13051 ++p;
13052
13053 if (name_expr == NULL)
13054 {
13055 error_at(val->location(), "mixture of field and value initializers");
13056 return Expression::make_error(location);
13057 }
13058
13059 bool bad_key = false;
13060 std::string name;
81c4b26b 13061 const Named_object* no = NULL;
e440a328 13062 switch (name_expr->classification())
13063 {
13064 case EXPRESSION_UNKNOWN_REFERENCE:
13065 name = name_expr->unknown_expression()->name();
13066 break;
13067
13068 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13069 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13070 break;
13071
13072 case EXPRESSION_TYPE:
13073 {
13074 Type* t = name_expr->type();
13075 Named_type* nt = t->named_type();
13076 if (nt == NULL)
13077 bad_key = true;
13078 else
81c4b26b 13079 no = nt->named_object();
e440a328 13080 }
13081 break;
13082
13083 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13084 no = name_expr->var_expression()->named_object();
e440a328 13085 break;
13086
13087 case EXPRESSION_FUNC_REFERENCE:
81c4b26b 13088 no = name_expr->func_expression()->named_object();
e440a328 13089 break;
13090
13091 case EXPRESSION_UNARY:
13092 // If there is a local variable around with the same name as
13093 // the field, and this occurs in the closure, then the
13094 // parser may turn the field reference into an indirection
13095 // through the closure. FIXME: This is a mess.
13096 {
13097 bad_key = true;
13098 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13099 if (ue->op() == OPERATOR_MULT)
13100 {
13101 Field_reference_expression* fre =
13102 ue->operand()->field_reference_expression();
13103 if (fre != NULL)
13104 {
13105 Struct_type* st =
13106 fre->expr()->type()->deref()->struct_type();
13107 if (st != NULL)
13108 {
13109 const Struct_field* sf = st->field(fre->field_index());
13110 name = sf->field_name();
2d29d278 13111
13112 // See below. FIXME.
13113 if (!Gogo::is_hidden_name(name)
13114 && name[0] >= 'a'
13115 && name[0] <= 'z')
13116 {
13117 if (gogo->lookup_global(name.c_str()) != NULL)
13118 name = gogo->pack_hidden_name(name, false);
13119 }
13120
e440a328 13121 char buf[20];
13122 snprintf(buf, sizeof buf, "%u", fre->field_index());
13123 size_t buflen = strlen(buf);
13124 if (name.compare(name.length() - buflen, buflen, buf)
13125 == 0)
13126 {
13127 name = name.substr(0, name.length() - buflen);
13128 bad_key = false;
13129 }
13130 }
13131 }
13132 }
13133 }
13134 break;
13135
13136 default:
13137 bad_key = true;
13138 break;
13139 }
13140 if (bad_key)
13141 {
13142 error_at(name_expr->location(), "expected struct field name");
13143 return Expression::make_error(location);
13144 }
13145
81c4b26b 13146 if (no != NULL)
13147 {
62750cd5 13148 if (no->package() != NULL && external_expr == NULL)
13149 {
13150 external_expr = name_expr;
13151 external_no = no;
13152 }
13153
81c4b26b 13154 name = no->name();
13155
13156 // A predefined name won't be packed. If it starts with a
13157 // lower case letter we need to check for that case, because
2d29d278 13158 // the field name will be packed. FIXME.
81c4b26b 13159 if (!Gogo::is_hidden_name(name)
13160 && name[0] >= 'a'
13161 && name[0] <= 'z')
13162 {
13163 Named_object* gno = gogo->lookup_global(name.c_str());
13164 if (gno == no)
13165 name = gogo->pack_hidden_name(name, false);
13166 }
13167 }
13168
e440a328 13169 unsigned int index;
13170 const Struct_field* sf = st->find_local_field(name, &index);
13171 if (sf == NULL)
13172 {
13173 error_at(name_expr->location(), "unknown field %qs in %qs",
13174 Gogo::message_name(name).c_str(),
13175 (type->named_type() != NULL
13176 ? type->named_type()->message_name().c_str()
13177 : "unnamed struct"));
13178 return Expression::make_error(location);
13179 }
13180 if (vals[index] != NULL)
13181 {
13182 error_at(name_expr->location(),
13183 "duplicate value for field %qs in %qs",
13184 Gogo::message_name(name).c_str(),
13185 (type->named_type() != NULL
13186 ? type->named_type()->message_name().c_str()
13187 : "unnamed struct"));
13188 return Expression::make_error(location);
13189 }
13190
07daa4e7 13191 if (type->named_type() != NULL
13192 && type->named_type()->named_object()->package() != NULL
13193 && Gogo::is_hidden_name(sf->field_name()))
13194 error_at(name_expr->location(),
13195 "assignment of unexported field %qs in %qs literal",
13196 Gogo::message_name(sf->field_name()).c_str(),
13197 type->named_type()->message_name().c_str());
07daa4e7 13198
e440a328 13199 vals[index] = val;
0c4f5a19 13200 traverse_order->push_back(index);
e440a328 13201 }
13202
62750cd5 13203 if (!this->all_are_names_)
13204 {
13205 // This is a weird case like bug462 in the testsuite.
13206 if (external_expr == NULL)
13207 error_at(this->location(), "unknown field in %qs literal",
13208 (type->named_type() != NULL
13209 ? type->named_type()->message_name().c_str()
13210 : "unnamed struct"));
13211 else
13212 error_at(external_expr->location(), "unknown field %qs in %qs",
13213 external_no->message_name().c_str(),
13214 (type->named_type() != NULL
13215 ? type->named_type()->message_name().c_str()
13216 : "unnamed struct"));
13217 return Expression::make_error(location);
13218 }
13219
e440a328 13220 Expression_list* list = new Expression_list;
13221 list->reserve(field_count);
13222 for (size_t i = 0; i < field_count; ++i)
13223 list->push_back(vals[i]);
13224
0c4f5a19 13225 Struct_construction_expression* ret =
13226 new Struct_construction_expression(type, list, location);
13227 ret->set_traverse_order(traverse_order);
13228 return ret;
e440a328 13229}
13230
00773463 13231// Used to sort an index/value array.
13232
13233class Index_value_compare
13234{
13235 public:
13236 bool
13237 operator()(const std::pair<unsigned long, Expression*>& a,
13238 const std::pair<unsigned long, Expression*>& b)
13239 { return a.first < b.first; }
13240};
13241
e440a328 13242// Lower an array composite literal.
13243
13244Expression*
113ef6a5 13245Composite_literal_expression::lower_array(Type* type)
e440a328 13246{
b13c66cd 13247 Location location = this->location();
e440a328 13248 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13249 return this->make_array(type, NULL, this->vals_);
e440a328 13250
ffe743ca 13251 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13252 indexes->reserve(this->vals_->size());
00773463 13253 bool indexes_out_of_order = false;
ffe743ca 13254 Expression_list* vals = new Expression_list();
13255 vals->reserve(this->vals_->size());
e440a328 13256 unsigned long index = 0;
13257 Expression_list::const_iterator p = this->vals_->begin();
13258 while (p != this->vals_->end())
13259 {
13260 Expression* index_expr = *p;
13261
13262 ++p;
c484d925 13263 go_assert(p != this->vals_->end());
e440a328 13264 Expression* val = *p;
13265
13266 ++p;
13267
ffe743ca 13268 if (index_expr == NULL)
13269 {
13270 if (!indexes->empty())
13271 indexes->push_back(index);
13272 }
13273 else
e440a328 13274 {
ffe743ca 13275 if (indexes->empty() && !vals->empty())
13276 {
13277 for (size_t i = 0; i < vals->size(); ++i)
13278 indexes->push_back(i);
13279 }
13280
0c77715b 13281 Numeric_constant nc;
13282 if (!index_expr->numeric_constant_value(&nc))
e440a328 13283 {
e440a328 13284 error_at(index_expr->location(),
13285 "index expression is not integer constant");
13286 return Expression::make_error(location);
13287 }
6f6d9955 13288
0c77715b 13289 switch (nc.to_unsigned_long(&index))
e440a328 13290 {
0c77715b 13291 case Numeric_constant::NC_UL_VALID:
13292 break;
13293 case Numeric_constant::NC_UL_NOTINT:
13294 error_at(index_expr->location(),
13295 "index expression is not integer constant");
13296 return Expression::make_error(location);
13297 case Numeric_constant::NC_UL_NEGATIVE:
e440a328 13298 error_at(index_expr->location(), "index expression is negative");
13299 return Expression::make_error(location);
0c77715b 13300 case Numeric_constant::NC_UL_BIG:
e440a328 13301 error_at(index_expr->location(), "index value overflow");
13302 return Expression::make_error(location);
0c77715b 13303 default:
13304 go_unreachable();
e440a328 13305 }
6f6d9955 13306
13307 Named_type* ntype = Type::lookup_integer_type("int");
13308 Integer_type* inttype = ntype->integer_type();
0c77715b 13309 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13310 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13311 {
6f6d9955 13312 error_at(index_expr->location(), "index value overflow");
13313 return Expression::make_error(location);
13314 }
13315
ffe743ca 13316 if (std::find(indexes->begin(), indexes->end(), index)
13317 != indexes->end())
e440a328 13318 {
ffe743ca 13319 error_at(index_expr->location(), "duplicate value for index %lu",
e440a328 13320 index);
13321 return Expression::make_error(location);
13322 }
ffe743ca 13323
00773463 13324 if (!indexes->empty() && index < indexes->back())
13325 indexes_out_of_order = true;
13326
ffe743ca 13327 indexes->push_back(index);
e440a328 13328 }
13329
ffe743ca 13330 vals->push_back(val);
13331
e440a328 13332 ++index;
13333 }
13334
ffe743ca 13335 if (indexes->empty())
13336 {
13337 delete indexes;
13338 indexes = NULL;
13339 }
e440a328 13340
00773463 13341 if (indexes_out_of_order)
13342 {
13343 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13344
13345 V v;
13346 v.reserve(indexes->size());
13347 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13348 for (Expression_list::const_iterator pe = vals->begin();
13349 pe != vals->end();
13350 ++pe, ++pi)
13351 v.push_back(std::make_pair(*pi, *pe));
13352
13353 std::sort(v.begin(), v.end(), Index_value_compare());
13354
13355 delete indexes;
13356 delete vals;
13357 indexes = new std::vector<unsigned long>();
13358 indexes->reserve(v.size());
13359 vals = new Expression_list();
13360 vals->reserve(v.size());
13361
13362 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13363 {
13364 indexes->push_back(p->first);
13365 vals->push_back(p->second);
13366 }
13367 }
13368
ffe743ca 13369 return this->make_array(type, indexes, vals);
e440a328 13370}
13371
13372// Actually build the array composite literal. This handles
13373// [...]{...}.
13374
13375Expression*
ffe743ca 13376Composite_literal_expression::make_array(
13377 Type* type,
13378 const std::vector<unsigned long>* indexes,
13379 Expression_list* vals)
e440a328 13380{
b13c66cd 13381 Location location = this->location();
e440a328 13382 Array_type* at = type->array_type();
ffe743ca 13383
e440a328 13384 if (at->length() != NULL && at->length()->is_nil_expression())
13385 {
ffe743ca 13386 size_t size;
13387 if (vals == NULL)
13388 size = 0;
00773463 13389 else if (indexes != NULL)
13390 size = indexes->back() + 1;
13391 else
ffe743ca 13392 {
13393 size = vals->size();
13394 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13395 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13396 && size >> (it->bits() - 1) != 0)
13397 {
13398 error_at(location, "too many elements in composite literal");
13399 return Expression::make_error(location);
13400 }
13401 }
ffe743ca 13402
e440a328 13403 mpz_t vlen;
13404 mpz_init_set_ui(vlen, size);
13405 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13406 mpz_clear(vlen);
13407 at = Type::make_array_type(at->element_type(), elen);
13408 type = at;
13409 }
ffe743ca 13410 else if (at->length() != NULL
13411 && !at->length()->is_error_expression()
13412 && this->vals_ != NULL)
13413 {
13414 Numeric_constant nc;
13415 unsigned long val;
13416 if (at->length()->numeric_constant_value(&nc)
13417 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13418 {
13419 if (indexes == NULL)
13420 {
13421 if (this->vals_->size() > val)
13422 {
13423 error_at(location, "too many elements in composite literal");
13424 return Expression::make_error(location);
13425 }
13426 }
13427 else
13428 {
00773463 13429 unsigned long max = indexes->back();
ffe743ca 13430 if (max >= val)
13431 {
13432 error_at(location,
13433 ("some element keys in composite literal "
13434 "are out of range"));
13435 return Expression::make_error(location);
13436 }
13437 }
13438 }
13439 }
13440
e440a328 13441 if (at->length() != NULL)
ffe743ca 13442 return new Fixed_array_construction_expression(type, indexes, vals,
13443 location);
e440a328 13444 else
2c809f8f 13445 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13446}
13447
13448// Lower a map composite literal.
13449
13450Expression*
a287720d 13451Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13452 Statement_inserter* inserter,
a287720d 13453 Type* type)
e440a328 13454{
b13c66cd 13455 Location location = this->location();
e440a328 13456 if (this->vals_ != NULL)
13457 {
13458 if (!this->has_keys_)
13459 {
13460 error_at(location, "map composite literal must have keys");
13461 return Expression::make_error(location);
13462 }
13463
a287720d 13464 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13465 p != this->vals_->end();
13466 p += 2)
13467 {
13468 if (*p == NULL)
13469 {
13470 ++p;
13471 error_at((*p)->location(),
13472 "map composite literal must have keys for every value");
13473 return Expression::make_error(location);
13474 }
a287720d 13475 // Make sure we have lowered the key; it may not have been
13476 // lowered in order to handle keys for struct composite
13477 // literals. Lower it now to get the right error message.
13478 if ((*p)->unknown_expression() != NULL)
13479 {
13480 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13481 gogo->lower_expression(function, inserter, &*p);
c484d925 13482 go_assert((*p)->is_error_expression());
a287720d 13483 return Expression::make_error(location);
13484 }
e440a328 13485 }
13486 }
13487
13488 return new Map_construction_expression(type, this->vals_, location);
13489}
13490
d751bb78 13491// Dump ast representation for a composite literal expression.
13492
13493void
13494Composite_literal_expression::do_dump_expression(
13495 Ast_dump_context* ast_dump_context) const
13496{
8b1c301d 13497 ast_dump_context->ostream() << "composite(";
d751bb78 13498 ast_dump_context->dump_type(this->type_);
13499 ast_dump_context->ostream() << ", {";
8b1c301d 13500 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13501 ast_dump_context->ostream() << "})";
13502}
13503
e440a328 13504// Make a composite literal expression.
13505
13506Expression*
13507Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13508 Expression_list* vals, bool all_are_names,
b13c66cd 13509 Location location)
e440a328 13510{
13511 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13512 all_are_names, location);
e440a328 13513}
13514
13515// Return whether this expression is a composite literal.
13516
13517bool
13518Expression::is_composite_literal() const
13519{
13520 switch (this->classification_)
13521 {
13522 case EXPRESSION_COMPOSITE_LITERAL:
13523 case EXPRESSION_STRUCT_CONSTRUCTION:
13524 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13525 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13526 case EXPRESSION_MAP_CONSTRUCTION:
13527 return true;
13528 default:
13529 return false;
13530 }
13531}
13532
13533// Return whether this expression is a composite literal which is not
13534// constant.
13535
13536bool
13537Expression::is_nonconstant_composite_literal() const
13538{
13539 switch (this->classification_)
13540 {
13541 case EXPRESSION_STRUCT_CONSTRUCTION:
13542 {
13543 const Struct_construction_expression *psce =
13544 static_cast<const Struct_construction_expression*>(this);
13545 return !psce->is_constant_struct();
13546 }
13547 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13548 {
13549 const Fixed_array_construction_expression *pace =
13550 static_cast<const Fixed_array_construction_expression*>(this);
13551 return !pace->is_constant_array();
13552 }
2c809f8f 13553 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13554 {
2c809f8f 13555 const Slice_construction_expression *pace =
13556 static_cast<const Slice_construction_expression*>(this);
e440a328 13557 return !pace->is_constant_array();
13558 }
13559 case EXPRESSION_MAP_CONSTRUCTION:
13560 return true;
13561 default:
13562 return false;
13563 }
13564}
13565
35a54f17 13566// Return true if this is a variable or temporary_variable.
13567
13568bool
13569Expression::is_variable() const
13570{
13571 switch (this->classification_)
13572 {
13573 case EXPRESSION_VAR_REFERENCE:
13574 case EXPRESSION_TEMPORARY_REFERENCE:
13575 case EXPRESSION_SET_AND_USE_TEMPORARY:
13576 return true;
13577 default:
13578 return false;
13579 }
13580}
13581
e440a328 13582// Return true if this is a reference to a local variable.
13583
13584bool
13585Expression::is_local_variable() const
13586{
13587 const Var_expression* ve = this->var_expression();
13588 if (ve == NULL)
13589 return false;
13590 const Named_object* no = ve->named_object();
13591 return (no->is_result_variable()
13592 || (no->is_variable() && !no->var_value()->is_global()));
13593}
13594
13595// Class Type_guard_expression.
13596
13597// Traversal.
13598
13599int
13600Type_guard_expression::do_traverse(Traverse* traverse)
13601{
13602 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13603 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13604 return TRAVERSE_EXIT;
13605 return TRAVERSE_CONTINUE;
13606}
13607
2c809f8f 13608Expression*
13609Type_guard_expression::do_flatten(Gogo*, Named_object*,
13610 Statement_inserter* inserter)
13611{
13612 if (!this->expr_->is_variable())
13613 {
13614 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13615 this->location());
13616 inserter->insert(temp);
13617 this->expr_ =
13618 Expression::make_temporary_reference(temp, this->location());
13619 }
13620 return this;
13621}
13622
e440a328 13623// Check types of a type guard expression. The expression must have
13624// an interface type, but the actual type conversion is checked at run
13625// time.
13626
13627void
13628Type_guard_expression::do_check_types(Gogo*)
13629{
e440a328 13630 Type* expr_type = this->expr_->type();
7e9da23f 13631 if (expr_type->interface_type() == NULL)
f725ade8 13632 {
5c13bd80 13633 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 13634 this->report_error(_("type assertion only valid for interface types"));
13635 this->set_is_error();
13636 }
e440a328 13637 else if (this->type_->interface_type() == NULL)
13638 {
13639 std::string reason;
13640 if (!expr_type->interface_type()->implements_interface(this->type_,
13641 &reason))
13642 {
5c13bd80 13643 if (!this->type_->is_error())
e440a328 13644 {
f725ade8 13645 if (reason.empty())
13646 this->report_error(_("impossible type assertion: "
13647 "type does not implement interface"));
13648 else
13649 error_at(this->location(),
13650 ("impossible type assertion: "
13651 "type does not implement interface (%s)"),
13652 reason.c_str());
e440a328 13653 }
f725ade8 13654 this->set_is_error();
e440a328 13655 }
13656 }
13657}
13658
13659// Return a tree for a type guard expression.
13660
13661tree
13662Type_guard_expression::do_get_tree(Translate_context* context)
13663{
2c809f8f 13664 Expression* conversion;
7e9da23f 13665 if (this->type_->interface_type() != NULL)
2c809f8f 13666 conversion =
13667 Expression::convert_interface_to_interface(this->type_, this->expr_,
13668 true, this->location());
e440a328 13669 else
2c809f8f 13670 conversion =
13671 Expression::convert_for_assignment(context->gogo(), this->type_,
13672 this->expr_, this->location());
13673
13674 return conversion->get_tree(context);
e440a328 13675}
13676
d751bb78 13677// Dump ast representation for a type guard expression.
13678
13679void
2c809f8f 13680Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 13681 const
13682{
13683 this->expr_->dump_expression(ast_dump_context);
13684 ast_dump_context->ostream() << ".";
13685 ast_dump_context->dump_type(this->type_);
13686}
13687
e440a328 13688// Make a type guard expression.
13689
13690Expression*
13691Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 13692 Location location)
e440a328 13693{
13694 return new Type_guard_expression(expr, type, location);
13695}
13696
2c809f8f 13697// Class Heap_expression.
e440a328 13698
2c809f8f 13699// When you take the address of an escaping expression, it is allocated
e440a328 13700// on the heap. This class implements that.
13701
2c809f8f 13702class Heap_expression : public Expression
e440a328 13703{
13704 public:
2c809f8f 13705 Heap_expression(Expression* expr, Location location)
13706 : Expression(EXPRESSION_HEAP, location),
e440a328 13707 expr_(expr)
13708 { }
13709
13710 protected:
13711 int
13712 do_traverse(Traverse* traverse)
13713 { return Expression::traverse(&this->expr_, traverse); }
13714
13715 Type*
13716 do_type()
13717 { return Type::make_pointer_type(this->expr_->type()); }
13718
13719 void
13720 do_determine_type(const Type_context*)
13721 { this->expr_->determine_type_no_context(); }
13722
13723 Expression*
13724 do_copy()
13725 {
2c809f8f 13726 return Expression::make_heap_expression(this->expr_->copy(),
13727 this->location());
e440a328 13728 }
13729
13730 tree
13731 do_get_tree(Translate_context*);
13732
13733 // We only export global objects, and the parser does not generate
13734 // this in global scope.
13735 void
13736 do_export(Export*) const
c3e6f413 13737 { go_unreachable(); }
e440a328 13738
d751bb78 13739 void
13740 do_dump_expression(Ast_dump_context*) const;
13741
e440a328 13742 private:
2c809f8f 13743 // The expression which is being put on the heap.
e440a328 13744 Expression* expr_;
13745};
13746
2c809f8f 13747// Return a tree which allocates an expression on the heap.
e440a328 13748
13749tree
2c809f8f 13750Heap_expression::do_get_tree(Translate_context* context)
e440a328 13751{
02c19a1a 13752 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
e440a328 13753 return error_mark_node;
2c809f8f 13754
02c19a1a 13755 Location loc = this->location();
2c809f8f 13756 Gogo* gogo = context->gogo();
02c19a1a 13757 Btype* btype = this->type()->get_backend(gogo);
13758 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
13759 Bexpression* space = tree_to_expr(alloc->get_tree(context));
13760
13761 Bstatement* decl;
13762 Named_object* fn = context->function();
13763 go_assert(fn != NULL);
13764 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13765 Bvariable* space_temp =
13766 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13767 space, true, loc, &decl);
13768 space = gogo->backend()->var_expression(space_temp, loc);
9b27b43c 13769 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13770 Bexpression* ref =
13771 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
02c19a1a 13772
13773 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
13774 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13775 decl = gogo->backend()->compound_statement(decl, assn);
13776 space = gogo->backend()->var_expression(space_temp, loc);
13777 Bexpression* ret = gogo->backend()->compound_expression(decl, space, loc);
13778 return expr_to_tree(ret);
e440a328 13779}
13780
2c809f8f 13781// Dump ast representation for a heap expression.
d751bb78 13782
13783void
2c809f8f 13784Heap_expression::do_dump_expression(
d751bb78 13785 Ast_dump_context* ast_dump_context) const
13786{
13787 ast_dump_context->ostream() << "&(";
13788 ast_dump_context->dump_expression(this->expr_);
13789 ast_dump_context->ostream() << ")";
13790}
13791
2c809f8f 13792// Allocate an expression on the heap.
e440a328 13793
13794Expression*
2c809f8f 13795Expression::make_heap_expression(Expression* expr, Location location)
e440a328 13796{
2c809f8f 13797 return new Heap_expression(expr, location);
e440a328 13798}
13799
13800// Class Receive_expression.
13801
13802// Return the type of a receive expression.
13803
13804Type*
13805Receive_expression::do_type()
13806{
13807 Channel_type* channel_type = this->channel_->type()->channel_type();
13808 if (channel_type == NULL)
13809 return Type::make_error_type();
13810 return channel_type->element_type();
13811}
13812
13813// Check types for a receive expression.
13814
13815void
13816Receive_expression::do_check_types(Gogo*)
13817{
13818 Type* type = this->channel_->type();
5c13bd80 13819 if (type->is_error())
e440a328 13820 {
13821 this->set_is_error();
13822 return;
13823 }
13824 if (type->channel_type() == NULL)
13825 {
13826 this->report_error(_("expected channel"));
13827 return;
13828 }
13829 if (!type->channel_type()->may_receive())
13830 {
13831 this->report_error(_("invalid receive on send-only channel"));
13832 return;
13833 }
13834}
13835
2c809f8f 13836// Flattening for receive expressions creates a temporary variable to store
13837// received data in for receives.
13838
13839Expression*
13840Receive_expression::do_flatten(Gogo*, Named_object*,
13841 Statement_inserter* inserter)
13842{
13843 Channel_type* channel_type = this->channel_->type()->channel_type();
13844 if (channel_type == NULL)
13845 {
13846 go_assert(saw_errors());
13847 return this;
13848 }
13849
13850 Type* element_type = channel_type->element_type();
13851 if (this->temp_receiver_ == NULL)
13852 {
13853 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13854 this->location());
13855 this->temp_receiver_->set_is_address_taken();
13856 inserter->insert(this->temp_receiver_);
13857 }
13858
13859 return this;
13860}
13861
e440a328 13862// Get a tree for a receive expression.
13863
13864tree
13865Receive_expression::do_get_tree(Translate_context* context)
13866{
f24f10bb 13867 Location loc = this->location();
13868
e440a328 13869 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 13870 if (channel_type == NULL)
13871 {
c484d925 13872 go_assert(this->channel_->type()->is_error());
5b8368f4 13873 return error_mark_node;
13874 }
f24f10bb 13875 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 13876
2c809f8f 13877 Expression* recv_ref =
13878 Expression::make_temporary_reference(this->temp_receiver_, loc);
13879 Expression* recv_addr =
13880 Expression::make_temporary_reference(this->temp_receiver_, loc);
13881 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13882 Expression* recv =
13883 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13884 td, this->channel_, recv_addr);
13885 recv = Expression::make_compound(recv, recv_ref, loc);
13886 return recv->get_tree(context);
e440a328 13887}
13888
d751bb78 13889// Dump ast representation for a receive expression.
13890
13891void
13892Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13893{
13894 ast_dump_context->ostream() << " <- " ;
13895 ast_dump_context->dump_expression(channel_);
13896}
13897
e440a328 13898// Make a receive expression.
13899
13900Receive_expression*
b13c66cd 13901Expression::make_receive(Expression* channel, Location location)
e440a328 13902{
13903 return new Receive_expression(channel, location);
13904}
13905
e440a328 13906// An expression which evaluates to a pointer to the type descriptor
13907// of a type.
13908
13909class Type_descriptor_expression : public Expression
13910{
13911 public:
b13c66cd 13912 Type_descriptor_expression(Type* type, Location location)
e440a328 13913 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13914 type_(type)
13915 { }
13916
13917 protected:
13918 Type*
13919 do_type()
13920 { return Type::make_type_descriptor_ptr_type(); }
13921
f9ca30f9 13922 bool
13923 do_is_immutable() const
13924 { return true; }
13925
e440a328 13926 void
13927 do_determine_type(const Type_context*)
13928 { }
13929
13930 Expression*
13931 do_copy()
13932 { return this; }
13933
13934 tree
13935 do_get_tree(Translate_context* context)
a1d23b41 13936 {
175a4612 13937 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
13938 this->location());
13939 return expr_to_tree(ret);
a1d23b41 13940 }
e440a328 13941
d751bb78 13942 void
13943 do_dump_expression(Ast_dump_context*) const;
13944
e440a328 13945 private:
13946 // The type for which this is the descriptor.
13947 Type* type_;
13948};
13949
d751bb78 13950// Dump ast representation for a type descriptor expression.
13951
13952void
13953Type_descriptor_expression::do_dump_expression(
13954 Ast_dump_context* ast_dump_context) const
13955{
13956 ast_dump_context->dump_type(this->type_);
13957}
13958
e440a328 13959// Make a type descriptor expression.
13960
13961Expression*
b13c66cd 13962Expression::make_type_descriptor(Type* type, Location location)
e440a328 13963{
13964 return new Type_descriptor_expression(type, location);
13965}
13966
13967// An expression which evaluates to some characteristic of a type.
13968// This is only used to initialize fields of a type descriptor. Using
13969// a new expression class is slightly inefficient but gives us a good
13970// separation between the frontend and the middle-end with regard to
13971// how types are laid out.
13972
13973class Type_info_expression : public Expression
13974{
13975 public:
13976 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 13977 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 13978 type_(type), type_info_(type_info)
13979 { }
13980
13981 protected:
0e168074 13982 bool
13983 do_is_immutable() const
13984 { return true; }
13985
e440a328 13986 Type*
13987 do_type();
13988
13989 void
13990 do_determine_type(const Type_context*)
13991 { }
13992
13993 Expression*
13994 do_copy()
13995 { return this; }
13996
13997 tree
13998 do_get_tree(Translate_context* context);
13999
d751bb78 14000 void
14001 do_dump_expression(Ast_dump_context*) const;
14002
e440a328 14003 private:
14004 // The type for which we are getting information.
14005 Type* type_;
14006 // What information we want.
14007 Type_info type_info_;
14008};
14009
14010// The type is chosen to match what the type descriptor struct
14011// expects.
14012
14013Type*
14014Type_info_expression::do_type()
14015{
14016 switch (this->type_info_)
14017 {
14018 case TYPE_INFO_SIZE:
14019 return Type::lookup_integer_type("uintptr");
14020 case TYPE_INFO_ALIGNMENT:
14021 case TYPE_INFO_FIELD_ALIGNMENT:
14022 return Type::lookup_integer_type("uint8");
14023 default:
c3e6f413 14024 go_unreachable();
e440a328 14025 }
14026}
14027
14028// Return type information in GENERIC.
14029
14030tree
14031Type_info_expression::do_get_tree(Translate_context* context)
14032{
927a01eb 14033 Btype* btype = this->type_->get_backend(context->gogo());
14034 Gogo* gogo = context->gogo();
14035 size_t val;
14036 switch (this->type_info_)
e440a328 14037 {
927a01eb 14038 case TYPE_INFO_SIZE:
14039 val = gogo->backend()->type_size(btype);
14040 break;
14041 case TYPE_INFO_ALIGNMENT:
14042 val = gogo->backend()->type_alignment(btype);
14043 break;
14044 case TYPE_INFO_FIELD_ALIGNMENT:
14045 val = gogo->backend()->type_field_alignment(btype);
14046 break;
14047 default:
14048 go_unreachable();
e440a328 14049 }
287cdcf4 14050 mpz_t cst;
14051 mpz_init_set_ui(cst, val);
14052 Btype* int_btype = this->type()->get_backend(gogo);
14053 Bexpression* ret =
14054 gogo->backend()->integer_constant_expression(int_btype, cst);
14055 mpz_clear(cst);
14056 return expr_to_tree(ret);
e440a328 14057}
14058
d751bb78 14059// Dump ast representation for a type info expression.
14060
14061void
14062Type_info_expression::do_dump_expression(
14063 Ast_dump_context* ast_dump_context) const
14064{
14065 ast_dump_context->ostream() << "typeinfo(";
14066 ast_dump_context->dump_type(this->type_);
14067 ast_dump_context->ostream() << ",";
14068 ast_dump_context->ostream() <<
14069 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14070 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14071 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14072 : "unknown");
14073 ast_dump_context->ostream() << ")";
14074}
14075
e440a328 14076// Make a type info expression.
14077
14078Expression*
14079Expression::make_type_info(Type* type, Type_info type_info)
14080{
14081 return new Type_info_expression(type, type_info);
14082}
14083
35a54f17 14084// An expression that evaluates to some characteristic of a slice.
14085// This is used when indexing, bound-checking, or nil checking a slice.
14086
14087class Slice_info_expression : public Expression
14088{
14089 public:
14090 Slice_info_expression(Expression* slice, Slice_info slice_info,
14091 Location location)
14092 : Expression(EXPRESSION_SLICE_INFO, location),
14093 slice_(slice), slice_info_(slice_info)
14094 { }
14095
14096 protected:
14097 Type*
14098 do_type();
14099
14100 void
14101 do_determine_type(const Type_context*)
14102 { }
14103
14104 Expression*
14105 do_copy()
14106 {
14107 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14108 this->location());
14109 }
14110
14111 tree
14112 do_get_tree(Translate_context* context);
14113
14114 void
14115 do_dump_expression(Ast_dump_context*) const;
14116
14117 void
14118 do_issue_nil_check()
14119 { this->slice_->issue_nil_check(); }
14120
14121 private:
14122 // The slice for which we are getting information.
14123 Expression* slice_;
14124 // What information we want.
14125 Slice_info slice_info_;
14126};
14127
14128// Return the type of the slice info.
14129
14130Type*
14131Slice_info_expression::do_type()
14132{
14133 switch (this->slice_info_)
14134 {
14135 case SLICE_INFO_VALUE_POINTER:
14136 return Type::make_pointer_type(
14137 this->slice_->type()->array_type()->element_type());
14138 case SLICE_INFO_LENGTH:
14139 case SLICE_INFO_CAPACITY:
14140 return Type::lookup_integer_type("int");
14141 default:
14142 go_unreachable();
14143 }
14144}
14145
14146// Return slice information in GENERIC.
14147
14148tree
14149Slice_info_expression::do_get_tree(Translate_context* context)
14150{
14151 Gogo* gogo = context->gogo();
14152
14153 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14154 Bexpression* ret;
14155 switch (this->slice_info_)
14156 {
14157 case SLICE_INFO_VALUE_POINTER:
14158 case SLICE_INFO_LENGTH:
14159 case SLICE_INFO_CAPACITY:
14160 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14161 this->location());
14162 break;
14163 default:
14164 go_unreachable();
14165 }
14166 return expr_to_tree(ret);
14167}
14168
14169// Dump ast representation for a type info expression.
14170
14171void
14172Slice_info_expression::do_dump_expression(
14173 Ast_dump_context* ast_dump_context) const
14174{
14175 ast_dump_context->ostream() << "sliceinfo(";
14176 this->slice_->dump_expression(ast_dump_context);
14177 ast_dump_context->ostream() << ",";
14178 ast_dump_context->ostream() <<
14179 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14180 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14181 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14182 : "unknown");
14183 ast_dump_context->ostream() << ")";
14184}
14185
14186// Make a slice info expression.
14187
14188Expression*
14189Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14190 Location location)
14191{
14192 return new Slice_info_expression(slice, slice_info, location);
14193}
14194
2c809f8f 14195// An expression that represents a slice value: a struct with value pointer,
14196// length, and capacity fields.
14197
14198class Slice_value_expression : public Expression
14199{
14200 public:
14201 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14202 Expression* cap, Location location)
14203 : Expression(EXPRESSION_SLICE_VALUE, location),
14204 type_(type), valptr_(valptr), len_(len), cap_(cap)
14205 { }
14206
14207 protected:
14208 int
14209 do_traverse(Traverse*);
14210
14211 Type*
14212 do_type()
14213 { return this->type_; }
14214
14215 void
14216 do_determine_type(const Type_context*)
14217 { go_unreachable(); }
14218
14219 Expression*
14220 do_copy()
14221 {
14222 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14223 this->len_->copy(), this->cap_->copy(),
14224 this->location());
14225 }
14226
14227 tree
14228 do_get_tree(Translate_context* context);
14229
14230 void
14231 do_dump_expression(Ast_dump_context*) const;
14232
14233 private:
14234 // The type of the slice value.
14235 Type* type_;
14236 // The pointer to the values in the slice.
14237 Expression* valptr_;
14238 // The length of the slice.
14239 Expression* len_;
14240 // The capacity of the slice.
14241 Expression* cap_;
14242};
14243
14244int
14245Slice_value_expression::do_traverse(Traverse* traverse)
14246{
14247 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14248 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14249 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14250 return TRAVERSE_EXIT;
14251 return TRAVERSE_CONTINUE;
14252}
14253
14254tree
14255Slice_value_expression::do_get_tree(Translate_context* context)
14256{
14257 std::vector<Bexpression*> vals(3);
14258 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14259 vals[1] = tree_to_expr(this->len_->get_tree(context));
14260 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14261
14262 Gogo* gogo = context->gogo();
14263 Btype* btype = this->type_->get_backend(gogo);
14264 Bexpression* ret =
14265 gogo->backend()->constructor_expression(btype, vals, this->location());
14266 return expr_to_tree(ret);
14267}
14268
14269void
14270Slice_value_expression::do_dump_expression(
14271 Ast_dump_context* ast_dump_context) const
14272{
14273 ast_dump_context->ostream() << "slicevalue(";
14274 ast_dump_context->ostream() << "values: ";
14275 this->valptr_->dump_expression(ast_dump_context);
14276 ast_dump_context->ostream() << ", length: ";
14277 this->len_->dump_expression(ast_dump_context);
14278 ast_dump_context->ostream() << ", capacity: ";
14279 this->cap_->dump_expression(ast_dump_context);
14280 ast_dump_context->ostream() << ")";
14281}
14282
14283Expression*
14284Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14285 Expression* cap, Location location)
14286{
14287 go_assert(at->is_slice_type());
14288 return new Slice_value_expression(at, valptr, len, cap, location);
14289}
2387f644 14290
14291// An expression that evaluates to some characteristic of a non-empty interface.
14292// This is used to access the method table or underlying object of an interface.
14293
14294class Interface_info_expression : public Expression
14295{
14296 public:
14297 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14298 Location location)
2387f644 14299 : Expression(EXPRESSION_INTERFACE_INFO, location),
14300 iface_(iface), iface_info_(iface_info)
14301 { }
14302
14303 protected:
14304 Type*
14305 do_type();
14306
14307 void
14308 do_determine_type(const Type_context*)
14309 { }
14310
14311 Expression*
14312 do_copy()
14313 {
14314 return new Interface_info_expression(this->iface_->copy(),
14315 this->iface_info_, this->location());
14316 }
14317
14318 tree
14319 do_get_tree(Translate_context* context);
14320
14321 void
14322 do_dump_expression(Ast_dump_context*) const;
14323
14324 void
14325 do_issue_nil_check()
14326 { this->iface_->issue_nil_check(); }
14327
14328 private:
14329 // The interface for which we are getting information.
14330 Expression* iface_;
14331 // What information we want.
14332 Interface_info iface_info_;
14333};
14334
14335// Return the type of the interface info.
14336
14337Type*
14338Interface_info_expression::do_type()
14339{
14340 switch (this->iface_info_)
14341 {
14342 case INTERFACE_INFO_METHODS:
14343 {
2c809f8f 14344 Type* pdt = Type::make_type_descriptor_ptr_type();
14345 if (this->iface_->type()->interface_type()->is_empty())
14346 return pdt;
14347
2387f644 14348 Location loc = this->location();
14349 Struct_field_list* sfl = new Struct_field_list();
2387f644 14350 sfl->push_back(
14351 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14352
14353 Interface_type* itype = this->iface_->type()->interface_type();
14354 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14355 p != itype->methods()->end();
14356 ++p)
14357 {
14358 Function_type* ft = p->type()->function_type();
14359 go_assert(ft->receiver() == NULL);
14360
14361 const Typed_identifier_list* params = ft->parameters();
14362 Typed_identifier_list* mparams = new Typed_identifier_list();
14363 if (params != NULL)
14364 mparams->reserve(params->size() + 1);
14365 Type* vt = Type::make_pointer_type(Type::make_void_type());
14366 mparams->push_back(Typed_identifier("", vt, ft->location()));
14367 if (params != NULL)
14368 {
14369 for (Typed_identifier_list::const_iterator pp = params->begin();
14370 pp != params->end();
14371 ++pp)
14372 mparams->push_back(*pp);
14373 }
14374
14375 Typed_identifier_list* mresults = (ft->results() == NULL
14376 ? NULL
14377 : ft->results()->copy());
14378 Backend_function_type* mft =
14379 Type::make_backend_function_type(NULL, mparams, mresults,
14380 ft->location());
14381
14382 std::string fname = Gogo::unpack_hidden_name(p->name());
14383 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14384 }
14385
14386 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14387 }
14388 case INTERFACE_INFO_OBJECT:
14389 return Type::make_pointer_type(Type::make_void_type());
14390 default:
14391 go_unreachable();
14392 }
14393}
14394
14395// Return interface information in GENERIC.
14396
14397tree
14398Interface_info_expression::do_get_tree(Translate_context* context)
14399{
14400 Gogo* gogo = context->gogo();
14401
14402 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14403 Bexpression* ret;
14404 switch (this->iface_info_)
14405 {
14406 case INTERFACE_INFO_METHODS:
14407 case INTERFACE_INFO_OBJECT:
14408 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14409 this->location());
14410 break;
14411 default:
14412 go_unreachable();
14413 }
14414 return expr_to_tree(ret);
14415}
14416
14417// Dump ast representation for an interface info expression.
14418
14419void
14420Interface_info_expression::do_dump_expression(
14421 Ast_dump_context* ast_dump_context) const
14422{
2c809f8f 14423 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14424 ast_dump_context->ostream() << "interfaceinfo(";
14425 this->iface_->dump_expression(ast_dump_context);
14426 ast_dump_context->ostream() << ",";
14427 ast_dump_context->ostream() <<
2c809f8f 14428 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14429 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14430 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14431 : "unknown");
14432 ast_dump_context->ostream() << ")";
14433}
14434
14435// Make an interface info expression.
14436
14437Expression*
14438Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14439 Location location)
14440{
14441 return new Interface_info_expression(iface, iface_info, location);
14442}
14443
2c809f8f 14444// An expression that represents an interface value. The first field is either
14445// a type descriptor for an empty interface or a pointer to the interface method
14446// table for a non-empty interface. The second field is always the object.
14447
14448class Interface_value_expression : public Expression
14449{
14450 public:
14451 Interface_value_expression(Type* type, Expression* first_field,
14452 Expression* obj, Location location)
14453 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14454 type_(type), first_field_(first_field), obj_(obj)
14455 { }
14456
14457 protected:
14458 int
14459 do_traverse(Traverse*);
14460
14461 Type*
14462 do_type()
14463 { return this->type_; }
14464
14465 void
14466 do_determine_type(const Type_context*)
14467 { go_unreachable(); }
14468
14469 Expression*
14470 do_copy()
14471 {
14472 return new Interface_value_expression(this->type_,
14473 this->first_field_->copy(),
14474 this->obj_->copy(), this->location());
14475 }
14476
14477 tree
14478 do_get_tree(Translate_context* context);
14479
14480 void
14481 do_dump_expression(Ast_dump_context*) const;
14482
14483 private:
14484 // The type of the interface value.
14485 Type* type_;
14486 // The first field of the interface (either a type descriptor or a pointer
14487 // to the method table.
14488 Expression* first_field_;
14489 // The underlying object of the interface.
14490 Expression* obj_;
14491};
14492
14493int
14494Interface_value_expression::do_traverse(Traverse* traverse)
14495{
14496 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14497 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14498 return TRAVERSE_EXIT;
14499 return TRAVERSE_CONTINUE;
14500}
14501
14502tree
14503Interface_value_expression::do_get_tree(Translate_context* context)
14504{
14505 std::vector<Bexpression*> vals(2);
14506 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14507 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14508
14509 Gogo* gogo = context->gogo();
14510 Btype* btype = this->type_->get_backend(gogo);
14511 Bexpression* ret =
14512 gogo->backend()->constructor_expression(btype, vals, this->location());
14513 return expr_to_tree(ret);
14514}
14515
14516void
14517Interface_value_expression::do_dump_expression(
14518 Ast_dump_context* ast_dump_context) const
14519{
14520 ast_dump_context->ostream() << "interfacevalue(";
14521 ast_dump_context->ostream() <<
14522 (this->type_->interface_type()->is_empty()
14523 ? "type_descriptor: "
14524 : "methods: ");
14525 this->first_field_->dump_expression(ast_dump_context);
14526 ast_dump_context->ostream() << ", object: ";
14527 this->obj_->dump_expression(ast_dump_context);
14528 ast_dump_context->ostream() << ")";
14529}
14530
14531Expression*
14532Expression::make_interface_value(Type* type, Expression* first_value,
14533 Expression* object, Location location)
14534{
14535 return new Interface_value_expression(type, first_value, object, location);
14536}
14537
14538// An interface method table for a pair of types: an interface type and a type
14539// that implements that interface.
14540
14541class Interface_mtable_expression : public Expression
14542{
14543 public:
14544 Interface_mtable_expression(Interface_type* itype, Type* type,
14545 bool is_pointer, Location location)
14546 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14547 itype_(itype), type_(type), is_pointer_(is_pointer),
14548 method_table_type_(NULL), bvar_(NULL)
14549 { }
14550
14551 protected:
14552 int
14553 do_traverse(Traverse*);
14554
14555 Type*
14556 do_type();
14557
14558 bool
14559 is_immutable() const
14560 { return true; }
14561
14562 void
14563 do_determine_type(const Type_context*)
14564 { go_unreachable(); }
14565
14566 Expression*
14567 do_copy()
14568 {
14569 return new Interface_mtable_expression(this->itype_, this->type_,
14570 this->is_pointer_, this->location());
14571 }
14572
14573 bool
14574 do_is_addressable() const
14575 { return true; }
14576
14577 tree
14578 do_get_tree(Translate_context* context);
14579
14580 void
14581 do_dump_expression(Ast_dump_context*) const;
14582
14583 private:
14584 // The interface type for which the methods are defined.
14585 Interface_type* itype_;
14586 // The type to construct the interface method table for.
14587 Type* type_;
14588 // Whether this table contains the method set for the receiver type or the
14589 // pointer receiver type.
14590 bool is_pointer_;
14591 // The type of the method table.
14592 Type* method_table_type_;
14593 // The backend variable that refers to the interface method table.
14594 Bvariable* bvar_;
14595};
14596
14597int
14598Interface_mtable_expression::do_traverse(Traverse* traverse)
14599{
14600 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14601 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14602 return TRAVERSE_EXIT;
14603 return TRAVERSE_CONTINUE;
14604}
14605
14606Type*
14607Interface_mtable_expression::do_type()
14608{
14609 if (this->method_table_type_ != NULL)
14610 return this->method_table_type_;
14611
14612 const Typed_identifier_list* interface_methods = this->itype_->methods();
14613 go_assert(!interface_methods->empty());
14614
14615 Struct_field_list* sfl = new Struct_field_list;
14616 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14617 this->location());
14618 sfl->push_back(Struct_field(tid));
14619 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14620 p != interface_methods->end();
14621 ++p)
14622 sfl->push_back(Struct_field(*p));
14623 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14624 return this->method_table_type_;
14625}
14626
14627tree
14628Interface_mtable_expression::do_get_tree(Translate_context* context)
14629{
14630 Gogo* gogo = context->gogo();
14631 Bexpression* ret;
14632 Location loc = Linemap::predeclared_location();
14633 if (this->bvar_ != NULL)
14634 {
14635 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14636 return expr_to_tree(ret);
14637 }
14638
14639 const Typed_identifier_list* interface_methods = this->itype_->methods();
14640 go_assert(!interface_methods->empty());
14641
14642 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14643 + this->itype_->mangled_name(gogo)
14644 + "__"
14645 + this->type_->mangled_name(gogo));
14646
14647 // See whether this interface has any hidden methods.
14648 bool has_hidden_methods = false;
14649 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14650 p != interface_methods->end();
14651 ++p)
14652 {
14653 if (Gogo::is_hidden_name(p->name()))
14654 {
14655 has_hidden_methods = true;
14656 break;
14657 }
14658 }
14659
14660 // We already know that the named type is convertible to the
14661 // interface. If the interface has hidden methods, and the named
14662 // type is defined in a different package, then the interface
14663 // conversion table will be defined by that other package.
14664 if (has_hidden_methods
14665 && this->type_->named_type() != NULL
14666 && this->type_->named_type()->named_object()->package() != NULL)
14667 {
14668 Btype* btype = this->type()->get_backend(gogo);
14669 this->bvar_ =
14670 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14671 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14672 return expr_to_tree(ret);
14673 }
14674
14675 // The first element is the type descriptor.
14676 Type* td_type;
14677 if (!this->is_pointer_)
14678 td_type = this->type_;
14679 else
14680 td_type = Type::make_pointer_type(this->type_);
14681
14682 // Build an interface method table for a type: a type descriptor followed by a
14683 // list of function pointers, one for each interface method. This is used for
14684 // interfaces.
14685 Expression_list* svals = new Expression_list();
14686 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14687
14688 Named_type* nt = this->type_->named_type();
14689 Struct_type* st = this->type_->struct_type();
14690 go_assert(nt != NULL || st != NULL);
14691
14692 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14693 p != interface_methods->end();
14694 ++p)
14695 {
14696 bool is_ambiguous;
14697 Method* m;
14698 if (nt != NULL)
14699 m = nt->method_function(p->name(), &is_ambiguous);
14700 else
14701 m = st->method_function(p->name(), &is_ambiguous);
14702 go_assert(m != NULL);
14703 Named_object* no = m->named_object();
14704
14705 go_assert(no->is_function() || no->is_function_declaration());
14706 svals->push_back(Expression::make_func_code_reference(no, loc));
14707 }
14708
14709 Btype* btype = this->type()->get_backend(gogo);
14710 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14711 svals, loc);
14712 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14713
14714 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14715 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14716 !is_public, btype, loc);
14717 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14718 !is_public, btype, loc, ctor);
14719 ret = gogo->backend()->var_expression(this->bvar_, loc);
14720 return expr_to_tree(ret);
14721}
14722
14723void
14724Interface_mtable_expression::do_dump_expression(
14725 Ast_dump_context* ast_dump_context) const
14726{
14727 ast_dump_context->ostream() << "__go_"
14728 << (this->is_pointer_ ? "pimt__" : "imt_");
14729 ast_dump_context->dump_type(this->itype_);
14730 ast_dump_context->ostream() << "__";
14731 ast_dump_context->dump_type(this->type_);
14732}
14733
14734Expression*
14735Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14736 bool is_pointer, Location location)
14737{
14738 return new Interface_mtable_expression(itype, type, is_pointer, location);
14739}
14740
e440a328 14741// An expression which evaluates to the offset of a field within a
14742// struct. This, like Type_info_expression, q.v., is only used to
14743// initialize fields of a type descriptor.
14744
14745class Struct_field_offset_expression : public Expression
14746{
14747 public:
14748 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 14749 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14750 Linemap::predeclared_location()),
e440a328 14751 type_(type), field_(field)
14752 { }
14753
14754 protected:
f23d7786 14755 bool
14756 do_is_immutable() const
14757 { return true; }
14758
e440a328 14759 Type*
14760 do_type()
14761 { return Type::lookup_integer_type("uintptr"); }
14762
14763 void
14764 do_determine_type(const Type_context*)
14765 { }
14766
14767 Expression*
14768 do_copy()
14769 { return this; }
14770
14771 tree
14772 do_get_tree(Translate_context* context);
14773
d751bb78 14774 void
14775 do_dump_expression(Ast_dump_context*) const;
14776
e440a328 14777 private:
14778 // The type of the struct.
14779 Struct_type* type_;
14780 // The field.
14781 const Struct_field* field_;
14782};
14783
14784// Return a struct field offset in GENERIC.
14785
14786tree
14787Struct_field_offset_expression::do_get_tree(Translate_context* context)
14788{
e440a328 14789 const Struct_field_list* fields = this->type_->fields();
e440a328 14790 Struct_field_list::const_iterator p;
2c8bda43 14791 unsigned i = 0;
e440a328 14792 for (p = fields->begin();
14793 p != fields->end();
2c8bda43 14794 ++p, ++i)
14795 if (&*p == this->field_)
14796 break;
c484d925 14797 go_assert(&*p == this->field_);
e440a328 14798
2c8bda43 14799 Gogo* gogo = context->gogo();
14800 Btype* btype = this->type_->get_backend(gogo);
14801
14802 size_t offset = gogo->backend()->type_field_offset(btype, i);
14803 mpz_t offsetval;
14804 mpz_init_set_ui(offsetval, offset);
14805 Type* uptr_type = Type::lookup_integer_type("uintptr");
14806 Expression* ret = Expression::make_integer(&offsetval, uptr_type,
14807 Linemap::predeclared_location());
14808 mpz_clear(offsetval);
14809 return ret->get_tree(context);
e440a328 14810}
14811
d751bb78 14812// Dump ast representation for a struct field offset expression.
14813
14814void
14815Struct_field_offset_expression::do_dump_expression(
14816 Ast_dump_context* ast_dump_context) const
14817{
14818 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 14819 ast_dump_context->dump_type(this->type_);
14820 ast_dump_context->ostream() << '.';
14821 ast_dump_context->ostream() <<
14822 Gogo::message_name(this->field_->field_name());
d751bb78 14823 ast_dump_context->ostream() << ")";
14824}
14825
e440a328 14826// Make an expression for a struct field offset.
14827
14828Expression*
14829Expression::make_struct_field_offset(Struct_type* type,
14830 const Struct_field* field)
14831{
14832 return new Struct_field_offset_expression(type, field);
14833}
14834
a9182619 14835// An expression which evaluates to a pointer to the map descriptor of
14836// a map type.
14837
14838class Map_descriptor_expression : public Expression
14839{
14840 public:
b13c66cd 14841 Map_descriptor_expression(Map_type* type, Location location)
a9182619 14842 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14843 type_(type)
14844 { }
14845
14846 protected:
14847 Type*
14848 do_type()
14849 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14850
14851 void
14852 do_determine_type(const Type_context*)
14853 { }
14854
14855 Expression*
14856 do_copy()
14857 { return this; }
14858
14859 tree
14860 do_get_tree(Translate_context* context)
14861 {
175a4612 14862 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14863 this->location());
14864 return expr_to_tree(ret);
a9182619 14865 }
14866
d751bb78 14867 void
14868 do_dump_expression(Ast_dump_context*) const;
14869
a9182619 14870 private:
14871 // The type for which this is the descriptor.
14872 Map_type* type_;
14873};
14874
d751bb78 14875// Dump ast representation for a map descriptor expression.
14876
14877void
14878Map_descriptor_expression::do_dump_expression(
14879 Ast_dump_context* ast_dump_context) const
14880{
14881 ast_dump_context->ostream() << "map_descriptor(";
14882 ast_dump_context->dump_type(this->type_);
14883 ast_dump_context->ostream() << ")";
14884}
14885
a9182619 14886// Make a map descriptor expression.
14887
14888Expression*
b13c66cd 14889Expression::make_map_descriptor(Map_type* type, Location location)
a9182619 14890{
14891 return new Map_descriptor_expression(type, location);
14892}
14893
e440a328 14894// An expression which evaluates to the address of an unnamed label.
14895
14896class Label_addr_expression : public Expression
14897{
14898 public:
b13c66cd 14899 Label_addr_expression(Label* label, Location location)
e440a328 14900 : Expression(EXPRESSION_LABEL_ADDR, location),
14901 label_(label)
14902 { }
14903
14904 protected:
14905 Type*
14906 do_type()
14907 { return Type::make_pointer_type(Type::make_void_type()); }
14908
14909 void
14910 do_determine_type(const Type_context*)
14911 { }
14912
14913 Expression*
14914 do_copy()
14915 { return new Label_addr_expression(this->label_, this->location()); }
14916
14917 tree
6e193e6f 14918 do_get_tree(Translate_context* context)
14919 {
e8816003 14920 return expr_to_tree(this->label_->get_addr(context, this->location()));
6e193e6f 14921 }
e440a328 14922
d751bb78 14923 void
14924 do_dump_expression(Ast_dump_context* ast_dump_context) const
14925 { ast_dump_context->ostream() << this->label_->name(); }
14926
e440a328 14927 private:
14928 // The label whose address we are taking.
14929 Label* label_;
14930};
14931
14932// Make an expression for the address of an unnamed label.
14933
14934Expression*
b13c66cd 14935Expression::make_label_addr(Label* label, Location location)
e440a328 14936{
14937 return new Label_addr_expression(label, location);
14938}
14939
283a177b 14940// Conditional expressions.
14941
14942class Conditional_expression : public Expression
14943{
14944 public:
14945 Conditional_expression(Expression* cond, Expression* then_expr,
14946 Expression* else_expr, Location location)
14947 : Expression(EXPRESSION_CONDITIONAL, location),
14948 cond_(cond), then_(then_expr), else_(else_expr)
14949 {}
14950
14951 protected:
2c809f8f 14952 int
14953 do_traverse(Traverse*);
14954
283a177b 14955 Type*
14956 do_type();
14957
14958 void
2c809f8f 14959 do_determine_type(const Type_context*);
283a177b 14960
14961 Expression*
14962 do_copy()
14963 {
14964 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14965 this->else_->copy(), this->location());
14966 }
14967
14968 tree
14969 do_get_tree(Translate_context* context);
14970
14971 void
14972 do_dump_expression(Ast_dump_context*) const;
14973
14974 private:
14975 // The condition to be checked.
14976 Expression* cond_;
14977 // The expression to execute if the condition is true.
14978 Expression* then_;
14979 // The expression to execute if the condition is false.
14980 Expression* else_;
14981};
14982
2c809f8f 14983// Traversal.
14984
14985int
14986Conditional_expression::do_traverse(Traverse* traverse)
14987{
14988 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14989 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14990 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14991 return TRAVERSE_EXIT;
14992 return TRAVERSE_CONTINUE;
14993}
14994
283a177b 14995// Return the type of the conditional expression.
14996
14997Type*
14998Conditional_expression::do_type()
14999{
15000 Type* result_type = Type::make_void_type();
2c809f8f 15001 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15002 NULL))
283a177b 15003 result_type = this->then_->type();
15004 else if (this->then_->is_nil_expression()
15005 || this->else_->is_nil_expression())
15006 result_type = (!this->then_->is_nil_expression()
15007 ? this->then_->type()
15008 : this->else_->type());
15009 return result_type;
15010}
15011
2c809f8f 15012// Determine type for a conditional expression.
15013
15014void
15015Conditional_expression::do_determine_type(const Type_context* context)
15016{
15017 this->cond_->determine_type_no_context();
15018 this->then_->determine_type(context);
15019 this->else_->determine_type(context);
15020}
15021
283a177b 15022// Get the backend representation of a conditional expression.
15023
15024tree
15025Conditional_expression::do_get_tree(Translate_context* context)
15026{
15027 Gogo* gogo = context->gogo();
15028 Btype* result_btype = this->type()->get_backend(gogo);
15029 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15030 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15031 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15032 Bexpression* ret =
15033 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15034 this->location());
15035 return expr_to_tree(ret);
15036}
15037
15038// Dump ast representation of a conditional expression.
15039
15040void
15041Conditional_expression::do_dump_expression(
15042 Ast_dump_context* ast_dump_context) const
15043{
15044 ast_dump_context->ostream() << "(";
15045 ast_dump_context->dump_expression(this->cond_);
15046 ast_dump_context->ostream() << " ? ";
15047 ast_dump_context->dump_expression(this->then_);
15048 ast_dump_context->ostream() << " : ";
15049 ast_dump_context->dump_expression(this->else_);
15050 ast_dump_context->ostream() << ") ";
15051}
15052
15053// Make a conditional expression.
15054
15055Expression*
15056Expression::make_conditional(Expression* cond, Expression* then,
15057 Expression* else_expr, Location location)
15058{
15059 return new Conditional_expression(cond, then, else_expr, location);
15060}
15061
2c809f8f 15062// Compound expressions.
15063
15064class Compound_expression : public Expression
15065{
15066 public:
15067 Compound_expression(Expression* init, Expression* expr, Location location)
15068 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15069 {}
15070
15071 protected:
15072 int
15073 do_traverse(Traverse*);
15074
15075 Type*
15076 do_type();
15077
15078 void
15079 do_determine_type(const Type_context*);
15080
15081 Expression*
15082 do_copy()
15083 {
15084 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15085 this->location());
15086 }
15087
15088 tree
15089 do_get_tree(Translate_context* context);
15090
15091 void
15092 do_dump_expression(Ast_dump_context*) const;
15093
15094 private:
15095 // The expression that is evaluated first and discarded.
15096 Expression* init_;
15097 // The expression that is evaluated and returned.
15098 Expression* expr_;
15099};
15100
15101// Traversal.
15102
15103int
15104Compound_expression::do_traverse(Traverse* traverse)
15105{
15106 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15107 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15108 return TRAVERSE_EXIT;
15109 return TRAVERSE_CONTINUE;
15110}
15111
15112// Return the type of the compound expression.
15113
15114Type*
15115Compound_expression::do_type()
15116{
15117 return this->expr_->type();
15118}
15119
15120// Determine type for a compound expression.
15121
15122void
15123Compound_expression::do_determine_type(const Type_context* context)
15124{
15125 this->init_->determine_type_no_context();
15126 this->expr_->determine_type(context);
15127}
15128
15129// Get the backend representation of a compound expression.
15130
15131tree
15132Compound_expression::do_get_tree(Translate_context* context)
15133{
15134 Gogo* gogo = context->gogo();
15135 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15136 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15137 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15138 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15139 this->location());
15140 return expr_to_tree(ret);
15141}
15142
15143// Dump ast representation of a conditional expression.
15144
15145void
15146Compound_expression::do_dump_expression(
15147 Ast_dump_context* ast_dump_context) const
15148{
15149 ast_dump_context->ostream() << "(";
15150 ast_dump_context->dump_expression(this->init_);
15151 ast_dump_context->ostream() << ",";
15152 ast_dump_context->dump_expression(this->expr_);
15153 ast_dump_context->ostream() << ") ";
15154}
15155
15156// Make a compound expression.
15157
15158Expression*
15159Expression::make_compound(Expression* init, Expression* expr, Location location)
15160{
15161 return new Compound_expression(init, expr, location);
15162}
15163
e440a328 15164// Import an expression. This comes at the end in order to see the
15165// various class definitions.
15166
15167Expression*
15168Expression::import_expression(Import* imp)
15169{
15170 int c = imp->peek_char();
15171 if (imp->match_c_string("- ")
15172 || imp->match_c_string("! ")
15173 || imp->match_c_string("^ "))
15174 return Unary_expression::do_import(imp);
15175 else if (c == '(')
15176 return Binary_expression::do_import(imp);
15177 else if (imp->match_c_string("true")
15178 || imp->match_c_string("false"))
15179 return Boolean_expression::do_import(imp);
15180 else if (c == '"')
15181 return String_expression::do_import(imp);
15182 else if (c == '-' || (c >= '0' && c <= '9'))
15183 {
15184 // This handles integers, floats and complex constants.
15185 return Integer_expression::do_import(imp);
15186 }
15187 else if (imp->match_c_string("nil"))
15188 return Nil_expression::do_import(imp);
15189 else if (imp->match_c_string("convert"))
15190 return Type_conversion_expression::do_import(imp);
15191 else
15192 {
15193 error_at(imp->location(), "import error: expected expression");
15194 return Expression::make_error(imp->location());
15195 }
15196}
15197
15198// Class Expression_list.
15199
15200// Traverse the list.
15201
15202int
15203Expression_list::traverse(Traverse* traverse)
15204{
15205 for (Expression_list::iterator p = this->begin();
15206 p != this->end();
15207 ++p)
15208 {
15209 if (*p != NULL)
15210 {
15211 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15212 return TRAVERSE_EXIT;
15213 }
15214 }
15215 return TRAVERSE_CONTINUE;
15216}
15217
15218// Copy the list.
15219
15220Expression_list*
15221Expression_list::copy()
15222{
15223 Expression_list* ret = new Expression_list();
15224 for (Expression_list::iterator p = this->begin();
15225 p != this->end();
15226 ++p)
15227 {
15228 if (*p == NULL)
15229 ret->push_back(NULL);
15230 else
15231 ret->push_back((*p)->copy());
15232 }
15233 return ret;
15234}
15235
15236// Return whether an expression list has an error expression.
15237
15238bool
15239Expression_list::contains_error() const
15240{
15241 for (Expression_list::const_iterator p = this->begin();
15242 p != this->end();
15243 ++p)
15244 if (*p != NULL && (*p)->is_error_expression())
15245 return true;
15246 return false;
15247}
0c77715b 15248
15249// Class Numeric_constant.
15250
15251// Destructor.
15252
15253Numeric_constant::~Numeric_constant()
15254{
15255 this->clear();
15256}
15257
15258// Copy constructor.
15259
15260Numeric_constant::Numeric_constant(const Numeric_constant& a)
15261 : classification_(a.classification_), type_(a.type_)
15262{
15263 switch (a.classification_)
15264 {
15265 case NC_INVALID:
15266 break;
15267 case NC_INT:
15268 case NC_RUNE:
15269 mpz_init_set(this->u_.int_val, a.u_.int_val);
15270 break;
15271 case NC_FLOAT:
15272 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15273 break;
15274 case NC_COMPLEX:
15275 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15276 GMP_RNDN);
15277 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15278 GMP_RNDN);
15279 break;
15280 default:
15281 go_unreachable();
15282 }
15283}
15284
15285// Assignment operator.
15286
15287Numeric_constant&
15288Numeric_constant::operator=(const Numeric_constant& a)
15289{
15290 this->clear();
15291 this->classification_ = a.classification_;
15292 this->type_ = a.type_;
15293 switch (a.classification_)
15294 {
15295 case NC_INVALID:
15296 break;
15297 case NC_INT:
15298 case NC_RUNE:
15299 mpz_init_set(this->u_.int_val, a.u_.int_val);
15300 break;
15301 case NC_FLOAT:
15302 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15303 break;
15304 case NC_COMPLEX:
15305 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15306 GMP_RNDN);
15307 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15308 GMP_RNDN);
15309 break;
15310 default:
15311 go_unreachable();
15312 }
15313 return *this;
15314}
15315
15316// Clear the contents.
15317
15318void
15319Numeric_constant::clear()
15320{
15321 switch (this->classification_)
15322 {
15323 case NC_INVALID:
15324 break;
15325 case NC_INT:
15326 case NC_RUNE:
15327 mpz_clear(this->u_.int_val);
15328 break;
15329 case NC_FLOAT:
15330 mpfr_clear(this->u_.float_val);
15331 break;
15332 case NC_COMPLEX:
15333 mpfr_clear(this->u_.complex_val.real);
15334 mpfr_clear(this->u_.complex_val.imag);
15335 break;
15336 default:
15337 go_unreachable();
15338 }
15339 this->classification_ = NC_INVALID;
15340}
15341
15342// Set to an unsigned long value.
15343
15344void
15345Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15346{
15347 this->clear();
15348 this->classification_ = NC_INT;
15349 this->type_ = type;
15350 mpz_init_set_ui(this->u_.int_val, val);
15351}
15352
15353// Set to an integer value.
15354
15355void
15356Numeric_constant::set_int(Type* type, const mpz_t val)
15357{
15358 this->clear();
15359 this->classification_ = NC_INT;
15360 this->type_ = type;
15361 mpz_init_set(this->u_.int_val, val);
15362}
15363
15364// Set to a rune value.
15365
15366void
15367Numeric_constant::set_rune(Type* type, const mpz_t val)
15368{
15369 this->clear();
15370 this->classification_ = NC_RUNE;
15371 this->type_ = type;
15372 mpz_init_set(this->u_.int_val, val);
15373}
15374
15375// Set to a floating point value.
15376
15377void
15378Numeric_constant::set_float(Type* type, const mpfr_t val)
15379{
15380 this->clear();
15381 this->classification_ = NC_FLOAT;
15382 this->type_ = type;
833b523c 15383 // Numeric constants do not have negative zero values, so remove
15384 // them here. They also don't have infinity or NaN values, but we
15385 // should never see them here.
15386 if (mpfr_zero_p(val))
15387 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15388 else
15389 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15390}
15391
15392// Set to a complex value.
15393
15394void
15395Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15396{
15397 this->clear();
15398 this->classification_ = NC_COMPLEX;
15399 this->type_ = type;
15400 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15401 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15402}
15403
15404// Get an int value.
15405
15406void
15407Numeric_constant::get_int(mpz_t* val) const
15408{
15409 go_assert(this->is_int());
15410 mpz_init_set(*val, this->u_.int_val);
15411}
15412
15413// Get a rune value.
15414
15415void
15416Numeric_constant::get_rune(mpz_t* val) const
15417{
15418 go_assert(this->is_rune());
15419 mpz_init_set(*val, this->u_.int_val);
15420}
15421
15422// Get a floating point value.
15423
15424void
15425Numeric_constant::get_float(mpfr_t* val) const
15426{
15427 go_assert(this->is_float());
15428 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15429}
15430
15431// Get a complex value.
15432
15433void
15434Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15435{
15436 go_assert(this->is_complex());
15437 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15438 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15439}
15440
15441// Express value as unsigned long if possible.
15442
15443Numeric_constant::To_unsigned_long
15444Numeric_constant::to_unsigned_long(unsigned long* val) const
15445{
15446 switch (this->classification_)
15447 {
15448 case NC_INT:
15449 case NC_RUNE:
15450 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15451 case NC_FLOAT:
15452 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15453 case NC_COMPLEX:
15454 if (!mpfr_zero_p(this->u_.complex_val.imag))
15455 return NC_UL_NOTINT;
15456 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15457 default:
15458 go_unreachable();
15459 }
15460}
15461
15462// Express integer value as unsigned long if possible.
15463
15464Numeric_constant::To_unsigned_long
15465Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15466 unsigned long *val) const
15467{
15468 if (mpz_sgn(ival) < 0)
15469 return NC_UL_NEGATIVE;
15470 unsigned long ui = mpz_get_ui(ival);
15471 if (mpz_cmp_ui(ival, ui) != 0)
15472 return NC_UL_BIG;
15473 *val = ui;
15474 return NC_UL_VALID;
15475}
15476
15477// Express floating point value as unsigned long if possible.
15478
15479Numeric_constant::To_unsigned_long
15480Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15481 unsigned long *val) const
15482{
15483 if (!mpfr_integer_p(fval))
15484 return NC_UL_NOTINT;
15485 mpz_t ival;
15486 mpz_init(ival);
15487 mpfr_get_z(ival, fval, GMP_RNDN);
15488 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15489 mpz_clear(ival);
15490 return ret;
15491}
15492
15493// Convert value to integer if possible.
15494
15495bool
15496Numeric_constant::to_int(mpz_t* val) const
15497{
15498 switch (this->classification_)
15499 {
15500 case NC_INT:
15501 case NC_RUNE:
15502 mpz_init_set(*val, this->u_.int_val);
15503 return true;
15504 case NC_FLOAT:
15505 if (!mpfr_integer_p(this->u_.float_val))
15506 return false;
15507 mpz_init(*val);
15508 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15509 return true;
15510 case NC_COMPLEX:
15511 if (!mpfr_zero_p(this->u_.complex_val.imag)
15512 || !mpfr_integer_p(this->u_.complex_val.real))
15513 return false;
15514 mpz_init(*val);
15515 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15516 return true;
15517 default:
15518 go_unreachable();
15519 }
15520}
15521
15522// Convert value to floating point if possible.
15523
15524bool
15525Numeric_constant::to_float(mpfr_t* val) const
15526{
15527 switch (this->classification_)
15528 {
15529 case NC_INT:
15530 case NC_RUNE:
15531 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15532 return true;
15533 case NC_FLOAT:
15534 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15535 return true;
15536 case NC_COMPLEX:
15537 if (!mpfr_zero_p(this->u_.complex_val.imag))
15538 return false;
15539 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15540 return true;
15541 default:
15542 go_unreachable();
15543 }
15544}
15545
15546// Convert value to complex.
15547
15548bool
15549Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15550{
15551 switch (this->classification_)
15552 {
15553 case NC_INT:
15554 case NC_RUNE:
15555 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15556 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15557 return true;
15558 case NC_FLOAT:
15559 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15560 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15561 return true;
15562 case NC_COMPLEX:
15563 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15564 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15565 return true;
15566 default:
15567 go_unreachable();
15568 }
15569}
15570
15571// Get the type.
15572
15573Type*
15574Numeric_constant::type() const
15575{
15576 if (this->type_ != NULL)
15577 return this->type_;
15578 switch (this->classification_)
15579 {
15580 case NC_INT:
15581 return Type::make_abstract_integer_type();
15582 case NC_RUNE:
15583 return Type::make_abstract_character_type();
15584 case NC_FLOAT:
15585 return Type::make_abstract_float_type();
15586 case NC_COMPLEX:
15587 return Type::make_abstract_complex_type();
15588 default:
15589 go_unreachable();
15590 }
15591}
15592
15593// If the constant can be expressed in TYPE, then set the type of the
15594// constant to TYPE and return true. Otherwise return false, and, if
15595// ISSUE_ERROR is true, report an appropriate error message.
15596
15597bool
15598Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15599{
15600 bool ret;
15601 if (type == NULL)
15602 ret = true;
15603 else if (type->integer_type() != NULL)
15604 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15605 else if (type->float_type() != NULL)
15606 ret = this->check_float_type(type->float_type(), issue_error, loc);
15607 else if (type->complex_type() != NULL)
15608 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15609 else
15610 go_unreachable();
15611 if (ret)
15612 this->type_ = type;
15613 return ret;
15614}
15615
15616// Check whether the constant can be expressed in an integer type.
15617
15618bool
15619Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15620 Location location) const
15621{
15622 mpz_t val;
15623 switch (this->classification_)
15624 {
15625 case NC_INT:
15626 case NC_RUNE:
15627 mpz_init_set(val, this->u_.int_val);
15628 break;
15629
15630 case NC_FLOAT:
15631 if (!mpfr_integer_p(this->u_.float_val))
15632 {
15633 if (issue_error)
15634 error_at(location, "floating point constant truncated to integer");
15635 return false;
15636 }
15637 mpz_init(val);
15638 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15639 break;
15640
15641 case NC_COMPLEX:
15642 if (!mpfr_integer_p(this->u_.complex_val.real)
15643 || !mpfr_zero_p(this->u_.complex_val.imag))
15644 {
15645 if (issue_error)
15646 error_at(location, "complex constant truncated to integer");
15647 return false;
15648 }
15649 mpz_init(val);
15650 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15651 break;
15652
15653 default:
15654 go_unreachable();
15655 }
15656
15657 bool ret;
15658 if (type->is_abstract())
15659 ret = true;
15660 else
15661 {
15662 int bits = mpz_sizeinbase(val, 2);
15663 if (type->is_unsigned())
15664 {
15665 // For an unsigned type we can only accept a nonnegative
15666 // number, and we must be able to represents at least BITS.
15667 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15668 }
15669 else
15670 {
15671 // For a signed type we need an extra bit to indicate the
15672 // sign. We have to handle the most negative integer
15673 // specially.
15674 ret = (bits + 1 <= type->bits()
15675 || (bits <= type->bits()
15676 && mpz_sgn(val) < 0
15677 && (mpz_scan1(val, 0)
15678 == static_cast<unsigned long>(type->bits() - 1))
15679 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15680 }
15681 }
15682
15683 if (!ret && issue_error)
15684 error_at(location, "integer constant overflow");
15685
15686 return ret;
15687}
15688
15689// Check whether the constant can be expressed in a floating point
15690// type.
15691
15692bool
15693Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15694 Location location)
0c77715b 15695{
15696 mpfr_t val;
15697 switch (this->classification_)
15698 {
15699 case NC_INT:
15700 case NC_RUNE:
15701 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15702 break;
15703
15704 case NC_FLOAT:
15705 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15706 break;
15707
15708 case NC_COMPLEX:
15709 if (!mpfr_zero_p(this->u_.complex_val.imag))
15710 {
15711 if (issue_error)
15712 error_at(location, "complex constant truncated to float");
15713 return false;
15714 }
15715 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15716 break;
15717
15718 default:
15719 go_unreachable();
15720 }
15721
15722 bool ret;
15723 if (type->is_abstract())
15724 ret = true;
15725 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15726 {
15727 // A NaN or Infinity always fits in the range of the type.
15728 ret = true;
15729 }
15730 else
15731 {
15732 mp_exp_t exp = mpfr_get_exp(val);
15733 mp_exp_t max_exp;
15734 switch (type->bits())
15735 {
15736 case 32:
15737 max_exp = 128;
15738 break;
15739 case 64:
15740 max_exp = 1024;
15741 break;
15742 default:
15743 go_unreachable();
15744 }
15745
15746 ret = exp <= max_exp;
d0bcce51 15747
15748 if (ret)
15749 {
15750 // Round the constant to the desired type.
15751 mpfr_t t;
15752 mpfr_init(t);
15753 switch (type->bits())
15754 {
15755 case 32:
15756 mpfr_set_prec(t, 24);
15757 break;
15758 case 64:
15759 mpfr_set_prec(t, 53);
15760 break;
15761 default:
15762 go_unreachable();
15763 }
15764 mpfr_set(t, val, GMP_RNDN);
15765 mpfr_set(val, t, GMP_RNDN);
15766 mpfr_clear(t);
15767
15768 this->set_float(type, val);
15769 }
0c77715b 15770 }
15771
15772 mpfr_clear(val);
15773
15774 if (!ret && issue_error)
15775 error_at(location, "floating point constant overflow");
15776
15777 return ret;
15778}
15779
15780// Check whether the constant can be expressed in a complex type.
15781
15782bool
15783Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 15784 Location location)
0c77715b 15785{
15786 if (type->is_abstract())
15787 return true;
15788
15789 mp_exp_t max_exp;
15790 switch (type->bits())
15791 {
15792 case 64:
15793 max_exp = 128;
15794 break;
15795 case 128:
15796 max_exp = 1024;
15797 break;
15798 default:
15799 go_unreachable();
15800 }
15801
15802 mpfr_t real;
d0bcce51 15803 mpfr_t imag;
0c77715b 15804 switch (this->classification_)
15805 {
15806 case NC_INT:
15807 case NC_RUNE:
15808 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
d0bcce51 15809 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15810 break;
15811
15812 case NC_FLOAT:
15813 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
d0bcce51 15814 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15815 break;
15816
15817 case NC_COMPLEX:
0c77715b 15818 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
d0bcce51 15819 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
0c77715b 15820 break;
15821
15822 default:
15823 go_unreachable();
15824 }
15825
d0bcce51 15826 bool ret = true;
15827 if (!mpfr_nan_p(real)
15828 && !mpfr_inf_p(real)
15829 && !mpfr_zero_p(real)
15830 && mpfr_get_exp(real) > max_exp)
15831 {
15832 if (issue_error)
15833 error_at(location, "complex real part overflow");
15834 ret = false;
15835 }
0c77715b 15836
d0bcce51 15837 if (!mpfr_nan_p(imag)
15838 && !mpfr_inf_p(imag)
15839 && !mpfr_zero_p(imag)
15840 && mpfr_get_exp(imag) > max_exp)
15841 {
15842 if (issue_error)
15843 error_at(location, "complex imaginary part overflow");
15844 ret = false;
15845 }
0c77715b 15846
d0bcce51 15847 if (ret)
15848 {
15849 // Round the constant to the desired type.
15850 mpfr_t t;
15851 mpfr_init(t);
15852 switch (type->bits())
15853 {
15854 case 64:
15855 mpfr_set_prec(t, 24);
15856 break;
15857 case 128:
15858 mpfr_set_prec(t, 53);
15859 break;
15860 default:
15861 go_unreachable();
15862 }
15863 mpfr_set(t, real, GMP_RNDN);
15864 mpfr_set(real, t, GMP_RNDN);
15865 mpfr_set(t, imag, GMP_RNDN);
15866 mpfr_set(imag, t, GMP_RNDN);
15867 mpfr_clear(t);
15868
15869 this->set_complex(type, real, imag);
15870 }
15871
15872 mpfr_clear(real);
15873 mpfr_clear(imag);
0c77715b 15874
15875 return ret;
15876}
15877
15878// Return an Expression for this value.
15879
15880Expression*
15881Numeric_constant::expression(Location loc) const
15882{
15883 switch (this->classification_)
15884 {
15885 case NC_INT:
15886 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15887 case NC_RUNE:
15888 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15889 case NC_FLOAT:
15890 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15891 case NC_COMPLEX:
15892 return Expression::make_complex(&this->u_.complex_val.real,
15893 &this->u_.complex_val.imag,
15894 this->type_, loc);
15895 default:
15896 go_unreachable();
15897 }
15898}