]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
PR go/60870
[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();
fe2f84cf 763 if (this->variable_->is_variable())
764 is_in_heap = this->variable_->var_value()->is_in_heap();
765 else if (this->variable_->is_result_variable())
766 is_in_heap = this->variable_->result_var_value()->is_in_heap();
767 else
c3e6f413 768 go_unreachable();
c6777780 769
770 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 771 if (is_in_heap)
c6777780 772 ret = context->backend()->indirect_expression(ret, true, loc);
773 return expr_to_tree(ret);
e440a328 774}
775
d751bb78 776// Ast dump for variable expression.
777
778void
779Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
780{
781 ast_dump_context->ostream() << this->variable_->name() ;
782}
783
e440a328 784// Make a reference to a variable in an expression.
785
786Expression*
b13c66cd 787Expression::make_var_reference(Named_object* var, Location location)
e440a328 788{
789 if (var->is_sink())
790 return Expression::make_sink(location);
791
792 // FIXME: Creating a new object for each reference to a variable is
793 // wasteful.
794 return new Var_expression(var, location);
795}
796
797// Class Temporary_reference_expression.
798
799// The type.
800
801Type*
802Temporary_reference_expression::do_type()
803{
804 return this->statement_->type();
805}
806
807// Called if something takes the address of this temporary variable.
808// We never have to move temporary variables to the heap, but we do
809// need to know that they must live in the stack rather than in a
810// register.
811
812void
813Temporary_reference_expression::do_address_taken(bool)
814{
815 this->statement_->set_is_address_taken();
816}
817
818// Get a tree referring to the variable.
819
820tree
eefc1ed3 821Temporary_reference_expression::do_get_tree(Translate_context* context)
e440a328 822{
cd440cff 823 Gogo* gogo = context->gogo();
eefc1ed3 824 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 825 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 826
cd440cff 827 // The backend can't always represent the same set of recursive types
eefc1ed3 828 // that the Go frontend can. In some cases this means that a
829 // temporary variable won't have the right backend type. Correct
830 // that here by adding a type cast. We need to use base() to push
831 // the circularity down one level.
cd440cff 832 Type* stype = this->statement_->type();
ceeb4318 833 if (!this->is_lvalue_
cd440cff 834 && stype->has_pointer()
835 && stype->deref()->is_void_type())
eefc1ed3 836 {
cd440cff 837 Btype* btype = this->type()->base()->get_backend(gogo);
838 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 839 }
cd440cff 840 return expr_to_tree(ret);
e440a328 841}
842
d751bb78 843// Ast dump for temporary reference.
844
845void
846Temporary_reference_expression::do_dump_expression(
847 Ast_dump_context* ast_dump_context) const
848{
849 ast_dump_context->dump_temp_variable_name(this->statement_);
850}
851
e440a328 852// Make a reference to a temporary variable.
853
ceeb4318 854Temporary_reference_expression*
e440a328 855Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 856 Location location)
e440a328 857{
858 return new Temporary_reference_expression(statement, location);
859}
860
e9d3367e 861// Class Set_and_use_temporary_expression.
862
863// Return the type.
864
865Type*
866Set_and_use_temporary_expression::do_type()
867{
868 return this->statement_->type();
869}
870
0afbb937 871// Determine the type of the expression.
872
873void
874Set_and_use_temporary_expression::do_determine_type(
875 const Type_context* context)
876{
877 this->expr_->determine_type(context);
878}
879
e9d3367e 880// Take the address.
881
882void
883Set_and_use_temporary_expression::do_address_taken(bool)
884{
885 this->statement_->set_is_address_taken();
886}
887
888// Return the backend representation.
889
890tree
891Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
892{
893 Bvariable* bvar = this->statement_->get_backend_variable(context);
894 tree var_tree = var_to_tree(bvar);
895 tree expr_tree = this->expr_->get_tree(context);
896 if (var_tree == error_mark_node || expr_tree == error_mark_node)
897 return error_mark_node;
898 Location loc = this->location();
899 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
900 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
901 var_tree, expr_tree),
902 var_tree);
903}
904
905// Dump.
906
907void
908Set_and_use_temporary_expression::do_dump_expression(
909 Ast_dump_context* ast_dump_context) const
910{
911 ast_dump_context->ostream() << '(';
912 ast_dump_context->dump_temp_variable_name(this->statement_);
913 ast_dump_context->ostream() << " = ";
914 this->expr_->dump_expression(ast_dump_context);
915 ast_dump_context->ostream() << ')';
916}
917
918// Make a set-and-use temporary.
919
920Set_and_use_temporary_expression*
921Expression::make_set_and_use_temporary(Temporary_statement* statement,
922 Expression* expr, Location location)
923{
924 return new Set_and_use_temporary_expression(statement, expr, location);
925}
926
e440a328 927// A sink expression--a use of the blank identifier _.
928
929class Sink_expression : public Expression
930{
931 public:
b13c66cd 932 Sink_expression(Location location)
e440a328 933 : Expression(EXPRESSION_SINK, location),
934 type_(NULL), var_(NULL_TREE)
935 { }
936
937 protected:
4f2138d7 938 bool
e440a328 939 do_discarding_value()
4f2138d7 940 { return true; }
e440a328 941
942 Type*
943 do_type();
944
945 void
946 do_determine_type(const Type_context*);
947
948 Expression*
949 do_copy()
950 { return new Sink_expression(this->location()); }
951
952 tree
953 do_get_tree(Translate_context*);
954
d751bb78 955 void
956 do_dump_expression(Ast_dump_context*) const;
957
e440a328 958 private:
959 // The type of this sink variable.
960 Type* type_;
961 // The temporary variable we generate.
962 tree var_;
963};
964
965// Return the type of a sink expression.
966
967Type*
968Sink_expression::do_type()
969{
970 if (this->type_ == NULL)
971 return Type::make_sink_type();
972 return this->type_;
973}
974
975// Determine the type of a sink expression.
976
977void
978Sink_expression::do_determine_type(const Type_context* context)
979{
980 if (context->type != NULL)
981 this->type_ = context->type;
982}
983
984// Return a temporary variable for a sink expression. This will
985// presumably be a write-only variable which the middle-end will drop.
986
987tree
988Sink_expression::do_get_tree(Translate_context* context)
989{
990 if (this->var_ == NULL_TREE)
991 {
c484d925 992 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
9f0e0513 993 Btype* bt = this->type_->get_backend(context->gogo());
994 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
e440a328 995 }
996 return this->var_;
997}
998
d751bb78 999// Ast dump for sink expression.
1000
1001void
1002Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1003{
1004 ast_dump_context->ostream() << "_" ;
1005}
1006
e440a328 1007// Make a sink expression.
1008
1009Expression*
b13c66cd 1010Expression::make_sink(Location location)
e440a328 1011{
1012 return new Sink_expression(location);
1013}
1014
1015// Class Func_expression.
1016
1017// FIXME: Can a function expression appear in a constant expression?
1018// The value is unchanging. Initializing a constant to the address of
1019// a function seems like it could work, though there might be little
1020// point to it.
1021
e440a328 1022// Traversal.
1023
1024int
1025Func_expression::do_traverse(Traverse* traverse)
1026{
1027 return (this->closure_ == NULL
1028 ? TRAVERSE_CONTINUE
1029 : Expression::traverse(&this->closure_, traverse));
1030}
1031
1032// Return the type of a function expression.
1033
1034Type*
1035Func_expression::do_type()
1036{
1037 if (this->function_->is_function())
1038 return this->function_->func_value()->type();
1039 else if (this->function_->is_function_declaration())
1040 return this->function_->func_declaration_value()->type();
1041 else
c3e6f413 1042 go_unreachable();
e440a328 1043}
1044
8381eda7 1045// Get the tree for the code of a function expression.
e440a328 1046
97267c39 1047Bexpression*
8381eda7 1048Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1049{
1050 Function_type* fntype;
8381eda7 1051 if (no->is_function())
1052 fntype = no->func_value()->type();
1053 else if (no->is_function_declaration())
1054 fntype = no->func_declaration_value()->type();
e440a328 1055 else
c3e6f413 1056 go_unreachable();
e440a328 1057
1058 // Builtin functions are handled specially by Call_expression. We
1059 // can't take their address.
1060 if (fntype->is_builtin())
1061 {
8381eda7 1062 error_at(loc,
cb0e02f3 1063 "invalid use of special builtin function %qs; must be called",
8381eda7 1064 no->message_name().c_str());
97267c39 1065 return gogo->backend()->error_expression();
e440a328 1066 }
1067
97267c39 1068 Bfunction* fndecl;
e440a328 1069 if (no->is_function())
cf3cae55 1070 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1071 else if (no->is_function_declaration())
cf3cae55 1072 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1073 else
c3e6f413 1074 go_unreachable();
e440a328 1075
97267c39 1076 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1077}
1078
1079// Get the tree for a function expression. This is used when we take
8381eda7 1080// the address of a function rather than simply calling it. A func
1081// value is represented as a pointer to a block of memory. The first
1082// word of that memory is a pointer to the function code. The
1083// remaining parts of that memory are the addresses of variables that
1084// the function closes over.
e440a328 1085
1086tree
1087Func_expression::do_get_tree(Translate_context* context)
1088{
8381eda7 1089 // If there is no closure, just use the function descriptor.
2010c17a 1090 if (this->closure_ == NULL)
8381eda7 1091 {
1092 Gogo* gogo = context->gogo();
1093 Named_object* no = this->function_;
1094 Expression* descriptor;
1095 if (no->is_function())
1096 descriptor = no->func_value()->descriptor(gogo, no);
1097 else if (no->is_function_declaration())
1098 {
1099 if (no->func_declaration_value()->type()->is_builtin())
1100 {
1101 error_at(this->location(),
1102 ("invalid use of special builtin function %qs; "
1103 "must be called"),
1104 no->message_name().c_str());
1105 return error_mark_node;
1106 }
1107 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1108 }
1109 else
1110 go_unreachable();
2010c17a 1111
8381eda7 1112 tree dtree = descriptor->get_tree(context);
1113 if (dtree == error_mark_node)
1114 return error_mark_node;
1115 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1116 }
e440a328 1117
8381eda7 1118 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1119
8381eda7 1120 // If there is a closure, then the closure is itself the function
1121 // expression. It is a pointer to a struct whose first field points
1122 // to the function code and whose remaining fields are the addresses
1123 // of the closed-over variables.
1124 return this->closure_->get_tree(context);
e440a328 1125}
1126
d751bb78 1127// Ast dump for function.
1128
1129void
1130Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1131{
8b1c301d 1132 ast_dump_context->ostream() << this->function_->name();
1133 if (this->closure_ != NULL)
1134 {
1135 ast_dump_context->ostream() << " {closure = ";
1136 this->closure_->dump_expression(ast_dump_context);
1137 ast_dump_context->ostream() << "}";
1138 }
d751bb78 1139}
1140
e440a328 1141// Make a reference to a function in an expression.
1142
1143Expression*
1144Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1145 Location location)
e440a328 1146{
1147 return new Func_expression(function, closure, location);
1148}
1149
c6837989 1150// Class Func_descriptor_expression.
8381eda7 1151
c6837989 1152// Constructor.
8381eda7 1153
c6837989 1154Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1155 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1156 fn_(fn), dvar_(NULL)
c6837989 1157{
1158 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1159}
8381eda7 1160
c6837989 1161// Traversal.
8381eda7 1162
c6837989 1163int
1164Func_descriptor_expression::do_traverse(Traverse*)
1165{
1166 return TRAVERSE_CONTINUE;
1167}
8381eda7 1168
1169// All function descriptors have the same type.
1170
1171Type* Func_descriptor_expression::descriptor_type;
1172
1173void
1174Func_descriptor_expression::make_func_descriptor_type()
1175{
1176 if (Func_descriptor_expression::descriptor_type != NULL)
1177 return;
1178 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1179 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1180 Func_descriptor_expression::descriptor_type =
1181 Type::make_builtin_named_type("functionDescriptor", struct_type);
1182}
1183
1184Type*
1185Func_descriptor_expression::do_type()
1186{
1187 Func_descriptor_expression::make_func_descriptor_type();
1188 return Func_descriptor_expression::descriptor_type;
1189}
1190
1191// The tree for a function descriptor.
1192
1193tree
1194Func_descriptor_expression::do_get_tree(Translate_context* context)
1195{
1196 if (this->dvar_ != NULL)
1197 return var_to_tree(this->dvar_);
1198
1199 Gogo* gogo = context->gogo();
1200 Named_object* no = this->fn_;
1201 Location loc = no->location();
1202
1203 std::string var_name;
1204 if (no->package() == NULL)
1205 var_name = gogo->pkgpath_symbol();
1206 else
1207 var_name = no->package()->pkgpath_symbol();
1208 var_name.push_back('.');
1209 var_name.append(Gogo::unpack_hidden_name(no->name()));
1210 var_name.append("$descriptor");
1211
1212 Btype* btype = this->type()->get_backend(gogo);
1213
1214 Bvariable* bvar;
1215 if (no->package() != NULL
1216 || Linemap::is_predeclared_location(no->location()))
f8bdf81a 1217 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1218 loc);
8381eda7 1219 else
1220 {
1221 Location bloc = Linemap::predeclared_location();
1222 bool is_hidden = ((no->is_function()
1223 && no->func_value()->enclosing() != NULL)
1224 || Gogo::is_thunk(no));
1225 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1226 btype, bloc);
1227 Expression_list* vals = new Expression_list();
f8bdf81a 1228 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1229 Expression* init =
1230 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1231 Translate_context bcontext(gogo, NULL, NULL, NULL);
1232 bcontext.set_is_const();
1233 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1234 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1235 false, btype, bloc, binit);
1236 }
1237
1238 this->dvar_ = bvar;
1239 return var_to_tree(bvar);
1240}
1241
c6837989 1242// Print a function descriptor expression.
1243
1244void
1245Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1246{
1247 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1248}
1249
8381eda7 1250// Make a function descriptor expression.
1251
c6837989 1252Func_descriptor_expression*
1253Expression::make_func_descriptor(Named_object* fn)
8381eda7 1254{
c6837989 1255 return new Func_descriptor_expression(fn);
8381eda7 1256}
1257
1258// Make the function descriptor type, so that it can be converted.
1259
1260void
1261Expression::make_func_descriptor_type()
1262{
1263 Func_descriptor_expression::make_func_descriptor_type();
1264}
1265
1266// A reference to just the code of a function.
1267
1268class Func_code_reference_expression : public Expression
1269{
1270 public:
1271 Func_code_reference_expression(Named_object* function, Location location)
1272 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1273 function_(function)
1274 { }
1275
1276 protected:
1277 int
1278 do_traverse(Traverse*)
1279 { return TRAVERSE_CONTINUE; }
1280
f9ca30f9 1281 bool
1282 do_is_immutable() const
1283 { return true; }
1284
8381eda7 1285 Type*
1286 do_type()
1287 { return Type::make_pointer_type(Type::make_void_type()); }
1288
1289 void
1290 do_determine_type(const Type_context*)
1291 { }
1292
1293 Expression*
1294 do_copy()
1295 {
1296 return Expression::make_func_code_reference(this->function_,
1297 this->location());
1298 }
1299
1300 tree
1301 do_get_tree(Translate_context*);
1302
1303 void
1304 do_dump_expression(Ast_dump_context* context) const
1305 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1306
1307 private:
1308 // The function.
1309 Named_object* function_;
1310};
1311
1312// Get the tree for a reference to function code.
1313
1314tree
1315Func_code_reference_expression::do_get_tree(Translate_context* context)
1316{
97267c39 1317 Bexpression* ret =
1318 Func_expression::get_code_pointer(context->gogo(), this->function_,
1319 this->location());
1320 return expr_to_tree(ret);
8381eda7 1321}
1322
1323// Make a reference to the code of a function.
1324
1325Expression*
1326Expression::make_func_code_reference(Named_object* function, Location location)
1327{
1328 return new Func_code_reference_expression(function, location);
1329}
1330
e440a328 1331// Class Unknown_expression.
1332
1333// Return the name of an unknown expression.
1334
1335const std::string&
1336Unknown_expression::name() const
1337{
1338 return this->named_object_->name();
1339}
1340
1341// Lower a reference to an unknown name.
1342
1343Expression*
ceeb4318 1344Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1345{
b13c66cd 1346 Location location = this->location();
e440a328 1347 Named_object* no = this->named_object_;
deded542 1348 Named_object* real;
1349 if (!no->is_unknown())
1350 real = no;
1351 else
e440a328 1352 {
deded542 1353 real = no->unknown_value()->real_named_object();
1354 if (real == NULL)
1355 {
1356 if (this->is_composite_literal_key_)
1357 return this;
acf8e158 1358 if (!this->no_error_message_)
1359 error_at(location, "reference to undefined name %qs",
1360 this->named_object_->message_name().c_str());
deded542 1361 return Expression::make_error(location);
1362 }
e440a328 1363 }
1364 switch (real->classification())
1365 {
1366 case Named_object::NAMED_OBJECT_CONST:
1367 return Expression::make_const_reference(real, location);
1368 case Named_object::NAMED_OBJECT_TYPE:
1369 return Expression::make_type(real->type_value(), location);
1370 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1371 if (this->is_composite_literal_key_)
1372 return this;
acf8e158 1373 if (!this->no_error_message_)
1374 error_at(location, "reference to undefined type %qs",
1375 real->message_name().c_str());
e440a328 1376 return Expression::make_error(location);
1377 case Named_object::NAMED_OBJECT_VAR:
7d834090 1378 real->var_value()->set_is_used();
e440a328 1379 return Expression::make_var_reference(real, location);
1380 case Named_object::NAMED_OBJECT_FUNC:
1381 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1382 return Expression::make_func_reference(real, NULL, location);
1383 case Named_object::NAMED_OBJECT_PACKAGE:
1384 if (this->is_composite_literal_key_)
1385 return this;
acf8e158 1386 if (!this->no_error_message_)
1387 error_at(location, "unexpected reference to package");
e440a328 1388 return Expression::make_error(location);
1389 default:
c3e6f413 1390 go_unreachable();
e440a328 1391 }
1392}
1393
d751bb78 1394// Dump the ast representation for an unknown expression to a dump context.
1395
1396void
1397Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1398{
1399 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1400 << ")";
d751bb78 1401}
1402
e440a328 1403// Make a reference to an unknown name.
1404
acf8e158 1405Unknown_expression*
b13c66cd 1406Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1407{
e440a328 1408 return new Unknown_expression(no, location);
1409}
1410
1411// A boolean expression.
1412
1413class Boolean_expression : public Expression
1414{
1415 public:
b13c66cd 1416 Boolean_expression(bool val, Location location)
e440a328 1417 : Expression(EXPRESSION_BOOLEAN, location),
1418 val_(val), type_(NULL)
1419 { }
1420
1421 static Expression*
1422 do_import(Import*);
1423
1424 protected:
1425 bool
1426 do_is_constant() const
1427 { return true; }
1428
0e168074 1429 bool
1430 do_is_immutable() const
1431 { return true; }
1432
e440a328 1433 Type*
1434 do_type();
1435
1436 void
1437 do_determine_type(const Type_context*);
1438
1439 Expression*
1440 do_copy()
1441 { return this; }
1442
1443 tree
1444 do_get_tree(Translate_context*)
1445 { return this->val_ ? boolean_true_node : boolean_false_node; }
1446
1447 void
1448 do_export(Export* exp) const
1449 { exp->write_c_string(this->val_ ? "true" : "false"); }
1450
d751bb78 1451 void
1452 do_dump_expression(Ast_dump_context* ast_dump_context) const
1453 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1454
e440a328 1455 private:
1456 // The constant.
1457 bool val_;
1458 // The type as determined by context.
1459 Type* type_;
1460};
1461
1462// Get the type.
1463
1464Type*
1465Boolean_expression::do_type()
1466{
1467 if (this->type_ == NULL)
1468 this->type_ = Type::make_boolean_type();
1469 return this->type_;
1470}
1471
1472// Set the type from the context.
1473
1474void
1475Boolean_expression::do_determine_type(const Type_context* context)
1476{
1477 if (this->type_ != NULL && !this->type_->is_abstract())
1478 ;
1479 else if (context->type != NULL && context->type->is_boolean_type())
1480 this->type_ = context->type;
1481 else if (!context->may_be_abstract)
1482 this->type_ = Type::lookup_bool_type();
1483}
1484
1485// Import a boolean constant.
1486
1487Expression*
1488Boolean_expression::do_import(Import* imp)
1489{
1490 if (imp->peek_char() == 't')
1491 {
1492 imp->require_c_string("true");
1493 return Expression::make_boolean(true, imp->location());
1494 }
1495 else
1496 {
1497 imp->require_c_string("false");
1498 return Expression::make_boolean(false, imp->location());
1499 }
1500}
1501
1502// Make a boolean expression.
1503
1504Expression*
b13c66cd 1505Expression::make_boolean(bool val, Location location)
e440a328 1506{
1507 return new Boolean_expression(val, location);
1508}
1509
1510// Class String_expression.
1511
1512// Get the type.
1513
1514Type*
1515String_expression::do_type()
1516{
1517 if (this->type_ == NULL)
1518 this->type_ = Type::make_string_type();
1519 return this->type_;
1520}
1521
1522// Set the type from the context.
1523
1524void
1525String_expression::do_determine_type(const Type_context* context)
1526{
1527 if (this->type_ != NULL && !this->type_->is_abstract())
1528 ;
1529 else if (context->type != NULL && context->type->is_string_type())
1530 this->type_ = context->type;
1531 else if (!context->may_be_abstract)
1532 this->type_ = Type::lookup_string_type();
1533}
1534
1535// Build a string constant.
1536
1537tree
1538String_expression::do_get_tree(Translate_context* context)
1539{
2c809f8f 1540 Gogo* gogo = context->gogo();
1541 Btype* btype = Type::make_string_type()->get_backend(gogo);
1542
1543 Location loc = this->location();
1544 std::vector<Bexpression*> init(2);
1545 Bexpression* str_cst =
1546 gogo->backend()->string_constant_expression(this->val_);
1547 init[0] = gogo->backend()->address_expression(str_cst, loc);
1548
1549 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1550 mpz_t lenval;
1551 mpz_init_set_ui(lenval, this->val_.length());
1552 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1553 mpz_clear(lenval);
1554
1555 Bexpression* ret = gogo->backend()->constructor_expression(btype, init, loc);
1556 return expr_to_tree(ret);
e440a328 1557}
1558
8b1c301d 1559 // Write string literal to string dump.
e440a328 1560
1561void
8b1c301d 1562String_expression::export_string(String_dump* exp,
1563 const String_expression* str)
e440a328 1564{
1565 std::string s;
8b1c301d 1566 s.reserve(str->val_.length() * 4 + 2);
e440a328 1567 s += '"';
8b1c301d 1568 for (std::string::const_iterator p = str->val_.begin();
1569 p != str->val_.end();
e440a328 1570 ++p)
1571 {
1572 if (*p == '\\' || *p == '"')
1573 {
1574 s += '\\';
1575 s += *p;
1576 }
1577 else if (*p >= 0x20 && *p < 0x7f)
1578 s += *p;
1579 else if (*p == '\n')
1580 s += "\\n";
1581 else if (*p == '\t')
1582 s += "\\t";
1583 else
1584 {
1585 s += "\\x";
1586 unsigned char c = *p;
1587 unsigned int dig = c >> 4;
1588 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1589 dig = c & 0xf;
1590 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1591 }
1592 }
1593 s += '"';
1594 exp->write_string(s);
1595}
1596
8b1c301d 1597// Export a string expression.
1598
1599void
1600String_expression::do_export(Export* exp) const
1601{
1602 String_expression::export_string(exp, this);
1603}
1604
e440a328 1605// Import a string expression.
1606
1607Expression*
1608String_expression::do_import(Import* imp)
1609{
1610 imp->require_c_string("\"");
1611 std::string val;
1612 while (true)
1613 {
1614 int c = imp->get_char();
1615 if (c == '"' || c == -1)
1616 break;
1617 if (c != '\\')
1618 val += static_cast<char>(c);
1619 else
1620 {
1621 c = imp->get_char();
1622 if (c == '\\' || c == '"')
1623 val += static_cast<char>(c);
1624 else if (c == 'n')
1625 val += '\n';
1626 else if (c == 't')
1627 val += '\t';
1628 else if (c == 'x')
1629 {
1630 c = imp->get_char();
1631 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1632 c = imp->get_char();
1633 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1634 char v = (vh << 4) | vl;
1635 val += v;
1636 }
1637 else
1638 {
1639 error_at(imp->location(), "bad string constant");
1640 return Expression::make_error(imp->location());
1641 }
1642 }
1643 }
1644 return Expression::make_string(val, imp->location());
1645}
1646
d751bb78 1647// Ast dump for string expression.
1648
1649void
1650String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1651{
8b1c301d 1652 String_expression::export_string(ast_dump_context, this);
d751bb78 1653}
1654
e440a328 1655// Make a string expression.
1656
1657Expression*
b13c66cd 1658Expression::make_string(const std::string& val, Location location)
e440a328 1659{
1660 return new String_expression(val, location);
1661}
1662
2c809f8f 1663// An expression that evaluates to some characteristic of a string.
1664// This is used when indexing, bound-checking, or nil checking a string.
1665
1666class String_info_expression : public Expression
1667{
1668 public:
1669 String_info_expression(Expression* string, String_info string_info,
1670 Location location)
1671 : Expression(EXPRESSION_STRING_INFO, location),
1672 string_(string), string_info_(string_info)
1673 { }
1674
1675 protected:
1676 Type*
1677 do_type();
1678
1679 void
1680 do_determine_type(const Type_context*)
1681 { go_unreachable(); }
1682
1683 Expression*
1684 do_copy()
1685 {
1686 return new String_info_expression(this->string_->copy(), this->string_info_,
1687 this->location());
1688 }
1689
1690 tree
1691 do_get_tree(Translate_context* context);
1692
1693 void
1694 do_dump_expression(Ast_dump_context*) const;
1695
1696 void
1697 do_issue_nil_check()
1698 { this->string_->issue_nil_check(); }
1699
1700 private:
1701 // The string for which we are getting information.
1702 Expression* string_;
1703 // What information we want.
1704 String_info string_info_;
1705};
1706
1707// Return the type of the string info.
1708
1709Type*
1710String_info_expression::do_type()
1711{
1712 switch (this->string_info_)
1713 {
1714 case STRING_INFO_DATA:
1715 {
1716 Type* byte_type = Type::lookup_integer_type("uint8");
1717 return Type::make_pointer_type(byte_type);
1718 }
1719 case STRING_INFO_LENGTH:
1720 return Type::lookup_integer_type("int");
1721 default:
1722 go_unreachable();
1723 }
1724}
1725
1726// Return string information in GENERIC.
1727
1728tree
1729String_info_expression::do_get_tree(Translate_context* context)
1730{
1731 Gogo* gogo = context->gogo();
1732
1733 Bexpression* bstring = tree_to_expr(this->string_->get_tree(context));
1734 Bexpression* ret;
1735 switch (this->string_info_)
1736 {
1737 case STRING_INFO_DATA:
1738 case STRING_INFO_LENGTH:
1739 ret = gogo->backend()->struct_field_expression(bstring, this->string_info_,
1740 this->location());
1741 break;
1742 default:
1743 go_unreachable();
1744 }
1745 return expr_to_tree(ret);
1746}
1747
1748// Dump ast representation for a type info expression.
1749
1750void
1751String_info_expression::do_dump_expression(
1752 Ast_dump_context* ast_dump_context) const
1753{
1754 ast_dump_context->ostream() << "stringinfo(";
1755 this->string_->dump_expression(ast_dump_context);
1756 ast_dump_context->ostream() << ",";
1757 ast_dump_context->ostream() <<
1758 (this->string_info_ == STRING_INFO_DATA ? "data"
1759 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1760 : "unknown");
1761 ast_dump_context->ostream() << ")";
1762}
1763
1764// Make a string info expression.
1765
1766Expression*
1767Expression::make_string_info(Expression* string, String_info string_info,
1768 Location location)
1769{
1770 return new String_info_expression(string, string_info, location);
1771}
1772
e440a328 1773// Make an integer expression.
1774
1775class Integer_expression : public Expression
1776{
1777 public:
5d4b8566 1778 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1779 Location location)
e440a328 1780 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1781 type_(type), is_character_constant_(is_character_constant)
e440a328 1782 { mpz_init_set(this->val_, *val); }
1783
1784 static Expression*
1785 do_import(Import*);
1786
8b1c301d 1787 // Write VAL to string dump.
e440a328 1788 static void
8b1c301d 1789 export_integer(String_dump* exp, const mpz_t val);
e440a328 1790
d751bb78 1791 // Write VAL to dump context.
1792 static void
1793 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1794
e440a328 1795 protected:
1796 bool
1797 do_is_constant() const
1798 { return true; }
1799
0e168074 1800 bool
1801 do_is_immutable() const
1802 { return true; }
1803
e440a328 1804 bool
0c77715b 1805 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1806
1807 Type*
1808 do_type();
1809
1810 void
1811 do_determine_type(const Type_context* context);
1812
1813 void
1814 do_check_types(Gogo*);
1815
1816 tree
1817 do_get_tree(Translate_context*);
1818
1819 Expression*
1820 do_copy()
5d4b8566 1821 {
1822 if (this->is_character_constant_)
1823 return Expression::make_character(&this->val_, this->type_,
1824 this->location());
1825 else
1826 return Expression::make_integer(&this->val_, this->type_,
1827 this->location());
1828 }
e440a328 1829
1830 void
1831 do_export(Export*) const;
1832
d751bb78 1833 void
1834 do_dump_expression(Ast_dump_context*) const;
1835
e440a328 1836 private:
1837 // The integer value.
1838 mpz_t val_;
1839 // The type so far.
1840 Type* type_;
5d4b8566 1841 // Whether this is a character constant.
1842 bool is_character_constant_;
e440a328 1843};
1844
0c77715b 1845// Return a numeric constant for this expression. We have to mark
1846// this as a character when appropriate.
e440a328 1847
1848bool
0c77715b 1849Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1850{
0c77715b 1851 if (this->is_character_constant_)
1852 nc->set_rune(this->type_, this->val_);
1853 else
1854 nc->set_int(this->type_, this->val_);
e440a328 1855 return true;
1856}
1857
1858// Return the current type. If we haven't set the type yet, we return
1859// an abstract integer type.
1860
1861Type*
1862Integer_expression::do_type()
1863{
1864 if (this->type_ == NULL)
5d4b8566 1865 {
1866 if (this->is_character_constant_)
1867 this->type_ = Type::make_abstract_character_type();
1868 else
1869 this->type_ = Type::make_abstract_integer_type();
1870 }
e440a328 1871 return this->type_;
1872}
1873
1874// Set the type of the integer value. Here we may switch from an
1875// abstract type to a real type.
1876
1877void
1878Integer_expression::do_determine_type(const Type_context* context)
1879{
1880 if (this->type_ != NULL && !this->type_->is_abstract())
1881 ;
0c77715b 1882 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1883 this->type_ = context->type;
1884 else if (!context->may_be_abstract)
5d4b8566 1885 {
1886 if (this->is_character_constant_)
1887 this->type_ = Type::lookup_integer_type("int32");
1888 else
1889 this->type_ = Type::lookup_integer_type("int");
1890 }
e440a328 1891}
1892
e440a328 1893// Check the type of an integer constant.
1894
1895void
1896Integer_expression::do_check_types(Gogo*)
1897{
0c77715b 1898 Type* type = this->type_;
1899 if (type == NULL)
e440a328 1900 return;
0c77715b 1901 Numeric_constant nc;
1902 if (this->is_character_constant_)
1903 nc.set_rune(NULL, this->val_);
1904 else
1905 nc.set_int(NULL, this->val_);
1906 if (!nc.set_type(type, true, this->location()))
e440a328 1907 this->set_is_error();
1908}
1909
1910// Get a tree for an integer constant.
1911
1912tree
1913Integer_expression::do_get_tree(Translate_context* context)
1914{
48c2a53a 1915 Type* resolved_type = NULL;
e440a328 1916 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 1917 resolved_type = this->type_;
e440a328 1918 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1919 {
1920 // We are converting to an abstract floating point type.
48c2a53a 1921 resolved_type = Type::lookup_float_type("float64");
e440a328 1922 }
1923 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1924 {
1925 // We are converting to an abstract complex type.
48c2a53a 1926 resolved_type = Type::lookup_complex_type("complex128");
e440a328 1927 }
1928 else
1929 {
1930 // If we still have an abstract type here, then this is being
1931 // used in a constant expression which didn't get reduced for
1932 // some reason. Use a type which will fit the value. We use <,
1933 // not <=, because we need an extra bit for the sign bit.
1934 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 1935 Type* int_type = Type::lookup_integer_type("int");
1936 if (bits < int_type->integer_type()->bits())
48c2a53a 1937 resolved_type = int_type;
e440a328 1938 else if (bits < 64)
48c2a53a 1939 resolved_type = Type::lookup_integer_type("int64");
e440a328 1940 else
48c2a53a 1941 {
1942 if (!saw_errors())
1943 error_at(this->location(),
1944 "unknown type for large integer constant");
1945 Bexpression* ret = context->gogo()->backend()->error_expression();
1946 return expr_to_tree(ret);
1947 }
e440a328 1948 }
48c2a53a 1949 Numeric_constant nc;
1950 nc.set_int(resolved_type, this->val_);
1951 Bexpression* ret =
1952 Expression::backend_numeric_constant_expression(context, &nc);
1953 return expr_to_tree(ret);
e440a328 1954}
1955
1956// Write VAL to export data.
1957
1958void
8b1c301d 1959Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 1960{
1961 char* s = mpz_get_str(NULL, 10, val);
1962 exp->write_c_string(s);
1963 free(s);
1964}
1965
1966// Export an integer in a constant expression.
1967
1968void
1969Integer_expression::do_export(Export* exp) const
1970{
1971 Integer_expression::export_integer(exp, this->val_);
5d4b8566 1972 if (this->is_character_constant_)
1973 exp->write_c_string("'");
e440a328 1974 // A trailing space lets us reliably identify the end of the number.
1975 exp->write_c_string(" ");
1976}
1977
1978// Import an integer, floating point, or complex value. This handles
1979// all these types because they all start with digits.
1980
1981Expression*
1982Integer_expression::do_import(Import* imp)
1983{
1984 std::string num = imp->read_identifier();
1985 imp->require_c_string(" ");
1986 if (!num.empty() && num[num.length() - 1] == 'i')
1987 {
1988 mpfr_t real;
1989 size_t plus_pos = num.find('+', 1);
1990 size_t minus_pos = num.find('-', 1);
1991 size_t pos;
1992 if (plus_pos == std::string::npos)
1993 pos = minus_pos;
1994 else if (minus_pos == std::string::npos)
1995 pos = plus_pos;
1996 else
1997 {
1998 error_at(imp->location(), "bad number in import data: %qs",
1999 num.c_str());
2000 return Expression::make_error(imp->location());
2001 }
2002 if (pos == std::string::npos)
2003 mpfr_set_ui(real, 0, GMP_RNDN);
2004 else
2005 {
2006 std::string real_str = num.substr(0, pos);
2007 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2008 {
2009 error_at(imp->location(), "bad number in import data: %qs",
2010 real_str.c_str());
2011 return Expression::make_error(imp->location());
2012 }
2013 }
2014
2015 std::string imag_str;
2016 if (pos == std::string::npos)
2017 imag_str = num;
2018 else
2019 imag_str = num.substr(pos);
2020 imag_str = imag_str.substr(0, imag_str.size() - 1);
2021 mpfr_t imag;
2022 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2023 {
2024 error_at(imp->location(), "bad number in import data: %qs",
2025 imag_str.c_str());
2026 return Expression::make_error(imp->location());
2027 }
2028 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2029 imp->location());
2030 mpfr_clear(real);
2031 mpfr_clear(imag);
2032 return ret;
2033 }
2034 else if (num.find('.') == std::string::npos
2035 && num.find('E') == std::string::npos)
2036 {
5d4b8566 2037 bool is_character_constant = (!num.empty()
2038 && num[num.length() - 1] == '\'');
2039 if (is_character_constant)
2040 num = num.substr(0, num.length() - 1);
e440a328 2041 mpz_t val;
2042 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2043 {
2044 error_at(imp->location(), "bad number in import data: %qs",
2045 num.c_str());
2046 return Expression::make_error(imp->location());
2047 }
5d4b8566 2048 Expression* ret;
2049 if (is_character_constant)
2050 ret = Expression::make_character(&val, NULL, imp->location());
2051 else
2052 ret = Expression::make_integer(&val, NULL, imp->location());
e440a328 2053 mpz_clear(val);
2054 return ret;
2055 }
2056 else
2057 {
2058 mpfr_t val;
2059 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2060 {
2061 error_at(imp->location(), "bad number in import data: %qs",
2062 num.c_str());
2063 return Expression::make_error(imp->location());
2064 }
2065 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2066 mpfr_clear(val);
2067 return ret;
2068 }
2069}
d751bb78 2070// Ast dump for integer expression.
2071
2072void
2073Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2074{
5d4b8566 2075 if (this->is_character_constant_)
2076 ast_dump_context->ostream() << '\'';
8b1c301d 2077 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2078 if (this->is_character_constant_)
2079 ast_dump_context->ostream() << '\'';
d751bb78 2080}
2081
e440a328 2082// Build a new integer value.
2083
2084Expression*
5d4b8566 2085Expression::make_integer(const mpz_t* val, Type* type, Location location)
2086{
2087 return new Integer_expression(val, type, false, location);
2088}
2089
2090// Build a new character constant value.
2091
2092Expression*
2093Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2094{
5d4b8566 2095 return new Integer_expression(val, type, true, location);
e440a328 2096}
2097
2098// Floats.
2099
2100class Float_expression : public Expression
2101{
2102 public:
b13c66cd 2103 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2104 : Expression(EXPRESSION_FLOAT, location),
2105 type_(type)
2106 {
2107 mpfr_init_set(this->val_, *val, GMP_RNDN);
2108 }
2109
e440a328 2110 // Write VAL to export data.
2111 static void
8b1c301d 2112 export_float(String_dump* exp, const mpfr_t val);
2113
d751bb78 2114 // Write VAL to dump file.
2115 static void
2116 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2117
2118 protected:
2119 bool
2120 do_is_constant() const
2121 { return true; }
2122
0e168074 2123 bool
2124 do_is_immutable() const
2125 { return true; }
2126
e440a328 2127 bool
0c77715b 2128 do_numeric_constant_value(Numeric_constant* nc) const
2129 {
2130 nc->set_float(this->type_, this->val_);
2131 return true;
2132 }
e440a328 2133
2134 Type*
2135 do_type();
2136
2137 void
2138 do_determine_type(const Type_context*);
2139
2140 void
2141 do_check_types(Gogo*);
2142
2143 Expression*
2144 do_copy()
2145 { return Expression::make_float(&this->val_, this->type_,
2146 this->location()); }
2147
2148 tree
2149 do_get_tree(Translate_context*);
2150
2151 void
2152 do_export(Export*) const;
2153
d751bb78 2154 void
2155 do_dump_expression(Ast_dump_context*) const;
2156
e440a328 2157 private:
2158 // The floating point value.
2159 mpfr_t val_;
2160 // The type so far.
2161 Type* type_;
2162};
2163
e440a328 2164// Return the current type. If we haven't set the type yet, we return
2165// an abstract float type.
2166
2167Type*
2168Float_expression::do_type()
2169{
2170 if (this->type_ == NULL)
2171 this->type_ = Type::make_abstract_float_type();
2172 return this->type_;
2173}
2174
2175// Set the type of the float value. Here we may switch from an
2176// abstract type to a real type.
2177
2178void
2179Float_expression::do_determine_type(const Type_context* context)
2180{
2181 if (this->type_ != NULL && !this->type_->is_abstract())
2182 ;
2183 else if (context->type != NULL
2184 && (context->type->integer_type() != NULL
2185 || context->type->float_type() != NULL
2186 || context->type->complex_type() != NULL))
2187 this->type_ = context->type;
2188 else if (!context->may_be_abstract)
48080209 2189 this->type_ = Type::lookup_float_type("float64");
e440a328 2190}
2191
e440a328 2192// Check the type of a float value.
2193
2194void
2195Float_expression::do_check_types(Gogo*)
2196{
0c77715b 2197 Type* type = this->type_;
2198 if (type == NULL)
e440a328 2199 return;
0c77715b 2200 Numeric_constant nc;
2201 nc.set_float(NULL, this->val_);
2202 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2203 this->set_is_error();
e440a328 2204}
2205
2206// Get a tree for a float constant.
2207
2208tree
2209Float_expression::do_get_tree(Translate_context* context)
2210{
48c2a53a 2211 Type* resolved_type;
e440a328 2212 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2213 resolved_type = this->type_;
e440a328 2214 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2215 {
2216 // We have an abstract integer type. We just hope for the best.
48c2a53a 2217 resolved_type = Type::lookup_integer_type("int");
2218 }
2219 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2220 {
2221 // We are converting to an abstract complex type.
2222 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2223 }
2224 else
2225 {
2226 // If we still have an abstract type here, then this is being
2227 // used in a constant expression which didn't get reduced. We
2228 // just use float64 and hope for the best.
48c2a53a 2229 resolved_type = Type::lookup_float_type("float64");
e440a328 2230 }
48c2a53a 2231
2232 Numeric_constant nc;
2233 nc.set_float(resolved_type, this->val_);
2234 Bexpression* ret =
2235 Expression::backend_numeric_constant_expression(context, &nc);
2236 return expr_to_tree(ret);
e440a328 2237}
2238
8b1c301d 2239// Write a floating point number to a string dump.
e440a328 2240
2241void
8b1c301d 2242Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2243{
2244 mp_exp_t exponent;
2245 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2246 if (*s == '-')
2247 exp->write_c_string("-");
2248 exp->write_c_string("0.");
2249 exp->write_c_string(*s == '-' ? s + 1 : s);
2250 mpfr_free_str(s);
2251 char buf[30];
2252 snprintf(buf, sizeof buf, "E%ld", exponent);
2253 exp->write_c_string(buf);
2254}
2255
2256// Export a floating point number in a constant expression.
2257
2258void
2259Float_expression::do_export(Export* exp) const
2260{
2261 Float_expression::export_float(exp, this->val_);
2262 // A trailing space lets us reliably identify the end of the number.
2263 exp->write_c_string(" ");
2264}
2265
d751bb78 2266// Dump a floating point number to the dump file.
2267
2268void
2269Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2270{
8b1c301d 2271 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2272}
2273
e440a328 2274// Make a float expression.
2275
2276Expression*
b13c66cd 2277Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2278{
2279 return new Float_expression(val, type, location);
2280}
2281
2282// Complex numbers.
2283
2284class Complex_expression : public Expression
2285{
2286 public:
2287 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2288 Location location)
e440a328 2289 : Expression(EXPRESSION_COMPLEX, location),
2290 type_(type)
2291 {
2292 mpfr_init_set(this->real_, *real, GMP_RNDN);
2293 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2294 }
2295
8b1c301d 2296 // Write REAL/IMAG to string dump.
e440a328 2297 static void
8b1c301d 2298 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
e440a328 2299
d751bb78 2300 // Write REAL/IMAG to dump context.
2301 static void
2302 dump_complex(Ast_dump_context* ast_dump_context,
2303 const mpfr_t real, const mpfr_t val);
2304
e440a328 2305 protected:
2306 bool
2307 do_is_constant() const
2308 { return true; }
2309
0e168074 2310 bool
2311 do_is_immutable() const
2312 { return true; }
2313
e440a328 2314 bool
0c77715b 2315 do_numeric_constant_value(Numeric_constant* nc) const
2316 {
2317 nc->set_complex(this->type_, this->real_, this->imag_);
2318 return true;
2319 }
e440a328 2320
2321 Type*
2322 do_type();
2323
2324 void
2325 do_determine_type(const Type_context*);
2326
2327 void
2328 do_check_types(Gogo*);
2329
2330 Expression*
2331 do_copy()
2332 {
2333 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2334 this->location());
2335 }
2336
2337 tree
2338 do_get_tree(Translate_context*);
2339
2340 void
2341 do_export(Export*) const;
2342
d751bb78 2343 void
2344 do_dump_expression(Ast_dump_context*) const;
2345
e440a328 2346 private:
2347 // The real part.
2348 mpfr_t real_;
2349 // The imaginary part;
2350 mpfr_t imag_;
2351 // The type if known.
2352 Type* type_;
2353};
2354
e440a328 2355// Return the current type. If we haven't set the type yet, we return
2356// an abstract complex type.
2357
2358Type*
2359Complex_expression::do_type()
2360{
2361 if (this->type_ == NULL)
2362 this->type_ = Type::make_abstract_complex_type();
2363 return this->type_;
2364}
2365
2366// Set the type of the complex value. Here we may switch from an
2367// abstract type to a real type.
2368
2369void
2370Complex_expression::do_determine_type(const Type_context* context)
2371{
2372 if (this->type_ != NULL && !this->type_->is_abstract())
2373 ;
2374 else if (context->type != NULL
2375 && context->type->complex_type() != NULL)
2376 this->type_ = context->type;
2377 else if (!context->may_be_abstract)
48080209 2378 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2379}
2380
e440a328 2381// Check the type of a complex value.
2382
2383void
2384Complex_expression::do_check_types(Gogo*)
2385{
0c77715b 2386 Type* type = this->type_;
2387 if (type == NULL)
e440a328 2388 return;
0c77715b 2389 Numeric_constant nc;
2390 nc.set_complex(NULL, this->real_, this->imag_);
2391 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2392 this->set_is_error();
2393}
2394
2395// Get a tree for a complex constant.
2396
2397tree
2398Complex_expression::do_get_tree(Translate_context* context)
2399{
48c2a53a 2400 Type* resolved_type;
e440a328 2401 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2402 resolved_type = this->type_;
2403 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2404 {
2405 // We are converting to an abstract integer type.
2406 resolved_type = Type::lookup_integer_type("int");
2407 }
2408 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2409 {
2410 // We are converting to an abstract float type.
2411 resolved_type = Type::lookup_float_type("float64");
2412 }
e440a328 2413 else
2414 {
2415 // If we still have an abstract type here, this this is being
2416 // used in a constant expression which didn't get reduced. We
2417 // just use complex128 and hope for the best.
48c2a53a 2418 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2419 }
48c2a53a 2420
2421 Numeric_constant nc;
2422 nc.set_complex(resolved_type, this->real_, this->imag_);
2423 Bexpression* ret =
2424 Expression::backend_numeric_constant_expression(context, &nc);
2425 return expr_to_tree(ret);
e440a328 2426}
2427
2428// Write REAL/IMAG to export data.
2429
2430void
8b1c301d 2431Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
e440a328 2432 const mpfr_t imag)
2433{
2434 if (!mpfr_zero_p(real))
2435 {
2436 Float_expression::export_float(exp, real);
2437 if (mpfr_sgn(imag) > 0)
2438 exp->write_c_string("+");
2439 }
2440 Float_expression::export_float(exp, imag);
2441 exp->write_c_string("i");
2442}
2443
2444// Export a complex number in a constant expression.
2445
2446void
2447Complex_expression::do_export(Export* exp) const
2448{
2449 Complex_expression::export_complex(exp, this->real_, this->imag_);
2450 // A trailing space lets us reliably identify the end of the number.
2451 exp->write_c_string(" ");
2452}
2453
d751bb78 2454// Dump a complex expression to the dump file.
2455
2456void
2457Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2458{
8b1c301d 2459 Complex_expression::export_complex(ast_dump_context,
d751bb78 2460 this->real_,
2461 this->imag_);
2462}
2463
e440a328 2464// Make a complex expression.
2465
2466Expression*
2467Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
b13c66cd 2468 Location location)
e440a328 2469{
2470 return new Complex_expression(real, imag, type, location);
2471}
2472
d5b605df 2473// Find a named object in an expression.
2474
2475class Find_named_object : public Traverse
2476{
2477 public:
2478 Find_named_object(Named_object* no)
2479 : Traverse(traverse_expressions),
2480 no_(no), found_(false)
2481 { }
2482
2483 // Whether we found the object.
2484 bool
2485 found() const
2486 { return this->found_; }
2487
2488 protected:
2489 int
2490 expression(Expression**);
2491
2492 private:
2493 // The object we are looking for.
2494 Named_object* no_;
2495 // Whether we found it.
2496 bool found_;
2497};
2498
e440a328 2499// A reference to a const in an expression.
2500
2501class Const_expression : public Expression
2502{
2503 public:
b13c66cd 2504 Const_expression(Named_object* constant, Location location)
e440a328 2505 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2506 constant_(constant), type_(NULL), seen_(false)
e440a328 2507 { }
2508
d5b605df 2509 Named_object*
2510 named_object()
2511 { return this->constant_; }
2512
a7f064d5 2513 // Check that the initializer does not refer to the constant itself.
2514 void
2515 check_for_init_loop();
2516
e440a328 2517 protected:
ba4aedd4 2518 int
2519 do_traverse(Traverse*);
2520
e440a328 2521 Expression*
ceeb4318 2522 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2523
2524 bool
2525 do_is_constant() const
2526 { return true; }
2527
0e168074 2528 bool
2529 do_is_immutable() const
2530 { return true; }
2531
e440a328 2532 bool
0c77715b 2533 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2534
2535 bool
af6b489a 2536 do_string_constant_value(std::string* val) const;
e440a328 2537
2538 Type*
2539 do_type();
2540
2541 // The type of a const is set by the declaration, not the use.
2542 void
2543 do_determine_type(const Type_context*);
2544
2545 void
2546 do_check_types(Gogo*);
2547
2548 Expression*
2549 do_copy()
2550 { return this; }
2551
2552 tree
2553 do_get_tree(Translate_context* context);
2554
2555 // When exporting a reference to a const as part of a const
2556 // expression, we export the value. We ignore the fact that it has
2557 // a name.
2558 void
2559 do_export(Export* exp) const
2560 { this->constant_->const_value()->expr()->export_expression(exp); }
2561
d751bb78 2562 void
2563 do_dump_expression(Ast_dump_context*) const;
2564
e440a328 2565 private:
2566 // The constant.
2567 Named_object* constant_;
2568 // The type of this reference. This is used if the constant has an
2569 // abstract type.
2570 Type* type_;
13e818f5 2571 // Used to prevent infinite recursion when a constant incorrectly
2572 // refers to itself.
2573 mutable bool seen_;
e440a328 2574};
2575
ba4aedd4 2576// Traversal.
2577
2578int
2579Const_expression::do_traverse(Traverse* traverse)
2580{
2581 if (this->type_ != NULL)
2582 return Type::traverse(this->type_, traverse);
2583 return TRAVERSE_CONTINUE;
2584}
2585
e440a328 2586// Lower a constant expression. This is where we convert the
2587// predeclared constant iota into an integer value.
2588
2589Expression*
ceeb4318 2590Const_expression::do_lower(Gogo* gogo, Named_object*,
2591 Statement_inserter*, int iota_value)
e440a328 2592{
2593 if (this->constant_->const_value()->expr()->classification()
2594 == EXPRESSION_IOTA)
2595 {
2596 if (iota_value == -1)
2597 {
2598 error_at(this->location(),
2599 "iota is only defined in const declarations");
2600 iota_value = 0;
2601 }
2602 mpz_t val;
2603 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2604 Expression* ret = Expression::make_integer(&val, NULL,
2605 this->location());
2606 mpz_clear(val);
2607 return ret;
2608 }
2609
2610 // Make sure that the constant itself has been lowered.
2611 gogo->lower_constant(this->constant_);
2612
2613 return this;
2614}
2615
0c77715b 2616// Return a numeric constant value.
e440a328 2617
2618bool
0c77715b 2619Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2620{
13e818f5 2621 if (this->seen_)
2622 return false;
2623
e440a328 2624 Expression* e = this->constant_->const_value()->expr();
0c77715b 2625
13e818f5 2626 this->seen_ = true;
2627
0c77715b 2628 bool r = e->numeric_constant_value(nc);
e440a328 2629
13e818f5 2630 this->seen_ = false;
2631
e440a328 2632 Type* ctype;
2633 if (this->type_ != NULL)
2634 ctype = this->type_;
2635 else
2636 ctype = this->constant_->const_value()->type();
e440a328 2637 if (r && ctype != NULL)
2638 {
0c77715b 2639 if (!nc->set_type(ctype, false, this->location()))
e440a328 2640 return false;
e440a328 2641 }
e440a328 2642
e440a328 2643 return r;
2644}
2645
af6b489a 2646bool
2647Const_expression::do_string_constant_value(std::string* val) const
2648{
2649 if (this->seen_)
2650 return false;
2651
2652 Expression* e = this->constant_->const_value()->expr();
2653
2654 this->seen_ = true;
2655 bool ok = e->string_constant_value(val);
2656 this->seen_ = false;
2657
2658 return ok;
2659}
2660
e440a328 2661// Return the type of the const reference.
2662
2663Type*
2664Const_expression::do_type()
2665{
2666 if (this->type_ != NULL)
2667 return this->type_;
13e818f5 2668
2f78f012 2669 Named_constant* nc = this->constant_->const_value();
2670
2671 if (this->seen_ || nc->lowering())
13e818f5 2672 {
2673 this->report_error(_("constant refers to itself"));
2674 this->type_ = Type::make_error_type();
2675 return this->type_;
2676 }
2677
2678 this->seen_ = true;
2679
e440a328 2680 Type* ret = nc->type();
13e818f5 2681
e440a328 2682 if (ret != NULL)
13e818f5 2683 {
2684 this->seen_ = false;
2685 return ret;
2686 }
2687
e440a328 2688 // During parsing, a named constant may have a NULL type, but we
2689 // must not return a NULL type here.
13e818f5 2690 ret = nc->expr()->type();
2691
2692 this->seen_ = false;
2693
2694 return ret;
e440a328 2695}
2696
2697// Set the type of the const reference.
2698
2699void
2700Const_expression::do_determine_type(const Type_context* context)
2701{
2702 Type* ctype = this->constant_->const_value()->type();
2703 Type* cetype = (ctype != NULL
2704 ? ctype
2705 : this->constant_->const_value()->expr()->type());
2706 if (ctype != NULL && !ctype->is_abstract())
2707 ;
2708 else if (context->type != NULL
0c77715b 2709 && context->type->is_numeric_type()
2710 && cetype->is_numeric_type())
e440a328 2711 this->type_ = context->type;
2712 else if (context->type != NULL
2713 && context->type->is_string_type()
2714 && cetype->is_string_type())
2715 this->type_ = context->type;
2716 else if (context->type != NULL
2717 && context->type->is_boolean_type()
2718 && cetype->is_boolean_type())
2719 this->type_ = context->type;
2720 else if (!context->may_be_abstract)
2721 {
2722 if (cetype->is_abstract())
2723 cetype = cetype->make_non_abstract_type();
2724 this->type_ = cetype;
2725 }
2726}
2727
a7f064d5 2728// Check for a loop in which the initializer of a constant refers to
2729// the constant itself.
e440a328 2730
2731void
a7f064d5 2732Const_expression::check_for_init_loop()
e440a328 2733{
5c13bd80 2734 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2735 return;
2736
a7f064d5 2737 if (this->seen_)
2738 {
2739 this->report_error(_("constant refers to itself"));
2740 this->type_ = Type::make_error_type();
2741 return;
2742 }
2743
d5b605df 2744 Expression* init = this->constant_->const_value()->expr();
2745 Find_named_object find_named_object(this->constant_);
a7f064d5 2746
2747 this->seen_ = true;
d5b605df 2748 Expression::traverse(&init, &find_named_object);
a7f064d5 2749 this->seen_ = false;
2750
d5b605df 2751 if (find_named_object.found())
2752 {
5c13bd80 2753 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2754 {
2755 this->report_error(_("constant refers to itself"));
2756 this->type_ = Type::make_error_type();
2757 }
d5b605df 2758 return;
2759 }
a7f064d5 2760}
2761
2762// Check types of a const reference.
2763
2764void
2765Const_expression::do_check_types(Gogo*)
2766{
5c13bd80 2767 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2768 return;
2769
2770 this->check_for_init_loop();
d5b605df 2771
0c77715b 2772 // Check that numeric constant fits in type.
2773 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2774 {
0c77715b 2775 Numeric_constant nc;
2776 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2777 {
0c77715b 2778 if (!nc.set_type(this->type_, true, this->location()))
2779 this->set_is_error();
e440a328 2780 }
e440a328 2781 }
2782}
2783
2784// Return a tree for the const reference.
2785
2786tree
2787Const_expression::do_get_tree(Translate_context* context)
2788{
2c809f8f 2789 if (this->type_ != NULL && this->type_->is_error())
2790 return error_mark_node;
e440a328 2791
2792 // If the type has been set for this expression, but the underlying
2793 // object is an abstract int or float, we try to get the abstract
2794 // value. Otherwise we may lose something in the conversion.
2795 if (this->type_ != NULL
0c77715b 2796 && this->type_->is_numeric_type()
a68492b4 2797 && (this->constant_->const_value()->type() == NULL
2798 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2799 {
2800 Expression* expr = this->constant_->const_value()->expr();
0c77715b 2801 Numeric_constant nc;
2802 if (expr->numeric_constant_value(&nc)
2803 && nc.set_type(this->type_, false, this->location()))
e440a328 2804 {
0c77715b 2805 Expression* e = nc.expression(this->location());
2806 return e->get_tree(context);
e440a328 2807 }
e440a328 2808 }
2809
2c809f8f 2810 Gogo* gogo = context->gogo();
2811 Bexpression* ret =
2812 tree_to_expr(this->constant_->get_tree(gogo, context->function()));
2813 if (this->type_ != NULL)
2814 {
2815 Btype* btype = this->type_->get_backend(gogo);
2816 ret = gogo->backend()->convert_expression(btype, ret, this->location());
2817 }
2818 return expr_to_tree(ret);
e440a328 2819}
2820
d751bb78 2821// Dump ast representation for constant expression.
2822
2823void
2824Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2825{
2826 ast_dump_context->ostream() << this->constant_->name();
2827}
2828
e440a328 2829// Make a reference to a constant in an expression.
2830
2831Expression*
2832Expression::make_const_reference(Named_object* constant,
b13c66cd 2833 Location location)
e440a328 2834{
2835 return new Const_expression(constant, location);
2836}
2837
d5b605df 2838// Find a named object in an expression.
2839
2840int
2841Find_named_object::expression(Expression** pexpr)
2842{
2843 switch ((*pexpr)->classification())
2844 {
2845 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 2846 {
2847 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2848 if (ce->named_object() == this->no_)
2849 break;
2850
2851 // We need to check a constant initializer explicitly, as
2852 // loops here will not be caught by the loop checking for
2853 // variable initializers.
2854 ce->check_for_init_loop();
2855
2856 return TRAVERSE_CONTINUE;
2857 }
2858
d5b605df 2859 case Expression::EXPRESSION_VAR_REFERENCE:
2860 if ((*pexpr)->var_expression()->named_object() == this->no_)
2861 break;
2862 return TRAVERSE_CONTINUE;
2863 case Expression::EXPRESSION_FUNC_REFERENCE:
2864 if ((*pexpr)->func_expression()->named_object() == this->no_)
2865 break;
2866 return TRAVERSE_CONTINUE;
2867 default:
2868 return TRAVERSE_CONTINUE;
2869 }
2870 this->found_ = true;
2871 return TRAVERSE_EXIT;
2872}
2873
e440a328 2874// The nil value.
2875
2876class Nil_expression : public Expression
2877{
2878 public:
b13c66cd 2879 Nil_expression(Location location)
e440a328 2880 : Expression(EXPRESSION_NIL, location)
2881 { }
2882
2883 static Expression*
2884 do_import(Import*);
2885
2886 protected:
2887 bool
2888 do_is_constant() const
2889 { return true; }
2890
f9ca30f9 2891 bool
2892 do_is_immutable() const
2893 { return true; }
2894
e440a328 2895 Type*
2896 do_type()
2897 { return Type::make_nil_type(); }
2898
2899 void
2900 do_determine_type(const Type_context*)
2901 { }
2902
2903 Expression*
2904 do_copy()
2905 { return this; }
2906
2907 tree
2908 do_get_tree(Translate_context*)
2909 { return null_pointer_node; }
2910
2911 void
2912 do_export(Export* exp) const
2913 { exp->write_c_string("nil"); }
d751bb78 2914
2915 void
2916 do_dump_expression(Ast_dump_context* ast_dump_context) const
2917 { ast_dump_context->ostream() << "nil"; }
e440a328 2918};
2919
2920// Import a nil expression.
2921
2922Expression*
2923Nil_expression::do_import(Import* imp)
2924{
2925 imp->require_c_string("nil");
2926 return Expression::make_nil(imp->location());
2927}
2928
2929// Make a nil expression.
2930
2931Expression*
b13c66cd 2932Expression::make_nil(Location location)
e440a328 2933{
2934 return new Nil_expression(location);
2935}
2936
2937// The value of the predeclared constant iota. This is little more
2938// than a marker. This will be lowered to an integer in
2939// Const_expression::do_lower, which is where we know the value that
2940// it should have.
2941
2942class Iota_expression : public Parser_expression
2943{
2944 public:
b13c66cd 2945 Iota_expression(Location location)
e440a328 2946 : Parser_expression(EXPRESSION_IOTA, location)
2947 { }
2948
2949 protected:
2950 Expression*
ceeb4318 2951 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 2952 { go_unreachable(); }
e440a328 2953
2954 // There should only ever be one of these.
2955 Expression*
2956 do_copy()
c3e6f413 2957 { go_unreachable(); }
d751bb78 2958
2959 void
2960 do_dump_expression(Ast_dump_context* ast_dump_context) const
2961 { ast_dump_context->ostream() << "iota"; }
e440a328 2962};
2963
2964// Make an iota expression. This is only called for one case: the
2965// value of the predeclared constant iota.
2966
2967Expression*
2968Expression::make_iota()
2969{
b13c66cd 2970 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 2971 return &iota_expression;
2972}
2973
2974// A type conversion expression.
2975
2976class Type_conversion_expression : public Expression
2977{
2978 public:
2979 Type_conversion_expression(Type* type, Expression* expr,
b13c66cd 2980 Location location)
e440a328 2981 : Expression(EXPRESSION_CONVERSION, location),
2982 type_(type), expr_(expr), may_convert_function_types_(false)
2983 { }
2984
2985 // Return the type to which we are converting.
2986 Type*
2987 type() const
2988 { return this->type_; }
2989
2990 // Return the expression which we are converting.
2991 Expression*
2992 expr() const
2993 { return this->expr_; }
2994
2995 // Permit converting from one function type to another. This is
2996 // used internally for method expressions.
2997 void
2998 set_may_convert_function_types()
2999 {
3000 this->may_convert_function_types_ = true;
3001 }
3002
3003 // Import a type conversion expression.
3004 static Expression*
3005 do_import(Import*);
3006
3007 protected:
3008 int
3009 do_traverse(Traverse* traverse);
3010
3011 Expression*
ceeb4318 3012 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3013
35a54f17 3014 Expression*
3015 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3016
e440a328 3017 bool
1ca01a59 3018 do_is_constant() const;
e440a328 3019
0e168074 3020 bool
3021 do_is_immutable() const;
3022
e440a328 3023 bool
0c77715b 3024 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3025
3026 bool
3027 do_string_constant_value(std::string*) const;
3028
3029 Type*
3030 do_type()
3031 { return this->type_; }
3032
3033 void
3034 do_determine_type(const Type_context*)
3035 {
3036 Type_context subcontext(this->type_, false);
3037 this->expr_->determine_type(&subcontext);
3038 }
3039
3040 void
3041 do_check_types(Gogo*);
3042
3043 Expression*
3044 do_copy()
3045 {
3046 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3047 this->location());
3048 }
3049
3050 tree
3051 do_get_tree(Translate_context* context);
3052
3053 void
3054 do_export(Export*) const;
3055
d751bb78 3056 void
3057 do_dump_expression(Ast_dump_context*) const;
3058
e440a328 3059 private:
3060 // The type to convert to.
3061 Type* type_;
3062 // The expression to convert.
3063 Expression* expr_;
3064 // True if this is permitted to convert function types. This is
3065 // used internally for method expressions.
3066 bool may_convert_function_types_;
3067};
3068
3069// Traversal.
3070
3071int
3072Type_conversion_expression::do_traverse(Traverse* traverse)
3073{
3074 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3075 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3076 return TRAVERSE_EXIT;
3077 return TRAVERSE_CONTINUE;
3078}
3079
3080// Convert to a constant at lowering time.
3081
3082Expression*
ceeb4318 3083Type_conversion_expression::do_lower(Gogo*, Named_object*,
3084 Statement_inserter*, int)
e440a328 3085{
3086 Type* type = this->type_;
3087 Expression* val = this->expr_;
b13c66cd 3088 Location location = this->location();
e440a328 3089
0c77715b 3090 if (type->is_numeric_type())
e440a328 3091 {
0c77715b 3092 Numeric_constant nc;
3093 if (val->numeric_constant_value(&nc))
e440a328 3094 {
0c77715b 3095 if (!nc.set_type(type, true, location))
3096 return Expression::make_error(location);
3097 return nc.expression(location);
e440a328 3098 }
e440a328 3099 }
3100
55072f2b 3101 if (type->is_slice_type())
e440a328 3102 {
3103 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3104 bool is_byte = (element_type->integer_type() != NULL
3105 && element_type->integer_type()->is_byte());
3106 bool is_rune = (element_type->integer_type() != NULL
3107 && element_type->integer_type()->is_rune());
3108 if (is_byte || is_rune)
e440a328 3109 {
3110 std::string s;
3111 if (val->string_constant_value(&s))
3112 {
3113 Expression_list* vals = new Expression_list();
3114 if (is_byte)
3115 {
3116 for (std::string::const_iterator p = s.begin();
3117 p != s.end();
3118 p++)
3119 {
3120 mpz_t val;
3121 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3122 Expression* v = Expression::make_integer(&val,
3123 element_type,
3124 location);
3125 vals->push_back(v);
3126 mpz_clear(val);
3127 }
3128 }
3129 else
3130 {
3131 const char *p = s.data();
3132 const char *pend = s.data() + s.length();
3133 while (p < pend)
3134 {
3135 unsigned int c;
3136 int adv = Lex::fetch_char(p, &c);
3137 if (adv == 0)
3138 {
3139 warning_at(this->location(), 0,
3140 "invalid UTF-8 encoding");
3141 adv = 1;
3142 }
3143 p += adv;
3144 mpz_t val;
3145 mpz_init_set_ui(val, c);
3146 Expression* v = Expression::make_integer(&val,
3147 element_type,
3148 location);
3149 vals->push_back(v);
3150 mpz_clear(val);
3151 }
3152 }
3153
3154 return Expression::make_slice_composite_literal(type, vals,
3155 location);
3156 }
3157 }
3158 }
3159
3160 return this;
3161}
3162
35a54f17 3163// Flatten a type conversion by using a temporary variable for the slice
3164// in slice to string conversions.
3165
3166Expression*
3167Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3168 Statement_inserter* inserter)
3169{
2c809f8f 3170 if (((this->type()->is_string_type()
3171 && this->expr_->type()->is_slice_type())
3172 || (this->type()->interface_type() != NULL
3173 && this->expr_->type()->interface_type() != NULL))
35a54f17 3174 && !this->expr_->is_variable())
3175 {
3176 Temporary_statement* temp =
3177 Statement::make_temporary(NULL, this->expr_, this->location());
3178 inserter->insert(temp);
3179 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3180 }
3181 return this;
3182}
3183
1ca01a59 3184// Return whether a type conversion is a constant.
3185
3186bool
3187Type_conversion_expression::do_is_constant() const
3188{
3189 if (!this->expr_->is_constant())
3190 return false;
3191
3192 // A conversion to a type that may not be used as a constant is not
3193 // a constant. For example, []byte(nil).
3194 Type* type = this->type_;
3195 if (type->integer_type() == NULL
3196 && type->float_type() == NULL
3197 && type->complex_type() == NULL
3198 && !type->is_boolean_type()
3199 && !type->is_string_type())
3200 return false;
3201
3202 return true;
3203}
3204
0e168074 3205// Return whether a type conversion is immutable.
3206
3207bool
3208Type_conversion_expression::do_is_immutable() const
3209{
3210 Type* type = this->type_;
3211 Type* expr_type = this->expr_->type();
3212
3213 if (type->interface_type() != NULL
3214 || expr_type->interface_type() != NULL)
3215 return false;
3216
3217 if (!this->expr_->is_immutable())
3218 return false;
3219
3220 if (Type::are_identical(type, expr_type, false, NULL))
3221 return true;
3222
3223 return type->is_basic_type() && expr_type->is_basic_type();
3224}
3225
0c77715b 3226// Return the constant numeric value if there is one.
e440a328 3227
3228bool
0c77715b 3229Type_conversion_expression::do_numeric_constant_value(
3230 Numeric_constant* nc) const
e440a328 3231{
0c77715b 3232 if (!this->type_->is_numeric_type())
e440a328 3233 return false;
0c77715b 3234 if (!this->expr_->numeric_constant_value(nc))
e440a328 3235 return false;
0c77715b 3236 return nc->set_type(this->type_, false, this->location());
e440a328 3237}
3238
3239// Return the constant string value if there is one.
3240
3241bool
3242Type_conversion_expression::do_string_constant_value(std::string* val) const
3243{
3244 if (this->type_->is_string_type()
3245 && this->expr_->type()->integer_type() != NULL)
3246 {
0c77715b 3247 Numeric_constant nc;
3248 if (this->expr_->numeric_constant_value(&nc))
e440a328 3249 {
0c77715b 3250 unsigned long ival;
3251 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3252 {
0c77715b 3253 val->clear();
3254 Lex::append_char(ival, true, val, this->location());
e440a328 3255 return true;
3256 }
3257 }
e440a328 3258 }
3259
3260 // FIXME: Could handle conversion from const []int here.
3261
3262 return false;
3263}
3264
3265// Check that types are convertible.
3266
3267void
3268Type_conversion_expression::do_check_types(Gogo*)
3269{
3270 Type* type = this->type_;
3271 Type* expr_type = this->expr_->type();
3272 std::string reason;
3273
5c13bd80 3274 if (type->is_error() || expr_type->is_error())
842f6425 3275 {
842f6425 3276 this->set_is_error();
3277 return;
3278 }
3279
e440a328 3280 if (this->may_convert_function_types_
3281 && type->function_type() != NULL
3282 && expr_type->function_type() != NULL)
3283 return;
3284
3285 if (Type::are_convertible(type, expr_type, &reason))
3286 return;
3287
3288 error_at(this->location(), "%s", reason.c_str());
3289 this->set_is_error();
3290}
3291
3292// Get a tree for a type conversion.
3293
3294tree
3295Type_conversion_expression::do_get_tree(Translate_context* context)
3296{
e440a328 3297 Type* type = this->type_;
3298 Type* expr_type = this->expr_->type();
2c809f8f 3299
3300 Gogo* gogo = context->gogo();
3301 Btype* btype = type->get_backend(gogo);
3302 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3303 Location loc = this->location();
3304
3305 if (Type::are_identical(type, expr_type, false, NULL))
e440a328 3306 {
2c809f8f 3307 Bexpression* bconvert =
3308 gogo->backend()->convert_expression(btype, bexpr, loc);
3309 return expr_to_tree(bconvert);
e440a328 3310 }
2c809f8f 3311 else if (type->interface_type() != NULL
3312 || expr_type->interface_type() != NULL)
e440a328 3313 {
2c809f8f 3314 Expression* conversion =
3315 Expression::convert_for_assignment(gogo, type, this->expr_,
3316 this->location());
3317 return conversion->get_tree(context);
e440a328 3318 }
3319 else if (type->is_string_type()
3320 && expr_type->integer_type() != NULL)
3321 {
2c809f8f 3322 mpz_t intval;
3323 Numeric_constant nc;
3324 if (this->expr_->numeric_constant_value(&nc)
3325 && nc.to_int(&intval)
3326 && mpz_fits_ushort_p(intval))
e440a328 3327 {
e440a328 3328 std::string s;
2c809f8f 3329 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3330 mpz_clear(intval);
3331 Expression* se = Expression::make_string(s, loc);
e440a328 3332 return se->get_tree(context);
3333 }
3334
f16ab008 3335 Expression* i2s_expr =
2c809f8f 3336 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3337 return Expression::make_cast(type, i2s_expr, loc)->get_tree(context);
e440a328 3338 }
55072f2b 3339 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3340 {
55072f2b 3341 Array_type* a = expr_type->array_type();
e440a328 3342 Type* e = a->element_type()->forwarded();
c484d925 3343 go_assert(e->integer_type() != NULL);
35a54f17 3344 go_assert(this->expr_->is_variable());
3345
3346 Runtime::Function code;
60963afd 3347 if (e->integer_type()->is_byte())
35a54f17 3348 code = Runtime::BYTE_ARRAY_TO_STRING;
e440a328 3349 else
35a54f17 3350 {
3351 go_assert(e->integer_type()->is_rune());
3352 code = Runtime::INT_ARRAY_TO_STRING;
3353 }
3354 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3355 Expression* len = a->get_length(gogo, this->expr_);
2c809f8f 3356 return Runtime::make_call(code, loc, 2, valptr, len)->get_tree(context);
e440a328 3357 }
411eb89e 3358 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3359 {
3360 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3361 go_assert(e->integer_type() != NULL);
6c252e42 3362
2c809f8f 3363 Runtime::Function code;
60963afd 3364 if (e->integer_type()->is_byte())
2c809f8f 3365 code = Runtime::STRING_TO_BYTE_ARRAY;
e440a328 3366 else
3367 {
60963afd 3368 go_assert(e->integer_type()->is_rune());
2c809f8f 3369 code = Runtime::STRING_TO_INT_ARRAY;
e440a328 3370 }
2c809f8f 3371 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3372 return Expression::make_unsafe_cast(type, s2a, loc)->get_tree(context);
3373 }
3374 else if (type->is_numeric_type())
3375 {
3376 go_assert(Type::are_convertible(type, expr_type, NULL));
3377 Bexpression* bconvert =
3378 gogo->backend()->convert_expression(btype, bexpr, loc);
3379 return expr_to_tree(bconvert);
e440a328 3380 }
3381 else if ((type->is_unsafe_pointer_type()
2c809f8f 3382 && (expr_type->points_to() != NULL
3383 || expr_type->integer_type()))
3384 || (expr_type->is_unsafe_pointer_type()
3385 && type->points_to() != NULL)
3386 || (this->may_convert_function_types_
3387 && type->function_type() != NULL
3388 && expr_type->function_type() != NULL))
3389 {
3390 Bexpression* bconvert =
3391 gogo->backend()->convert_expression(btype, bexpr, loc);
3392 return expr_to_tree(bconvert);
3393 }
e440a328 3394 else
2c809f8f 3395 {
3396 Expression* conversion =
3397 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3398 return conversion->get_tree(context);
3399 }
e440a328 3400}
3401
3402// Output a type conversion in a constant expression.
3403
3404void
3405Type_conversion_expression::do_export(Export* exp) const
3406{
3407 exp->write_c_string("convert(");
3408 exp->write_type(this->type_);
3409 exp->write_c_string(", ");
3410 this->expr_->export_expression(exp);
3411 exp->write_c_string(")");
3412}
3413
3414// Import a type conversion or a struct construction.
3415
3416Expression*
3417Type_conversion_expression::do_import(Import* imp)
3418{
3419 imp->require_c_string("convert(");
3420 Type* type = imp->read_type();
3421 imp->require_c_string(", ");
3422 Expression* val = Expression::import_expression(imp);
3423 imp->require_c_string(")");
3424 return Expression::make_cast(type, val, imp->location());
3425}
3426
d751bb78 3427// Dump ast representation for a type conversion expression.
3428
3429void
3430Type_conversion_expression::do_dump_expression(
3431 Ast_dump_context* ast_dump_context) const
3432{
3433 ast_dump_context->dump_type(this->type_);
3434 ast_dump_context->ostream() << "(";
3435 ast_dump_context->dump_expression(this->expr_);
3436 ast_dump_context->ostream() << ") ";
3437}
3438
e440a328 3439// Make a type cast expression.
3440
3441Expression*
b13c66cd 3442Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3443{
3444 if (type->is_error_type() || val->is_error_expression())
3445 return Expression::make_error(location);
3446 return new Type_conversion_expression(type, val, location);
3447}
3448
9581e91d 3449// An unsafe type conversion, used to pass values to builtin functions.
3450
3451class Unsafe_type_conversion_expression : public Expression
3452{
3453 public:
3454 Unsafe_type_conversion_expression(Type* type, Expression* expr,
b13c66cd 3455 Location location)
9581e91d 3456 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3457 type_(type), expr_(expr)
3458 { }
3459
3460 protected:
3461 int
3462 do_traverse(Traverse* traverse);
3463
3464 Type*
3465 do_type()
3466 { return this->type_; }
3467
3468 void
3469 do_determine_type(const Type_context*)
a9182619 3470 { this->expr_->determine_type_no_context(); }
9581e91d 3471
3472 Expression*
3473 do_copy()
3474 {
3475 return new Unsafe_type_conversion_expression(this->type_,
3476 this->expr_->copy(),
3477 this->location());
3478 }
3479
3480 tree
3481 do_get_tree(Translate_context*);
3482
d751bb78 3483 void
3484 do_dump_expression(Ast_dump_context*) const;
3485
9581e91d 3486 private:
3487 // The type to convert to.
3488 Type* type_;
3489 // The expression to convert.
3490 Expression* expr_;
3491};
3492
3493// Traversal.
3494
3495int
3496Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3497{
3498 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3499 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3500 return TRAVERSE_EXIT;
3501 return TRAVERSE_CONTINUE;
3502}
3503
3504// Convert to backend representation.
3505
3506tree
3507Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3508{
3509 // We are only called for a limited number of cases.
3510
3511 Type* t = this->type_;
3512 Type* et = this->expr_->type();
2c809f8f 3513 if (t->array_type() != NULL)
3514 go_assert(et->array_type() != NULL
3515 && t->is_slice_type() == et->is_slice_type());
3516 else if (t->struct_type() != NULL)
9581e91d 3517 {
2c809f8f 3518 if (t->named_type() != NULL
3519 && et->named_type() != NULL
3520 && !Type::are_convertible(t, et, NULL))
3521 {
3522 go_assert(saw_errors());
3523 return error_mark_node;
3524 }
3525
3526 go_assert(et->struct_type() != NULL
3527 && Type::are_convertible(t, et, NULL));
3528 }
3529 else if (t->map_type() != NULL)
c484d925 3530 go_assert(et->map_type() != NULL);
9581e91d 3531 else if (t->channel_type() != NULL)
c484d925 3532 go_assert(et->channel_type() != NULL);
09ea332d 3533 else if (t->points_to() != NULL)
2c809f8f 3534 go_assert(et->points_to() != NULL
3535 || et->channel_type() != NULL
3536 || et->map_type() != NULL
3537 || et->function_type() != NULL
3538 || et->is_nil_type());
9581e91d 3539 else if (et->is_unsafe_pointer_type())
c484d925 3540 go_assert(t->points_to() != NULL);
2c809f8f 3541 else if (t->interface_type() != NULL)
9581e91d 3542 {
2c809f8f 3543 bool empty_iface = t->interface_type()->is_empty();
c484d925 3544 go_assert(et->interface_type() != NULL
2c809f8f 3545 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3546 }
588e3cf9 3547 else if (t->integer_type() != NULL)
2c809f8f 3548 go_assert(et->is_boolean_type()
3549 || et->integer_type() != NULL
3550 || et->function_type() != NULL
3551 || et->points_to() != NULL
3552 || et->map_type() != NULL
3553 || et->channel_type() != NULL);
9581e91d 3554 else
c3e6f413 3555 go_unreachable();
9581e91d 3556
2c809f8f 3557 Gogo* gogo = context->gogo();
3558 Btype* btype = t->get_backend(gogo);
3559 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3560 Location loc = this->location();
3561 Bexpression* ret =
3562 gogo->backend()->convert_expression(btype, bexpr, loc);
3563 return expr_to_tree(ret);
9581e91d 3564}
3565
d751bb78 3566// Dump ast representation for an unsafe type conversion expression.
3567
3568void
3569Unsafe_type_conversion_expression::do_dump_expression(
3570 Ast_dump_context* ast_dump_context) const
3571{
3572 ast_dump_context->dump_type(this->type_);
3573 ast_dump_context->ostream() << "(";
3574 ast_dump_context->dump_expression(this->expr_);
3575 ast_dump_context->ostream() << ") ";
3576}
3577
9581e91d 3578// Make an unsafe type conversion expression.
3579
3580Expression*
3581Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3582 Location location)
9581e91d 3583{
3584 return new Unsafe_type_conversion_expression(type, expr, location);
3585}
3586
e440a328 3587// Unary expressions.
3588
3589class Unary_expression : public Expression
3590{
3591 public:
b13c66cd 3592 Unary_expression(Operator op, Expression* expr, Location location)
e440a328 3593 : Expression(EXPRESSION_UNARY, location),
56080003 3594 op_(op), escapes_(true), create_temp_(false), expr_(expr),
3595 issue_nil_check_(false)
e440a328 3596 { }
3597
3598 // Return the operator.
3599 Operator
3600 op() const
3601 { return this->op_; }
3602
3603 // Return the operand.
3604 Expression*
3605 operand() const
3606 { return this->expr_; }
3607
3608 // Record that an address expression does not escape.
3609 void
3610 set_does_not_escape()
3611 {
c484d925 3612 go_assert(this->op_ == OPERATOR_AND);
e440a328 3613 this->escapes_ = false;
3614 }
3615
09ea332d 3616 // Record that this is an address expression which should create a
3617 // temporary variable if necessary. This is used for method calls.
3618 void
3619 set_create_temp()
3620 {
3621 go_assert(this->op_ == OPERATOR_AND);
3622 this->create_temp_ = true;
3623 }
3624
0c77715b 3625 // Apply unary opcode OP to UNC, setting NC. Return true if this
3626 // could be done, false if not. Issue errors for overflow.
e440a328 3627 static bool
0c77715b 3628 eval_constant(Operator op, const Numeric_constant* unc,
3629 Location, Numeric_constant* nc);
e440a328 3630
3631 static Expression*
3632 do_import(Import*);
3633
3634 protected:
3635 int
3636 do_traverse(Traverse* traverse)
3637 { return Expression::traverse(&this->expr_, traverse); }
3638
3639 Expression*
ceeb4318 3640 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3641
f9ca30f9 3642 Expression*
3643 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3644
e440a328 3645 bool
3646 do_is_constant() const;
3647
f9ca30f9 3648 bool
3649 do_is_immutable() const
0e168074 3650 { return this->expr_->is_immutable()
3651 || (this->op_ == OPERATOR_AND && this->expr_->is_variable()); }
f9ca30f9 3652
e440a328 3653 bool
0c77715b 3654 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3655
3656 Type*
3657 do_type();
3658
3659 void
3660 do_determine_type(const Type_context*);
3661
3662 void
3663 do_check_types(Gogo*);
3664
3665 Expression*
3666 do_copy()
3667 {
3668 return Expression::make_unary(this->op_, this->expr_->copy(),
3669 this->location());
3670 }
3671
baef9f7a 3672 bool
3673 do_must_eval_subexpressions_in_order(int*) const
3674 { return this->op_ == OPERATOR_MULT; }
3675
e440a328 3676 bool
3677 do_is_addressable() const
3678 { return this->op_ == OPERATOR_MULT; }
3679
3680 tree
3681 do_get_tree(Translate_context*);
3682
3683 void
3684 do_export(Export*) const;
3685
d751bb78 3686 void
3687 do_dump_expression(Ast_dump_context*) const;
3688
56080003 3689 void
3690 do_issue_nil_check()
3691 { this->issue_nil_check_ = (this->op_ == OPERATOR_MULT); }
3692
e440a328 3693 private:
3694 // The unary operator to apply.
3695 Operator op_;
3696 // Normally true. False if this is an address expression which does
3697 // not escape the current function.
3698 bool escapes_;
09ea332d 3699 // True if this is an address expression which should create a
3700 // temporary variable if necessary.
3701 bool create_temp_;
e440a328 3702 // The operand.
3703 Expression* expr_;
56080003 3704 // Whether or not to issue a nil check for this expression if its address
3705 // is being taken.
3706 bool issue_nil_check_;
e440a328 3707};
3708
3709// If we are taking the address of a composite literal, and the
2c809f8f 3710// contents are not constant, then we want to make a heap expression
e440a328 3711// instead.
3712
3713Expression*
ceeb4318 3714Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3715{
b13c66cd 3716 Location loc = this->location();
e440a328 3717 Operator op = this->op_;
3718 Expression* expr = this->expr_;
3719
3720 if (op == OPERATOR_MULT && expr->is_type_expression())
3721 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3722
3723 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3724 // moving x to the heap. FIXME: Is it worth doing a real escape
3725 // analysis here? This case is found in math/unsafe.go and is
3726 // therefore worth special casing.
3727 if (op == OPERATOR_MULT)
3728 {
3729 Expression* e = expr;
3730 while (e->classification() == EXPRESSION_CONVERSION)
3731 {
3732 Type_conversion_expression* te
3733 = static_cast<Type_conversion_expression*>(e);
3734 e = te->expr();
3735 }
3736
3737 if (e->classification() == EXPRESSION_UNARY)
3738 {
3739 Unary_expression* ue = static_cast<Unary_expression*>(e);
3740 if (ue->op_ == OPERATOR_AND)
3741 {
3742 if (e == expr)
3743 {
3744 // *&x == x.
f4dea966 3745 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3746 {
3747 error_at(ue->location(),
3748 "invalid operand for unary %<&%>");
3749 this->set_is_error();
3750 }
e440a328 3751 return ue->expr_;
3752 }
3753 ue->set_does_not_escape();
3754 }
3755 }
3756 }
3757
55661ce9 3758 // Catching an invalid indirection of unsafe.Pointer here avoid
3759 // having to deal with TYPE_VOID in other places.
3760 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3761 {
3762 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3763 return Expression::make_error(this->location());
3764 }
3765
59a401fe 3766 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3767 {
0c77715b 3768 Numeric_constant nc;
3769 if (expr->numeric_constant_value(&nc))
e440a328 3770 {
0c77715b 3771 Numeric_constant result;
3772 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3773 return result.expression(loc);
e440a328 3774 }
3775 }
3776
3777 return this;
3778}
3779
f9ca30f9 3780// Flatten expression if a nil check must be performed and create temporary
3781// variables if necessary.
3782
3783Expression*
3784Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3785 Statement_inserter* inserter)
3786{
f4dea966 3787 if (this->is_error_expression() || this->expr_->is_error_expression())
3788 return Expression::make_error(this->location());
3789
f9ca30f9 3790 Location location = this->location();
3791 if (this->op_ == OPERATOR_MULT
3792 && !this->expr_->is_variable())
3793 {
3794 go_assert(this->expr_->type()->points_to() != NULL);
3795 Type* ptype = this->expr_->type()->points_to();
3796 if (!ptype->is_void_type())
3797 {
3798 Btype* pbtype = ptype->get_backend(gogo);
3799 size_t s = gogo->backend()->type_size(pbtype);
3800 if (s >= 4096 || this->issue_nil_check_)
3801 {
3802 Temporary_statement* temp =
3803 Statement::make_temporary(NULL, this->expr_, location);
3804 inserter->insert(temp);
3805 this->expr_ =
3806 Expression::make_temporary_reference(temp, location);
3807 }
3808 }
3809 }
3810
3811 if (this->create_temp_ && !this->expr_->is_variable())
3812 {
3813 Temporary_statement* temp =
3814 Statement::make_temporary(NULL, this->expr_, location);
3815 inserter->insert(temp);
3816 this->expr_ = Expression::make_temporary_reference(temp, location);
3817 }
3818
3819 return this;
3820}
3821
e440a328 3822// Return whether a unary expression is a constant.
3823
3824bool
3825Unary_expression::do_is_constant() const
3826{
3827 if (this->op_ == OPERATOR_MULT)
3828 {
3829 // Indirecting through a pointer is only constant if the object
3830 // to which the expression points is constant, but we currently
3831 // have no way to determine that.
3832 return false;
3833 }
3834 else if (this->op_ == OPERATOR_AND)
3835 {
3836 // Taking the address of a variable is constant if it is a
f9ca30f9 3837 // global variable, not constant otherwise. In other cases taking the
3838 // address is probably not a constant.
e440a328 3839 Var_expression* ve = this->expr_->var_expression();
3840 if (ve != NULL)
3841 {
3842 Named_object* no = ve->named_object();
3843 return no->is_variable() && no->var_value()->is_global();
3844 }
3845 return false;
3846 }
3847 else
3848 return this->expr_->is_constant();
3849}
3850
0c77715b 3851// Apply unary opcode OP to UNC, setting NC. Return true if this
3852// could be done, false if not. Issue errors for overflow.
e440a328 3853
3854bool
0c77715b 3855Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3856 Location location, Numeric_constant* nc)
e440a328 3857{
3858 switch (op)
3859 {
3860 case OPERATOR_PLUS:
0c77715b 3861 *nc = *unc;
e440a328 3862 return true;
0c77715b 3863
e440a328 3864 case OPERATOR_MINUS:
0c77715b 3865 if (unc->is_int() || unc->is_rune())
3866 break;
3867 else if (unc->is_float())
3868 {
3869 mpfr_t uval;
3870 unc->get_float(&uval);
3871 mpfr_t val;
3872 mpfr_init(val);
3873 mpfr_neg(val, uval, GMP_RNDN);
3874 nc->set_float(unc->type(), val);
3875 mpfr_clear(uval);
3876 mpfr_clear(val);
3877 return true;
3878 }
3879 else if (unc->is_complex())
3880 {
3881 mpfr_t ureal, uimag;
3882 unc->get_complex(&ureal, &uimag);
3883 mpfr_t real, imag;
3884 mpfr_init(real);
3885 mpfr_init(imag);
3886 mpfr_neg(real, ureal, GMP_RNDN);
3887 mpfr_neg(imag, uimag, GMP_RNDN);
3888 nc->set_complex(unc->type(), real, imag);
3889 mpfr_clear(ureal);
3890 mpfr_clear(uimag);
3891 mpfr_clear(real);
3892 mpfr_clear(imag);
3893 return true;
3894 }
e440a328 3895 else
0c77715b 3896 go_unreachable();
e440a328 3897
0c77715b 3898 case OPERATOR_XOR:
3899 break;
68448d53 3900
59a401fe 3901 case OPERATOR_NOT:
e440a328 3902 case OPERATOR_AND:
3903 case OPERATOR_MULT:
3904 return false;
0c77715b 3905
e440a328 3906 default:
c3e6f413 3907 go_unreachable();
e440a328 3908 }
e440a328 3909
0c77715b 3910 if (!unc->is_int() && !unc->is_rune())
3911 return false;
3912
3913 mpz_t uval;
8387e1df 3914 if (unc->is_rune())
3915 unc->get_rune(&uval);
3916 else
3917 unc->get_int(&uval);
0c77715b 3918 mpz_t val;
3919 mpz_init(val);
e440a328 3920
e440a328 3921 switch (op)
3922 {
e440a328 3923 case OPERATOR_MINUS:
0c77715b 3924 mpz_neg(val, uval);
3925 break;
3926
e440a328 3927 case OPERATOR_NOT:
0c77715b 3928 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3929 break;
3930
e440a328 3931 case OPERATOR_XOR:
0c77715b 3932 {
3933 Type* utype = unc->type();
3934 if (utype->integer_type() == NULL
3935 || utype->integer_type()->is_abstract())
3936 mpz_com(val, uval);
3937 else
3938 {
3939 // The number of HOST_WIDE_INTs that it takes to represent
3940 // UVAL.
3941 size_t count = ((mpz_sizeinbase(uval, 2)
3942 + HOST_BITS_PER_WIDE_INT
3943 - 1)
3944 / HOST_BITS_PER_WIDE_INT);
e440a328 3945
0c77715b 3946 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3947 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3948
3949 size_t obits = utype->integer_type()->bits();
3950
3951 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3952 {
3953 mpz_t adj;
3954 mpz_init_set_ui(adj, 1);
3955 mpz_mul_2exp(adj, adj, obits);
3956 mpz_add(uval, uval, adj);
3957 mpz_clear(adj);
3958 }
3959
3960 size_t ecount;
3961 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3962 go_assert(ecount <= count);
3963
3964 // Trim down to the number of words required by the type.
3965 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3966 / HOST_BITS_PER_WIDE_INT);
3967 go_assert(ocount <= count);
3968
3969 for (size_t i = 0; i < ocount; ++i)
3970 phwi[i] = ~phwi[i];
3971
3972 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3973 if (clearbits != 0)
3974 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3975 >> clearbits);
3976
3977 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3978
3979 if (!utype->integer_type()->is_unsigned()
3980 && mpz_tstbit(val, obits - 1))
3981 {
3982 mpz_t adj;
3983 mpz_init_set_ui(adj, 1);
3984 mpz_mul_2exp(adj, adj, obits);
3985 mpz_sub(val, val, adj);
3986 mpz_clear(adj);
3987 }
3988
3989 delete[] phwi;
3990 }
3991 }
3992 break;
e440a328 3993
e440a328 3994 default:
c3e6f413 3995 go_unreachable();
e440a328 3996 }
e440a328 3997
0c77715b 3998 if (unc->is_rune())
3999 nc->set_rune(NULL, val);
e440a328 4000 else
0c77715b 4001 nc->set_int(NULL, val);
e440a328 4002
0c77715b 4003 mpz_clear(uval);
4004 mpz_clear(val);
e440a328 4005
0c77715b 4006 return nc->set_type(unc->type(), true, location);
e440a328 4007}
4008
0c77715b 4009// Return the integral constant value of a unary expression, if it has one.
e440a328 4010
4011bool
0c77715b 4012Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 4013{
0c77715b 4014 Numeric_constant unc;
4015 if (!this->expr_->numeric_constant_value(&unc))
4016 return false;
4017 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4018 nc);
e440a328 4019}
4020
4021// Return the type of a unary expression.
4022
4023Type*
4024Unary_expression::do_type()
4025{
4026 switch (this->op_)
4027 {
4028 case OPERATOR_PLUS:
4029 case OPERATOR_MINUS:
4030 case OPERATOR_NOT:
4031 case OPERATOR_XOR:
4032 return this->expr_->type();
4033
4034 case OPERATOR_AND:
4035 return Type::make_pointer_type(this->expr_->type());
4036
4037 case OPERATOR_MULT:
4038 {
4039 Type* subtype = this->expr_->type();
4040 Type* points_to = subtype->points_to();
4041 if (points_to == NULL)
4042 return Type::make_error_type();
4043 return points_to;
4044 }
4045
4046 default:
c3e6f413 4047 go_unreachable();
e440a328 4048 }
4049}
4050
4051// Determine abstract types for a unary expression.
4052
4053void
4054Unary_expression::do_determine_type(const Type_context* context)
4055{
4056 switch (this->op_)
4057 {
4058 case OPERATOR_PLUS:
4059 case OPERATOR_MINUS:
4060 case OPERATOR_NOT:
4061 case OPERATOR_XOR:
4062 this->expr_->determine_type(context);
4063 break;
4064
4065 case OPERATOR_AND:
4066 // Taking the address of something.
4067 {
4068 Type* subtype = (context->type == NULL
4069 ? NULL
4070 : context->type->points_to());
4071 Type_context subcontext(subtype, false);
4072 this->expr_->determine_type(&subcontext);
4073 }
4074 break;
4075
4076 case OPERATOR_MULT:
4077 // Indirecting through a pointer.
4078 {
4079 Type* subtype = (context->type == NULL
4080 ? NULL
4081 : Type::make_pointer_type(context->type));
4082 Type_context subcontext(subtype, false);
4083 this->expr_->determine_type(&subcontext);
4084 }
4085 break;
4086
4087 default:
c3e6f413 4088 go_unreachable();
e440a328 4089 }
4090}
4091
4092// Check types for a unary expression.
4093
4094void
4095Unary_expression::do_check_types(Gogo*)
4096{
9fe897ef 4097 Type* type = this->expr_->type();
5c13bd80 4098 if (type->is_error())
9fe897ef 4099 {
4100 this->set_is_error();
4101 return;
4102 }
4103
e440a328 4104 switch (this->op_)
4105 {
4106 case OPERATOR_PLUS:
4107 case OPERATOR_MINUS:
9fe897ef 4108 if (type->integer_type() == NULL
4109 && type->float_type() == NULL
4110 && type->complex_type() == NULL)
4111 this->report_error(_("expected numeric type"));
e440a328 4112 break;
4113
4114 case OPERATOR_NOT:
59a401fe 4115 if (!type->is_boolean_type())
4116 this->report_error(_("expected boolean type"));
4117 break;
4118
e440a328 4119 case OPERATOR_XOR:
9fe897ef 4120 if (type->integer_type() == NULL
4121 && !type->is_boolean_type())
4122 this->report_error(_("expected integer or boolean type"));
e440a328 4123 break;
4124
4125 case OPERATOR_AND:
4126 if (!this->expr_->is_addressable())
09ea332d 4127 {
4128 if (!this->create_temp_)
f4dea966 4129 {
4130 error_at(this->location(), "invalid operand for unary %<&%>");
4131 this->set_is_error();
4132 }
09ea332d 4133 }
e440a328 4134 else
56080003 4135 {
4136 this->expr_->address_taken(this->escapes_);
4137 this->expr_->issue_nil_check();
4138 }
e440a328 4139 break;
4140
4141 case OPERATOR_MULT:
4142 // Indirecting through a pointer.
9fe897ef 4143 if (type->points_to() == NULL)
4144 this->report_error(_("expected pointer"));
e440a328 4145 break;
4146
4147 default:
c3e6f413 4148 go_unreachable();
e440a328 4149 }
4150}
4151
4152// Get a tree for a unary expression.
4153
4154tree
4155Unary_expression::do_get_tree(Translate_context* context)
4156{
1b1f2abf 4157 Gogo* gogo = context->gogo();
e9d3367e 4158 Location loc = this->location();
4159
4160 // Taking the address of a set-and-use-temporary expression requires
4161 // setting the temporary and then taking the address.
4162 if (this->op_ == OPERATOR_AND)
4163 {
4164 Set_and_use_temporary_expression* sut =
4165 this->expr_->set_and_use_temporary_expression();
4166 if (sut != NULL)
4167 {
4168 Temporary_statement* temp = sut->temporary();
4169 Bvariable* bvar = temp->get_backend_variable(context);
f9ca30f9 4170 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4171
4172 Expression* val = sut->expression();
4173 Bexpression* bval = tree_to_expr(val->get_tree(context));
4174
4175 Bstatement* bassign =
4176 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4177 Bexpression* bvar_addr =
4178 gogo->backend()->address_expression(bvar_expr, loc);
4179 Bexpression* ret =
4180 gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4181 return expr_to_tree(ret);
e9d3367e 4182 }
4183 }
4184
f9ca30f9 4185 Bexpression* ret;
e440a328 4186 tree expr = this->expr_->get_tree(context);
f9ca30f9 4187 Bexpression* bexpr = tree_to_expr(expr);
4188 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4189 switch (this->op_)
4190 {
4191 case OPERATOR_PLUS:
f9ca30f9 4192 ret = bexpr;
4193 break;
e440a328 4194
4195 case OPERATOR_MINUS:
f9ca30f9 4196 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4197 ret = gogo->backend()->convert_expression(btype, ret, loc);
4198 break;
e440a328 4199
4200 case OPERATOR_NOT:
e440a328 4201 case OPERATOR_XOR:
f9ca30f9 4202 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4203 break;
e440a328 4204
4205 case OPERATOR_AND:
09ea332d 4206 if (!this->create_temp_)
4207 {
4208 // We should not see a non-constant constructor here; cases
4209 // where we would see one should have been moved onto the
4210 // heap at parse time. Taking the address of a nonconstant
4211 // constructor will not do what the programmer expects.
f9ca30f9 4212
4213 go_assert(!this->expr_->is_composite_literal()
4214 || this->expr_->is_immutable());
24060bf9 4215 if (this->expr_->classification() == EXPRESSION_UNARY)
4216 {
4217 Unary_expression* ue =
4218 static_cast<Unary_expression*>(this->expr_);
4219 go_assert(ue->op() != OPERATOR_AND);
4220 }
09ea332d 4221 }
e440a328 4222
4223 // Build a decl for a constant constructor.
f9ca30f9 4224 if ((this->expr_->is_composite_literal()
4225 || this->expr_->string_expression() != NULL)
4226 && this->expr_->is_immutable())
4227 {
4228 static unsigned int counter;
4229 char buf[100];
4230 snprintf(buf, sizeof buf, "C%u", counter);
4231 ++counter;
4232
4233 Bvariable* decl =
4234 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4235 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4236 btype, loc, bexpr);
4237 bexpr = gogo->backend()->var_expression(decl, loc);
4238 }
09ea332d 4239
f9ca30f9 4240 go_assert(!this->create_temp_ || this->expr_->is_variable());
4241 ret = gogo->backend()->address_expression(bexpr, loc);
4242 break;
e440a328 4243
4244 case OPERATOR_MULT:
4245 {
f9ca30f9 4246 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4247
4248 // If we are dereferencing the pointer to a large struct, we
4249 // need to check for nil. We don't bother to check for small
4250 // structs because we expect the system to crash on a nil
56080003 4251 // pointer dereference. However, if we know the address of this
4252 // expression is being taken, we must always check for nil.
f9ca30f9 4253
4254 Type* ptype = this->expr_->type()->points_to();
4255 Btype* pbtype = ptype->get_backend(gogo);
4256 if (!ptype->is_void_type())
e440a328 4257 {
f9ca30f9 4258 size_t s = gogo->backend()->type_size(pbtype);
4259 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4260 {
f9ca30f9 4261 go_assert(this->expr_->is_variable());
4262
4263 Expression* nil_expr = Expression::make_nil(loc);
4264 Bexpression* nil = tree_to_expr(nil_expr->get_tree(context));
4265 Bexpression* compare =
4266 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4267 nil, loc);
4268
aff1f085 4269 Expression* crash_expr =
4270 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
f9ca30f9 4271 Bexpression* crash =
4272 tree_to_expr(crash_expr->get_tree(context));
4273 bexpr = gogo->backend()->conditional_expression(btype, compare,
4274 crash, bexpr,
4275 loc);
4276
19b4f09b 4277 }
e440a328 4278 }
4279
4280 // If the type of EXPR is a recursive pointer type, then we
4281 // need to insert a cast before indirecting.
f9ca30f9 4282 tree expr = expr_to_tree(bexpr);
4283 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4284 if (VOID_TYPE_P(target_type_tree))
4285 {
4286 tree ind = type_to_tree(pbtype);
4287 expr = fold_convert_loc(loc.gcc_location(),
b13c66cd 4288 build_pointer_type(ind), expr);
f9ca30f9 4289 bexpr = tree_to_expr(expr);
4290 }
e440a328 4291
f9ca30f9 4292 ret = gogo->backend()->indirect_expression(bexpr, false, loc);
e440a328 4293 }
f9ca30f9 4294 break;
e440a328 4295
4296 default:
c3e6f413 4297 go_unreachable();
e440a328 4298 }
f9ca30f9 4299
4300 return expr_to_tree(ret);
e440a328 4301}
4302
4303// Export a unary expression.
4304
4305void
4306Unary_expression::do_export(Export* exp) const
4307{
4308 switch (this->op_)
4309 {
4310 case OPERATOR_PLUS:
4311 exp->write_c_string("+ ");
4312 break;
4313 case OPERATOR_MINUS:
4314 exp->write_c_string("- ");
4315 break;
4316 case OPERATOR_NOT:
4317 exp->write_c_string("! ");
4318 break;
4319 case OPERATOR_XOR:
4320 exp->write_c_string("^ ");
4321 break;
4322 case OPERATOR_AND:
4323 case OPERATOR_MULT:
4324 default:
c3e6f413 4325 go_unreachable();
e440a328 4326 }
4327 this->expr_->export_expression(exp);
4328}
4329
4330// Import a unary expression.
4331
4332Expression*
4333Unary_expression::do_import(Import* imp)
4334{
4335 Operator op;
4336 switch (imp->get_char())
4337 {
4338 case '+':
4339 op = OPERATOR_PLUS;
4340 break;
4341 case '-':
4342 op = OPERATOR_MINUS;
4343 break;
4344 case '!':
4345 op = OPERATOR_NOT;
4346 break;
4347 case '^':
4348 op = OPERATOR_XOR;
4349 break;
4350 default:
c3e6f413 4351 go_unreachable();
e440a328 4352 }
4353 imp->require_c_string(" ");
4354 Expression* expr = Expression::import_expression(imp);
4355 return Expression::make_unary(op, expr, imp->location());
4356}
4357
d751bb78 4358// Dump ast representation of an unary expression.
4359
4360void
4361Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4362{
4363 ast_dump_context->dump_operator(this->op_);
4364 ast_dump_context->ostream() << "(";
4365 ast_dump_context->dump_expression(this->expr_);
4366 ast_dump_context->ostream() << ") ";
4367}
4368
e440a328 4369// Make a unary expression.
4370
4371Expression*
b13c66cd 4372Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4373{
4374 return new Unary_expression(op, expr, location);
4375}
4376
4377// If this is an indirection through a pointer, return the expression
4378// being pointed through. Otherwise return this.
4379
4380Expression*
4381Expression::deref()
4382{
4383 if (this->classification_ == EXPRESSION_UNARY)
4384 {
4385 Unary_expression* ue = static_cast<Unary_expression*>(this);
4386 if (ue->op() == OPERATOR_MULT)
4387 return ue->operand();
4388 }
4389 return this;
4390}
4391
4392// Class Binary_expression.
4393
4394// Traversal.
4395
4396int
4397Binary_expression::do_traverse(Traverse* traverse)
4398{
4399 int t = Expression::traverse(&this->left_, traverse);
4400 if (t == TRAVERSE_EXIT)
4401 return TRAVERSE_EXIT;
4402 return Expression::traverse(&this->right_, traverse);
4403}
4404
0c77715b 4405// Return the type to use for a binary operation on operands of
4406// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4407// such may be NULL or abstract.
4408
4409bool
4410Binary_expression::operation_type(Operator op, Type* left_type,
4411 Type* right_type, Type** result_type)
4412{
4413 if (left_type != right_type
4414 && !left_type->is_abstract()
4415 && !right_type->is_abstract()
4416 && left_type->base() != right_type->base()
4417 && op != OPERATOR_LSHIFT
4418 && op != OPERATOR_RSHIFT)
4419 {
4420 // May be a type error--let it be diagnosed elsewhere.
4421 return false;
4422 }
4423
4424 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4425 {
4426 if (left_type->integer_type() != NULL)
4427 *result_type = left_type;
4428 else
4429 *result_type = Type::make_abstract_integer_type();
4430 }
4431 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4432 *result_type = left_type;
4433 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4434 *result_type = right_type;
4435 else if (!left_type->is_abstract())
4436 *result_type = left_type;
4437 else if (!right_type->is_abstract())
4438 *result_type = right_type;
4439 else if (left_type->complex_type() != NULL)
4440 *result_type = left_type;
4441 else if (right_type->complex_type() != NULL)
4442 *result_type = right_type;
4443 else if (left_type->float_type() != NULL)
4444 *result_type = left_type;
4445 else if (right_type->float_type() != NULL)
4446 *result_type = right_type;
4447 else if (left_type->integer_type() != NULL
4448 && left_type->integer_type()->is_rune())
4449 *result_type = left_type;
4450 else if (right_type->integer_type() != NULL
4451 && right_type->integer_type()->is_rune())
4452 *result_type = right_type;
4453 else
4454 *result_type = left_type;
4455
4456 return true;
4457}
4458
4459// Convert an integer comparison code and an operator to a boolean
4460// value.
e440a328 4461
4462bool
0c77715b 4463Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4464{
e440a328 4465 switch (op)
4466 {
4467 case OPERATOR_EQEQ:
0c77715b 4468 return cmp == 0;
4469 break;
e440a328 4470 case OPERATOR_NOTEQ:
0c77715b 4471 return cmp != 0;
4472 break;
e440a328 4473 case OPERATOR_LT:
0c77715b 4474 return cmp < 0;
4475 break;
e440a328 4476 case OPERATOR_LE:
0c77715b 4477 return cmp <= 0;
e440a328 4478 case OPERATOR_GT:
0c77715b 4479 return cmp > 0;
e440a328 4480 case OPERATOR_GE:
0c77715b 4481 return cmp >= 0;
e440a328 4482 default:
c3e6f413 4483 go_unreachable();
e440a328 4484 }
4485}
4486
0c77715b 4487// Compare constants according to OP.
e440a328 4488
4489bool
0c77715b 4490Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4491 Numeric_constant* right_nc,
4492 Location location, bool* result)
e440a328 4493{
0c77715b 4494 Type* left_type = left_nc->type();
4495 Type* right_type = right_nc->type();
4496
4497 Type* type;
4498 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4499 return false;
4500
4501 // When comparing an untyped operand to a typed operand, we are
4502 // effectively coercing the untyped operand to the other operand's
4503 // type, so make sure that is valid.
4504 if (!left_nc->set_type(type, true, location)
4505 || !right_nc->set_type(type, true, location))
4506 return false;
4507
4508 bool ret;
4509 int cmp;
4510 if (type->complex_type() != NULL)
4511 {
4512 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4513 return false;
4514 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4515 }
4516 else if (type->float_type() != NULL)
4517 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4518 else
0c77715b 4519 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4520
4521 if (ret)
4522 *result = Binary_expression::cmp_to_bool(op, cmp);
4523
4524 return ret;
4525}
4526
4527// Compare integer constants.
4528
4529bool
4530Binary_expression::compare_integer(const Numeric_constant* left_nc,
4531 const Numeric_constant* right_nc,
4532 int* cmp)
4533{
4534 mpz_t left_val;
4535 if (!left_nc->to_int(&left_val))
4536 return false;
4537 mpz_t right_val;
4538 if (!right_nc->to_int(&right_val))
e440a328 4539 {
0c77715b 4540 mpz_clear(left_val);
4541 return false;
e440a328 4542 }
0c77715b 4543
4544 *cmp = mpz_cmp(left_val, right_val);
4545
4546 mpz_clear(left_val);
4547 mpz_clear(right_val);
4548
4549 return true;
4550}
4551
4552// Compare floating point constants.
4553
4554bool
4555Binary_expression::compare_float(const Numeric_constant* left_nc,
4556 const Numeric_constant* right_nc,
4557 int* cmp)
4558{
4559 mpfr_t left_val;
4560 if (!left_nc->to_float(&left_val))
4561 return false;
4562 mpfr_t right_val;
4563 if (!right_nc->to_float(&right_val))
e440a328 4564 {
0c77715b 4565 mpfr_clear(left_val);
4566 return false;
4567 }
4568
4569 // We already coerced both operands to the same type. If that type
4570 // is not an abstract type, we need to round the values accordingly.
4571 Type* type = left_nc->type();
4572 if (!type->is_abstract() && type->float_type() != NULL)
4573 {
4574 int bits = type->float_type()->bits();
4575 mpfr_prec_round(left_val, bits, GMP_RNDN);
4576 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4577 }
0c77715b 4578
4579 *cmp = mpfr_cmp(left_val, right_val);
4580
4581 mpfr_clear(left_val);
4582 mpfr_clear(right_val);
4583
4584 return true;
e440a328 4585}
4586
0c77715b 4587// Compare complex constants. Complex numbers may only be compared
4588// for equality.
e440a328 4589
4590bool
0c77715b 4591Binary_expression::compare_complex(const Numeric_constant* left_nc,
4592 const Numeric_constant* right_nc,
4593 int* cmp)
e440a328 4594{
0c77715b 4595 mpfr_t left_real, left_imag;
4596 if (!left_nc->to_complex(&left_real, &left_imag))
4597 return false;
4598 mpfr_t right_real, right_imag;
4599 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4600 {
0c77715b 4601 mpfr_clear(left_real);
4602 mpfr_clear(left_imag);
4603 return false;
e440a328 4604 }
0c77715b 4605
4606 // We already coerced both operands to the same type. If that type
4607 // is not an abstract type, we need to round the values accordingly.
4608 Type* type = left_nc->type();
4609 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4610 {
0c77715b 4611 int bits = type->complex_type()->bits();
4612 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4613 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4614 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4615 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
e440a328 4616 }
0c77715b 4617
4618 *cmp = (mpfr_cmp(left_real, right_real) != 0
4619 || mpfr_cmp(left_imag, right_imag) != 0);
4620
4621 mpfr_clear(left_real);
4622 mpfr_clear(left_imag);
4623 mpfr_clear(right_real);
4624 mpfr_clear(right_imag);
4625
4626 return true;
e440a328 4627}
4628
0c77715b 4629// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4630// true if this could be done, false if not. Issue errors at LOCATION
4631// as appropriate.
e440a328 4632
4633bool
0c77715b 4634Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4635 Numeric_constant* right_nc,
4636 Location location, Numeric_constant* nc)
e440a328 4637{
e440a328 4638 switch (op)
4639 {
4640 case OPERATOR_OROR:
4641 case OPERATOR_ANDAND:
4642 case OPERATOR_EQEQ:
4643 case OPERATOR_NOTEQ:
4644 case OPERATOR_LT:
4645 case OPERATOR_LE:
4646 case OPERATOR_GT:
4647 case OPERATOR_GE:
9767e2d3 4648 // These return boolean values, not numeric.
4649 return false;
0c77715b 4650 default:
4651 break;
4652 }
4653
4654 Type* left_type = left_nc->type();
4655 Type* right_type = right_nc->type();
4656
4657 Type* type;
4658 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4659 return false;
4660
4661 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4662
4663 // When combining an untyped operand with a typed operand, we are
4664 // effectively coercing the untyped operand to the other operand's
4665 // type, so make sure that is valid.
4666 if (!left_nc->set_type(type, true, location))
4667 return false;
4668 if (!is_shift && !right_nc->set_type(type, true, location))
4669 return false;
4670
4671 bool r;
4672 if (type->complex_type() != NULL)
4673 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4674 else if (type->float_type() != NULL)
4675 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4676 else
4677 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4678
4679 if (r)
4680 r = nc->set_type(type, true, location);
4681
4682 return r;
4683}
4684
4685// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4686// integer operations. Return true if this could be done, false if
4687// not.
4688
4689bool
4690Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4691 const Numeric_constant* right_nc,
4692 Location location, Numeric_constant* nc)
4693{
4694 mpz_t left_val;
4695 if (!left_nc->to_int(&left_val))
4696 return false;
4697 mpz_t right_val;
4698 if (!right_nc->to_int(&right_val))
4699 {
4700 mpz_clear(left_val);
e440a328 4701 return false;
0c77715b 4702 }
4703
4704 mpz_t val;
4705 mpz_init(val);
4706
4707 switch (op)
4708 {
e440a328 4709 case OPERATOR_PLUS:
4710 mpz_add(val, left_val, right_val);
2c809f8f 4711 if (mpz_sizeinbase(val, 2) > 0x100000)
4712 {
4713 error_at(location, "constant addition overflow");
4714 mpz_set_ui(val, 1);
4715 }
e440a328 4716 break;
4717 case OPERATOR_MINUS:
4718 mpz_sub(val, left_val, right_val);
2c809f8f 4719 if (mpz_sizeinbase(val, 2) > 0x100000)
4720 {
4721 error_at(location, "constant subtraction overflow");
4722 mpz_set_ui(val, 1);
4723 }
e440a328 4724 break;
4725 case OPERATOR_OR:
4726 mpz_ior(val, left_val, right_val);
4727 break;
4728 case OPERATOR_XOR:
4729 mpz_xor(val, left_val, right_val);
4730 break;
4731 case OPERATOR_MULT:
4732 mpz_mul(val, left_val, right_val);
2c809f8f 4733 if (mpz_sizeinbase(val, 2) > 0x100000)
4734 {
4735 error_at(location, "constant multiplication overflow");
4736 mpz_set_ui(val, 1);
4737 }
e440a328 4738 break;
4739 case OPERATOR_DIV:
4740 if (mpz_sgn(right_val) != 0)
4741 mpz_tdiv_q(val, left_val, right_val);
4742 else
4743 {
4744 error_at(location, "division by zero");
4745 mpz_set_ui(val, 0);
e440a328 4746 }
4747 break;
4748 case OPERATOR_MOD:
4749 if (mpz_sgn(right_val) != 0)
4750 mpz_tdiv_r(val, left_val, right_val);
4751 else
4752 {
4753 error_at(location, "division by zero");
4754 mpz_set_ui(val, 0);
e440a328 4755 }
4756 break;
4757 case OPERATOR_LSHIFT:
4758 {
4759 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4760 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4761 mpz_mul_2exp(val, left_val, shift);
4762 else
e440a328 4763 {
4764 error_at(location, "shift count overflow");
2c809f8f 4765 mpz_set_ui(val, 1);
e440a328 4766 }
e440a328 4767 break;
4768 }
4769 break;
4770 case OPERATOR_RSHIFT:
4771 {
4772 unsigned long shift = mpz_get_ui(right_val);
4773 if (mpz_cmp_ui(right_val, shift) != 0)
4774 {
4775 error_at(location, "shift count overflow");
2c809f8f 4776 mpz_set_ui(val, 1);
e440a328 4777 }
e440a328 4778 else
0c77715b 4779 {
4780 if (mpz_cmp_ui(left_val, 0) >= 0)
4781 mpz_tdiv_q_2exp(val, left_val, shift);
4782 else
4783 mpz_fdiv_q_2exp(val, left_val, shift);
4784 }
e440a328 4785 break;
4786 }
4787 break;
4788 case OPERATOR_AND:
4789 mpz_and(val, left_val, right_val);
4790 break;
4791 case OPERATOR_BITCLEAR:
4792 {
4793 mpz_t tval;
4794 mpz_init(tval);
4795 mpz_com(tval, right_val);
4796 mpz_and(val, left_val, tval);
4797 mpz_clear(tval);
4798 }
4799 break;
4800 default:
c3e6f413 4801 go_unreachable();
e440a328 4802 }
4803
0c77715b 4804 mpz_clear(left_val);
4805 mpz_clear(right_val);
e440a328 4806
0c77715b 4807 if (left_nc->is_rune()
4808 || (op != OPERATOR_LSHIFT
4809 && op != OPERATOR_RSHIFT
4810 && right_nc->is_rune()))
4811 nc->set_rune(NULL, val);
4812 else
4813 nc->set_int(NULL, val);
4814
4815 mpz_clear(val);
e440a328 4816
4817 return true;
4818}
4819
0c77715b 4820// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4821// floating point operations. Return true if this could be done,
4822// false if not.
e440a328 4823
4824bool
0c77715b 4825Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4826 const Numeric_constant* right_nc,
4827 Location location, Numeric_constant* nc)
e440a328 4828{
0c77715b 4829 mpfr_t left_val;
4830 if (!left_nc->to_float(&left_val))
4831 return false;
4832 mpfr_t right_val;
4833 if (!right_nc->to_float(&right_val))
e440a328 4834 {
0c77715b 4835 mpfr_clear(left_val);
e440a328 4836 return false;
0c77715b 4837 }
4838
4839 mpfr_t val;
4840 mpfr_init(val);
4841
4842 bool ret = true;
4843 switch (op)
4844 {
e440a328 4845 case OPERATOR_PLUS:
4846 mpfr_add(val, left_val, right_val, GMP_RNDN);
4847 break;
4848 case OPERATOR_MINUS:
4849 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4850 break;
4851 case OPERATOR_OR:
4852 case OPERATOR_XOR:
4853 case OPERATOR_AND:
4854 case OPERATOR_BITCLEAR:
0c77715b 4855 case OPERATOR_MOD:
4856 case OPERATOR_LSHIFT:
4857 case OPERATOR_RSHIFT:
4858 mpfr_set_ui(val, 0, GMP_RNDN);
4859 ret = false;
4860 break;
e440a328 4861 case OPERATOR_MULT:
4862 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4863 break;
4864 case OPERATOR_DIV:
0c77715b 4865 if (!mpfr_zero_p(right_val))
4866 mpfr_div(val, left_val, right_val, GMP_RNDN);
4867 else
4868 {
4869 error_at(location, "division by zero");
4870 mpfr_set_ui(val, 0, GMP_RNDN);
4871 }
e440a328 4872 break;
e440a328 4873 default:
c3e6f413 4874 go_unreachable();
e440a328 4875 }
4876
0c77715b 4877 mpfr_clear(left_val);
4878 mpfr_clear(right_val);
e440a328 4879
0c77715b 4880 nc->set_float(NULL, val);
4881 mpfr_clear(val);
e440a328 4882
0c77715b 4883 return ret;
e440a328 4884}
4885
0c77715b 4886// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4887// complex operations. Return true if this could be done, false if
4888// not.
e440a328 4889
4890bool
0c77715b 4891Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4892 const Numeric_constant* right_nc,
4893 Location location, Numeric_constant* nc)
e440a328 4894{
0c77715b 4895 mpfr_t left_real, left_imag;
4896 if (!left_nc->to_complex(&left_real, &left_imag))
4897 return false;
4898 mpfr_t right_real, right_imag;
4899 if (!right_nc->to_complex(&right_real, &right_imag))
e440a328 4900 {
0c77715b 4901 mpfr_clear(left_real);
4902 mpfr_clear(left_imag);
e440a328 4903 return false;
0c77715b 4904 }
4905
4906 mpfr_t real, imag;
4907 mpfr_init(real);
4908 mpfr_init(imag);
4909
4910 bool ret = true;
4911 switch (op)
4912 {
e440a328 4913 case OPERATOR_PLUS:
4914 mpfr_add(real, left_real, right_real, GMP_RNDN);
4915 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4916 break;
4917 case OPERATOR_MINUS:
4918 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4919 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4920 break;
4921 case OPERATOR_OR:
4922 case OPERATOR_XOR:
4923 case OPERATOR_AND:
4924 case OPERATOR_BITCLEAR:
0c77715b 4925 case OPERATOR_MOD:
4926 case OPERATOR_LSHIFT:
4927 case OPERATOR_RSHIFT:
4928 mpfr_set_ui(real, 0, GMP_RNDN);
4929 mpfr_set_ui(imag, 0, GMP_RNDN);
4930 ret = false;
4931 break;
e440a328 4932 case OPERATOR_MULT:
4933 {
4934 // You might think that multiplying two complex numbers would
4935 // be simple, and you would be right, until you start to think
4936 // about getting the right answer for infinity. If one
4937 // operand here is infinity and the other is anything other
4938 // than zero or NaN, then we are going to wind up subtracting
4939 // two infinity values. That will give us a NaN, but the
4940 // correct answer is infinity.
4941
4942 mpfr_t lrrr;
4943 mpfr_init(lrrr);
4944 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4945
4946 mpfr_t lrri;
4947 mpfr_init(lrri);
4948 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4949
4950 mpfr_t lirr;
4951 mpfr_init(lirr);
4952 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4953
4954 mpfr_t liri;
4955 mpfr_init(liri);
4956 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4957
4958 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4959 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4960
4961 // If we get NaN on both sides, check whether it should really
4962 // be infinity. The rule is that if either side of the
4963 // complex number is infinity, then the whole value is
4964 // infinity, even if the other side is NaN. So the only case
4965 // we have to fix is the one in which both sides are NaN.
4966 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4967 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4968 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4969 {
4970 bool is_infinity = false;
4971
4972 mpfr_t lr;
4973 mpfr_t li;
4974 mpfr_init_set(lr, left_real, GMP_RNDN);
4975 mpfr_init_set(li, left_imag, GMP_RNDN);
4976
4977 mpfr_t rr;
4978 mpfr_t ri;
4979 mpfr_init_set(rr, right_real, GMP_RNDN);
4980 mpfr_init_set(ri, right_imag, GMP_RNDN);
4981
4982 // If the left side is infinity, then the result is
4983 // infinity.
4984 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4985 {
4986 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4987 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4988 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4989 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4990 if (mpfr_nan_p(rr))
4991 {
4992 mpfr_set_ui(rr, 0, GMP_RNDN);
4993 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4994 }
4995 if (mpfr_nan_p(ri))
4996 {
4997 mpfr_set_ui(ri, 0, GMP_RNDN);
4998 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4999 }
5000 is_infinity = true;
5001 }
5002
5003 // If the right side is infinity, then the result is
5004 // infinity.
5005 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
5006 {
5007 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5008 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5009 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5010 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5011 if (mpfr_nan_p(lr))
5012 {
5013 mpfr_set_ui(lr, 0, GMP_RNDN);
5014 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5015 }
5016 if (mpfr_nan_p(li))
5017 {
5018 mpfr_set_ui(li, 0, GMP_RNDN);
5019 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5020 }
5021 is_infinity = true;
5022 }
5023
5024 // If we got an overflow in the intermediate computations,
5025 // then the result is infinity.
5026 if (!is_infinity
5027 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
5028 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
5029 {
5030 if (mpfr_nan_p(lr))
5031 {
5032 mpfr_set_ui(lr, 0, GMP_RNDN);
5033 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5034 }
5035 if (mpfr_nan_p(li))
5036 {
5037 mpfr_set_ui(li, 0, GMP_RNDN);
5038 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5039 }
5040 if (mpfr_nan_p(rr))
5041 {
5042 mpfr_set_ui(rr, 0, GMP_RNDN);
5043 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5044 }
5045 if (mpfr_nan_p(ri))
5046 {
5047 mpfr_set_ui(ri, 0, GMP_RNDN);
5048 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5049 }
5050 is_infinity = true;
5051 }
5052
5053 if (is_infinity)
5054 {
5055 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5056 mpfr_mul(lrri, lr, ri, GMP_RNDN);
5057 mpfr_mul(lirr, li, rr, GMP_RNDN);
5058 mpfr_mul(liri, li, ri, GMP_RNDN);
5059 mpfr_sub(real, lrrr, liri, GMP_RNDN);
5060 mpfr_add(imag, lrri, lirr, GMP_RNDN);
5061 mpfr_set_inf(real, mpfr_sgn(real));
5062 mpfr_set_inf(imag, mpfr_sgn(imag));
5063 }
5064
5065 mpfr_clear(lr);
5066 mpfr_clear(li);
5067 mpfr_clear(rr);
5068 mpfr_clear(ri);
5069 }
5070
5071 mpfr_clear(lrrr);
5072 mpfr_clear(lrri);
5073 mpfr_clear(lirr);
5074 mpfr_clear(liri);
5075 }
5076 break;
5077 case OPERATOR_DIV:
5078 {
5079 // For complex division we want to avoid having an
5080 // intermediate overflow turn the whole result in a NaN. We
5081 // scale the values to try to avoid this.
5082
5083 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
0c77715b 5084 {
5085 error_at(location, "division by zero");
5086 mpfr_set_ui(real, 0, GMP_RNDN);
5087 mpfr_set_ui(imag, 0, GMP_RNDN);
5088 break;
5089 }
e440a328 5090
5091 mpfr_t rra;
5092 mpfr_t ria;
5093 mpfr_init(rra);
5094 mpfr_init(ria);
5095 mpfr_abs(rra, right_real, GMP_RNDN);
5096 mpfr_abs(ria, right_imag, GMP_RNDN);
5097 mpfr_t t;
5098 mpfr_init(t);
5099 mpfr_max(t, rra, ria, GMP_RNDN);
5100
5101 mpfr_t rr;
5102 mpfr_t ri;
5103 mpfr_init_set(rr, right_real, GMP_RNDN);
5104 mpfr_init_set(ri, right_imag, GMP_RNDN);
5105 long ilogbw = 0;
5106 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5107 {
5108 ilogbw = mpfr_get_exp(t);
5109 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5110 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5111 }
5112
5113 mpfr_t denom;
5114 mpfr_init(denom);
5115 mpfr_mul(denom, rr, rr, GMP_RNDN);
5116 mpfr_mul(t, ri, ri, GMP_RNDN);
5117 mpfr_add(denom, denom, t, GMP_RNDN);
5118
5119 mpfr_mul(real, left_real, rr, GMP_RNDN);
5120 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5121 mpfr_add(real, real, t, GMP_RNDN);
5122 mpfr_div(real, real, denom, GMP_RNDN);
5123 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5124
5125 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5126 mpfr_mul(t, left_real, ri, GMP_RNDN);
5127 mpfr_sub(imag, imag, t, GMP_RNDN);
5128 mpfr_div(imag, imag, denom, GMP_RNDN);
5129 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5130
5131 // If we wind up with NaN on both sides, check whether we
5132 // should really have infinity. The rule is that if either
5133 // side of the complex number is infinity, then the whole
5134 // value is infinity, even if the other side is NaN. So the
5135 // only case we have to fix is the one in which both sides are
5136 // NaN.
5137 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5138 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5139 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5140 {
5141 if (mpfr_zero_p(denom))
5142 {
5143 mpfr_set_inf(real, mpfr_sgn(rr));
5144 mpfr_mul(real, real, left_real, GMP_RNDN);
5145 mpfr_set_inf(imag, mpfr_sgn(rr));
5146 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5147 }
5148 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5149 && mpfr_number_p(rr) && mpfr_number_p(ri))
5150 {
5151 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5152 mpfr_copysign(t, t, left_real, GMP_RNDN);
5153
5154 mpfr_t t2;
5155 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5156 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5157
5158 mpfr_t t3;
5159 mpfr_init(t3);
5160 mpfr_mul(t3, t, rr, GMP_RNDN);
5161
5162 mpfr_t t4;
5163 mpfr_init(t4);
5164 mpfr_mul(t4, t2, ri, GMP_RNDN);
5165
5166 mpfr_add(t3, t3, t4, GMP_RNDN);
5167 mpfr_set_inf(real, mpfr_sgn(t3));
5168
5169 mpfr_mul(t3, t2, rr, GMP_RNDN);
5170 mpfr_mul(t4, t, ri, GMP_RNDN);
5171 mpfr_sub(t3, t3, t4, GMP_RNDN);
5172 mpfr_set_inf(imag, mpfr_sgn(t3));
5173
5174 mpfr_clear(t2);
5175 mpfr_clear(t3);
5176 mpfr_clear(t4);
5177 }
5178 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5179 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5180 {
5181 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5182 mpfr_copysign(t, t, rr, GMP_RNDN);
5183
5184 mpfr_t t2;
5185 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5186 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5187
5188 mpfr_t t3;
5189 mpfr_init(t3);
5190 mpfr_mul(t3, left_real, t, GMP_RNDN);
5191
5192 mpfr_t t4;
5193 mpfr_init(t4);
5194 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5195
5196 mpfr_add(t3, t3, t4, GMP_RNDN);
5197 mpfr_set_ui(real, 0, GMP_RNDN);
5198 mpfr_mul(real, real, t3, GMP_RNDN);
5199
5200 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5201 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5202 mpfr_sub(t3, t3, t4, GMP_RNDN);
5203 mpfr_set_ui(imag, 0, GMP_RNDN);
5204 mpfr_mul(imag, imag, t3, GMP_RNDN);
5205
5206 mpfr_clear(t2);
5207 mpfr_clear(t3);
5208 mpfr_clear(t4);
5209 }
5210 }
5211
5212 mpfr_clear(denom);
5213 mpfr_clear(rr);
5214 mpfr_clear(ri);
5215 mpfr_clear(t);
5216 mpfr_clear(rra);
5217 mpfr_clear(ria);
5218 }
5219 break;
e440a328 5220 default:
c3e6f413 5221 go_unreachable();
e440a328 5222 }
5223
0c77715b 5224 mpfr_clear(left_real);
5225 mpfr_clear(left_imag);
5226 mpfr_clear(right_real);
5227 mpfr_clear(right_imag);
e440a328 5228
0c77715b 5229 nc->set_complex(NULL, real, imag);
5230 mpfr_clear(real);
5231 mpfr_clear(imag);
e440a328 5232
0c77715b 5233 return ret;
e440a328 5234}
5235
5236// Lower a binary expression. We have to evaluate constant
5237// expressions now, in order to implement Go's unlimited precision
5238// constants.
5239
5240Expression*
e9d3367e 5241Binary_expression::do_lower(Gogo* gogo, Named_object*,
5242 Statement_inserter* inserter, int)
e440a328 5243{
b13c66cd 5244 Location location = this->location();
e440a328 5245 Operator op = this->op_;
5246 Expression* left = this->left_;
5247 Expression* right = this->right_;
5248
5249 const bool is_comparison = (op == OPERATOR_EQEQ
5250 || op == OPERATOR_NOTEQ
5251 || op == OPERATOR_LT
5252 || op == OPERATOR_LE
5253 || op == OPERATOR_GT
5254 || op == OPERATOR_GE);
5255
0c77715b 5256 // Numeric constant expressions.
e440a328 5257 {
0c77715b 5258 Numeric_constant left_nc;
5259 Numeric_constant right_nc;
5260 if (left->numeric_constant_value(&left_nc)
5261 && right->numeric_constant_value(&right_nc))
e440a328 5262 {
0c77715b 5263 if (is_comparison)
e440a328 5264 {
0c77715b 5265 bool result;
5266 if (!Binary_expression::compare_constant(op, &left_nc,
5267 &right_nc, location,
5268 &result))
5269 return this;
e90c9dfc 5270 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5271 Expression::make_boolean(result,
5272 location),
5273 location);
e440a328 5274 }
5275 else
5276 {
0c77715b 5277 Numeric_constant nc;
5278 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5279 location, &nc))
5280 return this;
5281 return nc.expression(location);
e440a328 5282 }
5283 }
e440a328 5284 }
5285
5286 // String constant expressions.
315fa98d 5287 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5288 {
5289 std::string left_string;
5290 std::string right_string;
5291 if (left->string_constant_value(&left_string)
5292 && right->string_constant_value(&right_string))
315fa98d 5293 {
5294 if (op == OPERATOR_PLUS)
5295 return Expression::make_string(left_string + right_string,
5296 location);
5297 else if (is_comparison)
5298 {
5299 int cmp = left_string.compare(right_string);
0c77715b 5300 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5301 return Expression::make_boolean(r, location);
b40dc774 5302 }
5303 }
b40dc774 5304 }
5305
ceeb12d7 5306 // Lower struct, array, and some interface comparisons.
e9d3367e 5307 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5308 {
5309 if (left->type()->struct_type() != NULL)
5310 return this->lower_struct_comparison(gogo, inserter);
5311 else if (left->type()->array_type() != NULL
5312 && !left->type()->is_slice_type())
5313 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5314 else if ((left->type()->interface_type() != NULL
5315 && right->type()->interface_type() == NULL)
5316 || (left->type()->interface_type() == NULL
5317 && right->type()->interface_type() != NULL))
5318 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5319 }
5320
e440a328 5321 return this;
5322}
5323
e9d3367e 5324// Lower a struct comparison.
5325
5326Expression*
5327Binary_expression::lower_struct_comparison(Gogo* gogo,
5328 Statement_inserter* inserter)
5329{
5330 Struct_type* st = this->left_->type()->struct_type();
5331 Struct_type* st2 = this->right_->type()->struct_type();
5332 if (st2 == NULL)
5333 return this;
5334 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5335 return this;
5336 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5337 this->right_->type(), NULL))
5338 return this;
5339
5340 // See if we can compare using memcmp. As a heuristic, we use
5341 // memcmp rather than field references and comparisons if there are
5342 // more than two fields.
113ef6a5 5343 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5344 return this->lower_compare_to_memcmp(gogo, inserter);
5345
5346 Location loc = this->location();
5347
5348 Expression* left = this->left_;
5349 Temporary_statement* left_temp = NULL;
5350 if (left->var_expression() == NULL
5351 && left->temporary_reference_expression() == NULL)
5352 {
5353 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5354 inserter->insert(left_temp);
5355 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5356 }
5357
5358 Expression* right = this->right_;
5359 Temporary_statement* right_temp = NULL;
5360 if (right->var_expression() == NULL
5361 && right->temporary_reference_expression() == NULL)
5362 {
5363 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5364 inserter->insert(right_temp);
5365 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5366 }
5367
5368 Expression* ret = Expression::make_boolean(true, loc);
5369 const Struct_field_list* fields = st->fields();
5370 unsigned int field_index = 0;
5371 for (Struct_field_list::const_iterator pf = fields->begin();
5372 pf != fields->end();
5373 ++pf, ++field_index)
5374 {
f5165c05 5375 if (Gogo::is_sink_name(pf->field_name()))
5376 continue;
5377
e9d3367e 5378 if (field_index > 0)
5379 {
5380 if (left_temp == NULL)
5381 left = left->copy();
5382 else
5383 left = Expression::make_temporary_reference(left_temp, loc);
5384 if (right_temp == NULL)
5385 right = right->copy();
5386 else
5387 right = Expression::make_temporary_reference(right_temp, loc);
5388 }
5389 Expression* f1 = Expression::make_field_reference(left, field_index,
5390 loc);
5391 Expression* f2 = Expression::make_field_reference(right, field_index,
5392 loc);
5393 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5394 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5395 }
5396
5397 if (this->op_ == OPERATOR_NOTEQ)
5398 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5399
5400 return ret;
5401}
5402
5403// Lower an array comparison.
5404
5405Expression*
5406Binary_expression::lower_array_comparison(Gogo* gogo,
5407 Statement_inserter* inserter)
5408{
5409 Array_type* at = this->left_->type()->array_type();
5410 Array_type* at2 = this->right_->type()->array_type();
5411 if (at2 == NULL)
5412 return this;
5413 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5414 return this;
5415 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5416 this->right_->type(), NULL))
5417 return this;
5418
5419 // Call memcmp directly if possible. This may let the middle-end
5420 // optimize the call.
113ef6a5 5421 if (at->compare_is_identity(gogo))
e9d3367e 5422 return this->lower_compare_to_memcmp(gogo, inserter);
5423
5424 // Call the array comparison function.
5425 Named_object* hash_fn;
5426 Named_object* equal_fn;
5427 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5428 &hash_fn, &equal_fn);
5429
5430 Location loc = this->location();
5431
5432 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5433
5434 Expression_list* args = new Expression_list();
5435 args->push_back(this->operand_address(inserter, this->left_));
5436 args->push_back(this->operand_address(inserter, this->right_));
5437 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5438
5439 Expression* ret = Expression::make_call(func, args, false, loc);
5440
5441 if (this->op_ == OPERATOR_NOTEQ)
5442 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5443
5444 return ret;
5445}
5446
ceeb12d7 5447// Lower an interface to value comparison.
5448
5449Expression*
5450Binary_expression::lower_interface_value_comparison(Gogo*,
5451 Statement_inserter* inserter)
5452{
5453 Type* left_type = this->left_->type();
5454 Type* right_type = this->right_->type();
5455 Interface_type* ift;
5456 if (left_type->interface_type() != NULL)
5457 {
5458 ift = left_type->interface_type();
5459 if (!ift->implements_interface(right_type, NULL))
5460 return this;
5461 }
5462 else
5463 {
5464 ift = right_type->interface_type();
5465 if (!ift->implements_interface(left_type, NULL))
5466 return this;
5467 }
5468 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5469 return this;
5470
5471 Location loc = this->location();
5472
5473 if (left_type->interface_type() == NULL
5474 && left_type->points_to() == NULL
5475 && !this->left_->is_addressable())
5476 {
5477 Temporary_statement* temp =
5478 Statement::make_temporary(left_type, NULL, loc);
5479 inserter->insert(temp);
5480 this->left_ =
5481 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5482 }
5483
5484 if (right_type->interface_type() == NULL
5485 && right_type->points_to() == NULL
5486 && !this->right_->is_addressable())
5487 {
5488 Temporary_statement* temp =
5489 Statement::make_temporary(right_type, NULL, loc);
5490 inserter->insert(temp);
5491 this->right_ =
5492 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5493 }
5494
5495 return this;
5496}
5497
e9d3367e 5498// Lower a struct or array comparison to a call to memcmp.
5499
5500Expression*
5501Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5502{
5503 Location loc = this->location();
5504
5505 Expression* a1 = this->operand_address(inserter, this->left_);
5506 Expression* a2 = this->operand_address(inserter, this->right_);
5507 Expression* len = Expression::make_type_info(this->left_->type(),
5508 TYPE_INFO_SIZE);
5509
5510 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5511
5512 mpz_t zval;
5513 mpz_init_set_ui(zval, 0);
5514 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5515 mpz_clear(zval);
5516
5517 return Expression::make_binary(this->op_, call, zero, loc);
5518}
5519
a32698ee 5520Expression*
5521Binary_expression::do_flatten(Gogo*, Named_object*,
5522 Statement_inserter* inserter)
5523{
5524 Location loc = this->location();
5525 Temporary_statement* temp;
5526 if (this->left_->type()->is_string_type()
5527 && this->op_ == OPERATOR_PLUS)
5528 {
5529 if (!this->left_->is_variable())
5530 {
5531 temp = Statement::make_temporary(NULL, this->left_, loc);
5532 inserter->insert(temp);
5533 this->left_ = Expression::make_temporary_reference(temp, loc);
5534 }
5535 if (!this->right_->is_variable())
5536 {
5537 temp =
5538 Statement::make_temporary(this->left_->type(), this->right_, loc);
5539 this->right_ = Expression::make_temporary_reference(temp, loc);
5540 inserter->insert(temp);
5541 }
5542 }
5543
5544 Type* left_type = this->left_->type();
5545 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5546 || this->op_ == OPERATOR_RSHIFT);
5547 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5548 left_type->integer_type() != NULL)
5549 || this->op_ == OPERATOR_MOD);
5550
5551 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5552 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5553 // and accessed from the Gogo* passed to do_flatten.
5554 if (is_shift_op
5555 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5556 {
5557 if (!this->left_->is_variable())
5558 {
5559 temp = Statement::make_temporary(NULL, this->left_, loc);
5560 inserter->insert(temp);
5561 this->left_ = Expression::make_temporary_reference(temp, loc);
5562 }
5563 if (!this->right_->is_variable())
5564 {
5565 temp =
5566 Statement::make_temporary(NULL, this->right_, loc);
5567 this->right_ = Expression::make_temporary_reference(temp, loc);
5568 inserter->insert(temp);
5569 }
5570 }
5571 return this;
5572}
5573
5574
e9d3367e 5575// Return the address of EXPR, cast to unsafe.Pointer.
5576
5577Expression*
5578Binary_expression::operand_address(Statement_inserter* inserter,
5579 Expression* expr)
5580{
5581 Location loc = this->location();
5582
5583 if (!expr->is_addressable())
5584 {
5585 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5586 loc);
5587 inserter->insert(temp);
5588 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5589 }
5590 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5591 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5592 Type* void_type = Type::make_void_type();
5593 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5594 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5595}
5596
0c77715b 5597// Return the numeric constant value, if it has one.
e440a328 5598
5599bool
0c77715b 5600Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5601{
0c77715b 5602 Numeric_constant left_nc;
5603 if (!this->left_->numeric_constant_value(&left_nc))
5604 return false;
5605 Numeric_constant right_nc;
5606 if (!this->right_->numeric_constant_value(&right_nc))
5607 return false;
9767e2d3 5608 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5609 this->location(), nc);
e440a328 5610}
5611
5612// Note that the value is being discarded.
5613
4f2138d7 5614bool
e440a328 5615Binary_expression::do_discarding_value()
5616{
5617 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5618 return this->right_->discarding_value();
e440a328 5619 else
4f2138d7 5620 {
5621 this->unused_value_error();
5622 return false;
5623 }
e440a328 5624}
5625
5626// Get type.
5627
5628Type*
5629Binary_expression::do_type()
5630{
5f5fea79 5631 if (this->classification() == EXPRESSION_ERROR)
5632 return Type::make_error_type();
5633
e440a328 5634 switch (this->op_)
5635 {
e440a328 5636 case OPERATOR_EQEQ:
5637 case OPERATOR_NOTEQ:
5638 case OPERATOR_LT:
5639 case OPERATOR_LE:
5640 case OPERATOR_GT:
5641 case OPERATOR_GE:
e90c9dfc 5642 if (this->type_ == NULL)
5643 this->type_ = Type::make_boolean_type();
5644 return this->type_;
e440a328 5645
5646 case OPERATOR_PLUS:
5647 case OPERATOR_MINUS:
5648 case OPERATOR_OR:
5649 case OPERATOR_XOR:
5650 case OPERATOR_MULT:
5651 case OPERATOR_DIV:
5652 case OPERATOR_MOD:
5653 case OPERATOR_AND:
5654 case OPERATOR_BITCLEAR:
e90c9dfc 5655 case OPERATOR_OROR:
5656 case OPERATOR_ANDAND:
e440a328 5657 {
0c77715b 5658 Type* type;
5659 if (!Binary_expression::operation_type(this->op_,
5660 this->left_->type(),
5661 this->right_->type(),
5662 &type))
5663 return Type::make_error_type();
5664 return type;
e440a328 5665 }
5666
5667 case OPERATOR_LSHIFT:
5668 case OPERATOR_RSHIFT:
5669 return this->left_->type();
5670
5671 default:
c3e6f413 5672 go_unreachable();
e440a328 5673 }
5674}
5675
5676// Set type for a binary expression.
5677
5678void
5679Binary_expression::do_determine_type(const Type_context* context)
5680{
5681 Type* tleft = this->left_->type();
5682 Type* tright = this->right_->type();
5683
5684 // Both sides should have the same type, except for the shift
5685 // operations. For a comparison, we should ignore the incoming
5686 // type.
5687
5688 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5689 || this->op_ == OPERATOR_RSHIFT);
5690
5691 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5692 || this->op_ == OPERATOR_NOTEQ
5693 || this->op_ == OPERATOR_LT
5694 || this->op_ == OPERATOR_LE
5695 || this->op_ == OPERATOR_GT
5696 || this->op_ == OPERATOR_GE);
5697
5698 Type_context subcontext(*context);
5699
5700 if (is_comparison)
5701 {
5702 // In a comparison, the context does not determine the types of
5703 // the operands.
5704 subcontext.type = NULL;
5705 }
5706
02ffd97f 5707 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5708 {
5709 // For a logical operation, the context does not determine the
5710 // types of the operands. The operands must be some boolean
5711 // type but if the context has a boolean type they do not
5712 // inherit it. See http://golang.org/issue/3924.
5713 subcontext.type = NULL;
5714 }
5715
e440a328 5716 // Set the context for the left hand operand.
5717 if (is_shift_op)
5718 {
b40dc774 5719 // The right hand operand of a shift plays no role in
5720 // determining the type of the left hand operand.
e440a328 5721 }
5722 else if (!tleft->is_abstract())
5723 subcontext.type = tleft;
5724 else if (!tright->is_abstract())
5725 subcontext.type = tright;
5726 else if (subcontext.type == NULL)
5727 {
5728 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5729 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5730 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5731 {
5732 // Both sides have an abstract integer, abstract float, or
5733 // abstract complex type. Just let CONTEXT determine
5734 // whether they may remain abstract or not.
5735 }
5736 else if (tleft->complex_type() != NULL)
5737 subcontext.type = tleft;
5738 else if (tright->complex_type() != NULL)
5739 subcontext.type = tright;
5740 else if (tleft->float_type() != NULL)
5741 subcontext.type = tleft;
5742 else if (tright->float_type() != NULL)
5743 subcontext.type = tright;
5744 else
5745 subcontext.type = tleft;
f58a23ae 5746
5747 if (subcontext.type != NULL && !context->may_be_abstract)
5748 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5749 }
5750
5751 this->left_->determine_type(&subcontext);
5752
e440a328 5753 if (is_shift_op)
5754 {
b40dc774 5755 // We may have inherited an unusable type for the shift operand.
5756 // Give a useful error if that happened.
5757 if (tleft->is_abstract()
5758 && subcontext.type != NULL
8ab6effb 5759 && !subcontext.may_be_abstract
f6bc81e6 5760 && subcontext.type->interface_type() == NULL
8ab6effb 5761 && subcontext.type->integer_type() == NULL)
b40dc774 5762 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5763 "for left operand of shift"));
b40dc774 5764
5765 // The context for the right hand operand is the same as for the
5766 // left hand operand, except for a shift operator.
e440a328 5767 subcontext.type = Type::lookup_integer_type("uint");
5768 subcontext.may_be_abstract = false;
5769 }
5770
5771 this->right_->determine_type(&subcontext);
e90c9dfc 5772
5773 if (is_comparison)
5774 {
5775 if (this->type_ != NULL && !this->type_->is_abstract())
5776 ;
5777 else if (context->type != NULL && context->type->is_boolean_type())
5778 this->type_ = context->type;
5779 else if (!context->may_be_abstract)
5780 this->type_ = Type::lookup_bool_type();
5781 }
e440a328 5782}
5783
5784// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5785// OTYPE is the type of the other operand. Return whether the
5786// operation is OK. This should not be used for shift.
e440a328 5787
5788bool
be8b5eee 5789Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5790 Location location)
e440a328 5791{
5792 switch (op)
5793 {
5794 case OPERATOR_OROR:
5795 case OPERATOR_ANDAND:
5796 if (!type->is_boolean_type())
5797 {
5798 error_at(location, "expected boolean type");
5799 return false;
5800 }
5801 break;
5802
5803 case OPERATOR_EQEQ:
5804 case OPERATOR_NOTEQ:
e9d3367e 5805 {
5806 std::string reason;
5807 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5808 {
5809 error_at(location, "%s", reason.c_str());
5810 return false;
5811 }
5812 }
e440a328 5813 break;
5814
5815 case OPERATOR_LT:
5816 case OPERATOR_LE:
5817 case OPERATOR_GT:
5818 case OPERATOR_GE:
e9d3367e 5819 {
5820 std::string reason;
5821 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5822 {
5823 error_at(location, "%s", reason.c_str());
5824 return false;
5825 }
5826 }
e440a328 5827 break;
5828
5829 case OPERATOR_PLUS:
5830 case OPERATOR_PLUSEQ:
5831 if (type->integer_type() == NULL
5832 && type->float_type() == NULL
5833 && type->complex_type() == NULL
5834 && !type->is_string_type())
5835 {
5836 error_at(location,
5837 "expected integer, floating, complex, or string type");
5838 return false;
5839 }
5840 break;
5841
5842 case OPERATOR_MINUS:
5843 case OPERATOR_MINUSEQ:
5844 case OPERATOR_MULT:
5845 case OPERATOR_MULTEQ:
5846 case OPERATOR_DIV:
5847 case OPERATOR_DIVEQ:
5848 if (type->integer_type() == NULL
5849 && type->float_type() == NULL
5850 && type->complex_type() == NULL)
5851 {
5852 error_at(location, "expected integer, floating, or complex type");
5853 return false;
5854 }
5855 break;
5856
5857 case OPERATOR_MOD:
5858 case OPERATOR_MODEQ:
5859 case OPERATOR_OR:
5860 case OPERATOR_OREQ:
5861 case OPERATOR_AND:
5862 case OPERATOR_ANDEQ:
5863 case OPERATOR_XOR:
5864 case OPERATOR_XOREQ:
5865 case OPERATOR_BITCLEAR:
5866 case OPERATOR_BITCLEAREQ:
5867 if (type->integer_type() == NULL)
5868 {
5869 error_at(location, "expected integer type");
5870 return false;
5871 }
5872 break;
5873
5874 default:
c3e6f413 5875 go_unreachable();
e440a328 5876 }
5877
5878 return true;
5879}
5880
5881// Check types.
5882
5883void
5884Binary_expression::do_check_types(Gogo*)
5885{
5f5fea79 5886 if (this->classification() == EXPRESSION_ERROR)
5887 return;
5888
e440a328 5889 Type* left_type = this->left_->type();
5890 Type* right_type = this->right_->type();
5c13bd80 5891 if (left_type->is_error() || right_type->is_error())
9fe897ef 5892 {
5893 this->set_is_error();
5894 return;
5895 }
e440a328 5896
5897 if (this->op_ == OPERATOR_EQEQ
5898 || this->op_ == OPERATOR_NOTEQ
5899 || this->op_ == OPERATOR_LT
5900 || this->op_ == OPERATOR_LE
5901 || this->op_ == OPERATOR_GT
5902 || this->op_ == OPERATOR_GE)
5903 {
907c5ecd 5904 if (left_type->is_nil_type() && right_type->is_nil_type())
5905 {
5906 this->report_error(_("invalid comparison of nil with nil"));
5907 return;
5908 }
e440a328 5909 if (!Type::are_assignable(left_type, right_type, NULL)
5910 && !Type::are_assignable(right_type, left_type, NULL))
5911 {
5912 this->report_error(_("incompatible types in binary expression"));
5913 return;
5914 }
5915 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5916 right_type,
e440a328 5917 this->location())
5918 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5919 left_type,
e440a328 5920 this->location()))
5921 {
5922 this->set_is_error();
5923 return;
5924 }
5925 }
5926 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5927 {
5928 if (!Type::are_compatible_for_binop(left_type, right_type))
5929 {
5930 this->report_error(_("incompatible types in binary expression"));
5931 return;
5932 }
5933 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5934 right_type,
e440a328 5935 this->location()))
5936 {
5937 this->set_is_error();
5938 return;
5939 }
5c65b19d 5940 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5941 {
5942 // Division by a zero integer constant is an error.
5943 Numeric_constant rconst;
5944 unsigned long rval;
5945 if (left_type->integer_type() != NULL
5946 && this->right_->numeric_constant_value(&rconst)
5947 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5948 && rval == 0)
5949 {
5950 this->report_error(_("integer division by zero"));
5951 return;
5952 }
5953 }
e440a328 5954 }
5955 else
5956 {
5957 if (left_type->integer_type() == NULL)
5958 this->report_error(_("shift of non-integer operand"));
5959
5960 if (!right_type->is_abstract()
5961 && (right_type->integer_type() == NULL
5962 || !right_type->integer_type()->is_unsigned()))
5963 this->report_error(_("shift count not unsigned integer"));
5964 else
5965 {
0c77715b 5966 Numeric_constant nc;
5967 if (this->right_->numeric_constant_value(&nc))
e440a328 5968 {
0c77715b 5969 mpz_t val;
5970 if (!nc.to_int(&val))
5971 this->report_error(_("shift count not unsigned integer"));
5972 else
a4eba91b 5973 {
0c77715b 5974 if (mpz_sgn(val) < 0)
5975 {
5976 this->report_error(_("negative shift count"));
5977 mpz_set_ui(val, 0);
5978 Location rloc = this->right_->location();
5979 this->right_ = Expression::make_integer(&val, right_type,
5980 rloc);
5981 }
5982 mpz_clear(val);
a4eba91b 5983 }
e440a328 5984 }
e440a328 5985 }
5986 }
5987}
5988
5989// Get a tree for a binary expression.
5990
5991tree
5992Binary_expression::do_get_tree(Translate_context* context)
5993{
1b1f2abf 5994 Gogo* gogo = context->gogo();
a32698ee 5995 Location loc = this->location();
5996 Type* left_type = this->left_->type();
5997 Type* right_type = this->right_->type();
1b1f2abf 5998
e440a328 5999 bool use_left_type = true;
6000 bool is_shift_op = false;
29a2d1d8 6001 bool is_idiv_op = false;
e440a328 6002 switch (this->op_)
6003 {
6004 case OPERATOR_EQEQ:
6005 case OPERATOR_NOTEQ:
6006 case OPERATOR_LT:
6007 case OPERATOR_LE:
6008 case OPERATOR_GT:
6009 case OPERATOR_GE:
a32698ee 6010 {
6011 Bexpression* ret =
6012 Expression::comparison(context, this->type_, this->op_,
6013 this->left_, this->right_, loc);
6014 return expr_to_tree(ret);
6015 }
e440a328 6016
6017 case OPERATOR_OROR:
e440a328 6018 case OPERATOR_ANDAND:
e440a328 6019 use_left_type = false;
6020 break;
6021 case OPERATOR_PLUS:
e440a328 6022 case OPERATOR_MINUS:
e440a328 6023 case OPERATOR_OR:
e440a328 6024 case OPERATOR_XOR:
e440a328 6025 case OPERATOR_MULT:
e440a328 6026 break;
6027 case OPERATOR_DIV:
a32698ee 6028 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6029 break;
e440a328 6030 case OPERATOR_MOD:
29a2d1d8 6031 is_idiv_op = true;
e440a328 6032 break;
6033 case OPERATOR_LSHIFT:
e440a328 6034 case OPERATOR_RSHIFT:
e440a328 6035 is_shift_op = true;
6036 break;
e440a328 6037 case OPERATOR_BITCLEAR:
a32698ee 6038 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6039 case OPERATOR_AND:
e440a328 6040 break;
6041 default:
c3e6f413 6042 go_unreachable();
e440a328 6043 }
6044
a32698ee 6045 if (left_type->is_string_type())
e440a328 6046 {
c484d925 6047 go_assert(this->op_ == OPERATOR_PLUS);
a32698ee 6048 Expression* string_plus =
6049 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
6050 this->left_, this->right_);
6051 return string_plus->get_tree(context);
6052 }
6053
6054 // For complex division Go might want slightly different results than the
6055 // backend implementation provides, so we have our own runtime routine.
1850e20c 6056 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6057 {
a32698ee 6058 Runtime::Function complex_code;
1850e20c 6059 switch (this->left_->type()->complex_type()->bits())
6060 {
6061 case 64:
a32698ee 6062 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 6063 break;
6064 case 128:
a32698ee 6065 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 6066 break;
6067 default:
6068 go_unreachable();
6069 }
a32698ee 6070 Expression* complex_div =
6071 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6072 return complex_div->get_tree(context);
1850e20c 6073 }
6074
a32698ee 6075 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
6076 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
e440a328 6077
a32698ee 6078 Type* type = use_left_type ? left_type : right_type;
6079 Btype* btype = type->get_backend(gogo);
6080
6081 Bexpression* ret =
6082 gogo->backend()->binary_expression(this->op_, left, right, loc);
6083 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 6084
a32698ee 6085 // Initialize overflow constants.
6086 Bexpression* overflow;
6087 mpz_t zero;
6088 mpz_init_set_ui(zero, 0UL);
6089 mpz_t one;
6090 mpz_init_set_ui(one, 1UL);
6091 mpz_t neg_one;
6092 mpz_init_set_si(neg_one, -1);
e440a328 6093
a32698ee 6094 Btype* left_btype = left_type->get_backend(gogo);
6095 Btype* right_btype = right_type->get_backend(gogo);
e440a328 6096
6097 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 6098 // This is not true in C, so we need to insert a conditional.
e440a328 6099 if (is_shift_op)
6100 {
a32698ee 6101 go_assert(left_type->integer_type() != NULL);
e440a328 6102
a32698ee 6103 mpz_t bitsval;
6104 int bits = left_type->integer_type()->bits();
6105 mpz_init_set_ui(bitsval, bits);
6106 Bexpression* bits_expr =
6107 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6108 Bexpression* compare =
6109 gogo->backend()->binary_expression(OPERATOR_LT,
6110 right, bits_expr, loc);
e440a328 6111
a32698ee 6112 Bexpression* zero_expr =
6113 gogo->backend()->integer_constant_expression(left_btype, zero);
6114 overflow = zero_expr;
e440a328 6115 if (this->op_ == OPERATOR_RSHIFT
a32698ee 6116 && !left_type->integer_type()->is_unsigned())
e440a328 6117 {
a32698ee 6118 Bexpression* neg_expr =
6119 gogo->backend()->binary_expression(OPERATOR_LT, left,
6120 zero_expr, loc);
6121 Bexpression* neg_one_expr =
6122 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6123 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6124 neg_one_expr,
6125 zero_expr, loc);
29a2d1d8 6126 }
a32698ee 6127 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6128 overflow, loc);
6129 mpz_clear(bitsval);
29a2d1d8 6130 }
6131
6132 // Add checks for division by zero and division overflow as needed.
6133 if (is_idiv_op)
6134 {
6135 if (go_check_divide_zero)
6136 {
6137 // right == 0
a32698ee 6138 Bexpression* zero_expr =
6139 gogo->backend()->integer_constant_expression(right_btype, zero);
6140 Bexpression* check =
6141 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6142 right, zero_expr, loc);
29a2d1d8 6143
a32698ee 6144 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 6145 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
a32698ee 6146 Expression* crash = gogo->runtime_error(errcode, loc);
6147 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
29a2d1d8 6148
6149 // right == 0 ? (__go_runtime_error(...), 0) : ret
a32698ee 6150 ret = gogo->backend()->conditional_expression(btype, check,
6151 crash_expr, ret, loc);
b13c66cd 6152 }
6153
29a2d1d8 6154 if (go_check_divide_overflow)
6155 {
6156 // right == -1
6157 // FIXME: It would be nice to say that this test is expected
6158 // to return false.
a32698ee 6159
6160 Bexpression* neg_one_expr =
6161 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6162 Bexpression* check =
6163 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6164 right, neg_one_expr, loc);
6165
6166 Bexpression* zero_expr =
6167 gogo->backend()->integer_constant_expression(btype, zero);
6168 Bexpression* one_expr =
6169 gogo->backend()->integer_constant_expression(btype, one);
6170
6171 if (type->integer_type()->is_unsigned())
29a2d1d8 6172 {
6173 // An unsigned -1 is the largest possible number, so
6174 // dividing is always 1 or 0.
a32698ee 6175
6176 Bexpression* cmp =
6177 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6178 left, right, loc);
29a2d1d8 6179 if (this->op_ == OPERATOR_DIV)
a32698ee 6180 overflow =
6181 gogo->backend()->conditional_expression(btype, cmp,
6182 one_expr, zero_expr,
6183 loc);
29a2d1d8 6184 else
a32698ee 6185 overflow =
6186 gogo->backend()->conditional_expression(btype, cmp,
6187 zero_expr, left,
6188 loc);
29a2d1d8 6189 }
6190 else
6191 {
6192 // Computing left / -1 is the same as computing - left,
6193 // which does not overflow since Go sets -fwrapv.
6194 if (this->op_ == OPERATOR_DIV)
a32698ee 6195 {
6196 Expression* negate_expr =
6197 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6198 overflow = tree_to_expr(negate_expr->get_tree(context));
6199 }
29a2d1d8 6200 else
a32698ee 6201 overflow = zero_expr;
29a2d1d8 6202 }
a32698ee 6203 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 6204
6205 // right == -1 ? - left : ret
a32698ee 6206 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6207 ret, loc);
29a2d1d8 6208 }
e440a328 6209 }
6210
a32698ee 6211 mpz_clear(zero);
6212 mpz_clear(one);
6213 mpz_clear(neg_one);
6214 return expr_to_tree(ret);
e440a328 6215}
6216
6217// Export a binary expression.
6218
6219void
6220Binary_expression::do_export(Export* exp) const
6221{
6222 exp->write_c_string("(");
6223 this->left_->export_expression(exp);
6224 switch (this->op_)
6225 {
6226 case OPERATOR_OROR:
6227 exp->write_c_string(" || ");
6228 break;
6229 case OPERATOR_ANDAND:
6230 exp->write_c_string(" && ");
6231 break;
6232 case OPERATOR_EQEQ:
6233 exp->write_c_string(" == ");
6234 break;
6235 case OPERATOR_NOTEQ:
6236 exp->write_c_string(" != ");
6237 break;
6238 case OPERATOR_LT:
6239 exp->write_c_string(" < ");
6240 break;
6241 case OPERATOR_LE:
6242 exp->write_c_string(" <= ");
6243 break;
6244 case OPERATOR_GT:
6245 exp->write_c_string(" > ");
6246 break;
6247 case OPERATOR_GE:
6248 exp->write_c_string(" >= ");
6249 break;
6250 case OPERATOR_PLUS:
6251 exp->write_c_string(" + ");
6252 break;
6253 case OPERATOR_MINUS:
6254 exp->write_c_string(" - ");
6255 break;
6256 case OPERATOR_OR:
6257 exp->write_c_string(" | ");
6258 break;
6259 case OPERATOR_XOR:
6260 exp->write_c_string(" ^ ");
6261 break;
6262 case OPERATOR_MULT:
6263 exp->write_c_string(" * ");
6264 break;
6265 case OPERATOR_DIV:
6266 exp->write_c_string(" / ");
6267 break;
6268 case OPERATOR_MOD:
6269 exp->write_c_string(" % ");
6270 break;
6271 case OPERATOR_LSHIFT:
6272 exp->write_c_string(" << ");
6273 break;
6274 case OPERATOR_RSHIFT:
6275 exp->write_c_string(" >> ");
6276 break;
6277 case OPERATOR_AND:
6278 exp->write_c_string(" & ");
6279 break;
6280 case OPERATOR_BITCLEAR:
6281 exp->write_c_string(" &^ ");
6282 break;
6283 default:
c3e6f413 6284 go_unreachable();
e440a328 6285 }
6286 this->right_->export_expression(exp);
6287 exp->write_c_string(")");
6288}
6289
6290// Import a binary expression.
6291
6292Expression*
6293Binary_expression::do_import(Import* imp)
6294{
6295 imp->require_c_string("(");
6296
6297 Expression* left = Expression::import_expression(imp);
6298
6299 Operator op;
6300 if (imp->match_c_string(" || "))
6301 {
6302 op = OPERATOR_OROR;
6303 imp->advance(4);
6304 }
6305 else if (imp->match_c_string(" && "))
6306 {
6307 op = OPERATOR_ANDAND;
6308 imp->advance(4);
6309 }
6310 else if (imp->match_c_string(" == "))
6311 {
6312 op = OPERATOR_EQEQ;
6313 imp->advance(4);
6314 }
6315 else if (imp->match_c_string(" != "))
6316 {
6317 op = OPERATOR_NOTEQ;
6318 imp->advance(4);
6319 }
6320 else if (imp->match_c_string(" < "))
6321 {
6322 op = OPERATOR_LT;
6323 imp->advance(3);
6324 }
6325 else if (imp->match_c_string(" <= "))
6326 {
6327 op = OPERATOR_LE;
6328 imp->advance(4);
6329 }
6330 else if (imp->match_c_string(" > "))
6331 {
6332 op = OPERATOR_GT;
6333 imp->advance(3);
6334 }
6335 else if (imp->match_c_string(" >= "))
6336 {
6337 op = OPERATOR_GE;
6338 imp->advance(4);
6339 }
6340 else if (imp->match_c_string(" + "))
6341 {
6342 op = OPERATOR_PLUS;
6343 imp->advance(3);
6344 }
6345 else if (imp->match_c_string(" - "))
6346 {
6347 op = OPERATOR_MINUS;
6348 imp->advance(3);
6349 }
6350 else if (imp->match_c_string(" | "))
6351 {
6352 op = OPERATOR_OR;
6353 imp->advance(3);
6354 }
6355 else if (imp->match_c_string(" ^ "))
6356 {
6357 op = OPERATOR_XOR;
6358 imp->advance(3);
6359 }
6360 else if (imp->match_c_string(" * "))
6361 {
6362 op = OPERATOR_MULT;
6363 imp->advance(3);
6364 }
6365 else if (imp->match_c_string(" / "))
6366 {
6367 op = OPERATOR_DIV;
6368 imp->advance(3);
6369 }
6370 else if (imp->match_c_string(" % "))
6371 {
6372 op = OPERATOR_MOD;
6373 imp->advance(3);
6374 }
6375 else if (imp->match_c_string(" << "))
6376 {
6377 op = OPERATOR_LSHIFT;
6378 imp->advance(4);
6379 }
6380 else if (imp->match_c_string(" >> "))
6381 {
6382 op = OPERATOR_RSHIFT;
6383 imp->advance(4);
6384 }
6385 else if (imp->match_c_string(" & "))
6386 {
6387 op = OPERATOR_AND;
6388 imp->advance(3);
6389 }
6390 else if (imp->match_c_string(" &^ "))
6391 {
6392 op = OPERATOR_BITCLEAR;
6393 imp->advance(4);
6394 }
6395 else
6396 {
6397 error_at(imp->location(), "unrecognized binary operator");
6398 return Expression::make_error(imp->location());
6399 }
6400
6401 Expression* right = Expression::import_expression(imp);
6402
6403 imp->require_c_string(")");
6404
6405 return Expression::make_binary(op, left, right, imp->location());
6406}
6407
d751bb78 6408// Dump ast representation of a binary expression.
6409
6410void
6411Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6412{
6413 ast_dump_context->ostream() << "(";
6414 ast_dump_context->dump_expression(this->left_);
6415 ast_dump_context->ostream() << " ";
6416 ast_dump_context->dump_operator(this->op_);
6417 ast_dump_context->ostream() << " ";
6418 ast_dump_context->dump_expression(this->right_);
6419 ast_dump_context->ostream() << ") ";
6420}
6421
e440a328 6422// Make a binary expression.
6423
6424Expression*
6425Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6426 Location location)
e440a328 6427{
6428 return new Binary_expression(op, left, right, location);
6429}
6430
6431// Implement a comparison.
6432
a32698ee 6433Bexpression*
6434Expression::comparison(Translate_context* context, Type* result_type,
6435 Operator op, Expression* left, Expression* right,
6436 Location location)
e440a328 6437{
2387f644 6438 Type* left_type = left->type();
6439 Type* right_type = right->type();
ceeb12d7 6440
6441 mpz_t zval;
6442 mpz_init_set_ui(zval, 0UL);
6443 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6444 mpz_clear(zval);
1b1f2abf 6445
15c67ee2 6446 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6447 {
2387f644 6448 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6449 left, right);
6450 right = zexpr;
e440a328 6451 }
15c67ee2 6452 else if ((left_type->interface_type() != NULL
6453 && right_type->interface_type() == NULL
6454 && !right_type->is_nil_type())
6455 || (left_type->interface_type() == NULL
6456 && !left_type->is_nil_type()
6457 && right_type->interface_type() != NULL))
e440a328 6458 {
6459 // Comparing an interface value to a non-interface value.
6460 if (left_type->interface_type() == NULL)
6461 {
6462 std::swap(left_type, right_type);
2387f644 6463 std::swap(left, right);
e440a328 6464 }
6465
6466 // The right operand is not an interface. We need to take its
6467 // address if it is not a pointer.
ceeb12d7 6468 Expression* pointer_arg = NULL;
e440a328 6469 if (right_type->points_to() != NULL)
2387f644 6470 pointer_arg = right;
e440a328 6471 else
6472 {
2387f644 6473 go_assert(right->is_addressable());
6474 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6475 location);
e440a328 6476 }
e440a328 6477
2387f644 6478 Expression* descriptor =
6479 Expression::make_type_descriptor(right_type, location);
6480 left =
ceeb12d7 6481 Runtime::make_call((left_type->interface_type()->is_empty()
6482 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6483 : Runtime::INTERFACE_VALUE_COMPARE),
2387f644 6484 location, 3, left, descriptor,
ceeb12d7 6485 pointer_arg);
2387f644 6486 right = zexpr;
e440a328 6487 }
6488 else if (left_type->interface_type() != NULL
6489 && right_type->interface_type() != NULL)
6490 {
ceeb12d7 6491 Runtime::Function compare_function;
739bad04 6492 if (left_type->interface_type()->is_empty()
6493 && right_type->interface_type()->is_empty())
ceeb12d7 6494 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
739bad04 6495 else if (!left_type->interface_type()->is_empty()
6496 && !right_type->interface_type()->is_empty())
ceeb12d7 6497 compare_function = Runtime::INTERFACE_COMPARE;
739bad04 6498 else
6499 {
6500 if (left_type->interface_type()->is_empty())
6501 {
c484d925 6502 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
739bad04 6503 std::swap(left_type, right_type);
2387f644 6504 std::swap(left, right);
739bad04 6505 }
c484d925 6506 go_assert(!left_type->interface_type()->is_empty());
6507 go_assert(right_type->interface_type()->is_empty());
ceeb12d7 6508 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
739bad04 6509 }
6510
2387f644 6511 left = Runtime::make_call(compare_function, location, 2, left, right);
6512 right = zexpr;
e440a328 6513 }
6514
6515 if (left_type->is_nil_type()
6516 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6517 {
6518 std::swap(left_type, right_type);
2387f644 6519 std::swap(left, right);
e440a328 6520 }
6521
6522 if (right_type->is_nil_type())
6523 {
2387f644 6524 right = Expression::make_nil(location);
e440a328 6525 if (left_type->array_type() != NULL
6526 && left_type->array_type()->length() == NULL)
6527 {
6528 Array_type* at = left_type->array_type();
2387f644 6529 left = at->get_value_pointer(context->gogo(), left);
e440a328 6530 }
6531 else if (left_type->interface_type() != NULL)
6532 {
6533 // An interface is nil if the first field is nil.
2387f644 6534 left = Expression::make_field_reference(left, 0, location);
e440a328 6535 }
6536 }
6537
a32698ee 6538 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6539 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
e90c9dfc 6540
a32698ee 6541 Gogo* gogo = context->gogo();
6542 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6543 right_bexpr, location);
6544 if (result_type != NULL)
6545 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6546 ret, location);
e440a328 6547 return ret;
6548}
6549
6550// Class Bound_method_expression.
6551
6552// Traversal.
6553
6554int
6555Bound_method_expression::do_traverse(Traverse* traverse)
6556{
e0659c9e 6557 return Expression::traverse(&this->expr_, traverse);
e440a328 6558}
6559
0afbb937 6560// Lower the expression. If this is a method value rather than being
6561// called, and the method is accessed via a pointer, we may need to
6562// add nil checks. Introduce a temporary variable so that those nil
6563// checks do not cause multiple evaluation.
6564
6565Expression*
6566Bound_method_expression::do_lower(Gogo*, Named_object*,
6567 Statement_inserter* inserter, int)
6568{
6569 // For simplicity we use a temporary for every call to an embedded
6570 // method, even though some of them might be pure value methods and
6571 // not require a temporary.
6572 if (this->expr_->var_expression() == NULL
6573 && this->expr_->temporary_reference_expression() == NULL
6574 && this->expr_->set_and_use_temporary_expression() == NULL
6575 && (this->method_->field_indexes() != NULL
6576 || (this->method_->is_value_method()
6577 && this->expr_->type()->points_to() != NULL)))
6578 {
6579 Temporary_statement* temp =
6580 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6581 inserter->insert(temp);
6582 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6583 this->location());
6584 }
6585 return this;
6586}
6587
e440a328 6588// Return the type of a bound method expression. The type of this
0afbb937 6589// object is simply the type of the method with no receiver.
e440a328 6590
6591Type*
6592Bound_method_expression::do_type()
6593{
0afbb937 6594 Named_object* fn = this->method_->named_object();
6595 Function_type* fntype;
6596 if (fn->is_function())
6597 fntype = fn->func_value()->type();
6598 else if (fn->is_function_declaration())
6599 fntype = fn->func_declaration_value()->type();
e0659c9e 6600 else
6601 return Type::make_error_type();
0afbb937 6602 return fntype->copy_without_receiver();
e440a328 6603}
6604
6605// Determine the types of a method expression.
6606
6607void
6608Bound_method_expression::do_determine_type(const Type_context*)
6609{
0afbb937 6610 Named_object* fn = this->method_->named_object();
6611 Function_type* fntype;
6612 if (fn->is_function())
6613 fntype = fn->func_value()->type();
6614 else if (fn->is_function_declaration())
6615 fntype = fn->func_declaration_value()->type();
6616 else
6617 fntype = NULL;
e440a328 6618 if (fntype == NULL || !fntype->is_method())
6619 this->expr_->determine_type_no_context();
6620 else
6621 {
6622 Type_context subcontext(fntype->receiver()->type(), false);
6623 this->expr_->determine_type(&subcontext);
6624 }
6625}
6626
6627// Check the types of a method expression.
6628
6629void
6630Bound_method_expression::do_check_types(Gogo*)
6631{
0afbb937 6632 Named_object* fn = this->method_->named_object();
6633 if (!fn->is_function() && !fn->is_function_declaration())
6634 {
6635 this->report_error(_("object is not a method"));
6636 return;
6637 }
6638
6639 Function_type* fntype;
6640 if (fn->is_function())
6641 fntype = fn->func_value()->type();
6642 else if (fn->is_function_declaration())
6643 fntype = fn->func_declaration_value()->type();
e440a328 6644 else
0afbb937 6645 go_unreachable();
6646 Type* rtype = fntype->receiver()->type()->deref();
6647 Type* etype = (this->expr_type_ != NULL
6648 ? this->expr_type_
6649 : this->expr_->type());
6650 etype = etype->deref();
6651 if (!Type::are_identical(rtype, etype, true, NULL))
6652 this->report_error(_("method type does not match object type"));
6653}
6654
6655// If a bound method expression is not simply called, then it is
6656// represented as a closure. The closure will hold a single variable,
6657// the receiver to pass to the method. The function will be a simple
6658// thunk that pulls that value from the closure and calls the method
6659// with the remaining arguments.
6660//
6661// Because method values are not common, we don't build all thunks for
6662// every methods, but instead only build them as we need them. In
6663// particular, we even build them on demand for methods defined in
6664// other packages.
6665
6666Bound_method_expression::Method_value_thunks
6667 Bound_method_expression::method_value_thunks;
6668
6669// Find or create the thunk for METHOD.
6670
6671Named_object*
6672Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6673 Named_object* fn)
6674{
6675 std::pair<Named_object*, Named_object*> val(fn, NULL);
6676 std::pair<Method_value_thunks::iterator, bool> ins =
6677 Bound_method_expression::method_value_thunks.insert(val);
6678 if (!ins.second)
6679 {
6680 // We have seen this method before.
6681 go_assert(ins.first->second != NULL);
6682 return ins.first->second;
6683 }
6684
6685 Location loc = fn->location();
6686
6687 Function_type* orig_fntype;
6688 if (fn->is_function())
6689 orig_fntype = fn->func_value()->type();
6690 else if (fn->is_function_declaration())
6691 orig_fntype = fn->func_declaration_value()->type();
6692 else
6693 orig_fntype = NULL;
6694
6695 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6696 {
0afbb937 6697 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6698 return ins.first->second;
e440a328 6699 }
0afbb937 6700
6701 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6702 // The type here is wrong--it should be the C function type. But it
6703 // doesn't really matter.
0afbb937 6704 Type* vt = Type::make_pointer_type(Type::make_void_type());
6705 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6706 sfl->push_back(Struct_field(Typed_identifier("val.1",
6707 orig_fntype->receiver()->type(),
6708 loc)));
6709 Type* closure_type = Type::make_struct_type(sfl, loc);
6710 closure_type = Type::make_pointer_type(closure_type);
6711
f8bdf81a 6712 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6713
6714 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6715 false, loc);
6716
f8bdf81a 6717 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6718 cvar->set_is_used();
6719 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6720 new_no->func_value()->set_closure_var(cp);
0afbb937 6721
f8bdf81a 6722 gogo->start_block(loc);
0afbb937 6723
6724 // Field 0 of the closure is the function code pointer, field 1 is
6725 // the value on which to invoke the method.
6726 Expression* arg = Expression::make_var_reference(cp, loc);
6727 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6728 arg = Expression::make_field_reference(arg, 1, loc);
6729
6730 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6731
6732 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6733 Expression_list* args;
6734 if (orig_params == NULL || orig_params->empty())
6735 args = NULL;
6736 else
6737 {
6738 const Typed_identifier_list* new_params = new_fntype->parameters();
6739 args = new Expression_list();
6740 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6741 p != new_params->end();
0afbb937 6742 ++p)
6743 {
6744 Named_object* p_no = gogo->lookup(p->name(), NULL);
6745 go_assert(p_no != NULL
6746 && p_no->is_variable()
6747 && p_no->var_value()->is_parameter());
6748 args->push_back(Expression::make_var_reference(p_no, loc));
6749 }
6750 }
6751
6752 Call_expression* call = Expression::make_call(bme, args,
6753 orig_fntype->is_varargs(),
6754 loc);
6755 call->set_varargs_are_lowered();
6756
6757 Statement* s = Statement::make_return_from_call(call, loc);
6758 gogo->add_statement(s);
6759 Block* b = gogo->finish_block(loc);
6760 gogo->add_block(b, loc);
6761 gogo->lower_block(new_no, b);
a32698ee 6762 gogo->flatten_block(new_no, b);
0afbb937 6763 gogo->finish_function(loc);
6764
6765 ins.first->second = new_no;
6766 return new_no;
6767}
6768
6769// Return an expression to check *REF for nil while dereferencing
6770// according to FIELD_INDEXES. Update *REF to build up the field
6771// reference. This is a static function so that we don't have to
6772// worry about declaring Field_indexes in expressions.h.
6773
6774static Expression*
6775bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6776 Expression** ref)
6777{
6778 if (field_indexes == NULL)
6779 return Expression::make_boolean(false, loc);
6780 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6781 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6782 go_assert(stype != NULL
6783 && field_indexes->field_index < stype->field_count());
6784 if ((*ref)->type()->struct_type() == NULL)
6785 {
6786 go_assert((*ref)->type()->points_to() != NULL);
6787 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6788 Expression::make_nil(loc),
6789 loc);
6790 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6791 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6792 go_assert((*ref)->type()->struct_type() == stype);
6793 }
6794 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6795 loc);
6796 return cond;
e440a328 6797}
6798
0afbb937 6799// Get the tree for a method value.
e440a328 6800
6801tree
0afbb937 6802Bound_method_expression::do_get_tree(Translate_context* context)
e440a328 6803{
0afbb937 6804 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6805 this->method_,
6806 this->function_);
6807 if (thunk->is_erroneous())
6808 {
6809 go_assert(saw_errors());
6810 return error_mark_node;
6811 }
6812
6813 // FIXME: We should lower this earlier, but we can't lower it in the
6814 // lowering pass because at that point we don't know whether we need
6815 // to create the thunk or not. If the expression is called, we
6816 // don't need the thunk.
6817
6818 Location loc = this->location();
6819
6820 // If the method expects a value, and we have a pointer, we need to
6821 // dereference the pointer.
6822
6823 Named_object* fn = this->method_->named_object();
6824 Function_type* fntype;
6825 if (fn->is_function())
6826 fntype = fn->func_value()->type();
6827 else if (fn->is_function_declaration())
6828 fntype = fn->func_declaration_value()->type();
6829 else
6830 go_unreachable();
6831
6832 Expression* val = this->expr_;
6833 if (fntype->receiver()->type()->points_to() == NULL
6834 && val->type()->points_to() != NULL)
6835 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6836
6837 // Note that we are ignoring this->expr_type_ here. The thunk will
6838 // expect a closure whose second field has type this->expr_type_ (if
6839 // that is not NULL). We are going to pass it a closure whose
6840 // second field has type this->expr_->type(). Since
6841 // this->expr_type_ is only not-NULL for pointer types, we can get
6842 // away with this.
6843
6844 Struct_field_list* fields = new Struct_field_list();
6845 fields->push_back(Struct_field(Typed_identifier("fn.0",
6846 thunk->func_value()->type(),
6847 loc)));
6848 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6849 Struct_type* st = Type::make_struct_type(fields, loc);
6850
6851 Expression_list* vals = new Expression_list();
6852 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6853 vals->push_back(val);
6854
6855 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 6856 ret = Expression::make_heap_expression(ret, loc);
0afbb937 6857
6858 tree ret_tree = ret->get_tree(context);
6859
6860 Expression* nil_check = NULL;
6861
6862 // See whether the expression or any embedded pointers are nil.
6863
6864 Expression* expr = this->expr_;
6865 if (this->method_->field_indexes() != NULL)
6866 {
6867 // Note that we are evaluating this->expr_ twice, but that is OK
6868 // because in the lowering pass we forced it into a temporary
6869 // variable.
6870 Expression* ref = expr;
6871 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6872 expr = ref;
6873 }
6874
6875 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6876 {
6877 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6878 Expression::make_nil(loc),
6879 loc);
6880 if (nil_check == NULL)
6881 nil_check = n;
6882 else
6883 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6884 }
6885
6886 if (nil_check != NULL)
6887 {
6888 tree nil_check_tree = nil_check->get_tree(context);
aff1f085 6889 Expression* crash_expr =
0afbb937 6890 context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
aff1f085 6891 tree crash = crash_expr->get_tree(context);
0afbb937 6892 if (ret_tree == error_mark_node
6893 || nil_check_tree == error_mark_node
6894 || crash == error_mark_node)
6895 return error_mark_node;
6896
6897 ret_tree = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
6898 TREE_TYPE(ret_tree),
6899 build3_loc(loc.gcc_location(), COND_EXPR,
6900 void_type_node, nil_check_tree,
6901 crash, NULL_TREE),
6902 ret_tree);
6903 }
6904
6905 return ret_tree;
e440a328 6906}
6907
d751bb78 6908// Dump ast representation of a bound method expression.
6909
6910void
6911Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6912 const
6913{
6914 if (this->expr_type_ != NULL)
6915 ast_dump_context->ostream() << "(";
6916 ast_dump_context->dump_expression(this->expr_);
6917 if (this->expr_type_ != NULL)
6918 {
6919 ast_dump_context->ostream() << ":";
6920 ast_dump_context->dump_type(this->expr_type_);
6921 ast_dump_context->ostream() << ")";
6922 }
6923
0afbb937 6924 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6925}
6926
e440a328 6927// Make a method expression.
6928
6929Bound_method_expression*
0afbb937 6930Expression::make_bound_method(Expression* expr, const Method* method,
6931 Named_object* function, Location location)
e440a328 6932{
0afbb937 6933 return new Bound_method_expression(expr, method, function, location);
e440a328 6934}
6935
6936// Class Builtin_call_expression. This is used for a call to a
6937// builtin function.
6938
6939class Builtin_call_expression : public Call_expression
6940{
6941 public:
6942 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6943 bool is_varargs, Location location);
e440a328 6944
6945 protected:
6946 // This overrides Call_expression::do_lower.
6947 Expression*
ceeb4318 6948 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6949
35a54f17 6950 Expression*
6951 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6952
e440a328 6953 bool
6954 do_is_constant() const;
6955
6956 bool
0c77715b 6957 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6958
4f2138d7 6959 bool
a7549a6a 6960 do_discarding_value();
6961
e440a328 6962 Type*
6963 do_type();
6964
6965 void
6966 do_determine_type(const Type_context*);
6967
6968 void
6969 do_check_types(Gogo*);
6970
6971 Expression*
6972 do_copy()
6973 {
6974 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6975 this->args()->copy(),
6976 this->is_varargs(),
6977 this->location());
6978 }
6979
6980 tree
6981 do_get_tree(Translate_context*);
6982
6983 void
6984 do_export(Export*) const;
6985
6986 virtual bool
6987 do_is_recover_call() const;
6988
6989 virtual void
6990 do_set_recover_arg(Expression*);
6991
6992 private:
6993 // The builtin functions.
6994 enum Builtin_function_code
6995 {
6996 BUILTIN_INVALID,
6997
6998 // Predeclared builtin functions.
6999 BUILTIN_APPEND,
7000 BUILTIN_CAP,
7001 BUILTIN_CLOSE,
48080209 7002 BUILTIN_COMPLEX,
e440a328 7003 BUILTIN_COPY,
1cce762f 7004 BUILTIN_DELETE,
e440a328 7005 BUILTIN_IMAG,
7006 BUILTIN_LEN,
7007 BUILTIN_MAKE,
7008 BUILTIN_NEW,
7009 BUILTIN_PANIC,
7010 BUILTIN_PRINT,
7011 BUILTIN_PRINTLN,
7012 BUILTIN_REAL,
7013 BUILTIN_RECOVER,
7014
7015 // Builtin functions from the unsafe package.
7016 BUILTIN_ALIGNOF,
7017 BUILTIN_OFFSETOF,
7018 BUILTIN_SIZEOF
7019 };
7020
7021 Expression*
7022 one_arg() const;
7023
7024 bool
7025 check_one_arg();
7026
7027 static Type*
7028 real_imag_type(Type*);
7029
7030 static Type*
48080209 7031 complex_type(Type*);
e440a328 7032
a9182619 7033 Expression*
7034 lower_make();
7035
7036 bool
1ad00fd4 7037 check_int_value(Expression*, bool is_length);
a9182619 7038
e440a328 7039 // A pointer back to the general IR structure. This avoids a global
7040 // variable, or passing it around everywhere.
7041 Gogo* gogo_;
7042 // The builtin function being called.
7043 Builtin_function_code code_;
0f914071 7044 // Used to stop endless loops when the length of an array uses len
7045 // or cap of the array itself.
7046 mutable bool seen_;
e440a328 7047};
7048
7049Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7050 Expression* fn,
7051 Expression_list* args,
7052 bool is_varargs,
b13c66cd 7053 Location location)
e440a328 7054 : Call_expression(fn, args, is_varargs, location),
0f914071 7055 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
e440a328 7056{
7057 Func_expression* fnexp = this->fn()->func_expression();
c484d925 7058 go_assert(fnexp != NULL);
e440a328 7059 const std::string& name(fnexp->named_object()->name());
7060 if (name == "append")
7061 this->code_ = BUILTIN_APPEND;
7062 else if (name == "cap")
7063 this->code_ = BUILTIN_CAP;
7064 else if (name == "close")
7065 this->code_ = BUILTIN_CLOSE;
48080209 7066 else if (name == "complex")
7067 this->code_ = BUILTIN_COMPLEX;
e440a328 7068 else if (name == "copy")
7069 this->code_ = BUILTIN_COPY;
1cce762f 7070 else if (name == "delete")
7071 this->code_ = BUILTIN_DELETE;
e440a328 7072 else if (name == "imag")
7073 this->code_ = BUILTIN_IMAG;
7074 else if (name == "len")
7075 this->code_ = BUILTIN_LEN;
7076 else if (name == "make")
7077 this->code_ = BUILTIN_MAKE;
7078 else if (name == "new")
7079 this->code_ = BUILTIN_NEW;
7080 else if (name == "panic")
7081 this->code_ = BUILTIN_PANIC;
7082 else if (name == "print")
7083 this->code_ = BUILTIN_PRINT;
7084 else if (name == "println")
7085 this->code_ = BUILTIN_PRINTLN;
7086 else if (name == "real")
7087 this->code_ = BUILTIN_REAL;
7088 else if (name == "recover")
7089 this->code_ = BUILTIN_RECOVER;
7090 else if (name == "Alignof")
7091 this->code_ = BUILTIN_ALIGNOF;
7092 else if (name == "Offsetof")
7093 this->code_ = BUILTIN_OFFSETOF;
7094 else if (name == "Sizeof")
7095 this->code_ = BUILTIN_SIZEOF;
7096 else
c3e6f413 7097 go_unreachable();
e440a328 7098}
7099
7100// Return whether this is a call to recover. This is a virtual
7101// function called from the parent class.
7102
7103bool
7104Builtin_call_expression::do_is_recover_call() const
7105{
7106 if (this->classification() == EXPRESSION_ERROR)
7107 return false;
7108 return this->code_ == BUILTIN_RECOVER;
7109}
7110
7111// Set the argument for a call to recover.
7112
7113void
7114Builtin_call_expression::do_set_recover_arg(Expression* arg)
7115{
7116 const Expression_list* args = this->args();
c484d925 7117 go_assert(args == NULL || args->empty());
e440a328 7118 Expression_list* new_args = new Expression_list();
7119 new_args->push_back(arg);
7120 this->set_args(new_args);
7121}
7122
e440a328 7123// Lower a builtin call expression. This turns new and make into
7124// specific expressions. We also convert to a constant if we can.
7125
7126Expression*
ceeb4318 7127Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7128 Statement_inserter* inserter, int)
e440a328 7129{
a9182619 7130 if (this->classification() == EXPRESSION_ERROR)
7131 return this;
7132
b13c66cd 7133 Location loc = this->location();
1cce762f 7134
a8725655 7135 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7136 {
7137 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7138 return Expression::make_error(loc);
a8725655 7139 }
7140
393ba00b 7141 if (this->code_ == BUILTIN_OFFSETOF)
7142 {
7143 Expression* arg = this->one_arg();
12e69faa 7144
7145 if (arg->bound_method_expression() != NULL
7146 || arg->interface_field_reference_expression() != NULL)
7147 {
7148 this->report_error(_("invalid use of method value as argument "
7149 "of Offsetof"));
7150 return this;
7151 }
7152
393ba00b 7153 Field_reference_expression* farg = arg->field_reference_expression();
7154 while (farg != NULL)
7155 {
7156 if (!farg->implicit())
7157 break;
7158 // When the selector refers to an embedded field,
7159 // it must not be reached through pointer indirections.
7160 if (farg->expr()->deref() != farg->expr())
7161 {
12e69faa 7162 this->report_error(_("argument of Offsetof implies "
7163 "indirection of an embedded field"));
393ba00b 7164 return this;
7165 }
7166 // Go up until we reach the original base.
7167 farg = farg->expr()->field_reference_expression();
7168 }
7169 }
7170
1cce762f 7171 if (this->is_constant())
e440a328 7172 {
0c77715b 7173 Numeric_constant nc;
7174 if (this->numeric_constant_value(&nc))
7175 return nc.expression(loc);
e440a328 7176 }
1cce762f 7177
7178 switch (this->code_)
e440a328 7179 {
1cce762f 7180 default:
7181 break;
7182
7183 case BUILTIN_NEW:
7184 {
7185 const Expression_list* args = this->args();
7186 if (args == NULL || args->size() < 1)
7187 this->report_error(_("not enough arguments"));
7188 else if (args->size() > 1)
7189 this->report_error(_("too many arguments"));
7190 else
7191 {
7192 Expression* arg = args->front();
7193 if (!arg->is_type_expression())
7194 {
7195 error_at(arg->location(), "expected type");
7196 this->set_is_error();
7197 }
7198 else
7199 return Expression::make_allocation(arg->type(), loc);
7200 }
7201 }
7202 break;
7203
7204 case BUILTIN_MAKE:
7205 return this->lower_make();
7206
7207 case BUILTIN_RECOVER:
e440a328 7208 if (function != NULL)
7209 function->func_value()->set_calls_recover();
7210 else
7211 {
7212 // Calling recover outside of a function always returns the
7213 // nil empty interface.
823c7e3d 7214 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7215 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7216 }
1cce762f 7217 break;
7218
7219 case BUILTIN_APPEND:
7220 {
7221 // Lower the varargs.
7222 const Expression_list* args = this->args();
7223 if (args == NULL || args->empty())
e440a328 7224 return this;
1cce762f 7225 Type* slice_type = args->front()->type();
7226 if (!slice_type->is_slice_type())
7227 {
3ff4863b 7228 if (slice_type->is_nil_type())
7229 error_at(args->front()->location(), "use of untyped nil");
7230 else
7231 error_at(args->front()->location(),
7232 "argument 1 must be a slice");
1cce762f 7233 this->set_is_error();
7234 return this;
7235 }
19fd40c3 7236 Type* element_type = slice_type->array_type()->element_type();
7237 this->lower_varargs(gogo, function, inserter,
7238 Type::make_array_type(element_type, NULL),
7239 2);
1cce762f 7240 }
7241 break;
7242
7243 case BUILTIN_DELETE:
7244 {
7245 // Lower to a runtime function call.
7246 const Expression_list* args = this->args();
7247 if (args == NULL || args->size() < 2)
7248 this->report_error(_("not enough arguments"));
7249 else if (args->size() > 2)
7250 this->report_error(_("too many arguments"));
7251 else if (args->front()->type()->map_type() == NULL)
7252 this->report_error(_("argument 1 must be a map"));
7253 else
7254 {
7255 // Since this function returns no value it must appear in
7256 // a statement by itself, so we don't have to worry about
7257 // order of evaluation of values around it. Evaluate the
7258 // map first to get order of evaluation right.
7259 Map_type* mt = args->front()->type()->map_type();
7260 Temporary_statement* map_temp =
7261 Statement::make_temporary(mt, args->front(), loc);
7262 inserter->insert(map_temp);
7263
7264 Temporary_statement* key_temp =
7265 Statement::make_temporary(mt->key_type(), args->back(), loc);
7266 inserter->insert(key_temp);
7267
7268 Expression* e1 = Expression::make_temporary_reference(map_temp,
7269 loc);
7270 Expression* e2 = Expression::make_temporary_reference(key_temp,
7271 loc);
7272 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7273 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7274 2, e1, e2);
7275 }
7276 }
7277 break;
e440a328 7278 }
7279
7280 return this;
7281}
7282
35a54f17 7283// Flatten a builtin call expression. This turns the arguments of copy and
7284// append into temporary expressions.
7285
7286Expression*
7287Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7288 Statement_inserter* inserter)
7289{
7290 if (this->code_ == BUILTIN_APPEND
7291 || this->code_ == BUILTIN_COPY)
7292 {
7293 Location loc = this->location();
7294 Type* at = this->args()->front()->type();
7295 for (Expression_list::iterator pa = this->args()->begin();
7296 pa != this->args()->end();
7297 ++pa)
7298 {
7299 if ((*pa)->is_nil_expression())
7300 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7301 if (!(*pa)->is_variable())
7302 {
7303 Temporary_statement* temp =
7304 Statement::make_temporary(NULL, *pa, loc);
7305 inserter->insert(temp);
7306 *pa = Expression::make_temporary_reference(temp, loc);
7307 }
7308 }
7309 }
7310 return this;
7311}
7312
a9182619 7313// Lower a make expression.
7314
7315Expression*
7316Builtin_call_expression::lower_make()
7317{
b13c66cd 7318 Location loc = this->location();
a9182619 7319
7320 const Expression_list* args = this->args();
7321 if (args == NULL || args->size() < 1)
7322 {
7323 this->report_error(_("not enough arguments"));
7324 return Expression::make_error(this->location());
7325 }
7326
7327 Expression_list::const_iterator parg = args->begin();
7328
7329 Expression* first_arg = *parg;
7330 if (!first_arg->is_type_expression())
7331 {
7332 error_at(first_arg->location(), "expected type");
7333 this->set_is_error();
7334 return Expression::make_error(this->location());
7335 }
7336 Type* type = first_arg->type();
7337
7338 bool is_slice = false;
7339 bool is_map = false;
7340 bool is_chan = false;
411eb89e 7341 if (type->is_slice_type())
a9182619 7342 is_slice = true;
7343 else if (type->map_type() != NULL)
7344 is_map = true;
7345 else if (type->channel_type() != NULL)
7346 is_chan = true;
7347 else
7348 {
7349 this->report_error(_("invalid type for make function"));
7350 return Expression::make_error(this->location());
7351 }
7352
ac84c822 7353 bool have_big_args = false;
7354 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7355 int uintptr_bits = uintptr_type->integer_type()->bits();
7356
f6bc81e6 7357 Type_context int_context(Type::lookup_integer_type("int"), false);
7358
a9182619 7359 ++parg;
7360 Expression* len_arg;
7361 if (parg == args->end())
7362 {
7363 if (is_slice)
7364 {
7365 this->report_error(_("length required when allocating a slice"));
7366 return Expression::make_error(this->location());
7367 }
7368
7369 mpz_t zval;
7370 mpz_init_set_ui(zval, 0);
7371 len_arg = Expression::make_integer(&zval, NULL, loc);
7372 mpz_clear(zval);
7373 }
7374 else
7375 {
7376 len_arg = *parg;
f6bc81e6 7377 len_arg->determine_type(&int_context);
1ad00fd4 7378 if (!this->check_int_value(len_arg, true))
7379 return Expression::make_error(this->location());
ac84c822 7380 if (len_arg->type()->integer_type() != NULL
7381 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7382 have_big_args = true;
a9182619 7383 ++parg;
7384 }
7385
7386 Expression* cap_arg = NULL;
7387 if (is_slice && parg != args->end())
7388 {
7389 cap_arg = *parg;
f6bc81e6 7390 cap_arg->determine_type(&int_context);
1ad00fd4 7391 if (!this->check_int_value(cap_arg, false))
7392 return Expression::make_error(this->location());
7393
7394 Numeric_constant nclen;
7395 Numeric_constant nccap;
7396 unsigned long vlen;
7397 unsigned long vcap;
7398 if (len_arg->numeric_constant_value(&nclen)
7399 && cap_arg->numeric_constant_value(&nccap)
7400 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7401 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7402 && vlen > vcap)
a9182619 7403 {
1ad00fd4 7404 this->report_error(_("len larger than cap"));
a9182619 7405 return Expression::make_error(this->location());
7406 }
1ad00fd4 7407
ac84c822 7408 if (cap_arg->type()->integer_type() != NULL
7409 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7410 have_big_args = true;
a9182619 7411 ++parg;
7412 }
7413
7414 if (parg != args->end())
7415 {
7416 this->report_error(_("too many arguments to make"));
7417 return Expression::make_error(this->location());
7418 }
7419
b13c66cd 7420 Location type_loc = first_arg->location();
a9182619 7421 Expression* type_arg;
7422 if (is_slice || is_chan)
7423 type_arg = Expression::make_type_descriptor(type, type_loc);
7424 else if (is_map)
7425 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7426 else
7427 go_unreachable();
7428
7429 Expression* call;
7430 if (is_slice)
7431 {
7432 if (cap_arg == NULL)
ac84c822 7433 call = Runtime::make_call((have_big_args
7434 ? Runtime::MAKESLICE1BIG
7435 : Runtime::MAKESLICE1),
7436 loc, 2, type_arg, len_arg);
a9182619 7437 else
ac84c822 7438 call = Runtime::make_call((have_big_args
7439 ? Runtime::MAKESLICE2BIG
7440 : Runtime::MAKESLICE2),
7441 loc, 3, type_arg, len_arg, cap_arg);
a9182619 7442 }
7443 else if (is_map)
ac84c822 7444 call = Runtime::make_call((have_big_args
7445 ? Runtime::MAKEMAPBIG
7446 : Runtime::MAKEMAP),
7447 loc, 2, type_arg, len_arg);
a9182619 7448 else if (is_chan)
ac84c822 7449 call = Runtime::make_call((have_big_args
7450 ? Runtime::MAKECHANBIG
7451 : Runtime::MAKECHAN),
7452 loc, 2, type_arg, len_arg);
a9182619 7453 else
7454 go_unreachable();
7455
7456 return Expression::make_unsafe_cast(type, call, loc);
7457}
7458
7459// Return whether an expression has an integer value. Report an error
7460// if not. This is used when handling calls to the predeclared make
7461// function.
7462
7463bool
1ad00fd4 7464Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7465{
0c77715b 7466 Numeric_constant nc;
1ad00fd4 7467 if (e->numeric_constant_value(&nc))
a9182619 7468 {
1ad00fd4 7469 unsigned long v;
7470 switch (nc.to_unsigned_long(&v))
7471 {
7472 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7473 break;
1ad00fd4 7474 case Numeric_constant::NC_UL_NOTINT:
7475 error_at(e->location(), "non-integer %s argument to make",
7476 is_length ? "len" : "cap");
7477 return false;
7478 case Numeric_constant::NC_UL_NEGATIVE:
7479 error_at(e->location(), "negative %s argument to make",
7480 is_length ? "len" : "cap");
7481 return false;
7482 case Numeric_constant::NC_UL_BIG:
7483 // We don't want to give a compile-time error for a 64-bit
7484 // value on a 32-bit target.
1b10c5e7 7485 break;
1ad00fd4 7486 }
1b10c5e7 7487
7488 mpz_t val;
7489 if (!nc.to_int(&val))
7490 go_unreachable();
7491 int bits = mpz_sizeinbase(val, 2);
7492 mpz_clear(val);
7493 Type* int_type = Type::lookup_integer_type("int");
7494 if (bits >= int_type->integer_type()->bits())
7495 {
7496 error_at(e->location(), "%s argument too large for make",
7497 is_length ? "len" : "cap");
7498 return false;
7499 }
7500
7501 return true;
a9182619 7502 }
7503
1ad00fd4 7504 if (e->type()->integer_type() != NULL)
7505 return true;
7506
7507 error_at(e->location(), "non-integer %s argument to make",
7508 is_length ? "len" : "cap");
a9182619 7509 return false;
7510}
7511
e440a328 7512// Return the type of the real or imag functions, given the type of
7513// the argument. We need to map complex to float, complex64 to
7514// float32, and complex128 to float64, so it has to be done by name.
7515// This returns NULL if it can't figure out the type.
7516
7517Type*
7518Builtin_call_expression::real_imag_type(Type* arg_type)
7519{
7520 if (arg_type == NULL || arg_type->is_abstract())
7521 return NULL;
7522 Named_type* nt = arg_type->named_type();
7523 if (nt == NULL)
7524 return NULL;
7525 while (nt->real_type()->named_type() != NULL)
7526 nt = nt->real_type()->named_type();
48080209 7527 if (nt->name() == "complex64")
e440a328 7528 return Type::lookup_float_type("float32");
7529 else if (nt->name() == "complex128")
7530 return Type::lookup_float_type("float64");
7531 else
7532 return NULL;
7533}
7534
48080209 7535// Return the type of the complex function, given the type of one of the
e440a328 7536// argments. Like real_imag_type, we have to map by name.
7537
7538Type*
48080209 7539Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7540{
7541 if (arg_type == NULL || arg_type->is_abstract())
7542 return NULL;
7543 Named_type* nt = arg_type->named_type();
7544 if (nt == NULL)
7545 return NULL;
7546 while (nt->real_type()->named_type() != NULL)
7547 nt = nt->real_type()->named_type();
48080209 7548 if (nt->name() == "float32")
e440a328 7549 return Type::lookup_complex_type("complex64");
7550 else if (nt->name() == "float64")
7551 return Type::lookup_complex_type("complex128");
7552 else
7553 return NULL;
7554}
7555
7556// Return a single argument, or NULL if there isn't one.
7557
7558Expression*
7559Builtin_call_expression::one_arg() const
7560{
7561 const Expression_list* args = this->args();
aa615cb3 7562 if (args == NULL || args->size() != 1)
e440a328 7563 return NULL;
7564 return args->front();
7565}
7566
83921647 7567// A traversal class which looks for a call or receive expression.
7568
7569class Find_call_expression : public Traverse
7570{
7571 public:
7572 Find_call_expression()
7573 : Traverse(traverse_expressions),
7574 found_(false)
7575 { }
7576
7577 int
7578 expression(Expression**);
7579
7580 bool
7581 found()
7582 { return this->found_; }
7583
7584 private:
7585 bool found_;
7586};
7587
7588int
7589Find_call_expression::expression(Expression** pexpr)
7590{
7591 if ((*pexpr)->call_expression() != NULL
7592 || (*pexpr)->receive_expression() != NULL)
7593 {
7594 this->found_ = true;
7595 return TRAVERSE_EXIT;
7596 }
7597 return TRAVERSE_CONTINUE;
7598}
7599
7600// Return whether this is constant: len of a string constant, or len
7601// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7602// unsafe.Alignof.
e440a328 7603
7604bool
7605Builtin_call_expression::do_is_constant() const
7606{
12e69faa 7607 if (this->is_error_expression())
7608 return true;
e440a328 7609 switch (this->code_)
7610 {
7611 case BUILTIN_LEN:
7612 case BUILTIN_CAP:
7613 {
0f914071 7614 if (this->seen_)
7615 return false;
7616
e440a328 7617 Expression* arg = this->one_arg();
7618 if (arg == NULL)
7619 return false;
7620 Type* arg_type = arg->type();
7621
7622 if (arg_type->points_to() != NULL
7623 && arg_type->points_to()->array_type() != NULL
411eb89e 7624 && !arg_type->points_to()->is_slice_type())
e440a328 7625 arg_type = arg_type->points_to();
7626
83921647 7627 // The len and cap functions are only constant if there are no
7628 // function calls or channel operations in the arguments.
7629 // Otherwise we have to make the call.
7630 if (!arg->is_constant())
7631 {
7632 Find_call_expression find_call;
7633 Expression::traverse(&arg, &find_call);
7634 if (find_call.found())
7635 return false;
7636 }
7637
e440a328 7638 if (arg_type->array_type() != NULL
7639 && arg_type->array_type()->length() != NULL)
0f914071 7640 return true;
e440a328 7641
7642 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7643 {
7644 this->seen_ = true;
7645 bool ret = arg->is_constant();
7646 this->seen_ = false;
7647 return ret;
7648 }
e440a328 7649 }
7650 break;
7651
7652 case BUILTIN_SIZEOF:
7653 case BUILTIN_ALIGNOF:
7654 return this->one_arg() != NULL;
7655
7656 case BUILTIN_OFFSETOF:
7657 {
7658 Expression* arg = this->one_arg();
7659 if (arg == NULL)
7660 return false;
7661 return arg->field_reference_expression() != NULL;
7662 }
7663
48080209 7664 case BUILTIN_COMPLEX:
e440a328 7665 {
7666 const Expression_list* args = this->args();
7667 if (args != NULL && args->size() == 2)
7668 return args->front()->is_constant() && args->back()->is_constant();
7669 }
7670 break;
7671
7672 case BUILTIN_REAL:
7673 case BUILTIN_IMAG:
7674 {
7675 Expression* arg = this->one_arg();
7676 return arg != NULL && arg->is_constant();
7677 }
7678
7679 default:
7680 break;
7681 }
7682
7683 return false;
7684}
7685
0c77715b 7686// Return a numeric constant if possible.
e440a328 7687
7688bool
0c77715b 7689Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7690{
7691 if (this->code_ == BUILTIN_LEN
7692 || this->code_ == BUILTIN_CAP)
7693 {
7694 Expression* arg = this->one_arg();
7695 if (arg == NULL)
7696 return false;
7697 Type* arg_type = arg->type();
7698
7699 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7700 {
7701 std::string sval;
7702 if (arg->string_constant_value(&sval))
7703 {
0c77715b 7704 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7705 sval.length());
e440a328 7706 return true;
7707 }
7708 }
7709
7710 if (arg_type->points_to() != NULL
7711 && arg_type->points_to()->array_type() != NULL
411eb89e 7712 && !arg_type->points_to()->is_slice_type())
e440a328 7713 arg_type = arg_type->points_to();
7714
7715 if (arg_type->array_type() != NULL
7716 && arg_type->array_type()->length() != NULL)
7717 {
0f914071 7718 if (this->seen_)
7719 return false;
e440a328 7720 Expression* e = arg_type->array_type()->length();
0f914071 7721 this->seen_ = true;
0c77715b 7722 bool r = e->numeric_constant_value(nc);
0f914071 7723 this->seen_ = false;
7724 if (r)
e440a328 7725 {
0c77715b 7726 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7727 this->location()))
7728 r = false;
e440a328 7729 }
0c77715b 7730 return r;
e440a328 7731 }
7732 }
7733 else if (this->code_ == BUILTIN_SIZEOF
7734 || this->code_ == BUILTIN_ALIGNOF)
7735 {
7736 Expression* arg = this->one_arg();
7737 if (arg == NULL)
7738 return false;
7739 Type* arg_type = arg->type();
5c13bd80 7740 if (arg_type->is_error())
e440a328 7741 return false;
7742 if (arg_type->is_abstract())
7743 return false;
2c809f8f 7744 if (this->seen_)
7745 return false;
927a01eb 7746
7747 unsigned int ret;
e440a328 7748 if (this->code_ == BUILTIN_SIZEOF)
7749 {
2c809f8f 7750 this->seen_ = true;
7751 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7752 this->seen_ = false;
7753 if (!ok)
e440a328 7754 return false;
7755 }
7756 else if (this->code_ == BUILTIN_ALIGNOF)
7757 {
2c809f8f 7758 bool ok;
7759 this->seen_ = true;
637bd3af 7760 if (arg->field_reference_expression() == NULL)
2c809f8f 7761 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7762 else
e440a328 7763 {
7764 // Calling unsafe.Alignof(s.f) returns the alignment of
7765 // the type of f when it is used as a field in a struct.
2c809f8f 7766 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7767 }
2c809f8f 7768 this->seen_ = false;
7769 if (!ok)
7770 return false;
e440a328 7771 }
7772 else
c3e6f413 7773 go_unreachable();
927a01eb 7774
7ba86326 7775 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7776 static_cast<unsigned long>(ret));
e440a328 7777 return true;
7778 }
7779 else if (this->code_ == BUILTIN_OFFSETOF)
7780 {
7781 Expression* arg = this->one_arg();
7782 if (arg == NULL)
7783 return false;
7784 Field_reference_expression* farg = arg->field_reference_expression();
7785 if (farg == NULL)
7786 return false;
2c809f8f 7787 if (this->seen_)
7788 return false;
7789
9a4bd570 7790 unsigned int total_offset = 0;
7791 while (true)
7792 {
7793 Expression* struct_expr = farg->expr();
7794 Type* st = struct_expr->type();
7795 if (st->struct_type() == NULL)
7796 return false;
7797 if (st->named_type() != NULL)
7798 st->named_type()->convert(this->gogo_);
7799 unsigned int offset;
2c809f8f 7800 this->seen_ = true;
7801 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7802 farg->field_index(),
7803 &offset);
7804 this->seen_ = false;
7805 if (!ok)
7806 return false;
9a4bd570 7807 total_offset += offset;
7808 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7809 {
7810 // Go up until we reach the original base.
7811 farg = struct_expr->field_reference_expression();
7812 continue;
7813 }
7814 break;
7815 }
7ba86326 7816 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
9a4bd570 7817 static_cast<unsigned long>(total_offset));
e440a328 7818 return true;
7819 }
0c77715b 7820 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7821 {
7822 Expression* arg = this->one_arg();
7823 if (arg == NULL)
7824 return false;
7825
0c77715b 7826 Numeric_constant argnc;
7827 if (!arg->numeric_constant_value(&argnc))
7828 return false;
7829
e440a328 7830 mpfr_t real;
7831 mpfr_t imag;
0c77715b 7832 if (!argnc.to_complex(&real, &imag))
7833 return false;
e440a328 7834
0c77715b 7835 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7836 if (this->code_ == BUILTIN_REAL)
7837 nc->set_float(type, real);
7838 else
7839 nc->set_float(type, imag);
7840 return true;
e440a328 7841 }
0c77715b 7842 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7843 {
7844 const Expression_list* args = this->args();
7845 if (args == NULL || args->size() != 2)
7846 return false;
7847
0c77715b 7848 Numeric_constant rnc;
7849 if (!args->front()->numeric_constant_value(&rnc))
7850 return false;
7851 Numeric_constant inc;
7852 if (!args->back()->numeric_constant_value(&inc))
7853 return false;
7854
7855 if (rnc.type() != NULL
7856 && !rnc.type()->is_abstract()
7857 && inc.type() != NULL
7858 && !inc.type()->is_abstract()
7859 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7860 return false;
7861
e440a328 7862 mpfr_t r;
0c77715b 7863 if (!rnc.to_float(&r))
7864 return false;
7865 mpfr_t i;
7866 if (!inc.to_float(&i))
e440a328 7867 {
7868 mpfr_clear(r);
7869 return false;
7870 }
7871
0c77715b 7872 Type* arg_type = rnc.type();
7873 if (arg_type == NULL || arg_type->is_abstract())
7874 arg_type = inc.type();
e440a328 7875
0c77715b 7876 Type* type = Builtin_call_expression::complex_type(arg_type);
7877 nc->set_complex(type, r, i);
e440a328 7878
7879 mpfr_clear(r);
7880 mpfr_clear(i);
7881
0c77715b 7882 return true;
e440a328 7883 }
7884
7885 return false;
7886}
7887
a7549a6a 7888// Give an error if we are discarding the value of an expression which
7889// should not normally be discarded. We don't give an error for
7890// discarding the value of an ordinary function call, but we do for
7891// builtin functions, purely for consistency with the gc compiler.
7892
4f2138d7 7893bool
a7549a6a 7894Builtin_call_expression::do_discarding_value()
7895{
7896 switch (this->code_)
7897 {
7898 case BUILTIN_INVALID:
7899 default:
7900 go_unreachable();
7901
7902 case BUILTIN_APPEND:
7903 case BUILTIN_CAP:
7904 case BUILTIN_COMPLEX:
7905 case BUILTIN_IMAG:
7906 case BUILTIN_LEN:
7907 case BUILTIN_MAKE:
7908 case BUILTIN_NEW:
7909 case BUILTIN_REAL:
7910 case BUILTIN_ALIGNOF:
7911 case BUILTIN_OFFSETOF:
7912 case BUILTIN_SIZEOF:
7913 this->unused_value_error();
4f2138d7 7914 return false;
a7549a6a 7915
7916 case BUILTIN_CLOSE:
7917 case BUILTIN_COPY:
1cce762f 7918 case BUILTIN_DELETE:
a7549a6a 7919 case BUILTIN_PANIC:
7920 case BUILTIN_PRINT:
7921 case BUILTIN_PRINTLN:
7922 case BUILTIN_RECOVER:
4f2138d7 7923 return true;
a7549a6a 7924 }
7925}
7926
e440a328 7927// Return the type.
7928
7929Type*
7930Builtin_call_expression::do_type()
7931{
7932 switch (this->code_)
7933 {
7934 case BUILTIN_INVALID:
7935 default:
c3e6f413 7936 go_unreachable();
e440a328 7937
7938 case BUILTIN_NEW:
7939 case BUILTIN_MAKE:
7940 {
7941 const Expression_list* args = this->args();
7942 if (args == NULL || args->empty())
7943 return Type::make_error_type();
7944 return Type::make_pointer_type(args->front()->type());
7945 }
7946
7947 case BUILTIN_CAP:
7948 case BUILTIN_COPY:
7949 case BUILTIN_LEN:
7ba86326 7950 return Type::lookup_integer_type("int");
7951
e440a328 7952 case BUILTIN_ALIGNOF:
7953 case BUILTIN_OFFSETOF:
7954 case BUILTIN_SIZEOF:
7ba86326 7955 return Type::lookup_integer_type("uintptr");
e440a328 7956
7957 case BUILTIN_CLOSE:
1cce762f 7958 case BUILTIN_DELETE:
e440a328 7959 case BUILTIN_PANIC:
7960 case BUILTIN_PRINT:
7961 case BUILTIN_PRINTLN:
7962 return Type::make_void_type();
7963
e440a328 7964 case BUILTIN_RECOVER:
823c7e3d 7965 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 7966
7967 case BUILTIN_APPEND:
7968 {
7969 const Expression_list* args = this->args();
7970 if (args == NULL || args->empty())
7971 return Type::make_error_type();
3ff4863b 7972 Type *ret = args->front()->type();
7973 if (!ret->is_slice_type())
7974 return Type::make_error_type();
7975 return ret;
e440a328 7976 }
7977
7978 case BUILTIN_REAL:
7979 case BUILTIN_IMAG:
7980 {
7981 Expression* arg = this->one_arg();
7982 if (arg == NULL)
7983 return Type::make_error_type();
7984 Type* t = arg->type();
7985 if (t->is_abstract())
7986 t = t->make_non_abstract_type();
7987 t = Builtin_call_expression::real_imag_type(t);
7988 if (t == NULL)
7989 t = Type::make_error_type();
7990 return t;
7991 }
7992
48080209 7993 case BUILTIN_COMPLEX:
e440a328 7994 {
7995 const Expression_list* args = this->args();
7996 if (args == NULL || args->size() != 2)
7997 return Type::make_error_type();
7998 Type* t = args->front()->type();
7999 if (t->is_abstract())
8000 {
8001 t = args->back()->type();
8002 if (t->is_abstract())
8003 t = t->make_non_abstract_type();
8004 }
48080209 8005 t = Builtin_call_expression::complex_type(t);
e440a328 8006 if (t == NULL)
8007 t = Type::make_error_type();
8008 return t;
8009 }
8010 }
8011}
8012
8013// Determine the type.
8014
8015void
8016Builtin_call_expression::do_determine_type(const Type_context* context)
8017{
fb94b0ca 8018 if (!this->determining_types())
8019 return;
8020
e440a328 8021 this->fn()->determine_type_no_context();
8022
8023 const Expression_list* args = this->args();
8024
8025 bool is_print;
8026 Type* arg_type = NULL;
8027 switch (this->code_)
8028 {
8029 case BUILTIN_PRINT:
8030 case BUILTIN_PRINTLN:
8031 // Do not force a large integer constant to "int".
8032 is_print = true;
8033 break;
8034
8035 case BUILTIN_REAL:
8036 case BUILTIN_IMAG:
48080209 8037 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 8038 if (arg_type == NULL)
8039 arg_type = Type::lookup_complex_type("complex128");
e440a328 8040 is_print = false;
8041 break;
8042
48080209 8043 case BUILTIN_COMPLEX:
e440a328 8044 {
48080209 8045 // For the complex function the type of one operand can
e440a328 8046 // determine the type of the other, as in a binary expression.
8047 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 8048 if (arg_type == NULL)
8049 arg_type = Type::lookup_float_type("float64");
e440a328 8050 if (args != NULL && args->size() == 2)
8051 {
8052 Type* t1 = args->front()->type();
c849bb59 8053 Type* t2 = args->back()->type();
e440a328 8054 if (!t1->is_abstract())
8055 arg_type = t1;
8056 else if (!t2->is_abstract())
8057 arg_type = t2;
8058 }
8059 is_print = false;
8060 }
8061 break;
8062
8063 default:
8064 is_print = false;
8065 break;
8066 }
8067
8068 if (args != NULL)
8069 {
8070 for (Expression_list::const_iterator pa = args->begin();
8071 pa != args->end();
8072 ++pa)
8073 {
8074 Type_context subcontext;
8075 subcontext.type = arg_type;
8076
8077 if (is_print)
8078 {
8079 // We want to print large constants, we so can't just
8080 // use the appropriate nonabstract type. Use uint64 for
8081 // an integer if we know it is nonnegative, otherwise
8082 // use int64 for a integer, otherwise use float64 for a
8083 // float or complex128 for a complex.
8084 Type* want_type = NULL;
8085 Type* atype = (*pa)->type();
8086 if (atype->is_abstract())
8087 {
8088 if (atype->integer_type() != NULL)
8089 {
0c77715b 8090 Numeric_constant nc;
8091 if (this->numeric_constant_value(&nc))
8092 {
8093 mpz_t val;
8094 if (nc.to_int(&val))
8095 {
8096 if (mpz_sgn(val) >= 0)
8097 want_type = Type::lookup_integer_type("uint64");
8098 mpz_clear(val);
8099 }
8100 }
8101 if (want_type == NULL)
e440a328 8102 want_type = Type::lookup_integer_type("int64");
e440a328 8103 }
8104 else if (atype->float_type() != NULL)
8105 want_type = Type::lookup_float_type("float64");
8106 else if (atype->complex_type() != NULL)
8107 want_type = Type::lookup_complex_type("complex128");
8108 else if (atype->is_abstract_string_type())
8109 want_type = Type::lookup_string_type();
8110 else if (atype->is_abstract_boolean_type())
8111 want_type = Type::lookup_bool_type();
8112 else
c3e6f413 8113 go_unreachable();
e440a328 8114 subcontext.type = want_type;
8115 }
8116 }
8117
8118 (*pa)->determine_type(&subcontext);
8119 }
8120 }
8121}
8122
8123// If there is exactly one argument, return true. Otherwise give an
8124// error message and return false.
8125
8126bool
8127Builtin_call_expression::check_one_arg()
8128{
8129 const Expression_list* args = this->args();
8130 if (args == NULL || args->size() < 1)
8131 {
8132 this->report_error(_("not enough arguments"));
8133 return false;
8134 }
8135 else if (args->size() > 1)
8136 {
8137 this->report_error(_("too many arguments"));
8138 return false;
8139 }
8140 if (args->front()->is_error_expression()
5c13bd80 8141 || args->front()->type()->is_error())
e440a328 8142 {
8143 this->set_is_error();
8144 return false;
8145 }
8146 return true;
8147}
8148
8149// Check argument types for a builtin function.
8150
8151void
8152Builtin_call_expression::do_check_types(Gogo*)
8153{
375646ea 8154 if (this->is_error_expression())
8155 return;
e440a328 8156 switch (this->code_)
8157 {
8158 case BUILTIN_INVALID:
8159 case BUILTIN_NEW:
8160 case BUILTIN_MAKE:
cd238b8d 8161 case BUILTIN_DELETE:
e440a328 8162 return;
8163
8164 case BUILTIN_LEN:
8165 case BUILTIN_CAP:
8166 {
8167 // The single argument may be either a string or an array or a
8168 // map or a channel, or a pointer to a closed array.
8169 if (this->check_one_arg())
8170 {
8171 Type* arg_type = this->one_arg()->type();
8172 if (arg_type->points_to() != NULL
8173 && arg_type->points_to()->array_type() != NULL
411eb89e 8174 && !arg_type->points_to()->is_slice_type())
e440a328 8175 arg_type = arg_type->points_to();
8176 if (this->code_ == BUILTIN_CAP)
8177 {
5c13bd80 8178 if (!arg_type->is_error()
e440a328 8179 && arg_type->array_type() == NULL
8180 && arg_type->channel_type() == NULL)
8181 this->report_error(_("argument must be array or slice "
8182 "or channel"));
8183 }
8184 else
8185 {
5c13bd80 8186 if (!arg_type->is_error()
e440a328 8187 && !arg_type->is_string_type()
8188 && arg_type->array_type() == NULL
8189 && arg_type->map_type() == NULL
8190 && arg_type->channel_type() == NULL)
8191 this->report_error(_("argument must be string or "
8192 "array or slice or map or channel"));
8193 }
8194 }
8195 }
8196 break;
8197
8198 case BUILTIN_PRINT:
8199 case BUILTIN_PRINTLN:
8200 {
8201 const Expression_list* args = this->args();
8202 if (args == NULL)
8203 {
8204 if (this->code_ == BUILTIN_PRINT)
8205 warning_at(this->location(), 0,
8206 "no arguments for builtin function %<%s%>",
8207 (this->code_ == BUILTIN_PRINT
8208 ? "print"
8209 : "println"));
8210 }
8211 else
8212 {
8213 for (Expression_list::const_iterator p = args->begin();
8214 p != args->end();
8215 ++p)
8216 {
8217 Type* type = (*p)->type();
5c13bd80 8218 if (type->is_error()
e440a328 8219 || type->is_string_type()
8220 || type->integer_type() != NULL
8221 || type->float_type() != NULL
8222 || type->complex_type() != NULL
8223 || type->is_boolean_type()
8224 || type->points_to() != NULL
8225 || type->interface_type() != NULL
8226 || type->channel_type() != NULL
8227 || type->map_type() != NULL
8228 || type->function_type() != NULL
411eb89e 8229 || type->is_slice_type())
e440a328 8230 ;
acf8e158 8231 else if ((*p)->is_type_expression())
8232 {
8233 // If this is a type expression it's going to give
8234 // an error anyhow, so we don't need one here.
8235 }
e440a328 8236 else
8237 this->report_error(_("unsupported argument type to "
8238 "builtin function"));
8239 }
8240 }
8241 }
8242 break;
8243
8244 case BUILTIN_CLOSE:
e440a328 8245 if (this->check_one_arg())
8246 {
8247 if (this->one_arg()->type()->channel_type() == NULL)
8248 this->report_error(_("argument must be channel"));
5202d986 8249 else if (!this->one_arg()->type()->channel_type()->may_send())
8250 this->report_error(_("cannot close receive-only channel"));
e440a328 8251 }
8252 break;
8253
8254 case BUILTIN_PANIC:
8255 case BUILTIN_SIZEOF:
8256 case BUILTIN_ALIGNOF:
8257 this->check_one_arg();
8258 break;
8259
8260 case BUILTIN_RECOVER:
8261 if (this->args() != NULL && !this->args()->empty())
8262 this->report_error(_("too many arguments"));
8263 break;
8264
8265 case BUILTIN_OFFSETOF:
8266 if (this->check_one_arg())
8267 {
8268 Expression* arg = this->one_arg();
8269 if (arg->field_reference_expression() == NULL)
8270 this->report_error(_("argument must be a field reference"));
8271 }
8272 break;
8273
8274 case BUILTIN_COPY:
8275 {
8276 const Expression_list* args = this->args();
8277 if (args == NULL || args->size() < 2)
8278 {
8279 this->report_error(_("not enough arguments"));
8280 break;
8281 }
8282 else if (args->size() > 2)
8283 {
8284 this->report_error(_("too many arguments"));
8285 break;
8286 }
8287 Type* arg1_type = args->front()->type();
8288 Type* arg2_type = args->back()->type();
5c13bd80 8289 if (arg1_type->is_error() || arg2_type->is_error())
e440a328 8290 break;
8291
8292 Type* e1;
411eb89e 8293 if (arg1_type->is_slice_type())
e440a328 8294 e1 = arg1_type->array_type()->element_type();
8295 else
8296 {
8297 this->report_error(_("left argument must be a slice"));
8298 break;
8299 }
8300
411eb89e 8301 if (arg2_type->is_slice_type())
60963afd 8302 {
8303 Type* e2 = arg2_type->array_type()->element_type();
8304 if (!Type::are_identical(e1, e2, true, NULL))
8305 this->report_error(_("element types must be the same"));
8306 }
e440a328 8307 else if (arg2_type->is_string_type())
e440a328 8308 {
60963afd 8309 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8310 this->report_error(_("first argument must be []byte"));
e440a328 8311 }
60963afd 8312 else
8313 this->report_error(_("second argument must be slice or string"));
e440a328 8314 }
8315 break;
8316
8317 case BUILTIN_APPEND:
8318 {
8319 const Expression_list* args = this->args();
b0d311a1 8320 if (args == NULL || args->size() < 2)
e440a328 8321 {
8322 this->report_error(_("not enough arguments"));
8323 break;
8324 }
0b7755ec 8325 if (args->size() > 2)
8326 {
8327 this->report_error(_("too many arguments"));
8328 break;
8329 }
cd238b8d 8330 if (args->front()->type()->is_error()
8331 || args->back()->type()->is_error())
8332 break;
8333
8334 Array_type* at = args->front()->type()->array_type();
8335 Type* e = at->element_type();
4fd4fcf4 8336
8337 // The language permits appending a string to a []byte, as a
8338 // special case.
8339 if (args->back()->type()->is_string_type())
8340 {
60963afd 8341 if (e->integer_type() != NULL && e->integer_type()->is_byte())
4fd4fcf4 8342 break;
8343 }
8344
19fd40c3 8345 // The language says that the second argument must be
8346 // assignable to a slice of the element type of the first
8347 // argument. We already know the first argument is a slice
8348 // type.
cd238b8d 8349 Type* arg2_type = Type::make_array_type(e, NULL);
e440a328 8350 std::string reason;
19fd40c3 8351 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
e440a328 8352 {
8353 if (reason.empty())
19fd40c3 8354 this->report_error(_("argument 2 has invalid type"));
e440a328 8355 else
8356 {
19fd40c3 8357 error_at(this->location(), "argument 2 has invalid type (%s)",
e440a328 8358 reason.c_str());
8359 this->set_is_error();
8360 }
8361 }
8362 break;
8363 }
8364
8365 case BUILTIN_REAL:
8366 case BUILTIN_IMAG:
8367 if (this->check_one_arg())
8368 {
8369 if (this->one_arg()->type()->complex_type() == NULL)
8370 this->report_error(_("argument must have complex type"));
8371 }
8372 break;
8373
48080209 8374 case BUILTIN_COMPLEX:
e440a328 8375 {
8376 const Expression_list* args = this->args();
8377 if (args == NULL || args->size() < 2)
8378 this->report_error(_("not enough arguments"));
8379 else if (args->size() > 2)
8380 this->report_error(_("too many arguments"));
8381 else if (args->front()->is_error_expression()
5c13bd80 8382 || args->front()->type()->is_error()
e440a328 8383 || args->back()->is_error_expression()
5c13bd80 8384 || args->back()->type()->is_error())
e440a328 8385 this->set_is_error();
8386 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8387 args->back()->type(), true, NULL))
48080209 8388 this->report_error(_("complex arguments must have identical types"));
e440a328 8389 else if (args->front()->type()->float_type() == NULL)
48080209 8390 this->report_error(_("complex arguments must have "
e440a328 8391 "floating-point type"));
8392 }
8393 break;
8394
8395 default:
c3e6f413 8396 go_unreachable();
e440a328 8397 }
8398}
8399
8400// Return the tree for a builtin function.
8401
8402tree
8403Builtin_call_expression::do_get_tree(Translate_context* context)
8404{
8405 Gogo* gogo = context->gogo();
b13c66cd 8406 Location location = this->location();
e440a328 8407 switch (this->code_)
8408 {
8409 case BUILTIN_INVALID:
8410 case BUILTIN_NEW:
8411 case BUILTIN_MAKE:
c3e6f413 8412 go_unreachable();
e440a328 8413
8414 case BUILTIN_LEN:
8415 case BUILTIN_CAP:
8416 {
8417 const Expression_list* args = this->args();
c484d925 8418 go_assert(args != NULL && args->size() == 1);
2c809f8f 8419 Expression* arg = args->front();
e440a328 8420 Type* arg_type = arg->type();
0f914071 8421
8422 if (this->seen_)
8423 {
c484d925 8424 go_assert(saw_errors());
0f914071 8425 return error_mark_node;
8426 }
8427 this->seen_ = true;
0f914071 8428 this->seen_ = false;
e440a328 8429 if (arg_type->points_to() != NULL)
8430 {
8431 arg_type = arg_type->points_to();
c484d925 8432 go_assert(arg_type->array_type() != NULL
411eb89e 8433 && !arg_type->is_slice_type());
2c809f8f 8434 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8435 }
8436
1b1f2abf 8437 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8438 Expression* val;
e440a328 8439 if (this->code_ == BUILTIN_LEN)
8440 {
8441 if (arg_type->is_string_type())
2c809f8f 8442 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8443 location);
e440a328 8444 else if (arg_type->array_type() != NULL)
0f914071 8445 {
8446 if (this->seen_)
8447 {
c484d925 8448 go_assert(saw_errors());
0f914071 8449 return error_mark_node;
8450 }
8451 this->seen_ = true;
2c809f8f 8452 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8453 this->seen_ = false;
8454 }
e440a328 8455 else if (arg_type->map_type() != NULL)
2c809f8f 8456 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
e440a328 8457 else if (arg_type->channel_type() != NULL)
2c809f8f 8458 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
e440a328 8459 else
c3e6f413 8460 go_unreachable();
e440a328 8461 }
8462 else
8463 {
8464 if (arg_type->array_type() != NULL)
0f914071 8465 {
8466 if (this->seen_)
8467 {
c484d925 8468 go_assert(saw_errors());
0f914071 8469 return error_mark_node;
8470 }
8471 this->seen_ = true;
2c809f8f 8472 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8473 this->seen_ = false;
8474 }
e440a328 8475 else if (arg_type->channel_type() != NULL)
2c809f8f 8476 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
e440a328 8477 else
c3e6f413 8478 go_unreachable();
e440a328 8479 }
8480
2c809f8f 8481 return Expression::make_cast(int_type, val,
8482 location)->get_tree(context);
e440a328 8483 }
8484
8485 case BUILTIN_PRINT:
8486 case BUILTIN_PRINTLN:
8487 {
8488 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
2c809f8f 8489 Expression* print_stmts = NULL;
e440a328 8490
8491 const Expression_list* call_args = this->args();
8492 if (call_args != NULL)
8493 {
8494 for (Expression_list::const_iterator p = call_args->begin();
8495 p != call_args->end();
8496 ++p)
8497 {
8498 if (is_ln && p != call_args->begin())
8499 {
2c809f8f 8500 Expression* print_space =
8501 Runtime::make_call(Runtime::PRINT_SPACE,
8502 this->location(), 0);
e440a328 8503
2c809f8f 8504 print_stmts =
8505 Expression::make_compound(print_stmts, print_space,
8506 location);
8507 }
e440a328 8508
2c809f8f 8509 Expression* arg = *p;
8510 Type* type = arg->type();
8511 Runtime::Function code;
e440a328 8512 if (type->is_string_type())
2c809f8f 8513 code = Runtime::PRINT_STRING;
e440a328 8514 else if (type->integer_type() != NULL
8515 && type->integer_type()->is_unsigned())
8516 {
e440a328 8517 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8518 arg = Expression::make_cast(itype, arg, location);
8519 code = Runtime::PRINT_UINT64;
e440a328 8520 }
8521 else if (type->integer_type() != NULL)
8522 {
e440a328 8523 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8524 arg = Expression::make_cast(itype, arg, location);
8525 code = Runtime::PRINT_INT64;
e440a328 8526 }
8527 else if (type->float_type() != NULL)
8528 {
2c809f8f 8529 Type* dtype = Type::lookup_float_type("float64");
8530 arg = Expression::make_cast(dtype, arg, location);
8531 code = Runtime::PRINT_DOUBLE;
e440a328 8532 }
8533 else if (type->complex_type() != NULL)
8534 {
2c809f8f 8535 Type* ctype = Type::lookup_complex_type("complex128");
8536 arg = Expression::make_cast(ctype, arg, location);
8537 code = Runtime::PRINT_COMPLEX;
e440a328 8538 }
8539 else if (type->is_boolean_type())
2c809f8f 8540 code = Runtime::PRINT_BOOL;
e440a328 8541 else if (type->points_to() != NULL
8542 || type->channel_type() != NULL
8543 || type->map_type() != NULL
8544 || type->function_type() != NULL)
8545 {
2c809f8f 8546 arg = Expression::make_cast(type, arg, location);
8547 code = Runtime::PRINT_POINTER;
e440a328 8548 }
8549 else if (type->interface_type() != NULL)
8550 {
8551 if (type->interface_type()->is_empty())
2c809f8f 8552 code = Runtime::PRINT_EMPTY_INTERFACE;
e440a328 8553 else
2c809f8f 8554 code = Runtime::PRINT_INTERFACE;
e440a328 8555 }
411eb89e 8556 else if (type->is_slice_type())
2c809f8f 8557 code = Runtime::PRINT_SLICE;
e440a328 8558 else
cd238b8d 8559 {
8560 go_assert(saw_errors());
8561 return error_mark_node;
8562 }
e440a328 8563
2c809f8f 8564 Expression* call = Runtime::make_call(code, location, 1, arg);
8565 if (print_stmts == NULL)
8566 print_stmts = call;
8567 else
8568 print_stmts = Expression::make_compound(print_stmts, call,
8569 location);
e440a328 8570 }
8571 }
8572
8573 if (is_ln)
8574 {
2c809f8f 8575 Expression* print_nl =
8576 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8577 if (print_stmts == NULL)
8578 print_stmts = print_nl;
8579 else
8580 print_stmts = Expression::make_compound(print_stmts, print_nl,
8581 location);
e440a328 8582 }
8583
2c809f8f 8584 return print_stmts->get_tree(context);
e440a328 8585 }
8586
8587 case BUILTIN_PANIC:
8588 {
8589 const Expression_list* args = this->args();
c484d925 8590 go_assert(args != NULL && args->size() == 1);
e440a328 8591 Expression* arg = args->front();
b13c66cd 8592 Type *empty =
823c7e3d 8593 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8594 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8595
8596 Expression* panic =
8597 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8598 return panic->get_tree(context);
e440a328 8599 }
8600
8601 case BUILTIN_RECOVER:
8602 {
8603 // The argument is set when building recover thunks. It's a
8604 // boolean value which is true if we can recover a value now.
8605 const Expression_list* args = this->args();
c484d925 8606 go_assert(args != NULL && args->size() == 1);
e440a328 8607 Expression* arg = args->front();
b13c66cd 8608 Type *empty =
823c7e3d 8609 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8610
e440a328 8611 Expression* nil = Expression::make_nil(location);
2c809f8f 8612 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8613
8614 // We need to handle a deferred call to recover specially,
8615 // because it changes whether it can recover a panic or not.
8616 // See test7 in test/recover1.go.
2c809f8f 8617 Expression* recover = Runtime::make_call((this->is_deferred()
8618 ? Runtime::DEFERRED_RECOVER
8619 : Runtime::RECOVER),
8620 location, 0);
8621 Expression* cond =
8622 Expression::make_conditional(arg, recover, nil, location);
8623 return cond->get_tree(context);
e440a328 8624 }
8625
8626 case BUILTIN_CLOSE:
e440a328 8627 {
8628 const Expression_list* args = this->args();
c484d925 8629 go_assert(args != NULL && args->size() == 1);
e440a328 8630 Expression* arg = args->front();
2c809f8f 8631 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8632 1, arg);
8633 return close->get_tree(context);
e440a328 8634 }
8635
8636 case BUILTIN_SIZEOF:
8637 case BUILTIN_OFFSETOF:
8638 case BUILTIN_ALIGNOF:
8639 {
0c77715b 8640 Numeric_constant nc;
8641 unsigned long val;
8642 if (!this->numeric_constant_value(&nc)
8643 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8644 {
c484d925 8645 go_assert(saw_errors());
7f1d9abd 8646 return error_mark_node;
8647 }
7ba86326 8648 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 8649 mpz_t ival;
8650 nc.get_int(&ival);
8651 Expression* int_cst =
8652 Expression::make_integer(&ival, uintptr_type, location);
8653 mpz_clear(ival);
8654 return int_cst->get_tree(context);
e440a328 8655 }
8656
8657 case BUILTIN_COPY:
8658 {
8659 const Expression_list* args = this->args();
c484d925 8660 go_assert(args != NULL && args->size() == 2);
e440a328 8661 Expression* arg1 = args->front();
8662 Expression* arg2 = args->back();
8663
e440a328 8664 Type* arg1_type = arg1->type();
8665 Array_type* at = arg1_type->array_type();
35a54f17 8666 go_assert(arg1->is_variable());
2c809f8f 8667 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8668 Expression* arg1_len = at->get_length(gogo, arg1);
e440a328 8669
8670 Type* arg2_type = arg2->type();
2c809f8f 8671 go_assert(arg2->is_variable());
8672 Expression* arg2_val;
8673 Expression* arg2_len;
411eb89e 8674 if (arg2_type->is_slice_type())
e440a328 8675 {
8676 at = arg2_type->array_type();
2c809f8f 8677 arg2_val = at->get_value_pointer(gogo, arg2);
8678 arg2_len = at->get_length(gogo, arg2);
e440a328 8679 }
8680 else
8681 {
2c809f8f 8682 go_assert(arg2->is_variable());
8683 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8684 location);
8685 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8686 location);
e440a328 8687 }
2c809f8f 8688 Expression* cond =
8689 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8690 Expression* length =
8691 Expression::make_conditional(cond, arg1_len, arg2_len, location);
e440a328 8692
8693 Type* element_type = at->element_type();
9f0e0513 8694 Btype* element_btype = element_type->get_backend(gogo);
e440a328 8695
2c809f8f 8696 mpz_t size;
8697 size_t element_size = gogo->backend()->type_size(element_btype);
8698 mpz_init_set_ui(size, element_size);
8699 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8700 mpz_clear(size);
8701
8702 Expression* bytecount =
8703 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8704 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8705 arg1_val, arg2_val, bytecount);
8706
8707 Expression* compound = Expression::make_compound(copy, length, location);
8708 return compound->get_tree(context);
e440a328 8709 }
8710
8711 case BUILTIN_APPEND:
8712 {
8713 const Expression_list* args = this->args();
c484d925 8714 go_assert(args != NULL && args->size() == 2);
e440a328 8715 Expression* arg1 = args->front();
8716 Expression* arg2 = args->back();
8717
9d44fbe3 8718 Array_type* at = arg1->type()->array_type();
4fd4fcf4 8719 Type* element_type = at->element_type()->forwarded();
9d44fbe3 8720
2c809f8f 8721 go_assert(arg2->is_variable());
8722 Expression* arg2_val;
8723 Expression* arg2_len;
8724 mpz_t size;
4fd4fcf4 8725 if (arg2->type()->is_string_type()
60963afd 8726 && element_type->integer_type() != NULL
8727 && element_type->integer_type()->is_byte())
4fd4fcf4 8728 {
2c809f8f 8729 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8730 location);
8731 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8732 location);
8733 mpz_init_set_ui(size, 1UL);
4fd4fcf4 8734 }
8735 else
8736 {
2c809f8f 8737 arg2_val = at->get_value_pointer(gogo, arg2);
8738 arg2_len = at->get_length(gogo, arg2);
35a54f17 8739 Btype* element_btype = element_type->get_backend(gogo);
2c809f8f 8740 size_t element_size = gogo->backend()->type_size(element_btype);
8741 mpz_init_set_ui(size, element_size);
4fd4fcf4 8742 }
2c809f8f 8743 Expression* element_size =
8744 Expression::make_integer(&size, NULL, location);
8745 mpz_clear(size);
8746
8747 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8748 arg1, arg2_val, arg2_len,
8749 element_size);
8750 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8751 return append->get_tree(context);
e440a328 8752 }
8753
8754 case BUILTIN_REAL:
8755 case BUILTIN_IMAG:
8756 {
8757 const Expression_list* args = this->args();
c484d925 8758 go_assert(args != NULL && args->size() == 1);
e440a328 8759 Expression* arg = args->front();
2c809f8f 8760
8761 Bexpression* ret;
8762 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8763 if (this->code_ == BUILTIN_REAL)
8764 ret = gogo->backend()->real_part_expression(bcomplex, location);
8765 else
8766 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8767 return expr_to_tree(ret);
e440a328 8768 }
8769
48080209 8770 case BUILTIN_COMPLEX:
e440a328 8771 {
8772 const Expression_list* args = this->args();
c484d925 8773 go_assert(args != NULL && args->size() == 2);
2c809f8f 8774 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8775 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8776 Bexpression* ret =
8777 gogo->backend()->complex_expression(breal, bimag, location);
8778 return expr_to_tree(ret);
e440a328 8779 }
8780
8781 default:
c3e6f413 8782 go_unreachable();
e440a328 8783 }
8784}
8785
8786// We have to support exporting a builtin call expression, because
8787// code can set a constant to the result of a builtin expression.
8788
8789void
8790Builtin_call_expression::do_export(Export* exp) const
8791{
0c77715b 8792 Numeric_constant nc;
8793 if (!this->numeric_constant_value(&nc))
8794 {
8795 error_at(this->location(), "value is not constant");
8796 return;
8797 }
e440a328 8798
0c77715b 8799 if (nc.is_int())
e440a328 8800 {
0c77715b 8801 mpz_t val;
8802 nc.get_int(&val);
e440a328 8803 Integer_expression::export_integer(exp, val);
0c77715b 8804 mpz_clear(val);
e440a328 8805 }
0c77715b 8806 else if (nc.is_float())
e440a328 8807 {
8808 mpfr_t fval;
0c77715b 8809 nc.get_float(&fval);
8810 Float_expression::export_float(exp, fval);
e440a328 8811 mpfr_clear(fval);
8812 }
0c77715b 8813 else if (nc.is_complex())
e440a328 8814 {
8815 mpfr_t real;
8816 mpfr_t imag;
0c77715b 8817 Complex_expression::export_complex(exp, real, imag);
e440a328 8818 mpfr_clear(real);
8819 mpfr_clear(imag);
8820 }
0c77715b 8821 else
8822 go_unreachable();
e440a328 8823
8824 // A trailing space lets us reliably identify the end of the number.
8825 exp->write_c_string(" ");
8826}
8827
8828// Class Call_expression.
8829
8381eda7 8830// A Go function can be viewed in a couple of different ways. The
8831// code of a Go function becomes a backend function with parameters
8832// whose types are simply the backend representation of the Go types.
8833// If there are multiple results, they are returned as a backend
8834// struct.
8835
8836// However, when Go code refers to a function other than simply
8837// calling it, the backend type of that function is actually a struct.
8838// The first field of the struct points to the Go function code
8839// (sometimes a wrapper as described below). The remaining fields
8840// hold addresses of closed-over variables. This struct is called a
8841// closure.
8842
8843// There are a few cases to consider.
8844
8845// A direct function call of a known function in package scope. In
8846// this case there are no closed-over variables, and we know the name
8847// of the function code. We can simply produce a backend call to the
8848// function directly, and not worry about the closure.
8849
8850// A direct function call of a known function literal. In this case
8851// we know the function code and we know the closure. We generate the
8852// function code such that it expects an additional final argument of
8853// the closure type. We pass the closure as the last argument, after
8854// the other arguments.
8855
8856// An indirect function call. In this case we have a closure. We
8857// load the pointer to the function code from the first field of the
8858// closure. We pass the address of the closure as the last argument.
8859
8860// A call to a method of an interface. Type methods are always at
8861// package scope, so we call the function directly, and don't worry
8862// about the closure.
8863
8864// This means that for a function at package scope we have two cases.
8865// One is the direct call, which has no closure. The other is the
8866// indirect call, which does have a closure. We can't simply ignore
8867// the closure, even though it is the last argument, because that will
8868// fail on targets where the function pops its arguments. So when
8869// generating a closure for a package-scope function we set the
8870// function code pointer in the closure to point to a wrapper
8871// function. This wrapper function accepts a final argument that
8872// points to the closure, ignores it, and calls the real function as a
8873// direct function call. This wrapper will normally be efficient, and
8874// can often simply be a tail call to the real function.
8875
8876// We don't use GCC's static chain pointer because 1) we don't need
8877// it; 2) GCC only permits using a static chain to call a known
8878// function, so we can't use it for an indirect call anyhow. Since we
8879// can't use it for an indirect call, we may as well not worry about
8880// using it for a direct call either.
8881
8882// We pass the closure last rather than first because it means that
8883// the function wrapper we put into a closure for a package-scope
8884// function can normally just be a tail call to the real function.
8885
8886// For method expressions we generate a wrapper that loads the
8887// receiver from the closure and then calls the method. This
8888// unfortunately forces reshuffling the arguments, since there is a
8889// new first argument, but we can't avoid reshuffling either for
8890// method expressions or for indirect calls of package-scope
8891// functions, and since the latter are more common we reshuffle for
8892// method expressions.
8893
8894// Note that the Go code retains the Go types. The extra final
8895// argument only appears when we convert to the backend
8896// representation.
8897
e440a328 8898// Traversal.
8899
8900int
8901Call_expression::do_traverse(Traverse* traverse)
8902{
8903 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8904 return TRAVERSE_EXIT;
8905 if (this->args_ != NULL)
8906 {
8907 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8908 return TRAVERSE_EXIT;
8909 }
8910 return TRAVERSE_CONTINUE;
8911}
8912
8913// Lower a call statement.
8914
8915Expression*
ceeb4318 8916Call_expression::do_lower(Gogo* gogo, Named_object* function,
8917 Statement_inserter* inserter, int)
e440a328 8918{
b13c66cd 8919 Location loc = this->location();
09ea332d 8920
ceeb4318 8921 // A type cast can look like a function call.
e440a328 8922 if (this->fn_->is_type_expression()
8923 && this->args_ != NULL
8924 && this->args_->size() == 1)
8925 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 8926 loc);
e440a328 8927
88f06749 8928 // Because do_type will return an error type and thus prevent future
8929 // errors, check for that case now to ensure that the error gets
8930 // reported.
37448b10 8931 Function_type* fntype = this->get_function_type();
8932 if (fntype == NULL)
88f06749 8933 {
8934 if (!this->fn_->type()->is_error())
8935 this->report_error(_("expected function"));
8936 return Expression::make_error(loc);
8937 }
8938
e440a328 8939 // Handle an argument which is a call to a function which returns
8940 // multiple results.
8941 if (this->args_ != NULL
8942 && this->args_->size() == 1
37448b10 8943 && this->args_->front()->call_expression() != NULL)
e440a328 8944 {
e440a328 8945 size_t rc = this->args_->front()->call_expression()->result_count();
8946 if (rc > 1
37448b10 8947 && ((fntype->parameters() != NULL
8948 && (fntype->parameters()->size() == rc
8949 || (fntype->is_varargs()
8950 && fntype->parameters()->size() - 1 <= rc)))
8951 || fntype->is_builtin()))
e440a328 8952 {
8953 Call_expression* call = this->args_->front()->call_expression();
8954 Expression_list* args = new Expression_list;
8955 for (size_t i = 0; i < rc; ++i)
8956 args->push_back(Expression::make_call_result(call, i));
8957 // We can't return a new call expression here, because this
42535814 8958 // one may be referenced by Call_result expressions. We
8959 // also can't delete the old arguments, because we may still
8960 // traverse them somewhere up the call stack. FIXME.
e440a328 8961 this->args_ = args;
8962 }
8963 }
8964
37448b10 8965 // Recognize a call to a builtin function.
8966 if (fntype->is_builtin())
8967 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8968 this->is_varargs_, loc);
8969
ceeb4318 8970 // If this call returns multiple results, create a temporary
8971 // variable for each result.
8972 size_t rc = this->result_count();
8973 if (rc > 1 && this->results_ == NULL)
8974 {
8975 std::vector<Temporary_statement*>* temps =
8976 new std::vector<Temporary_statement*>;
8977 temps->reserve(rc);
37448b10 8978 const Typed_identifier_list* results = fntype->results();
ceeb4318 8979 for (Typed_identifier_list::const_iterator p = results->begin();
8980 p != results->end();
8981 ++p)
8982 {
8983 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 8984 NULL, loc);
ceeb4318 8985 inserter->insert(temp);
8986 temps->push_back(temp);
8987 }
8988 this->results_ = temps;
8989 }
8990
e440a328 8991 // Handle a call to a varargs function by packaging up the extra
8992 // parameters.
37448b10 8993 if (fntype->is_varargs())
e440a328 8994 {
e440a328 8995 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 8996 go_assert(parameters != NULL && !parameters->empty());
e440a328 8997 Type* varargs_type = parameters->back().type();
09ea332d 8998 this->lower_varargs(gogo, function, inserter, varargs_type,
8999 parameters->size());
9000 }
9001
9002 // If this is call to a method, call the method directly passing the
9003 // object as the first parameter.
9004 Bound_method_expression* bme = this->fn_->bound_method_expression();
9005 if (bme != NULL)
9006 {
0afbb937 9007 Named_object* methodfn = bme->function();
09ea332d 9008 Expression* first_arg = bme->first_argument();
9009
9010 // We always pass a pointer when calling a method.
9011 if (first_arg->type()->points_to() == NULL
9012 && !first_arg->type()->is_error())
9013 {
9014 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9015 // We may need to create a temporary variable so that we can
9016 // take the address. We can't do that here because it will
9017 // mess up the order of evaluation.
9018 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9019 ue->set_create_temp();
9020 }
9021
9022 // If we are calling a method which was inherited from an
9023 // embedded struct, and the method did not get a stub, then the
9024 // first type may be wrong.
9025 Type* fatype = bme->first_argument_type();
9026 if (fatype != NULL)
9027 {
9028 if (fatype->points_to() == NULL)
9029 fatype = Type::make_pointer_type(fatype);
9030 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9031 }
9032
9033 Expression_list* new_args = new Expression_list();
9034 new_args->push_back(first_arg);
9035 if (this->args_ != NULL)
9036 {
9037 for (Expression_list::const_iterator p = this->args_->begin();
9038 p != this->args_->end();
9039 ++p)
9040 new_args->push_back(*p);
9041 }
9042
9043 // We have to change in place because this structure may be
9044 // referenced by Call_result_expressions. We can't delete the
9045 // old arguments, because we may be traversing them up in some
9046 // caller. FIXME.
9047 this->args_ = new_args;
0afbb937 9048 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 9049 bme->location());
e440a328 9050 }
9051
9052 return this;
9053}
9054
9055// Lower a call to a varargs function. FUNCTION is the function in
9056// which the call occurs--it's not the function we are calling.
9057// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9058// PARAM_COUNT is the number of parameters of the function we are
9059// calling; the last of these parameters will be the varargs
9060// parameter.
9061
09ea332d 9062void
e440a328 9063Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 9064 Statement_inserter* inserter,
e440a328 9065 Type* varargs_type, size_t param_count)
9066{
9067 if (this->varargs_are_lowered_)
09ea332d 9068 return;
e440a328 9069
b13c66cd 9070 Location loc = this->location();
e440a328 9071
c484d925 9072 go_assert(param_count > 0);
411eb89e 9073 go_assert(varargs_type->is_slice_type());
e440a328 9074
9075 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9076 if (arg_count < param_count - 1)
9077 {
9078 // Not enough arguments; will be caught in check_types.
09ea332d 9079 return;
e440a328 9080 }
9081
9082 Expression_list* old_args = this->args_;
9083 Expression_list* new_args = new Expression_list();
9084 bool push_empty_arg = false;
9085 if (old_args == NULL || old_args->empty())
9086 {
c484d925 9087 go_assert(param_count == 1);
e440a328 9088 push_empty_arg = true;
9089 }
9090 else
9091 {
9092 Expression_list::const_iterator pa;
9093 int i = 1;
9094 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9095 {
9096 if (static_cast<size_t>(i) == param_count)
9097 break;
9098 new_args->push_back(*pa);
9099 }
9100
9101 // We have reached the varargs parameter.
9102
9103 bool issued_error = false;
9104 if (pa == old_args->end())
9105 push_empty_arg = true;
9106 else if (pa + 1 == old_args->end() && this->is_varargs_)
9107 new_args->push_back(*pa);
9108 else if (this->is_varargs_)
9109 {
a6645f74 9110 if ((*pa)->type()->is_slice_type())
9111 this->report_error(_("too many arguments"));
9112 else
9113 {
9114 error_at(this->location(),
9115 _("invalid use of %<...%> with non-slice"));
9116 this->set_is_error();
9117 }
09ea332d 9118 return;
e440a328 9119 }
e440a328 9120 else
9121 {
9122 Type* element_type = varargs_type->array_type()->element_type();
9123 Expression_list* vals = new Expression_list;
9124 for (; pa != old_args->end(); ++pa, ++i)
9125 {
9126 // Check types here so that we get a better message.
9127 Type* patype = (*pa)->type();
b13c66cd 9128 Location paloc = (*pa)->location();
e440a328 9129 if (!this->check_argument_type(i, element_type, patype,
9130 paloc, issued_error))
9131 continue;
9132 vals->push_back(*pa);
9133 }
9134 Expression* val =
9135 Expression::make_slice_composite_literal(varargs_type, vals, loc);
09ea332d 9136 gogo->lower_expression(function, inserter, &val);
e440a328 9137 new_args->push_back(val);
9138 }
9139 }
9140
9141 if (push_empty_arg)
9142 new_args->push_back(Expression::make_nil(loc));
9143
9144 // We can't return a new call expression here, because this one may
6d4c2432 9145 // be referenced by Call_result expressions. FIXME. We can't
9146 // delete OLD_ARGS because we may have both a Call_expression and a
9147 // Builtin_call_expression which refer to them. FIXME.
e440a328 9148 this->args_ = new_args;
9149 this->varargs_are_lowered_ = true;
e440a328 9150}
9151
2c809f8f 9152// Flatten a call with multiple results into a temporary.
9153
9154Expression*
9155Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9156{
9157 size_t rc = this->result_count();
9158 if (rc > 1 && this->call_temp_ == NULL)
9159 {
9160 Struct_field_list* sfl = new Struct_field_list();
9161 Function_type* fntype = this->get_function_type();
9162 const Typed_identifier_list* results = fntype->results();
9163 Location loc = this->location();
9164
9165 int i = 0;
9166 char buf[10];
9167 for (Typed_identifier_list::const_iterator p = results->begin();
9168 p != results->end();
9169 ++p, ++i)
9170 {
9171 snprintf(buf, sizeof buf, "res%d", i);
9172 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9173 }
9174
9175 Struct_type* st = Type::make_struct_type(sfl, loc);
9176 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9177 inserter->insert(this->call_temp_);
9178 }
9179
9180 return this;
9181}
9182
ceeb4318 9183// Get the function type. This can return NULL in error cases.
e440a328 9184
9185Function_type*
9186Call_expression::get_function_type() const
9187{
9188 return this->fn_->type()->function_type();
9189}
9190
9191// Return the number of values which this call will return.
9192
9193size_t
9194Call_expression::result_count() const
9195{
9196 const Function_type* fntype = this->get_function_type();
9197 if (fntype == NULL)
9198 return 0;
9199 if (fntype->results() == NULL)
9200 return 0;
9201 return fntype->results()->size();
9202}
9203
ceeb4318 9204// Return the temporary which holds a result.
9205
9206Temporary_statement*
9207Call_expression::result(size_t i) const
9208{
cd238b8d 9209 if (this->results_ == NULL || this->results_->size() <= i)
9210 {
9211 go_assert(saw_errors());
9212 return NULL;
9213 }
ceeb4318 9214 return (*this->results_)[i];
9215}
9216
e440a328 9217// Return whether this is a call to the predeclared function recover.
9218
9219bool
9220Call_expression::is_recover_call() const
9221{
9222 return this->do_is_recover_call();
9223}
9224
9225// Set the argument to the recover function.
9226
9227void
9228Call_expression::set_recover_arg(Expression* arg)
9229{
9230 this->do_set_recover_arg(arg);
9231}
9232
9233// Virtual functions also implemented by Builtin_call_expression.
9234
9235bool
9236Call_expression::do_is_recover_call() const
9237{
9238 return false;
9239}
9240
9241void
9242Call_expression::do_set_recover_arg(Expression*)
9243{
c3e6f413 9244 go_unreachable();
e440a328 9245}
9246
ceeb4318 9247// We have found an error with this call expression; return true if
9248// we should report it.
9249
9250bool
9251Call_expression::issue_error()
9252{
9253 if (this->issued_error_)
9254 return false;
9255 else
9256 {
9257 this->issued_error_ = true;
9258 return true;
9259 }
9260}
9261
e440a328 9262// Get the type.
9263
9264Type*
9265Call_expression::do_type()
9266{
9267 if (this->type_ != NULL)
9268 return this->type_;
9269
9270 Type* ret;
9271 Function_type* fntype = this->get_function_type();
9272 if (fntype == NULL)
9273 return Type::make_error_type();
9274
9275 const Typed_identifier_list* results = fntype->results();
9276 if (results == NULL)
9277 ret = Type::make_void_type();
9278 else if (results->size() == 1)
9279 ret = results->begin()->type();
9280 else
9281 ret = Type::make_call_multiple_result_type(this);
9282
9283 this->type_ = ret;
9284
9285 return this->type_;
9286}
9287
9288// Determine types for a call expression. We can use the function
9289// parameter types to set the types of the arguments.
9290
9291void
9292Call_expression::do_determine_type(const Type_context*)
9293{
fb94b0ca 9294 if (!this->determining_types())
9295 return;
9296
e440a328 9297 this->fn_->determine_type_no_context();
9298 Function_type* fntype = this->get_function_type();
9299 const Typed_identifier_list* parameters = NULL;
9300 if (fntype != NULL)
9301 parameters = fntype->parameters();
9302 if (this->args_ != NULL)
9303 {
9304 Typed_identifier_list::const_iterator pt;
9305 if (parameters != NULL)
9306 pt = parameters->begin();
09ea332d 9307 bool first = true;
e440a328 9308 for (Expression_list::const_iterator pa = this->args_->begin();
9309 pa != this->args_->end();
9310 ++pa)
9311 {
09ea332d 9312 if (first)
9313 {
9314 first = false;
9315 // If this is a method, the first argument is the
9316 // receiver.
9317 if (fntype != NULL && fntype->is_method())
9318 {
9319 Type* rtype = fntype->receiver()->type();
9320 // The receiver is always passed as a pointer.
9321 if (rtype->points_to() == NULL)
9322 rtype = Type::make_pointer_type(rtype);
9323 Type_context subcontext(rtype, false);
9324 (*pa)->determine_type(&subcontext);
9325 continue;
9326 }
9327 }
9328
e440a328 9329 if (parameters != NULL && pt != parameters->end())
9330 {
9331 Type_context subcontext(pt->type(), false);
9332 (*pa)->determine_type(&subcontext);
9333 ++pt;
9334 }
9335 else
9336 (*pa)->determine_type_no_context();
9337 }
9338 }
9339}
9340
fb94b0ca 9341// Called when determining types for a Call_expression. Return true
9342// if we should go ahead, false if they have already been determined.
9343
9344bool
9345Call_expression::determining_types()
9346{
9347 if (this->types_are_determined_)
9348 return false;
9349 else
9350 {
9351 this->types_are_determined_ = true;
9352 return true;
9353 }
9354}
9355
e440a328 9356// Check types for parameter I.
9357
9358bool
9359Call_expression::check_argument_type(int i, const Type* parameter_type,
9360 const Type* argument_type,
b13c66cd 9361 Location argument_location,
e440a328 9362 bool issued_error)
9363{
9364 std::string reason;
053ee6ca 9365 bool ok;
9366 if (this->are_hidden_fields_ok_)
9367 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9368 &reason);
9369 else
9370 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9371 if (!ok)
e440a328 9372 {
9373 if (!issued_error)
9374 {
9375 if (reason.empty())
9376 error_at(argument_location, "argument %d has incompatible type", i);
9377 else
9378 error_at(argument_location,
9379 "argument %d has incompatible type (%s)",
9380 i, reason.c_str());
9381 }
9382 this->set_is_error();
9383 return false;
9384 }
9385 return true;
9386}
9387
9388// Check types.
9389
9390void
9391Call_expression::do_check_types(Gogo*)
9392{
a6645f74 9393 if (this->classification() == EXPRESSION_ERROR)
9394 return;
9395
e440a328 9396 Function_type* fntype = this->get_function_type();
9397 if (fntype == NULL)
9398 {
5c13bd80 9399 if (!this->fn_->type()->is_error())
e440a328 9400 this->report_error(_("expected function"));
9401 return;
9402 }
9403
09ea332d 9404 bool is_method = fntype->is_method();
9405 if (is_method)
e440a328 9406 {
09ea332d 9407 go_assert(this->args_ != NULL && !this->args_->empty());
9408 Type* rtype = fntype->receiver()->type();
9409 Expression* first_arg = this->args_->front();
9410 // The language permits copying hidden fields for a method
9411 // receiver. We dereference the values since receivers are
9412 // always passed as pointers.
9413 std::string reason;
9414 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9415 first_arg->type()->deref(),
9416 &reason))
e440a328 9417 {
09ea332d 9418 if (reason.empty())
9419 this->report_error(_("incompatible type for receiver"));
9420 else
e440a328 9421 {
09ea332d 9422 error_at(this->location(),
9423 "incompatible type for receiver (%s)",
9424 reason.c_str());
9425 this->set_is_error();
e440a328 9426 }
9427 }
9428 }
9429
9430 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9431 // we don't have to worry about it here unless something is wrong.
9432 if (this->is_varargs_ && !this->varargs_are_lowered_)
9433 {
9434 if (!fntype->is_varargs())
9435 {
9436 error_at(this->location(),
9437 _("invalid use of %<...%> calling non-variadic function"));
9438 this->set_is_error();
9439 return;
9440 }
9441 }
e440a328 9442
9443 const Typed_identifier_list* parameters = fntype->parameters();
9444 if (this->args_ == NULL)
9445 {
9446 if (parameters != NULL && !parameters->empty())
9447 this->report_error(_("not enough arguments"));
9448 }
9449 else if (parameters == NULL)
09ea332d 9450 {
9451 if (!is_method || this->args_->size() > 1)
9452 this->report_error(_("too many arguments"));
9453 }
e440a328 9454 else
9455 {
9456 int i = 0;
09ea332d 9457 Expression_list::const_iterator pa = this->args_->begin();
9458 if (is_method)
9459 ++pa;
9460 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9461 pt != parameters->end();
9462 ++pt, ++pa, ++i)
e440a328 9463 {
09ea332d 9464 if (pa == this->args_->end())
e440a328 9465 {
09ea332d 9466 this->report_error(_("not enough arguments"));
e440a328 9467 return;
9468 }
9469 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9470 (*pa)->location(), false);
9471 }
09ea332d 9472 if (pa != this->args_->end())
9473 this->report_error(_("too many arguments"));
e440a328 9474 }
9475}
9476
9477// Return whether we have to use a temporary variable to ensure that
9478// we evaluate this call expression in order. If the call returns no
ceeb4318 9479// results then it will inevitably be executed last.
e440a328 9480
9481bool
9482Call_expression::do_must_eval_in_order() const
9483{
ceeb4318 9484 return this->result_count() > 0;
e440a328 9485}
9486
e440a328 9487// Get the function and the first argument to use when calling an
9488// interface method.
9489
2387f644 9490Expression*
e440a328 9491Call_expression::interface_method_function(
e440a328 9492 Interface_field_reference_expression* interface_method,
2387f644 9493 Expression** first_arg_ptr)
e440a328 9494{
2387f644 9495 *first_arg_ptr = interface_method->get_underlying_object();
9496 return interface_method->get_function();
e440a328 9497}
9498
9499// Build the call expression.
9500
9501tree
9502Call_expression::do_get_tree(Translate_context* context)
9503{
2c809f8f 9504 if (this->call_ != NULL)
9505 return expr_to_tree(this->call_);
e440a328 9506
9507 Function_type* fntype = this->get_function_type();
9508 if (fntype == NULL)
9509 return error_mark_node;
9510
9511 if (this->fn_->is_error_expression())
9512 return error_mark_node;
9513
9514 Gogo* gogo = context->gogo();
b13c66cd 9515 Location location = this->location();
e440a328 9516
9517 Func_expression* func = this->fn_->func_expression();
e440a328 9518 Interface_field_reference_expression* interface_method =
9519 this->fn_->interface_field_reference_expression();
9520 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9521 const bool is_interface_method = interface_method != NULL;
e440a328 9522
f8bdf81a 9523 bool has_closure_arg;
8381eda7 9524 if (has_closure)
f8bdf81a 9525 has_closure_arg = true;
8381eda7 9526 else if (func != NULL)
f8bdf81a 9527 has_closure_arg = false;
8381eda7 9528 else if (is_interface_method)
f8bdf81a 9529 has_closure_arg = false;
8381eda7 9530 else
f8bdf81a 9531 has_closure_arg = true;
8381eda7 9532
e440a328 9533 int nargs;
2c809f8f 9534 std::vector<Bexpression*> fn_args;
e440a328 9535 if (this->args_ == NULL || this->args_->empty())
9536 {
f8bdf81a 9537 nargs = is_interface_method ? 1 : 0;
2c809f8f 9538 if (nargs > 0)
9539 fn_args.resize(1);
e440a328 9540 }
09ea332d 9541 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9542 {
9543 // Passing a receiver parameter.
9544 go_assert(!is_interface_method
9545 && fntype->is_method()
9546 && this->args_->size() == 1);
f8bdf81a 9547 nargs = 1;
2c809f8f 9548 fn_args.resize(1);
9549 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
09ea332d 9550 }
e440a328 9551 else
9552 {
9553 const Typed_identifier_list* params = fntype->parameters();
e440a328 9554
9555 nargs = this->args_->size();
09ea332d 9556 int i = is_interface_method ? 1 : 0;
e440a328 9557 nargs += i;
2c809f8f 9558 fn_args.resize(nargs);
e440a328 9559
9560 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 9561 Expression_list::const_iterator pe = this->args_->begin();
9562 if (!is_interface_method && fntype->is_method())
9563 {
2c809f8f 9564 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
09ea332d 9565 ++pe;
9566 ++i;
9567 }
9568 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 9569 {
c484d925 9570 go_assert(pp != params->end());
2c809f8f 9571 Expression* arg =
9572 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9573 location);
9574 fn_args[i] = tree_to_expr(arg->get_tree(context));
e440a328 9575 }
c484d925 9576 go_assert(pp == params->end());
f8bdf81a 9577 go_assert(i == nargs);
e440a328 9578 }
9579
2c809f8f 9580 Expression* fn;
9581 Expression* closure = NULL;
8381eda7 9582 if (func != NULL)
9583 {
9584 Named_object* no = func->named_object();
2c809f8f 9585 fn = Expression::make_func_code_reference(no, location);
9586 if (has_closure)
9587 closure = func->closure();
8381eda7 9588 }
09ea332d 9589 else if (!is_interface_method)
8381eda7 9590 {
2c809f8f 9591 closure = this->fn_;
9592
9593 // The backend representation of this function type is a pointer
9594 // to a struct whose first field is the actual function to call.
9595 Type* pfntype =
9596 Type::make_pointer_type(
9597 Type::make_pointer_type(Type::make_void_type()));
9598 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9599 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9600 }
e440a328 9601 else
cf609de4 9602 {
2387f644 9603 Expression* first_arg;
2c809f8f 9604 fn = this->interface_method_function(interface_method, &first_arg);
9605 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
e440a328 9606 }
9607
f8bdf81a 9608 if (!has_closure_arg)
2c809f8f 9609 go_assert(closure == NULL);
f8bdf81a 9610 else
9611 {
9612 // Pass the closure argument by calling the function function
9613 // __go_set_closure. In the order_evaluations pass we have
9614 // ensured that if any parameters contain call expressions, they
9615 // will have been moved out to temporary variables.
2c809f8f 9616 go_assert(closure != NULL);
9617 Expression* set_closure =
9618 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9619 fn = Expression::make_compound(set_closure, fn, location);
f8bdf81a 9620 }
9621
2c809f8f 9622 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
80d1e1a8 9623
9624 // When not calling a named function directly, use a type conversion
9625 // in case the type of the function is a recursive type which refers
9626 // to itself. We don't do this for an interface method because 1)
9627 // an interface method never refers to itself, so we always have a
9628 // function type here; 2) we pass an extra first argument to an
9629 // interface method, so fntype is not correct.
9630 if (func == NULL && !is_interface_method)
9631 {
9632 Btype* bft = fntype->get_backend_fntype(gogo);
9633 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9634 }
9635
2c809f8f 9636 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
e440a328 9637
2c809f8f 9638 if (this->results_ != NULL)
e440a328 9639 {
2c809f8f 9640 go_assert(this->call_temp_ != NULL);
9641 Expression* call_ref =
9642 Expression::make_temporary_reference(this->call_temp_, location);
9643 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9644 Bstatement* assn_stmt =
9645 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 9646
2c809f8f 9647 this->call_ = this->set_results(context, bcall_ref);
e440a328 9648
2c809f8f 9649 Bexpression* set_and_call =
9650 gogo->backend()->compound_expression(assn_stmt, this->call_,
9651 location);
9652 return expr_to_tree(set_and_call);
9653 }
e440a328 9654
2c809f8f 9655 this->call_ = call;
9656 return expr_to_tree(this->call_);
e440a328 9657}
9658
ceeb4318 9659// Set the result variables if this call returns multiple results.
9660
2c809f8f 9661Bexpression*
9662Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 9663{
2c809f8f 9664 Gogo* gogo = context->gogo();
ceeb4318 9665
2c809f8f 9666 Bexpression* results = NULL;
b13c66cd 9667 Location loc = this->location();
2c809f8f 9668
ceeb4318 9669 size_t rc = this->result_count();
2c809f8f 9670 for (size_t i = 0; i < rc; ++i)
ceeb4318 9671 {
ceeb4318 9672 Temporary_statement* temp = this->result(i);
cd238b8d 9673 if (temp == NULL)
9674 {
9675 go_assert(saw_errors());
2c809f8f 9676 return gogo->backend()->error_expression();
cd238b8d 9677 }
ceeb4318 9678 Temporary_reference_expression* ref =
9679 Expression::make_temporary_reference(temp, loc);
9680 ref->set_is_lvalue();
ceeb4318 9681
2c809f8f 9682 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9683 Bexpression* call_result =
9684 gogo->backend()->struct_field_expression(call, i, loc);
9685 Bstatement* assn_stmt =
9686 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 9687
2c809f8f 9688 Bexpression* result =
9689 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 9690
2c809f8f 9691 if (results == NULL)
9692 results = result;
9693 else
9694 {
9695 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9696 results =
9697 gogo->backend()->compound_expression(expr_stmt, results, loc);
9698 }
9699 }
9700 return results;
ceeb4318 9701}
9702
d751bb78 9703// Dump ast representation for a call expressin.
9704
9705void
9706Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9707{
9708 this->fn_->dump_expression(ast_dump_context);
9709 ast_dump_context->ostream() << "(";
9710 if (args_ != NULL)
9711 ast_dump_context->dump_expression_list(this->args_);
9712
9713 ast_dump_context->ostream() << ") ";
9714}
9715
e440a328 9716// Make a call expression.
9717
9718Call_expression*
9719Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 9720 Location location)
e440a328 9721{
9722 return new Call_expression(fn, args, is_varargs, location);
9723}
9724
9725// A single result from a call which returns multiple results.
9726
9727class Call_result_expression : public Expression
9728{
9729 public:
9730 Call_result_expression(Call_expression* call, unsigned int index)
9731 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9732 call_(call), index_(index)
9733 { }
9734
9735 protected:
9736 int
9737 do_traverse(Traverse*);
9738
9739 Type*
9740 do_type();
9741
9742 void
9743 do_determine_type(const Type_context*);
9744
9745 void
9746 do_check_types(Gogo*);
9747
9748 Expression*
9749 do_copy()
9750 {
9751 return new Call_result_expression(this->call_->call_expression(),
9752 this->index_);
9753 }
9754
9755 bool
9756 do_must_eval_in_order() const
9757 { return true; }
9758
9759 tree
9760 do_get_tree(Translate_context*);
9761
d751bb78 9762 void
9763 do_dump_expression(Ast_dump_context*) const;
9764
e440a328 9765 private:
9766 // The underlying call expression.
9767 Expression* call_;
9768 // Which result we want.
9769 unsigned int index_;
9770};
9771
9772// Traverse a call result.
9773
9774int
9775Call_result_expression::do_traverse(Traverse* traverse)
9776{
9777 if (traverse->remember_expression(this->call_))
9778 {
9779 // We have already traversed the call expression.
9780 return TRAVERSE_CONTINUE;
9781 }
9782 return Expression::traverse(&this->call_, traverse);
9783}
9784
9785// Get the type.
9786
9787Type*
9788Call_result_expression::do_type()
9789{
425dd051 9790 if (this->classification() == EXPRESSION_ERROR)
9791 return Type::make_error_type();
9792
e440a328 9793 // THIS->CALL_ can be replaced with a temporary reference due to
9794 // Call_expression::do_must_eval_in_order when there is an error.
9795 Call_expression* ce = this->call_->call_expression();
9796 if (ce == NULL)
5e85f268 9797 {
9798 this->set_is_error();
9799 return Type::make_error_type();
9800 }
e440a328 9801 Function_type* fntype = ce->get_function_type();
9802 if (fntype == NULL)
5e85f268 9803 {
e37658e2 9804 if (ce->issue_error())
99b3f06f 9805 {
9806 if (!ce->fn()->type()->is_error())
9807 this->report_error(_("expected function"));
9808 }
5e85f268 9809 this->set_is_error();
9810 return Type::make_error_type();
9811 }
e440a328 9812 const Typed_identifier_list* results = fntype->results();
ceeb4318 9813 if (results == NULL || results->size() < 2)
7b8d861f 9814 {
ceeb4318 9815 if (ce->issue_error())
9816 this->report_error(_("number of results does not match "
9817 "number of values"));
7b8d861f 9818 return Type::make_error_type();
9819 }
e440a328 9820 Typed_identifier_list::const_iterator pr = results->begin();
9821 for (unsigned int i = 0; i < this->index_; ++i)
9822 {
9823 if (pr == results->end())
425dd051 9824 break;
e440a328 9825 ++pr;
9826 }
9827 if (pr == results->end())
425dd051 9828 {
ceeb4318 9829 if (ce->issue_error())
9830 this->report_error(_("number of results does not match "
9831 "number of values"));
425dd051 9832 return Type::make_error_type();
9833 }
e440a328 9834 return pr->type();
9835}
9836
425dd051 9837// Check the type. Just make sure that we trigger the warning in
9838// do_type.
e440a328 9839
9840void
9841Call_result_expression::do_check_types(Gogo*)
9842{
425dd051 9843 this->type();
e440a328 9844}
9845
9846// Determine the type. We have nothing to do here, but the 0 result
9847// needs to pass down to the caller.
9848
9849void
9850Call_result_expression::do_determine_type(const Type_context*)
9851{
fb94b0ca 9852 this->call_->determine_type_no_context();
e440a328 9853}
9854
ceeb4318 9855// Return the tree. We just refer to the temporary set by the call
9856// expression. We don't do this at lowering time because it makes it
9857// hard to evaluate the call at the right time.
e440a328 9858
9859tree
9860Call_result_expression::do_get_tree(Translate_context* context)
9861{
ceeb4318 9862 Call_expression* ce = this->call_->call_expression();
cd238b8d 9863 if (ce == NULL)
9864 {
9865 go_assert(this->call_->is_error_expression());
9866 return error_mark_node;
9867 }
ceeb4318 9868 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 9869 if (ts == NULL)
9870 {
9871 go_assert(saw_errors());
9872 return error_mark_node;
9873 }
ceeb4318 9874 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9875 return ref->get_tree(context);
e440a328 9876}
9877
d751bb78 9878// Dump ast representation for a call result expression.
9879
9880void
9881Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9882 const
9883{
9884 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9885 // (struct) and the fields are referenced instead.
9886 ast_dump_context->ostream() << this->index_ << "@(";
9887 ast_dump_context->dump_expression(this->call_);
9888 ast_dump_context->ostream() << ")";
9889}
9890
e440a328 9891// Make a reference to a single result of a call which returns
9892// multiple results.
9893
9894Expression*
9895Expression::make_call_result(Call_expression* call, unsigned int index)
9896{
9897 return new Call_result_expression(call, index);
9898}
9899
9900// Class Index_expression.
9901
9902// Traversal.
9903
9904int
9905Index_expression::do_traverse(Traverse* traverse)
9906{
9907 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9908 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9909 || (this->end_ != NULL
acf2b673 9910 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9911 || (this->cap_ != NULL
9912 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 9913 return TRAVERSE_EXIT;
9914 return TRAVERSE_CONTINUE;
9915}
9916
9917// Lower an index expression. This converts the generic index
9918// expression into an array index, a string index, or a map index.
9919
9920Expression*
ceeb4318 9921Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 9922{
b13c66cd 9923 Location location = this->location();
e440a328 9924 Expression* left = this->left_;
9925 Expression* start = this->start_;
9926 Expression* end = this->end_;
acf2b673 9927 Expression* cap = this->cap_;
e440a328 9928
9929 Type* type = left->type();
5c13bd80 9930 if (type->is_error())
e440a328 9931 return Expression::make_error(location);
b0cf7ddd 9932 else if (left->is_type_expression())
9933 {
9934 error_at(location, "attempt to index type expression");
9935 return Expression::make_error(location);
9936 }
e440a328 9937 else if (type->array_type() != NULL)
acf2b673 9938 return Expression::make_array_index(left, start, end, cap, location);
e440a328 9939 else if (type->points_to() != NULL
9940 && type->points_to()->array_type() != NULL
411eb89e 9941 && !type->points_to()->is_slice_type())
e440a328 9942 {
9943 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9944 location);
38092374 9945
9946 // For an ordinary index into the array, the pointer will be
9947 // dereferenced. For a slice it will not--the resulting slice
9948 // will simply reuse the pointer, which is incorrect if that
9949 // pointer is nil.
9950 if (end != NULL || cap != NULL)
9951 deref->issue_nil_check();
9952
acf2b673 9953 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 9954 }
9955 else if (type->is_string_type())
acf2b673 9956 {
9957 if (cap != NULL)
9958 {
9959 error_at(location, "invalid 3-index slice of string");
9960 return Expression::make_error(location);
9961 }
9962 return Expression::make_string_index(left, start, end, location);
9963 }
e440a328 9964 else if (type->map_type() != NULL)
9965 {
acf2b673 9966 if (end != NULL || cap != NULL)
e440a328 9967 {
9968 error_at(location, "invalid slice of map");
9969 return Expression::make_error(location);
9970 }
6d4c2432 9971 Map_index_expression* ret = Expression::make_map_index(left, start,
9972 location);
e440a328 9973 if (this->is_lvalue_)
9974 ret->set_is_lvalue();
9975 return ret;
9976 }
9977 else
9978 {
9979 error_at(location,
9980 "attempt to index object which is not array, string, or map");
9981 return Expression::make_error(location);
9982 }
9983}
9984
acf2b673 9985// Write an indexed expression
9986// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 9987
9988void
9989Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9990 const Expression* expr,
9991 const Expression* start,
acf2b673 9992 const Expression* end,
9993 const Expression* cap)
d751bb78 9994{
9995 expr->dump_expression(ast_dump_context);
9996 ast_dump_context->ostream() << "[";
9997 start->dump_expression(ast_dump_context);
9998 if (end != NULL)
9999 {
10000 ast_dump_context->ostream() << ":";
10001 end->dump_expression(ast_dump_context);
10002 }
acf2b673 10003 if (cap != NULL)
10004 {
10005 ast_dump_context->ostream() << ":";
10006 cap->dump_expression(ast_dump_context);
10007 }
d751bb78 10008 ast_dump_context->ostream() << "]";
10009}
10010
10011// Dump ast representation for an index expression.
10012
10013void
10014Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10015 const
10016{
10017 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 10018 this->start_, this->end_, this->cap_);
d751bb78 10019}
10020
e440a328 10021// Make an index expression.
10022
10023Expression*
10024Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 10025 Expression* cap, Location location)
e440a328 10026{
acf2b673 10027 return new Index_expression(left, start, end, cap, location);
e440a328 10028}
10029
10030// An array index. This is used for both indexing and slicing.
10031
10032class Array_index_expression : public Expression
10033{
10034 public:
10035 Array_index_expression(Expression* array, Expression* start,
acf2b673 10036 Expression* end, Expression* cap, Location location)
e440a328 10037 : Expression(EXPRESSION_ARRAY_INDEX, location),
acf2b673 10038 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
e440a328 10039 { }
10040
10041 protected:
10042 int
10043 do_traverse(Traverse*);
10044
2c809f8f 10045 Expression*
10046 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10047
e440a328 10048 Type*
10049 do_type();
10050
10051 void
10052 do_determine_type(const Type_context*);
10053
10054 void
10055 do_check_types(Gogo*);
10056
10057 Expression*
10058 do_copy()
10059 {
10060 return Expression::make_array_index(this->array_->copy(),
10061 this->start_->copy(),
10062 (this->end_ == NULL
10063 ? NULL
10064 : this->end_->copy()),
acf2b673 10065 (this->cap_ == NULL
10066 ? NULL
10067 : this->cap_->copy()),
e440a328 10068 this->location());
10069 }
10070
baef9f7a 10071 bool
10072 do_must_eval_subexpressions_in_order(int* skip) const
10073 {
10074 *skip = 1;
10075 return true;
10076 }
10077
e440a328 10078 bool
10079 do_is_addressable() const;
10080
10081 void
10082 do_address_taken(bool escapes)
10083 { this->array_->address_taken(escapes); }
10084
56080003 10085 void
10086 do_issue_nil_check()
10087 { this->array_->issue_nil_check(); }
10088
e440a328 10089 tree
10090 do_get_tree(Translate_context*);
10091
d751bb78 10092 void
10093 do_dump_expression(Ast_dump_context*) const;
10094
e440a328 10095 private:
10096 // The array we are getting a value from.
10097 Expression* array_;
10098 // The start or only index.
10099 Expression* start_;
10100 // The end index of a slice. This may be NULL for a simple array
10101 // index, or it may be a nil expression for the length of the array.
10102 Expression* end_;
acf2b673 10103 // The capacity argument of a slice. This may be NULL for an array index or
10104 // slice.
10105 Expression* cap_;
e440a328 10106 // The type of the expression.
10107 Type* type_;
10108};
10109
10110// Array index traversal.
10111
10112int
10113Array_index_expression::do_traverse(Traverse* traverse)
10114{
10115 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10116 return TRAVERSE_EXIT;
10117 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10118 return TRAVERSE_EXIT;
10119 if (this->end_ != NULL)
10120 {
10121 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10122 return TRAVERSE_EXIT;
10123 }
acf2b673 10124 if (this->cap_ != NULL)
10125 {
10126 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10127 return TRAVERSE_EXIT;
10128 }
e440a328 10129 return TRAVERSE_CONTINUE;
10130}
10131
10132// Return the type of an array index.
10133
10134Type*
10135Array_index_expression::do_type()
10136{
10137 if (this->type_ == NULL)
10138 {
10139 Array_type* type = this->array_->type()->array_type();
10140 if (type == NULL)
10141 this->type_ = Type::make_error_type();
10142 else if (this->end_ == NULL)
10143 this->type_ = type->element_type();
411eb89e 10144 else if (type->is_slice_type())
e440a328 10145 {
10146 // A slice of a slice has the same type as the original
10147 // slice.
10148 this->type_ = this->array_->type()->deref();
10149 }
10150 else
10151 {
10152 // A slice of an array is a slice.
10153 this->type_ = Type::make_array_type(type->element_type(), NULL);
10154 }
10155 }
10156 return this->type_;
10157}
10158
10159// Set the type of an array index.
10160
10161void
10162Array_index_expression::do_determine_type(const Type_context*)
10163{
10164 this->array_->determine_type_no_context();
7917ad68 10165 this->start_->determine_type_no_context();
e440a328 10166 if (this->end_ != NULL)
7917ad68 10167 this->end_->determine_type_no_context();
acf2b673 10168 if (this->cap_ != NULL)
10169 this->cap_->determine_type_no_context();
e440a328 10170}
10171
10172// Check types of an array index.
10173
10174void
10175Array_index_expression::do_check_types(Gogo*)
10176{
f6bc81e6 10177 Numeric_constant nc;
10178 unsigned long v;
10179 if (this->start_->type()->integer_type() == NULL
10180 && !this->start_->type()->is_error()
10181 && (!this->start_->numeric_constant_value(&nc)
10182 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10183 this->report_error(_("index must be integer"));
10184 if (this->end_ != NULL
10185 && this->end_->type()->integer_type() == NULL
99b3f06f 10186 && !this->end_->type()->is_error()
10187 && !this->end_->is_nil_expression()
f6bc81e6 10188 && !this->end_->is_error_expression()
10189 && (!this->end_->numeric_constant_value(&nc)
10190 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10191 this->report_error(_("slice end must be integer"));
acf2b673 10192 if (this->cap_ != NULL
10193 && this->cap_->type()->integer_type() == NULL
10194 && !this->cap_->type()->is_error()
10195 && !this->cap_->is_nil_expression()
10196 && !this->cap_->is_error_expression()
10197 && (!this->cap_->numeric_constant_value(&nc)
10198 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10199 this->report_error(_("slice capacity must be integer"));
e440a328 10200
10201 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10202 if (array_type == NULL)
10203 {
c484d925 10204 go_assert(this->array_->type()->is_error());
f9c68f17 10205 return;
10206 }
e440a328 10207
10208 unsigned int int_bits =
10209 Type::lookup_integer_type("int")->integer_type()->bits();
10210
0c77715b 10211 Numeric_constant lvalnc;
e440a328 10212 mpz_t lval;
e440a328 10213 bool lval_valid = (array_type->length() != NULL
0c77715b 10214 && array_type->length()->numeric_constant_value(&lvalnc)
10215 && lvalnc.to_int(&lval));
10216 Numeric_constant inc;
e440a328 10217 mpz_t ival;
0bd5d859 10218 bool ival_valid = false;
0c77715b 10219 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10220 {
0bd5d859 10221 ival_valid = true;
e440a328 10222 if (mpz_sgn(ival) < 0
10223 || mpz_sizeinbase(ival, 2) >= int_bits
10224 || (lval_valid
10225 && (this->end_ == NULL
10226 ? mpz_cmp(ival, lval) >= 0
10227 : mpz_cmp(ival, lval) > 0)))
10228 {
10229 error_at(this->start_->location(), "array index out of bounds");
10230 this->set_is_error();
10231 }
10232 }
10233 if (this->end_ != NULL && !this->end_->is_nil_expression())
10234 {
0c77715b 10235 Numeric_constant enc;
10236 mpz_t eval;
acf2b673 10237 bool eval_valid = false;
0c77715b 10238 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10239 {
acf2b673 10240 eval_valid = true;
0c77715b 10241 if (mpz_sgn(eval) < 0
10242 || mpz_sizeinbase(eval, 2) >= int_bits
10243 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10244 {
10245 error_at(this->end_->location(), "array index out of bounds");
10246 this->set_is_error();
10247 }
0bd5d859 10248 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10249 this->report_error(_("inverted slice range"));
e440a328 10250 }
acf2b673 10251
10252 Numeric_constant cnc;
10253 mpz_t cval;
10254 if (this->cap_ != NULL
10255 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10256 {
10257 if (mpz_sgn(cval) < 0
10258 || mpz_sizeinbase(cval, 2) >= int_bits
10259 || (lval_valid && mpz_cmp(cval, lval) > 0))
10260 {
10261 error_at(this->cap_->location(), "array index out of bounds");
10262 this->set_is_error();
10263 }
10264 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10265 {
10266 error_at(this->cap_->location(),
10267 "invalid slice index: capacity less than start");
10268 this->set_is_error();
10269 }
10270 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10271 {
10272 error_at(this->cap_->location(),
10273 "invalid slice index: capacity less than length");
10274 this->set_is_error();
10275 }
10276 mpz_clear(cval);
10277 }
10278
10279 if (eval_valid)
10280 mpz_clear(eval);
e440a328 10281 }
0bd5d859 10282 if (ival_valid)
10283 mpz_clear(ival);
0c77715b 10284 if (lval_valid)
10285 mpz_clear(lval);
e440a328 10286
10287 // A slice of an array requires an addressable array. A slice of a
10288 // slice is always possible.
411eb89e 10289 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10290 {
10291 if (!this->array_->is_addressable())
8da39c3b 10292 this->report_error(_("slice of unaddressable value"));
88ec30c8 10293 else
10294 this->array_->address_taken(true);
10295 }
e440a328 10296}
10297
2c809f8f 10298// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10299
10300Expression*
10301Array_index_expression::do_flatten(Gogo*, Named_object*,
10302 Statement_inserter* inserter)
10303{
10304 Location loc = this->location();
2c809f8f 10305 Temporary_statement* temp;
35a54f17 10306 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10307 {
2c809f8f 10308 temp = Statement::make_temporary(NULL, this->array_, loc);
35a54f17 10309 inserter->insert(temp);
10310 this->array_ = Expression::make_temporary_reference(temp, loc);
10311 }
2c809f8f 10312 if (!this->start_->is_variable())
10313 {
10314 temp = Statement::make_temporary(NULL, this->start_, loc);
10315 inserter->insert(temp);
10316 this->start_ = Expression::make_temporary_reference(temp, loc);
10317 }
10318 if (this->end_ != NULL
10319 && !this->end_->is_nil_expression()
10320 && !this->end_->is_variable())
10321 {
10322 temp = Statement::make_temporary(NULL, this->end_, loc);
10323 inserter->insert(temp);
10324 this->end_ = Expression::make_temporary_reference(temp, loc);
10325 }
10326 if (this->cap_ != NULL && !this->cap_->is_variable())
10327 {
10328 temp = Statement::make_temporary(NULL, this->cap_, loc);
10329 inserter->insert(temp);
10330 this->cap_ = Expression::make_temporary_reference(temp, loc);
10331 }
10332
35a54f17 10333 return this;
10334}
10335
e440a328 10336// Return whether this expression is addressable.
10337
10338bool
10339Array_index_expression::do_is_addressable() const
10340{
10341 // A slice expression is not addressable.
10342 if (this->end_ != NULL)
10343 return false;
10344
10345 // An index into a slice is addressable.
411eb89e 10346 if (this->array_->type()->is_slice_type())
e440a328 10347 return true;
10348
10349 // An index into an array is addressable if the array is
10350 // addressable.
10351 return this->array_->is_addressable();
10352}
10353
10354// Get a tree for an array index.
10355
10356tree
10357Array_index_expression::do_get_tree(Translate_context* context)
10358{
e440a328 10359 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10360 if (array_type == NULL)
10361 {
c484d925 10362 go_assert(this->array_->type()->is_error());
d8cd8e2d 10363 return error_mark_node;
10364 }
35a54f17 10365 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10366
2c809f8f 10367 Location loc = this->location();
10368 Gogo* gogo = context->gogo();
10369
10370 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
e440a328 10371
2c809f8f 10372 // We need to convert the length and capacity to the Go "int" type here
10373 // because the length of a fixed-length array could be of type "uintptr"
10374 // and gimple disallows binary operations between "uintptr" and other
10375 // integer types. FIXME.
10376 Bexpression* length = NULL;
a04bfdfc 10377 if (this->end_ == NULL || this->end_->is_nil_expression())
10378 {
35a54f17 10379 Expression* len = array_type->get_length(gogo, this->array_);
2c809f8f 10380 length = tree_to_expr(len->get_tree(context));
10381 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10382 }
10383
2c809f8f 10384 Bexpression* capacity = NULL;
a04bfdfc 10385 if (this->end_ != NULL)
10386 {
35a54f17 10387 Expression* cap = array_type->get_capacity(gogo, this->array_);
2c809f8f 10388 capacity = tree_to_expr(cap->get_tree(context));
10389 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10390 }
10391
2c809f8f 10392 Bexpression* cap_arg = capacity;
acf2b673 10393 if (this->cap_ != NULL)
10394 {
2c809f8f 10395 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10396 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10397 }
10398
2c809f8f 10399 if (length == NULL)
10400 length = cap_arg;
e440a328 10401
10402 int code = (array_type->length() != NULL
10403 ? (this->end_ == NULL
10404 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10405 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10406 : (this->end_ == NULL
10407 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10408 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
2c809f8f 10409 Bexpression* crash =
10410 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10411
10412 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10413 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10414
10415 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10416 start = gogo->backend()->convert_expression(int_btype, start, loc);
10417 Bexpression* start_too_large =
10418 gogo->backend()->binary_expression((this->end_ == NULL
10419 ? OPERATOR_GE
10420 : OPERATOR_GT),
10421 start,
10422 (this->end_ == NULL
10423 ? length
10424 : capacity),
10425 loc);
10426 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10427 bad_index, loc);
e440a328 10428
10429 if (this->end_ == NULL)
10430 {
10431 // Simple array indexing. This has to return an l-value, so
2c809f8f 10432 // wrap the index check into START.
10433 start =
10434 gogo->backend()->conditional_expression(int_btype, bad_index,
10435 crash, start, loc);
e440a328 10436
2c809f8f 10437 Bexpression* ret;
e440a328 10438 if (array_type->length() != NULL)
10439 {
2c809f8f 10440 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10441 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10442 }
10443 else
10444 {
2c809f8f 10445 // Slice.
10446 Expression* valptr =
35a54f17 10447 array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10448 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10449 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10450 ret = gogo->backend()->indirect_expression(ptr, true, loc);
e440a328 10451 }
2c809f8f 10452 return expr_to_tree(ret);
e440a328 10453 }
10454
10455 // Array slice.
10456
acf2b673 10457 if (this->cap_ != NULL)
10458 {
2c809f8f 10459 bounds_check = Expression::check_bounds(this->cap_, loc);
10460 Bexpression* bounds_bcheck =
10461 tree_to_expr(bounds_check->get_tree(context));
10462 bad_index =
10463 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10464 bad_index, loc);
10465 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10466
10467 Bexpression* cap_too_small =
10468 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10469 Bexpression* cap_too_large =
10470 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10471 Bexpression* bad_cap =
10472 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10473 cap_too_large, loc);
10474 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10475 bad_index, loc);
10476 }
10477
10478 Bexpression* end;
e440a328 10479 if (this->end_->is_nil_expression())
2c809f8f 10480 end = length;
e440a328 10481 else
10482 {
2c809f8f 10483 bounds_check = Expression::check_bounds(this->end_, loc);
10484 Bexpression* bounds_bcheck =
10485 tree_to_expr(bounds_check->get_tree(context));
e440a328 10486
2c809f8f 10487 bad_index =
10488 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10489 bad_index, loc);
e440a328 10490
2c809f8f 10491 end = tree_to_expr(this->end_->get_tree(context));
10492 end = gogo->backend()->convert_expression(int_btype, end, loc);
10493 Bexpression* end_too_small =
10494 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10495 Bexpression* end_too_large =
10496 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10497 Bexpression* bad_end =
10498 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10499 end_too_large, loc);
10500 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10501 bad_index, loc);
e440a328 10502 }
10503
35a54f17 10504 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
2c809f8f 10505 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10506 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10507
2c809f8f 10508 Bexpression* result_length =
10509 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10510
2c809f8f 10511 Bexpression* result_capacity =
10512 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10513
2c809f8f 10514 Btype* struct_btype = this->type()->get_backend(gogo);
10515 std::vector<Bexpression*> init;
10516 init.push_back(val);
10517 init.push_back(result_length);
10518 init.push_back(result_capacity);
e440a328 10519
2c809f8f 10520 Bexpression* ctor =
10521 gogo->backend()->constructor_expression(struct_btype, init, loc);
10522 Bexpression* ret =
10523 gogo->backend()->conditional_expression(struct_btype, bad_index,
10524 crash, ctor, loc);
e440a328 10525
2c809f8f 10526 return expr_to_tree(ret);
e440a328 10527}
10528
d751bb78 10529// Dump ast representation for an array index expression.
10530
10531void
10532Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10533 const
10534{
10535 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10536 this->start_, this->end_, this->cap_);
d751bb78 10537}
10538
acf2b673 10539// Make an array index expression. END and CAP may be NULL.
e440a328 10540
10541Expression*
10542Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10543 Expression* end, Expression* cap,
10544 Location location)
e440a328 10545{
acf2b673 10546 return new Array_index_expression(array, start, end, cap, location);
e440a328 10547}
10548
10549// A string index. This is used for both indexing and slicing.
10550
10551class String_index_expression : public Expression
10552{
10553 public:
10554 String_index_expression(Expression* string, Expression* start,
b13c66cd 10555 Expression* end, Location location)
e440a328 10556 : Expression(EXPRESSION_STRING_INDEX, location),
10557 string_(string), start_(start), end_(end)
10558 { }
10559
10560 protected:
10561 int
10562 do_traverse(Traverse*);
10563
2c809f8f 10564 Expression*
10565 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10566
e440a328 10567 Type*
10568 do_type();
10569
10570 void
10571 do_determine_type(const Type_context*);
10572
10573 void
10574 do_check_types(Gogo*);
10575
10576 Expression*
10577 do_copy()
10578 {
10579 return Expression::make_string_index(this->string_->copy(),
10580 this->start_->copy(),
10581 (this->end_ == NULL
10582 ? NULL
10583 : this->end_->copy()),
10584 this->location());
10585 }
10586
baef9f7a 10587 bool
10588 do_must_eval_subexpressions_in_order(int* skip) const
10589 {
10590 *skip = 1;
10591 return true;
10592 }
10593
e440a328 10594 tree
10595 do_get_tree(Translate_context*);
10596
d751bb78 10597 void
10598 do_dump_expression(Ast_dump_context*) const;
10599
e440a328 10600 private:
10601 // The string we are getting a value from.
10602 Expression* string_;
10603 // The start or only index.
10604 Expression* start_;
10605 // The end index of a slice. This may be NULL for a single index,
10606 // or it may be a nil expression for the length of the string.
10607 Expression* end_;
10608};
10609
10610// String index traversal.
10611
10612int
10613String_index_expression::do_traverse(Traverse* traverse)
10614{
10615 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10616 return TRAVERSE_EXIT;
10617 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10618 return TRAVERSE_EXIT;
10619 if (this->end_ != NULL)
10620 {
10621 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10622 return TRAVERSE_EXIT;
10623 }
10624 return TRAVERSE_CONTINUE;
10625}
10626
2c809f8f 10627Expression*
10628String_index_expression::do_flatten(Gogo*, Named_object*,
10629 Statement_inserter* inserter)
e440a328 10630{
2c809f8f 10631 Temporary_statement* temp;
10632 Location loc = this->location();
10633 if (!this->string_->is_variable())
10634 {
10635 temp = Statement::make_temporary(NULL, this->string_, loc);
10636 inserter->insert(temp);
10637 this->string_ = Expression::make_temporary_reference(temp, loc);
10638 }
10639 if (!this->start_->is_variable())
10640 {
10641 temp = Statement::make_temporary(NULL, this->start_, loc);
10642 inserter->insert(temp);
10643 this->start_ = Expression::make_temporary_reference(temp, loc);
10644 }
10645 if (this->end_ != NULL
10646 && !this->end_->is_nil_expression()
10647 && !this->end_->is_variable())
10648 {
10649 temp = Statement::make_temporary(NULL, this->end_, loc);
10650 inserter->insert(temp);
10651 this->end_ = Expression::make_temporary_reference(temp, loc);
10652 }
10653
10654 return this;
10655}
10656
10657// Return the type of a string index.
10658
10659Type*
10660String_index_expression::do_type()
10661{
10662 if (this->end_ == NULL)
10663 return Type::lookup_integer_type("uint8");
10664 else
10665 return this->string_->type();
10666}
10667
10668// Determine the type of a string index.
10669
10670void
10671String_index_expression::do_determine_type(const Type_context*)
10672{
10673 this->string_->determine_type_no_context();
10674 this->start_->determine_type_no_context();
e440a328 10675 if (this->end_ != NULL)
93000773 10676 this->end_->determine_type_no_context();
e440a328 10677}
10678
10679// Check types of a string index.
10680
10681void
10682String_index_expression::do_check_types(Gogo*)
10683{
acdc230d 10684 Numeric_constant nc;
10685 unsigned long v;
10686 if (this->start_->type()->integer_type() == NULL
10687 && !this->start_->type()->is_error()
10688 && (!this->start_->numeric_constant_value(&nc)
10689 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10690 this->report_error(_("index must be integer"));
10691 if (this->end_ != NULL
10692 && this->end_->type()->integer_type() == NULL
acdc230d 10693 && !this->end_->type()->is_error()
10694 && !this->end_->is_nil_expression()
10695 && !this->end_->is_error_expression()
10696 && (!this->end_->numeric_constant_value(&nc)
10697 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10698 this->report_error(_("slice end must be integer"));
10699
10700 std::string sval;
10701 bool sval_valid = this->string_->string_constant_value(&sval);
10702
0c77715b 10703 Numeric_constant inc;
e440a328 10704 mpz_t ival;
0bd5d859 10705 bool ival_valid = false;
0c77715b 10706 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10707 {
0bd5d859 10708 ival_valid = true;
e440a328 10709 if (mpz_sgn(ival) < 0
10710 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10711 {
10712 error_at(this->start_->location(), "string index out of bounds");
10713 this->set_is_error();
10714 }
10715 }
10716 if (this->end_ != NULL && !this->end_->is_nil_expression())
10717 {
0c77715b 10718 Numeric_constant enc;
10719 mpz_t eval;
10720 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10721 {
0c77715b 10722 if (mpz_sgn(eval) < 0
10723 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 10724 {
10725 error_at(this->end_->location(), "string index out of bounds");
10726 this->set_is_error();
10727 }
0bd5d859 10728 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10729 this->report_error(_("inverted slice range"));
0c77715b 10730 mpz_clear(eval);
e440a328 10731 }
10732 }
0bd5d859 10733 if (ival_valid)
10734 mpz_clear(ival);
e440a328 10735}
10736
10737// Get a tree for a string index.
10738
10739tree
10740String_index_expression::do_get_tree(Translate_context* context)
10741{
b13c66cd 10742 Location loc = this->location();
2c809f8f 10743 Expression* string_arg = this->string_;
10744 if (this->string_->type()->points_to() != NULL)
10745 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 10746
2c809f8f 10747 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 10748
2c809f8f 10749 int code = (this->end_ == NULL
10750 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10751 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 10752
2c809f8f 10753 Gogo* gogo = context->gogo();
10754 Bexpression* crash =
10755 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
1b1f2abf 10756
10757 Type* int_type = Type::lookup_integer_type("int");
e440a328 10758
2c809f8f 10759 // It is possible that an error occurred earlier because the start index
10760 // cannot be represented as an integer type. In this case, we shouldn't
10761 // try casting the starting index into an integer since
10762 // Type_conversion_expression will fail to get the backend representation.
10763 // FIXME.
10764 if (this->start_->type()->integer_type() == NULL
10765 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10766 {
10767 go_assert(saw_errors());
10768 return error_mark_node;
10769 }
e440a328 10770
2c809f8f 10771 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 10772
2c809f8f 10773 if (this->end_ == NULL)
10774 {
10775 Expression* length =
10776 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 10777
2c809f8f 10778 Expression* start_too_large =
10779 Expression::make_binary(OPERATOR_GE, start, length, loc);
10780 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10781 bad_index, loc);
10782 Expression* bytes =
10783 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 10784
2c809f8f 10785 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10786 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10787 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10788 Bexpression* index = gogo->backend()->indirect_expression(ptr, true, loc);
e440a328 10789
2c809f8f 10790 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10791 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10792 Bexpression* ret =
10793 gogo->backend()->conditional_expression(byte_btype, index_error,
10794 crash, index, loc);
10795 return expr_to_tree(ret);
10796 }
10797
10798 Expression* end = NULL;
10799 if (this->end_->is_nil_expression())
e440a328 10800 {
2c809f8f 10801 mpz_t neg_one;
10802 mpz_init_set_si(neg_one, -1);
10803 end = Expression::make_integer(&neg_one, int_type, loc);
10804 mpz_clear(neg_one);
e440a328 10805 }
10806 else
10807 {
2c809f8f 10808 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10809 bad_index =
10810 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10811 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 10812 }
2c809f8f 10813
10814 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10815 string_arg, start, end);
10816 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10817
10818 Btype* str_btype = strslice->type()->get_backend(gogo);
10819 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10820 Bexpression* ret =
10821 gogo->backend()->conditional_expression(str_btype, index_error,
10822 crash, bstrslice, loc);
10823 return expr_to_tree(ret);
e440a328 10824}
10825
d751bb78 10826// Dump ast representation for a string index expression.
10827
10828void
10829String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10830 const
10831{
acf2b673 10832 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10833 this->start_, this->end_, NULL);
d751bb78 10834}
10835
e440a328 10836// Make a string index expression. END may be NULL.
10837
10838Expression*
10839Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 10840 Expression* end, Location location)
e440a328 10841{
10842 return new String_index_expression(string, start, end, location);
10843}
10844
10845// Class Map_index.
10846
10847// Get the type of the map.
10848
10849Map_type*
10850Map_index_expression::get_map_type() const
10851{
10852 Map_type* mt = this->map_->type()->deref()->map_type();
c7524fae 10853 if (mt == NULL)
c484d925 10854 go_assert(saw_errors());
e440a328 10855 return mt;
10856}
10857
10858// Map index traversal.
10859
10860int
10861Map_index_expression::do_traverse(Traverse* traverse)
10862{
10863 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10864 return TRAVERSE_EXIT;
10865 return Expression::traverse(&this->index_, traverse);
10866}
10867
2c809f8f 10868// We need to pass in a pointer to the key, so flatten the index into a
10869// temporary variable if it isn't already. The value pointer will be
10870// dereferenced and checked for nil, so flatten into a temporary to avoid
10871// recomputation.
10872
10873Expression*
10874Map_index_expression::do_flatten(Gogo*, Named_object*,
10875 Statement_inserter* inserter)
10876{
10877 Map_type* mt = this->get_map_type();
10878 if (this->index_->type() != mt->key_type())
10879 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10880 this->location());
10881
10882 if (!this->index_->is_variable())
10883 {
10884 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10885 this->location());
10886 inserter->insert(temp);
10887 this->index_ = Expression::make_temporary_reference(temp,
10888 this->location());
10889 }
10890
10891 if (this->value_pointer_ == NULL)
10892 this->get_value_pointer(this->is_lvalue_);
10893 if (!this->value_pointer_->is_variable())
10894 {
10895 Temporary_statement* temp =
10896 Statement::make_temporary(NULL, this->value_pointer_,
10897 this->location());
10898 inserter->insert(temp);
10899 this->value_pointer_ =
10900 Expression::make_temporary_reference(temp, this->location());
10901 }
10902
10903 return this;
10904}
10905
e440a328 10906// Return the type of a map index.
10907
10908Type*
10909Map_index_expression::do_type()
10910{
c7524fae 10911 Map_type* mt = this->get_map_type();
10912 if (mt == NULL)
10913 return Type::make_error_type();
10914 Type* type = mt->val_type();
e440a328 10915 // If this map index is in a tuple assignment, we actually return a
10916 // pointer to the value type. Tuple_map_assignment_statement is
10917 // responsible for handling this correctly. We need to get the type
10918 // right in case this gets assigned to a temporary variable.
10919 if (this->is_in_tuple_assignment_)
10920 type = Type::make_pointer_type(type);
10921 return type;
10922}
10923
10924// Fix the type of a map index.
10925
10926void
10927Map_index_expression::do_determine_type(const Type_context*)
10928{
10929 this->map_->determine_type_no_context();
c7524fae 10930 Map_type* mt = this->get_map_type();
10931 Type* key_type = mt == NULL ? NULL : mt->key_type();
10932 Type_context subcontext(key_type, false);
e440a328 10933 this->index_->determine_type(&subcontext);
10934}
10935
10936// Check types of a map index.
10937
10938void
10939Map_index_expression::do_check_types(Gogo*)
10940{
10941 std::string reason;
c7524fae 10942 Map_type* mt = this->get_map_type();
10943 if (mt == NULL)
10944 return;
10945 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 10946 {
10947 if (reason.empty())
10948 this->report_error(_("incompatible type for map index"));
10949 else
10950 {
10951 error_at(this->location(), "incompatible type for map index (%s)",
10952 reason.c_str());
10953 this->set_is_error();
10954 }
10955 }
10956}
10957
10958// Get a tree for a map index.
10959
10960tree
10961Map_index_expression::do_get_tree(Translate_context* context)
10962{
10963 Map_type* type = this->get_map_type();
c7524fae 10964 if (type == NULL)
2c809f8f 10965 {
10966 go_assert(saw_errors());
10967 return error_mark_node;
10968 }
e440a328 10969
2c809f8f 10970 go_assert(this->value_pointer_ != NULL
10971 && this->value_pointer_->is_variable());
e440a328 10972
2c809f8f 10973 Bexpression* ret;
e440a328 10974 if (this->is_lvalue_)
2c809f8f 10975 {
10976 Expression* val =
10977 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10978 this->location());
10979 ret = tree_to_expr(val->get_tree(context));
10980 }
e440a328 10981 else if (this->is_in_tuple_assignment_)
10982 {
10983 // Tuple_map_assignment_statement is responsible for using this
10984 // appropriately.
2c809f8f 10985 ret = tree_to_expr(this->value_pointer_->get_tree(context));
e440a328 10986 }
10987 else
10988 {
2c809f8f 10989 Location loc = this->location();
10990
10991 Expression* nil_check =
10992 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10993 Expression::make_nil(loc), loc);
10994 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10995 Expression* val =
10996 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10997 Bexpression* bval = tree_to_expr(val->get_tree(context));
10998
63697958 10999 Gogo* gogo = context->gogo();
11000 Btype* val_btype = type->val_type()->get_backend(gogo);
11001 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
2c809f8f 11002 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
11003 val_zero, bval, loc);
e440a328 11004 }
2c809f8f 11005
11006 return expr_to_tree(ret);
e440a328 11007}
11008
2c809f8f 11009// Get an expression for the map index. This returns an expression which
11010// evaluates to a pointer to a value. The pointer will be NULL if the key is
e440a328 11011// not in the map.
11012
2c809f8f 11013Expression*
11014Map_index_expression::get_value_pointer(bool insert)
e440a328 11015{
2c809f8f 11016 if (this->value_pointer_ == NULL)
746d2e73 11017 {
2c809f8f 11018 Map_type* type = this->get_map_type();
11019 if (type == NULL)
746d2e73 11020 {
2c809f8f 11021 go_assert(saw_errors());
11022 return Expression::make_error(this->location());
746d2e73 11023 }
e440a328 11024
2c809f8f 11025 Location loc = this->location();
11026 Expression* map_ref = this->map_;
11027 if (this->map_->type()->points_to() != NULL)
11028 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
e440a328 11029
2c809f8f 11030 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
11031 loc);
11032 Expression* map_index =
11033 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
11034 map_ref, index_ptr,
11035 Expression::make_boolean(insert, loc));
11036
11037 Type* val_type = type->val_type();
11038 this->value_pointer_ =
11039 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11040 map_index, this->location());
11041 }
11042 return this->value_pointer_;
e440a328 11043}
11044
d751bb78 11045// Dump ast representation for a map index expression
11046
11047void
11048Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11049 const
11050{
acf2b673 11051 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11052 this->index_, NULL, NULL);
d751bb78 11053}
11054
e440a328 11055// Make a map index expression.
11056
11057Map_index_expression*
11058Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 11059 Location location)
e440a328 11060{
11061 return new Map_index_expression(map, index, location);
11062}
11063
11064// Class Field_reference_expression.
11065
149eabc5 11066// Lower a field reference expression. There is nothing to lower, but
11067// this is where we generate the tracking information for fields with
11068// the magic go:"track" tag.
11069
11070Expression*
11071Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11072 Statement_inserter* inserter, int)
11073{
11074 Struct_type* struct_type = this->expr_->type()->struct_type();
11075 if (struct_type == NULL)
11076 {
11077 // Error will be reported elsewhere.
11078 return this;
11079 }
11080 const Struct_field* field = struct_type->field(this->field_index_);
11081 if (field == NULL)
11082 return this;
11083 if (!field->has_tag())
11084 return this;
11085 if (field->tag().find("go:\"track\"") == std::string::npos)
11086 return this;
11087
11088 // We have found a reference to a tracked field. Build a call to
11089 // the runtime function __go_fieldtrack with a string that describes
11090 // the field. FIXME: We should only call this once per referenced
11091 // field per function, not once for each reference to the field.
11092
11093 if (this->called_fieldtrack_)
11094 return this;
11095 this->called_fieldtrack_ = true;
11096
11097 Location loc = this->location();
11098
11099 std::string s = "fieldtrack \"";
11100 Named_type* nt = this->expr_->type()->named_type();
11101 if (nt == NULL || nt->named_object()->package() == NULL)
11102 s.append(gogo->pkgpath());
11103 else
11104 s.append(nt->named_object()->package()->pkgpath());
11105 s.push_back('.');
11106 if (nt != NULL)
5c29ad36 11107 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11108 s.push_back('.');
11109 s.append(field->field_name());
11110 s.push_back('"');
11111
11112 // We can't use a string here, because internally a string holds a
11113 // pointer to the actual bytes; when the linker garbage collects the
11114 // string, it won't garbage collect the bytes. So we use a
11115 // [...]byte.
11116
11117 mpz_t val;
11118 mpz_init_set_ui(val, s.length());
11119 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11120 mpz_clear(val);
11121
11122 Type* byte_type = gogo->lookup_global("byte")->type_value();
11123 Type* array_type = Type::make_array_type(byte_type, length_expr);
11124
11125 Expression_list* bytes = new Expression_list();
11126 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11127 {
11128 mpz_init_set_ui(val, *p);
11129 Expression* byte = Expression::make_integer(&val, NULL, loc);
11130 mpz_clear(val);
11131 bytes->push_back(byte);
11132 }
11133
11134 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11135 bytes, false, loc);
149eabc5 11136
11137 Variable* var = new Variable(array_type, e, true, false, false, loc);
11138
11139 static int count;
11140 char buf[50];
11141 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11142 ++count;
11143
11144 Named_object* no = gogo->add_variable(buf, var);
11145 e = Expression::make_var_reference(no, loc);
11146 e = Expression::make_unary(OPERATOR_AND, e, loc);
11147
11148 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11149 inserter->insert(Statement::make_statement(call, false));
11150
11151 // Put this function, and the global variable we just created, into
11152 // unique sections. This will permit the linker to garbage collect
11153 // them if they are not referenced. The effect is that the only
11154 // strings, indicating field references, that will wind up in the
11155 // executable will be those for functions that are actually needed.
66a6be58 11156 if (function != NULL)
11157 function->func_value()->set_in_unique_section();
149eabc5 11158 var->set_in_unique_section();
11159
11160 return this;
11161}
11162
e440a328 11163// Return the type of a field reference.
11164
11165Type*
11166Field_reference_expression::do_type()
11167{
b0e628fb 11168 Type* type = this->expr_->type();
5c13bd80 11169 if (type->is_error())
b0e628fb 11170 return type;
11171 Struct_type* struct_type = type->struct_type();
c484d925 11172 go_assert(struct_type != NULL);
e440a328 11173 return struct_type->field(this->field_index_)->type();
11174}
11175
11176// Check the types for a field reference.
11177
11178void
11179Field_reference_expression::do_check_types(Gogo*)
11180{
b0e628fb 11181 Type* type = this->expr_->type();
5c13bd80 11182 if (type->is_error())
b0e628fb 11183 return;
11184 Struct_type* struct_type = type->struct_type();
c484d925 11185 go_assert(struct_type != NULL);
11186 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11187}
11188
11189// Get a tree for a field reference.
11190
11191tree
11192Field_reference_expression::do_get_tree(Translate_context* context)
11193{
fbb851c5 11194 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11195 Bexpression* ret =
11196 context->gogo()->backend()->struct_field_expression(bstruct,
11197 this->field_index_,
11198 this->location());
11199 return expr_to_tree(ret);
e440a328 11200}
11201
d751bb78 11202// Dump ast representation for a field reference expression.
11203
11204void
11205Field_reference_expression::do_dump_expression(
11206 Ast_dump_context* ast_dump_context) const
11207{
11208 this->expr_->dump_expression(ast_dump_context);
11209 ast_dump_context->ostream() << "." << this->field_index_;
11210}
11211
e440a328 11212// Make a reference to a qualified identifier in an expression.
11213
11214Field_reference_expression*
11215Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11216 Location location)
e440a328 11217{
11218 return new Field_reference_expression(expr, field_index, location);
11219}
11220
11221// Class Interface_field_reference_expression.
11222
2387f644 11223// Return an expression for the pointer to the function to call.
e440a328 11224
2387f644 11225Expression*
11226Interface_field_reference_expression::get_function()
e440a328 11227{
2387f644 11228 Expression* ref = this->expr_;
11229 Location loc = this->location();
11230 if (ref->type()->points_to() != NULL)
11231 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11232
2387f644 11233 Expression* mtable =
11234 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11235 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11236
11237 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11238 unsigned int index;
11239 const Struct_field* field = mtable_type->find_local_field(name, &index);
11240 go_assert(field != NULL);
11241 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11242 return Expression::make_field_reference(mtable, index, loc);
e440a328 11243}
11244
2387f644 11245// Return an expression for the first argument to pass to the interface
e440a328 11246// function.
11247
2387f644 11248Expression*
11249Interface_field_reference_expression::get_underlying_object()
e440a328 11250{
2387f644 11251 Expression* expr = this->expr_;
11252 if (expr->type()->points_to() != NULL)
11253 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11254 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11255 this->location());
e440a328 11256}
11257
11258// Traversal.
11259
11260int
11261Interface_field_reference_expression::do_traverse(Traverse* traverse)
11262{
11263 return Expression::traverse(&this->expr_, traverse);
11264}
11265
0afbb937 11266// Lower the expression. If this expression is not called, we need to
11267// evaluate the expression twice when converting to the backend
11268// interface. So introduce a temporary variable if necessary.
11269
11270Expression*
11271Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11272 Statement_inserter* inserter,
11273 int)
11274{
2387f644 11275 if (!this->expr_->is_variable())
0afbb937 11276 {
11277 Temporary_statement* temp =
11278 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11279 inserter->insert(temp);
11280 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11281 this->location());
11282 }
11283 return this;
11284}
11285
e440a328 11286// Return the type of an interface field reference.
11287
11288Type*
11289Interface_field_reference_expression::do_type()
11290{
11291 Type* expr_type = this->expr_->type();
11292
11293 Type* points_to = expr_type->points_to();
11294 if (points_to != NULL)
11295 expr_type = points_to;
11296
11297 Interface_type* interface_type = expr_type->interface_type();
11298 if (interface_type == NULL)
11299 return Type::make_error_type();
11300
11301 const Typed_identifier* method = interface_type->find_method(this->name_);
11302 if (method == NULL)
11303 return Type::make_error_type();
11304
11305 return method->type();
11306}
11307
11308// Determine types.
11309
11310void
11311Interface_field_reference_expression::do_determine_type(const Type_context*)
11312{
11313 this->expr_->determine_type_no_context();
11314}
11315
11316// Check the types for an interface field reference.
11317
11318void
11319Interface_field_reference_expression::do_check_types(Gogo*)
11320{
11321 Type* type = this->expr_->type();
11322
11323 Type* points_to = type->points_to();
11324 if (points_to != NULL)
11325 type = points_to;
11326
11327 Interface_type* interface_type = type->interface_type();
11328 if (interface_type == NULL)
5c491127 11329 {
11330 if (!type->is_error_type())
11331 this->report_error(_("expected interface or pointer to interface"));
11332 }
e440a328 11333 else
11334 {
11335 const Typed_identifier* method =
11336 interface_type->find_method(this->name_);
11337 if (method == NULL)
11338 {
11339 error_at(this->location(), "method %qs not in interface",
11340 Gogo::message_name(this->name_).c_str());
11341 this->set_is_error();
11342 }
11343 }
11344}
11345
0afbb937 11346// If an interface field reference is not simply called, then it is
11347// represented as a closure. The closure will hold a single variable,
11348// the value of the interface on which the method should be called.
11349// The function will be a simple thunk that pulls the value from the
11350// closure and calls the method with the remaining arguments.
11351
11352// Because method values are not common, we don't build all thunks for
11353// all possible interface methods, but instead only build them as we
11354// need them. In particular, we even build them on demand for
11355// interface methods defined in other packages.
11356
11357Interface_field_reference_expression::Interface_method_thunks
11358 Interface_field_reference_expression::interface_method_thunks;
11359
11360// Find or create the thunk to call method NAME on TYPE.
11361
11362Named_object*
11363Interface_field_reference_expression::create_thunk(Gogo* gogo,
11364 Interface_type* type,
11365 const std::string& name)
11366{
11367 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11368 std::pair<Interface_method_thunks::iterator, bool> ins =
11369 Interface_field_reference_expression::interface_method_thunks.insert(val);
11370 if (ins.second)
11371 {
11372 // This is the first time we have seen this interface.
11373 ins.first->second = new Method_thunks();
11374 }
11375
11376 for (Method_thunks::const_iterator p = ins.first->second->begin();
11377 p != ins.first->second->end();
11378 p++)
11379 if (p->first == name)
11380 return p->second;
11381
11382 Location loc = type->location();
11383
11384 const Typed_identifier* method_id = type->find_method(name);
11385 if (method_id == NULL)
11386 return Named_object::make_erroneous_name(Gogo::thunk_name());
11387
11388 Function_type* orig_fntype = method_id->type()->function_type();
11389 if (orig_fntype == NULL)
11390 return Named_object::make_erroneous_name(Gogo::thunk_name());
11391
11392 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11393 // The type here is wrong--it should be the C function type. But it
11394 // doesn't really matter.
0afbb937 11395 Type* vt = Type::make_pointer_type(Type::make_void_type());
11396 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11397 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11398 Type* closure_type = Type::make_struct_type(sfl, loc);
11399 closure_type = Type::make_pointer_type(closure_type);
11400
f8bdf81a 11401 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11402
11403 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11404 false, loc);
11405
f8bdf81a 11406 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11407 cvar->set_is_used();
11408 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11409 new_no->func_value()->set_closure_var(cp);
0afbb937 11410
f8bdf81a 11411 gogo->start_block(loc);
0afbb937 11412
11413 // Field 0 of the closure is the function code pointer, field 1 is
11414 // the value on which to invoke the method.
11415 Expression* arg = Expression::make_var_reference(cp, loc);
11416 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11417 arg = Expression::make_field_reference(arg, 1, loc);
11418
11419 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11420 loc);
11421
11422 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11423 Expression_list* args;
11424 if (orig_params == NULL || orig_params->empty())
11425 args = NULL;
11426 else
11427 {
11428 const Typed_identifier_list* new_params = new_fntype->parameters();
11429 args = new Expression_list();
11430 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11431 p != new_params->end();
0afbb937 11432 ++p)
11433 {
11434 Named_object* p_no = gogo->lookup(p->name(), NULL);
11435 go_assert(p_no != NULL
11436 && p_no->is_variable()
11437 && p_no->var_value()->is_parameter());
11438 args->push_back(Expression::make_var_reference(p_no, loc));
11439 }
11440 }
11441
11442 Call_expression* call = Expression::make_call(ifre, args,
11443 orig_fntype->is_varargs(),
11444 loc);
11445 call->set_varargs_are_lowered();
11446
11447 Statement* s = Statement::make_return_from_call(call, loc);
11448 gogo->add_statement(s);
11449 Block* b = gogo->finish_block(loc);
11450 gogo->add_block(b, loc);
11451 gogo->lower_block(new_no, b);
a32698ee 11452 gogo->flatten_block(new_no, b);
0afbb937 11453 gogo->finish_function(loc);
11454
11455 ins.first->second->push_back(std::make_pair(name, new_no));
11456 return new_no;
11457}
11458
11459// Get a tree for a method value.
e440a328 11460
11461tree
0afbb937 11462Interface_field_reference_expression::do_get_tree(Translate_context* context)
e440a328 11463{
0afbb937 11464 Interface_type* type = this->expr_->type()->interface_type();
11465 if (type == NULL)
11466 {
11467 go_assert(saw_errors());
11468 return error_mark_node;
11469 }
11470
11471 Named_object* thunk =
11472 Interface_field_reference_expression::create_thunk(context->gogo(),
11473 type, this->name_);
11474 if (thunk->is_erroneous())
11475 {
11476 go_assert(saw_errors());
11477 return error_mark_node;
11478 }
11479
11480 // FIXME: We should lower this earlier, but we can't it lower it in
11481 // the lowering pass because at that point we don't know whether we
11482 // need to create the thunk or not. If the expression is called, we
11483 // don't need the thunk.
11484
11485 Location loc = this->location();
11486
11487 Struct_field_list* fields = new Struct_field_list();
11488 fields->push_back(Struct_field(Typed_identifier("fn.0",
11489 thunk->func_value()->type(),
11490 loc)));
11491 fields->push_back(Struct_field(Typed_identifier("val.1",
11492 this->expr_->type(),
11493 loc)));
11494 Struct_type* st = Type::make_struct_type(fields, loc);
11495
11496 Expression_list* vals = new Expression_list();
11497 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11498 vals->push_back(this->expr_);
11499
11500 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 11501 expr = Expression::make_heap_expression(expr, loc);
0afbb937 11502
2387f644 11503 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11504 Expression* nil_check =
11505 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11506 Expression::make_nil(loc), loc);
11507 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
0afbb937 11508
2387f644 11509 Gogo* gogo = context->gogo();
11510 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11511 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11512
11513 Bexpression* bcond =
a32698ee 11514 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11515 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11516 Bexpression* ret =
11517 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11518 return expr_to_tree(ret);
e440a328 11519}
11520
d751bb78 11521// Dump ast representation for an interface field reference.
11522
11523void
11524Interface_field_reference_expression::do_dump_expression(
11525 Ast_dump_context* ast_dump_context) const
11526{
11527 this->expr_->dump_expression(ast_dump_context);
11528 ast_dump_context->ostream() << "." << this->name_;
11529}
11530
e440a328 11531// Make a reference to a field in an interface.
11532
11533Expression*
11534Expression::make_interface_field_reference(Expression* expr,
11535 const std::string& field,
b13c66cd 11536 Location location)
e440a328 11537{
11538 return new Interface_field_reference_expression(expr, field, location);
11539}
11540
11541// A general selector. This is a Parser_expression for LEFT.NAME. It
11542// is lowered after we know the type of the left hand side.
11543
11544class Selector_expression : public Parser_expression
11545{
11546 public:
11547 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11548 Location location)
e440a328 11549 : Parser_expression(EXPRESSION_SELECTOR, location),
11550 left_(left), name_(name)
11551 { }
11552
11553 protected:
11554 int
11555 do_traverse(Traverse* traverse)
11556 { return Expression::traverse(&this->left_, traverse); }
11557
11558 Expression*
ceeb4318 11559 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11560
11561 Expression*
11562 do_copy()
11563 {
11564 return new Selector_expression(this->left_->copy(), this->name_,
11565 this->location());
11566 }
11567
d751bb78 11568 void
11569 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11570
e440a328 11571 private:
11572 Expression*
11573 lower_method_expression(Gogo*);
11574
11575 // The expression on the left hand side.
11576 Expression* left_;
11577 // The name on the right hand side.
11578 std::string name_;
11579};
11580
11581// Lower a selector expression once we know the real type of the left
11582// hand side.
11583
11584Expression*
ceeb4318 11585Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11586 int)
e440a328 11587{
11588 Expression* left = this->left_;
11589 if (left->is_type_expression())
11590 return this->lower_method_expression(gogo);
11591 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11592 this->location());
11593}
11594
11595// Lower a method expression T.M or (*T).M. We turn this into a
11596// function literal.
11597
11598Expression*
11599Selector_expression::lower_method_expression(Gogo* gogo)
11600{
b13c66cd 11601 Location location = this->location();
e440a328 11602 Type* type = this->left_->type();
11603 const std::string& name(this->name_);
11604
11605 bool is_pointer;
11606 if (type->points_to() == NULL)
11607 is_pointer = false;
11608 else
11609 {
11610 is_pointer = true;
11611 type = type->points_to();
11612 }
11613 Named_type* nt = type->named_type();
11614 if (nt == NULL)
11615 {
11616 error_at(location,
11617 ("method expression requires named type or "
11618 "pointer to named type"));
11619 return Expression::make_error(location);
11620 }
11621
11622 bool is_ambiguous;
11623 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11624 const Typed_identifier* imethod = NULL;
dcc8506b 11625 if (method == NULL && !is_pointer)
ab1468c3 11626 {
11627 Interface_type* it = nt->interface_type();
11628 if (it != NULL)
11629 imethod = it->find_method(name);
11630 }
11631
11632 if (method == NULL && imethod == NULL)
e440a328 11633 {
11634 if (!is_ambiguous)
dcc8506b 11635 error_at(location, "type %<%s%s%> has no method %<%s%>",
11636 is_pointer ? "*" : "",
e440a328 11637 nt->message_name().c_str(),
11638 Gogo::message_name(name).c_str());
11639 else
dcc8506b 11640 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
e440a328 11641 Gogo::message_name(name).c_str(),
dcc8506b 11642 is_pointer ? "*" : "",
e440a328 11643 nt->message_name().c_str());
11644 return Expression::make_error(location);
11645 }
11646
ab1468c3 11647 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11648 {
11649 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11650 nt->message_name().c_str(),
11651 Gogo::message_name(name).c_str());
11652 return Expression::make_error(location);
11653 }
11654
11655 // Build a new function type in which the receiver becomes the first
11656 // argument.
ab1468c3 11657 Function_type* method_type;
11658 if (method != NULL)
11659 {
11660 method_type = method->type();
c484d925 11661 go_assert(method_type->is_method());
ab1468c3 11662 }
11663 else
11664 {
11665 method_type = imethod->type()->function_type();
c484d925 11666 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11667 }
e440a328 11668
11669 const char* const receiver_name = "$this";
11670 Typed_identifier_list* parameters = new Typed_identifier_list();
11671 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11672 location));
11673
11674 const Typed_identifier_list* method_parameters = method_type->parameters();
11675 if (method_parameters != NULL)
11676 {
f470da59 11677 int i = 0;
e440a328 11678 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11679 p != method_parameters->end();
f470da59 11680 ++p, ++i)
11681 {
68883531 11682 if (!p->name().empty())
f470da59 11683 parameters->push_back(*p);
11684 else
11685 {
11686 char buf[20];
11687 snprintf(buf, sizeof buf, "$param%d", i);
11688 parameters->push_back(Typed_identifier(buf, p->type(),
11689 p->location()));
11690 }
11691 }
e440a328 11692 }
11693
11694 const Typed_identifier_list* method_results = method_type->results();
11695 Typed_identifier_list* results;
11696 if (method_results == NULL)
11697 results = NULL;
11698 else
11699 {
11700 results = new Typed_identifier_list();
11701 for (Typed_identifier_list::const_iterator p = method_results->begin();
11702 p != method_results->end();
11703 ++p)
11704 results->push_back(*p);
11705 }
11706
11707 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11708 location);
11709 if (method_type->is_varargs())
11710 fntype->set_is_varargs();
11711
11712 // We generate methods which always takes a pointer to the receiver
11713 // as their first argument. If this is for a pointer type, we can
11714 // simply reuse the existing function. We use an internal hack to
11715 // get the right type.
8381eda7 11716 // FIXME: This optimization is disabled because it doesn't yet work
11717 // with function descriptors when the method expression is not
11718 // directly called.
11719 if (method != NULL && is_pointer && false)
e440a328 11720 {
11721 Named_object* mno = (method->needs_stub_method()
11722 ? method->stub_object()
11723 : method->named_object());
11724 Expression* f = Expression::make_func_reference(mno, NULL, location);
11725 f = Expression::make_cast(fntype, f, location);
11726 Type_conversion_expression* tce =
11727 static_cast<Type_conversion_expression*>(f);
11728 tce->set_may_convert_function_types();
11729 return f;
11730 }
11731
11732 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11733 location);
11734
11735 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 11736 go_assert(vno != NULL);
e440a328 11737 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 11738 Expression* bm;
11739 if (method != NULL)
11740 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11741 else
11742 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 11743
11744 // Even though we found the method above, if it has an error type we
11745 // may see an error here.
11746 if (bm->is_error_expression())
463fe805 11747 {
11748 gogo->finish_function(location);
11749 return bm;
11750 }
e440a328 11751
11752 Expression_list* args;
f470da59 11753 if (parameters->size() <= 1)
e440a328 11754 args = NULL;
11755 else
11756 {
11757 args = new Expression_list();
f470da59 11758 Typed_identifier_list::const_iterator p = parameters->begin();
11759 ++p;
11760 for (; p != parameters->end(); ++p)
e440a328 11761 {
11762 vno = gogo->lookup(p->name(), NULL);
c484d925 11763 go_assert(vno != NULL);
e440a328 11764 args->push_back(Expression::make_var_reference(vno, location));
11765 }
11766 }
11767
ceeb4318 11768 gogo->start_block(location);
11769
e440a328 11770 Call_expression* call = Expression::make_call(bm, args,
11771 method_type->is_varargs(),
11772 location);
11773
0afbb937 11774 Statement* s = Statement::make_return_from_call(call, location);
e440a328 11775 gogo->add_statement(s);
11776
ceeb4318 11777 Block* b = gogo->finish_block(location);
11778
11779 gogo->add_block(b, location);
11780
11781 // Lower the call in case there are multiple results.
11782 gogo->lower_block(no, b);
a32698ee 11783 gogo->flatten_block(no, b);
ceeb4318 11784
e440a328 11785 gogo->finish_function(location);
11786
11787 return Expression::make_func_reference(no, NULL, location);
11788}
11789
d751bb78 11790// Dump the ast for a selector expression.
11791
11792void
11793Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11794 const
11795{
11796 ast_dump_context->dump_expression(this->left_);
11797 ast_dump_context->ostream() << ".";
11798 ast_dump_context->ostream() << this->name_;
11799}
11800
e440a328 11801// Make a selector expression.
11802
11803Expression*
11804Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 11805 Location location)
e440a328 11806{
11807 return new Selector_expression(left, name, location);
11808}
11809
11810// Implement the builtin function new.
11811
11812class Allocation_expression : public Expression
11813{
11814 public:
b13c66cd 11815 Allocation_expression(Type* type, Location location)
e440a328 11816 : Expression(EXPRESSION_ALLOCATION, location),
11817 type_(type)
11818 { }
11819
11820 protected:
11821 int
11822 do_traverse(Traverse* traverse)
11823 { return Type::traverse(this->type_, traverse); }
11824
11825 Type*
11826 do_type()
11827 { return Type::make_pointer_type(this->type_); }
11828
11829 void
11830 do_determine_type(const Type_context*)
11831 { }
11832
e440a328 11833 Expression*
11834 do_copy()
11835 { return new Allocation_expression(this->type_, this->location()); }
11836
11837 tree
11838 do_get_tree(Translate_context*);
11839
d751bb78 11840 void
11841 do_dump_expression(Ast_dump_context*) const;
11842
e440a328 11843 private:
11844 // The type we are allocating.
11845 Type* type_;
11846};
11847
e440a328 11848// Return a tree for an allocation expression.
11849
11850tree
11851Allocation_expression::do_get_tree(Translate_context* context)
11852{
2c809f8f 11853 Gogo* gogo = context->gogo();
11854 Location loc = this->location();
11855 Expression* space = gogo->allocate_memory(this->type_, loc);
11856 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11857 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11858 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11859 return expr_to_tree(ret);
e440a328 11860}
11861
d751bb78 11862// Dump ast representation for an allocation expression.
11863
11864void
11865Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11866 const
11867{
11868 ast_dump_context->ostream() << "new(";
11869 ast_dump_context->dump_type(this->type_);
11870 ast_dump_context->ostream() << ")";
11871}
11872
e440a328 11873// Make an allocation expression.
11874
11875Expression*
b13c66cd 11876Expression::make_allocation(Type* type, Location location)
e440a328 11877{
11878 return new Allocation_expression(type, location);
11879}
11880
e440a328 11881// Construct a struct.
11882
11883class Struct_construction_expression : public Expression
11884{
11885 public:
11886 Struct_construction_expression(Type* type, Expression_list* vals,
b13c66cd 11887 Location location)
e440a328 11888 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
0c4f5a19 11889 type_(type), vals_(vals), traverse_order_(NULL)
e440a328 11890 { }
11891
0c4f5a19 11892 // Set the traversal order, used to ensure that we implement the
11893 // order of evaluation rules. Takes ownership of the argument.
11894 void
11895 set_traverse_order(std::vector<int>* traverse_order)
11896 { this->traverse_order_ = traverse_order; }
11897
e440a328 11898 // Return whether this is a constant initializer.
11899 bool
11900 is_constant_struct() const;
11901
11902 protected:
11903 int
11904 do_traverse(Traverse* traverse);
11905
f9ca30f9 11906 bool
11907 do_is_immutable() const;
11908
e440a328 11909 Type*
11910 do_type()
11911 { return this->type_; }
11912
11913 void
11914 do_determine_type(const Type_context*);
11915
11916 void
11917 do_check_types(Gogo*);
11918
11919 Expression*
11920 do_copy()
11921 {
0c4f5a19 11922 Struct_construction_expression* ret =
11923 new Struct_construction_expression(this->type_, this->vals_->copy(),
11924 this->location());
11925 if (this->traverse_order_ != NULL)
11926 ret->set_traverse_order(this->traverse_order_);
11927 return ret;
e440a328 11928 }
11929
e440a328 11930 tree
11931 do_get_tree(Translate_context*);
11932
11933 void
11934 do_export(Export*) const;
11935
d751bb78 11936 void
11937 do_dump_expression(Ast_dump_context*) const;
11938
e440a328 11939 private:
11940 // The type of the struct to construct.
11941 Type* type_;
11942 // The list of values, in order of the fields in the struct. A NULL
11943 // entry means that the field should be zero-initialized.
11944 Expression_list* vals_;
0c4f5a19 11945 // If not NULL, the order in which to traverse vals_. This is used
11946 // so that we implement the order of evaluation rules correctly.
11947 std::vector<int>* traverse_order_;
e440a328 11948};
11949
11950// Traversal.
11951
11952int
11953Struct_construction_expression::do_traverse(Traverse* traverse)
11954{
0c4f5a19 11955 if (this->vals_ != NULL)
11956 {
11957 if (this->traverse_order_ == NULL)
11958 {
11959 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11960 return TRAVERSE_EXIT;
11961 }
11962 else
11963 {
11964 for (std::vector<int>::const_iterator p =
11965 this->traverse_order_->begin();
11966 p != this->traverse_order_->end();
11967 ++p)
11968 {
11969 if (Expression::traverse(&this->vals_->at(*p), traverse)
11970 == TRAVERSE_EXIT)
11971 return TRAVERSE_EXIT;
11972 }
11973 }
11974 }
e440a328 11975 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11976 return TRAVERSE_EXIT;
11977 return TRAVERSE_CONTINUE;
11978}
11979
11980// Return whether this is a constant initializer.
11981
11982bool
11983Struct_construction_expression::is_constant_struct() const
11984{
11985 if (this->vals_ == NULL)
11986 return true;
11987 for (Expression_list::const_iterator pv = this->vals_->begin();
11988 pv != this->vals_->end();
11989 ++pv)
11990 {
11991 if (*pv != NULL
11992 && !(*pv)->is_constant()
11993 && (!(*pv)->is_composite_literal()
11994 || (*pv)->is_nonconstant_composite_literal()))
11995 return false;
11996 }
11997
11998 const Struct_field_list* fields = this->type_->struct_type()->fields();
11999 for (Struct_field_list::const_iterator pf = fields->begin();
12000 pf != fields->end();
12001 ++pf)
12002 {
12003 // There are no constant constructors for interfaces.
12004 if (pf->type()->interface_type() != NULL)
12005 return false;
12006 }
12007
12008 return true;
12009}
12010
f9ca30f9 12011// Return whether this struct is immutable.
12012
12013bool
12014Struct_construction_expression::do_is_immutable() const
12015{
12016 if (this->vals_ == NULL)
12017 return true;
12018 for (Expression_list::const_iterator pv = this->vals_->begin();
12019 pv != this->vals_->end();
12020 ++pv)
12021 {
12022 if (*pv != NULL && !(*pv)->is_immutable())
12023 return false;
12024 }
12025 return true;
12026}
12027
e440a328 12028// Final type determination.
12029
12030void
12031Struct_construction_expression::do_determine_type(const Type_context*)
12032{
12033 if (this->vals_ == NULL)
12034 return;
12035 const Struct_field_list* fields = this->type_->struct_type()->fields();
12036 Expression_list::const_iterator pv = this->vals_->begin();
12037 for (Struct_field_list::const_iterator pf = fields->begin();
12038 pf != fields->end();
12039 ++pf, ++pv)
12040 {
12041 if (pv == this->vals_->end())
12042 return;
12043 if (*pv != NULL)
12044 {
12045 Type_context subcontext(pf->type(), false);
12046 (*pv)->determine_type(&subcontext);
12047 }
12048 }
a6cb4c0e 12049 // Extra values are an error we will report elsewhere; we still want
12050 // to determine the type to avoid knockon errors.
12051 for (; pv != this->vals_->end(); ++pv)
12052 (*pv)->determine_type_no_context();
e440a328 12053}
12054
12055// Check types.
12056
12057void
12058Struct_construction_expression::do_check_types(Gogo*)
12059{
12060 if (this->vals_ == NULL)
12061 return;
12062
12063 Struct_type* st = this->type_->struct_type();
12064 if (this->vals_->size() > st->field_count())
12065 {
12066 this->report_error(_("too many expressions for struct"));
12067 return;
12068 }
12069
12070 const Struct_field_list* fields = st->fields();
12071 Expression_list::const_iterator pv = this->vals_->begin();
12072 int i = 0;
12073 for (Struct_field_list::const_iterator pf = fields->begin();
12074 pf != fields->end();
12075 ++pf, ++pv, ++i)
12076 {
12077 if (pv == this->vals_->end())
12078 {
12079 this->report_error(_("too few expressions for struct"));
12080 break;
12081 }
12082
12083 if (*pv == NULL)
12084 continue;
12085
12086 std::string reason;
12087 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12088 {
12089 if (reason.empty())
12090 error_at((*pv)->location(),
12091 "incompatible type for field %d in struct construction",
12092 i + 1);
12093 else
12094 error_at((*pv)->location(),
12095 ("incompatible type for field %d in "
12096 "struct construction (%s)"),
12097 i + 1, reason.c_str());
12098 this->set_is_error();
12099 }
12100 }
c484d925 12101 go_assert(pv == this->vals_->end());
e440a328 12102}
12103
12104// Return a tree for constructing a struct.
12105
12106tree
12107Struct_construction_expression::do_get_tree(Translate_context* context)
12108{
12109 Gogo* gogo = context->gogo();
12110
2c809f8f 12111 Btype* btype = this->type_->get_backend(gogo);
e440a328 12112 if (this->vals_ == NULL)
2c809f8f 12113 return expr_to_tree(gogo->backend()->zero_expression(btype));
e440a328 12114
e440a328 12115 const Struct_field_list* fields = this->type_->struct_type()->fields();
e440a328 12116 Expression_list::const_iterator pv = this->vals_->begin();
2c809f8f 12117 std::vector<Bexpression*> init;
12118 for (Struct_field_list::const_iterator pf = fields->begin();
12119 pf != fields->end();
12120 ++pf)
e440a328 12121 {
63697958 12122 Btype* fbtype = pf->type()->get_backend(gogo);
e440a328 12123 if (pv == this->vals_->end())
2c809f8f 12124 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12125 else if (*pv == NULL)
12126 {
2c809f8f 12127 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12128 ++pv;
12129 }
12130 else
12131 {
2c809f8f 12132 Expression* val =
12133 Expression::convert_for_assignment(gogo, pf->type(),
12134 *pv, this->location());
12135 init.push_back(tree_to_expr(val->get_tree(context)));
e440a328 12136 ++pv;
12137 }
e440a328 12138 }
e440a328 12139
2c809f8f 12140 Bexpression* ret =
12141 gogo->backend()->constructor_expression(btype, init, this->location());
12142 return expr_to_tree(ret);
e440a328 12143}
12144
12145// Export a struct construction.
12146
12147void
12148Struct_construction_expression::do_export(Export* exp) const
12149{
12150 exp->write_c_string("convert(");
12151 exp->write_type(this->type_);
12152 for (Expression_list::const_iterator pv = this->vals_->begin();
12153 pv != this->vals_->end();
12154 ++pv)
12155 {
12156 exp->write_c_string(", ");
12157 if (*pv != NULL)
12158 (*pv)->export_expression(exp);
12159 }
12160 exp->write_c_string(")");
12161}
12162
d751bb78 12163// Dump ast representation of a struct construction expression.
12164
12165void
12166Struct_construction_expression::do_dump_expression(
12167 Ast_dump_context* ast_dump_context) const
12168{
d751bb78 12169 ast_dump_context->dump_type(this->type_);
12170 ast_dump_context->ostream() << "{";
12171 ast_dump_context->dump_expression_list(this->vals_);
12172 ast_dump_context->ostream() << "}";
12173}
12174
e440a328 12175// Make a struct composite literal. This used by the thunk code.
12176
12177Expression*
12178Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12179 Location location)
e440a328 12180{
c484d925 12181 go_assert(type->struct_type() != NULL);
e440a328 12182 return new Struct_construction_expression(type, vals, location);
12183}
12184
12185// Construct an array. This class is not used directly; instead we
12186// use the child classes, Fixed_array_construction_expression and
2c809f8f 12187// Slice_construction_expression.
e440a328 12188
12189class Array_construction_expression : public Expression
12190{
12191 protected:
12192 Array_construction_expression(Expression_classification classification,
ffe743ca 12193 Type* type,
12194 const std::vector<unsigned long>* indexes,
12195 Expression_list* vals, Location location)
e440a328 12196 : Expression(classification, location),
ffe743ca 12197 type_(type), indexes_(indexes), vals_(vals)
12198 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
e440a328 12199
12200 public:
12201 // Return whether this is a constant initializer.
12202 bool
12203 is_constant_array() const;
12204
12205 // Return the number of elements.
12206 size_t
12207 element_count() const
12208 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12209
12210protected:
12211 int
12212 do_traverse(Traverse* traverse);
12213
f9ca30f9 12214 bool
12215 do_is_immutable() const;
12216
e440a328 12217 Type*
12218 do_type()
12219 { return this->type_; }
12220
12221 void
12222 do_determine_type(const Type_context*);
12223
12224 void
12225 do_check_types(Gogo*);
12226
e440a328 12227 void
12228 do_export(Export*) const;
12229
ffe743ca 12230 // The indexes.
12231 const std::vector<unsigned long>*
12232 indexes()
12233 { return this->indexes_; }
12234
e440a328 12235 // The list of values.
12236 Expression_list*
12237 vals()
12238 { return this->vals_; }
12239
2c809f8f 12240 // Get the backend constructor for the array values.
12241 Bexpression*
12242 get_constructor(Translate_context* context, Btype* btype);
e440a328 12243
d751bb78 12244 void
12245 do_dump_expression(Ast_dump_context*) const;
12246
e440a328 12247 private:
12248 // The type of the array to construct.
12249 Type* type_;
ffe743ca 12250 // The list of indexes into the array, one for each value. This may
12251 // be NULL, in which case the indexes start at zero and increment.
12252 const std::vector<unsigned long>* indexes_;
12253 // The list of values. This may be NULL if there are no values.
e440a328 12254 Expression_list* vals_;
12255};
12256
12257// Traversal.
12258
12259int
12260Array_construction_expression::do_traverse(Traverse* traverse)
12261{
12262 if (this->vals_ != NULL
12263 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12264 return TRAVERSE_EXIT;
12265 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12266 return TRAVERSE_EXIT;
12267 return TRAVERSE_CONTINUE;
12268}
12269
12270// Return whether this is a constant initializer.
12271
12272bool
12273Array_construction_expression::is_constant_array() const
12274{
12275 if (this->vals_ == NULL)
12276 return true;
12277
12278 // There are no constant constructors for interfaces.
12279 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12280 return false;
12281
12282 for (Expression_list::const_iterator pv = this->vals_->begin();
12283 pv != this->vals_->end();
12284 ++pv)
12285 {
12286 if (*pv != NULL
12287 && !(*pv)->is_constant()
12288 && (!(*pv)->is_composite_literal()
12289 || (*pv)->is_nonconstant_composite_literal()))
12290 return false;
12291 }
12292 return true;
12293}
12294
f9ca30f9 12295// Return whether this is an immutable array initializer.
12296
12297bool
12298Array_construction_expression::do_is_immutable() const
12299{
12300 if (this->vals_ == NULL)
12301 return true;
12302 for (Expression_list::const_iterator pv = this->vals_->begin();
12303 pv != this->vals_->end();
12304 ++pv)
12305 {
12306 if (*pv != NULL && !(*pv)->is_immutable())
12307 return false;
12308 }
12309 return true;
12310}
12311
e440a328 12312// Final type determination.
12313
12314void
12315Array_construction_expression::do_determine_type(const Type_context*)
12316{
12317 if (this->vals_ == NULL)
12318 return;
12319 Type_context subcontext(this->type_->array_type()->element_type(), false);
12320 for (Expression_list::const_iterator pv = this->vals_->begin();
12321 pv != this->vals_->end();
12322 ++pv)
12323 {
12324 if (*pv != NULL)
12325 (*pv)->determine_type(&subcontext);
12326 }
12327}
12328
12329// Check types.
12330
12331void
12332Array_construction_expression::do_check_types(Gogo*)
12333{
12334 if (this->vals_ == NULL)
12335 return;
12336
12337 Array_type* at = this->type_->array_type();
12338 int i = 0;
12339 Type* element_type = at->element_type();
12340 for (Expression_list::const_iterator pv = this->vals_->begin();
12341 pv != this->vals_->end();
12342 ++pv, ++i)
12343 {
12344 if (*pv != NULL
12345 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12346 {
12347 error_at((*pv)->location(),
12348 "incompatible type for element %d in composite literal",
12349 i + 1);
12350 this->set_is_error();
12351 }
12352 }
e440a328 12353}
12354
2c809f8f 12355// Get a constructor expression for the array values.
e440a328 12356
2c809f8f 12357Bexpression*
12358Array_construction_expression::get_constructor(Translate_context* context,
12359 Btype* array_btype)
e440a328 12360{
e440a328 12361 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12362
12363 std::vector<unsigned long> indexes;
12364 std::vector<Bexpression*> vals;
12365 Gogo* gogo = context->gogo();
e440a328 12366 if (this->vals_ != NULL)
12367 {
12368 size_t i = 0;
ffe743ca 12369 std::vector<unsigned long>::const_iterator pi;
12370 if (this->indexes_ != NULL)
12371 pi = this->indexes_->begin();
e440a328 12372 for (Expression_list::const_iterator pv = this->vals_->begin();
12373 pv != this->vals_->end();
12374 ++pv, ++i)
12375 {
ffe743ca 12376 if (this->indexes_ != NULL)
12377 go_assert(pi != this->indexes_->end());
ffe743ca 12378
12379 if (this->indexes_ == NULL)
2c809f8f 12380 indexes.push_back(i);
ffe743ca 12381 else
2c809f8f 12382 indexes.push_back(*pi);
e440a328 12383 if (*pv == NULL)
63697958 12384 {
63697958 12385 Btype* ebtype = element_type->get_backend(gogo);
12386 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12387 vals.push_back(zv);
63697958 12388 }
e440a328 12389 else
12390 {
2c809f8f 12391 Expression* val_expr =
12392 Expression::convert_for_assignment(gogo, element_type, *pv,
12393 this->location());
12394 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
e440a328 12395 }
ffe743ca 12396 if (this->indexes_ != NULL)
12397 ++pi;
e440a328 12398 }
ffe743ca 12399 if (this->indexes_ != NULL)
12400 go_assert(pi == this->indexes_->end());
e440a328 12401 }
2c809f8f 12402 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12403 vals, this->location());
e440a328 12404}
12405
12406// Export an array construction.
12407
12408void
12409Array_construction_expression::do_export(Export* exp) const
12410{
12411 exp->write_c_string("convert(");
12412 exp->write_type(this->type_);
12413 if (this->vals_ != NULL)
12414 {
ffe743ca 12415 std::vector<unsigned long>::const_iterator pi;
12416 if (this->indexes_ != NULL)
12417 pi = this->indexes_->begin();
e440a328 12418 for (Expression_list::const_iterator pv = this->vals_->begin();
12419 pv != this->vals_->end();
12420 ++pv)
12421 {
12422 exp->write_c_string(", ");
ffe743ca 12423
12424 if (this->indexes_ != NULL)
12425 {
12426 char buf[100];
12427 snprintf(buf, sizeof buf, "%lu", *pi);
12428 exp->write_c_string(buf);
12429 exp->write_c_string(":");
12430 }
12431
e440a328 12432 if (*pv != NULL)
12433 (*pv)->export_expression(exp);
ffe743ca 12434
12435 if (this->indexes_ != NULL)
12436 ++pi;
e440a328 12437 }
12438 }
12439 exp->write_c_string(")");
12440}
12441
d751bb78 12442// Dump ast representation of an array construction expressin.
12443
12444void
12445Array_construction_expression::do_dump_expression(
12446 Ast_dump_context* ast_dump_context) const
12447{
ffe743ca 12448 Expression* length = this->type_->array_type()->length();
8b1c301d 12449
12450 ast_dump_context->ostream() << "[" ;
12451 if (length != NULL)
12452 {
12453 ast_dump_context->dump_expression(length);
12454 }
12455 ast_dump_context->ostream() << "]" ;
d751bb78 12456 ast_dump_context->dump_type(this->type_);
12457 ast_dump_context->ostream() << "{" ;
ffe743ca 12458 if (this->indexes_ == NULL)
12459 ast_dump_context->dump_expression_list(this->vals_);
12460 else
12461 {
12462 Expression_list::const_iterator pv = this->vals_->begin();
12463 for (std::vector<unsigned long>::const_iterator pi =
12464 this->indexes_->begin();
12465 pi != this->indexes_->end();
12466 ++pi, ++pv)
12467 {
12468 if (pi != this->indexes_->begin())
12469 ast_dump_context->ostream() << ", ";
12470 ast_dump_context->ostream() << *pi << ':';
12471 ast_dump_context->dump_expression(*pv);
12472 }
12473 }
d751bb78 12474 ast_dump_context->ostream() << "}" ;
12475
12476}
12477
e440a328 12478// Construct a fixed array.
12479
12480class Fixed_array_construction_expression :
12481 public Array_construction_expression
12482{
12483 public:
ffe743ca 12484 Fixed_array_construction_expression(Type* type,
12485 const std::vector<unsigned long>* indexes,
12486 Expression_list* vals, Location location)
e440a328 12487 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
ffe743ca 12488 type, indexes, vals, location)
12489 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12490
12491 protected:
12492 Expression*
12493 do_copy()
12494 {
12495 return new Fixed_array_construction_expression(this->type(),
ffe743ca 12496 this->indexes(),
e440a328 12497 (this->vals() == NULL
12498 ? NULL
12499 : this->vals()->copy()),
12500 this->location());
12501 }
12502
12503 tree
12504 do_get_tree(Translate_context*);
12505};
12506
12507// Return a tree for constructing a fixed array.
12508
12509tree
12510Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12511{
9f0e0513 12512 Type* type = this->type();
12513 Btype* btype = type->get_backend(context->gogo());
2c809f8f 12514 return expr_to_tree(this->get_constructor(context, btype));
e440a328 12515}
12516
2c809f8f 12517// Construct a slice.
e440a328 12518
2c809f8f 12519class Slice_construction_expression : public Array_construction_expression
e440a328 12520{
12521 public:
2c809f8f 12522 Slice_construction_expression(Type* type,
12523 const std::vector<unsigned long>* indexes,
12524 Expression_list* vals, Location location)
12525 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12526 type, indexes, vals, location),
12527 valtype_(NULL)
ffe743ca 12528 { go_assert(type->is_slice_type()); }
e440a328 12529
12530 protected:
2c809f8f 12531 // Note that taking the address of a slice literal is invalid.
e440a328 12532
12533 Expression*
12534 do_copy()
12535 {
2c809f8f 12536 return new Slice_construction_expression(this->type(), this->indexes(),
12537 (this->vals() == NULL
12538 ? NULL
12539 : this->vals()->copy()),
12540 this->location());
e440a328 12541 }
12542
12543 tree
12544 do_get_tree(Translate_context*);
2c809f8f 12545
12546 private:
12547 // The type of the values in this slice.
12548 Type* valtype_;
e440a328 12549};
12550
2c809f8f 12551// Return a tree for constructing a slice.
e440a328 12552
12553tree
2c809f8f 12554Slice_construction_expression::do_get_tree(Translate_context* context)
e440a328 12555{
f9c68f17 12556 Array_type* array_type = this->type()->array_type();
12557 if (array_type == NULL)
12558 {
c484d925 12559 go_assert(this->type()->is_error());
f9c68f17 12560 return error_mark_node;
12561 }
12562
12563 Type* element_type = array_type->element_type();
2c809f8f 12564 if (this->valtype_ == NULL)
12565 {
12566 mpz_t lenval;
12567 Expression* length;
12568 if (this->vals() == NULL || this->vals()->empty())
12569 mpz_init_set_ui(lenval, 0);
12570 else
12571 {
12572 if (this->indexes() == NULL)
12573 mpz_init_set_ui(lenval, this->vals()->size());
12574 else
12575 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12576 }
12577 Location loc = this->location();
12578 Type* int_type = Type::lookup_integer_type("int");
12579 length = Expression::make_integer(&lenval, int_type, loc);
12580 mpz_clear(lenval);
12581 this->valtype_ = Type::make_array_type(element_type, length);
12582 }
3d60812e 12583
e440a328 12584 tree values;
2c809f8f 12585 Gogo* gogo = context->gogo();
12586 Btype* val_btype = this->valtype_->get_backend(gogo);
e440a328 12587 if (this->vals() == NULL || this->vals()->empty())
12588 {
12589 // We need to create a unique value.
2c809f8f 12590 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
12591 Bexpression* zero = gogo->backend()->zero_expression(int_btype);
12592 std::vector<unsigned long> index(1, 0);
12593 std::vector<Bexpression*> val(1, zero);
12594 Bexpression* ctor =
12595 gogo->backend()->array_constructor_expression(val_btype, index, val,
12596 this->location());
12597 values = expr_to_tree(ctor);
e440a328 12598 }
12599 else
2c809f8f 12600 values = expr_to_tree(this->get_constructor(context, val_btype));
e440a328 12601
12602 if (values == error_mark_node)
12603 return error_mark_node;
12604
12605 bool is_constant_initializer = TREE_CONSTANT(values);
d8829beb 12606
12607 // We have to copy the initial values into heap memory if we are in
12608 // a function or if the values are not constants. We also have to
12609 // copy them if they may contain pointers in a non-constant context,
12610 // as otherwise the garbage collector won't see them.
12611 bool copy_to_heap = (context->function() != NULL
12612 || !is_constant_initializer
12613 || (element_type->has_pointer()
12614 && !context->is_const()));
e440a328 12615
12616 if (is_constant_initializer)
12617 {
b13c66cd 12618 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
e440a328 12619 create_tmp_var_name("C"), TREE_TYPE(values));
12620 DECL_EXTERNAL(tmp) = 0;
12621 TREE_PUBLIC(tmp) = 0;
12622 TREE_STATIC(tmp) = 1;
12623 DECL_ARTIFICIAL(tmp) = 1;
d8829beb 12624 if (copy_to_heap)
e440a328 12625 {
d8829beb 12626 // If we are not copying the value to the heap, we will only
12627 // initialize the value once, so we can use this directly
12628 // rather than copying it. In that case we can't make it
12629 // read-only, because the program is permitted to change it.
e440a328 12630 TREE_READONLY(tmp) = 1;
12631 TREE_CONSTANT(tmp) = 1;
12632 }
12633 DECL_INITIAL(tmp) = values;
12634 rest_of_decl_compilation(tmp, 1, 0);
12635 values = tmp;
12636 }
12637
12638 tree space;
12639 tree set;
d8829beb 12640 if (!copy_to_heap)
e440a328 12641 {
d8829beb 12642 // the initializer will only run once.
e440a328 12643 space = build_fold_addr_expr(values);
12644 set = NULL_TREE;
12645 }
12646 else
12647 {
2c809f8f 12648 Expression* alloc =
12649 context->gogo()->allocate_memory(this->valtype_, this->location());
12650 space = save_expr(alloc->get_tree(context));
e440a328 12651
12652 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
b13c66cd 12653 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12654 s);
e440a328 12655 TREE_THIS_NOTRAP(ref) = 1;
12656 set = build2(MODIFY_EXPR, void_type_node, ref, values);
12657 }
12658
2c809f8f 12659 // Build a constructor for the slice.
e440a328 12660
9f0e0513 12661 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
3d60812e 12662 if (type_tree == error_mark_node)
12663 return error_mark_node;
c484d925 12664 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
e440a328 12665
95f84544 12666 vec<constructor_elt, va_gc> *init;
12667 vec_alloc(init, 3);
e440a328 12668
e82e4eb5 12669 constructor_elt empty = {NULL, NULL};
95f84544 12670 constructor_elt* elt = init->quick_push(empty);
e440a328 12671 tree field = TYPE_FIELDS(type_tree);
c484d925 12672 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
e440a328 12673 elt->index = field;
12674 elt->value = fold_convert(TREE_TYPE(field), space);
12675
2c809f8f 12676 tree length_tree = this->valtype_->array_type()->length()->get_tree(context);
95f84544 12677 elt = init->quick_push(empty);
e440a328 12678 field = DECL_CHAIN(field);
c484d925 12679 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
e440a328 12680 elt->index = field;
12681 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12682
95f84544 12683 elt = init->quick_push(empty);
e440a328 12684 field = DECL_CHAIN(field);
c484d925 12685 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
e440a328 12686 elt->index = field;
12687 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12688
12689 tree constructor = build_constructor(type_tree, init);
3d60812e 12690 if (constructor == error_mark_node)
12691 return error_mark_node;
d8829beb 12692 if (!copy_to_heap)
e440a328 12693 TREE_CONSTANT(constructor) = 1;
12694
12695 if (set == NULL_TREE)
12696 return constructor;
12697 else
12698 return build2(COMPOUND_EXPR, type_tree, set, constructor);
12699}
12700
12701// Make a slice composite literal. This is used by the type
12702// descriptor code.
12703
12704Expression*
12705Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12706 Location location)
e440a328 12707{
411eb89e 12708 go_assert(type->is_slice_type());
2c809f8f 12709 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 12710}
12711
12712// Construct a map.
12713
12714class Map_construction_expression : public Expression
12715{
12716 public:
12717 Map_construction_expression(Type* type, Expression_list* vals,
b13c66cd 12718 Location location)
e440a328 12719 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
2c809f8f 12720 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
c484d925 12721 { go_assert(vals == NULL || vals->size() % 2 == 0); }
e440a328 12722
12723 protected:
12724 int
12725 do_traverse(Traverse* traverse);
12726
2c809f8f 12727 Expression*
12728 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12729
e440a328 12730 Type*
12731 do_type()
12732 { return this->type_; }
12733
12734 void
12735 do_determine_type(const Type_context*);
12736
12737 void
12738 do_check_types(Gogo*);
12739
12740 Expression*
12741 do_copy()
12742 {
12743 return new Map_construction_expression(this->type_, this->vals_->copy(),
12744 this->location());
12745 }
12746
12747 tree
12748 do_get_tree(Translate_context*);
12749
12750 void
12751 do_export(Export*) const;
12752
d751bb78 12753 void
12754 do_dump_expression(Ast_dump_context*) const;
12755
e440a328 12756 private:
12757 // The type of the map to construct.
12758 Type* type_;
12759 // The list of values.
12760 Expression_list* vals_;
2c809f8f 12761 // The type of the key-value pair struct for each map element.
12762 Struct_type* element_type_;
12763 // A temporary reference to the variable storing the constructor initializer.
12764 Temporary_statement* constructor_temp_;
e440a328 12765};
12766
12767// Traversal.
12768
12769int
12770Map_construction_expression::do_traverse(Traverse* traverse)
12771{
12772 if (this->vals_ != NULL
12773 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12774 return TRAVERSE_EXIT;
12775 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12776 return TRAVERSE_EXIT;
12777 return TRAVERSE_CONTINUE;
12778}
12779
2c809f8f 12780// Flatten constructor initializer into a temporary variable since
12781// we need to take its address for __go_construct_map.
12782
12783Expression*
12784Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12785 Statement_inserter* inserter)
12786{
12787 if (!this->is_error_expression()
12788 && this->vals_ != NULL
12789 && !this->vals_->empty()
12790 && this->constructor_temp_ == NULL)
12791 {
12792 Map_type* mt = this->type_->map_type();
12793 Type* key_type = mt->key_type();
12794 Type* val_type = mt->val_type();
12795 this->element_type_ = Type::make_builtin_struct_type(2,
12796 "__key", key_type,
12797 "__val", val_type);
12798
12799 Expression_list* value_pairs = new Expression_list();
12800 Location loc = this->location();
12801
12802 size_t i = 0;
12803 for (Expression_list::const_iterator pv = this->vals_->begin();
12804 pv != this->vals_->end();
12805 ++pv, ++i)
12806 {
12807 Expression_list* key_value_pair = new Expression_list();
12808 Expression* key =
12809 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12810
12811 ++pv;
12812 Expression* val =
12813 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12814
12815 key_value_pair->push_back(key);
12816 key_value_pair->push_back(val);
12817 value_pairs->push_back(
12818 Expression::make_struct_composite_literal(this->element_type_,
12819 key_value_pair, loc));
12820 }
12821
12822 mpz_t lenval;
12823 mpz_init_set_ui(lenval, i);
12824 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12825 mpz_clear(lenval);
12826
12827 Type* ctor_type =
12828 Type::make_array_type(this->element_type_, element_count);
12829 Expression* constructor =
12830 new Fixed_array_construction_expression(ctor_type, NULL,
12831 value_pairs, loc);
12832
12833 this->constructor_temp_ =
12834 Statement::make_temporary(NULL, constructor, loc);
12835 constructor->issue_nil_check();
12836 this->constructor_temp_->set_is_address_taken();
12837 inserter->insert(this->constructor_temp_);
12838 }
12839
12840 return this;
12841}
12842
e440a328 12843// Final type determination.
12844
12845void
12846Map_construction_expression::do_determine_type(const Type_context*)
12847{
12848 if (this->vals_ == NULL)
12849 return;
12850
12851 Map_type* mt = this->type_->map_type();
12852 Type_context key_context(mt->key_type(), false);
12853 Type_context val_context(mt->val_type(), false);
12854 for (Expression_list::const_iterator pv = this->vals_->begin();
12855 pv != this->vals_->end();
12856 ++pv)
12857 {
12858 (*pv)->determine_type(&key_context);
12859 ++pv;
12860 (*pv)->determine_type(&val_context);
12861 }
12862}
12863
12864// Check types.
12865
12866void
12867Map_construction_expression::do_check_types(Gogo*)
12868{
12869 if (this->vals_ == NULL)
12870 return;
12871
12872 Map_type* mt = this->type_->map_type();
12873 int i = 0;
12874 Type* key_type = mt->key_type();
12875 Type* val_type = mt->val_type();
12876 for (Expression_list::const_iterator pv = this->vals_->begin();
12877 pv != this->vals_->end();
12878 ++pv, ++i)
12879 {
12880 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12881 {
12882 error_at((*pv)->location(),
12883 "incompatible type for element %d key in map construction",
12884 i + 1);
12885 this->set_is_error();
12886 }
12887 ++pv;
12888 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12889 {
12890 error_at((*pv)->location(),
12891 ("incompatible type for element %d value "
12892 "in map construction"),
12893 i + 1);
12894 this->set_is_error();
12895 }
12896 }
12897}
12898
12899// Return a tree for constructing a map.
12900
12901tree
12902Map_construction_expression::do_get_tree(Translate_context* context)
12903{
2c809f8f 12904 if (this->is_error_expression())
5845bde6 12905 return error_mark_node;
2c809f8f 12906 Location loc = this->location();
e440a328 12907
e440a328 12908 size_t i = 0;
2c809f8f 12909 Expression* ventries;
e440a328 12910 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 12911 ventries = Expression::make_nil(loc);
e440a328 12912 else
12913 {
2c809f8f 12914 go_assert(this->constructor_temp_ != NULL);
12915 i = this->vals_->size() / 2;
e440a328 12916
2c809f8f 12917 Expression* ctor_ref =
12918 Expression::make_temporary_reference(this->constructor_temp_, loc);
12919 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12920 }
e440a328 12921
2c809f8f 12922 Map_type* mt = this->type_->map_type();
12923 if (this->element_type_ == NULL)
12924 this->element_type_ =
12925 Type::make_builtin_struct_type(2,
12926 "__key", mt->key_type(),
12927 "__val", mt->val_type());
12928 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12929
12930 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12931 mpz_t countval;
12932 mpz_init_set_ui(countval, i);
12933 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12934 mpz_clear(countval);
12935
12936 Expression* entry_size =
12937 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12938
12939 unsigned int field_index;
12940 const Struct_field* valfield =
12941 this->element_type_->find_local_field("__val", &field_index);
12942 Expression* val_offset =
12943 Expression::make_struct_field_offset(this->element_type_, valfield);
12944 Expression* val_size =
12945 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12946
12947 Expression* map_ctor =
12948 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12949 entry_size, val_offset, val_size, ventries);
12950 return map_ctor->get_tree(context);
12951}
e440a328 12952
2c809f8f 12953// Export an array construction.
e440a328 12954
2c809f8f 12955void
12956Map_construction_expression::do_export(Export* exp) const
12957{
12958 exp->write_c_string("convert(");
12959 exp->write_type(this->type_);
12960 for (Expression_list::const_iterator pv = this->vals_->begin();
12961 pv != this->vals_->end();
12962 ++pv)
12963 {
12964 exp->write_c_string(", ");
12965 (*pv)->export_expression(exp);
12966 }
12967 exp->write_c_string(")");
12968}
e440a328 12969
2c809f8f 12970// Dump ast representation for a map construction expression.
d751bb78 12971
12972void
12973Map_construction_expression::do_dump_expression(
12974 Ast_dump_context* ast_dump_context) const
12975{
d751bb78 12976 ast_dump_context->ostream() << "{" ;
8b1c301d 12977 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 12978 ast_dump_context->ostream() << "}";
12979}
12980
e440a328 12981// A general composite literal. This is lowered to a type specific
12982// version.
12983
12984class Composite_literal_expression : public Parser_expression
12985{
12986 public:
12987 Composite_literal_expression(Type* type, int depth, bool has_keys,
62750cd5 12988 Expression_list* vals, bool all_are_names,
12989 Location location)
e440a328 12990 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
62750cd5 12991 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12992 all_are_names_(all_are_names)
e440a328 12993 { }
12994
12995 protected:
12996 int
12997 do_traverse(Traverse* traverse);
12998
12999 Expression*
ceeb4318 13000 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 13001
13002 Expression*
13003 do_copy()
13004 {
13005 return new Composite_literal_expression(this->type_, this->depth_,
13006 this->has_keys_,
13007 (this->vals_ == NULL
13008 ? NULL
13009 : this->vals_->copy()),
62750cd5 13010 this->all_are_names_,
e440a328 13011 this->location());
13012 }
13013
d751bb78 13014 void
13015 do_dump_expression(Ast_dump_context*) const;
13016
e440a328 13017 private:
13018 Expression*
81c4b26b 13019 lower_struct(Gogo*, Type*);
e440a328 13020
13021 Expression*
113ef6a5 13022 lower_array(Type*);
e440a328 13023
13024 Expression*
ffe743ca 13025 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
e440a328 13026
13027 Expression*
ceeb4318 13028 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
e440a328 13029
13030 // The type of the composite literal.
13031 Type* type_;
13032 // The depth within a list of composite literals within a composite
13033 // literal, when the type is omitted.
13034 int depth_;
13035 // The values to put in the composite literal.
13036 Expression_list* vals_;
13037 // If this is true, then VALS_ is a list of pairs: a key and a
13038 // value. In an array initializer, a missing key will be NULL.
13039 bool has_keys_;
62750cd5 13040 // If this is true, then HAS_KEYS_ is true, and every key is a
13041 // simple identifier.
13042 bool all_are_names_;
e440a328 13043};
13044
13045// Traversal.
13046
13047int
13048Composite_literal_expression::do_traverse(Traverse* traverse)
13049{
dbffccfc 13050 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 13051 return TRAVERSE_EXIT;
dbffccfc 13052
13053 // If this is a struct composite literal with keys, then the keys
13054 // are field names, not expressions. We don't want to traverse them
13055 // in that case. If we do, we can give an erroneous error "variable
13056 // initializer refers to itself." See bug482.go in the testsuite.
13057 if (this->has_keys_ && this->vals_ != NULL)
13058 {
13059 // The type may not be resolvable at this point.
13060 Type* type = this->type_;
a01f2481 13061
13062 for (int depth = this->depth_; depth > 0; --depth)
13063 {
13064 if (type->array_type() != NULL)
13065 type = type->array_type()->element_type();
13066 else if (type->map_type() != NULL)
13067 type = type->map_type()->val_type();
13068 else
13069 {
13070 // This error will be reported during lowering.
13071 return TRAVERSE_CONTINUE;
13072 }
13073 }
13074
dbffccfc 13075 while (true)
13076 {
13077 if (type->classification() == Type::TYPE_NAMED)
13078 type = type->named_type()->real_type();
13079 else if (type->classification() == Type::TYPE_FORWARD)
13080 {
13081 Type* t = type->forwarded();
13082 if (t == type)
13083 break;
13084 type = t;
13085 }
13086 else
13087 break;
13088 }
13089
13090 if (type->classification() == Type::TYPE_STRUCT)
13091 {
13092 Expression_list::iterator p = this->vals_->begin();
13093 while (p != this->vals_->end())
13094 {
13095 // Skip key.
13096 ++p;
13097 go_assert(p != this->vals_->end());
13098 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13099 return TRAVERSE_EXIT;
13100 ++p;
13101 }
13102 return TRAVERSE_CONTINUE;
13103 }
13104 }
13105
13106 if (this->vals_ != NULL)
13107 return this->vals_->traverse(traverse);
13108
13109 return TRAVERSE_CONTINUE;
e440a328 13110}
13111
13112// Lower a generic composite literal into a specific version based on
13113// the type.
13114
13115Expression*
ceeb4318 13116Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13117 Statement_inserter* inserter, int)
e440a328 13118{
13119 Type* type = this->type_;
13120
13121 for (int depth = this->depth_; depth > 0; --depth)
13122 {
13123 if (type->array_type() != NULL)
13124 type = type->array_type()->element_type();
13125 else if (type->map_type() != NULL)
13126 type = type->map_type()->val_type();
13127 else
13128 {
5c13bd80 13129 if (!type->is_error())
e440a328 13130 error_at(this->location(),
13131 ("may only omit types within composite literals "
13132 "of slice, array, or map type"));
13133 return Expression::make_error(this->location());
13134 }
13135 }
13136
e00772b3 13137 Type *pt = type->points_to();
13138 bool is_pointer = false;
13139 if (pt != NULL)
13140 {
13141 is_pointer = true;
13142 type = pt;
13143 }
13144
13145 Expression* ret;
5c13bd80 13146 if (type->is_error())
e440a328 13147 return Expression::make_error(this->location());
13148 else if (type->struct_type() != NULL)
e00772b3 13149 ret = this->lower_struct(gogo, type);
e440a328 13150 else if (type->array_type() != NULL)
113ef6a5 13151 ret = this->lower_array(type);
e440a328 13152 else if (type->map_type() != NULL)
e00772b3 13153 ret = this->lower_map(gogo, function, inserter, type);
e440a328 13154 else
13155 {
13156 error_at(this->location(),
13157 ("expected struct, slice, array, or map type "
13158 "for composite literal"));
13159 return Expression::make_error(this->location());
13160 }
e00772b3 13161
13162 if (is_pointer)
2c809f8f 13163 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13164
13165 return ret;
e440a328 13166}
13167
13168// Lower a struct composite literal.
13169
13170Expression*
81c4b26b 13171Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13172{
b13c66cd 13173 Location location = this->location();
e440a328 13174 Struct_type* st = type->struct_type();
13175 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13176 {
e6013c28 13177 if (this->vals_ != NULL
13178 && !this->vals_->empty()
13179 && type->named_type() != NULL
13180 && type->named_type()->named_object()->package() != NULL)
13181 {
13182 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13183 pf != st->fields()->end();
13184 ++pf)
07daa4e7 13185 {
e6013c28 13186 if (Gogo::is_hidden_name(pf->field_name()))
07daa4e7 13187 error_at(this->location(),
e6013c28 13188 "assignment of unexported field %qs in %qs literal",
13189 Gogo::message_name(pf->field_name()).c_str(),
13190 type->named_type()->message_name().c_str());
07daa4e7 13191 }
13192 }
13193
13194 return new Struct_construction_expression(type, this->vals_, location);
13195 }
e440a328 13196
13197 size_t field_count = st->field_count();
13198 std::vector<Expression*> vals(field_count);
0c4f5a19 13199 std::vector<int>* traverse_order = new(std::vector<int>);
e440a328 13200 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13201 Expression* external_expr = NULL;
13202 const Named_object* external_no = NULL;
e440a328 13203 while (p != this->vals_->end())
13204 {
13205 Expression* name_expr = *p;
13206
13207 ++p;
c484d925 13208 go_assert(p != this->vals_->end());
e440a328 13209 Expression* val = *p;
13210
13211 ++p;
13212
13213 if (name_expr == NULL)
13214 {
13215 error_at(val->location(), "mixture of field and value initializers");
13216 return Expression::make_error(location);
13217 }
13218
13219 bool bad_key = false;
13220 std::string name;
81c4b26b 13221 const Named_object* no = NULL;
e440a328 13222 switch (name_expr->classification())
13223 {
13224 case EXPRESSION_UNKNOWN_REFERENCE:
13225 name = name_expr->unknown_expression()->name();
13226 break;
13227
13228 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13229 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13230 break;
13231
13232 case EXPRESSION_TYPE:
13233 {
13234 Type* t = name_expr->type();
13235 Named_type* nt = t->named_type();
13236 if (nt == NULL)
13237 bad_key = true;
13238 else
81c4b26b 13239 no = nt->named_object();
e440a328 13240 }
13241 break;
13242
13243 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13244 no = name_expr->var_expression()->named_object();
e440a328 13245 break;
13246
13247 case EXPRESSION_FUNC_REFERENCE:
81c4b26b 13248 no = name_expr->func_expression()->named_object();
e440a328 13249 break;
13250
13251 case EXPRESSION_UNARY:
13252 // If there is a local variable around with the same name as
13253 // the field, and this occurs in the closure, then the
13254 // parser may turn the field reference into an indirection
13255 // through the closure. FIXME: This is a mess.
13256 {
13257 bad_key = true;
13258 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13259 if (ue->op() == OPERATOR_MULT)
13260 {
13261 Field_reference_expression* fre =
13262 ue->operand()->field_reference_expression();
13263 if (fre != NULL)
13264 {
13265 Struct_type* st =
13266 fre->expr()->type()->deref()->struct_type();
13267 if (st != NULL)
13268 {
13269 const Struct_field* sf = st->field(fre->field_index());
13270 name = sf->field_name();
2d29d278 13271
13272 // See below. FIXME.
13273 if (!Gogo::is_hidden_name(name)
13274 && name[0] >= 'a'
13275 && name[0] <= 'z')
13276 {
13277 if (gogo->lookup_global(name.c_str()) != NULL)
13278 name = gogo->pack_hidden_name(name, false);
13279 }
13280
e440a328 13281 char buf[20];
13282 snprintf(buf, sizeof buf, "%u", fre->field_index());
13283 size_t buflen = strlen(buf);
13284 if (name.compare(name.length() - buflen, buflen, buf)
13285 == 0)
13286 {
13287 name = name.substr(0, name.length() - buflen);
13288 bad_key = false;
13289 }
13290 }
13291 }
13292 }
13293 }
13294 break;
13295
13296 default:
13297 bad_key = true;
13298 break;
13299 }
13300 if (bad_key)
13301 {
13302 error_at(name_expr->location(), "expected struct field name");
13303 return Expression::make_error(location);
13304 }
13305
81c4b26b 13306 if (no != NULL)
13307 {
62750cd5 13308 if (no->package() != NULL && external_expr == NULL)
13309 {
13310 external_expr = name_expr;
13311 external_no = no;
13312 }
13313
81c4b26b 13314 name = no->name();
13315
13316 // A predefined name won't be packed. If it starts with a
13317 // lower case letter we need to check for that case, because
2d29d278 13318 // the field name will be packed. FIXME.
81c4b26b 13319 if (!Gogo::is_hidden_name(name)
13320 && name[0] >= 'a'
13321 && name[0] <= 'z')
13322 {
13323 Named_object* gno = gogo->lookup_global(name.c_str());
13324 if (gno == no)
13325 name = gogo->pack_hidden_name(name, false);
13326 }
13327 }
13328
e440a328 13329 unsigned int index;
13330 const Struct_field* sf = st->find_local_field(name, &index);
13331 if (sf == NULL)
13332 {
13333 error_at(name_expr->location(), "unknown field %qs in %qs",
13334 Gogo::message_name(name).c_str(),
13335 (type->named_type() != NULL
13336 ? type->named_type()->message_name().c_str()
13337 : "unnamed struct"));
13338 return Expression::make_error(location);
13339 }
13340 if (vals[index] != NULL)
13341 {
13342 error_at(name_expr->location(),
13343 "duplicate value for field %qs in %qs",
13344 Gogo::message_name(name).c_str(),
13345 (type->named_type() != NULL
13346 ? type->named_type()->message_name().c_str()
13347 : "unnamed struct"));
13348 return Expression::make_error(location);
13349 }
13350
07daa4e7 13351 if (type->named_type() != NULL
13352 && type->named_type()->named_object()->package() != NULL
13353 && Gogo::is_hidden_name(sf->field_name()))
13354 error_at(name_expr->location(),
13355 "assignment of unexported field %qs in %qs literal",
13356 Gogo::message_name(sf->field_name()).c_str(),
13357 type->named_type()->message_name().c_str());
07daa4e7 13358
e440a328 13359 vals[index] = val;
0c4f5a19 13360 traverse_order->push_back(index);
e440a328 13361 }
13362
62750cd5 13363 if (!this->all_are_names_)
13364 {
13365 // This is a weird case like bug462 in the testsuite.
13366 if (external_expr == NULL)
13367 error_at(this->location(), "unknown field in %qs literal",
13368 (type->named_type() != NULL
13369 ? type->named_type()->message_name().c_str()
13370 : "unnamed struct"));
13371 else
13372 error_at(external_expr->location(), "unknown field %qs in %qs",
13373 external_no->message_name().c_str(),
13374 (type->named_type() != NULL
13375 ? type->named_type()->message_name().c_str()
13376 : "unnamed struct"));
13377 return Expression::make_error(location);
13378 }
13379
e440a328 13380 Expression_list* list = new Expression_list;
13381 list->reserve(field_count);
13382 for (size_t i = 0; i < field_count; ++i)
13383 list->push_back(vals[i]);
13384
0c4f5a19 13385 Struct_construction_expression* ret =
13386 new Struct_construction_expression(type, list, location);
13387 ret->set_traverse_order(traverse_order);
13388 return ret;
e440a328 13389}
13390
00773463 13391// Used to sort an index/value array.
13392
13393class Index_value_compare
13394{
13395 public:
13396 bool
13397 operator()(const std::pair<unsigned long, Expression*>& a,
13398 const std::pair<unsigned long, Expression*>& b)
13399 { return a.first < b.first; }
13400};
13401
e440a328 13402// Lower an array composite literal.
13403
13404Expression*
113ef6a5 13405Composite_literal_expression::lower_array(Type* type)
e440a328 13406{
b13c66cd 13407 Location location = this->location();
e440a328 13408 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13409 return this->make_array(type, NULL, this->vals_);
e440a328 13410
ffe743ca 13411 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13412 indexes->reserve(this->vals_->size());
00773463 13413 bool indexes_out_of_order = false;
ffe743ca 13414 Expression_list* vals = new Expression_list();
13415 vals->reserve(this->vals_->size());
e440a328 13416 unsigned long index = 0;
13417 Expression_list::const_iterator p = this->vals_->begin();
13418 while (p != this->vals_->end())
13419 {
13420 Expression* index_expr = *p;
13421
13422 ++p;
c484d925 13423 go_assert(p != this->vals_->end());
e440a328 13424 Expression* val = *p;
13425
13426 ++p;
13427
ffe743ca 13428 if (index_expr == NULL)
13429 {
13430 if (!indexes->empty())
13431 indexes->push_back(index);
13432 }
13433 else
e440a328 13434 {
ffe743ca 13435 if (indexes->empty() && !vals->empty())
13436 {
13437 for (size_t i = 0; i < vals->size(); ++i)
13438 indexes->push_back(i);
13439 }
13440
0c77715b 13441 Numeric_constant nc;
13442 if (!index_expr->numeric_constant_value(&nc))
e440a328 13443 {
e440a328 13444 error_at(index_expr->location(),
13445 "index expression is not integer constant");
13446 return Expression::make_error(location);
13447 }
6f6d9955 13448
0c77715b 13449 switch (nc.to_unsigned_long(&index))
e440a328 13450 {
0c77715b 13451 case Numeric_constant::NC_UL_VALID:
13452 break;
13453 case Numeric_constant::NC_UL_NOTINT:
13454 error_at(index_expr->location(),
13455 "index expression is not integer constant");
13456 return Expression::make_error(location);
13457 case Numeric_constant::NC_UL_NEGATIVE:
e440a328 13458 error_at(index_expr->location(), "index expression is negative");
13459 return Expression::make_error(location);
0c77715b 13460 case Numeric_constant::NC_UL_BIG:
e440a328 13461 error_at(index_expr->location(), "index value overflow");
13462 return Expression::make_error(location);
0c77715b 13463 default:
13464 go_unreachable();
e440a328 13465 }
6f6d9955 13466
13467 Named_type* ntype = Type::lookup_integer_type("int");
13468 Integer_type* inttype = ntype->integer_type();
0c77715b 13469 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13470 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13471 {
6f6d9955 13472 error_at(index_expr->location(), "index value overflow");
13473 return Expression::make_error(location);
13474 }
13475
ffe743ca 13476 if (std::find(indexes->begin(), indexes->end(), index)
13477 != indexes->end())
e440a328 13478 {
ffe743ca 13479 error_at(index_expr->location(), "duplicate value for index %lu",
e440a328 13480 index);
13481 return Expression::make_error(location);
13482 }
ffe743ca 13483
00773463 13484 if (!indexes->empty() && index < indexes->back())
13485 indexes_out_of_order = true;
13486
ffe743ca 13487 indexes->push_back(index);
e440a328 13488 }
13489
ffe743ca 13490 vals->push_back(val);
13491
e440a328 13492 ++index;
13493 }
13494
ffe743ca 13495 if (indexes->empty())
13496 {
13497 delete indexes;
13498 indexes = NULL;
13499 }
e440a328 13500
00773463 13501 if (indexes_out_of_order)
13502 {
13503 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13504
13505 V v;
13506 v.reserve(indexes->size());
13507 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13508 for (Expression_list::const_iterator pe = vals->begin();
13509 pe != vals->end();
13510 ++pe, ++pi)
13511 v.push_back(std::make_pair(*pi, *pe));
13512
13513 std::sort(v.begin(), v.end(), Index_value_compare());
13514
13515 delete indexes;
13516 delete vals;
13517 indexes = new std::vector<unsigned long>();
13518 indexes->reserve(v.size());
13519 vals = new Expression_list();
13520 vals->reserve(v.size());
13521
13522 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13523 {
13524 indexes->push_back(p->first);
13525 vals->push_back(p->second);
13526 }
13527 }
13528
ffe743ca 13529 return this->make_array(type, indexes, vals);
e440a328 13530}
13531
13532// Actually build the array composite literal. This handles
13533// [...]{...}.
13534
13535Expression*
ffe743ca 13536Composite_literal_expression::make_array(
13537 Type* type,
13538 const std::vector<unsigned long>* indexes,
13539 Expression_list* vals)
e440a328 13540{
b13c66cd 13541 Location location = this->location();
e440a328 13542 Array_type* at = type->array_type();
ffe743ca 13543
e440a328 13544 if (at->length() != NULL && at->length()->is_nil_expression())
13545 {
ffe743ca 13546 size_t size;
13547 if (vals == NULL)
13548 size = 0;
00773463 13549 else if (indexes != NULL)
13550 size = indexes->back() + 1;
13551 else
ffe743ca 13552 {
13553 size = vals->size();
13554 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13555 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13556 && size >> (it->bits() - 1) != 0)
13557 {
13558 error_at(location, "too many elements in composite literal");
13559 return Expression::make_error(location);
13560 }
13561 }
ffe743ca 13562
e440a328 13563 mpz_t vlen;
13564 mpz_init_set_ui(vlen, size);
13565 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13566 mpz_clear(vlen);
13567 at = Type::make_array_type(at->element_type(), elen);
13568 type = at;
13569 }
ffe743ca 13570 else if (at->length() != NULL
13571 && !at->length()->is_error_expression()
13572 && this->vals_ != NULL)
13573 {
13574 Numeric_constant nc;
13575 unsigned long val;
13576 if (at->length()->numeric_constant_value(&nc)
13577 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13578 {
13579 if (indexes == NULL)
13580 {
13581 if (this->vals_->size() > val)
13582 {
13583 error_at(location, "too many elements in composite literal");
13584 return Expression::make_error(location);
13585 }
13586 }
13587 else
13588 {
00773463 13589 unsigned long max = indexes->back();
ffe743ca 13590 if (max >= val)
13591 {
13592 error_at(location,
13593 ("some element keys in composite literal "
13594 "are out of range"));
13595 return Expression::make_error(location);
13596 }
13597 }
13598 }
13599 }
13600
e440a328 13601 if (at->length() != NULL)
ffe743ca 13602 return new Fixed_array_construction_expression(type, indexes, vals,
13603 location);
e440a328 13604 else
2c809f8f 13605 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13606}
13607
13608// Lower a map composite literal.
13609
13610Expression*
a287720d 13611Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13612 Statement_inserter* inserter,
a287720d 13613 Type* type)
e440a328 13614{
b13c66cd 13615 Location location = this->location();
e440a328 13616 if (this->vals_ != NULL)
13617 {
13618 if (!this->has_keys_)
13619 {
13620 error_at(location, "map composite literal must have keys");
13621 return Expression::make_error(location);
13622 }
13623
a287720d 13624 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13625 p != this->vals_->end();
13626 p += 2)
13627 {
13628 if (*p == NULL)
13629 {
13630 ++p;
13631 error_at((*p)->location(),
13632 "map composite literal must have keys for every value");
13633 return Expression::make_error(location);
13634 }
a287720d 13635 // Make sure we have lowered the key; it may not have been
13636 // lowered in order to handle keys for struct composite
13637 // literals. Lower it now to get the right error message.
13638 if ((*p)->unknown_expression() != NULL)
13639 {
13640 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13641 gogo->lower_expression(function, inserter, &*p);
c484d925 13642 go_assert((*p)->is_error_expression());
a287720d 13643 return Expression::make_error(location);
13644 }
e440a328 13645 }
13646 }
13647
13648 return new Map_construction_expression(type, this->vals_, location);
13649}
13650
d751bb78 13651// Dump ast representation for a composite literal expression.
13652
13653void
13654Composite_literal_expression::do_dump_expression(
13655 Ast_dump_context* ast_dump_context) const
13656{
8b1c301d 13657 ast_dump_context->ostream() << "composite(";
d751bb78 13658 ast_dump_context->dump_type(this->type_);
13659 ast_dump_context->ostream() << ", {";
8b1c301d 13660 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13661 ast_dump_context->ostream() << "})";
13662}
13663
e440a328 13664// Make a composite literal expression.
13665
13666Expression*
13667Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13668 Expression_list* vals, bool all_are_names,
b13c66cd 13669 Location location)
e440a328 13670{
13671 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13672 all_are_names, location);
e440a328 13673}
13674
13675// Return whether this expression is a composite literal.
13676
13677bool
13678Expression::is_composite_literal() const
13679{
13680 switch (this->classification_)
13681 {
13682 case EXPRESSION_COMPOSITE_LITERAL:
13683 case EXPRESSION_STRUCT_CONSTRUCTION:
13684 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13685 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13686 case EXPRESSION_MAP_CONSTRUCTION:
13687 return true;
13688 default:
13689 return false;
13690 }
13691}
13692
13693// Return whether this expression is a composite literal which is not
13694// constant.
13695
13696bool
13697Expression::is_nonconstant_composite_literal() const
13698{
13699 switch (this->classification_)
13700 {
13701 case EXPRESSION_STRUCT_CONSTRUCTION:
13702 {
13703 const Struct_construction_expression *psce =
13704 static_cast<const Struct_construction_expression*>(this);
13705 return !psce->is_constant_struct();
13706 }
13707 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13708 {
13709 const Fixed_array_construction_expression *pace =
13710 static_cast<const Fixed_array_construction_expression*>(this);
13711 return !pace->is_constant_array();
13712 }
2c809f8f 13713 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13714 {
2c809f8f 13715 const Slice_construction_expression *pace =
13716 static_cast<const Slice_construction_expression*>(this);
e440a328 13717 return !pace->is_constant_array();
13718 }
13719 case EXPRESSION_MAP_CONSTRUCTION:
13720 return true;
13721 default:
13722 return false;
13723 }
13724}
13725
35a54f17 13726// Return true if this is a variable or temporary_variable.
13727
13728bool
13729Expression::is_variable() const
13730{
13731 switch (this->classification_)
13732 {
13733 case EXPRESSION_VAR_REFERENCE:
13734 case EXPRESSION_TEMPORARY_REFERENCE:
13735 case EXPRESSION_SET_AND_USE_TEMPORARY:
13736 return true;
13737 default:
13738 return false;
13739 }
13740}
13741
e440a328 13742// Return true if this is a reference to a local variable.
13743
13744bool
13745Expression::is_local_variable() const
13746{
13747 const Var_expression* ve = this->var_expression();
13748 if (ve == NULL)
13749 return false;
13750 const Named_object* no = ve->named_object();
13751 return (no->is_result_variable()
13752 || (no->is_variable() && !no->var_value()->is_global()));
13753}
13754
13755// Class Type_guard_expression.
13756
13757// Traversal.
13758
13759int
13760Type_guard_expression::do_traverse(Traverse* traverse)
13761{
13762 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13763 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13764 return TRAVERSE_EXIT;
13765 return TRAVERSE_CONTINUE;
13766}
13767
2c809f8f 13768Expression*
13769Type_guard_expression::do_flatten(Gogo*, Named_object*,
13770 Statement_inserter* inserter)
13771{
13772 if (!this->expr_->is_variable())
13773 {
13774 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13775 this->location());
13776 inserter->insert(temp);
13777 this->expr_ =
13778 Expression::make_temporary_reference(temp, this->location());
13779 }
13780 return this;
13781}
13782
e440a328 13783// Check types of a type guard expression. The expression must have
13784// an interface type, but the actual type conversion is checked at run
13785// time.
13786
13787void
13788Type_guard_expression::do_check_types(Gogo*)
13789{
e440a328 13790 Type* expr_type = this->expr_->type();
7e9da23f 13791 if (expr_type->interface_type() == NULL)
f725ade8 13792 {
5c13bd80 13793 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 13794 this->report_error(_("type assertion only valid for interface types"));
13795 this->set_is_error();
13796 }
e440a328 13797 else if (this->type_->interface_type() == NULL)
13798 {
13799 std::string reason;
13800 if (!expr_type->interface_type()->implements_interface(this->type_,
13801 &reason))
13802 {
5c13bd80 13803 if (!this->type_->is_error())
e440a328 13804 {
f725ade8 13805 if (reason.empty())
13806 this->report_error(_("impossible type assertion: "
13807 "type does not implement interface"));
13808 else
13809 error_at(this->location(),
13810 ("impossible type assertion: "
13811 "type does not implement interface (%s)"),
13812 reason.c_str());
e440a328 13813 }
f725ade8 13814 this->set_is_error();
e440a328 13815 }
13816 }
13817}
13818
13819// Return a tree for a type guard expression.
13820
13821tree
13822Type_guard_expression::do_get_tree(Translate_context* context)
13823{
2c809f8f 13824 Expression* conversion;
7e9da23f 13825 if (this->type_->interface_type() != NULL)
2c809f8f 13826 conversion =
13827 Expression::convert_interface_to_interface(this->type_, this->expr_,
13828 true, this->location());
e440a328 13829 else
2c809f8f 13830 conversion =
13831 Expression::convert_for_assignment(context->gogo(), this->type_,
13832 this->expr_, this->location());
13833
13834 return conversion->get_tree(context);
e440a328 13835}
13836
d751bb78 13837// Dump ast representation for a type guard expression.
13838
13839void
2c809f8f 13840Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 13841 const
13842{
13843 this->expr_->dump_expression(ast_dump_context);
13844 ast_dump_context->ostream() << ".";
13845 ast_dump_context->dump_type(this->type_);
13846}
13847
e440a328 13848// Make a type guard expression.
13849
13850Expression*
13851Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 13852 Location location)
e440a328 13853{
13854 return new Type_guard_expression(expr, type, location);
13855}
13856
2c809f8f 13857// Class Heap_expression.
e440a328 13858
2c809f8f 13859// When you take the address of an escaping expression, it is allocated
e440a328 13860// on the heap. This class implements that.
13861
2c809f8f 13862class Heap_expression : public Expression
e440a328 13863{
13864 public:
2c809f8f 13865 Heap_expression(Expression* expr, Location location)
13866 : Expression(EXPRESSION_HEAP, location),
e440a328 13867 expr_(expr)
13868 { }
13869
13870 protected:
13871 int
13872 do_traverse(Traverse* traverse)
13873 { return Expression::traverse(&this->expr_, traverse); }
13874
13875 Type*
13876 do_type()
13877 { return Type::make_pointer_type(this->expr_->type()); }
13878
13879 void
13880 do_determine_type(const Type_context*)
13881 { this->expr_->determine_type_no_context(); }
13882
13883 Expression*
13884 do_copy()
13885 {
2c809f8f 13886 return Expression::make_heap_expression(this->expr_->copy(),
13887 this->location());
e440a328 13888 }
13889
13890 tree
13891 do_get_tree(Translate_context*);
13892
13893 // We only export global objects, and the parser does not generate
13894 // this in global scope.
13895 void
13896 do_export(Export*) const
c3e6f413 13897 { go_unreachable(); }
e440a328 13898
d751bb78 13899 void
13900 do_dump_expression(Ast_dump_context*) const;
13901
e440a328 13902 private:
2c809f8f 13903 // The expression which is being put on the heap.
e440a328 13904 Expression* expr_;
13905};
13906
2c809f8f 13907// Return a tree which allocates an expression on the heap.
e440a328 13908
13909tree
2c809f8f 13910Heap_expression::do_get_tree(Translate_context* context)
e440a328 13911{
13912 tree expr_tree = this->expr_->get_tree(context);
6d3ed74c 13913 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
e440a328 13914 return error_mark_node;
2c809f8f 13915
13916 Expression* alloc =
13917 Expression::make_allocation(this->expr_->type(), this->location());
13918
13919 Gogo* gogo = context->gogo();
13920 Btype* btype = this->expr_->type()->get_backend(gogo);
13921 size_t expr_size = gogo->backend()->type_size(btype);
13922 tree space = alloc->get_tree(context);
13923 if (expr_size == 0)
13924 return space;
13925
e440a328 13926 space = save_expr(space);
b13c66cd 13927 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13928 space);
e440a328 13929 TREE_THIS_NOTRAP(ref) = 1;
2c809f8f 13930 tree ret = build2(COMPOUND_EXPR,
13931 type_to_tree(this->type()->get_backend(gogo)),
e440a328 13932 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13933 space);
b13c66cd 13934 SET_EXPR_LOCATION(ret, this->location().gcc_location());
e440a328 13935 return ret;
13936}
13937
2c809f8f 13938// Dump ast representation for a heap expression.
d751bb78 13939
13940void
2c809f8f 13941Heap_expression::do_dump_expression(
d751bb78 13942 Ast_dump_context* ast_dump_context) const
13943{
13944 ast_dump_context->ostream() << "&(";
13945 ast_dump_context->dump_expression(this->expr_);
13946 ast_dump_context->ostream() << ")";
13947}
13948
2c809f8f 13949// Allocate an expression on the heap.
e440a328 13950
13951Expression*
2c809f8f 13952Expression::make_heap_expression(Expression* expr, Location location)
e440a328 13953{
2c809f8f 13954 return new Heap_expression(expr, location);
e440a328 13955}
13956
13957// Class Receive_expression.
13958
13959// Return the type of a receive expression.
13960
13961Type*
13962Receive_expression::do_type()
13963{
13964 Channel_type* channel_type = this->channel_->type()->channel_type();
13965 if (channel_type == NULL)
13966 return Type::make_error_type();
13967 return channel_type->element_type();
13968}
13969
13970// Check types for a receive expression.
13971
13972void
13973Receive_expression::do_check_types(Gogo*)
13974{
13975 Type* type = this->channel_->type();
5c13bd80 13976 if (type->is_error())
e440a328 13977 {
13978 this->set_is_error();
13979 return;
13980 }
13981 if (type->channel_type() == NULL)
13982 {
13983 this->report_error(_("expected channel"));
13984 return;
13985 }
13986 if (!type->channel_type()->may_receive())
13987 {
13988 this->report_error(_("invalid receive on send-only channel"));
13989 return;
13990 }
13991}
13992
2c809f8f 13993// Flattening for receive expressions creates a temporary variable to store
13994// received data in for receives.
13995
13996Expression*
13997Receive_expression::do_flatten(Gogo*, Named_object*,
13998 Statement_inserter* inserter)
13999{
14000 Channel_type* channel_type = this->channel_->type()->channel_type();
14001 if (channel_type == NULL)
14002 {
14003 go_assert(saw_errors());
14004 return this;
14005 }
14006
14007 Type* element_type = channel_type->element_type();
14008 if (this->temp_receiver_ == NULL)
14009 {
14010 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14011 this->location());
14012 this->temp_receiver_->set_is_address_taken();
14013 inserter->insert(this->temp_receiver_);
14014 }
14015
14016 return this;
14017}
14018
e440a328 14019// Get a tree for a receive expression.
14020
14021tree
14022Receive_expression::do_get_tree(Translate_context* context)
14023{
f24f10bb 14024 Location loc = this->location();
14025
e440a328 14026 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 14027 if (channel_type == NULL)
14028 {
c484d925 14029 go_assert(this->channel_->type()->is_error());
5b8368f4 14030 return error_mark_node;
14031 }
f24f10bb 14032 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 14033
2c809f8f 14034 Expression* recv_ref =
14035 Expression::make_temporary_reference(this->temp_receiver_, loc);
14036 Expression* recv_addr =
14037 Expression::make_temporary_reference(this->temp_receiver_, loc);
14038 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14039 Expression* recv =
14040 Runtime::make_call(Runtime::RECEIVE, loc, 3,
14041 td, this->channel_, recv_addr);
14042 recv = Expression::make_compound(recv, recv_ref, loc);
14043 return recv->get_tree(context);
e440a328 14044}
14045
d751bb78 14046// Dump ast representation for a receive expression.
14047
14048void
14049Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14050{
14051 ast_dump_context->ostream() << " <- " ;
14052 ast_dump_context->dump_expression(channel_);
14053}
14054
e440a328 14055// Make a receive expression.
14056
14057Receive_expression*
b13c66cd 14058Expression::make_receive(Expression* channel, Location location)
e440a328 14059{
14060 return new Receive_expression(channel, location);
14061}
14062
e440a328 14063// An expression which evaluates to a pointer to the type descriptor
14064// of a type.
14065
14066class Type_descriptor_expression : public Expression
14067{
14068 public:
b13c66cd 14069 Type_descriptor_expression(Type* type, Location location)
e440a328 14070 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14071 type_(type)
14072 { }
14073
14074 protected:
14075 Type*
14076 do_type()
14077 { return Type::make_type_descriptor_ptr_type(); }
14078
f9ca30f9 14079 bool
14080 do_is_immutable() const
14081 { return true; }
14082
e440a328 14083 void
14084 do_determine_type(const Type_context*)
14085 { }
14086
14087 Expression*
14088 do_copy()
14089 { return this; }
14090
14091 tree
14092 do_get_tree(Translate_context* context)
a1d23b41 14093 {
175a4612 14094 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
14095 this->location());
14096 return expr_to_tree(ret);
a1d23b41 14097 }
e440a328 14098
d751bb78 14099 void
14100 do_dump_expression(Ast_dump_context*) const;
14101
e440a328 14102 private:
14103 // The type for which this is the descriptor.
14104 Type* type_;
14105};
14106
d751bb78 14107// Dump ast representation for a type descriptor expression.
14108
14109void
14110Type_descriptor_expression::do_dump_expression(
14111 Ast_dump_context* ast_dump_context) const
14112{
14113 ast_dump_context->dump_type(this->type_);
14114}
14115
e440a328 14116// Make a type descriptor expression.
14117
14118Expression*
b13c66cd 14119Expression::make_type_descriptor(Type* type, Location location)
e440a328 14120{
14121 return new Type_descriptor_expression(type, location);
14122}
14123
14124// An expression which evaluates to some characteristic of a type.
14125// This is only used to initialize fields of a type descriptor. Using
14126// a new expression class is slightly inefficient but gives us a good
14127// separation between the frontend and the middle-end with regard to
14128// how types are laid out.
14129
14130class Type_info_expression : public Expression
14131{
14132 public:
14133 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 14134 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 14135 type_(type), type_info_(type_info)
14136 { }
14137
14138 protected:
0e168074 14139 bool
14140 do_is_immutable() const
14141 { return true; }
14142
e440a328 14143 Type*
14144 do_type();
14145
14146 void
14147 do_determine_type(const Type_context*)
14148 { }
14149
14150 Expression*
14151 do_copy()
14152 { return this; }
14153
14154 tree
14155 do_get_tree(Translate_context* context);
14156
d751bb78 14157 void
14158 do_dump_expression(Ast_dump_context*) const;
14159
e440a328 14160 private:
14161 // The type for which we are getting information.
14162 Type* type_;
14163 // What information we want.
14164 Type_info type_info_;
14165};
14166
14167// The type is chosen to match what the type descriptor struct
14168// expects.
14169
14170Type*
14171Type_info_expression::do_type()
14172{
14173 switch (this->type_info_)
14174 {
14175 case TYPE_INFO_SIZE:
14176 return Type::lookup_integer_type("uintptr");
14177 case TYPE_INFO_ALIGNMENT:
14178 case TYPE_INFO_FIELD_ALIGNMENT:
14179 return Type::lookup_integer_type("uint8");
14180 default:
c3e6f413 14181 go_unreachable();
e440a328 14182 }
14183}
14184
14185// Return type information in GENERIC.
14186
14187tree
14188Type_info_expression::do_get_tree(Translate_context* context)
14189{
927a01eb 14190 Btype* btype = this->type_->get_backend(context->gogo());
14191 Gogo* gogo = context->gogo();
14192 size_t val;
14193 switch (this->type_info_)
e440a328 14194 {
927a01eb 14195 case TYPE_INFO_SIZE:
14196 val = gogo->backend()->type_size(btype);
14197 break;
14198 case TYPE_INFO_ALIGNMENT:
14199 val = gogo->backend()->type_alignment(btype);
14200 break;
14201 case TYPE_INFO_FIELD_ALIGNMENT:
14202 val = gogo->backend()->type_field_alignment(btype);
14203 break;
14204 default:
14205 go_unreachable();
e440a328 14206 }
927a01eb 14207 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14208 go_assert(val_type_tree != error_mark_node);
14209 return build_int_cstu(val_type_tree, val);
e440a328 14210}
14211
d751bb78 14212// Dump ast representation for a type info expression.
14213
14214void
14215Type_info_expression::do_dump_expression(
14216 Ast_dump_context* ast_dump_context) const
14217{
14218 ast_dump_context->ostream() << "typeinfo(";
14219 ast_dump_context->dump_type(this->type_);
14220 ast_dump_context->ostream() << ",";
14221 ast_dump_context->ostream() <<
14222 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14223 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14224 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14225 : "unknown");
14226 ast_dump_context->ostream() << ")";
14227}
14228
e440a328 14229// Make a type info expression.
14230
14231Expression*
14232Expression::make_type_info(Type* type, Type_info type_info)
14233{
14234 return new Type_info_expression(type, type_info);
14235}
14236
35a54f17 14237// An expression that evaluates to some characteristic of a slice.
14238// This is used when indexing, bound-checking, or nil checking a slice.
14239
14240class Slice_info_expression : public Expression
14241{
14242 public:
14243 Slice_info_expression(Expression* slice, Slice_info slice_info,
14244 Location location)
14245 : Expression(EXPRESSION_SLICE_INFO, location),
14246 slice_(slice), slice_info_(slice_info)
14247 { }
14248
14249 protected:
14250 Type*
14251 do_type();
14252
14253 void
14254 do_determine_type(const Type_context*)
14255 { }
14256
14257 Expression*
14258 do_copy()
14259 {
14260 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14261 this->location());
14262 }
14263
14264 tree
14265 do_get_tree(Translate_context* context);
14266
14267 void
14268 do_dump_expression(Ast_dump_context*) const;
14269
14270 void
14271 do_issue_nil_check()
14272 { this->slice_->issue_nil_check(); }
14273
14274 private:
14275 // The slice for which we are getting information.
14276 Expression* slice_;
14277 // What information we want.
14278 Slice_info slice_info_;
14279};
14280
14281// Return the type of the slice info.
14282
14283Type*
14284Slice_info_expression::do_type()
14285{
14286 switch (this->slice_info_)
14287 {
14288 case SLICE_INFO_VALUE_POINTER:
14289 return Type::make_pointer_type(
14290 this->slice_->type()->array_type()->element_type());
14291 case SLICE_INFO_LENGTH:
14292 case SLICE_INFO_CAPACITY:
14293 return Type::lookup_integer_type("int");
14294 default:
14295 go_unreachable();
14296 }
14297}
14298
14299// Return slice information in GENERIC.
14300
14301tree
14302Slice_info_expression::do_get_tree(Translate_context* context)
14303{
14304 Gogo* gogo = context->gogo();
14305
14306 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14307 Bexpression* ret;
14308 switch (this->slice_info_)
14309 {
14310 case SLICE_INFO_VALUE_POINTER:
14311 case SLICE_INFO_LENGTH:
14312 case SLICE_INFO_CAPACITY:
14313 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14314 this->location());
14315 break;
14316 default:
14317 go_unreachable();
14318 }
14319 return expr_to_tree(ret);
14320}
14321
14322// Dump ast representation for a type info expression.
14323
14324void
14325Slice_info_expression::do_dump_expression(
14326 Ast_dump_context* ast_dump_context) const
14327{
14328 ast_dump_context->ostream() << "sliceinfo(";
14329 this->slice_->dump_expression(ast_dump_context);
14330 ast_dump_context->ostream() << ",";
14331 ast_dump_context->ostream() <<
14332 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14333 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14334 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14335 : "unknown");
14336 ast_dump_context->ostream() << ")";
14337}
14338
14339// Make a slice info expression.
14340
14341Expression*
14342Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14343 Location location)
14344{
14345 return new Slice_info_expression(slice, slice_info, location);
14346}
14347
2c809f8f 14348// An expression that represents a slice value: a struct with value pointer,
14349// length, and capacity fields.
14350
14351class Slice_value_expression : public Expression
14352{
14353 public:
14354 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14355 Expression* cap, Location location)
14356 : Expression(EXPRESSION_SLICE_VALUE, location),
14357 type_(type), valptr_(valptr), len_(len), cap_(cap)
14358 { }
14359
14360 protected:
14361 int
14362 do_traverse(Traverse*);
14363
14364 Type*
14365 do_type()
14366 { return this->type_; }
14367
14368 void
14369 do_determine_type(const Type_context*)
14370 { go_unreachable(); }
14371
14372 Expression*
14373 do_copy()
14374 {
14375 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14376 this->len_->copy(), this->cap_->copy(),
14377 this->location());
14378 }
14379
14380 tree
14381 do_get_tree(Translate_context* context);
14382
14383 void
14384 do_dump_expression(Ast_dump_context*) const;
14385
14386 private:
14387 // The type of the slice value.
14388 Type* type_;
14389 // The pointer to the values in the slice.
14390 Expression* valptr_;
14391 // The length of the slice.
14392 Expression* len_;
14393 // The capacity of the slice.
14394 Expression* cap_;
14395};
14396
14397int
14398Slice_value_expression::do_traverse(Traverse* traverse)
14399{
14400 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14401 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14402 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14403 return TRAVERSE_EXIT;
14404 return TRAVERSE_CONTINUE;
14405}
14406
14407tree
14408Slice_value_expression::do_get_tree(Translate_context* context)
14409{
14410 std::vector<Bexpression*> vals(3);
14411 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14412 vals[1] = tree_to_expr(this->len_->get_tree(context));
14413 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14414
14415 Gogo* gogo = context->gogo();
14416 Btype* btype = this->type_->get_backend(gogo);
14417 Bexpression* ret =
14418 gogo->backend()->constructor_expression(btype, vals, this->location());
14419 return expr_to_tree(ret);
14420}
14421
14422void
14423Slice_value_expression::do_dump_expression(
14424 Ast_dump_context* ast_dump_context) const
14425{
14426 ast_dump_context->ostream() << "slicevalue(";
14427 ast_dump_context->ostream() << "values: ";
14428 this->valptr_->dump_expression(ast_dump_context);
14429 ast_dump_context->ostream() << ", length: ";
14430 this->len_->dump_expression(ast_dump_context);
14431 ast_dump_context->ostream() << ", capacity: ";
14432 this->cap_->dump_expression(ast_dump_context);
14433 ast_dump_context->ostream() << ")";
14434}
14435
14436Expression*
14437Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14438 Expression* cap, Location location)
14439{
14440 go_assert(at->is_slice_type());
14441 return new Slice_value_expression(at, valptr, len, cap, location);
14442}
2387f644 14443
14444// An expression that evaluates to some characteristic of a non-empty interface.
14445// This is used to access the method table or underlying object of an interface.
14446
14447class Interface_info_expression : public Expression
14448{
14449 public:
14450 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14451 Location location)
2387f644 14452 : Expression(EXPRESSION_INTERFACE_INFO, location),
14453 iface_(iface), iface_info_(iface_info)
14454 { }
14455
14456 protected:
14457 Type*
14458 do_type();
14459
14460 void
14461 do_determine_type(const Type_context*)
14462 { }
14463
14464 Expression*
14465 do_copy()
14466 {
14467 return new Interface_info_expression(this->iface_->copy(),
14468 this->iface_info_, this->location());
14469 }
14470
14471 tree
14472 do_get_tree(Translate_context* context);
14473
14474 void
14475 do_dump_expression(Ast_dump_context*) const;
14476
14477 void
14478 do_issue_nil_check()
14479 { this->iface_->issue_nil_check(); }
14480
14481 private:
14482 // The interface for which we are getting information.
14483 Expression* iface_;
14484 // What information we want.
14485 Interface_info iface_info_;
14486};
14487
14488// Return the type of the interface info.
14489
14490Type*
14491Interface_info_expression::do_type()
14492{
14493 switch (this->iface_info_)
14494 {
14495 case INTERFACE_INFO_METHODS:
14496 {
2c809f8f 14497 Type* pdt = Type::make_type_descriptor_ptr_type();
14498 if (this->iface_->type()->interface_type()->is_empty())
14499 return pdt;
14500
2387f644 14501 Location loc = this->location();
14502 Struct_field_list* sfl = new Struct_field_list();
2387f644 14503 sfl->push_back(
14504 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14505
14506 Interface_type* itype = this->iface_->type()->interface_type();
14507 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14508 p != itype->methods()->end();
14509 ++p)
14510 {
14511 Function_type* ft = p->type()->function_type();
14512 go_assert(ft->receiver() == NULL);
14513
14514 const Typed_identifier_list* params = ft->parameters();
14515 Typed_identifier_list* mparams = new Typed_identifier_list();
14516 if (params != NULL)
14517 mparams->reserve(params->size() + 1);
14518 Type* vt = Type::make_pointer_type(Type::make_void_type());
14519 mparams->push_back(Typed_identifier("", vt, ft->location()));
14520 if (params != NULL)
14521 {
14522 for (Typed_identifier_list::const_iterator pp = params->begin();
14523 pp != params->end();
14524 ++pp)
14525 mparams->push_back(*pp);
14526 }
14527
14528 Typed_identifier_list* mresults = (ft->results() == NULL
14529 ? NULL
14530 : ft->results()->copy());
14531 Backend_function_type* mft =
14532 Type::make_backend_function_type(NULL, mparams, mresults,
14533 ft->location());
14534
14535 std::string fname = Gogo::unpack_hidden_name(p->name());
14536 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14537 }
14538
14539 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14540 }
14541 case INTERFACE_INFO_OBJECT:
14542 return Type::make_pointer_type(Type::make_void_type());
14543 default:
14544 go_unreachable();
14545 }
14546}
14547
14548// Return interface information in GENERIC.
14549
14550tree
14551Interface_info_expression::do_get_tree(Translate_context* context)
14552{
14553 Gogo* gogo = context->gogo();
14554
14555 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14556 Bexpression* ret;
14557 switch (this->iface_info_)
14558 {
14559 case INTERFACE_INFO_METHODS:
14560 case INTERFACE_INFO_OBJECT:
14561 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14562 this->location());
14563 break;
14564 default:
14565 go_unreachable();
14566 }
14567 return expr_to_tree(ret);
14568}
14569
14570// Dump ast representation for an interface info expression.
14571
14572void
14573Interface_info_expression::do_dump_expression(
14574 Ast_dump_context* ast_dump_context) const
14575{
2c809f8f 14576 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14577 ast_dump_context->ostream() << "interfaceinfo(";
14578 this->iface_->dump_expression(ast_dump_context);
14579 ast_dump_context->ostream() << ",";
14580 ast_dump_context->ostream() <<
2c809f8f 14581 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14582 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14583 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14584 : "unknown");
14585 ast_dump_context->ostream() << ")";
14586}
14587
14588// Make an interface info expression.
14589
14590Expression*
14591Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14592 Location location)
14593{
14594 return new Interface_info_expression(iface, iface_info, location);
14595}
14596
2c809f8f 14597// An expression that represents an interface value. The first field is either
14598// a type descriptor for an empty interface or a pointer to the interface method
14599// table for a non-empty interface. The second field is always the object.
14600
14601class Interface_value_expression : public Expression
14602{
14603 public:
14604 Interface_value_expression(Type* type, Expression* first_field,
14605 Expression* obj, Location location)
14606 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14607 type_(type), first_field_(first_field), obj_(obj)
14608 { }
14609
14610 protected:
14611 int
14612 do_traverse(Traverse*);
14613
14614 Type*
14615 do_type()
14616 { return this->type_; }
14617
14618 void
14619 do_determine_type(const Type_context*)
14620 { go_unreachable(); }
14621
14622 Expression*
14623 do_copy()
14624 {
14625 return new Interface_value_expression(this->type_,
14626 this->first_field_->copy(),
14627 this->obj_->copy(), this->location());
14628 }
14629
14630 tree
14631 do_get_tree(Translate_context* context);
14632
14633 void
14634 do_dump_expression(Ast_dump_context*) const;
14635
14636 private:
14637 // The type of the interface value.
14638 Type* type_;
14639 // The first field of the interface (either a type descriptor or a pointer
14640 // to the method table.
14641 Expression* first_field_;
14642 // The underlying object of the interface.
14643 Expression* obj_;
14644};
14645
14646int
14647Interface_value_expression::do_traverse(Traverse* traverse)
14648{
14649 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14650 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14651 return TRAVERSE_EXIT;
14652 return TRAVERSE_CONTINUE;
14653}
14654
14655tree
14656Interface_value_expression::do_get_tree(Translate_context* context)
14657{
14658 std::vector<Bexpression*> vals(2);
14659 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14660 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14661
14662 Gogo* gogo = context->gogo();
14663 Btype* btype = this->type_->get_backend(gogo);
14664 Bexpression* ret =
14665 gogo->backend()->constructor_expression(btype, vals, this->location());
14666 return expr_to_tree(ret);
14667}
14668
14669void
14670Interface_value_expression::do_dump_expression(
14671 Ast_dump_context* ast_dump_context) const
14672{
14673 ast_dump_context->ostream() << "interfacevalue(";
14674 ast_dump_context->ostream() <<
14675 (this->type_->interface_type()->is_empty()
14676 ? "type_descriptor: "
14677 : "methods: ");
14678 this->first_field_->dump_expression(ast_dump_context);
14679 ast_dump_context->ostream() << ", object: ";
14680 this->obj_->dump_expression(ast_dump_context);
14681 ast_dump_context->ostream() << ")";
14682}
14683
14684Expression*
14685Expression::make_interface_value(Type* type, Expression* first_value,
14686 Expression* object, Location location)
14687{
14688 return new Interface_value_expression(type, first_value, object, location);
14689}
14690
14691// An interface method table for a pair of types: an interface type and a type
14692// that implements that interface.
14693
14694class Interface_mtable_expression : public Expression
14695{
14696 public:
14697 Interface_mtable_expression(Interface_type* itype, Type* type,
14698 bool is_pointer, Location location)
14699 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14700 itype_(itype), type_(type), is_pointer_(is_pointer),
14701 method_table_type_(NULL), bvar_(NULL)
14702 { }
14703
14704 protected:
14705 int
14706 do_traverse(Traverse*);
14707
14708 Type*
14709 do_type();
14710
14711 bool
14712 is_immutable() const
14713 { return true; }
14714
14715 void
14716 do_determine_type(const Type_context*)
14717 { go_unreachable(); }
14718
14719 Expression*
14720 do_copy()
14721 {
14722 return new Interface_mtable_expression(this->itype_, this->type_,
14723 this->is_pointer_, this->location());
14724 }
14725
14726 bool
14727 do_is_addressable() const
14728 { return true; }
14729
14730 tree
14731 do_get_tree(Translate_context* context);
14732
14733 void
14734 do_dump_expression(Ast_dump_context*) const;
14735
14736 private:
14737 // The interface type for which the methods are defined.
14738 Interface_type* itype_;
14739 // The type to construct the interface method table for.
14740 Type* type_;
14741 // Whether this table contains the method set for the receiver type or the
14742 // pointer receiver type.
14743 bool is_pointer_;
14744 // The type of the method table.
14745 Type* method_table_type_;
14746 // The backend variable that refers to the interface method table.
14747 Bvariable* bvar_;
14748};
14749
14750int
14751Interface_mtable_expression::do_traverse(Traverse* traverse)
14752{
14753 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14754 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14755 return TRAVERSE_EXIT;
14756 return TRAVERSE_CONTINUE;
14757}
14758
14759Type*
14760Interface_mtable_expression::do_type()
14761{
14762 if (this->method_table_type_ != NULL)
14763 return this->method_table_type_;
14764
14765 const Typed_identifier_list* interface_methods = this->itype_->methods();
14766 go_assert(!interface_methods->empty());
14767
14768 Struct_field_list* sfl = new Struct_field_list;
14769 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14770 this->location());
14771 sfl->push_back(Struct_field(tid));
14772 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14773 p != interface_methods->end();
14774 ++p)
14775 sfl->push_back(Struct_field(*p));
14776 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14777 return this->method_table_type_;
14778}
14779
14780tree
14781Interface_mtable_expression::do_get_tree(Translate_context* context)
14782{
14783 Gogo* gogo = context->gogo();
14784 Bexpression* ret;
14785 Location loc = Linemap::predeclared_location();
14786 if (this->bvar_ != NULL)
14787 {
14788 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14789 return expr_to_tree(ret);
14790 }
14791
14792 const Typed_identifier_list* interface_methods = this->itype_->methods();
14793 go_assert(!interface_methods->empty());
14794
14795 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14796 + this->itype_->mangled_name(gogo)
14797 + "__"
14798 + this->type_->mangled_name(gogo));
14799
14800 // See whether this interface has any hidden methods.
14801 bool has_hidden_methods = false;
14802 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14803 p != interface_methods->end();
14804 ++p)
14805 {
14806 if (Gogo::is_hidden_name(p->name()))
14807 {
14808 has_hidden_methods = true;
14809 break;
14810 }
14811 }
14812
14813 // We already know that the named type is convertible to the
14814 // interface. If the interface has hidden methods, and the named
14815 // type is defined in a different package, then the interface
14816 // conversion table will be defined by that other package.
14817 if (has_hidden_methods
14818 && this->type_->named_type() != NULL
14819 && this->type_->named_type()->named_object()->package() != NULL)
14820 {
14821 Btype* btype = this->type()->get_backend(gogo);
14822 this->bvar_ =
14823 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14824 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14825 return expr_to_tree(ret);
14826 }
14827
14828 // The first element is the type descriptor.
14829 Type* td_type;
14830 if (!this->is_pointer_)
14831 td_type = this->type_;
14832 else
14833 td_type = Type::make_pointer_type(this->type_);
14834
14835 // Build an interface method table for a type: a type descriptor followed by a
14836 // list of function pointers, one for each interface method. This is used for
14837 // interfaces.
14838 Expression_list* svals = new Expression_list();
14839 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14840
14841 Named_type* nt = this->type_->named_type();
14842 Struct_type* st = this->type_->struct_type();
14843 go_assert(nt != NULL || st != NULL);
14844
14845 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14846 p != interface_methods->end();
14847 ++p)
14848 {
14849 bool is_ambiguous;
14850 Method* m;
14851 if (nt != NULL)
14852 m = nt->method_function(p->name(), &is_ambiguous);
14853 else
14854 m = st->method_function(p->name(), &is_ambiguous);
14855 go_assert(m != NULL);
14856 Named_object* no = m->named_object();
14857
14858 go_assert(no->is_function() || no->is_function_declaration());
14859 svals->push_back(Expression::make_func_code_reference(no, loc));
14860 }
14861
14862 Btype* btype = this->type()->get_backend(gogo);
14863 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14864 svals, loc);
14865 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14866
14867 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14868 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14869 !is_public, btype, loc);
14870 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14871 !is_public, btype, loc, ctor);
14872 ret = gogo->backend()->var_expression(this->bvar_, loc);
14873 return expr_to_tree(ret);
14874}
14875
14876void
14877Interface_mtable_expression::do_dump_expression(
14878 Ast_dump_context* ast_dump_context) const
14879{
14880 ast_dump_context->ostream() << "__go_"
14881 << (this->is_pointer_ ? "pimt__" : "imt_");
14882 ast_dump_context->dump_type(this->itype_);
14883 ast_dump_context->ostream() << "__";
14884 ast_dump_context->dump_type(this->type_);
14885}
14886
14887Expression*
14888Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14889 bool is_pointer, Location location)
14890{
14891 return new Interface_mtable_expression(itype, type, is_pointer, location);
14892}
14893
e440a328 14894// An expression which evaluates to the offset of a field within a
14895// struct. This, like Type_info_expression, q.v., is only used to
14896// initialize fields of a type descriptor.
14897
14898class Struct_field_offset_expression : public Expression
14899{
14900 public:
14901 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 14902 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14903 Linemap::predeclared_location()),
e440a328 14904 type_(type), field_(field)
14905 { }
14906
14907 protected:
14908 Type*
14909 do_type()
14910 { return Type::lookup_integer_type("uintptr"); }
14911
14912 void
14913 do_determine_type(const Type_context*)
14914 { }
14915
14916 Expression*
14917 do_copy()
14918 { return this; }
14919
14920 tree
14921 do_get_tree(Translate_context* context);
14922
d751bb78 14923 void
14924 do_dump_expression(Ast_dump_context*) const;
14925
e440a328 14926 private:
14927 // The type of the struct.
14928 Struct_type* type_;
14929 // The field.
14930 const Struct_field* field_;
14931};
14932
14933// Return a struct field offset in GENERIC.
14934
14935tree
14936Struct_field_offset_expression::do_get_tree(Translate_context* context)
14937{
9f0e0513 14938 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
e440a328 14939 if (type_tree == error_mark_node)
14940 return error_mark_node;
14941
9f0e0513 14942 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
c484d925 14943 go_assert(val_type_tree != error_mark_node);
e440a328 14944
14945 const Struct_field_list* fields = this->type_->fields();
14946 tree struct_field_tree = TYPE_FIELDS(type_tree);
14947 Struct_field_list::const_iterator p;
14948 for (p = fields->begin();
14949 p != fields->end();
14950 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14951 {
c484d925 14952 go_assert(struct_field_tree != NULL_TREE);
e440a328 14953 if (&*p == this->field_)
14954 break;
14955 }
c484d925 14956 go_assert(&*p == this->field_);
e440a328 14957
14958 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14959 byte_position(struct_field_tree));
14960}
14961
d751bb78 14962// Dump ast representation for a struct field offset expression.
14963
14964void
14965Struct_field_offset_expression::do_dump_expression(
14966 Ast_dump_context* ast_dump_context) const
14967{
14968 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 14969 ast_dump_context->dump_type(this->type_);
14970 ast_dump_context->ostream() << '.';
14971 ast_dump_context->ostream() <<
14972 Gogo::message_name(this->field_->field_name());
d751bb78 14973 ast_dump_context->ostream() << ")";
14974}
14975
e440a328 14976// Make an expression for a struct field offset.
14977
14978Expression*
14979Expression::make_struct_field_offset(Struct_type* type,
14980 const Struct_field* field)
14981{
14982 return new Struct_field_offset_expression(type, field);
14983}
14984
a9182619 14985// An expression which evaluates to a pointer to the map descriptor of
14986// a map type.
14987
14988class Map_descriptor_expression : public Expression
14989{
14990 public:
b13c66cd 14991 Map_descriptor_expression(Map_type* type, Location location)
a9182619 14992 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14993 type_(type)
14994 { }
14995
14996 protected:
14997 Type*
14998 do_type()
14999 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
15000
15001 void
15002 do_determine_type(const Type_context*)
15003 { }
15004
15005 Expression*
15006 do_copy()
15007 { return this; }
15008
15009 tree
15010 do_get_tree(Translate_context* context)
15011 {
175a4612 15012 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
15013 this->location());
15014 return expr_to_tree(ret);
a9182619 15015 }
15016
d751bb78 15017 void
15018 do_dump_expression(Ast_dump_context*) const;
15019
a9182619 15020 private:
15021 // The type for which this is the descriptor.
15022 Map_type* type_;
15023};
15024
d751bb78 15025// Dump ast representation for a map descriptor expression.
15026
15027void
15028Map_descriptor_expression::do_dump_expression(
15029 Ast_dump_context* ast_dump_context) const
15030{
15031 ast_dump_context->ostream() << "map_descriptor(";
15032 ast_dump_context->dump_type(this->type_);
15033 ast_dump_context->ostream() << ")";
15034}
15035
a9182619 15036// Make a map descriptor expression.
15037
15038Expression*
b13c66cd 15039Expression::make_map_descriptor(Map_type* type, Location location)
a9182619 15040{
15041 return new Map_descriptor_expression(type, location);
15042}
15043
e440a328 15044// An expression which evaluates to the address of an unnamed label.
15045
15046class Label_addr_expression : public Expression
15047{
15048 public:
b13c66cd 15049 Label_addr_expression(Label* label, Location location)
e440a328 15050 : Expression(EXPRESSION_LABEL_ADDR, location),
15051 label_(label)
15052 { }
15053
15054 protected:
15055 Type*
15056 do_type()
15057 { return Type::make_pointer_type(Type::make_void_type()); }
15058
15059 void
15060 do_determine_type(const Type_context*)
15061 { }
15062
15063 Expression*
15064 do_copy()
15065 { return new Label_addr_expression(this->label_, this->location()); }
15066
15067 tree
6e193e6f 15068 do_get_tree(Translate_context* context)
15069 {
e8816003 15070 return expr_to_tree(this->label_->get_addr(context, this->location()));
6e193e6f 15071 }
e440a328 15072
d751bb78 15073 void
15074 do_dump_expression(Ast_dump_context* ast_dump_context) const
15075 { ast_dump_context->ostream() << this->label_->name(); }
15076
e440a328 15077 private:
15078 // The label whose address we are taking.
15079 Label* label_;
15080};
15081
15082// Make an expression for the address of an unnamed label.
15083
15084Expression*
b13c66cd 15085Expression::make_label_addr(Label* label, Location location)
e440a328 15086{
15087 return new Label_addr_expression(label, location);
15088}
15089
283a177b 15090// Conditional expressions.
15091
15092class Conditional_expression : public Expression
15093{
15094 public:
15095 Conditional_expression(Expression* cond, Expression* then_expr,
15096 Expression* else_expr, Location location)
15097 : Expression(EXPRESSION_CONDITIONAL, location),
15098 cond_(cond), then_(then_expr), else_(else_expr)
15099 {}
15100
15101 protected:
2c809f8f 15102 int
15103 do_traverse(Traverse*);
15104
283a177b 15105 Type*
15106 do_type();
15107
15108 void
2c809f8f 15109 do_determine_type(const Type_context*);
283a177b 15110
15111 Expression*
15112 do_copy()
15113 {
15114 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
15115 this->else_->copy(), this->location());
15116 }
15117
15118 tree
15119 do_get_tree(Translate_context* context);
15120
15121 void
15122 do_dump_expression(Ast_dump_context*) const;
15123
15124 private:
15125 // The condition to be checked.
15126 Expression* cond_;
15127 // The expression to execute if the condition is true.
15128 Expression* then_;
15129 // The expression to execute if the condition is false.
15130 Expression* else_;
15131};
15132
2c809f8f 15133// Traversal.
15134
15135int
15136Conditional_expression::do_traverse(Traverse* traverse)
15137{
15138 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15139 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15140 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15141 return TRAVERSE_EXIT;
15142 return TRAVERSE_CONTINUE;
15143}
15144
283a177b 15145// Return the type of the conditional expression.
15146
15147Type*
15148Conditional_expression::do_type()
15149{
15150 Type* result_type = Type::make_void_type();
2c809f8f 15151 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15152 NULL))
283a177b 15153 result_type = this->then_->type();
15154 else if (this->then_->is_nil_expression()
15155 || this->else_->is_nil_expression())
15156 result_type = (!this->then_->is_nil_expression()
15157 ? this->then_->type()
15158 : this->else_->type());
15159 return result_type;
15160}
15161
2c809f8f 15162// Determine type for a conditional expression.
15163
15164void
15165Conditional_expression::do_determine_type(const Type_context* context)
15166{
15167 this->cond_->determine_type_no_context();
15168 this->then_->determine_type(context);
15169 this->else_->determine_type(context);
15170}
15171
283a177b 15172// Get the backend representation of a conditional expression.
15173
15174tree
15175Conditional_expression::do_get_tree(Translate_context* context)
15176{
15177 Gogo* gogo = context->gogo();
15178 Btype* result_btype = this->type()->get_backend(gogo);
15179 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15180 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15181 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15182 Bexpression* ret =
15183 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15184 this->location());
15185 return expr_to_tree(ret);
15186}
15187
15188// Dump ast representation of a conditional expression.
15189
15190void
15191Conditional_expression::do_dump_expression(
15192 Ast_dump_context* ast_dump_context) const
15193{
15194 ast_dump_context->ostream() << "(";
15195 ast_dump_context->dump_expression(this->cond_);
15196 ast_dump_context->ostream() << " ? ";
15197 ast_dump_context->dump_expression(this->then_);
15198 ast_dump_context->ostream() << " : ";
15199 ast_dump_context->dump_expression(this->else_);
15200 ast_dump_context->ostream() << ") ";
15201}
15202
15203// Make a conditional expression.
15204
15205Expression*
15206Expression::make_conditional(Expression* cond, Expression* then,
15207 Expression* else_expr, Location location)
15208{
15209 return new Conditional_expression(cond, then, else_expr, location);
15210}
15211
2c809f8f 15212// Compound expressions.
15213
15214class Compound_expression : public Expression
15215{
15216 public:
15217 Compound_expression(Expression* init, Expression* expr, Location location)
15218 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15219 {}
15220
15221 protected:
15222 int
15223 do_traverse(Traverse*);
15224
15225 Type*
15226 do_type();
15227
15228 void
15229 do_determine_type(const Type_context*);
15230
15231 Expression*
15232 do_copy()
15233 {
15234 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15235 this->location());
15236 }
15237
15238 tree
15239 do_get_tree(Translate_context* context);
15240
15241 void
15242 do_dump_expression(Ast_dump_context*) const;
15243
15244 private:
15245 // The expression that is evaluated first and discarded.
15246 Expression* init_;
15247 // The expression that is evaluated and returned.
15248 Expression* expr_;
15249};
15250
15251// Traversal.
15252
15253int
15254Compound_expression::do_traverse(Traverse* traverse)
15255{
15256 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15257 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15258 return TRAVERSE_EXIT;
15259 return TRAVERSE_CONTINUE;
15260}
15261
15262// Return the type of the compound expression.
15263
15264Type*
15265Compound_expression::do_type()
15266{
15267 return this->expr_->type();
15268}
15269
15270// Determine type for a compound expression.
15271
15272void
15273Compound_expression::do_determine_type(const Type_context* context)
15274{
15275 this->init_->determine_type_no_context();
15276 this->expr_->determine_type(context);
15277}
15278
15279// Get the backend representation of a compound expression.
15280
15281tree
15282Compound_expression::do_get_tree(Translate_context* context)
15283{
15284 Gogo* gogo = context->gogo();
15285 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15286 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15287 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15288 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15289 this->location());
15290 return expr_to_tree(ret);
15291}
15292
15293// Dump ast representation of a conditional expression.
15294
15295void
15296Compound_expression::do_dump_expression(
15297 Ast_dump_context* ast_dump_context) const
15298{
15299 ast_dump_context->ostream() << "(";
15300 ast_dump_context->dump_expression(this->init_);
15301 ast_dump_context->ostream() << ",";
15302 ast_dump_context->dump_expression(this->expr_);
15303 ast_dump_context->ostream() << ") ";
15304}
15305
15306// Make a compound expression.
15307
15308Expression*
15309Expression::make_compound(Expression* init, Expression* expr, Location location)
15310{
15311 return new Compound_expression(init, expr, location);
15312}
15313
e440a328 15314// Import an expression. This comes at the end in order to see the
15315// various class definitions.
15316
15317Expression*
15318Expression::import_expression(Import* imp)
15319{
15320 int c = imp->peek_char();
15321 if (imp->match_c_string("- ")
15322 || imp->match_c_string("! ")
15323 || imp->match_c_string("^ "))
15324 return Unary_expression::do_import(imp);
15325 else if (c == '(')
15326 return Binary_expression::do_import(imp);
15327 else if (imp->match_c_string("true")
15328 || imp->match_c_string("false"))
15329 return Boolean_expression::do_import(imp);
15330 else if (c == '"')
15331 return String_expression::do_import(imp);
15332 else if (c == '-' || (c >= '0' && c <= '9'))
15333 {
15334 // This handles integers, floats and complex constants.
15335 return Integer_expression::do_import(imp);
15336 }
15337 else if (imp->match_c_string("nil"))
15338 return Nil_expression::do_import(imp);
15339 else if (imp->match_c_string("convert"))
15340 return Type_conversion_expression::do_import(imp);
15341 else
15342 {
15343 error_at(imp->location(), "import error: expected expression");
15344 return Expression::make_error(imp->location());
15345 }
15346}
15347
15348// Class Expression_list.
15349
15350// Traverse the list.
15351
15352int
15353Expression_list::traverse(Traverse* traverse)
15354{
15355 for (Expression_list::iterator p = this->begin();
15356 p != this->end();
15357 ++p)
15358 {
15359 if (*p != NULL)
15360 {
15361 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15362 return TRAVERSE_EXIT;
15363 }
15364 }
15365 return TRAVERSE_CONTINUE;
15366}
15367
15368// Copy the list.
15369
15370Expression_list*
15371Expression_list::copy()
15372{
15373 Expression_list* ret = new Expression_list();
15374 for (Expression_list::iterator p = this->begin();
15375 p != this->end();
15376 ++p)
15377 {
15378 if (*p == NULL)
15379 ret->push_back(NULL);
15380 else
15381 ret->push_back((*p)->copy());
15382 }
15383 return ret;
15384}
15385
15386// Return whether an expression list has an error expression.
15387
15388bool
15389Expression_list::contains_error() const
15390{
15391 for (Expression_list::const_iterator p = this->begin();
15392 p != this->end();
15393 ++p)
15394 if (*p != NULL && (*p)->is_error_expression())
15395 return true;
15396 return false;
15397}
0c77715b 15398
15399// Class Numeric_constant.
15400
15401// Destructor.
15402
15403Numeric_constant::~Numeric_constant()
15404{
15405 this->clear();
15406}
15407
15408// Copy constructor.
15409
15410Numeric_constant::Numeric_constant(const Numeric_constant& a)
15411 : classification_(a.classification_), type_(a.type_)
15412{
15413 switch (a.classification_)
15414 {
15415 case NC_INVALID:
15416 break;
15417 case NC_INT:
15418 case NC_RUNE:
15419 mpz_init_set(this->u_.int_val, a.u_.int_val);
15420 break;
15421 case NC_FLOAT:
15422 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15423 break;
15424 case NC_COMPLEX:
15425 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15426 GMP_RNDN);
15427 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15428 GMP_RNDN);
15429 break;
15430 default:
15431 go_unreachable();
15432 }
15433}
15434
15435// Assignment operator.
15436
15437Numeric_constant&
15438Numeric_constant::operator=(const Numeric_constant& a)
15439{
15440 this->clear();
15441 this->classification_ = a.classification_;
15442 this->type_ = a.type_;
15443 switch (a.classification_)
15444 {
15445 case NC_INVALID:
15446 break;
15447 case NC_INT:
15448 case NC_RUNE:
15449 mpz_init_set(this->u_.int_val, a.u_.int_val);
15450 break;
15451 case NC_FLOAT:
15452 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15453 break;
15454 case NC_COMPLEX:
15455 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15456 GMP_RNDN);
15457 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15458 GMP_RNDN);
15459 break;
15460 default:
15461 go_unreachable();
15462 }
15463 return *this;
15464}
15465
15466// Clear the contents.
15467
15468void
15469Numeric_constant::clear()
15470{
15471 switch (this->classification_)
15472 {
15473 case NC_INVALID:
15474 break;
15475 case NC_INT:
15476 case NC_RUNE:
15477 mpz_clear(this->u_.int_val);
15478 break;
15479 case NC_FLOAT:
15480 mpfr_clear(this->u_.float_val);
15481 break;
15482 case NC_COMPLEX:
15483 mpfr_clear(this->u_.complex_val.real);
15484 mpfr_clear(this->u_.complex_val.imag);
15485 break;
15486 default:
15487 go_unreachable();
15488 }
15489 this->classification_ = NC_INVALID;
15490}
15491
15492// Set to an unsigned long value.
15493
15494void
15495Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15496{
15497 this->clear();
15498 this->classification_ = NC_INT;
15499 this->type_ = type;
15500 mpz_init_set_ui(this->u_.int_val, val);
15501}
15502
15503// Set to an integer value.
15504
15505void
15506Numeric_constant::set_int(Type* type, const mpz_t val)
15507{
15508 this->clear();
15509 this->classification_ = NC_INT;
15510 this->type_ = type;
15511 mpz_init_set(this->u_.int_val, val);
15512}
15513
15514// Set to a rune value.
15515
15516void
15517Numeric_constant::set_rune(Type* type, const mpz_t val)
15518{
15519 this->clear();
15520 this->classification_ = NC_RUNE;
15521 this->type_ = type;
15522 mpz_init_set(this->u_.int_val, val);
15523}
15524
15525// Set to a floating point value.
15526
15527void
15528Numeric_constant::set_float(Type* type, const mpfr_t val)
15529{
15530 this->clear();
15531 this->classification_ = NC_FLOAT;
15532 this->type_ = type;
833b523c 15533 // Numeric constants do not have negative zero values, so remove
15534 // them here. They also don't have infinity or NaN values, but we
15535 // should never see them here.
15536 if (mpfr_zero_p(val))
15537 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15538 else
15539 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15540}
15541
15542// Set to a complex value.
15543
15544void
15545Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15546{
15547 this->clear();
15548 this->classification_ = NC_COMPLEX;
15549 this->type_ = type;
15550 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15551 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15552}
15553
15554// Get an int value.
15555
15556void
15557Numeric_constant::get_int(mpz_t* val) const
15558{
15559 go_assert(this->is_int());
15560 mpz_init_set(*val, this->u_.int_val);
15561}
15562
15563// Get a rune value.
15564
15565void
15566Numeric_constant::get_rune(mpz_t* val) const
15567{
15568 go_assert(this->is_rune());
15569 mpz_init_set(*val, this->u_.int_val);
15570}
15571
15572// Get a floating point value.
15573
15574void
15575Numeric_constant::get_float(mpfr_t* val) const
15576{
15577 go_assert(this->is_float());
15578 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15579}
15580
15581// Get a complex value.
15582
15583void
15584Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15585{
15586 go_assert(this->is_complex());
15587 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15588 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15589}
15590
15591// Express value as unsigned long if possible.
15592
15593Numeric_constant::To_unsigned_long
15594Numeric_constant::to_unsigned_long(unsigned long* val) const
15595{
15596 switch (this->classification_)
15597 {
15598 case NC_INT:
15599 case NC_RUNE:
15600 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15601 case NC_FLOAT:
15602 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15603 case NC_COMPLEX:
15604 if (!mpfr_zero_p(this->u_.complex_val.imag))
15605 return NC_UL_NOTINT;
15606 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15607 default:
15608 go_unreachable();
15609 }
15610}
15611
15612// Express integer value as unsigned long if possible.
15613
15614Numeric_constant::To_unsigned_long
15615Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15616 unsigned long *val) const
15617{
15618 if (mpz_sgn(ival) < 0)
15619 return NC_UL_NEGATIVE;
15620 unsigned long ui = mpz_get_ui(ival);
15621 if (mpz_cmp_ui(ival, ui) != 0)
15622 return NC_UL_BIG;
15623 *val = ui;
15624 return NC_UL_VALID;
15625}
15626
15627// Express floating point value as unsigned long if possible.
15628
15629Numeric_constant::To_unsigned_long
15630Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15631 unsigned long *val) const
15632{
15633 if (!mpfr_integer_p(fval))
15634 return NC_UL_NOTINT;
15635 mpz_t ival;
15636 mpz_init(ival);
15637 mpfr_get_z(ival, fval, GMP_RNDN);
15638 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15639 mpz_clear(ival);
15640 return ret;
15641}
15642
15643// Convert value to integer if possible.
15644
15645bool
15646Numeric_constant::to_int(mpz_t* val) const
15647{
15648 switch (this->classification_)
15649 {
15650 case NC_INT:
15651 case NC_RUNE:
15652 mpz_init_set(*val, this->u_.int_val);
15653 return true;
15654 case NC_FLOAT:
15655 if (!mpfr_integer_p(this->u_.float_val))
15656 return false;
15657 mpz_init(*val);
15658 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15659 return true;
15660 case NC_COMPLEX:
15661 if (!mpfr_zero_p(this->u_.complex_val.imag)
15662 || !mpfr_integer_p(this->u_.complex_val.real))
15663 return false;
15664 mpz_init(*val);
15665 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15666 return true;
15667 default:
15668 go_unreachable();
15669 }
15670}
15671
15672// Convert value to floating point if possible.
15673
15674bool
15675Numeric_constant::to_float(mpfr_t* val) const
15676{
15677 switch (this->classification_)
15678 {
15679 case NC_INT:
15680 case NC_RUNE:
15681 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15682 return true;
15683 case NC_FLOAT:
15684 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15685 return true;
15686 case NC_COMPLEX:
15687 if (!mpfr_zero_p(this->u_.complex_val.imag))
15688 return false;
15689 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15690 return true;
15691 default:
15692 go_unreachable();
15693 }
15694}
15695
15696// Convert value to complex.
15697
15698bool
15699Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15700{
15701 switch (this->classification_)
15702 {
15703 case NC_INT:
15704 case NC_RUNE:
15705 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15706 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15707 return true;
15708 case NC_FLOAT:
15709 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15710 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15711 return true;
15712 case NC_COMPLEX:
15713 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15714 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15715 return true;
15716 default:
15717 go_unreachable();
15718 }
15719}
15720
15721// Get the type.
15722
15723Type*
15724Numeric_constant::type() const
15725{
15726 if (this->type_ != NULL)
15727 return this->type_;
15728 switch (this->classification_)
15729 {
15730 case NC_INT:
15731 return Type::make_abstract_integer_type();
15732 case NC_RUNE:
15733 return Type::make_abstract_character_type();
15734 case NC_FLOAT:
15735 return Type::make_abstract_float_type();
15736 case NC_COMPLEX:
15737 return Type::make_abstract_complex_type();
15738 default:
15739 go_unreachable();
15740 }
15741}
15742
15743// If the constant can be expressed in TYPE, then set the type of the
15744// constant to TYPE and return true. Otherwise return false, and, if
15745// ISSUE_ERROR is true, report an appropriate error message.
15746
15747bool
15748Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15749{
15750 bool ret;
15751 if (type == NULL)
15752 ret = true;
15753 else if (type->integer_type() != NULL)
15754 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15755 else if (type->float_type() != NULL)
15756 ret = this->check_float_type(type->float_type(), issue_error, loc);
15757 else if (type->complex_type() != NULL)
15758 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15759 else
15760 go_unreachable();
15761 if (ret)
15762 this->type_ = type;
15763 return ret;
15764}
15765
15766// Check whether the constant can be expressed in an integer type.
15767
15768bool
15769Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15770 Location location) const
15771{
15772 mpz_t val;
15773 switch (this->classification_)
15774 {
15775 case NC_INT:
15776 case NC_RUNE:
15777 mpz_init_set(val, this->u_.int_val);
15778 break;
15779
15780 case NC_FLOAT:
15781 if (!mpfr_integer_p(this->u_.float_val))
15782 {
15783 if (issue_error)
15784 error_at(location, "floating point constant truncated to integer");
15785 return false;
15786 }
15787 mpz_init(val);
15788 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15789 break;
15790
15791 case NC_COMPLEX:
15792 if (!mpfr_integer_p(this->u_.complex_val.real)
15793 || !mpfr_zero_p(this->u_.complex_val.imag))
15794 {
15795 if (issue_error)
15796 error_at(location, "complex constant truncated to integer");
15797 return false;
15798 }
15799 mpz_init(val);
15800 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15801 break;
15802
15803 default:
15804 go_unreachable();
15805 }
15806
15807 bool ret;
15808 if (type->is_abstract())
15809 ret = true;
15810 else
15811 {
15812 int bits = mpz_sizeinbase(val, 2);
15813 if (type->is_unsigned())
15814 {
15815 // For an unsigned type we can only accept a nonnegative
15816 // number, and we must be able to represents at least BITS.
15817 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15818 }
15819 else
15820 {
15821 // For a signed type we need an extra bit to indicate the
15822 // sign. We have to handle the most negative integer
15823 // specially.
15824 ret = (bits + 1 <= type->bits()
15825 || (bits <= type->bits()
15826 && mpz_sgn(val) < 0
15827 && (mpz_scan1(val, 0)
15828 == static_cast<unsigned long>(type->bits() - 1))
15829 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15830 }
15831 }
15832
15833 if (!ret && issue_error)
15834 error_at(location, "integer constant overflow");
15835
15836 return ret;
15837}
15838
15839// Check whether the constant can be expressed in a floating point
15840// type.
15841
15842bool
15843Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15844 Location location)
0c77715b 15845{
15846 mpfr_t val;
15847 switch (this->classification_)
15848 {
15849 case NC_INT:
15850 case NC_RUNE:
15851 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15852 break;
15853
15854 case NC_FLOAT:
15855 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15856 break;
15857
15858 case NC_COMPLEX:
15859 if (!mpfr_zero_p(this->u_.complex_val.imag))
15860 {
15861 if (issue_error)
15862 error_at(location, "complex constant truncated to float");
15863 return false;
15864 }
15865 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15866 break;
15867
15868 default:
15869 go_unreachable();
15870 }
15871
15872 bool ret;
15873 if (type->is_abstract())
15874 ret = true;
15875 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15876 {
15877 // A NaN or Infinity always fits in the range of the type.
15878 ret = true;
15879 }
15880 else
15881 {
15882 mp_exp_t exp = mpfr_get_exp(val);
15883 mp_exp_t max_exp;
15884 switch (type->bits())
15885 {
15886 case 32:
15887 max_exp = 128;
15888 break;
15889 case 64:
15890 max_exp = 1024;
15891 break;
15892 default:
15893 go_unreachable();
15894 }
15895
15896 ret = exp <= max_exp;
d0bcce51 15897
15898 if (ret)
15899 {
15900 // Round the constant to the desired type.
15901 mpfr_t t;
15902 mpfr_init(t);
15903 switch (type->bits())
15904 {
15905 case 32:
15906 mpfr_set_prec(t, 24);
15907 break;
15908 case 64:
15909 mpfr_set_prec(t, 53);
15910 break;
15911 default:
15912 go_unreachable();
15913 }
15914 mpfr_set(t, val, GMP_RNDN);
15915 mpfr_set(val, t, GMP_RNDN);
15916 mpfr_clear(t);
15917
15918 this->set_float(type, val);
15919 }
0c77715b 15920 }
15921
15922 mpfr_clear(val);
15923
15924 if (!ret && issue_error)
15925 error_at(location, "floating point constant overflow");
15926
15927 return ret;
15928}
15929
15930// Check whether the constant can be expressed in a complex type.
15931
15932bool
15933Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 15934 Location location)
0c77715b 15935{
15936 if (type->is_abstract())
15937 return true;
15938
15939 mp_exp_t max_exp;
15940 switch (type->bits())
15941 {
15942 case 64:
15943 max_exp = 128;
15944 break;
15945 case 128:
15946 max_exp = 1024;
15947 break;
15948 default:
15949 go_unreachable();
15950 }
15951
15952 mpfr_t real;
d0bcce51 15953 mpfr_t imag;
0c77715b 15954 switch (this->classification_)
15955 {
15956 case NC_INT:
15957 case NC_RUNE:
15958 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
d0bcce51 15959 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15960 break;
15961
15962 case NC_FLOAT:
15963 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
d0bcce51 15964 mpfr_init_set_ui(imag, 0, GMP_RNDN);
0c77715b 15965 break;
15966
15967 case NC_COMPLEX:
0c77715b 15968 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
d0bcce51 15969 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
0c77715b 15970 break;
15971
15972 default:
15973 go_unreachable();
15974 }
15975
d0bcce51 15976 bool ret = true;
15977 if (!mpfr_nan_p(real)
15978 && !mpfr_inf_p(real)
15979 && !mpfr_zero_p(real)
15980 && mpfr_get_exp(real) > max_exp)
15981 {
15982 if (issue_error)
15983 error_at(location, "complex real part overflow");
15984 ret = false;
15985 }
0c77715b 15986
d0bcce51 15987 if (!mpfr_nan_p(imag)
15988 && !mpfr_inf_p(imag)
15989 && !mpfr_zero_p(imag)
15990 && mpfr_get_exp(imag) > max_exp)
15991 {
15992 if (issue_error)
15993 error_at(location, "complex imaginary part overflow");
15994 ret = false;
15995 }
0c77715b 15996
d0bcce51 15997 if (ret)
15998 {
15999 // Round the constant to the desired type.
16000 mpfr_t t;
16001 mpfr_init(t);
16002 switch (type->bits())
16003 {
16004 case 64:
16005 mpfr_set_prec(t, 24);
16006 break;
16007 case 128:
16008 mpfr_set_prec(t, 53);
16009 break;
16010 default:
16011 go_unreachable();
16012 }
16013 mpfr_set(t, real, GMP_RNDN);
16014 mpfr_set(real, t, GMP_RNDN);
16015 mpfr_set(t, imag, GMP_RNDN);
16016 mpfr_set(imag, t, GMP_RNDN);
16017 mpfr_clear(t);
16018
16019 this->set_complex(type, real, imag);
16020 }
16021
16022 mpfr_clear(real);
16023 mpfr_clear(imag);
0c77715b 16024
16025 return ret;
16026}
16027
16028// Return an Expression for this value.
16029
16030Expression*
16031Numeric_constant::expression(Location loc) const
16032{
16033 switch (this->classification_)
16034 {
16035 case NC_INT:
16036 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
16037 case NC_RUNE:
16038 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16039 case NC_FLOAT:
16040 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16041 case NC_COMPLEX:
16042 return Expression::make_complex(&this->u_.complex_val.real,
16043 &this->u_.complex_val.imag,
16044 this->type_, loc);
16045 default:
16046 go_unreachable();
16047 }
16048}