]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
compiler: Use backend interface for heap expressions.
[thirdparty/gcc.git] / gcc / go / gofrontend / expressions.cc
CommitLineData
7a938933
ILT
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
52556f04
ILT
9#include <algorithm>
10
7a938933
ILT
11#include "toplev.h"
12#include "intl.h"
13#include "tree.h"
d8a2d370
DN
14#include "stringpool.h"
15#include "stor-layout.h"
861c1d8e 16#include "gimple-expr.h"
7a938933
ILT
17#include "tree-iterator.h"
18#include "convert.h"
19#include "real.h"
20#include "realmpfr.h"
7a938933 21
7a938933
ILT
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"
3b8dffe7 29#include "runtime.h"
d56e6679 30#include "backend.h"
7a938933 31#include "expressions.h"
16c57fe2 32#include "ast-dump.h"
7a938933
ILT
33
34// Class Expression.
35
36Expression::Expression(Expression_classification classification,
8afa2bfb 37 Location location)
7a938933
ILT
38 : classification_(classification), location_(location)
39{
40}
41
42Expression::~Expression()
43{
44}
45
7a938933
ILT
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
3c365907
ILT
80// expression is being discarded. By default, we give an error.
81// Expressions with side effects override.
7a938933 82
3f7af571 83bool
7a938933
ILT
84Expression::do_discarding_value()
85{
3c365907 86 this->unused_value_error();
3f7af571 87 return false;
7a938933
ILT
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{
8c0d1865 96 go_unreachable();
7a938933
ILT
97}
98
3c365907 99// Give an error saying that the value of the expression is not used.
7a938933
ILT
100
101void
3c365907 102Expression::unused_value_error()
7a938933 103{
3f7af571 104 this->report_error(_("value computed is not used"));
7a938933
ILT
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
7035307e 143// Return an expression handling any conversions which must be done during
7a938933
ILT
144// assignment.
145
7035307e
CM
146Expression*
147Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
148 Expression* rhs, Location location)
7a938933 149{
7035307e
CM
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);
7a938933 155
c4675e5e
ILT
156 if (lhs_type->forwarded() != rhs_type->forwarded()
157 && lhs_type->interface_type() != NULL)
7a938933
ILT
158 {
159 if (rhs_type->interface_type() == NULL)
7035307e 160 return Expression::convert_type_to_interface(lhs_type, rhs, location);
7a938933 161 else
7035307e
CM
162 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
163 location);
7a938933 164 }
c4675e5e
ILT
165 else if (lhs_type->forwarded() != rhs_type->forwarded()
166 && rhs_type->interface_type() != NULL)
7035307e 167 return Expression::convert_interface_to_type(lhs_type, rhs, location);
b7190f2f 168 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
7a938933 169 {
7035307e
CM
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);
7a938933
ILT
177 }
178 else if (rhs_type->is_nil_type())
7035307e
CM
179 return Expression::make_nil(location);
180 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
7a938933
ILT
181 {
182 // No conversion is needed.
7035307e
CM
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))
7a938933 193 {
68c5d97b
ILT
194 // Avoid confusion from zero sized variables which may be
195 // represented as non-zero-sized.
7035307e
CM
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;
68c5d97b 202
7a938933
ILT
203 // This conversion must be permitted by Go, or we wouldn't have
204 // gotten here.
7035307e 205 return Expression::make_unsafe_cast(lhs_type, rhs, location);
7a938933
ILT
206 }
207 else
7035307e 208 return rhs;
7a938933
ILT
209}
210
7035307e 211// Return an expression for a conversion from a non-interface type to an
7a938933
ILT
212// interface type.
213
7035307e
CM
214Expression*
215Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
216 Location location)
7a938933 217{
7a938933
ILT
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.
7035307e 226 Type* rhs_type = rhs->type();
7a938933 227 if (rhs_type->is_nil_type())
54466dde 228 {
7035307e
CM
229 Expression* nil = Expression::make_nil(location);
230 return Expression::make_interface_value(lhs_type, nil, nil, location);
54466dde 231 }
7a938933
ILT
232
233 // This should have been checked already.
26409c52 234 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
7a938933 235
7a938933
ILT
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.
7035307e 239 Expression* first_field;
7a938933 240 if (lhs_is_empty)
7035307e 241 first_field = Expression::make_type_descriptor(rhs_type, location);
7a938933
ILT
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();
0efaba3c 248 Struct_type* rhs_struct_type = rhs_type->struct_type();
7a938933 249 bool is_pointer = false;
0efaba3c 250 if (rhs_named_type == NULL && rhs_struct_type == NULL)
7a938933
ILT
251 {
252 rhs_named_type = rhs_type->deref()->named_type();
0efaba3c 253 rhs_struct_type = rhs_type->deref()->struct_type();
7a938933
ILT
254 is_pointer = true;
255 }
0efaba3c 256 if (rhs_named_type != NULL)
7035307e
CM
257 first_field =
258 rhs_named_type->interface_method_table(lhs_interface_type,
259 is_pointer);
0efaba3c 260 else if (rhs_struct_type != NULL)
7035307e
CM
261 first_field =
262 rhs_struct_type->interface_method_table(lhs_interface_type,
263 is_pointer);
0efaba3c 264 else
7035307e 265 first_field = Expression::make_nil(location);
7a938933 266 }
7a938933 267
7035307e 268 Expression* obj;
7a938933
ILT
269 if (rhs_type->points_to() != NULL)
270 {
7035307e 271 // We are assigning a pointer to the interface; the interface
7a938933 272 // holds the pointer itself.
7035307e
CM
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);
7a938933
ILT
280 }
281
7035307e
CM
282 return Expression::make_interface_value(lhs_type, first_field, obj, location);
283}
7a938933 284
7035307e 285// Return an expression for the type descriptor of RHS.
7a938933 286
7035307e
CM
287Expression*
288Expression::get_interface_type_descriptor(Expression* rhs)
289{
290 go_assert(rhs->type()->interface_type() != NULL);
291 Location location = rhs->location();
7a938933 292
7035307e
CM
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);
7a938933 300
7035307e
CM
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);
7a938933 305
7035307e
CM
306 Expression* eq =
307 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
308 return Expression::make_conditional(eq, nil, descriptor, location);
7a938933
ILT
309}
310
7035307e 311// Return an expression for the conversion of an interface type to an
7a938933
ILT
312// interface type.
313
7035307e
CM
314Expression*
315Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
316 bool for_type_guard,
317 Location location)
7a938933 318{
7a938933
ILT
319 Interface_type* lhs_interface_type = lhs_type->interface_type();
320 bool lhs_is_empty = lhs_interface_type->is_empty();
321
7a938933
ILT
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.
7035307e
CM
332 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
333 Expression* lhs_type_expr =
334 Expression::make_type_descriptor(lhs_type, location);
7a938933 335
7035307e 336 Expression* first_field;
7a938933
ILT
337 if (for_type_guard)
338 {
339 // A type assertion fails when converting a nil interface.
7035307e
CM
340 first_field =
341 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
7a938933
ILT
343 }
344 else if (lhs_is_empty)
345 {
7035307e 346 // A conversion to an empty interface always succeeds, and the
7a938933 347 // first field is just the type descriptor of the object.
7035307e 348 first_field = rhs_type_expr;
7a938933
ILT
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.
7035307e
CM
354 first_field =
355 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
356 lhs_type_expr, rhs_type_expr);
7a938933
ILT
357 }
358
359 // The second field is simply the object pointer.
7035307e
CM
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);
7a938933
ILT
363}
364
7035307e 365// Return an expression for the conversion of an interface type to a
7a938933
ILT
366// non-interface type.
367
7035307e
CM
368Expression*
369Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
370 Location location)
7a938933 371{
7a938933
ILT
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.
7035307e
CM
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);
7a938933
ILT
387
388 // If the call succeeds, pull out the value.
7035307e
CM
389 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
390 location);
7a938933
ILT
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 {
7035307e
CM
396 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
397 location);
398 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
7a938933 399 }
7035307e 400 return Expression::make_compound(check_iface, obj, location);
7a938933
ILT
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
002ee4d1
CM
417// Return a backend expression for VAL.
418Bexpression*
419Expression::backend_numeric_constant_expression(Translate_context* context,
420 Numeric_constant* val)
7a938933 421{
002ee4d1
CM
422 Gogo* gogo = context->gogo();
423 Type* type = val->type();
424 if (type == NULL)
425 return gogo->backend()->error_expression();
7a938933 426
002ee4d1
CM
427 Btype* btype = type->get_backend(gogo);
428 Bexpression* ret;
429 if (type->integer_type() != NULL)
7a938933
ILT
430 {
431 mpz_t ival;
002ee4d1
CM
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);
7a938933 438 mpz_clear(ival);
7a938933 439 }
002ee4d1 440 else if (type->float_type() != NULL)
7a938933 441 {
002ee4d1
CM
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);
7a938933 450 }
002ee4d1 451 else if (type->complex_type() != NULL)
7a938933 452 {
002ee4d1
CM
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);
7a938933
ILT
463 }
464 else
8c0d1865 465 go_unreachable();
7a938933 466
002ee4d1 467 return ret;
7a938933
ILT
468}
469
7035307e
CM
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".
7a938933 472
7035307e
CM
473Expression*
474Expression::check_bounds(Expression* val, Location loc)
7a938933 475{
7035307e
CM
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 }
7a938933 494
7035307e
CM
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)
7a938933 504 {
7035307e
CM
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);
7a938933
ILT
511 }
512
7035307e 513 int bound_type_size = bound_type->integer_type()->bits();
24271501
ILT
514 if (val_type_size > bound_type_size
515 || (val_type_size == bound_type_size
7035307e
CM
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);
7a938933
ILT
531 }
532
7035307e
CM
533 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
534 loc);
7a938933
ILT
535}
536
16c57fe2
RL
537void
538Expression::dump_expression(Ast_dump_context* ast_dump_context) const
539{
540 this->do_dump_expression(ast_dump_context);
541}
542
7a938933
ILT
543// Error expressions. This are used to avoid cascading errors.
544
545class Error_expression : public Expression
546{
547 public:
8afa2bfb 548 Error_expression(Location location)
7a938933
ILT
549 : Expression(EXPRESSION_ERROR, location)
550 { }
551
552 protected:
553 bool
554 do_is_constant() const
555 { return true; }
556
39be2171
ILT
557 bool
558 do_is_immutable() const
559 { return true; }
560
7a938933 561 bool
5caf63ca 562 do_numeric_constant_value(Numeric_constant* nc) const
7a938933 563 {
5caf63ca 564 nc->set_unsigned_long(NULL, 0);
7a938933
ILT
565 return true;
566 }
567
3f7af571 568 bool
7a938933 569 do_discarding_value()
3f7af571 570 { return true; }
7a938933
ILT
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; }
16c57fe2
RL
591
592 void
593 do_dump_expression(Ast_dump_context*) const;
7a938933
ILT
594};
595
16c57fe2
RL
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
7a938933 604Expression*
8afa2bfb 605Expression::make_error(Location location)
7a938933
ILT
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:
8afa2bfb 617 Type_expression(Type* type, Location location)
7a938933
ILT
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*)
8c0d1865 645 { go_unreachable(); }
7a938933 646
16c57fe2
RL
647 void do_dump_expression(Ast_dump_context*) const;
648
7a938933
ILT
649 private:
650 // The type which we are representing as an expression.
651 Type* type_;
652};
653
16c57fe2
RL
654void
655Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
656{
657 ast_dump_context->dump_type(this->type_);
658}
659
7a938933 660Expression*
8afa2bfb 661Expression::make_type(Type* type, Location location)
7a938933
ILT
662{
663 return new Type_expression(type, location);
664}
665
8211d03c
ILT
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.
26409c52 675 go_assert(saw_errors());
8211d03c
ILT
676 return Type::make_error_type();
677}
678
7a938933
ILT
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*
8586635c
ILT
687Var_expression::do_lower(Gogo* gogo, Named_object* function,
688 Statement_inserter* inserter, int)
7a938933
ILT
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())
8586635c
ILT
697 {
698 function = NULL;
699 inserter = NULL;
700 }
701 var->lower_init_expression(gogo, function, inserter);
7a938933
ILT
702 }
703 return this;
704}
705
7a938933
ILT
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
8c0d1865 716 go_unreachable();
7a938933
ILT
717}
718
eba4ad89
ILT
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
7a938933
ILT
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)
acf98146
ILT
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 }
7a938933 743 else
acf98146
ILT
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 }
7a938933
ILT
752}
753
754// Get the tree for a reference to a variable.
755
756tree
757Var_expression::do_get_tree(Translate_context* context)
758{
e09ce6c5
ILT
759 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
760 context->function());
e09ce6c5 761 bool is_in_heap;
d4fe7beb 762 Location loc = this->location();
e09ce6c5
ILT
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
8c0d1865 768 go_unreachable();
d4fe7beb
CM
769
770 Bexpression* ret = context->backend()->var_expression(bvar, loc);
e09ce6c5 771 if (is_in_heap)
d4fe7beb
CM
772 ret = context->backend()->indirect_expression(ret, true, loc);
773 return expr_to_tree(ret);
7a938933
ILT
774}
775
16c57fe2
RL
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
7a938933
ILT
784// Make a reference to a variable in an expression.
785
786Expression*
8afa2bfb 787Expression::make_var_reference(Named_object* var, Location location)
7a938933
ILT
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
9131ad67 821Temporary_reference_expression::do_get_tree(Translate_context* context)
7a938933 822{
c6d2bfbb 823 Gogo* gogo = context->gogo();
9131ad67 824 Bvariable* bvar = this->statement_->get_backend_variable(context);
c6d2bfbb 825 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
9131ad67 826
c6d2bfbb 827 // The backend can't always represent the same set of recursive types
9131ad67
ILT
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.
c6d2bfbb 832 Type* stype = this->statement_->type();
8586635c 833 if (!this->is_lvalue_
c6d2bfbb
CM
834 && stype->has_pointer()
835 && stype->deref()->is_void_type())
9131ad67 836 {
c6d2bfbb
CM
837 Btype* btype = this->type()->base()->get_backend(gogo);
838 ret = gogo->backend()->convert_expression(btype, ret, this->location());
9131ad67 839 }
c6d2bfbb 840 return expr_to_tree(ret);
7a938933
ILT
841}
842
16c57fe2
RL
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
7a938933
ILT
852// Make a reference to a temporary variable.
853
8586635c 854Temporary_reference_expression*
7a938933 855Expression::make_temporary_reference(Temporary_statement* statement,
8afa2bfb 856 Location location)
7a938933
ILT
857{
858 return new Temporary_reference_expression(statement, location);
859}
860
f9f96987
ILT
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
571d3f91
ILT
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
f9f96987
ILT
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
7a938933
ILT
927// A sink expression--a use of the blank identifier _.
928
929class Sink_expression : public Expression
930{
931 public:
8afa2bfb 932 Sink_expression(Location location)
7a938933
ILT
933 : Expression(EXPRESSION_SINK, location),
934 type_(NULL), var_(NULL_TREE)
935 { }
936
937 protected:
3f7af571 938 bool
7a938933 939 do_discarding_value()
3f7af571 940 { return true; }
7a938933
ILT
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
16c57fe2
RL
955 void
956 do_dump_expression(Ast_dump_context*) const;
957
7a938933
ILT
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 {
26409c52 992 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
5b735706
ILT
993 Btype* bt = this->type_->get_backend(context->gogo());
994 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
7a938933
ILT
995 }
996 return this->var_;
997}
998
16c57fe2
RL
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
7a938933
ILT
1007// Make a sink expression.
1008
1009Expression*
8afa2bfb 1010Expression::make_sink(Location location)
7a938933
ILT
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
7a938933
ILT
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
8c0d1865 1042 go_unreachable();
7a938933
ILT
1043}
1044
fdbc38a6 1045// Get the tree for the code of a function expression.
7a938933 1046
b7d93b46 1047Bexpression*
fdbc38a6 1048Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
7a938933
ILT
1049{
1050 Function_type* fntype;
fdbc38a6
ILT
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();
7a938933 1055 else
8c0d1865 1056 go_unreachable();
7a938933
ILT
1057
1058 // Builtin functions are handled specially by Call_expression. We
1059 // can't take their address.
1060 if (fntype->is_builtin())
1061 {
fdbc38a6 1062 error_at(loc,
a0236882 1063 "invalid use of special builtin function %qs; must be called",
fdbc38a6 1064 no->message_name().c_str());
b7d93b46 1065 return gogo->backend()->error_expression();
7a938933
ILT
1066 }
1067
b7d93b46 1068 Bfunction* fndecl;
7a938933 1069 if (no->is_function())
f7191ecd 1070 fndecl = no->func_value()->get_or_make_decl(gogo, no);
7a938933 1071 else if (no->is_function_declaration())
f7191ecd 1072 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
7a938933 1073 else
8c0d1865 1074 go_unreachable();
7a938933 1075
b7d93b46 1076 return gogo->backend()->function_code_expression(fndecl, loc);
7a938933
ILT
1077}
1078
1079// Get the tree for a function expression. This is used when we take
fdbc38a6
ILT
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.
7a938933
ILT
1085
1086tree
1087Func_expression::do_get_tree(Translate_context* context)
1088{
fdbc38a6 1089 // If there is no closure, just use the function descriptor.
40bb0243 1090 if (this->closure_ == NULL)
fdbc38a6
ILT
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();
40bb0243 1111
fdbc38a6
ILT
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 }
7a938933 1117
fdbc38a6 1118 go_assert(this->function_->func_value()->enclosing() != NULL);
7a938933 1119
fdbc38a6
ILT
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);
7a938933
ILT
1125}
1126
16c57fe2
RL
1127// Ast dump for function.
1128
1129void
1130Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1131{
706cd57f
RL
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 }
16c57fe2
RL
1139}
1140
7a938933
ILT
1141// Make a reference to a function in an expression.
1142
1143Expression*
1144Expression::make_func_reference(Named_object* function, Expression* closure,
8afa2bfb 1145 Location location)
7a938933
ILT
1146{
1147 return new Func_expression(function, closure, location);
1148}
1149
ed3cd943 1150// Class Func_descriptor_expression.
fdbc38a6 1151
ed3cd943 1152// Constructor.
fdbc38a6 1153
ed3cd943
ILT
1154Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1155 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
05a7d566 1156 fn_(fn), dvar_(NULL)
ed3cd943
ILT
1157{
1158 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1159}
fdbc38a6 1160
ed3cd943 1161// Traversal.
fdbc38a6 1162
ed3cd943
ILT
1163int
1164Func_descriptor_expression::do_traverse(Traverse*)
1165{
1166 return TRAVERSE_CONTINUE;
1167}
fdbc38a6
ILT
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()))
05a7d566
ILT
1217 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1218 loc);
fdbc38a6
ILT
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();
05a7d566 1228 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
fdbc38a6
ILT
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
ed3cd943
ILT
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
fdbc38a6
ILT
1250// Make a function descriptor expression.
1251
ed3cd943
ILT
1252Func_descriptor_expression*
1253Expression::make_func_descriptor(Named_object* fn)
fdbc38a6 1254{
ed3cd943 1255 return new Func_descriptor_expression(fn);
fdbc38a6
ILT
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
8a35e18d
CM
1281 bool
1282 do_is_immutable() const
1283 { return true; }
1284
fdbc38a6
ILT
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{
b7d93b46
CM
1317 Bexpression* ret =
1318 Func_expression::get_code_pointer(context->gogo(), this->function_,
1319 this->location());
1320 return expr_to_tree(ret);
fdbc38a6
ILT
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
7a938933
ILT
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*
8586635c 1344Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
7a938933 1345{
8afa2bfb 1346 Location location = this->location();
7a938933 1347 Named_object* no = this->named_object_;
62d1a8f9
ILT
1348 Named_object* real;
1349 if (!no->is_unknown())
1350 real = no;
1351 else
7a938933 1352 {
62d1a8f9
ILT
1353 real = no->unknown_value()->real_named_object();
1354 if (real == NULL)
1355 {
1356 if (this->is_composite_literal_key_)
1357 return this;
d4157849
ILT
1358 if (!this->no_error_message_)
1359 error_at(location, "reference to undefined name %qs",
1360 this->named_object_->message_name().c_str());
62d1a8f9
ILT
1361 return Expression::make_error(location);
1362 }
7a938933
ILT
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;
d4157849
ILT
1373 if (!this->no_error_message_)
1374 error_at(location, "reference to undefined type %qs",
1375 real->message_name().c_str());
7a938933
ILT
1376 return Expression::make_error(location);
1377 case Named_object::NAMED_OBJECT_VAR:
b1b3aec1 1378 real->var_value()->set_is_used();
7a938933
ILT
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;
d4157849
ILT
1386 if (!this->no_error_message_)
1387 error_at(location, "unexpected reference to package");
7a938933
ILT
1388 return Expression::make_error(location);
1389 default:
8c0d1865 1390 go_unreachable();
7a938933
ILT
1391 }
1392}
1393
16c57fe2
RL
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 << ")";
16c57fe2
RL
1401}
1402
7a938933
ILT
1403// Make a reference to an unknown name.
1404
d4157849 1405Unknown_expression*
8afa2bfb 1406Expression::make_unknown_reference(Named_object* no, Location location)
7a938933 1407{
7a938933
ILT
1408 return new Unknown_expression(no, location);
1409}
1410
1411// A boolean expression.
1412
1413class Boolean_expression : public Expression
1414{
1415 public:
8afa2bfb 1416 Boolean_expression(bool val, Location location)
7a938933
ILT
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
39be2171
ILT
1429 bool
1430 do_is_immutable() const
1431 { return true; }
1432
7a938933
ILT
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
16c57fe2
RL
1451 void
1452 do_dump_expression(Ast_dump_context* ast_dump_context) const
1453 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1454
7a938933
ILT
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*
8afa2bfb 1505Expression::make_boolean(bool val, Location location)
7a938933
ILT
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{
7035307e
CM
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);
7a938933
ILT
1557}
1558
706cd57f 1559 // Write string literal to string dump.
7a938933
ILT
1560
1561void
706cd57f
RL
1562String_expression::export_string(String_dump* exp,
1563 const String_expression* str)
7a938933
ILT
1564{
1565 std::string s;
706cd57f 1566 s.reserve(str->val_.length() * 4 + 2);
7a938933 1567 s += '"';
706cd57f
RL
1568 for (std::string::const_iterator p = str->val_.begin();
1569 p != str->val_.end();
7a938933
ILT
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
706cd57f
RL
1597// Export a string expression.
1598
1599void
1600String_expression::do_export(Export* exp) const
1601{
1602 String_expression::export_string(exp, this);
1603}
1604
7a938933
ILT
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
16c57fe2
RL
1647// Ast dump for string expression.
1648
1649void
1650String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1651{
706cd57f 1652 String_expression::export_string(ast_dump_context, this);
16c57fe2
RL
1653}
1654
7a938933
ILT
1655// Make a string expression.
1656
1657Expression*
8afa2bfb 1658Expression::make_string(const std::string& val, Location location)
7a938933
ILT
1659{
1660 return new String_expression(val, location);
1661}
1662
7035307e
CM
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
7a938933
ILT
1773// Make an integer expression.
1774
1775class Integer_expression : public Expression
1776{
1777 public:
fb3f3aa2
ILT
1778 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1779 Location location)
7a938933 1780 : Expression(EXPRESSION_INTEGER, location),
fb3f3aa2 1781 type_(type), is_character_constant_(is_character_constant)
7a938933
ILT
1782 { mpz_init_set(this->val_, *val); }
1783
1784 static Expression*
1785 do_import(Import*);
1786
706cd57f 1787 // Write VAL to string dump.
7a938933 1788 static void
706cd57f 1789 export_integer(String_dump* exp, const mpz_t val);
7a938933 1790
16c57fe2
RL
1791 // Write VAL to dump context.
1792 static void
1793 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1794
7a938933
ILT
1795 protected:
1796 bool
1797 do_is_constant() const
1798 { return true; }
1799
39be2171
ILT
1800 bool
1801 do_is_immutable() const
1802 { return true; }
1803
7a938933 1804 bool
5caf63ca 1805 do_numeric_constant_value(Numeric_constant* nc) const;
7a938933
ILT
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()
fb3f3aa2
ILT
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 }
7a938933
ILT
1829
1830 void
1831 do_export(Export*) const;
1832
16c57fe2
RL
1833 void
1834 do_dump_expression(Ast_dump_context*) const;
1835
7a938933
ILT
1836 private:
1837 // The integer value.
1838 mpz_t val_;
1839 // The type so far.
1840 Type* type_;
fb3f3aa2
ILT
1841 // Whether this is a character constant.
1842 bool is_character_constant_;
7a938933
ILT
1843};
1844
5caf63ca
ILT
1845// Return a numeric constant for this expression. We have to mark
1846// this as a character when appropriate.
7a938933
ILT
1847
1848bool
5caf63ca 1849Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
7a938933 1850{
5caf63ca
ILT
1851 if (this->is_character_constant_)
1852 nc->set_rune(this->type_, this->val_);
1853 else
1854 nc->set_int(this->type_, this->val_);
7a938933
ILT
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)
fb3f3aa2
ILT
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 }
7a938933
ILT
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 ;
5caf63ca 1882 else if (context->type != NULL && context->type->is_numeric_type())
7a938933
ILT
1883 this->type_ = context->type;
1884 else if (!context->may_be_abstract)
fb3f3aa2
ILT
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 }
7a938933
ILT
1891}
1892
7a938933
ILT
1893// Check the type of an integer constant.
1894
1895void
1896Integer_expression::do_check_types(Gogo*)
1897{
5caf63ca
ILT
1898 Type* type = this->type_;
1899 if (type == NULL)
7a938933 1900 return;
5caf63ca
ILT
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()))
7a938933
ILT
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{
002ee4d1 1915 Type* resolved_type = NULL;
7a938933 1916 if (this->type_ != NULL && !this->type_->is_abstract())
002ee4d1 1917 resolved_type = this->type_;
7a938933
ILT
1918 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1919 {
1920 // We are converting to an abstract floating point type.
002ee4d1 1921 resolved_type = Type::lookup_float_type("float64");
7a938933
ILT
1922 }
1923 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1924 {
1925 // We are converting to an abstract complex type.
002ee4d1 1926 resolved_type = Type::lookup_complex_type("complex128");
7a938933
ILT
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);
776f27a6
ILT
1935 Type* int_type = Type::lookup_integer_type("int");
1936 if (bits < int_type->integer_type()->bits())
002ee4d1 1937 resolved_type = int_type;
7a938933 1938 else if (bits < 64)
002ee4d1 1939 resolved_type = Type::lookup_integer_type("int64");
7a938933 1940 else
002ee4d1
CM
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 }
7a938933 1948 }
002ee4d1
CM
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);
7a938933
ILT
1954}
1955
1956// Write VAL to export data.
1957
1958void
706cd57f 1959Integer_expression::export_integer(String_dump* exp, const mpz_t val)
7a938933
ILT
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_);
fb3f3aa2
ILT
1972 if (this->is_character_constant_)
1973 exp->write_c_string("'");
7a938933
ILT
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 {
fb3f3aa2
ILT
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);
7a938933
ILT
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 }
fb3f3aa2
ILT
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());
7a938933
ILT
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}
16c57fe2
RL
2070// Ast dump for integer expression.
2071
2072void
2073Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2074{
fb3f3aa2
ILT
2075 if (this->is_character_constant_)
2076 ast_dump_context->ostream() << '\'';
706cd57f 2077 Integer_expression::export_integer(ast_dump_context, this->val_);
fb3f3aa2
ILT
2078 if (this->is_character_constant_)
2079 ast_dump_context->ostream() << '\'';
16c57fe2
RL
2080}
2081
7a938933
ILT
2082// Build a new integer value.
2083
2084Expression*
fb3f3aa2
ILT
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)
7a938933 2094{
fb3f3aa2 2095 return new Integer_expression(val, type, true, location);
7a938933
ILT
2096}
2097
2098// Floats.
2099
2100class Float_expression : public Expression
2101{
2102 public:
8afa2bfb 2103 Float_expression(const mpfr_t* val, Type* type, Location location)
7a938933
ILT
2104 : Expression(EXPRESSION_FLOAT, location),
2105 type_(type)
2106 {
2107 mpfr_init_set(this->val_, *val, GMP_RNDN);
2108 }
2109
7a938933
ILT
2110 // Write VAL to export data.
2111 static void
706cd57f
RL
2112 export_float(String_dump* exp, const mpfr_t val);
2113
16c57fe2
RL
2114 // Write VAL to dump file.
2115 static void
2116 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
7a938933
ILT
2117
2118 protected:
2119 bool
2120 do_is_constant() const
2121 { return true; }
2122
39be2171
ILT
2123 bool
2124 do_is_immutable() const
2125 { return true; }
2126
7a938933 2127 bool
5caf63ca
ILT
2128 do_numeric_constant_value(Numeric_constant* nc) const
2129 {
2130 nc->set_float(this->type_, this->val_);
2131 return true;
2132 }
7a938933
ILT
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
16c57fe2
RL
2154 void
2155 do_dump_expression(Ast_dump_context*) const;
2156
7a938933
ILT
2157 private:
2158 // The floating point value.
2159 mpfr_t val_;
2160 // The type so far.
2161 Type* type_;
2162};
2163
7a938933
ILT
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)
ff5f50c5 2189 this->type_ = Type::lookup_float_type("float64");
7a938933
ILT
2190}
2191
7a938933
ILT
2192// Check the type of a float value.
2193
2194void
2195Float_expression::do_check_types(Gogo*)
2196{
5caf63ca
ILT
2197 Type* type = this->type_;
2198 if (type == NULL)
7a938933 2199 return;
5caf63ca
ILT
2200 Numeric_constant nc;
2201 nc.set_float(NULL, this->val_);
2202 if (!nc.set_type(this->type_, true, this->location()))
7a938933 2203 this->set_is_error();
7a938933
ILT
2204}
2205
2206// Get a tree for a float constant.
2207
2208tree
2209Float_expression::do_get_tree(Translate_context* context)
2210{
002ee4d1 2211 Type* resolved_type;
7a938933 2212 if (this->type_ != NULL && !this->type_->is_abstract())
002ee4d1 2213 resolved_type = this->type_;
7a938933
ILT
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.
002ee4d1
CM
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");
7a938933
ILT
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.
002ee4d1 2229 resolved_type = Type::lookup_float_type("float64");
7a938933 2230 }
002ee4d1
CM
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);
7a938933
ILT
2237}
2238
706cd57f 2239// Write a floating point number to a string dump.
7a938933
ILT
2240
2241void
706cd57f 2242Float_expression::export_float(String_dump *exp, const mpfr_t val)
7a938933
ILT
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
16c57fe2
RL
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{
706cd57f 2271 Float_expression::export_float(ast_dump_context, this->val_);
16c57fe2
RL
2272}
2273
7a938933
ILT
2274// Make a float expression.
2275
2276Expression*
8afa2bfb 2277Expression::make_float(const mpfr_t* val, Type* type, Location location)
7a938933
ILT
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,
8afa2bfb 2288 Location location)
7a938933
ILT
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
706cd57f 2296 // Write REAL/IMAG to string dump.
7a938933 2297 static void
706cd57f 2298 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
7a938933 2299
16c57fe2
RL
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
7a938933
ILT
2305 protected:
2306 bool
2307 do_is_constant() const
2308 { return true; }
2309
39be2171
ILT
2310 bool
2311 do_is_immutable() const
2312 { return true; }
2313
7a938933 2314 bool
5caf63ca
ILT
2315 do_numeric_constant_value(Numeric_constant* nc) const
2316 {
2317 nc->set_complex(this->type_, this->real_, this->imag_);
2318 return true;
2319 }
7a938933
ILT
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
16c57fe2
RL
2343 void
2344 do_dump_expression(Ast_dump_context*) const;
2345
7a938933
ILT
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
7a938933
ILT
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)
ff5f50c5 2378 this->type_ = Type::lookup_complex_type("complex128");
7a938933
ILT
2379}
2380
7a938933
ILT
2381// Check the type of a complex value.
2382
2383void
2384Complex_expression::do_check_types(Gogo*)
2385{
5caf63ca
ILT
2386 Type* type = this->type_;
2387 if (type == NULL)
7a938933 2388 return;
5caf63ca
ILT
2389 Numeric_constant nc;
2390 nc.set_complex(NULL, this->real_, this->imag_);
2391 if (!nc.set_type(this->type_, true, this->location()))
7a938933
ILT
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{
002ee4d1 2400 Type* resolved_type;
7a938933 2401 if (this->type_ != NULL && !this->type_->is_abstract())
002ee4d1
CM
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 }
7a938933
ILT
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.
002ee4d1 2418 resolved_type = Type::lookup_complex_type("complex128");
7a938933 2419 }
002ee4d1
CM
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);
7a938933
ILT
2426}
2427
2428// Write REAL/IMAG to export data.
2429
2430void
706cd57f 2431Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
7a938933
ILT
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
16c57fe2
RL
2454// Dump a complex expression to the dump file.
2455
2456void
2457Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2458{
706cd57f 2459 Complex_expression::export_complex(ast_dump_context,
16c57fe2
RL
2460 this->real_,
2461 this->imag_);
2462}
2463
7a938933
ILT
2464// Make a complex expression.
2465
2466Expression*
2467Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
8afa2bfb 2468 Location location)
7a938933
ILT
2469{
2470 return new Complex_expression(real, imag, type, location);
2471}
2472
6e25f095
ILT
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
7a938933
ILT
2499// A reference to a const in an expression.
2500
2501class Const_expression : public Expression
2502{
2503 public:
8afa2bfb 2504 Const_expression(Named_object* constant, Location location)
7a938933 2505 : Expression(EXPRESSION_CONST_REFERENCE, location),
f80d990e 2506 constant_(constant), type_(NULL), seen_(false)
7a938933
ILT
2507 { }
2508
6e25f095
ILT
2509 Named_object*
2510 named_object()
2511 { return this->constant_; }
2512
036c8f37
ILT
2513 // Check that the initializer does not refer to the constant itself.
2514 void
2515 check_for_init_loop();
2516
7a938933 2517 protected:
b68a9b10
ILT
2518 int
2519 do_traverse(Traverse*);
2520
7a938933 2521 Expression*
8586635c 2522 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7a938933
ILT
2523
2524 bool
2525 do_is_constant() const
2526 { return true; }
2527
39be2171
ILT
2528 bool
2529 do_is_immutable() const
2530 { return true; }
2531
7a938933 2532 bool
5caf63ca 2533 do_numeric_constant_value(Numeric_constant* nc) const;
7a938933
ILT
2534
2535 bool
2dfc736c 2536 do_string_constant_value(std::string* val) const;
7a938933
ILT
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
16c57fe2
RL
2562 void
2563 do_dump_expression(Ast_dump_context*) const;
2564
7a938933
ILT
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_;
f80d990e
ILT
2571 // Used to prevent infinite recursion when a constant incorrectly
2572 // refers to itself.
2573 mutable bool seen_;
7a938933
ILT
2574};
2575
b68a9b10
ILT
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
7a938933
ILT
2586// Lower a constant expression. This is where we convert the
2587// predeclared constant iota into an integer value.
2588
2589Expression*
8586635c
ILT
2590Const_expression::do_lower(Gogo* gogo, Named_object*,
2591 Statement_inserter*, int iota_value)
7a938933
ILT
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
5caf63ca 2616// Return a numeric constant value.
7a938933
ILT
2617
2618bool
5caf63ca 2619Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
7a938933 2620{
f80d990e
ILT
2621 if (this->seen_)
2622 return false;
2623
7a938933 2624 Expression* e = this->constant_->const_value()->expr();
5caf63ca 2625
f80d990e
ILT
2626 this->seen_ = true;
2627
5caf63ca 2628 bool r = e->numeric_constant_value(nc);
7a938933 2629
f80d990e
ILT
2630 this->seen_ = false;
2631
7a938933
ILT
2632 Type* ctype;
2633 if (this->type_ != NULL)
2634 ctype = this->type_;
2635 else
2636 ctype = this->constant_->const_value()->type();
7a938933
ILT
2637 if (r && ctype != NULL)
2638 {
5caf63ca 2639 if (!nc->set_type(ctype, false, this->location()))
7a938933 2640 return false;
7a938933 2641 }
7a938933 2642
7a938933
ILT
2643 return r;
2644}
2645
2dfc736c
ILT
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
7a938933
ILT
2661// Return the type of the const reference.
2662
2663Type*
2664Const_expression::do_type()
2665{
2666 if (this->type_ != NULL)
2667 return this->type_;
f80d990e 2668
8e6c2a27
ILT
2669 Named_constant* nc = this->constant_->const_value();
2670
2671 if (this->seen_ || nc->lowering())
f80d990e
ILT
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
7a938933 2680 Type* ret = nc->type();
f80d990e 2681
7a938933 2682 if (ret != NULL)
f80d990e
ILT
2683 {
2684 this->seen_ = false;
2685 return ret;
2686 }
2687
7a938933
ILT
2688 // During parsing, a named constant may have a NULL type, but we
2689 // must not return a NULL type here.
f80d990e
ILT
2690 ret = nc->expr()->type();
2691
2692 this->seen_ = false;
2693
2694 return ret;
7a938933
ILT
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
5caf63ca
ILT
2709 && context->type->is_numeric_type()
2710 && cetype->is_numeric_type())
7a938933
ILT
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
036c8f37
ILT
2728// Check for a loop in which the initializer of a constant refers to
2729// the constant itself.
7a938933
ILT
2730
2731void
036c8f37 2732Const_expression::check_for_init_loop()
7a938933 2733{
02ed921a 2734 if (this->type_ != NULL && this->type_->is_error())
6e25f095
ILT
2735 return;
2736
036c8f37
ILT
2737 if (this->seen_)
2738 {
2739 this->report_error(_("constant refers to itself"));
2740 this->type_ = Type::make_error_type();
2741 return;
2742 }
2743
6e25f095
ILT
2744 Expression* init = this->constant_->const_value()->expr();
2745 Find_named_object find_named_object(this->constant_);
036c8f37
ILT
2746
2747 this->seen_ = true;
6e25f095 2748 Expression::traverse(&init, &find_named_object);
036c8f37
ILT
2749 this->seen_ = false;
2750
6e25f095
ILT
2751 if (find_named_object.found())
2752 {
02ed921a 2753 if (this->type_ == NULL || !this->type_->is_error())
036c8f37
ILT
2754 {
2755 this->report_error(_("constant refers to itself"));
2756 this->type_ = Type::make_error_type();
2757 }
6e25f095
ILT
2758 return;
2759 }
036c8f37
ILT
2760}
2761
2762// Check types of a const reference.
2763
2764void
2765Const_expression::do_check_types(Gogo*)
2766{
02ed921a 2767 if (this->type_ != NULL && this->type_->is_error())
036c8f37
ILT
2768 return;
2769
2770 this->check_for_init_loop();
6e25f095 2771
5caf63ca
ILT
2772 // Check that numeric constant fits in type.
2773 if (this->type_ != NULL && this->type_->is_numeric_type())
7a938933 2774 {
5caf63ca
ILT
2775 Numeric_constant nc;
2776 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
7a938933 2777 {
5caf63ca
ILT
2778 if (!nc.set_type(this->type_, true, this->location()))
2779 this->set_is_error();
7a938933 2780 }
7a938933
ILT
2781 }
2782}
2783
2784// Return a tree for the const reference.
2785
2786tree
2787Const_expression::do_get_tree(Translate_context* context)
2788{
7035307e
CM
2789 if (this->type_ != NULL && this->type_->is_error())
2790 return error_mark_node;
7a938933
ILT
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.
e85baec7 2795 Expression* expr = this->constant_->const_value()->expr();
7a938933 2796 if (this->type_ != NULL
5caf63ca 2797 && this->type_->is_numeric_type()
1ed36e90
ILT
2798 && (this->constant_->const_value()->type() == NULL
2799 || this->constant_->const_value()->type()->is_abstract()))
7a938933 2800 {
5caf63ca
ILT
2801 Numeric_constant nc;
2802 if (expr->numeric_constant_value(&nc)
2803 && nc.set_type(this->type_, false, this->location()))
7a938933 2804 {
5caf63ca
ILT
2805 Expression* e = nc.expression(this->location());
2806 return e->get_tree(context);
7a938933 2807 }
7a938933
ILT
2808 }
2809
7035307e 2810 if (this->type_ != NULL)
e85baec7
CM
2811 expr = Expression::make_cast(this->type_, expr, this->location());
2812 return expr->get_tree(context);
7a938933
ILT
2813}
2814
16c57fe2
RL
2815// Dump ast representation for constant expression.
2816
2817void
2818Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2819{
2820 ast_dump_context->ostream() << this->constant_->name();
2821}
2822
7a938933
ILT
2823// Make a reference to a constant in an expression.
2824
2825Expression*
2826Expression::make_const_reference(Named_object* constant,
8afa2bfb 2827 Location location)
7a938933
ILT
2828{
2829 return new Const_expression(constant, location);
2830}
2831
6e25f095
ILT
2832// Find a named object in an expression.
2833
2834int
2835Find_named_object::expression(Expression** pexpr)
2836{
2837 switch ((*pexpr)->classification())
2838 {
2839 case Expression::EXPRESSION_CONST_REFERENCE:
036c8f37
ILT
2840 {
2841 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2842 if (ce->named_object() == this->no_)
2843 break;
2844
2845 // We need to check a constant initializer explicitly, as
2846 // loops here will not be caught by the loop checking for
2847 // variable initializers.
2848 ce->check_for_init_loop();
2849
2850 return TRAVERSE_CONTINUE;
2851 }
2852
6e25f095
ILT
2853 case Expression::EXPRESSION_VAR_REFERENCE:
2854 if ((*pexpr)->var_expression()->named_object() == this->no_)
2855 break;
2856 return TRAVERSE_CONTINUE;
2857 case Expression::EXPRESSION_FUNC_REFERENCE:
2858 if ((*pexpr)->func_expression()->named_object() == this->no_)
2859 break;
2860 return TRAVERSE_CONTINUE;
2861 default:
2862 return TRAVERSE_CONTINUE;
2863 }
2864 this->found_ = true;
2865 return TRAVERSE_EXIT;
2866}
2867
7a938933
ILT
2868// The nil value.
2869
2870class Nil_expression : public Expression
2871{
2872 public:
8afa2bfb 2873 Nil_expression(Location location)
7a938933
ILT
2874 : Expression(EXPRESSION_NIL, location)
2875 { }
2876
2877 static Expression*
2878 do_import(Import*);
2879
2880 protected:
2881 bool
2882 do_is_constant() const
2883 { return true; }
2884
8a35e18d
CM
2885 bool
2886 do_is_immutable() const
2887 { return true; }
2888
7a938933
ILT
2889 Type*
2890 do_type()
2891 { return Type::make_nil_type(); }
2892
2893 void
2894 do_determine_type(const Type_context*)
2895 { }
2896
2897 Expression*
2898 do_copy()
2899 { return this; }
2900
2901 tree
2902 do_get_tree(Translate_context*)
2903 { return null_pointer_node; }
2904
2905 void
2906 do_export(Export* exp) const
2907 { exp->write_c_string("nil"); }
16c57fe2
RL
2908
2909 void
2910 do_dump_expression(Ast_dump_context* ast_dump_context) const
2911 { ast_dump_context->ostream() << "nil"; }
7a938933
ILT
2912};
2913
2914// Import a nil expression.
2915
2916Expression*
2917Nil_expression::do_import(Import* imp)
2918{
2919 imp->require_c_string("nil");
2920 return Expression::make_nil(imp->location());
2921}
2922
2923// Make a nil expression.
2924
2925Expression*
8afa2bfb 2926Expression::make_nil(Location location)
7a938933
ILT
2927{
2928 return new Nil_expression(location);
2929}
2930
2931// The value of the predeclared constant iota. This is little more
2932// than a marker. This will be lowered to an integer in
2933// Const_expression::do_lower, which is where we know the value that
2934// it should have.
2935
2936class Iota_expression : public Parser_expression
2937{
2938 public:
8afa2bfb 2939 Iota_expression(Location location)
7a938933
ILT
2940 : Parser_expression(EXPRESSION_IOTA, location)
2941 { }
2942
2943 protected:
2944 Expression*
8586635c 2945 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
8c0d1865 2946 { go_unreachable(); }
7a938933
ILT
2947
2948 // There should only ever be one of these.
2949 Expression*
2950 do_copy()
8c0d1865 2951 { go_unreachable(); }
16c57fe2
RL
2952
2953 void
2954 do_dump_expression(Ast_dump_context* ast_dump_context) const
2955 { ast_dump_context->ostream() << "iota"; }
7a938933
ILT
2956};
2957
2958// Make an iota expression. This is only called for one case: the
2959// value of the predeclared constant iota.
2960
2961Expression*
2962Expression::make_iota()
2963{
8afa2bfb 2964 static Iota_expression iota_expression(Linemap::unknown_location());
7a938933
ILT
2965 return &iota_expression;
2966}
2967
2968// A type conversion expression.
2969
2970class Type_conversion_expression : public Expression
2971{
2972 public:
2973 Type_conversion_expression(Type* type, Expression* expr,
8afa2bfb 2974 Location location)
7a938933
ILT
2975 : Expression(EXPRESSION_CONVERSION, location),
2976 type_(type), expr_(expr), may_convert_function_types_(false)
2977 { }
2978
2979 // Return the type to which we are converting.
2980 Type*
2981 type() const
2982 { return this->type_; }
2983
2984 // Return the expression which we are converting.
2985 Expression*
2986 expr() const
2987 { return this->expr_; }
2988
2989 // Permit converting from one function type to another. This is
2990 // used internally for method expressions.
2991 void
2992 set_may_convert_function_types()
2993 {
2994 this->may_convert_function_types_ = true;
2995 }
2996
2997 // Import a type conversion expression.
2998 static Expression*
2999 do_import(Import*);
3000
3001 protected:
3002 int
3003 do_traverse(Traverse* traverse);
3004
3005 Expression*
8586635c 3006 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7a938933 3007
6ddb6288
ILT
3008 Expression*
3009 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3010
7a938933 3011 bool
e7d9342c 3012 do_is_constant() const;
7a938933 3013
39be2171
ILT
3014 bool
3015 do_is_immutable() const;
3016
7a938933 3017 bool
5caf63ca 3018 do_numeric_constant_value(Numeric_constant*) const;
7a938933
ILT
3019
3020 bool
3021 do_string_constant_value(std::string*) const;
3022
3023 Type*
3024 do_type()
3025 { return this->type_; }
3026
3027 void
3028 do_determine_type(const Type_context*)
3029 {
3030 Type_context subcontext(this->type_, false);
3031 this->expr_->determine_type(&subcontext);
3032 }
3033
3034 void
3035 do_check_types(Gogo*);
3036
3037 Expression*
3038 do_copy()
3039 {
3040 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3041 this->location());
3042 }
3043
3044 tree
3045 do_get_tree(Translate_context* context);
3046
3047 void
3048 do_export(Export*) const;
3049
16c57fe2
RL
3050 void
3051 do_dump_expression(Ast_dump_context*) const;
3052
7a938933
ILT
3053 private:
3054 // The type to convert to.
3055 Type* type_;
3056 // The expression to convert.
3057 Expression* expr_;
3058 // True if this is permitted to convert function types. This is
3059 // used internally for method expressions.
3060 bool may_convert_function_types_;
3061};
3062
3063// Traversal.
3064
3065int
3066Type_conversion_expression::do_traverse(Traverse* traverse)
3067{
3068 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3069 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3070 return TRAVERSE_EXIT;
3071 return TRAVERSE_CONTINUE;
3072}
3073
3074// Convert to a constant at lowering time.
3075
3076Expression*
8586635c
ILT
3077Type_conversion_expression::do_lower(Gogo*, Named_object*,
3078 Statement_inserter*, int)
7a938933
ILT
3079{
3080 Type* type = this->type_;
3081 Expression* val = this->expr_;
8afa2bfb 3082 Location location = this->location();
7a938933 3083
5caf63ca 3084 if (type->is_numeric_type())
7a938933 3085 {
5caf63ca
ILT
3086 Numeric_constant nc;
3087 if (val->numeric_constant_value(&nc))
7a938933 3088 {
5caf63ca
ILT
3089 if (!nc.set_type(type, true, location))
3090 return Expression::make_error(location);
3091 return nc.expression(location);
7a938933 3092 }
7a938933
ILT
3093 }
3094
863ea6cf 3095 if (type->is_slice_type())
7a938933
ILT
3096 {
3097 Type* element_type = type->array_type()->element_type()->forwarded();
7b31a84d
ILT
3098 bool is_byte = (element_type->integer_type() != NULL
3099 && element_type->integer_type()->is_byte());
3100 bool is_rune = (element_type->integer_type() != NULL
3101 && element_type->integer_type()->is_rune());
3102 if (is_byte || is_rune)
7a938933
ILT
3103 {
3104 std::string s;
3105 if (val->string_constant_value(&s))
3106 {
3107 Expression_list* vals = new Expression_list();
3108 if (is_byte)
3109 {
3110 for (std::string::const_iterator p = s.begin();
3111 p != s.end();
3112 p++)
3113 {
3114 mpz_t val;
3115 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3116 Expression* v = Expression::make_integer(&val,
3117 element_type,
3118 location);
3119 vals->push_back(v);
3120 mpz_clear(val);
3121 }
3122 }
3123 else
3124 {
3125 const char *p = s.data();
3126 const char *pend = s.data() + s.length();
3127 while (p < pend)
3128 {
3129 unsigned int c;
3130 int adv = Lex::fetch_char(p, &c);
3131 if (adv == 0)
3132 {
3133 warning_at(this->location(), 0,
3134 "invalid UTF-8 encoding");
3135 adv = 1;
3136 }
3137 p += adv;
3138 mpz_t val;
3139 mpz_init_set_ui(val, c);
3140 Expression* v = Expression::make_integer(&val,
3141 element_type,
3142 location);
3143 vals->push_back(v);
3144 mpz_clear(val);
3145 }
3146 }
3147
3148 return Expression::make_slice_composite_literal(type, vals,
3149 location);
3150 }
3151 }
3152 }
3153
3154 return this;
3155}
3156
6ddb6288
ILT
3157// Flatten a type conversion by using a temporary variable for the slice
3158// in slice to string conversions.
3159
3160Expression*
3161Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3162 Statement_inserter* inserter)
3163{
7035307e
CM
3164 if (((this->type()->is_string_type()
3165 && this->expr_->type()->is_slice_type())
3166 || (this->type()->interface_type() != NULL
3167 && this->expr_->type()->interface_type() != NULL))
6ddb6288
ILT
3168 && !this->expr_->is_variable())
3169 {
3170 Temporary_statement* temp =
3171 Statement::make_temporary(NULL, this->expr_, this->location());
3172 inserter->insert(temp);
3173 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3174 }
3175 return this;
3176}
3177
e7d9342c
ILT
3178// Return whether a type conversion is a constant.
3179
3180bool
3181Type_conversion_expression::do_is_constant() const
3182{
3183 if (!this->expr_->is_constant())
3184 return false;
3185
3186 // A conversion to a type that may not be used as a constant is not
3187 // a constant. For example, []byte(nil).
3188 Type* type = this->type_;
3189 if (type->integer_type() == NULL
3190 && type->float_type() == NULL
3191 && type->complex_type() == NULL
3192 && !type->is_boolean_type()
3193 && !type->is_string_type())
3194 return false;
3195
3196 return true;
3197}
3198
39be2171
ILT
3199// Return whether a type conversion is immutable.
3200
3201bool
3202Type_conversion_expression::do_is_immutable() const
3203{
3204 Type* type = this->type_;
3205 Type* expr_type = this->expr_->type();
3206
3207 if (type->interface_type() != NULL
3208 || expr_type->interface_type() != NULL)
3209 return false;
3210
3211 if (!this->expr_->is_immutable())
3212 return false;
3213
3214 if (Type::are_identical(type, expr_type, false, NULL))
3215 return true;
3216
3217 return type->is_basic_type() && expr_type->is_basic_type();
3218}
3219
5caf63ca 3220// Return the constant numeric value if there is one.
7a938933
ILT
3221
3222bool
5caf63ca
ILT
3223Type_conversion_expression::do_numeric_constant_value(
3224 Numeric_constant* nc) const
7a938933 3225{
5caf63ca 3226 if (!this->type_->is_numeric_type())
7a938933 3227 return false;
5caf63ca 3228 if (!this->expr_->numeric_constant_value(nc))
7a938933 3229 return false;
5caf63ca 3230 return nc->set_type(this->type_, false, this->location());
7a938933
ILT
3231}
3232
3233// Return the constant string value if there is one.
3234
3235bool
3236Type_conversion_expression::do_string_constant_value(std::string* val) const
3237{
3238 if (this->type_->is_string_type()
3239 && this->expr_->type()->integer_type() != NULL)
3240 {
5caf63ca
ILT
3241 Numeric_constant nc;
3242 if (this->expr_->numeric_constant_value(&nc))
7a938933 3243 {
5caf63ca
ILT
3244 unsigned long ival;
3245 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
7a938933 3246 {
5caf63ca
ILT
3247 val->clear();
3248 Lex::append_char(ival, true, val, this->location());
7a938933
ILT
3249 return true;
3250 }
3251 }
7a938933
ILT
3252 }
3253
3254 // FIXME: Could handle conversion from const []int here.
3255
3256 return false;
3257}
3258
3259// Check that types are convertible.
3260
3261void
3262Type_conversion_expression::do_check_types(Gogo*)
3263{
3264 Type* type = this->type_;
3265 Type* expr_type = this->expr_->type();
3266 std::string reason;
3267
02ed921a 3268 if (type->is_error() || expr_type->is_error())
ecdacbb3 3269 {
ecdacbb3
ILT
3270 this->set_is_error();
3271 return;
3272 }
3273
7a938933
ILT
3274 if (this->may_convert_function_types_
3275 && type->function_type() != NULL
3276 && expr_type->function_type() != NULL)
3277 return;
3278
3279 if (Type::are_convertible(type, expr_type, &reason))
3280 return;
3281
3282 error_at(this->location(), "%s", reason.c_str());
3283 this->set_is_error();
3284}
3285
3286// Get a tree for a type conversion.
3287
3288tree
3289Type_conversion_expression::do_get_tree(Translate_context* context)
3290{
7a938933
ILT
3291 Type* type = this->type_;
3292 Type* expr_type = this->expr_->type();
7035307e
CM
3293
3294 Gogo* gogo = context->gogo();
3295 Btype* btype = type->get_backend(gogo);
3296 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3297 Location loc = this->location();
3298
3299 if (Type::are_identical(type, expr_type, false, NULL))
7a938933 3300 {
7035307e
CM
3301 Bexpression* bconvert =
3302 gogo->backend()->convert_expression(btype, bexpr, loc);
3303 return expr_to_tree(bconvert);
7a938933 3304 }
7035307e
CM
3305 else if (type->interface_type() != NULL
3306 || expr_type->interface_type() != NULL)
7a938933 3307 {
7035307e
CM
3308 Expression* conversion =
3309 Expression::convert_for_assignment(gogo, type, this->expr_,
3310 this->location());
3311 return conversion->get_tree(context);
7a938933
ILT
3312 }
3313 else if (type->is_string_type()
3314 && expr_type->integer_type() != NULL)
3315 {
7035307e
CM
3316 mpz_t intval;
3317 Numeric_constant nc;
3318 if (this->expr_->numeric_constant_value(&nc)
3319 && nc.to_int(&intval)
3320 && mpz_fits_ushort_p(intval))
7a938933 3321 {
7a938933 3322 std::string s;
7035307e
CM
3323 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3324 mpz_clear(intval);
3325 Expression* se = Expression::make_string(s, loc);
7a938933
ILT
3326 return se->get_tree(context);
3327 }
3328
7d6c5039 3329 Expression* i2s_expr =
7035307e
CM
3330 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3331 return Expression::make_cast(type, i2s_expr, loc)->get_tree(context);
7a938933 3332 }
863ea6cf 3333 else if (type->is_string_type() && expr_type->is_slice_type())
7a938933 3334 {
863ea6cf 3335 Array_type* a = expr_type->array_type();
7a938933 3336 Type* e = a->element_type()->forwarded();
26409c52 3337 go_assert(e->integer_type() != NULL);
6ddb6288
ILT
3338 go_assert(this->expr_->is_variable());
3339
3340 Runtime::Function code;
7b31a84d 3341 if (e->integer_type()->is_byte())
6ddb6288 3342 code = Runtime::BYTE_ARRAY_TO_STRING;
7a938933 3343 else
6ddb6288
ILT
3344 {
3345 go_assert(e->integer_type()->is_rune());
3346 code = Runtime::INT_ARRAY_TO_STRING;
3347 }
3348 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3349 Expression* len = a->get_length(gogo, this->expr_);
7035307e 3350 return Runtime::make_call(code, loc, 2, valptr, len)->get_tree(context);
7a938933 3351 }
b7190f2f 3352 else if (type->is_slice_type() && expr_type->is_string_type())
7a938933
ILT
3353 {
3354 Type* e = type->array_type()->element_type()->forwarded();
26409c52 3355 go_assert(e->integer_type() != NULL);
a81eaeed 3356
7035307e 3357 Runtime::Function code;
7b31a84d 3358 if (e->integer_type()->is_byte())
7035307e 3359 code = Runtime::STRING_TO_BYTE_ARRAY;
7a938933
ILT
3360 else
3361 {
7b31a84d 3362 go_assert(e->integer_type()->is_rune());
7035307e 3363 code = Runtime::STRING_TO_INT_ARRAY;
7a938933 3364 }
7035307e
CM
3365 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3366 return Expression::make_unsafe_cast(type, s2a, loc)->get_tree(context);
3367 }
3368 else if (type->is_numeric_type())
3369 {
3370 go_assert(Type::are_convertible(type, expr_type, NULL));
3371 Bexpression* bconvert =
3372 gogo->backend()->convert_expression(btype, bexpr, loc);
3373 return expr_to_tree(bconvert);
7a938933
ILT
3374 }
3375 else if ((type->is_unsafe_pointer_type()
7035307e
CM
3376 && (expr_type->points_to() != NULL
3377 || expr_type->integer_type()))
3378 || (expr_type->is_unsafe_pointer_type()
3379 && type->points_to() != NULL)
3380 || (this->may_convert_function_types_
3381 && type->function_type() != NULL
3382 && expr_type->function_type() != NULL))
3383 {
3384 Bexpression* bconvert =
3385 gogo->backend()->convert_expression(btype, bexpr, loc);
3386 return expr_to_tree(bconvert);
3387 }
7a938933 3388 else
7035307e
CM
3389 {
3390 Expression* conversion =
3391 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3392 return conversion->get_tree(context);
3393 }
7a938933
ILT
3394}
3395
3396// Output a type conversion in a constant expression.
3397
3398void
3399Type_conversion_expression::do_export(Export* exp) const
3400{
3401 exp->write_c_string("convert(");
3402 exp->write_type(this->type_);
3403 exp->write_c_string(", ");
3404 this->expr_->export_expression(exp);
3405 exp->write_c_string(")");
3406}
3407
3408// Import a type conversion or a struct construction.
3409
3410Expression*
3411Type_conversion_expression::do_import(Import* imp)
3412{
3413 imp->require_c_string("convert(");
3414 Type* type = imp->read_type();
3415 imp->require_c_string(", ");
3416 Expression* val = Expression::import_expression(imp);
3417 imp->require_c_string(")");
3418 return Expression::make_cast(type, val, imp->location());
3419}
3420
16c57fe2
RL
3421// Dump ast representation for a type conversion expression.
3422
3423void
3424Type_conversion_expression::do_dump_expression(
3425 Ast_dump_context* ast_dump_context) const
3426{
3427 ast_dump_context->dump_type(this->type_);
3428 ast_dump_context->ostream() << "(";
3429 ast_dump_context->dump_expression(this->expr_);
3430 ast_dump_context->ostream() << ") ";
3431}
3432
7a938933
ILT
3433// Make a type cast expression.
3434
3435Expression*
8afa2bfb 3436Expression::make_cast(Type* type, Expression* val, Location location)
7a938933
ILT
3437{
3438 if (type->is_error_type() || val->is_error_expression())
3439 return Expression::make_error(location);
3440 return new Type_conversion_expression(type, val, location);
3441}
3442
b39c10b8
ILT
3443// An unsafe type conversion, used to pass values to builtin functions.
3444
3445class Unsafe_type_conversion_expression : public Expression
3446{
3447 public:
3448 Unsafe_type_conversion_expression(Type* type, Expression* expr,
8afa2bfb 3449 Location location)
b39c10b8
ILT
3450 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3451 type_(type), expr_(expr)
3452 { }
3453
3454 protected:
3455 int
3456 do_traverse(Traverse* traverse);
3457
3458 Type*
3459 do_type()
3460 { return this->type_; }
3461
3462 void
3463 do_determine_type(const Type_context*)
3b8dffe7 3464 { this->expr_->determine_type_no_context(); }
b39c10b8
ILT
3465
3466 Expression*
3467 do_copy()
3468 {
3469 return new Unsafe_type_conversion_expression(this->type_,
3470 this->expr_->copy(),
3471 this->location());
3472 }
3473
3474 tree
3475 do_get_tree(Translate_context*);
3476
16c57fe2
RL
3477 void
3478 do_dump_expression(Ast_dump_context*) const;
3479
b39c10b8
ILT
3480 private:
3481 // The type to convert to.
3482 Type* type_;
3483 // The expression to convert.
3484 Expression* expr_;
3485};
3486
3487// Traversal.
3488
3489int
3490Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3491{
3492 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3493 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3494 return TRAVERSE_EXIT;
3495 return TRAVERSE_CONTINUE;
3496}
3497
3498// Convert to backend representation.
3499
3500tree
3501Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3502{
3503 // We are only called for a limited number of cases.
3504
3505 Type* t = this->type_;
3506 Type* et = this->expr_->type();
7035307e
CM
3507 if (t->array_type() != NULL)
3508 go_assert(et->array_type() != NULL
3509 && t->is_slice_type() == et->is_slice_type());
3510 else if (t->struct_type() != NULL)
b39c10b8 3511 {
7035307e
CM
3512 if (t->named_type() != NULL
3513 && et->named_type() != NULL
3514 && !Type::are_convertible(t, et, NULL))
3515 {
3516 go_assert(saw_errors());
3517 return error_mark_node;
3518 }
3519
3520 go_assert(et->struct_type() != NULL
3521 && Type::are_convertible(t, et, NULL));
3522 }
3523 else if (t->map_type() != NULL)
26409c52 3524 go_assert(et->map_type() != NULL);
b39c10b8 3525 else if (t->channel_type() != NULL)
26409c52 3526 go_assert(et->channel_type() != NULL);
1bbf7edb 3527 else if (t->points_to() != NULL)
7035307e
CM
3528 go_assert(et->points_to() != NULL
3529 || et->channel_type() != NULL
3530 || et->map_type() != NULL
3531 || et->function_type() != NULL
3532 || et->is_nil_type());
b39c10b8 3533 else if (et->is_unsafe_pointer_type())
26409c52 3534 go_assert(t->points_to() != NULL);
7035307e 3535 else if (t->interface_type() != NULL)
b39c10b8 3536 {
7035307e 3537 bool empty_iface = t->interface_type()->is_empty();
26409c52 3538 go_assert(et->interface_type() != NULL
7035307e 3539 && et->interface_type()->is_empty() == empty_iface);
b39c10b8 3540 }
a6de01a6 3541 else if (t->integer_type() != NULL)
7035307e
CM
3542 go_assert(et->is_boolean_type()
3543 || et->integer_type() != NULL
3544 || et->function_type() != NULL
3545 || et->points_to() != NULL
3546 || et->map_type() != NULL
3547 || et->channel_type() != NULL);
b39c10b8 3548 else
8c0d1865 3549 go_unreachable();
b39c10b8 3550
7035307e
CM
3551 Gogo* gogo = context->gogo();
3552 Btype* btype = t->get_backend(gogo);
3553 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3554 Location loc = this->location();
3555 Bexpression* ret =
3556 gogo->backend()->convert_expression(btype, bexpr, loc);
3557 return expr_to_tree(ret);
b39c10b8
ILT
3558}
3559
16c57fe2
RL
3560// Dump ast representation for an unsafe type conversion expression.
3561
3562void
3563Unsafe_type_conversion_expression::do_dump_expression(
3564 Ast_dump_context* ast_dump_context) const
3565{
3566 ast_dump_context->dump_type(this->type_);
3567 ast_dump_context->ostream() << "(";
3568 ast_dump_context->dump_expression(this->expr_);
3569 ast_dump_context->ostream() << ") ";
3570}
3571
b39c10b8
ILT
3572// Make an unsafe type conversion expression.
3573
3574Expression*
3575Expression::make_unsafe_cast(Type* type, Expression* expr,
8afa2bfb 3576 Location location)
b39c10b8
ILT
3577{
3578 return new Unsafe_type_conversion_expression(type, expr, location);
3579}
3580
036165d8 3581// Class Unary_expression.
7a938933
ILT
3582
3583// If we are taking the address of a composite literal, and the
7035307e 3584// contents are not constant, then we want to make a heap expression
7a938933
ILT
3585// instead.
3586
3587Expression*
8586635c 3588Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
7a938933 3589{
8afa2bfb 3590 Location loc = this->location();
7a938933
ILT
3591 Operator op = this->op_;
3592 Expression* expr = this->expr_;
3593
3594 if (op == OPERATOR_MULT && expr->is_type_expression())
3595 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3596
3597 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3598 // moving x to the heap. FIXME: Is it worth doing a real escape
3599 // analysis here? This case is found in math/unsafe.go and is
3600 // therefore worth special casing.
3601 if (op == OPERATOR_MULT)
3602 {
3603 Expression* e = expr;
3604 while (e->classification() == EXPRESSION_CONVERSION)
3605 {
3606 Type_conversion_expression* te
3607 = static_cast<Type_conversion_expression*>(e);
3608 e = te->expr();
3609 }
3610
3611 if (e->classification() == EXPRESSION_UNARY)
3612 {
3613 Unary_expression* ue = static_cast<Unary_expression*>(e);
3614 if (ue->op_ == OPERATOR_AND)
3615 {
3616 if (e == expr)
3617 {
3618 // *&x == x.
7f5e8188
ILT
3619 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3620 {
3621 error_at(ue->location(),
3622 "invalid operand for unary %<&%>");
3623 this->set_is_error();
3624 }
7a938933
ILT
3625 return ue->expr_;
3626 }
3627 ue->set_does_not_escape();
3628 }
3629 }
3630 }
3631
15ea09a0
ILT
3632 // Catching an invalid indirection of unsafe.Pointer here avoid
3633 // having to deal with TYPE_VOID in other places.
3634 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3635 {
3636 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3637 return Expression::make_error(this->location());
3638 }
3639
c414667b 3640 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
7a938933 3641 {
5caf63ca
ILT
3642 Numeric_constant nc;
3643 if (expr->numeric_constant_value(&nc))
7a938933 3644 {
5caf63ca
ILT
3645 Numeric_constant result;
3646 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3647 return result.expression(loc);
7a938933
ILT
3648 }
3649 }
3650
3651 return this;
3652}
3653
8a35e18d
CM
3654// Flatten expression if a nil check must be performed and create temporary
3655// variables if necessary.
3656
3657Expression*
3658Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3659 Statement_inserter* inserter)
3660{
7f5e8188
ILT
3661 if (this->is_error_expression() || this->expr_->is_error_expression())
3662 return Expression::make_error(this->location());
3663
8a35e18d
CM
3664 Location location = this->location();
3665 if (this->op_ == OPERATOR_MULT
3666 && !this->expr_->is_variable())
3667 {
3668 go_assert(this->expr_->type()->points_to() != NULL);
3669 Type* ptype = this->expr_->type()->points_to();
3670 if (!ptype->is_void_type())
3671 {
3672 Btype* pbtype = ptype->get_backend(gogo);
3673 size_t s = gogo->backend()->type_size(pbtype);
3674 if (s >= 4096 || this->issue_nil_check_)
3675 {
3676 Temporary_statement* temp =
3677 Statement::make_temporary(NULL, this->expr_, location);
3678 inserter->insert(temp);
3679 this->expr_ =
3680 Expression::make_temporary_reference(temp, location);
3681 }
3682 }
3683 }
3684
3685 if (this->create_temp_ && !this->expr_->is_variable())
3686 {
3687 Temporary_statement* temp =
3688 Statement::make_temporary(NULL, this->expr_, location);
3689 inserter->insert(temp);
3690 this->expr_ = Expression::make_temporary_reference(temp, location);
3691 }
3692
3693 return this;
3694}
3695
7a938933
ILT
3696// Return whether a unary expression is a constant.
3697
3698bool
3699Unary_expression::do_is_constant() const
3700{
3701 if (this->op_ == OPERATOR_MULT)
3702 {
3703 // Indirecting through a pointer is only constant if the object
3704 // to which the expression points is constant, but we currently
3705 // have no way to determine that.
3706 return false;
3707 }
3708 else if (this->op_ == OPERATOR_AND)
3709 {
3710 // Taking the address of a variable is constant if it is a
8a35e18d
CM
3711 // global variable, not constant otherwise. In other cases taking the
3712 // address is probably not a constant.
7a938933
ILT
3713 Var_expression* ve = this->expr_->var_expression();
3714 if (ve != NULL)
3715 {
3716 Named_object* no = ve->named_object();
3717 return no->is_variable() && no->var_value()->is_global();
3718 }
3719 return false;
3720 }
3721 else
3722 return this->expr_->is_constant();
3723}
3724
5caf63ca
ILT
3725// Apply unary opcode OP to UNC, setting NC. Return true if this
3726// could be done, false if not. Issue errors for overflow.
7a938933
ILT
3727
3728bool
5caf63ca
ILT
3729Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3730 Location location, Numeric_constant* nc)
7a938933
ILT
3731{
3732 switch (op)
3733 {
3734 case OPERATOR_PLUS:
5caf63ca 3735 *nc = *unc;
7a938933 3736 return true;
5caf63ca 3737
7a938933 3738 case OPERATOR_MINUS:
5caf63ca
ILT
3739 if (unc->is_int() || unc->is_rune())
3740 break;
3741 else if (unc->is_float())
3742 {
3743 mpfr_t uval;
3744 unc->get_float(&uval);
3745 mpfr_t val;
3746 mpfr_init(val);
3747 mpfr_neg(val, uval, GMP_RNDN);
3748 nc->set_float(unc->type(), val);
3749 mpfr_clear(uval);
3750 mpfr_clear(val);
3751 return true;
3752 }
3753 else if (unc->is_complex())
3754 {
3755 mpfr_t ureal, uimag;
3756 unc->get_complex(&ureal, &uimag);
3757 mpfr_t real, imag;
3758 mpfr_init(real);
3759 mpfr_init(imag);
3760 mpfr_neg(real, ureal, GMP_RNDN);
3761 mpfr_neg(imag, uimag, GMP_RNDN);
3762 nc->set_complex(unc->type(), real, imag);
3763 mpfr_clear(ureal);
3764 mpfr_clear(uimag);
3765 mpfr_clear(real);
3766 mpfr_clear(imag);
3767 return true;
3768 }
7a938933 3769 else
5caf63ca 3770 go_unreachable();
7a938933 3771
5caf63ca
ILT
3772 case OPERATOR_XOR:
3773 break;
fc24bee9 3774
c414667b 3775 case OPERATOR_NOT:
7a938933
ILT
3776 case OPERATOR_AND:
3777 case OPERATOR_MULT:
3778 return false;
5caf63ca 3779
7a938933 3780 default:
8c0d1865 3781 go_unreachable();
7a938933 3782 }
7a938933 3783
5caf63ca
ILT
3784 if (!unc->is_int() && !unc->is_rune())
3785 return false;
3786
3787 mpz_t uval;
ca30ba74
ILT
3788 if (unc->is_rune())
3789 unc->get_rune(&uval);
3790 else
3791 unc->get_int(&uval);
5caf63ca
ILT
3792 mpz_t val;
3793 mpz_init(val);
7a938933 3794
7a938933
ILT
3795 switch (op)
3796 {
7a938933 3797 case OPERATOR_MINUS:
5caf63ca
ILT
3798 mpz_neg(val, uval);
3799 break;
3800
7a938933 3801 case OPERATOR_NOT:
5caf63ca
ILT
3802 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3803 break;
3804
7a938933 3805 case OPERATOR_XOR:
5caf63ca
ILT
3806 {
3807 Type* utype = unc->type();
3808 if (utype->integer_type() == NULL
3809 || utype->integer_type()->is_abstract())
3810 mpz_com(val, uval);
3811 else
3812 {
3813 // The number of HOST_WIDE_INTs that it takes to represent
3814 // UVAL.
3815 size_t count = ((mpz_sizeinbase(uval, 2)
3816 + HOST_BITS_PER_WIDE_INT
3817 - 1)
3818 / HOST_BITS_PER_WIDE_INT);
7a938933 3819
5caf63ca
ILT
3820 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3821 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3822
3823 size_t obits = utype->integer_type()->bits();
3824
3825 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3826 {
3827 mpz_t adj;
3828 mpz_init_set_ui(adj, 1);
3829 mpz_mul_2exp(adj, adj, obits);
3830 mpz_add(uval, uval, adj);
3831 mpz_clear(adj);
3832 }
3833
3834 size_t ecount;
3835 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3836 go_assert(ecount <= count);
3837
3838 // Trim down to the number of words required by the type.
3839 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3840 / HOST_BITS_PER_WIDE_INT);
3841 go_assert(ocount <= count);
3842
3843 for (size_t i = 0; i < ocount; ++i)
3844 phwi[i] = ~phwi[i];
3845
3846 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3847 if (clearbits != 0)
3848 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3849 >> clearbits);
3850
3851 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3852
3853 if (!utype->integer_type()->is_unsigned()
3854 && mpz_tstbit(val, obits - 1))
3855 {
3856 mpz_t adj;
3857 mpz_init_set_ui(adj, 1);
3858 mpz_mul_2exp(adj, adj, obits);
3859 mpz_sub(val, val, adj);
3860 mpz_clear(adj);
3861 }
3862
3863 delete[] phwi;
3864 }
3865 }
3866 break;
7a938933 3867
7a938933 3868 default:
8c0d1865 3869 go_unreachable();
7a938933 3870 }
7a938933 3871
5caf63ca
ILT
3872 if (unc->is_rune())
3873 nc->set_rune(NULL, val);
7a938933 3874 else
5caf63ca 3875 nc->set_int(NULL, val);
7a938933 3876
5caf63ca
ILT
3877 mpz_clear(uval);
3878 mpz_clear(val);
7a938933 3879
5caf63ca 3880 return nc->set_type(unc->type(), true, location);
7a938933
ILT
3881}
3882
5caf63ca 3883// Return the integral constant value of a unary expression, if it has one.
7a938933
ILT
3884
3885bool
5caf63ca 3886Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
7a938933 3887{
5caf63ca
ILT
3888 Numeric_constant unc;
3889 if (!this->expr_->numeric_constant_value(&unc))
3890 return false;
3891 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3892 nc);
7a938933
ILT
3893}
3894
3895// Return the type of a unary expression.
3896
3897Type*
3898Unary_expression::do_type()
3899{
3900 switch (this->op_)
3901 {
3902 case OPERATOR_PLUS:
3903 case OPERATOR_MINUS:
3904 case OPERATOR_NOT:
3905 case OPERATOR_XOR:
3906 return this->expr_->type();
3907
3908 case OPERATOR_AND:
3909 return Type::make_pointer_type(this->expr_->type());
3910
3911 case OPERATOR_MULT:
3912 {
3913 Type* subtype = this->expr_->type();
3914 Type* points_to = subtype->points_to();
3915 if (points_to == NULL)
3916 return Type::make_error_type();
3917 return points_to;
3918 }
3919
3920 default:
8c0d1865 3921 go_unreachable();
7a938933
ILT
3922 }
3923}
3924
3925// Determine abstract types for a unary expression.
3926
3927void
3928Unary_expression::do_determine_type(const Type_context* context)
3929{
3930 switch (this->op_)
3931 {
3932 case OPERATOR_PLUS:
3933 case OPERATOR_MINUS:
3934 case OPERATOR_NOT:
3935 case OPERATOR_XOR:
3936 this->expr_->determine_type(context);
3937 break;
3938
3939 case OPERATOR_AND:
3940 // Taking the address of something.
3941 {
3942 Type* subtype = (context->type == NULL
3943 ? NULL
3944 : context->type->points_to());
3945 Type_context subcontext(subtype, false);
3946 this->expr_->determine_type(&subcontext);
3947 }
3948 break;
3949
3950 case OPERATOR_MULT:
3951 // Indirecting through a pointer.
3952 {
3953 Type* subtype = (context->type == NULL
3954 ? NULL
3955 : Type::make_pointer_type(context->type));
3956 Type_context subcontext(subtype, false);
3957 this->expr_->determine_type(&subcontext);
3958 }
3959 break;
3960
3961 default:
8c0d1865 3962 go_unreachable();
7a938933
ILT
3963 }
3964}
3965
3966// Check types for a unary expression.
3967
3968void
3969Unary_expression::do_check_types(Gogo*)
3970{
173fb2ff 3971 Type* type = this->expr_->type();
02ed921a 3972 if (type->is_error())
173fb2ff
ILT
3973 {
3974 this->set_is_error();
3975 return;
3976 }
3977
7a938933
ILT
3978 switch (this->op_)
3979 {
3980 case OPERATOR_PLUS:
3981 case OPERATOR_MINUS:
173fb2ff
ILT
3982 if (type->integer_type() == NULL
3983 && type->float_type() == NULL
3984 && type->complex_type() == NULL)
3985 this->report_error(_("expected numeric type"));
7a938933
ILT
3986 break;
3987
3988 case OPERATOR_NOT:
c414667b
ILT
3989 if (!type->is_boolean_type())
3990 this->report_error(_("expected boolean type"));
3991 break;
3992
7a938933 3993 case OPERATOR_XOR:
173fb2ff
ILT
3994 if (type->integer_type() == NULL
3995 && !type->is_boolean_type())
3996 this->report_error(_("expected integer or boolean type"));
7a938933
ILT
3997 break;
3998
3999 case OPERATOR_AND:
4000 if (!this->expr_->is_addressable())
1bbf7edb
ILT
4001 {
4002 if (!this->create_temp_)
7f5e8188
ILT
4003 {
4004 error_at(this->location(), "invalid operand for unary %<&%>");
4005 this->set_is_error();
4006 }
1bbf7edb 4007 }
7a938933 4008 else
64c7b4c0
ILT
4009 {
4010 this->expr_->address_taken(this->escapes_);
4011 this->expr_->issue_nil_check();
4012 }
7a938933
ILT
4013 break;
4014
4015 case OPERATOR_MULT:
4016 // Indirecting through a pointer.
173fb2ff
ILT
4017 if (type->points_to() == NULL)
4018 this->report_error(_("expected pointer"));
7a938933
ILT
4019 break;
4020
4021 default:
8c0d1865 4022 go_unreachable();
7a938933
ILT
4023 }
4024}
4025
4026// Get a tree for a unary expression.
4027
4028tree
4029Unary_expression::do_get_tree(Translate_context* context)
4030{
776f27a6 4031 Gogo* gogo = context->gogo();
f9f96987
ILT
4032 Location loc = this->location();
4033
4034 // Taking the address of a set-and-use-temporary expression requires
4035 // setting the temporary and then taking the address.
4036 if (this->op_ == OPERATOR_AND)
4037 {
4038 Set_and_use_temporary_expression* sut =
4039 this->expr_->set_and_use_temporary_expression();
4040 if (sut != NULL)
4041 {
4042 Temporary_statement* temp = sut->temporary();
4043 Bvariable* bvar = temp->get_backend_variable(context);
8a35e18d
CM
4044 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4045
4046 Expression* val = sut->expression();
4047 Bexpression* bval = tree_to_expr(val->get_tree(context));
4048
4049 Bstatement* bassign =
4050 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4051 Bexpression* bvar_addr =
4052 gogo->backend()->address_expression(bvar_expr, loc);
4053 Bexpression* ret =
4054 gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4055 return expr_to_tree(ret);
f9f96987
ILT
4056 }
4057 }
4058
8a35e18d 4059 Bexpression* ret;
7a938933 4060 tree expr = this->expr_->get_tree(context);
8a35e18d
CM
4061 Bexpression* bexpr = tree_to_expr(expr);
4062 Btype* btype = this->expr_->type()->get_backend(gogo);
7a938933
ILT
4063 switch (this->op_)
4064 {
4065 case OPERATOR_PLUS:
8a35e18d
CM
4066 ret = bexpr;
4067 break;
7a938933
ILT
4068
4069 case OPERATOR_MINUS:
8a35e18d
CM
4070 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4071 ret = gogo->backend()->convert_expression(btype, ret, loc);
4072 break;
7a938933
ILT
4073
4074 case OPERATOR_NOT:
7a938933 4075 case OPERATOR_XOR:
8a35e18d
CM
4076 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4077 break;
7a938933
ILT
4078
4079 case OPERATOR_AND:
1bbf7edb
ILT
4080 if (!this->create_temp_)
4081 {
4082 // We should not see a non-constant constructor here; cases
4083 // where we would see one should have been moved onto the
4084 // heap at parse time. Taking the address of a nonconstant
4085 // constructor will not do what the programmer expects.
8a35e18d
CM
4086
4087 go_assert(!this->expr_->is_composite_literal()
4088 || this->expr_->is_immutable());
3700e947
ILT
4089 if (this->expr_->classification() == EXPRESSION_UNARY)
4090 {
4091 Unary_expression* ue =
4092 static_cast<Unary_expression*>(this->expr_);
4093 go_assert(ue->op() != OPERATOR_AND);
4094 }
1bbf7edb 4095 }
7a938933 4096
036165d8
CM
4097 if (this->is_gc_root_)
4098 {
4099 // Build a decl for a GC root variable. GC roots are mutable, so they
4100 // cannot be represented as an immutable_struct in the backend.
4101 Bvariable* gc_root = gogo->backend()->gc_root_variable(btype, bexpr);
4102 bexpr = gogo->backend()->var_expression(gc_root, loc);
4103 }
4104 else if ((this->expr_->is_composite_literal()
8a35e18d
CM
4105 || this->expr_->string_expression() != NULL)
4106 && this->expr_->is_immutable())
4107 {
036165d8 4108 // Build a decl for a constant constructor.
8a35e18d
CM
4109 static unsigned int counter;
4110 char buf[100];
4111 snprintf(buf, sizeof buf, "C%u", counter);
4112 ++counter;
4113
4114 Bvariable* decl =
4115 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4116 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4117 btype, loc, bexpr);
4118 bexpr = gogo->backend()->var_expression(decl, loc);
4119 }
1bbf7edb 4120
8a35e18d
CM
4121 go_assert(!this->create_temp_ || this->expr_->is_variable());
4122 ret = gogo->backend()->address_expression(bexpr, loc);
4123 break;
7a938933
ILT
4124
4125 case OPERATOR_MULT:
4126 {
8a35e18d 4127 go_assert(this->expr_->type()->points_to() != NULL);
7a938933
ILT
4128
4129 // If we are dereferencing the pointer to a large struct, we
4130 // need to check for nil. We don't bother to check for small
4131 // structs because we expect the system to crash on a nil
64c7b4c0
ILT
4132 // pointer dereference. However, if we know the address of this
4133 // expression is being taken, we must always check for nil.
8a35e18d
CM
4134
4135 Type* ptype = this->expr_->type()->points_to();
4136 Btype* pbtype = ptype->get_backend(gogo);
4137 if (!ptype->is_void_type())
7a938933 4138 {
8a35e18d
CM
4139 size_t s = gogo->backend()->type_size(pbtype);
4140 if (s >= 4096 || this->issue_nil_check_)
bedcedc1 4141 {
8a35e18d
CM
4142 go_assert(this->expr_->is_variable());
4143
4144 Expression* nil_expr = Expression::make_nil(loc);
4145 Bexpression* nil = tree_to_expr(nil_expr->get_tree(context));
4146 Bexpression* compare =
4147 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4148 nil, loc);
4149
5aac5cb2
ILT
4150 Expression* crash_expr =
4151 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
8a35e18d
CM
4152 Bexpression* crash =
4153 tree_to_expr(crash_expr->get_tree(context));
4154 bexpr = gogo->backend()->conditional_expression(btype, compare,
4155 crash, bexpr,
4156 loc);
4157
bedcedc1 4158 }
7a938933
ILT
4159 }
4160
4161 // If the type of EXPR is a recursive pointer type, then we
4162 // need to insert a cast before indirecting.
8a35e18d
CM
4163 tree expr = expr_to_tree(bexpr);
4164 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4165 if (VOID_TYPE_P(target_type_tree))
4166 {
4167 tree ind = type_to_tree(pbtype);
4168 expr = fold_convert_loc(loc.gcc_location(),
8afa2bfb 4169 build_pointer_type(ind), expr);
8a35e18d
CM
4170 bexpr = tree_to_expr(expr);
4171 }
7a938933 4172
8a35e18d 4173 ret = gogo->backend()->indirect_expression(bexpr, false, loc);
7a938933 4174 }
8a35e18d 4175 break;
7a938933
ILT
4176
4177 default:
8c0d1865 4178 go_unreachable();
7a938933 4179 }
8a35e18d
CM
4180
4181 return expr_to_tree(ret);
7a938933
ILT
4182}
4183
4184// Export a unary expression.
4185
4186void
4187Unary_expression::do_export(Export* exp) const
4188{
4189 switch (this->op_)
4190 {
4191 case OPERATOR_PLUS:
4192 exp->write_c_string("+ ");
4193 break;
4194 case OPERATOR_MINUS:
4195 exp->write_c_string("- ");
4196 break;
4197 case OPERATOR_NOT:
4198 exp->write_c_string("! ");
4199 break;
4200 case OPERATOR_XOR:
4201 exp->write_c_string("^ ");
4202 break;
4203 case OPERATOR_AND:
4204 case OPERATOR_MULT:
4205 default:
8c0d1865 4206 go_unreachable();
7a938933
ILT
4207 }
4208 this->expr_->export_expression(exp);
4209}
4210
4211// Import a unary expression.
4212
4213Expression*
4214Unary_expression::do_import(Import* imp)
4215{
4216 Operator op;
4217 switch (imp->get_char())
4218 {
4219 case '+':
4220 op = OPERATOR_PLUS;
4221 break;
4222 case '-':
4223 op = OPERATOR_MINUS;
4224 break;
4225 case '!':
4226 op = OPERATOR_NOT;
4227 break;
4228 case '^':
4229 op = OPERATOR_XOR;
4230 break;
4231 default:
8c0d1865 4232 go_unreachable();
7a938933
ILT
4233 }
4234 imp->require_c_string(" ");
4235 Expression* expr = Expression::import_expression(imp);
4236 return Expression::make_unary(op, expr, imp->location());
4237}
4238
16c57fe2
RL
4239// Dump ast representation of an unary expression.
4240
4241void
4242Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4243{
4244 ast_dump_context->dump_operator(this->op_);
4245 ast_dump_context->ostream() << "(";
4246 ast_dump_context->dump_expression(this->expr_);
4247 ast_dump_context->ostream() << ") ";
4248}
4249
7a938933
ILT
4250// Make a unary expression.
4251
4252Expression*
8afa2bfb 4253Expression::make_unary(Operator op, Expression* expr, Location location)
7a938933
ILT
4254{
4255 return new Unary_expression(op, expr, location);
4256}
4257
4258// If this is an indirection through a pointer, return the expression
4259// being pointed through. Otherwise return this.
4260
4261Expression*
4262Expression::deref()
4263{
4264 if (this->classification_ == EXPRESSION_UNARY)
4265 {
4266 Unary_expression* ue = static_cast<Unary_expression*>(this);
4267 if (ue->op() == OPERATOR_MULT)
4268 return ue->operand();
4269 }
4270 return this;
4271}
4272
4273// Class Binary_expression.
4274
4275// Traversal.
4276
4277int
4278Binary_expression::do_traverse(Traverse* traverse)
4279{
4280 int t = Expression::traverse(&this->left_, traverse);
4281 if (t == TRAVERSE_EXIT)
4282 return TRAVERSE_EXIT;
4283 return Expression::traverse(&this->right_, traverse);
4284}
4285
5caf63ca
ILT
4286// Return the type to use for a binary operation on operands of
4287// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4288// such may be NULL or abstract.
4289
4290bool
4291Binary_expression::operation_type(Operator op, Type* left_type,
4292 Type* right_type, Type** result_type)
4293{
4294 if (left_type != right_type
4295 && !left_type->is_abstract()
4296 && !right_type->is_abstract()
4297 && left_type->base() != right_type->base()
4298 && op != OPERATOR_LSHIFT
4299 && op != OPERATOR_RSHIFT)
4300 {
4301 // May be a type error--let it be diagnosed elsewhere.
4302 return false;
4303 }
4304
4305 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4306 {
4307 if (left_type->integer_type() != NULL)
4308 *result_type = left_type;
4309 else
4310 *result_type = Type::make_abstract_integer_type();
4311 }
4312 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4313 *result_type = left_type;
4314 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4315 *result_type = right_type;
4316 else if (!left_type->is_abstract())
4317 *result_type = left_type;
4318 else if (!right_type->is_abstract())
4319 *result_type = right_type;
4320 else if (left_type->complex_type() != NULL)
4321 *result_type = left_type;
4322 else if (right_type->complex_type() != NULL)
4323 *result_type = right_type;
4324 else if (left_type->float_type() != NULL)
4325 *result_type = left_type;
4326 else if (right_type->float_type() != NULL)
4327 *result_type = right_type;
4328 else if (left_type->integer_type() != NULL
4329 && left_type->integer_type()->is_rune())
4330 *result_type = left_type;
4331 else if (right_type->integer_type() != NULL
4332 && right_type->integer_type()->is_rune())
4333 *result_type = right_type;
4334 else
4335 *result_type = left_type;
4336
4337 return true;
4338}
4339
4340// Convert an integer comparison code and an operator to a boolean
4341// value.
7a938933
ILT
4342
4343bool
5caf63ca 4344Binary_expression::cmp_to_bool(Operator op, int cmp)
7a938933 4345{
7a938933
ILT
4346 switch (op)
4347 {
4348 case OPERATOR_EQEQ:
5caf63ca
ILT
4349 return cmp == 0;
4350 break;
7a938933 4351 case OPERATOR_NOTEQ:
5caf63ca
ILT
4352 return cmp != 0;
4353 break;
7a938933 4354 case OPERATOR_LT:
5caf63ca
ILT
4355 return cmp < 0;
4356 break;
7a938933 4357 case OPERATOR_LE:
5caf63ca 4358 return cmp <= 0;
7a938933 4359 case OPERATOR_GT:
5caf63ca 4360 return cmp > 0;
7a938933 4361 case OPERATOR_GE:
5caf63ca 4362 return cmp >= 0;
7a938933 4363 default:
8c0d1865 4364 go_unreachable();
7a938933
ILT
4365 }
4366}
4367
5caf63ca 4368// Compare constants according to OP.
7a938933
ILT
4369
4370bool
5caf63ca
ILT
4371Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4372 Numeric_constant* right_nc,
4373 Location location, bool* result)
7a938933 4374{
5caf63ca
ILT
4375 Type* left_type = left_nc->type();
4376 Type* right_type = right_nc->type();
4377
4378 Type* type;
4379 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4380 return false;
4381
4382 // When comparing an untyped operand to a typed operand, we are
4383 // effectively coercing the untyped operand to the other operand's
4384 // type, so make sure that is valid.
4385 if (!left_nc->set_type(type, true, location)
4386 || !right_nc->set_type(type, true, location))
4387 return false;
4388
4389 bool ret;
4390 int cmp;
4391 if (type->complex_type() != NULL)
4392 {
4393 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4394 return false;
4395 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4396 }
4397 else if (type->float_type() != NULL)
4398 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
7a938933 4399 else
5caf63ca
ILT
4400 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4401
4402 if (ret)
4403 *result = Binary_expression::cmp_to_bool(op, cmp);
4404
4405 return ret;
4406}
4407
4408// Compare integer constants.
4409
4410bool
4411Binary_expression::compare_integer(const Numeric_constant* left_nc,
4412 const Numeric_constant* right_nc,
4413 int* cmp)
4414{
4415 mpz_t left_val;
4416 if (!left_nc->to_int(&left_val))
4417 return false;
4418 mpz_t right_val;
4419 if (!right_nc->to_int(&right_val))
7a938933 4420 {
5caf63ca
ILT
4421 mpz_clear(left_val);
4422 return false;
7a938933 4423 }
5caf63ca
ILT
4424
4425 *cmp = mpz_cmp(left_val, right_val);
4426
4427 mpz_clear(left_val);
4428 mpz_clear(right_val);
4429
4430 return true;
4431}
4432
4433// Compare floating point constants.
4434
4435bool
4436Binary_expression::compare_float(const Numeric_constant* left_nc,
4437 const Numeric_constant* right_nc,
4438 int* cmp)
4439{
4440 mpfr_t left_val;
4441 if (!left_nc->to_float(&left_val))
4442 return false;
4443 mpfr_t right_val;
4444 if (!right_nc->to_float(&right_val))
7a938933 4445 {
5caf63ca
ILT
4446 mpfr_clear(left_val);
4447 return false;
4448 }
4449
4450 // We already coerced both operands to the same type. If that type
4451 // is not an abstract type, we need to round the values accordingly.
4452 Type* type = left_nc->type();
4453 if (!type->is_abstract() && type->float_type() != NULL)
4454 {
4455 int bits = type->float_type()->bits();
4456 mpfr_prec_round(left_val, bits, GMP_RNDN);
4457 mpfr_prec_round(right_val, bits, GMP_RNDN);
7a938933 4458 }
5caf63ca
ILT
4459
4460 *cmp = mpfr_cmp(left_val, right_val);
4461
4462 mpfr_clear(left_val);
4463 mpfr_clear(right_val);
4464
4465 return true;
7a938933
ILT
4466}
4467
5caf63ca
ILT
4468// Compare complex constants. Complex numbers may only be compared
4469// for equality.
7a938933
ILT
4470
4471bool
5caf63ca
ILT
4472Binary_expression::compare_complex(const Numeric_constant* left_nc,
4473 const Numeric_constant* right_nc,
4474 int* cmp)
7a938933 4475{
5caf63ca
ILT
4476 mpfr_t left_real, left_imag;
4477 if (!left_nc->to_complex(&left_real, &left_imag))
4478 return false;
4479 mpfr_t right_real, right_imag;
4480 if (!right_nc->to_complex(&right_real, &right_imag))
7a938933 4481 {
5caf63ca
ILT
4482 mpfr_clear(left_real);
4483 mpfr_clear(left_imag);
4484 return false;
7a938933 4485 }
5caf63ca
ILT
4486
4487 // We already coerced both operands to the same type. If that type
4488 // is not an abstract type, we need to round the values accordingly.
4489 Type* type = left_nc->type();
4490 if (!type->is_abstract() && type->complex_type() != NULL)
7a938933 4491 {
5caf63ca
ILT
4492 int bits = type->complex_type()->bits();
4493 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4494 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4495 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4496 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
7a938933 4497 }
5caf63ca
ILT
4498
4499 *cmp = (mpfr_cmp(left_real, right_real) != 0
4500 || mpfr_cmp(left_imag, right_imag) != 0);
4501
4502 mpfr_clear(left_real);
4503 mpfr_clear(left_imag);
4504 mpfr_clear(right_real);
4505 mpfr_clear(right_imag);
4506
4507 return true;
7a938933
ILT
4508}
4509
5caf63ca
ILT
4510// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4511// true if this could be done, false if not. Issue errors at LOCATION
4512// as appropriate.
7a938933
ILT
4513
4514bool
5caf63ca
ILT
4515Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4516 Numeric_constant* right_nc,
4517 Location location, Numeric_constant* nc)
7a938933 4518{
7a938933
ILT
4519 switch (op)
4520 {
4521 case OPERATOR_OROR:
4522 case OPERATOR_ANDAND:
4523 case OPERATOR_EQEQ:
4524 case OPERATOR_NOTEQ:
4525 case OPERATOR_LT:
4526 case OPERATOR_LE:
4527 case OPERATOR_GT:
4528 case OPERATOR_GE:
ea3ef06a
ILT
4529 // These return boolean values, not numeric.
4530 return false;
5caf63ca
ILT
4531 default:
4532 break;
4533 }
4534
4535 Type* left_type = left_nc->type();
4536 Type* right_type = right_nc->type();
4537
4538 Type* type;
4539 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4540 return false;
4541
4542 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4543
4544 // When combining an untyped operand with a typed operand, we are
4545 // effectively coercing the untyped operand to the other operand's
4546 // type, so make sure that is valid.
4547 if (!left_nc->set_type(type, true, location))
4548 return false;
4549 if (!is_shift && !right_nc->set_type(type, true, location))
4550 return false;
4551
4552 bool r;
4553 if (type->complex_type() != NULL)
4554 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4555 else if (type->float_type() != NULL)
4556 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4557 else
4558 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4559
4560 if (r)
4561 r = nc->set_type(type, true, location);
4562
4563 return r;
4564}
4565
4566// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4567// integer operations. Return true if this could be done, false if
4568// not.
4569
4570bool
4571Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4572 const Numeric_constant* right_nc,
4573 Location location, Numeric_constant* nc)
4574{
4575 mpz_t left_val;
4576 if (!left_nc->to_int(&left_val))
4577 return false;
4578 mpz_t right_val;
4579 if (!right_nc->to_int(&right_val))
4580 {
4581 mpz_clear(left_val);
7a938933 4582 return false;
5caf63ca
ILT
4583 }
4584
4585 mpz_t val;
4586 mpz_init(val);
4587
4588 switch (op)
4589 {
7a938933
ILT
4590 case OPERATOR_PLUS:
4591 mpz_add(val, left_val, right_val);
7035307e
CM
4592 if (mpz_sizeinbase(val, 2) > 0x100000)
4593 {
4594 error_at(location, "constant addition overflow");
4595 mpz_set_ui(val, 1);
4596 }
7a938933
ILT
4597 break;
4598 case OPERATOR_MINUS:
4599 mpz_sub(val, left_val, right_val);
7035307e
CM
4600 if (mpz_sizeinbase(val, 2) > 0x100000)
4601 {
4602 error_at(location, "constant subtraction overflow");
4603 mpz_set_ui(val, 1);
4604 }
7a938933
ILT
4605 break;
4606 case OPERATOR_OR:
4607 mpz_ior(val, left_val, right_val);
4608 break;
4609 case OPERATOR_XOR:
4610 mpz_xor(val, left_val, right_val);
4611 break;
4612 case OPERATOR_MULT:
4613 mpz_mul(val, left_val, right_val);
7035307e
CM
4614 if (mpz_sizeinbase(val, 2) > 0x100000)
4615 {
4616 error_at(location, "constant multiplication overflow");
4617 mpz_set_ui(val, 1);
4618 }
7a938933
ILT
4619 break;
4620 case OPERATOR_DIV:
4621 if (mpz_sgn(right_val) != 0)
4622 mpz_tdiv_q(val, left_val, right_val);
4623 else
4624 {
4625 error_at(location, "division by zero");
4626 mpz_set_ui(val, 0);
7a938933
ILT
4627 }
4628 break;
4629 case OPERATOR_MOD:
4630 if (mpz_sgn(right_val) != 0)
4631 mpz_tdiv_r(val, left_val, right_val);
4632 else
4633 {
4634 error_at(location, "division by zero");
4635 mpz_set_ui(val, 0);
7a938933
ILT
4636 }
4637 break;
4638 case OPERATOR_LSHIFT:
4639 {
4640 unsigned long shift = mpz_get_ui(right_val);
5caf63ca
ILT
4641 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4642 mpz_mul_2exp(val, left_val, shift);
4643 else
7a938933
ILT
4644 {
4645 error_at(location, "shift count overflow");
7035307e 4646 mpz_set_ui(val, 1);
7a938933 4647 }
7a938933
ILT
4648 break;
4649 }
4650 break;
4651 case OPERATOR_RSHIFT:
4652 {
4653 unsigned long shift = mpz_get_ui(right_val);
4654 if (mpz_cmp_ui(right_val, shift) != 0)
4655 {
4656 error_at(location, "shift count overflow");
7035307e 4657 mpz_set_ui(val, 1);
7a938933 4658 }
7a938933 4659 else
5caf63ca
ILT
4660 {
4661 if (mpz_cmp_ui(left_val, 0) >= 0)
4662 mpz_tdiv_q_2exp(val, left_val, shift);
4663 else
4664 mpz_fdiv_q_2exp(val, left_val, shift);
4665 }
7a938933
ILT
4666 break;
4667 }
4668 break;
4669 case OPERATOR_AND:
4670 mpz_and(val, left_val, right_val);
4671 break;
4672 case OPERATOR_BITCLEAR:
4673 {
4674 mpz_t tval;
4675 mpz_init(tval);
4676 mpz_com(tval, right_val);
4677 mpz_and(val, left_val, tval);
4678 mpz_clear(tval);
4679 }
4680 break;
4681 default:
8c0d1865 4682 go_unreachable();
7a938933
ILT
4683 }
4684
5caf63ca
ILT
4685 mpz_clear(left_val);
4686 mpz_clear(right_val);
7a938933 4687
5caf63ca
ILT
4688 if (left_nc->is_rune()
4689 || (op != OPERATOR_LSHIFT
4690 && op != OPERATOR_RSHIFT
4691 && right_nc->is_rune()))
4692 nc->set_rune(NULL, val);
4693 else
4694 nc->set_int(NULL, val);
4695
4696 mpz_clear(val);
7a938933
ILT
4697
4698 return true;
4699}
4700
5caf63ca
ILT
4701// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4702// floating point operations. Return true if this could be done,
4703// false if not.
7a938933
ILT
4704
4705bool
5caf63ca
ILT
4706Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4707 const Numeric_constant* right_nc,
4708 Location location, Numeric_constant* nc)
7a938933 4709{
5caf63ca
ILT
4710 mpfr_t left_val;
4711 if (!left_nc->to_float(&left_val))
4712 return false;
4713 mpfr_t right_val;
4714 if (!right_nc->to_float(&right_val))
7a938933 4715 {
5caf63ca 4716 mpfr_clear(left_val);
7a938933 4717 return false;
5caf63ca
ILT
4718 }
4719
4720 mpfr_t val;
4721 mpfr_init(val);
4722
4723 bool ret = true;
4724 switch (op)
4725 {
7a938933
ILT
4726 case OPERATOR_PLUS:
4727 mpfr_add(val, left_val, right_val, GMP_RNDN);
4728 break;
4729 case OPERATOR_MINUS:
4730 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4731 break;
4732 case OPERATOR_OR:
4733 case OPERATOR_XOR:
4734 case OPERATOR_AND:
4735 case OPERATOR_BITCLEAR:
5caf63ca
ILT
4736 case OPERATOR_MOD:
4737 case OPERATOR_LSHIFT:
4738 case OPERATOR_RSHIFT:
4739 mpfr_set_ui(val, 0, GMP_RNDN);
4740 ret = false;
4741 break;
7a938933
ILT
4742 case OPERATOR_MULT:
4743 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4744 break;
4745 case OPERATOR_DIV:
5caf63ca
ILT
4746 if (!mpfr_zero_p(right_val))
4747 mpfr_div(val, left_val, right_val, GMP_RNDN);
4748 else
4749 {
4750 error_at(location, "division by zero");
4751 mpfr_set_ui(val, 0, GMP_RNDN);
4752 }
7a938933 4753 break;
7a938933 4754 default:
8c0d1865 4755 go_unreachable();
7a938933
ILT
4756 }
4757
5caf63ca
ILT
4758 mpfr_clear(left_val);
4759 mpfr_clear(right_val);
7a938933 4760
5caf63ca
ILT
4761 nc->set_float(NULL, val);
4762 mpfr_clear(val);
7a938933 4763
5caf63ca 4764 return ret;
7a938933
ILT
4765}
4766
5caf63ca
ILT
4767// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4768// complex operations. Return true if this could be done, false if
4769// not.
7a938933
ILT
4770
4771bool
5caf63ca
ILT
4772Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4773 const Numeric_constant* right_nc,
4774 Location location, Numeric_constant* nc)
7a938933 4775{
5caf63ca
ILT
4776 mpfr_t left_real, left_imag;
4777 if (!left_nc->to_complex(&left_real, &left_imag))
4778 return false;
4779 mpfr_t right_real, right_imag;
4780 if (!right_nc->to_complex(&right_real, &right_imag))
7a938933 4781 {
5caf63ca
ILT
4782 mpfr_clear(left_real);
4783 mpfr_clear(left_imag);
7a938933 4784 return false;
5caf63ca
ILT
4785 }
4786
4787 mpfr_t real, imag;
4788 mpfr_init(real);
4789 mpfr_init(imag);
4790
4791 bool ret = true;
4792 switch (op)
4793 {
7a938933
ILT
4794 case OPERATOR_PLUS:
4795 mpfr_add(real, left_real, right_real, GMP_RNDN);
4796 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4797 break;
4798 case OPERATOR_MINUS:
4799 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4800 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4801 break;
4802 case OPERATOR_OR:
4803 case OPERATOR_XOR:
4804 case OPERATOR_AND:
4805 case OPERATOR_BITCLEAR:
5caf63ca
ILT
4806 case OPERATOR_MOD:
4807 case OPERATOR_LSHIFT:
4808 case OPERATOR_RSHIFT:
4809 mpfr_set_ui(real, 0, GMP_RNDN);
4810 mpfr_set_ui(imag, 0, GMP_RNDN);
4811 ret = false;
4812 break;
7a938933
ILT
4813 case OPERATOR_MULT:
4814 {
4815 // You might think that multiplying two complex numbers would
4816 // be simple, and you would be right, until you start to think
4817 // about getting the right answer for infinity. If one
4818 // operand here is infinity and the other is anything other
4819 // than zero or NaN, then we are going to wind up subtracting
4820 // two infinity values. That will give us a NaN, but the
4821 // correct answer is infinity.
4822
4823 mpfr_t lrrr;
4824 mpfr_init(lrrr);
4825 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4826
4827 mpfr_t lrri;
4828 mpfr_init(lrri);
4829 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4830
4831 mpfr_t lirr;
4832 mpfr_init(lirr);
4833 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4834
4835 mpfr_t liri;
4836 mpfr_init(liri);
4837 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4838
4839 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4840 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4841
4842 // If we get NaN on both sides, check whether it should really
4843 // be infinity. The rule is that if either side of the
4844 // complex number is infinity, then the whole value is
4845 // infinity, even if the other side is NaN. So the only case
4846 // we have to fix is the one in which both sides are NaN.
4847 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4848 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4849 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4850 {
4851 bool is_infinity = false;
4852
4853 mpfr_t lr;
4854 mpfr_t li;
4855 mpfr_init_set(lr, left_real, GMP_RNDN);
4856 mpfr_init_set(li, left_imag, GMP_RNDN);
4857
4858 mpfr_t rr;
4859 mpfr_t ri;
4860 mpfr_init_set(rr, right_real, GMP_RNDN);
4861 mpfr_init_set(ri, right_imag, GMP_RNDN);
4862
4863 // If the left side is infinity, then the result is
4864 // infinity.
4865 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4866 {
4867 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4868 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4869 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4870 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4871 if (mpfr_nan_p(rr))
4872 {
4873 mpfr_set_ui(rr, 0, GMP_RNDN);
4874 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4875 }
4876 if (mpfr_nan_p(ri))
4877 {
4878 mpfr_set_ui(ri, 0, GMP_RNDN);
4879 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4880 }
4881 is_infinity = true;
4882 }
4883
4884 // If the right side is infinity, then the result is
4885 // infinity.
4886 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4887 {
4888 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4889 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4890 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4891 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4892 if (mpfr_nan_p(lr))
4893 {
4894 mpfr_set_ui(lr, 0, GMP_RNDN);
4895 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4896 }
4897 if (mpfr_nan_p(li))
4898 {
4899 mpfr_set_ui(li, 0, GMP_RNDN);
4900 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4901 }
4902 is_infinity = true;
4903 }
4904
4905 // If we got an overflow in the intermediate computations,
4906 // then the result is infinity.
4907 if (!is_infinity
4908 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4909 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4910 {
4911 if (mpfr_nan_p(lr))
4912 {
4913 mpfr_set_ui(lr, 0, GMP_RNDN);
4914 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4915 }
4916 if (mpfr_nan_p(li))
4917 {
4918 mpfr_set_ui(li, 0, GMP_RNDN);
4919 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4920 }
4921 if (mpfr_nan_p(rr))
4922 {
4923 mpfr_set_ui(rr, 0, GMP_RNDN);
4924 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4925 }
4926 if (mpfr_nan_p(ri))
4927 {
4928 mpfr_set_ui(ri, 0, GMP_RNDN);
4929 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4930 }
4931 is_infinity = true;
4932 }
4933
4934 if (is_infinity)
4935 {
4936 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4937 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4938 mpfr_mul(lirr, li, rr, GMP_RNDN);
4939 mpfr_mul(liri, li, ri, GMP_RNDN);
4940 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4941 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4942 mpfr_set_inf(real, mpfr_sgn(real));
4943 mpfr_set_inf(imag, mpfr_sgn(imag));
4944 }
4945
4946 mpfr_clear(lr);
4947 mpfr_clear(li);
4948 mpfr_clear(rr);
4949 mpfr_clear(ri);
4950 }
4951
4952 mpfr_clear(lrrr);
4953 mpfr_clear(lrri);
4954 mpfr_clear(lirr);
4955 mpfr_clear(liri);
4956 }
4957 break;
4958 case OPERATOR_DIV:
4959 {
4960 // For complex division we want to avoid having an
4961 // intermediate overflow turn the whole result in a NaN. We
4962 // scale the values to try to avoid this.
4963
4964 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
5caf63ca
ILT
4965 {
4966 error_at(location, "division by zero");
4967 mpfr_set_ui(real, 0, GMP_RNDN);
4968 mpfr_set_ui(imag, 0, GMP_RNDN);
4969 break;
4970 }
7a938933
ILT
4971
4972 mpfr_t rra;
4973 mpfr_t ria;
4974 mpfr_init(rra);
4975 mpfr_init(ria);
4976 mpfr_abs(rra, right_real, GMP_RNDN);
4977 mpfr_abs(ria, right_imag, GMP_RNDN);
4978 mpfr_t t;
4979 mpfr_init(t);
4980 mpfr_max(t, rra, ria, GMP_RNDN);
4981
4982 mpfr_t rr;
4983 mpfr_t ri;
4984 mpfr_init_set(rr, right_real, GMP_RNDN);
4985 mpfr_init_set(ri, right_imag, GMP_RNDN);
4986 long ilogbw = 0;
4987 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4988 {
4989 ilogbw = mpfr_get_exp(t);
4990 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4991 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4992 }
4993
4994 mpfr_t denom;
4995 mpfr_init(denom);
4996 mpfr_mul(denom, rr, rr, GMP_RNDN);
4997 mpfr_mul(t, ri, ri, GMP_RNDN);
4998 mpfr_add(denom, denom, t, GMP_RNDN);
4999
5000 mpfr_mul(real, left_real, rr, GMP_RNDN);
5001 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5002 mpfr_add(real, real, t, GMP_RNDN);
5003 mpfr_div(real, real, denom, GMP_RNDN);
5004 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5005
5006 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5007 mpfr_mul(t, left_real, ri, GMP_RNDN);
5008 mpfr_sub(imag, imag, t, GMP_RNDN);
5009 mpfr_div(imag, imag, denom, GMP_RNDN);
5010 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5011
5012 // If we wind up with NaN on both sides, check whether we
5013 // should really have infinity. The rule is that if either
5014 // side of the complex number is infinity, then the whole
5015 // value is infinity, even if the other side is NaN. So the
5016 // only case we have to fix is the one in which both sides are
5017 // NaN.
5018 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5019 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5020 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5021 {
5022 if (mpfr_zero_p(denom))
5023 {
5024 mpfr_set_inf(real, mpfr_sgn(rr));
5025 mpfr_mul(real, real, left_real, GMP_RNDN);
5026 mpfr_set_inf(imag, mpfr_sgn(rr));
5027 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5028 }
5029 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5030 && mpfr_number_p(rr) && mpfr_number_p(ri))
5031 {
5032 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5033 mpfr_copysign(t, t, left_real, GMP_RNDN);
5034
5035 mpfr_t t2;
5036 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5037 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5038
5039 mpfr_t t3;
5040 mpfr_init(t3);
5041 mpfr_mul(t3, t, rr, GMP_RNDN);
5042
5043 mpfr_t t4;
5044 mpfr_init(t4);
5045 mpfr_mul(t4, t2, ri, GMP_RNDN);
5046
5047 mpfr_add(t3, t3, t4, GMP_RNDN);
5048 mpfr_set_inf(real, mpfr_sgn(t3));
5049
5050 mpfr_mul(t3, t2, rr, GMP_RNDN);
5051 mpfr_mul(t4, t, ri, GMP_RNDN);
5052 mpfr_sub(t3, t3, t4, GMP_RNDN);
5053 mpfr_set_inf(imag, mpfr_sgn(t3));
5054
5055 mpfr_clear(t2);
5056 mpfr_clear(t3);
5057 mpfr_clear(t4);
5058 }
5059 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5060 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5061 {
5062 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5063 mpfr_copysign(t, t, rr, GMP_RNDN);
5064
5065 mpfr_t t2;
5066 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5067 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5068
5069 mpfr_t t3;
5070 mpfr_init(t3);
5071 mpfr_mul(t3, left_real, t, GMP_RNDN);
5072
5073 mpfr_t t4;
5074 mpfr_init(t4);
5075 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5076
5077 mpfr_add(t3, t3, t4, GMP_RNDN);
5078 mpfr_set_ui(real, 0, GMP_RNDN);
5079 mpfr_mul(real, real, t3, GMP_RNDN);
5080
5081 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5082 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5083 mpfr_sub(t3, t3, t4, GMP_RNDN);
5084 mpfr_set_ui(imag, 0, GMP_RNDN);
5085 mpfr_mul(imag, imag, t3, GMP_RNDN);
5086
5087 mpfr_clear(t2);
5088 mpfr_clear(t3);
5089 mpfr_clear(t4);
5090 }
5091 }
5092
5093 mpfr_clear(denom);
5094 mpfr_clear(rr);
5095 mpfr_clear(ri);
5096 mpfr_clear(t);
5097 mpfr_clear(rra);
5098 mpfr_clear(ria);
5099 }
5100 break;
7a938933 5101 default:
8c0d1865 5102 go_unreachable();
7a938933
ILT
5103 }
5104
5caf63ca
ILT
5105 mpfr_clear(left_real);
5106 mpfr_clear(left_imag);
5107 mpfr_clear(right_real);
5108 mpfr_clear(right_imag);
7a938933 5109
5caf63ca
ILT
5110 nc->set_complex(NULL, real, imag);
5111 mpfr_clear(real);
5112 mpfr_clear(imag);
7a938933 5113
5caf63ca 5114 return ret;
7a938933
ILT
5115}
5116
5117// Lower a binary expression. We have to evaluate constant
5118// expressions now, in order to implement Go's unlimited precision
5119// constants.
5120
5121Expression*
f9f96987
ILT
5122Binary_expression::do_lower(Gogo* gogo, Named_object*,
5123 Statement_inserter* inserter, int)
7a938933 5124{
8afa2bfb 5125 Location location = this->location();
7a938933
ILT
5126 Operator op = this->op_;
5127 Expression* left = this->left_;
5128 Expression* right = this->right_;
5129
5130 const bool is_comparison = (op == OPERATOR_EQEQ
5131 || op == OPERATOR_NOTEQ
5132 || op == OPERATOR_LT
5133 || op == OPERATOR_LE
5134 || op == OPERATOR_GT
5135 || op == OPERATOR_GE);
5136
5caf63ca 5137 // Numeric constant expressions.
7a938933 5138 {
5caf63ca
ILT
5139 Numeric_constant left_nc;
5140 Numeric_constant right_nc;
5141 if (left->numeric_constant_value(&left_nc)
5142 && right->numeric_constant_value(&right_nc))
7a938933 5143 {
5caf63ca 5144 if (is_comparison)
7a938933 5145 {
5caf63ca
ILT
5146 bool result;
5147 if (!Binary_expression::compare_constant(op, &left_nc,
5148 &right_nc, location,
5149 &result))
5150 return this;
610d0e16 5151 return Expression::make_cast(Type::make_boolean_type(),
5caf63ca
ILT
5152 Expression::make_boolean(result,
5153 location),
5154 location);
7a938933
ILT
5155 }
5156 else
5157 {
5caf63ca
ILT
5158 Numeric_constant nc;
5159 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5160 location, &nc))
5161 return this;
5162 return nc.expression(location);
7a938933
ILT
5163 }
5164 }
7a938933
ILT
5165 }
5166
5167 // String constant expressions.
60a3da27 5168 if (left->type()->is_string_type() && right->type()->is_string_type())
7a938933
ILT
5169 {
5170 std::string left_string;
5171 std::string right_string;
5172 if (left->string_constant_value(&left_string)
5173 && right->string_constant_value(&right_string))
60a3da27
ILT
5174 {
5175 if (op == OPERATOR_PLUS)
5176 return Expression::make_string(left_string + right_string,
5177 location);
5178 else if (is_comparison)
5179 {
5180 int cmp = left_string.compare(right_string);
5caf63ca 5181 bool r = Binary_expression::cmp_to_bool(op, cmp);
610d0e16 5182 return Expression::make_boolean(r, location);
fe53b3dd
ILT
5183 }
5184 }
fe53b3dd
ILT
5185 }
5186
58c55a32 5187 // Lower struct, array, and some interface comparisons.
f9f96987
ILT
5188 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5189 {
5190 if (left->type()->struct_type() != NULL)
5191 return this->lower_struct_comparison(gogo, inserter);
5192 else if (left->type()->array_type() != NULL
5193 && !left->type()->is_slice_type())
5194 return this->lower_array_comparison(gogo, inserter);
58c55a32
ILT
5195 else if ((left->type()->interface_type() != NULL
5196 && right->type()->interface_type() == NULL)
5197 || (left->type()->interface_type() == NULL
5198 && right->type()->interface_type() != NULL))
5199 return this->lower_interface_value_comparison(gogo, inserter);
f9f96987
ILT
5200 }
5201
7a938933
ILT
5202 return this;
5203}
5204
f9f96987
ILT
5205// Lower a struct comparison.
5206
5207Expression*
5208Binary_expression::lower_struct_comparison(Gogo* gogo,
5209 Statement_inserter* inserter)
5210{
5211 Struct_type* st = this->left_->type()->struct_type();
5212 Struct_type* st2 = this->right_->type()->struct_type();
5213 if (st2 == NULL)
5214 return this;
5215 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5216 return this;
5217 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5218 this->right_->type(), NULL))
5219 return this;
5220
5221 // See if we can compare using memcmp. As a heuristic, we use
5222 // memcmp rather than field references and comparisons if there are
5223 // more than two fields.
11d8e1a4 5224 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
f9f96987
ILT
5225 return this->lower_compare_to_memcmp(gogo, inserter);
5226
5227 Location loc = this->location();
5228
5229 Expression* left = this->left_;
5230 Temporary_statement* left_temp = NULL;
5231 if (left->var_expression() == NULL
5232 && left->temporary_reference_expression() == NULL)
5233 {
5234 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5235 inserter->insert(left_temp);
5236 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5237 }
5238
5239 Expression* right = this->right_;
5240 Temporary_statement* right_temp = NULL;
5241 if (right->var_expression() == NULL
5242 && right->temporary_reference_expression() == NULL)
5243 {
5244 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5245 inserter->insert(right_temp);
5246 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5247 }
5248
5249 Expression* ret = Expression::make_boolean(true, loc);
5250 const Struct_field_list* fields = st->fields();
5251 unsigned int field_index = 0;
5252 for (Struct_field_list::const_iterator pf = fields->begin();
5253 pf != fields->end();
5254 ++pf, ++field_index)
5255 {
6c74ce92
ILT
5256 if (Gogo::is_sink_name(pf->field_name()))
5257 continue;
5258
f9f96987
ILT
5259 if (field_index > 0)
5260 {
5261 if (left_temp == NULL)
5262 left = left->copy();
5263 else
5264 left = Expression::make_temporary_reference(left_temp, loc);
5265 if (right_temp == NULL)
5266 right = right->copy();
5267 else
5268 right = Expression::make_temporary_reference(right_temp, loc);
5269 }
5270 Expression* f1 = Expression::make_field_reference(left, field_index,
5271 loc);
5272 Expression* f2 = Expression::make_field_reference(right, field_index,
5273 loc);
5274 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5275 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5276 }
5277
5278 if (this->op_ == OPERATOR_NOTEQ)
5279 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5280
5281 return ret;
5282}
5283
5284// Lower an array comparison.
5285
5286Expression*
5287Binary_expression::lower_array_comparison(Gogo* gogo,
5288 Statement_inserter* inserter)
5289{
5290 Array_type* at = this->left_->type()->array_type();
5291 Array_type* at2 = this->right_->type()->array_type();
5292 if (at2 == NULL)
5293 return this;
5294 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5295 return this;
5296 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5297 this->right_->type(), NULL))
5298 return this;
5299
5300 // Call memcmp directly if possible. This may let the middle-end
5301 // optimize the call.
11d8e1a4 5302 if (at->compare_is_identity(gogo))
f9f96987
ILT
5303 return this->lower_compare_to_memcmp(gogo, inserter);
5304
5305 // Call the array comparison function.
5306 Named_object* hash_fn;
5307 Named_object* equal_fn;
5308 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5309 &hash_fn, &equal_fn);
5310
5311 Location loc = this->location();
5312
5313 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5314
5315 Expression_list* args = new Expression_list();
5316 args->push_back(this->operand_address(inserter, this->left_));
5317 args->push_back(this->operand_address(inserter, this->right_));
5318 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5319
5320 Expression* ret = Expression::make_call(func, args, false, loc);
5321
5322 if (this->op_ == OPERATOR_NOTEQ)
5323 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5324
5325 return ret;
5326}
5327
58c55a32
ILT
5328// Lower an interface to value comparison.
5329
5330Expression*
5331Binary_expression::lower_interface_value_comparison(Gogo*,
5332 Statement_inserter* inserter)
5333{
5334 Type* left_type = this->left_->type();
5335 Type* right_type = this->right_->type();
5336 Interface_type* ift;
5337 if (left_type->interface_type() != NULL)
5338 {
5339 ift = left_type->interface_type();
5340 if (!ift->implements_interface(right_type, NULL))
5341 return this;
5342 }
5343 else
5344 {
5345 ift = right_type->interface_type();
5346 if (!ift->implements_interface(left_type, NULL))
5347 return this;
5348 }
5349 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5350 return this;
5351
5352 Location loc = this->location();
5353
5354 if (left_type->interface_type() == NULL
5355 && left_type->points_to() == NULL
5356 && !this->left_->is_addressable())
5357 {
5358 Temporary_statement* temp =
5359 Statement::make_temporary(left_type, NULL, loc);
5360 inserter->insert(temp);
5361 this->left_ =
5362 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5363 }
5364
5365 if (right_type->interface_type() == NULL
5366 && right_type->points_to() == NULL
5367 && !this->right_->is_addressable())
5368 {
5369 Temporary_statement* temp =
5370 Statement::make_temporary(right_type, NULL, loc);
5371 inserter->insert(temp);
5372 this->right_ =
5373 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5374 }
5375
5376 return this;
5377}
5378
f9f96987
ILT
5379// Lower a struct or array comparison to a call to memcmp.
5380
5381Expression*
5382Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5383{
5384 Location loc = this->location();
5385
5386 Expression* a1 = this->operand_address(inserter, this->left_);
5387 Expression* a2 = this->operand_address(inserter, this->right_);
5388 Expression* len = Expression::make_type_info(this->left_->type(),
5389 TYPE_INFO_SIZE);
5390
5391 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5392
5393 mpz_t zval;
5394 mpz_init_set_ui(zval, 0);
5395 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5396 mpz_clear(zval);
5397
5398 return Expression::make_binary(this->op_, call, zero, loc);
5399}
5400
b5407ad1
CM
5401Expression*
5402Binary_expression::do_flatten(Gogo*, Named_object*,
5403 Statement_inserter* inserter)
5404{
5405 Location loc = this->location();
5406 Temporary_statement* temp;
5407 if (this->left_->type()->is_string_type()
5408 && this->op_ == OPERATOR_PLUS)
5409 {
5410 if (!this->left_->is_variable())
5411 {
5412 temp = Statement::make_temporary(NULL, this->left_, loc);
5413 inserter->insert(temp);
5414 this->left_ = Expression::make_temporary_reference(temp, loc);
5415 }
5416 if (!this->right_->is_variable())
5417 {
5418 temp =
5419 Statement::make_temporary(this->left_->type(), this->right_, loc);
5420 this->right_ = Expression::make_temporary_reference(temp, loc);
5421 inserter->insert(temp);
5422 }
5423 }
5424
5425 Type* left_type = this->left_->type();
5426 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5427 || this->op_ == OPERATOR_RSHIFT);
5428 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5429 left_type->integer_type() != NULL)
5430 || this->op_ == OPERATOR_MOD);
5431
5432 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5433 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5434 // and accessed from the Gogo* passed to do_flatten.
5435 if (is_shift_op
5436 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5437 {
5438 if (!this->left_->is_variable())
5439 {
5440 temp = Statement::make_temporary(NULL, this->left_, loc);
5441 inserter->insert(temp);
5442 this->left_ = Expression::make_temporary_reference(temp, loc);
5443 }
5444 if (!this->right_->is_variable())
5445 {
5446 temp =
5447 Statement::make_temporary(NULL, this->right_, loc);
5448 this->right_ = Expression::make_temporary_reference(temp, loc);
5449 inserter->insert(temp);
5450 }
5451 }
5452 return this;
5453}
5454
5455
f9f96987
ILT
5456// Return the address of EXPR, cast to unsafe.Pointer.
5457
5458Expression*
5459Binary_expression::operand_address(Statement_inserter* inserter,
5460 Expression* expr)
5461{
5462 Location loc = this->location();
5463
5464 if (!expr->is_addressable())
5465 {
5466 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5467 loc);
5468 inserter->insert(temp);
5469 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5470 }
5471 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5472 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5473 Type* void_type = Type::make_void_type();
5474 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5475 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5476}
5477
5caf63ca 5478// Return the numeric constant value, if it has one.
7a938933
ILT
5479
5480bool
5caf63ca 5481Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
7a938933 5482{
5caf63ca
ILT
5483 Numeric_constant left_nc;
5484 if (!this->left_->numeric_constant_value(&left_nc))
5485 return false;
5486 Numeric_constant right_nc;
5487 if (!this->right_->numeric_constant_value(&right_nc))
5488 return false;
ea3ef06a 5489 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5caf63ca 5490 this->location(), nc);
7a938933
ILT
5491}
5492
5493// Note that the value is being discarded.
5494
3f7af571 5495bool
7a938933
ILT
5496Binary_expression::do_discarding_value()
5497{
5498 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
3f7af571 5499 return this->right_->discarding_value();
7a938933 5500 else
3f7af571
ILT
5501 {
5502 this->unused_value_error();
5503 return false;
5504 }
7a938933
ILT
5505}
5506
5507// Get type.
5508
5509Type*
5510Binary_expression::do_type()
5511{
ced2ec3b
ILT
5512 if (this->classification() == EXPRESSION_ERROR)
5513 return Type::make_error_type();
5514
7a938933
ILT
5515 switch (this->op_)
5516 {
7a938933
ILT
5517 case OPERATOR_EQEQ:
5518 case OPERATOR_NOTEQ:
5519 case OPERATOR_LT:
5520 case OPERATOR_LE:
5521 case OPERATOR_GT:
5522 case OPERATOR_GE:
610d0e16
ILT
5523 if (this->type_ == NULL)
5524 this->type_ = Type::make_boolean_type();
5525 return this->type_;
7a938933
ILT
5526
5527 case OPERATOR_PLUS:
5528 case OPERATOR_MINUS:
5529 case OPERATOR_OR:
5530 case OPERATOR_XOR:
5531 case OPERATOR_MULT:
5532 case OPERATOR_DIV:
5533 case OPERATOR_MOD:
5534 case OPERATOR_AND:
5535 case OPERATOR_BITCLEAR:
610d0e16
ILT
5536 case OPERATOR_OROR:
5537 case OPERATOR_ANDAND:
7a938933 5538 {
5caf63ca
ILT
5539 Type* type;
5540 if (!Binary_expression::operation_type(this->op_,
5541 this->left_->type(),
5542 this->right_->type(),
5543 &type))
5544 return Type::make_error_type();
5545 return type;
7a938933
ILT
5546 }
5547
5548 case OPERATOR_LSHIFT:
5549 case OPERATOR_RSHIFT:
5550 return this->left_->type();
5551
5552 default:
8c0d1865 5553 go_unreachable();
7a938933
ILT
5554 }
5555}
5556
5557// Set type for a binary expression.
5558
5559void
5560Binary_expression::do_determine_type(const Type_context* context)
5561{
5562 Type* tleft = this->left_->type();
5563 Type* tright = this->right_->type();
5564
5565 // Both sides should have the same type, except for the shift
5566 // operations. For a comparison, we should ignore the incoming
5567 // type.
5568
5569 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5570 || this->op_ == OPERATOR_RSHIFT);
5571
5572 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5573 || this->op_ == OPERATOR_NOTEQ
5574 || this->op_ == OPERATOR_LT
5575 || this->op_ == OPERATOR_LE
5576 || this->op_ == OPERATOR_GT
5577 || this->op_ == OPERATOR_GE);
5578
5579 Type_context subcontext(*context);
5580
5581 if (is_comparison)
5582 {
5583 // In a comparison, the context does not determine the types of
5584 // the operands.
5585 subcontext.type = NULL;
5586 }
5587
3d317d48
ILT
5588 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5589 {
5590 // For a logical operation, the context does not determine the
5591 // types of the operands. The operands must be some boolean
5592 // type but if the context has a boolean type they do not
5593 // inherit it. See http://golang.org/issue/3924.
5594 subcontext.type = NULL;
5595 }
5596
7a938933
ILT
5597 // Set the context for the left hand operand.
5598 if (is_shift_op)
5599 {
fe53b3dd
ILT
5600 // The right hand operand of a shift plays no role in
5601 // determining the type of the left hand operand.
7a938933
ILT
5602 }
5603 else if (!tleft->is_abstract())
5604 subcontext.type = tleft;
5605 else if (!tright->is_abstract())
5606 subcontext.type = tright;
5607 else if (subcontext.type == NULL)
5608 {
5609 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5610 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5611 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5612 {
5613 // Both sides have an abstract integer, abstract float, or
5614 // abstract complex type. Just let CONTEXT determine
5615 // whether they may remain abstract or not.
5616 }
5617 else if (tleft->complex_type() != NULL)
5618 subcontext.type = tleft;
5619 else if (tright->complex_type() != NULL)
5620 subcontext.type = tright;
5621 else if (tleft->float_type() != NULL)
5622 subcontext.type = tleft;
5623 else if (tright->float_type() != NULL)
5624 subcontext.type = tright;
5625 else
5626 subcontext.type = tleft;
e372156c
ILT
5627
5628 if (subcontext.type != NULL && !context->may_be_abstract)
5629 subcontext.type = subcontext.type->make_non_abstract_type();
7a938933
ILT
5630 }
5631
5632 this->left_->determine_type(&subcontext);
5633
7a938933
ILT
5634 if (is_shift_op)
5635 {
fe53b3dd
ILT
5636 // We may have inherited an unusable type for the shift operand.
5637 // Give a useful error if that happened.
5638 if (tleft->is_abstract()
5639 && subcontext.type != NULL
d720b70f 5640 && !subcontext.may_be_abstract
69d8df44 5641 && subcontext.type->interface_type() == NULL
d720b70f 5642 && subcontext.type->integer_type() == NULL)
fe53b3dd 5643 this->report_error(("invalid context-determined non-integer type "
d720b70f 5644 "for left operand of shift"));
fe53b3dd
ILT
5645
5646 // The context for the right hand operand is the same as for the
5647 // left hand operand, except for a shift operator.
7a938933
ILT
5648 subcontext.type = Type::lookup_integer_type("uint");
5649 subcontext.may_be_abstract = false;
5650 }
5651
5652 this->right_->determine_type(&subcontext);
610d0e16
ILT
5653
5654 if (is_comparison)
5655 {
5656 if (this->type_ != NULL && !this->type_->is_abstract())
5657 ;
5658 else if (context->type != NULL && context->type->is_boolean_type())
5659 this->type_ = context->type;
5660 else if (!context->may_be_abstract)
5661 this->type_ = Type::lookup_bool_type();
5662 }
7a938933
ILT
5663}
5664
5665// Report an error if the binary operator OP does not support TYPE.
1358551f
ILT
5666// OTYPE is the type of the other operand. Return whether the
5667// operation is OK. This should not be used for shift.
7a938933
ILT
5668
5669bool
1358551f 5670Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
8afa2bfb 5671 Location location)
7a938933
ILT
5672{
5673 switch (op)
5674 {
5675 case OPERATOR_OROR:
5676 case OPERATOR_ANDAND:
5677 if (!type->is_boolean_type())
5678 {
5679 error_at(location, "expected boolean type");
5680 return false;
5681 }
5682 break;
5683
5684 case OPERATOR_EQEQ:
5685 case OPERATOR_NOTEQ:
f9f96987
ILT
5686 {
5687 std::string reason;
5688 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5689 {
5690 error_at(location, "%s", reason.c_str());
5691 return false;
5692 }
5693 }
7a938933
ILT
5694 break;
5695
5696 case OPERATOR_LT:
5697 case OPERATOR_LE:
5698 case OPERATOR_GT:
5699 case OPERATOR_GE:
f9f96987
ILT
5700 {
5701 std::string reason;
5702 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5703 {
5704 error_at(location, "%s", reason.c_str());
5705 return false;
5706 }
5707 }
7a938933
ILT
5708 break;
5709
5710 case OPERATOR_PLUS:
5711 case OPERATOR_PLUSEQ:
5712 if (type->integer_type() == NULL
5713 && type->float_type() == NULL
5714 && type->complex_type() == NULL
5715 && !type->is_string_type())
5716 {
5717 error_at(location,
5718 "expected integer, floating, complex, or string type");
5719 return false;
5720 }
5721 break;
5722
5723 case OPERATOR_MINUS:
5724 case OPERATOR_MINUSEQ:
5725 case OPERATOR_MULT:
5726 case OPERATOR_MULTEQ:
5727 case OPERATOR_DIV:
5728 case OPERATOR_DIVEQ:
5729 if (type->integer_type() == NULL
5730 && type->float_type() == NULL
5731 && type->complex_type() == NULL)
5732 {
5733 error_at(location, "expected integer, floating, or complex type");
5734 return false;
5735 }
5736 break;
5737
5738 case OPERATOR_MOD:
5739 case OPERATOR_MODEQ:
5740 case OPERATOR_OR:
5741 case OPERATOR_OREQ:
5742 case OPERATOR_AND:
5743 case OPERATOR_ANDEQ:
5744 case OPERATOR_XOR:
5745 case OPERATOR_XOREQ:
5746 case OPERATOR_BITCLEAR:
5747 case OPERATOR_BITCLEAREQ:
5748 if (type->integer_type() == NULL)
5749 {
5750 error_at(location, "expected integer type");
5751 return false;
5752 }
5753 break;
5754
5755 default:
8c0d1865 5756 go_unreachable();
7a938933
ILT
5757 }
5758
5759 return true;
5760}
5761
5762// Check types.
5763
5764void
5765Binary_expression::do_check_types(Gogo*)
5766{
ced2ec3b
ILT
5767 if (this->classification() == EXPRESSION_ERROR)
5768 return;
5769
7a938933
ILT
5770 Type* left_type = this->left_->type();
5771 Type* right_type = this->right_->type();
02ed921a 5772 if (left_type->is_error() || right_type->is_error())
173fb2ff
ILT
5773 {
5774 this->set_is_error();
5775 return;
5776 }
7a938933
ILT
5777
5778 if (this->op_ == OPERATOR_EQEQ
5779 || this->op_ == OPERATOR_NOTEQ
5780 || this->op_ == OPERATOR_LT
5781 || this->op_ == OPERATOR_LE
5782 || this->op_ == OPERATOR_GT
5783 || this->op_ == OPERATOR_GE)
5784 {
3fa057a4
ILT
5785 if (left_type->is_nil_type() && right_type->is_nil_type())
5786 {
5787 this->report_error(_("invalid comparison of nil with nil"));
5788 return;
5789 }
7a938933
ILT
5790 if (!Type::are_assignable(left_type, right_type, NULL)
5791 && !Type::are_assignable(right_type, left_type, NULL))
5792 {
5793 this->report_error(_("incompatible types in binary expression"));
5794 return;
5795 }
5796 if (!Binary_expression::check_operator_type(this->op_, left_type,
1358551f 5797 right_type,
7a938933
ILT
5798 this->location())
5799 || !Binary_expression::check_operator_type(this->op_, right_type,
1358551f 5800 left_type,
7a938933
ILT
5801 this->location()))
5802 {
5803 this->set_is_error();
5804 return;
5805 }
5806 }
5807 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5808 {
5809 if (!Type::are_compatible_for_binop(left_type, right_type))
5810 {
5811 this->report_error(_("incompatible types in binary expression"));
5812 return;
5813 }
5814 if (!Binary_expression::check_operator_type(this->op_, left_type,
1358551f 5815 right_type,
7a938933
ILT
5816 this->location()))
5817 {
5818 this->set_is_error();
5819 return;
5820 }
69908ca8
ILT
5821 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5822 {
5823 // Division by a zero integer constant is an error.
5824 Numeric_constant rconst;
5825 unsigned long rval;
5826 if (left_type->integer_type() != NULL
5827 && this->right_->numeric_constant_value(&rconst)
5828 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5829 && rval == 0)
5830 {
5831 this->report_error(_("integer division by zero"));
5832 return;
5833 }
5834 }
7a938933
ILT
5835 }
5836 else
5837 {
5838 if (left_type->integer_type() == NULL)
5839 this->report_error(_("shift of non-integer operand"));
5840
5841 if (!right_type->is_abstract()
5842 && (right_type->integer_type() == NULL
5843 || !right_type->integer_type()->is_unsigned()))
5844 this->report_error(_("shift count not unsigned integer"));
5845 else
5846 {
5caf63ca
ILT
5847 Numeric_constant nc;
5848 if (this->right_->numeric_constant_value(&nc))
7a938933 5849 {
5caf63ca
ILT
5850 mpz_t val;
5851 if (!nc.to_int(&val))
5852 this->report_error(_("shift count not unsigned integer"));
5853 else
7657ab90 5854 {
5caf63ca
ILT
5855 if (mpz_sgn(val) < 0)
5856 {
5857 this->report_error(_("negative shift count"));
5858 mpz_set_ui(val, 0);
5859 Location rloc = this->right_->location();
5860 this->right_ = Expression::make_integer(&val, right_type,
5861 rloc);
5862 }
5863 mpz_clear(val);
7657ab90 5864 }
7a938933 5865 }
7a938933
ILT
5866 }
5867 }
5868}
5869
5870// Get a tree for a binary expression.
5871
5872tree
5873Binary_expression::do_get_tree(Translate_context* context)
5874{
776f27a6 5875 Gogo* gogo = context->gogo();
b5407ad1
CM
5876 Location loc = this->location();
5877 Type* left_type = this->left_->type();
5878 Type* right_type = this->right_->type();
776f27a6 5879
7a938933
ILT
5880 bool use_left_type = true;
5881 bool is_shift_op = false;
63d1e46d 5882 bool is_idiv_op = false;
7a938933
ILT
5883 switch (this->op_)
5884 {
5885 case OPERATOR_EQEQ:
5886 case OPERATOR_NOTEQ:
5887 case OPERATOR_LT:
5888 case OPERATOR_LE:
5889 case OPERATOR_GT:
5890 case OPERATOR_GE:
b5407ad1
CM
5891 {
5892 Bexpression* ret =
5893 Expression::comparison(context, this->type_, this->op_,
5894 this->left_, this->right_, loc);
5895 return expr_to_tree(ret);
5896 }
7a938933
ILT
5897
5898 case OPERATOR_OROR:
7a938933 5899 case OPERATOR_ANDAND:
7a938933
ILT
5900 use_left_type = false;
5901 break;
5902 case OPERATOR_PLUS:
7a938933 5903 case OPERATOR_MINUS:
7a938933 5904 case OPERATOR_OR:
7a938933 5905 case OPERATOR_XOR:
7a938933 5906 case OPERATOR_MULT:
7a938933
ILT
5907 break;
5908 case OPERATOR_DIV:
b5407ad1
CM
5909 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5910 break;
7a938933 5911 case OPERATOR_MOD:
63d1e46d 5912 is_idiv_op = true;
7a938933
ILT
5913 break;
5914 case OPERATOR_LSHIFT:
7a938933 5915 case OPERATOR_RSHIFT:
7a938933
ILT
5916 is_shift_op = true;
5917 break;
7a938933 5918 case OPERATOR_BITCLEAR:
b5407ad1
CM
5919 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5920 case OPERATOR_AND:
7a938933
ILT
5921 break;
5922 default:
8c0d1865 5923 go_unreachable();
7a938933
ILT
5924 }
5925
b5407ad1 5926 if (left_type->is_string_type())
7a938933 5927 {
26409c52 5928 go_assert(this->op_ == OPERATOR_PLUS);
b5407ad1
CM
5929 Expression* string_plus =
5930 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5931 this->left_, this->right_);
5932 return string_plus->get_tree(context);
5933 }
5934
5935 // For complex division Go might want slightly different results than the
5936 // backend implementation provides, so we have our own runtime routine.
215552ad
ILT
5937 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5938 {
b5407ad1 5939 Runtime::Function complex_code;
215552ad
ILT
5940 switch (this->left_->type()->complex_type()->bits())
5941 {
5942 case 64:
b5407ad1 5943 complex_code = Runtime::COMPLEX64_DIV;
215552ad
ILT
5944 break;
5945 case 128:
b5407ad1 5946 complex_code = Runtime::COMPLEX128_DIV;
215552ad
ILT
5947 break;
5948 default:
5949 go_unreachable();
5950 }
b5407ad1
CM
5951 Expression* complex_div =
5952 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5953 return complex_div->get_tree(context);
215552ad
ILT
5954 }
5955
b5407ad1
CM
5956 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
5957 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
7a938933 5958
b5407ad1
CM
5959 Type* type = use_left_type ? left_type : right_type;
5960 Btype* btype = type->get_backend(gogo);
5961
5962 Bexpression* ret =
5963 gogo->backend()->binary_expression(this->op_, left, right, loc);
5964 ret = gogo->backend()->convert_expression(btype, ret, loc);
7a938933 5965
b5407ad1
CM
5966 // Initialize overflow constants.
5967 Bexpression* overflow;
5968 mpz_t zero;
5969 mpz_init_set_ui(zero, 0UL);
5970 mpz_t one;
5971 mpz_init_set_ui(one, 1UL);
5972 mpz_t neg_one;
5973 mpz_init_set_si(neg_one, -1);
7a938933 5974
b5407ad1
CM
5975 Btype* left_btype = left_type->get_backend(gogo);
5976 Btype* right_btype = right_type->get_backend(gogo);
7a938933
ILT
5977
5978 // In Go, a shift larger than the size of the type is well-defined.
b5407ad1 5979 // This is not true in C, so we need to insert a conditional.
7a938933
ILT
5980 if (is_shift_op)
5981 {
b5407ad1 5982 go_assert(left_type->integer_type() != NULL);
7a938933 5983
b5407ad1
CM
5984 mpz_t bitsval;
5985 int bits = left_type->integer_type()->bits();
5986 mpz_init_set_ui(bitsval, bits);
5987 Bexpression* bits_expr =
5988 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5989 Bexpression* compare =
5990 gogo->backend()->binary_expression(OPERATOR_LT,
5991 right, bits_expr, loc);
7a938933 5992
b5407ad1
CM
5993 Bexpression* zero_expr =
5994 gogo->backend()->integer_constant_expression(left_btype, zero);
5995 overflow = zero_expr;
7a938933 5996 if (this->op_ == OPERATOR_RSHIFT
b5407ad1 5997 && !left_type->integer_type()->is_unsigned())
7a938933 5998 {
b5407ad1
CM
5999 Bexpression* neg_expr =
6000 gogo->backend()->binary_expression(OPERATOR_LT, left,
6001 zero_expr, loc);
6002 Bexpression* neg_one_expr =
6003 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6004 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6005 neg_one_expr,
6006 zero_expr, loc);
63d1e46d 6007 }
b5407ad1
CM
6008 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6009 overflow, loc);
6010 mpz_clear(bitsval);
63d1e46d
ILT
6011 }
6012
6013 // Add checks for division by zero and division overflow as needed.
6014 if (is_idiv_op)
6015 {
6016 if (go_check_divide_zero)
6017 {
6018 // right == 0
b5407ad1
CM
6019 Bexpression* zero_expr =
6020 gogo->backend()->integer_constant_expression(right_btype, zero);
6021 Bexpression* check =
6022 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6023 right, zero_expr, loc);
63d1e46d 6024
b5407ad1 6025 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
63d1e46d 6026 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
b5407ad1
CM
6027 Expression* crash = gogo->runtime_error(errcode, loc);
6028 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
63d1e46d
ILT
6029
6030 // right == 0 ? (__go_runtime_error(...), 0) : ret
b5407ad1
CM
6031 ret = gogo->backend()->conditional_expression(btype, check,
6032 crash_expr, ret, loc);
8afa2bfb
SD
6033 }
6034
63d1e46d
ILT
6035 if (go_check_divide_overflow)
6036 {
6037 // right == -1
6038 // FIXME: It would be nice to say that this test is expected
6039 // to return false.
b5407ad1
CM
6040
6041 Bexpression* neg_one_expr =
6042 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6043 Bexpression* check =
6044 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6045 right, neg_one_expr, loc);
6046
6047 Bexpression* zero_expr =
6048 gogo->backend()->integer_constant_expression(btype, zero);
6049 Bexpression* one_expr =
6050 gogo->backend()->integer_constant_expression(btype, one);
6051
6052 if (type->integer_type()->is_unsigned())
63d1e46d
ILT
6053 {
6054 // An unsigned -1 is the largest possible number, so
6055 // dividing is always 1 or 0.
b5407ad1
CM
6056
6057 Bexpression* cmp =
6058 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6059 left, right, loc);
63d1e46d 6060 if (this->op_ == OPERATOR_DIV)
b5407ad1
CM
6061 overflow =
6062 gogo->backend()->conditional_expression(btype, cmp,
6063 one_expr, zero_expr,
6064 loc);
63d1e46d 6065 else
b5407ad1
CM
6066 overflow =
6067 gogo->backend()->conditional_expression(btype, cmp,
6068 zero_expr, left,
6069 loc);
63d1e46d
ILT
6070 }
6071 else
6072 {
6073 // Computing left / -1 is the same as computing - left,
6074 // which does not overflow since Go sets -fwrapv.
6075 if (this->op_ == OPERATOR_DIV)
b5407ad1
CM
6076 {
6077 Expression* negate_expr =
6078 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6079 overflow = tree_to_expr(negate_expr->get_tree(context));
6080 }
63d1e46d 6081 else
b5407ad1 6082 overflow = zero_expr;
63d1e46d 6083 }
b5407ad1 6084 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
63d1e46d
ILT
6085
6086 // right == -1 ? - left : ret
b5407ad1
CM
6087 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6088 ret, loc);
63d1e46d 6089 }
7a938933
ILT
6090 }
6091
b5407ad1
CM
6092 mpz_clear(zero);
6093 mpz_clear(one);
6094 mpz_clear(neg_one);
6095 return expr_to_tree(ret);
7a938933
ILT
6096}
6097
6098// Export a binary expression.
6099
6100void
6101Binary_expression::do_export(Export* exp) const
6102{
6103 exp->write_c_string("(");
6104 this->left_->export_expression(exp);
6105 switch (this->op_)
6106 {
6107 case OPERATOR_OROR:
6108 exp->write_c_string(" || ");
6109 break;
6110 case OPERATOR_ANDAND:
6111 exp->write_c_string(" && ");
6112 break;
6113 case OPERATOR_EQEQ:
6114 exp->write_c_string(" == ");
6115 break;
6116 case OPERATOR_NOTEQ:
6117 exp->write_c_string(" != ");
6118 break;
6119 case OPERATOR_LT:
6120 exp->write_c_string(" < ");
6121 break;
6122 case OPERATOR_LE:
6123 exp->write_c_string(" <= ");
6124 break;
6125 case OPERATOR_GT:
6126 exp->write_c_string(" > ");
6127 break;
6128 case OPERATOR_GE:
6129 exp->write_c_string(" >= ");
6130 break;
6131 case OPERATOR_PLUS:
6132 exp->write_c_string(" + ");
6133 break;
6134 case OPERATOR_MINUS:
6135 exp->write_c_string(" - ");
6136 break;
6137 case OPERATOR_OR:
6138 exp->write_c_string(" | ");
6139 break;
6140 case OPERATOR_XOR:
6141 exp->write_c_string(" ^ ");
6142 break;
6143 case OPERATOR_MULT:
6144 exp->write_c_string(" * ");
6145 break;
6146 case OPERATOR_DIV:
6147 exp->write_c_string(" / ");
6148 break;
6149 case OPERATOR_MOD:
6150 exp->write_c_string(" % ");
6151 break;
6152 case OPERATOR_LSHIFT:
6153 exp->write_c_string(" << ");
6154 break;
6155 case OPERATOR_RSHIFT:
6156 exp->write_c_string(" >> ");
6157 break;
6158 case OPERATOR_AND:
6159 exp->write_c_string(" & ");
6160 break;
6161 case OPERATOR_BITCLEAR:
6162 exp->write_c_string(" &^ ");
6163 break;
6164 default:
8c0d1865 6165 go_unreachable();
7a938933
ILT
6166 }
6167 this->right_->export_expression(exp);
6168 exp->write_c_string(")");
6169}
6170
6171// Import a binary expression.
6172
6173Expression*
6174Binary_expression::do_import(Import* imp)
6175{
6176 imp->require_c_string("(");
6177
6178 Expression* left = Expression::import_expression(imp);
6179
6180 Operator op;
6181 if (imp->match_c_string(" || "))
6182 {
6183 op = OPERATOR_OROR;
6184 imp->advance(4);
6185 }
6186 else if (imp->match_c_string(" && "))
6187 {
6188 op = OPERATOR_ANDAND;
6189 imp->advance(4);
6190 }
6191 else if (imp->match_c_string(" == "))
6192 {
6193 op = OPERATOR_EQEQ;
6194 imp->advance(4);
6195 }
6196 else if (imp->match_c_string(" != "))
6197 {
6198 op = OPERATOR_NOTEQ;
6199 imp->advance(4);
6200 }
6201 else if (imp->match_c_string(" < "))
6202 {
6203 op = OPERATOR_LT;
6204 imp->advance(3);
6205 }
6206 else if (imp->match_c_string(" <= "))
6207 {
6208 op = OPERATOR_LE;
6209 imp->advance(4);
6210 }
6211 else if (imp->match_c_string(" > "))
6212 {
6213 op = OPERATOR_GT;
6214 imp->advance(3);
6215 }
6216 else if (imp->match_c_string(" >= "))
6217 {
6218 op = OPERATOR_GE;
6219 imp->advance(4);
6220 }
6221 else if (imp->match_c_string(" + "))
6222 {
6223 op = OPERATOR_PLUS;
6224 imp->advance(3);
6225 }
6226 else if (imp->match_c_string(" - "))
6227 {
6228 op = OPERATOR_MINUS;
6229 imp->advance(3);
6230 }
6231 else if (imp->match_c_string(" | "))
6232 {
6233 op = OPERATOR_OR;
6234 imp->advance(3);
6235 }
6236 else if (imp->match_c_string(" ^ "))
6237 {
6238 op = OPERATOR_XOR;
6239 imp->advance(3);
6240 }
6241 else if (imp->match_c_string(" * "))
6242 {
6243 op = OPERATOR_MULT;
6244 imp->advance(3);
6245 }
6246 else if (imp->match_c_string(" / "))
6247 {
6248 op = OPERATOR_DIV;
6249 imp->advance(3);
6250 }
6251 else if (imp->match_c_string(" % "))
6252 {
6253 op = OPERATOR_MOD;
6254 imp->advance(3);
6255 }
6256 else if (imp->match_c_string(" << "))
6257 {
6258 op = OPERATOR_LSHIFT;
6259 imp->advance(4);
6260 }
6261 else if (imp->match_c_string(" >> "))
6262 {
6263 op = OPERATOR_RSHIFT;
6264 imp->advance(4);
6265 }
6266 else if (imp->match_c_string(" & "))
6267 {
6268 op = OPERATOR_AND;
6269 imp->advance(3);
6270 }
6271 else if (imp->match_c_string(" &^ "))
6272 {
6273 op = OPERATOR_BITCLEAR;
6274 imp->advance(4);
6275 }
6276 else
6277 {
6278 error_at(imp->location(), "unrecognized binary operator");
6279 return Expression::make_error(imp->location());
6280 }
6281
6282 Expression* right = Expression::import_expression(imp);
6283
6284 imp->require_c_string(")");
6285
6286 return Expression::make_binary(op, left, right, imp->location());
6287}
6288
16c57fe2
RL
6289// Dump ast representation of a binary expression.
6290
6291void
6292Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6293{
6294 ast_dump_context->ostream() << "(";
6295 ast_dump_context->dump_expression(this->left_);
6296 ast_dump_context->ostream() << " ";
6297 ast_dump_context->dump_operator(this->op_);
6298 ast_dump_context->ostream() << " ";
6299 ast_dump_context->dump_expression(this->right_);
6300 ast_dump_context->ostream() << ") ";
6301}
6302
7a938933
ILT
6303// Make a binary expression.
6304
6305Expression*
6306Expression::make_binary(Operator op, Expression* left, Expression* right,
8afa2bfb 6307 Location location)
7a938933
ILT
6308{
6309 return new Binary_expression(op, left, right, location);
6310}
6311
6312// Implement a comparison.
6313
b5407ad1
CM
6314Bexpression*
6315Expression::comparison(Translate_context* context, Type* result_type,
6316 Operator op, Expression* left, Expression* right,
6317 Location location)
7a938933 6318{
eb6eb862
CM
6319 Type* left_type = left->type();
6320 Type* right_type = right->type();
58c55a32
ILT
6321
6322 mpz_t zval;
6323 mpz_init_set_ui(zval, 0UL);
6324 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6325 mpz_clear(zval);
776f27a6 6326
10a0275d 6327 if (left_type->is_string_type() && right_type->is_string_type())
7a938933 6328 {
eb6eb862
CM
6329 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6330 left, right);
6331 right = zexpr;
7a938933 6332 }
10a0275d
ILT
6333 else if ((left_type->interface_type() != NULL
6334 && right_type->interface_type() == NULL
6335 && !right_type->is_nil_type())
6336 || (left_type->interface_type() == NULL
6337 && !left_type->is_nil_type()
6338 && right_type->interface_type() != NULL))
7a938933
ILT
6339 {
6340 // Comparing an interface value to a non-interface value.
6341 if (left_type->interface_type() == NULL)
6342 {
6343 std::swap(left_type, right_type);
eb6eb862 6344 std::swap(left, right);
7a938933
ILT
6345 }
6346
6347 // The right operand is not an interface. We need to take its
6348 // address if it is not a pointer.
58c55a32 6349 Expression* pointer_arg = NULL;
7a938933 6350 if (right_type->points_to() != NULL)
eb6eb862 6351 pointer_arg = right;
7a938933
ILT
6352 else
6353 {
eb6eb862
CM
6354 go_assert(right->is_addressable());
6355 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
58c55a32 6356 location);
7a938933 6357 }
7a938933 6358
eb6eb862
CM
6359 Expression* descriptor =
6360 Expression::make_type_descriptor(right_type, location);
6361 left =
58c55a32
ILT
6362 Runtime::make_call((left_type->interface_type()->is_empty()
6363 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6364 : Runtime::INTERFACE_VALUE_COMPARE),
eb6eb862 6365 location, 3, left, descriptor,
58c55a32 6366 pointer_arg);
eb6eb862 6367 right = zexpr;
7a938933
ILT
6368 }
6369 else if (left_type->interface_type() != NULL
6370 && right_type->interface_type() != NULL)
6371 {
58c55a32 6372 Runtime::Function compare_function;
7b67393d
ILT
6373 if (left_type->interface_type()->is_empty()
6374 && right_type->interface_type()->is_empty())
58c55a32 6375 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
7b67393d
ILT
6376 else if (!left_type->interface_type()->is_empty()
6377 && !right_type->interface_type()->is_empty())
58c55a32 6378 compare_function = Runtime::INTERFACE_COMPARE;
7b67393d
ILT
6379 else
6380 {
6381 if (left_type->interface_type()->is_empty())
6382 {
26409c52 6383 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7b67393d 6384 std::swap(left_type, right_type);
eb6eb862 6385 std::swap(left, right);
7b67393d 6386 }
26409c52
ILT
6387 go_assert(!left_type->interface_type()->is_empty());
6388 go_assert(right_type->interface_type()->is_empty());
58c55a32 6389 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
7b67393d
ILT
6390 }
6391
eb6eb862
CM
6392 left = Runtime::make_call(compare_function, location, 2, left, right);
6393 right = zexpr;
7a938933
ILT
6394 }
6395
6396 if (left_type->is_nil_type()
6397 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6398 {
6399 std::swap(left_type, right_type);
eb6eb862 6400 std::swap(left, right);
7a938933
ILT
6401 }
6402
6403 if (right_type->is_nil_type())
6404 {
eb6eb862 6405 right = Expression::make_nil(location);
7a938933
ILT
6406 if (left_type->array_type() != NULL
6407 && left_type->array_type()->length() == NULL)
6408 {
6409 Array_type* at = left_type->array_type();
eb6eb862 6410 left = at->get_value_pointer(context->gogo(), left);
7a938933
ILT
6411 }
6412 else if (left_type->interface_type() != NULL)
6413 {
6414 // An interface is nil if the first field is nil.
eb6eb862 6415 left = Expression::make_field_reference(left, 0, location);
7a938933
ILT
6416 }
6417 }
6418
b5407ad1
CM
6419 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6420 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
610d0e16 6421
b5407ad1
CM
6422 Gogo* gogo = context->gogo();
6423 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6424 right_bexpr, location);
6425 if (result_type != NULL)
6426 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6427 ret, location);
7a938933
ILT
6428 return ret;
6429}
6430
6431// Class Bound_method_expression.
6432
6433// Traversal.
6434
6435int
6436Bound_method_expression::do_traverse(Traverse* traverse)
6437{
48ab8ba6 6438 return Expression::traverse(&this->expr_, traverse);
7a938933
ILT
6439}
6440
571d3f91
ILT
6441// Lower the expression. If this is a method value rather than being
6442// called, and the method is accessed via a pointer, we may need to
6443// add nil checks. Introduce a temporary variable so that those nil
6444// checks do not cause multiple evaluation.
6445
6446Expression*
6447Bound_method_expression::do_lower(Gogo*, Named_object*,
6448 Statement_inserter* inserter, int)
6449{
6450 // For simplicity we use a temporary for every call to an embedded
6451 // method, even though some of them might be pure value methods and
6452 // not require a temporary.
6453 if (this->expr_->var_expression() == NULL
6454 && this->expr_->temporary_reference_expression() == NULL
6455 && this->expr_->set_and_use_temporary_expression() == NULL
6456 && (this->method_->field_indexes() != NULL
6457 || (this->method_->is_value_method()
6458 && this->expr_->type()->points_to() != NULL)))
6459 {
6460 Temporary_statement* temp =
6461 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6462 inserter->insert(temp);
6463 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6464 this->location());
6465 }
6466 return this;
6467}
6468
7a938933 6469// Return the type of a bound method expression. The type of this
571d3f91 6470// object is simply the type of the method with no receiver.
7a938933
ILT
6471
6472Type*
6473Bound_method_expression::do_type()
6474{
571d3f91
ILT
6475 Named_object* fn = this->method_->named_object();
6476 Function_type* fntype;
6477 if (fn->is_function())
6478 fntype = fn->func_value()->type();
6479 else if (fn->is_function_declaration())
6480 fntype = fn->func_declaration_value()->type();
48ab8ba6
ILT
6481 else
6482 return Type::make_error_type();
571d3f91 6483 return fntype->copy_without_receiver();
7a938933
ILT
6484}
6485
6486// Determine the types of a method expression.
6487
6488void
6489Bound_method_expression::do_determine_type(const Type_context*)
6490{
571d3f91
ILT
6491 Named_object* fn = this->method_->named_object();
6492 Function_type* fntype;
6493 if (fn->is_function())
6494 fntype = fn->func_value()->type();
6495 else if (fn->is_function_declaration())
6496 fntype = fn->func_declaration_value()->type();
6497 else
6498 fntype = NULL;
7a938933
ILT
6499 if (fntype == NULL || !fntype->is_method())
6500 this->expr_->determine_type_no_context();
6501 else
6502 {
6503 Type_context subcontext(fntype->receiver()->type(), false);
6504 this->expr_->determine_type(&subcontext);
6505 }
6506}
6507
6508// Check the types of a method expression.
6509
6510void
6511Bound_method_expression::do_check_types(Gogo*)
6512{
571d3f91
ILT
6513 Named_object* fn = this->method_->named_object();
6514 if (!fn->is_function() && !fn->is_function_declaration())
6515 {
6516 this->report_error(_("object is not a method"));
6517 return;
6518 }
6519
6520 Function_type* fntype;
6521 if (fn->is_function())
6522 fntype = fn->func_value()->type();
6523 else if (fn->is_function_declaration())
6524 fntype = fn->func_declaration_value()->type();
7a938933 6525 else
571d3f91
ILT
6526 go_unreachable();
6527 Type* rtype = fntype->receiver()->type()->deref();
6528 Type* etype = (this->expr_type_ != NULL
6529 ? this->expr_type_
6530 : this->expr_->type());
6531 etype = etype->deref();
6532 if (!Type::are_identical(rtype, etype, true, NULL))
6533 this->report_error(_("method type does not match object type"));
6534}
6535
6536// If a bound method expression is not simply called, then it is
6537// represented as a closure. The closure will hold a single variable,
6538// the receiver to pass to the method. The function will be a simple
6539// thunk that pulls that value from the closure and calls the method
6540// with the remaining arguments.
6541//
6542// Because method values are not common, we don't build all thunks for
6543// every methods, but instead only build them as we need them. In
6544// particular, we even build them on demand for methods defined in
6545// other packages.
6546
6547Bound_method_expression::Method_value_thunks
6548 Bound_method_expression::method_value_thunks;
6549
6550// Find or create the thunk for METHOD.
6551
6552Named_object*
6553Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6554 Named_object* fn)
6555{
6556 std::pair<Named_object*, Named_object*> val(fn, NULL);
6557 std::pair<Method_value_thunks::iterator, bool> ins =
6558 Bound_method_expression::method_value_thunks.insert(val);
6559 if (!ins.second)
6560 {
6561 // We have seen this method before.
6562 go_assert(ins.first->second != NULL);
6563 return ins.first->second;
6564 }
6565
6566 Location loc = fn->location();
6567
6568 Function_type* orig_fntype;
6569 if (fn->is_function())
6570 orig_fntype = fn->func_value()->type();
6571 else if (fn->is_function_declaration())
6572 orig_fntype = fn->func_declaration_value()->type();
6573 else
6574 orig_fntype = NULL;
6575
6576 if (orig_fntype == NULL || !orig_fntype->is_method())
7a938933 6577 {
571d3f91
ILT
6578 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6579 return ins.first->second;
7a938933 6580 }
571d3f91
ILT
6581
6582 Struct_field_list* sfl = new Struct_field_list();
05a7d566
ILT
6583 // The type here is wrong--it should be the C function type. But it
6584 // doesn't really matter.
571d3f91
ILT
6585 Type* vt = Type::make_pointer_type(Type::make_void_type());
6586 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6587 sfl->push_back(Struct_field(Typed_identifier("val.1",
6588 orig_fntype->receiver()->type(),
6589 loc)));
6590 Type* closure_type = Type::make_struct_type(sfl, loc);
6591 closure_type = Type::make_pointer_type(closure_type);
6592
05a7d566 6593 Function_type* new_fntype = orig_fntype->copy_with_names();
571d3f91
ILT
6594
6595 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6596 false, loc);
6597
05a7d566
ILT
6598 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6599 cvar->set_is_used();
6600 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6601 new_no->func_value()->set_closure_var(cp);
571d3f91 6602
05a7d566 6603 gogo->start_block(loc);
571d3f91
ILT
6604
6605 // Field 0 of the closure is the function code pointer, field 1 is
6606 // the value on which to invoke the method.
6607 Expression* arg = Expression::make_var_reference(cp, loc);
6608 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6609 arg = Expression::make_field_reference(arg, 1, loc);
6610
6611 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6612
6613 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6614 Expression_list* args;
6615 if (orig_params == NULL || orig_params->empty())
6616 args = NULL;
6617 else
6618 {
6619 const Typed_identifier_list* new_params = new_fntype->parameters();
6620 args = new Expression_list();
6621 for (Typed_identifier_list::const_iterator p = new_params->begin();
05a7d566 6622 p != new_params->end();
571d3f91
ILT
6623 ++p)
6624 {
6625 Named_object* p_no = gogo->lookup(p->name(), NULL);
6626 go_assert(p_no != NULL
6627 && p_no->is_variable()
6628 && p_no->var_value()->is_parameter());
6629 args->push_back(Expression::make_var_reference(p_no, loc));
6630 }
6631 }
6632
6633 Call_expression* call = Expression::make_call(bme, args,
6634 orig_fntype->is_varargs(),
6635 loc);
6636 call->set_varargs_are_lowered();
6637
6638 Statement* s = Statement::make_return_from_call(call, loc);
6639 gogo->add_statement(s);
6640 Block* b = gogo->finish_block(loc);
6641 gogo->add_block(b, loc);
6642 gogo->lower_block(new_no, b);
b5407ad1 6643 gogo->flatten_block(new_no, b);
571d3f91
ILT
6644 gogo->finish_function(loc);
6645
6646 ins.first->second = new_no;
6647 return new_no;
6648}
6649
6650// Return an expression to check *REF for nil while dereferencing
6651// according to FIELD_INDEXES. Update *REF to build up the field
6652// reference. This is a static function so that we don't have to
6653// worry about declaring Field_indexes in expressions.h.
6654
6655static Expression*
6656bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6657 Expression** ref)
6658{
6659 if (field_indexes == NULL)
6660 return Expression::make_boolean(false, loc);
6661 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6662 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6663 go_assert(stype != NULL
6664 && field_indexes->field_index < stype->field_count());
6665 if ((*ref)->type()->struct_type() == NULL)
6666 {
6667 go_assert((*ref)->type()->points_to() != NULL);
6668 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6669 Expression::make_nil(loc),
6670 loc);
6671 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6672 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6673 go_assert((*ref)->type()->struct_type() == stype);
6674 }
6675 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6676 loc);
6677 return cond;
7a938933
ILT
6678}
6679
571d3f91 6680// Get the tree for a method value.
7a938933
ILT
6681
6682tree
571d3f91 6683Bound_method_expression::do_get_tree(Translate_context* context)
7a938933 6684{
571d3f91
ILT
6685 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6686 this->method_,
6687 this->function_);
6688 if (thunk->is_erroneous())
6689 {
6690 go_assert(saw_errors());
6691 return error_mark_node;
6692 }
6693
6694 // FIXME: We should lower this earlier, but we can't lower it in the
6695 // lowering pass because at that point we don't know whether we need
6696 // to create the thunk or not. If the expression is called, we
6697 // don't need the thunk.
6698
6699 Location loc = this->location();
6700
6701 // If the method expects a value, and we have a pointer, we need to
6702 // dereference the pointer.
6703
6704 Named_object* fn = this->method_->named_object();
6705 Function_type* fntype;
6706 if (fn->is_function())
6707 fntype = fn->func_value()->type();
6708 else if (fn->is_function_declaration())
6709 fntype = fn->func_declaration_value()->type();
6710 else
6711 go_unreachable();
6712
6713 Expression* val = this->expr_;
6714 if (fntype->receiver()->type()->points_to() == NULL
6715 && val->type()->points_to() != NULL)
6716 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6717
6718 // Note that we are ignoring this->expr_type_ here. The thunk will
6719 // expect a closure whose second field has type this->expr_type_ (if
6720 // that is not NULL). We are going to pass it a closure whose
6721 // second field has type this->expr_->type(). Since
6722 // this->expr_type_ is only not-NULL for pointer types, we can get
6723 // away with this.
6724
6725 Struct_field_list* fields = new Struct_field_list();
6726 fields->push_back(Struct_field(Typed_identifier("fn.0",
6727 thunk->func_value()->type(),
6728 loc)));
6729 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6730 Struct_type* st = Type::make_struct_type(fields, loc);
6731
6732 Expression_list* vals = new Expression_list();
6733 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6734 vals->push_back(val);
6735
6736 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7035307e 6737 ret = Expression::make_heap_expression(ret, loc);
571d3f91
ILT
6738
6739 tree ret_tree = ret->get_tree(context);
6740
6741 Expression* nil_check = NULL;
6742
6743 // See whether the expression or any embedded pointers are nil.
6744
6745 Expression* expr = this->expr_;
6746 if (this->method_->field_indexes() != NULL)
6747 {
6748 // Note that we are evaluating this->expr_ twice, but that is OK
6749 // because in the lowering pass we forced it into a temporary
6750 // variable.
6751 Expression* ref = expr;
6752 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6753 expr = ref;
6754 }
6755
6756 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6757 {
6758 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6759 Expression::make_nil(loc),
6760 loc);
6761 if (nil_check == NULL)
6762 nil_check = n;
6763 else
6764 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6765 }
6766
6767 if (nil_check != NULL)
6768 {
6769 tree nil_check_tree = nil_check->get_tree(context);
5aac5cb2 6770 Expression* crash_expr =
571d3f91 6771 context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
5aac5cb2 6772 tree crash = crash_expr->get_tree(context);
571d3f91
ILT
6773 if (ret_tree == error_mark_node
6774 || nil_check_tree == error_mark_node
6775 || crash == error_mark_node)
6776 return error_mark_node;
6777
6778 ret_tree = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
6779 TREE_TYPE(ret_tree),
6780 build3_loc(loc.gcc_location(), COND_EXPR,
6781 void_type_node, nil_check_tree,
6782 crash, NULL_TREE),
6783 ret_tree);
6784 }
6785
6786 return ret_tree;
7a938933
ILT
6787}
6788
16c57fe2
RL
6789// Dump ast representation of a bound method expression.
6790
6791void
6792Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6793 const
6794{
6795 if (this->expr_type_ != NULL)
6796 ast_dump_context->ostream() << "(";
6797 ast_dump_context->dump_expression(this->expr_);
6798 if (this->expr_type_ != NULL)
6799 {
6800 ast_dump_context->ostream() << ":";
6801 ast_dump_context->dump_type(this->expr_type_);
6802 ast_dump_context->ostream() << ")";
6803 }
6804
571d3f91 6805 ast_dump_context->ostream() << "." << this->function_->name();
16c57fe2
RL
6806}
6807
7a938933
ILT
6808// Make a method expression.
6809
6810Bound_method_expression*
571d3f91
ILT
6811Expression::make_bound_method(Expression* expr, const Method* method,
6812 Named_object* function, Location location)
7a938933 6813{
571d3f91 6814 return new Bound_method_expression(expr, method, function, location);
7a938933
ILT
6815}
6816
6817// Class Builtin_call_expression. This is used for a call to a
6818// builtin function.
6819
6820class Builtin_call_expression : public Call_expression
6821{
6822 public:
6823 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
8afa2bfb 6824 bool is_varargs, Location location);
7a938933
ILT
6825
6826 protected:
6827 // This overrides Call_expression::do_lower.
6828 Expression*
8586635c 6829 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7a938933 6830
6ddb6288
ILT
6831 Expression*
6832 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6833
7a938933
ILT
6834 bool
6835 do_is_constant() const;
6836
6837 bool
5caf63ca 6838 do_numeric_constant_value(Numeric_constant*) const;
7a938933 6839
3f7af571 6840 bool
3c365907
ILT
6841 do_discarding_value();
6842
7a938933
ILT
6843 Type*
6844 do_type();
6845
6846 void
6847 do_determine_type(const Type_context*);
6848
6849 void
6850 do_check_types(Gogo*);
6851
6852 Expression*
6853 do_copy()
6854 {
6855 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6856 this->args()->copy(),
6857 this->is_varargs(),
6858 this->location());
6859 }
6860
6861 tree
6862 do_get_tree(Translate_context*);
6863
6864 void
6865 do_export(Export*) const;
6866
6867 virtual bool
6868 do_is_recover_call() const;
6869
6870 virtual void
6871 do_set_recover_arg(Expression*);
6872
6873 private:
6874 // The builtin functions.
6875 enum Builtin_function_code
6876 {
6877 BUILTIN_INVALID,
6878
6879 // Predeclared builtin functions.
6880 BUILTIN_APPEND,
6881 BUILTIN_CAP,
6882 BUILTIN_CLOSE,
ff5f50c5 6883 BUILTIN_COMPLEX,
7a938933 6884 BUILTIN_COPY,
f29ce5f5 6885 BUILTIN_DELETE,
7a938933
ILT
6886 BUILTIN_IMAG,
6887 BUILTIN_LEN,
6888 BUILTIN_MAKE,
6889 BUILTIN_NEW,
6890 BUILTIN_PANIC,
6891 BUILTIN_PRINT,
6892 BUILTIN_PRINTLN,
6893 BUILTIN_REAL,
6894 BUILTIN_RECOVER,
6895
6896 // Builtin functions from the unsafe package.
6897 BUILTIN_ALIGNOF,
6898 BUILTIN_OFFSETOF,
6899 BUILTIN_SIZEOF
6900 };
6901
6902 Expression*
6903 one_arg() const;
6904
6905 bool
6906 check_one_arg();
6907
6908 static Type*
6909 real_imag_type(Type*);
6910
6911 static Type*
ff5f50c5 6912 complex_type(Type*);
7a938933 6913
3b8dffe7
ILT
6914 Expression*
6915 lower_make();
6916
6917 bool
54d04de7 6918 check_int_value(Expression*, bool is_length);
3b8dffe7 6919
7a938933
ILT
6920 // A pointer back to the general IR structure. This avoids a global
6921 // variable, or passing it around everywhere.
6922 Gogo* gogo_;
6923 // The builtin function being called.
6924 Builtin_function_code code_;
ab9d6dcf
ILT
6925 // Used to stop endless loops when the length of an array uses len
6926 // or cap of the array itself.
6927 mutable bool seen_;
7a938933
ILT
6928};
6929
6930Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6931 Expression* fn,
6932 Expression_list* args,
6933 bool is_varargs,
8afa2bfb 6934 Location location)
7a938933 6935 : Call_expression(fn, args, is_varargs, location),
ab9d6dcf 6936 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
7a938933
ILT
6937{
6938 Func_expression* fnexp = this->fn()->func_expression();
26409c52 6939 go_assert(fnexp != NULL);
7a938933
ILT
6940 const std::string& name(fnexp->named_object()->name());
6941 if (name == "append")
6942 this->code_ = BUILTIN_APPEND;
6943 else if (name == "cap")
6944 this->code_ = BUILTIN_CAP;
6945 else if (name == "close")
6946 this->code_ = BUILTIN_CLOSE;
ff5f50c5
ILT
6947 else if (name == "complex")
6948 this->code_ = BUILTIN_COMPLEX;
7a938933
ILT
6949 else if (name == "copy")
6950 this->code_ = BUILTIN_COPY;
f29ce5f5
ILT
6951 else if (name == "delete")
6952 this->code_ = BUILTIN_DELETE;
7a938933
ILT
6953 else if (name == "imag")
6954 this->code_ = BUILTIN_IMAG;
6955 else if (name == "len")
6956 this->code_ = BUILTIN_LEN;
6957 else if (name == "make")
6958 this->code_ = BUILTIN_MAKE;
6959 else if (name == "new")
6960 this->code_ = BUILTIN_NEW;
6961 else if (name == "panic")
6962 this->code_ = BUILTIN_PANIC;
6963 else if (name == "print")
6964 this->code_ = BUILTIN_PRINT;
6965 else if (name == "println")
6966 this->code_ = BUILTIN_PRINTLN;
6967 else if (name == "real")
6968 this->code_ = BUILTIN_REAL;
6969 else if (name == "recover")
6970 this->code_ = BUILTIN_RECOVER;
6971 else if (name == "Alignof")
6972 this->code_ = BUILTIN_ALIGNOF;
6973 else if (name == "Offsetof")
6974 this->code_ = BUILTIN_OFFSETOF;
6975 else if (name == "Sizeof")
6976 this->code_ = BUILTIN_SIZEOF;
6977 else
8c0d1865 6978 go_unreachable();
7a938933
ILT
6979}
6980
6981// Return whether this is a call to recover. This is a virtual
6982// function called from the parent class.
6983
6984bool
6985Builtin_call_expression::do_is_recover_call() const
6986{
6987 if (this->classification() == EXPRESSION_ERROR)
6988 return false;
6989 return this->code_ == BUILTIN_RECOVER;
6990}
6991
6992// Set the argument for a call to recover.
6993
6994void
6995Builtin_call_expression::do_set_recover_arg(Expression* arg)
6996{
6997 const Expression_list* args = this->args();
26409c52 6998 go_assert(args == NULL || args->empty());
7a938933
ILT
6999 Expression_list* new_args = new Expression_list();
7000 new_args->push_back(arg);
7001 this->set_args(new_args);
7002}
7003
7a938933
ILT
7004// Lower a builtin call expression. This turns new and make into
7005// specific expressions. We also convert to a constant if we can.
7006
7007Expression*
8586635c
ILT
7008Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7009 Statement_inserter* inserter, int)
7a938933 7010{
3b8dffe7
ILT
7011 if (this->classification() == EXPRESSION_ERROR)
7012 return this;
7013
8afa2bfb 7014 Location loc = this->location();
f29ce5f5 7015
530f4f43
ILT
7016 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7017 {
7018 this->report_error(_("invalid use of %<...%> with builtin function"));
f29ce5f5 7019 return Expression::make_error(loc);
530f4f43
ILT
7020 }
7021
8259d364
ILT
7022 if (this->code_ == BUILTIN_OFFSETOF)
7023 {
7024 Expression* arg = this->one_arg();
d6218114
ILT
7025
7026 if (arg->bound_method_expression() != NULL
7027 || arg->interface_field_reference_expression() != NULL)
7028 {
7029 this->report_error(_("invalid use of method value as argument "
7030 "of Offsetof"));
7031 return this;
7032 }
7033
8259d364
ILT
7034 Field_reference_expression* farg = arg->field_reference_expression();
7035 while (farg != NULL)
7036 {
7037 if (!farg->implicit())
7038 break;
7039 // When the selector refers to an embedded field,
7040 // it must not be reached through pointer indirections.
7041 if (farg->expr()->deref() != farg->expr())
7042 {
d6218114
ILT
7043 this->report_error(_("argument of Offsetof implies "
7044 "indirection of an embedded field"));
8259d364
ILT
7045 return this;
7046 }
7047 // Go up until we reach the original base.
7048 farg = farg->expr()->field_reference_expression();
7049 }
7050 }
7051
f29ce5f5 7052 if (this->is_constant())
7a938933 7053 {
5caf63ca
ILT
7054 Numeric_constant nc;
7055 if (this->numeric_constant_value(&nc))
7056 return nc.expression(loc);
7a938933 7057 }
f29ce5f5
ILT
7058
7059 switch (this->code_)
7a938933 7060 {
f29ce5f5
ILT
7061 default:
7062 break;
7063
7064 case BUILTIN_NEW:
7065 {
7066 const Expression_list* args = this->args();
7067 if (args == NULL || args->size() < 1)
7068 this->report_error(_("not enough arguments"));
7069 else if (args->size() > 1)
7070 this->report_error(_("too many arguments"));
7071 else
7072 {
7073 Expression* arg = args->front();
7074 if (!arg->is_type_expression())
7075 {
7076 error_at(arg->location(), "expected type");
7077 this->set_is_error();
7078 }
7079 else
7080 return Expression::make_allocation(arg->type(), loc);
7081 }
7082 }
7083 break;
7084
7085 case BUILTIN_MAKE:
7086 return this->lower_make();
7087
7088 case BUILTIN_RECOVER:
7a938933
ILT
7089 if (function != NULL)
7090 function->func_value()->set_calls_recover();
7091 else
7092 {
7093 // Calling recover outside of a function always returns the
7094 // nil empty interface.
7c0434e5 7095 Type* eface = Type::make_empty_interface_type(loc);
f29ce5f5 7096 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7a938933 7097 }
f29ce5f5
ILT
7098 break;
7099
7100 case BUILTIN_APPEND:
7101 {
7102 // Lower the varargs.
7103 const Expression_list* args = this->args();
7104 if (args == NULL || args->empty())
7a938933 7105 return this;
f29ce5f5
ILT
7106 Type* slice_type = args->front()->type();
7107 if (!slice_type->is_slice_type())
7108 {
3a24b265
ILT
7109 if (slice_type->is_nil_type())
7110 error_at(args->front()->location(), "use of untyped nil");
7111 else
7112 error_at(args->front()->location(),
7113 "argument 1 must be a slice");
f29ce5f5
ILT
7114 this->set_is_error();
7115 return this;
7116 }
80678229
ILT
7117 Type* element_type = slice_type->array_type()->element_type();
7118 this->lower_varargs(gogo, function, inserter,
7119 Type::make_array_type(element_type, NULL),
7120 2);
f29ce5f5
ILT
7121 }
7122 break;
7123
7124 case BUILTIN_DELETE:
7125 {
7126 // Lower to a runtime function call.
7127 const Expression_list* args = this->args();
7128 if (args == NULL || args->size() < 2)
7129 this->report_error(_("not enough arguments"));
7130 else if (args->size() > 2)
7131 this->report_error(_("too many arguments"));
7132 else if (args->front()->type()->map_type() == NULL)
7133 this->report_error(_("argument 1 must be a map"));
7134 else
7135 {
7136 // Since this function returns no value it must appear in
7137 // a statement by itself, so we don't have to worry about
7138 // order of evaluation of values around it. Evaluate the
7139 // map first to get order of evaluation right.
7140 Map_type* mt = args->front()->type()->map_type();
7141 Temporary_statement* map_temp =
7142 Statement::make_temporary(mt, args->front(), loc);
7143 inserter->insert(map_temp);
7144
7145 Temporary_statement* key_temp =
7146 Statement::make_temporary(mt->key_type(), args->back(), loc);
7147 inserter->insert(key_temp);
7148
7149 Expression* e1 = Expression::make_temporary_reference(map_temp,
7150 loc);
7151 Expression* e2 = Expression::make_temporary_reference(key_temp,
7152 loc);
7153 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7154 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7155 2, e1, e2);
7156 }
7157 }
7158 break;
7a938933
ILT
7159 }
7160
7161 return this;
7162}
7163
6ddb6288
ILT
7164// Flatten a builtin call expression. This turns the arguments of copy and
7165// append into temporary expressions.
7166
7167Expression*
7168Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7169 Statement_inserter* inserter)
7170{
7171 if (this->code_ == BUILTIN_APPEND
7172 || this->code_ == BUILTIN_COPY)
7173 {
7174 Location loc = this->location();
7175 Type* at = this->args()->front()->type();
7176 for (Expression_list::iterator pa = this->args()->begin();
7177 pa != this->args()->end();
7178 ++pa)
7179 {
7180 if ((*pa)->is_nil_expression())
7181 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7182 if (!(*pa)->is_variable())
7183 {
7184 Temporary_statement* temp =
7185 Statement::make_temporary(NULL, *pa, loc);
7186 inserter->insert(temp);
7187 *pa = Expression::make_temporary_reference(temp, loc);
7188 }
7189 }
7190 }
7191 return this;
7192}
7193
3b8dffe7
ILT
7194// Lower a make expression.
7195
7196Expression*
7197Builtin_call_expression::lower_make()
7198{
8afa2bfb 7199 Location loc = this->location();
3b8dffe7
ILT
7200
7201 const Expression_list* args = this->args();
7202 if (args == NULL || args->size() < 1)
7203 {
7204 this->report_error(_("not enough arguments"));
7205 return Expression::make_error(this->location());
7206 }
7207
7208 Expression_list::const_iterator parg = args->begin();
7209
7210 Expression* first_arg = *parg;
7211 if (!first_arg->is_type_expression())
7212 {
7213 error_at(first_arg->location(), "expected type");
7214 this->set_is_error();
7215 return Expression::make_error(this->location());
7216 }
7217 Type* type = first_arg->type();
7218
7219 bool is_slice = false;
7220 bool is_map = false;
7221 bool is_chan = false;
b7190f2f 7222 if (type->is_slice_type())
3b8dffe7
ILT
7223 is_slice = true;
7224 else if (type->map_type() != NULL)
7225 is_map = true;
7226 else if (type->channel_type() != NULL)
7227 is_chan = true;
7228 else
7229 {
7230 this->report_error(_("invalid type for make function"));
7231 return Expression::make_error(this->location());
7232 }
7233
047cff81
ILT
7234 bool have_big_args = false;
7235 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7236 int uintptr_bits = uintptr_type->integer_type()->bits();
7237
69d8df44
ILT
7238 Type_context int_context(Type::lookup_integer_type("int"), false);
7239
3b8dffe7
ILT
7240 ++parg;
7241 Expression* len_arg;
7242 if (parg == args->end())
7243 {
7244 if (is_slice)
7245 {
7246 this->report_error(_("length required when allocating a slice"));
7247 return Expression::make_error(this->location());
7248 }
7249
7250 mpz_t zval;
7251 mpz_init_set_ui(zval, 0);
7252 len_arg = Expression::make_integer(&zval, NULL, loc);
7253 mpz_clear(zval);
7254 }
7255 else
7256 {
7257 len_arg = *parg;
69d8df44 7258 len_arg->determine_type(&int_context);
54d04de7
ILT
7259 if (!this->check_int_value(len_arg, true))
7260 return Expression::make_error(this->location());
047cff81
ILT
7261 if (len_arg->type()->integer_type() != NULL
7262 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7263 have_big_args = true;
3b8dffe7
ILT
7264 ++parg;
7265 }
7266
7267 Expression* cap_arg = NULL;
7268 if (is_slice && parg != args->end())
7269 {
7270 cap_arg = *parg;
69d8df44 7271 cap_arg->determine_type(&int_context);
54d04de7
ILT
7272 if (!this->check_int_value(cap_arg, false))
7273 return Expression::make_error(this->location());
7274
7275 Numeric_constant nclen;
7276 Numeric_constant nccap;
7277 unsigned long vlen;
7278 unsigned long vcap;
7279 if (len_arg->numeric_constant_value(&nclen)
7280 && cap_arg->numeric_constant_value(&nccap)
7281 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7282 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7283 && vlen > vcap)
3b8dffe7 7284 {
54d04de7 7285 this->report_error(_("len larger than cap"));
3b8dffe7
ILT
7286 return Expression::make_error(this->location());
7287 }
54d04de7 7288
047cff81
ILT
7289 if (cap_arg->type()->integer_type() != NULL
7290 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7291 have_big_args = true;
3b8dffe7
ILT
7292 ++parg;
7293 }
7294
7295 if (parg != args->end())
7296 {
7297 this->report_error(_("too many arguments to make"));
7298 return Expression::make_error(this->location());
7299 }
7300
8afa2bfb 7301 Location type_loc = first_arg->location();
3b8dffe7
ILT
7302 Expression* type_arg;
7303 if (is_slice || is_chan)
7304 type_arg = Expression::make_type_descriptor(type, type_loc);
7305 else if (is_map)
7306 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7307 else
7308 go_unreachable();
7309
7310 Expression* call;
7311 if (is_slice)
7312 {
7313 if (cap_arg == NULL)
047cff81
ILT
7314 call = Runtime::make_call((have_big_args
7315 ? Runtime::MAKESLICE1BIG
7316 : Runtime::MAKESLICE1),
7317 loc, 2, type_arg, len_arg);
3b8dffe7 7318 else
047cff81
ILT
7319 call = Runtime::make_call((have_big_args
7320 ? Runtime::MAKESLICE2BIG
7321 : Runtime::MAKESLICE2),
7322 loc, 3, type_arg, len_arg, cap_arg);
3b8dffe7
ILT
7323 }
7324 else if (is_map)
047cff81
ILT
7325 call = Runtime::make_call((have_big_args
7326 ? Runtime::MAKEMAPBIG
7327 : Runtime::MAKEMAP),
7328 loc, 2, type_arg, len_arg);
3b8dffe7 7329 else if (is_chan)
047cff81
ILT
7330 call = Runtime::make_call((have_big_args
7331 ? Runtime::MAKECHANBIG
7332 : Runtime::MAKECHAN),
7333 loc, 2, type_arg, len_arg);
3b8dffe7
ILT
7334 else
7335 go_unreachable();
7336
7337 return Expression::make_unsafe_cast(type, call, loc);
7338}
7339
7340// Return whether an expression has an integer value. Report an error
7341// if not. This is used when handling calls to the predeclared make
7342// function.
7343
7344bool
54d04de7 7345Builtin_call_expression::check_int_value(Expression* e, bool is_length)
3b8dffe7 7346{
5caf63ca 7347 Numeric_constant nc;
54d04de7 7348 if (e->numeric_constant_value(&nc))
3b8dffe7 7349 {
54d04de7
ILT
7350 unsigned long v;
7351 switch (nc.to_unsigned_long(&v))
7352 {
7353 case Numeric_constant::NC_UL_VALID:
d6394e2b 7354 break;
54d04de7
ILT
7355 case Numeric_constant::NC_UL_NOTINT:
7356 error_at(e->location(), "non-integer %s argument to make",
7357 is_length ? "len" : "cap");
7358 return false;
7359 case Numeric_constant::NC_UL_NEGATIVE:
7360 error_at(e->location(), "negative %s argument to make",
7361 is_length ? "len" : "cap");
7362 return false;
7363 case Numeric_constant::NC_UL_BIG:
7364 // We don't want to give a compile-time error for a 64-bit
7365 // value on a 32-bit target.
d6394e2b 7366 break;
54d04de7 7367 }
d6394e2b
ILT
7368
7369 mpz_t val;
7370 if (!nc.to_int(&val))
7371 go_unreachable();
7372 int bits = mpz_sizeinbase(val, 2);
7373 mpz_clear(val);
7374 Type* int_type = Type::lookup_integer_type("int");
7375 if (bits >= int_type->integer_type()->bits())
7376 {
7377 error_at(e->location(), "%s argument too large for make",
7378 is_length ? "len" : "cap");
7379 return false;
7380 }
7381
7382 return true;
3b8dffe7
ILT
7383 }
7384
54d04de7
ILT
7385 if (e->type()->integer_type() != NULL)
7386 return true;
7387
7388 error_at(e->location(), "non-integer %s argument to make",
7389 is_length ? "len" : "cap");
3b8dffe7
ILT
7390 return false;
7391}
7392
7a938933
ILT
7393// Return the type of the real or imag functions, given the type of
7394// the argument. We need to map complex to float, complex64 to
7395// float32, and complex128 to float64, so it has to be done by name.
7396// This returns NULL if it can't figure out the type.
7397
7398Type*
7399Builtin_call_expression::real_imag_type(Type* arg_type)
7400{
7401 if (arg_type == NULL || arg_type->is_abstract())
7402 return NULL;
7403 Named_type* nt = arg_type->named_type();
7404 if (nt == NULL)
7405 return NULL;
7406 while (nt->real_type()->named_type() != NULL)
7407 nt = nt->real_type()->named_type();
ff5f50c5 7408 if (nt->name() == "complex64")
7a938933
ILT
7409 return Type::lookup_float_type("float32");
7410 else if (nt->name() == "complex128")
7411 return Type::lookup_float_type("float64");
7412 else
7413 return NULL;
7414}
7415
ff5f50c5 7416// Return the type of the complex function, given the type of one of the
7a938933
ILT
7417// argments. Like real_imag_type, we have to map by name.
7418
7419Type*
ff5f50c5 7420Builtin_call_expression::complex_type(Type* arg_type)
7a938933
ILT
7421{
7422 if (arg_type == NULL || arg_type->is_abstract())
7423 return NULL;
7424 Named_type* nt = arg_type->named_type();
7425 if (nt == NULL)
7426 return NULL;
7427 while (nt->real_type()->named_type() != NULL)
7428 nt = nt->real_type()->named_type();
ff5f50c5 7429 if (nt->name() == "float32")
7a938933
ILT
7430 return Type::lookup_complex_type("complex64");
7431 else if (nt->name() == "float64")
7432 return Type::lookup_complex_type("complex128");
7433 else
7434 return NULL;
7435}
7436
7437// Return a single argument, or NULL if there isn't one.
7438
7439Expression*
7440Builtin_call_expression::one_arg() const
7441{
7442 const Expression_list* args = this->args();
2e540b50 7443 if (args == NULL || args->size() != 1)
7a938933
ILT
7444 return NULL;
7445 return args->front();
7446}
7447
211993b3
ILT
7448// A traversal class which looks for a call or receive expression.
7449
7450class Find_call_expression : public Traverse
7451{
7452 public:
7453 Find_call_expression()
7454 : Traverse(traverse_expressions),
7455 found_(false)
7456 { }
7457
7458 int
7459 expression(Expression**);
7460
7461 bool
7462 found()
7463 { return this->found_; }
7464
7465 private:
7466 bool found_;
7467};
7468
7469int
7470Find_call_expression::expression(Expression** pexpr)
7471{
7472 if ((*pexpr)->call_expression() != NULL
7473 || (*pexpr)->receive_expression() != NULL)
7474 {
7475 this->found_ = true;
7476 return TRAVERSE_EXIT;
7477 }
7478 return TRAVERSE_CONTINUE;
7479}
7480
7481// Return whether this is constant: len of a string constant, or len
7482// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7483// unsafe.Alignof.
7a938933
ILT
7484
7485bool
7486Builtin_call_expression::do_is_constant() const
7487{
d6218114
ILT
7488 if (this->is_error_expression())
7489 return true;
7a938933
ILT
7490 switch (this->code_)
7491 {
7492 case BUILTIN_LEN:
7493 case BUILTIN_CAP:
7494 {
ab9d6dcf
ILT
7495 if (this->seen_)
7496 return false;
7497
7a938933
ILT
7498 Expression* arg = this->one_arg();
7499 if (arg == NULL)
7500 return false;
7501 Type* arg_type = arg->type();
7502
7503 if (arg_type->points_to() != NULL
7504 && arg_type->points_to()->array_type() != NULL
b7190f2f 7505 && !arg_type->points_to()->is_slice_type())
7a938933
ILT
7506 arg_type = arg_type->points_to();
7507
211993b3
ILT
7508 // The len and cap functions are only constant if there are no
7509 // function calls or channel operations in the arguments.
7510 // Otherwise we have to make the call.
7511 if (!arg->is_constant())
7512 {
7513 Find_call_expression find_call;
7514 Expression::traverse(&arg, &find_call);
7515 if (find_call.found())
7516 return false;
7517 }
7518
7a938933
ILT
7519 if (arg_type->array_type() != NULL
7520 && arg_type->array_type()->length() != NULL)
ab9d6dcf 7521 return true;
7a938933
ILT
7522
7523 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
ab9d6dcf
ILT
7524 {
7525 this->seen_ = true;
7526 bool ret = arg->is_constant();
7527 this->seen_ = false;
7528 return ret;
7529 }
7a938933
ILT
7530 }
7531 break;
7532
7533 case BUILTIN_SIZEOF:
7534 case BUILTIN_ALIGNOF:
7535 return this->one_arg() != NULL;
7536
7537 case BUILTIN_OFFSETOF:
7538 {
7539 Expression* arg = this->one_arg();
7540 if (arg == NULL)
7541 return false;
7542 return arg->field_reference_expression() != NULL;
7543 }
7544
ff5f50c5 7545 case BUILTIN_COMPLEX:
7a938933
ILT
7546 {
7547 const Expression_list* args = this->args();
7548 if (args != NULL && args->size() == 2)
7549 return args->front()->is_constant() && args->back()->is_constant();
7550 }
7551 break;
7552
7553 case BUILTIN_REAL:
7554 case BUILTIN_IMAG:
7555 {
7556 Expression* arg = this->one_arg();
7557 return arg != NULL && arg->is_constant();
7558 }
7559
7560 default:
7561 break;
7562 }
7563
7564 return false;
7565}
7566
5caf63ca 7567// Return a numeric constant if possible.
7a938933
ILT
7568
7569bool
5caf63ca 7570Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7a938933
ILT
7571{
7572 if (this->code_ == BUILTIN_LEN
7573 || this->code_ == BUILTIN_CAP)
7574 {
7575 Expression* arg = this->one_arg();
7576 if (arg == NULL)
7577 return false;
7578 Type* arg_type = arg->type();
7579
7580 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7581 {
7582 std::string sval;
7583 if (arg->string_constant_value(&sval))
7584 {
5caf63ca
ILT
7585 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7586 sval.length());
7a938933
ILT
7587 return true;
7588 }
7589 }
7590
7591 if (arg_type->points_to() != NULL
7592 && arg_type->points_to()->array_type() != NULL
b7190f2f 7593 && !arg_type->points_to()->is_slice_type())
7a938933
ILT
7594 arg_type = arg_type->points_to();
7595
7596 if (arg_type->array_type() != NULL
7597 && arg_type->array_type()->length() != NULL)
7598 {
ab9d6dcf
ILT
7599 if (this->seen_)
7600 return false;
7a938933 7601 Expression* e = arg_type->array_type()->length();
ab9d6dcf 7602 this->seen_ = true;
5caf63ca 7603 bool r = e->numeric_constant_value(nc);
ab9d6dcf
ILT
7604 this->seen_ = false;
7605 if (r)
7a938933 7606 {
5caf63ca
ILT
7607 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7608 this->location()))
7609 r = false;
7a938933 7610 }
5caf63ca 7611 return r;
7a938933
ILT
7612 }
7613 }
7614 else if (this->code_ == BUILTIN_SIZEOF
7615 || this->code_ == BUILTIN_ALIGNOF)
7616 {
7617 Expression* arg = this->one_arg();
7618 if (arg == NULL)
7619 return false;
7620 Type* arg_type = arg->type();
02ed921a 7621 if (arg_type->is_error())
7a938933
ILT
7622 return false;
7623 if (arg_type->is_abstract())
7624 return false;
7035307e
CM
7625 if (this->seen_)
7626 return false;
ef1ed13d
ILT
7627
7628 unsigned int ret;
7a938933
ILT
7629 if (this->code_ == BUILTIN_SIZEOF)
7630 {
7035307e
CM
7631 this->seen_ = true;
7632 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7633 this->seen_ = false;
7634 if (!ok)
7a938933
ILT
7635 return false;
7636 }
7637 else if (this->code_ == BUILTIN_ALIGNOF)
7638 {
7035307e
CM
7639 bool ok;
7640 this->seen_ = true;
3dcdeeb2 7641 if (arg->field_reference_expression() == NULL)
7035307e 7642 ok = arg_type->backend_type_align(this->gogo_, &ret);
3dcdeeb2 7643 else
7a938933
ILT
7644 {
7645 // Calling unsafe.Alignof(s.f) returns the alignment of
7646 // the type of f when it is used as a field in a struct.
7035307e 7647 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7a938933 7648 }
7035307e
CM
7649 this->seen_ = false;
7650 if (!ok)
7651 return false;
7a938933
ILT
7652 }
7653 else
8c0d1865 7654 go_unreachable();
ef1ed13d 7655
a0c8ad3b
ILT
7656 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7657 static_cast<unsigned long>(ret));
7a938933
ILT
7658 return true;
7659 }
7660 else if (this->code_ == BUILTIN_OFFSETOF)
7661 {
7662 Expression* arg = this->one_arg();
7663 if (arg == NULL)
7664 return false;
7665 Field_reference_expression* farg = arg->field_reference_expression();
7666 if (farg == NULL)
7667 return false;
7035307e
CM
7668 if (this->seen_)
7669 return false;
7670
51b08ada
ILT
7671 unsigned int total_offset = 0;
7672 while (true)
7673 {
7674 Expression* struct_expr = farg->expr();
7675 Type* st = struct_expr->type();
7676 if (st->struct_type() == NULL)
7677 return false;
7678 if (st->named_type() != NULL)
7679 st->named_type()->convert(this->gogo_);
7680 unsigned int offset;
7035307e
CM
7681 this->seen_ = true;
7682 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7683 farg->field_index(),
7684 &offset);
7685 this->seen_ = false;
7686 if (!ok)
7687 return false;
51b08ada
ILT
7688 total_offset += offset;
7689 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7690 {
7691 // Go up until we reach the original base.
7692 farg = struct_expr->field_reference_expression();
7693 continue;
7694 }
7695 break;
7696 }
a0c8ad3b 7697 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
51b08ada 7698 static_cast<unsigned long>(total_offset));
7a938933
ILT
7699 return true;
7700 }
5caf63ca 7701 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7a938933
ILT
7702 {
7703 Expression* arg = this->one_arg();
7704 if (arg == NULL)
7705 return false;
7706
5caf63ca
ILT
7707 Numeric_constant argnc;
7708 if (!arg->numeric_constant_value(&argnc))
7709 return false;
7710
7a938933
ILT
7711 mpfr_t real;
7712 mpfr_t imag;
5caf63ca
ILT
7713 if (!argnc.to_complex(&real, &imag))
7714 return false;
7a938933 7715
5caf63ca
ILT
7716 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7717 if (this->code_ == BUILTIN_REAL)
7718 nc->set_float(type, real);
7719 else
7720 nc->set_float(type, imag);
7721 return true;
7a938933 7722 }
5caf63ca 7723 else if (this->code_ == BUILTIN_COMPLEX)
7a938933
ILT
7724 {
7725 const Expression_list* args = this->args();
7726 if (args == NULL || args->size() != 2)
7727 return false;
7728
5caf63ca
ILT
7729 Numeric_constant rnc;
7730 if (!args->front()->numeric_constant_value(&rnc))
7731 return false;
7732 Numeric_constant inc;
7733 if (!args->back()->numeric_constant_value(&inc))
7734 return false;
7735
7736 if (rnc.type() != NULL
7737 && !rnc.type()->is_abstract()
7738 && inc.type() != NULL
7739 && !inc.type()->is_abstract()
7740 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7741 return false;
7742
7a938933 7743 mpfr_t r;
5caf63ca
ILT
7744 if (!rnc.to_float(&r))
7745 return false;
7746 mpfr_t i;
7747 if (!inc.to_float(&i))
7a938933
ILT
7748 {
7749 mpfr_clear(r);
7750 return false;
7751 }
7752
5caf63ca
ILT
7753 Type* arg_type = rnc.type();
7754 if (arg_type == NULL || arg_type->is_abstract())
7755 arg_type = inc.type();
7a938933 7756
5caf63ca
ILT
7757 Type* type = Builtin_call_expression::complex_type(arg_type);
7758 nc->set_complex(type, r, i);
7a938933
ILT
7759
7760 mpfr_clear(r);
7761 mpfr_clear(i);
7762
5caf63ca 7763 return true;
7a938933
ILT
7764 }
7765
7766 return false;
7767}
7768
3c365907
ILT
7769// Give an error if we are discarding the value of an expression which
7770// should not normally be discarded. We don't give an error for
7771// discarding the value of an ordinary function call, but we do for
7772// builtin functions, purely for consistency with the gc compiler.
7773
3f7af571 7774bool
3c365907
ILT
7775Builtin_call_expression::do_discarding_value()
7776{
7777 switch (this->code_)
7778 {
7779 case BUILTIN_INVALID:
7780 default:
7781 go_unreachable();
7782
7783 case BUILTIN_APPEND:
7784 case BUILTIN_CAP:
7785 case BUILTIN_COMPLEX:
7786 case BUILTIN_IMAG:
7787 case BUILTIN_LEN:
7788 case BUILTIN_MAKE:
7789 case BUILTIN_NEW:
7790 case BUILTIN_REAL:
7791 case BUILTIN_ALIGNOF:
7792 case BUILTIN_OFFSETOF:
7793 case BUILTIN_SIZEOF:
7794 this->unused_value_error();
3f7af571 7795 return false;
3c365907
ILT
7796
7797 case BUILTIN_CLOSE:
7798 case BUILTIN_COPY:
f29ce5f5 7799 case BUILTIN_DELETE:
3c365907
ILT
7800 case BUILTIN_PANIC:
7801 case BUILTIN_PRINT:
7802 case BUILTIN_PRINTLN:
7803 case BUILTIN_RECOVER:
3f7af571 7804 return true;
3c365907
ILT
7805 }
7806}
7807
7a938933
ILT
7808// Return the type.
7809
7810Type*
7811Builtin_call_expression::do_type()
7812{
7813 switch (this->code_)
7814 {
7815 case BUILTIN_INVALID:
7816 default:
8c0d1865 7817 go_unreachable();
7a938933
ILT
7818
7819 case BUILTIN_NEW:
7820 case BUILTIN_MAKE:
7821 {
7822 const Expression_list* args = this->args();
7823 if (args == NULL || args->empty())
7824 return Type::make_error_type();
7825 return Type::make_pointer_type(args->front()->type());
7826 }
7827
7828 case BUILTIN_CAP:
7829 case BUILTIN_COPY:
7830 case BUILTIN_LEN:
a0c8ad3b
ILT
7831 return Type::lookup_integer_type("int");
7832
7a938933
ILT
7833 case BUILTIN_ALIGNOF:
7834 case BUILTIN_OFFSETOF:
7835 case BUILTIN_SIZEOF:
a0c8ad3b 7836 return Type::lookup_integer_type("uintptr");
7a938933
ILT
7837
7838 case BUILTIN_CLOSE:
f29ce5f5 7839 case BUILTIN_DELETE:
7a938933
ILT
7840 case BUILTIN_PANIC:
7841 case BUILTIN_PRINT:
7842 case BUILTIN_PRINTLN:
7843 return Type::make_void_type();
7844
7a938933 7845 case BUILTIN_RECOVER:
7c0434e5 7846 return Type::make_empty_interface_type(Linemap::predeclared_location());
7a938933
ILT
7847
7848 case BUILTIN_APPEND:
7849 {
7850 const Expression_list* args = this->args();
7851 if (args == NULL || args->empty())
7852 return Type::make_error_type();
3a24b265
ILT
7853 Type *ret = args->front()->type();
7854 if (!ret->is_slice_type())
7855 return Type::make_error_type();
7856 return ret;
7a938933
ILT
7857 }
7858
7859 case BUILTIN_REAL:
7860 case BUILTIN_IMAG:
7861 {
7862 Expression* arg = this->one_arg();
7863 if (arg == NULL)
7864 return Type::make_error_type();
7865 Type* t = arg->type();
7866 if (t->is_abstract())
7867 t = t->make_non_abstract_type();
7868 t = Builtin_call_expression::real_imag_type(t);
7869 if (t == NULL)
7870 t = Type::make_error_type();
7871 return t;
7872 }
7873
ff5f50c5 7874 case BUILTIN_COMPLEX:
7a938933
ILT
7875 {
7876 const Expression_list* args = this->args();
7877 if (args == NULL || args->size() != 2)
7878 return Type::make_error_type();
7879 Type* t = args->front()->type();
7880 if (t->is_abstract())
7881 {
7882 t = args->back()->type();
7883 if (t->is_abstract())
7884 t = t->make_non_abstract_type();
7885 }
ff5f50c5 7886 t = Builtin_call_expression::complex_type(t);
7a938933
ILT
7887 if (t == NULL)
7888 t = Type::make_error_type();
7889 return t;
7890 }
7891 }
7892}
7893
7894// Determine the type.
7895
7896void
7897Builtin_call_expression::do_determine_type(const Type_context* context)
7898{
20532210
ILT
7899 if (!this->determining_types())
7900 return;
7901
7a938933
ILT
7902 this->fn()->determine_type_no_context();
7903
7904 const Expression_list* args = this->args();
7905
7906 bool is_print;
7907 Type* arg_type = NULL;
7908 switch (this->code_)
7909 {
7910 case BUILTIN_PRINT:
7911 case BUILTIN_PRINTLN:
7912 // Do not force a large integer constant to "int".
7913 is_print = true;
7914 break;
7915
7916 case BUILTIN_REAL:
7917 case BUILTIN_IMAG:
ff5f50c5 7918 arg_type = Builtin_call_expression::complex_type(context->type);
69d8df44
ILT
7919 if (arg_type == NULL)
7920 arg_type = Type::lookup_complex_type("complex128");
7a938933
ILT
7921 is_print = false;
7922 break;
7923
ff5f50c5 7924 case BUILTIN_COMPLEX:
7a938933 7925 {
ff5f50c5 7926 // For the complex function the type of one operand can
7a938933
ILT
7927 // determine the type of the other, as in a binary expression.
7928 arg_type = Builtin_call_expression::real_imag_type(context->type);
69d8df44
ILT
7929 if (arg_type == NULL)
7930 arg_type = Type::lookup_float_type("float64");
7a938933
ILT
7931 if (args != NULL && args->size() == 2)
7932 {
7933 Type* t1 = args->front()->type();
a7a90456 7934 Type* t2 = args->back()->type();
7a938933
ILT
7935 if (!t1->is_abstract())
7936 arg_type = t1;
7937 else if (!t2->is_abstract())
7938 arg_type = t2;
7939 }
7940 is_print = false;
7941 }
7942 break;
7943
7944 default:
7945 is_print = false;
7946 break;
7947 }
7948
7949 if (args != NULL)
7950 {
7951 for (Expression_list::const_iterator pa = args->begin();
7952 pa != args->end();
7953 ++pa)
7954 {
7955 Type_context subcontext;
7956 subcontext.type = arg_type;
7957
7958 if (is_print)
7959 {
7960 // We want to print large constants, we so can't just
7961 // use the appropriate nonabstract type. Use uint64 for
7962 // an integer if we know it is nonnegative, otherwise
7963 // use int64 for a integer, otherwise use float64 for a
7964 // float or complex128 for a complex.
7965 Type* want_type = NULL;
7966 Type* atype = (*pa)->type();
7967 if (atype->is_abstract())
7968 {
7969 if (atype->integer_type() != NULL)
7970 {
5caf63ca
ILT
7971 Numeric_constant nc;
7972 if (this->numeric_constant_value(&nc))
7973 {
7974 mpz_t val;
7975 if (nc.to_int(&val))
7976 {
7977 if (mpz_sgn(val) >= 0)
7978 want_type = Type::lookup_integer_type("uint64");
7979 mpz_clear(val);
7980 }
7981 }
7982 if (want_type == NULL)
7a938933 7983 want_type = Type::lookup_integer_type("int64");
7a938933
ILT
7984 }
7985 else if (atype->float_type() != NULL)
7986 want_type = Type::lookup_float_type("float64");
7987 else if (atype->complex_type() != NULL)
7988 want_type = Type::lookup_complex_type("complex128");
7989 else if (atype->is_abstract_string_type())
7990 want_type = Type::lookup_string_type();
7991 else if (atype->is_abstract_boolean_type())
7992 want_type = Type::lookup_bool_type();
7993 else
8c0d1865 7994 go_unreachable();
7a938933
ILT
7995 subcontext.type = want_type;
7996 }
7997 }
7998
7999 (*pa)->determine_type(&subcontext);
8000 }
8001 }
8002}
8003
8004// If there is exactly one argument, return true. Otherwise give an
8005// error message and return false.
8006
8007bool
8008Builtin_call_expression::check_one_arg()
8009{
8010 const Expression_list* args = this->args();
8011 if (args == NULL || args->size() < 1)
8012 {
8013 this->report_error(_("not enough arguments"));
8014 return false;
8015 }
8016 else if (args->size() > 1)
8017 {
8018 this->report_error(_("too many arguments"));
8019 return false;
8020 }
8021 if (args->front()->is_error_expression()
02ed921a 8022 || args->front()->type()->is_error())
7a938933
ILT
8023 {
8024 this->set_is_error();
8025 return false;
8026 }
8027 return true;
8028}
8029
8030// Check argument types for a builtin function.
8031
8032void
8033Builtin_call_expression::do_check_types(Gogo*)
8034{
552ab977
ILT
8035 if (this->is_error_expression())
8036 return;
7a938933
ILT
8037 switch (this->code_)
8038 {
8039 case BUILTIN_INVALID:
8040 case BUILTIN_NEW:
8041 case BUILTIN_MAKE:
9b83b6d2 8042 case BUILTIN_DELETE:
7a938933
ILT
8043 return;
8044
8045 case BUILTIN_LEN:
8046 case BUILTIN_CAP:
8047 {
8048 // The single argument may be either a string or an array or a
8049 // map or a channel, or a pointer to a closed array.
8050 if (this->check_one_arg())
8051 {
8052 Type* arg_type = this->one_arg()->type();
8053 if (arg_type->points_to() != NULL
8054 && arg_type->points_to()->array_type() != NULL
b7190f2f 8055 && !arg_type->points_to()->is_slice_type())
7a938933
ILT
8056 arg_type = arg_type->points_to();
8057 if (this->code_ == BUILTIN_CAP)
8058 {
02ed921a 8059 if (!arg_type->is_error()
7a938933
ILT
8060 && arg_type->array_type() == NULL
8061 && arg_type->channel_type() == NULL)
8062 this->report_error(_("argument must be array or slice "
8063 "or channel"));
8064 }
8065 else
8066 {
02ed921a 8067 if (!arg_type->is_error()
7a938933
ILT
8068 && !arg_type->is_string_type()
8069 && arg_type->array_type() == NULL
8070 && arg_type->map_type() == NULL
8071 && arg_type->channel_type() == NULL)
8072 this->report_error(_("argument must be string or "
8073 "array or slice or map or channel"));
8074 }
8075 }
8076 }
8077 break;
8078
8079 case BUILTIN_PRINT:
8080 case BUILTIN_PRINTLN:
8081 {
8082 const Expression_list* args = this->args();
8083 if (args == NULL)
8084 {
8085 if (this->code_ == BUILTIN_PRINT)
8086 warning_at(this->location(), 0,
8087 "no arguments for builtin function %<%s%>",
8088 (this->code_ == BUILTIN_PRINT
8089 ? "print"
8090 : "println"));
8091 }
8092 else
8093 {
8094 for (Expression_list::const_iterator p = args->begin();
8095 p != args->end();
8096 ++p)
8097 {
8098 Type* type = (*p)->type();
02ed921a 8099 if (type->is_error()
7a938933
ILT
8100 || type->is_string_type()
8101 || type->integer_type() != NULL
8102 || type->float_type() != NULL
8103 || type->complex_type() != NULL
8104 || type->is_boolean_type()
8105 || type->points_to() != NULL
8106 || type->interface_type() != NULL
8107 || type->channel_type() != NULL
8108 || type->map_type() != NULL
8109 || type->function_type() != NULL
b7190f2f 8110 || type->is_slice_type())
7a938933 8111 ;
d4157849
ILT
8112 else if ((*p)->is_type_expression())
8113 {
8114 // If this is a type expression it's going to give
8115 // an error anyhow, so we don't need one here.
8116 }
7a938933
ILT
8117 else
8118 this->report_error(_("unsupported argument type to "
8119 "builtin function"));
8120 }
8121 }
8122 }
8123 break;
8124
8125 case BUILTIN_CLOSE:
7a938933
ILT
8126 if (this->check_one_arg())
8127 {
8128 if (this->one_arg()->type()->channel_type() == NULL)
8129 this->report_error(_("argument must be channel"));
09367c0d
ILT
8130 else if (!this->one_arg()->type()->channel_type()->may_send())
8131 this->report_error(_("cannot close receive-only channel"));
7a938933
ILT
8132 }
8133 break;
8134
8135 case BUILTIN_PANIC:
8136 case BUILTIN_SIZEOF:
8137 case BUILTIN_ALIGNOF:
8138 this->check_one_arg();
8139 break;
8140
8141 case BUILTIN_RECOVER:
8142 if (this->args() != NULL && !this->args()->empty())
8143 this->report_error(_("too many arguments"));
8144 break;
8145
8146 case BUILTIN_OFFSETOF:
8147 if (this->check_one_arg())
8148 {
8149 Expression* arg = this->one_arg();
8150 if (arg->field_reference_expression() == NULL)
8151 this->report_error(_("argument must be a field reference"));
8152 }
8153 break;
8154
8155 case BUILTIN_COPY:
8156 {
8157 const Expression_list* args = this->args();
8158 if (args == NULL || args->size() < 2)
8159 {
8160 this->report_error(_("not enough arguments"));
8161 break;
8162 }
8163 else if (args->size() > 2)
8164 {
8165 this->report_error(_("too many arguments"));
8166 break;
8167 }
8168 Type* arg1_type = args->front()->type();
8169 Type* arg2_type = args->back()->type();
02ed921a 8170 if (arg1_type->is_error() || arg2_type->is_error())
7a938933
ILT
8171 break;
8172
8173 Type* e1;
b7190f2f 8174 if (arg1_type->is_slice_type())
7a938933
ILT
8175 e1 = arg1_type->array_type()->element_type();
8176 else
8177 {
8178 this->report_error(_("left argument must be a slice"));
8179 break;
8180 }
8181
b7190f2f 8182 if (arg2_type->is_slice_type())
7b31a84d
ILT
8183 {
8184 Type* e2 = arg2_type->array_type()->element_type();
8185 if (!Type::are_identical(e1, e2, true, NULL))
8186 this->report_error(_("element types must be the same"));
8187 }
7a938933 8188 else if (arg2_type->is_string_type())
7a938933 8189 {
7b31a84d
ILT
8190 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8191 this->report_error(_("first argument must be []byte"));
7a938933 8192 }
7b31a84d
ILT
8193 else
8194 this->report_error(_("second argument must be slice or string"));
7a938933
ILT
8195 }
8196 break;
8197
8198 case BUILTIN_APPEND:
8199 {
8200 const Expression_list* args = this->args();
d7ab2512 8201 if (args == NULL || args->size() < 2)
7a938933
ILT
8202 {
8203 this->report_error(_("not enough arguments"));
8204 break;
8205 }
7838059f
ILT
8206 if (args->size() > 2)
8207 {
8208 this->report_error(_("too many arguments"));
8209 break;
8210 }
9b83b6d2
ILT
8211 if (args->front()->type()->is_error()
8212 || args->back()->type()->is_error())
8213 break;
8214
8215 Array_type* at = args->front()->type()->array_type();
8216 Type* e = at->element_type();
a1ee0aaf
ILT
8217
8218 // The language permits appending a string to a []byte, as a
8219 // special case.
8220 if (args->back()->type()->is_string_type())
8221 {
7b31a84d 8222 if (e->integer_type() != NULL && e->integer_type()->is_byte())
a1ee0aaf
ILT
8223 break;
8224 }
8225
80678229
ILT
8226 // The language says that the second argument must be
8227 // assignable to a slice of the element type of the first
8228 // argument. We already know the first argument is a slice
8229 // type.
9b83b6d2 8230 Type* arg2_type = Type::make_array_type(e, NULL);
7a938933 8231 std::string reason;
80678229 8232 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7a938933
ILT
8233 {
8234 if (reason.empty())
80678229 8235 this->report_error(_("argument 2 has invalid type"));
7a938933
ILT
8236 else
8237 {
80678229 8238 error_at(this->location(), "argument 2 has invalid type (%s)",
7a938933
ILT
8239 reason.c_str());
8240 this->set_is_error();
8241 }
8242 }
8243 break;
8244 }
8245
8246 case BUILTIN_REAL:
8247 case BUILTIN_IMAG:
8248 if (this->check_one_arg())
8249 {
8250 if (this->one_arg()->type()->complex_type() == NULL)
8251 this->report_error(_("argument must have complex type"));
8252 }
8253 break;
8254
ff5f50c5 8255 case BUILTIN_COMPLEX:
7a938933
ILT
8256 {
8257 const Expression_list* args = this->args();
8258 if (args == NULL || args->size() < 2)
8259 this->report_error(_("not enough arguments"));
8260 else if (args->size() > 2)
8261 this->report_error(_("too many arguments"));
8262 else if (args->front()->is_error_expression()
02ed921a 8263 || args->front()->type()->is_error()
7a938933 8264 || args->back()->is_error_expression()
02ed921a 8265 || args->back()->type()->is_error())
7a938933
ILT
8266 this->set_is_error();
8267 else if (!Type::are_identical(args->front()->type(),
50ba28bb 8268 args->back()->type(), true, NULL))
ff5f50c5 8269 this->report_error(_("complex arguments must have identical types"));
7a938933 8270 else if (args->front()->type()->float_type() == NULL)
ff5f50c5 8271 this->report_error(_("complex arguments must have "
7a938933
ILT
8272 "floating-point type"));
8273 }
8274 break;
8275
8276 default:
8c0d1865 8277 go_unreachable();
7a938933
ILT
8278 }
8279}
8280
8281// Return the tree for a builtin function.
8282
8283tree
8284Builtin_call_expression::do_get_tree(Translate_context* context)
8285{
8286 Gogo* gogo = context->gogo();
8afa2bfb 8287 Location location = this->location();
7a938933
ILT
8288 switch (this->code_)
8289 {
8290 case BUILTIN_INVALID:
8291 case BUILTIN_NEW:
8292 case BUILTIN_MAKE:
8c0d1865 8293 go_unreachable();
7a938933
ILT
8294
8295 case BUILTIN_LEN:
8296 case BUILTIN_CAP:
8297 {
8298 const Expression_list* args = this->args();
26409c52 8299 go_assert(args != NULL && args->size() == 1);
7035307e 8300 Expression* arg = args->front();
7a938933 8301 Type* arg_type = arg->type();
ab9d6dcf
ILT
8302
8303 if (this->seen_)
8304 {
26409c52 8305 go_assert(saw_errors());
ab9d6dcf
ILT
8306 return error_mark_node;
8307 }
8308 this->seen_ = true;
ab9d6dcf 8309 this->seen_ = false;
7a938933
ILT
8310 if (arg_type->points_to() != NULL)
8311 {
8312 arg_type = arg_type->points_to();
26409c52 8313 go_assert(arg_type->array_type() != NULL
b7190f2f 8314 && !arg_type->is_slice_type());
7035307e 8315 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
7a938933
ILT
8316 }
8317
776f27a6 8318 Type* int_type = Type::lookup_integer_type("int");
7035307e 8319 Expression* val;
7a938933
ILT
8320 if (this->code_ == BUILTIN_LEN)
8321 {
8322 if (arg_type->is_string_type())
7035307e
CM
8323 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8324 location);
7a938933 8325 else if (arg_type->array_type() != NULL)
ab9d6dcf
ILT
8326 {
8327 if (this->seen_)
8328 {
26409c52 8329 go_assert(saw_errors());
ab9d6dcf
ILT
8330 return error_mark_node;
8331 }
8332 this->seen_ = true;
7035307e 8333 val = arg_type->array_type()->get_length(gogo, arg);
ab9d6dcf
ILT
8334 this->seen_ = false;
8335 }
7a938933 8336 else if (arg_type->map_type() != NULL)
7035307e 8337 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
7a938933 8338 else if (arg_type->channel_type() != NULL)
7035307e 8339 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
7a938933 8340 else
8c0d1865 8341 go_unreachable();
7a938933
ILT
8342 }
8343 else
8344 {
8345 if (arg_type->array_type() != NULL)
ab9d6dcf
ILT
8346 {
8347 if (this->seen_)
8348 {
26409c52 8349 go_assert(saw_errors());
ab9d6dcf
ILT
8350 return error_mark_node;
8351 }
8352 this->seen_ = true;
7035307e 8353 val = arg_type->array_type()->get_capacity(gogo, arg);
ab9d6dcf
ILT
8354 this->seen_ = false;
8355 }
7a938933 8356 else if (arg_type->channel_type() != NULL)
7035307e 8357 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
7a938933 8358 else
8c0d1865 8359 go_unreachable();
7a938933
ILT
8360 }
8361
7035307e
CM
8362 return Expression::make_cast(int_type, val,
8363 location)->get_tree(context);
7a938933
ILT
8364 }
8365
8366 case BUILTIN_PRINT:
8367 case BUILTIN_PRINTLN:
8368 {
8369 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7035307e 8370 Expression* print_stmts = NULL;
7a938933
ILT
8371
8372 const Expression_list* call_args = this->args();
8373 if (call_args != NULL)
8374 {
8375 for (Expression_list::const_iterator p = call_args->begin();
8376 p != call_args->end();
8377 ++p)
8378 {
8379 if (is_ln && p != call_args->begin())
8380 {
7035307e
CM
8381 Expression* print_space =
8382 Runtime::make_call(Runtime::PRINT_SPACE,
8383 this->location(), 0);
7a938933 8384
7035307e
CM
8385 print_stmts =
8386 Expression::make_compound(print_stmts, print_space,
8387 location);
8388 }
7a938933 8389
7035307e
CM
8390 Expression* arg = *p;
8391 Type* type = arg->type();
8392 Runtime::Function code;
7a938933 8393 if (type->is_string_type())
7035307e 8394 code = Runtime::PRINT_STRING;
7a938933
ILT
8395 else if (type->integer_type() != NULL
8396 && type->integer_type()->is_unsigned())
8397 {
7a938933 8398 Type* itype = Type::lookup_integer_type("uint64");
7035307e
CM
8399 arg = Expression::make_cast(itype, arg, location);
8400 code = Runtime::PRINT_UINT64;
7a938933
ILT
8401 }
8402 else if (type->integer_type() != NULL)
8403 {
7a938933 8404 Type* itype = Type::lookup_integer_type("int64");
7035307e
CM
8405 arg = Expression::make_cast(itype, arg, location);
8406 code = Runtime::PRINT_INT64;
7a938933
ILT
8407 }
8408 else if (type->float_type() != NULL)
8409 {
7035307e
CM
8410 Type* dtype = Type::lookup_float_type("float64");
8411 arg = Expression::make_cast(dtype, arg, location);
8412 code = Runtime::PRINT_DOUBLE;
7a938933
ILT
8413 }
8414 else if (type->complex_type() != NULL)
8415 {
7035307e
CM
8416 Type* ctype = Type::lookup_complex_type("complex128");
8417 arg = Expression::make_cast(ctype, arg, location);
8418 code = Runtime::PRINT_COMPLEX;
7a938933
ILT
8419 }
8420 else if (type->is_boolean_type())
7035307e 8421 code = Runtime::PRINT_BOOL;
7a938933
ILT
8422 else if (type->points_to() != NULL
8423 || type->channel_type() != NULL
8424 || type->map_type() != NULL
8425 || type->function_type() != NULL)
8426 {
7035307e
CM
8427 arg = Expression::make_cast(type, arg, location);
8428 code = Runtime::PRINT_POINTER;
7a938933
ILT
8429 }
8430 else if (type->interface_type() != NULL)
8431 {
8432 if (type->interface_type()->is_empty())
7035307e 8433 code = Runtime::PRINT_EMPTY_INTERFACE;
7a938933 8434 else
7035307e 8435 code = Runtime::PRINT_INTERFACE;
7a938933 8436 }
b7190f2f 8437 else if (type->is_slice_type())
7035307e 8438 code = Runtime::PRINT_SLICE;
7a938933 8439 else
9b83b6d2
ILT
8440 {
8441 go_assert(saw_errors());
8442 return error_mark_node;
8443 }
7a938933 8444
7035307e
CM
8445 Expression* call = Runtime::make_call(code, location, 1, arg);
8446 if (print_stmts == NULL)
8447 print_stmts = call;
8448 else
8449 print_stmts = Expression::make_compound(print_stmts, call,
8450 location);
7a938933
ILT
8451 }
8452 }
8453
8454 if (is_ln)
8455 {
7035307e
CM
8456 Expression* print_nl =
8457 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8458 if (print_stmts == NULL)
8459 print_stmts = print_nl;
8460 else
8461 print_stmts = Expression::make_compound(print_stmts, print_nl,
8462 location);
7a938933
ILT
8463 }
8464
7035307e 8465 return print_stmts->get_tree(context);
7a938933
ILT
8466 }
8467
8468 case BUILTIN_PANIC:
8469 {
8470 const Expression_list* args = this->args();
26409c52 8471 go_assert(args != NULL && args->size() == 1);
7a938933 8472 Expression* arg = args->front();
8afa2bfb 8473 Type *empty =
7c0434e5 8474 Type::make_empty_interface_type(Linemap::predeclared_location());
7035307e
CM
8475 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8476
8477 Expression* panic =
8478 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8479 return panic->get_tree(context);
7a938933
ILT
8480 }
8481
8482 case BUILTIN_RECOVER:
8483 {
8484 // The argument is set when building recover thunks. It's a
8485 // boolean value which is true if we can recover a value now.
8486 const Expression_list* args = this->args();
26409c52 8487 go_assert(args != NULL && args->size() == 1);
7a938933 8488 Expression* arg = args->front();
8afa2bfb 8489 Type *empty =
7c0434e5 8490 Type::make_empty_interface_type(Linemap::predeclared_location());
7a938933 8491
7a938933 8492 Expression* nil = Expression::make_nil(location);
7035307e 8493 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
7a938933
ILT
8494
8495 // We need to handle a deferred call to recover specially,
8496 // because it changes whether it can recover a panic or not.
8497 // See test7 in test/recover1.go.
7035307e
CM
8498 Expression* recover = Runtime::make_call((this->is_deferred()
8499 ? Runtime::DEFERRED_RECOVER
8500 : Runtime::RECOVER),
8501 location, 0);
8502 Expression* cond =
8503 Expression::make_conditional(arg, recover, nil, location);
8504 return cond->get_tree(context);
7a938933
ILT
8505 }
8506
8507 case BUILTIN_CLOSE:
7a938933
ILT
8508 {
8509 const Expression_list* args = this->args();
26409c52 8510 go_assert(args != NULL && args->size() == 1);
7a938933 8511 Expression* arg = args->front();
7035307e
CM
8512 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8513 1, arg);
8514 return close->get_tree(context);
7a938933
ILT
8515 }
8516
8517 case BUILTIN_SIZEOF:
8518 case BUILTIN_OFFSETOF:
8519 case BUILTIN_ALIGNOF:
8520 {
5caf63ca
ILT
8521 Numeric_constant nc;
8522 unsigned long val;
8523 if (!this->numeric_constant_value(&nc)
8524 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
f315816c 8525 {
26409c52 8526 go_assert(saw_errors());
f315816c
ILT
8527 return error_mark_node;
8528 }
a0c8ad3b 8529 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7035307e
CM
8530 mpz_t ival;
8531 nc.get_int(&ival);
8532 Expression* int_cst =
8533 Expression::make_integer(&ival, uintptr_type, location);
8534 mpz_clear(ival);
8535 return int_cst->get_tree(context);
7a938933
ILT
8536 }
8537
8538 case BUILTIN_COPY:
8539 {
8540 const Expression_list* args = this->args();
26409c52 8541 go_assert(args != NULL && args->size() == 2);
7a938933
ILT
8542 Expression* arg1 = args->front();
8543 Expression* arg2 = args->back();
8544
7a938933
ILT
8545 Type* arg1_type = arg1->type();
8546 Array_type* at = arg1_type->array_type();
6ddb6288 8547 go_assert(arg1->is_variable());
7035307e
CM
8548 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8549 Expression* arg1_len = at->get_length(gogo, arg1);
7a938933
ILT
8550
8551 Type* arg2_type = arg2->type();
7035307e
CM
8552 go_assert(arg2->is_variable());
8553 Expression* arg2_val;
8554 Expression* arg2_len;
b7190f2f 8555 if (arg2_type->is_slice_type())
7a938933
ILT
8556 {
8557 at = arg2_type->array_type();
7035307e
CM
8558 arg2_val = at->get_value_pointer(gogo, arg2);
8559 arg2_len = at->get_length(gogo, arg2);
7a938933
ILT
8560 }
8561 else
8562 {
7035307e
CM
8563 go_assert(arg2->is_variable());
8564 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8565 location);
8566 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8567 location);
7a938933 8568 }
7035307e
CM
8569 Expression* cond =
8570 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8571 Expression* length =
8572 Expression::make_conditional(cond, arg1_len, arg2_len, location);
7a938933
ILT
8573
8574 Type* element_type = at->element_type();
5b735706 8575 Btype* element_btype = element_type->get_backend(gogo);
7a938933 8576
7035307e
CM
8577 mpz_t size;
8578 size_t element_size = gogo->backend()->type_size(element_btype);
8579 mpz_init_set_ui(size, element_size);
8580 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8581 mpz_clear(size);
8582
8583 Expression* bytecount =
8584 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8585 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8586 arg1_val, arg2_val, bytecount);
8587
8588 Expression* compound = Expression::make_compound(copy, length, location);
8589 return compound->get_tree(context);
7a938933
ILT
8590 }
8591
8592 case BUILTIN_APPEND:
8593 {
8594 const Expression_list* args = this->args();
26409c52 8595 go_assert(args != NULL && args->size() == 2);
7a938933
ILT
8596 Expression* arg1 = args->front();
8597 Expression* arg2 = args->back();
8598
c7f15f80 8599 Array_type* at = arg1->type()->array_type();
a1ee0aaf 8600 Type* element_type = at->element_type()->forwarded();
c7f15f80 8601
7035307e
CM
8602 go_assert(arg2->is_variable());
8603 Expression* arg2_val;
8604 Expression* arg2_len;
8605 mpz_t size;
a1ee0aaf 8606 if (arg2->type()->is_string_type()
7b31a84d
ILT
8607 && element_type->integer_type() != NULL
8608 && element_type->integer_type()->is_byte())
a1ee0aaf 8609 {
7035307e
CM
8610 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8611 location);
8612 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8613 location);
8614 mpz_init_set_ui(size, 1UL);
a1ee0aaf
ILT
8615 }
8616 else
8617 {
7035307e
CM
8618 arg2_val = at->get_value_pointer(gogo, arg2);
8619 arg2_len = at->get_length(gogo, arg2);
6ddb6288 8620 Btype* element_btype = element_type->get_backend(gogo);
7035307e
CM
8621 size_t element_size = gogo->backend()->type_size(element_btype);
8622 mpz_init_set_ui(size, element_size);
a1ee0aaf 8623 }
7035307e
CM
8624 Expression* element_size =
8625 Expression::make_integer(&size, NULL, location);
8626 mpz_clear(size);
8627
8628 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8629 arg1, arg2_val, arg2_len,
8630 element_size);
8631 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8632 return append->get_tree(context);
7a938933
ILT
8633 }
8634
8635 case BUILTIN_REAL:
8636 case BUILTIN_IMAG:
8637 {
8638 const Expression_list* args = this->args();
26409c52 8639 go_assert(args != NULL && args->size() == 1);
7a938933 8640 Expression* arg = args->front();
7035307e
CM
8641
8642 Bexpression* ret;
8643 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8644 if (this->code_ == BUILTIN_REAL)
8645 ret = gogo->backend()->real_part_expression(bcomplex, location);
8646 else
8647 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8648 return expr_to_tree(ret);
7a938933
ILT
8649 }
8650
ff5f50c5 8651 case BUILTIN_COMPLEX:
7a938933
ILT
8652 {
8653 const Expression_list* args = this->args();
26409c52 8654 go_assert(args != NULL && args->size() == 2);
7035307e
CM
8655 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8656 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8657 Bexpression* ret =
8658 gogo->backend()->complex_expression(breal, bimag, location);
8659 return expr_to_tree(ret);
7a938933
ILT
8660 }
8661
8662 default:
8c0d1865 8663 go_unreachable();
7a938933
ILT
8664 }
8665}
8666
8667// We have to support exporting a builtin call expression, because
8668// code can set a constant to the result of a builtin expression.
8669
8670void
8671Builtin_call_expression::do_export(Export* exp) const
8672{
5caf63ca
ILT
8673 Numeric_constant nc;
8674 if (!this->numeric_constant_value(&nc))
8675 {
8676 error_at(this->location(), "value is not constant");
8677 return;
8678 }
7a938933 8679
5caf63ca 8680 if (nc.is_int())
7a938933 8681 {
5caf63ca
ILT
8682 mpz_t val;
8683 nc.get_int(&val);
7a938933 8684 Integer_expression::export_integer(exp, val);
5caf63ca 8685 mpz_clear(val);
7a938933 8686 }
5caf63ca 8687 else if (nc.is_float())
7a938933
ILT
8688 {
8689 mpfr_t fval;
5caf63ca
ILT
8690 nc.get_float(&fval);
8691 Float_expression::export_float(exp, fval);
7a938933
ILT
8692 mpfr_clear(fval);
8693 }
5caf63ca 8694 else if (nc.is_complex())
7a938933
ILT
8695 {
8696 mpfr_t real;
8697 mpfr_t imag;
5caf63ca 8698 Complex_expression::export_complex(exp, real, imag);
7a938933
ILT
8699 mpfr_clear(real);
8700 mpfr_clear(imag);
8701 }
5caf63ca
ILT
8702 else
8703 go_unreachable();
7a938933
ILT
8704
8705 // A trailing space lets us reliably identify the end of the number.
8706 exp->write_c_string(" ");
8707}
8708
8709// Class Call_expression.
8710
fdbc38a6
ILT
8711// A Go function can be viewed in a couple of different ways. The
8712// code of a Go function becomes a backend function with parameters
8713// whose types are simply the backend representation of the Go types.
8714// If there are multiple results, they are returned as a backend
8715// struct.
8716
8717// However, when Go code refers to a function other than simply
8718// calling it, the backend type of that function is actually a struct.
8719// The first field of the struct points to the Go function code
8720// (sometimes a wrapper as described below). The remaining fields
8721// hold addresses of closed-over variables. This struct is called a
8722// closure.
8723
8724// There are a few cases to consider.
8725
8726// A direct function call of a known function in package scope. In
8727// this case there are no closed-over variables, and we know the name
8728// of the function code. We can simply produce a backend call to the
8729// function directly, and not worry about the closure.
8730
8731// A direct function call of a known function literal. In this case
8732// we know the function code and we know the closure. We generate the
8733// function code such that it expects an additional final argument of
8734// the closure type. We pass the closure as the last argument, after
8735// the other arguments.
8736
8737// An indirect function call. In this case we have a closure. We
8738// load the pointer to the function code from the first field of the
8739// closure. We pass the address of the closure as the last argument.
8740
8741// A call to a method of an interface. Type methods are always at
8742// package scope, so we call the function directly, and don't worry
8743// about the closure.
8744
8745// This means that for a function at package scope we have two cases.
8746// One is the direct call, which has no closure. The other is the
8747// indirect call, which does have a closure. We can't simply ignore
8748// the closure, even though it is the last argument, because that will
8749// fail on targets where the function pops its arguments. So when
8750// generating a closure for a package-scope function we set the
8751// function code pointer in the closure to point to a wrapper
8752// function. This wrapper function accepts a final argument that
8753// points to the closure, ignores it, and calls the real function as a
8754// direct function call. This wrapper will normally be efficient, and
8755// can often simply be a tail call to the real function.
8756
8757// We don't use GCC's static chain pointer because 1) we don't need
8758// it; 2) GCC only permits using a static chain to call a known
8759// function, so we can't use it for an indirect call anyhow. Since we
8760// can't use it for an indirect call, we may as well not worry about
8761// using it for a direct call either.
8762
8763// We pass the closure last rather than first because it means that
8764// the function wrapper we put into a closure for a package-scope
8765// function can normally just be a tail call to the real function.
8766
8767// For method expressions we generate a wrapper that loads the
8768// receiver from the closure and then calls the method. This
8769// unfortunately forces reshuffling the arguments, since there is a
8770// new first argument, but we can't avoid reshuffling either for
8771// method expressions or for indirect calls of package-scope
8772// functions, and since the latter are more common we reshuffle for
8773// method expressions.
8774
8775// Note that the Go code retains the Go types. The extra final
8776// argument only appears when we convert to the backend
8777// representation.
8778
7a938933
ILT
8779// Traversal.
8780
8781int
8782Call_expression::do_traverse(Traverse* traverse)
8783{
8784 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8785 return TRAVERSE_EXIT;
8786 if (this->args_ != NULL)
8787 {
8788 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8789 return TRAVERSE_EXIT;
8790 }
8791 return TRAVERSE_CONTINUE;
8792}
8793
8794// Lower a call statement.
8795
8796Expression*
8586635c
ILT
8797Call_expression::do_lower(Gogo* gogo, Named_object* function,
8798 Statement_inserter* inserter, int)
7a938933 8799{
8afa2bfb 8800 Location loc = this->location();
1bbf7edb 8801
8586635c 8802 // A type cast can look like a function call.
7a938933
ILT
8803 if (this->fn_->is_type_expression()
8804 && this->args_ != NULL
8805 && this->args_->size() == 1)
8806 return Expression::make_cast(this->fn_->type(), this->args_->front(),
1bbf7edb 8807 loc);
7a938933 8808
d59a4c82
ILT
8809 // Because do_type will return an error type and thus prevent future
8810 // errors, check for that case now to ensure that the error gets
8811 // reported.
7bacbe5c
ILT
8812 Function_type* fntype = this->get_function_type();
8813 if (fntype == NULL)
d59a4c82
ILT
8814 {
8815 if (!this->fn_->type()->is_error())
8816 this->report_error(_("expected function"));
8817 return Expression::make_error(loc);
8818 }
8819
7a938933
ILT
8820 // Handle an argument which is a call to a function which returns
8821 // multiple results.
8822 if (this->args_ != NULL
8823 && this->args_->size() == 1
7bacbe5c 8824 && this->args_->front()->call_expression() != NULL)
7a938933 8825 {
7a938933
ILT
8826 size_t rc = this->args_->front()->call_expression()->result_count();
8827 if (rc > 1
7bacbe5c
ILT
8828 && ((fntype->parameters() != NULL
8829 && (fntype->parameters()->size() == rc
8830 || (fntype->is_varargs()
8831 && fntype->parameters()->size() - 1 <= rc)))
8832 || fntype->is_builtin()))
7a938933
ILT
8833 {
8834 Call_expression* call = this->args_->front()->call_expression();
8835 Expression_list* args = new Expression_list;
8836 for (size_t i = 0; i < rc; ++i)
8837 args->push_back(Expression::make_call_result(call, i));
8838 // We can't return a new call expression here, because this
01bd5703
ILT
8839 // one may be referenced by Call_result expressions. We
8840 // also can't delete the old arguments, because we may still
8841 // traverse them somewhere up the call stack. FIXME.
7a938933
ILT
8842 this->args_ = args;
8843 }
8844 }
8845
7bacbe5c
ILT
8846 // Recognize a call to a builtin function.
8847 if (fntype->is_builtin())
8848 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8849 this->is_varargs_, loc);
8850
8586635c
ILT
8851 // If this call returns multiple results, create a temporary
8852 // variable for each result.
8853 size_t rc = this->result_count();
8854 if (rc > 1 && this->results_ == NULL)
8855 {
8856 std::vector<Temporary_statement*>* temps =
8857 new std::vector<Temporary_statement*>;
8858 temps->reserve(rc);
7bacbe5c 8859 const Typed_identifier_list* results = fntype->results();
8586635c
ILT
8860 for (Typed_identifier_list::const_iterator p = results->begin();
8861 p != results->end();
8862 ++p)
8863 {
8864 Temporary_statement* temp = Statement::make_temporary(p->type(),
1bbf7edb 8865 NULL, loc);
8586635c
ILT
8866 inserter->insert(temp);
8867 temps->push_back(temp);
8868 }
8869 this->results_ = temps;
8870 }
8871
7a938933
ILT
8872 // Handle a call to a varargs function by packaging up the extra
8873 // parameters.
7bacbe5c 8874 if (fntype->is_varargs())
7a938933 8875 {
7a938933 8876 const Typed_identifier_list* parameters = fntype->parameters();
26409c52 8877 go_assert(parameters != NULL && !parameters->empty());
7a938933 8878 Type* varargs_type = parameters->back().type();
1bbf7edb
ILT
8879 this->lower_varargs(gogo, function, inserter, varargs_type,
8880 parameters->size());
8881 }
8882
8883 // If this is call to a method, call the method directly passing the
8884 // object as the first parameter.
8885 Bound_method_expression* bme = this->fn_->bound_method_expression();
8886 if (bme != NULL)
8887 {
571d3f91 8888 Named_object* methodfn = bme->function();
1bbf7edb
ILT
8889 Expression* first_arg = bme->first_argument();
8890
8891 // We always pass a pointer when calling a method.
8892 if (first_arg->type()->points_to() == NULL
8893 && !first_arg->type()->is_error())
8894 {
8895 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8896 // We may need to create a temporary variable so that we can
8897 // take the address. We can't do that here because it will
8898 // mess up the order of evaluation.
8899 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8900 ue->set_create_temp();
8901 }
8902
8903 // If we are calling a method which was inherited from an
8904 // embedded struct, and the method did not get a stub, then the
8905 // first type may be wrong.
8906 Type* fatype = bme->first_argument_type();
8907 if (fatype != NULL)
8908 {
8909 if (fatype->points_to() == NULL)
8910 fatype = Type::make_pointer_type(fatype);
8911 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8912 }
8913
8914 Expression_list* new_args = new Expression_list();
8915 new_args->push_back(first_arg);
8916 if (this->args_ != NULL)
8917 {
8918 for (Expression_list::const_iterator p = this->args_->begin();
8919 p != this->args_->end();
8920 ++p)
8921 new_args->push_back(*p);
8922 }
8923
8924 // We have to change in place because this structure may be
8925 // referenced by Call_result_expressions. We can't delete the
8926 // old arguments, because we may be traversing them up in some
8927 // caller. FIXME.
8928 this->args_ = new_args;
571d3f91 8929 this->fn_ = Expression::make_func_reference(methodfn, NULL,
1bbf7edb 8930 bme->location());
7a938933
ILT
8931 }
8932
8933 return this;
8934}
8935
8936// Lower a call to a varargs function. FUNCTION is the function in
8937// which the call occurs--it's not the function we are calling.
8938// VARARGS_TYPE is the type of the varargs parameter, a slice type.
8939// PARAM_COUNT is the number of parameters of the function we are
8940// calling; the last of these parameters will be the varargs
8941// parameter.
8942
1bbf7edb 8943void
7a938933 8944Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8586635c 8945 Statement_inserter* inserter,
7a938933
ILT
8946 Type* varargs_type, size_t param_count)
8947{
8948 if (this->varargs_are_lowered_)
1bbf7edb 8949 return;
7a938933 8950
8afa2bfb 8951 Location loc = this->location();
7a938933 8952
26409c52 8953 go_assert(param_count > 0);
b7190f2f 8954 go_assert(varargs_type->is_slice_type());
7a938933
ILT
8955
8956 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8957 if (arg_count < param_count - 1)
8958 {
8959 // Not enough arguments; will be caught in check_types.
1bbf7edb 8960 return;
7a938933
ILT
8961 }
8962
8963 Expression_list* old_args = this->args_;
8964 Expression_list* new_args = new Expression_list();
8965 bool push_empty_arg = false;
8966 if (old_args == NULL || old_args->empty())
8967 {
26409c52 8968 go_assert(param_count == 1);
7a938933
ILT
8969 push_empty_arg = true;
8970 }
8971 else
8972 {
8973 Expression_list::const_iterator pa;
8974 int i = 1;
8975 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8976 {
8977 if (static_cast<size_t>(i) == param_count)
8978 break;
8979 new_args->push_back(*pa);
8980 }
8981
8982 // We have reached the varargs parameter.
8983
8984 bool issued_error = false;
8985 if (pa == old_args->end())
8986 push_empty_arg = true;
8987 else if (pa + 1 == old_args->end() && this->is_varargs_)
8988 new_args->push_back(*pa);
8989 else if (this->is_varargs_)
8990 {
234bdd5b
ILT
8991 if ((*pa)->type()->is_slice_type())
8992 this->report_error(_("too many arguments"));
8993 else
8994 {
8995 error_at(this->location(),
8996 _("invalid use of %<...%> with non-slice"));
8997 this->set_is_error();
8998 }
1bbf7edb 8999 return;
7a938933 9000 }
7a938933
ILT
9001 else
9002 {
9003 Type* element_type = varargs_type->array_type()->element_type();
9004 Expression_list* vals = new Expression_list;
9005 for (; pa != old_args->end(); ++pa, ++i)
9006 {
9007 // Check types here so that we get a better message.
9008 Type* patype = (*pa)->type();
8afa2bfb 9009 Location paloc = (*pa)->location();
7a938933
ILT
9010 if (!this->check_argument_type(i, element_type, patype,
9011 paloc, issued_error))
9012 continue;
9013 vals->push_back(*pa);
9014 }
9015 Expression* val =
9016 Expression::make_slice_composite_literal(varargs_type, vals, loc);
1bbf7edb 9017 gogo->lower_expression(function, inserter, &val);
7a938933
ILT
9018 new_args->push_back(val);
9019 }
9020 }
9021
9022 if (push_empty_arg)
9023 new_args->push_back(Expression::make_nil(loc));
9024
9025 // We can't return a new call expression here, because this one may
2d8f63a1
ILT
9026 // be referenced by Call_result expressions. FIXME. We can't
9027 // delete OLD_ARGS because we may have both a Call_expression and a
9028 // Builtin_call_expression which refer to them. FIXME.
7a938933
ILT
9029 this->args_ = new_args;
9030 this->varargs_are_lowered_ = true;
7a938933
ILT
9031}
9032
7035307e
CM
9033// Flatten a call with multiple results into a temporary.
9034
9035Expression*
9036Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9037{
9038 size_t rc = this->result_count();
9039 if (rc > 1 && this->call_temp_ == NULL)
9040 {
9041 Struct_field_list* sfl = new Struct_field_list();
9042 Function_type* fntype = this->get_function_type();
9043 const Typed_identifier_list* results = fntype->results();
9044 Location loc = this->location();
9045
9046 int i = 0;
9047 char buf[10];
9048 for (Typed_identifier_list::const_iterator p = results->begin();
9049 p != results->end();
9050 ++p, ++i)
9051 {
9052 snprintf(buf, sizeof buf, "res%d", i);
9053 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9054 }
9055
9056 Struct_type* st = Type::make_struct_type(sfl, loc);
9057 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9058 inserter->insert(this->call_temp_);
9059 }
9060
9061 return this;
9062}
9063
8586635c 9064// Get the function type. This can return NULL in error cases.
7a938933
ILT
9065
9066Function_type*
9067Call_expression::get_function_type() const
9068{
9069 return this->fn_->type()->function_type();
9070}
9071
9072// Return the number of values which this call will return.
9073
9074size_t
9075Call_expression::result_count() const
9076{
9077 const Function_type* fntype = this->get_function_type();
9078 if (fntype == NULL)
9079 return 0;
9080 if (fntype->results() == NULL)
9081 return 0;
9082 return fntype->results()->size();
9083}
9084
8586635c
ILT
9085// Return the temporary which holds a result.
9086
9087Temporary_statement*
9088Call_expression::result(size_t i) const
9089{
9b83b6d2
ILT
9090 if (this->results_ == NULL || this->results_->size() <= i)
9091 {
9092 go_assert(saw_errors());
9093 return NULL;
9094 }
8586635c
ILT
9095 return (*this->results_)[i];
9096}
9097
7a938933
ILT
9098// Return whether this is a call to the predeclared function recover.
9099
9100bool
9101Call_expression::is_recover_call() const
9102{
9103 return this->do_is_recover_call();
9104}
9105
9106// Set the argument to the recover function.
9107
9108void
9109Call_expression::set_recover_arg(Expression* arg)
9110{
9111 this->do_set_recover_arg(arg);
9112}
9113
9114// Virtual functions also implemented by Builtin_call_expression.
9115
9116bool
9117Call_expression::do_is_recover_call() const
9118{
9119 return false;
9120}
9121
9122void
9123Call_expression::do_set_recover_arg(Expression*)
9124{
8c0d1865 9125 go_unreachable();
7a938933
ILT
9126}
9127
8586635c
ILT
9128// We have found an error with this call expression; return true if
9129// we should report it.
9130
9131bool
9132Call_expression::issue_error()
9133{
9134 if (this->issued_error_)
9135 return false;
9136 else
9137 {
9138 this->issued_error_ = true;
9139 return true;
9140 }
9141}
9142
7a938933
ILT
9143// Get the type.
9144
9145Type*
9146Call_expression::do_type()
9147{
9148 if (this->type_ != NULL)
9149 return this->type_;
9150
9151 Type* ret;
9152 Function_type* fntype = this->get_function_type();
9153 if (fntype == NULL)
9154 return Type::make_error_type();
9155
9156 const Typed_identifier_list* results = fntype->results();
9157 if (results == NULL)
9158 ret = Type::make_void_type();
9159 else if (results->size() == 1)
9160 ret = results->begin()->type();
9161 else
9162 ret = Type::make_call_multiple_result_type(this);
9163
9164 this->type_ = ret;
9165
9166 return this->type_;
9167}
9168
9169// Determine types for a call expression. We can use the function
9170// parameter types to set the types of the arguments.
9171
9172void
9173Call_expression::do_determine_type(const Type_context*)
9174{
20532210
ILT
9175 if (!this->determining_types())
9176 return;
9177
7a938933
ILT
9178 this->fn_->determine_type_no_context();
9179 Function_type* fntype = this->get_function_type();
9180 const Typed_identifier_list* parameters = NULL;
9181 if (fntype != NULL)
9182 parameters = fntype->parameters();
9183 if (this->args_ != NULL)
9184 {
9185 Typed_identifier_list::const_iterator pt;
9186 if (parameters != NULL)
9187 pt = parameters->begin();
1bbf7edb 9188 bool first = true;
7a938933
ILT
9189 for (Expression_list::const_iterator pa = this->args_->begin();
9190 pa != this->args_->end();
9191 ++pa)
9192 {
1bbf7edb
ILT
9193 if (first)
9194 {
9195 first = false;
9196 // If this is a method, the first argument is the
9197 // receiver.
9198 if (fntype != NULL && fntype->is_method())
9199 {
9200 Type* rtype = fntype->receiver()->type();
9201 // The receiver is always passed as a pointer.
9202 if (rtype->points_to() == NULL)
9203 rtype = Type::make_pointer_type(rtype);
9204 Type_context subcontext(rtype, false);
9205 (*pa)->determine_type(&subcontext);
9206 continue;
9207 }
9208 }
9209
7a938933
ILT
9210 if (parameters != NULL && pt != parameters->end())
9211 {
9212 Type_context subcontext(pt->type(), false);
9213 (*pa)->determine_type(&subcontext);
9214 ++pt;
9215 }
9216 else
9217 (*pa)->determine_type_no_context();
9218 }
9219 }
9220}
9221
20532210
ILT
9222// Called when determining types for a Call_expression. Return true
9223// if we should go ahead, false if they have already been determined.
9224
9225bool
9226Call_expression::determining_types()
9227{
9228 if (this->types_are_determined_)
9229 return false;
9230 else
9231 {
9232 this->types_are_determined_ = true;
9233 return true;
9234 }
9235}
9236
7a938933
ILT
9237// Check types for parameter I.
9238
9239bool
9240Call_expression::check_argument_type(int i, const Type* parameter_type,
9241 const Type* argument_type,
8afa2bfb 9242 Location argument_location,
7a938933
ILT
9243 bool issued_error)
9244{
9245 std::string reason;
d9930d55
ILT
9246 bool ok;
9247 if (this->are_hidden_fields_ok_)
9248 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9249 &reason);
9250 else
9251 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9252 if (!ok)
7a938933
ILT
9253 {
9254 if (!issued_error)
9255 {
9256 if (reason.empty())
9257 error_at(argument_location, "argument %d has incompatible type", i);
9258 else
9259 error_at(argument_location,
9260 "argument %d has incompatible type (%s)",
9261 i, reason.c_str());
9262 }
9263 this->set_is_error();
9264 return false;
9265 }
9266 return true;
9267}
9268
9269// Check types.
9270
9271void
9272Call_expression::do_check_types(Gogo*)
9273{
234bdd5b
ILT
9274 if (this->classification() == EXPRESSION_ERROR)
9275 return;
9276
7a938933
ILT
9277 Function_type* fntype = this->get_function_type();
9278 if (fntype == NULL)
9279 {
02ed921a 9280 if (!this->fn_->type()->is_error())
7a938933
ILT
9281 this->report_error(_("expected function"));
9282 return;
9283 }
9284
1bbf7edb
ILT
9285 bool is_method = fntype->is_method();
9286 if (is_method)
7a938933 9287 {
1bbf7edb
ILT
9288 go_assert(this->args_ != NULL && !this->args_->empty());
9289 Type* rtype = fntype->receiver()->type();
9290 Expression* first_arg = this->args_->front();
9291 // The language permits copying hidden fields for a method
9292 // receiver. We dereference the values since receivers are
9293 // always passed as pointers.
9294 std::string reason;
9295 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9296 first_arg->type()->deref(),
9297 &reason))
7a938933 9298 {
1bbf7edb
ILT
9299 if (reason.empty())
9300 this->report_error(_("incompatible type for receiver"));
9301 else
7a938933 9302 {
1bbf7edb
ILT
9303 error_at(this->location(),
9304 "incompatible type for receiver (%s)",
9305 reason.c_str());
9306 this->set_is_error();
7a938933
ILT
9307 }
9308 }
9309 }
9310
9311 // Note that varargs was handled by the lower_varargs() method, so
234bdd5b
ILT
9312 // we don't have to worry about it here unless something is wrong.
9313 if (this->is_varargs_ && !this->varargs_are_lowered_)
9314 {
9315 if (!fntype->is_varargs())
9316 {
9317 error_at(this->location(),
9318 _("invalid use of %<...%> calling non-variadic function"));
9319 this->set_is_error();
9320 return;
9321 }
9322 }
7a938933
ILT
9323
9324 const Typed_identifier_list* parameters = fntype->parameters();
9325 if (this->args_ == NULL)
9326 {
9327 if (parameters != NULL && !parameters->empty())
9328 this->report_error(_("not enough arguments"));
9329 }
9330 else if (parameters == NULL)
1bbf7edb
ILT
9331 {
9332 if (!is_method || this->args_->size() > 1)
9333 this->report_error(_("too many arguments"));
9334 }
7a938933
ILT
9335 else
9336 {
9337 int i = 0;
1bbf7edb
ILT
9338 Expression_list::const_iterator pa = this->args_->begin();
9339 if (is_method)
9340 ++pa;
9341 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9342 pt != parameters->end();
9343 ++pt, ++pa, ++i)
7a938933 9344 {
1bbf7edb 9345 if (pa == this->args_->end())
7a938933 9346 {
1bbf7edb 9347 this->report_error(_("not enough arguments"));
7a938933
ILT
9348 return;
9349 }
9350 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9351 (*pa)->location(), false);
9352 }
1bbf7edb
ILT
9353 if (pa != this->args_->end())
9354 this->report_error(_("too many arguments"));
7a938933
ILT
9355 }
9356}
9357
9358// Return whether we have to use a temporary variable to ensure that
9359// we evaluate this call expression in order. If the call returns no
8586635c 9360// results then it will inevitably be executed last.
7a938933
ILT
9361
9362bool
9363Call_expression::do_must_eval_in_order() const
9364{
8586635c 9365 return this->result_count() > 0;
7a938933
ILT
9366}
9367
7a938933
ILT
9368// Get the function and the first argument to use when calling an
9369// interface method.
9370
eb6eb862 9371Expression*
7a938933 9372Call_expression::interface_method_function(
7a938933 9373 Interface_field_reference_expression* interface_method,
eb6eb862 9374 Expression** first_arg_ptr)
7a938933 9375{
eb6eb862
CM
9376 *first_arg_ptr = interface_method->get_underlying_object();
9377 return interface_method->get_function();
7a938933
ILT
9378}
9379
9380// Build the call expression.
9381
9382tree
9383Call_expression::do_get_tree(Translate_context* context)
9384{
7035307e
CM
9385 if (this->call_ != NULL)
9386 return expr_to_tree(this->call_);
7a938933
ILT
9387
9388 Function_type* fntype = this->get_function_type();
9389 if (fntype == NULL)
9390 return error_mark_node;
9391
9392 if (this->fn_->is_error_expression())
9393 return error_mark_node;
9394
9395 Gogo* gogo = context->gogo();
8afa2bfb 9396 Location location = this->location();
7a938933
ILT
9397
9398 Func_expression* func = this->fn_->func_expression();
7a938933
ILT
9399 Interface_field_reference_expression* interface_method =
9400 this->fn_->interface_field_reference_expression();
9401 const bool has_closure = func != NULL && func->closure() != NULL;
1bbf7edb 9402 const bool is_interface_method = interface_method != NULL;
7a938933 9403
05a7d566 9404 bool has_closure_arg;
fdbc38a6 9405 if (has_closure)
05a7d566 9406 has_closure_arg = true;
fdbc38a6 9407 else if (func != NULL)
05a7d566 9408 has_closure_arg = false;
fdbc38a6 9409 else if (is_interface_method)
05a7d566 9410 has_closure_arg = false;
fdbc38a6 9411 else
05a7d566 9412 has_closure_arg = true;
fdbc38a6 9413
7a938933 9414 int nargs;
7035307e 9415 std::vector<Bexpression*> fn_args;
7a938933
ILT
9416 if (this->args_ == NULL || this->args_->empty())
9417 {
05a7d566 9418 nargs = is_interface_method ? 1 : 0;
7035307e
CM
9419 if (nargs > 0)
9420 fn_args.resize(1);
7a938933 9421 }
1bbf7edb
ILT
9422 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9423 {
9424 // Passing a receiver parameter.
9425 go_assert(!is_interface_method
9426 && fntype->is_method()
9427 && this->args_->size() == 1);
05a7d566 9428 nargs = 1;
7035307e
CM
9429 fn_args.resize(1);
9430 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
1bbf7edb 9431 }
7a938933
ILT
9432 else
9433 {
9434 const Typed_identifier_list* params = fntype->parameters();
7a938933
ILT
9435
9436 nargs = this->args_->size();
1bbf7edb 9437 int i = is_interface_method ? 1 : 0;
7a938933 9438 nargs += i;
7035307e 9439 fn_args.resize(nargs);
7a938933
ILT
9440
9441 Typed_identifier_list::const_iterator pp = params->begin();
1bbf7edb
ILT
9442 Expression_list::const_iterator pe = this->args_->begin();
9443 if (!is_interface_method && fntype->is_method())
9444 {
7035307e 9445 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
1bbf7edb
ILT
9446 ++pe;
9447 ++i;
9448 }
9449 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
7a938933 9450 {
26409c52 9451 go_assert(pp != params->end());
7035307e
CM
9452 Expression* arg =
9453 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9454 location);
9455 fn_args[i] = tree_to_expr(arg->get_tree(context));
7a938933 9456 }
26409c52 9457 go_assert(pp == params->end());
05a7d566 9458 go_assert(i == nargs);
7a938933
ILT
9459 }
9460
7035307e
CM
9461 Expression* fn;
9462 Expression* closure = NULL;
fdbc38a6
ILT
9463 if (func != NULL)
9464 {
9465 Named_object* no = func->named_object();
7035307e
CM
9466 fn = Expression::make_func_code_reference(no, location);
9467 if (has_closure)
9468 closure = func->closure();
fdbc38a6 9469 }
1bbf7edb 9470 else if (!is_interface_method)
fdbc38a6 9471 {
7035307e
CM
9472 closure = this->fn_;
9473
9474 // The backend representation of this function type is a pointer
9475 // to a struct whose first field is the actual function to call.
9476 Type* pfntype =
9477 Type::make_pointer_type(
9478 Type::make_pointer_type(Type::make_void_type()));
9479 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9480 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9481 }
7a938933 9482 else
6452b112 9483 {
eb6eb862 9484 Expression* first_arg;
7035307e
CM
9485 fn = this->interface_method_function(interface_method, &first_arg);
9486 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
7a938933
ILT
9487 }
9488
05a7d566 9489 if (!has_closure_arg)
7035307e 9490 go_assert(closure == NULL);
05a7d566
ILT
9491 else
9492 {
9493 // Pass the closure argument by calling the function function
9494 // __go_set_closure. In the order_evaluations pass we have
9495 // ensured that if any parameters contain call expressions, they
9496 // will have been moved out to temporary variables.
7035307e
CM
9497 go_assert(closure != NULL);
9498 Expression* set_closure =
9499 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9500 fn = Expression::make_compound(set_closure, fn, location);
05a7d566
ILT
9501 }
9502
7035307e 9503 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
be7341a8
ILT
9504
9505 // When not calling a named function directly, use a type conversion
9506 // in case the type of the function is a recursive type which refers
9507 // to itself. We don't do this for an interface method because 1)
9508 // an interface method never refers to itself, so we always have a
9509 // function type here; 2) we pass an extra first argument to an
9510 // interface method, so fntype is not correct.
9511 if (func == NULL && !is_interface_method)
9512 {
9513 Btype* bft = fntype->get_backend_fntype(gogo);
9514 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9515 }
9516
7035307e 9517 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
7a938933 9518
7035307e 9519 if (this->results_ != NULL)
7a938933 9520 {
7035307e
CM
9521 go_assert(this->call_temp_ != NULL);
9522 Expression* call_ref =
9523 Expression::make_temporary_reference(this->call_temp_, location);
9524 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9525 Bstatement* assn_stmt =
9526 gogo->backend()->assignment_statement(bcall_ref, call, location);
7a938933 9527
7035307e 9528 this->call_ = this->set_results(context, bcall_ref);
7a938933 9529
7035307e
CM
9530 Bexpression* set_and_call =
9531 gogo->backend()->compound_expression(assn_stmt, this->call_,
9532 location);
9533 return expr_to_tree(set_and_call);
9534 }
7a938933 9535
7035307e
CM
9536 this->call_ = call;
9537 return expr_to_tree(this->call_);
7a938933
ILT
9538}
9539
8586635c
ILT
9540// Set the result variables if this call returns multiple results.
9541
7035307e
CM
9542Bexpression*
9543Call_expression::set_results(Translate_context* context, Bexpression* call)
8586635c 9544{
7035307e 9545 Gogo* gogo = context->gogo();
8586635c 9546
7035307e 9547 Bexpression* results = NULL;
8afa2bfb 9548 Location loc = this->location();
7035307e 9549
8586635c 9550 size_t rc = this->result_count();
7035307e 9551 for (size_t i = 0; i < rc; ++i)
8586635c 9552 {
8586635c 9553 Temporary_statement* temp = this->result(i);
9b83b6d2
ILT
9554 if (temp == NULL)
9555 {
9556 go_assert(saw_errors());
7035307e 9557 return gogo->backend()->error_expression();
9b83b6d2 9558 }
8586635c
ILT
9559 Temporary_reference_expression* ref =
9560 Expression::make_temporary_reference(temp, loc);
9561 ref->set_is_lvalue();
8586635c 9562
7035307e
CM
9563 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9564 Bexpression* call_result =
9565 gogo->backend()->struct_field_expression(call, i, loc);
9566 Bstatement* assn_stmt =
9567 gogo->backend()->assignment_statement(result_ref, call_result, loc);
8586635c 9568
7035307e
CM
9569 Bexpression* result =
9570 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
8586635c 9571
7035307e
CM
9572 if (results == NULL)
9573 results = result;
9574 else
9575 {
9576 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9577 results =
9578 gogo->backend()->compound_expression(expr_stmt, results, loc);
9579 }
9580 }
9581 return results;
8586635c
ILT
9582}
9583
16c57fe2
RL
9584// Dump ast representation for a call expressin.
9585
9586void
9587Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9588{
9589 this->fn_->dump_expression(ast_dump_context);
9590 ast_dump_context->ostream() << "(";
9591 if (args_ != NULL)
9592 ast_dump_context->dump_expression_list(this->args_);
9593
9594 ast_dump_context->ostream() << ") ";
9595}
9596
7a938933
ILT
9597// Make a call expression.
9598
9599Call_expression*
9600Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
8afa2bfb 9601 Location location)
7a938933
ILT
9602{
9603 return new Call_expression(fn, args, is_varargs, location);
9604}
9605
9606// A single result from a call which returns multiple results.
9607
9608class Call_result_expression : public Expression
9609{
9610 public:
9611 Call_result_expression(Call_expression* call, unsigned int index)
9612 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9613 call_(call), index_(index)
9614 { }
9615
9616 protected:
9617 int
9618 do_traverse(Traverse*);
9619
9620 Type*
9621 do_type();
9622
9623 void
9624 do_determine_type(const Type_context*);
9625
9626 void
9627 do_check_types(Gogo*);
9628
9629 Expression*
9630 do_copy()
9631 {
9632 return new Call_result_expression(this->call_->call_expression(),
9633 this->index_);
9634 }
9635
9636 bool
9637 do_must_eval_in_order() const
9638 { return true; }
9639
9640 tree
9641 do_get_tree(Translate_context*);
9642
16c57fe2
RL
9643 void
9644 do_dump_expression(Ast_dump_context*) const;
9645
7a938933
ILT
9646 private:
9647 // The underlying call expression.
9648 Expression* call_;
9649 // Which result we want.
9650 unsigned int index_;
9651};
9652
9653// Traverse a call result.
9654
9655int
9656Call_result_expression::do_traverse(Traverse* traverse)
9657{
9658 if (traverse->remember_expression(this->call_))
9659 {
9660 // We have already traversed the call expression.
9661 return TRAVERSE_CONTINUE;
9662 }
9663 return Expression::traverse(&this->call_, traverse);
9664}
9665
9666// Get the type.
9667
9668Type*
9669Call_result_expression::do_type()
9670{
7a2d845d
ILT
9671 if (this->classification() == EXPRESSION_ERROR)
9672 return Type::make_error_type();
9673
7a938933
ILT
9674 // THIS->CALL_ can be replaced with a temporary reference due to
9675 // Call_expression::do_must_eval_in_order when there is an error.
9676 Call_expression* ce = this->call_->call_expression();
9677 if (ce == NULL)
10d53f5d
ILT
9678 {
9679 this->set_is_error();
9680 return Type::make_error_type();
9681 }
7a938933
ILT
9682 Function_type* fntype = ce->get_function_type();
9683 if (fntype == NULL)
10d53f5d 9684 {
22508cae 9685 if (ce->issue_error())
02a72827
ILT
9686 {
9687 if (!ce->fn()->type()->is_error())
9688 this->report_error(_("expected function"));
9689 }
10d53f5d
ILT
9690 this->set_is_error();
9691 return Type::make_error_type();
9692 }
7a938933 9693 const Typed_identifier_list* results = fntype->results();
8586635c 9694 if (results == NULL || results->size() < 2)
428f5f5f 9695 {
8586635c
ILT
9696 if (ce->issue_error())
9697 this->report_error(_("number of results does not match "
9698 "number of values"));
428f5f5f
ILT
9699 return Type::make_error_type();
9700 }
7a938933
ILT
9701 Typed_identifier_list::const_iterator pr = results->begin();
9702 for (unsigned int i = 0; i < this->index_; ++i)
9703 {
9704 if (pr == results->end())
7a2d845d 9705 break;
7a938933
ILT
9706 ++pr;
9707 }
9708 if (pr == results->end())
7a2d845d 9709 {
8586635c
ILT
9710 if (ce->issue_error())
9711 this->report_error(_("number of results does not match "
9712 "number of values"));
7a2d845d
ILT
9713 return Type::make_error_type();
9714 }
7a938933
ILT
9715 return pr->type();
9716}
9717
7a2d845d
ILT
9718// Check the type. Just make sure that we trigger the warning in
9719// do_type.
7a938933
ILT
9720
9721void
9722Call_result_expression::do_check_types(Gogo*)
9723{
7a2d845d 9724 this->type();
7a938933
ILT
9725}
9726
9727// Determine the type. We have nothing to do here, but the 0 result
9728// needs to pass down to the caller.
9729
9730void
9731Call_result_expression::do_determine_type(const Type_context*)
9732{
20532210 9733 this->call_->determine_type_no_context();
7a938933
ILT
9734}
9735
8586635c
ILT
9736// Return the tree. We just refer to the temporary set by the call
9737// expression. We don't do this at lowering time because it makes it
9738// hard to evaluate the call at the right time.
7a938933
ILT
9739
9740tree
9741Call_result_expression::do_get_tree(Translate_context* context)
9742{
8586635c 9743 Call_expression* ce = this->call_->call_expression();
9b83b6d2
ILT
9744 if (ce == NULL)
9745 {
9746 go_assert(this->call_->is_error_expression());
9747 return error_mark_node;
9748 }
8586635c 9749 Temporary_statement* ts = ce->result(this->index_);
9b83b6d2
ILT
9750 if (ts == NULL)
9751 {
9752 go_assert(saw_errors());
9753 return error_mark_node;
9754 }
8586635c
ILT
9755 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9756 return ref->get_tree(context);
7a938933
ILT
9757}
9758
16c57fe2
RL
9759// Dump ast representation for a call result expression.
9760
9761void
9762Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9763 const
9764{
9765 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9766 // (struct) and the fields are referenced instead.
9767 ast_dump_context->ostream() << this->index_ << "@(";
9768 ast_dump_context->dump_expression(this->call_);
9769 ast_dump_context->ostream() << ")";
9770}
9771
7a938933
ILT
9772// Make a reference to a single result of a call which returns
9773// multiple results.
9774
9775Expression*
9776Expression::make_call_result(Call_expression* call, unsigned int index)
9777{
9778 return new Call_result_expression(call, index);
9779}
9780
9781// Class Index_expression.
9782
9783// Traversal.
9784
9785int
9786Index_expression::do_traverse(Traverse* traverse)
9787{
9788 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9789 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9790 || (this->end_ != NULL
26b8f7eb
ILT
9791 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9792 || (this->cap_ != NULL
9793 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
7a938933
ILT
9794 return TRAVERSE_EXIT;
9795 return TRAVERSE_CONTINUE;
9796}
9797
9798// Lower an index expression. This converts the generic index
9799// expression into an array index, a string index, or a map index.
9800
9801Expression*
8586635c 9802Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
7a938933 9803{
8afa2bfb 9804 Location location = this->location();
7a938933
ILT
9805 Expression* left = this->left_;
9806 Expression* start = this->start_;
9807 Expression* end = this->end_;
26b8f7eb 9808 Expression* cap = this->cap_;
7a938933
ILT
9809
9810 Type* type = left->type();
02ed921a 9811 if (type->is_error())
7a938933 9812 return Expression::make_error(location);
d18c88a8
ILT
9813 else if (left->is_type_expression())
9814 {
9815 error_at(location, "attempt to index type expression");
9816 return Expression::make_error(location);
9817 }
7a938933 9818 else if (type->array_type() != NULL)
26b8f7eb 9819 return Expression::make_array_index(left, start, end, cap, location);
7a938933
ILT
9820 else if (type->points_to() != NULL
9821 && type->points_to()->array_type() != NULL
b7190f2f 9822 && !type->points_to()->is_slice_type())
7a938933
ILT
9823 {
9824 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9825 location);
5dd0cef6
ILT
9826
9827 // For an ordinary index into the array, the pointer will be
9828 // dereferenced. For a slice it will not--the resulting slice
9829 // will simply reuse the pointer, which is incorrect if that
9830 // pointer is nil.
9831 if (end != NULL || cap != NULL)
9832 deref->issue_nil_check();
9833
26b8f7eb 9834 return Expression::make_array_index(deref, start, end, cap, location);
7a938933
ILT
9835 }
9836 else if (type->is_string_type())
26b8f7eb
ILT
9837 {
9838 if (cap != NULL)
9839 {
9840 error_at(location, "invalid 3-index slice of string");
9841 return Expression::make_error(location);
9842 }
9843 return Expression::make_string_index(left, start, end, location);
9844 }
7a938933
ILT
9845 else if (type->map_type() != NULL)
9846 {
26b8f7eb 9847 if (end != NULL || cap != NULL)
7a938933
ILT
9848 {
9849 error_at(location, "invalid slice of map");
9850 return Expression::make_error(location);
9851 }
2d8f63a1
ILT
9852 Map_index_expression* ret = Expression::make_map_index(left, start,
9853 location);
7a938933
ILT
9854 if (this->is_lvalue_)
9855 ret->set_is_lvalue();
9856 return ret;
9857 }
9858 else
9859 {
9860 error_at(location,
9861 "attempt to index object which is not array, string, or map");
9862 return Expression::make_error(location);
9863 }
9864}
9865
26b8f7eb
ILT
9866// Write an indexed expression
9867// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
16c57fe2
RL
9868
9869void
9870Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9871 const Expression* expr,
9872 const Expression* start,
26b8f7eb
ILT
9873 const Expression* end,
9874 const Expression* cap)
16c57fe2
RL
9875{
9876 expr->dump_expression(ast_dump_context);
9877 ast_dump_context->ostream() << "[";
9878 start->dump_expression(ast_dump_context);
9879 if (end != NULL)
9880 {
9881 ast_dump_context->ostream() << ":";
9882 end->dump_expression(ast_dump_context);
9883 }
26b8f7eb
ILT
9884 if (cap != NULL)
9885 {
9886 ast_dump_context->ostream() << ":";
9887 cap->dump_expression(ast_dump_context);
9888 }
16c57fe2
RL
9889 ast_dump_context->ostream() << "]";
9890}
9891
9892// Dump ast representation for an index expression.
9893
9894void
9895Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9896 const
9897{
9898 Index_expression::dump_index_expression(ast_dump_context, this->left_,
26b8f7eb 9899 this->start_, this->end_, this->cap_);
16c57fe2
RL
9900}
9901
7a938933
ILT
9902// Make an index expression.
9903
9904Expression*
9905Expression::make_index(Expression* left, Expression* start, Expression* end,
26b8f7eb 9906 Expression* cap, Location location)
7a938933 9907{
26b8f7eb 9908 return new Index_expression(left, start, end, cap, location);
7a938933
ILT
9909}
9910
9911// An array index. This is used for both indexing and slicing.
9912
9913class Array_index_expression : public Expression
9914{
9915 public:
9916 Array_index_expression(Expression* array, Expression* start,
26b8f7eb 9917 Expression* end, Expression* cap, Location location)
7a938933 9918 : Expression(EXPRESSION_ARRAY_INDEX, location),
26b8f7eb 9919 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
7a938933
ILT
9920 { }
9921
9922 protected:
9923 int
9924 do_traverse(Traverse*);
9925
7035307e
CM
9926 Expression*
9927 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9928
7a938933
ILT
9929 Type*
9930 do_type();
9931
9932 void
9933 do_determine_type(const Type_context*);
9934
9935 void
9936 do_check_types(Gogo*);
9937
9938 Expression*
9939 do_copy()
9940 {
9941 return Expression::make_array_index(this->array_->copy(),
9942 this->start_->copy(),
9943 (this->end_ == NULL
9944 ? NULL
9945 : this->end_->copy()),
26b8f7eb
ILT
9946 (this->cap_ == NULL
9947 ? NULL
9948 : this->cap_->copy()),
7a938933
ILT
9949 this->location());
9950 }
9951
cbe98a41
ILT
9952 bool
9953 do_must_eval_subexpressions_in_order(int* skip) const
9954 {
9955 *skip = 1;
9956 return true;
9957 }
9958
7a938933
ILT
9959 bool
9960 do_is_addressable() const;
9961
9962 void
9963 do_address_taken(bool escapes)
9964 { this->array_->address_taken(escapes); }
9965
64c7b4c0
ILT
9966 void
9967 do_issue_nil_check()
9968 { this->array_->issue_nil_check(); }
9969
7a938933
ILT
9970 tree
9971 do_get_tree(Translate_context*);
9972
16c57fe2
RL
9973 void
9974 do_dump_expression(Ast_dump_context*) const;
9975
7a938933
ILT
9976 private:
9977 // The array we are getting a value from.
9978 Expression* array_;
9979 // The start or only index.
9980 Expression* start_;
9981 // The end index of a slice. This may be NULL for a simple array
9982 // index, or it may be a nil expression for the length of the array.
9983 Expression* end_;
26b8f7eb
ILT
9984 // The capacity argument of a slice. This may be NULL for an array index or
9985 // slice.
9986 Expression* cap_;
7a938933
ILT
9987 // The type of the expression.
9988 Type* type_;
9989};
9990
9991// Array index traversal.
9992
9993int
9994Array_index_expression::do_traverse(Traverse* traverse)
9995{
9996 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9997 return TRAVERSE_EXIT;
9998 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9999 return TRAVERSE_EXIT;
10000 if (this->end_ != NULL)
10001 {
10002 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10003 return TRAVERSE_EXIT;
10004 }
26b8f7eb
ILT
10005 if (this->cap_ != NULL)
10006 {
10007 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10008 return TRAVERSE_EXIT;
10009 }
7a938933
ILT
10010 return TRAVERSE_CONTINUE;
10011}
10012
10013// Return the type of an array index.
10014
10015Type*
10016Array_index_expression::do_type()
10017{
10018 if (this->type_ == NULL)
10019 {
10020 Array_type* type = this->array_->type()->array_type();
10021 if (type == NULL)
10022 this->type_ = Type::make_error_type();
10023 else if (this->end_ == NULL)
10024 this->type_ = type->element_type();
b7190f2f 10025 else if (type->is_slice_type())
7a938933
ILT
10026 {
10027 // A slice of a slice has the same type as the original
10028 // slice.
10029 this->type_ = this->array_->type()->deref();
10030 }
10031 else
10032 {
10033 // A slice of an array is a slice.
10034 this->type_ = Type::make_array_type(type->element_type(), NULL);
10035 }
10036 }
10037 return this->type_;
10038}
10039
10040// Set the type of an array index.
10041
10042void
10043Array_index_expression::do_determine_type(const Type_context*)
10044{
10045 this->array_->determine_type_no_context();
1c4a5fc8 10046 this->start_->determine_type_no_context();
7a938933 10047 if (this->end_ != NULL)
1c4a5fc8 10048 this->end_->determine_type_no_context();
26b8f7eb
ILT
10049 if (this->cap_ != NULL)
10050 this->cap_->determine_type_no_context();
7a938933
ILT
10051}
10052
10053// Check types of an array index.
10054
10055void
10056Array_index_expression::do_check_types(Gogo*)
10057{
69d8df44
ILT
10058 Numeric_constant nc;
10059 unsigned long v;
10060 if (this->start_->type()->integer_type() == NULL
10061 && !this->start_->type()->is_error()
10062 && (!this->start_->numeric_constant_value(&nc)
10063 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
7a938933
ILT
10064 this->report_error(_("index must be integer"));
10065 if (this->end_ != NULL
10066 && this->end_->type()->integer_type() == NULL
02a72827
ILT
10067 && !this->end_->type()->is_error()
10068 && !this->end_->is_nil_expression()
69d8df44
ILT
10069 && !this->end_->is_error_expression()
10070 && (!this->end_->numeric_constant_value(&nc)
10071 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
7a938933 10072 this->report_error(_("slice end must be integer"));
26b8f7eb
ILT
10073 if (this->cap_ != NULL
10074 && this->cap_->type()->integer_type() == NULL
10075 && !this->cap_->type()->is_error()
10076 && !this->cap_->is_nil_expression()
10077 && !this->cap_->is_error_expression()
10078 && (!this->cap_->numeric_constant_value(&nc)
10079 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10080 this->report_error(_("slice capacity must be integer"));
7a938933
ILT
10081
10082 Array_type* array_type = this->array_->type()->array_type();
f39c772f
ILT
10083 if (array_type == NULL)
10084 {
26409c52 10085 go_assert(this->array_->type()->is_error());
f39c772f
ILT
10086 return;
10087 }
7a938933
ILT
10088
10089 unsigned int int_bits =
10090 Type::lookup_integer_type("int")->integer_type()->bits();
10091
5caf63ca 10092 Numeric_constant lvalnc;
7a938933 10093 mpz_t lval;
7a938933 10094 bool lval_valid = (array_type->length() != NULL
5caf63ca
ILT
10095 && array_type->length()->numeric_constant_value(&lvalnc)
10096 && lvalnc.to_int(&lval));
10097 Numeric_constant inc;
7a938933 10098 mpz_t ival;
f2b2ead4 10099 bool ival_valid = false;
5caf63ca 10100 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
7a938933 10101 {
f2b2ead4 10102 ival_valid = true;
7a938933
ILT
10103 if (mpz_sgn(ival) < 0
10104 || mpz_sizeinbase(ival, 2) >= int_bits
10105 || (lval_valid
10106 && (this->end_ == NULL
10107 ? mpz_cmp(ival, lval) >= 0
10108 : mpz_cmp(ival, lval) > 0)))
10109 {
10110 error_at(this->start_->location(), "array index out of bounds");
10111 this->set_is_error();
10112 }
10113 }
10114 if (this->end_ != NULL && !this->end_->is_nil_expression())
10115 {
5caf63ca
ILT
10116 Numeric_constant enc;
10117 mpz_t eval;
26b8f7eb 10118 bool eval_valid = false;
5caf63ca 10119 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
7a938933 10120 {
26b8f7eb 10121 eval_valid = true;
5caf63ca
ILT
10122 if (mpz_sgn(eval) < 0
10123 || mpz_sizeinbase(eval, 2) >= int_bits
10124 || (lval_valid && mpz_cmp(eval, lval) > 0))
7a938933
ILT
10125 {
10126 error_at(this->end_->location(), "array index out of bounds");
10127 this->set_is_error();
10128 }
f2b2ead4
ILT
10129 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10130 this->report_error(_("inverted slice range"));
7a938933 10131 }
26b8f7eb
ILT
10132
10133 Numeric_constant cnc;
10134 mpz_t cval;
10135 if (this->cap_ != NULL
10136 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10137 {
10138 if (mpz_sgn(cval) < 0
10139 || mpz_sizeinbase(cval, 2) >= int_bits
10140 || (lval_valid && mpz_cmp(cval, lval) > 0))
10141 {
10142 error_at(this->cap_->location(), "array index out of bounds");
10143 this->set_is_error();
10144 }
10145 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10146 {
10147 error_at(this->cap_->location(),
10148 "invalid slice index: capacity less than start");
10149 this->set_is_error();
10150 }
10151 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10152 {
10153 error_at(this->cap_->location(),
10154 "invalid slice index: capacity less than length");
10155 this->set_is_error();
10156 }
10157 mpz_clear(cval);
10158 }
10159
10160 if (eval_valid)
10161 mpz_clear(eval);
7a938933 10162 }
f2b2ead4
ILT
10163 if (ival_valid)
10164 mpz_clear(ival);
5caf63ca
ILT
10165 if (lval_valid)
10166 mpz_clear(lval);
7a938933
ILT
10167
10168 // A slice of an array requires an addressable array. A slice of a
10169 // slice is always possible.
b7190f2f 10170 if (this->end_ != NULL && !array_type->is_slice_type())
9ebd2806
ILT
10171 {
10172 if (!this->array_->is_addressable())
5fca1e3f 10173 this->report_error(_("slice of unaddressable value"));
9ebd2806
ILT
10174 else
10175 this->array_->address_taken(true);
10176 }
7a938933
ILT
10177}
10178
7035307e 10179// Flatten array indexing by using temporary variables for slices and indexes.
6ddb6288
ILT
10180
10181Expression*
10182Array_index_expression::do_flatten(Gogo*, Named_object*,
10183 Statement_inserter* inserter)
10184{
10185 Location loc = this->location();
7035307e 10186 Temporary_statement* temp;
6ddb6288
ILT
10187 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10188 {
7035307e 10189 temp = Statement::make_temporary(NULL, this->array_, loc);
6ddb6288
ILT
10190 inserter->insert(temp);
10191 this->array_ = Expression::make_temporary_reference(temp, loc);
10192 }
7035307e
CM
10193 if (!this->start_->is_variable())
10194 {
10195 temp = Statement::make_temporary(NULL, this->start_, loc);
10196 inserter->insert(temp);
10197 this->start_ = Expression::make_temporary_reference(temp, loc);
10198 }
10199 if (this->end_ != NULL
10200 && !this->end_->is_nil_expression()
10201 && !this->end_->is_variable())
10202 {
10203 temp = Statement::make_temporary(NULL, this->end_, loc);
10204 inserter->insert(temp);
10205 this->end_ = Expression::make_temporary_reference(temp, loc);
10206 }
10207 if (this->cap_ != NULL && !this->cap_->is_variable())
10208 {
10209 temp = Statement::make_temporary(NULL, this->cap_, loc);
10210 inserter->insert(temp);
10211 this->cap_ = Expression::make_temporary_reference(temp, loc);
10212 }
10213
6ddb6288
ILT
10214 return this;
10215}
10216
7a938933
ILT
10217// Return whether this expression is addressable.
10218
10219bool
10220Array_index_expression::do_is_addressable() const
10221{
10222 // A slice expression is not addressable.
10223 if (this->end_ != NULL)
10224 return false;
10225
10226 // An index into a slice is addressable.
b7190f2f 10227 if (this->array_->type()->is_slice_type())
7a938933
ILT
10228 return true;
10229
10230 // An index into an array is addressable if the array is
10231 // addressable.
10232 return this->array_->is_addressable();
10233}
10234
10235// Get a tree for an array index.
10236
10237tree
10238Array_index_expression::do_get_tree(Translate_context* context)
10239{
7a938933 10240 Array_type* array_type = this->array_->type()->array_type();
91ab2208
ILT
10241 if (array_type == NULL)
10242 {
26409c52 10243 go_assert(this->array_->type()->is_error());
91ab2208
ILT
10244 return error_mark_node;
10245 }
6ddb6288 10246 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
7a938933 10247
7035307e
CM
10248 Location loc = this->location();
10249 Gogo* gogo = context->gogo();
10250
10251 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
7a938933 10252
7035307e
CM
10253 // We need to convert the length and capacity to the Go "int" type here
10254 // because the length of a fixed-length array could be of type "uintptr"
10255 // and gimple disallows binary operations between "uintptr" and other
10256 // integer types. FIXME.
10257 Bexpression* length = NULL;
b6422b37
ILT
10258 if (this->end_ == NULL || this->end_->is_nil_expression())
10259 {
6ddb6288 10260 Expression* len = array_type->get_length(gogo, this->array_);
7035307e
CM
10261 length = tree_to_expr(len->get_tree(context));
10262 length = gogo->backend()->convert_expression(int_btype, length, loc);
b6422b37
ILT
10263 }
10264
7035307e 10265 Bexpression* capacity = NULL;
b6422b37
ILT
10266 if (this->end_ != NULL)
10267 {
6ddb6288 10268 Expression* cap = array_type->get_capacity(gogo, this->array_);
7035307e
CM
10269 capacity = tree_to_expr(cap->get_tree(context));
10270 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
b6422b37
ILT
10271 }
10272
7035307e 10273 Bexpression* cap_arg = capacity;
26b8f7eb
ILT
10274 if (this->cap_ != NULL)
10275 {
7035307e
CM
10276 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10277 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
26b8f7eb
ILT
10278 }
10279
7035307e
CM
10280 if (length == NULL)
10281 length = cap_arg;
7a938933
ILT
10282
10283 int code = (array_type->length() != NULL
10284 ? (this->end_ == NULL
10285 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10286 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10287 : (this->end_ == NULL
10288 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10289 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
7035307e
CM
10290 Bexpression* crash =
10291 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10292
10293 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10294 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10295
10296 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10297 start = gogo->backend()->convert_expression(int_btype, start, loc);
10298 Bexpression* start_too_large =
10299 gogo->backend()->binary_expression((this->end_ == NULL
10300 ? OPERATOR_GE
10301 : OPERATOR_GT),
10302 start,
10303 (this->end_ == NULL
10304 ? length
10305 : capacity),
10306 loc);
10307 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10308 bad_index, loc);
7a938933
ILT
10309
10310 if (this->end_ == NULL)
10311 {
10312 // Simple array indexing. This has to return an l-value, so
7035307e
CM
10313 // wrap the index check into START.
10314 start =
10315 gogo->backend()->conditional_expression(int_btype, bad_index,
10316 crash, start, loc);
7a938933 10317
7035307e 10318 Bexpression* ret;
7a938933
ILT
10319 if (array_type->length() != NULL)
10320 {
7035307e
CM
10321 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10322 ret = gogo->backend()->array_index_expression(array, start, loc);
7a938933
ILT
10323 }
10324 else
10325 {
7035307e
CM
10326 // Slice.
10327 Expression* valptr =
6ddb6288 10328 array_type->get_value_pointer(gogo, this->array_);
7035307e
CM
10329 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10330 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10331 ret = gogo->backend()->indirect_expression(ptr, true, loc);
7a938933 10332 }
7035307e 10333 return expr_to_tree(ret);
7a938933
ILT
10334 }
10335
10336 // Array slice.
10337
26b8f7eb
ILT
10338 if (this->cap_ != NULL)
10339 {
7035307e
CM
10340 bounds_check = Expression::check_bounds(this->cap_, loc);
10341 Bexpression* bounds_bcheck =
10342 tree_to_expr(bounds_check->get_tree(context));
10343 bad_index =
10344 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10345 bad_index, loc);
10346 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10347
10348 Bexpression* cap_too_small =
10349 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10350 Bexpression* cap_too_large =
10351 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10352 Bexpression* bad_cap =
10353 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10354 cap_too_large, loc);
10355 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10356 bad_index, loc);
10357 }
10358
10359 Bexpression* end;
7a938933 10360 if (this->end_->is_nil_expression())
7035307e 10361 end = length;
7a938933
ILT
10362 else
10363 {
7035307e
CM
10364 bounds_check = Expression::check_bounds(this->end_, loc);
10365 Bexpression* bounds_bcheck =
10366 tree_to_expr(bounds_check->get_tree(context));
7a938933 10367
7035307e
CM
10368 bad_index =
10369 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10370 bad_index, loc);
7a938933 10371
7035307e
CM
10372 end = tree_to_expr(this->end_->get_tree(context));
10373 end = gogo->backend()->convert_expression(int_btype, end, loc);
10374 Bexpression* end_too_small =
10375 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10376 Bexpression* end_too_large =
10377 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10378 Bexpression* bad_end =
10379 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10380 end_too_large, loc);
10381 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10382 bad_index, loc);
7a938933
ILT
10383 }
10384
6ddb6288 10385 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
7035307e
CM
10386 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10387 val = gogo->backend()->pointer_offset_expression(val, start, loc);
7a938933 10388
7035307e
CM
10389 Bexpression* result_length =
10390 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
7a938933 10391
7035307e
CM
10392 Bexpression* result_capacity =
10393 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
7a938933 10394
7035307e
CM
10395 Btype* struct_btype = this->type()->get_backend(gogo);
10396 std::vector<Bexpression*> init;
10397 init.push_back(val);
10398 init.push_back(result_length);
10399 init.push_back(result_capacity);
7a938933 10400
7035307e
CM
10401 Bexpression* ctor =
10402 gogo->backend()->constructor_expression(struct_btype, init, loc);
10403 Bexpression* ret =
10404 gogo->backend()->conditional_expression(struct_btype, bad_index,
10405 crash, ctor, loc);
7a938933 10406
7035307e 10407 return expr_to_tree(ret);
7a938933
ILT
10408}
10409
16c57fe2
RL
10410// Dump ast representation for an array index expression.
10411
10412void
10413Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10414 const
10415{
10416 Index_expression::dump_index_expression(ast_dump_context, this->array_,
26b8f7eb 10417 this->start_, this->end_, this->cap_);
16c57fe2
RL
10418}
10419
26b8f7eb 10420// Make an array index expression. END and CAP may be NULL.
7a938933
ILT
10421
10422Expression*
10423Expression::make_array_index(Expression* array, Expression* start,
26b8f7eb
ILT
10424 Expression* end, Expression* cap,
10425 Location location)
7a938933 10426{
26b8f7eb 10427 return new Array_index_expression(array, start, end, cap, location);
7a938933
ILT
10428}
10429
10430// A string index. This is used for both indexing and slicing.
10431
10432class String_index_expression : public Expression
10433{
10434 public:
10435 String_index_expression(Expression* string, Expression* start,
8afa2bfb 10436 Expression* end, Location location)
7a938933
ILT
10437 : Expression(EXPRESSION_STRING_INDEX, location),
10438 string_(string), start_(start), end_(end)
10439 { }
10440
10441 protected:
10442 int
10443 do_traverse(Traverse*);
10444
7035307e
CM
10445 Expression*
10446 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10447
7a938933
ILT
10448 Type*
10449 do_type();
10450
10451 void
10452 do_determine_type(const Type_context*);
10453
10454 void
10455 do_check_types(Gogo*);
10456
10457 Expression*
10458 do_copy()
10459 {
10460 return Expression::make_string_index(this->string_->copy(),
10461 this->start_->copy(),
10462 (this->end_ == NULL
10463 ? NULL
10464 : this->end_->copy()),
10465 this->location());
10466 }
10467
cbe98a41
ILT
10468 bool
10469 do_must_eval_subexpressions_in_order(int* skip) const
10470 {
10471 *skip = 1;
10472 return true;
10473 }
10474
7a938933
ILT
10475 tree
10476 do_get_tree(Translate_context*);
10477
16c57fe2
RL
10478 void
10479 do_dump_expression(Ast_dump_context*) const;
10480
7a938933
ILT
10481 private:
10482 // The string we are getting a value from.
10483 Expression* string_;
10484 // The start or only index.
10485 Expression* start_;
10486 // The end index of a slice. This may be NULL for a single index,
10487 // or it may be a nil expression for the length of the string.
10488 Expression* end_;
10489};
10490
10491// String index traversal.
10492
10493int
10494String_index_expression::do_traverse(Traverse* traverse)
10495{
10496 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10497 return TRAVERSE_EXIT;
10498 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10499 return TRAVERSE_EXIT;
10500 if (this->end_ != NULL)
10501 {
10502 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10503 return TRAVERSE_EXIT;
10504 }
10505 return TRAVERSE_CONTINUE;
10506}
10507
7035307e
CM
10508Expression*
10509String_index_expression::do_flatten(Gogo*, Named_object*,
10510 Statement_inserter* inserter)
7a938933 10511{
7035307e
CM
10512 Temporary_statement* temp;
10513 Location loc = this->location();
10514 if (!this->string_->is_variable())
10515 {
10516 temp = Statement::make_temporary(NULL, this->string_, loc);
10517 inserter->insert(temp);
10518 this->string_ = Expression::make_temporary_reference(temp, loc);
10519 }
10520 if (!this->start_->is_variable())
10521 {
10522 temp = Statement::make_temporary(NULL, this->start_, loc);
10523 inserter->insert(temp);
10524 this->start_ = Expression::make_temporary_reference(temp, loc);
10525 }
10526 if (this->end_ != NULL
10527 && !this->end_->is_nil_expression()
10528 && !this->end_->is_variable())
10529 {
10530 temp = Statement::make_temporary(NULL, this->end_, loc);
10531 inserter->insert(temp);
10532 this->end_ = Expression::make_temporary_reference(temp, loc);
10533 }
10534
10535 return this;
10536}
10537
10538// Return the type of a string index.
10539
10540Type*
10541String_index_expression::do_type()
10542{
10543 if (this->end_ == NULL)
10544 return Type::lookup_integer_type("uint8");
10545 else
10546 return this->string_->type();
10547}
10548
10549// Determine the type of a string index.
10550
10551void
10552String_index_expression::do_determine_type(const Type_context*)
10553{
10554 this->string_->determine_type_no_context();
10555 this->start_->determine_type_no_context();
7a938933 10556 if (this->end_ != NULL)
e811e209 10557 this->end_->determine_type_no_context();
7a938933
ILT
10558}
10559
10560// Check types of a string index.
10561
10562void
10563String_index_expression::do_check_types(Gogo*)
10564{
0213a547
ILT
10565 Numeric_constant nc;
10566 unsigned long v;
10567 if (this->start_->type()->integer_type() == NULL
10568 && !this->start_->type()->is_error()
10569 && (!this->start_->numeric_constant_value(&nc)
10570 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
7a938933
ILT
10571 this->report_error(_("index must be integer"));
10572 if (this->end_ != NULL
10573 && this->end_->type()->integer_type() == NULL
0213a547
ILT
10574 && !this->end_->type()->is_error()
10575 && !this->end_->is_nil_expression()
10576 && !this->end_->is_error_expression()
10577 && (!this->end_->numeric_constant_value(&nc)
10578 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
7a938933
ILT
10579 this->report_error(_("slice end must be integer"));
10580
10581 std::string sval;
10582 bool sval_valid = this->string_->string_constant_value(&sval);
10583
5caf63ca 10584 Numeric_constant inc;
7a938933 10585 mpz_t ival;
f2b2ead4 10586 bool ival_valid = false;
5caf63ca 10587 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
7a938933 10588 {
f2b2ead4 10589 ival_valid = true;
7a938933
ILT
10590 if (mpz_sgn(ival) < 0
10591 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10592 {
10593 error_at(this->start_->location(), "string index out of bounds");
10594 this->set_is_error();
10595 }
10596 }
10597 if (this->end_ != NULL && !this->end_->is_nil_expression())
10598 {
5caf63ca
ILT
10599 Numeric_constant enc;
10600 mpz_t eval;
10601 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
7a938933 10602 {
5caf63ca
ILT
10603 if (mpz_sgn(eval) < 0
10604 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
7a938933
ILT
10605 {
10606 error_at(this->end_->location(), "string index out of bounds");
10607 this->set_is_error();
10608 }
f2b2ead4
ILT
10609 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10610 this->report_error(_("inverted slice range"));
5caf63ca 10611 mpz_clear(eval);
7a938933
ILT
10612 }
10613 }
f2b2ead4
ILT
10614 if (ival_valid)
10615 mpz_clear(ival);
7a938933
ILT
10616}
10617
10618// Get a tree for a string index.
10619
10620tree
10621String_index_expression::do_get_tree(Translate_context* context)
10622{
8afa2bfb 10623 Location loc = this->location();
7035307e
CM
10624 Expression* string_arg = this->string_;
10625 if (this->string_->type()->points_to() != NULL)
10626 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
7a938933 10627
7035307e 10628 Expression* bad_index = Expression::check_bounds(this->start_, loc);
7a938933 10629
7035307e
CM
10630 int code = (this->end_ == NULL
10631 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10632 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
7a938933 10633
7035307e
CM
10634 Gogo* gogo = context->gogo();
10635 Bexpression* crash =
10636 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
776f27a6
ILT
10637
10638 Type* int_type = Type::lookup_integer_type("int");
7a938933 10639
7035307e
CM
10640 // It is possible that an error occurred earlier because the start index
10641 // cannot be represented as an integer type. In this case, we shouldn't
10642 // try casting the starting index into an integer since
10643 // Type_conversion_expression will fail to get the backend representation.
10644 // FIXME.
10645 if (this->start_->type()->integer_type() == NULL
10646 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10647 {
10648 go_assert(saw_errors());
10649 return error_mark_node;
10650 }
7a938933 10651
7035307e 10652 Expression* start = Expression::make_cast(int_type, this->start_, loc);
7a938933 10653
7035307e
CM
10654 if (this->end_ == NULL)
10655 {
10656 Expression* length =
10657 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
7a938933 10658
7035307e
CM
10659 Expression* start_too_large =
10660 Expression::make_binary(OPERATOR_GE, start, length, loc);
10661 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10662 bad_index, loc);
10663 Expression* bytes =
10664 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
7a938933 10665
7035307e
CM
10666 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10667 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10668 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10669 Bexpression* index = gogo->backend()->indirect_expression(ptr, true, loc);
7a938933 10670
7035307e
CM
10671 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10672 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10673 Bexpression* ret =
10674 gogo->backend()->conditional_expression(byte_btype, index_error,
10675 crash, index, loc);
10676 return expr_to_tree(ret);
10677 }
10678
10679 Expression* end = NULL;
10680 if (this->end_->is_nil_expression())
7a938933 10681 {
7035307e
CM
10682 mpz_t neg_one;
10683 mpz_init_set_si(neg_one, -1);
10684 end = Expression::make_integer(&neg_one, int_type, loc);
10685 mpz_clear(neg_one);
7a938933
ILT
10686 }
10687 else
10688 {
7035307e
CM
10689 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10690 bad_index =
10691 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10692 end = Expression::make_cast(int_type, this->end_, loc);
7a938933 10693 }
7035307e
CM
10694
10695 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10696 string_arg, start, end);
10697 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10698
10699 Btype* str_btype = strslice->type()->get_backend(gogo);
10700 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10701 Bexpression* ret =
10702 gogo->backend()->conditional_expression(str_btype, index_error,
10703 crash, bstrslice, loc);
10704 return expr_to_tree(ret);
7a938933
ILT
10705}
10706
16c57fe2
RL
10707// Dump ast representation for a string index expression.
10708
10709void
10710String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10711 const
10712{
26b8f7eb
ILT
10713 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10714 this->start_, this->end_, NULL);
16c57fe2
RL
10715}
10716
7a938933
ILT
10717// Make a string index expression. END may be NULL.
10718
10719Expression*
10720Expression::make_string_index(Expression* string, Expression* start,
8afa2bfb 10721 Expression* end, Location location)
7a938933
ILT
10722{
10723 return new String_index_expression(string, start, end, location);
10724}
10725
10726// Class Map_index.
10727
10728// Get the type of the map.
10729
10730Map_type*
10731Map_index_expression::get_map_type() const
10732{
10733 Map_type* mt = this->map_->type()->deref()->map_type();
7cfc62ba 10734 if (mt == NULL)
26409c52 10735 go_assert(saw_errors());
7a938933
ILT
10736 return mt;
10737}
10738
10739// Map index traversal.
10740
10741int
10742Map_index_expression::do_traverse(Traverse* traverse)
10743{
10744 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10745 return TRAVERSE_EXIT;
10746 return Expression::traverse(&this->index_, traverse);
10747}
10748
7035307e
CM
10749// We need to pass in a pointer to the key, so flatten the index into a
10750// temporary variable if it isn't already. The value pointer will be
10751// dereferenced and checked for nil, so flatten into a temporary to avoid
10752// recomputation.
10753
10754Expression*
10755Map_index_expression::do_flatten(Gogo*, Named_object*,
10756 Statement_inserter* inserter)
10757{
10758 Map_type* mt = this->get_map_type();
10759 if (this->index_->type() != mt->key_type())
10760 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10761 this->location());
10762
10763 if (!this->index_->is_variable())
10764 {
10765 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10766 this->location());
10767 inserter->insert(temp);
10768 this->index_ = Expression::make_temporary_reference(temp,
10769 this->location());
10770 }
10771
10772 if (this->value_pointer_ == NULL)
10773 this->get_value_pointer(this->is_lvalue_);
10774 if (!this->value_pointer_->is_variable())
10775 {
10776 Temporary_statement* temp =
10777 Statement::make_temporary(NULL, this->value_pointer_,
10778 this->location());
10779 inserter->insert(temp);
10780 this->value_pointer_ =
10781 Expression::make_temporary_reference(temp, this->location());
10782 }
10783
10784 return this;
10785}
10786
7a938933
ILT
10787// Return the type of a map index.
10788
10789Type*
10790Map_index_expression::do_type()
10791{
7cfc62ba
ILT
10792 Map_type* mt = this->get_map_type();
10793 if (mt == NULL)
10794 return Type::make_error_type();
10795 Type* type = mt->val_type();
7a938933
ILT
10796 // If this map index is in a tuple assignment, we actually return a
10797 // pointer to the value type. Tuple_map_assignment_statement is
10798 // responsible for handling this correctly. We need to get the type
10799 // right in case this gets assigned to a temporary variable.
10800 if (this->is_in_tuple_assignment_)
10801 type = Type::make_pointer_type(type);
10802 return type;
10803}
10804
10805// Fix the type of a map index.
10806
10807void
10808Map_index_expression::do_determine_type(const Type_context*)
10809{
10810 this->map_->determine_type_no_context();
7cfc62ba
ILT
10811 Map_type* mt = this->get_map_type();
10812 Type* key_type = mt == NULL ? NULL : mt->key_type();
10813 Type_context subcontext(key_type, false);
7a938933
ILT
10814 this->index_->determine_type(&subcontext);
10815}
10816
10817// Check types of a map index.
10818
10819void
10820Map_index_expression::do_check_types(Gogo*)
10821{
10822 std::string reason;
7cfc62ba
ILT
10823 Map_type* mt = this->get_map_type();
10824 if (mt == NULL)
10825 return;
10826 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
7a938933
ILT
10827 {
10828 if (reason.empty())
10829 this->report_error(_("incompatible type for map index"));
10830 else
10831 {
10832 error_at(this->location(), "incompatible type for map index (%s)",
10833 reason.c_str());
10834 this->set_is_error();
10835 }
10836 }
10837}
10838
10839// Get a tree for a map index.
10840
10841tree
10842Map_index_expression::do_get_tree(Translate_context* context)
10843{
10844 Map_type* type = this->get_map_type();
7cfc62ba 10845 if (type == NULL)
7035307e
CM
10846 {
10847 go_assert(saw_errors());
10848 return error_mark_node;
10849 }
7a938933 10850
7035307e
CM
10851 go_assert(this->value_pointer_ != NULL
10852 && this->value_pointer_->is_variable());
7a938933 10853
7035307e 10854 Bexpression* ret;
7a938933 10855 if (this->is_lvalue_)
7035307e
CM
10856 {
10857 Expression* val =
10858 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10859 this->location());
10860 ret = tree_to_expr(val->get_tree(context));
10861 }
7a938933
ILT
10862 else if (this->is_in_tuple_assignment_)
10863 {
10864 // Tuple_map_assignment_statement is responsible for using this
10865 // appropriately.
7035307e 10866 ret = tree_to_expr(this->value_pointer_->get_tree(context));
7a938933
ILT
10867 }
10868 else
10869 {
7035307e
CM
10870 Location loc = this->location();
10871
10872 Expression* nil_check =
10873 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10874 Expression::make_nil(loc), loc);
10875 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10876 Expression* val =
10877 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10878 Bexpression* bval = tree_to_expr(val->get_tree(context));
10879
54466dde
ILT
10880 Gogo* gogo = context->gogo();
10881 Btype* val_btype = type->val_type()->get_backend(gogo);
10882 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
7035307e
CM
10883 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10884 val_zero, bval, loc);
7a938933 10885 }
7035307e
CM
10886
10887 return expr_to_tree(ret);
7a938933
ILT
10888}
10889
7035307e
CM
10890// Get an expression for the map index. This returns an expression which
10891// evaluates to a pointer to a value. The pointer will be NULL if the key is
7a938933
ILT
10892// not in the map.
10893
7035307e
CM
10894Expression*
10895Map_index_expression::get_value_pointer(bool insert)
7a938933 10896{
7035307e 10897 if (this->value_pointer_ == NULL)
76ace672 10898 {
7035307e
CM
10899 Map_type* type = this->get_map_type();
10900 if (type == NULL)
76ace672 10901 {
7035307e
CM
10902 go_assert(saw_errors());
10903 return Expression::make_error(this->location());
76ace672 10904 }
7a938933 10905
7035307e
CM
10906 Location loc = this->location();
10907 Expression* map_ref = this->map_;
10908 if (this->map_->type()->points_to() != NULL)
10909 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
7a938933 10910
7035307e
CM
10911 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10912 loc);
10913 Expression* map_index =
10914 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10915 map_ref, index_ptr,
10916 Expression::make_boolean(insert, loc));
10917
10918 Type* val_type = type->val_type();
10919 this->value_pointer_ =
10920 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10921 map_index, this->location());
10922 }
10923 return this->value_pointer_;
7a938933
ILT
10924}
10925
16c57fe2
RL
10926// Dump ast representation for a map index expression
10927
10928void
10929Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10930 const
10931{
26b8f7eb
ILT
10932 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10933 this->index_, NULL, NULL);
16c57fe2
RL
10934}
10935
7a938933
ILT
10936// Make a map index expression.
10937
10938Map_index_expression*
10939Expression::make_map_index(Expression* map, Expression* index,
8afa2bfb 10940 Location location)
7a938933
ILT
10941{
10942 return new Map_index_expression(map, index, location);
10943}
10944
10945// Class Field_reference_expression.
10946
744c3195
ILT
10947// Lower a field reference expression. There is nothing to lower, but
10948// this is where we generate the tracking information for fields with
10949// the magic go:"track" tag.
10950
10951Expression*
10952Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10953 Statement_inserter* inserter, int)
10954{
10955 Struct_type* struct_type = this->expr_->type()->struct_type();
10956 if (struct_type == NULL)
10957 {
10958 // Error will be reported elsewhere.
10959 return this;
10960 }
10961 const Struct_field* field = struct_type->field(this->field_index_);
10962 if (field == NULL)
10963 return this;
10964 if (!field->has_tag())
10965 return this;
10966 if (field->tag().find("go:\"track\"") == std::string::npos)
10967 return this;
10968
10969 // We have found a reference to a tracked field. Build a call to
10970 // the runtime function __go_fieldtrack with a string that describes
10971 // the field. FIXME: We should only call this once per referenced
10972 // field per function, not once for each reference to the field.
10973
10974 if (this->called_fieldtrack_)
10975 return this;
10976 this->called_fieldtrack_ = true;
10977
10978 Location loc = this->location();
10979
10980 std::string s = "fieldtrack \"";
10981 Named_type* nt = this->expr_->type()->named_type();
10982 if (nt == NULL || nt->named_object()->package() == NULL)
10983 s.append(gogo->pkgpath());
10984 else
10985 s.append(nt->named_object()->package()->pkgpath());
10986 s.push_back('.');
10987 if (nt != NULL)
df9471b6 10988 s.append(Gogo::unpack_hidden_name(nt->name()));
744c3195
ILT
10989 s.push_back('.');
10990 s.append(field->field_name());
10991 s.push_back('"');
10992
10993 // We can't use a string here, because internally a string holds a
10994 // pointer to the actual bytes; when the linker garbage collects the
10995 // string, it won't garbage collect the bytes. So we use a
10996 // [...]byte.
10997
10998 mpz_t val;
10999 mpz_init_set_ui(val, s.length());
11000 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11001 mpz_clear(val);
11002
11003 Type* byte_type = gogo->lookup_global("byte")->type_value();
11004 Type* array_type = Type::make_array_type(byte_type, length_expr);
11005
11006 Expression_list* bytes = new Expression_list();
11007 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11008 {
11009 mpz_init_set_ui(val, *p);
11010 Expression* byte = Expression::make_integer(&val, NULL, loc);
11011 mpz_clear(val);
11012 bytes->push_back(byte);
11013 }
11014
11015 Expression* e = Expression::make_composite_literal(array_type, 0, false,
8ae4c35c 11016 bytes, false, loc);
744c3195
ILT
11017
11018 Variable* var = new Variable(array_type, e, true, false, false, loc);
11019
11020 static int count;
11021 char buf[50];
11022 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11023 ++count;
11024
11025 Named_object* no = gogo->add_variable(buf, var);
11026 e = Expression::make_var_reference(no, loc);
11027 e = Expression::make_unary(OPERATOR_AND, e, loc);
11028
11029 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11030 inserter->insert(Statement::make_statement(call, false));
11031
11032 // Put this function, and the global variable we just created, into
11033 // unique sections. This will permit the linker to garbage collect
11034 // them if they are not referenced. The effect is that the only
11035 // strings, indicating field references, that will wind up in the
11036 // executable will be those for functions that are actually needed.
9cc263b8
ILT
11037 if (function != NULL)
11038 function->func_value()->set_in_unique_section();
744c3195
ILT
11039 var->set_in_unique_section();
11040
11041 return this;
11042}
11043
7a938933
ILT
11044// Return the type of a field reference.
11045
11046Type*
11047Field_reference_expression::do_type()
11048{
0f9f95ad 11049 Type* type = this->expr_->type();
02ed921a 11050 if (type->is_error())
0f9f95ad
ILT
11051 return type;
11052 Struct_type* struct_type = type->struct_type();
26409c52 11053 go_assert(struct_type != NULL);
7a938933
ILT
11054 return struct_type->field(this->field_index_)->type();
11055}
11056
11057// Check the types for a field reference.
11058
11059void
11060Field_reference_expression::do_check_types(Gogo*)
11061{
0f9f95ad 11062 Type* type = this->expr_->type();
02ed921a 11063 if (type->is_error())
0f9f95ad
ILT
11064 return;
11065 Struct_type* struct_type = type->struct_type();
26409c52
ILT
11066 go_assert(struct_type != NULL);
11067 go_assert(struct_type->field(this->field_index_) != NULL);
7a938933
ILT
11068}
11069
11070// Get a tree for a field reference.
11071
11072tree
11073Field_reference_expression::do_get_tree(Translate_context* context)
11074{
71eba7a0
CM
11075 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11076 Bexpression* ret =
11077 context->gogo()->backend()->struct_field_expression(bstruct,
11078 this->field_index_,
11079 this->location());
11080 return expr_to_tree(ret);
7a938933
ILT
11081}
11082
16c57fe2
RL
11083// Dump ast representation for a field reference expression.
11084
11085void
11086Field_reference_expression::do_dump_expression(
11087 Ast_dump_context* ast_dump_context) const
11088{
11089 this->expr_->dump_expression(ast_dump_context);
11090 ast_dump_context->ostream() << "." << this->field_index_;
11091}
11092
7a938933
ILT
11093// Make a reference to a qualified identifier in an expression.
11094
11095Field_reference_expression*
11096Expression::make_field_reference(Expression* expr, unsigned int field_index,
8afa2bfb 11097 Location location)
7a938933
ILT
11098{
11099 return new Field_reference_expression(expr, field_index, location);
11100}
11101
11102// Class Interface_field_reference_expression.
11103
eb6eb862 11104// Return an expression for the pointer to the function to call.
7a938933 11105
eb6eb862
CM
11106Expression*
11107Interface_field_reference_expression::get_function()
7a938933 11108{
eb6eb862
CM
11109 Expression* ref = this->expr_;
11110 Location loc = this->location();
11111 if (ref->type()->points_to() != NULL)
11112 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
7a938933 11113
eb6eb862
CM
11114 Expression* mtable =
11115 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11116 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
7a938933
ILT
11117
11118 std::string name = Gogo::unpack_hidden_name(this->name_);
eb6eb862
CM
11119 unsigned int index;
11120 const Struct_field* field = mtable_type->find_local_field(name, &index);
11121 go_assert(field != NULL);
11122 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11123 return Expression::make_field_reference(mtable, index, loc);
7a938933
ILT
11124}
11125
eb6eb862 11126// Return an expression for the first argument to pass to the interface
7a938933
ILT
11127// function.
11128
eb6eb862
CM
11129Expression*
11130Interface_field_reference_expression::get_underlying_object()
7a938933 11131{
eb6eb862
CM
11132 Expression* expr = this->expr_;
11133 if (expr->type()->points_to() != NULL)
11134 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11135 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11136 this->location());
7a938933
ILT
11137}
11138
11139// Traversal.
11140
11141int
11142Interface_field_reference_expression::do_traverse(Traverse* traverse)
11143{
11144 return Expression::traverse(&this->expr_, traverse);
11145}
11146
571d3f91
ILT
11147// Lower the expression. If this expression is not called, we need to
11148// evaluate the expression twice when converting to the backend
11149// interface. So introduce a temporary variable if necessary.
11150
11151Expression*
11152Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11153 Statement_inserter* inserter,
11154 int)
11155{
eb6eb862 11156 if (!this->expr_->is_variable())
571d3f91
ILT
11157 {
11158 Temporary_statement* temp =
11159 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11160 inserter->insert(temp);
11161 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11162 this->location());
11163 }
11164 return this;
11165}
11166
7a938933
ILT
11167// Return the type of an interface field reference.
11168
11169Type*
11170Interface_field_reference_expression::do_type()
11171{
11172 Type* expr_type = this->expr_->type();
11173
11174 Type* points_to = expr_type->points_to();
11175 if (points_to != NULL)
11176 expr_type = points_to;
11177
11178 Interface_type* interface_type = expr_type->interface_type();
11179 if (interface_type == NULL)
11180 return Type::make_error_type();
11181
11182 const Typed_identifier* method = interface_type->find_method(this->name_);
11183 if (method == NULL)
11184 return Type::make_error_type();
11185
11186 return method->type();
11187}
11188
11189// Determine types.
11190
11191void
11192Interface_field_reference_expression::do_determine_type(const Type_context*)
11193{
11194 this->expr_->determine_type_no_context();
11195}
11196
11197// Check the types for an interface field reference.
11198
11199void
11200Interface_field_reference_expression::do_check_types(Gogo*)
11201{
11202 Type* type = this->expr_->type();
11203
11204 Type* points_to = type->points_to();
11205 if (points_to != NULL)
11206 type = points_to;
11207
11208 Interface_type* interface_type = type->interface_type();
11209 if (interface_type == NULL)
f7b8b261
ILT
11210 {
11211 if (!type->is_error_type())
11212 this->report_error(_("expected interface or pointer to interface"));
11213 }
7a938933
ILT
11214 else
11215 {
11216 const Typed_identifier* method =
11217 interface_type->find_method(this->name_);
11218 if (method == NULL)
11219 {
11220 error_at(this->location(), "method %qs not in interface",
11221 Gogo::message_name(this->name_).c_str());
11222 this->set_is_error();
11223 }
11224 }
11225}
11226
571d3f91
ILT
11227// If an interface field reference is not simply called, then it is
11228// represented as a closure. The closure will hold a single variable,
11229// the value of the interface on which the method should be called.
11230// The function will be a simple thunk that pulls the value from the
11231// closure and calls the method with the remaining arguments.
11232
11233// Because method values are not common, we don't build all thunks for
11234// all possible interface methods, but instead only build them as we
11235// need them. In particular, we even build them on demand for
11236// interface methods defined in other packages.
11237
11238Interface_field_reference_expression::Interface_method_thunks
11239 Interface_field_reference_expression::interface_method_thunks;
11240
11241// Find or create the thunk to call method NAME on TYPE.
11242
11243Named_object*
11244Interface_field_reference_expression::create_thunk(Gogo* gogo,
11245 Interface_type* type,
11246 const std::string& name)
11247{
11248 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11249 std::pair<Interface_method_thunks::iterator, bool> ins =
11250 Interface_field_reference_expression::interface_method_thunks.insert(val);
11251 if (ins.second)
11252 {
11253 // This is the first time we have seen this interface.
11254 ins.first->second = new Method_thunks();
11255 }
11256
11257 for (Method_thunks::const_iterator p = ins.first->second->begin();
11258 p != ins.first->second->end();
11259 p++)
11260 if (p->first == name)
11261 return p->second;
11262
11263 Location loc = type->location();
11264
11265 const Typed_identifier* method_id = type->find_method(name);
11266 if (method_id == NULL)
11267 return Named_object::make_erroneous_name(Gogo::thunk_name());
11268
11269 Function_type* orig_fntype = method_id->type()->function_type();
11270 if (orig_fntype == NULL)
11271 return Named_object::make_erroneous_name(Gogo::thunk_name());
11272
11273 Struct_field_list* sfl = new Struct_field_list();
05a7d566
ILT
11274 // The type here is wrong--it should be the C function type. But it
11275 // doesn't really matter.
571d3f91
ILT
11276 Type* vt = Type::make_pointer_type(Type::make_void_type());
11277 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11278 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11279 Type* closure_type = Type::make_struct_type(sfl, loc);
11280 closure_type = Type::make_pointer_type(closure_type);
11281
05a7d566 11282 Function_type* new_fntype = orig_fntype->copy_with_names();
571d3f91
ILT
11283
11284 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11285 false, loc);
11286
05a7d566
ILT
11287 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11288 cvar->set_is_used();
11289 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11290 new_no->func_value()->set_closure_var(cp);
571d3f91 11291
05a7d566 11292 gogo->start_block(loc);
571d3f91
ILT
11293
11294 // Field 0 of the closure is the function code pointer, field 1 is
11295 // the value on which to invoke the method.
11296 Expression* arg = Expression::make_var_reference(cp, loc);
11297 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11298 arg = Expression::make_field_reference(arg, 1, loc);
11299
11300 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11301 loc);
11302
11303 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11304 Expression_list* args;
11305 if (orig_params == NULL || orig_params->empty())
11306 args = NULL;
11307 else
11308 {
11309 const Typed_identifier_list* new_params = new_fntype->parameters();
11310 args = new Expression_list();
11311 for (Typed_identifier_list::const_iterator p = new_params->begin();
05a7d566 11312 p != new_params->end();
571d3f91
ILT
11313 ++p)
11314 {
11315 Named_object* p_no = gogo->lookup(p->name(), NULL);
11316 go_assert(p_no != NULL
11317 && p_no->is_variable()
11318 && p_no->var_value()->is_parameter());
11319 args->push_back(Expression::make_var_reference(p_no, loc));
11320 }
11321 }
11322
11323 Call_expression* call = Expression::make_call(ifre, args,
11324 orig_fntype->is_varargs(),
11325 loc);
11326 call->set_varargs_are_lowered();
11327
11328 Statement* s = Statement::make_return_from_call(call, loc);
11329 gogo->add_statement(s);
11330 Block* b = gogo->finish_block(loc);
11331 gogo->add_block(b, loc);
11332 gogo->lower_block(new_no, b);
b5407ad1 11333 gogo->flatten_block(new_no, b);
571d3f91
ILT
11334 gogo->finish_function(loc);
11335
11336 ins.first->second->push_back(std::make_pair(name, new_no));
11337 return new_no;
11338}
11339
11340// Get a tree for a method value.
7a938933
ILT
11341
11342tree
571d3f91 11343Interface_field_reference_expression::do_get_tree(Translate_context* context)
7a938933 11344{
571d3f91
ILT
11345 Interface_type* type = this->expr_->type()->interface_type();
11346 if (type == NULL)
11347 {
11348 go_assert(saw_errors());
11349 return error_mark_node;
11350 }
11351
11352 Named_object* thunk =
11353 Interface_field_reference_expression::create_thunk(context->gogo(),
11354 type, this->name_);
11355 if (thunk->is_erroneous())
11356 {
11357 go_assert(saw_errors());
11358 return error_mark_node;
11359 }
11360
11361 // FIXME: We should lower this earlier, but we can't it lower it in
11362 // the lowering pass because at that point we don't know whether we
11363 // need to create the thunk or not. If the expression is called, we
11364 // don't need the thunk.
11365
11366 Location loc = this->location();
11367
11368 Struct_field_list* fields = new Struct_field_list();
11369 fields->push_back(Struct_field(Typed_identifier("fn.0",
11370 thunk->func_value()->type(),
11371 loc)));
11372 fields->push_back(Struct_field(Typed_identifier("val.1",
11373 this->expr_->type(),
11374 loc)));
11375 Struct_type* st = Type::make_struct_type(fields, loc);
11376
11377 Expression_list* vals = new Expression_list();
11378 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11379 vals->push_back(this->expr_);
11380
11381 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
7035307e 11382 expr = Expression::make_heap_expression(expr, loc);
571d3f91 11383
eb6eb862
CM
11384 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11385 Expression* nil_check =
11386 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11387 Expression::make_nil(loc), loc);
11388 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
571d3f91 11389
eb6eb862
CM
11390 Gogo* gogo = context->gogo();
11391 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11392 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11393
11394 Bexpression* bcond =
b5407ad1 11395 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
eb6eb862
CM
11396 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11397 Bexpression* ret =
11398 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11399 return expr_to_tree(ret);
7a938933
ILT
11400}
11401
16c57fe2
RL
11402// Dump ast representation for an interface field reference.
11403
11404void
11405Interface_field_reference_expression::do_dump_expression(
11406 Ast_dump_context* ast_dump_context) const
11407{
11408 this->expr_->dump_expression(ast_dump_context);
11409 ast_dump_context->ostream() << "." << this->name_;
11410}
11411
7a938933
ILT
11412// Make a reference to a field in an interface.
11413
11414Expression*
11415Expression::make_interface_field_reference(Expression* expr,
11416 const std::string& field,
8afa2bfb 11417 Location location)
7a938933
ILT
11418{
11419 return new Interface_field_reference_expression(expr, field, location);
11420}
11421
11422// A general selector. This is a Parser_expression for LEFT.NAME. It
11423// is lowered after we know the type of the left hand side.
11424
11425class Selector_expression : public Parser_expression
11426{
11427 public:
11428 Selector_expression(Expression* left, const std::string& name,
8afa2bfb 11429 Location location)
7a938933
ILT
11430 : Parser_expression(EXPRESSION_SELECTOR, location),
11431 left_(left), name_(name)
11432 { }
11433
11434 protected:
11435 int
11436 do_traverse(Traverse* traverse)
11437 { return Expression::traverse(&this->left_, traverse); }
11438
11439 Expression*
8586635c 11440 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7a938933
ILT
11441
11442 Expression*
11443 do_copy()
11444 {
11445 return new Selector_expression(this->left_->copy(), this->name_,
11446 this->location());
11447 }
11448
16c57fe2
RL
11449 void
11450 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11451
7a938933
ILT
11452 private:
11453 Expression*
11454 lower_method_expression(Gogo*);
11455
11456 // The expression on the left hand side.
11457 Expression* left_;
11458 // The name on the right hand side.
11459 std::string name_;
11460};
11461
11462// Lower a selector expression once we know the real type of the left
11463// hand side.
11464
11465Expression*
8586635c
ILT
11466Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11467 int)
7a938933
ILT
11468{
11469 Expression* left = this->left_;
11470 if (left->is_type_expression())
11471 return this->lower_method_expression(gogo);
11472 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11473 this->location());
11474}
11475
11476// Lower a method expression T.M or (*T).M. We turn this into a
11477// function literal.
11478
11479Expression*
11480Selector_expression::lower_method_expression(Gogo* gogo)
11481{
8afa2bfb 11482 Location location = this->location();
7a938933
ILT
11483 Type* type = this->left_->type();
11484 const std::string& name(this->name_);
11485
11486 bool is_pointer;
11487 if (type->points_to() == NULL)
11488 is_pointer = false;
11489 else
11490 {
11491 is_pointer = true;
11492 type = type->points_to();
11493 }
11494 Named_type* nt = type->named_type();
11495 if (nt == NULL)
11496 {
11497 error_at(location,
11498 ("method expression requires named type or "
11499 "pointer to named type"));
11500 return Expression::make_error(location);
11501 }
11502
11503 bool is_ambiguous;
11504 Method* method = nt->method_function(name, &is_ambiguous);
80607544 11505 const Typed_identifier* imethod = NULL;
e45f44f3 11506 if (method == NULL && !is_pointer)
80607544
ILT
11507 {
11508 Interface_type* it = nt->interface_type();
11509 if (it != NULL)
11510 imethod = it->find_method(name);
11511 }
11512
11513 if (method == NULL && imethod == NULL)
7a938933
ILT
11514 {
11515 if (!is_ambiguous)
e45f44f3
ILT
11516 error_at(location, "type %<%s%s%> has no method %<%s%>",
11517 is_pointer ? "*" : "",
7a938933
ILT
11518 nt->message_name().c_str(),
11519 Gogo::message_name(name).c_str());
11520 else
e45f44f3 11521 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
7a938933 11522 Gogo::message_name(name).c_str(),
e45f44f3 11523 is_pointer ? "*" : "",
7a938933
ILT
11524 nt->message_name().c_str());
11525 return Expression::make_error(location);
11526 }
11527
80607544 11528 if (method != NULL && !is_pointer && !method->is_value_method())
7a938933
ILT
11529 {
11530 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11531 nt->message_name().c_str(),
11532 Gogo::message_name(name).c_str());
11533 return Expression::make_error(location);
11534 }
11535
11536 // Build a new function type in which the receiver becomes the first
11537 // argument.
80607544
ILT
11538 Function_type* method_type;
11539 if (method != NULL)
11540 {
11541 method_type = method->type();
26409c52 11542 go_assert(method_type->is_method());
80607544
ILT
11543 }
11544 else
11545 {
11546 method_type = imethod->type()->function_type();
26409c52 11547 go_assert(method_type != NULL && !method_type->is_method());
80607544 11548 }
7a938933
ILT
11549
11550 const char* const receiver_name = "$this";
11551 Typed_identifier_list* parameters = new Typed_identifier_list();
11552 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11553 location));
11554
11555 const Typed_identifier_list* method_parameters = method_type->parameters();
11556 if (method_parameters != NULL)
11557 {
3375a6c9 11558 int i = 0;
7a938933
ILT
11559 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11560 p != method_parameters->end();
3375a6c9
ILT
11561 ++p, ++i)
11562 {
b2c4b7b9 11563 if (!p->name().empty())
3375a6c9
ILT
11564 parameters->push_back(*p);
11565 else
11566 {
11567 char buf[20];
11568 snprintf(buf, sizeof buf, "$param%d", i);
11569 parameters->push_back(Typed_identifier(buf, p->type(),
11570 p->location()));
11571 }
11572 }
7a938933
ILT
11573 }
11574
11575 const Typed_identifier_list* method_results = method_type->results();
11576 Typed_identifier_list* results;
11577 if (method_results == NULL)
11578 results = NULL;
11579 else
11580 {
11581 results = new Typed_identifier_list();
11582 for (Typed_identifier_list::const_iterator p = method_results->begin();
11583 p != method_results->end();
11584 ++p)
11585 results->push_back(*p);
11586 }
11587
11588 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11589 location);
11590 if (method_type->is_varargs())
11591 fntype->set_is_varargs();
11592
11593 // We generate methods which always takes a pointer to the receiver
11594 // as their first argument. If this is for a pointer type, we can
11595 // simply reuse the existing function. We use an internal hack to
11596 // get the right type.
fdbc38a6
ILT
11597 // FIXME: This optimization is disabled because it doesn't yet work
11598 // with function descriptors when the method expression is not
11599 // directly called.
11600 if (method != NULL && is_pointer && false)
7a938933
ILT
11601 {
11602 Named_object* mno = (method->needs_stub_method()
11603 ? method->stub_object()
11604 : method->named_object());
11605 Expression* f = Expression::make_func_reference(mno, NULL, location);
11606 f = Expression::make_cast(fntype, f, location);
11607 Type_conversion_expression* tce =
11608 static_cast<Type_conversion_expression*>(f);
11609 tce->set_may_convert_function_types();
11610 return f;
11611 }
11612
11613 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11614 location);
11615
11616 Named_object* vno = gogo->lookup(receiver_name, NULL);
26409c52 11617 go_assert(vno != NULL);
7a938933 11618 Expression* ve = Expression::make_var_reference(vno, location);
80607544
ILT
11619 Expression* bm;
11620 if (method != NULL)
11621 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11622 else
11623 bm = Expression::make_interface_field_reference(ve, name, location);
1e2afadb
ILT
11624
11625 // Even though we found the method above, if it has an error type we
11626 // may see an error here.
11627 if (bm->is_error_expression())
196bc407
ILT
11628 {
11629 gogo->finish_function(location);
11630 return bm;
11631 }
7a938933
ILT
11632
11633 Expression_list* args;
3375a6c9 11634 if (parameters->size() <= 1)
7a938933
ILT
11635 args = NULL;
11636 else
11637 {
11638 args = new Expression_list();
3375a6c9
ILT
11639 Typed_identifier_list::const_iterator p = parameters->begin();
11640 ++p;
11641 for (; p != parameters->end(); ++p)
7a938933
ILT
11642 {
11643 vno = gogo->lookup(p->name(), NULL);
26409c52 11644 go_assert(vno != NULL);
7a938933
ILT
11645 args->push_back(Expression::make_var_reference(vno, location));
11646 }
11647 }
11648
8586635c
ILT
11649 gogo->start_block(location);
11650
7a938933
ILT
11651 Call_expression* call = Expression::make_call(bm, args,
11652 method_type->is_varargs(),
11653 location);
11654
571d3f91 11655 Statement* s = Statement::make_return_from_call(call, location);
7a938933
ILT
11656 gogo->add_statement(s);
11657
8586635c
ILT
11658 Block* b = gogo->finish_block(location);
11659
11660 gogo->add_block(b, location);
11661
11662 // Lower the call in case there are multiple results.
11663 gogo->lower_block(no, b);
b5407ad1 11664 gogo->flatten_block(no, b);
8586635c 11665
7a938933
ILT
11666 gogo->finish_function(location);
11667
11668 return Expression::make_func_reference(no, NULL, location);
11669}
11670
16c57fe2
RL
11671// Dump the ast for a selector expression.
11672
11673void
11674Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11675 const
11676{
11677 ast_dump_context->dump_expression(this->left_);
11678 ast_dump_context->ostream() << ".";
11679 ast_dump_context->ostream() << this->name_;
11680}
11681
7a938933
ILT
11682// Make a selector expression.
11683
11684Expression*
11685Expression::make_selector(Expression* left, const std::string& name,
8afa2bfb 11686 Location location)
7a938933
ILT
11687{
11688 return new Selector_expression(left, name, location);
11689}
11690
11691// Implement the builtin function new.
11692
11693class Allocation_expression : public Expression
11694{
11695 public:
8afa2bfb 11696 Allocation_expression(Type* type, Location location)
7a938933
ILT
11697 : Expression(EXPRESSION_ALLOCATION, location),
11698 type_(type)
11699 { }
11700
11701 protected:
11702 int
11703 do_traverse(Traverse* traverse)
11704 { return Type::traverse(this->type_, traverse); }
11705
11706 Type*
11707 do_type()
11708 { return Type::make_pointer_type(this->type_); }
11709
11710 void
11711 do_determine_type(const Type_context*)
11712 { }
11713
7a938933
ILT
11714 Expression*
11715 do_copy()
11716 { return new Allocation_expression(this->type_, this->location()); }
11717
11718 tree
11719 do_get_tree(Translate_context*);
11720
16c57fe2
RL
11721 void
11722 do_dump_expression(Ast_dump_context*) const;
11723
7a938933
ILT
11724 private:
11725 // The type we are allocating.
11726 Type* type_;
11727};
11728
7a938933
ILT
11729// Return a tree for an allocation expression.
11730
11731tree
11732Allocation_expression::do_get_tree(Translate_context* context)
11733{
7035307e
CM
11734 Gogo* gogo = context->gogo();
11735 Location loc = this->location();
11736 Expression* space = gogo->allocate_memory(this->type_, loc);
11737 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11738 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11739 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11740 return expr_to_tree(ret);
7a938933
ILT
11741}
11742
16c57fe2
RL
11743// Dump ast representation for an allocation expression.
11744
11745void
11746Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11747 const
11748{
11749 ast_dump_context->ostream() << "new(";
11750 ast_dump_context->dump_type(this->type_);
11751 ast_dump_context->ostream() << ")";
11752}
11753
7a938933
ILT
11754// Make an allocation expression.
11755
11756Expression*
8afa2bfb 11757Expression::make_allocation(Type* type, Location location)
7a938933
ILT
11758{
11759 return new Allocation_expression(type, location);
11760}
11761
7a938933
ILT
11762// Construct a struct.
11763
11764class Struct_construction_expression : public Expression
11765{
11766 public:
11767 Struct_construction_expression(Type* type, Expression_list* vals,
8afa2bfb 11768 Location location)
7a938933 11769 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
50f671c6 11770 type_(type), vals_(vals), traverse_order_(NULL)
7a938933
ILT
11771 { }
11772
50f671c6
ILT
11773 // Set the traversal order, used to ensure that we implement the
11774 // order of evaluation rules. Takes ownership of the argument.
11775 void
11776 set_traverse_order(std::vector<int>* traverse_order)
11777 { this->traverse_order_ = traverse_order; }
11778
7a938933
ILT
11779 // Return whether this is a constant initializer.
11780 bool
11781 is_constant_struct() const;
11782
11783 protected:
11784 int
11785 do_traverse(Traverse* traverse);
11786
8a35e18d
CM
11787 bool
11788 do_is_immutable() const;
11789
7a938933
ILT
11790 Type*
11791 do_type()
11792 { return this->type_; }
11793
11794 void
11795 do_determine_type(const Type_context*);
11796
11797 void
11798 do_check_types(Gogo*);
11799
11800 Expression*
11801 do_copy()
11802 {
50f671c6
ILT
11803 Struct_construction_expression* ret =
11804 new Struct_construction_expression(this->type_, this->vals_->copy(),
11805 this->location());
11806 if (this->traverse_order_ != NULL)
11807 ret->set_traverse_order(this->traverse_order_);
11808 return ret;
7a938933
ILT
11809 }
11810
7a938933
ILT
11811 tree
11812 do_get_tree(Translate_context*);
11813
11814 void
11815 do_export(Export*) const;
11816
16c57fe2
RL
11817 void
11818 do_dump_expression(Ast_dump_context*) const;
11819
7a938933
ILT
11820 private:
11821 // The type of the struct to construct.
11822 Type* type_;
11823 // The list of values, in order of the fields in the struct. A NULL
11824 // entry means that the field should be zero-initialized.
11825 Expression_list* vals_;
50f671c6
ILT
11826 // If not NULL, the order in which to traverse vals_. This is used
11827 // so that we implement the order of evaluation rules correctly.
11828 std::vector<int>* traverse_order_;
7a938933
ILT
11829};
11830
11831// Traversal.
11832
11833int
11834Struct_construction_expression::do_traverse(Traverse* traverse)
11835{
50f671c6
ILT
11836 if (this->vals_ != NULL)
11837 {
11838 if (this->traverse_order_ == NULL)
11839 {
11840 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11841 return TRAVERSE_EXIT;
11842 }
11843 else
11844 {
11845 for (std::vector<int>::const_iterator p =
11846 this->traverse_order_->begin();
11847 p != this->traverse_order_->end();
11848 ++p)
11849 {
11850 if (Expression::traverse(&this->vals_->at(*p), traverse)
11851 == TRAVERSE_EXIT)
11852 return TRAVERSE_EXIT;
11853 }
11854 }
11855 }
7a938933
ILT
11856 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11857 return TRAVERSE_EXIT;
11858 return TRAVERSE_CONTINUE;
11859}
11860
11861// Return whether this is a constant initializer.
11862
11863bool
11864Struct_construction_expression::is_constant_struct() const
11865{
11866 if (this->vals_ == NULL)
11867 return true;
11868 for (Expression_list::const_iterator pv = this->vals_->begin();
11869 pv != this->vals_->end();
11870 ++pv)
11871 {
11872 if (*pv != NULL
11873 && !(*pv)->is_constant()
11874 && (!(*pv)->is_composite_literal()
11875 || (*pv)->is_nonconstant_composite_literal()))
11876 return false;
11877 }
11878
11879 const Struct_field_list* fields = this->type_->struct_type()->fields();
11880 for (Struct_field_list::const_iterator pf = fields->begin();
11881 pf != fields->end();
11882 ++pf)
11883 {
11884 // There are no constant constructors for interfaces.
11885 if (pf->type()->interface_type() != NULL)
11886 return false;
11887 }
11888
11889 return true;
11890}
11891
8a35e18d
CM
11892// Return whether this struct is immutable.
11893
11894bool
11895Struct_construction_expression::do_is_immutable() const
11896{
11897 if (this->vals_ == NULL)
11898 return true;
11899 for (Expression_list::const_iterator pv = this->vals_->begin();
11900 pv != this->vals_->end();
11901 ++pv)
11902 {
11903 if (*pv != NULL && !(*pv)->is_immutable())
11904 return false;
11905 }
11906 return true;
11907}
11908
7a938933
ILT
11909// Final type determination.
11910
11911void
11912Struct_construction_expression::do_determine_type(const Type_context*)
11913{
11914 if (this->vals_ == NULL)
11915 return;
11916 const Struct_field_list* fields = this->type_->struct_type()->fields();
11917 Expression_list::const_iterator pv = this->vals_->begin();
11918 for (Struct_field_list::const_iterator pf = fields->begin();
11919 pf != fields->end();
11920 ++pf, ++pv)
11921 {
11922 if (pv == this->vals_->end())
11923 return;
11924 if (*pv != NULL)
11925 {
11926 Type_context subcontext(pf->type(), false);
11927 (*pv)->determine_type(&subcontext);
11928 }
11929 }
9081b67b
ILT
11930 // Extra values are an error we will report elsewhere; we still want
11931 // to determine the type to avoid knockon errors.
11932 for (; pv != this->vals_->end(); ++pv)
11933 (*pv)->determine_type_no_context();
7a938933
ILT
11934}
11935
11936// Check types.
11937
11938void
11939Struct_construction_expression::do_check_types(Gogo*)
11940{
11941 if (this->vals_ == NULL)
11942 return;
11943
11944 Struct_type* st = this->type_->struct_type();
11945 if (this->vals_->size() > st->field_count())
11946 {
11947 this->report_error(_("too many expressions for struct"));
11948 return;
11949 }
11950
11951 const Struct_field_list* fields = st->fields();
11952 Expression_list::const_iterator pv = this->vals_->begin();
11953 int i = 0;
11954 for (Struct_field_list::const_iterator pf = fields->begin();
11955 pf != fields->end();
11956 ++pf, ++pv, ++i)
11957 {
11958 if (pv == this->vals_->end())
11959 {
11960 this->report_error(_("too few expressions for struct"));
11961 break;
11962 }
11963
11964 if (*pv == NULL)
11965 continue;
11966
11967 std::string reason;
11968 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11969 {
11970 if (reason.empty())
11971 error_at((*pv)->location(),
11972 "incompatible type for field %d in struct construction",
11973 i + 1);
11974 else
11975 error_at((*pv)->location(),
11976 ("incompatible type for field %d in "
11977 "struct construction (%s)"),
11978 i + 1, reason.c_str());
11979 this->set_is_error();
11980 }
11981 }
26409c52 11982 go_assert(pv == this->vals_->end());
7a938933
ILT
11983}
11984
11985// Return a tree for constructing a struct.
11986
11987tree
11988Struct_construction_expression::do_get_tree(Translate_context* context)
11989{
11990 Gogo* gogo = context->gogo();
11991
7035307e 11992 Btype* btype = this->type_->get_backend(gogo);
7a938933 11993 if (this->vals_ == NULL)
7035307e 11994 return expr_to_tree(gogo->backend()->zero_expression(btype));
7a938933 11995
7a938933 11996 const Struct_field_list* fields = this->type_->struct_type()->fields();
7a938933 11997 Expression_list::const_iterator pv = this->vals_->begin();
7035307e
CM
11998 std::vector<Bexpression*> init;
11999 for (Struct_field_list::const_iterator pf = fields->begin();
12000 pf != fields->end();
12001 ++pf)
7a938933 12002 {
54466dde 12003 Btype* fbtype = pf->type()->get_backend(gogo);
7a938933 12004 if (pv == this->vals_->end())
7035307e 12005 init.push_back(gogo->backend()->zero_expression(fbtype));
7a938933
ILT
12006 else if (*pv == NULL)
12007 {
7035307e 12008 init.push_back(gogo->backend()->zero_expression(fbtype));
7a938933
ILT
12009 ++pv;
12010 }
12011 else
12012 {
7035307e
CM
12013 Expression* val =
12014 Expression::convert_for_assignment(gogo, pf->type(),
12015 *pv, this->location());
12016 init.push_back(tree_to_expr(val->get_tree(context)));
7a938933
ILT
12017 ++pv;
12018 }
7a938933 12019 }
7a938933 12020
7035307e
CM
12021 Bexpression* ret =
12022 gogo->backend()->constructor_expression(btype, init, this->location());
12023 return expr_to_tree(ret);
7a938933
ILT
12024}
12025
12026// Export a struct construction.
12027
12028void
12029Struct_construction_expression::do_export(Export* exp) const
12030{
12031 exp->write_c_string("convert(");
12032 exp->write_type(this->type_);
12033 for (Expression_list::const_iterator pv = this->vals_->begin();
12034 pv != this->vals_->end();
12035 ++pv)
12036 {
12037 exp->write_c_string(", ");
12038 if (*pv != NULL)
12039 (*pv)->export_expression(exp);
12040 }
12041 exp->write_c_string(")");
12042}
12043
16c57fe2
RL
12044// Dump ast representation of a struct construction expression.
12045
12046void
12047Struct_construction_expression::do_dump_expression(
12048 Ast_dump_context* ast_dump_context) const
12049{
16c57fe2
RL
12050 ast_dump_context->dump_type(this->type_);
12051 ast_dump_context->ostream() << "{";
12052 ast_dump_context->dump_expression_list(this->vals_);
12053 ast_dump_context->ostream() << "}";
12054}
12055
7a938933
ILT
12056// Make a struct composite literal. This used by the thunk code.
12057
12058Expression*
12059Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
8afa2bfb 12060 Location location)
7a938933 12061{
26409c52 12062 go_assert(type->struct_type() != NULL);
7a938933
ILT
12063 return new Struct_construction_expression(type, vals, location);
12064}
12065
12066// Construct an array. This class is not used directly; instead we
12067// use the child classes, Fixed_array_construction_expression and
7035307e 12068// Slice_construction_expression.
7a938933
ILT
12069
12070class Array_construction_expression : public Expression
12071{
12072 protected:
12073 Array_construction_expression(Expression_classification classification,
52556f04
ILT
12074 Type* type,
12075 const std::vector<unsigned long>* indexes,
12076 Expression_list* vals, Location location)
7a938933 12077 : Expression(classification, location),
52556f04
ILT
12078 type_(type), indexes_(indexes), vals_(vals)
12079 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
7a938933
ILT
12080
12081 public:
12082 // Return whether this is a constant initializer.
12083 bool
12084 is_constant_array() const;
12085
12086 // Return the number of elements.
12087 size_t
12088 element_count() const
12089 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12090
12091protected:
12092 int
12093 do_traverse(Traverse* traverse);
12094
8a35e18d
CM
12095 bool
12096 do_is_immutable() const;
12097
7a938933
ILT
12098 Type*
12099 do_type()
12100 { return this->type_; }
12101
12102 void
12103 do_determine_type(const Type_context*);
12104
12105 void
12106 do_check_types(Gogo*);
12107
7a938933
ILT
12108 void
12109 do_export(Export*) const;
12110
52556f04
ILT
12111 // The indexes.
12112 const std::vector<unsigned long>*
12113 indexes()
12114 { return this->indexes_; }
12115
7a938933
ILT
12116 // The list of values.
12117 Expression_list*
12118 vals()
12119 { return this->vals_; }
12120
7035307e
CM
12121 // Get the backend constructor for the array values.
12122 Bexpression*
12123 get_constructor(Translate_context* context, Btype* btype);
7a938933 12124
16c57fe2
RL
12125 void
12126 do_dump_expression(Ast_dump_context*) const;
12127
7a938933
ILT
12128 private:
12129 // The type of the array to construct.
12130 Type* type_;
52556f04
ILT
12131 // The list of indexes into the array, one for each value. This may
12132 // be NULL, in which case the indexes start at zero and increment.
12133 const std::vector<unsigned long>* indexes_;
12134 // The list of values. This may be NULL if there are no values.
7a938933
ILT
12135 Expression_list* vals_;
12136};
12137
12138// Traversal.
12139
12140int
12141Array_construction_expression::do_traverse(Traverse* traverse)
12142{
12143 if (this->vals_ != NULL
12144 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12145 return TRAVERSE_EXIT;
12146 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12147 return TRAVERSE_EXIT;
12148 return TRAVERSE_CONTINUE;
12149}
12150
12151// Return whether this is a constant initializer.
12152
12153bool
12154Array_construction_expression::is_constant_array() const
12155{
12156 if (this->vals_ == NULL)
12157 return true;
12158
12159 // There are no constant constructors for interfaces.
12160 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12161 return false;
12162
12163 for (Expression_list::const_iterator pv = this->vals_->begin();
12164 pv != this->vals_->end();
12165 ++pv)
12166 {
12167 if (*pv != NULL
12168 && !(*pv)->is_constant()
12169 && (!(*pv)->is_composite_literal()
12170 || (*pv)->is_nonconstant_composite_literal()))
12171 return false;
12172 }
12173 return true;
12174}
12175
8a35e18d
CM
12176// Return whether this is an immutable array initializer.
12177
12178bool
12179Array_construction_expression::do_is_immutable() const
12180{
12181 if (this->vals_ == NULL)
12182 return true;
12183 for (Expression_list::const_iterator pv = this->vals_->begin();
12184 pv != this->vals_->end();
12185 ++pv)
12186 {
12187 if (*pv != NULL && !(*pv)->is_immutable())
12188 return false;
12189 }
12190 return true;
12191}
12192
7a938933
ILT
12193// Final type determination.
12194
12195void
12196Array_construction_expression::do_determine_type(const Type_context*)
12197{
12198 if (this->vals_ == NULL)
12199 return;
12200 Type_context subcontext(this->type_->array_type()->element_type(), false);
12201 for (Expression_list::const_iterator pv = this->vals_->begin();
12202 pv != this->vals_->end();
12203 ++pv)
12204 {
12205 if (*pv != NULL)
12206 (*pv)->determine_type(&subcontext);
12207 }
12208}
12209
12210// Check types.
12211
12212void
12213Array_construction_expression::do_check_types(Gogo*)
12214{
12215 if (this->vals_ == NULL)
12216 return;
12217
12218 Array_type* at = this->type_->array_type();
12219 int i = 0;
12220 Type* element_type = at->element_type();
12221 for (Expression_list::const_iterator pv = this->vals_->begin();
12222 pv != this->vals_->end();
12223 ++pv, ++i)
12224 {
12225 if (*pv != NULL
12226 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12227 {
12228 error_at((*pv)->location(),
12229 "incompatible type for element %d in composite literal",
12230 i + 1);
12231 this->set_is_error();
12232 }
12233 }
7a938933
ILT
12234}
12235
7035307e 12236// Get a constructor expression for the array values.
7a938933 12237
7035307e
CM
12238Bexpression*
12239Array_construction_expression::get_constructor(Translate_context* context,
12240 Btype* array_btype)
7a938933 12241{
7a938933 12242 Type* element_type = this->type_->array_type()->element_type();
7035307e
CM
12243
12244 std::vector<unsigned long> indexes;
12245 std::vector<Bexpression*> vals;
12246 Gogo* gogo = context->gogo();
7a938933
ILT
12247 if (this->vals_ != NULL)
12248 {
12249 size_t i = 0;
52556f04
ILT
12250 std::vector<unsigned long>::const_iterator pi;
12251 if (this->indexes_ != NULL)
12252 pi = this->indexes_->begin();
7a938933
ILT
12253 for (Expression_list::const_iterator pv = this->vals_->begin();
12254 pv != this->vals_->end();
12255 ++pv, ++i)
12256 {
52556f04
ILT
12257 if (this->indexes_ != NULL)
12258 go_assert(pi != this->indexes_->end());
52556f04
ILT
12259
12260 if (this->indexes_ == NULL)
7035307e 12261 indexes.push_back(i);
52556f04 12262 else
7035307e 12263 indexes.push_back(*pi);
7a938933 12264 if (*pv == NULL)
54466dde 12265 {
54466dde
ILT
12266 Btype* ebtype = element_type->get_backend(gogo);
12267 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
7035307e 12268 vals.push_back(zv);
54466dde 12269 }
7a938933
ILT
12270 else
12271 {
7035307e
CM
12272 Expression* val_expr =
12273 Expression::convert_for_assignment(gogo, element_type, *pv,
12274 this->location());
12275 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
7a938933 12276 }
52556f04
ILT
12277 if (this->indexes_ != NULL)
12278 ++pi;
7a938933 12279 }
52556f04
ILT
12280 if (this->indexes_ != NULL)
12281 go_assert(pi == this->indexes_->end());
7a938933 12282 }
7035307e
CM
12283 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12284 vals, this->location());
7a938933
ILT
12285}
12286
12287// Export an array construction.
12288
12289void
12290Array_construction_expression::do_export(Export* exp) const
12291{
12292 exp->write_c_string("convert(");
12293 exp->write_type(this->type_);
12294 if (this->vals_ != NULL)
12295 {
52556f04
ILT
12296 std::vector<unsigned long>::const_iterator pi;
12297 if (this->indexes_ != NULL)
12298 pi = this->indexes_->begin();
7a938933
ILT
12299 for (Expression_list::const_iterator pv = this->vals_->begin();
12300 pv != this->vals_->end();
12301 ++pv)
12302 {
12303 exp->write_c_string(", ");
52556f04
ILT
12304
12305 if (this->indexes_ != NULL)
12306 {
12307 char buf[100];
12308 snprintf(buf, sizeof buf, "%lu", *pi);
12309 exp->write_c_string(buf);
12310 exp->write_c_string(":");
12311 }
12312
7a938933
ILT
12313 if (*pv != NULL)
12314 (*pv)->export_expression(exp);
52556f04
ILT
12315
12316 if (this->indexes_ != NULL)
12317 ++pi;
7a938933
ILT
12318 }
12319 }
12320 exp->write_c_string(")");
12321}
12322
16c57fe2
RL
12323// Dump ast representation of an array construction expressin.
12324
12325void
12326Array_construction_expression::do_dump_expression(
12327 Ast_dump_context* ast_dump_context) const
12328{
52556f04 12329 Expression* length = this->type_->array_type()->length();
706cd57f
RL
12330
12331 ast_dump_context->ostream() << "[" ;
12332 if (length != NULL)
12333 {
12334 ast_dump_context->dump_expression(length);
12335 }
12336 ast_dump_context->ostream() << "]" ;
16c57fe2
RL
12337 ast_dump_context->dump_type(this->type_);
12338 ast_dump_context->ostream() << "{" ;
52556f04
ILT
12339 if (this->indexes_ == NULL)
12340 ast_dump_context->dump_expression_list(this->vals_);
12341 else
12342 {
12343 Expression_list::const_iterator pv = this->vals_->begin();
12344 for (std::vector<unsigned long>::const_iterator pi =
12345 this->indexes_->begin();
12346 pi != this->indexes_->end();
12347 ++pi, ++pv)
12348 {
12349 if (pi != this->indexes_->begin())
12350 ast_dump_context->ostream() << ", ";
12351 ast_dump_context->ostream() << *pi << ':';
12352 ast_dump_context->dump_expression(*pv);
12353 }
12354 }
16c57fe2
RL
12355 ast_dump_context->ostream() << "}" ;
12356
12357}
12358
7a938933
ILT
12359// Construct a fixed array.
12360
12361class Fixed_array_construction_expression :
12362 public Array_construction_expression
12363{
12364 public:
52556f04
ILT
12365 Fixed_array_construction_expression(Type* type,
12366 const std::vector<unsigned long>* indexes,
12367 Expression_list* vals, Location location)
7a938933 12368 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
52556f04
ILT
12369 type, indexes, vals, location)
12370 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
7a938933
ILT
12371
12372 protected:
12373 Expression*
12374 do_copy()
12375 {
12376 return new Fixed_array_construction_expression(this->type(),
52556f04 12377 this->indexes(),
7a938933
ILT
12378 (this->vals() == NULL
12379 ? NULL
12380 : this->vals()->copy()),
12381 this->location());
12382 }
12383
12384 tree
12385 do_get_tree(Translate_context*);
12386};
12387
12388// Return a tree for constructing a fixed array.
12389
12390tree
12391Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12392{
5b735706
ILT
12393 Type* type = this->type();
12394 Btype* btype = type->get_backend(context->gogo());
7035307e 12395 return expr_to_tree(this->get_constructor(context, btype));
7a938933
ILT
12396}
12397
036165d8
CM
12398Expression*
12399Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12400 Location location)
12401{
12402 go_assert(type->array_type() != NULL && !type->is_slice_type());
12403 return new Fixed_array_construction_expression(type, NULL, vals, location);
12404}
12405
7035307e 12406// Construct a slice.
7a938933 12407
7035307e 12408class Slice_construction_expression : public Array_construction_expression
7a938933
ILT
12409{
12410 public:
7035307e
CM
12411 Slice_construction_expression(Type* type,
12412 const std::vector<unsigned long>* indexes,
12413 Expression_list* vals, Location location)
12414 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12415 type, indexes, vals, location),
12416 valtype_(NULL)
52556f04 12417 { go_assert(type->is_slice_type()); }
7a938933
ILT
12418
12419 protected:
7035307e 12420 // Note that taking the address of a slice literal is invalid.
7a938933
ILT
12421
12422 Expression*
12423 do_copy()
12424 {
7035307e
CM
12425 return new Slice_construction_expression(this->type(), this->indexes(),
12426 (this->vals() == NULL
12427 ? NULL
12428 : this->vals()->copy()),
12429 this->location());
7a938933
ILT
12430 }
12431
12432 tree
12433 do_get_tree(Translate_context*);
7035307e
CM
12434
12435 private:
12436 // The type of the values in this slice.
12437 Type* valtype_;
7a938933
ILT
12438};
12439
7035307e 12440// Return a tree for constructing a slice.
7a938933
ILT
12441
12442tree
7035307e 12443Slice_construction_expression::do_get_tree(Translate_context* context)
7a938933 12444{
f39c772f
ILT
12445 Array_type* array_type = this->type()->array_type();
12446 if (array_type == NULL)
12447 {
26409c52 12448 go_assert(this->type()->is_error());
f39c772f
ILT
12449 return error_mark_node;
12450 }
12451
12452 Type* element_type = array_type->element_type();
7035307e
CM
12453 if (this->valtype_ == NULL)
12454 {
12455 mpz_t lenval;
12456 Expression* length;
12457 if (this->vals() == NULL || this->vals()->empty())
12458 mpz_init_set_ui(lenval, 0);
12459 else
12460 {
12461 if (this->indexes() == NULL)
12462 mpz_init_set_ui(lenval, this->vals()->size());
12463 else
12464 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12465 }
12466 Location loc = this->location();
12467 Type* int_type = Type::lookup_integer_type("int");
12468 length = Expression::make_integer(&lenval, int_type, loc);
12469 mpz_clear(lenval);
12470 this->valtype_ = Type::make_array_type(element_type, length);
12471 }
6930f562 12472
7a938933 12473 tree values;
7035307e
CM
12474 Gogo* gogo = context->gogo();
12475 Btype* val_btype = this->valtype_->get_backend(gogo);
7a938933
ILT
12476 if (this->vals() == NULL || this->vals()->empty())
12477 {
12478 // We need to create a unique value.
7035307e
CM
12479 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
12480 Bexpression* zero = gogo->backend()->zero_expression(int_btype);
12481 std::vector<unsigned long> index(1, 0);
12482 std::vector<Bexpression*> val(1, zero);
12483 Bexpression* ctor =
12484 gogo->backend()->array_constructor_expression(val_btype, index, val,
12485 this->location());
12486 values = expr_to_tree(ctor);
7a938933
ILT
12487 }
12488 else
7035307e 12489 values = expr_to_tree(this->get_constructor(context, val_btype));
7a938933
ILT
12490
12491 if (values == error_mark_node)
12492 return error_mark_node;
12493
12494 bool is_constant_initializer = TREE_CONSTANT(values);
01c59996
ILT
12495
12496 // We have to copy the initial values into heap memory if we are in
12497 // a function or if the values are not constants. We also have to
12498 // copy them if they may contain pointers in a non-constant context,
12499 // as otherwise the garbage collector won't see them.
12500 bool copy_to_heap = (context->function() != NULL
12501 || !is_constant_initializer
12502 || (element_type->has_pointer()
12503 && !context->is_const()));
7a938933
ILT
12504
12505 if (is_constant_initializer)
12506 {
8afa2bfb 12507 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
7a938933
ILT
12508 create_tmp_var_name("C"), TREE_TYPE(values));
12509 DECL_EXTERNAL(tmp) = 0;
12510 TREE_PUBLIC(tmp) = 0;
12511 TREE_STATIC(tmp) = 1;
12512 DECL_ARTIFICIAL(tmp) = 1;
01c59996 12513 if (copy_to_heap)
7a938933 12514 {
01c59996
ILT
12515 // If we are not copying the value to the heap, we will only
12516 // initialize the value once, so we can use this directly
12517 // rather than copying it. In that case we can't make it
12518 // read-only, because the program is permitted to change it.
7a938933
ILT
12519 TREE_READONLY(tmp) = 1;
12520 TREE_CONSTANT(tmp) = 1;
12521 }
12522 DECL_INITIAL(tmp) = values;
12523 rest_of_decl_compilation(tmp, 1, 0);
12524 values = tmp;
12525 }
12526
12527 tree space;
12528 tree set;
01c59996 12529 if (!copy_to_heap)
7a938933 12530 {
01c59996 12531 // the initializer will only run once.
7a938933
ILT
12532 space = build_fold_addr_expr(values);
12533 set = NULL_TREE;
12534 }
12535 else
12536 {
7035307e
CM
12537 Expression* alloc =
12538 context->gogo()->allocate_memory(this->valtype_, this->location());
12539 space = save_expr(alloc->get_tree(context));
7a938933
ILT
12540
12541 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
8afa2bfb
SD
12542 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12543 s);
7a938933
ILT
12544 TREE_THIS_NOTRAP(ref) = 1;
12545 set = build2(MODIFY_EXPR, void_type_node, ref, values);
12546 }
12547
7035307e 12548 // Build a constructor for the slice.
7a938933 12549
5b735706 12550 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
6930f562
ILT
12551 if (type_tree == error_mark_node)
12552 return error_mark_node;
26409c52 12553 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
7a938933 12554
4efdbe5a
ILT
12555 vec<constructor_elt, va_gc> *init;
12556 vec_alloc(init, 3);
7a938933 12557
f32682ca 12558 constructor_elt empty = {NULL, NULL};
4efdbe5a 12559 constructor_elt* elt = init->quick_push(empty);
7a938933 12560 tree field = TYPE_FIELDS(type_tree);
26409c52 12561 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
7a938933
ILT
12562 elt->index = field;
12563 elt->value = fold_convert(TREE_TYPE(field), space);
12564
7035307e 12565 tree length_tree = this->valtype_->array_type()->length()->get_tree(context);
4efdbe5a 12566 elt = init->quick_push(empty);
7a938933 12567 field = DECL_CHAIN(field);
26409c52 12568 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
7a938933
ILT
12569 elt->index = field;
12570 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12571
4efdbe5a 12572 elt = init->quick_push(empty);
7a938933 12573 field = DECL_CHAIN(field);
26409c52 12574 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
7a938933
ILT
12575 elt->index = field;
12576 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12577
12578 tree constructor = build_constructor(type_tree, init);
6930f562
ILT
12579 if (constructor == error_mark_node)
12580 return error_mark_node;
01c59996 12581 if (!copy_to_heap)
7a938933
ILT
12582 TREE_CONSTANT(constructor) = 1;
12583
12584 if (set == NULL_TREE)
12585 return constructor;
12586 else
12587 return build2(COMPOUND_EXPR, type_tree, set, constructor);
12588}
12589
12590// Make a slice composite literal. This is used by the type
12591// descriptor code.
12592
12593Expression*
12594Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
8afa2bfb 12595 Location location)
7a938933 12596{
b7190f2f 12597 go_assert(type->is_slice_type());
7035307e 12598 return new Slice_construction_expression(type, NULL, vals, location);
7a938933
ILT
12599}
12600
12601// Construct a map.
12602
12603class Map_construction_expression : public Expression
12604{
12605 public:
12606 Map_construction_expression(Type* type, Expression_list* vals,
8afa2bfb 12607 Location location)
7a938933 12608 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
7035307e 12609 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
26409c52 12610 { go_assert(vals == NULL || vals->size() % 2 == 0); }
7a938933
ILT
12611
12612 protected:
12613 int
12614 do_traverse(Traverse* traverse);
12615
7035307e
CM
12616 Expression*
12617 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12618
7a938933
ILT
12619 Type*
12620 do_type()
12621 { return this->type_; }
12622
12623 void
12624 do_determine_type(const Type_context*);
12625
12626 void
12627 do_check_types(Gogo*);
12628
12629 Expression*
12630 do_copy()
12631 {
12632 return new Map_construction_expression(this->type_, this->vals_->copy(),
12633 this->location());
12634 }
12635
12636 tree
12637 do_get_tree(Translate_context*);
12638
12639 void
12640 do_export(Export*) const;
12641
16c57fe2
RL
12642 void
12643 do_dump_expression(Ast_dump_context*) const;
12644
7a938933
ILT
12645 private:
12646 // The type of the map to construct.
12647 Type* type_;
12648 // The list of values.
12649 Expression_list* vals_;
7035307e
CM
12650 // The type of the key-value pair struct for each map element.
12651 Struct_type* element_type_;
12652 // A temporary reference to the variable storing the constructor initializer.
12653 Temporary_statement* constructor_temp_;
7a938933
ILT
12654};
12655
12656// Traversal.
12657
12658int
12659Map_construction_expression::do_traverse(Traverse* traverse)
12660{
12661 if (this->vals_ != NULL
12662 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12663 return TRAVERSE_EXIT;
12664 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12665 return TRAVERSE_EXIT;
12666 return TRAVERSE_CONTINUE;
12667}
12668
7035307e
CM
12669// Flatten constructor initializer into a temporary variable since
12670// we need to take its address for __go_construct_map.
12671
12672Expression*
12673Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12674 Statement_inserter* inserter)
12675{
12676 if (!this->is_error_expression()
12677 && this->vals_ != NULL
12678 && !this->vals_->empty()
12679 && this->constructor_temp_ == NULL)
12680 {
12681 Map_type* mt = this->type_->map_type();
12682 Type* key_type = mt->key_type();
12683 Type* val_type = mt->val_type();
12684 this->element_type_ = Type::make_builtin_struct_type(2,
12685 "__key", key_type,
12686 "__val", val_type);
12687
12688 Expression_list* value_pairs = new Expression_list();
12689 Location loc = this->location();
12690
12691 size_t i = 0;
12692 for (Expression_list::const_iterator pv = this->vals_->begin();
12693 pv != this->vals_->end();
12694 ++pv, ++i)
12695 {
12696 Expression_list* key_value_pair = new Expression_list();
12697 Expression* key =
12698 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12699
12700 ++pv;
12701 Expression* val =
12702 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12703
12704 key_value_pair->push_back(key);
12705 key_value_pair->push_back(val);
12706 value_pairs->push_back(
12707 Expression::make_struct_composite_literal(this->element_type_,
12708 key_value_pair, loc));
12709 }
12710
12711 mpz_t lenval;
12712 mpz_init_set_ui(lenval, i);
12713 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12714 mpz_clear(lenval);
12715
12716 Type* ctor_type =
12717 Type::make_array_type(this->element_type_, element_count);
12718 Expression* constructor =
12719 new Fixed_array_construction_expression(ctor_type, NULL,
12720 value_pairs, loc);
12721
12722 this->constructor_temp_ =
12723 Statement::make_temporary(NULL, constructor, loc);
12724 constructor->issue_nil_check();
12725 this->constructor_temp_->set_is_address_taken();
12726 inserter->insert(this->constructor_temp_);
12727 }
12728
12729 return this;
12730}
12731
7a938933
ILT
12732// Final type determination.
12733
12734void
12735Map_construction_expression::do_determine_type(const Type_context*)
12736{
12737 if (this->vals_ == NULL)
12738 return;
12739
12740 Map_type* mt = this->type_->map_type();
12741 Type_context key_context(mt->key_type(), false);
12742 Type_context val_context(mt->val_type(), false);
12743 for (Expression_list::const_iterator pv = this->vals_->begin();
12744 pv != this->vals_->end();
12745 ++pv)
12746 {
12747 (*pv)->determine_type(&key_context);
12748 ++pv;
12749 (*pv)->determine_type(&val_context);
12750 }
12751}
12752
12753// Check types.
12754
12755void
12756Map_construction_expression::do_check_types(Gogo*)
12757{
12758 if (this->vals_ == NULL)
12759 return;
12760
12761 Map_type* mt = this->type_->map_type();
12762 int i = 0;
12763 Type* key_type = mt->key_type();
12764 Type* val_type = mt->val_type();
12765 for (Expression_list::const_iterator pv = this->vals_->begin();
12766 pv != this->vals_->end();
12767 ++pv, ++i)
12768 {
12769 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12770 {
12771 error_at((*pv)->location(),
12772 "incompatible type for element %d key in map construction",
12773 i + 1);
12774 this->set_is_error();
12775 }
12776 ++pv;
12777 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12778 {
12779 error_at((*pv)->location(),
12780 ("incompatible type for element %d value "
12781 "in map construction"),
12782 i + 1);
12783 this->set_is_error();
12784 }
12785 }
12786}
12787
12788// Return a tree for constructing a map.
12789
12790tree
12791Map_construction_expression::do_get_tree(Translate_context* context)
12792{
7035307e 12793 if (this->is_error_expression())
0cc3d14e 12794 return error_mark_node;
7035307e 12795 Location loc = this->location();
7a938933 12796
7a938933 12797 size_t i = 0;
7035307e 12798 Expression* ventries;
7a938933 12799 if (this->vals_ == NULL || this->vals_->empty())
7035307e 12800 ventries = Expression::make_nil(loc);
7a938933
ILT
12801 else
12802 {
7035307e
CM
12803 go_assert(this->constructor_temp_ != NULL);
12804 i = this->vals_->size() / 2;
7a938933 12805
7035307e
CM
12806 Expression* ctor_ref =
12807 Expression::make_temporary_reference(this->constructor_temp_, loc);
12808 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12809 }
7a938933 12810
7035307e
CM
12811 Map_type* mt = this->type_->map_type();
12812 if (this->element_type_ == NULL)
12813 this->element_type_ =
12814 Type::make_builtin_struct_type(2,
12815 "__key", mt->key_type(),
12816 "__val", mt->val_type());
12817 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12818
12819 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12820 mpz_t countval;
12821 mpz_init_set_ui(countval, i);
12822 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12823 mpz_clear(countval);
12824
12825 Expression* entry_size =
12826 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12827
12828 unsigned int field_index;
12829 const Struct_field* valfield =
12830 this->element_type_->find_local_field("__val", &field_index);
12831 Expression* val_offset =
12832 Expression::make_struct_field_offset(this->element_type_, valfield);
12833 Expression* val_size =
12834 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12835
12836 Expression* map_ctor =
12837 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12838 entry_size, val_offset, val_size, ventries);
12839 return map_ctor->get_tree(context);
12840}
7a938933 12841
7035307e 12842// Export an array construction.
7a938933 12843
7035307e
CM
12844void
12845Map_construction_expression::do_export(Export* exp) const
12846{
12847 exp->write_c_string("convert(");
12848 exp->write_type(this->type_);
12849 for (Expression_list::const_iterator pv = this->vals_->begin();
12850 pv != this->vals_->end();
12851 ++pv)
12852 {
12853 exp->write_c_string(", ");
12854 (*pv)->export_expression(exp);
12855 }
12856 exp->write_c_string(")");
12857}
7a938933 12858
7035307e 12859// Dump ast representation for a map construction expression.
16c57fe2
RL
12860
12861void
12862Map_construction_expression::do_dump_expression(
12863 Ast_dump_context* ast_dump_context) const
12864{
16c57fe2 12865 ast_dump_context->ostream() << "{" ;
706cd57f 12866 ast_dump_context->dump_expression_list(this->vals_, true);
16c57fe2
RL
12867 ast_dump_context->ostream() << "}";
12868}
12869
7a938933
ILT
12870// A general composite literal. This is lowered to a type specific
12871// version.
12872
12873class Composite_literal_expression : public Parser_expression
12874{
12875 public:
12876 Composite_literal_expression(Type* type, int depth, bool has_keys,
8ae4c35c
ILT
12877 Expression_list* vals, bool all_are_names,
12878 Location location)
7a938933 12879 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
8ae4c35c
ILT
12880 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12881 all_are_names_(all_are_names)
7a938933
ILT
12882 { }
12883
12884 protected:
12885 int
12886 do_traverse(Traverse* traverse);
12887
12888 Expression*
8586635c 12889 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7a938933
ILT
12890
12891 Expression*
12892 do_copy()
12893 {
12894 return new Composite_literal_expression(this->type_, this->depth_,
12895 this->has_keys_,
12896 (this->vals_ == NULL
12897 ? NULL
12898 : this->vals_->copy()),
8ae4c35c 12899 this->all_are_names_,
7a938933
ILT
12900 this->location());
12901 }
12902
16c57fe2
RL
12903 void
12904 do_dump_expression(Ast_dump_context*) const;
12905
7a938933
ILT
12906 private:
12907 Expression*
6481a43b 12908 lower_struct(Gogo*, Type*);
7a938933
ILT
12909
12910 Expression*
11d8e1a4 12911 lower_array(Type*);
7a938933
ILT
12912
12913 Expression*
52556f04 12914 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
7a938933
ILT
12915
12916 Expression*
8586635c 12917 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
7a938933
ILT
12918
12919 // The type of the composite literal.
12920 Type* type_;
12921 // The depth within a list of composite literals within a composite
12922 // literal, when the type is omitted.
12923 int depth_;
12924 // The values to put in the composite literal.
12925 Expression_list* vals_;
12926 // If this is true, then VALS_ is a list of pairs: a key and a
12927 // value. In an array initializer, a missing key will be NULL.
12928 bool has_keys_;
8ae4c35c
ILT
12929 // If this is true, then HAS_KEYS_ is true, and every key is a
12930 // simple identifier.
12931 bool all_are_names_;
7a938933
ILT
12932};
12933
12934// Traversal.
12935
12936int
12937Composite_literal_expression::do_traverse(Traverse* traverse)
12938{
68607055 12939 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
7a938933 12940 return TRAVERSE_EXIT;
68607055
ILT
12941
12942 // If this is a struct composite literal with keys, then the keys
12943 // are field names, not expressions. We don't want to traverse them
12944 // in that case. If we do, we can give an erroneous error "variable
12945 // initializer refers to itself." See bug482.go in the testsuite.
12946 if (this->has_keys_ && this->vals_ != NULL)
12947 {
12948 // The type may not be resolvable at this point.
12949 Type* type = this->type_;
207c82c4
ILT
12950
12951 for (int depth = this->depth_; depth > 0; --depth)
12952 {
12953 if (type->array_type() != NULL)
12954 type = type->array_type()->element_type();
12955 else if (type->map_type() != NULL)
12956 type = type->map_type()->val_type();
12957 else
12958 {
12959 // This error will be reported during lowering.
12960 return TRAVERSE_CONTINUE;
12961 }
12962 }
12963
68607055
ILT
12964 while (true)
12965 {
12966 if (type->classification() == Type::TYPE_NAMED)
12967 type = type->named_type()->real_type();
12968 else if (type->classification() == Type::TYPE_FORWARD)
12969 {
12970 Type* t = type->forwarded();
12971 if (t == type)
12972 break;
12973 type = t;
12974 }
12975 else
12976 break;
12977 }
12978
12979 if (type->classification() == Type::TYPE_STRUCT)
12980 {
12981 Expression_list::iterator p = this->vals_->begin();
12982 while (p != this->vals_->end())
12983 {
12984 // Skip key.
12985 ++p;
12986 go_assert(p != this->vals_->end());
12987 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12988 return TRAVERSE_EXIT;
12989 ++p;
12990 }
12991 return TRAVERSE_CONTINUE;
12992 }
12993 }
12994
12995 if (this->vals_ != NULL)
12996 return this->vals_->traverse(traverse);
12997
12998 return TRAVERSE_CONTINUE;
7a938933
ILT
12999}
13000
13001// Lower a generic composite literal into a specific version based on
13002// the type.
13003
13004Expression*
8586635c
ILT
13005Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13006 Statement_inserter* inserter, int)
7a938933
ILT
13007{
13008 Type* type = this->type_;
13009
13010 for (int depth = this->depth_; depth > 0; --depth)
13011 {
13012 if (type->array_type() != NULL)
13013 type = type->array_type()->element_type();
13014 else if (type->map_type() != NULL)
13015 type = type->map_type()->val_type();
13016 else
13017 {
02ed921a 13018 if (!type->is_error())
7a938933
ILT
13019 error_at(this->location(),
13020 ("may only omit types within composite literals "
13021 "of slice, array, or map type"));
13022 return Expression::make_error(this->location());
13023 }
13024 }
13025
c623f837
ILT
13026 Type *pt = type->points_to();
13027 bool is_pointer = false;
13028 if (pt != NULL)
13029 {
13030 is_pointer = true;
13031 type = pt;
13032 }
13033
13034 Expression* ret;
02ed921a 13035 if (type->is_error())
7a938933
ILT
13036 return Expression::make_error(this->location());
13037 else if (type->struct_type() != NULL)
c623f837 13038 ret = this->lower_struct(gogo, type);
7a938933 13039 else if (type->array_type() != NULL)
11d8e1a4 13040 ret = this->lower_array(type);
7a938933 13041 else if (type->map_type() != NULL)
c623f837 13042 ret = this->lower_map(gogo, function, inserter, type);
7a938933
ILT
13043 else
13044 {
13045 error_at(this->location(),
13046 ("expected struct, slice, array, or map type "
13047 "for composite literal"));
13048 return Expression::make_error(this->location());
13049 }
c623f837
ILT
13050
13051 if (is_pointer)
7035307e 13052 ret = Expression::make_heap_expression(ret, this->location());
c623f837
ILT
13053
13054 return ret;
7a938933
ILT
13055}
13056
13057// Lower a struct composite literal.
13058
13059Expression*
6481a43b 13060Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
7a938933 13061{
8afa2bfb 13062 Location location = this->location();
7a938933
ILT
13063 Struct_type* st = type->struct_type();
13064 if (this->vals_ == NULL || !this->has_keys_)
1fbbc69c 13065 {
c573faf5
ILT
13066 if (this->vals_ != NULL
13067 && !this->vals_->empty()
13068 && type->named_type() != NULL
13069 && type->named_type()->named_object()->package() != NULL)
13070 {
13071 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13072 pf != st->fields()->end();
13073 ++pf)
1fbbc69c 13074 {
c573faf5 13075 if (Gogo::is_hidden_name(pf->field_name()))
1fbbc69c 13076 error_at(this->location(),
c573faf5
ILT
13077 "assignment of unexported field %qs in %qs literal",
13078 Gogo::message_name(pf->field_name()).c_str(),
13079 type->named_type()->message_name().c_str());
1fbbc69c
ILT
13080 }
13081 }
13082
13083 return new Struct_construction_expression(type, this->vals_, location);
13084 }
7a938933
ILT
13085
13086 size_t field_count = st->field_count();
13087 std::vector<Expression*> vals(field_count);
50f671c6 13088 std::vector<int>* traverse_order = new(std::vector<int>);
7a938933 13089 Expression_list::const_iterator p = this->vals_->begin();
8ae4c35c
ILT
13090 Expression* external_expr = NULL;
13091 const Named_object* external_no = NULL;
7a938933
ILT
13092 while (p != this->vals_->end())
13093 {
13094 Expression* name_expr = *p;
13095
13096 ++p;
26409c52 13097 go_assert(p != this->vals_->end());
7a938933
ILT
13098 Expression* val = *p;
13099
13100 ++p;
13101
13102 if (name_expr == NULL)
13103 {
13104 error_at(val->location(), "mixture of field and value initializers");
13105 return Expression::make_error(location);
13106 }
13107
13108 bool bad_key = false;
13109 std::string name;
6481a43b 13110 const Named_object* no = NULL;
7a938933
ILT
13111 switch (name_expr->classification())
13112 {
13113 case EXPRESSION_UNKNOWN_REFERENCE:
13114 name = name_expr->unknown_expression()->name();
13115 break;
13116
13117 case EXPRESSION_CONST_REFERENCE:
6481a43b 13118 no = static_cast<Const_expression*>(name_expr)->named_object();
7a938933
ILT
13119 break;
13120
13121 case EXPRESSION_TYPE:
13122 {
13123 Type* t = name_expr->type();
13124 Named_type* nt = t->named_type();
13125 if (nt == NULL)
13126 bad_key = true;
13127 else
6481a43b 13128 no = nt->named_object();
7a938933
ILT
13129 }
13130 break;
13131
13132 case EXPRESSION_VAR_REFERENCE:
6481a43b 13133 no = name_expr->var_expression()->named_object();
7a938933
ILT
13134 break;
13135
13136 case EXPRESSION_FUNC_REFERENCE:
6481a43b 13137 no = name_expr->func_expression()->named_object();
7a938933
ILT
13138 break;
13139
13140 case EXPRESSION_UNARY:
13141 // If there is a local variable around with the same name as
13142 // the field, and this occurs in the closure, then the
13143 // parser may turn the field reference into an indirection
13144 // through the closure. FIXME: This is a mess.
13145 {
13146 bad_key = true;
13147 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13148 if (ue->op() == OPERATOR_MULT)
13149 {
13150 Field_reference_expression* fre =
13151 ue->operand()->field_reference_expression();
13152 if (fre != NULL)
13153 {
13154 Struct_type* st =
13155 fre->expr()->type()->deref()->struct_type();
13156 if (st != NULL)
13157 {
13158 const Struct_field* sf = st->field(fre->field_index());
13159 name = sf->field_name();
ffe08917
ILT
13160
13161 // See below. FIXME.
13162 if (!Gogo::is_hidden_name(name)
13163 && name[0] >= 'a'
13164 && name[0] <= 'z')
13165 {
13166 if (gogo->lookup_global(name.c_str()) != NULL)
13167 name = gogo->pack_hidden_name(name, false);
13168 }
13169
7a938933
ILT
13170 char buf[20];
13171 snprintf(buf, sizeof buf, "%u", fre->field_index());
13172 size_t buflen = strlen(buf);
13173 if (name.compare(name.length() - buflen, buflen, buf)
13174 == 0)
13175 {
13176 name = name.substr(0, name.length() - buflen);
13177 bad_key = false;
13178 }
13179 }
13180 }
13181 }
13182 }
13183 break;
13184
13185 default:
13186 bad_key = true;
13187 break;
13188 }
13189 if (bad_key)
13190 {
13191 error_at(name_expr->location(), "expected struct field name");
13192 return Expression::make_error(location);
13193 }
13194
6481a43b
ILT
13195 if (no != NULL)
13196 {
8ae4c35c
ILT
13197 if (no->package() != NULL && external_expr == NULL)
13198 {
13199 external_expr = name_expr;
13200 external_no = no;
13201 }
13202
6481a43b
ILT
13203 name = no->name();
13204
13205 // A predefined name won't be packed. If it starts with a
13206 // lower case letter we need to check for that case, because
ffe08917 13207 // the field name will be packed. FIXME.
6481a43b
ILT
13208 if (!Gogo::is_hidden_name(name)
13209 && name[0] >= 'a'
13210 && name[0] <= 'z')
13211 {
13212 Named_object* gno = gogo->lookup_global(name.c_str());
13213 if (gno == no)
13214 name = gogo->pack_hidden_name(name, false);
13215 }
13216 }
13217
7a938933
ILT
13218 unsigned int index;
13219 const Struct_field* sf = st->find_local_field(name, &index);
13220 if (sf == NULL)
13221 {
13222 error_at(name_expr->location(), "unknown field %qs in %qs",
13223 Gogo::message_name(name).c_str(),
13224 (type->named_type() != NULL
13225 ? type->named_type()->message_name().c_str()
13226 : "unnamed struct"));
13227 return Expression::make_error(location);
13228 }
13229 if (vals[index] != NULL)
13230 {
13231 error_at(name_expr->location(),
13232 "duplicate value for field %qs in %qs",
13233 Gogo::message_name(name).c_str(),
13234 (type->named_type() != NULL
13235 ? type->named_type()->message_name().c_str()
13236 : "unnamed struct"));
13237 return Expression::make_error(location);
13238 }
13239
1fbbc69c
ILT
13240 if (type->named_type() != NULL
13241 && type->named_type()->named_object()->package() != NULL
13242 && Gogo::is_hidden_name(sf->field_name()))
13243 error_at(name_expr->location(),
13244 "assignment of unexported field %qs in %qs literal",
13245 Gogo::message_name(sf->field_name()).c_str(),
13246 type->named_type()->message_name().c_str());
1fbbc69c 13247
7a938933 13248 vals[index] = val;
50f671c6 13249 traverse_order->push_back(index);
7a938933
ILT
13250 }
13251
8ae4c35c
ILT
13252 if (!this->all_are_names_)
13253 {
13254 // This is a weird case like bug462 in the testsuite.
13255 if (external_expr == NULL)
13256 error_at(this->location(), "unknown field in %qs literal",
13257 (type->named_type() != NULL
13258 ? type->named_type()->message_name().c_str()
13259 : "unnamed struct"));
13260 else
13261 error_at(external_expr->location(), "unknown field %qs in %qs",
13262 external_no->message_name().c_str(),
13263 (type->named_type() != NULL
13264 ? type->named_type()->message_name().c_str()
13265 : "unnamed struct"));
13266 return Expression::make_error(location);
13267 }
13268
7a938933
ILT
13269 Expression_list* list = new Expression_list;
13270 list->reserve(field_count);
13271 for (size_t i = 0; i < field_count; ++i)
13272 list->push_back(vals[i]);
13273
50f671c6
ILT
13274 Struct_construction_expression* ret =
13275 new Struct_construction_expression(type, list, location);
13276 ret->set_traverse_order(traverse_order);
13277 return ret;
7a938933
ILT
13278}
13279
87fd4bbf
ILT
13280// Used to sort an index/value array.
13281
13282class Index_value_compare
13283{
13284 public:
13285 bool
13286 operator()(const std::pair<unsigned long, Expression*>& a,
13287 const std::pair<unsigned long, Expression*>& b)
13288 { return a.first < b.first; }
13289};
13290
7a938933
ILT
13291// Lower an array composite literal.
13292
13293Expression*
11d8e1a4 13294Composite_literal_expression::lower_array(Type* type)
7a938933 13295{
8afa2bfb 13296 Location location = this->location();
7a938933 13297 if (this->vals_ == NULL || !this->has_keys_)
52556f04 13298 return this->make_array(type, NULL, this->vals_);
7a938933 13299
52556f04
ILT
13300 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13301 indexes->reserve(this->vals_->size());
87fd4bbf 13302 bool indexes_out_of_order = false;
52556f04
ILT
13303 Expression_list* vals = new Expression_list();
13304 vals->reserve(this->vals_->size());
7a938933
ILT
13305 unsigned long index = 0;
13306 Expression_list::const_iterator p = this->vals_->begin();
13307 while (p != this->vals_->end())
13308 {
13309 Expression* index_expr = *p;
13310
13311 ++p;
26409c52 13312 go_assert(p != this->vals_->end());
7a938933
ILT
13313 Expression* val = *p;
13314
13315 ++p;
13316
52556f04
ILT
13317 if (index_expr == NULL)
13318 {
13319 if (!indexes->empty())
13320 indexes->push_back(index);
13321 }
13322 else
7a938933 13323 {
52556f04
ILT
13324 if (indexes->empty() && !vals->empty())
13325 {
13326 for (size_t i = 0; i < vals->size(); ++i)
13327 indexes->push_back(i);
13328 }
13329
5caf63ca
ILT
13330 Numeric_constant nc;
13331 if (!index_expr->numeric_constant_value(&nc))
7a938933 13332 {
7a938933
ILT
13333 error_at(index_expr->location(),
13334 "index expression is not integer constant");
13335 return Expression::make_error(location);
13336 }
e2e280a3 13337
5caf63ca 13338 switch (nc.to_unsigned_long(&index))
7a938933 13339 {
5caf63ca
ILT
13340 case Numeric_constant::NC_UL_VALID:
13341 break;
13342 case Numeric_constant::NC_UL_NOTINT:
13343 error_at(index_expr->location(),
13344 "index expression is not integer constant");
13345 return Expression::make_error(location);
13346 case Numeric_constant::NC_UL_NEGATIVE:
7a938933
ILT
13347 error_at(index_expr->location(), "index expression is negative");
13348 return Expression::make_error(location);
5caf63ca 13349 case Numeric_constant::NC_UL_BIG:
7a938933
ILT
13350 error_at(index_expr->location(), "index value overflow");
13351 return Expression::make_error(location);
5caf63ca
ILT
13352 default:
13353 go_unreachable();
7a938933 13354 }
e2e280a3
ILT
13355
13356 Named_type* ntype = Type::lookup_integer_type("int");
13357 Integer_type* inttype = ntype->integer_type();
5caf63ca
ILT
13358 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13359 && index >> (inttype->bits() - 1) != 0)
e2e280a3 13360 {
e2e280a3
ILT
13361 error_at(index_expr->location(), "index value overflow");
13362 return Expression::make_error(location);
13363 }
13364
52556f04
ILT
13365 if (std::find(indexes->begin(), indexes->end(), index)
13366 != indexes->end())
7a938933 13367 {
52556f04 13368 error_at(index_expr->location(), "duplicate value for index %lu",
7a938933
ILT
13369 index);
13370 return Expression::make_error(location);
13371 }
52556f04 13372
87fd4bbf
ILT
13373 if (!indexes->empty() && index < indexes->back())
13374 indexes_out_of_order = true;
13375
52556f04 13376 indexes->push_back(index);
7a938933
ILT
13377 }
13378
52556f04
ILT
13379 vals->push_back(val);
13380
7a938933
ILT
13381 ++index;
13382 }
13383
52556f04
ILT
13384 if (indexes->empty())
13385 {
13386 delete indexes;
13387 indexes = NULL;
13388 }
7a938933 13389
87fd4bbf
ILT
13390 if (indexes_out_of_order)
13391 {
13392 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13393
13394 V v;
13395 v.reserve(indexes->size());
13396 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13397 for (Expression_list::const_iterator pe = vals->begin();
13398 pe != vals->end();
13399 ++pe, ++pi)
13400 v.push_back(std::make_pair(*pi, *pe));
13401
13402 std::sort(v.begin(), v.end(), Index_value_compare());
13403
13404 delete indexes;
13405 delete vals;
13406 indexes = new std::vector<unsigned long>();
13407 indexes->reserve(v.size());
13408 vals = new Expression_list();
13409 vals->reserve(v.size());
13410
13411 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13412 {
13413 indexes->push_back(p->first);
13414 vals->push_back(p->second);
13415 }
13416 }
13417
52556f04 13418 return this->make_array(type, indexes, vals);
7a938933
ILT
13419}
13420
13421// Actually build the array composite literal. This handles
13422// [...]{...}.
13423
13424Expression*
52556f04
ILT
13425Composite_literal_expression::make_array(
13426 Type* type,
13427 const std::vector<unsigned long>* indexes,
13428 Expression_list* vals)
7a938933 13429{
8afa2bfb 13430 Location location = this->location();
7a938933 13431 Array_type* at = type->array_type();
52556f04 13432
7a938933
ILT
13433 if (at->length() != NULL && at->length()->is_nil_expression())
13434 {
52556f04
ILT
13435 size_t size;
13436 if (vals == NULL)
13437 size = 0;
87fd4bbf
ILT
13438 else if (indexes != NULL)
13439 size = indexes->back() + 1;
13440 else
52556f04
ILT
13441 {
13442 size = vals->size();
13443 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13444 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13445 && size >> (it->bits() - 1) != 0)
13446 {
13447 error_at(location, "too many elements in composite literal");
13448 return Expression::make_error(location);
13449 }
13450 }
52556f04 13451
7a938933
ILT
13452 mpz_t vlen;
13453 mpz_init_set_ui(vlen, size);
13454 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13455 mpz_clear(vlen);
13456 at = Type::make_array_type(at->element_type(), elen);
13457 type = at;
13458 }
52556f04
ILT
13459 else if (at->length() != NULL
13460 && !at->length()->is_error_expression()
13461 && this->vals_ != NULL)
13462 {
13463 Numeric_constant nc;
13464 unsigned long val;
13465 if (at->length()->numeric_constant_value(&nc)
13466 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13467 {
13468 if (indexes == NULL)
13469 {
13470 if (this->vals_->size() > val)
13471 {
13472 error_at(location, "too many elements in composite literal");
13473 return Expression::make_error(location);
13474 }
13475 }
13476 else
13477 {
87fd4bbf 13478 unsigned long max = indexes->back();
52556f04
ILT
13479 if (max >= val)
13480 {
13481 error_at(location,
13482 ("some element keys in composite literal "
13483 "are out of range"));
13484 return Expression::make_error(location);
13485 }
13486 }
13487 }
13488 }
13489
7a938933 13490 if (at->length() != NULL)
52556f04
ILT
13491 return new Fixed_array_construction_expression(type, indexes, vals,
13492 location);
7a938933 13493 else
7035307e 13494 return new Slice_construction_expression(type, indexes, vals, location);
7a938933
ILT
13495}
13496
13497// Lower a map composite literal.
13498
13499Expression*
cd96b4e2 13500Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
8586635c 13501 Statement_inserter* inserter,
cd96b4e2 13502 Type* type)
7a938933 13503{
8afa2bfb 13504 Location location = this->location();
7a938933
ILT
13505 if (this->vals_ != NULL)
13506 {
13507 if (!this->has_keys_)
13508 {
13509 error_at(location, "map composite literal must have keys");
13510 return Expression::make_error(location);
13511 }
13512
cd96b4e2 13513 for (Expression_list::iterator p = this->vals_->begin();
7a938933
ILT
13514 p != this->vals_->end();
13515 p += 2)
13516 {
13517 if (*p == NULL)
13518 {
13519 ++p;
13520 error_at((*p)->location(),
13521 "map composite literal must have keys for every value");
13522 return Expression::make_error(location);
13523 }
cd96b4e2
ILT
13524 // Make sure we have lowered the key; it may not have been
13525 // lowered in order to handle keys for struct composite
13526 // literals. Lower it now to get the right error message.
13527 if ((*p)->unknown_expression() != NULL)
13528 {
13529 (*p)->unknown_expression()->clear_is_composite_literal_key();
8586635c 13530 gogo->lower_expression(function, inserter, &*p);
26409c52 13531 go_assert((*p)->is_error_expression());
cd96b4e2
ILT
13532 return Expression::make_error(location);
13533 }
7a938933
ILT
13534 }
13535 }
13536
13537 return new Map_construction_expression(type, this->vals_, location);
13538}
13539
16c57fe2
RL
13540// Dump ast representation for a composite literal expression.
13541
13542void
13543Composite_literal_expression::do_dump_expression(
13544 Ast_dump_context* ast_dump_context) const
13545{
706cd57f 13546 ast_dump_context->ostream() << "composite(";
16c57fe2
RL
13547 ast_dump_context->dump_type(this->type_);
13548 ast_dump_context->ostream() << ", {";
706cd57f 13549 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
16c57fe2
RL
13550 ast_dump_context->ostream() << "})";
13551}
13552
7a938933
ILT
13553// Make a composite literal expression.
13554
13555Expression*
13556Expression::make_composite_literal(Type* type, int depth, bool has_keys,
8ae4c35c 13557 Expression_list* vals, bool all_are_names,
8afa2bfb 13558 Location location)
7a938933
ILT
13559{
13560 return new Composite_literal_expression(type, depth, has_keys, vals,
8ae4c35c 13561 all_are_names, location);
7a938933
ILT
13562}
13563
13564// Return whether this expression is a composite literal.
13565
13566bool
13567Expression::is_composite_literal() const
13568{
13569 switch (this->classification_)
13570 {
13571 case EXPRESSION_COMPOSITE_LITERAL:
13572 case EXPRESSION_STRUCT_CONSTRUCTION:
13573 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
7035307e 13574 case EXPRESSION_SLICE_CONSTRUCTION:
7a938933
ILT
13575 case EXPRESSION_MAP_CONSTRUCTION:
13576 return true;
13577 default:
13578 return false;
13579 }
13580}
13581
13582// Return whether this expression is a composite literal which is not
13583// constant.
13584
13585bool
13586Expression::is_nonconstant_composite_literal() const
13587{
13588 switch (this->classification_)
13589 {
13590 case EXPRESSION_STRUCT_CONSTRUCTION:
13591 {
13592 const Struct_construction_expression *psce =
13593 static_cast<const Struct_construction_expression*>(this);
13594 return !psce->is_constant_struct();
13595 }
13596 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13597 {
13598 const Fixed_array_construction_expression *pace =
13599 static_cast<const Fixed_array_construction_expression*>(this);
13600 return !pace->is_constant_array();
13601 }
7035307e 13602 case EXPRESSION_SLICE_CONSTRUCTION:
7a938933 13603 {
7035307e
CM
13604 const Slice_construction_expression *pace =
13605 static_cast<const Slice_construction_expression*>(this);
7a938933
ILT
13606 return !pace->is_constant_array();
13607 }
13608 case EXPRESSION_MAP_CONSTRUCTION:
13609 return true;
13610 default:
13611 return false;
13612 }
13613}
13614
6ddb6288
ILT
13615// Return true if this is a variable or temporary_variable.
13616
13617bool
13618Expression::is_variable() const
13619{
13620 switch (this->classification_)
13621 {
13622 case EXPRESSION_VAR_REFERENCE:
13623 case EXPRESSION_TEMPORARY_REFERENCE:
13624 case EXPRESSION_SET_AND_USE_TEMPORARY:
13625 return true;
13626 default:
13627 return false;
13628 }
13629}
13630
7a938933
ILT
13631// Return true if this is a reference to a local variable.
13632
13633bool
13634Expression::is_local_variable() const
13635{
13636 const Var_expression* ve = this->var_expression();
13637 if (ve == NULL)
13638 return false;
13639 const Named_object* no = ve->named_object();
13640 return (no->is_result_variable()
13641 || (no->is_variable() && !no->var_value()->is_global()));
13642}
13643
13644// Class Type_guard_expression.
13645
13646// Traversal.
13647
13648int
13649Type_guard_expression::do_traverse(Traverse* traverse)
13650{
13651 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13652 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13653 return TRAVERSE_EXIT;
13654 return TRAVERSE_CONTINUE;
13655}
13656
7035307e
CM
13657Expression*
13658Type_guard_expression::do_flatten(Gogo*, Named_object*,
13659 Statement_inserter* inserter)
13660{
13661 if (!this->expr_->is_variable())
13662 {
13663 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13664 this->location());
13665 inserter->insert(temp);
13666 this->expr_ =
13667 Expression::make_temporary_reference(temp, this->location());
13668 }
13669 return this;
13670}
13671
7a938933
ILT
13672// Check types of a type guard expression. The expression must have
13673// an interface type, but the actual type conversion is checked at run
13674// time.
13675
13676void
13677Type_guard_expression::do_check_types(Gogo*)
13678{
7a938933 13679 Type* expr_type = this->expr_->type();
c92900d1 13680 if (expr_type->interface_type() == NULL)
05d556e8 13681 {
02ed921a 13682 if (!expr_type->is_error() && !this->type_->is_error())
05d556e8
ILT
13683 this->report_error(_("type assertion only valid for interface types"));
13684 this->set_is_error();
13685 }
7a938933
ILT
13686 else if (this->type_->interface_type() == NULL)
13687 {
13688 std::string reason;
13689 if (!expr_type->interface_type()->implements_interface(this->type_,
13690 &reason))
13691 {
02ed921a 13692 if (!this->type_->is_error())
7a938933 13693 {
05d556e8
ILT
13694 if (reason.empty())
13695 this->report_error(_("impossible type assertion: "
13696 "type does not implement interface"));
13697 else
13698 error_at(this->location(),
13699 ("impossible type assertion: "
13700 "type does not implement interface (%s)"),
13701 reason.c_str());
7a938933 13702 }
05d556e8 13703 this->set_is_error();
7a938933
ILT
13704 }
13705 }
13706}
13707
13708// Return a tree for a type guard expression.
13709
13710tree
13711Type_guard_expression::do_get_tree(Translate_context* context)
13712{
7035307e 13713 Expression* conversion;
c92900d1 13714 if (this->type_->interface_type() != NULL)
7035307e
CM
13715 conversion =
13716 Expression::convert_interface_to_interface(this->type_, this->expr_,
13717 true, this->location());
7a938933 13718 else
7035307e
CM
13719 conversion =
13720 Expression::convert_for_assignment(context->gogo(), this->type_,
13721 this->expr_, this->location());
13722
13723 return conversion->get_tree(context);
7a938933
ILT
13724}
13725
16c57fe2
RL
13726// Dump ast representation for a type guard expression.
13727
13728void
7035307e 13729Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
16c57fe2
RL
13730 const
13731{
13732 this->expr_->dump_expression(ast_dump_context);
13733 ast_dump_context->ostream() << ".";
13734 ast_dump_context->dump_type(this->type_);
13735}
13736
7a938933
ILT
13737// Make a type guard expression.
13738
13739Expression*
13740Expression::make_type_guard(Expression* expr, Type* type,
8afa2bfb 13741 Location location)
7a938933
ILT
13742{
13743 return new Type_guard_expression(expr, type, location);
13744}
13745
7035307e 13746// Class Heap_expression.
7a938933 13747
7035307e 13748// When you take the address of an escaping expression, it is allocated
7a938933
ILT
13749// on the heap. This class implements that.
13750
7035307e 13751class Heap_expression : public Expression
7a938933
ILT
13752{
13753 public:
7035307e
CM
13754 Heap_expression(Expression* expr, Location location)
13755 : Expression(EXPRESSION_HEAP, location),
7a938933
ILT
13756 expr_(expr)
13757 { }
13758
13759 protected:
13760 int
13761 do_traverse(Traverse* traverse)
13762 { return Expression::traverse(&this->expr_, traverse); }
13763
13764 Type*
13765 do_type()
13766 { return Type::make_pointer_type(this->expr_->type()); }
13767
13768 void
13769 do_determine_type(const Type_context*)
13770 { this->expr_->determine_type_no_context(); }
13771
13772 Expression*
13773 do_copy()
13774 {
7035307e
CM
13775 return Expression::make_heap_expression(this->expr_->copy(),
13776 this->location());
7a938933
ILT
13777 }
13778
13779 tree
13780 do_get_tree(Translate_context*);
13781
13782 // We only export global objects, and the parser does not generate
13783 // this in global scope.
13784 void
13785 do_export(Export*) const
8c0d1865 13786 { go_unreachable(); }
7a938933 13787
16c57fe2
RL
13788 void
13789 do_dump_expression(Ast_dump_context*) const;
13790
7a938933 13791 private:
7035307e 13792 // The expression which is being put on the heap.
7a938933
ILT
13793 Expression* expr_;
13794};
13795
7035307e 13796// Return a tree which allocates an expression on the heap.
7a938933
ILT
13797
13798tree
7035307e 13799Heap_expression::do_get_tree(Translate_context* context)
7a938933 13800{
e14b9135 13801 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
7a938933 13802 return error_mark_node;
7035307e 13803
e14b9135 13804 Location loc = this->location();
7035307e 13805 Gogo* gogo = context->gogo();
e14b9135
ILT
13806 Btype* btype = this->type()->get_backend(gogo);
13807 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
13808 Bexpression* space = tree_to_expr(alloc->get_tree(context));
13809
13810 Bstatement* decl;
13811 Named_object* fn = context->function();
13812 go_assert(fn != NULL);
13813 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13814 Bvariable* space_temp =
13815 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13816 space, true, loc, &decl);
13817 space = gogo->backend()->var_expression(space_temp, loc);
13818 Bexpression* ref = gogo->backend()->indirect_expression(space, true, loc);
13819
13820 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
13821 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13822 decl = gogo->backend()->compound_statement(decl, assn);
13823 space = gogo->backend()->var_expression(space_temp, loc);
13824 Bexpression* ret = gogo->backend()->compound_expression(decl, space, loc);
13825 return expr_to_tree(ret);
7a938933
ILT
13826}
13827
7035307e 13828// Dump ast representation for a heap expression.
16c57fe2
RL
13829
13830void
7035307e 13831Heap_expression::do_dump_expression(
16c57fe2
RL
13832 Ast_dump_context* ast_dump_context) const
13833{
13834 ast_dump_context->ostream() << "&(";
13835 ast_dump_context->dump_expression(this->expr_);
13836 ast_dump_context->ostream() << ")";
13837}
13838
7035307e 13839// Allocate an expression on the heap.
7a938933
ILT
13840
13841Expression*
7035307e 13842Expression::make_heap_expression(Expression* expr, Location location)
7a938933 13843{
7035307e 13844 return new Heap_expression(expr, location);
7a938933
ILT
13845}
13846
13847// Class Receive_expression.
13848
13849// Return the type of a receive expression.
13850
13851Type*
13852Receive_expression::do_type()
13853{
13854 Channel_type* channel_type = this->channel_->type()->channel_type();
13855 if (channel_type == NULL)
13856 return Type::make_error_type();
13857 return channel_type->element_type();
13858}
13859
13860// Check types for a receive expression.
13861
13862void
13863Receive_expression::do_check_types(Gogo*)
13864{
13865 Type* type = this->channel_->type();
02ed921a 13866 if (type->is_error())
7a938933
ILT
13867 {
13868 this->set_is_error();
13869 return;
13870 }
13871 if (type->channel_type() == NULL)
13872 {
13873 this->report_error(_("expected channel"));
13874 return;
13875 }
13876 if (!type->channel_type()->may_receive())
13877 {
13878 this->report_error(_("invalid receive on send-only channel"));
13879 return;
13880 }
13881}
13882
7035307e
CM
13883// Flattening for receive expressions creates a temporary variable to store
13884// received data in for receives.
13885
13886Expression*
13887Receive_expression::do_flatten(Gogo*, Named_object*,
13888 Statement_inserter* inserter)
13889{
13890 Channel_type* channel_type = this->channel_->type()->channel_type();
13891 if (channel_type == NULL)
13892 {
13893 go_assert(saw_errors());
13894 return this;
13895 }
13896
13897 Type* element_type = channel_type->element_type();
13898 if (this->temp_receiver_ == NULL)
13899 {
13900 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13901 this->location());
13902 this->temp_receiver_->set_is_address_taken();
13903 inserter->insert(this->temp_receiver_);
13904 }
13905
13906 return this;
13907}
13908
7a938933
ILT
13909// Get a tree for a receive expression.
13910
13911tree
13912Receive_expression::do_get_tree(Translate_context* context)
13913{
3e68d6d7
ILT
13914 Location loc = this->location();
13915
7a938933 13916 Channel_type* channel_type = this->channel_->type()->channel_type();
bf6526a0
ILT
13917 if (channel_type == NULL)
13918 {
26409c52 13919 go_assert(this->channel_->type()->is_error());
bf6526a0
ILT
13920 return error_mark_node;
13921 }
3e68d6d7 13922 Expression* td = Expression::make_type_descriptor(channel_type, loc);
7a938933 13923
7035307e
CM
13924 Expression* recv_ref =
13925 Expression::make_temporary_reference(this->temp_receiver_, loc);
13926 Expression* recv_addr =
13927 Expression::make_temporary_reference(this->temp_receiver_, loc);
13928 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13929 Expression* recv =
13930 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13931 td, this->channel_, recv_addr);
13932 recv = Expression::make_compound(recv, recv_ref, loc);
13933 return recv->get_tree(context);
7a938933
ILT
13934}
13935
16c57fe2
RL
13936// Dump ast representation for a receive expression.
13937
13938void
13939Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13940{
13941 ast_dump_context->ostream() << " <- " ;
13942 ast_dump_context->dump_expression(channel_);
13943}
13944
7a938933
ILT
13945// Make a receive expression.
13946
13947Receive_expression*
8afa2bfb 13948Expression::make_receive(Expression* channel, Location location)
7a938933
ILT
13949{
13950 return new Receive_expression(channel, location);
13951}
13952
7a938933
ILT
13953// An expression which evaluates to a pointer to the type descriptor
13954// of a type.
13955
13956class Type_descriptor_expression : public Expression
13957{
13958 public:
8afa2bfb 13959 Type_descriptor_expression(Type* type, Location location)
7a938933
ILT
13960 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13961 type_(type)
13962 { }
13963
13964 protected:
13965 Type*
13966 do_type()
13967 { return Type::make_type_descriptor_ptr_type(); }
13968
8a35e18d
CM
13969 bool
13970 do_is_immutable() const
13971 { return true; }
13972
7a938933
ILT
13973 void
13974 do_determine_type(const Type_context*)
13975 { }
13976
13977 Expression*
13978 do_copy()
13979 { return this; }
13980
13981 tree
13982 do_get_tree(Translate_context* context)
70f91024 13983 {
b93e0cfd
CM
13984 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
13985 this->location());
13986 return expr_to_tree(ret);
70f91024 13987 }
7a938933 13988
16c57fe2
RL
13989 void
13990 do_dump_expression(Ast_dump_context*) const;
13991
7a938933
ILT
13992 private:
13993 // The type for which this is the descriptor.
13994 Type* type_;
13995};
13996
16c57fe2
RL
13997// Dump ast representation for a type descriptor expression.
13998
13999void
14000Type_descriptor_expression::do_dump_expression(
14001 Ast_dump_context* ast_dump_context) const
14002{
14003 ast_dump_context->dump_type(this->type_);
14004}
14005
7a938933
ILT
14006// Make a type descriptor expression.
14007
14008Expression*
8afa2bfb 14009Expression::make_type_descriptor(Type* type, Location location)
7a938933
ILT
14010{
14011 return new Type_descriptor_expression(type, location);
14012}
14013
14014// An expression which evaluates to some characteristic of a type.
14015// This is only used to initialize fields of a type descriptor. Using
14016// a new expression class is slightly inefficient but gives us a good
14017// separation between the frontend and the middle-end with regard to
14018// how types are laid out.
14019
14020class Type_info_expression : public Expression
14021{
14022 public:
14023 Type_info_expression(Type* type, Type_info type_info)
8afa2bfb 14024 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
7a938933
ILT
14025 type_(type), type_info_(type_info)
14026 { }
14027
14028 protected:
39be2171
ILT
14029 bool
14030 do_is_immutable() const
14031 { return true; }
14032
7a938933
ILT
14033 Type*
14034 do_type();
14035
14036 void
14037 do_determine_type(const Type_context*)
14038 { }
14039
14040 Expression*
14041 do_copy()
14042 { return this; }
14043
14044 tree
14045 do_get_tree(Translate_context* context);
14046
16c57fe2
RL
14047 void
14048 do_dump_expression(Ast_dump_context*) const;
14049
7a938933
ILT
14050 private:
14051 // The type for which we are getting information.
14052 Type* type_;
14053 // What information we want.
14054 Type_info type_info_;
14055};
14056
14057// The type is chosen to match what the type descriptor struct
14058// expects.
14059
14060Type*
14061Type_info_expression::do_type()
14062{
14063 switch (this->type_info_)
14064 {
14065 case TYPE_INFO_SIZE:
14066 return Type::lookup_integer_type("uintptr");
14067 case TYPE_INFO_ALIGNMENT:
14068 case TYPE_INFO_FIELD_ALIGNMENT:
14069 return Type::lookup_integer_type("uint8");
14070 default:
8c0d1865 14071 go_unreachable();
7a938933
ILT
14072 }
14073}
14074
14075// Return type information in GENERIC.
14076
14077tree
14078Type_info_expression::do_get_tree(Translate_context* context)
14079{
ef1ed13d
ILT
14080 Btype* btype = this->type_->get_backend(context->gogo());
14081 Gogo* gogo = context->gogo();
14082 size_t val;
14083 switch (this->type_info_)
7a938933 14084 {
ef1ed13d
ILT
14085 case TYPE_INFO_SIZE:
14086 val = gogo->backend()->type_size(btype);
14087 break;
14088 case TYPE_INFO_ALIGNMENT:
14089 val = gogo->backend()->type_alignment(btype);
14090 break;
14091 case TYPE_INFO_FIELD_ALIGNMENT:
14092 val = gogo->backend()->type_field_alignment(btype);
14093 break;
14094 default:
14095 go_unreachable();
7a938933 14096 }
ef1ed13d
ILT
14097 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14098 go_assert(val_type_tree != error_mark_node);
14099 return build_int_cstu(val_type_tree, val);
7a938933
ILT
14100}
14101
16c57fe2
RL
14102// Dump ast representation for a type info expression.
14103
14104void
14105Type_info_expression::do_dump_expression(
14106 Ast_dump_context* ast_dump_context) const
14107{
14108 ast_dump_context->ostream() << "typeinfo(";
14109 ast_dump_context->dump_type(this->type_);
14110 ast_dump_context->ostream() << ",";
14111 ast_dump_context->ostream() <<
14112 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14113 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14114 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14115 : "unknown");
14116 ast_dump_context->ostream() << ")";
14117}
14118
7a938933
ILT
14119// Make a type info expression.
14120
14121Expression*
14122Expression::make_type_info(Type* type, Type_info type_info)
14123{
14124 return new Type_info_expression(type, type_info);
14125}
14126
6ddb6288
ILT
14127// An expression that evaluates to some characteristic of a slice.
14128// This is used when indexing, bound-checking, or nil checking a slice.
14129
14130class Slice_info_expression : public Expression
14131{
14132 public:
14133 Slice_info_expression(Expression* slice, Slice_info slice_info,
14134 Location location)
14135 : Expression(EXPRESSION_SLICE_INFO, location),
14136 slice_(slice), slice_info_(slice_info)
14137 { }
14138
14139 protected:
14140 Type*
14141 do_type();
14142
14143 void
14144 do_determine_type(const Type_context*)
14145 { }
14146
14147 Expression*
14148 do_copy()
14149 {
14150 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14151 this->location());
14152 }
14153
14154 tree
14155 do_get_tree(Translate_context* context);
14156
14157 void
14158 do_dump_expression(Ast_dump_context*) const;
14159
14160 void
14161 do_issue_nil_check()
14162 { this->slice_->issue_nil_check(); }
14163
14164 private:
14165 // The slice for which we are getting information.
14166 Expression* slice_;
14167 // What information we want.
14168 Slice_info slice_info_;
14169};
14170
14171// Return the type of the slice info.
14172
14173Type*
14174Slice_info_expression::do_type()
14175{
14176 switch (this->slice_info_)
14177 {
14178 case SLICE_INFO_VALUE_POINTER:
14179 return Type::make_pointer_type(
14180 this->slice_->type()->array_type()->element_type());
14181 case SLICE_INFO_LENGTH:
14182 case SLICE_INFO_CAPACITY:
14183 return Type::lookup_integer_type("int");
14184 default:
14185 go_unreachable();
14186 }
14187}
14188
14189// Return slice information in GENERIC.
14190
14191tree
14192Slice_info_expression::do_get_tree(Translate_context* context)
14193{
14194 Gogo* gogo = context->gogo();
14195
14196 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14197 Bexpression* ret;
14198 switch (this->slice_info_)
14199 {
14200 case SLICE_INFO_VALUE_POINTER:
14201 case SLICE_INFO_LENGTH:
14202 case SLICE_INFO_CAPACITY:
14203 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14204 this->location());
14205 break;
14206 default:
14207 go_unreachable();
14208 }
14209 return expr_to_tree(ret);
14210}
14211
14212// Dump ast representation for a type info expression.
14213
14214void
14215Slice_info_expression::do_dump_expression(
14216 Ast_dump_context* ast_dump_context) const
14217{
14218 ast_dump_context->ostream() << "sliceinfo(";
14219 this->slice_->dump_expression(ast_dump_context);
14220 ast_dump_context->ostream() << ",";
14221 ast_dump_context->ostream() <<
14222 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14223 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14224 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14225 : "unknown");
14226 ast_dump_context->ostream() << ")";
14227}
14228
14229// Make a slice info expression.
14230
14231Expression*
14232Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14233 Location location)
14234{
14235 return new Slice_info_expression(slice, slice_info, location);
14236}
14237
7035307e
CM
14238// An expression that represents a slice value: a struct with value pointer,
14239// length, and capacity fields.
14240
14241class Slice_value_expression : public Expression
14242{
14243 public:
14244 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14245 Expression* cap, Location location)
14246 : Expression(EXPRESSION_SLICE_VALUE, location),
14247 type_(type), valptr_(valptr), len_(len), cap_(cap)
14248 { }
14249
14250 protected:
14251 int
14252 do_traverse(Traverse*);
14253
14254 Type*
14255 do_type()
14256 { return this->type_; }
14257
14258 void
14259 do_determine_type(const Type_context*)
14260 { go_unreachable(); }
14261
14262 Expression*
14263 do_copy()
14264 {
14265 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14266 this->len_->copy(), this->cap_->copy(),
14267 this->location());
14268 }
14269
14270 tree
14271 do_get_tree(Translate_context* context);
14272
14273 void
14274 do_dump_expression(Ast_dump_context*) const;
14275
14276 private:
14277 // The type of the slice value.
14278 Type* type_;
14279 // The pointer to the values in the slice.
14280 Expression* valptr_;
14281 // The length of the slice.
14282 Expression* len_;
14283 // The capacity of the slice.
14284 Expression* cap_;
14285};
14286
14287int
14288Slice_value_expression::do_traverse(Traverse* traverse)
14289{
14290 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14291 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14292 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14293 return TRAVERSE_EXIT;
14294 return TRAVERSE_CONTINUE;
14295}
14296
14297tree
14298Slice_value_expression::do_get_tree(Translate_context* context)
14299{
14300 std::vector<Bexpression*> vals(3);
14301 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14302 vals[1] = tree_to_expr(this->len_->get_tree(context));
14303 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14304
14305 Gogo* gogo = context->gogo();
14306 Btype* btype = this->type_->get_backend(gogo);
14307 Bexpression* ret =
14308 gogo->backend()->constructor_expression(btype, vals, this->location());
14309 return expr_to_tree(ret);
14310}
14311
14312void
14313Slice_value_expression::do_dump_expression(
14314 Ast_dump_context* ast_dump_context) const
14315{
14316 ast_dump_context->ostream() << "slicevalue(";
14317 ast_dump_context->ostream() << "values: ";
14318 this->valptr_->dump_expression(ast_dump_context);
14319 ast_dump_context->ostream() << ", length: ";
14320 this->len_->dump_expression(ast_dump_context);
14321 ast_dump_context->ostream() << ", capacity: ";
14322 this->cap_->dump_expression(ast_dump_context);
14323 ast_dump_context->ostream() << ")";
14324}
14325
14326Expression*
14327Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14328 Expression* cap, Location location)
14329{
14330 go_assert(at->is_slice_type());
14331 return new Slice_value_expression(at, valptr, len, cap, location);
14332}
eb6eb862
CM
14333
14334// An expression that evaluates to some characteristic of a non-empty interface.
14335// This is used to access the method table or underlying object of an interface.
14336
14337class Interface_info_expression : public Expression
14338{
14339 public:
14340 Interface_info_expression(Expression* iface, Interface_info iface_info,
7035307e 14341 Location location)
eb6eb862
CM
14342 : Expression(EXPRESSION_INTERFACE_INFO, location),
14343 iface_(iface), iface_info_(iface_info)
14344 { }
14345
14346 protected:
14347 Type*
14348 do_type();
14349
14350 void
14351 do_determine_type(const Type_context*)
14352 { }
14353
14354 Expression*
14355 do_copy()
14356 {
14357 return new Interface_info_expression(this->iface_->copy(),
14358 this->iface_info_, this->location());
14359 }
14360
14361 tree
14362 do_get_tree(Translate_context* context);
14363
14364 void
14365 do_dump_expression(Ast_dump_context*) const;
14366
14367 void
14368 do_issue_nil_check()
14369 { this->iface_->issue_nil_check(); }
14370
14371 private:
14372 // The interface for which we are getting information.
14373 Expression* iface_;
14374 // What information we want.
14375 Interface_info iface_info_;
14376};
14377
14378// Return the type of the interface info.
14379
14380Type*
14381Interface_info_expression::do_type()
14382{
14383 switch (this->iface_info_)
14384 {
14385 case INTERFACE_INFO_METHODS:
14386 {
7035307e
CM
14387 Type* pdt = Type::make_type_descriptor_ptr_type();
14388 if (this->iface_->type()->interface_type()->is_empty())
14389 return pdt;
14390
eb6eb862
CM
14391 Location loc = this->location();
14392 Struct_field_list* sfl = new Struct_field_list();
eb6eb862
CM
14393 sfl->push_back(
14394 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14395
14396 Interface_type* itype = this->iface_->type()->interface_type();
14397 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14398 p != itype->methods()->end();
14399 ++p)
14400 {
14401 Function_type* ft = p->type()->function_type();
14402 go_assert(ft->receiver() == NULL);
14403
14404 const Typed_identifier_list* params = ft->parameters();
14405 Typed_identifier_list* mparams = new Typed_identifier_list();
14406 if (params != NULL)
14407 mparams->reserve(params->size() + 1);
14408 Type* vt = Type::make_pointer_type(Type::make_void_type());
14409 mparams->push_back(Typed_identifier("", vt, ft->location()));
14410 if (params != NULL)
14411 {
14412 for (Typed_identifier_list::const_iterator pp = params->begin();
14413 pp != params->end();
14414 ++pp)
14415 mparams->push_back(*pp);
14416 }
14417
14418 Typed_identifier_list* mresults = (ft->results() == NULL
14419 ? NULL
14420 : ft->results()->copy());
14421 Backend_function_type* mft =
14422 Type::make_backend_function_type(NULL, mparams, mresults,
14423 ft->location());
14424
14425 std::string fname = Gogo::unpack_hidden_name(p->name());
14426 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14427 }
14428
14429 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14430 }
14431 case INTERFACE_INFO_OBJECT:
14432 return Type::make_pointer_type(Type::make_void_type());
14433 default:
14434 go_unreachable();
14435 }
14436}
14437
14438// Return interface information in GENERIC.
14439
14440tree
14441Interface_info_expression::do_get_tree(Translate_context* context)
14442{
14443 Gogo* gogo = context->gogo();
14444
14445 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14446 Bexpression* ret;
14447 switch (this->iface_info_)
14448 {
14449 case INTERFACE_INFO_METHODS:
14450 case INTERFACE_INFO_OBJECT:
14451 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14452 this->location());
14453 break;
14454 default:
14455 go_unreachable();
14456 }
14457 return expr_to_tree(ret);
14458}
14459
14460// Dump ast representation for an interface info expression.
14461
14462void
14463Interface_info_expression::do_dump_expression(
14464 Ast_dump_context* ast_dump_context) const
14465{
7035307e 14466 bool is_empty = this->iface_->type()->interface_type()->is_empty();
eb6eb862
CM
14467 ast_dump_context->ostream() << "interfaceinfo(";
14468 this->iface_->dump_expression(ast_dump_context);
14469 ast_dump_context->ostream() << ",";
14470 ast_dump_context->ostream() <<
7035307e
CM
14471 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14472 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
eb6eb862
CM
14473 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14474 : "unknown");
14475 ast_dump_context->ostream() << ")";
14476}
14477
14478// Make an interface info expression.
14479
14480Expression*
14481Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14482 Location location)
14483{
14484 return new Interface_info_expression(iface, iface_info, location);
14485}
14486
7035307e
CM
14487// An expression that represents an interface value. The first field is either
14488// a type descriptor for an empty interface or a pointer to the interface method
14489// table for a non-empty interface. The second field is always the object.
14490
14491class Interface_value_expression : public Expression
14492{
14493 public:
14494 Interface_value_expression(Type* type, Expression* first_field,
14495 Expression* obj, Location location)
14496 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14497 type_(type), first_field_(first_field), obj_(obj)
14498 { }
14499
14500 protected:
14501 int
14502 do_traverse(Traverse*);
14503
14504 Type*
14505 do_type()
14506 { return this->type_; }
14507
14508 void
14509 do_determine_type(const Type_context*)
14510 { go_unreachable(); }
14511
14512 Expression*
14513 do_copy()
14514 {
14515 return new Interface_value_expression(this->type_,
14516 this->first_field_->copy(),
14517 this->obj_->copy(), this->location());
14518 }
14519
14520 tree
14521 do_get_tree(Translate_context* context);
14522
14523 void
14524 do_dump_expression(Ast_dump_context*) const;
14525
14526 private:
14527 // The type of the interface value.
14528 Type* type_;
14529 // The first field of the interface (either a type descriptor or a pointer
14530 // to the method table.
14531 Expression* first_field_;
14532 // The underlying object of the interface.
14533 Expression* obj_;
14534};
14535
14536int
14537Interface_value_expression::do_traverse(Traverse* traverse)
14538{
14539 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14540 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14541 return TRAVERSE_EXIT;
14542 return TRAVERSE_CONTINUE;
14543}
14544
14545tree
14546Interface_value_expression::do_get_tree(Translate_context* context)
14547{
14548 std::vector<Bexpression*> vals(2);
14549 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14550 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14551
14552 Gogo* gogo = context->gogo();
14553 Btype* btype = this->type_->get_backend(gogo);
14554 Bexpression* ret =
14555 gogo->backend()->constructor_expression(btype, vals, this->location());
14556 return expr_to_tree(ret);
14557}
14558
14559void
14560Interface_value_expression::do_dump_expression(
14561 Ast_dump_context* ast_dump_context) const
14562{
14563 ast_dump_context->ostream() << "interfacevalue(";
14564 ast_dump_context->ostream() <<
14565 (this->type_->interface_type()->is_empty()
14566 ? "type_descriptor: "
14567 : "methods: ");
14568 this->first_field_->dump_expression(ast_dump_context);
14569 ast_dump_context->ostream() << ", object: ";
14570 this->obj_->dump_expression(ast_dump_context);
14571 ast_dump_context->ostream() << ")";
14572}
14573
14574Expression*
14575Expression::make_interface_value(Type* type, Expression* first_value,
14576 Expression* object, Location location)
14577{
14578 return new Interface_value_expression(type, first_value, object, location);
14579}
14580
14581// An interface method table for a pair of types: an interface type and a type
14582// that implements that interface.
14583
14584class Interface_mtable_expression : public Expression
14585{
14586 public:
14587 Interface_mtable_expression(Interface_type* itype, Type* type,
14588 bool is_pointer, Location location)
14589 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14590 itype_(itype), type_(type), is_pointer_(is_pointer),
14591 method_table_type_(NULL), bvar_(NULL)
14592 { }
14593
14594 protected:
14595 int
14596 do_traverse(Traverse*);
14597
14598 Type*
14599 do_type();
14600
14601 bool
14602 is_immutable() const
14603 { return true; }
14604
14605 void
14606 do_determine_type(const Type_context*)
14607 { go_unreachable(); }
14608
14609 Expression*
14610 do_copy()
14611 {
14612 return new Interface_mtable_expression(this->itype_, this->type_,
14613 this->is_pointer_, this->location());
14614 }
14615
14616 bool
14617 do_is_addressable() const
14618 { return true; }
14619
14620 tree
14621 do_get_tree(Translate_context* context);
14622
14623 void
14624 do_dump_expression(Ast_dump_context*) const;
14625
14626 private:
14627 // The interface type for which the methods are defined.
14628 Interface_type* itype_;
14629 // The type to construct the interface method table for.
14630 Type* type_;
14631 // Whether this table contains the method set for the receiver type or the
14632 // pointer receiver type.
14633 bool is_pointer_;
14634 // The type of the method table.
14635 Type* method_table_type_;
14636 // The backend variable that refers to the interface method table.
14637 Bvariable* bvar_;
14638};
14639
14640int
14641Interface_mtable_expression::do_traverse(Traverse* traverse)
14642{
14643 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14644 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14645 return TRAVERSE_EXIT;
14646 return TRAVERSE_CONTINUE;
14647}
14648
14649Type*
14650Interface_mtable_expression::do_type()
14651{
14652 if (this->method_table_type_ != NULL)
14653 return this->method_table_type_;
14654
14655 const Typed_identifier_list* interface_methods = this->itype_->methods();
14656 go_assert(!interface_methods->empty());
14657
14658 Struct_field_list* sfl = new Struct_field_list;
14659 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14660 this->location());
14661 sfl->push_back(Struct_field(tid));
14662 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14663 p != interface_methods->end();
14664 ++p)
14665 sfl->push_back(Struct_field(*p));
14666 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14667 return this->method_table_type_;
14668}
14669
14670tree
14671Interface_mtable_expression::do_get_tree(Translate_context* context)
14672{
14673 Gogo* gogo = context->gogo();
14674 Bexpression* ret;
14675 Location loc = Linemap::predeclared_location();
14676 if (this->bvar_ != NULL)
14677 {
14678 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14679 return expr_to_tree(ret);
14680 }
14681
14682 const Typed_identifier_list* interface_methods = this->itype_->methods();
14683 go_assert(!interface_methods->empty());
14684
14685 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14686 + this->itype_->mangled_name(gogo)
14687 + "__"
14688 + this->type_->mangled_name(gogo));
14689
14690 // See whether this interface has any hidden methods.
14691 bool has_hidden_methods = false;
14692 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14693 p != interface_methods->end();
14694 ++p)
14695 {
14696 if (Gogo::is_hidden_name(p->name()))
14697 {
14698 has_hidden_methods = true;
14699 break;
14700 }
14701 }
14702
14703 // We already know that the named type is convertible to the
14704 // interface. If the interface has hidden methods, and the named
14705 // type is defined in a different package, then the interface
14706 // conversion table will be defined by that other package.
14707 if (has_hidden_methods
14708 && this->type_->named_type() != NULL
14709 && this->type_->named_type()->named_object()->package() != NULL)
14710 {
14711 Btype* btype = this->type()->get_backend(gogo);
14712 this->bvar_ =
14713 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14714 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14715 return expr_to_tree(ret);
14716 }
14717
14718 // The first element is the type descriptor.
14719 Type* td_type;
14720 if (!this->is_pointer_)
14721 td_type = this->type_;
14722 else
14723 td_type = Type::make_pointer_type(this->type_);
14724
14725 // Build an interface method table for a type: a type descriptor followed by a
14726 // list of function pointers, one for each interface method. This is used for
14727 // interfaces.
14728 Expression_list* svals = new Expression_list();
14729 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14730
14731 Named_type* nt = this->type_->named_type();
14732 Struct_type* st = this->type_->struct_type();
14733 go_assert(nt != NULL || st != NULL);
14734
14735 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14736 p != interface_methods->end();
14737 ++p)
14738 {
14739 bool is_ambiguous;
14740 Method* m;
14741 if (nt != NULL)
14742 m = nt->method_function(p->name(), &is_ambiguous);
14743 else
14744 m = st->method_function(p->name(), &is_ambiguous);
14745 go_assert(m != NULL);
14746 Named_object* no = m->named_object();
14747
14748 go_assert(no->is_function() || no->is_function_declaration());
14749 svals->push_back(Expression::make_func_code_reference(no, loc));
14750 }
14751
14752 Btype* btype = this->type()->get_backend(gogo);
14753 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14754 svals, loc);
14755 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14756
14757 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14758 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14759 !is_public, btype, loc);
14760 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14761 !is_public, btype, loc, ctor);
14762 ret = gogo->backend()->var_expression(this->bvar_, loc);
14763 return expr_to_tree(ret);
14764}
14765
14766void
14767Interface_mtable_expression::do_dump_expression(
14768 Ast_dump_context* ast_dump_context) const
14769{
14770 ast_dump_context->ostream() << "__go_"
14771 << (this->is_pointer_ ? "pimt__" : "imt_");
14772 ast_dump_context->dump_type(this->itype_);
14773 ast_dump_context->ostream() << "__";
14774 ast_dump_context->dump_type(this->type_);
14775}
14776
14777Expression*
14778Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14779 bool is_pointer, Location location)
14780{
14781 return new Interface_mtable_expression(itype, type, is_pointer, location);
14782}
14783
7a938933
ILT
14784// An expression which evaluates to the offset of a field within a
14785// struct. This, like Type_info_expression, q.v., is only used to
14786// initialize fields of a type descriptor.
14787
14788class Struct_field_offset_expression : public Expression
14789{
14790 public:
14791 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
8afa2bfb
SD
14792 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14793 Linemap::predeclared_location()),
7a938933
ILT
14794 type_(type), field_(field)
14795 { }
14796
14797 protected:
14798 Type*
14799 do_type()
14800 { return Type::lookup_integer_type("uintptr"); }
14801
14802 void
14803 do_determine_type(const Type_context*)
14804 { }
14805
14806 Expression*
14807 do_copy()
14808 { return this; }
14809
14810 tree
14811 do_get_tree(Translate_context* context);
14812
16c57fe2
RL
14813 void
14814 do_dump_expression(Ast_dump_context*) const;
14815
7a938933
ILT
14816 private:
14817 // The type of the struct.
14818 Struct_type* type_;
14819 // The field.
14820 const Struct_field* field_;
14821};
14822
14823// Return a struct field offset in GENERIC.
14824
14825tree
14826Struct_field_offset_expression::do_get_tree(Translate_context* context)
14827{
5b735706 14828 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
7a938933
ILT
14829 if (type_tree == error_mark_node)
14830 return error_mark_node;
14831
5b735706 14832 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
26409c52 14833 go_assert(val_type_tree != error_mark_node);
7a938933
ILT
14834
14835 const Struct_field_list* fields = this->type_->fields();
14836 tree struct_field_tree = TYPE_FIELDS(type_tree);
14837 Struct_field_list::const_iterator p;
14838 for (p = fields->begin();
14839 p != fields->end();
14840 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14841 {
26409c52 14842 go_assert(struct_field_tree != NULL_TREE);
7a938933
ILT
14843 if (&*p == this->field_)
14844 break;
14845 }
26409c52 14846 go_assert(&*p == this->field_);
7a938933
ILT
14847
14848 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14849 byte_position(struct_field_tree));
14850}
14851
16c57fe2
RL
14852// Dump ast representation for a struct field offset expression.
14853
14854void
14855Struct_field_offset_expression::do_dump_expression(
14856 Ast_dump_context* ast_dump_context) const
14857{
14858 ast_dump_context->ostream() << "unsafe.Offsetof(";
ffe08917
ILT
14859 ast_dump_context->dump_type(this->type_);
14860 ast_dump_context->ostream() << '.';
14861 ast_dump_context->ostream() <<
14862 Gogo::message_name(this->field_->field_name());
16c57fe2
RL
14863 ast_dump_context->ostream() << ")";
14864}
14865
7a938933
ILT
14866// Make an expression for a struct field offset.
14867
14868Expression*
14869Expression::make_struct_field_offset(Struct_type* type,
14870 const Struct_field* field)
14871{
14872 return new Struct_field_offset_expression(type, field);
14873}
14874
3b8dffe7
ILT
14875// An expression which evaluates to a pointer to the map descriptor of
14876// a map type.
14877
14878class Map_descriptor_expression : public Expression
14879{
14880 public:
8afa2bfb 14881 Map_descriptor_expression(Map_type* type, Location location)
3b8dffe7
ILT
14882 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14883 type_(type)
14884 { }
14885
14886 protected:
14887 Type*
14888 do_type()
14889 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14890
14891 void
14892 do_determine_type(const Type_context*)
14893 { }
14894
14895 Expression*
14896 do_copy()
14897 { return this; }
14898
14899 tree
14900 do_get_tree(Translate_context* context)
14901 {
b93e0cfd
CM
14902 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14903 this->location());
14904 return expr_to_tree(ret);
3b8dffe7
ILT
14905 }
14906
16c57fe2
RL
14907 void
14908 do_dump_expression(Ast_dump_context*) const;
14909
3b8dffe7
ILT
14910 private:
14911 // The type for which this is the descriptor.
14912 Map_type* type_;
14913};
14914
16c57fe2
RL
14915// Dump ast representation for a map descriptor expression.
14916
14917void
14918Map_descriptor_expression::do_dump_expression(
14919 Ast_dump_context* ast_dump_context) const
14920{
14921 ast_dump_context->ostream() << "map_descriptor(";
14922 ast_dump_context->dump_type(this->type_);
14923 ast_dump_context->ostream() << ")";
14924}
14925
3b8dffe7
ILT
14926// Make a map descriptor expression.
14927
14928Expression*
8afa2bfb 14929Expression::make_map_descriptor(Map_type* type, Location location)
3b8dffe7
ILT
14930{
14931 return new Map_descriptor_expression(type, location);
14932}
14933
7a938933
ILT
14934// An expression which evaluates to the address of an unnamed label.
14935
14936class Label_addr_expression : public Expression
14937{
14938 public:
8afa2bfb 14939 Label_addr_expression(Label* label, Location location)
7a938933
ILT
14940 : Expression(EXPRESSION_LABEL_ADDR, location),
14941 label_(label)
14942 { }
14943
14944 protected:
14945 Type*
14946 do_type()
14947 { return Type::make_pointer_type(Type::make_void_type()); }
14948
14949 void
14950 do_determine_type(const Type_context*)
14951 { }
14952
14953 Expression*
14954 do_copy()
14955 { return new Label_addr_expression(this->label_, this->location()); }
14956
14957 tree
d56e6679
ILT
14958 do_get_tree(Translate_context* context)
14959 {
db0adf82 14960 return expr_to_tree(this->label_->get_addr(context, this->location()));
d56e6679 14961 }
7a938933 14962
16c57fe2
RL
14963 void
14964 do_dump_expression(Ast_dump_context* ast_dump_context) const
14965 { ast_dump_context->ostream() << this->label_->name(); }
14966
7a938933
ILT
14967 private:
14968 // The label whose address we are taking.
14969 Label* label_;
14970};
14971
14972// Make an expression for the address of an unnamed label.
14973
14974Expression*
8afa2bfb 14975Expression::make_label_addr(Label* label, Location location)
7a938933
ILT
14976{
14977 return new Label_addr_expression(label, location);
14978}
14979
56e13ae0
ILT
14980// Conditional expressions.
14981
14982class Conditional_expression : public Expression
14983{
14984 public:
14985 Conditional_expression(Expression* cond, Expression* then_expr,
14986 Expression* else_expr, Location location)
14987 : Expression(EXPRESSION_CONDITIONAL, location),
14988 cond_(cond), then_(then_expr), else_(else_expr)
14989 {}
14990
14991 protected:
7035307e
CM
14992 int
14993 do_traverse(Traverse*);
14994
56e13ae0
ILT
14995 Type*
14996 do_type();
14997
14998 void
7035307e 14999 do_determine_type(const Type_context*);
56e13ae0
ILT
15000
15001 Expression*
15002 do_copy()
15003 {
15004 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
15005 this->else_->copy(), this->location());
15006 }
15007
15008 tree
15009 do_get_tree(Translate_context* context);
15010
15011 void
15012 do_dump_expression(Ast_dump_context*) const;
15013
15014 private:
15015 // The condition to be checked.
15016 Expression* cond_;
15017 // The expression to execute if the condition is true.
15018 Expression* then_;
15019 // The expression to execute if the condition is false.
15020 Expression* else_;
15021};
15022
7035307e
CM
15023// Traversal.
15024
15025int
15026Conditional_expression::do_traverse(Traverse* traverse)
15027{
15028 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15029 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15030 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15031 return TRAVERSE_EXIT;
15032 return TRAVERSE_CONTINUE;
15033}
15034
56e13ae0
ILT
15035// Return the type of the conditional expression.
15036
15037Type*
15038Conditional_expression::do_type()
15039{
15040 Type* result_type = Type::make_void_type();
7035307e
CM
15041 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15042 NULL))
56e13ae0
ILT
15043 result_type = this->then_->type();
15044 else if (this->then_->is_nil_expression()
15045 || this->else_->is_nil_expression())
15046 result_type = (!this->then_->is_nil_expression()
15047 ? this->then_->type()
15048 : this->else_->type());
15049 return result_type;
15050}
15051
7035307e
CM
15052// Determine type for a conditional expression.
15053
15054void
15055Conditional_expression::do_determine_type(const Type_context* context)
15056{
15057 this->cond_->determine_type_no_context();
15058 this->then_->determine_type(context);
15059 this->else_->determine_type(context);
15060}
15061
56e13ae0
ILT
15062// Get the backend representation of a conditional expression.
15063
15064tree
15065Conditional_expression::do_get_tree(Translate_context* context)
15066{
15067 Gogo* gogo = context->gogo();
15068 Btype* result_btype = this->type()->get_backend(gogo);
15069 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15070 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15071 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15072 Bexpression* ret =
15073 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15074 this->location());
15075 return expr_to_tree(ret);
15076}
15077
15078// Dump ast representation of a conditional expression.
15079
15080void
15081Conditional_expression::do_dump_expression(
15082 Ast_dump_context* ast_dump_context) const
15083{
15084 ast_dump_context->ostream() << "(";
15085 ast_dump_context->dump_expression(this->cond_);
15086 ast_dump_context->ostream() << " ? ";
15087 ast_dump_context->dump_expression(this->then_);
15088 ast_dump_context->ostream() << " : ";
15089 ast_dump_context->dump_expression(this->else_);
15090 ast_dump_context->ostream() << ") ";
15091}
15092
15093// Make a conditional expression.
15094
15095Expression*
15096Expression::make_conditional(Expression* cond, Expression* then,
15097 Expression* else_expr, Location location)
15098{
15099 return new Conditional_expression(cond, then, else_expr, location);
15100}
15101
7035307e
CM
15102// Compound expressions.
15103
15104class Compound_expression : public Expression
15105{
15106 public:
15107 Compound_expression(Expression* init, Expression* expr, Location location)
15108 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15109 {}
15110
15111 protected:
15112 int
15113 do_traverse(Traverse*);
15114
15115 Type*
15116 do_type();
15117
15118 void
15119 do_determine_type(const Type_context*);
15120
15121 Expression*
15122 do_copy()
15123 {
15124 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15125 this->location());
15126 }
15127
15128 tree
15129 do_get_tree(Translate_context* context);
15130
15131 void
15132 do_dump_expression(Ast_dump_context*) const;
15133
15134 private:
15135 // The expression that is evaluated first and discarded.
15136 Expression* init_;
15137 // The expression that is evaluated and returned.
15138 Expression* expr_;
15139};
15140
15141// Traversal.
15142
15143int
15144Compound_expression::do_traverse(Traverse* traverse)
15145{
15146 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15147 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15148 return TRAVERSE_EXIT;
15149 return TRAVERSE_CONTINUE;
15150}
15151
15152// Return the type of the compound expression.
15153
15154Type*
15155Compound_expression::do_type()
15156{
15157 return this->expr_->type();
15158}
15159
15160// Determine type for a compound expression.
15161
15162void
15163Compound_expression::do_determine_type(const Type_context* context)
15164{
15165 this->init_->determine_type_no_context();
15166 this->expr_->determine_type(context);
15167}
15168
15169// Get the backend representation of a compound expression.
15170
15171tree
15172Compound_expression::do_get_tree(Translate_context* context)
15173{
15174 Gogo* gogo = context->gogo();
15175 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15176 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15177 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15178 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15179 this->location());
15180 return expr_to_tree(ret);
15181}
15182
15183// Dump ast representation of a conditional expression.
15184
15185void
15186Compound_expression::do_dump_expression(
15187 Ast_dump_context* ast_dump_context) const
15188{
15189 ast_dump_context->ostream() << "(";
15190 ast_dump_context->dump_expression(this->init_);
15191 ast_dump_context->ostream() << ",";
15192 ast_dump_context->dump_expression(this->expr_);
15193 ast_dump_context->ostream() << ") ";
15194}
15195
15196// Make a compound expression.
15197
15198Expression*
15199Expression::make_compound(Expression* init, Expression* expr, Location location)
15200{
15201 return new Compound_expression(init, expr, location);
15202}
15203
7a938933
ILT
15204// Import an expression. This comes at the end in order to see the
15205// various class definitions.
15206
15207Expression*
15208Expression::import_expression(Import* imp)
15209{
15210 int c = imp->peek_char();
15211 if (imp->match_c_string("- ")
15212 || imp->match_c_string("! ")
15213 || imp->match_c_string("^ "))
15214 return Unary_expression::do_import(imp);
15215 else if (c == '(')
15216 return Binary_expression::do_import(imp);
15217 else if (imp->match_c_string("true")
15218 || imp->match_c_string("false"))
15219 return Boolean_expression::do_import(imp);
15220 else if (c == '"')
15221 return String_expression::do_import(imp);
15222 else if (c == '-' || (c >= '0' && c <= '9'))
15223 {
15224 // This handles integers, floats and complex constants.
15225 return Integer_expression::do_import(imp);
15226 }
15227 else if (imp->match_c_string("nil"))
15228 return Nil_expression::do_import(imp);
15229 else if (imp->match_c_string("convert"))
15230 return Type_conversion_expression::do_import(imp);
15231 else
15232 {
15233 error_at(imp->location(), "import error: expected expression");
15234 return Expression::make_error(imp->location());
15235 }
15236}
15237
15238// Class Expression_list.
15239
15240// Traverse the list.
15241
15242int
15243Expression_list::traverse(Traverse* traverse)
15244{
15245 for (Expression_list::iterator p = this->begin();
15246 p != this->end();
15247 ++p)
15248 {
15249 if (*p != NULL)
15250 {
15251 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15252 return TRAVERSE_EXIT;
15253 }
15254 }
15255 return TRAVERSE_CONTINUE;
15256}
15257
15258// Copy the list.
15259
15260Expression_list*
15261Expression_list::copy()
15262{
15263 Expression_list* ret = new Expression_list();
15264 for (Expression_list::iterator p = this->begin();
15265 p != this->end();
15266 ++p)
15267 {
15268 if (*p == NULL)
15269 ret->push_back(NULL);
15270 else
15271 ret->push_back((*p)->copy());
15272 }
15273 return ret;
15274}
15275
15276// Return whether an expression list has an error expression.
15277
15278bool
15279Expression_list::contains_error() const
15280{
15281 for (Expression_list::const_iterator p = this->begin();
15282 p != this->end();
15283 ++p)
15284 if (*p != NULL && (*p)->is_error_expression())
15285 return true;
15286 return false;
15287}
5caf63ca
ILT
15288
15289// Class Numeric_constant.
15290
15291// Destructor.
15292
15293Numeric_constant::~Numeric_constant()
15294{
15295 this->clear();
15296}
15297
15298// Copy constructor.
15299
15300Numeric_constant::Numeric_constant(const Numeric_constant& a)
15301 : classification_(a.classification_), type_(a.type_)
15302{
15303 switch (a.classification_)
15304 {
15305 case NC_INVALID:
15306 break;
15307 case NC_INT:
15308 case NC_RUNE:
15309 mpz_init_set(this->u_.int_val, a.u_.int_val);
15310 break;
15311 case NC_FLOAT:
15312 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15313 break;
15314 case NC_COMPLEX:
15315 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15316 GMP_RNDN);
15317 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15318 GMP_RNDN);
15319 break;
15320 default:
15321 go_unreachable();
15322 }
15323}
15324
15325// Assignment operator.
15326
15327Numeric_constant&
15328Numeric_constant::operator=(const Numeric_constant& a)
15329{
15330 this->clear();
15331 this->classification_ = a.classification_;
15332 this->type_ = a.type_;
15333 switch (a.classification_)
15334 {
15335 case NC_INVALID:
15336 break;
15337 case NC_INT:
15338 case NC_RUNE:
15339 mpz_init_set(this->u_.int_val, a.u_.int_val);
15340 break;
15341 case NC_FLOAT:
15342 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15343 break;
15344 case NC_COMPLEX:
15345 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15346 GMP_RNDN);
15347 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15348 GMP_RNDN);
15349 break;
15350 default:
15351 go_unreachable();
15352 }
15353 return *this;
15354}
15355
15356// Clear the contents.
15357
15358void
15359Numeric_constant::clear()
15360{
15361 switch (this->classification_)
15362 {
15363 case NC_INVALID:
15364 break;
15365 case NC_INT:
15366 case NC_RUNE:
15367 mpz_clear(this->u_.int_val);
15368 break;
15369 case NC_FLOAT:
15370 mpfr_clear(this->u_.float_val);
15371 break;
15372 case NC_COMPLEX:
15373 mpfr_clear(this->u_.complex_val.real);
15374 mpfr_clear(this->u_.complex_val.imag);
15375 break;
15376 default:
15377 go_unreachable();
15378 }
15379 this->classification_ = NC_INVALID;
15380}
15381
15382// Set to an unsigned long value.
15383
15384void
15385Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15386{
15387 this->clear();
15388 this->classification_ = NC_INT;
15389 this->type_ = type;
15390 mpz_init_set_ui(this->u_.int_val, val);
15391}
15392
15393// Set to an integer value.
15394
15395void
15396Numeric_constant::set_int(Type* type, const mpz_t val)
15397{
15398 this->clear();
15399 this->classification_ = NC_INT;
15400 this->type_ = type;
15401 mpz_init_set(this->u_.int_val, val);
15402}
15403
15404// Set to a rune value.
15405
15406void
15407Numeric_constant::set_rune(Type* type, const mpz_t val)
15408{
15409 this->clear();
15410 this->classification_ = NC_RUNE;
15411 this->type_ = type;
15412 mpz_init_set(this->u_.int_val, val);
15413}
15414
15415// Set to a floating point value.
15416
15417void
15418Numeric_constant::set_float(Type* type, const mpfr_t val)
15419{
15420 this->clear();
15421 this->classification_ = NC_FLOAT;
15422 this->type_ = type;
073d123c
ILT
15423 // Numeric constants do not have negative zero values, so remove
15424 // them here. They also don't have infinity or NaN values, but we
15425 // should never see them here.
15426 if (mpfr_zero_p(val))
15427 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15428 else
15429 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
5caf63ca
ILT
15430}
15431
15432// Set to a complex value.
15433
15434void
15435Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15436{
15437 this->clear();
15438 this->classification_ = NC_COMPLEX;
15439 this->type_ = type;
15440 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15441 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15442}
15443
15444// Get an int value.
15445
15446void
15447Numeric_constant::get_int(mpz_t* val) const
15448{
15449 go_assert(this->is_int());
15450 mpz_init_set(*val, this->u_.int_val);
15451}
15452
15453// Get a rune value.
15454
15455void
15456Numeric_constant::get_rune(mpz_t* val) const
15457{
15458 go_assert(this->is_rune());
15459 mpz_init_set(*val, this->u_.int_val);
15460}
15461
15462// Get a floating point value.
15463
15464void
15465Numeric_constant::get_float(mpfr_t* val) const
15466{
15467 go_assert(this->is_float());
15468 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15469}
15470
15471// Get a complex value.
15472
15473void
15474Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15475{
15476 go_assert(this->is_complex());
15477 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15478 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15479}
15480
15481// Express value as unsigned long if possible.
15482
15483Numeric_constant::To_unsigned_long
15484Numeric_constant::to_unsigned_long(unsigned long* val) const
15485{
15486 switch (this->classification_)
15487 {
15488 case NC_INT:
15489 case NC_RUNE:
15490 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15491 case NC_FLOAT:
15492 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15493 case NC_COMPLEX:
15494 if (!mpfr_zero_p(this->u_.complex_val.imag))
15495 return NC_UL_NOTINT;
15496 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15497 default:
15498 go_unreachable();
15499 }
15500}
15501
15502// Express integer value as unsigned long if possible.
15503
15504Numeric_constant::To_unsigned_long
15505Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15506 unsigned long *val) const
15507{
15508 if (mpz_sgn(ival) < 0)
15509 return NC_UL_NEGATIVE;
15510 unsigned long ui = mpz_get_ui(ival);
15511 if (mpz_cmp_ui(ival, ui) != 0)
15512 return NC_UL_BIG;
15513 *val = ui;
15514 return NC_UL_VALID;
15515}
15516
15517// Express floating point value as unsigned long if possible.
15518
15519Numeric_constant::To_unsigned_long
15520Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15521 unsigned long *val) const
15522{
15523 if (!mpfr_integer_p(fval))
15524 return NC_UL_NOTINT;
15525 mpz_t ival;
15526 mpz_init(ival);
15527 mpfr_get_z(ival, fval, GMP_RNDN);
15528 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15529 mpz_clear(ival);
15530 return ret;
15531}
15532
15533// Convert value to integer if possible.
15534
15535bool
15536Numeric_constant::to_int(mpz_t* val) const
15537{
15538 switch (this->classification_)
15539 {
15540 case NC_INT:
15541 case NC_RUNE:
15542 mpz_init_set(*val, this->u_.int_val);
15543 return true;
15544 case NC_FLOAT:
15545 if (!mpfr_integer_p(this->u_.float_val))
15546 return false;
15547 mpz_init(*val);
15548 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15549 return true;
15550 case NC_COMPLEX:
15551 if (!mpfr_zero_p(this->u_.complex_val.imag)
15552 || !mpfr_integer_p(this->u_.complex_val.real))
15553 return false;
15554 mpz_init(*val);
15555 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15556 return true;
15557 default:
15558 go_unreachable();
15559 }
15560}
15561
15562// Convert value to floating point if possible.
15563
15564bool
15565Numeric_constant::to_float(mpfr_t* val) const
15566{
15567 switch (this->classification_)
15568 {
15569 case NC_INT:
15570 case NC_RUNE:
15571 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15572 return true;
15573 case NC_FLOAT:
15574 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15575 return true;
15576 case NC_COMPLEX:
15577 if (!mpfr_zero_p(this->u_.complex_val.imag))
15578 return false;
15579 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15580 return true;
15581 default:
15582 go_unreachable();
15583 }
15584}
15585
15586// Convert value to complex.
15587
15588bool
15589Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15590{
15591 switch (this->classification_)
15592 {
15593 case NC_INT:
15594 case NC_RUNE:
15595 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15596 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15597 return true;
15598 case NC_FLOAT:
15599 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15600 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15601 return true;
15602 case NC_COMPLEX:
15603 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15604 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15605 return true;
15606 default:
15607 go_unreachable();
15608 }
15609}
15610
15611// Get the type.
15612
15613Type*
15614Numeric_constant::type() const
15615{
15616 if (this->type_ != NULL)
15617 return this->type_;
15618 switch (this->classification_)
15619 {
15620 case NC_INT:
15621 return Type::make_abstract_integer_type();
15622 case NC_RUNE:
15623 return Type::make_abstract_character_type();
15624 case NC_FLOAT:
15625 return Type::make_abstract_float_type();
15626 case NC_COMPLEX:
15627 return Type::make_abstract_complex_type();
15628 default:
15629 go_unreachable();
15630 }
15631}
15632
15633// If the constant can be expressed in TYPE, then set the type of the
15634// constant to TYPE and return true. Otherwise return false, and, if
15635// ISSUE_ERROR is true, report an appropriate error message.
15636
15637bool
15638Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15639{
15640 bool ret;
15641 if (type == NULL)
15642 ret = true;
15643 else if (type->integer_type() != NULL)
15644 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15645 else if (type->float_type() != NULL)
15646 ret = this->check_float_type(type->float_type(), issue_error, loc);
15647 else if (type->complex_type() != NULL)
15648 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15649 else
15650 go_unreachable();
15651 if (ret)
15652 this->type_ = type;
15653 return ret;
15654}
15655
15656// Check whether the constant can be expressed in an integer type.
15657
15658bool
15659Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15660 Location location) const
15661{
15662 mpz_t val;
15663 switch (this->classification_)
15664 {
15665 case NC_INT:
15666 case NC_RUNE:
15667 mpz_init_set(val, this->u_.int_val);
15668 break;
15669
15670 case NC_FLOAT:
15671 if (!mpfr_integer_p(this->u_.float_val))
15672 {
15673 if (issue_error)
15674 error_at(location, "floating point constant truncated to integer");
15675 return false;
15676 }
15677 mpz_init(val);
15678 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15679 break;
15680
15681 case NC_COMPLEX:
15682 if (!mpfr_integer_p(this->u_.complex_val.real)
15683 || !mpfr_zero_p(this->u_.complex_val.imag))
15684 {
15685 if (issue_error)
15686 error_at(location, "complex constant truncated to integer");
15687 return false;
15688 }
15689 mpz_init(val);
15690 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15691 break;
15692
15693 default:
15694 go_unreachable();
15695 }
15696
15697 bool ret;
15698 if (type->is_abstract())
15699 ret = true;
15700 else
15701 {
15702 int bits = mpz_sizeinbase(val, 2);
15703 if (type->is_unsigned())
15704 {
15705 // For an unsigned type we can only accept a nonnegative
15706 // number, and we must be able to represents at least BITS.
15707 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15708 }
15709 else
15710 {
15711 // For a signed type we need an extra bit to indicate the
15712 // sign. We have to handle the most negative integer
15713 // specially.
15714 ret = (bits + 1 <= type->bits()
15715 || (bits <= type->bits()
15716 && mpz_sgn(val) < 0
15717 && (mpz_scan1(val, 0)
15718 == static_cast<unsigned long>(type->bits() - 1))
15719 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15720 }
15721 }
15722
15723 if (!ret && issue_error)
15724 error_at(location, "integer constant overflow");
15725
15726 return ret;
15727}
15728
15729// Check whether the constant can be expressed in a floating point
15730// type.
15731
15732bool
15733Numeric_constant::check_float_type(Float_type* type, bool issue_error,
405c87c4 15734 Location location)
5caf63ca
ILT
15735{
15736 mpfr_t val;
15737 switch (this->classification_)
15738 {
15739 case NC_INT:
15740 case NC_RUNE:
15741 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15742 break;
15743
15744 case NC_FLOAT:
15745 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15746 break;
15747
15748 case NC_COMPLEX:
15749 if (!mpfr_zero_p(this->u_.complex_val.imag))
15750 {
15751 if (issue_error)
15752 error_at(location, "complex constant truncated to float");
15753 return false;
15754 }
15755 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15756 break;
15757
15758 default:
15759 go_unreachable();
15760 }
15761
15762 bool ret;
15763 if (type->is_abstract())
15764 ret = true;
15765 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15766 {
15767 // A NaN or Infinity always fits in the range of the type.
15768 ret = true;
15769 }
15770 else
15771 {
15772 mp_exp_t exp = mpfr_get_exp(val);
15773 mp_exp_t max_exp;
15774 switch (type->bits())
15775 {
15776 case 32:
15777 max_exp = 128;
15778 break;
15779 case 64:
15780 max_exp = 1024;
15781 break;
15782 default:
15783 go_unreachable();
15784 }
15785
15786 ret = exp <= max_exp;
405c87c4
ILT
15787
15788 if (ret)
15789 {
15790 // Round the constant to the desired type.
15791 mpfr_t t;
15792 mpfr_init(t);
15793 switch (type->bits())
15794 {
15795 case 32:
15796 mpfr_set_prec(t, 24);
15797 break;
15798 case 64:
15799 mpfr_set_prec(t, 53);
15800 break;
15801 default:
15802 go_unreachable();
15803 }
15804 mpfr_set(t, val, GMP_RNDN);
15805 mpfr_set(val, t, GMP_RNDN);
15806 mpfr_clear(t);
15807
15808 this->set_float(type, val);
15809 }
5caf63ca
ILT
15810 }
15811
15812 mpfr_clear(val);
15813
15814 if (!ret && issue_error)
15815 error_at(location, "floating point constant overflow");
15816
15817 return ret;
15818}
15819
15820// Check whether the constant can be expressed in a complex type.
15821
15822bool
15823Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
405c87c4 15824 Location location)
5caf63ca
ILT
15825{
15826 if (type->is_abstract())
15827 return true;
15828
15829 mp_exp_t max_exp;
15830 switch (type->bits())
15831 {
15832 case 64:
15833 max_exp = 128;
15834 break;
15835 case 128:
15836 max_exp = 1024;
15837 break;
15838 default:
15839 go_unreachable();
15840 }
15841
15842 mpfr_t real;
405c87c4 15843 mpfr_t imag;
5caf63ca
ILT
15844 switch (this->classification_)
15845 {
15846 case NC_INT:
15847 case NC_RUNE:
15848 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
405c87c4 15849 mpfr_init_set_ui(imag, 0, GMP_RNDN);
5caf63ca
ILT
15850 break;
15851
15852 case NC_FLOAT:
15853 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
405c87c4 15854 mpfr_init_set_ui(imag, 0, GMP_RNDN);
5caf63ca
ILT
15855 break;
15856
15857 case NC_COMPLEX:
5caf63ca 15858 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
405c87c4 15859 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
5caf63ca
ILT
15860 break;
15861
15862 default:
15863 go_unreachable();
15864 }
15865
405c87c4
ILT
15866 bool ret = true;
15867 if (!mpfr_nan_p(real)
15868 && !mpfr_inf_p(real)
15869 && !mpfr_zero_p(real)
15870 && mpfr_get_exp(real) > max_exp)
15871 {
15872 if (issue_error)
15873 error_at(location, "complex real part overflow");
15874 ret = false;
15875 }
5caf63ca 15876
405c87c4
ILT
15877 if (!mpfr_nan_p(imag)
15878 && !mpfr_inf_p(imag)
15879 && !mpfr_zero_p(imag)
15880 && mpfr_get_exp(imag) > max_exp)
15881 {
15882 if (issue_error)
15883 error_at(location, "complex imaginary part overflow");
15884 ret = false;
15885 }
5caf63ca 15886
405c87c4
ILT
15887 if (ret)
15888 {
15889 // Round the constant to the desired type.
15890 mpfr_t t;
15891 mpfr_init(t);
15892 switch (type->bits())
15893 {
15894 case 64:
15895 mpfr_set_prec(t, 24);
15896 break;
15897 case 128:
15898 mpfr_set_prec(t, 53);
15899 break;
15900 default:
15901 go_unreachable();
15902 }
15903 mpfr_set(t, real, GMP_RNDN);
15904 mpfr_set(real, t, GMP_RNDN);
15905 mpfr_set(t, imag, GMP_RNDN);
15906 mpfr_set(imag, t, GMP_RNDN);
15907 mpfr_clear(t);
15908
15909 this->set_complex(type, real, imag);
15910 }
15911
15912 mpfr_clear(real);
15913 mpfr_clear(imag);
5caf63ca
ILT
15914
15915 return ret;
15916}
15917
15918// Return an Expression for this value.
15919
15920Expression*
15921Numeric_constant::expression(Location loc) const
15922{
15923 switch (this->classification_)
15924 {
15925 case NC_INT:
15926 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15927 case NC_RUNE:
15928 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15929 case NC_FLOAT:
15930 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15931 case NC_COMPLEX:
15932 return Expression::make_complex(&this->u_.complex_val.real,
15933 &this->u_.complex_val.imag,
15934 this->type_, loc);
15935 default:
15936 go_unreachable();
15937 }
15938}