]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
gcc/
[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*
5c3f3470 5435Binary_expression::do_flatten(Gogo* gogo, Named_object*,
a32698ee 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
a32698ee 5465 if (is_shift_op
5c3f3470 5466 || (is_idiv_op
5467 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
a32698ee 5468 {
5469 if (!this->left_->is_variable())
5470 {
5471 temp = Statement::make_temporary(NULL, this->left_, loc);
5472 inserter->insert(temp);
5473 this->left_ = Expression::make_temporary_reference(temp, loc);
5474 }
5475 if (!this->right_->is_variable())
5476 {
5477 temp =
5478 Statement::make_temporary(NULL, this->right_, loc);
5479 this->right_ = Expression::make_temporary_reference(temp, loc);
5480 inserter->insert(temp);
5481 }
5482 }
5483 return this;
5484}
5485
5486
e9d3367e 5487// Return the address of EXPR, cast to unsafe.Pointer.
5488
5489Expression*
5490Binary_expression::operand_address(Statement_inserter* inserter,
5491 Expression* expr)
5492{
5493 Location loc = this->location();
5494
5495 if (!expr->is_addressable())
5496 {
5497 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5498 loc);
5499 inserter->insert(temp);
5500 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5501 }
5502 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5503 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5504 Type* void_type = Type::make_void_type();
5505 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5506 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5507}
5508
0c77715b 5509// Return the numeric constant value, if it has one.
e440a328 5510
5511bool
0c77715b 5512Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5513{
0c77715b 5514 Numeric_constant left_nc;
5515 if (!this->left_->numeric_constant_value(&left_nc))
5516 return false;
5517 Numeric_constant right_nc;
5518 if (!this->right_->numeric_constant_value(&right_nc))
5519 return false;
9767e2d3 5520 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5521 this->location(), nc);
e440a328 5522}
5523
5524// Note that the value is being discarded.
5525
4f2138d7 5526bool
e440a328 5527Binary_expression::do_discarding_value()
5528{
5529 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5530 return this->right_->discarding_value();
e440a328 5531 else
4f2138d7 5532 {
5533 this->unused_value_error();
5534 return false;
5535 }
e440a328 5536}
5537
5538// Get type.
5539
5540Type*
5541Binary_expression::do_type()
5542{
5f5fea79 5543 if (this->classification() == EXPRESSION_ERROR)
5544 return Type::make_error_type();
5545
e440a328 5546 switch (this->op_)
5547 {
e440a328 5548 case OPERATOR_EQEQ:
5549 case OPERATOR_NOTEQ:
5550 case OPERATOR_LT:
5551 case OPERATOR_LE:
5552 case OPERATOR_GT:
5553 case OPERATOR_GE:
e90c9dfc 5554 if (this->type_ == NULL)
5555 this->type_ = Type::make_boolean_type();
5556 return this->type_;
e440a328 5557
5558 case OPERATOR_PLUS:
5559 case OPERATOR_MINUS:
5560 case OPERATOR_OR:
5561 case OPERATOR_XOR:
5562 case OPERATOR_MULT:
5563 case OPERATOR_DIV:
5564 case OPERATOR_MOD:
5565 case OPERATOR_AND:
5566 case OPERATOR_BITCLEAR:
e90c9dfc 5567 case OPERATOR_OROR:
5568 case OPERATOR_ANDAND:
e440a328 5569 {
0c77715b 5570 Type* type;
5571 if (!Binary_expression::operation_type(this->op_,
5572 this->left_->type(),
5573 this->right_->type(),
5574 &type))
5575 return Type::make_error_type();
5576 return type;
e440a328 5577 }
5578
5579 case OPERATOR_LSHIFT:
5580 case OPERATOR_RSHIFT:
5581 return this->left_->type();
5582
5583 default:
c3e6f413 5584 go_unreachable();
e440a328 5585 }
5586}
5587
5588// Set type for a binary expression.
5589
5590void
5591Binary_expression::do_determine_type(const Type_context* context)
5592{
5593 Type* tleft = this->left_->type();
5594 Type* tright = this->right_->type();
5595
5596 // Both sides should have the same type, except for the shift
5597 // operations. For a comparison, we should ignore the incoming
5598 // type.
5599
5600 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5601 || this->op_ == OPERATOR_RSHIFT);
5602
5603 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5604 || this->op_ == OPERATOR_NOTEQ
5605 || this->op_ == OPERATOR_LT
5606 || this->op_ == OPERATOR_LE
5607 || this->op_ == OPERATOR_GT
5608 || this->op_ == OPERATOR_GE);
5609
5610 Type_context subcontext(*context);
5611
5612 if (is_comparison)
5613 {
5614 // In a comparison, the context does not determine the types of
5615 // the operands.
5616 subcontext.type = NULL;
5617 }
5618
02ffd97f 5619 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5620 {
5621 // For a logical operation, the context does not determine the
5622 // types of the operands. The operands must be some boolean
5623 // type but if the context has a boolean type they do not
5624 // inherit it. See http://golang.org/issue/3924.
5625 subcontext.type = NULL;
5626 }
5627
e440a328 5628 // Set the context for the left hand operand.
5629 if (is_shift_op)
5630 {
b40dc774 5631 // The right hand operand of a shift plays no role in
5632 // determining the type of the left hand operand.
e440a328 5633 }
5634 else if (!tleft->is_abstract())
5635 subcontext.type = tleft;
5636 else if (!tright->is_abstract())
5637 subcontext.type = tright;
5638 else if (subcontext.type == NULL)
5639 {
5640 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5641 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5642 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5643 {
5644 // Both sides have an abstract integer, abstract float, or
5645 // abstract complex type. Just let CONTEXT determine
5646 // whether they may remain abstract or not.
5647 }
5648 else if (tleft->complex_type() != NULL)
5649 subcontext.type = tleft;
5650 else if (tright->complex_type() != NULL)
5651 subcontext.type = tright;
5652 else if (tleft->float_type() != NULL)
5653 subcontext.type = tleft;
5654 else if (tright->float_type() != NULL)
5655 subcontext.type = tright;
5656 else
5657 subcontext.type = tleft;
f58a23ae 5658
5659 if (subcontext.type != NULL && !context->may_be_abstract)
5660 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5661 }
5662
5663 this->left_->determine_type(&subcontext);
5664
e440a328 5665 if (is_shift_op)
5666 {
b40dc774 5667 // We may have inherited an unusable type for the shift operand.
5668 // Give a useful error if that happened.
5669 if (tleft->is_abstract()
5670 && subcontext.type != NULL
8ab6effb 5671 && !subcontext.may_be_abstract
f6bc81e6 5672 && subcontext.type->interface_type() == NULL
8ab6effb 5673 && subcontext.type->integer_type() == NULL)
b40dc774 5674 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5675 "for left operand of shift"));
b40dc774 5676
5677 // The context for the right hand operand is the same as for the
5678 // left hand operand, except for a shift operator.
e440a328 5679 subcontext.type = Type::lookup_integer_type("uint");
5680 subcontext.may_be_abstract = false;
5681 }
5682
5683 this->right_->determine_type(&subcontext);
e90c9dfc 5684
5685 if (is_comparison)
5686 {
5687 if (this->type_ != NULL && !this->type_->is_abstract())
5688 ;
5689 else if (context->type != NULL && context->type->is_boolean_type())
5690 this->type_ = context->type;
5691 else if (!context->may_be_abstract)
5692 this->type_ = Type::lookup_bool_type();
5693 }
e440a328 5694}
5695
5696// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5697// OTYPE is the type of the other operand. Return whether the
5698// operation is OK. This should not be used for shift.
e440a328 5699
5700bool
be8b5eee 5701Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5702 Location location)
e440a328 5703{
5704 switch (op)
5705 {
5706 case OPERATOR_OROR:
5707 case OPERATOR_ANDAND:
5708 if (!type->is_boolean_type())
5709 {
5710 error_at(location, "expected boolean type");
5711 return false;
5712 }
5713 break;
5714
5715 case OPERATOR_EQEQ:
5716 case OPERATOR_NOTEQ:
e9d3367e 5717 {
5718 std::string reason;
5719 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5720 {
5721 error_at(location, "%s", reason.c_str());
5722 return false;
5723 }
5724 }
e440a328 5725 break;
5726
5727 case OPERATOR_LT:
5728 case OPERATOR_LE:
5729 case OPERATOR_GT:
5730 case OPERATOR_GE:
e9d3367e 5731 {
5732 std::string reason;
5733 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5734 {
5735 error_at(location, "%s", reason.c_str());
5736 return false;
5737 }
5738 }
e440a328 5739 break;
5740
5741 case OPERATOR_PLUS:
5742 case OPERATOR_PLUSEQ:
5743 if (type->integer_type() == NULL
5744 && type->float_type() == NULL
5745 && type->complex_type() == NULL
5746 && !type->is_string_type())
5747 {
5748 error_at(location,
5749 "expected integer, floating, complex, or string type");
5750 return false;
5751 }
5752 break;
5753
5754 case OPERATOR_MINUS:
5755 case OPERATOR_MINUSEQ:
5756 case OPERATOR_MULT:
5757 case OPERATOR_MULTEQ:
5758 case OPERATOR_DIV:
5759 case OPERATOR_DIVEQ:
5760 if (type->integer_type() == NULL
5761 && type->float_type() == NULL
5762 && type->complex_type() == NULL)
5763 {
5764 error_at(location, "expected integer, floating, or complex type");
5765 return false;
5766 }
5767 break;
5768
5769 case OPERATOR_MOD:
5770 case OPERATOR_MODEQ:
5771 case OPERATOR_OR:
5772 case OPERATOR_OREQ:
5773 case OPERATOR_AND:
5774 case OPERATOR_ANDEQ:
5775 case OPERATOR_XOR:
5776 case OPERATOR_XOREQ:
5777 case OPERATOR_BITCLEAR:
5778 case OPERATOR_BITCLEAREQ:
5779 if (type->integer_type() == NULL)
5780 {
5781 error_at(location, "expected integer type");
5782 return false;
5783 }
5784 break;
5785
5786 default:
c3e6f413 5787 go_unreachable();
e440a328 5788 }
5789
5790 return true;
5791}
5792
5793// Check types.
5794
5795void
5796Binary_expression::do_check_types(Gogo*)
5797{
5f5fea79 5798 if (this->classification() == EXPRESSION_ERROR)
5799 return;
5800
e440a328 5801 Type* left_type = this->left_->type();
5802 Type* right_type = this->right_->type();
5c13bd80 5803 if (left_type->is_error() || right_type->is_error())
9fe897ef 5804 {
5805 this->set_is_error();
5806 return;
5807 }
e440a328 5808
5809 if (this->op_ == OPERATOR_EQEQ
5810 || this->op_ == OPERATOR_NOTEQ
5811 || this->op_ == OPERATOR_LT
5812 || this->op_ == OPERATOR_LE
5813 || this->op_ == OPERATOR_GT
5814 || this->op_ == OPERATOR_GE)
5815 {
907c5ecd 5816 if (left_type->is_nil_type() && right_type->is_nil_type())
5817 {
5818 this->report_error(_("invalid comparison of nil with nil"));
5819 return;
5820 }
e440a328 5821 if (!Type::are_assignable(left_type, right_type, NULL)
5822 && !Type::are_assignable(right_type, left_type, NULL))
5823 {
5824 this->report_error(_("incompatible types in binary expression"));
5825 return;
5826 }
5827 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5828 right_type,
e440a328 5829 this->location())
5830 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5831 left_type,
e440a328 5832 this->location()))
5833 {
5834 this->set_is_error();
5835 return;
5836 }
5837 }
5838 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5839 {
5840 if (!Type::are_compatible_for_binop(left_type, right_type))
5841 {
5842 this->report_error(_("incompatible types in binary expression"));
5843 return;
5844 }
5845 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5846 right_type,
e440a328 5847 this->location()))
5848 {
5849 this->set_is_error();
5850 return;
5851 }
5c65b19d 5852 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5853 {
5854 // Division by a zero integer constant is an error.
5855 Numeric_constant rconst;
5856 unsigned long rval;
5857 if (left_type->integer_type() != NULL
5858 && this->right_->numeric_constant_value(&rconst)
5859 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5860 && rval == 0)
5861 {
5862 this->report_error(_("integer division by zero"));
5863 return;
5864 }
5865 }
e440a328 5866 }
5867 else
5868 {
5869 if (left_type->integer_type() == NULL)
5870 this->report_error(_("shift of non-integer operand"));
5871
5872 if (!right_type->is_abstract()
5873 && (right_type->integer_type() == NULL
5874 || !right_type->integer_type()->is_unsigned()))
5875 this->report_error(_("shift count not unsigned integer"));
5876 else
5877 {
0c77715b 5878 Numeric_constant nc;
5879 if (this->right_->numeric_constant_value(&nc))
e440a328 5880 {
0c77715b 5881 mpz_t val;
5882 if (!nc.to_int(&val))
5883 this->report_error(_("shift count not unsigned integer"));
5884 else
a4eba91b 5885 {
0c77715b 5886 if (mpz_sgn(val) < 0)
5887 {
5888 this->report_error(_("negative shift count"));
5889 mpz_set_ui(val, 0);
5890 Location rloc = this->right_->location();
5891 this->right_ = Expression::make_integer(&val, right_type,
5892 rloc);
5893 }
5894 mpz_clear(val);
a4eba91b 5895 }
e440a328 5896 }
e440a328 5897 }
5898 }
5899}
5900
5901// Get a tree for a binary expression.
5902
5903tree
5904Binary_expression::do_get_tree(Translate_context* context)
5905{
1b1f2abf 5906 Gogo* gogo = context->gogo();
a32698ee 5907 Location loc = this->location();
5908 Type* left_type = this->left_->type();
5909 Type* right_type = this->right_->type();
1b1f2abf 5910
e440a328 5911 bool use_left_type = true;
5912 bool is_shift_op = false;
29a2d1d8 5913 bool is_idiv_op = false;
e440a328 5914 switch (this->op_)
5915 {
5916 case OPERATOR_EQEQ:
5917 case OPERATOR_NOTEQ:
5918 case OPERATOR_LT:
5919 case OPERATOR_LE:
5920 case OPERATOR_GT:
5921 case OPERATOR_GE:
a32698ee 5922 {
5923 Bexpression* ret =
5924 Expression::comparison(context, this->type_, this->op_,
5925 this->left_, this->right_, loc);
5926 return expr_to_tree(ret);
5927 }
e440a328 5928
5929 case OPERATOR_OROR:
e440a328 5930 case OPERATOR_ANDAND:
e440a328 5931 use_left_type = false;
5932 break;
5933 case OPERATOR_PLUS:
e440a328 5934 case OPERATOR_MINUS:
e440a328 5935 case OPERATOR_OR:
e440a328 5936 case OPERATOR_XOR:
e440a328 5937 case OPERATOR_MULT:
e440a328 5938 break;
5939 case OPERATOR_DIV:
a32698ee 5940 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5941 break;
e440a328 5942 case OPERATOR_MOD:
29a2d1d8 5943 is_idiv_op = true;
e440a328 5944 break;
5945 case OPERATOR_LSHIFT:
e440a328 5946 case OPERATOR_RSHIFT:
e440a328 5947 is_shift_op = true;
5948 break;
e440a328 5949 case OPERATOR_BITCLEAR:
a32698ee 5950 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5951 case OPERATOR_AND:
e440a328 5952 break;
5953 default:
c3e6f413 5954 go_unreachable();
e440a328 5955 }
5956
a32698ee 5957 if (left_type->is_string_type())
e440a328 5958 {
c484d925 5959 go_assert(this->op_ == OPERATOR_PLUS);
a32698ee 5960 Expression* string_plus =
5961 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5962 this->left_, this->right_);
5963 return string_plus->get_tree(context);
5964 }
5965
5966 // For complex division Go might want slightly different results than the
5967 // backend implementation provides, so we have our own runtime routine.
1850e20c 5968 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5969 {
a32698ee 5970 Runtime::Function complex_code;
1850e20c 5971 switch (this->left_->type()->complex_type()->bits())
5972 {
5973 case 64:
a32698ee 5974 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5975 break;
5976 case 128:
a32698ee 5977 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5978 break;
5979 default:
5980 go_unreachable();
5981 }
a32698ee 5982 Expression* complex_div =
5983 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5984 return complex_div->get_tree(context);
1850e20c 5985 }
5986
a32698ee 5987 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
5988 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
e440a328 5989
a32698ee 5990 Type* type = use_left_type ? left_type : right_type;
5991 Btype* btype = type->get_backend(gogo);
5992
5993 Bexpression* ret =
5994 gogo->backend()->binary_expression(this->op_, left, right, loc);
5995 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 5996
a32698ee 5997 // Initialize overflow constants.
5998 Bexpression* overflow;
5999 mpz_t zero;
6000 mpz_init_set_ui(zero, 0UL);
6001 mpz_t one;
6002 mpz_init_set_ui(one, 1UL);
6003 mpz_t neg_one;
6004 mpz_init_set_si(neg_one, -1);
e440a328 6005
a32698ee 6006 Btype* left_btype = left_type->get_backend(gogo);
6007 Btype* right_btype = right_type->get_backend(gogo);
e440a328 6008
6009 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 6010 // This is not true in C, so we need to insert a conditional.
e440a328 6011 if (is_shift_op)
6012 {
a32698ee 6013 go_assert(left_type->integer_type() != NULL);
e440a328 6014
a32698ee 6015 mpz_t bitsval;
6016 int bits = left_type->integer_type()->bits();
6017 mpz_init_set_ui(bitsval, bits);
6018 Bexpression* bits_expr =
6019 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6020 Bexpression* compare =
6021 gogo->backend()->binary_expression(OPERATOR_LT,
6022 right, bits_expr, loc);
e440a328 6023
a32698ee 6024 Bexpression* zero_expr =
6025 gogo->backend()->integer_constant_expression(left_btype, zero);
6026 overflow = zero_expr;
e440a328 6027 if (this->op_ == OPERATOR_RSHIFT
a32698ee 6028 && !left_type->integer_type()->is_unsigned())
e440a328 6029 {
a32698ee 6030 Bexpression* neg_expr =
6031 gogo->backend()->binary_expression(OPERATOR_LT, left,
6032 zero_expr, loc);
6033 Bexpression* neg_one_expr =
6034 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6035 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6036 neg_one_expr,
6037 zero_expr, loc);
29a2d1d8 6038 }
a32698ee 6039 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6040 overflow, loc);
6041 mpz_clear(bitsval);
29a2d1d8 6042 }
6043
6044 // Add checks for division by zero and division overflow as needed.
6045 if (is_idiv_op)
6046 {
5c3f3470 6047 if (gogo->check_divide_by_zero())
29a2d1d8 6048 {
6049 // right == 0
a32698ee 6050 Bexpression* zero_expr =
6051 gogo->backend()->integer_constant_expression(right_btype, zero);
6052 Bexpression* check =
6053 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6054 right, zero_expr, loc);
29a2d1d8 6055
a32698ee 6056 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 6057 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
a32698ee 6058 Expression* crash = gogo->runtime_error(errcode, loc);
6059 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
29a2d1d8 6060
6061 // right == 0 ? (__go_runtime_error(...), 0) : ret
a32698ee 6062 ret = gogo->backend()->conditional_expression(btype, check,
6063 crash_expr, ret, loc);
b13c66cd 6064 }
6065
5c3f3470 6066 if (gogo->check_divide_overflow())
29a2d1d8 6067 {
6068 // right == -1
6069 // FIXME: It would be nice to say that this test is expected
6070 // to return false.
a32698ee 6071
6072 Bexpression* neg_one_expr =
6073 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6074 Bexpression* check =
6075 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6076 right, neg_one_expr, loc);
6077
6078 Bexpression* zero_expr =
6079 gogo->backend()->integer_constant_expression(btype, zero);
6080 Bexpression* one_expr =
6081 gogo->backend()->integer_constant_expression(btype, one);
6082
6083 if (type->integer_type()->is_unsigned())
29a2d1d8 6084 {
6085 // An unsigned -1 is the largest possible number, so
6086 // dividing is always 1 or 0.
a32698ee 6087
6088 Bexpression* cmp =
6089 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6090 left, right, loc);
29a2d1d8 6091 if (this->op_ == OPERATOR_DIV)
a32698ee 6092 overflow =
6093 gogo->backend()->conditional_expression(btype, cmp,
6094 one_expr, zero_expr,
6095 loc);
29a2d1d8 6096 else
a32698ee 6097 overflow =
6098 gogo->backend()->conditional_expression(btype, cmp,
6099 zero_expr, left,
6100 loc);
29a2d1d8 6101 }
6102 else
6103 {
6104 // Computing left / -1 is the same as computing - left,
6105 // which does not overflow since Go sets -fwrapv.
6106 if (this->op_ == OPERATOR_DIV)
a32698ee 6107 {
6108 Expression* negate_expr =
6109 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6110 overflow = tree_to_expr(negate_expr->get_tree(context));
6111 }
29a2d1d8 6112 else
a32698ee 6113 overflow = zero_expr;
29a2d1d8 6114 }
a32698ee 6115 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6116
6117 // right == -1 ? - left : ret
a32698ee 6118 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6119 ret, loc);
29a2d1d8 6120 }
e440a328 6121 }
6122
a32698ee 6123 mpz_clear(zero);
6124 mpz_clear(one);
6125 mpz_clear(neg_one);
6126 return expr_to_tree(ret);
e440a328 6127}
6128
6129// Export a binary expression.
6130
6131void
6132Binary_expression::do_export(Export* exp) const
6133{
6134 exp->write_c_string("(");
6135 this->left_->export_expression(exp);
6136 switch (this->op_)
6137 {
6138 case OPERATOR_OROR:
6139 exp->write_c_string(" || ");
6140 break;
6141 case OPERATOR_ANDAND:
6142 exp->write_c_string(" && ");
6143 break;
6144 case OPERATOR_EQEQ:
6145 exp->write_c_string(" == ");
6146 break;
6147 case OPERATOR_NOTEQ:
6148 exp->write_c_string(" != ");
6149 break;
6150 case OPERATOR_LT:
6151 exp->write_c_string(" < ");
6152 break;
6153 case OPERATOR_LE:
6154 exp->write_c_string(" <= ");
6155 break;
6156 case OPERATOR_GT:
6157 exp->write_c_string(" > ");
6158 break;
6159 case OPERATOR_GE:
6160 exp->write_c_string(" >= ");
6161 break;
6162 case OPERATOR_PLUS:
6163 exp->write_c_string(" + ");
6164 break;
6165 case OPERATOR_MINUS:
6166 exp->write_c_string(" - ");
6167 break;
6168 case OPERATOR_OR:
6169 exp->write_c_string(" | ");
6170 break;
6171 case OPERATOR_XOR:
6172 exp->write_c_string(" ^ ");
6173 break;
6174 case OPERATOR_MULT:
6175 exp->write_c_string(" * ");
6176 break;
6177 case OPERATOR_DIV:
6178 exp->write_c_string(" / ");
6179 break;
6180 case OPERATOR_MOD:
6181 exp->write_c_string(" % ");
6182 break;
6183 case OPERATOR_LSHIFT:
6184 exp->write_c_string(" << ");
6185 break;
6186 case OPERATOR_RSHIFT:
6187 exp->write_c_string(" >> ");
6188 break;
6189 case OPERATOR_AND:
6190 exp->write_c_string(" & ");
6191 break;
6192 case OPERATOR_BITCLEAR:
6193 exp->write_c_string(" &^ ");
6194 break;
6195 default:
c3e6f413 6196 go_unreachable();
e440a328 6197 }
6198 this->right_->export_expression(exp);
6199 exp->write_c_string(")");
6200}
6201
6202// Import a binary expression.
6203
6204Expression*
6205Binary_expression::do_import(Import* imp)
6206{
6207 imp->require_c_string("(");
6208
6209 Expression* left = Expression::import_expression(imp);
6210
6211 Operator op;
6212 if (imp->match_c_string(" || "))
6213 {
6214 op = OPERATOR_OROR;
6215 imp->advance(4);
6216 }
6217 else if (imp->match_c_string(" && "))
6218 {
6219 op = OPERATOR_ANDAND;
6220 imp->advance(4);
6221 }
6222 else if (imp->match_c_string(" == "))
6223 {
6224 op = OPERATOR_EQEQ;
6225 imp->advance(4);
6226 }
6227 else if (imp->match_c_string(" != "))
6228 {
6229 op = OPERATOR_NOTEQ;
6230 imp->advance(4);
6231 }
6232 else if (imp->match_c_string(" < "))
6233 {
6234 op = OPERATOR_LT;
6235 imp->advance(3);
6236 }
6237 else if (imp->match_c_string(" <= "))
6238 {
6239 op = OPERATOR_LE;
6240 imp->advance(4);
6241 }
6242 else if (imp->match_c_string(" > "))
6243 {
6244 op = OPERATOR_GT;
6245 imp->advance(3);
6246 }
6247 else if (imp->match_c_string(" >= "))
6248 {
6249 op = OPERATOR_GE;
6250 imp->advance(4);
6251 }
6252 else if (imp->match_c_string(" + "))
6253 {
6254 op = OPERATOR_PLUS;
6255 imp->advance(3);
6256 }
6257 else if (imp->match_c_string(" - "))
6258 {
6259 op = OPERATOR_MINUS;
6260 imp->advance(3);
6261 }
6262 else if (imp->match_c_string(" | "))
6263 {
6264 op = OPERATOR_OR;
6265 imp->advance(3);
6266 }
6267 else if (imp->match_c_string(" ^ "))
6268 {
6269 op = OPERATOR_XOR;
6270 imp->advance(3);
6271 }
6272 else if (imp->match_c_string(" * "))
6273 {
6274 op = OPERATOR_MULT;
6275 imp->advance(3);
6276 }
6277 else if (imp->match_c_string(" / "))
6278 {
6279 op = OPERATOR_DIV;
6280 imp->advance(3);
6281 }
6282 else if (imp->match_c_string(" % "))
6283 {
6284 op = OPERATOR_MOD;
6285 imp->advance(3);
6286 }
6287 else if (imp->match_c_string(" << "))
6288 {
6289 op = OPERATOR_LSHIFT;
6290 imp->advance(4);
6291 }
6292 else if (imp->match_c_string(" >> "))
6293 {
6294 op = OPERATOR_RSHIFT;
6295 imp->advance(4);
6296 }
6297 else if (imp->match_c_string(" & "))
6298 {
6299 op = OPERATOR_AND;
6300 imp->advance(3);
6301 }
6302 else if (imp->match_c_string(" &^ "))
6303 {
6304 op = OPERATOR_BITCLEAR;
6305 imp->advance(4);
6306 }
6307 else
6308 {
6309 error_at(imp->location(), "unrecognized binary operator");
6310 return Expression::make_error(imp->location());
6311 }
6312
6313 Expression* right = Expression::import_expression(imp);
6314
6315 imp->require_c_string(")");
6316
6317 return Expression::make_binary(op, left, right, imp->location());
6318}
6319
d751bb78 6320// Dump ast representation of a binary expression.
6321
6322void
6323Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6324{
6325 ast_dump_context->ostream() << "(";
6326 ast_dump_context->dump_expression(this->left_);
6327 ast_dump_context->ostream() << " ";
6328 ast_dump_context->dump_operator(this->op_);
6329 ast_dump_context->ostream() << " ";
6330 ast_dump_context->dump_expression(this->right_);
6331 ast_dump_context->ostream() << ") ";
6332}
6333
e440a328 6334// Make a binary expression.
6335
6336Expression*
6337Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6338 Location location)
e440a328 6339{
6340 return new Binary_expression(op, left, right, location);
6341}
6342
6343// Implement a comparison.
6344
a32698ee 6345Bexpression*
6346Expression::comparison(Translate_context* context, Type* result_type,
6347 Operator op, Expression* left, Expression* right,
6348 Location location)
e440a328 6349{
2387f644 6350 Type* left_type = left->type();
6351 Type* right_type = right->type();
ceeb12d7 6352
6353 mpz_t zval;
6354 mpz_init_set_ui(zval, 0UL);
6355 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6356 mpz_clear(zval);
1b1f2abf 6357
15c67ee2 6358 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6359 {
2387f644 6360 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6361 left, right);
6362 right = zexpr;
e440a328 6363 }
15c67ee2 6364 else if ((left_type->interface_type() != NULL
6365 && right_type->interface_type() == NULL
6366 && !right_type->is_nil_type())
6367 || (left_type->interface_type() == NULL
6368 && !left_type->is_nil_type()
6369 && right_type->interface_type() != NULL))
e440a328 6370 {
6371 // Comparing an interface value to a non-interface value.
6372 if (left_type->interface_type() == NULL)
6373 {
6374 std::swap(left_type, right_type);
2387f644 6375 std::swap(left, right);
e440a328 6376 }
6377
6378 // The right operand is not an interface. We need to take its
6379 // address if it is not a pointer.
ceeb12d7 6380 Expression* pointer_arg = NULL;
e440a328 6381 if (right_type->points_to() != NULL)
2387f644 6382 pointer_arg = right;
e440a328 6383 else
6384 {
2387f644 6385 go_assert(right->is_addressable());
6386 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6387 location);
e440a328 6388 }
e440a328 6389
2387f644 6390 Expression* descriptor =
6391 Expression::make_type_descriptor(right_type, location);
6392 left =
ceeb12d7 6393 Runtime::make_call((left_type->interface_type()->is_empty()
6394 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6395 : Runtime::INTERFACE_VALUE_COMPARE),
2387f644 6396 location, 3, left, descriptor,
ceeb12d7 6397 pointer_arg);
2387f644 6398 right = zexpr;
e440a328 6399 }
6400 else if (left_type->interface_type() != NULL
6401 && right_type->interface_type() != NULL)
6402 {
ceeb12d7 6403 Runtime::Function compare_function;
739bad04 6404 if (left_type->interface_type()->is_empty()
6405 && right_type->interface_type()->is_empty())
ceeb12d7 6406 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
739bad04 6407 else if (!left_type->interface_type()->is_empty()
6408 && !right_type->interface_type()->is_empty())
ceeb12d7 6409 compare_function = Runtime::INTERFACE_COMPARE;
739bad04 6410 else
6411 {
6412 if (left_type->interface_type()->is_empty())
6413 {
c484d925 6414 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
739bad04 6415 std::swap(left_type, right_type);
2387f644 6416 std::swap(left, right);
739bad04 6417 }
c484d925 6418 go_assert(!left_type->interface_type()->is_empty());
6419 go_assert(right_type->interface_type()->is_empty());
ceeb12d7 6420 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
739bad04 6421 }
6422
2387f644 6423 left = Runtime::make_call(compare_function, location, 2, left, right);
6424 right = zexpr;
e440a328 6425 }
6426
6427 if (left_type->is_nil_type()
6428 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6429 {
6430 std::swap(left_type, right_type);
2387f644 6431 std::swap(left, right);
e440a328 6432 }
6433
6434 if (right_type->is_nil_type())
6435 {
2387f644 6436 right = Expression::make_nil(location);
e440a328 6437 if (left_type->array_type() != NULL
6438 && left_type->array_type()->length() == NULL)
6439 {
6440 Array_type* at = left_type->array_type();
2387f644 6441 left = at->get_value_pointer(context->gogo(), left);
e440a328 6442 }
6443 else if (left_type->interface_type() != NULL)
6444 {
6445 // An interface is nil if the first field is nil.
2387f644 6446 left = Expression::make_field_reference(left, 0, location);
e440a328 6447 }
6448 }
6449
a32698ee 6450 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6451 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
e90c9dfc 6452
a32698ee 6453 Gogo* gogo = context->gogo();
6454 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6455 right_bexpr, location);
6456 if (result_type != NULL)
6457 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6458 ret, location);
e440a328 6459 return ret;
6460}
6461
6462// Class Bound_method_expression.
6463
6464// Traversal.
6465
6466int
6467Bound_method_expression::do_traverse(Traverse* traverse)
6468{
e0659c9e 6469 return Expression::traverse(&this->expr_, traverse);
e440a328 6470}
6471
0afbb937 6472// Lower the expression. If this is a method value rather than being
6473// called, and the method is accessed via a pointer, we may need to
6474// add nil checks. Introduce a temporary variable so that those nil
6475// checks do not cause multiple evaluation.
6476
6477Expression*
6478Bound_method_expression::do_lower(Gogo*, Named_object*,
6479 Statement_inserter* inserter, int)
6480{
6481 // For simplicity we use a temporary for every call to an embedded
6482 // method, even though some of them might be pure value methods and
6483 // not require a temporary.
6484 if (this->expr_->var_expression() == NULL
6485 && this->expr_->temporary_reference_expression() == NULL
6486 && this->expr_->set_and_use_temporary_expression() == NULL
6487 && (this->method_->field_indexes() != NULL
6488 || (this->method_->is_value_method()
6489 && this->expr_->type()->points_to() != NULL)))
6490 {
6491 Temporary_statement* temp =
6492 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6493 inserter->insert(temp);
6494 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6495 this->location());
6496 }
6497 return this;
6498}
6499
e440a328 6500// Return the type of a bound method expression. The type of this
0afbb937 6501// object is simply the type of the method with no receiver.
e440a328 6502
6503Type*
6504Bound_method_expression::do_type()
6505{
0afbb937 6506 Named_object* fn = this->method_->named_object();
6507 Function_type* fntype;
6508 if (fn->is_function())
6509 fntype = fn->func_value()->type();
6510 else if (fn->is_function_declaration())
6511 fntype = fn->func_declaration_value()->type();
e0659c9e 6512 else
6513 return Type::make_error_type();
0afbb937 6514 return fntype->copy_without_receiver();
e440a328 6515}
6516
6517// Determine the types of a method expression.
6518
6519void
6520Bound_method_expression::do_determine_type(const Type_context*)
6521{
0afbb937 6522 Named_object* fn = this->method_->named_object();
6523 Function_type* fntype;
6524 if (fn->is_function())
6525 fntype = fn->func_value()->type();
6526 else if (fn->is_function_declaration())
6527 fntype = fn->func_declaration_value()->type();
6528 else
6529 fntype = NULL;
e440a328 6530 if (fntype == NULL || !fntype->is_method())
6531 this->expr_->determine_type_no_context();
6532 else
6533 {
6534 Type_context subcontext(fntype->receiver()->type(), false);
6535 this->expr_->determine_type(&subcontext);
6536 }
6537}
6538
6539// Check the types of a method expression.
6540
6541void
6542Bound_method_expression::do_check_types(Gogo*)
6543{
0afbb937 6544 Named_object* fn = this->method_->named_object();
6545 if (!fn->is_function() && !fn->is_function_declaration())
6546 {
6547 this->report_error(_("object is not a method"));
6548 return;
6549 }
6550
6551 Function_type* fntype;
6552 if (fn->is_function())
6553 fntype = fn->func_value()->type();
6554 else if (fn->is_function_declaration())
6555 fntype = fn->func_declaration_value()->type();
e440a328 6556 else
0afbb937 6557 go_unreachable();
6558 Type* rtype = fntype->receiver()->type()->deref();
6559 Type* etype = (this->expr_type_ != NULL
6560 ? this->expr_type_
6561 : this->expr_->type());
6562 etype = etype->deref();
6563 if (!Type::are_identical(rtype, etype, true, NULL))
6564 this->report_error(_("method type does not match object type"));
6565}
6566
6567// If a bound method expression is not simply called, then it is
6568// represented as a closure. The closure will hold a single variable,
6569// the receiver to pass to the method. The function will be a simple
6570// thunk that pulls that value from the closure and calls the method
6571// with the remaining arguments.
6572//
6573// Because method values are not common, we don't build all thunks for
6574// every methods, but instead only build them as we need them. In
6575// particular, we even build them on demand for methods defined in
6576// other packages.
6577
6578Bound_method_expression::Method_value_thunks
6579 Bound_method_expression::method_value_thunks;
6580
6581// Find or create the thunk for METHOD.
6582
6583Named_object*
6584Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6585 Named_object* fn)
6586{
6587 std::pair<Named_object*, Named_object*> val(fn, NULL);
6588 std::pair<Method_value_thunks::iterator, bool> ins =
6589 Bound_method_expression::method_value_thunks.insert(val);
6590 if (!ins.second)
6591 {
6592 // We have seen this method before.
6593 go_assert(ins.first->second != NULL);
6594 return ins.first->second;
6595 }
6596
6597 Location loc = fn->location();
6598
6599 Function_type* orig_fntype;
6600 if (fn->is_function())
6601 orig_fntype = fn->func_value()->type();
6602 else if (fn->is_function_declaration())
6603 orig_fntype = fn->func_declaration_value()->type();
6604 else
6605 orig_fntype = NULL;
6606
6607 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6608 {
0afbb937 6609 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6610 return ins.first->second;
e440a328 6611 }
0afbb937 6612
6613 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6614 // The type here is wrong--it should be the C function type. But it
6615 // doesn't really matter.
0afbb937 6616 Type* vt = Type::make_pointer_type(Type::make_void_type());
6617 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6618 sfl->push_back(Struct_field(Typed_identifier("val.1",
6619 orig_fntype->receiver()->type(),
6620 loc)));
6621 Type* closure_type = Type::make_struct_type(sfl, loc);
6622 closure_type = Type::make_pointer_type(closure_type);
6623
f8bdf81a 6624 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6625
6626 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6627 false, loc);
6628
f8bdf81a 6629 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6630 cvar->set_is_used();
6631 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6632 new_no->func_value()->set_closure_var(cp);
0afbb937 6633
f8bdf81a 6634 gogo->start_block(loc);
0afbb937 6635
6636 // Field 0 of the closure is the function code pointer, field 1 is
6637 // the value on which to invoke the method.
6638 Expression* arg = Expression::make_var_reference(cp, loc);
6639 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6640 arg = Expression::make_field_reference(arg, 1, loc);
6641
6642 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6643
6644 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6645 Expression_list* args;
6646 if (orig_params == NULL || orig_params->empty())
6647 args = NULL;
6648 else
6649 {
6650 const Typed_identifier_list* new_params = new_fntype->parameters();
6651 args = new Expression_list();
6652 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6653 p != new_params->end();
0afbb937 6654 ++p)
6655 {
6656 Named_object* p_no = gogo->lookup(p->name(), NULL);
6657 go_assert(p_no != NULL
6658 && p_no->is_variable()
6659 && p_no->var_value()->is_parameter());
6660 args->push_back(Expression::make_var_reference(p_no, loc));
6661 }
6662 }
6663
6664 Call_expression* call = Expression::make_call(bme, args,
6665 orig_fntype->is_varargs(),
6666 loc);
6667 call->set_varargs_are_lowered();
6668
6669 Statement* s = Statement::make_return_from_call(call, loc);
6670 gogo->add_statement(s);
6671 Block* b = gogo->finish_block(loc);
6672 gogo->add_block(b, loc);
6673 gogo->lower_block(new_no, b);
a32698ee 6674 gogo->flatten_block(new_no, b);
0afbb937 6675 gogo->finish_function(loc);
6676
6677 ins.first->second = new_no;
6678 return new_no;
6679}
6680
6681// Return an expression to check *REF for nil while dereferencing
6682// according to FIELD_INDEXES. Update *REF to build up the field
6683// reference. This is a static function so that we don't have to
6684// worry about declaring Field_indexes in expressions.h.
6685
6686static Expression*
6687bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6688 Expression** ref)
6689{
6690 if (field_indexes == NULL)
6691 return Expression::make_boolean(false, loc);
6692 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6693 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6694 go_assert(stype != NULL
6695 && field_indexes->field_index < stype->field_count());
6696 if ((*ref)->type()->struct_type() == NULL)
6697 {
6698 go_assert((*ref)->type()->points_to() != NULL);
6699 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6700 Expression::make_nil(loc),
6701 loc);
6702 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6703 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6704 go_assert((*ref)->type()->struct_type() == stype);
6705 }
6706 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6707 loc);
6708 return cond;
e440a328 6709}
6710
0afbb937 6711// Get the tree for a method value.
e440a328 6712
6713tree
0afbb937 6714Bound_method_expression::do_get_tree(Translate_context* context)
e440a328 6715{
0afbb937 6716 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6717 this->method_,
6718 this->function_);
6719 if (thunk->is_erroneous())
6720 {
6721 go_assert(saw_errors());
6722 return error_mark_node;
6723 }
6724
6725 // FIXME: We should lower this earlier, but we can't lower it in the
6726 // lowering pass because at that point we don't know whether we need
6727 // to create the thunk or not. If the expression is called, we
6728 // don't need the thunk.
6729
6730 Location loc = this->location();
6731
6732 // If the method expects a value, and we have a pointer, we need to
6733 // dereference the pointer.
6734
6735 Named_object* fn = this->method_->named_object();
6736 Function_type* fntype;
6737 if (fn->is_function())
6738 fntype = fn->func_value()->type();
6739 else if (fn->is_function_declaration())
6740 fntype = fn->func_declaration_value()->type();
6741 else
6742 go_unreachable();
6743
6744 Expression* val = this->expr_;
6745 if (fntype->receiver()->type()->points_to() == NULL
6746 && val->type()->points_to() != NULL)
6747 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6748
6749 // Note that we are ignoring this->expr_type_ here. The thunk will
6750 // expect a closure whose second field has type this->expr_type_ (if
6751 // that is not NULL). We are going to pass it a closure whose
6752 // second field has type this->expr_->type(). Since
6753 // this->expr_type_ is only not-NULL for pointer types, we can get
6754 // away with this.
6755
6756 Struct_field_list* fields = new Struct_field_list();
6757 fields->push_back(Struct_field(Typed_identifier("fn.0",
6758 thunk->func_value()->type(),
6759 loc)));
6760 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6761 Struct_type* st = Type::make_struct_type(fields, loc);
6762
6763 Expression_list* vals = new Expression_list();
6764 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6765 vals->push_back(val);
6766
6767 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 6768 ret = Expression::make_heap_expression(ret, loc);
0afbb937 6769
0afbb937 6770 // See whether the expression or any embedded pointers are nil.
6771
df7ef1fd 6772 Expression* nil_check = NULL;
0afbb937 6773 Expression* expr = this->expr_;
6774 if (this->method_->field_indexes() != NULL)
6775 {
6776 // Note that we are evaluating this->expr_ twice, but that is OK
6777 // because in the lowering pass we forced it into a temporary
6778 // variable.
6779 Expression* ref = expr;
6780 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6781 expr = ref;
6782 }
6783
6784 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6785 {
6786 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6787 Expression::make_nil(loc),
6788 loc);
6789 if (nil_check == NULL)
6790 nil_check = n;
6791 else
6792 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6793 }
6794
df7ef1fd 6795 Bexpression* bme = tree_to_expr(ret->get_tree(context));
0afbb937 6796 if (nil_check != NULL)
6797 {
df7ef1fd 6798 Gogo* gogo = context->gogo();
6799 Expression* crash =
6800 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
6801 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
6802 Btype* btype = ret->type()->get_backend(gogo);
6803 Bexpression* bcheck = tree_to_expr(nil_check->get_tree(context));
6804 bme = gogo->backend()->conditional_expression(btype, bcheck, bcrash,
6805 bme, loc);
6806 }
6807 return expr_to_tree(bme);
e440a328 6808}
6809
d751bb78 6810// Dump ast representation of a bound method expression.
6811
6812void
6813Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6814 const
6815{
6816 if (this->expr_type_ != NULL)
6817 ast_dump_context->ostream() << "(";
6818 ast_dump_context->dump_expression(this->expr_);
6819 if (this->expr_type_ != NULL)
6820 {
6821 ast_dump_context->ostream() << ":";
6822 ast_dump_context->dump_type(this->expr_type_);
6823 ast_dump_context->ostream() << ")";
6824 }
6825
0afbb937 6826 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6827}
6828
e440a328 6829// Make a method expression.
6830
6831Bound_method_expression*
0afbb937 6832Expression::make_bound_method(Expression* expr, const Method* method,
6833 Named_object* function, Location location)
e440a328 6834{
0afbb937 6835 return new Bound_method_expression(expr, method, function, location);
e440a328 6836}
6837
6838// Class Builtin_call_expression. This is used for a call to a
6839// builtin function.
6840
6841class Builtin_call_expression : public Call_expression
6842{
6843 public:
6844 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6845 bool is_varargs, Location location);
e440a328 6846
6847 protected:
6848 // This overrides Call_expression::do_lower.
6849 Expression*
ceeb4318 6850 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6851
35a54f17 6852 Expression*
6853 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6854
e440a328 6855 bool
6856 do_is_constant() const;
6857
6858 bool
0c77715b 6859 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6860
4f2138d7 6861 bool
a7549a6a 6862 do_discarding_value();
6863
e440a328 6864 Type*
6865 do_type();
6866
6867 void
6868 do_determine_type(const Type_context*);
6869
6870 void
6871 do_check_types(Gogo*);
6872
6873 Expression*
6874 do_copy()
6875 {
6876 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6877 this->args()->copy(),
6878 this->is_varargs(),
6879 this->location());
6880 }
6881
6882 tree
6883 do_get_tree(Translate_context*);
6884
6885 void
6886 do_export(Export*) const;
6887
6888 virtual bool
6889 do_is_recover_call() const;
6890
6891 virtual void
6892 do_set_recover_arg(Expression*);
6893
6894 private:
6895 // The builtin functions.
6896 enum Builtin_function_code
6897 {
6898 BUILTIN_INVALID,
6899
6900 // Predeclared builtin functions.
6901 BUILTIN_APPEND,
6902 BUILTIN_CAP,
6903 BUILTIN_CLOSE,
48080209 6904 BUILTIN_COMPLEX,
e440a328 6905 BUILTIN_COPY,
1cce762f 6906 BUILTIN_DELETE,
e440a328 6907 BUILTIN_IMAG,
6908 BUILTIN_LEN,
6909 BUILTIN_MAKE,
6910 BUILTIN_NEW,
6911 BUILTIN_PANIC,
6912 BUILTIN_PRINT,
6913 BUILTIN_PRINTLN,
6914 BUILTIN_REAL,
6915 BUILTIN_RECOVER,
6916
6917 // Builtin functions from the unsafe package.
6918 BUILTIN_ALIGNOF,
6919 BUILTIN_OFFSETOF,
6920 BUILTIN_SIZEOF
6921 };
6922
6923 Expression*
6924 one_arg() const;
6925
6926 bool
6927 check_one_arg();
6928
6929 static Type*
6930 real_imag_type(Type*);
6931
6932 static Type*
48080209 6933 complex_type(Type*);
e440a328 6934
a9182619 6935 Expression*
6936 lower_make();
6937
6938 bool
1ad00fd4 6939 check_int_value(Expression*, bool is_length);
a9182619 6940
e440a328 6941 // A pointer back to the general IR structure. This avoids a global
6942 // variable, or passing it around everywhere.
6943 Gogo* gogo_;
6944 // The builtin function being called.
6945 Builtin_function_code code_;
0f914071 6946 // Used to stop endless loops when the length of an array uses len
6947 // or cap of the array itself.
6948 mutable bool seen_;
e440a328 6949};
6950
6951Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6952 Expression* fn,
6953 Expression_list* args,
6954 bool is_varargs,
b13c66cd 6955 Location location)
e440a328 6956 : Call_expression(fn, args, is_varargs, location),
0f914071 6957 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
e440a328 6958{
6959 Func_expression* fnexp = this->fn()->func_expression();
c484d925 6960 go_assert(fnexp != NULL);
e440a328 6961 const std::string& name(fnexp->named_object()->name());
6962 if (name == "append")
6963 this->code_ = BUILTIN_APPEND;
6964 else if (name == "cap")
6965 this->code_ = BUILTIN_CAP;
6966 else if (name == "close")
6967 this->code_ = BUILTIN_CLOSE;
48080209 6968 else if (name == "complex")
6969 this->code_ = BUILTIN_COMPLEX;
e440a328 6970 else if (name == "copy")
6971 this->code_ = BUILTIN_COPY;
1cce762f 6972 else if (name == "delete")
6973 this->code_ = BUILTIN_DELETE;
e440a328 6974 else if (name == "imag")
6975 this->code_ = BUILTIN_IMAG;
6976 else if (name == "len")
6977 this->code_ = BUILTIN_LEN;
6978 else if (name == "make")
6979 this->code_ = BUILTIN_MAKE;
6980 else if (name == "new")
6981 this->code_ = BUILTIN_NEW;
6982 else if (name == "panic")
6983 this->code_ = BUILTIN_PANIC;
6984 else if (name == "print")
6985 this->code_ = BUILTIN_PRINT;
6986 else if (name == "println")
6987 this->code_ = BUILTIN_PRINTLN;
6988 else if (name == "real")
6989 this->code_ = BUILTIN_REAL;
6990 else if (name == "recover")
6991 this->code_ = BUILTIN_RECOVER;
6992 else if (name == "Alignof")
6993 this->code_ = BUILTIN_ALIGNOF;
6994 else if (name == "Offsetof")
6995 this->code_ = BUILTIN_OFFSETOF;
6996 else if (name == "Sizeof")
6997 this->code_ = BUILTIN_SIZEOF;
6998 else
c3e6f413 6999 go_unreachable();
e440a328 7000}
7001
7002// Return whether this is a call to recover. This is a virtual
7003// function called from the parent class.
7004
7005bool
7006Builtin_call_expression::do_is_recover_call() const
7007{
7008 if (this->classification() == EXPRESSION_ERROR)
7009 return false;
7010 return this->code_ == BUILTIN_RECOVER;
7011}
7012
7013// Set the argument for a call to recover.
7014
7015void
7016Builtin_call_expression::do_set_recover_arg(Expression* arg)
7017{
7018 const Expression_list* args = this->args();
c484d925 7019 go_assert(args == NULL || args->empty());
e440a328 7020 Expression_list* new_args = new Expression_list();
7021 new_args->push_back(arg);
7022 this->set_args(new_args);
7023}
7024
e440a328 7025// Lower a builtin call expression. This turns new and make into
7026// specific expressions. We also convert to a constant if we can.
7027
7028Expression*
ceeb4318 7029Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7030 Statement_inserter* inserter, int)
e440a328 7031{
a9182619 7032 if (this->classification() == EXPRESSION_ERROR)
7033 return this;
7034
b13c66cd 7035 Location loc = this->location();
1cce762f 7036
a8725655 7037 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7038 {
7039 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7040 return Expression::make_error(loc);
a8725655 7041 }
7042
393ba00b 7043 if (this->code_ == BUILTIN_OFFSETOF)
7044 {
7045 Expression* arg = this->one_arg();
12e69faa 7046
7047 if (arg->bound_method_expression() != NULL
7048 || arg->interface_field_reference_expression() != NULL)
7049 {
7050 this->report_error(_("invalid use of method value as argument "
7051 "of Offsetof"));
7052 return this;
7053 }
7054
393ba00b 7055 Field_reference_expression* farg = arg->field_reference_expression();
7056 while (farg != NULL)
7057 {
7058 if (!farg->implicit())
7059 break;
7060 // When the selector refers to an embedded field,
7061 // it must not be reached through pointer indirections.
7062 if (farg->expr()->deref() != farg->expr())
7063 {
12e69faa 7064 this->report_error(_("argument of Offsetof implies "
7065 "indirection of an embedded field"));
393ba00b 7066 return this;
7067 }
7068 // Go up until we reach the original base.
7069 farg = farg->expr()->field_reference_expression();
7070 }
7071 }
7072
1cce762f 7073 if (this->is_constant())
e440a328 7074 {
0c77715b 7075 Numeric_constant nc;
7076 if (this->numeric_constant_value(&nc))
7077 return nc.expression(loc);
e440a328 7078 }
1cce762f 7079
7080 switch (this->code_)
e440a328 7081 {
1cce762f 7082 default:
7083 break;
7084
7085 case BUILTIN_NEW:
7086 {
7087 const Expression_list* args = this->args();
7088 if (args == NULL || args->size() < 1)
7089 this->report_error(_("not enough arguments"));
7090 else if (args->size() > 1)
7091 this->report_error(_("too many arguments"));
7092 else
7093 {
7094 Expression* arg = args->front();
7095 if (!arg->is_type_expression())
7096 {
7097 error_at(arg->location(), "expected type");
7098 this->set_is_error();
7099 }
7100 else
7101 return Expression::make_allocation(arg->type(), loc);
7102 }
7103 }
7104 break;
7105
7106 case BUILTIN_MAKE:
7107 return this->lower_make();
7108
7109 case BUILTIN_RECOVER:
e440a328 7110 if (function != NULL)
7111 function->func_value()->set_calls_recover();
7112 else
7113 {
7114 // Calling recover outside of a function always returns the
7115 // nil empty interface.
823c7e3d 7116 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7117 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7118 }
1cce762f 7119 break;
7120
7121 case BUILTIN_APPEND:
7122 {
7123 // Lower the varargs.
7124 const Expression_list* args = this->args();
7125 if (args == NULL || args->empty())
e440a328 7126 return this;
1cce762f 7127 Type* slice_type = args->front()->type();
7128 if (!slice_type->is_slice_type())
7129 {
3ff4863b 7130 if (slice_type->is_nil_type())
7131 error_at(args->front()->location(), "use of untyped nil");
7132 else
7133 error_at(args->front()->location(),
7134 "argument 1 must be a slice");
1cce762f 7135 this->set_is_error();
7136 return this;
7137 }
19fd40c3 7138 Type* element_type = slice_type->array_type()->element_type();
7139 this->lower_varargs(gogo, function, inserter,
7140 Type::make_array_type(element_type, NULL),
7141 2);
1cce762f 7142 }
7143 break;
7144
7145 case BUILTIN_DELETE:
7146 {
7147 // Lower to a runtime function call.
7148 const Expression_list* args = this->args();
7149 if (args == NULL || args->size() < 2)
7150 this->report_error(_("not enough arguments"));
7151 else if (args->size() > 2)
7152 this->report_error(_("too many arguments"));
7153 else if (args->front()->type()->map_type() == NULL)
7154 this->report_error(_("argument 1 must be a map"));
7155 else
7156 {
7157 // Since this function returns no value it must appear in
7158 // a statement by itself, so we don't have to worry about
7159 // order of evaluation of values around it. Evaluate the
7160 // map first to get order of evaluation right.
7161 Map_type* mt = args->front()->type()->map_type();
7162 Temporary_statement* map_temp =
7163 Statement::make_temporary(mt, args->front(), loc);
7164 inserter->insert(map_temp);
7165
7166 Temporary_statement* key_temp =
7167 Statement::make_temporary(mt->key_type(), args->back(), loc);
7168 inserter->insert(key_temp);
7169
7170 Expression* e1 = Expression::make_temporary_reference(map_temp,
7171 loc);
7172 Expression* e2 = Expression::make_temporary_reference(key_temp,
7173 loc);
7174 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7175 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7176 2, e1, e2);
7177 }
7178 }
7179 break;
e440a328 7180 }
7181
7182 return this;
7183}
7184
35a54f17 7185// Flatten a builtin call expression. This turns the arguments of copy and
7186// append into temporary expressions.
7187
7188Expression*
7189Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7190 Statement_inserter* inserter)
7191{
7192 if (this->code_ == BUILTIN_APPEND
7193 || this->code_ == BUILTIN_COPY)
7194 {
7195 Location loc = this->location();
7196 Type* at = this->args()->front()->type();
7197 for (Expression_list::iterator pa = this->args()->begin();
7198 pa != this->args()->end();
7199 ++pa)
7200 {
7201 if ((*pa)->is_nil_expression())
7202 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7203 if (!(*pa)->is_variable())
7204 {
7205 Temporary_statement* temp =
7206 Statement::make_temporary(NULL, *pa, loc);
7207 inserter->insert(temp);
7208 *pa = Expression::make_temporary_reference(temp, loc);
7209 }
7210 }
7211 }
7212 return this;
7213}
7214
a9182619 7215// Lower a make expression.
7216
7217Expression*
7218Builtin_call_expression::lower_make()
7219{
b13c66cd 7220 Location loc = this->location();
a9182619 7221
7222 const Expression_list* args = this->args();
7223 if (args == NULL || args->size() < 1)
7224 {
7225 this->report_error(_("not enough arguments"));
7226 return Expression::make_error(this->location());
7227 }
7228
7229 Expression_list::const_iterator parg = args->begin();
7230
7231 Expression* first_arg = *parg;
7232 if (!first_arg->is_type_expression())
7233 {
7234 error_at(first_arg->location(), "expected type");
7235 this->set_is_error();
7236 return Expression::make_error(this->location());
7237 }
7238 Type* type = first_arg->type();
7239
7240 bool is_slice = false;
7241 bool is_map = false;
7242 bool is_chan = false;
411eb89e 7243 if (type->is_slice_type())
a9182619 7244 is_slice = true;
7245 else if (type->map_type() != NULL)
7246 is_map = true;
7247 else if (type->channel_type() != NULL)
7248 is_chan = true;
7249 else
7250 {
7251 this->report_error(_("invalid type for make function"));
7252 return Expression::make_error(this->location());
7253 }
7254
ac84c822 7255 bool have_big_args = false;
7256 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7257 int uintptr_bits = uintptr_type->integer_type()->bits();
7258
f6bc81e6 7259 Type_context int_context(Type::lookup_integer_type("int"), false);
7260
a9182619 7261 ++parg;
7262 Expression* len_arg;
7263 if (parg == args->end())
7264 {
7265 if (is_slice)
7266 {
7267 this->report_error(_("length required when allocating a slice"));
7268 return Expression::make_error(this->location());
7269 }
7270
7271 mpz_t zval;
7272 mpz_init_set_ui(zval, 0);
7273 len_arg = Expression::make_integer(&zval, NULL, loc);
7274 mpz_clear(zval);
7275 }
7276 else
7277 {
7278 len_arg = *parg;
f6bc81e6 7279 len_arg->determine_type(&int_context);
1ad00fd4 7280 if (!this->check_int_value(len_arg, true))
7281 return Expression::make_error(this->location());
ac84c822 7282 if (len_arg->type()->integer_type() != NULL
7283 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7284 have_big_args = true;
a9182619 7285 ++parg;
7286 }
7287
7288 Expression* cap_arg = NULL;
7289 if (is_slice && parg != args->end())
7290 {
7291 cap_arg = *parg;
f6bc81e6 7292 cap_arg->determine_type(&int_context);
1ad00fd4 7293 if (!this->check_int_value(cap_arg, false))
7294 return Expression::make_error(this->location());
7295
7296 Numeric_constant nclen;
7297 Numeric_constant nccap;
7298 unsigned long vlen;
7299 unsigned long vcap;
7300 if (len_arg->numeric_constant_value(&nclen)
7301 && cap_arg->numeric_constant_value(&nccap)
7302 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7303 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7304 && vlen > vcap)
a9182619 7305 {
1ad00fd4 7306 this->report_error(_("len larger than cap"));
a9182619 7307 return Expression::make_error(this->location());
7308 }
1ad00fd4 7309
ac84c822 7310 if (cap_arg->type()->integer_type() != NULL
7311 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7312 have_big_args = true;
a9182619 7313 ++parg;
7314 }
7315
7316 if (parg != args->end())
7317 {
7318 this->report_error(_("too many arguments to make"));
7319 return Expression::make_error(this->location());
7320 }
7321
b13c66cd 7322 Location type_loc = first_arg->location();
a9182619 7323 Expression* type_arg;
7324 if (is_slice || is_chan)
7325 type_arg = Expression::make_type_descriptor(type, type_loc);
7326 else if (is_map)
7327 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7328 else
7329 go_unreachable();
7330
7331 Expression* call;
7332 if (is_slice)
7333 {
7334 if (cap_arg == NULL)
ac84c822 7335 call = Runtime::make_call((have_big_args
7336 ? Runtime::MAKESLICE1BIG
7337 : Runtime::MAKESLICE1),
7338 loc, 2, type_arg, len_arg);
a9182619 7339 else
ac84c822 7340 call = Runtime::make_call((have_big_args
7341 ? Runtime::MAKESLICE2BIG
7342 : Runtime::MAKESLICE2),
7343 loc, 3, type_arg, len_arg, cap_arg);
a9182619 7344 }
7345 else if (is_map)
ac84c822 7346 call = Runtime::make_call((have_big_args
7347 ? Runtime::MAKEMAPBIG
7348 : Runtime::MAKEMAP),
7349 loc, 2, type_arg, len_arg);
a9182619 7350 else if (is_chan)
ac84c822 7351 call = Runtime::make_call((have_big_args
7352 ? Runtime::MAKECHANBIG
7353 : Runtime::MAKECHAN),
7354 loc, 2, type_arg, len_arg);
a9182619 7355 else
7356 go_unreachable();
7357
7358 return Expression::make_unsafe_cast(type, call, loc);
7359}
7360
7361// Return whether an expression has an integer value. Report an error
7362// if not. This is used when handling calls to the predeclared make
7363// function.
7364
7365bool
1ad00fd4 7366Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7367{
0c77715b 7368 Numeric_constant nc;
1ad00fd4 7369 if (e->numeric_constant_value(&nc))
a9182619 7370 {
1ad00fd4 7371 unsigned long v;
7372 switch (nc.to_unsigned_long(&v))
7373 {
7374 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7375 break;
1ad00fd4 7376 case Numeric_constant::NC_UL_NOTINT:
7377 error_at(e->location(), "non-integer %s argument to make",
7378 is_length ? "len" : "cap");
7379 return false;
7380 case Numeric_constant::NC_UL_NEGATIVE:
7381 error_at(e->location(), "negative %s argument to make",
7382 is_length ? "len" : "cap");
7383 return false;
7384 case Numeric_constant::NC_UL_BIG:
7385 // We don't want to give a compile-time error for a 64-bit
7386 // value on a 32-bit target.
1b10c5e7 7387 break;
1ad00fd4 7388 }
1b10c5e7 7389
7390 mpz_t val;
7391 if (!nc.to_int(&val))
7392 go_unreachable();
7393 int bits = mpz_sizeinbase(val, 2);
7394 mpz_clear(val);
7395 Type* int_type = Type::lookup_integer_type("int");
7396 if (bits >= int_type->integer_type()->bits())
7397 {
7398 error_at(e->location(), "%s argument too large for make",
7399 is_length ? "len" : "cap");
7400 return false;
7401 }
7402
7403 return true;
a9182619 7404 }
7405
1ad00fd4 7406 if (e->type()->integer_type() != NULL)
7407 return true;
7408
7409 error_at(e->location(), "non-integer %s argument to make",
7410 is_length ? "len" : "cap");
a9182619 7411 return false;
7412}
7413
e440a328 7414// Return the type of the real or imag functions, given the type of
7415// the argument. We need to map complex to float, complex64 to
7416// float32, and complex128 to float64, so it has to be done by name.
7417// This returns NULL if it can't figure out the type.
7418
7419Type*
7420Builtin_call_expression::real_imag_type(Type* arg_type)
7421{
7422 if (arg_type == NULL || arg_type->is_abstract())
7423 return NULL;
7424 Named_type* nt = arg_type->named_type();
7425 if (nt == NULL)
7426 return NULL;
7427 while (nt->real_type()->named_type() != NULL)
7428 nt = nt->real_type()->named_type();
48080209 7429 if (nt->name() == "complex64")
e440a328 7430 return Type::lookup_float_type("float32");
7431 else if (nt->name() == "complex128")
7432 return Type::lookup_float_type("float64");
7433 else
7434 return NULL;
7435}
7436
48080209 7437// Return the type of the complex function, given the type of one of the
e440a328 7438// argments. Like real_imag_type, we have to map by name.
7439
7440Type*
48080209 7441Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7442{
7443 if (arg_type == NULL || arg_type->is_abstract())
7444 return NULL;
7445 Named_type* nt = arg_type->named_type();
7446 if (nt == NULL)
7447 return NULL;
7448 while (nt->real_type()->named_type() != NULL)
7449 nt = nt->real_type()->named_type();
48080209 7450 if (nt->name() == "float32")
e440a328 7451 return Type::lookup_complex_type("complex64");
7452 else if (nt->name() == "float64")
7453 return Type::lookup_complex_type("complex128");
7454 else
7455 return NULL;
7456}
7457
7458// Return a single argument, or NULL if there isn't one.
7459
7460Expression*
7461Builtin_call_expression::one_arg() const
7462{
7463 const Expression_list* args = this->args();
aa615cb3 7464 if (args == NULL || args->size() != 1)
e440a328 7465 return NULL;
7466 return args->front();
7467}
7468
83921647 7469// A traversal class which looks for a call or receive expression.
7470
7471class Find_call_expression : public Traverse
7472{
7473 public:
7474 Find_call_expression()
7475 : Traverse(traverse_expressions),
7476 found_(false)
7477 { }
7478
7479 int
7480 expression(Expression**);
7481
7482 bool
7483 found()
7484 { return this->found_; }
7485
7486 private:
7487 bool found_;
7488};
7489
7490int
7491Find_call_expression::expression(Expression** pexpr)
7492{
7493 if ((*pexpr)->call_expression() != NULL
7494 || (*pexpr)->receive_expression() != NULL)
7495 {
7496 this->found_ = true;
7497 return TRAVERSE_EXIT;
7498 }
7499 return TRAVERSE_CONTINUE;
7500}
7501
7502// Return whether this is constant: len of a string constant, or len
7503// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7504// unsafe.Alignof.
e440a328 7505
7506bool
7507Builtin_call_expression::do_is_constant() const
7508{
12e69faa 7509 if (this->is_error_expression())
7510 return true;
e440a328 7511 switch (this->code_)
7512 {
7513 case BUILTIN_LEN:
7514 case BUILTIN_CAP:
7515 {
0f914071 7516 if (this->seen_)
7517 return false;
7518
e440a328 7519 Expression* arg = this->one_arg();
7520 if (arg == NULL)
7521 return false;
7522 Type* arg_type = arg->type();
7523
7524 if (arg_type->points_to() != NULL
7525 && arg_type->points_to()->array_type() != NULL
411eb89e 7526 && !arg_type->points_to()->is_slice_type())
e440a328 7527 arg_type = arg_type->points_to();
7528
83921647 7529 // The len and cap functions are only constant if there are no
7530 // function calls or channel operations in the arguments.
7531 // Otherwise we have to make the call.
7532 if (!arg->is_constant())
7533 {
7534 Find_call_expression find_call;
7535 Expression::traverse(&arg, &find_call);
7536 if (find_call.found())
7537 return false;
7538 }
7539
e440a328 7540 if (arg_type->array_type() != NULL
7541 && arg_type->array_type()->length() != NULL)
0f914071 7542 return true;
e440a328 7543
7544 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7545 {
7546 this->seen_ = true;
7547 bool ret = arg->is_constant();
7548 this->seen_ = false;
7549 return ret;
7550 }
e440a328 7551 }
7552 break;
7553
7554 case BUILTIN_SIZEOF:
7555 case BUILTIN_ALIGNOF:
7556 return this->one_arg() != NULL;
7557
7558 case BUILTIN_OFFSETOF:
7559 {
7560 Expression* arg = this->one_arg();
7561 if (arg == NULL)
7562 return false;
7563 return arg->field_reference_expression() != NULL;
7564 }
7565
48080209 7566 case BUILTIN_COMPLEX:
e440a328 7567 {
7568 const Expression_list* args = this->args();
7569 if (args != NULL && args->size() == 2)
7570 return args->front()->is_constant() && args->back()->is_constant();
7571 }
7572 break;
7573
7574 case BUILTIN_REAL:
7575 case BUILTIN_IMAG:
7576 {
7577 Expression* arg = this->one_arg();
7578 return arg != NULL && arg->is_constant();
7579 }
7580
7581 default:
7582 break;
7583 }
7584
7585 return false;
7586}
7587
0c77715b 7588// Return a numeric constant if possible.
e440a328 7589
7590bool
0c77715b 7591Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7592{
7593 if (this->code_ == BUILTIN_LEN
7594 || this->code_ == BUILTIN_CAP)
7595 {
7596 Expression* arg = this->one_arg();
7597 if (arg == NULL)
7598 return false;
7599 Type* arg_type = arg->type();
7600
7601 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7602 {
7603 std::string sval;
7604 if (arg->string_constant_value(&sval))
7605 {
0c77715b 7606 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7607 sval.length());
e440a328 7608 return true;
7609 }
7610 }
7611
7612 if (arg_type->points_to() != NULL
7613 && arg_type->points_to()->array_type() != NULL
411eb89e 7614 && !arg_type->points_to()->is_slice_type())
e440a328 7615 arg_type = arg_type->points_to();
7616
7617 if (arg_type->array_type() != NULL
7618 && arg_type->array_type()->length() != NULL)
7619 {
0f914071 7620 if (this->seen_)
7621 return false;
e440a328 7622 Expression* e = arg_type->array_type()->length();
0f914071 7623 this->seen_ = true;
0c77715b 7624 bool r = e->numeric_constant_value(nc);
0f914071 7625 this->seen_ = false;
7626 if (r)
e440a328 7627 {
0c77715b 7628 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7629 this->location()))
7630 r = false;
e440a328 7631 }
0c77715b 7632 return r;
e440a328 7633 }
7634 }
7635 else if (this->code_ == BUILTIN_SIZEOF
7636 || this->code_ == BUILTIN_ALIGNOF)
7637 {
7638 Expression* arg = this->one_arg();
7639 if (arg == NULL)
7640 return false;
7641 Type* arg_type = arg->type();
5c13bd80 7642 if (arg_type->is_error())
e440a328 7643 return false;
7644 if (arg_type->is_abstract())
7645 return false;
2c809f8f 7646 if (this->seen_)
7647 return false;
927a01eb 7648
7649 unsigned int ret;
e440a328 7650 if (this->code_ == BUILTIN_SIZEOF)
7651 {
2c809f8f 7652 this->seen_ = true;
7653 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7654 this->seen_ = false;
7655 if (!ok)
e440a328 7656 return false;
7657 }
7658 else if (this->code_ == BUILTIN_ALIGNOF)
7659 {
2c809f8f 7660 bool ok;
7661 this->seen_ = true;
637bd3af 7662 if (arg->field_reference_expression() == NULL)
2c809f8f 7663 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7664 else
e440a328 7665 {
7666 // Calling unsafe.Alignof(s.f) returns the alignment of
7667 // the type of f when it is used as a field in a struct.
2c809f8f 7668 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7669 }
2c809f8f 7670 this->seen_ = false;
7671 if (!ok)
7672 return false;
e440a328 7673 }
7674 else
c3e6f413 7675 go_unreachable();
927a01eb 7676
7ba86326 7677 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7678 static_cast<unsigned long>(ret));
e440a328 7679 return true;
7680 }
7681 else if (this->code_ == BUILTIN_OFFSETOF)
7682 {
7683 Expression* arg = this->one_arg();
7684 if (arg == NULL)
7685 return false;
7686 Field_reference_expression* farg = arg->field_reference_expression();
7687 if (farg == NULL)
7688 return false;
2c809f8f 7689 if (this->seen_)
7690 return false;
7691
9a4bd570 7692 unsigned int total_offset = 0;
7693 while (true)
7694 {
7695 Expression* struct_expr = farg->expr();
7696 Type* st = struct_expr->type();
7697 if (st->struct_type() == NULL)
7698 return false;
7699 if (st->named_type() != NULL)
7700 st->named_type()->convert(this->gogo_);
7701 unsigned int offset;
2c809f8f 7702 this->seen_ = true;
7703 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7704 farg->field_index(),
7705 &offset);
7706 this->seen_ = false;
7707 if (!ok)
7708 return false;
9a4bd570 7709 total_offset += offset;
7710 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7711 {
7712 // Go up until we reach the original base.
7713 farg = struct_expr->field_reference_expression();
7714 continue;
7715 }
7716 break;
7717 }
7ba86326 7718 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
9a4bd570 7719 static_cast<unsigned long>(total_offset));
e440a328 7720 return true;
7721 }
0c77715b 7722 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7723 {
7724 Expression* arg = this->one_arg();
7725 if (arg == NULL)
7726 return false;
7727
0c77715b 7728 Numeric_constant argnc;
7729 if (!arg->numeric_constant_value(&argnc))
7730 return false;
7731
e440a328 7732 mpfr_t real;
7733 mpfr_t imag;
0c77715b 7734 if (!argnc.to_complex(&real, &imag))
7735 return false;
e440a328 7736
0c77715b 7737 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7738 if (this->code_ == BUILTIN_REAL)
7739 nc->set_float(type, real);
7740 else
7741 nc->set_float(type, imag);
7742 return true;
e440a328 7743 }
0c77715b 7744 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7745 {
7746 const Expression_list* args = this->args();
7747 if (args == NULL || args->size() != 2)
7748 return false;
7749
0c77715b 7750 Numeric_constant rnc;
7751 if (!args->front()->numeric_constant_value(&rnc))
7752 return false;
7753 Numeric_constant inc;
7754 if (!args->back()->numeric_constant_value(&inc))
7755 return false;
7756
7757 if (rnc.type() != NULL
7758 && !rnc.type()->is_abstract()
7759 && inc.type() != NULL
7760 && !inc.type()->is_abstract()
7761 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7762 return false;
7763
e440a328 7764 mpfr_t r;
0c77715b 7765 if (!rnc.to_float(&r))
7766 return false;
7767 mpfr_t i;
7768 if (!inc.to_float(&i))
e440a328 7769 {
7770 mpfr_clear(r);
7771 return false;
7772 }
7773
0c77715b 7774 Type* arg_type = rnc.type();
7775 if (arg_type == NULL || arg_type->is_abstract())
7776 arg_type = inc.type();
e440a328 7777
0c77715b 7778 Type* type = Builtin_call_expression::complex_type(arg_type);
7779 nc->set_complex(type, r, i);
e440a328 7780
7781 mpfr_clear(r);
7782 mpfr_clear(i);
7783
0c77715b 7784 return true;
e440a328 7785 }
7786
7787 return false;
7788}
7789
a7549a6a 7790// Give an error if we are discarding the value of an expression which
7791// should not normally be discarded. We don't give an error for
7792// discarding the value of an ordinary function call, but we do for
7793// builtin functions, purely for consistency with the gc compiler.
7794
4f2138d7 7795bool
a7549a6a 7796Builtin_call_expression::do_discarding_value()
7797{
7798 switch (this->code_)
7799 {
7800 case BUILTIN_INVALID:
7801 default:
7802 go_unreachable();
7803
7804 case BUILTIN_APPEND:
7805 case BUILTIN_CAP:
7806 case BUILTIN_COMPLEX:
7807 case BUILTIN_IMAG:
7808 case BUILTIN_LEN:
7809 case BUILTIN_MAKE:
7810 case BUILTIN_NEW:
7811 case BUILTIN_REAL:
7812 case BUILTIN_ALIGNOF:
7813 case BUILTIN_OFFSETOF:
7814 case BUILTIN_SIZEOF:
7815 this->unused_value_error();
4f2138d7 7816 return false;
a7549a6a 7817
7818 case BUILTIN_CLOSE:
7819 case BUILTIN_COPY:
1cce762f 7820 case BUILTIN_DELETE:
a7549a6a 7821 case BUILTIN_PANIC:
7822 case BUILTIN_PRINT:
7823 case BUILTIN_PRINTLN:
7824 case BUILTIN_RECOVER:
4f2138d7 7825 return true;
a7549a6a 7826 }
7827}
7828
e440a328 7829// Return the type.
7830
7831Type*
7832Builtin_call_expression::do_type()
7833{
7834 switch (this->code_)
7835 {
7836 case BUILTIN_INVALID:
7837 default:
c3e6f413 7838 go_unreachable();
e440a328 7839
7840 case BUILTIN_NEW:
7841 case BUILTIN_MAKE:
7842 {
7843 const Expression_list* args = this->args();
7844 if (args == NULL || args->empty())
7845 return Type::make_error_type();
7846 return Type::make_pointer_type(args->front()->type());
7847 }
7848
7849 case BUILTIN_CAP:
7850 case BUILTIN_COPY:
7851 case BUILTIN_LEN:
7ba86326 7852 return Type::lookup_integer_type("int");
7853
e440a328 7854 case BUILTIN_ALIGNOF:
7855 case BUILTIN_OFFSETOF:
7856 case BUILTIN_SIZEOF:
7ba86326 7857 return Type::lookup_integer_type("uintptr");
e440a328 7858
7859 case BUILTIN_CLOSE:
1cce762f 7860 case BUILTIN_DELETE:
e440a328 7861 case BUILTIN_PANIC:
7862 case BUILTIN_PRINT:
7863 case BUILTIN_PRINTLN:
7864 return Type::make_void_type();
7865
e440a328 7866 case BUILTIN_RECOVER:
823c7e3d 7867 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 7868
7869 case BUILTIN_APPEND:
7870 {
7871 const Expression_list* args = this->args();
7872 if (args == NULL || args->empty())
7873 return Type::make_error_type();
3ff4863b 7874 Type *ret = args->front()->type();
7875 if (!ret->is_slice_type())
7876 return Type::make_error_type();
7877 return ret;
e440a328 7878 }
7879
7880 case BUILTIN_REAL:
7881 case BUILTIN_IMAG:
7882 {
7883 Expression* arg = this->one_arg();
7884 if (arg == NULL)
7885 return Type::make_error_type();
7886 Type* t = arg->type();
7887 if (t->is_abstract())
7888 t = t->make_non_abstract_type();
7889 t = Builtin_call_expression::real_imag_type(t);
7890 if (t == NULL)
7891 t = Type::make_error_type();
7892 return t;
7893 }
7894
48080209 7895 case BUILTIN_COMPLEX:
e440a328 7896 {
7897 const Expression_list* args = this->args();
7898 if (args == NULL || args->size() != 2)
7899 return Type::make_error_type();
7900 Type* t = args->front()->type();
7901 if (t->is_abstract())
7902 {
7903 t = args->back()->type();
7904 if (t->is_abstract())
7905 t = t->make_non_abstract_type();
7906 }
48080209 7907 t = Builtin_call_expression::complex_type(t);
e440a328 7908 if (t == NULL)
7909 t = Type::make_error_type();
7910 return t;
7911 }
7912 }
7913}
7914
7915// Determine the type.
7916
7917void
7918Builtin_call_expression::do_determine_type(const Type_context* context)
7919{
fb94b0ca 7920 if (!this->determining_types())
7921 return;
7922
e440a328 7923 this->fn()->determine_type_no_context();
7924
7925 const Expression_list* args = this->args();
7926
7927 bool is_print;
7928 Type* arg_type = NULL;
7929 switch (this->code_)
7930 {
7931 case BUILTIN_PRINT:
7932 case BUILTIN_PRINTLN:
7933 // Do not force a large integer constant to "int".
7934 is_print = true;
7935 break;
7936
7937 case BUILTIN_REAL:
7938 case BUILTIN_IMAG:
48080209 7939 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 7940 if (arg_type == NULL)
7941 arg_type = Type::lookup_complex_type("complex128");
e440a328 7942 is_print = false;
7943 break;
7944
48080209 7945 case BUILTIN_COMPLEX:
e440a328 7946 {
48080209 7947 // For the complex function the type of one operand can
e440a328 7948 // determine the type of the other, as in a binary expression.
7949 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 7950 if (arg_type == NULL)
7951 arg_type = Type::lookup_float_type("float64");
e440a328 7952 if (args != NULL && args->size() == 2)
7953 {
7954 Type* t1 = args->front()->type();
c849bb59 7955 Type* t2 = args->back()->type();
e440a328 7956 if (!t1->is_abstract())
7957 arg_type = t1;
7958 else if (!t2->is_abstract())
7959 arg_type = t2;
7960 }
7961 is_print = false;
7962 }
7963 break;
7964
7965 default:
7966 is_print = false;
7967 break;
7968 }
7969
7970 if (args != NULL)
7971 {
7972 for (Expression_list::const_iterator pa = args->begin();
7973 pa != args->end();
7974 ++pa)
7975 {
7976 Type_context subcontext;
7977 subcontext.type = arg_type;
7978
7979 if (is_print)
7980 {
7981 // We want to print large constants, we so can't just
7982 // use the appropriate nonabstract type. Use uint64 for
7983 // an integer if we know it is nonnegative, otherwise
7984 // use int64 for a integer, otherwise use float64 for a
7985 // float or complex128 for a complex.
7986 Type* want_type = NULL;
7987 Type* atype = (*pa)->type();
7988 if (atype->is_abstract())
7989 {
7990 if (atype->integer_type() != NULL)
7991 {
0c77715b 7992 Numeric_constant nc;
7993 if (this->numeric_constant_value(&nc))
7994 {
7995 mpz_t val;
7996 if (nc.to_int(&val))
7997 {
7998 if (mpz_sgn(val) >= 0)
7999 want_type = Type::lookup_integer_type("uint64");
8000 mpz_clear(val);
8001 }
8002 }
8003 if (want_type == NULL)
e440a328 8004 want_type = Type::lookup_integer_type("int64");
e440a328 8005 }
8006 else if (atype->float_type() != NULL)
8007 want_type = Type::lookup_float_type("float64");
8008 else if (atype->complex_type() != NULL)
8009 want_type = Type::lookup_complex_type("complex128");
8010 else if (atype->is_abstract_string_type())
8011 want_type = Type::lookup_string_type();
8012 else if (atype->is_abstract_boolean_type())
8013 want_type = Type::lookup_bool_type();
8014 else
c3e6f413 8015 go_unreachable();
e440a328 8016 subcontext.type = want_type;
8017 }
8018 }
8019
8020 (*pa)->determine_type(&subcontext);
8021 }
8022 }
8023}
8024
8025// If there is exactly one argument, return true. Otherwise give an
8026// error message and return false.
8027
8028bool
8029Builtin_call_expression::check_one_arg()
8030{
8031 const Expression_list* args = this->args();
8032 if (args == NULL || args->size() < 1)
8033 {
8034 this->report_error(_("not enough arguments"));
8035 return false;
8036 }
8037 else if (args->size() > 1)
8038 {
8039 this->report_error(_("too many arguments"));
8040 return false;
8041 }
8042 if (args->front()->is_error_expression()
5c13bd80 8043 || args->front()->type()->is_error())
e440a328 8044 {
8045 this->set_is_error();
8046 return false;
8047 }
8048 return true;
8049}
8050
8051// Check argument types for a builtin function.
8052
8053void
8054Builtin_call_expression::do_check_types(Gogo*)
8055{
375646ea 8056 if (this->is_error_expression())
8057 return;
e440a328 8058 switch (this->code_)
8059 {
8060 case BUILTIN_INVALID:
8061 case BUILTIN_NEW:
8062 case BUILTIN_MAKE:
cd238b8d 8063 case BUILTIN_DELETE:
e440a328 8064 return;
8065
8066 case BUILTIN_LEN:
8067 case BUILTIN_CAP:
8068 {
8069 // The single argument may be either a string or an array or a
8070 // map or a channel, or a pointer to a closed array.
8071 if (this->check_one_arg())
8072 {
8073 Type* arg_type = this->one_arg()->type();
8074 if (arg_type->points_to() != NULL
8075 && arg_type->points_to()->array_type() != NULL
411eb89e 8076 && !arg_type->points_to()->is_slice_type())
e440a328 8077 arg_type = arg_type->points_to();
8078 if (this->code_ == BUILTIN_CAP)
8079 {
5c13bd80 8080 if (!arg_type->is_error()
e440a328 8081 && arg_type->array_type() == NULL
8082 && arg_type->channel_type() == NULL)
8083 this->report_error(_("argument must be array or slice "
8084 "or channel"));
8085 }
8086 else
8087 {
5c13bd80 8088 if (!arg_type->is_error()
e440a328 8089 && !arg_type->is_string_type()
8090 && arg_type->array_type() == NULL
8091 && arg_type->map_type() == NULL
8092 && arg_type->channel_type() == NULL)
8093 this->report_error(_("argument must be string or "
8094 "array or slice or map or channel"));
8095 }
8096 }
8097 }
8098 break;
8099
8100 case BUILTIN_PRINT:
8101 case BUILTIN_PRINTLN:
8102 {
8103 const Expression_list* args = this->args();
8104 if (args == NULL)
8105 {
8106 if (this->code_ == BUILTIN_PRINT)
8107 warning_at(this->location(), 0,
8108 "no arguments for builtin function %<%s%>",
8109 (this->code_ == BUILTIN_PRINT
8110 ? "print"
8111 : "println"));
8112 }
8113 else
8114 {
8115 for (Expression_list::const_iterator p = args->begin();
8116 p != args->end();
8117 ++p)
8118 {
8119 Type* type = (*p)->type();
5c13bd80 8120 if (type->is_error()
e440a328 8121 || type->is_string_type()
8122 || type->integer_type() != NULL
8123 || type->float_type() != NULL
8124 || type->complex_type() != NULL
8125 || type->is_boolean_type()
8126 || type->points_to() != NULL
8127 || type->interface_type() != NULL
8128 || type->channel_type() != NULL
8129 || type->map_type() != NULL
8130 || type->function_type() != NULL
411eb89e 8131 || type->is_slice_type())
e440a328 8132 ;
acf8e158 8133 else if ((*p)->is_type_expression())
8134 {
8135 // If this is a type expression it's going to give
8136 // an error anyhow, so we don't need one here.
8137 }
e440a328 8138 else
8139 this->report_error(_("unsupported argument type to "
8140 "builtin function"));
8141 }
8142 }
8143 }
8144 break;
8145
8146 case BUILTIN_CLOSE:
e440a328 8147 if (this->check_one_arg())
8148 {
8149 if (this->one_arg()->type()->channel_type() == NULL)
8150 this->report_error(_("argument must be channel"));
5202d986 8151 else if (!this->one_arg()->type()->channel_type()->may_send())
8152 this->report_error(_("cannot close receive-only channel"));
e440a328 8153 }
8154 break;
8155
8156 case BUILTIN_PANIC:
8157 case BUILTIN_SIZEOF:
8158 case BUILTIN_ALIGNOF:
8159 this->check_one_arg();
8160 break;
8161
8162 case BUILTIN_RECOVER:
8163 if (this->args() != NULL && !this->args()->empty())
8164 this->report_error(_("too many arguments"));
8165 break;
8166
8167 case BUILTIN_OFFSETOF:
8168 if (this->check_one_arg())
8169 {
8170 Expression* arg = this->one_arg();
8171 if (arg->field_reference_expression() == NULL)
8172 this->report_error(_("argument must be a field reference"));
8173 }
8174 break;
8175
8176 case BUILTIN_COPY:
8177 {
8178 const Expression_list* args = this->args();
8179 if (args == NULL || args->size() < 2)
8180 {
8181 this->report_error(_("not enough arguments"));
8182 break;
8183 }
8184 else if (args->size() > 2)
8185 {
8186 this->report_error(_("too many arguments"));
8187 break;
8188 }
8189 Type* arg1_type = args->front()->type();
8190 Type* arg2_type = args->back()->type();
5c13bd80 8191 if (arg1_type->is_error() || arg2_type->is_error())
e440a328 8192 break;
8193
8194 Type* e1;
411eb89e 8195 if (arg1_type->is_slice_type())
e440a328 8196 e1 = arg1_type->array_type()->element_type();
8197 else
8198 {
8199 this->report_error(_("left argument must be a slice"));
8200 break;
8201 }
8202
411eb89e 8203 if (arg2_type->is_slice_type())
60963afd 8204 {
8205 Type* e2 = arg2_type->array_type()->element_type();
8206 if (!Type::are_identical(e1, e2, true, NULL))
8207 this->report_error(_("element types must be the same"));
8208 }
e440a328 8209 else if (arg2_type->is_string_type())
e440a328 8210 {
60963afd 8211 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8212 this->report_error(_("first argument must be []byte"));
e440a328 8213 }
60963afd 8214 else
8215 this->report_error(_("second argument must be slice or string"));
e440a328 8216 }
8217 break;
8218
8219 case BUILTIN_APPEND:
8220 {
8221 const Expression_list* args = this->args();
b0d311a1 8222 if (args == NULL || args->size() < 2)
e440a328 8223 {
8224 this->report_error(_("not enough arguments"));
8225 break;
8226 }
0b7755ec 8227 if (args->size() > 2)
8228 {
8229 this->report_error(_("too many arguments"));
8230 break;
8231 }
cd238b8d 8232 if (args->front()->type()->is_error()
8233 || args->back()->type()->is_error())
8234 break;
8235
8236 Array_type* at = args->front()->type()->array_type();
8237 Type* e = at->element_type();
4fd4fcf4 8238
8239 // The language permits appending a string to a []byte, as a
8240 // special case.
8241 if (args->back()->type()->is_string_type())
8242 {
60963afd 8243 if (e->integer_type() != NULL && e->integer_type()->is_byte())
4fd4fcf4 8244 break;
8245 }
8246
19fd40c3 8247 // The language says that the second argument must be
8248 // assignable to a slice of the element type of the first
8249 // argument. We already know the first argument is a slice
8250 // type.
cd238b8d 8251 Type* arg2_type = Type::make_array_type(e, NULL);
e440a328 8252 std::string reason;
19fd40c3 8253 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
e440a328 8254 {
8255 if (reason.empty())
19fd40c3 8256 this->report_error(_("argument 2 has invalid type"));
e440a328 8257 else
8258 {
19fd40c3 8259 error_at(this->location(), "argument 2 has invalid type (%s)",
e440a328 8260 reason.c_str());
8261 this->set_is_error();
8262 }
8263 }
8264 break;
8265 }
8266
8267 case BUILTIN_REAL:
8268 case BUILTIN_IMAG:
8269 if (this->check_one_arg())
8270 {
8271 if (this->one_arg()->type()->complex_type() == NULL)
8272 this->report_error(_("argument must have complex type"));
8273 }
8274 break;
8275
48080209 8276 case BUILTIN_COMPLEX:
e440a328 8277 {
8278 const Expression_list* args = this->args();
8279 if (args == NULL || args->size() < 2)
8280 this->report_error(_("not enough arguments"));
8281 else if (args->size() > 2)
8282 this->report_error(_("too many arguments"));
8283 else if (args->front()->is_error_expression()
5c13bd80 8284 || args->front()->type()->is_error()
e440a328 8285 || args->back()->is_error_expression()
5c13bd80 8286 || args->back()->type()->is_error())
e440a328 8287 this->set_is_error();
8288 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8289 args->back()->type(), true, NULL))
48080209 8290 this->report_error(_("complex arguments must have identical types"));
e440a328 8291 else if (args->front()->type()->float_type() == NULL)
48080209 8292 this->report_error(_("complex arguments must have "
e440a328 8293 "floating-point type"));
8294 }
8295 break;
8296
8297 default:
c3e6f413 8298 go_unreachable();
e440a328 8299 }
8300}
8301
8302// Return the tree for a builtin function.
8303
8304tree
8305Builtin_call_expression::do_get_tree(Translate_context* context)
8306{
8307 Gogo* gogo = context->gogo();
b13c66cd 8308 Location location = this->location();
e440a328 8309 switch (this->code_)
8310 {
8311 case BUILTIN_INVALID:
8312 case BUILTIN_NEW:
8313 case BUILTIN_MAKE:
c3e6f413 8314 go_unreachable();
e440a328 8315
8316 case BUILTIN_LEN:
8317 case BUILTIN_CAP:
8318 {
8319 const Expression_list* args = this->args();
c484d925 8320 go_assert(args != NULL && args->size() == 1);
2c809f8f 8321 Expression* arg = args->front();
e440a328 8322 Type* arg_type = arg->type();
0f914071 8323
8324 if (this->seen_)
8325 {
c484d925 8326 go_assert(saw_errors());
0f914071 8327 return error_mark_node;
8328 }
8329 this->seen_ = true;
0f914071 8330 this->seen_ = false;
e440a328 8331 if (arg_type->points_to() != NULL)
8332 {
8333 arg_type = arg_type->points_to();
c484d925 8334 go_assert(arg_type->array_type() != NULL
411eb89e 8335 && !arg_type->is_slice_type());
2c809f8f 8336 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8337 }
8338
1b1f2abf 8339 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8340 Expression* val;
e440a328 8341 if (this->code_ == BUILTIN_LEN)
8342 {
8343 if (arg_type->is_string_type())
2c809f8f 8344 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8345 location);
e440a328 8346 else if (arg_type->array_type() != NULL)
0f914071 8347 {
8348 if (this->seen_)
8349 {
c484d925 8350 go_assert(saw_errors());
0f914071 8351 return error_mark_node;
8352 }
8353 this->seen_ = true;
2c809f8f 8354 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8355 this->seen_ = false;
8356 }
e440a328 8357 else if (arg_type->map_type() != NULL)
2c809f8f 8358 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
e440a328 8359 else if (arg_type->channel_type() != NULL)
2c809f8f 8360 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
e440a328 8361 else
c3e6f413 8362 go_unreachable();
e440a328 8363 }
8364 else
8365 {
8366 if (arg_type->array_type() != NULL)
0f914071 8367 {
8368 if (this->seen_)
8369 {
c484d925 8370 go_assert(saw_errors());
0f914071 8371 return error_mark_node;
8372 }
8373 this->seen_ = true;
2c809f8f 8374 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8375 this->seen_ = false;
8376 }
e440a328 8377 else if (arg_type->channel_type() != NULL)
2c809f8f 8378 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
e440a328 8379 else
c3e6f413 8380 go_unreachable();
e440a328 8381 }
8382
2c809f8f 8383 return Expression::make_cast(int_type, val,
8384 location)->get_tree(context);
e440a328 8385 }
8386
8387 case BUILTIN_PRINT:
8388 case BUILTIN_PRINTLN:
8389 {
8390 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
2c809f8f 8391 Expression* print_stmts = NULL;
e440a328 8392
8393 const Expression_list* call_args = this->args();
8394 if (call_args != NULL)
8395 {
8396 for (Expression_list::const_iterator p = call_args->begin();
8397 p != call_args->end();
8398 ++p)
8399 {
8400 if (is_ln && p != call_args->begin())
8401 {
2c809f8f 8402 Expression* print_space =
8403 Runtime::make_call(Runtime::PRINT_SPACE,
8404 this->location(), 0);
e440a328 8405
2c809f8f 8406 print_stmts =
8407 Expression::make_compound(print_stmts, print_space,
8408 location);
8409 }
e440a328 8410
2c809f8f 8411 Expression* arg = *p;
8412 Type* type = arg->type();
8413 Runtime::Function code;
e440a328 8414 if (type->is_string_type())
2c809f8f 8415 code = Runtime::PRINT_STRING;
e440a328 8416 else if (type->integer_type() != NULL
8417 && type->integer_type()->is_unsigned())
8418 {
e440a328 8419 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8420 arg = Expression::make_cast(itype, arg, location);
8421 code = Runtime::PRINT_UINT64;
e440a328 8422 }
8423 else if (type->integer_type() != NULL)
8424 {
e440a328 8425 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8426 arg = Expression::make_cast(itype, arg, location);
8427 code = Runtime::PRINT_INT64;
e440a328 8428 }
8429 else if (type->float_type() != NULL)
8430 {
2c809f8f 8431 Type* dtype = Type::lookup_float_type("float64");
8432 arg = Expression::make_cast(dtype, arg, location);
8433 code = Runtime::PRINT_DOUBLE;
e440a328 8434 }
8435 else if (type->complex_type() != NULL)
8436 {
2c809f8f 8437 Type* ctype = Type::lookup_complex_type("complex128");
8438 arg = Expression::make_cast(ctype, arg, location);
8439 code = Runtime::PRINT_COMPLEX;
e440a328 8440 }
8441 else if (type->is_boolean_type())
2c809f8f 8442 code = Runtime::PRINT_BOOL;
e440a328 8443 else if (type->points_to() != NULL
8444 || type->channel_type() != NULL
8445 || type->map_type() != NULL
8446 || type->function_type() != NULL)
8447 {
2c809f8f 8448 arg = Expression::make_cast(type, arg, location);
8449 code = Runtime::PRINT_POINTER;
e440a328 8450 }
8451 else if (type->interface_type() != NULL)
8452 {
8453 if (type->interface_type()->is_empty())
2c809f8f 8454 code = Runtime::PRINT_EMPTY_INTERFACE;
e440a328 8455 else
2c809f8f 8456 code = Runtime::PRINT_INTERFACE;
e440a328 8457 }
411eb89e 8458 else if (type->is_slice_type())
2c809f8f 8459 code = Runtime::PRINT_SLICE;
e440a328 8460 else
cd238b8d 8461 {
8462 go_assert(saw_errors());
8463 return error_mark_node;
8464 }
e440a328 8465
2c809f8f 8466 Expression* call = Runtime::make_call(code, location, 1, arg);
8467 if (print_stmts == NULL)
8468 print_stmts = call;
8469 else
8470 print_stmts = Expression::make_compound(print_stmts, call,
8471 location);
e440a328 8472 }
8473 }
8474
8475 if (is_ln)
8476 {
2c809f8f 8477 Expression* print_nl =
8478 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8479 if (print_stmts == NULL)
8480 print_stmts = print_nl;
8481 else
8482 print_stmts = Expression::make_compound(print_stmts, print_nl,
8483 location);
e440a328 8484 }
8485
2c809f8f 8486 return print_stmts->get_tree(context);
e440a328 8487 }
8488
8489 case BUILTIN_PANIC:
8490 {
8491 const Expression_list* args = this->args();
c484d925 8492 go_assert(args != NULL && args->size() == 1);
e440a328 8493 Expression* arg = args->front();
b13c66cd 8494 Type *empty =
823c7e3d 8495 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8496 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8497
8498 Expression* panic =
8499 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8500 return panic->get_tree(context);
e440a328 8501 }
8502
8503 case BUILTIN_RECOVER:
8504 {
8505 // The argument is set when building recover thunks. It's a
8506 // boolean value which is true if we can recover a value now.
8507 const Expression_list* args = this->args();
c484d925 8508 go_assert(args != NULL && args->size() == 1);
e440a328 8509 Expression* arg = args->front();
b13c66cd 8510 Type *empty =
823c7e3d 8511 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8512
e440a328 8513 Expression* nil = Expression::make_nil(location);
2c809f8f 8514 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8515
8516 // We need to handle a deferred call to recover specially,
8517 // because it changes whether it can recover a panic or not.
8518 // See test7 in test/recover1.go.
2c809f8f 8519 Expression* recover = Runtime::make_call((this->is_deferred()
8520 ? Runtime::DEFERRED_RECOVER
8521 : Runtime::RECOVER),
8522 location, 0);
8523 Expression* cond =
8524 Expression::make_conditional(arg, recover, nil, location);
8525 return cond->get_tree(context);
e440a328 8526 }
8527
8528 case BUILTIN_CLOSE:
e440a328 8529 {
8530 const Expression_list* args = this->args();
c484d925 8531 go_assert(args != NULL && args->size() == 1);
e440a328 8532 Expression* arg = args->front();
2c809f8f 8533 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8534 1, arg);
8535 return close->get_tree(context);
e440a328 8536 }
8537
8538 case BUILTIN_SIZEOF:
8539 case BUILTIN_OFFSETOF:
8540 case BUILTIN_ALIGNOF:
8541 {
0c77715b 8542 Numeric_constant nc;
8543 unsigned long val;
8544 if (!this->numeric_constant_value(&nc)
8545 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8546 {
c484d925 8547 go_assert(saw_errors());
7f1d9abd 8548 return error_mark_node;
8549 }
7ba86326 8550 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 8551 mpz_t ival;
8552 nc.get_int(&ival);
8553 Expression* int_cst =
8554 Expression::make_integer(&ival, uintptr_type, location);
8555 mpz_clear(ival);
8556 return int_cst->get_tree(context);
e440a328 8557 }
8558
8559 case BUILTIN_COPY:
8560 {
8561 const Expression_list* args = this->args();
c484d925 8562 go_assert(args != NULL && args->size() == 2);
e440a328 8563 Expression* arg1 = args->front();
8564 Expression* arg2 = args->back();
8565
e440a328 8566 Type* arg1_type = arg1->type();
8567 Array_type* at = arg1_type->array_type();
35a54f17 8568 go_assert(arg1->is_variable());
2c809f8f 8569 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8570 Expression* arg1_len = at->get_length(gogo, arg1);
e440a328 8571
8572 Type* arg2_type = arg2->type();
2c809f8f 8573 go_assert(arg2->is_variable());
8574 Expression* arg2_val;
8575 Expression* arg2_len;
411eb89e 8576 if (arg2_type->is_slice_type())
e440a328 8577 {
8578 at = arg2_type->array_type();
2c809f8f 8579 arg2_val = at->get_value_pointer(gogo, arg2);
8580 arg2_len = at->get_length(gogo, arg2);
e440a328 8581 }
8582 else
8583 {
2c809f8f 8584 go_assert(arg2->is_variable());
8585 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8586 location);
8587 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8588 location);
e440a328 8589 }
2c809f8f 8590 Expression* cond =
8591 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8592 Expression* length =
8593 Expression::make_conditional(cond, arg1_len, arg2_len, location);
e440a328 8594
8595 Type* element_type = at->element_type();
9f0e0513 8596 Btype* element_btype = element_type->get_backend(gogo);
e440a328 8597
2c809f8f 8598 mpz_t size;
8599 size_t element_size = gogo->backend()->type_size(element_btype);
8600 mpz_init_set_ui(size, element_size);
8601 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8602 mpz_clear(size);
8603
8604 Expression* bytecount =
8605 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8606 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8607 arg1_val, arg2_val, bytecount);
8608
8609 Expression* compound = Expression::make_compound(copy, length, location);
8610 return compound->get_tree(context);
e440a328 8611 }
8612
8613 case BUILTIN_APPEND:
8614 {
8615 const Expression_list* args = this->args();
c484d925 8616 go_assert(args != NULL && args->size() == 2);
e440a328 8617 Expression* arg1 = args->front();
8618 Expression* arg2 = args->back();
8619
9d44fbe3 8620 Array_type* at = arg1->type()->array_type();
4fd4fcf4 8621 Type* element_type = at->element_type()->forwarded();
9d44fbe3 8622
2c809f8f 8623 go_assert(arg2->is_variable());
8624 Expression* arg2_val;
8625 Expression* arg2_len;
8626 mpz_t size;
4fd4fcf4 8627 if (arg2->type()->is_string_type()
60963afd 8628 && element_type->integer_type() != NULL
8629 && element_type->integer_type()->is_byte())
4fd4fcf4 8630 {
2c809f8f 8631 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8632 location);
8633 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8634 location);
8635 mpz_init_set_ui(size, 1UL);
4fd4fcf4 8636 }
8637 else
8638 {
2c809f8f 8639 arg2_val = at->get_value_pointer(gogo, arg2);
8640 arg2_len = at->get_length(gogo, arg2);
35a54f17 8641 Btype* element_btype = element_type->get_backend(gogo);
2c809f8f 8642 size_t element_size = gogo->backend()->type_size(element_btype);
8643 mpz_init_set_ui(size, element_size);
4fd4fcf4 8644 }
2c809f8f 8645 Expression* element_size =
8646 Expression::make_integer(&size, NULL, location);
8647 mpz_clear(size);
8648
8649 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8650 arg1, arg2_val, arg2_len,
8651 element_size);
8652 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8653 return append->get_tree(context);
e440a328 8654 }
8655
8656 case BUILTIN_REAL:
8657 case BUILTIN_IMAG:
8658 {
8659 const Expression_list* args = this->args();
c484d925 8660 go_assert(args != NULL && args->size() == 1);
e440a328 8661 Expression* arg = args->front();
2c809f8f 8662
8663 Bexpression* ret;
8664 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8665 if (this->code_ == BUILTIN_REAL)
8666 ret = gogo->backend()->real_part_expression(bcomplex, location);
8667 else
8668 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8669 return expr_to_tree(ret);
e440a328 8670 }
8671
48080209 8672 case BUILTIN_COMPLEX:
e440a328 8673 {
8674 const Expression_list* args = this->args();
c484d925 8675 go_assert(args != NULL && args->size() == 2);
2c809f8f 8676 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8677 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8678 Bexpression* ret =
8679 gogo->backend()->complex_expression(breal, bimag, location);
8680 return expr_to_tree(ret);
e440a328 8681 }
8682
8683 default:
c3e6f413 8684 go_unreachable();
e440a328 8685 }
8686}
8687
8688// We have to support exporting a builtin call expression, because
8689// code can set a constant to the result of a builtin expression.
8690
8691void
8692Builtin_call_expression::do_export(Export* exp) const
8693{
0c77715b 8694 Numeric_constant nc;
8695 if (!this->numeric_constant_value(&nc))
8696 {
8697 error_at(this->location(), "value is not constant");
8698 return;
8699 }
e440a328 8700
0c77715b 8701 if (nc.is_int())
e440a328 8702 {
0c77715b 8703 mpz_t val;
8704 nc.get_int(&val);
e440a328 8705 Integer_expression::export_integer(exp, val);
0c77715b 8706 mpz_clear(val);
e440a328 8707 }
0c77715b 8708 else if (nc.is_float())
e440a328 8709 {
8710 mpfr_t fval;
0c77715b 8711 nc.get_float(&fval);
8712 Float_expression::export_float(exp, fval);
e440a328 8713 mpfr_clear(fval);
8714 }
0c77715b 8715 else if (nc.is_complex())
e440a328 8716 {
8717 mpfr_t real;
8718 mpfr_t imag;
0c77715b 8719 Complex_expression::export_complex(exp, real, imag);
e440a328 8720 mpfr_clear(real);
8721 mpfr_clear(imag);
8722 }
0c77715b 8723 else
8724 go_unreachable();
e440a328 8725
8726 // A trailing space lets us reliably identify the end of the number.
8727 exp->write_c_string(" ");
8728}
8729
8730// Class Call_expression.
8731
8381eda7 8732// A Go function can be viewed in a couple of different ways. The
8733// code of a Go function becomes a backend function with parameters
8734// whose types are simply the backend representation of the Go types.
8735// If there are multiple results, they are returned as a backend
8736// struct.
8737
8738// However, when Go code refers to a function other than simply
8739// calling it, the backend type of that function is actually a struct.
8740// The first field of the struct points to the Go function code
8741// (sometimes a wrapper as described below). The remaining fields
8742// hold addresses of closed-over variables. This struct is called a
8743// closure.
8744
8745// There are a few cases to consider.
8746
8747// A direct function call of a known function in package scope. In
8748// this case there are no closed-over variables, and we know the name
8749// of the function code. We can simply produce a backend call to the
8750// function directly, and not worry about the closure.
8751
8752// A direct function call of a known function literal. In this case
8753// we know the function code and we know the closure. We generate the
8754// function code such that it expects an additional final argument of
8755// the closure type. We pass the closure as the last argument, after
8756// the other arguments.
8757
8758// An indirect function call. In this case we have a closure. We
8759// load the pointer to the function code from the first field of the
8760// closure. We pass the address of the closure as the last argument.
8761
8762// A call to a method of an interface. Type methods are always at
8763// package scope, so we call the function directly, and don't worry
8764// about the closure.
8765
8766// This means that for a function at package scope we have two cases.
8767// One is the direct call, which has no closure. The other is the
8768// indirect call, which does have a closure. We can't simply ignore
8769// the closure, even though it is the last argument, because that will
8770// fail on targets where the function pops its arguments. So when
8771// generating a closure for a package-scope function we set the
8772// function code pointer in the closure to point to a wrapper
8773// function. This wrapper function accepts a final argument that
8774// points to the closure, ignores it, and calls the real function as a
8775// direct function call. This wrapper will normally be efficient, and
8776// can often simply be a tail call to the real function.
8777
8778// We don't use GCC's static chain pointer because 1) we don't need
8779// it; 2) GCC only permits using a static chain to call a known
8780// function, so we can't use it for an indirect call anyhow. Since we
8781// can't use it for an indirect call, we may as well not worry about
8782// using it for a direct call either.
8783
8784// We pass the closure last rather than first because it means that
8785// the function wrapper we put into a closure for a package-scope
8786// function can normally just be a tail call to the real function.
8787
8788// For method expressions we generate a wrapper that loads the
8789// receiver from the closure and then calls the method. This
8790// unfortunately forces reshuffling the arguments, since there is a
8791// new first argument, but we can't avoid reshuffling either for
8792// method expressions or for indirect calls of package-scope
8793// functions, and since the latter are more common we reshuffle for
8794// method expressions.
8795
8796// Note that the Go code retains the Go types. The extra final
8797// argument only appears when we convert to the backend
8798// representation.
8799
e440a328 8800// Traversal.
8801
8802int
8803Call_expression::do_traverse(Traverse* traverse)
8804{
8805 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8806 return TRAVERSE_EXIT;
8807 if (this->args_ != NULL)
8808 {
8809 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8810 return TRAVERSE_EXIT;
8811 }
8812 return TRAVERSE_CONTINUE;
8813}
8814
8815// Lower a call statement.
8816
8817Expression*
ceeb4318 8818Call_expression::do_lower(Gogo* gogo, Named_object* function,
8819 Statement_inserter* inserter, int)
e440a328 8820{
b13c66cd 8821 Location loc = this->location();
09ea332d 8822
ceeb4318 8823 // A type cast can look like a function call.
e440a328 8824 if (this->fn_->is_type_expression()
8825 && this->args_ != NULL
8826 && this->args_->size() == 1)
8827 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 8828 loc);
e440a328 8829
88f06749 8830 // Because do_type will return an error type and thus prevent future
8831 // errors, check for that case now to ensure that the error gets
8832 // reported.
37448b10 8833 Function_type* fntype = this->get_function_type();
8834 if (fntype == NULL)
88f06749 8835 {
8836 if (!this->fn_->type()->is_error())
8837 this->report_error(_("expected function"));
8838 return Expression::make_error(loc);
8839 }
8840
e440a328 8841 // Handle an argument which is a call to a function which returns
8842 // multiple results.
8843 if (this->args_ != NULL
8844 && this->args_->size() == 1
37448b10 8845 && this->args_->front()->call_expression() != NULL)
e440a328 8846 {
e440a328 8847 size_t rc = this->args_->front()->call_expression()->result_count();
8848 if (rc > 1
37448b10 8849 && ((fntype->parameters() != NULL
8850 && (fntype->parameters()->size() == rc
8851 || (fntype->is_varargs()
8852 && fntype->parameters()->size() - 1 <= rc)))
8853 || fntype->is_builtin()))
e440a328 8854 {
8855 Call_expression* call = this->args_->front()->call_expression();
8856 Expression_list* args = new Expression_list;
8857 for (size_t i = 0; i < rc; ++i)
8858 args->push_back(Expression::make_call_result(call, i));
8859 // We can't return a new call expression here, because this
42535814 8860 // one may be referenced by Call_result expressions. We
8861 // also can't delete the old arguments, because we may still
8862 // traverse them somewhere up the call stack. FIXME.
e440a328 8863 this->args_ = args;
8864 }
8865 }
8866
37448b10 8867 // Recognize a call to a builtin function.
8868 if (fntype->is_builtin())
8869 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8870 this->is_varargs_, loc);
8871
ceeb4318 8872 // If this call returns multiple results, create a temporary
8873 // variable for each result.
8874 size_t rc = this->result_count();
8875 if (rc > 1 && this->results_ == NULL)
8876 {
8877 std::vector<Temporary_statement*>* temps =
8878 new std::vector<Temporary_statement*>;
8879 temps->reserve(rc);
37448b10 8880 const Typed_identifier_list* results = fntype->results();
ceeb4318 8881 for (Typed_identifier_list::const_iterator p = results->begin();
8882 p != results->end();
8883 ++p)
8884 {
8885 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 8886 NULL, loc);
ceeb4318 8887 inserter->insert(temp);
8888 temps->push_back(temp);
8889 }
8890 this->results_ = temps;
8891 }
8892
e440a328 8893 // Handle a call to a varargs function by packaging up the extra
8894 // parameters.
37448b10 8895 if (fntype->is_varargs())
e440a328 8896 {
e440a328 8897 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 8898 go_assert(parameters != NULL && !parameters->empty());
e440a328 8899 Type* varargs_type = parameters->back().type();
09ea332d 8900 this->lower_varargs(gogo, function, inserter, varargs_type,
8901 parameters->size());
8902 }
8903
8904 // If this is call to a method, call the method directly passing the
8905 // object as the first parameter.
8906 Bound_method_expression* bme = this->fn_->bound_method_expression();
8907 if (bme != NULL)
8908 {
0afbb937 8909 Named_object* methodfn = bme->function();
09ea332d 8910 Expression* first_arg = bme->first_argument();
8911
8912 // We always pass a pointer when calling a method.
8913 if (first_arg->type()->points_to() == NULL
8914 && !first_arg->type()->is_error())
8915 {
8916 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8917 // We may need to create a temporary variable so that we can
8918 // take the address. We can't do that here because it will
8919 // mess up the order of evaluation.
8920 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8921 ue->set_create_temp();
8922 }
8923
8924 // If we are calling a method which was inherited from an
8925 // embedded struct, and the method did not get a stub, then the
8926 // first type may be wrong.
8927 Type* fatype = bme->first_argument_type();
8928 if (fatype != NULL)
8929 {
8930 if (fatype->points_to() == NULL)
8931 fatype = Type::make_pointer_type(fatype);
8932 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8933 }
8934
8935 Expression_list* new_args = new Expression_list();
8936 new_args->push_back(first_arg);
8937 if (this->args_ != NULL)
8938 {
8939 for (Expression_list::const_iterator p = this->args_->begin();
8940 p != this->args_->end();
8941 ++p)
8942 new_args->push_back(*p);
8943 }
8944
8945 // We have to change in place because this structure may be
8946 // referenced by Call_result_expressions. We can't delete the
8947 // old arguments, because we may be traversing them up in some
8948 // caller. FIXME.
8949 this->args_ = new_args;
0afbb937 8950 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 8951 bme->location());
e440a328 8952 }
8953
8954 return this;
8955}
8956
8957// Lower a call to a varargs function. FUNCTION is the function in
8958// which the call occurs--it's not the function we are calling.
8959// VARARGS_TYPE is the type of the varargs parameter, a slice type.
8960// PARAM_COUNT is the number of parameters of the function we are
8961// calling; the last of these parameters will be the varargs
8962// parameter.
8963
09ea332d 8964void
e440a328 8965Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 8966 Statement_inserter* inserter,
e440a328 8967 Type* varargs_type, size_t param_count)
8968{
8969 if (this->varargs_are_lowered_)
09ea332d 8970 return;
e440a328 8971
b13c66cd 8972 Location loc = this->location();
e440a328 8973
c484d925 8974 go_assert(param_count > 0);
411eb89e 8975 go_assert(varargs_type->is_slice_type());
e440a328 8976
8977 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8978 if (arg_count < param_count - 1)
8979 {
8980 // Not enough arguments; will be caught in check_types.
09ea332d 8981 return;
e440a328 8982 }
8983
8984 Expression_list* old_args = this->args_;
8985 Expression_list* new_args = new Expression_list();
8986 bool push_empty_arg = false;
8987 if (old_args == NULL || old_args->empty())
8988 {
c484d925 8989 go_assert(param_count == 1);
e440a328 8990 push_empty_arg = true;
8991 }
8992 else
8993 {
8994 Expression_list::const_iterator pa;
8995 int i = 1;
8996 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8997 {
8998 if (static_cast<size_t>(i) == param_count)
8999 break;
9000 new_args->push_back(*pa);
9001 }
9002
9003 // We have reached the varargs parameter.
9004
9005 bool issued_error = false;
9006 if (pa == old_args->end())
9007 push_empty_arg = true;
9008 else if (pa + 1 == old_args->end() && this->is_varargs_)
9009 new_args->push_back(*pa);
9010 else if (this->is_varargs_)
9011 {
a6645f74 9012 if ((*pa)->type()->is_slice_type())
9013 this->report_error(_("too many arguments"));
9014 else
9015 {
9016 error_at(this->location(),
9017 _("invalid use of %<...%> with non-slice"));
9018 this->set_is_error();
9019 }
09ea332d 9020 return;
e440a328 9021 }
e440a328 9022 else
9023 {
9024 Type* element_type = varargs_type->array_type()->element_type();
9025 Expression_list* vals = new Expression_list;
9026 for (; pa != old_args->end(); ++pa, ++i)
9027 {
9028 // Check types here so that we get a better message.
9029 Type* patype = (*pa)->type();
b13c66cd 9030 Location paloc = (*pa)->location();
e440a328 9031 if (!this->check_argument_type(i, element_type, patype,
9032 paloc, issued_error))
9033 continue;
9034 vals->push_back(*pa);
9035 }
9036 Expression* val =
9037 Expression::make_slice_composite_literal(varargs_type, vals, loc);
09ea332d 9038 gogo->lower_expression(function, inserter, &val);
e440a328 9039 new_args->push_back(val);
9040 }
9041 }
9042
9043 if (push_empty_arg)
9044 new_args->push_back(Expression::make_nil(loc));
9045
9046 // We can't return a new call expression here, because this one may
6d4c2432 9047 // be referenced by Call_result expressions. FIXME. We can't
9048 // delete OLD_ARGS because we may have both a Call_expression and a
9049 // Builtin_call_expression which refer to them. FIXME.
e440a328 9050 this->args_ = new_args;
9051 this->varargs_are_lowered_ = true;
e440a328 9052}
9053
2c809f8f 9054// Flatten a call with multiple results into a temporary.
9055
9056Expression*
9057Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9058{
9059 size_t rc = this->result_count();
9060 if (rc > 1 && this->call_temp_ == NULL)
9061 {
9062 Struct_field_list* sfl = new Struct_field_list();
9063 Function_type* fntype = this->get_function_type();
9064 const Typed_identifier_list* results = fntype->results();
9065 Location loc = this->location();
9066
9067 int i = 0;
9068 char buf[10];
9069 for (Typed_identifier_list::const_iterator p = results->begin();
9070 p != results->end();
9071 ++p, ++i)
9072 {
9073 snprintf(buf, sizeof buf, "res%d", i);
9074 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9075 }
9076
9077 Struct_type* st = Type::make_struct_type(sfl, loc);
9078 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9079 inserter->insert(this->call_temp_);
9080 }
9081
9082 return this;
9083}
9084
ceeb4318 9085// Get the function type. This can return NULL in error cases.
e440a328 9086
9087Function_type*
9088Call_expression::get_function_type() const
9089{
9090 return this->fn_->type()->function_type();
9091}
9092
9093// Return the number of values which this call will return.
9094
9095size_t
9096Call_expression::result_count() const
9097{
9098 const Function_type* fntype = this->get_function_type();
9099 if (fntype == NULL)
9100 return 0;
9101 if (fntype->results() == NULL)
9102 return 0;
9103 return fntype->results()->size();
9104}
9105
ceeb4318 9106// Return the temporary which holds a result.
9107
9108Temporary_statement*
9109Call_expression::result(size_t i) const
9110{
cd238b8d 9111 if (this->results_ == NULL || this->results_->size() <= i)
9112 {
9113 go_assert(saw_errors());
9114 return NULL;
9115 }
ceeb4318 9116 return (*this->results_)[i];
9117}
9118
e440a328 9119// Return whether this is a call to the predeclared function recover.
9120
9121bool
9122Call_expression::is_recover_call() const
9123{
9124 return this->do_is_recover_call();
9125}
9126
9127// Set the argument to the recover function.
9128
9129void
9130Call_expression::set_recover_arg(Expression* arg)
9131{
9132 this->do_set_recover_arg(arg);
9133}
9134
9135// Virtual functions also implemented by Builtin_call_expression.
9136
9137bool
9138Call_expression::do_is_recover_call() const
9139{
9140 return false;
9141}
9142
9143void
9144Call_expression::do_set_recover_arg(Expression*)
9145{
c3e6f413 9146 go_unreachable();
e440a328 9147}
9148
ceeb4318 9149// We have found an error with this call expression; return true if
9150// we should report it.
9151
9152bool
9153Call_expression::issue_error()
9154{
9155 if (this->issued_error_)
9156 return false;
9157 else
9158 {
9159 this->issued_error_ = true;
9160 return true;
9161 }
9162}
9163
e440a328 9164// Get the type.
9165
9166Type*
9167Call_expression::do_type()
9168{
9169 if (this->type_ != NULL)
9170 return this->type_;
9171
9172 Type* ret;
9173 Function_type* fntype = this->get_function_type();
9174 if (fntype == NULL)
9175 return Type::make_error_type();
9176
9177 const Typed_identifier_list* results = fntype->results();
9178 if (results == NULL)
9179 ret = Type::make_void_type();
9180 else if (results->size() == 1)
9181 ret = results->begin()->type();
9182 else
9183 ret = Type::make_call_multiple_result_type(this);
9184
9185 this->type_ = ret;
9186
9187 return this->type_;
9188}
9189
9190// Determine types for a call expression. We can use the function
9191// parameter types to set the types of the arguments.
9192
9193void
9194Call_expression::do_determine_type(const Type_context*)
9195{
fb94b0ca 9196 if (!this->determining_types())
9197 return;
9198
e440a328 9199 this->fn_->determine_type_no_context();
9200 Function_type* fntype = this->get_function_type();
9201 const Typed_identifier_list* parameters = NULL;
9202 if (fntype != NULL)
9203 parameters = fntype->parameters();
9204 if (this->args_ != NULL)
9205 {
9206 Typed_identifier_list::const_iterator pt;
9207 if (parameters != NULL)
9208 pt = parameters->begin();
09ea332d 9209 bool first = true;
e440a328 9210 for (Expression_list::const_iterator pa = this->args_->begin();
9211 pa != this->args_->end();
9212 ++pa)
9213 {
09ea332d 9214 if (first)
9215 {
9216 first = false;
9217 // If this is a method, the first argument is the
9218 // receiver.
9219 if (fntype != NULL && fntype->is_method())
9220 {
9221 Type* rtype = fntype->receiver()->type();
9222 // The receiver is always passed as a pointer.
9223 if (rtype->points_to() == NULL)
9224 rtype = Type::make_pointer_type(rtype);
9225 Type_context subcontext(rtype, false);
9226 (*pa)->determine_type(&subcontext);
9227 continue;
9228 }
9229 }
9230
e440a328 9231 if (parameters != NULL && pt != parameters->end())
9232 {
9233 Type_context subcontext(pt->type(), false);
9234 (*pa)->determine_type(&subcontext);
9235 ++pt;
9236 }
9237 else
9238 (*pa)->determine_type_no_context();
9239 }
9240 }
9241}
9242
fb94b0ca 9243// Called when determining types for a Call_expression. Return true
9244// if we should go ahead, false if they have already been determined.
9245
9246bool
9247Call_expression::determining_types()
9248{
9249 if (this->types_are_determined_)
9250 return false;
9251 else
9252 {
9253 this->types_are_determined_ = true;
9254 return true;
9255 }
9256}
9257
e440a328 9258// Check types for parameter I.
9259
9260bool
9261Call_expression::check_argument_type(int i, const Type* parameter_type,
9262 const Type* argument_type,
b13c66cd 9263 Location argument_location,
e440a328 9264 bool issued_error)
9265{
9266 std::string reason;
053ee6ca 9267 bool ok;
9268 if (this->are_hidden_fields_ok_)
9269 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9270 &reason);
9271 else
9272 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9273 if (!ok)
e440a328 9274 {
9275 if (!issued_error)
9276 {
9277 if (reason.empty())
9278 error_at(argument_location, "argument %d has incompatible type", i);
9279 else
9280 error_at(argument_location,
9281 "argument %d has incompatible type (%s)",
9282 i, reason.c_str());
9283 }
9284 this->set_is_error();
9285 return false;
9286 }
9287 return true;
9288}
9289
9290// Check types.
9291
9292void
9293Call_expression::do_check_types(Gogo*)
9294{
a6645f74 9295 if (this->classification() == EXPRESSION_ERROR)
9296 return;
9297
e440a328 9298 Function_type* fntype = this->get_function_type();
9299 if (fntype == NULL)
9300 {
5c13bd80 9301 if (!this->fn_->type()->is_error())
e440a328 9302 this->report_error(_("expected function"));
9303 return;
9304 }
9305
09ea332d 9306 bool is_method = fntype->is_method();
9307 if (is_method)
e440a328 9308 {
09ea332d 9309 go_assert(this->args_ != NULL && !this->args_->empty());
9310 Type* rtype = fntype->receiver()->type();
9311 Expression* first_arg = this->args_->front();
9312 // The language permits copying hidden fields for a method
9313 // receiver. We dereference the values since receivers are
9314 // always passed as pointers.
9315 std::string reason;
9316 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9317 first_arg->type()->deref(),
9318 &reason))
e440a328 9319 {
09ea332d 9320 if (reason.empty())
9321 this->report_error(_("incompatible type for receiver"));
9322 else
e440a328 9323 {
09ea332d 9324 error_at(this->location(),
9325 "incompatible type for receiver (%s)",
9326 reason.c_str());
9327 this->set_is_error();
e440a328 9328 }
9329 }
9330 }
9331
9332 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9333 // we don't have to worry about it here unless something is wrong.
9334 if (this->is_varargs_ && !this->varargs_are_lowered_)
9335 {
9336 if (!fntype->is_varargs())
9337 {
9338 error_at(this->location(),
9339 _("invalid use of %<...%> calling non-variadic function"));
9340 this->set_is_error();
9341 return;
9342 }
9343 }
e440a328 9344
9345 const Typed_identifier_list* parameters = fntype->parameters();
9346 if (this->args_ == NULL)
9347 {
9348 if (parameters != NULL && !parameters->empty())
9349 this->report_error(_("not enough arguments"));
9350 }
9351 else if (parameters == NULL)
09ea332d 9352 {
9353 if (!is_method || this->args_->size() > 1)
9354 this->report_error(_("too many arguments"));
9355 }
e440a328 9356 else
9357 {
9358 int i = 0;
09ea332d 9359 Expression_list::const_iterator pa = this->args_->begin();
9360 if (is_method)
9361 ++pa;
9362 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9363 pt != parameters->end();
9364 ++pt, ++pa, ++i)
e440a328 9365 {
09ea332d 9366 if (pa == this->args_->end())
e440a328 9367 {
09ea332d 9368 this->report_error(_("not enough arguments"));
e440a328 9369 return;
9370 }
9371 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9372 (*pa)->location(), false);
9373 }
09ea332d 9374 if (pa != this->args_->end())
9375 this->report_error(_("too many arguments"));
e440a328 9376 }
9377}
9378
9379// Return whether we have to use a temporary variable to ensure that
9380// we evaluate this call expression in order. If the call returns no
ceeb4318 9381// results then it will inevitably be executed last.
e440a328 9382
9383bool
9384Call_expression::do_must_eval_in_order() const
9385{
ceeb4318 9386 return this->result_count() > 0;
e440a328 9387}
9388
e440a328 9389// Get the function and the first argument to use when calling an
9390// interface method.
9391
2387f644 9392Expression*
e440a328 9393Call_expression::interface_method_function(
e440a328 9394 Interface_field_reference_expression* interface_method,
2387f644 9395 Expression** first_arg_ptr)
e440a328 9396{
2387f644 9397 *first_arg_ptr = interface_method->get_underlying_object();
9398 return interface_method->get_function();
e440a328 9399}
9400
9401// Build the call expression.
9402
9403tree
9404Call_expression::do_get_tree(Translate_context* context)
9405{
2c809f8f 9406 if (this->call_ != NULL)
9407 return expr_to_tree(this->call_);
e440a328 9408
9409 Function_type* fntype = this->get_function_type();
9410 if (fntype == NULL)
9411 return error_mark_node;
9412
9413 if (this->fn_->is_error_expression())
9414 return error_mark_node;
9415
9416 Gogo* gogo = context->gogo();
b13c66cd 9417 Location location = this->location();
e440a328 9418
9419 Func_expression* func = this->fn_->func_expression();
e440a328 9420 Interface_field_reference_expression* interface_method =
9421 this->fn_->interface_field_reference_expression();
9422 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9423 const bool is_interface_method = interface_method != NULL;
e440a328 9424
f8bdf81a 9425 bool has_closure_arg;
8381eda7 9426 if (has_closure)
f8bdf81a 9427 has_closure_arg = true;
8381eda7 9428 else if (func != NULL)
f8bdf81a 9429 has_closure_arg = false;
8381eda7 9430 else if (is_interface_method)
f8bdf81a 9431 has_closure_arg = false;
8381eda7 9432 else
f8bdf81a 9433 has_closure_arg = true;
8381eda7 9434
e440a328 9435 int nargs;
2c809f8f 9436 std::vector<Bexpression*> fn_args;
e440a328 9437 if (this->args_ == NULL || this->args_->empty())
9438 {
f8bdf81a 9439 nargs = is_interface_method ? 1 : 0;
2c809f8f 9440 if (nargs > 0)
9441 fn_args.resize(1);
e440a328 9442 }
09ea332d 9443 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9444 {
9445 // Passing a receiver parameter.
9446 go_assert(!is_interface_method
9447 && fntype->is_method()
9448 && this->args_->size() == 1);
f8bdf81a 9449 nargs = 1;
2c809f8f 9450 fn_args.resize(1);
9451 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
09ea332d 9452 }
e440a328 9453 else
9454 {
9455 const Typed_identifier_list* params = fntype->parameters();
e440a328 9456
9457 nargs = this->args_->size();
09ea332d 9458 int i = is_interface_method ? 1 : 0;
e440a328 9459 nargs += i;
2c809f8f 9460 fn_args.resize(nargs);
e440a328 9461
9462 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 9463 Expression_list::const_iterator pe = this->args_->begin();
9464 if (!is_interface_method && fntype->is_method())
9465 {
2c809f8f 9466 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
09ea332d 9467 ++pe;
9468 ++i;
9469 }
9470 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 9471 {
c484d925 9472 go_assert(pp != params->end());
2c809f8f 9473 Expression* arg =
9474 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9475 location);
9476 fn_args[i] = tree_to_expr(arg->get_tree(context));
e440a328 9477 }
c484d925 9478 go_assert(pp == params->end());
f8bdf81a 9479 go_assert(i == nargs);
e440a328 9480 }
9481
2c809f8f 9482 Expression* fn;
9483 Expression* closure = NULL;
8381eda7 9484 if (func != NULL)
9485 {
9486 Named_object* no = func->named_object();
2c809f8f 9487 fn = Expression::make_func_code_reference(no, location);
9488 if (has_closure)
9489 closure = func->closure();
8381eda7 9490 }
09ea332d 9491 else if (!is_interface_method)
8381eda7 9492 {
2c809f8f 9493 closure = this->fn_;
9494
9495 // The backend representation of this function type is a pointer
9496 // to a struct whose first field is the actual function to call.
9497 Type* pfntype =
9498 Type::make_pointer_type(
9499 Type::make_pointer_type(Type::make_void_type()));
9500 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9501 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9502 }
e440a328 9503 else
cf609de4 9504 {
2387f644 9505 Expression* first_arg;
2c809f8f 9506 fn = this->interface_method_function(interface_method, &first_arg);
9507 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
e440a328 9508 }
9509
f8bdf81a 9510 if (!has_closure_arg)
2c809f8f 9511 go_assert(closure == NULL);
f8bdf81a 9512 else
9513 {
9514 // Pass the closure argument by calling the function function
9515 // __go_set_closure. In the order_evaluations pass we have
9516 // ensured that if any parameters contain call expressions, they
9517 // will have been moved out to temporary variables.
2c809f8f 9518 go_assert(closure != NULL);
9519 Expression* set_closure =
9520 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9521 fn = Expression::make_compound(set_closure, fn, location);
f8bdf81a 9522 }
9523
2c809f8f 9524 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
80d1e1a8 9525
9526 // When not calling a named function directly, use a type conversion
9527 // in case the type of the function is a recursive type which refers
9528 // to itself. We don't do this for an interface method because 1)
9529 // an interface method never refers to itself, so we always have a
9530 // function type here; 2) we pass an extra first argument to an
9531 // interface method, so fntype is not correct.
9532 if (func == NULL && !is_interface_method)
9533 {
9534 Btype* bft = fntype->get_backend_fntype(gogo);
9535 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9536 }
9537
2c809f8f 9538 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
e440a328 9539
2c809f8f 9540 if (this->results_ != NULL)
e440a328 9541 {
2c809f8f 9542 go_assert(this->call_temp_ != NULL);
9543 Expression* call_ref =
9544 Expression::make_temporary_reference(this->call_temp_, location);
9545 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9546 Bstatement* assn_stmt =
9547 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 9548
2c809f8f 9549 this->call_ = this->set_results(context, bcall_ref);
e440a328 9550
2c809f8f 9551 Bexpression* set_and_call =
9552 gogo->backend()->compound_expression(assn_stmt, this->call_,
9553 location);
9554 return expr_to_tree(set_and_call);
9555 }
e440a328 9556
2c809f8f 9557 this->call_ = call;
9558 return expr_to_tree(this->call_);
e440a328 9559}
9560
ceeb4318 9561// Set the result variables if this call returns multiple results.
9562
2c809f8f 9563Bexpression*
9564Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 9565{
2c809f8f 9566 Gogo* gogo = context->gogo();
ceeb4318 9567
2c809f8f 9568 Bexpression* results = NULL;
b13c66cd 9569 Location loc = this->location();
2c809f8f 9570
ceeb4318 9571 size_t rc = this->result_count();
2c809f8f 9572 for (size_t i = 0; i < rc; ++i)
ceeb4318 9573 {
ceeb4318 9574 Temporary_statement* temp = this->result(i);
cd238b8d 9575 if (temp == NULL)
9576 {
9577 go_assert(saw_errors());
2c809f8f 9578 return gogo->backend()->error_expression();
cd238b8d 9579 }
ceeb4318 9580 Temporary_reference_expression* ref =
9581 Expression::make_temporary_reference(temp, loc);
9582 ref->set_is_lvalue();
ceeb4318 9583
2c809f8f 9584 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9585 Bexpression* call_result =
9586 gogo->backend()->struct_field_expression(call, i, loc);
9587 Bstatement* assn_stmt =
9588 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 9589
2c809f8f 9590 Bexpression* result =
9591 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 9592
2c809f8f 9593 if (results == NULL)
9594 results = result;
9595 else
9596 {
9597 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9598 results =
9599 gogo->backend()->compound_expression(expr_stmt, results, loc);
9600 }
9601 }
9602 return results;
ceeb4318 9603}
9604
d751bb78 9605// Dump ast representation for a call expressin.
9606
9607void
9608Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9609{
9610 this->fn_->dump_expression(ast_dump_context);
9611 ast_dump_context->ostream() << "(";
9612 if (args_ != NULL)
9613 ast_dump_context->dump_expression_list(this->args_);
9614
9615 ast_dump_context->ostream() << ") ";
9616}
9617
e440a328 9618// Make a call expression.
9619
9620Call_expression*
9621Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 9622 Location location)
e440a328 9623{
9624 return new Call_expression(fn, args, is_varargs, location);
9625}
9626
9627// A single result from a call which returns multiple results.
9628
9629class Call_result_expression : public Expression
9630{
9631 public:
9632 Call_result_expression(Call_expression* call, unsigned int index)
9633 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9634 call_(call), index_(index)
9635 { }
9636
9637 protected:
9638 int
9639 do_traverse(Traverse*);
9640
9641 Type*
9642 do_type();
9643
9644 void
9645 do_determine_type(const Type_context*);
9646
9647 void
9648 do_check_types(Gogo*);
9649
9650 Expression*
9651 do_copy()
9652 {
9653 return new Call_result_expression(this->call_->call_expression(),
9654 this->index_);
9655 }
9656
9657 bool
9658 do_must_eval_in_order() const
9659 { return true; }
9660
9661 tree
9662 do_get_tree(Translate_context*);
9663
d751bb78 9664 void
9665 do_dump_expression(Ast_dump_context*) const;
9666
e440a328 9667 private:
9668 // The underlying call expression.
9669 Expression* call_;
9670 // Which result we want.
9671 unsigned int index_;
9672};
9673
9674// Traverse a call result.
9675
9676int
9677Call_result_expression::do_traverse(Traverse* traverse)
9678{
9679 if (traverse->remember_expression(this->call_))
9680 {
9681 // We have already traversed the call expression.
9682 return TRAVERSE_CONTINUE;
9683 }
9684 return Expression::traverse(&this->call_, traverse);
9685}
9686
9687// Get the type.
9688
9689Type*
9690Call_result_expression::do_type()
9691{
425dd051 9692 if (this->classification() == EXPRESSION_ERROR)
9693 return Type::make_error_type();
9694
e440a328 9695 // THIS->CALL_ can be replaced with a temporary reference due to
9696 // Call_expression::do_must_eval_in_order when there is an error.
9697 Call_expression* ce = this->call_->call_expression();
9698 if (ce == NULL)
5e85f268 9699 {
9700 this->set_is_error();
9701 return Type::make_error_type();
9702 }
e440a328 9703 Function_type* fntype = ce->get_function_type();
9704 if (fntype == NULL)
5e85f268 9705 {
e37658e2 9706 if (ce->issue_error())
99b3f06f 9707 {
9708 if (!ce->fn()->type()->is_error())
9709 this->report_error(_("expected function"));
9710 }
5e85f268 9711 this->set_is_error();
9712 return Type::make_error_type();
9713 }
e440a328 9714 const Typed_identifier_list* results = fntype->results();
ceeb4318 9715 if (results == NULL || results->size() < 2)
7b8d861f 9716 {
ceeb4318 9717 if (ce->issue_error())
9718 this->report_error(_("number of results does not match "
9719 "number of values"));
7b8d861f 9720 return Type::make_error_type();
9721 }
e440a328 9722 Typed_identifier_list::const_iterator pr = results->begin();
9723 for (unsigned int i = 0; i < this->index_; ++i)
9724 {
9725 if (pr == results->end())
425dd051 9726 break;
e440a328 9727 ++pr;
9728 }
9729 if (pr == results->end())
425dd051 9730 {
ceeb4318 9731 if (ce->issue_error())
9732 this->report_error(_("number of results does not match "
9733 "number of values"));
425dd051 9734 return Type::make_error_type();
9735 }
e440a328 9736 return pr->type();
9737}
9738
425dd051 9739// Check the type. Just make sure that we trigger the warning in
9740// do_type.
e440a328 9741
9742void
9743Call_result_expression::do_check_types(Gogo*)
9744{
425dd051 9745 this->type();
e440a328 9746}
9747
9748// Determine the type. We have nothing to do here, but the 0 result
9749// needs to pass down to the caller.
9750
9751void
9752Call_result_expression::do_determine_type(const Type_context*)
9753{
fb94b0ca 9754 this->call_->determine_type_no_context();
e440a328 9755}
9756
ceeb4318 9757// Return the tree. We just refer to the temporary set by the call
9758// expression. We don't do this at lowering time because it makes it
9759// hard to evaluate the call at the right time.
e440a328 9760
9761tree
9762Call_result_expression::do_get_tree(Translate_context* context)
9763{
ceeb4318 9764 Call_expression* ce = this->call_->call_expression();
cd238b8d 9765 if (ce == NULL)
9766 {
9767 go_assert(this->call_->is_error_expression());
9768 return error_mark_node;
9769 }
ceeb4318 9770 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 9771 if (ts == NULL)
9772 {
9773 go_assert(saw_errors());
9774 return error_mark_node;
9775 }
ceeb4318 9776 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9777 return ref->get_tree(context);
e440a328 9778}
9779
d751bb78 9780// Dump ast representation for a call result expression.
9781
9782void
9783Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9784 const
9785{
9786 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9787 // (struct) and the fields are referenced instead.
9788 ast_dump_context->ostream() << this->index_ << "@(";
9789 ast_dump_context->dump_expression(this->call_);
9790 ast_dump_context->ostream() << ")";
9791}
9792
e440a328 9793// Make a reference to a single result of a call which returns
9794// multiple results.
9795
9796Expression*
9797Expression::make_call_result(Call_expression* call, unsigned int index)
9798{
9799 return new Call_result_expression(call, index);
9800}
9801
9802// Class Index_expression.
9803
9804// Traversal.
9805
9806int
9807Index_expression::do_traverse(Traverse* traverse)
9808{
9809 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9810 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9811 || (this->end_ != NULL
acf2b673 9812 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9813 || (this->cap_ != NULL
9814 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 9815 return TRAVERSE_EXIT;
9816 return TRAVERSE_CONTINUE;
9817}
9818
9819// Lower an index expression. This converts the generic index
9820// expression into an array index, a string index, or a map index.
9821
9822Expression*
ceeb4318 9823Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 9824{
b13c66cd 9825 Location location = this->location();
e440a328 9826 Expression* left = this->left_;
9827 Expression* start = this->start_;
9828 Expression* end = this->end_;
acf2b673 9829 Expression* cap = this->cap_;
e440a328 9830
9831 Type* type = left->type();
5c13bd80 9832 if (type->is_error())
e440a328 9833 return Expression::make_error(location);
b0cf7ddd 9834 else if (left->is_type_expression())
9835 {
9836 error_at(location, "attempt to index type expression");
9837 return Expression::make_error(location);
9838 }
e440a328 9839 else if (type->array_type() != NULL)
acf2b673 9840 return Expression::make_array_index(left, start, end, cap, location);
e440a328 9841 else if (type->points_to() != NULL
9842 && type->points_to()->array_type() != NULL
411eb89e 9843 && !type->points_to()->is_slice_type())
e440a328 9844 {
9845 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9846 location);
38092374 9847
9848 // For an ordinary index into the array, the pointer will be
9849 // dereferenced. For a slice it will not--the resulting slice
9850 // will simply reuse the pointer, which is incorrect if that
9851 // pointer is nil.
9852 if (end != NULL || cap != NULL)
9853 deref->issue_nil_check();
9854
acf2b673 9855 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 9856 }
9857 else if (type->is_string_type())
acf2b673 9858 {
9859 if (cap != NULL)
9860 {
9861 error_at(location, "invalid 3-index slice of string");
9862 return Expression::make_error(location);
9863 }
9864 return Expression::make_string_index(left, start, end, location);
9865 }
e440a328 9866 else if (type->map_type() != NULL)
9867 {
acf2b673 9868 if (end != NULL || cap != NULL)
e440a328 9869 {
9870 error_at(location, "invalid slice of map");
9871 return Expression::make_error(location);
9872 }
6d4c2432 9873 Map_index_expression* ret = Expression::make_map_index(left, start,
9874 location);
e440a328 9875 if (this->is_lvalue_)
9876 ret->set_is_lvalue();
9877 return ret;
9878 }
9879 else
9880 {
9881 error_at(location,
9882 "attempt to index object which is not array, string, or map");
9883 return Expression::make_error(location);
9884 }
9885}
9886
acf2b673 9887// Write an indexed expression
9888// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 9889
9890void
9891Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9892 const Expression* expr,
9893 const Expression* start,
acf2b673 9894 const Expression* end,
9895 const Expression* cap)
d751bb78 9896{
9897 expr->dump_expression(ast_dump_context);
9898 ast_dump_context->ostream() << "[";
9899 start->dump_expression(ast_dump_context);
9900 if (end != NULL)
9901 {
9902 ast_dump_context->ostream() << ":";
9903 end->dump_expression(ast_dump_context);
9904 }
acf2b673 9905 if (cap != NULL)
9906 {
9907 ast_dump_context->ostream() << ":";
9908 cap->dump_expression(ast_dump_context);
9909 }
d751bb78 9910 ast_dump_context->ostream() << "]";
9911}
9912
9913// Dump ast representation for an index expression.
9914
9915void
9916Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9917 const
9918{
9919 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 9920 this->start_, this->end_, this->cap_);
d751bb78 9921}
9922
e440a328 9923// Make an index expression.
9924
9925Expression*
9926Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 9927 Expression* cap, Location location)
e440a328 9928{
acf2b673 9929 return new Index_expression(left, start, end, cap, location);
e440a328 9930}
9931
9932// An array index. This is used for both indexing and slicing.
9933
9934class Array_index_expression : public Expression
9935{
9936 public:
9937 Array_index_expression(Expression* array, Expression* start,
acf2b673 9938 Expression* end, Expression* cap, Location location)
e440a328 9939 : Expression(EXPRESSION_ARRAY_INDEX, location),
acf2b673 9940 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
e440a328 9941 { }
9942
9943 protected:
9944 int
9945 do_traverse(Traverse*);
9946
2c809f8f 9947 Expression*
9948 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9949
e440a328 9950 Type*
9951 do_type();
9952
9953 void
9954 do_determine_type(const Type_context*);
9955
9956 void
9957 do_check_types(Gogo*);
9958
9959 Expression*
9960 do_copy()
9961 {
9962 return Expression::make_array_index(this->array_->copy(),
9963 this->start_->copy(),
9964 (this->end_ == NULL
9965 ? NULL
9966 : this->end_->copy()),
acf2b673 9967 (this->cap_ == NULL
9968 ? NULL
9969 : this->cap_->copy()),
e440a328 9970 this->location());
9971 }
9972
baef9f7a 9973 bool
9974 do_must_eval_subexpressions_in_order(int* skip) const
9975 {
9976 *skip = 1;
9977 return true;
9978 }
9979
e440a328 9980 bool
9981 do_is_addressable() const;
9982
9983 void
9984 do_address_taken(bool escapes)
9985 { this->array_->address_taken(escapes); }
9986
56080003 9987 void
9988 do_issue_nil_check()
9989 { this->array_->issue_nil_check(); }
9990
e440a328 9991 tree
9992 do_get_tree(Translate_context*);
9993
d751bb78 9994 void
9995 do_dump_expression(Ast_dump_context*) const;
9996
e440a328 9997 private:
9998 // The array we are getting a value from.
9999 Expression* array_;
10000 // The start or only index.
10001 Expression* start_;
10002 // The end index of a slice. This may be NULL for a simple array
10003 // index, or it may be a nil expression for the length of the array.
10004 Expression* end_;
acf2b673 10005 // The capacity argument of a slice. This may be NULL for an array index or
10006 // slice.
10007 Expression* cap_;
e440a328 10008 // The type of the expression.
10009 Type* type_;
10010};
10011
10012// Array index traversal.
10013
10014int
10015Array_index_expression::do_traverse(Traverse* traverse)
10016{
10017 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10018 return TRAVERSE_EXIT;
10019 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10020 return TRAVERSE_EXIT;
10021 if (this->end_ != NULL)
10022 {
10023 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10024 return TRAVERSE_EXIT;
10025 }
acf2b673 10026 if (this->cap_ != NULL)
10027 {
10028 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10029 return TRAVERSE_EXIT;
10030 }
e440a328 10031 return TRAVERSE_CONTINUE;
10032}
10033
10034// Return the type of an array index.
10035
10036Type*
10037Array_index_expression::do_type()
10038{
10039 if (this->type_ == NULL)
10040 {
10041 Array_type* type = this->array_->type()->array_type();
10042 if (type == NULL)
10043 this->type_ = Type::make_error_type();
10044 else if (this->end_ == NULL)
10045 this->type_ = type->element_type();
411eb89e 10046 else if (type->is_slice_type())
e440a328 10047 {
10048 // A slice of a slice has the same type as the original
10049 // slice.
10050 this->type_ = this->array_->type()->deref();
10051 }
10052 else
10053 {
10054 // A slice of an array is a slice.
10055 this->type_ = Type::make_array_type(type->element_type(), NULL);
10056 }
10057 }
10058 return this->type_;
10059}
10060
10061// Set the type of an array index.
10062
10063void
10064Array_index_expression::do_determine_type(const Type_context*)
10065{
10066 this->array_->determine_type_no_context();
7917ad68 10067 this->start_->determine_type_no_context();
e440a328 10068 if (this->end_ != NULL)
7917ad68 10069 this->end_->determine_type_no_context();
acf2b673 10070 if (this->cap_ != NULL)
10071 this->cap_->determine_type_no_context();
e440a328 10072}
10073
10074// Check types of an array index.
10075
10076void
10077Array_index_expression::do_check_types(Gogo*)
10078{
f6bc81e6 10079 Numeric_constant nc;
10080 unsigned long v;
10081 if (this->start_->type()->integer_type() == NULL
10082 && !this->start_->type()->is_error()
10083 && (!this->start_->numeric_constant_value(&nc)
10084 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10085 this->report_error(_("index must be integer"));
10086 if (this->end_ != NULL
10087 && this->end_->type()->integer_type() == NULL
99b3f06f 10088 && !this->end_->type()->is_error()
10089 && !this->end_->is_nil_expression()
f6bc81e6 10090 && !this->end_->is_error_expression()
10091 && (!this->end_->numeric_constant_value(&nc)
10092 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10093 this->report_error(_("slice end must be integer"));
acf2b673 10094 if (this->cap_ != NULL
10095 && this->cap_->type()->integer_type() == NULL
10096 && !this->cap_->type()->is_error()
10097 && !this->cap_->is_nil_expression()
10098 && !this->cap_->is_error_expression()
10099 && (!this->cap_->numeric_constant_value(&nc)
10100 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10101 this->report_error(_("slice capacity must be integer"));
e440a328 10102
10103 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10104 if (array_type == NULL)
10105 {
c484d925 10106 go_assert(this->array_->type()->is_error());
f9c68f17 10107 return;
10108 }
e440a328 10109
10110 unsigned int int_bits =
10111 Type::lookup_integer_type("int")->integer_type()->bits();
10112
0c77715b 10113 Numeric_constant lvalnc;
e440a328 10114 mpz_t lval;
e440a328 10115 bool lval_valid = (array_type->length() != NULL
0c77715b 10116 && array_type->length()->numeric_constant_value(&lvalnc)
10117 && lvalnc.to_int(&lval));
10118 Numeric_constant inc;
e440a328 10119 mpz_t ival;
0bd5d859 10120 bool ival_valid = false;
0c77715b 10121 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10122 {
0bd5d859 10123 ival_valid = true;
e440a328 10124 if (mpz_sgn(ival) < 0
10125 || mpz_sizeinbase(ival, 2) >= int_bits
10126 || (lval_valid
10127 && (this->end_ == NULL
10128 ? mpz_cmp(ival, lval) >= 0
10129 : mpz_cmp(ival, lval) > 0)))
10130 {
10131 error_at(this->start_->location(), "array index out of bounds");
10132 this->set_is_error();
10133 }
10134 }
10135 if (this->end_ != NULL && !this->end_->is_nil_expression())
10136 {
0c77715b 10137 Numeric_constant enc;
10138 mpz_t eval;
acf2b673 10139 bool eval_valid = false;
0c77715b 10140 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10141 {
acf2b673 10142 eval_valid = true;
0c77715b 10143 if (mpz_sgn(eval) < 0
10144 || mpz_sizeinbase(eval, 2) >= int_bits
10145 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10146 {
10147 error_at(this->end_->location(), "array index out of bounds");
10148 this->set_is_error();
10149 }
0bd5d859 10150 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10151 this->report_error(_("inverted slice range"));
e440a328 10152 }
acf2b673 10153
10154 Numeric_constant cnc;
10155 mpz_t cval;
10156 if (this->cap_ != NULL
10157 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10158 {
10159 if (mpz_sgn(cval) < 0
10160 || mpz_sizeinbase(cval, 2) >= int_bits
10161 || (lval_valid && mpz_cmp(cval, lval) > 0))
10162 {
10163 error_at(this->cap_->location(), "array index out of bounds");
10164 this->set_is_error();
10165 }
10166 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10167 {
10168 error_at(this->cap_->location(),
10169 "invalid slice index: capacity less than start");
10170 this->set_is_error();
10171 }
10172 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10173 {
10174 error_at(this->cap_->location(),
10175 "invalid slice index: capacity less than length");
10176 this->set_is_error();
10177 }
10178 mpz_clear(cval);
10179 }
10180
10181 if (eval_valid)
10182 mpz_clear(eval);
e440a328 10183 }
0bd5d859 10184 if (ival_valid)
10185 mpz_clear(ival);
0c77715b 10186 if (lval_valid)
10187 mpz_clear(lval);
e440a328 10188
10189 // A slice of an array requires an addressable array. A slice of a
10190 // slice is always possible.
411eb89e 10191 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10192 {
10193 if (!this->array_->is_addressable())
8da39c3b 10194 this->report_error(_("slice of unaddressable value"));
88ec30c8 10195 else
10196 this->array_->address_taken(true);
10197 }
e440a328 10198}
10199
2c809f8f 10200// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10201
10202Expression*
10203Array_index_expression::do_flatten(Gogo*, Named_object*,
10204 Statement_inserter* inserter)
10205{
10206 Location loc = this->location();
2c809f8f 10207 Temporary_statement* temp;
35a54f17 10208 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10209 {
2c809f8f 10210 temp = Statement::make_temporary(NULL, this->array_, loc);
35a54f17 10211 inserter->insert(temp);
10212 this->array_ = Expression::make_temporary_reference(temp, loc);
10213 }
2c809f8f 10214 if (!this->start_->is_variable())
10215 {
10216 temp = Statement::make_temporary(NULL, this->start_, loc);
10217 inserter->insert(temp);
10218 this->start_ = Expression::make_temporary_reference(temp, loc);
10219 }
10220 if (this->end_ != NULL
10221 && !this->end_->is_nil_expression()
10222 && !this->end_->is_variable())
10223 {
10224 temp = Statement::make_temporary(NULL, this->end_, loc);
10225 inserter->insert(temp);
10226 this->end_ = Expression::make_temporary_reference(temp, loc);
10227 }
10228 if (this->cap_ != NULL && !this->cap_->is_variable())
10229 {
10230 temp = Statement::make_temporary(NULL, this->cap_, loc);
10231 inserter->insert(temp);
10232 this->cap_ = Expression::make_temporary_reference(temp, loc);
10233 }
10234
35a54f17 10235 return this;
10236}
10237
e440a328 10238// Return whether this expression is addressable.
10239
10240bool
10241Array_index_expression::do_is_addressable() const
10242{
10243 // A slice expression is not addressable.
10244 if (this->end_ != NULL)
10245 return false;
10246
10247 // An index into a slice is addressable.
411eb89e 10248 if (this->array_->type()->is_slice_type())
e440a328 10249 return true;
10250
10251 // An index into an array is addressable if the array is
10252 // addressable.
10253 return this->array_->is_addressable();
10254}
10255
10256// Get a tree for an array index.
10257
10258tree
10259Array_index_expression::do_get_tree(Translate_context* context)
10260{
e440a328 10261 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10262 if (array_type == NULL)
10263 {
c484d925 10264 go_assert(this->array_->type()->is_error());
d8cd8e2d 10265 return error_mark_node;
10266 }
35a54f17 10267 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10268
2c809f8f 10269 Location loc = this->location();
10270 Gogo* gogo = context->gogo();
10271
10272 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
e440a328 10273
2c809f8f 10274 // We need to convert the length and capacity to the Go "int" type here
10275 // because the length of a fixed-length array could be of type "uintptr"
10276 // and gimple disallows binary operations between "uintptr" and other
10277 // integer types. FIXME.
10278 Bexpression* length = NULL;
a04bfdfc 10279 if (this->end_ == NULL || this->end_->is_nil_expression())
10280 {
35a54f17 10281 Expression* len = array_type->get_length(gogo, this->array_);
2c809f8f 10282 length = tree_to_expr(len->get_tree(context));
10283 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10284 }
10285
2c809f8f 10286 Bexpression* capacity = NULL;
a04bfdfc 10287 if (this->end_ != NULL)
10288 {
35a54f17 10289 Expression* cap = array_type->get_capacity(gogo, this->array_);
2c809f8f 10290 capacity = tree_to_expr(cap->get_tree(context));
10291 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10292 }
10293
2c809f8f 10294 Bexpression* cap_arg = capacity;
acf2b673 10295 if (this->cap_ != NULL)
10296 {
2c809f8f 10297 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10298 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10299 }
10300
2c809f8f 10301 if (length == NULL)
10302 length = cap_arg;
e440a328 10303
10304 int code = (array_type->length() != NULL
10305 ? (this->end_ == NULL
10306 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10307 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10308 : (this->end_ == NULL
10309 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10310 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
2c809f8f 10311 Bexpression* crash =
10312 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10313
10314 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10315 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10316
10317 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10318 start = gogo->backend()->convert_expression(int_btype, start, loc);
10319 Bexpression* start_too_large =
10320 gogo->backend()->binary_expression((this->end_ == NULL
10321 ? OPERATOR_GE
10322 : OPERATOR_GT),
10323 start,
10324 (this->end_ == NULL
10325 ? length
10326 : capacity),
10327 loc);
10328 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10329 bad_index, loc);
e440a328 10330
10331 if (this->end_ == NULL)
10332 {
10333 // Simple array indexing. This has to return an l-value, so
2c809f8f 10334 // wrap the index check into START.
10335 start =
10336 gogo->backend()->conditional_expression(int_btype, bad_index,
10337 crash, start, loc);
e440a328 10338
2c809f8f 10339 Bexpression* ret;
e440a328 10340 if (array_type->length() != NULL)
10341 {
2c809f8f 10342 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10343 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10344 }
10345 else
10346 {
2c809f8f 10347 // Slice.
10348 Expression* valptr =
35a54f17 10349 array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10350 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10351 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 10352
10353 Type* ele_type = this->array_->type()->array_type()->element_type();
10354 Btype* ele_btype = ele_type->get_backend(gogo);
10355 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 10356 }
2c809f8f 10357 return expr_to_tree(ret);
e440a328 10358 }
10359
10360 // Array slice.
10361
acf2b673 10362 if (this->cap_ != NULL)
10363 {
2c809f8f 10364 bounds_check = Expression::check_bounds(this->cap_, loc);
10365 Bexpression* bounds_bcheck =
10366 tree_to_expr(bounds_check->get_tree(context));
10367 bad_index =
10368 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10369 bad_index, loc);
10370 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10371
10372 Bexpression* cap_too_small =
10373 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10374 Bexpression* cap_too_large =
10375 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10376 Bexpression* bad_cap =
10377 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10378 cap_too_large, loc);
10379 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10380 bad_index, loc);
10381 }
10382
10383 Bexpression* end;
e440a328 10384 if (this->end_->is_nil_expression())
2c809f8f 10385 end = length;
e440a328 10386 else
10387 {
2c809f8f 10388 bounds_check = Expression::check_bounds(this->end_, loc);
10389 Bexpression* bounds_bcheck =
10390 tree_to_expr(bounds_check->get_tree(context));
e440a328 10391
2c809f8f 10392 bad_index =
10393 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10394 bad_index, loc);
e440a328 10395
2c809f8f 10396 end = tree_to_expr(this->end_->get_tree(context));
10397 end = gogo->backend()->convert_expression(int_btype, end, loc);
10398 Bexpression* end_too_small =
10399 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10400 Bexpression* end_too_large =
10401 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10402 Bexpression* bad_end =
10403 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10404 end_too_large, loc);
10405 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10406 bad_index, loc);
e440a328 10407 }
10408
35a54f17 10409 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10410 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10411 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10412
2c809f8f 10413 Bexpression* result_length =
10414 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10415
2c809f8f 10416 Bexpression* result_capacity =
10417 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10418
2c809f8f 10419 Btype* struct_btype = this->type()->get_backend(gogo);
10420 std::vector<Bexpression*> init;
10421 init.push_back(val);
10422 init.push_back(result_length);
10423 init.push_back(result_capacity);
e440a328 10424
2c809f8f 10425 Bexpression* ctor =
10426 gogo->backend()->constructor_expression(struct_btype, init, loc);
10427 Bexpression* ret =
10428 gogo->backend()->conditional_expression(struct_btype, bad_index,
10429 crash, ctor, loc);
e440a328 10430
2c809f8f 10431 return expr_to_tree(ret);
e440a328 10432}
10433
d751bb78 10434// Dump ast representation for an array index expression.
10435
10436void
10437Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10438 const
10439{
10440 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10441 this->start_, this->end_, this->cap_);
d751bb78 10442}
10443
acf2b673 10444// Make an array index expression. END and CAP may be NULL.
e440a328 10445
10446Expression*
10447Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10448 Expression* end, Expression* cap,
10449 Location location)
e440a328 10450{
acf2b673 10451 return new Array_index_expression(array, start, end, cap, location);
e440a328 10452}
10453
10454// A string index. This is used for both indexing and slicing.
10455
10456class String_index_expression : public Expression
10457{
10458 public:
10459 String_index_expression(Expression* string, Expression* start,
b13c66cd 10460 Expression* end, Location location)
e440a328 10461 : Expression(EXPRESSION_STRING_INDEX, location),
10462 string_(string), start_(start), end_(end)
10463 { }
10464
10465 protected:
10466 int
10467 do_traverse(Traverse*);
10468
2c809f8f 10469 Expression*
10470 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10471
e440a328 10472 Type*
10473 do_type();
10474
10475 void
10476 do_determine_type(const Type_context*);
10477
10478 void
10479 do_check_types(Gogo*);
10480
10481 Expression*
10482 do_copy()
10483 {
10484 return Expression::make_string_index(this->string_->copy(),
10485 this->start_->copy(),
10486 (this->end_ == NULL
10487 ? NULL
10488 : this->end_->copy()),
10489 this->location());
10490 }
10491
baef9f7a 10492 bool
10493 do_must_eval_subexpressions_in_order(int* skip) const
10494 {
10495 *skip = 1;
10496 return true;
10497 }
10498
e440a328 10499 tree
10500 do_get_tree(Translate_context*);
10501
d751bb78 10502 void
10503 do_dump_expression(Ast_dump_context*) const;
10504
e440a328 10505 private:
10506 // The string we are getting a value from.
10507 Expression* string_;
10508 // The start or only index.
10509 Expression* start_;
10510 // The end index of a slice. This may be NULL for a single index,
10511 // or it may be a nil expression for the length of the string.
10512 Expression* end_;
10513};
10514
10515// String index traversal.
10516
10517int
10518String_index_expression::do_traverse(Traverse* traverse)
10519{
10520 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10521 return TRAVERSE_EXIT;
10522 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10523 return TRAVERSE_EXIT;
10524 if (this->end_ != NULL)
10525 {
10526 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10527 return TRAVERSE_EXIT;
10528 }
10529 return TRAVERSE_CONTINUE;
10530}
10531
2c809f8f 10532Expression*
10533String_index_expression::do_flatten(Gogo*, Named_object*,
10534 Statement_inserter* inserter)
e440a328 10535{
2c809f8f 10536 Temporary_statement* temp;
10537 Location loc = this->location();
10538 if (!this->string_->is_variable())
10539 {
10540 temp = Statement::make_temporary(NULL, this->string_, loc);
10541 inserter->insert(temp);
10542 this->string_ = Expression::make_temporary_reference(temp, loc);
10543 }
10544 if (!this->start_->is_variable())
10545 {
10546 temp = Statement::make_temporary(NULL, this->start_, loc);
10547 inserter->insert(temp);
10548 this->start_ = Expression::make_temporary_reference(temp, loc);
10549 }
10550 if (this->end_ != NULL
10551 && !this->end_->is_nil_expression()
10552 && !this->end_->is_variable())
10553 {
10554 temp = Statement::make_temporary(NULL, this->end_, loc);
10555 inserter->insert(temp);
10556 this->end_ = Expression::make_temporary_reference(temp, loc);
10557 }
10558
10559 return this;
10560}
10561
10562// Return the type of a string index.
10563
10564Type*
10565String_index_expression::do_type()
10566{
10567 if (this->end_ == NULL)
10568 return Type::lookup_integer_type("uint8");
10569 else
10570 return this->string_->type();
10571}
10572
10573// Determine the type of a string index.
10574
10575void
10576String_index_expression::do_determine_type(const Type_context*)
10577{
10578 this->string_->determine_type_no_context();
10579 this->start_->determine_type_no_context();
e440a328 10580 if (this->end_ != NULL)
93000773 10581 this->end_->determine_type_no_context();
e440a328 10582}
10583
10584// Check types of a string index.
10585
10586void
10587String_index_expression::do_check_types(Gogo*)
10588{
acdc230d 10589 Numeric_constant nc;
10590 unsigned long v;
10591 if (this->start_->type()->integer_type() == NULL
10592 && !this->start_->type()->is_error()
10593 && (!this->start_->numeric_constant_value(&nc)
10594 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10595 this->report_error(_("index must be integer"));
10596 if (this->end_ != NULL
10597 && this->end_->type()->integer_type() == NULL
acdc230d 10598 && !this->end_->type()->is_error()
10599 && !this->end_->is_nil_expression()
10600 && !this->end_->is_error_expression()
10601 && (!this->end_->numeric_constant_value(&nc)
10602 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10603 this->report_error(_("slice end must be integer"));
10604
10605 std::string sval;
10606 bool sval_valid = this->string_->string_constant_value(&sval);
10607
0c77715b 10608 Numeric_constant inc;
e440a328 10609 mpz_t ival;
0bd5d859 10610 bool ival_valid = false;
0c77715b 10611 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10612 {
0bd5d859 10613 ival_valid = true;
e440a328 10614 if (mpz_sgn(ival) < 0
10615 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10616 {
10617 error_at(this->start_->location(), "string index out of bounds");
10618 this->set_is_error();
10619 }
10620 }
10621 if (this->end_ != NULL && !this->end_->is_nil_expression())
10622 {
0c77715b 10623 Numeric_constant enc;
10624 mpz_t eval;
10625 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10626 {
0c77715b 10627 if (mpz_sgn(eval) < 0
10628 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 10629 {
10630 error_at(this->end_->location(), "string index out of bounds");
10631 this->set_is_error();
10632 }
0bd5d859 10633 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10634 this->report_error(_("inverted slice range"));
0c77715b 10635 mpz_clear(eval);
e440a328 10636 }
10637 }
0bd5d859 10638 if (ival_valid)
10639 mpz_clear(ival);
e440a328 10640}
10641
10642// Get a tree for a string index.
10643
10644tree
10645String_index_expression::do_get_tree(Translate_context* context)
10646{
b13c66cd 10647 Location loc = this->location();
2c809f8f 10648 Expression* string_arg = this->string_;
10649 if (this->string_->type()->points_to() != NULL)
10650 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 10651
2c809f8f 10652 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 10653
2c809f8f 10654 int code = (this->end_ == NULL
10655 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10656 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 10657
2c809f8f 10658 Gogo* gogo = context->gogo();
10659 Bexpression* crash =
10660 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
1b1f2abf 10661
10662 Type* int_type = Type::lookup_integer_type("int");
e440a328 10663
2c809f8f 10664 // It is possible that an error occurred earlier because the start index
10665 // cannot be represented as an integer type. In this case, we shouldn't
10666 // try casting the starting index into an integer since
10667 // Type_conversion_expression will fail to get the backend representation.
10668 // FIXME.
10669 if (this->start_->type()->integer_type() == NULL
10670 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10671 {
10672 go_assert(saw_errors());
10673 return error_mark_node;
10674 }
e440a328 10675
2c809f8f 10676 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 10677
2c809f8f 10678 if (this->end_ == NULL)
10679 {
10680 Expression* length =
10681 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 10682
2c809f8f 10683 Expression* start_too_large =
10684 Expression::make_binary(OPERATOR_GE, start, length, loc);
10685 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10686 bad_index, loc);
10687 Expression* bytes =
10688 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 10689
2c809f8f 10690 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10691 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10692 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 10693 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10694 Bexpression* index =
10695 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 10696
2c809f8f 10697 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10698 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10699 Bexpression* ret =
10700 gogo->backend()->conditional_expression(byte_btype, index_error,
10701 crash, index, loc);
10702 return expr_to_tree(ret);
10703 }
10704
10705 Expression* end = NULL;
10706 if (this->end_->is_nil_expression())
e440a328 10707 {
2c809f8f 10708 mpz_t neg_one;
10709 mpz_init_set_si(neg_one, -1);
10710 end = Expression::make_integer(&neg_one, int_type, loc);
10711 mpz_clear(neg_one);
e440a328 10712 }
10713 else
10714 {
2c809f8f 10715 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10716 bad_index =
10717 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10718 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 10719 }
2c809f8f 10720
10721 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10722 string_arg, start, end);
10723 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10724
10725 Btype* str_btype = strslice->type()->get_backend(gogo);
10726 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10727 Bexpression* ret =
10728 gogo->backend()->conditional_expression(str_btype, index_error,
10729 crash, bstrslice, loc);
10730 return expr_to_tree(ret);
e440a328 10731}
10732
d751bb78 10733// Dump ast representation for a string index expression.
10734
10735void
10736String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10737 const
10738{
acf2b673 10739 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10740 this->start_, this->end_, NULL);
d751bb78 10741}
10742
e440a328 10743// Make a string index expression. END may be NULL.
10744
10745Expression*
10746Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 10747 Expression* end, Location location)
e440a328 10748{
10749 return new String_index_expression(string, start, end, location);
10750}
10751
10752// Class Map_index.
10753
10754// Get the type of the map.
10755
10756Map_type*
10757Map_index_expression::get_map_type() const
10758{
10759 Map_type* mt = this->map_->type()->deref()->map_type();
c7524fae 10760 if (mt == NULL)
c484d925 10761 go_assert(saw_errors());
e440a328 10762 return mt;
10763}
10764
10765// Map index traversal.
10766
10767int
10768Map_index_expression::do_traverse(Traverse* traverse)
10769{
10770 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10771 return TRAVERSE_EXIT;
10772 return Expression::traverse(&this->index_, traverse);
10773}
10774
2c809f8f 10775// We need to pass in a pointer to the key, so flatten the index into a
10776// temporary variable if it isn't already. The value pointer will be
10777// dereferenced and checked for nil, so flatten into a temporary to avoid
10778// recomputation.
10779
10780Expression*
10781Map_index_expression::do_flatten(Gogo*, Named_object*,
10782 Statement_inserter* inserter)
10783{
10784 Map_type* mt = this->get_map_type();
10785 if (this->index_->type() != mt->key_type())
10786 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10787 this->location());
10788
10789 if (!this->index_->is_variable())
10790 {
10791 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10792 this->location());
10793 inserter->insert(temp);
10794 this->index_ = Expression::make_temporary_reference(temp,
10795 this->location());
10796 }
10797
10798 if (this->value_pointer_ == NULL)
10799 this->get_value_pointer(this->is_lvalue_);
10800 if (!this->value_pointer_->is_variable())
10801 {
10802 Temporary_statement* temp =
10803 Statement::make_temporary(NULL, this->value_pointer_,
10804 this->location());
10805 inserter->insert(temp);
10806 this->value_pointer_ =
10807 Expression::make_temporary_reference(temp, this->location());
10808 }
10809
10810 return this;
10811}
10812
e440a328 10813// Return the type of a map index.
10814
10815Type*
10816Map_index_expression::do_type()
10817{
c7524fae 10818 Map_type* mt = this->get_map_type();
10819 if (mt == NULL)
10820 return Type::make_error_type();
10821 Type* type = mt->val_type();
e440a328 10822 // If this map index is in a tuple assignment, we actually return a
10823 // pointer to the value type. Tuple_map_assignment_statement is
10824 // responsible for handling this correctly. We need to get the type
10825 // right in case this gets assigned to a temporary variable.
10826 if (this->is_in_tuple_assignment_)
10827 type = Type::make_pointer_type(type);
10828 return type;
10829}
10830
10831// Fix the type of a map index.
10832
10833void
10834Map_index_expression::do_determine_type(const Type_context*)
10835{
10836 this->map_->determine_type_no_context();
c7524fae 10837 Map_type* mt = this->get_map_type();
10838 Type* key_type = mt == NULL ? NULL : mt->key_type();
10839 Type_context subcontext(key_type, false);
e440a328 10840 this->index_->determine_type(&subcontext);
10841}
10842
10843// Check types of a map index.
10844
10845void
10846Map_index_expression::do_check_types(Gogo*)
10847{
10848 std::string reason;
c7524fae 10849 Map_type* mt = this->get_map_type();
10850 if (mt == NULL)
10851 return;
10852 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 10853 {
10854 if (reason.empty())
10855 this->report_error(_("incompatible type for map index"));
10856 else
10857 {
10858 error_at(this->location(), "incompatible type for map index (%s)",
10859 reason.c_str());
10860 this->set_is_error();
10861 }
10862 }
10863}
10864
10865// Get a tree for a map index.
10866
10867tree
10868Map_index_expression::do_get_tree(Translate_context* context)
10869{
10870 Map_type* type = this->get_map_type();
c7524fae 10871 if (type == NULL)
2c809f8f 10872 {
10873 go_assert(saw_errors());
10874 return error_mark_node;
10875 }
e440a328 10876
2c809f8f 10877 go_assert(this->value_pointer_ != NULL
10878 && this->value_pointer_->is_variable());
e440a328 10879
2c809f8f 10880 Bexpression* ret;
e440a328 10881 if (this->is_lvalue_)
2c809f8f 10882 {
10883 Expression* val =
10884 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10885 this->location());
10886 ret = tree_to_expr(val->get_tree(context));
10887 }
e440a328 10888 else if (this->is_in_tuple_assignment_)
10889 {
10890 // Tuple_map_assignment_statement is responsible for using this
10891 // appropriately.
2c809f8f 10892 ret = tree_to_expr(this->value_pointer_->get_tree(context));
e440a328 10893 }
10894 else
10895 {
2c809f8f 10896 Location loc = this->location();
10897
10898 Expression* nil_check =
10899 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10900 Expression::make_nil(loc), loc);
10901 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10902 Expression* val =
10903 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10904 Bexpression* bval = tree_to_expr(val->get_tree(context));
10905
63697958 10906 Gogo* gogo = context->gogo();
10907 Btype* val_btype = type->val_type()->get_backend(gogo);
10908 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
2c809f8f 10909 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10910 val_zero, bval, loc);
e440a328 10911 }
2c809f8f 10912
10913 return expr_to_tree(ret);
e440a328 10914}
10915
2c809f8f 10916// Get an expression for the map index. This returns an expression which
10917// evaluates to a pointer to a value. The pointer will be NULL if the key is
e440a328 10918// not in the map.
10919
2c809f8f 10920Expression*
10921Map_index_expression::get_value_pointer(bool insert)
e440a328 10922{
2c809f8f 10923 if (this->value_pointer_ == NULL)
746d2e73 10924 {
2c809f8f 10925 Map_type* type = this->get_map_type();
10926 if (type == NULL)
746d2e73 10927 {
2c809f8f 10928 go_assert(saw_errors());
10929 return Expression::make_error(this->location());
746d2e73 10930 }
e440a328 10931
2c809f8f 10932 Location loc = this->location();
10933 Expression* map_ref = this->map_;
10934 if (this->map_->type()->points_to() != NULL)
10935 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
e440a328 10936
2c809f8f 10937 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10938 loc);
10939 Expression* map_index =
10940 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10941 map_ref, index_ptr,
10942 Expression::make_boolean(insert, loc));
10943
10944 Type* val_type = type->val_type();
10945 this->value_pointer_ =
10946 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10947 map_index, this->location());
10948 }
10949 return this->value_pointer_;
e440a328 10950}
10951
d751bb78 10952// Dump ast representation for a map index expression
10953
10954void
10955Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10956 const
10957{
acf2b673 10958 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10959 this->index_, NULL, NULL);
d751bb78 10960}
10961
e440a328 10962// Make a map index expression.
10963
10964Map_index_expression*
10965Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 10966 Location location)
e440a328 10967{
10968 return new Map_index_expression(map, index, location);
10969}
10970
10971// Class Field_reference_expression.
10972
149eabc5 10973// Lower a field reference expression. There is nothing to lower, but
10974// this is where we generate the tracking information for fields with
10975// the magic go:"track" tag.
10976
10977Expression*
10978Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10979 Statement_inserter* inserter, int)
10980{
10981 Struct_type* struct_type = this->expr_->type()->struct_type();
10982 if (struct_type == NULL)
10983 {
10984 // Error will be reported elsewhere.
10985 return this;
10986 }
10987 const Struct_field* field = struct_type->field(this->field_index_);
10988 if (field == NULL)
10989 return this;
10990 if (!field->has_tag())
10991 return this;
10992 if (field->tag().find("go:\"track\"") == std::string::npos)
10993 return this;
10994
10995 // We have found a reference to a tracked field. Build a call to
10996 // the runtime function __go_fieldtrack with a string that describes
10997 // the field. FIXME: We should only call this once per referenced
10998 // field per function, not once for each reference to the field.
10999
11000 if (this->called_fieldtrack_)
11001 return this;
11002 this->called_fieldtrack_ = true;
11003
11004 Location loc = this->location();
11005
11006 std::string s = "fieldtrack \"";
11007 Named_type* nt = this->expr_->type()->named_type();
11008 if (nt == NULL || nt->named_object()->package() == NULL)
11009 s.append(gogo->pkgpath());
11010 else
11011 s.append(nt->named_object()->package()->pkgpath());
11012 s.push_back('.');
11013 if (nt != NULL)
5c29ad36 11014 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11015 s.push_back('.');
11016 s.append(field->field_name());
11017 s.push_back('"');
11018
11019 // We can't use a string here, because internally a string holds a
11020 // pointer to the actual bytes; when the linker garbage collects the
11021 // string, it won't garbage collect the bytes. So we use a
11022 // [...]byte.
11023
11024 mpz_t val;
11025 mpz_init_set_ui(val, s.length());
11026 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11027 mpz_clear(val);
11028
11029 Type* byte_type = gogo->lookup_global("byte")->type_value();
11030 Type* array_type = Type::make_array_type(byte_type, length_expr);
11031
11032 Expression_list* bytes = new Expression_list();
11033 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11034 {
11035 mpz_init_set_ui(val, *p);
11036 Expression* byte = Expression::make_integer(&val, NULL, loc);
11037 mpz_clear(val);
11038 bytes->push_back(byte);
11039 }
11040
11041 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11042 bytes, false, loc);
149eabc5 11043
11044 Variable* var = new Variable(array_type, e, true, false, false, loc);
11045
11046 static int count;
11047 char buf[50];
11048 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11049 ++count;
11050
11051 Named_object* no = gogo->add_variable(buf, var);
11052 e = Expression::make_var_reference(no, loc);
11053 e = Expression::make_unary(OPERATOR_AND, e, loc);
11054
11055 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11056 inserter->insert(Statement::make_statement(call, false));
11057
11058 // Put this function, and the global variable we just created, into
11059 // unique sections. This will permit the linker to garbage collect
11060 // them if they are not referenced. The effect is that the only
11061 // strings, indicating field references, that will wind up in the
11062 // executable will be those for functions that are actually needed.
66a6be58 11063 if (function != NULL)
11064 function->func_value()->set_in_unique_section();
149eabc5 11065 var->set_in_unique_section();
11066
11067 return this;
11068}
11069
e440a328 11070// Return the type of a field reference.
11071
11072Type*
11073Field_reference_expression::do_type()
11074{
b0e628fb 11075 Type* type = this->expr_->type();
5c13bd80 11076 if (type->is_error())
b0e628fb 11077 return type;
11078 Struct_type* struct_type = type->struct_type();
c484d925 11079 go_assert(struct_type != NULL);
e440a328 11080 return struct_type->field(this->field_index_)->type();
11081}
11082
11083// Check the types for a field reference.
11084
11085void
11086Field_reference_expression::do_check_types(Gogo*)
11087{
b0e628fb 11088 Type* type = this->expr_->type();
5c13bd80 11089 if (type->is_error())
b0e628fb 11090 return;
11091 Struct_type* struct_type = type->struct_type();
c484d925 11092 go_assert(struct_type != NULL);
11093 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11094}
11095
11096// Get a tree for a field reference.
11097
11098tree
11099Field_reference_expression::do_get_tree(Translate_context* context)
11100{
fbb851c5 11101 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11102 Bexpression* ret =
11103 context->gogo()->backend()->struct_field_expression(bstruct,
11104 this->field_index_,
11105 this->location());
11106 return expr_to_tree(ret);
e440a328 11107}
11108
d751bb78 11109// Dump ast representation for a field reference expression.
11110
11111void
11112Field_reference_expression::do_dump_expression(
11113 Ast_dump_context* ast_dump_context) const
11114{
11115 this->expr_->dump_expression(ast_dump_context);
11116 ast_dump_context->ostream() << "." << this->field_index_;
11117}
11118
e440a328 11119// Make a reference to a qualified identifier in an expression.
11120
11121Field_reference_expression*
11122Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11123 Location location)
e440a328 11124{
11125 return new Field_reference_expression(expr, field_index, location);
11126}
11127
11128// Class Interface_field_reference_expression.
11129
2387f644 11130// Return an expression for the pointer to the function to call.
e440a328 11131
2387f644 11132Expression*
11133Interface_field_reference_expression::get_function()
e440a328 11134{
2387f644 11135 Expression* ref = this->expr_;
11136 Location loc = this->location();
11137 if (ref->type()->points_to() != NULL)
11138 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11139
2387f644 11140 Expression* mtable =
11141 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11142 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11143
11144 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11145 unsigned int index;
11146 const Struct_field* field = mtable_type->find_local_field(name, &index);
11147 go_assert(field != NULL);
11148 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11149 return Expression::make_field_reference(mtable, index, loc);
e440a328 11150}
11151
2387f644 11152// Return an expression for the first argument to pass to the interface
e440a328 11153// function.
11154
2387f644 11155Expression*
11156Interface_field_reference_expression::get_underlying_object()
e440a328 11157{
2387f644 11158 Expression* expr = this->expr_;
11159 if (expr->type()->points_to() != NULL)
11160 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11161 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11162 this->location());
e440a328 11163}
11164
11165// Traversal.
11166
11167int
11168Interface_field_reference_expression::do_traverse(Traverse* traverse)
11169{
11170 return Expression::traverse(&this->expr_, traverse);
11171}
11172
0afbb937 11173// Lower the expression. If this expression is not called, we need to
11174// evaluate the expression twice when converting to the backend
11175// interface. So introduce a temporary variable if necessary.
11176
11177Expression*
11178Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11179 Statement_inserter* inserter,
11180 int)
11181{
2387f644 11182 if (!this->expr_->is_variable())
0afbb937 11183 {
11184 Temporary_statement* temp =
11185 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11186 inserter->insert(temp);
11187 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11188 this->location());
11189 }
11190 return this;
11191}
11192
e440a328 11193// Return the type of an interface field reference.
11194
11195Type*
11196Interface_field_reference_expression::do_type()
11197{
11198 Type* expr_type = this->expr_->type();
11199
11200 Type* points_to = expr_type->points_to();
11201 if (points_to != NULL)
11202 expr_type = points_to;
11203
11204 Interface_type* interface_type = expr_type->interface_type();
11205 if (interface_type == NULL)
11206 return Type::make_error_type();
11207
11208 const Typed_identifier* method = interface_type->find_method(this->name_);
11209 if (method == NULL)
11210 return Type::make_error_type();
11211
11212 return method->type();
11213}
11214
11215// Determine types.
11216
11217void
11218Interface_field_reference_expression::do_determine_type(const Type_context*)
11219{
11220 this->expr_->determine_type_no_context();
11221}
11222
11223// Check the types for an interface field reference.
11224
11225void
11226Interface_field_reference_expression::do_check_types(Gogo*)
11227{
11228 Type* type = this->expr_->type();
11229
11230 Type* points_to = type->points_to();
11231 if (points_to != NULL)
11232 type = points_to;
11233
11234 Interface_type* interface_type = type->interface_type();
11235 if (interface_type == NULL)
5c491127 11236 {
11237 if (!type->is_error_type())
11238 this->report_error(_("expected interface or pointer to interface"));
11239 }
e440a328 11240 else
11241 {
11242 const Typed_identifier* method =
11243 interface_type->find_method(this->name_);
11244 if (method == NULL)
11245 {
11246 error_at(this->location(), "method %qs not in interface",
11247 Gogo::message_name(this->name_).c_str());
11248 this->set_is_error();
11249 }
11250 }
11251}
11252
0afbb937 11253// If an interface field reference is not simply called, then it is
11254// represented as a closure. The closure will hold a single variable,
11255// the value of the interface on which the method should be called.
11256// The function will be a simple thunk that pulls the value from the
11257// closure and calls the method with the remaining arguments.
11258
11259// Because method values are not common, we don't build all thunks for
11260// all possible interface methods, but instead only build them as we
11261// need them. In particular, we even build them on demand for
11262// interface methods defined in other packages.
11263
11264Interface_field_reference_expression::Interface_method_thunks
11265 Interface_field_reference_expression::interface_method_thunks;
11266
11267// Find or create the thunk to call method NAME on TYPE.
11268
11269Named_object*
11270Interface_field_reference_expression::create_thunk(Gogo* gogo,
11271 Interface_type* type,
11272 const std::string& name)
11273{
11274 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11275 std::pair<Interface_method_thunks::iterator, bool> ins =
11276 Interface_field_reference_expression::interface_method_thunks.insert(val);
11277 if (ins.second)
11278 {
11279 // This is the first time we have seen this interface.
11280 ins.first->second = new Method_thunks();
11281 }
11282
11283 for (Method_thunks::const_iterator p = ins.first->second->begin();
11284 p != ins.first->second->end();
11285 p++)
11286 if (p->first == name)
11287 return p->second;
11288
11289 Location loc = type->location();
11290
11291 const Typed_identifier* method_id = type->find_method(name);
11292 if (method_id == NULL)
11293 return Named_object::make_erroneous_name(Gogo::thunk_name());
11294
11295 Function_type* orig_fntype = method_id->type()->function_type();
11296 if (orig_fntype == NULL)
11297 return Named_object::make_erroneous_name(Gogo::thunk_name());
11298
11299 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11300 // The type here is wrong--it should be the C function type. But it
11301 // doesn't really matter.
0afbb937 11302 Type* vt = Type::make_pointer_type(Type::make_void_type());
11303 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11304 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11305 Type* closure_type = Type::make_struct_type(sfl, loc);
11306 closure_type = Type::make_pointer_type(closure_type);
11307
f8bdf81a 11308 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11309
11310 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11311 false, loc);
11312
f8bdf81a 11313 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11314 cvar->set_is_used();
11315 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11316 new_no->func_value()->set_closure_var(cp);
0afbb937 11317
f8bdf81a 11318 gogo->start_block(loc);
0afbb937 11319
11320 // Field 0 of the closure is the function code pointer, field 1 is
11321 // the value on which to invoke the method.
11322 Expression* arg = Expression::make_var_reference(cp, loc);
11323 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11324 arg = Expression::make_field_reference(arg, 1, loc);
11325
11326 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11327 loc);
11328
11329 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11330 Expression_list* args;
11331 if (orig_params == NULL || orig_params->empty())
11332 args = NULL;
11333 else
11334 {
11335 const Typed_identifier_list* new_params = new_fntype->parameters();
11336 args = new Expression_list();
11337 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11338 p != new_params->end();
0afbb937 11339 ++p)
11340 {
11341 Named_object* p_no = gogo->lookup(p->name(), NULL);
11342 go_assert(p_no != NULL
11343 && p_no->is_variable()
11344 && p_no->var_value()->is_parameter());
11345 args->push_back(Expression::make_var_reference(p_no, loc));
11346 }
11347 }
11348
11349 Call_expression* call = Expression::make_call(ifre, args,
11350 orig_fntype->is_varargs(),
11351 loc);
11352 call->set_varargs_are_lowered();
11353
11354 Statement* s = Statement::make_return_from_call(call, loc);
11355 gogo->add_statement(s);
11356 Block* b = gogo->finish_block(loc);
11357 gogo->add_block(b, loc);
11358 gogo->lower_block(new_no, b);
a32698ee 11359 gogo->flatten_block(new_no, b);
0afbb937 11360 gogo->finish_function(loc);
11361
11362 ins.first->second->push_back(std::make_pair(name, new_no));
11363 return new_no;
11364}
11365
11366// Get a tree for a method value.
e440a328 11367
11368tree
0afbb937 11369Interface_field_reference_expression::do_get_tree(Translate_context* context)
e440a328 11370{
0afbb937 11371 Interface_type* type = this->expr_->type()->interface_type();
11372 if (type == NULL)
11373 {
11374 go_assert(saw_errors());
11375 return error_mark_node;
11376 }
11377
11378 Named_object* thunk =
11379 Interface_field_reference_expression::create_thunk(context->gogo(),
11380 type, this->name_);
11381 if (thunk->is_erroneous())
11382 {
11383 go_assert(saw_errors());
11384 return error_mark_node;
11385 }
11386
11387 // FIXME: We should lower this earlier, but we can't it lower it in
11388 // the lowering pass because at that point we don't know whether we
11389 // need to create the thunk or not. If the expression is called, we
11390 // don't need the thunk.
11391
11392 Location loc = this->location();
11393
11394 Struct_field_list* fields = new Struct_field_list();
11395 fields->push_back(Struct_field(Typed_identifier("fn.0",
11396 thunk->func_value()->type(),
11397 loc)));
11398 fields->push_back(Struct_field(Typed_identifier("val.1",
11399 this->expr_->type(),
11400 loc)));
11401 Struct_type* st = Type::make_struct_type(fields, loc);
11402
11403 Expression_list* vals = new Expression_list();
11404 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11405 vals->push_back(this->expr_);
11406
11407 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 11408 expr = Expression::make_heap_expression(expr, loc);
0afbb937 11409
2387f644 11410 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11411 Expression* nil_check =
11412 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11413 Expression::make_nil(loc), loc);
11414 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
0afbb937 11415
2387f644 11416 Gogo* gogo = context->gogo();
11417 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11418 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11419
11420 Bexpression* bcond =
a32698ee 11421 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11422 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11423 Bexpression* ret =
11424 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11425 return expr_to_tree(ret);
e440a328 11426}
11427
d751bb78 11428// Dump ast representation for an interface field reference.
11429
11430void
11431Interface_field_reference_expression::do_dump_expression(
11432 Ast_dump_context* ast_dump_context) const
11433{
11434 this->expr_->dump_expression(ast_dump_context);
11435 ast_dump_context->ostream() << "." << this->name_;
11436}
11437
e440a328 11438// Make a reference to a field in an interface.
11439
11440Expression*
11441Expression::make_interface_field_reference(Expression* expr,
11442 const std::string& field,
b13c66cd 11443 Location location)
e440a328 11444{
11445 return new Interface_field_reference_expression(expr, field, location);
11446}
11447
11448// A general selector. This is a Parser_expression for LEFT.NAME. It
11449// is lowered after we know the type of the left hand side.
11450
11451class Selector_expression : public Parser_expression
11452{
11453 public:
11454 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11455 Location location)
e440a328 11456 : Parser_expression(EXPRESSION_SELECTOR, location),
11457 left_(left), name_(name)
11458 { }
11459
11460 protected:
11461 int
11462 do_traverse(Traverse* traverse)
11463 { return Expression::traverse(&this->left_, traverse); }
11464
11465 Expression*
ceeb4318 11466 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11467
11468 Expression*
11469 do_copy()
11470 {
11471 return new Selector_expression(this->left_->copy(), this->name_,
11472 this->location());
11473 }
11474
d751bb78 11475 void
11476 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11477
e440a328 11478 private:
11479 Expression*
11480 lower_method_expression(Gogo*);
11481
11482 // The expression on the left hand side.
11483 Expression* left_;
11484 // The name on the right hand side.
11485 std::string name_;
11486};
11487
11488// Lower a selector expression once we know the real type of the left
11489// hand side.
11490
11491Expression*
ceeb4318 11492Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11493 int)
e440a328 11494{
11495 Expression* left = this->left_;
11496 if (left->is_type_expression())
11497 return this->lower_method_expression(gogo);
11498 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11499 this->location());
11500}
11501
11502// Lower a method expression T.M or (*T).M. We turn this into a
11503// function literal.
11504
11505Expression*
11506Selector_expression::lower_method_expression(Gogo* gogo)
11507{
b13c66cd 11508 Location location = this->location();
e440a328 11509 Type* type = this->left_->type();
11510 const std::string& name(this->name_);
11511
11512 bool is_pointer;
11513 if (type->points_to() == NULL)
11514 is_pointer = false;
11515 else
11516 {
11517 is_pointer = true;
11518 type = type->points_to();
11519 }
11520 Named_type* nt = type->named_type();
11521 if (nt == NULL)
11522 {
11523 error_at(location,
11524 ("method expression requires named type or "
11525 "pointer to named type"));
11526 return Expression::make_error(location);
11527 }
11528
11529 bool is_ambiguous;
11530 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11531 const Typed_identifier* imethod = NULL;
dcc8506b 11532 if (method == NULL && !is_pointer)
ab1468c3 11533 {
11534 Interface_type* it = nt->interface_type();
11535 if (it != NULL)
11536 imethod = it->find_method(name);
11537 }
11538
11539 if (method == NULL && imethod == NULL)
e440a328 11540 {
11541 if (!is_ambiguous)
dcc8506b 11542 error_at(location, "type %<%s%s%> has no method %<%s%>",
11543 is_pointer ? "*" : "",
e440a328 11544 nt->message_name().c_str(),
11545 Gogo::message_name(name).c_str());
11546 else
dcc8506b 11547 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
e440a328 11548 Gogo::message_name(name).c_str(),
dcc8506b 11549 is_pointer ? "*" : "",
e440a328 11550 nt->message_name().c_str());
11551 return Expression::make_error(location);
11552 }
11553
ab1468c3 11554 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11555 {
11556 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11557 nt->message_name().c_str(),
11558 Gogo::message_name(name).c_str());
11559 return Expression::make_error(location);
11560 }
11561
11562 // Build a new function type in which the receiver becomes the first
11563 // argument.
ab1468c3 11564 Function_type* method_type;
11565 if (method != NULL)
11566 {
11567 method_type = method->type();
c484d925 11568 go_assert(method_type->is_method());
ab1468c3 11569 }
11570 else
11571 {
11572 method_type = imethod->type()->function_type();
c484d925 11573 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11574 }
e440a328 11575
11576 const char* const receiver_name = "$this";
11577 Typed_identifier_list* parameters = new Typed_identifier_list();
11578 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11579 location));
11580
11581 const Typed_identifier_list* method_parameters = method_type->parameters();
11582 if (method_parameters != NULL)
11583 {
f470da59 11584 int i = 0;
e440a328 11585 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11586 p != method_parameters->end();
f470da59 11587 ++p, ++i)
11588 {
68883531 11589 if (!p->name().empty())
f470da59 11590 parameters->push_back(*p);
11591 else
11592 {
11593 char buf[20];
11594 snprintf(buf, sizeof buf, "$param%d", i);
11595 parameters->push_back(Typed_identifier(buf, p->type(),
11596 p->location()));
11597 }
11598 }
e440a328 11599 }
11600
11601 const Typed_identifier_list* method_results = method_type->results();
11602 Typed_identifier_list* results;
11603 if (method_results == NULL)
11604 results = NULL;
11605 else
11606 {
11607 results = new Typed_identifier_list();
11608 for (Typed_identifier_list::const_iterator p = method_results->begin();
11609 p != method_results->end();
11610 ++p)
11611 results->push_back(*p);
11612 }
11613
11614 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11615 location);
11616 if (method_type->is_varargs())
11617 fntype->set_is_varargs();
11618
11619 // We generate methods which always takes a pointer to the receiver
11620 // as their first argument. If this is for a pointer type, we can
11621 // simply reuse the existing function. We use an internal hack to
11622 // get the right type.
8381eda7 11623 // FIXME: This optimization is disabled because it doesn't yet work
11624 // with function descriptors when the method expression is not
11625 // directly called.
11626 if (method != NULL && is_pointer && false)
e440a328 11627 {
11628 Named_object* mno = (method->needs_stub_method()
11629 ? method->stub_object()
11630 : method->named_object());
11631 Expression* f = Expression::make_func_reference(mno, NULL, location);
11632 f = Expression::make_cast(fntype, f, location);
11633 Type_conversion_expression* tce =
11634 static_cast<Type_conversion_expression*>(f);
11635 tce->set_may_convert_function_types();
11636 return f;
11637 }
11638
11639 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11640 location);
11641
11642 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 11643 go_assert(vno != NULL);
e440a328 11644 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 11645 Expression* bm;
11646 if (method != NULL)
11647 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11648 else
11649 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 11650
11651 // Even though we found the method above, if it has an error type we
11652 // may see an error here.
11653 if (bm->is_error_expression())
463fe805 11654 {
11655 gogo->finish_function(location);
11656 return bm;
11657 }
e440a328 11658
11659 Expression_list* args;
f470da59 11660 if (parameters->size() <= 1)
e440a328 11661 args = NULL;
11662 else
11663 {
11664 args = new Expression_list();
f470da59 11665 Typed_identifier_list::const_iterator p = parameters->begin();
11666 ++p;
11667 for (; p != parameters->end(); ++p)
e440a328 11668 {
11669 vno = gogo->lookup(p->name(), NULL);
c484d925 11670 go_assert(vno != NULL);
e440a328 11671 args->push_back(Expression::make_var_reference(vno, location));
11672 }
11673 }
11674
ceeb4318 11675 gogo->start_block(location);
11676
e440a328 11677 Call_expression* call = Expression::make_call(bm, args,
11678 method_type->is_varargs(),
11679 location);
11680
0afbb937 11681 Statement* s = Statement::make_return_from_call(call, location);
e440a328 11682 gogo->add_statement(s);
11683
ceeb4318 11684 Block* b = gogo->finish_block(location);
11685
11686 gogo->add_block(b, location);
11687
11688 // Lower the call in case there are multiple results.
11689 gogo->lower_block(no, b);
a32698ee 11690 gogo->flatten_block(no, b);
ceeb4318 11691
e440a328 11692 gogo->finish_function(location);
11693
11694 return Expression::make_func_reference(no, NULL, location);
11695}
11696
d751bb78 11697// Dump the ast for a selector expression.
11698
11699void
11700Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11701 const
11702{
11703 ast_dump_context->dump_expression(this->left_);
11704 ast_dump_context->ostream() << ".";
11705 ast_dump_context->ostream() << this->name_;
11706}
11707
e440a328 11708// Make a selector expression.
11709
11710Expression*
11711Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 11712 Location location)
e440a328 11713{
11714 return new Selector_expression(left, name, location);
11715}
11716
11717// Implement the builtin function new.
11718
11719class Allocation_expression : public Expression
11720{
11721 public:
b13c66cd 11722 Allocation_expression(Type* type, Location location)
e440a328 11723 : Expression(EXPRESSION_ALLOCATION, location),
11724 type_(type)
11725 { }
11726
11727 protected:
11728 int
11729 do_traverse(Traverse* traverse)
11730 { return Type::traverse(this->type_, traverse); }
11731
11732 Type*
11733 do_type()
11734 { return Type::make_pointer_type(this->type_); }
11735
11736 void
11737 do_determine_type(const Type_context*)
11738 { }
11739
e440a328 11740 Expression*
11741 do_copy()
11742 { return new Allocation_expression(this->type_, this->location()); }
11743
11744 tree
11745 do_get_tree(Translate_context*);
11746
d751bb78 11747 void
11748 do_dump_expression(Ast_dump_context*) const;
11749
e440a328 11750 private:
11751 // The type we are allocating.
11752 Type* type_;
11753};
11754
e440a328 11755// Return a tree for an allocation expression.
11756
11757tree
11758Allocation_expression::do_get_tree(Translate_context* context)
11759{
2c809f8f 11760 Gogo* gogo = context->gogo();
11761 Location loc = this->location();
11762 Expression* space = gogo->allocate_memory(this->type_, loc);
11763 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11764 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11765 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11766 return expr_to_tree(ret);
e440a328 11767}
11768
d751bb78 11769// Dump ast representation for an allocation expression.
11770
11771void
11772Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11773 const
11774{
11775 ast_dump_context->ostream() << "new(";
11776 ast_dump_context->dump_type(this->type_);
11777 ast_dump_context->ostream() << ")";
11778}
11779
e440a328 11780// Make an allocation expression.
11781
11782Expression*
b13c66cd 11783Expression::make_allocation(Type* type, Location location)
e440a328 11784{
11785 return new Allocation_expression(type, location);
11786}
11787
e440a328 11788// Construct a struct.
11789
11790class Struct_construction_expression : public Expression
11791{
11792 public:
11793 Struct_construction_expression(Type* type, Expression_list* vals,
b13c66cd 11794 Location location)
e440a328 11795 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
0c4f5a19 11796 type_(type), vals_(vals), traverse_order_(NULL)
e440a328 11797 { }
11798
0c4f5a19 11799 // Set the traversal order, used to ensure that we implement the
11800 // order of evaluation rules. Takes ownership of the argument.
11801 void
11802 set_traverse_order(std::vector<int>* traverse_order)
11803 { this->traverse_order_ = traverse_order; }
11804
e440a328 11805 // Return whether this is a constant initializer.
11806 bool
11807 is_constant_struct() const;
11808
11809 protected:
11810 int
11811 do_traverse(Traverse* traverse);
11812
f9ca30f9 11813 bool
11814 do_is_immutable() const;
11815
e440a328 11816 Type*
11817 do_type()
11818 { return this->type_; }
11819
11820 void
11821 do_determine_type(const Type_context*);
11822
11823 void
11824 do_check_types(Gogo*);
11825
11826 Expression*
11827 do_copy()
11828 {
0c4f5a19 11829 Struct_construction_expression* ret =
11830 new Struct_construction_expression(this->type_, this->vals_->copy(),
11831 this->location());
11832 if (this->traverse_order_ != NULL)
11833 ret->set_traverse_order(this->traverse_order_);
11834 return ret;
e440a328 11835 }
11836
e440a328 11837 tree
11838 do_get_tree(Translate_context*);
11839
11840 void
11841 do_export(Export*) const;
11842
d751bb78 11843 void
11844 do_dump_expression(Ast_dump_context*) const;
11845
e440a328 11846 private:
11847 // The type of the struct to construct.
11848 Type* type_;
11849 // The list of values, in order of the fields in the struct. A NULL
11850 // entry means that the field should be zero-initialized.
11851 Expression_list* vals_;
0c4f5a19 11852 // If not NULL, the order in which to traverse vals_. This is used
11853 // so that we implement the order of evaluation rules correctly.
11854 std::vector<int>* traverse_order_;
e440a328 11855};
11856
11857// Traversal.
11858
11859int
11860Struct_construction_expression::do_traverse(Traverse* traverse)
11861{
0c4f5a19 11862 if (this->vals_ != NULL)
11863 {
11864 if (this->traverse_order_ == NULL)
11865 {
11866 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11867 return TRAVERSE_EXIT;
11868 }
11869 else
11870 {
11871 for (std::vector<int>::const_iterator p =
11872 this->traverse_order_->begin();
11873 p != this->traverse_order_->end();
11874 ++p)
11875 {
11876 if (Expression::traverse(&this->vals_->at(*p), traverse)
11877 == TRAVERSE_EXIT)
11878 return TRAVERSE_EXIT;
11879 }
11880 }
11881 }
e440a328 11882 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11883 return TRAVERSE_EXIT;
11884 return TRAVERSE_CONTINUE;
11885}
11886
11887// Return whether this is a constant initializer.
11888
11889bool
11890Struct_construction_expression::is_constant_struct() const
11891{
11892 if (this->vals_ == NULL)
11893 return true;
11894 for (Expression_list::const_iterator pv = this->vals_->begin();
11895 pv != this->vals_->end();
11896 ++pv)
11897 {
11898 if (*pv != NULL
11899 && !(*pv)->is_constant()
11900 && (!(*pv)->is_composite_literal()
11901 || (*pv)->is_nonconstant_composite_literal()))
11902 return false;
11903 }
11904
11905 const Struct_field_list* fields = this->type_->struct_type()->fields();
11906 for (Struct_field_list::const_iterator pf = fields->begin();
11907 pf != fields->end();
11908 ++pf)
11909 {
11910 // There are no constant constructors for interfaces.
11911 if (pf->type()->interface_type() != NULL)
11912 return false;
11913 }
11914
11915 return true;
11916}
11917
f9ca30f9 11918// Return whether this struct is immutable.
11919
11920bool
11921Struct_construction_expression::do_is_immutable() const
11922{
11923 if (this->vals_ == NULL)
11924 return true;
11925 for (Expression_list::const_iterator pv = this->vals_->begin();
11926 pv != this->vals_->end();
11927 ++pv)
11928 {
11929 if (*pv != NULL && !(*pv)->is_immutable())
11930 return false;
11931 }
11932 return true;
11933}
11934
e440a328 11935// Final type determination.
11936
11937void
11938Struct_construction_expression::do_determine_type(const Type_context*)
11939{
11940 if (this->vals_ == NULL)
11941 return;
11942 const Struct_field_list* fields = this->type_->struct_type()->fields();
11943 Expression_list::const_iterator pv = this->vals_->begin();
11944 for (Struct_field_list::const_iterator pf = fields->begin();
11945 pf != fields->end();
11946 ++pf, ++pv)
11947 {
11948 if (pv == this->vals_->end())
11949 return;
11950 if (*pv != NULL)
11951 {
11952 Type_context subcontext(pf->type(), false);
11953 (*pv)->determine_type(&subcontext);
11954 }
11955 }
a6cb4c0e 11956 // Extra values are an error we will report elsewhere; we still want
11957 // to determine the type to avoid knockon errors.
11958 for (; pv != this->vals_->end(); ++pv)
11959 (*pv)->determine_type_no_context();
e440a328 11960}
11961
11962// Check types.
11963
11964void
11965Struct_construction_expression::do_check_types(Gogo*)
11966{
11967 if (this->vals_ == NULL)
11968 return;
11969
11970 Struct_type* st = this->type_->struct_type();
11971 if (this->vals_->size() > st->field_count())
11972 {
11973 this->report_error(_("too many expressions for struct"));
11974 return;
11975 }
11976
11977 const Struct_field_list* fields = st->fields();
11978 Expression_list::const_iterator pv = this->vals_->begin();
11979 int i = 0;
11980 for (Struct_field_list::const_iterator pf = fields->begin();
11981 pf != fields->end();
11982 ++pf, ++pv, ++i)
11983 {
11984 if (pv == this->vals_->end())
11985 {
11986 this->report_error(_("too few expressions for struct"));
11987 break;
11988 }
11989
11990 if (*pv == NULL)
11991 continue;
11992
11993 std::string reason;
11994 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11995 {
11996 if (reason.empty())
11997 error_at((*pv)->location(),
11998 "incompatible type for field %d in struct construction",
11999 i + 1);
12000 else
12001 error_at((*pv)->location(),
12002 ("incompatible type for field %d in "
12003 "struct construction (%s)"),
12004 i + 1, reason.c_str());
12005 this->set_is_error();
12006 }
12007 }
c484d925 12008 go_assert(pv == this->vals_->end());
e440a328 12009}
12010
12011// Return a tree for constructing a struct.
12012
12013tree
12014Struct_construction_expression::do_get_tree(Translate_context* context)
12015{
12016 Gogo* gogo = context->gogo();
12017
2c809f8f 12018 Btype* btype = this->type_->get_backend(gogo);
e440a328 12019 if (this->vals_ == NULL)
2c809f8f 12020 return expr_to_tree(gogo->backend()->zero_expression(btype));
e440a328 12021
e440a328 12022 const Struct_field_list* fields = this->type_->struct_type()->fields();
e440a328 12023 Expression_list::const_iterator pv = this->vals_->begin();
2c809f8f 12024 std::vector<Bexpression*> init;
12025 for (Struct_field_list::const_iterator pf = fields->begin();
12026 pf != fields->end();
12027 ++pf)
e440a328 12028 {
63697958 12029 Btype* fbtype = pf->type()->get_backend(gogo);
e440a328 12030 if (pv == this->vals_->end())
2c809f8f 12031 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12032 else if (*pv == NULL)
12033 {
2c809f8f 12034 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12035 ++pv;
12036 }
12037 else
12038 {
2c809f8f 12039 Expression* val =
12040 Expression::convert_for_assignment(gogo, pf->type(),
12041 *pv, this->location());
12042 init.push_back(tree_to_expr(val->get_tree(context)));
e440a328 12043 ++pv;
12044 }
e440a328 12045 }
e440a328 12046
2c809f8f 12047 Bexpression* ret =
12048 gogo->backend()->constructor_expression(btype, init, this->location());
12049 return expr_to_tree(ret);
e440a328 12050}
12051
12052// Export a struct construction.
12053
12054void
12055Struct_construction_expression::do_export(Export* exp) const
12056{
12057 exp->write_c_string("convert(");
12058 exp->write_type(this->type_);
12059 for (Expression_list::const_iterator pv = this->vals_->begin();
12060 pv != this->vals_->end();
12061 ++pv)
12062 {
12063 exp->write_c_string(", ");
12064 if (*pv != NULL)
12065 (*pv)->export_expression(exp);
12066 }
12067 exp->write_c_string(")");
12068}
12069
d751bb78 12070// Dump ast representation of a struct construction expression.
12071
12072void
12073Struct_construction_expression::do_dump_expression(
12074 Ast_dump_context* ast_dump_context) const
12075{
d751bb78 12076 ast_dump_context->dump_type(this->type_);
12077 ast_dump_context->ostream() << "{";
12078 ast_dump_context->dump_expression_list(this->vals_);
12079 ast_dump_context->ostream() << "}";
12080}
12081
e440a328 12082// Make a struct composite literal. This used by the thunk code.
12083
12084Expression*
12085Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12086 Location location)
e440a328 12087{
c484d925 12088 go_assert(type->struct_type() != NULL);
e440a328 12089 return new Struct_construction_expression(type, vals, location);
12090}
12091
12092// Construct an array. This class is not used directly; instead we
12093// use the child classes, Fixed_array_construction_expression and
2c809f8f 12094// Slice_construction_expression.
e440a328 12095
12096class Array_construction_expression : public Expression
12097{
12098 protected:
12099 Array_construction_expression(Expression_classification classification,
ffe743ca 12100 Type* type,
12101 const std::vector<unsigned long>* indexes,
12102 Expression_list* vals, Location location)
e440a328 12103 : Expression(classification, location),
ffe743ca 12104 type_(type), indexes_(indexes), vals_(vals)
12105 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
e440a328 12106
12107 public:
12108 // Return whether this is a constant initializer.
12109 bool
12110 is_constant_array() const;
12111
12112 // Return the number of elements.
12113 size_t
12114 element_count() const
12115 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12116
12117protected:
12118 int
12119 do_traverse(Traverse* traverse);
12120
f9ca30f9 12121 bool
12122 do_is_immutable() const;
12123
e440a328 12124 Type*
12125 do_type()
12126 { return this->type_; }
12127
12128 void
12129 do_determine_type(const Type_context*);
12130
12131 void
12132 do_check_types(Gogo*);
12133
e440a328 12134 void
12135 do_export(Export*) const;
12136
ffe743ca 12137 // The indexes.
12138 const std::vector<unsigned long>*
12139 indexes()
12140 { return this->indexes_; }
12141
e440a328 12142 // The list of values.
12143 Expression_list*
12144 vals()
12145 { return this->vals_; }
12146
2c809f8f 12147 // Get the backend constructor for the array values.
12148 Bexpression*
12149 get_constructor(Translate_context* context, Btype* btype);
e440a328 12150
d751bb78 12151 void
12152 do_dump_expression(Ast_dump_context*) const;
12153
e440a328 12154 private:
12155 // The type of the array to construct.
12156 Type* type_;
ffe743ca 12157 // The list of indexes into the array, one for each value. This may
12158 // be NULL, in which case the indexes start at zero and increment.
12159 const std::vector<unsigned long>* indexes_;
12160 // The list of values. This may be NULL if there are no values.
e440a328 12161 Expression_list* vals_;
12162};
12163
12164// Traversal.
12165
12166int
12167Array_construction_expression::do_traverse(Traverse* traverse)
12168{
12169 if (this->vals_ != NULL
12170 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12171 return TRAVERSE_EXIT;
12172 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12173 return TRAVERSE_EXIT;
12174 return TRAVERSE_CONTINUE;
12175}
12176
12177// Return whether this is a constant initializer.
12178
12179bool
12180Array_construction_expression::is_constant_array() const
12181{
12182 if (this->vals_ == NULL)
12183 return true;
12184
12185 // There are no constant constructors for interfaces.
12186 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12187 return false;
12188
12189 for (Expression_list::const_iterator pv = this->vals_->begin();
12190 pv != this->vals_->end();
12191 ++pv)
12192 {
12193 if (*pv != NULL
12194 && !(*pv)->is_constant()
12195 && (!(*pv)->is_composite_literal()
12196 || (*pv)->is_nonconstant_composite_literal()))
12197 return false;
12198 }
12199 return true;
12200}
12201
f9ca30f9 12202// Return whether this is an immutable array initializer.
12203
12204bool
12205Array_construction_expression::do_is_immutable() const
12206{
12207 if (this->vals_ == NULL)
12208 return true;
12209 for (Expression_list::const_iterator pv = this->vals_->begin();
12210 pv != this->vals_->end();
12211 ++pv)
12212 {
12213 if (*pv != NULL && !(*pv)->is_immutable())
12214 return false;
12215 }
12216 return true;
12217}
12218
e440a328 12219// Final type determination.
12220
12221void
12222Array_construction_expression::do_determine_type(const Type_context*)
12223{
12224 if (this->vals_ == NULL)
12225 return;
12226 Type_context subcontext(this->type_->array_type()->element_type(), false);
12227 for (Expression_list::const_iterator pv = this->vals_->begin();
12228 pv != this->vals_->end();
12229 ++pv)
12230 {
12231 if (*pv != NULL)
12232 (*pv)->determine_type(&subcontext);
12233 }
12234}
12235
12236// Check types.
12237
12238void
12239Array_construction_expression::do_check_types(Gogo*)
12240{
12241 if (this->vals_ == NULL)
12242 return;
12243
12244 Array_type* at = this->type_->array_type();
12245 int i = 0;
12246 Type* element_type = at->element_type();
12247 for (Expression_list::const_iterator pv = this->vals_->begin();
12248 pv != this->vals_->end();
12249 ++pv, ++i)
12250 {
12251 if (*pv != NULL
12252 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12253 {
12254 error_at((*pv)->location(),
12255 "incompatible type for element %d in composite literal",
12256 i + 1);
12257 this->set_is_error();
12258 }
12259 }
e440a328 12260}
12261
2c809f8f 12262// Get a constructor expression for the array values.
e440a328 12263
2c809f8f 12264Bexpression*
12265Array_construction_expression::get_constructor(Translate_context* context,
12266 Btype* array_btype)
e440a328 12267{
e440a328 12268 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12269
12270 std::vector<unsigned long> indexes;
12271 std::vector<Bexpression*> vals;
12272 Gogo* gogo = context->gogo();
e440a328 12273 if (this->vals_ != NULL)
12274 {
12275 size_t i = 0;
ffe743ca 12276 std::vector<unsigned long>::const_iterator pi;
12277 if (this->indexes_ != NULL)
12278 pi = this->indexes_->begin();
e440a328 12279 for (Expression_list::const_iterator pv = this->vals_->begin();
12280 pv != this->vals_->end();
12281 ++pv, ++i)
12282 {
ffe743ca 12283 if (this->indexes_ != NULL)
12284 go_assert(pi != this->indexes_->end());
ffe743ca 12285
12286 if (this->indexes_ == NULL)
2c809f8f 12287 indexes.push_back(i);
ffe743ca 12288 else
2c809f8f 12289 indexes.push_back(*pi);
e440a328 12290 if (*pv == NULL)
63697958 12291 {
63697958 12292 Btype* ebtype = element_type->get_backend(gogo);
12293 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12294 vals.push_back(zv);
63697958 12295 }
e440a328 12296 else
12297 {
2c809f8f 12298 Expression* val_expr =
12299 Expression::convert_for_assignment(gogo, element_type, *pv,
12300 this->location());
12301 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
e440a328 12302 }
ffe743ca 12303 if (this->indexes_ != NULL)
12304 ++pi;
e440a328 12305 }
ffe743ca 12306 if (this->indexes_ != NULL)
12307 go_assert(pi == this->indexes_->end());
e440a328 12308 }
2c809f8f 12309 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12310 vals, this->location());
e440a328 12311}
12312
12313// Export an array construction.
12314
12315void
12316Array_construction_expression::do_export(Export* exp) const
12317{
12318 exp->write_c_string("convert(");
12319 exp->write_type(this->type_);
12320 if (this->vals_ != NULL)
12321 {
ffe743ca 12322 std::vector<unsigned long>::const_iterator pi;
12323 if (this->indexes_ != NULL)
12324 pi = this->indexes_->begin();
e440a328 12325 for (Expression_list::const_iterator pv = this->vals_->begin();
12326 pv != this->vals_->end();
12327 ++pv)
12328 {
12329 exp->write_c_string(", ");
ffe743ca 12330
12331 if (this->indexes_ != NULL)
12332 {
12333 char buf[100];
12334 snprintf(buf, sizeof buf, "%lu", *pi);
12335 exp->write_c_string(buf);
12336 exp->write_c_string(":");
12337 }
12338
e440a328 12339 if (*pv != NULL)
12340 (*pv)->export_expression(exp);
ffe743ca 12341
12342 if (this->indexes_ != NULL)
12343 ++pi;
e440a328 12344 }
12345 }
12346 exp->write_c_string(")");
12347}
12348
d751bb78 12349// Dump ast representation of an array construction expressin.
12350
12351void
12352Array_construction_expression::do_dump_expression(
12353 Ast_dump_context* ast_dump_context) const
12354{
ffe743ca 12355 Expression* length = this->type_->array_type()->length();
8b1c301d 12356
12357 ast_dump_context->ostream() << "[" ;
12358 if (length != NULL)
12359 {
12360 ast_dump_context->dump_expression(length);
12361 }
12362 ast_dump_context->ostream() << "]" ;
d751bb78 12363 ast_dump_context->dump_type(this->type_);
12364 ast_dump_context->ostream() << "{" ;
ffe743ca 12365 if (this->indexes_ == NULL)
12366 ast_dump_context->dump_expression_list(this->vals_);
12367 else
12368 {
12369 Expression_list::const_iterator pv = this->vals_->begin();
12370 for (std::vector<unsigned long>::const_iterator pi =
12371 this->indexes_->begin();
12372 pi != this->indexes_->end();
12373 ++pi, ++pv)
12374 {
12375 if (pi != this->indexes_->begin())
12376 ast_dump_context->ostream() << ", ";
12377 ast_dump_context->ostream() << *pi << ':';
12378 ast_dump_context->dump_expression(*pv);
12379 }
12380 }
d751bb78 12381 ast_dump_context->ostream() << "}" ;
12382
12383}
12384
e440a328 12385// Construct a fixed array.
12386
12387class Fixed_array_construction_expression :
12388 public Array_construction_expression
12389{
12390 public:
ffe743ca 12391 Fixed_array_construction_expression(Type* type,
12392 const std::vector<unsigned long>* indexes,
12393 Expression_list* vals, Location location)
e440a328 12394 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
ffe743ca 12395 type, indexes, vals, location)
12396 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12397
12398 protected:
12399 Expression*
12400 do_copy()
12401 {
12402 return new Fixed_array_construction_expression(this->type(),
ffe743ca 12403 this->indexes(),
e440a328 12404 (this->vals() == NULL
12405 ? NULL
12406 : this->vals()->copy()),
12407 this->location());
12408 }
12409
12410 tree
12411 do_get_tree(Translate_context*);
12412};
12413
12414// Return a tree for constructing a fixed array.
12415
12416tree
12417Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12418{
9f0e0513 12419 Type* type = this->type();
12420 Btype* btype = type->get_backend(context->gogo());
2c809f8f 12421 return expr_to_tree(this->get_constructor(context, btype));
e440a328 12422}
12423
76f85fd6 12424Expression*
12425Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12426 Location location)
12427{
12428 go_assert(type->array_type() != NULL && !type->is_slice_type());
12429 return new Fixed_array_construction_expression(type, NULL, vals, location);
12430}
12431
2c809f8f 12432// Construct a slice.
e440a328 12433
2c809f8f 12434class Slice_construction_expression : public Array_construction_expression
e440a328 12435{
12436 public:
2c809f8f 12437 Slice_construction_expression(Type* type,
12438 const std::vector<unsigned long>* indexes,
12439 Expression_list* vals, Location location)
12440 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12441 type, indexes, vals, location),
12442 valtype_(NULL)
ffe743ca 12443 { go_assert(type->is_slice_type()); }
e440a328 12444
12445 protected:
2c809f8f 12446 // Note that taking the address of a slice literal is invalid.
e440a328 12447
12448 Expression*
12449 do_copy()
12450 {
2c809f8f 12451 return new Slice_construction_expression(this->type(), this->indexes(),
12452 (this->vals() == NULL
12453 ? NULL
12454 : this->vals()->copy()),
12455 this->location());
e440a328 12456 }
12457
12458 tree
12459 do_get_tree(Translate_context*);
2c809f8f 12460
12461 private:
12462 // The type of the values in this slice.
12463 Type* valtype_;
e440a328 12464};
12465
2c809f8f 12466// Return a tree for constructing a slice.
e440a328 12467
12468tree
2c809f8f 12469Slice_construction_expression::do_get_tree(Translate_context* context)
e440a328 12470{
f9c68f17 12471 Array_type* array_type = this->type()->array_type();
12472 if (array_type == NULL)
12473 {
c484d925 12474 go_assert(this->type()->is_error());
f9c68f17 12475 return error_mark_node;
12476 }
12477
f23d7786 12478 Location loc = this->location();
f9c68f17 12479 Type* element_type = array_type->element_type();
2c809f8f 12480 if (this->valtype_ == NULL)
12481 {
12482 mpz_t lenval;
12483 Expression* length;
12484 if (this->vals() == NULL || this->vals()->empty())
12485 mpz_init_set_ui(lenval, 0);
12486 else
12487 {
12488 if (this->indexes() == NULL)
12489 mpz_init_set_ui(lenval, this->vals()->size());
12490 else
12491 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12492 }
2c809f8f 12493 Type* int_type = Type::lookup_integer_type("int");
12494 length = Expression::make_integer(&lenval, int_type, loc);
12495 mpz_clear(lenval);
12496 this->valtype_ = Type::make_array_type(element_type, length);
12497 }
3d60812e 12498
f23d7786 12499 Expression_list* vals = this->vals();
e440a328 12500 if (this->vals() == NULL || this->vals()->empty())
12501 {
f23d7786 12502 // We need to create a unique value for the empty array literal.
12503 vals = new Expression_list;
12504 vals->push_back(NULL);
e440a328 12505 }
f23d7786 12506 Expression* array_val =
12507 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12508 vals, loc);
e440a328 12509
f23d7786 12510 bool is_constant_initializer = array_val->is_immutable();
d8829beb 12511
12512 // We have to copy the initial values into heap memory if we are in
12513 // a function or if the values are not constants. We also have to
12514 // copy them if they may contain pointers in a non-constant context,
12515 // as otherwise the garbage collector won't see them.
12516 bool copy_to_heap = (context->function() != NULL
12517 || !is_constant_initializer
12518 || (element_type->has_pointer()
12519 && !context->is_const()));
e440a328 12520
f23d7786 12521 Expression* space;
d8829beb 12522 if (!copy_to_heap)
e440a328 12523 {
f23d7786 12524 // The initializer will only run once.
12525 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12526 space->unary_expression()->set_is_slice_init();
e440a328 12527 }
12528 else
f23d7786 12529 space = Expression::make_heap_expression(array_val, loc);
e440a328 12530
2c809f8f 12531 // Build a constructor for the slice.
e440a328 12532
f23d7786 12533 Expression* len = this->valtype_->array_type()->length();
12534 Expression* slice_val =
12535 Expression::make_slice_value(this->type(), space, len, len, loc);
12536 return slice_val->get_tree(context);
e440a328 12537}
12538
12539// Make a slice composite literal. This is used by the type
12540// descriptor code.
12541
12542Expression*
12543Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12544 Location location)
e440a328 12545{
411eb89e 12546 go_assert(type->is_slice_type());
2c809f8f 12547 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 12548}
12549
12550// Construct a map.
12551
12552class Map_construction_expression : public Expression
12553{
12554 public:
12555 Map_construction_expression(Type* type, Expression_list* vals,
b13c66cd 12556 Location location)
e440a328 12557 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
2c809f8f 12558 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
c484d925 12559 { go_assert(vals == NULL || vals->size() % 2 == 0); }
e440a328 12560
12561 protected:
12562 int
12563 do_traverse(Traverse* traverse);
12564
2c809f8f 12565 Expression*
12566 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12567
e440a328 12568 Type*
12569 do_type()
12570 { return this->type_; }
12571
12572 void
12573 do_determine_type(const Type_context*);
12574
12575 void
12576 do_check_types(Gogo*);
12577
12578 Expression*
12579 do_copy()
12580 {
12581 return new Map_construction_expression(this->type_, this->vals_->copy(),
12582 this->location());
12583 }
12584
12585 tree
12586 do_get_tree(Translate_context*);
12587
12588 void
12589 do_export(Export*) const;
12590
d751bb78 12591 void
12592 do_dump_expression(Ast_dump_context*) const;
12593
e440a328 12594 private:
12595 // The type of the map to construct.
12596 Type* type_;
12597 // The list of values.
12598 Expression_list* vals_;
2c809f8f 12599 // The type of the key-value pair struct for each map element.
12600 Struct_type* element_type_;
12601 // A temporary reference to the variable storing the constructor initializer.
12602 Temporary_statement* constructor_temp_;
e440a328 12603};
12604
12605// Traversal.
12606
12607int
12608Map_construction_expression::do_traverse(Traverse* traverse)
12609{
12610 if (this->vals_ != NULL
12611 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12612 return TRAVERSE_EXIT;
12613 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12614 return TRAVERSE_EXIT;
12615 return TRAVERSE_CONTINUE;
12616}
12617
2c809f8f 12618// Flatten constructor initializer into a temporary variable since
12619// we need to take its address for __go_construct_map.
12620
12621Expression*
12622Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12623 Statement_inserter* inserter)
12624{
12625 if (!this->is_error_expression()
12626 && this->vals_ != NULL
12627 && !this->vals_->empty()
12628 && this->constructor_temp_ == NULL)
12629 {
12630 Map_type* mt = this->type_->map_type();
12631 Type* key_type = mt->key_type();
12632 Type* val_type = mt->val_type();
12633 this->element_type_ = Type::make_builtin_struct_type(2,
12634 "__key", key_type,
12635 "__val", val_type);
12636
12637 Expression_list* value_pairs = new Expression_list();
12638 Location loc = this->location();
12639
12640 size_t i = 0;
12641 for (Expression_list::const_iterator pv = this->vals_->begin();
12642 pv != this->vals_->end();
12643 ++pv, ++i)
12644 {
12645 Expression_list* key_value_pair = new Expression_list();
12646 Expression* key =
12647 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12648
12649 ++pv;
12650 Expression* val =
12651 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12652
12653 key_value_pair->push_back(key);
12654 key_value_pair->push_back(val);
12655 value_pairs->push_back(
12656 Expression::make_struct_composite_literal(this->element_type_,
12657 key_value_pair, loc));
12658 }
12659
12660 mpz_t lenval;
12661 mpz_init_set_ui(lenval, i);
12662 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12663 mpz_clear(lenval);
12664
12665 Type* ctor_type =
12666 Type::make_array_type(this->element_type_, element_count);
12667 Expression* constructor =
12668 new Fixed_array_construction_expression(ctor_type, NULL,
12669 value_pairs, loc);
12670
12671 this->constructor_temp_ =
12672 Statement::make_temporary(NULL, constructor, loc);
12673 constructor->issue_nil_check();
12674 this->constructor_temp_->set_is_address_taken();
12675 inserter->insert(this->constructor_temp_);
12676 }
12677
12678 return this;
12679}
12680
e440a328 12681// Final type determination.
12682
12683void
12684Map_construction_expression::do_determine_type(const Type_context*)
12685{
12686 if (this->vals_ == NULL)
12687 return;
12688
12689 Map_type* mt = this->type_->map_type();
12690 Type_context key_context(mt->key_type(), false);
12691 Type_context val_context(mt->val_type(), false);
12692 for (Expression_list::const_iterator pv = this->vals_->begin();
12693 pv != this->vals_->end();
12694 ++pv)
12695 {
12696 (*pv)->determine_type(&key_context);
12697 ++pv;
12698 (*pv)->determine_type(&val_context);
12699 }
12700}
12701
12702// Check types.
12703
12704void
12705Map_construction_expression::do_check_types(Gogo*)
12706{
12707 if (this->vals_ == NULL)
12708 return;
12709
12710 Map_type* mt = this->type_->map_type();
12711 int i = 0;
12712 Type* key_type = mt->key_type();
12713 Type* val_type = mt->val_type();
12714 for (Expression_list::const_iterator pv = this->vals_->begin();
12715 pv != this->vals_->end();
12716 ++pv, ++i)
12717 {
12718 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12719 {
12720 error_at((*pv)->location(),
12721 "incompatible type for element %d key in map construction",
12722 i + 1);
12723 this->set_is_error();
12724 }
12725 ++pv;
12726 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12727 {
12728 error_at((*pv)->location(),
12729 ("incompatible type for element %d value "
12730 "in map construction"),
12731 i + 1);
12732 this->set_is_error();
12733 }
12734 }
12735}
12736
12737// Return a tree for constructing a map.
12738
12739tree
12740Map_construction_expression::do_get_tree(Translate_context* context)
12741{
2c809f8f 12742 if (this->is_error_expression())
5845bde6 12743 return error_mark_node;
2c809f8f 12744 Location loc = this->location();
e440a328 12745
e440a328 12746 size_t i = 0;
2c809f8f 12747 Expression* ventries;
e440a328 12748 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 12749 ventries = Expression::make_nil(loc);
e440a328 12750 else
12751 {
2c809f8f 12752 go_assert(this->constructor_temp_ != NULL);
12753 i = this->vals_->size() / 2;
e440a328 12754
2c809f8f 12755 Expression* ctor_ref =
12756 Expression::make_temporary_reference(this->constructor_temp_, loc);
12757 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12758 }
e440a328 12759
2c809f8f 12760 Map_type* mt = this->type_->map_type();
12761 if (this->element_type_ == NULL)
12762 this->element_type_ =
12763 Type::make_builtin_struct_type(2,
12764 "__key", mt->key_type(),
12765 "__val", mt->val_type());
12766 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12767
12768 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12769 mpz_t countval;
12770 mpz_init_set_ui(countval, i);
12771 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12772 mpz_clear(countval);
12773
12774 Expression* entry_size =
12775 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12776
12777 unsigned int field_index;
12778 const Struct_field* valfield =
12779 this->element_type_->find_local_field("__val", &field_index);
12780 Expression* val_offset =
12781 Expression::make_struct_field_offset(this->element_type_, valfield);
12782 Expression* val_size =
12783 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12784
12785 Expression* map_ctor =
12786 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12787 entry_size, val_offset, val_size, ventries);
12788 return map_ctor->get_tree(context);
12789}
e440a328 12790
2c809f8f 12791// Export an array construction.
e440a328 12792
2c809f8f 12793void
12794Map_construction_expression::do_export(Export* exp) const
12795{
12796 exp->write_c_string("convert(");
12797 exp->write_type(this->type_);
12798 for (Expression_list::const_iterator pv = this->vals_->begin();
12799 pv != this->vals_->end();
12800 ++pv)
12801 {
12802 exp->write_c_string(", ");
12803 (*pv)->export_expression(exp);
12804 }
12805 exp->write_c_string(")");
12806}
e440a328 12807
2c809f8f 12808// Dump ast representation for a map construction expression.
d751bb78 12809
12810void
12811Map_construction_expression::do_dump_expression(
12812 Ast_dump_context* ast_dump_context) const
12813{
d751bb78 12814 ast_dump_context->ostream() << "{" ;
8b1c301d 12815 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 12816 ast_dump_context->ostream() << "}";
12817}
12818
e440a328 12819// A general composite literal. This is lowered to a type specific
12820// version.
12821
12822class Composite_literal_expression : public Parser_expression
12823{
12824 public:
12825 Composite_literal_expression(Type* type, int depth, bool has_keys,
62750cd5 12826 Expression_list* vals, bool all_are_names,
12827 Location location)
e440a328 12828 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
62750cd5 12829 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12830 all_are_names_(all_are_names)
e440a328 12831 { }
12832
12833 protected:
12834 int
12835 do_traverse(Traverse* traverse);
12836
12837 Expression*
ceeb4318 12838 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 12839
12840 Expression*
12841 do_copy()
12842 {
12843 return new Composite_literal_expression(this->type_, this->depth_,
12844 this->has_keys_,
12845 (this->vals_ == NULL
12846 ? NULL
12847 : this->vals_->copy()),
62750cd5 12848 this->all_are_names_,
e440a328 12849 this->location());
12850 }
12851
d751bb78 12852 void
12853 do_dump_expression(Ast_dump_context*) const;
12854
e440a328 12855 private:
12856 Expression*
81c4b26b 12857 lower_struct(Gogo*, Type*);
e440a328 12858
12859 Expression*
113ef6a5 12860 lower_array(Type*);
e440a328 12861
12862 Expression*
ffe743ca 12863 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
e440a328 12864
12865 Expression*
ceeb4318 12866 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
e440a328 12867
12868 // The type of the composite literal.
12869 Type* type_;
12870 // The depth within a list of composite literals within a composite
12871 // literal, when the type is omitted.
12872 int depth_;
12873 // The values to put in the composite literal.
12874 Expression_list* vals_;
12875 // If this is true, then VALS_ is a list of pairs: a key and a
12876 // value. In an array initializer, a missing key will be NULL.
12877 bool has_keys_;
62750cd5 12878 // If this is true, then HAS_KEYS_ is true, and every key is a
12879 // simple identifier.
12880 bool all_are_names_;
e440a328 12881};
12882
12883// Traversal.
12884
12885int
12886Composite_literal_expression::do_traverse(Traverse* traverse)
12887{
dbffccfc 12888 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 12889 return TRAVERSE_EXIT;
dbffccfc 12890
12891 // If this is a struct composite literal with keys, then the keys
12892 // are field names, not expressions. We don't want to traverse them
12893 // in that case. If we do, we can give an erroneous error "variable
12894 // initializer refers to itself." See bug482.go in the testsuite.
12895 if (this->has_keys_ && this->vals_ != NULL)
12896 {
12897 // The type may not be resolvable at this point.
12898 Type* type = this->type_;
a01f2481 12899
12900 for (int depth = this->depth_; depth > 0; --depth)
12901 {
12902 if (type->array_type() != NULL)
12903 type = type->array_type()->element_type();
12904 else if (type->map_type() != NULL)
12905 type = type->map_type()->val_type();
12906 else
12907 {
12908 // This error will be reported during lowering.
12909 return TRAVERSE_CONTINUE;
12910 }
12911 }
12912
dbffccfc 12913 while (true)
12914 {
12915 if (type->classification() == Type::TYPE_NAMED)
12916 type = type->named_type()->real_type();
12917 else if (type->classification() == Type::TYPE_FORWARD)
12918 {
12919 Type* t = type->forwarded();
12920 if (t == type)
12921 break;
12922 type = t;
12923 }
12924 else
12925 break;
12926 }
12927
12928 if (type->classification() == Type::TYPE_STRUCT)
12929 {
12930 Expression_list::iterator p = this->vals_->begin();
12931 while (p != this->vals_->end())
12932 {
12933 // Skip key.
12934 ++p;
12935 go_assert(p != this->vals_->end());
12936 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12937 return TRAVERSE_EXIT;
12938 ++p;
12939 }
12940 return TRAVERSE_CONTINUE;
12941 }
12942 }
12943
12944 if (this->vals_ != NULL)
12945 return this->vals_->traverse(traverse);
12946
12947 return TRAVERSE_CONTINUE;
e440a328 12948}
12949
12950// Lower a generic composite literal into a specific version based on
12951// the type.
12952
12953Expression*
ceeb4318 12954Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12955 Statement_inserter* inserter, int)
e440a328 12956{
12957 Type* type = this->type_;
12958
12959 for (int depth = this->depth_; depth > 0; --depth)
12960 {
12961 if (type->array_type() != NULL)
12962 type = type->array_type()->element_type();
12963 else if (type->map_type() != NULL)
12964 type = type->map_type()->val_type();
12965 else
12966 {
5c13bd80 12967 if (!type->is_error())
e440a328 12968 error_at(this->location(),
12969 ("may only omit types within composite literals "
12970 "of slice, array, or map type"));
12971 return Expression::make_error(this->location());
12972 }
12973 }
12974
e00772b3 12975 Type *pt = type->points_to();
12976 bool is_pointer = false;
12977 if (pt != NULL)
12978 {
12979 is_pointer = true;
12980 type = pt;
12981 }
12982
12983 Expression* ret;
5c13bd80 12984 if (type->is_error())
e440a328 12985 return Expression::make_error(this->location());
12986 else if (type->struct_type() != NULL)
e00772b3 12987 ret = this->lower_struct(gogo, type);
e440a328 12988 else if (type->array_type() != NULL)
113ef6a5 12989 ret = this->lower_array(type);
e440a328 12990 else if (type->map_type() != NULL)
e00772b3 12991 ret = this->lower_map(gogo, function, inserter, type);
e440a328 12992 else
12993 {
12994 error_at(this->location(),
12995 ("expected struct, slice, array, or map type "
12996 "for composite literal"));
12997 return Expression::make_error(this->location());
12998 }
e00772b3 12999
13000 if (is_pointer)
2c809f8f 13001 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13002
13003 return ret;
e440a328 13004}
13005
13006// Lower a struct composite literal.
13007
13008Expression*
81c4b26b 13009Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13010{
b13c66cd 13011 Location location = this->location();
e440a328 13012 Struct_type* st = type->struct_type();
13013 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13014 {
e6013c28 13015 if (this->vals_ != NULL
13016 && !this->vals_->empty()
13017 && type->named_type() != NULL
13018 && type->named_type()->named_object()->package() != NULL)
13019 {
13020 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13021 pf != st->fields()->end();
13022 ++pf)
07daa4e7 13023 {
e6013c28 13024 if (Gogo::is_hidden_name(pf->field_name()))
07daa4e7 13025 error_at(this->location(),
e6013c28 13026 "assignment of unexported field %qs in %qs literal",
13027 Gogo::message_name(pf->field_name()).c_str(),
13028 type->named_type()->message_name().c_str());
07daa4e7 13029 }
13030 }
13031
13032 return new Struct_construction_expression(type, this->vals_, location);
13033 }
e440a328 13034
13035 size_t field_count = st->field_count();
13036 std::vector<Expression*> vals(field_count);
0c4f5a19 13037 std::vector<int>* traverse_order = new(std::vector<int>);
e440a328 13038 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13039 Expression* external_expr = NULL;
13040 const Named_object* external_no = NULL;
e440a328 13041 while (p != this->vals_->end())
13042 {
13043 Expression* name_expr = *p;
13044
13045 ++p;
c484d925 13046 go_assert(p != this->vals_->end());
e440a328 13047 Expression* val = *p;
13048
13049 ++p;
13050
13051 if (name_expr == NULL)
13052 {
13053 error_at(val->location(), "mixture of field and value initializers");
13054 return Expression::make_error(location);
13055 }
13056
13057 bool bad_key = false;
13058 std::string name;
81c4b26b 13059 const Named_object* no = NULL;
e440a328 13060 switch (name_expr->classification())
13061 {
13062 case EXPRESSION_UNKNOWN_REFERENCE:
13063 name = name_expr->unknown_expression()->name();
13064 break;
13065
13066 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13067 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13068 break;
13069
13070 case EXPRESSION_TYPE:
13071 {
13072 Type* t = name_expr->type();
13073 Named_type* nt = t->named_type();
13074 if (nt == NULL)
13075 bad_key = true;
13076 else
81c4b26b 13077 no = nt->named_object();
e440a328 13078 }
13079 break;
13080
13081 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13082 no = name_expr->var_expression()->named_object();
e440a328 13083 break;
13084
13085 case EXPRESSION_FUNC_REFERENCE:
81c4b26b 13086 no = name_expr->func_expression()->named_object();
e440a328 13087 break;
13088
13089 case EXPRESSION_UNARY:
13090 // If there is a local variable around with the same name as
13091 // the field, and this occurs in the closure, then the
13092 // parser may turn the field reference into an indirection
13093 // through the closure. FIXME: This is a mess.
13094 {
13095 bad_key = true;
13096 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13097 if (ue->op() == OPERATOR_MULT)
13098 {
13099 Field_reference_expression* fre =
13100 ue->operand()->field_reference_expression();
13101 if (fre != NULL)
13102 {
13103 Struct_type* st =
13104 fre->expr()->type()->deref()->struct_type();
13105 if (st != NULL)
13106 {
13107 const Struct_field* sf = st->field(fre->field_index());
13108 name = sf->field_name();
2d29d278 13109
13110 // See below. FIXME.
13111 if (!Gogo::is_hidden_name(name)
13112 && name[0] >= 'a'
13113 && name[0] <= 'z')
13114 {
13115 if (gogo->lookup_global(name.c_str()) != NULL)
13116 name = gogo->pack_hidden_name(name, false);
13117 }
13118
e440a328 13119 char buf[20];
13120 snprintf(buf, sizeof buf, "%u", fre->field_index());
13121 size_t buflen = strlen(buf);
13122 if (name.compare(name.length() - buflen, buflen, buf)
13123 == 0)
13124 {
13125 name = name.substr(0, name.length() - buflen);
13126 bad_key = false;
13127 }
13128 }
13129 }
13130 }
13131 }
13132 break;
13133
13134 default:
13135 bad_key = true;
13136 break;
13137 }
13138 if (bad_key)
13139 {
13140 error_at(name_expr->location(), "expected struct field name");
13141 return Expression::make_error(location);
13142 }
13143
81c4b26b 13144 if (no != NULL)
13145 {
62750cd5 13146 if (no->package() != NULL && external_expr == NULL)
13147 {
13148 external_expr = name_expr;
13149 external_no = no;
13150 }
13151
81c4b26b 13152 name = no->name();
13153
13154 // A predefined name won't be packed. If it starts with a
13155 // lower case letter we need to check for that case, because
2d29d278 13156 // the field name will be packed. FIXME.
81c4b26b 13157 if (!Gogo::is_hidden_name(name)
13158 && name[0] >= 'a'
13159 && name[0] <= 'z')
13160 {
13161 Named_object* gno = gogo->lookup_global(name.c_str());
13162 if (gno == no)
13163 name = gogo->pack_hidden_name(name, false);
13164 }
13165 }
13166
e440a328 13167 unsigned int index;
13168 const Struct_field* sf = st->find_local_field(name, &index);
13169 if (sf == NULL)
13170 {
13171 error_at(name_expr->location(), "unknown field %qs in %qs",
13172 Gogo::message_name(name).c_str(),
13173 (type->named_type() != NULL
13174 ? type->named_type()->message_name().c_str()
13175 : "unnamed struct"));
13176 return Expression::make_error(location);
13177 }
13178 if (vals[index] != NULL)
13179 {
13180 error_at(name_expr->location(),
13181 "duplicate value for field %qs in %qs",
13182 Gogo::message_name(name).c_str(),
13183 (type->named_type() != NULL
13184 ? type->named_type()->message_name().c_str()
13185 : "unnamed struct"));
13186 return Expression::make_error(location);
13187 }
13188
07daa4e7 13189 if (type->named_type() != NULL
13190 && type->named_type()->named_object()->package() != NULL
13191 && Gogo::is_hidden_name(sf->field_name()))
13192 error_at(name_expr->location(),
13193 "assignment of unexported field %qs in %qs literal",
13194 Gogo::message_name(sf->field_name()).c_str(),
13195 type->named_type()->message_name().c_str());
07daa4e7 13196
e440a328 13197 vals[index] = val;
0c4f5a19 13198 traverse_order->push_back(index);
e440a328 13199 }
13200
62750cd5 13201 if (!this->all_are_names_)
13202 {
13203 // This is a weird case like bug462 in the testsuite.
13204 if (external_expr == NULL)
13205 error_at(this->location(), "unknown field in %qs literal",
13206 (type->named_type() != NULL
13207 ? type->named_type()->message_name().c_str()
13208 : "unnamed struct"));
13209 else
13210 error_at(external_expr->location(), "unknown field %qs in %qs",
13211 external_no->message_name().c_str(),
13212 (type->named_type() != NULL
13213 ? type->named_type()->message_name().c_str()
13214 : "unnamed struct"));
13215 return Expression::make_error(location);
13216 }
13217
e440a328 13218 Expression_list* list = new Expression_list;
13219 list->reserve(field_count);
13220 for (size_t i = 0; i < field_count; ++i)
13221 list->push_back(vals[i]);
13222
0c4f5a19 13223 Struct_construction_expression* ret =
13224 new Struct_construction_expression(type, list, location);
13225 ret->set_traverse_order(traverse_order);
13226 return ret;
e440a328 13227}
13228
00773463 13229// Used to sort an index/value array.
13230
13231class Index_value_compare
13232{
13233 public:
13234 bool
13235 operator()(const std::pair<unsigned long, Expression*>& a,
13236 const std::pair<unsigned long, Expression*>& b)
13237 { return a.first < b.first; }
13238};
13239
e440a328 13240// Lower an array composite literal.
13241
13242Expression*
113ef6a5 13243Composite_literal_expression::lower_array(Type* type)
e440a328 13244{
b13c66cd 13245 Location location = this->location();
e440a328 13246 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13247 return this->make_array(type, NULL, this->vals_);
e440a328 13248
ffe743ca 13249 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13250 indexes->reserve(this->vals_->size());
00773463 13251 bool indexes_out_of_order = false;
ffe743ca 13252 Expression_list* vals = new Expression_list();
13253 vals->reserve(this->vals_->size());
e440a328 13254 unsigned long index = 0;
13255 Expression_list::const_iterator p = this->vals_->begin();
13256 while (p != this->vals_->end())
13257 {
13258 Expression* index_expr = *p;
13259
13260 ++p;
c484d925 13261 go_assert(p != this->vals_->end());
e440a328 13262 Expression* val = *p;
13263
13264 ++p;
13265
ffe743ca 13266 if (index_expr == NULL)
13267 {
13268 if (!indexes->empty())
13269 indexes->push_back(index);
13270 }
13271 else
e440a328 13272 {
ffe743ca 13273 if (indexes->empty() && !vals->empty())
13274 {
13275 for (size_t i = 0; i < vals->size(); ++i)
13276 indexes->push_back(i);
13277 }
13278
0c77715b 13279 Numeric_constant nc;
13280 if (!index_expr->numeric_constant_value(&nc))
e440a328 13281 {
e440a328 13282 error_at(index_expr->location(),
13283 "index expression is not integer constant");
13284 return Expression::make_error(location);
13285 }
6f6d9955 13286
0c77715b 13287 switch (nc.to_unsigned_long(&index))
e440a328 13288 {
0c77715b 13289 case Numeric_constant::NC_UL_VALID:
13290 break;
13291 case Numeric_constant::NC_UL_NOTINT:
13292 error_at(index_expr->location(),
13293 "index expression is not integer constant");
13294 return Expression::make_error(location);
13295 case Numeric_constant::NC_UL_NEGATIVE:
e440a328 13296 error_at(index_expr->location(), "index expression is negative");
13297 return Expression::make_error(location);
0c77715b 13298 case Numeric_constant::NC_UL_BIG:
e440a328 13299 error_at(index_expr->location(), "index value overflow");
13300 return Expression::make_error(location);
0c77715b 13301 default:
13302 go_unreachable();
e440a328 13303 }
6f6d9955 13304
13305 Named_type* ntype = Type::lookup_integer_type("int");
13306 Integer_type* inttype = ntype->integer_type();
0c77715b 13307 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13308 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13309 {
6f6d9955 13310 error_at(index_expr->location(), "index value overflow");
13311 return Expression::make_error(location);
13312 }
13313
ffe743ca 13314 if (std::find(indexes->begin(), indexes->end(), index)
13315 != indexes->end())
e440a328 13316 {
ffe743ca 13317 error_at(index_expr->location(), "duplicate value for index %lu",
e440a328 13318 index);
13319 return Expression::make_error(location);
13320 }
ffe743ca 13321
00773463 13322 if (!indexes->empty() && index < indexes->back())
13323 indexes_out_of_order = true;
13324
ffe743ca 13325 indexes->push_back(index);
e440a328 13326 }
13327
ffe743ca 13328 vals->push_back(val);
13329
e440a328 13330 ++index;
13331 }
13332
ffe743ca 13333 if (indexes->empty())
13334 {
13335 delete indexes;
13336 indexes = NULL;
13337 }
e440a328 13338
00773463 13339 if (indexes_out_of_order)
13340 {
13341 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13342
13343 V v;
13344 v.reserve(indexes->size());
13345 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13346 for (Expression_list::const_iterator pe = vals->begin();
13347 pe != vals->end();
13348 ++pe, ++pi)
13349 v.push_back(std::make_pair(*pi, *pe));
13350
13351 std::sort(v.begin(), v.end(), Index_value_compare());
13352
13353 delete indexes;
13354 delete vals;
13355 indexes = new std::vector<unsigned long>();
13356 indexes->reserve(v.size());
13357 vals = new Expression_list();
13358 vals->reserve(v.size());
13359
13360 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13361 {
13362 indexes->push_back(p->first);
13363 vals->push_back(p->second);
13364 }
13365 }
13366
ffe743ca 13367 return this->make_array(type, indexes, vals);
e440a328 13368}
13369
13370// Actually build the array composite literal. This handles
13371// [...]{...}.
13372
13373Expression*
ffe743ca 13374Composite_literal_expression::make_array(
13375 Type* type,
13376 const std::vector<unsigned long>* indexes,
13377 Expression_list* vals)
e440a328 13378{
b13c66cd 13379 Location location = this->location();
e440a328 13380 Array_type* at = type->array_type();
ffe743ca 13381
e440a328 13382 if (at->length() != NULL && at->length()->is_nil_expression())
13383 {
ffe743ca 13384 size_t size;
13385 if (vals == NULL)
13386 size = 0;
00773463 13387 else if (indexes != NULL)
13388 size = indexes->back() + 1;
13389 else
ffe743ca 13390 {
13391 size = vals->size();
13392 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13393 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13394 && size >> (it->bits() - 1) != 0)
13395 {
13396 error_at(location, "too many elements in composite literal");
13397 return Expression::make_error(location);
13398 }
13399 }
ffe743ca 13400
e440a328 13401 mpz_t vlen;
13402 mpz_init_set_ui(vlen, size);
13403 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13404 mpz_clear(vlen);
13405 at = Type::make_array_type(at->element_type(), elen);
13406 type = at;
13407 }
ffe743ca 13408 else if (at->length() != NULL
13409 && !at->length()->is_error_expression()
13410 && this->vals_ != NULL)
13411 {
13412 Numeric_constant nc;
13413 unsigned long val;
13414 if (at->length()->numeric_constant_value(&nc)
13415 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13416 {
13417 if (indexes == NULL)
13418 {
13419 if (this->vals_->size() > val)
13420 {
13421 error_at(location, "too many elements in composite literal");
13422 return Expression::make_error(location);
13423 }
13424 }
13425 else
13426 {
00773463 13427 unsigned long max = indexes->back();
ffe743ca 13428 if (max >= val)
13429 {
13430 error_at(location,
13431 ("some element keys in composite literal "
13432 "are out of range"));
13433 return Expression::make_error(location);
13434 }
13435 }
13436 }
13437 }
13438
e440a328 13439 if (at->length() != NULL)
ffe743ca 13440 return new Fixed_array_construction_expression(type, indexes, vals,
13441 location);
e440a328 13442 else
2c809f8f 13443 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13444}
13445
13446// Lower a map composite literal.
13447
13448Expression*
a287720d 13449Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13450 Statement_inserter* inserter,
a287720d 13451 Type* type)
e440a328 13452{
b13c66cd 13453 Location location = this->location();
e440a328 13454 if (this->vals_ != NULL)
13455 {
13456 if (!this->has_keys_)
13457 {
13458 error_at(location, "map composite literal must have keys");
13459 return Expression::make_error(location);
13460 }
13461
a287720d 13462 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13463 p != this->vals_->end();
13464 p += 2)
13465 {
13466 if (*p == NULL)
13467 {
13468 ++p;
13469 error_at((*p)->location(),
13470 "map composite literal must have keys for every value");
13471 return Expression::make_error(location);
13472 }
a287720d 13473 // Make sure we have lowered the key; it may not have been
13474 // lowered in order to handle keys for struct composite
13475 // literals. Lower it now to get the right error message.
13476 if ((*p)->unknown_expression() != NULL)
13477 {
13478 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13479 gogo->lower_expression(function, inserter, &*p);
c484d925 13480 go_assert((*p)->is_error_expression());
a287720d 13481 return Expression::make_error(location);
13482 }
e440a328 13483 }
13484 }
13485
13486 return new Map_construction_expression(type, this->vals_, location);
13487}
13488
d751bb78 13489// Dump ast representation for a composite literal expression.
13490
13491void
13492Composite_literal_expression::do_dump_expression(
13493 Ast_dump_context* ast_dump_context) const
13494{
8b1c301d 13495 ast_dump_context->ostream() << "composite(";
d751bb78 13496 ast_dump_context->dump_type(this->type_);
13497 ast_dump_context->ostream() << ", {";
8b1c301d 13498 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13499 ast_dump_context->ostream() << "})";
13500}
13501
e440a328 13502// Make a composite literal expression.
13503
13504Expression*
13505Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13506 Expression_list* vals, bool all_are_names,
b13c66cd 13507 Location location)
e440a328 13508{
13509 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13510 all_are_names, location);
e440a328 13511}
13512
13513// Return whether this expression is a composite literal.
13514
13515bool
13516Expression::is_composite_literal() const
13517{
13518 switch (this->classification_)
13519 {
13520 case EXPRESSION_COMPOSITE_LITERAL:
13521 case EXPRESSION_STRUCT_CONSTRUCTION:
13522 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13523 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13524 case EXPRESSION_MAP_CONSTRUCTION:
13525 return true;
13526 default:
13527 return false;
13528 }
13529}
13530
13531// Return whether this expression is a composite literal which is not
13532// constant.
13533
13534bool
13535Expression::is_nonconstant_composite_literal() const
13536{
13537 switch (this->classification_)
13538 {
13539 case EXPRESSION_STRUCT_CONSTRUCTION:
13540 {
13541 const Struct_construction_expression *psce =
13542 static_cast<const Struct_construction_expression*>(this);
13543 return !psce->is_constant_struct();
13544 }
13545 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13546 {
13547 const Fixed_array_construction_expression *pace =
13548 static_cast<const Fixed_array_construction_expression*>(this);
13549 return !pace->is_constant_array();
13550 }
2c809f8f 13551 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13552 {
2c809f8f 13553 const Slice_construction_expression *pace =
13554 static_cast<const Slice_construction_expression*>(this);
e440a328 13555 return !pace->is_constant_array();
13556 }
13557 case EXPRESSION_MAP_CONSTRUCTION:
13558 return true;
13559 default:
13560 return false;
13561 }
13562}
13563
35a54f17 13564// Return true if this is a variable or temporary_variable.
13565
13566bool
13567Expression::is_variable() const
13568{
13569 switch (this->classification_)
13570 {
13571 case EXPRESSION_VAR_REFERENCE:
13572 case EXPRESSION_TEMPORARY_REFERENCE:
13573 case EXPRESSION_SET_AND_USE_TEMPORARY:
13574 return true;
13575 default:
13576 return false;
13577 }
13578}
13579
e440a328 13580// Return true if this is a reference to a local variable.
13581
13582bool
13583Expression::is_local_variable() const
13584{
13585 const Var_expression* ve = this->var_expression();
13586 if (ve == NULL)
13587 return false;
13588 const Named_object* no = ve->named_object();
13589 return (no->is_result_variable()
13590 || (no->is_variable() && !no->var_value()->is_global()));
13591}
13592
13593// Class Type_guard_expression.
13594
13595// Traversal.
13596
13597int
13598Type_guard_expression::do_traverse(Traverse* traverse)
13599{
13600 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13601 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13602 return TRAVERSE_EXIT;
13603 return TRAVERSE_CONTINUE;
13604}
13605
2c809f8f 13606Expression*
13607Type_guard_expression::do_flatten(Gogo*, Named_object*,
13608 Statement_inserter* inserter)
13609{
13610 if (!this->expr_->is_variable())
13611 {
13612 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13613 this->location());
13614 inserter->insert(temp);
13615 this->expr_ =
13616 Expression::make_temporary_reference(temp, this->location());
13617 }
13618 return this;
13619}
13620
e440a328 13621// Check types of a type guard expression. The expression must have
13622// an interface type, but the actual type conversion is checked at run
13623// time.
13624
13625void
13626Type_guard_expression::do_check_types(Gogo*)
13627{
e440a328 13628 Type* expr_type = this->expr_->type();
7e9da23f 13629 if (expr_type->interface_type() == NULL)
f725ade8 13630 {
5c13bd80 13631 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 13632 this->report_error(_("type assertion only valid for interface types"));
13633 this->set_is_error();
13634 }
e440a328 13635 else if (this->type_->interface_type() == NULL)
13636 {
13637 std::string reason;
13638 if (!expr_type->interface_type()->implements_interface(this->type_,
13639 &reason))
13640 {
5c13bd80 13641 if (!this->type_->is_error())
e440a328 13642 {
f725ade8 13643 if (reason.empty())
13644 this->report_error(_("impossible type assertion: "
13645 "type does not implement interface"));
13646 else
13647 error_at(this->location(),
13648 ("impossible type assertion: "
13649 "type does not implement interface (%s)"),
13650 reason.c_str());
e440a328 13651 }
f725ade8 13652 this->set_is_error();
e440a328 13653 }
13654 }
13655}
13656
13657// Return a tree for a type guard expression.
13658
13659tree
13660Type_guard_expression::do_get_tree(Translate_context* context)
13661{
2c809f8f 13662 Expression* conversion;
7e9da23f 13663 if (this->type_->interface_type() != NULL)
2c809f8f 13664 conversion =
13665 Expression::convert_interface_to_interface(this->type_, this->expr_,
13666 true, this->location());
e440a328 13667 else
2c809f8f 13668 conversion =
13669 Expression::convert_for_assignment(context->gogo(), this->type_,
13670 this->expr_, this->location());
13671
13672 return conversion->get_tree(context);
e440a328 13673}
13674
d751bb78 13675// Dump ast representation for a type guard expression.
13676
13677void
2c809f8f 13678Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 13679 const
13680{
13681 this->expr_->dump_expression(ast_dump_context);
13682 ast_dump_context->ostream() << ".";
13683 ast_dump_context->dump_type(this->type_);
13684}
13685
e440a328 13686// Make a type guard expression.
13687
13688Expression*
13689Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 13690 Location location)
e440a328 13691{
13692 return new Type_guard_expression(expr, type, location);
13693}
13694
2c809f8f 13695// Class Heap_expression.
e440a328 13696
2c809f8f 13697// When you take the address of an escaping expression, it is allocated
e440a328 13698// on the heap. This class implements that.
13699
2c809f8f 13700class Heap_expression : public Expression
e440a328 13701{
13702 public:
2c809f8f 13703 Heap_expression(Expression* expr, Location location)
13704 : Expression(EXPRESSION_HEAP, location),
e440a328 13705 expr_(expr)
13706 { }
13707
13708 protected:
13709 int
13710 do_traverse(Traverse* traverse)
13711 { return Expression::traverse(&this->expr_, traverse); }
13712
13713 Type*
13714 do_type()
13715 { return Type::make_pointer_type(this->expr_->type()); }
13716
13717 void
13718 do_determine_type(const Type_context*)
13719 { this->expr_->determine_type_no_context(); }
13720
13721 Expression*
13722 do_copy()
13723 {
2c809f8f 13724 return Expression::make_heap_expression(this->expr_->copy(),
13725 this->location());
e440a328 13726 }
13727
13728 tree
13729 do_get_tree(Translate_context*);
13730
13731 // We only export global objects, and the parser does not generate
13732 // this in global scope.
13733 void
13734 do_export(Export*) const
c3e6f413 13735 { go_unreachable(); }
e440a328 13736
d751bb78 13737 void
13738 do_dump_expression(Ast_dump_context*) const;
13739
e440a328 13740 private:
2c809f8f 13741 // The expression which is being put on the heap.
e440a328 13742 Expression* expr_;
13743};
13744
2c809f8f 13745// Return a tree which allocates an expression on the heap.
e440a328 13746
13747tree
2c809f8f 13748Heap_expression::do_get_tree(Translate_context* context)
e440a328 13749{
02c19a1a 13750 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
e440a328 13751 return error_mark_node;
2c809f8f 13752
02c19a1a 13753 Location loc = this->location();
2c809f8f 13754 Gogo* gogo = context->gogo();
02c19a1a 13755 Btype* btype = this->type()->get_backend(gogo);
13756 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
13757 Bexpression* space = tree_to_expr(alloc->get_tree(context));
13758
13759 Bstatement* decl;
13760 Named_object* fn = context->function();
13761 go_assert(fn != NULL);
13762 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13763 Bvariable* space_temp =
13764 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13765 space, true, loc, &decl);
13766 space = gogo->backend()->var_expression(space_temp, loc);
9b27b43c 13767 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13768 Bexpression* ref =
13769 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
02c19a1a 13770
13771 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
13772 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13773 decl = gogo->backend()->compound_statement(decl, assn);
13774 space = gogo->backend()->var_expression(space_temp, loc);
13775 Bexpression* ret = gogo->backend()->compound_expression(decl, space, loc);
13776 return expr_to_tree(ret);
e440a328 13777}
13778
2c809f8f 13779// Dump ast representation for a heap expression.
d751bb78 13780
13781void
2c809f8f 13782Heap_expression::do_dump_expression(
d751bb78 13783 Ast_dump_context* ast_dump_context) const
13784{
13785 ast_dump_context->ostream() << "&(";
13786 ast_dump_context->dump_expression(this->expr_);
13787 ast_dump_context->ostream() << ")";
13788}
13789
2c809f8f 13790// Allocate an expression on the heap.
e440a328 13791
13792Expression*
2c809f8f 13793Expression::make_heap_expression(Expression* expr, Location location)
e440a328 13794{
2c809f8f 13795 return new Heap_expression(expr, location);
e440a328 13796}
13797
13798// Class Receive_expression.
13799
13800// Return the type of a receive expression.
13801
13802Type*
13803Receive_expression::do_type()
13804{
13805 Channel_type* channel_type = this->channel_->type()->channel_type();
13806 if (channel_type == NULL)
13807 return Type::make_error_type();
13808 return channel_type->element_type();
13809}
13810
13811// Check types for a receive expression.
13812
13813void
13814Receive_expression::do_check_types(Gogo*)
13815{
13816 Type* type = this->channel_->type();
5c13bd80 13817 if (type->is_error())
e440a328 13818 {
13819 this->set_is_error();
13820 return;
13821 }
13822 if (type->channel_type() == NULL)
13823 {
13824 this->report_error(_("expected channel"));
13825 return;
13826 }
13827 if (!type->channel_type()->may_receive())
13828 {
13829 this->report_error(_("invalid receive on send-only channel"));
13830 return;
13831 }
13832}
13833
2c809f8f 13834// Flattening for receive expressions creates a temporary variable to store
13835// received data in for receives.
13836
13837Expression*
13838Receive_expression::do_flatten(Gogo*, Named_object*,
13839 Statement_inserter* inserter)
13840{
13841 Channel_type* channel_type = this->channel_->type()->channel_type();
13842 if (channel_type == NULL)
13843 {
13844 go_assert(saw_errors());
13845 return this;
13846 }
13847
13848 Type* element_type = channel_type->element_type();
13849 if (this->temp_receiver_ == NULL)
13850 {
13851 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13852 this->location());
13853 this->temp_receiver_->set_is_address_taken();
13854 inserter->insert(this->temp_receiver_);
13855 }
13856
13857 return this;
13858}
13859
e440a328 13860// Get a tree for a receive expression.
13861
13862tree
13863Receive_expression::do_get_tree(Translate_context* context)
13864{
f24f10bb 13865 Location loc = this->location();
13866
e440a328 13867 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 13868 if (channel_type == NULL)
13869 {
c484d925 13870 go_assert(this->channel_->type()->is_error());
5b8368f4 13871 return error_mark_node;
13872 }
f24f10bb 13873 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 13874
2c809f8f 13875 Expression* recv_ref =
13876 Expression::make_temporary_reference(this->temp_receiver_, loc);
13877 Expression* recv_addr =
13878 Expression::make_temporary_reference(this->temp_receiver_, loc);
13879 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13880 Expression* recv =
13881 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13882 td, this->channel_, recv_addr);
13883 recv = Expression::make_compound(recv, recv_ref, loc);
13884 return recv->get_tree(context);
e440a328 13885}
13886
d751bb78 13887// Dump ast representation for a receive expression.
13888
13889void
13890Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13891{
13892 ast_dump_context->ostream() << " <- " ;
13893 ast_dump_context->dump_expression(channel_);
13894}
13895
e440a328 13896// Make a receive expression.
13897
13898Receive_expression*
b13c66cd 13899Expression::make_receive(Expression* channel, Location location)
e440a328 13900{
13901 return new Receive_expression(channel, location);
13902}
13903
e440a328 13904// An expression which evaluates to a pointer to the type descriptor
13905// of a type.
13906
13907class Type_descriptor_expression : public Expression
13908{
13909 public:
b13c66cd 13910 Type_descriptor_expression(Type* type, Location location)
e440a328 13911 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13912 type_(type)
13913 { }
13914
13915 protected:
13916 Type*
13917 do_type()
13918 { return Type::make_type_descriptor_ptr_type(); }
13919
f9ca30f9 13920 bool
13921 do_is_immutable() const
13922 { return true; }
13923
e440a328 13924 void
13925 do_determine_type(const Type_context*)
13926 { }
13927
13928 Expression*
13929 do_copy()
13930 { return this; }
13931
13932 tree
13933 do_get_tree(Translate_context* context)
a1d23b41 13934 {
175a4612 13935 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
13936 this->location());
13937 return expr_to_tree(ret);
a1d23b41 13938 }
e440a328 13939
d751bb78 13940 void
13941 do_dump_expression(Ast_dump_context*) const;
13942
e440a328 13943 private:
13944 // The type for which this is the descriptor.
13945 Type* type_;
13946};
13947
d751bb78 13948// Dump ast representation for a type descriptor expression.
13949
13950void
13951Type_descriptor_expression::do_dump_expression(
13952 Ast_dump_context* ast_dump_context) const
13953{
13954 ast_dump_context->dump_type(this->type_);
13955}
13956
e440a328 13957// Make a type descriptor expression.
13958
13959Expression*
b13c66cd 13960Expression::make_type_descriptor(Type* type, Location location)
e440a328 13961{
13962 return new Type_descriptor_expression(type, location);
13963}
13964
13965// An expression which evaluates to some characteristic of a type.
13966// This is only used to initialize fields of a type descriptor. Using
13967// a new expression class is slightly inefficient but gives us a good
13968// separation between the frontend and the middle-end with regard to
13969// how types are laid out.
13970
13971class Type_info_expression : public Expression
13972{
13973 public:
13974 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 13975 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 13976 type_(type), type_info_(type_info)
13977 { }
13978
13979 protected:
0e168074 13980 bool
13981 do_is_immutable() const
13982 { return true; }
13983
e440a328 13984 Type*
13985 do_type();
13986
13987 void
13988 do_determine_type(const Type_context*)
13989 { }
13990
13991 Expression*
13992 do_copy()
13993 { return this; }
13994
13995 tree
13996 do_get_tree(Translate_context* context);
13997
d751bb78 13998 void
13999 do_dump_expression(Ast_dump_context*) const;
14000
e440a328 14001 private:
14002 // The type for which we are getting information.
14003 Type* type_;
14004 // What information we want.
14005 Type_info type_info_;
14006};
14007
14008// The type is chosen to match what the type descriptor struct
14009// expects.
14010
14011Type*
14012Type_info_expression::do_type()
14013{
14014 switch (this->type_info_)
14015 {
14016 case TYPE_INFO_SIZE:
14017 return Type::lookup_integer_type("uintptr");
14018 case TYPE_INFO_ALIGNMENT:
14019 case TYPE_INFO_FIELD_ALIGNMENT:
14020 return Type::lookup_integer_type("uint8");
14021 default:
c3e6f413 14022 go_unreachable();
e440a328 14023 }
14024}
14025
14026// Return type information in GENERIC.
14027
14028tree
14029Type_info_expression::do_get_tree(Translate_context* context)
14030{
927a01eb 14031 Btype* btype = this->type_->get_backend(context->gogo());
14032 Gogo* gogo = context->gogo();
14033 size_t val;
14034 switch (this->type_info_)
e440a328 14035 {
927a01eb 14036 case TYPE_INFO_SIZE:
14037 val = gogo->backend()->type_size(btype);
14038 break;
14039 case TYPE_INFO_ALIGNMENT:
14040 val = gogo->backend()->type_alignment(btype);
14041 break;
14042 case TYPE_INFO_FIELD_ALIGNMENT:
14043 val = gogo->backend()->type_field_alignment(btype);
14044 break;
14045 default:
14046 go_unreachable();
e440a328 14047 }
287cdcf4 14048 mpz_t cst;
14049 mpz_init_set_ui(cst, val);
14050 Btype* int_btype = this->type()->get_backend(gogo);
14051 Bexpression* ret =
14052 gogo->backend()->integer_constant_expression(int_btype, cst);
14053 mpz_clear(cst);
14054 return expr_to_tree(ret);
e440a328 14055}
14056
d751bb78 14057// Dump ast representation for a type info expression.
14058
14059void
14060Type_info_expression::do_dump_expression(
14061 Ast_dump_context* ast_dump_context) const
14062{
14063 ast_dump_context->ostream() << "typeinfo(";
14064 ast_dump_context->dump_type(this->type_);
14065 ast_dump_context->ostream() << ",";
14066 ast_dump_context->ostream() <<
14067 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14068 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14069 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14070 : "unknown");
14071 ast_dump_context->ostream() << ")";
14072}
14073
e440a328 14074// Make a type info expression.
14075
14076Expression*
14077Expression::make_type_info(Type* type, Type_info type_info)
14078{
14079 return new Type_info_expression(type, type_info);
14080}
14081
35a54f17 14082// An expression that evaluates to some characteristic of a slice.
14083// This is used when indexing, bound-checking, or nil checking a slice.
14084
14085class Slice_info_expression : public Expression
14086{
14087 public:
14088 Slice_info_expression(Expression* slice, Slice_info slice_info,
14089 Location location)
14090 : Expression(EXPRESSION_SLICE_INFO, location),
14091 slice_(slice), slice_info_(slice_info)
14092 { }
14093
14094 protected:
14095 Type*
14096 do_type();
14097
14098 void
14099 do_determine_type(const Type_context*)
14100 { }
14101
14102 Expression*
14103 do_copy()
14104 {
14105 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14106 this->location());
14107 }
14108
14109 tree
14110 do_get_tree(Translate_context* context);
14111
14112 void
14113 do_dump_expression(Ast_dump_context*) const;
14114
14115 void
14116 do_issue_nil_check()
14117 { this->slice_->issue_nil_check(); }
14118
14119 private:
14120 // The slice for which we are getting information.
14121 Expression* slice_;
14122 // What information we want.
14123 Slice_info slice_info_;
14124};
14125
14126// Return the type of the slice info.
14127
14128Type*
14129Slice_info_expression::do_type()
14130{
14131 switch (this->slice_info_)
14132 {
14133 case SLICE_INFO_VALUE_POINTER:
14134 return Type::make_pointer_type(
14135 this->slice_->type()->array_type()->element_type());
14136 case SLICE_INFO_LENGTH:
14137 case SLICE_INFO_CAPACITY:
14138 return Type::lookup_integer_type("int");
14139 default:
14140 go_unreachable();
14141 }
14142}
14143
14144// Return slice information in GENERIC.
14145
14146tree
14147Slice_info_expression::do_get_tree(Translate_context* context)
14148{
14149 Gogo* gogo = context->gogo();
14150
14151 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14152 Bexpression* ret;
14153 switch (this->slice_info_)
14154 {
14155 case SLICE_INFO_VALUE_POINTER:
14156 case SLICE_INFO_LENGTH:
14157 case SLICE_INFO_CAPACITY:
14158 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14159 this->location());
14160 break;
14161 default:
14162 go_unreachable();
14163 }
14164 return expr_to_tree(ret);
14165}
14166
14167// Dump ast representation for a type info expression.
14168
14169void
14170Slice_info_expression::do_dump_expression(
14171 Ast_dump_context* ast_dump_context) const
14172{
14173 ast_dump_context->ostream() << "sliceinfo(";
14174 this->slice_->dump_expression(ast_dump_context);
14175 ast_dump_context->ostream() << ",";
14176 ast_dump_context->ostream() <<
14177 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14178 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14179 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14180 : "unknown");
14181 ast_dump_context->ostream() << ")";
14182}
14183
14184// Make a slice info expression.
14185
14186Expression*
14187Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14188 Location location)
14189{
14190 return new Slice_info_expression(slice, slice_info, location);
14191}
14192
2c809f8f 14193// An expression that represents a slice value: a struct with value pointer,
14194// length, and capacity fields.
14195
14196class Slice_value_expression : public Expression
14197{
14198 public:
14199 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14200 Expression* cap, Location location)
14201 : Expression(EXPRESSION_SLICE_VALUE, location),
14202 type_(type), valptr_(valptr), len_(len), cap_(cap)
14203 { }
14204
14205 protected:
14206 int
14207 do_traverse(Traverse*);
14208
14209 Type*
14210 do_type()
14211 { return this->type_; }
14212
14213 void
14214 do_determine_type(const Type_context*)
14215 { go_unreachable(); }
14216
14217 Expression*
14218 do_copy()
14219 {
14220 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14221 this->len_->copy(), this->cap_->copy(),
14222 this->location());
14223 }
14224
14225 tree
14226 do_get_tree(Translate_context* context);
14227
14228 void
14229 do_dump_expression(Ast_dump_context*) const;
14230
14231 private:
14232 // The type of the slice value.
14233 Type* type_;
14234 // The pointer to the values in the slice.
14235 Expression* valptr_;
14236 // The length of the slice.
14237 Expression* len_;
14238 // The capacity of the slice.
14239 Expression* cap_;
14240};
14241
14242int
14243Slice_value_expression::do_traverse(Traverse* traverse)
14244{
14245 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14246 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14247 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14248 return TRAVERSE_EXIT;
14249 return TRAVERSE_CONTINUE;
14250}
14251
14252tree
14253Slice_value_expression::do_get_tree(Translate_context* context)
14254{
14255 std::vector<Bexpression*> vals(3);
14256 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14257 vals[1] = tree_to_expr(this->len_->get_tree(context));
14258 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14259
14260 Gogo* gogo = context->gogo();
14261 Btype* btype = this->type_->get_backend(gogo);
14262 Bexpression* ret =
14263 gogo->backend()->constructor_expression(btype, vals, this->location());
14264 return expr_to_tree(ret);
14265}
14266
14267void
14268Slice_value_expression::do_dump_expression(
14269 Ast_dump_context* ast_dump_context) const
14270{
14271 ast_dump_context->ostream() << "slicevalue(";
14272 ast_dump_context->ostream() << "values: ";
14273 this->valptr_->dump_expression(ast_dump_context);
14274 ast_dump_context->ostream() << ", length: ";
14275 this->len_->dump_expression(ast_dump_context);
14276 ast_dump_context->ostream() << ", capacity: ";
14277 this->cap_->dump_expression(ast_dump_context);
14278 ast_dump_context->ostream() << ")";
14279}
14280
14281Expression*
14282Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14283 Expression* cap, Location location)
14284{
14285 go_assert(at->is_slice_type());
14286 return new Slice_value_expression(at, valptr, len, cap, location);
14287}
2387f644 14288
14289// An expression that evaluates to some characteristic of a non-empty interface.
14290// This is used to access the method table or underlying object of an interface.
14291
14292class Interface_info_expression : public Expression
14293{
14294 public:
14295 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14296 Location location)
2387f644 14297 : Expression(EXPRESSION_INTERFACE_INFO, location),
14298 iface_(iface), iface_info_(iface_info)
14299 { }
14300
14301 protected:
14302 Type*
14303 do_type();
14304
14305 void
14306 do_determine_type(const Type_context*)
14307 { }
14308
14309 Expression*
14310 do_copy()
14311 {
14312 return new Interface_info_expression(this->iface_->copy(),
14313 this->iface_info_, this->location());
14314 }
14315
14316 tree
14317 do_get_tree(Translate_context* context);
14318
14319 void
14320 do_dump_expression(Ast_dump_context*) const;
14321
14322 void
14323 do_issue_nil_check()
14324 { this->iface_->issue_nil_check(); }
14325
14326 private:
14327 // The interface for which we are getting information.
14328 Expression* iface_;
14329 // What information we want.
14330 Interface_info iface_info_;
14331};
14332
14333// Return the type of the interface info.
14334
14335Type*
14336Interface_info_expression::do_type()
14337{
14338 switch (this->iface_info_)
14339 {
14340 case INTERFACE_INFO_METHODS:
14341 {
2c809f8f 14342 Type* pdt = Type::make_type_descriptor_ptr_type();
14343 if (this->iface_->type()->interface_type()->is_empty())
14344 return pdt;
14345
2387f644 14346 Location loc = this->location();
14347 Struct_field_list* sfl = new Struct_field_list();
2387f644 14348 sfl->push_back(
14349 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14350
14351 Interface_type* itype = this->iface_->type()->interface_type();
14352 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14353 p != itype->methods()->end();
14354 ++p)
14355 {
14356 Function_type* ft = p->type()->function_type();
14357 go_assert(ft->receiver() == NULL);
14358
14359 const Typed_identifier_list* params = ft->parameters();
14360 Typed_identifier_list* mparams = new Typed_identifier_list();
14361 if (params != NULL)
14362 mparams->reserve(params->size() + 1);
14363 Type* vt = Type::make_pointer_type(Type::make_void_type());
14364 mparams->push_back(Typed_identifier("", vt, ft->location()));
14365 if (params != NULL)
14366 {
14367 for (Typed_identifier_list::const_iterator pp = params->begin();
14368 pp != params->end();
14369 ++pp)
14370 mparams->push_back(*pp);
14371 }
14372
14373 Typed_identifier_list* mresults = (ft->results() == NULL
14374 ? NULL
14375 : ft->results()->copy());
14376 Backend_function_type* mft =
14377 Type::make_backend_function_type(NULL, mparams, mresults,
14378 ft->location());
14379
14380 std::string fname = Gogo::unpack_hidden_name(p->name());
14381 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14382 }
14383
14384 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14385 }
14386 case INTERFACE_INFO_OBJECT:
14387 return Type::make_pointer_type(Type::make_void_type());
14388 default:
14389 go_unreachable();
14390 }
14391}
14392
14393// Return interface information in GENERIC.
14394
14395tree
14396Interface_info_expression::do_get_tree(Translate_context* context)
14397{
14398 Gogo* gogo = context->gogo();
14399
14400 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14401 Bexpression* ret;
14402 switch (this->iface_info_)
14403 {
14404 case INTERFACE_INFO_METHODS:
14405 case INTERFACE_INFO_OBJECT:
14406 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14407 this->location());
14408 break;
14409 default:
14410 go_unreachable();
14411 }
14412 return expr_to_tree(ret);
14413}
14414
14415// Dump ast representation for an interface info expression.
14416
14417void
14418Interface_info_expression::do_dump_expression(
14419 Ast_dump_context* ast_dump_context) const
14420{
2c809f8f 14421 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14422 ast_dump_context->ostream() << "interfaceinfo(";
14423 this->iface_->dump_expression(ast_dump_context);
14424 ast_dump_context->ostream() << ",";
14425 ast_dump_context->ostream() <<
2c809f8f 14426 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14427 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14428 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14429 : "unknown");
14430 ast_dump_context->ostream() << ")";
14431}
14432
14433// Make an interface info expression.
14434
14435Expression*
14436Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14437 Location location)
14438{
14439 return new Interface_info_expression(iface, iface_info, location);
14440}
14441
2c809f8f 14442// An expression that represents an interface value. The first field is either
14443// a type descriptor for an empty interface or a pointer to the interface method
14444// table for a non-empty interface. The second field is always the object.
14445
14446class Interface_value_expression : public Expression
14447{
14448 public:
14449 Interface_value_expression(Type* type, Expression* first_field,
14450 Expression* obj, Location location)
14451 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14452 type_(type), first_field_(first_field), obj_(obj)
14453 { }
14454
14455 protected:
14456 int
14457 do_traverse(Traverse*);
14458
14459 Type*
14460 do_type()
14461 { return this->type_; }
14462
14463 void
14464 do_determine_type(const Type_context*)
14465 { go_unreachable(); }
14466
14467 Expression*
14468 do_copy()
14469 {
14470 return new Interface_value_expression(this->type_,
14471 this->first_field_->copy(),
14472 this->obj_->copy(), this->location());
14473 }
14474
14475 tree
14476 do_get_tree(Translate_context* context);
14477
14478 void
14479 do_dump_expression(Ast_dump_context*) const;
14480
14481 private:
14482 // The type of the interface value.
14483 Type* type_;
14484 // The first field of the interface (either a type descriptor or a pointer
14485 // to the method table.
14486 Expression* first_field_;
14487 // The underlying object of the interface.
14488 Expression* obj_;
14489};
14490
14491int
14492Interface_value_expression::do_traverse(Traverse* traverse)
14493{
14494 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14495 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14496 return TRAVERSE_EXIT;
14497 return TRAVERSE_CONTINUE;
14498}
14499
14500tree
14501Interface_value_expression::do_get_tree(Translate_context* context)
14502{
14503 std::vector<Bexpression*> vals(2);
14504 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14505 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14506
14507 Gogo* gogo = context->gogo();
14508 Btype* btype = this->type_->get_backend(gogo);
14509 Bexpression* ret =
14510 gogo->backend()->constructor_expression(btype, vals, this->location());
14511 return expr_to_tree(ret);
14512}
14513
14514void
14515Interface_value_expression::do_dump_expression(
14516 Ast_dump_context* ast_dump_context) const
14517{
14518 ast_dump_context->ostream() << "interfacevalue(";
14519 ast_dump_context->ostream() <<
14520 (this->type_->interface_type()->is_empty()
14521 ? "type_descriptor: "
14522 : "methods: ");
14523 this->first_field_->dump_expression(ast_dump_context);
14524 ast_dump_context->ostream() << ", object: ";
14525 this->obj_->dump_expression(ast_dump_context);
14526 ast_dump_context->ostream() << ")";
14527}
14528
14529Expression*
14530Expression::make_interface_value(Type* type, Expression* first_value,
14531 Expression* object, Location location)
14532{
14533 return new Interface_value_expression(type, first_value, object, location);
14534}
14535
14536// An interface method table for a pair of types: an interface type and a type
14537// that implements that interface.
14538
14539class Interface_mtable_expression : public Expression
14540{
14541 public:
14542 Interface_mtable_expression(Interface_type* itype, Type* type,
14543 bool is_pointer, Location location)
14544 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14545 itype_(itype), type_(type), is_pointer_(is_pointer),
14546 method_table_type_(NULL), bvar_(NULL)
14547 { }
14548
14549 protected:
14550 int
14551 do_traverse(Traverse*);
14552
14553 Type*
14554 do_type();
14555
14556 bool
14557 is_immutable() const
14558 { return true; }
14559
14560 void
14561 do_determine_type(const Type_context*)
14562 { go_unreachable(); }
14563
14564 Expression*
14565 do_copy()
14566 {
14567 return new Interface_mtable_expression(this->itype_, this->type_,
14568 this->is_pointer_, this->location());
14569 }
14570
14571 bool
14572 do_is_addressable() const
14573 { return true; }
14574
14575 tree
14576 do_get_tree(Translate_context* context);
14577
14578 void
14579 do_dump_expression(Ast_dump_context*) const;
14580
14581 private:
14582 // The interface type for which the methods are defined.
14583 Interface_type* itype_;
14584 // The type to construct the interface method table for.
14585 Type* type_;
14586 // Whether this table contains the method set for the receiver type or the
14587 // pointer receiver type.
14588 bool is_pointer_;
14589 // The type of the method table.
14590 Type* method_table_type_;
14591 // The backend variable that refers to the interface method table.
14592 Bvariable* bvar_;
14593};
14594
14595int
14596Interface_mtable_expression::do_traverse(Traverse* traverse)
14597{
14598 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14599 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14600 return TRAVERSE_EXIT;
14601 return TRAVERSE_CONTINUE;
14602}
14603
14604Type*
14605Interface_mtable_expression::do_type()
14606{
14607 if (this->method_table_type_ != NULL)
14608 return this->method_table_type_;
14609
14610 const Typed_identifier_list* interface_methods = this->itype_->methods();
14611 go_assert(!interface_methods->empty());
14612
14613 Struct_field_list* sfl = new Struct_field_list;
14614 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14615 this->location());
14616 sfl->push_back(Struct_field(tid));
14617 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14618 p != interface_methods->end();
14619 ++p)
14620 sfl->push_back(Struct_field(*p));
14621 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14622 return this->method_table_type_;
14623}
14624
14625tree
14626Interface_mtable_expression::do_get_tree(Translate_context* context)
14627{
14628 Gogo* gogo = context->gogo();
14629 Bexpression* ret;
14630 Location loc = Linemap::predeclared_location();
14631 if (this->bvar_ != NULL)
14632 {
14633 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14634 return expr_to_tree(ret);
14635 }
14636
14637 const Typed_identifier_list* interface_methods = this->itype_->methods();
14638 go_assert(!interface_methods->empty());
14639
14640 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14641 + this->itype_->mangled_name(gogo)
14642 + "__"
14643 + this->type_->mangled_name(gogo));
14644
14645 // See whether this interface has any hidden methods.
14646 bool has_hidden_methods = false;
14647 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14648 p != interface_methods->end();
14649 ++p)
14650 {
14651 if (Gogo::is_hidden_name(p->name()))
14652 {
14653 has_hidden_methods = true;
14654 break;
14655 }
14656 }
14657
14658 // We already know that the named type is convertible to the
14659 // interface. If the interface has hidden methods, and the named
14660 // type is defined in a different package, then the interface
14661 // conversion table will be defined by that other package.
14662 if (has_hidden_methods
14663 && this->type_->named_type() != NULL
14664 && this->type_->named_type()->named_object()->package() != NULL)
14665 {
14666 Btype* btype = this->type()->get_backend(gogo);
14667 this->bvar_ =
14668 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14669 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14670 return expr_to_tree(ret);
14671 }
14672
14673 // The first element is the type descriptor.
14674 Type* td_type;
14675 if (!this->is_pointer_)
14676 td_type = this->type_;
14677 else
14678 td_type = Type::make_pointer_type(this->type_);
14679
14680 // Build an interface method table for a type: a type descriptor followed by a
14681 // list of function pointers, one for each interface method. This is used for
14682 // interfaces.
14683 Expression_list* svals = new Expression_list();
14684 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14685
14686 Named_type* nt = this->type_->named_type();
14687 Struct_type* st = this->type_->struct_type();
14688 go_assert(nt != NULL || st != NULL);
14689
14690 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14691 p != interface_methods->end();
14692 ++p)
14693 {
14694 bool is_ambiguous;
14695 Method* m;
14696 if (nt != NULL)
14697 m = nt->method_function(p->name(), &is_ambiguous);
14698 else
14699 m = st->method_function(p->name(), &is_ambiguous);
14700 go_assert(m != NULL);
14701 Named_object* no = m->named_object();
14702
14703 go_assert(no->is_function() || no->is_function_declaration());
14704 svals->push_back(Expression::make_func_code_reference(no, loc));
14705 }
14706
14707 Btype* btype = this->type()->get_backend(gogo);
14708 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14709 svals, loc);
14710 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14711
14712 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14713 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14714 !is_public, btype, loc);
14715 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14716 !is_public, btype, loc, ctor);
14717 ret = gogo->backend()->var_expression(this->bvar_, loc);
14718 return expr_to_tree(ret);
14719}
14720
14721void
14722Interface_mtable_expression::do_dump_expression(
14723 Ast_dump_context* ast_dump_context) const
14724{
14725 ast_dump_context->ostream() << "__go_"
14726 << (this->is_pointer_ ? "pimt__" : "imt_");
14727 ast_dump_context->dump_type(this->itype_);
14728 ast_dump_context->ostream() << "__";
14729 ast_dump_context->dump_type(this->type_);
14730}
14731
14732Expression*
14733Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14734 bool is_pointer, Location location)
14735{
14736 return new Interface_mtable_expression(itype, type, is_pointer, location);
14737}
14738
e440a328 14739// An expression which evaluates to the offset of a field within a
14740// struct. This, like Type_info_expression, q.v., is only used to
14741// initialize fields of a type descriptor.
14742
14743class Struct_field_offset_expression : public Expression
14744{
14745 public:
14746 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 14747 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14748 Linemap::predeclared_location()),
e440a328 14749 type_(type), field_(field)
14750 { }
14751
14752 protected:
f23d7786 14753 bool
14754 do_is_immutable() const
14755 { return true; }
14756
e440a328 14757 Type*
14758 do_type()
14759 { return Type::lookup_integer_type("uintptr"); }
14760
14761 void
14762 do_determine_type(const Type_context*)
14763 { }
14764
14765 Expression*
14766 do_copy()
14767 { return this; }
14768
14769 tree
14770 do_get_tree(Translate_context* context);
14771
d751bb78 14772 void
14773 do_dump_expression(Ast_dump_context*) const;
14774
e440a328 14775 private:
14776 // The type of the struct.
14777 Struct_type* type_;
14778 // The field.
14779 const Struct_field* field_;
14780};
14781
14782// Return a struct field offset in GENERIC.
14783
14784tree
14785Struct_field_offset_expression::do_get_tree(Translate_context* context)
14786{
e440a328 14787 const Struct_field_list* fields = this->type_->fields();
e440a328 14788 Struct_field_list::const_iterator p;
2c8bda43 14789 unsigned i = 0;
e440a328 14790 for (p = fields->begin();
14791 p != fields->end();
2c8bda43 14792 ++p, ++i)
14793 if (&*p == this->field_)
14794 break;
c484d925 14795 go_assert(&*p == this->field_);
e440a328 14796
2c8bda43 14797 Gogo* gogo = context->gogo();
14798 Btype* btype = this->type_->get_backend(gogo);
14799
14800 size_t offset = gogo->backend()->type_field_offset(btype, i);
14801 mpz_t offsetval;
14802 mpz_init_set_ui(offsetval, offset);
14803 Type* uptr_type = Type::lookup_integer_type("uintptr");
14804 Expression* ret = Expression::make_integer(&offsetval, uptr_type,
14805 Linemap::predeclared_location());
14806 mpz_clear(offsetval);
14807 return ret->get_tree(context);
e440a328 14808}
14809
d751bb78 14810// Dump ast representation for a struct field offset expression.
14811
14812void
14813Struct_field_offset_expression::do_dump_expression(
14814 Ast_dump_context* ast_dump_context) const
14815{
14816 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 14817 ast_dump_context->dump_type(this->type_);
14818 ast_dump_context->ostream() << '.';
14819 ast_dump_context->ostream() <<
14820 Gogo::message_name(this->field_->field_name());
d751bb78 14821 ast_dump_context->ostream() << ")";
14822}
14823
e440a328 14824// Make an expression for a struct field offset.
14825
14826Expression*
14827Expression::make_struct_field_offset(Struct_type* type,
14828 const Struct_field* field)
14829{
14830 return new Struct_field_offset_expression(type, field);
14831}
14832
a9182619 14833// An expression which evaluates to a pointer to the map descriptor of
14834// a map type.
14835
14836class Map_descriptor_expression : public Expression
14837{
14838 public:
b13c66cd 14839 Map_descriptor_expression(Map_type* type, Location location)
a9182619 14840 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14841 type_(type)
14842 { }
14843
14844 protected:
14845 Type*
14846 do_type()
14847 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14848
14849 void
14850 do_determine_type(const Type_context*)
14851 { }
14852
14853 Expression*
14854 do_copy()
14855 { return this; }
14856
14857 tree
14858 do_get_tree(Translate_context* context)
14859 {
175a4612 14860 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14861 this->location());
14862 return expr_to_tree(ret);
a9182619 14863 }
14864
d751bb78 14865 void
14866 do_dump_expression(Ast_dump_context*) const;
14867
a9182619 14868 private:
14869 // The type for which this is the descriptor.
14870 Map_type* type_;
14871};
14872
d751bb78 14873// Dump ast representation for a map descriptor expression.
14874
14875void
14876Map_descriptor_expression::do_dump_expression(
14877 Ast_dump_context* ast_dump_context) const
14878{
14879 ast_dump_context->ostream() << "map_descriptor(";
14880 ast_dump_context->dump_type(this->type_);
14881 ast_dump_context->ostream() << ")";
14882}
14883
a9182619 14884// Make a map descriptor expression.
14885
14886Expression*
b13c66cd 14887Expression::make_map_descriptor(Map_type* type, Location location)
a9182619 14888{
14889 return new Map_descriptor_expression(type, location);
14890}
14891
e440a328 14892// An expression which evaluates to the address of an unnamed label.
14893
14894class Label_addr_expression : public Expression
14895{
14896 public:
b13c66cd 14897 Label_addr_expression(Label* label, Location location)
e440a328 14898 : Expression(EXPRESSION_LABEL_ADDR, location),
14899 label_(label)
14900 { }
14901
14902 protected:
14903 Type*
14904 do_type()
14905 { return Type::make_pointer_type(Type::make_void_type()); }
14906
14907 void
14908 do_determine_type(const Type_context*)
14909 { }
14910
14911 Expression*
14912 do_copy()
14913 { return new Label_addr_expression(this->label_, this->location()); }
14914
14915 tree
6e193e6f 14916 do_get_tree(Translate_context* context)
14917 {
e8816003 14918 return expr_to_tree(this->label_->get_addr(context, this->location()));
6e193e6f 14919 }
e440a328 14920
d751bb78 14921 void
14922 do_dump_expression(Ast_dump_context* ast_dump_context) const
14923 { ast_dump_context->ostream() << this->label_->name(); }
14924
e440a328 14925 private:
14926 // The label whose address we are taking.
14927 Label* label_;
14928};
14929
14930// Make an expression for the address of an unnamed label.
14931
14932Expression*
b13c66cd 14933Expression::make_label_addr(Label* label, Location location)
e440a328 14934{
14935 return new Label_addr_expression(label, location);
14936}
14937
283a177b 14938// Conditional expressions.
14939
14940class Conditional_expression : public Expression
14941{
14942 public:
14943 Conditional_expression(Expression* cond, Expression* then_expr,
14944 Expression* else_expr, Location location)
14945 : Expression(EXPRESSION_CONDITIONAL, location),
14946 cond_(cond), then_(then_expr), else_(else_expr)
14947 {}
14948
14949 protected:
2c809f8f 14950 int
14951 do_traverse(Traverse*);
14952
283a177b 14953 Type*
14954 do_type();
14955
14956 void
2c809f8f 14957 do_determine_type(const Type_context*);
283a177b 14958
14959 Expression*
14960 do_copy()
14961 {
14962 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14963 this->else_->copy(), this->location());
14964 }
14965
14966 tree
14967 do_get_tree(Translate_context* context);
14968
14969 void
14970 do_dump_expression(Ast_dump_context*) const;
14971
14972 private:
14973 // The condition to be checked.
14974 Expression* cond_;
14975 // The expression to execute if the condition is true.
14976 Expression* then_;
14977 // The expression to execute if the condition is false.
14978 Expression* else_;
14979};
14980
2c809f8f 14981// Traversal.
14982
14983int
14984Conditional_expression::do_traverse(Traverse* traverse)
14985{
14986 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14987 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14988 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14989 return TRAVERSE_EXIT;
14990 return TRAVERSE_CONTINUE;
14991}
14992
283a177b 14993// Return the type of the conditional expression.
14994
14995Type*
14996Conditional_expression::do_type()
14997{
14998 Type* result_type = Type::make_void_type();
2c809f8f 14999 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15000 NULL))
283a177b 15001 result_type = this->then_->type();
15002 else if (this->then_->is_nil_expression()
15003 || this->else_->is_nil_expression())
15004 result_type = (!this->then_->is_nil_expression()
15005 ? this->then_->type()
15006 : this->else_->type());
15007 return result_type;
15008}
15009
2c809f8f 15010// Determine type for a conditional expression.
15011
15012void
15013Conditional_expression::do_determine_type(const Type_context* context)
15014{
15015 this->cond_->determine_type_no_context();
15016 this->then_->determine_type(context);
15017 this->else_->determine_type(context);
15018}
15019
283a177b 15020// Get the backend representation of a conditional expression.
15021
15022tree
15023Conditional_expression::do_get_tree(Translate_context* context)
15024{
15025 Gogo* gogo = context->gogo();
15026 Btype* result_btype = this->type()->get_backend(gogo);
15027 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15028 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15029 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15030 Bexpression* ret =
15031 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15032 this->location());
15033 return expr_to_tree(ret);
15034}
15035
15036// Dump ast representation of a conditional expression.
15037
15038void
15039Conditional_expression::do_dump_expression(
15040 Ast_dump_context* ast_dump_context) const
15041{
15042 ast_dump_context->ostream() << "(";
15043 ast_dump_context->dump_expression(this->cond_);
15044 ast_dump_context->ostream() << " ? ";
15045 ast_dump_context->dump_expression(this->then_);
15046 ast_dump_context->ostream() << " : ";
15047 ast_dump_context->dump_expression(this->else_);
15048 ast_dump_context->ostream() << ") ";
15049}
15050
15051// Make a conditional expression.
15052
15053Expression*
15054Expression::make_conditional(Expression* cond, Expression* then,
15055 Expression* else_expr, Location location)
15056{
15057 return new Conditional_expression(cond, then, else_expr, location);
15058}
15059
2c809f8f 15060// Compound expressions.
15061
15062class Compound_expression : public Expression
15063{
15064 public:
15065 Compound_expression(Expression* init, Expression* expr, Location location)
15066 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15067 {}
15068
15069 protected:
15070 int
15071 do_traverse(Traverse*);
15072
15073 Type*
15074 do_type();
15075
15076 void
15077 do_determine_type(const Type_context*);
15078
15079 Expression*
15080 do_copy()
15081 {
15082 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15083 this->location());
15084 }
15085
15086 tree
15087 do_get_tree(Translate_context* context);
15088
15089 void
15090 do_dump_expression(Ast_dump_context*) const;
15091
15092 private:
15093 // The expression that is evaluated first and discarded.
15094 Expression* init_;
15095 // The expression that is evaluated and returned.
15096 Expression* expr_;
15097};
15098
15099// Traversal.
15100
15101int
15102Compound_expression::do_traverse(Traverse* traverse)
15103{
15104 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15105 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15106 return TRAVERSE_EXIT;
15107 return TRAVERSE_CONTINUE;
15108}
15109
15110// Return the type of the compound expression.
15111
15112Type*
15113Compound_expression::do_type()
15114{
15115 return this->expr_->type();
15116}
15117
15118// Determine type for a compound expression.
15119
15120void
15121Compound_expression::do_determine_type(const Type_context* context)
15122{
15123 this->init_->determine_type_no_context();
15124 this->expr_->determine_type(context);
15125}
15126
15127// Get the backend representation of a compound expression.
15128
15129tree
15130Compound_expression::do_get_tree(Translate_context* context)
15131{
15132 Gogo* gogo = context->gogo();
15133 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15134 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15135 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15136 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15137 this->location());
15138 return expr_to_tree(ret);
15139}
15140
15141// Dump ast representation of a conditional expression.
15142
15143void
15144Compound_expression::do_dump_expression(
15145 Ast_dump_context* ast_dump_context) const
15146{
15147 ast_dump_context->ostream() << "(";
15148 ast_dump_context->dump_expression(this->init_);
15149 ast_dump_context->ostream() << ",";
15150 ast_dump_context->dump_expression(this->expr_);
15151 ast_dump_context->ostream() << ") ";
15152}
15153
15154// Make a compound expression.
15155
15156Expression*
15157Expression::make_compound(Expression* init, Expression* expr, Location location)
15158{
15159 return new Compound_expression(init, expr, location);
15160}
15161
e440a328 15162// Import an expression. This comes at the end in order to see the
15163// various class definitions.
15164
15165Expression*
15166Expression::import_expression(Import* imp)
15167{
15168 int c = imp->peek_char();
15169 if (imp->match_c_string("- ")
15170 || imp->match_c_string("! ")
15171 || imp->match_c_string("^ "))
15172 return Unary_expression::do_import(imp);
15173 else if (c == '(')
15174 return Binary_expression::do_import(imp);
15175 else if (imp->match_c_string("true")
15176 || imp->match_c_string("false"))
15177 return Boolean_expression::do_import(imp);
15178 else if (c == '"')
15179 return String_expression::do_import(imp);
15180 else if (c == '-' || (c >= '0' && c <= '9'))
15181 {
15182 // This handles integers, floats and complex constants.
15183 return Integer_expression::do_import(imp);
15184 }
15185 else if (imp->match_c_string("nil"))
15186 return Nil_expression::do_import(imp);
15187 else if (imp->match_c_string("convert"))
15188 return Type_conversion_expression::do_import(imp);
15189 else
15190 {
15191 error_at(imp->location(), "import error: expected expression");
15192 return Expression::make_error(imp->location());
15193 }
15194}
15195
15196// Class Expression_list.
15197
15198// Traverse the list.
15199
15200int
15201Expression_list::traverse(Traverse* traverse)
15202{
15203 for (Expression_list::iterator p = this->begin();
15204 p != this->end();
15205 ++p)
15206 {
15207 if (*p != NULL)
15208 {
15209 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15210 return TRAVERSE_EXIT;
15211 }
15212 }
15213 return TRAVERSE_CONTINUE;
15214}
15215
15216// Copy the list.
15217
15218Expression_list*
15219Expression_list::copy()
15220{
15221 Expression_list* ret = new Expression_list();
15222 for (Expression_list::iterator p = this->begin();
15223 p != this->end();
15224 ++p)
15225 {
15226 if (*p == NULL)
15227 ret->push_back(NULL);
15228 else
15229 ret->push_back((*p)->copy());
15230 }
15231 return ret;
15232}
15233
15234// Return whether an expression list has an error expression.
15235
15236bool
15237Expression_list::contains_error() const
15238{
15239 for (Expression_list::const_iterator p = this->begin();
15240 p != this->end();
15241 ++p)
15242 if (*p != NULL && (*p)->is_error_expression())
15243 return true;
15244 return false;
15245}
0c77715b 15246
15247// Class Numeric_constant.
15248
15249// Destructor.
15250
15251Numeric_constant::~Numeric_constant()
15252{
15253 this->clear();
15254}
15255
15256// Copy constructor.
15257
15258Numeric_constant::Numeric_constant(const Numeric_constant& a)
15259 : classification_(a.classification_), type_(a.type_)
15260{
15261 switch (a.classification_)
15262 {
15263 case NC_INVALID:
15264 break;
15265 case NC_INT:
15266 case NC_RUNE:
15267 mpz_init_set(this->u_.int_val, a.u_.int_val);
15268 break;
15269 case NC_FLOAT:
15270 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15271 break;
15272 case NC_COMPLEX:
15273 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15274 GMP_RNDN);
15275 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15276 GMP_RNDN);
15277 break;
15278 default:
15279 go_unreachable();
15280 }
15281}
15282
15283// Assignment operator.
15284
15285Numeric_constant&
15286Numeric_constant::operator=(const Numeric_constant& a)
15287{
15288 this->clear();
15289 this->classification_ = a.classification_;
15290 this->type_ = a.type_;
15291 switch (a.classification_)
15292 {
15293 case NC_INVALID:
15294 break;
15295 case NC_INT:
15296 case NC_RUNE:
15297 mpz_init_set(this->u_.int_val, a.u_.int_val);
15298 break;
15299 case NC_FLOAT:
15300 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15301 break;
15302 case NC_COMPLEX:
15303 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15304 GMP_RNDN);
15305 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15306 GMP_RNDN);
15307 break;
15308 default:
15309 go_unreachable();
15310 }
15311 return *this;
15312}
15313
15314// Clear the contents.
15315
15316void
15317Numeric_constant::clear()
15318{
15319 switch (this->classification_)
15320 {
15321 case NC_INVALID:
15322 break;
15323 case NC_INT:
15324 case NC_RUNE:
15325 mpz_clear(this->u_.int_val);
15326 break;
15327 case NC_FLOAT:
15328 mpfr_clear(this->u_.float_val);
15329 break;
15330 case NC_COMPLEX:
15331 mpfr_clear(this->u_.complex_val.real);
15332 mpfr_clear(this->u_.complex_val.imag);
15333 break;
15334 default:
15335 go_unreachable();
15336 }
15337 this->classification_ = NC_INVALID;
15338}
15339
15340// Set to an unsigned long value.
15341
15342void
15343Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15344{
15345 this->clear();
15346 this->classification_ = NC_INT;
15347 this->type_ = type;
15348 mpz_init_set_ui(this->u_.int_val, val);
15349}
15350
15351// Set to an integer value.
15352
15353void
15354Numeric_constant::set_int(Type* type, const mpz_t val)
15355{
15356 this->clear();
15357 this->classification_ = NC_INT;
15358 this->type_ = type;
15359 mpz_init_set(this->u_.int_val, val);
15360}
15361
15362// Set to a rune value.
15363
15364void
15365Numeric_constant::set_rune(Type* type, const mpz_t val)
15366{
15367 this->clear();
15368 this->classification_ = NC_RUNE;
15369 this->type_ = type;
15370 mpz_init_set(this->u_.int_val, val);
15371}
15372
15373// Set to a floating point value.
15374
15375void
15376Numeric_constant::set_float(Type* type, const mpfr_t val)
15377{
15378 this->clear();
15379 this->classification_ = NC_FLOAT;
15380 this->type_ = type;
833b523c 15381 // Numeric constants do not have negative zero values, so remove
15382 // them here. They also don't have infinity or NaN values, but we
15383 // should never see them here.
15384 if (mpfr_zero_p(val))
15385 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15386 else
15387 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15388}
15389
15390// Set to a complex value.
15391
15392void
15393Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15394{
15395 this->clear();
15396 this->classification_ = NC_COMPLEX;
15397 this->type_ = type;
15398 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15399 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15400}
15401
15402// Get an int value.
15403
15404void
15405Numeric_constant::get_int(mpz_t* val) const
15406{
15407 go_assert(this->is_int());
15408 mpz_init_set(*val, this->u_.int_val);
15409}
15410
15411// Get a rune value.
15412
15413void
15414Numeric_constant::get_rune(mpz_t* val) const
15415{
15416 go_assert(this->is_rune());
15417 mpz_init_set(*val, this->u_.int_val);
15418}
15419
15420// Get a floating point value.
15421
15422void
15423Numeric_constant::get_float(mpfr_t* val) const
15424{
15425 go_assert(this->is_float());
15426 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15427}
15428
15429// Get a complex value.
15430
15431void
15432Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15433{
15434 go_assert(this->is_complex());
15435 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15436 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15437}
15438
15439// Express value as unsigned long if possible.
15440
15441Numeric_constant::To_unsigned_long
15442Numeric_constant::to_unsigned_long(unsigned long* val) const
15443{
15444 switch (this->classification_)
15445 {
15446 case NC_INT:
15447 case NC_RUNE:
15448 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15449 case NC_FLOAT:
15450 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15451 case NC_COMPLEX:
15452 if (!mpfr_zero_p(this->u_.complex_val.imag))
15453 return NC_UL_NOTINT;
15454 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15455 default:
15456 go_unreachable();
15457 }
15458}
15459
15460// Express integer value as unsigned long if possible.
15461
15462Numeric_constant::To_unsigned_long
15463Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15464 unsigned long *val) const
15465{
15466 if (mpz_sgn(ival) < 0)
15467 return NC_UL_NEGATIVE;
15468 unsigned long ui = mpz_get_ui(ival);
15469 if (mpz_cmp_ui(ival, ui) != 0)
15470 return NC_UL_BIG;
15471 *val = ui;
15472 return NC_UL_VALID;
15473}
15474
15475// Express floating point value as unsigned long if possible.
15476
15477Numeric_constant::To_unsigned_long
15478Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15479 unsigned long *val) const
15480{
15481 if (!mpfr_integer_p(fval))
15482 return NC_UL_NOTINT;
15483 mpz_t ival;
15484 mpz_init(ival);
15485 mpfr_get_z(ival, fval, GMP_RNDN);
15486 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15487 mpz_clear(ival);
15488 return ret;
15489}
15490
15491// Convert value to integer if possible.
15492
15493bool
15494Numeric_constant::to_int(mpz_t* val) const
15495{
15496 switch (this->classification_)
15497 {
15498 case NC_INT:
15499 case NC_RUNE:
15500 mpz_init_set(*val, this->u_.int_val);
15501 return true;
15502 case NC_FLOAT:
15503 if (!mpfr_integer_p(this->u_.float_val))
15504 return false;
15505 mpz_init(*val);
15506 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15507 return true;
15508 case NC_COMPLEX:
15509 if (!mpfr_zero_p(this->u_.complex_val.imag)
15510 || !mpfr_integer_p(this->u_.complex_val.real))
15511 return false;
15512 mpz_init(*val);
15513 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15514 return true;
15515 default:
15516 go_unreachable();
15517 }
15518}
15519
15520// Convert value to floating point if possible.
15521
15522bool
15523Numeric_constant::to_float(mpfr_t* val) const
15524{
15525 switch (this->classification_)
15526 {
15527 case NC_INT:
15528 case NC_RUNE:
15529 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15530 return true;
15531 case NC_FLOAT:
15532 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15533 return true;
15534 case NC_COMPLEX:
15535 if (!mpfr_zero_p(this->u_.complex_val.imag))
15536 return false;
15537 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15538 return true;
15539 default:
15540 go_unreachable();
15541 }
15542}
15543
15544// Convert value to complex.
15545
15546bool
15547Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15548{
15549 switch (this->classification_)
15550 {
15551 case NC_INT:
15552 case NC_RUNE:
15553 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15554 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15555 return true;
15556 case NC_FLOAT:
15557 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15558 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15559 return true;
15560 case NC_COMPLEX:
15561 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15562 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15563 return true;
15564 default:
15565 go_unreachable();
15566 }
15567}
15568
15569// Get the type.
15570
15571Type*
15572Numeric_constant::type() const
15573{
15574 if (this->type_ != NULL)
15575 return this->type_;
15576 switch (this->classification_)
15577 {
15578 case NC_INT:
15579 return Type::make_abstract_integer_type();
15580 case NC_RUNE:
15581 return Type::make_abstract_character_type();
15582 case NC_FLOAT:
15583 return Type::make_abstract_float_type();
15584 case NC_COMPLEX:
15585 return Type::make_abstract_complex_type();
15586 default:
15587 go_unreachable();
15588 }
15589}
15590
15591// If the constant can be expressed in TYPE, then set the type of the
15592// constant to TYPE and return true. Otherwise return false, and, if
15593// ISSUE_ERROR is true, report an appropriate error message.
15594
15595bool
15596Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15597{
15598 bool ret;
15599 if (type == NULL)
15600 ret = true;
15601 else if (type->integer_type() != NULL)
15602 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15603 else if (type->float_type() != NULL)
15604 ret = this->check_float_type(type->float_type(), issue_error, loc);
15605 else if (type->complex_type() != NULL)
15606 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15607 else
15608 go_unreachable();
15609 if (ret)
15610 this->type_ = type;
15611 return ret;
15612}
15613
15614// Check whether the constant can be expressed in an integer type.
15615
15616bool
15617Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15618 Location location) const
15619{
15620 mpz_t val;
15621 switch (this->classification_)
15622 {
15623 case NC_INT:
15624 case NC_RUNE:
15625 mpz_init_set(val, this->u_.int_val);
15626 break;
15627
15628 case NC_FLOAT:
15629 if (!mpfr_integer_p(this->u_.float_val))
15630 {
15631 if (issue_error)
15632 error_at(location, "floating point constant truncated to integer");
15633 return false;
15634 }
15635 mpz_init(val);
15636 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15637 break;
15638
15639 case NC_COMPLEX:
15640 if (!mpfr_integer_p(this->u_.complex_val.real)
15641 || !mpfr_zero_p(this->u_.complex_val.imag))
15642 {
15643 if (issue_error)
15644 error_at(location, "complex constant truncated to integer");
15645 return false;
15646 }
15647 mpz_init(val);
15648 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15649 break;
15650
15651 default:
15652 go_unreachable();
15653 }
15654
15655 bool ret;
15656 if (type->is_abstract())
15657 ret = true;
15658 else
15659 {
15660 int bits = mpz_sizeinbase(val, 2);
15661 if (type->is_unsigned())
15662 {
15663 // For an unsigned type we can only accept a nonnegative
15664 // number, and we must be able to represents at least BITS.
15665 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15666 }
15667 else
15668 {
15669 // For a signed type we need an extra bit to indicate the
15670 // sign. We have to handle the most negative integer
15671 // specially.
15672 ret = (bits + 1 <= type->bits()
15673 || (bits <= type->bits()
15674 && mpz_sgn(val) < 0
15675 && (mpz_scan1(val, 0)
15676 == static_cast<unsigned long>(type->bits() - 1))
15677 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15678 }
15679 }
15680
15681 if (!ret && issue_error)
15682 error_at(location, "integer constant overflow");
15683
15684 return ret;
15685}
15686
15687// Check whether the constant can be expressed in a floating point
15688// type.
15689
15690bool
15691Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15692 Location location)
0c77715b 15693{
15694 mpfr_t val;
15695 switch (this->classification_)
15696 {
15697 case NC_INT:
15698 case NC_RUNE:
15699 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15700 break;
15701
15702 case NC_FLOAT:
15703 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15704 break;
15705
15706 case NC_COMPLEX:
15707 if (!mpfr_zero_p(this->u_.complex_val.imag))
15708 {
15709 if (issue_error)
15710 error_at(location, "complex constant truncated to float");
15711 return false;
15712 }
15713 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15714 break;
15715
15716 default:
15717 go_unreachable();
15718 }
15719
15720 bool ret;
15721 if (type->is_abstract())
15722 ret = true;
15723 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15724 {
15725 // A NaN or Infinity always fits in the range of the type.
15726 ret = true;
15727 }
15728 else
15729 {
15730 mp_exp_t exp = mpfr_get_exp(val);
15731 mp_exp_t max_exp;
15732 switch (type->bits())
15733 {
15734 case 32:
15735 max_exp = 128;
15736 break;
15737 case 64:
15738 max_exp = 1024;
15739 break;
15740 default:
15741 go_unreachable();
15742 }
15743
15744 ret = exp <= max_exp;
d0bcce51 15745
15746 if (ret)
15747 {
15748 // Round the constant to the desired type.
15749 mpfr_t t;
15750 mpfr_init(t);
15751 switch (type->bits())
15752 {
15753 case 32:
15754 mpfr_set_prec(t, 24);
15755 break;
15756 case 64:
15757 mpfr_set_prec(t, 53);
15758 break;
15759 default:
15760 go_unreachable();
15761 }
15762 mpfr_set(t, val, GMP_RNDN);
15763 mpfr_set(val, t, GMP_RNDN);
15764 mpfr_clear(t);
15765
15766 this->set_float(type, val);
15767 }
0c77715b 15768 }
15769
15770 mpfr_clear(val);
15771
15772 if (!ret && issue_error)
15773 error_at(location, "floating point constant overflow");
15774
15775 return ret;
15776}
15777
15778// Check whether the constant can be expressed in a complex type.
15779
15780bool
15781Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 15782 Location location)
0c77715b 15783{
15784 if (type->is_abstract())
15785 return true;
15786
15787 mp_exp_t max_exp;
15788 switch (type->bits())
15789 {
15790 case 64:
15791 max_exp = 128;
15792 break;
15793 case 128:
15794 max_exp = 1024;
15795 break;
15796 default:
15797 go_unreachable();
15798 }
15799
15800 mpfr_t real;
d0bcce51 15801 mpfr_t imag;
0c77715b 15802 switch (this->classification_)
15803 {
15804 case NC_INT:
15805 case NC_RUNE:
15806 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
d0bcce51 15807 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15808 break;
15809
15810 case NC_FLOAT:
15811 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
d0bcce51 15812 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15813 break;
15814
15815 case NC_COMPLEX:
0c77715b 15816 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
d0bcce51 15817 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
0c77715b 15818 break;
15819
15820 default:
15821 go_unreachable();
15822 }
15823
d0bcce51 15824 bool ret = true;
15825 if (!mpfr_nan_p(real)
15826 && !mpfr_inf_p(real)
15827 && !mpfr_zero_p(real)
15828 && mpfr_get_exp(real) > max_exp)
15829 {
15830 if (issue_error)
15831 error_at(location, "complex real part overflow");
15832 ret = false;
15833 }
0c77715b 15834
d0bcce51 15835 if (!mpfr_nan_p(imag)
15836 && !mpfr_inf_p(imag)
15837 && !mpfr_zero_p(imag)
15838 && mpfr_get_exp(imag) > max_exp)
15839 {
15840 if (issue_error)
15841 error_at(location, "complex imaginary part overflow");
15842 ret = false;
15843 }
0c77715b 15844
d0bcce51 15845 if (ret)
15846 {
15847 // Round the constant to the desired type.
15848 mpfr_t t;
15849 mpfr_init(t);
15850 switch (type->bits())
15851 {
15852 case 64:
15853 mpfr_set_prec(t, 24);
15854 break;
15855 case 128:
15856 mpfr_set_prec(t, 53);
15857 break;
15858 default:
15859 go_unreachable();
15860 }
15861 mpfr_set(t, real, GMP_RNDN);
15862 mpfr_set(real, t, GMP_RNDN);
15863 mpfr_set(t, imag, GMP_RNDN);
15864 mpfr_set(imag, t, GMP_RNDN);
15865 mpfr_clear(t);
15866
15867 this->set_complex(type, real, imag);
15868 }
15869
15870 mpfr_clear(real);
15871 mpfr_clear(imag);
0c77715b 15872
15873 return ret;
15874}
15875
15876// Return an Expression for this value.
15877
15878Expression*
15879Numeric_constant::expression(Location loc) const
15880{
15881 switch (this->classification_)
15882 {
15883 case NC_INT:
15884 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15885 case NC_RUNE:
15886 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15887 case NC_FLOAT:
15888 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15889 case NC_COMPLEX:
15890 return Expression::make_complex(&this->u_.complex_val.real,
15891 &this->u_.complex_val.imag,
15892 this->type_, loc);
15893 default:
15894 go_unreachable();
15895 }
15896}